file_id stringlengths 5 10 | content stringlengths 96 41.7k | repo stringlengths 7 108 | path stringlengths 8 211 | token_length int64 28 8.19k | original_comment stringlengths 8 5.72k | comment_type stringclasses 2 values | detected_lang stringclasses 1 value | prompt stringlengths 43 41.7k |
|---|---|---|---|---|---|---|---|---|
198409_22 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2024 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.utils;
import java.util.Calendar;
import java.util.GregorianCalendar;
public enum Holiday {
NONE,
LUNAR_NEW_YEAR, //Varies, sometime in late Jan to Late Feb (7 days)
APRIL_FOOLS, //April 1st, can override easter (1 day)
EASTER, //Varies, sometime in Late Mar to Late Apr (6-7 days)
//Nothing in May
PRIDE, //Jun 24th to Jun 30th (7 days)
//Nothing in Jul
SHATTEREDPD_BIRTHDAY, //Aug 1st to Aug 7th (7 days)
//Nothing in Sept
HALLOWEEN, //Oct 24th to Oct 31st (7 days)
//Nothing in Nov
PD_BIRTHDAY, //Dec 1st to Dec 7th (7 days)
WINTER_HOLIDAYS, //Dec 15th to Dec 26th (12 days)
NEW_YEARS; //Dec 27th to Jan 2nd (7 days)
//total of 61-62 festive days each year, mainly concentrated in Late Oct to Early Feb
//we cache the holiday here so that holiday logic doesn't suddenly shut off mid-game
//this gets cleared on game launch (of course), and whenever leaving a game scene
private static Holiday cached;
public static void clearCachedHoliday(){
cached = null;
}
public static Holiday getCurrentHoliday(){
if (cached == null){
cached = getHolidayForDate((GregorianCalendar) GregorianCalendar.getInstance());
}
return cached;
}
//requires a gregorian calendar
public static Holiday getHolidayForDate(GregorianCalendar cal){
//Lunar New Year
if (isLunarNewYear(cal.get(Calendar.YEAR),
cal.get(Calendar.DAY_OF_YEAR))){
return LUNAR_NEW_YEAR;
}
//April Fools
if (cal.get(Calendar.MONTH) == Calendar.APRIL
&& cal.get(Calendar.DAY_OF_MONTH) == 1){
return APRIL_FOOLS;
}
//Easter
if (isEaster(cal.get(Calendar.YEAR),
cal.get(Calendar.DAY_OF_YEAR),
cal.getActualMaximum(Calendar.DAY_OF_YEAR) == 366)){
return EASTER;
}
//Pride
if (cal.get(Calendar.MONTH) == Calendar.JUNE
&& cal.get(Calendar.DAY_OF_MONTH) >= 24){
return PRIDE;
}
//Shattered's Birthday
if (cal.get(Calendar.MONTH) == Calendar.AUGUST
&& cal.get(Calendar.DAY_OF_MONTH) <= 7){
return SHATTEREDPD_BIRTHDAY;
}
//Halloween
if (cal.get(Calendar.MONTH) == Calendar.OCTOBER
&& cal.get(Calendar.DAY_OF_MONTH) >= 24){
return HALLOWEEN;
}
//Pixel Dungeon's Birthday
if (cal.get(Calendar.MONTH) == Calendar.DECEMBER
&& cal.get(Calendar.DAY_OF_MONTH) <= 7){
return PD_BIRTHDAY;
}
//Winter Holidays
if (cal.get(Calendar.MONTH) == Calendar.DECEMBER
&& cal.get(Calendar.DAY_OF_MONTH) >= 15
&& cal.get(Calendar.DAY_OF_MONTH) <= 26){
return WINTER_HOLIDAYS;
}
//New Years
if ((cal.get(Calendar.MONTH) == Calendar.DECEMBER && cal.get(Calendar.DAY_OF_MONTH) >= 27)
|| (cal.get(Calendar.MONTH) == Calendar.JANUARY && cal.get(Calendar.DAY_OF_MONTH) <= 2)){
return NEW_YEARS;
}
return NONE;
}
//has to be hard-coded on a per-year basis =S
public static boolean isLunarNewYear(int year, int dayOfYear){
int lunarNewYearDayOfYear;
switch (year){
//yes, I really did hardcode this all the way from 2020 to 2100
default: lunarNewYearDayOfYear = 31+5; break; //defaults to February 5th
case 2020: lunarNewYearDayOfYear = 25; break; //January 25th
case 2021: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2022: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2023: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2024: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2025: lunarNewYearDayOfYear = 29; break; //January 29th
case 2026: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2027: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2028: lunarNewYearDayOfYear = 26; break; //January 26th
case 2029: lunarNewYearDayOfYear = 31+13; break; //February 13th
case 2030: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2031: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2032: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2033: lunarNewYearDayOfYear = 31; break; //January 31st
case 2034: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2035: lunarNewYearDayOfYear = 31+8; break; //February 8th
case 2036: lunarNewYearDayOfYear = 28; break; //January 28th
case 2037: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2038: lunarNewYearDayOfYear = 31+4; break; //February 4th
case 2039: lunarNewYearDayOfYear = 24; break; //January 24th
case 2040: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2041: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2042: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2043: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2044: lunarNewYearDayOfYear = 30; break; //January 30th
case 2045: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2046: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2047: lunarNewYearDayOfYear = 26; break; //January 26th
case 2048: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2049: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2050: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2051: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2052: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2053: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2054: lunarNewYearDayOfYear = 31+8; break; //February 8th
case 2055: lunarNewYearDayOfYear = 28; break; //January 28th
case 2056: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2057: lunarNewYearDayOfYear = 31+4; break; //February 4th
case 2058: lunarNewYearDayOfYear = 24; break; //January 24th
case 2059: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2060: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2061: lunarNewYearDayOfYear = 21; break; //January 21st
case 2062: lunarNewYearDayOfYear = 31+9; break; //February 9th
case 2063: lunarNewYearDayOfYear = 29; break; //January 29th
case 2064: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2065: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2066: lunarNewYearDayOfYear = 26; break; //January 26th
case 2067: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2068: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2069: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2070: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2071: lunarNewYearDayOfYear = 31; break; //January 31st
case 2072: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2073: lunarNewYearDayOfYear = 31+7; break; //February 7th
case 2074: lunarNewYearDayOfYear = 27; break; //January 27th
case 2075: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2076: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2077: lunarNewYearDayOfYear = 24; break; //January 24th
case 2078: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2079: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2080: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2081: lunarNewYearDayOfYear = 31+9; break; //February 9th
case 2082: lunarNewYearDayOfYear = 29; break; //January 29th
case 2083: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2084: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2085: lunarNewYearDayOfYear = 26; break; //January 26th
case 2086: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2087: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2088: lunarNewYearDayOfYear = 24; break; //January 24th
case 2089: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2090: lunarNewYearDayOfYear = 30; break; //January 30th
case 2091: lunarNewYearDayOfYear = 31+18; break; //February 18th
case 2092: lunarNewYearDayOfYear = 31+7; break; //February 7th
case 2093: lunarNewYearDayOfYear = 27; break; //January 27th
case 2094: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2095: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2096: lunarNewYearDayOfYear = 25; break; //January 25th
case 2097: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2098: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2099: lunarNewYearDayOfYear = 21; break; //January 21st
case 2100: lunarNewYearDayOfYear = 31+9; break; //February 9th
}
//celebrate for 7 days total, with Lunar New Year on the 5th day
return dayOfYear >= lunarNewYearDayOfYear-4 && dayOfYear <= lunarNewYearDayOfYear+2;
}
//has to be algorithmically computed =S
public static boolean isEaster(int year, int dayOfYear, boolean isLeapYear){
//if we're not in March or April, just skip out of all these calculations
if (dayOfYear < 59 || dayOfYear > 121) {
return false;
}
//Uses the Anonymous Gregorian Algorithm
int a = year % 19;
int b = year / 100;
int c = year % 100;
int d = b / 4;
int e = b % 4;
int f = (b + 8) / 25;
int g = (b - f + 1) / 3;
int h = (a*19 + b - d - g + 15) % 30;
int i = c / 4;
int k = c % 4;
int l = (32 + 2*e + 2*i - h - k) % 7;
int m = (a + h*11 + l*22)/451;
int n = (h + l - m*7 + 114) / 31;
int o = (h + l - m*7 + 114) % 31;
int easterDayOfYear = 0;
if (n == 3){
easterDayOfYear += 59; //march
} else {
easterDayOfYear += 90; //april
}
if (isLeapYear) {
easterDayOfYear += 1; //add an extra day to account for February 29th
}
easterDayOfYear += (o+1); //add day of month
//celebrate for 7 days total, with Easter Sunday on the 5th day
return dayOfYear >= easterDayOfYear-4 && dayOfYear <= easterDayOfYear+2;
}
}
| 00-Evan/shattered-pixel-dungeon | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/utils/Holiday.java | 4,181 | //Halloween | line_comment | nl | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2024 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.utils;
import java.util.Calendar;
import java.util.GregorianCalendar;
public enum Holiday {
NONE,
LUNAR_NEW_YEAR, //Varies, sometime in late Jan to Late Feb (7 days)
APRIL_FOOLS, //April 1st, can override easter (1 day)
EASTER, //Varies, sometime in Late Mar to Late Apr (6-7 days)
//Nothing in May
PRIDE, //Jun 24th to Jun 30th (7 days)
//Nothing in Jul
SHATTEREDPD_BIRTHDAY, //Aug 1st to Aug 7th (7 days)
//Nothing in Sept
HALLOWEEN, //Oct 24th to Oct 31st (7 days)
//Nothing in Nov
PD_BIRTHDAY, //Dec 1st to Dec 7th (7 days)
WINTER_HOLIDAYS, //Dec 15th to Dec 26th (12 days)
NEW_YEARS; //Dec 27th to Jan 2nd (7 days)
//total of 61-62 festive days each year, mainly concentrated in Late Oct to Early Feb
//we cache the holiday here so that holiday logic doesn't suddenly shut off mid-game
//this gets cleared on game launch (of course), and whenever leaving a game scene
private static Holiday cached;
public static void clearCachedHoliday(){
cached = null;
}
public static Holiday getCurrentHoliday(){
if (cached == null){
cached = getHolidayForDate((GregorianCalendar) GregorianCalendar.getInstance());
}
return cached;
}
//requires a gregorian calendar
public static Holiday getHolidayForDate(GregorianCalendar cal){
//Lunar New Year
if (isLunarNewYear(cal.get(Calendar.YEAR),
cal.get(Calendar.DAY_OF_YEAR))){
return LUNAR_NEW_YEAR;
}
//April Fools
if (cal.get(Calendar.MONTH) == Calendar.APRIL
&& cal.get(Calendar.DAY_OF_MONTH) == 1){
return APRIL_FOOLS;
}
//Easter
if (isEaster(cal.get(Calendar.YEAR),
cal.get(Calendar.DAY_OF_YEAR),
cal.getActualMaximum(Calendar.DAY_OF_YEAR) == 366)){
return EASTER;
}
//Pride
if (cal.get(Calendar.MONTH) == Calendar.JUNE
&& cal.get(Calendar.DAY_OF_MONTH) >= 24){
return PRIDE;
}
//Shattered's Birthday
if (cal.get(Calendar.MONTH) == Calendar.AUGUST
&& cal.get(Calendar.DAY_OF_MONTH) <= 7){
return SHATTEREDPD_BIRTHDAY;
}
//Hallo<SUF>
if (cal.get(Calendar.MONTH) == Calendar.OCTOBER
&& cal.get(Calendar.DAY_OF_MONTH) >= 24){
return HALLOWEEN;
}
//Pixel Dungeon's Birthday
if (cal.get(Calendar.MONTH) == Calendar.DECEMBER
&& cal.get(Calendar.DAY_OF_MONTH) <= 7){
return PD_BIRTHDAY;
}
//Winter Holidays
if (cal.get(Calendar.MONTH) == Calendar.DECEMBER
&& cal.get(Calendar.DAY_OF_MONTH) >= 15
&& cal.get(Calendar.DAY_OF_MONTH) <= 26){
return WINTER_HOLIDAYS;
}
//New Years
if ((cal.get(Calendar.MONTH) == Calendar.DECEMBER && cal.get(Calendar.DAY_OF_MONTH) >= 27)
|| (cal.get(Calendar.MONTH) == Calendar.JANUARY && cal.get(Calendar.DAY_OF_MONTH) <= 2)){
return NEW_YEARS;
}
return NONE;
}
//has to be hard-coded on a per-year basis =S
public static boolean isLunarNewYear(int year, int dayOfYear){
int lunarNewYearDayOfYear;
switch (year){
//yes, I really did hardcode this all the way from 2020 to 2100
default: lunarNewYearDayOfYear = 31+5; break; //defaults to February 5th
case 2020: lunarNewYearDayOfYear = 25; break; //January 25th
case 2021: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2022: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2023: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2024: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2025: lunarNewYearDayOfYear = 29; break; //January 29th
case 2026: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2027: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2028: lunarNewYearDayOfYear = 26; break; //January 26th
case 2029: lunarNewYearDayOfYear = 31+13; break; //February 13th
case 2030: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2031: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2032: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2033: lunarNewYearDayOfYear = 31; break; //January 31st
case 2034: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2035: lunarNewYearDayOfYear = 31+8; break; //February 8th
case 2036: lunarNewYearDayOfYear = 28; break; //January 28th
case 2037: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2038: lunarNewYearDayOfYear = 31+4; break; //February 4th
case 2039: lunarNewYearDayOfYear = 24; break; //January 24th
case 2040: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2041: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2042: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2043: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2044: lunarNewYearDayOfYear = 30; break; //January 30th
case 2045: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2046: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2047: lunarNewYearDayOfYear = 26; break; //January 26th
case 2048: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2049: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2050: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2051: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2052: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2053: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2054: lunarNewYearDayOfYear = 31+8; break; //February 8th
case 2055: lunarNewYearDayOfYear = 28; break; //January 28th
case 2056: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2057: lunarNewYearDayOfYear = 31+4; break; //February 4th
case 2058: lunarNewYearDayOfYear = 24; break; //January 24th
case 2059: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2060: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2061: lunarNewYearDayOfYear = 21; break; //January 21st
case 2062: lunarNewYearDayOfYear = 31+9; break; //February 9th
case 2063: lunarNewYearDayOfYear = 29; break; //January 29th
case 2064: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2065: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2066: lunarNewYearDayOfYear = 26; break; //January 26th
case 2067: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2068: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2069: lunarNewYearDayOfYear = 23; break; //January 23rd
case 2070: lunarNewYearDayOfYear = 31+11; break; //February 11th
case 2071: lunarNewYearDayOfYear = 31; break; //January 31st
case 2072: lunarNewYearDayOfYear = 31+19; break; //February 19th
case 2073: lunarNewYearDayOfYear = 31+7; break; //February 7th
case 2074: lunarNewYearDayOfYear = 27; break; //January 27th
case 2075: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2076: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2077: lunarNewYearDayOfYear = 24; break; //January 24th
case 2078: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2079: lunarNewYearDayOfYear = 31+2; break; //February 2nd
case 2080: lunarNewYearDayOfYear = 22; break; //January 22nd
case 2081: lunarNewYearDayOfYear = 31+9; break; //February 9th
case 2082: lunarNewYearDayOfYear = 29; break; //January 29th
case 2083: lunarNewYearDayOfYear = 31+17; break; //February 17th
case 2084: lunarNewYearDayOfYear = 31+6; break; //February 6th
case 2085: lunarNewYearDayOfYear = 26; break; //January 26th
case 2086: lunarNewYearDayOfYear = 31+14; break; //February 14th
case 2087: lunarNewYearDayOfYear = 31+3; break; //February 3rd
case 2088: lunarNewYearDayOfYear = 24; break; //January 24th
case 2089: lunarNewYearDayOfYear = 31+10; break; //February 10th
case 2090: lunarNewYearDayOfYear = 30; break; //January 30th
case 2091: lunarNewYearDayOfYear = 31+18; break; //February 18th
case 2092: lunarNewYearDayOfYear = 31+7; break; //February 7th
case 2093: lunarNewYearDayOfYear = 27; break; //January 27th
case 2094: lunarNewYearDayOfYear = 31+15; break; //February 15th
case 2095: lunarNewYearDayOfYear = 31+5; break; //February 5th
case 2096: lunarNewYearDayOfYear = 25; break; //January 25th
case 2097: lunarNewYearDayOfYear = 31+12; break; //February 12th
case 2098: lunarNewYearDayOfYear = 31+1; break; //February 1st
case 2099: lunarNewYearDayOfYear = 21; break; //January 21st
case 2100: lunarNewYearDayOfYear = 31+9; break; //February 9th
}
//celebrate for 7 days total, with Lunar New Year on the 5th day
return dayOfYear >= lunarNewYearDayOfYear-4 && dayOfYear <= lunarNewYearDayOfYear+2;
}
//has to be algorithmically computed =S
public static boolean isEaster(int year, int dayOfYear, boolean isLeapYear){
//if we're not in March or April, just skip out of all these calculations
if (dayOfYear < 59 || dayOfYear > 121) {
return false;
}
//Uses the Anonymous Gregorian Algorithm
int a = year % 19;
int b = year / 100;
int c = year % 100;
int d = b / 4;
int e = b % 4;
int f = (b + 8) / 25;
int g = (b - f + 1) / 3;
int h = (a*19 + b - d - g + 15) % 30;
int i = c / 4;
int k = c % 4;
int l = (32 + 2*e + 2*i - h - k) % 7;
int m = (a + h*11 + l*22)/451;
int n = (h + l - m*7 + 114) / 31;
int o = (h + l - m*7 + 114) % 31;
int easterDayOfYear = 0;
if (n == 3){
easterDayOfYear += 59; //march
} else {
easterDayOfYear += 90; //april
}
if (isLeapYear) {
easterDayOfYear += 1; //add an extra day to account for February 29th
}
easterDayOfYear += (o+1); //add day of month
//celebrate for 7 days total, with Easter Sunday on the 5th day
return dayOfYear >= easterDayOfYear-4 && dayOfYear <= easterDayOfYear+2;
}
}
|
11193_1 | package com.steen.controllers;
import com.steen.models.*;
import com.steen.velocity.VelocityTemplateEngine;
import spark.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.steen.Main.p_layout;
import static com.steen.Main.sfp;
import static spark.Spark.get;
import static spark.Spark.post;
public class CartController {
private CartModel cartModel;
private final int ADD = 0;
private final int DELETE = 1;
public CartController(final HashMap<String, Model> models) {
cartModel = (CartModel) models.get("cart");
post("/cart/act", (request, response) -> {
try {
int action = Integer.parseInt(request.queryParams("action"));
switch (action) {
case ADD:
int p_id = Integer.parseInt(request.queryParams("productId"));
int amount = Integer.parseInt(request.queryParams("amount"));
cartModel.addToCart(p_id, amount);
return "Product toegevoegd aan winkelwagen.";
case DELETE:
List<Integer> idsToDelete = new ArrayList<>();
for (int i = 0; true; i++) {
String p_idString = request.queryParams("p_id" + i);
if (p_idString == null) break;
int productID = Integer.parseInt(p_idString);
idsToDelete.add(productID);
}
int itemsdeleted = cartModel.removeFromCart(idsToDelete, -1);
if (itemsdeleted > 0){
if (itemsdeleted == 1)
return "1 product verwijderd.";
return itemsdeleted + " producten verwijderd.";
} else {
// return "Kon de geselecteerde producten niet verwijderen. " +
// "Neem aub. contact op met de sitebeheerder als dit vaak voor komt..";
return "0 producten verwijderd.";
}
default: throw new Exception();
}
} catch (Exception e) {
e.printStackTrace();
return "Er ging iets mis aan onze kant, " +
"neem aub. contact op met de sitebeheerder als dit vaak voor komt. ";
}
});
get("/cart", (request, response) -> {
Map<String, Object> model = new HashMap<>();
model.put("login_modal", sfp + "html/login_mod.vtl");
model.put("template", sfp + "html/cart.html");
model.put("admin", request.session().attribute("admin"));
model.put("correctinfo", request.session().attribute("correctinfo"));
model.put("username", request.session().attribute("username"));
return new ModelAndView(model, p_layout);
}, new VelocityTemplateEngine());
}
}
| 0912293/PythonMasterRace | src/main/java/com/steen/controllers/CartController.java | 697 | // "Neem aub. contact op met de sitebeheerder als dit vaak voor komt.."; | line_comment | nl | package com.steen.controllers;
import com.steen.models.*;
import com.steen.velocity.VelocityTemplateEngine;
import spark.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.steen.Main.p_layout;
import static com.steen.Main.sfp;
import static spark.Spark.get;
import static spark.Spark.post;
public class CartController {
private CartModel cartModel;
private final int ADD = 0;
private final int DELETE = 1;
public CartController(final HashMap<String, Model> models) {
cartModel = (CartModel) models.get("cart");
post("/cart/act", (request, response) -> {
try {
int action = Integer.parseInt(request.queryParams("action"));
switch (action) {
case ADD:
int p_id = Integer.parseInt(request.queryParams("productId"));
int amount = Integer.parseInt(request.queryParams("amount"));
cartModel.addToCart(p_id, amount);
return "Product toegevoegd aan winkelwagen.";
case DELETE:
List<Integer> idsToDelete = new ArrayList<>();
for (int i = 0; true; i++) {
String p_idString = request.queryParams("p_id" + i);
if (p_idString == null) break;
int productID = Integer.parseInt(p_idString);
idsToDelete.add(productID);
}
int itemsdeleted = cartModel.removeFromCart(idsToDelete, -1);
if (itemsdeleted > 0){
if (itemsdeleted == 1)
return "1 product verwijderd.";
return itemsdeleted + " producten verwijderd.";
} else {
// return "Kon de geselecteerde producten niet verwijderen. " +
// "Neem<SUF>
return "0 producten verwijderd.";
}
default: throw new Exception();
}
} catch (Exception e) {
e.printStackTrace();
return "Er ging iets mis aan onze kant, " +
"neem aub. contact op met de sitebeheerder als dit vaak voor komt. ";
}
});
get("/cart", (request, response) -> {
Map<String, Object> model = new HashMap<>();
model.put("login_modal", sfp + "html/login_mod.vtl");
model.put("template", sfp + "html/cart.html");
model.put("admin", request.session().attribute("admin"));
model.put("correctinfo", request.session().attribute("correctinfo"));
model.put("username", request.session().attribute("username"));
return new ModelAndView(model, p_layout);
}, new VelocityTemplateEngine());
}
}
|
18424_7 | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst zeker zijn dat de camera niet gebruikt wordt.
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien ik al eentje heb gemaakt aan het begin...
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
| 0974201/code-bin | java/backup camerax proj.java | 1,963 | //eerst zeker zijn dat de camera niet gebruikt wordt. | line_comment | nl | package com.example.idek;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraX;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageAnalysisConfig;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureConfig;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.PreviewConfig;
import androidx.lifecycle.LifecycleOwner;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.util.Rational;
import android.util.Size;
import android.view.TextureView;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.nio.ByteBuffer;
//ik haat mijzelf dus daarom maak ik een camera ding met een api dat nog niet eens in de beta stage is
//en waarvan de tutorial in een taal is dat ik 0% begrijp
//saus: https://codelabs.developers.google.com/codelabs/camerax-getting-started/
public class MainActivity extends AppCompatActivity {
//private int REQUEST_CODE_PERMISSIONS = 10; //idek volgens tutorial is dit een arbitraire nummer zou helpen als je app meerdere toestimmingen vraagt
//private final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"}; //array met permissions vermeld in manifest
TextureView txView;
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txView = findViewById(R.id.view_finder);
startCamera();
/*if(allPermissionsGranted()){
} else{
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}*/
}
private void startCamera() {//heel veel dingen gebeuren hier
//eerst<SUF>
CameraX.unbindAll();
/* doe preview weergeven */
int aspRatioW = txView.getWidth(); //haalt breedte scherm op
int aspRatioH = txView.getHeight(); //haalt hoogte scherm op
Rational asp = new Rational (aspRatioW, aspRatioH); //helpt bij zetten aspect ratio
Size screen = new Size(aspRatioW, aspRatioH); //grootte scherm ofc
PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(asp).setTargetResolution(screen).build();
Preview pview = new Preview(pConfig);
pview.setOnPreviewOutputUpdateListener(
new Preview.OnPreviewOutputUpdateListener() {
//eigenlijk maakt dit al een nieuwe texturesurface aan
//maar aangezien ik al eentje heb gemaakt aan het begin...
@Override
public void onUpdated(Preview.PreviewOutput output){
ViewGroup parent = (ViewGroup) txView.getParent();
parent.removeView(txView); //moeten wij hem eerst yeeten
parent.addView(txView, 0);
txView.setSurfaceTexture(output.getSurfaceTexture()); //dan weer toevoegen
//updateTransform(); //en dan updaten
}
});
/* image capture */
/*ImageCaptureConfig imgConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).build();
ImageCapture imgCap = new ImageCapture(imgConfig);*/
/* image analyser */
ImageAnalysisConfig imgAConfig = new ImageAnalysisConfig.Builder().setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE).build();
final ImageAnalysis imgAsys = new ImageAnalysis(imgAConfig);
imgAsys.setAnalyzer(
new ImageAnalysis.Analyzer(){
@Override
public void analyze(ImageProxy image, int rotationDegrees){
try {
ByteBuffer bf = image.getPlanes()[0].getBuffer();
byte[] b = new byte[bf.capacity()];
bf.get(b);
Rect r = image.getCropRect();
int w = image.getWidth();
int h = image.getHeight();
PlanarYUVLuminanceSource sauce = new PlanarYUVLuminanceSource(b ,w, h, r.left, r.top, r.width(), r.height(),false);
BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(sauce));
result = new qrReader().decoded(bit);
System.out.println(result);
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Log.wtf("F: ", result);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
}
}
);
//bindt de shit hierboven aan de lifecycle:
CameraX.bindToLifecycle((LifecycleOwner)this, imgAsys, /*imgCap,*/ pview);
}
/*private void updateTransform(){
//compenseert veranderingen in orientatie voor viewfinder, aangezien de rest van de layout in portrait mode blijft.
//methinks :thonk:
Matrix mx = new Matrix();
float w = txView.getMeasuredWidth();
float h = txView.getMeasuredHeight();
//berekent het midden
float cX = w / 2f;
float cY = h / 2f;
int rotDgr; //voor de switch < propt in hoeveel graden shit is gekanteld
//Display a = txView.getDisplay(); //ok dan stoppen wij .getdisplay in z'n eigen shit.
int rtrn = (int)txView.getRotation(); //dan dit maar in een aparte int zetten want alles deed boem bij het opstarten
//omfg het komt omdat .getDisplay erin zit.
switch(rtrn){
case Surface.ROTATION_0:
rotDgr = 0;
break;
case Surface.ROTATION_90:
rotDgr = 90;
break;
case Surface.ROTATION_180:
rotDgr = 180;
break;
case Surface.ROTATION_270:
rotDgr = 270;
break;
default:
return;
}
mx.postRotate((float)rotDgr, cX, cY); //berekent preview out put aan de hand van hoe de toestel gedraaid is
float buffer = txView.getMeasuredHeight() / txView.getMeasuredWidth() ;
int scaleW;
int scaleH;
if(w > h){ //center-crop transformation
scaleH = (int)w;
scaleW = Math.round(w * buffer);
} else{
scaleH = (int)h;
scaleW = Math.round(h * buffer);
}
float x = scaleW / w; //doet schaal berekenen
float y = scaleH / h;
mx.preScale(x, y, cX, cY); //vult preview op
txView.setTransform(mx); //past dit op preview toe
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//als alle permissies zijn toegestaan start camera
if(requestCode == REQUEST_CODE_PERMISSIONS){
if(allPermissionsGranted()){
startCamera();
} else{
Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionsGranted(){
//kijken of alle permissies zijn toegestaan
for(String permission : REQUIRED_PERMISSIONS){
if(ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}*/
}
|
111409_1 | package com.example.idek;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.qrcode.QRCodeReader;
import java.util.HashMap;
public class qrReader {
public String decoded(BinaryBitmap plaatje, HashMap<DecodeHintType,?> ddog) throws NotFoundException, FormatException, ChecksumException {
QRCodeReader qr = new QRCodeReader(); // (*・ω・)ノ ghelleu QRCodeReader
String qrResultDing; //alvast een string aanmaken waarin later de gedecodeerde zooi in gestopt wordt
try{
Result resDing = qr.decode(plaatje, ddog); //wauw. zonder medicatie is mijn beste uitleg hiervoor: "magic happens (/ ̄ー ̄)/~~☆’.・.・:★’.・.・:☆"
//aight op basis van wat je allemaal kan vragen van Result, slaat hij de ingelezen qr code in zijn geheel op.
//je zou specifieke shit kunnen opvragen afhankelijk van welke type barcode je hebt ingescand, bijv de "result points" (waarvan ik gok dat het in een qr code de grote blokken kunnen zijn?)
//en bytes en bits van wat er geencodeerd is in een qr code/aztec ding/barcode
//mensen hadden echt honger toen ze de namen hiervoor bedachten huh. "nibble, bit, byte" zolang je toetsenbord maar vrij blijft van kruimels, i guess
//alleen is dat alles niet echt relevant hier want ik wil een string terug hebben en Result kan dat ook teruggeven :D
qrResultDing = resDing.getText(); //en dat doen wij hier! geeft de string wat in de qr code stond terug en stopt dat in de string wat eerder is aangemaakt.
return qrResultDing; //< sssh ik fix het later wel als ik minder slaperig ben en shit kan lezen < VERANDER GEWOON WAT VOOR SHIT HIJ MOET TERUG GEVEN PROBLEM FIXED.
} catch (NotFoundException nf){
//aaaaaaaah oke wat doe ik met de rest. NVM I CAN'T READ/ ik kan letterlijk kiezen welke exception ik wil hebben?? < nope.
nf.printStackTrace();
} catch(FormatException fx){
fx.printStackTrace();
} catch (ChecksumException e){
e.printStackTrace();
}
return null;
}
}
| 0974201/qr-ding | app/src/main/java/com/example/idek/qrReader.java | 604 | //alvast een string aanmaken waarin later de gedecodeerde zooi in gestopt wordt | line_comment | nl | package com.example.idek;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.qrcode.QRCodeReader;
import java.util.HashMap;
public class qrReader {
public String decoded(BinaryBitmap plaatje, HashMap<DecodeHintType,?> ddog) throws NotFoundException, FormatException, ChecksumException {
QRCodeReader qr = new QRCodeReader(); // (*・ω・)ノ ghelleu QRCodeReader
String qrResultDing; //alvas<SUF>
try{
Result resDing = qr.decode(plaatje, ddog); //wauw. zonder medicatie is mijn beste uitleg hiervoor: "magic happens (/ ̄ー ̄)/~~☆’.・.・:★’.・.・:☆"
//aight op basis van wat je allemaal kan vragen van Result, slaat hij de ingelezen qr code in zijn geheel op.
//je zou specifieke shit kunnen opvragen afhankelijk van welke type barcode je hebt ingescand, bijv de "result points" (waarvan ik gok dat het in een qr code de grote blokken kunnen zijn?)
//en bytes en bits van wat er geencodeerd is in een qr code/aztec ding/barcode
//mensen hadden echt honger toen ze de namen hiervoor bedachten huh. "nibble, bit, byte" zolang je toetsenbord maar vrij blijft van kruimels, i guess
//alleen is dat alles niet echt relevant hier want ik wil een string terug hebben en Result kan dat ook teruggeven :D
qrResultDing = resDing.getText(); //en dat doen wij hier! geeft de string wat in de qr code stond terug en stopt dat in de string wat eerder is aangemaakt.
return qrResultDing; //< sssh ik fix het later wel als ik minder slaperig ben en shit kan lezen < VERANDER GEWOON WAT VOOR SHIT HIJ MOET TERUG GEVEN PROBLEM FIXED.
} catch (NotFoundException nf){
//aaaaaaaah oke wat doe ik met de rest. NVM I CAN'T READ/ ik kan letterlijk kiezen welke exception ik wil hebben?? < nope.
nf.printStackTrace();
} catch(FormatException fx){
fx.printStackTrace();
} catch (ChecksumException e){
e.printStackTrace();
}
return null;
}
}
|
42150_10 | /*
* 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 rekenmachine;
/**
*
* @author adeliae
*/
public class Telraam extends javax.swing.JFrame {
//"" achter strings gezet om te voorkomen dat null als input wordt gegeven
String eersteGetal = "";
String tweedeGetal = "";
String invoer = "";
String operatie = "";
String antwoord = "";
double uitkomst;
/**
* Creates new form Telraam
*/
public Telraam() {
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() {
jTextField1 = new javax.swing.JTextField();
invoer7 = new javax.swing.JButton();
invoer8 = new javax.swing.JButton();
invoer9 = new javax.swing.JButton();
invoer4 = new javax.swing.JButton();
invoer5 = new javax.swing.JButton();
invoer6 = new javax.swing.JButton();
invoer1 = new javax.swing.JButton();
invoer2 = new javax.swing.JButton();
invoer3 = new javax.swing.JButton();
invoer0 = new javax.swing.JButton();
invoerkomma = new javax.swing.JButton();
clearbutton = new javax.swing.JButton();
invoerplus = new javax.swing.JButton();
invoermin = new javax.swing.JButton();
invoerdelen = new javax.swing.JButton();
invoerkeer = new javax.swing.JButton();
invoermacht = new javax.swing.JButton();
uitrekenen = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Rekenmachine");
setName("telraamForm"); // NOI18N
invoer7.setText("7");
invoer7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer7ActionPerformed(evt);
}
});
invoer8.setText("8");
invoer8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer8ActionPerformed(evt);
}
});
invoer9.setText("9");
invoer9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer9ActionPerformed(evt);
}
});
invoer4.setText("4");
invoer4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer4ActionPerformed(evt);
}
});
invoer5.setText("5");
invoer5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer5ActionPerformed(evt);
}
});
invoer6.setText("6");
invoer6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer6ActionPerformed(evt);
}
});
invoer1.setText("1");
invoer1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer1ActionPerformed(evt);
}
});
invoer2.setText("2");
invoer2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer2ActionPerformed(evt);
}
});
invoer3.setText("3");
invoer3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer3ActionPerformed(evt);
}
});
invoer0.setText("0");
invoer0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer0ActionPerformed(evt);
}
});
invoerkomma.setText(".");
invoerkomma.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerkommaActionPerformed(evt);
}
});
clearbutton.setText("C");
clearbutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearbuttonActionPerformed(evt);
}
});
invoerplus.setText("+");
invoerplus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerplusActionPerformed(evt);
}
});
invoermin.setText("-");
invoermin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerminActionPerformed(evt);
}
});
invoerdelen.setText("/");
invoerdelen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerdelenActionPerformed(evt);
}
});
invoerkeer.setText("*");
invoerkeer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerkeerActionPerformed(evt);
}
});
invoermacht.setText("^");
invoermacht.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoermachtActionPerformed(evt);
}
});
uitrekenen.setText("=");
uitrekenen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
uitrekenenActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(invoer1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(invoer4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(clearbutton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoer8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer0, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoer9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerkomma, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(uitrekenen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoermacht, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(invoerplus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoermin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerdelen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerkeer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerplus, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoermin, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerdelen, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer0, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerkomma, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(clearbutton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerkeer, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoermacht, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(uitrekenen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//tijd om de knopjes een functie te geven ヾ(*・ω・)ノ゜+.゜★ィェィ☆゜+.゜ヾ(・ω・*)ノ
private void invoer7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer7ActionPerformed
String invoerGetal = jTextField1.getText() + invoer7.getText();
jTextField1.setText(invoerGetal);
//if statement gemaakt om te controleren of er al iets is ingevoerd
//zodat je niet telkens op de c knop hoeft te klikken om een nieuwe
//berekening te maken. (alleen gaat er na drie berekeningen iets mis oopsΣ(っ゚Д゚;)っ )
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 7;
} else{
invoer += 7;
}
}//GEN-LAST:event_invoer7ActionPerformed
private void invoer8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer8ActionPerformed
String invoerGetal = jTextField1.getText() + invoer8.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 8;
} else{
invoer += 8;
}
}//GEN-LAST:event_invoer8ActionPerformed
private void invoer9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer9ActionPerformed
String invoerGetal = jTextField1.getText() + invoer9.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 9;
} else{
invoer += 9;
}
}//GEN-LAST:event_invoer9ActionPerformed
private void invoer4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer4ActionPerformed
String invoerGetal = jTextField1.getText() + invoer4.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 4;
} else{
invoer += 4;
}
}//GEN-LAST:event_invoer4ActionPerformed
private void invoer5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer5ActionPerformed
String invoerGetal = jTextField1.getText() + invoer5.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 5;
} else{
invoer += 5;
}
}//GEN-LAST:event_invoer5ActionPerformed
private void invoer6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer6ActionPerformed
String invoerGetal = jTextField1.getText() + invoer6.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 6;
} else{
invoer += 6;
}
}//GEN-LAST:event_invoer6ActionPerformed
private void invoer1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer1ActionPerformed
String invoerGetal = jTextField1.getText() + invoer1.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 1;
} else{
invoer += 1;
}
}//GEN-LAST:event_invoer1ActionPerformed
private void invoer2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer2ActionPerformed
String invoerGetal = jTextField1.getText() + invoer2.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 2;
} else{
invoer += 2;
}
}//GEN-LAST:event_invoer2ActionPerformed
private void invoer3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer3ActionPerformed
String invoerGetal = jTextField1.getText() + invoer3.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 3;
} else{
invoer += 3;
}
}//GEN-LAST:event_invoer3ActionPerformed
private void invoer0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer0ActionPerformed
String invoerGetal = jTextField1.getText() + invoer0.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 0;
} else{
invoer += 0;
}
}//GEN-LAST:event_invoer0ActionPerformed
private void invoerkommaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerkommaActionPerformed
String invoerGetal = jTextField1.getText() + invoerkomma.getText();
jTextField1.setText(invoerGetal);
invoer += ".";
}//GEN-LAST:event_invoerkommaActionPerformed
private void clearbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearbuttonActionPerformed
jTextField1.setText("");
eersteGetal = "";
tweedeGetal = "";
invoer = "";
}//GEN-LAST:event_clearbuttonActionPerformed
private void invoerplusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerplusActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("+");
eersteGetal = invoer;
invoer = "";
operatie = "+";
}//GEN-LAST:event_invoerplusActionPerformed
private void invoerminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerminActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("-");
eersteGetal = invoer;
invoer = "";
operatie = "-";
}//GEN-LAST:event_invoerminActionPerformed
private void invoerdelenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerdelenActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("/");
eersteGetal = invoer;
invoer = "";
operatie = "/";
}//GEN-LAST:event_invoerdelenActionPerformed
private void invoerkeerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerkeerActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("*");
eersteGetal = invoer;
invoer = "";
operatie = "*";
//hhahaa ben opnieuw begonnen omdat ik de in de vorige versie
//de vermenigvuldig functie was vergeten te maken
//good job me (屮゜Д゜)屮
}//GEN-LAST:event_invoerkeerActionPerformed
private void invoermachtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoermachtActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("^");
eersteGetal = invoer;
//int uitreken = Integer.parseInt(invoer) * Integer.parseInt(invoer);
//eersteGetal = uitreken + "";
invoer = "";
operatie = "^";
//System.out.println(eersteGetal);
//eersteGetal = uitkomst + "";
//jTextField1.setText(eersteGetal);
}//GEN-LAST:event_invoermachtActionPerformed
private void uitrekenenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uitrekenenActionPerformed
//TO INFINITY AND BEYOOOOOOOOOOOOOOOOOOOOND ゚+.(ノ。'▽')ノ*.オオォォ☆゚・:*☆
//hier wordt alles berekend
tweedeGetal = invoer;
//System.out.println(eersteGetal);
//System.out.println(tweedeGetal);
if(eersteGetal!= "" && tweedeGetal != ""){
if(operatie == "+" ){
uitkomst = Double.parseDouble(eersteGetal) + Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "-"){
uitkomst = Double.parseDouble(eersteGetal) - Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "/"){
uitkomst = Double.parseDouble(eersteGetal) / Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "*"){
uitkomst = Double.parseDouble(eersteGetal) * Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "^"){
uitkomst = Double.parseDouble(eersteGetal) * Double.parseDouble(eersteGetal); //heb dit gebruikt ipv math.pow
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
}
}
}//GEN-LAST:event_uitrekenenActionPerformed
/* het is mij niet echt gelukt om een manier te vinden om het resultaat
* van het machtsverheffen te laten weergeven, aangezien mijn rekenmachine
* eerst twee inputs wilt hebben.
* heb geprobeerd om het op een andere manier te doen (zie de comments in
* invoermacht) maar dat lukte ook niet echt. het kan het in iedergeval wel
* uitrekenen.
*/
/**
* @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(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Telraam.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 Telraam().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton clearbutton;
private javax.swing.JButton invoer0;
private javax.swing.JButton invoer1;
private javax.swing.JButton invoer2;
private javax.swing.JButton invoer3;
private javax.swing.JButton invoer4;
private javax.swing.JButton invoer5;
private javax.swing.JButton invoer6;
private javax.swing.JButton invoer7;
private javax.swing.JButton invoer8;
private javax.swing.JButton invoer9;
private javax.swing.JButton invoerdelen;
private javax.swing.JButton invoerkeer;
private javax.swing.JButton invoerkomma;
private javax.swing.JButton invoermacht;
private javax.swing.JButton invoermin;
private javax.swing.JButton invoerplus;
private javax.swing.JTextField jTextField1;
private javax.swing.JButton uitrekenen;
// End of variables declaration//GEN-END:variables
}
| 0974201/rekenmachine2 | src/rekenmachine/Telraam.java | 6,708 | //if statement gemaakt om te controleren of er al iets is ingevoerd | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rekenmachine;
/**
*
* @author adeliae
*/
public class Telraam extends javax.swing.JFrame {
//"" achter strings gezet om te voorkomen dat null als input wordt gegeven
String eersteGetal = "";
String tweedeGetal = "";
String invoer = "";
String operatie = "";
String antwoord = "";
double uitkomst;
/**
* Creates new form Telraam
*/
public Telraam() {
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() {
jTextField1 = new javax.swing.JTextField();
invoer7 = new javax.swing.JButton();
invoer8 = new javax.swing.JButton();
invoer9 = new javax.swing.JButton();
invoer4 = new javax.swing.JButton();
invoer5 = new javax.swing.JButton();
invoer6 = new javax.swing.JButton();
invoer1 = new javax.swing.JButton();
invoer2 = new javax.swing.JButton();
invoer3 = new javax.swing.JButton();
invoer0 = new javax.swing.JButton();
invoerkomma = new javax.swing.JButton();
clearbutton = new javax.swing.JButton();
invoerplus = new javax.swing.JButton();
invoermin = new javax.swing.JButton();
invoerdelen = new javax.swing.JButton();
invoerkeer = new javax.swing.JButton();
invoermacht = new javax.swing.JButton();
uitrekenen = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Rekenmachine");
setName("telraamForm"); // NOI18N
invoer7.setText("7");
invoer7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer7ActionPerformed(evt);
}
});
invoer8.setText("8");
invoer8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer8ActionPerformed(evt);
}
});
invoer9.setText("9");
invoer9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer9ActionPerformed(evt);
}
});
invoer4.setText("4");
invoer4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer4ActionPerformed(evt);
}
});
invoer5.setText("5");
invoer5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer5ActionPerformed(evt);
}
});
invoer6.setText("6");
invoer6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer6ActionPerformed(evt);
}
});
invoer1.setText("1");
invoer1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer1ActionPerformed(evt);
}
});
invoer2.setText("2");
invoer2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer2ActionPerformed(evt);
}
});
invoer3.setText("3");
invoer3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer3ActionPerformed(evt);
}
});
invoer0.setText("0");
invoer0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoer0ActionPerformed(evt);
}
});
invoerkomma.setText(".");
invoerkomma.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerkommaActionPerformed(evt);
}
});
clearbutton.setText("C");
clearbutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearbuttonActionPerformed(evt);
}
});
invoerplus.setText("+");
invoerplus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerplusActionPerformed(evt);
}
});
invoermin.setText("-");
invoermin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerminActionPerformed(evt);
}
});
invoerdelen.setText("/");
invoerdelen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerdelenActionPerformed(evt);
}
});
invoerkeer.setText("*");
invoerkeer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoerkeerActionPerformed(evt);
}
});
invoermacht.setText("^");
invoermacht.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
invoermachtActionPerformed(evt);
}
});
uitrekenen.setText("=");
uitrekenen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
uitrekenenActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(invoer1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(invoer4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(clearbutton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoer8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer0, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoer9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoer3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerkomma, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(uitrekenen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoermacht, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(invoerplus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoermin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerdelen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(invoerkeer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer7, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer8, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer9, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerplus, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer4, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer5, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer6, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoermin, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoer3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerdelen, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(invoer0, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerkomma, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(clearbutton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(invoerkeer, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(invoermacht, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
.addComponent(uitrekenen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//tijd om de knopjes een functie te geven ヾ(*・ω・)ノ゜+.゜★ィェィ☆゜+.゜ヾ(・ω・*)ノ
private void invoer7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer7ActionPerformed
String invoerGetal = jTextField1.getText() + invoer7.getText();
jTextField1.setText(invoerGetal);
//if st<SUF>
//zodat je niet telkens op de c knop hoeft te klikken om een nieuwe
//berekening te maken. (alleen gaat er na drie berekeningen iets mis oopsΣ(っ゚Д゚;)っ )
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 7;
} else{
invoer += 7;
}
}//GEN-LAST:event_invoer7ActionPerformed
private void invoer8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer8ActionPerformed
String invoerGetal = jTextField1.getText() + invoer8.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 8;
} else{
invoer += 8;
}
}//GEN-LAST:event_invoer8ActionPerformed
private void invoer9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer9ActionPerformed
String invoerGetal = jTextField1.getText() + invoer9.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 9;
} else{
invoer += 9;
}
}//GEN-LAST:event_invoer9ActionPerformed
private void invoer4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer4ActionPerformed
String invoerGetal = jTextField1.getText() + invoer4.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 4;
} else{
invoer += 4;
}
}//GEN-LAST:event_invoer4ActionPerformed
private void invoer5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer5ActionPerformed
String invoerGetal = jTextField1.getText() + invoer5.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 5;
} else{
invoer += 5;
}
}//GEN-LAST:event_invoer5ActionPerformed
private void invoer6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer6ActionPerformed
String invoerGetal = jTextField1.getText() + invoer6.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 6;
} else{
invoer += 6;
}
}//GEN-LAST:event_invoer6ActionPerformed
private void invoer1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer1ActionPerformed
String invoerGetal = jTextField1.getText() + invoer1.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 1;
} else{
invoer += 1;
}
}//GEN-LAST:event_invoer1ActionPerformed
private void invoer2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer2ActionPerformed
String invoerGetal = jTextField1.getText() + invoer2.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 2;
} else{
invoer += 2;
}
}//GEN-LAST:event_invoer2ActionPerformed
private void invoer3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer3ActionPerformed
String invoerGetal = jTextField1.getText() + invoer3.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 3;
} else{
invoer += 3;
}
}//GEN-LAST:event_invoer3ActionPerformed
private void invoer0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoer0ActionPerformed
String invoerGetal = jTextField1.getText() + invoer0.getText();
jTextField1.setText(invoerGetal);
if(eersteGetal != "" && tweedeGetal != ""){
eersteGetal = antwoord;
invoer += 0;
} else{
invoer += 0;
}
}//GEN-LAST:event_invoer0ActionPerformed
private void invoerkommaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerkommaActionPerformed
String invoerGetal = jTextField1.getText() + invoerkomma.getText();
jTextField1.setText(invoerGetal);
invoer += ".";
}//GEN-LAST:event_invoerkommaActionPerformed
private void clearbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearbuttonActionPerformed
jTextField1.setText("");
eersteGetal = "";
tweedeGetal = "";
invoer = "";
}//GEN-LAST:event_clearbuttonActionPerformed
private void invoerplusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerplusActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("+");
eersteGetal = invoer;
invoer = "";
operatie = "+";
}//GEN-LAST:event_invoerplusActionPerformed
private void invoerminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerminActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("-");
eersteGetal = invoer;
invoer = "";
operatie = "-";
}//GEN-LAST:event_invoerminActionPerformed
private void invoerdelenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerdelenActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("/");
eersteGetal = invoer;
invoer = "";
operatie = "/";
}//GEN-LAST:event_invoerdelenActionPerformed
private void invoerkeerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoerkeerActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("*");
eersteGetal = invoer;
invoer = "";
operatie = "*";
//hhahaa ben opnieuw begonnen omdat ik de in de vorige versie
//de vermenigvuldig functie was vergeten te maken
//good job me (屮゜Д゜)屮
}//GEN-LAST:event_invoerkeerActionPerformed
private void invoermachtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoermachtActionPerformed
eersteGetal = jTextField1.getText();
jTextField1.setText("^");
eersteGetal = invoer;
//int uitreken = Integer.parseInt(invoer) * Integer.parseInt(invoer);
//eersteGetal = uitreken + "";
invoer = "";
operatie = "^";
//System.out.println(eersteGetal);
//eersteGetal = uitkomst + "";
//jTextField1.setText(eersteGetal);
}//GEN-LAST:event_invoermachtActionPerformed
private void uitrekenenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uitrekenenActionPerformed
//TO INFINITY AND BEYOOOOOOOOOOOOOOOOOOOOND ゚+.(ノ。'▽')ノ*.オオォォ☆゚・:*☆
//hier wordt alles berekend
tweedeGetal = invoer;
//System.out.println(eersteGetal);
//System.out.println(tweedeGetal);
if(eersteGetal!= "" && tweedeGetal != ""){
if(operatie == "+" ){
uitkomst = Double.parseDouble(eersteGetal) + Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "-"){
uitkomst = Double.parseDouble(eersteGetal) - Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "/"){
uitkomst = Double.parseDouble(eersteGetal) / Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "*"){
uitkomst = Double.parseDouble(eersteGetal) * Double.parseDouble(tweedeGetal);
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
} else if(operatie == "^"){
uitkomst = Double.parseDouble(eersteGetal) * Double.parseDouble(eersteGetal); //heb dit gebruikt ipv math.pow
antwoord = uitkomst + "";
jTextField1.setText(antwoord);
}
}
}//GEN-LAST:event_uitrekenenActionPerformed
/* het is mij niet echt gelukt om een manier te vinden om het resultaat
* van het machtsverheffen te laten weergeven, aangezien mijn rekenmachine
* eerst twee inputs wilt hebben.
* heb geprobeerd om het op een andere manier te doen (zie de comments in
* invoermacht) maar dat lukte ook niet echt. het kan het in iedergeval wel
* uitrekenen.
*/
/**
* @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(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Telraam.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Telraam.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 Telraam().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton clearbutton;
private javax.swing.JButton invoer0;
private javax.swing.JButton invoer1;
private javax.swing.JButton invoer2;
private javax.swing.JButton invoer3;
private javax.swing.JButton invoer4;
private javax.swing.JButton invoer5;
private javax.swing.JButton invoer6;
private javax.swing.JButton invoer7;
private javax.swing.JButton invoer8;
private javax.swing.JButton invoer9;
private javax.swing.JButton invoerdelen;
private javax.swing.JButton invoerkeer;
private javax.swing.JButton invoerkomma;
private javax.swing.JButton invoermacht;
private javax.swing.JButton invoermin;
private javax.swing.JButton invoerplus;
private javax.swing.JTextField jTextField1;
private javax.swing.JButton uitrekenen;
// End of variables declaration//GEN-END:variables
}
|
87789_1 |
package mongodbtest;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
*
* @author Alex
*/
// Er is geen mapreduce, lambda functies verwerken in java was te tijd rovend naar het uitvinden van hoe mongoDB werkt
public class MongoDBTest<T>{
public static void main(String[] args) throws UnknownHostException {
DB db = (new MongoClient("localhost",27017)).getDB("Hro");//database
DBCollection colEmployee = db.getCollection("Employee");//table
List<String> listName = new ArrayList<>(Arrays.asList("Peter","Jay","Mike","Sally","Michel","Bob","Jenny"));
List<String> listSurname = new ArrayList<>(Arrays.asList("Ra","Grey","Uks","Bla","Woo","Foo","Lu"));
List<String> listOccupation = new ArrayList<>(Arrays.asList("Analyst","Developer","Tester"));
List<Integer> listHours = new ArrayList<>(Arrays.asList(4,5,6,19,20,21));
// Forloop dient als een generator die gebruik maakt van een random method
/////////////////////////////////////////////////
//// Generate random database info /////
/////////////////////////////////////////////////
for(int i = 11000; i < 21000;i++){ // creëren hiermee bsn nummers van 5 cijfers
String json = "{'e_bsn': '" + Integer.toString(i) + "', 'Name':'" + getRandomItem(listName) +"','Surname':'" + getRandomItem(listSurname) +"'"
+ ",'building_name':'H-Gebouw'"
+ ",'address':[{'country': 'Nederland','Postal_code':'3201TL','City':'Spijkenisse','Street':'Wagenmaker','house_nr':25},"
+ "{'country': 'Nederland','Postal_code':'3201RR','City':'Spijkenisse','Street':'Slaanbreek','house_nr':126}],"
+ "'Position_project': [{'p_id': 'P" + Integer.toString(i%100) + "','position_project':'"+ getRandomItem(listOccupation) // modulo zorgt voor projecten P0 t/m P99
+"', 'worked_hours':"+ getRandomItem(listHours) +"}],"
+ "'degree_employee': [{'Course':'Informatica','School':'HogeSchool Rotterdam','Level':'Bachelorr'}]}";
DBObject dbObject = (DBObject)JSON.parse(json);//parser
colEmployee.insert(dbObject);// insert in database
}
BasicDBObject fields = new BasicDBObject();
fields.put("e_bsn", 1);//get only 1 field
BasicDBObject uWQuery = new BasicDBObject();
uWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", -1).append("$lt", 5));//underworking
BasicDBObject nWQuery = new BasicDBObject();
nWQuery.put("Position_project.worked_hours", new BasicDBObject("$gte", 5).append("$lte", 20));//working normal
BasicDBObject oWQuery = new BasicDBObject();
oWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", 20));//overwork
BasicDBObject pidQuery = new BasicDBObject();
pidQuery.put("Position_project.p_id", new BasicDBObject("$eq", "P20"));//work in project
BasicDBObject hourQuery = new BasicDBObject();
hourQuery.put("Position_project.worked_hours", new BasicDBObject("$eq", 20));//overwork
BasicDBObject nameQuery = new BasicDBObject();
nameQuery.put("e_bsn", new BasicDBObject("$eq", "11200"));//find e_bsn
DBCursor cursorDocJSON = colEmployee.find(nameQuery,fields); //get documents USE the QUERY and the FIELDS
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
colEmployee.remove(new BasicDBObject());
}
static Random rand = new Random();
static <T> T getRandomItem(List<T> list) {
return list.get(rand.nextInt(list.size()));
}
} | 0NightBot0/DevDatabase | assignment 2/MongoDB/src/mongodbtest/MongoDBTest.java | 1,099 | // Er is geen mapreduce, lambda functies verwerken in java was te tijd rovend naar het uitvinden van hoe mongoDB werkt | line_comment | nl |
package mongodbtest;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
*
* @author Alex
*/
// Er is<SUF>
public class MongoDBTest<T>{
public static void main(String[] args) throws UnknownHostException {
DB db = (new MongoClient("localhost",27017)).getDB("Hro");//database
DBCollection colEmployee = db.getCollection("Employee");//table
List<String> listName = new ArrayList<>(Arrays.asList("Peter","Jay","Mike","Sally","Michel","Bob","Jenny"));
List<String> listSurname = new ArrayList<>(Arrays.asList("Ra","Grey","Uks","Bla","Woo","Foo","Lu"));
List<String> listOccupation = new ArrayList<>(Arrays.asList("Analyst","Developer","Tester"));
List<Integer> listHours = new ArrayList<>(Arrays.asList(4,5,6,19,20,21));
// Forloop dient als een generator die gebruik maakt van een random method
/////////////////////////////////////////////////
//// Generate random database info /////
/////////////////////////////////////////////////
for(int i = 11000; i < 21000;i++){ // creëren hiermee bsn nummers van 5 cijfers
String json = "{'e_bsn': '" + Integer.toString(i) + "', 'Name':'" + getRandomItem(listName) +"','Surname':'" + getRandomItem(listSurname) +"'"
+ ",'building_name':'H-Gebouw'"
+ ",'address':[{'country': 'Nederland','Postal_code':'3201TL','City':'Spijkenisse','Street':'Wagenmaker','house_nr':25},"
+ "{'country': 'Nederland','Postal_code':'3201RR','City':'Spijkenisse','Street':'Slaanbreek','house_nr':126}],"
+ "'Position_project': [{'p_id': 'P" + Integer.toString(i%100) + "','position_project':'"+ getRandomItem(listOccupation) // modulo zorgt voor projecten P0 t/m P99
+"', 'worked_hours':"+ getRandomItem(listHours) +"}],"
+ "'degree_employee': [{'Course':'Informatica','School':'HogeSchool Rotterdam','Level':'Bachelorr'}]}";
DBObject dbObject = (DBObject)JSON.parse(json);//parser
colEmployee.insert(dbObject);// insert in database
}
BasicDBObject fields = new BasicDBObject();
fields.put("e_bsn", 1);//get only 1 field
BasicDBObject uWQuery = new BasicDBObject();
uWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", -1).append("$lt", 5));//underworking
BasicDBObject nWQuery = new BasicDBObject();
nWQuery.put("Position_project.worked_hours", new BasicDBObject("$gte", 5).append("$lte", 20));//working normal
BasicDBObject oWQuery = new BasicDBObject();
oWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", 20));//overwork
BasicDBObject pidQuery = new BasicDBObject();
pidQuery.put("Position_project.p_id", new BasicDBObject("$eq", "P20"));//work in project
BasicDBObject hourQuery = new BasicDBObject();
hourQuery.put("Position_project.worked_hours", new BasicDBObject("$eq", 20));//overwork
BasicDBObject nameQuery = new BasicDBObject();
nameQuery.put("e_bsn", new BasicDBObject("$eq", "11200"));//find e_bsn
DBCursor cursorDocJSON = colEmployee.find(nameQuery,fields); //get documents USE the QUERY and the FIELDS
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
colEmployee.remove(new BasicDBObject());
}
static Random rand = new Random();
static <T> T getRandomItem(List<T> list) {
return list.get(rand.nextInt(list.size()));
}
} |
158349_78 | package com.spaceproject.math;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import java.math.BigDecimal;
import java.util.Arrays;
/**
* Disclaimer: I am not a physicist. There may be errata but I will do my best.
* Sources:
* https://en.wikipedia.org/wiki/Black-body_radiation
* https://en.wikipedia.org/wiki/Planck%27s_law
* https://en.wikipedia.org/wiki/Wien%27s_displacement_law
* https://en.wikipedia.org/wiki/Rayleigh%E2%80%93Jeans_law
* https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law
* https://en.wikipedia.org/wiki/Stellar_classification
*
* https://www.fourmilab.ch/documents/specrend/
* https://en.wikipedia.org/wiki/CIE_1931_color_space#Color_matching_functions
*
* Wolfram Alpha for testing and confirming formulas and values.
* https://www.wolframalpha.com/widgets/view.jsp?id=5072e9b72faacd73c9a4e4cb36ad08d
*
* Also found a tool that simulates:
* https://phet.colorado.edu/sims/html/blackbody-spectrum/latest/blackbody-spectrum_en.html
*/
public class Physics {
// ------ Universal Constants ------
// c: Speed of light: 299,792,458 (meters per second)
public static final long speedOfLight = 299792458; //m/s
// h: Planck's constant: 6.626 × 10^-34 (Joule seconds)
public static final double planckConstant = 6.626 * Math.pow(10, -34); //Js
public static final BigDecimal planckBig = new BigDecimal("6.62607015").movePointLeft(34);
// h*c: precalculated planckConstant * speedOfLight = 1.98644586...× 10^−25 J⋅m
public static final double hc = planckConstant * speedOfLight;
public static final BigDecimal hcBig = new BigDecimal("1.98644586").movePointLeft(25);
public static final BigDecimal hcCalculated = planckBig.multiply(new BigDecimal(speedOfLight));
// k: Boltzmann constant: 1.380649 × 10^-23 J⋅K (Joules per Kelvin)
public static final double boltzmannConstant = 1.380649 * Math.pow(10, -23); //JK
public static final BigDecimal boltzmannBig = new BigDecimal("1.380649").movePointLeft(23); //JK
// b: Wien's displacement constant: 2.897771955 × 10−3 m⋅K,[1] or b ≈ 2898 μm⋅K
public static final double wiensConstant = 2.8977719; //mK
// G: Gravitational constant: 6.674×10−11 Nm^2 / kg^2 (newton square meters per kilogram squared)
public static final double gravitationalConstant = 6.674 * Math.pow(10, -11);
// ? : not sure what to call this, but it doesn't change so we can precalculate it
public static final double unnamedConstant = (2 * planckConstant * Math.pow(speedOfLight, 2));
/** Wien's displacement law: λₘT = b
* Hotter things - peak at shorter wavelengths - bluer
* Cooler things - peak at longer wavelengths - redder
* λₘ = The maximum wavelength in nanometers corresponding to peak intensity
* T = The absolute temperature in kelvin
* b = Wein’s Constant: 2.88 x 10-3 m-K or 0.288 cm-K
*/
public static double temperatureToWavelength(double kelvin) {
return wiensConstant / kelvin;
}
/** T = b / λₘ */
public static double wavelengthToTemperature(double wavelength) {
return wiensConstant / wavelength;
}
/** ν = c / λ
* ν = frequency (hertz)
* λ = wavelength (nanometers)
* c = speed of light
*/
public static double wavelengthToFrequency(double wavelength) {
return speedOfLight / wavelength;
}
/** E = (h * c) / λ
* E = energy
* λ = wavelength (nanometers)
* h = planck constant
* c = speed of light
*/
public static double wavelengthToPhotonEnergy(double wavelength) {
//energy = (planckConstant * speedOfLight) / wavelength;
return hc / wavelength;
}
/** E = hv
* E = energy
* v = frequency (hertz)
* h = planck constant
*/
public static double frequencyToPhotonEnergy(double frequency) {
//energy = planckConstant * frequency;
return planckConstant * frequency;
}
/** Rayleigh–Jeans law: uν = (8 * π * (ν^2) * k * T) / (c^2)
* Note: formula fits low frequencies but fails increasingly for higher frequencies.
* see: "ultraviolet catastrophe"
* uν =
* v = frequency (hertz)
* k = Boltzmann's constant
* T = is the absolute temperature of the radiating bod
* c = speed of light
*/
public static double RayleighJeansLaw(int wavelength) {
double frequency = wavelengthToFrequency(wavelength);
double temperature = wavelengthToTemperature(wavelength);
return (8 * Math.PI * Math.pow(frequency, 2) * boltzmannConstant * temperature) / Math.pow(speedOfLight, 2);
}
/** Planck's law of black-body radiation: L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
* L(λ) = spectral radiance as function of wavelength
* λ = wavelength
* T = temperature of the body Kelvin
* h = Planck constant (≈ 6.626×10^-34 J s)
* c = speed of light (≈ 2.998×10^8 m/s)
* k Boltzmann constant (≈ 1.381×10^-23 J/K)
*/
public static double calcSpectralRadiance(int wavelength, double temperature) {
//L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
//L = (2 * planckConstant * (speedOfLight ^ 2)) /
//((wavelength ^ 5) * (Math.E ^ ( ((planckConstant * speedOfLight) / (wavelength * boltzmannConstant * temperature)) - 1)));
//break down
//double unnamedConstant = (2.0 * planckConstant * Math.pow(speedOfLight, 2));//(2 h c^2)
//double hc = planckConstant * speedOfLight;
double a = wavelength * boltzmannConstant * temperature;
double b = Math.exp(hc / a) - 1; //(e^((h c)/(λ k T)) - 1)
return unnamedConstant / (Math.pow(wavelength, 5) * b);
}
public static void calculateBlackBody(int wavelengthStart, int wavelengthEnd, double temperature) {
//double temperature = 5772;// wavelengthToTemperature(502);
for (int wavelength = wavelengthStart; wavelength <= wavelengthEnd; wavelength++) {
//we can kinda ignore rayleigh jean as we know it will produce incorrect values, just testing
//double r = RayleighJeansLaw(wavelength);
//Gdx.app.debug("Raleigh Jean ", String.format("%s - %g", wavelength, r));
double spectralRadiance = calcSpectralRadiance(wavelength, temperature);
Gdx.app.debug("spectralRadiance", String.format("%s - %g", wavelength, spectralRadiance));
//just a test: i don't think we have a precision issue...
//BigDecimal spectralBigDecimal = calcSpectralRadianceBig(wavelength);
//Gdx.app.debug("spectral precise", wavelength + " - " + spectralBigDecimal.toPlainString());
}
//expected output: 2.19308090702e+13
// 5772k, 502nm
// Radiant emittance: 6.29403e+07 W/m2
// Radiance: 2.00345e+07 W/m2/sr
// Peak spectral radiance: 2.19308090702e+13 (W*sr-1*m-3)
// 26239737.802334465 (W/m2-sr-um)
// Spectral Radiance: 4207.38 W/m2/sr/µm (5.03412e+19 photons/J)
//
//current broken outputs:
// [Raleigh Jean ] 502 - 7.94834e-30
// [spectralRadiance] 502 - 1.01051e-29
// [spectral precise] 502 - 0.000000000000000000000000000010105
//502 - 1.17864e+13
//1.01051e-29
//7.50587e-28
//7.52394e-22
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm
* Ported from: RGB VALUES FOR VISIBLE WAVELENGTHS by Dan Bruton ([email protected])
* http://www.physics.sfasu.edu/astro/color/spectra.html
*/
public static int[] wavelengthToRGB(double wavelength, double gamma) {
double factor;
double red, green, blue;
if ((wavelength >= 380) && (wavelength < 440)) {
red = -(wavelength - 440) / (440 - 380);
green = 0.0;
blue = 1.0;
} else if ((wavelength >= 440) && (wavelength < 490)) {
red = 0.0;
green = (wavelength - 440) / (490 - 440);
blue = 1.0;
} else if ((wavelength >= 490) && (wavelength < 510)) {
red = 0.0;
green = 1.0;
blue = -(wavelength - 510) / (510 - 490);
} else if ((wavelength >= 510) && (wavelength < 580)) {
red = (wavelength - 510) / (580 - 510);
green = 1.0;
blue = 0.0;
} else if ((wavelength >= 580) && (wavelength < 645)) {
red = 1.0;
green = -(wavelength - 645) / (645 - 580);
blue = 0.0;
} else if ((wavelength >= 645) && (wavelength < 781)) {
red = 1.0;
green = 0.0;
blue = 0.0;
} else {
red = 0.0;
green = 0.0;
blue = 0.0;
}
// Let the intensity fall off near the vision limits
if ((wavelength >= 380) && (wavelength < 420)) {
factor = 0.3 + 0.7 * (wavelength - 380) / (420 - 380);
} else if ((wavelength >= 420) && (wavelength < 701)) {
factor = 1.0;
} else if ((wavelength >= 701) && (wavelength < 781)) {
factor = 0.3 + 0.7 * (780 - wavelength) / (780 - 700);
} else {
factor = 0.0;
}
// Don't want 0^x = 1 for x <> 0
final double intensityMax = 255;
int[] rgb = new int[3];
rgb[0] = red == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(red * factor, gamma));
rgb[1] = green == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(green * factor, gamma));
rgb[2] = blue == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(blue * factor, gamma));
return rgb;
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm with a default gamma of 0.8 */
public static int[] wavelengthToRGB(double wavelength) {
return wavelengthToRGB(wavelength, 0.8);
}
public static void test() {
/* Black Body Radiation!
* Common color temperatures (Kelvin):
* 1900 Candle flame
* 2000 Sunlight at sunset
* 2800 Tungsten bulb—60 watt
* 2900 Tungsten bulb—200 watt
* 3300 Tungsten/halogen lamp
* 3780 Carbon arc lamp
* 5500 Sunlight plus skylight
* 5772 Sun "effective temperature"
* 6000 Xenon strobe light
* 6500 Overcast sky
* 7500 North sky light
*
* Harvard spectral classification
* O ≥ 33,000 K blue
* B 10,000–33,000 K blue white
* A 7,500–10,000 K white
* F 6,000–7,500 K yellow white
* G 5,200–6,000 K yellow
* K 3,700–5,200 K orange
* M 2,000–3,700 K red
* R 1,300–2,000 K red
* N 1,300–2,000 K red
* S 1,300–2,000 K red
*/
//Known sun values: 5772K | 502nm | 597.2 terahertz | 2.47 eV
double kelvin = Sun.kelvin; //5772
double expectedWavelength = 502;
double expectedFrequency = 597.2;
double expectedEnergy = 2.47;
double calculatedWavelength = temperatureToWavelength(kelvin);
double calculatedTemperature = wavelengthToTemperature(expectedWavelength);
double calculatedFrequency = wavelengthToFrequency(expectedWavelength);
Gdx.app.debug("PhysicsDebug", kelvin + " K = " + MyMath.round(calculatedWavelength * 1000000, 1) + " nm");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedTemperature * 1000000, 1) + " K");
Gdx.app.debug("PhysicsDebug", "temp(wave(" + kelvin + ")) = " + wavelengthToTemperature(calculatedWavelength));
Gdx.app.debug("PhysicsDebug", "wave(temp(" + expectedWavelength +")) = " + temperatureToWavelength(calculatedTemperature));
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedFrequency / 1000, 1) + " THz");
Gdx.app.debug("PhysicsDebug", "wavelength expected: " + MathUtils.isEqual((float)calculatedWavelength * 1000000, (float) expectedWavelength, 0.1f));
Gdx.app.debug("PhysicsDebug", "temperature expected: " + MathUtils.isEqual((float)calculatedTemperature * 1000000, (float) kelvin, 0.5f));
//Gdx.app.debug("PhysicsDebug", "frequency expected: " + MathUtils.isEqual((float)calculatedFrequency , (float) expectedFrequency, 0.1f));
//todo: photon energy calculations are returning 3.95706346613546E-28, expecting 2.47 eV
// bug: planck is coming out as -291.54400000000004. expected: 6.626 * (10 ^ -34)
// update, turns out i need to use math.pow, not ^ [^ = Bitwise exclusive OR] ....i'm a little rusty
// have we hit the Double.MIN_EXPONENT...is there a precision bug or is my math wrong?
// frequencyToPhotonEnergy: 502.0 nm = 3.9570634604560330026360810734331607818603515625E-28 eV
// wavelengthToPhotonEnergy: 502.0 nm = 3.95706346613546E-28 eV
// expected: 2.47 eV
// photonEnergy 0.000000000000000000000000198644586 precision: 47 - scale: 74
Gdx.app.debug("PhysicsDebug", "planck double: " + planckConstant);
Gdx.app.debug("PhysicsDebug", "size of double: [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE
+ "] exp: [" + Double.MIN_EXPONENT + " to " + Double.MAX_EXPONENT + "]");
//high precision big decimals
Gdx.app.debug("PhysicsDebug","planck bigdecimal: " + planckBig.toString() + " -> " + planckBig.toPlainString()
+ " | precision: " + planckBig.precision() + " - scale: " + planckBig.scale());
Gdx.app.debug("PhysicsDebug","h * c def: " + hcBig.toPlainString()
+ " | precision: " + hcBig.precision() + " - scale: " + hcBig.scale());
Gdx.app.debug("PhysicsDebug","h * c calc: " + hcCalculated.toString() + " -> " + hcCalculated.toPlainString()
+ " | precision: " + hcCalculated.precision() + " - scale: " + hcCalculated.scale());
//BigDecimal photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
//Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy.toString() + " eV -> " + hcBig.toPlainString() + " | precision: " + photonEnergy.precision() + " - scale: " + photonEnergy.scale());
double photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy + " eV ");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + wavelengthToPhotonEnergy(expectedWavelength) + " eV");
/* A typical human eye will respond to wavelengths from about 380 to about 750 nanometers.
* Tristimulus values: The human eye with normal vision has three kinds of cone cells that sense light, having peaks of spectral sensitivity in
* short 420 nm – 440 nm
* middle 530 nm – 540 nm
* long 560 nm – 580 nm
*
* Typical color ranges:
* Color Wavelength(nm) Frequency(THz)
* Red 620-750 484-400
* Orange 590-620 508-484
* Yellow 570-590 526-508
* Green 495-570 606-526
* Blue 450-495 668-606
* Violet 380-450 789-668
*/
double gamma = 0.8;
int red = 650;
int green = 540;
int blue = 470;
Gdx.app.debug("PhysicsDebug", expectedWavelength + " -> " + Arrays.toString(wavelengthToRGB(expectedWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", red + " -> " + Arrays.toString(wavelengthToRGB(red, gamma)));//red-ish
Gdx.app.debug("PhysicsDebug", green + " -> " + Arrays.toString(wavelengthToRGB(green, gamma)));//green-ish
Gdx.app.debug("PhysicsDebug", blue + " -> " + Arrays.toString(wavelengthToRGB(blue, gamma)));//blue-ish
//wavelengthToRGB() approximates 380 nm and 780 nm
int rgbMinWavelength = 380;
int rgbMaxWavelength = 780;
double lowestVisibleTemperature = wavelengthToTemperature(rgbMinWavelength);
double highestVisibleTemperature = wavelengthToTemperature(rgbMaxWavelength);
Gdx.app.debug("PhysicsDebug", "380nm to 780nm = " + MyMath.round(lowestVisibleTemperature * 1000000, 1)
+ "K" + " to " + MyMath.round(highestVisibleTemperature * 1000000, 1) + "K");
Gdx.app.debug("PhysicsDebug", rgbMinWavelength + "nm " + MyMath.round(lowestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMinWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", rgbMaxWavelength + "nm " + MyMath.round(highestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMaxWavelength, gamma)));
//calculateBlackBody(rgbMinWavelength, rgbMaxWavelength, kelvin);
//calculateBlackBody(380, 400);
BlackBodyColorSpectrum.test();
// 5772 K -> xyz 0.3266 0.3359 0.3376 -> rgb 1.000 0.867 0.813
Vector3 spectrum = BlackBodyColorSpectrum.spectrumToXYZ(kelvin);
Vector3 color = BlackBodyColorSpectrum.xyzToRGB(BlackBodyColorSpectrum.SMPTEsystem, spectrum.x, spectrum.y, spectrum.z);
String xyzTemp = String.format(" %5.0f K %.4f %.4f %.4f ", kelvin, spectrum.x, spectrum.y, spectrum.z);
if (BlackBodyColorSpectrum.constrainRGB(color)) {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", normal.x, normal.y, normal.z));
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", color.z, color.y, color.z));
} else {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f", color.x, color.y, color.z));
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f", normal.x, normal.y, normal.z));
}
}
public static class Sun {
public static final String spectralClass = "GV2 (main sequence)";
//mass: nominal solar mass parameter: GM⊙ = 1.3271244 × 10^20 m3 s−2 or 1.9885 × 10^30 kg.
public static final double mass = 1.9885 * Math.pow(10, 30);//kg
//radius: nominal solar radius R⊙ = 6.957 × 10^8 m
public static final double radius = 6.957 * Math.pow(10, 8);//m
//effective temperature
public static final double kelvin = 5772; //K
//5772K = 502nm = 597 THz = green light
public static final double peakWavelength = temperatureToWavelength(kelvin) * 1000000;
//luminosity: 1 sol -> L⊙ = nominal solar luminosity: L⊙ = 3.828 × 10^26 W
public static final double luminosity = 3.828 * Math.pow(10, 26); //Watts
//public static final age = 4.78 billion years
//AU Astronomical unit: roughly the distance from Earth to the Sun ~1.495978707 × 10^11 m
public static final long astronomicalUnit = 149597870700L;
}
}
| 0XDE57/SpaceProject | core/src/com/spaceproject/math/Physics.java | 6,603 | //5772K = 502nm = 597 THz = green light | line_comment | nl | package com.spaceproject.math;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import java.math.BigDecimal;
import java.util.Arrays;
/**
* Disclaimer: I am not a physicist. There may be errata but I will do my best.
* Sources:
* https://en.wikipedia.org/wiki/Black-body_radiation
* https://en.wikipedia.org/wiki/Planck%27s_law
* https://en.wikipedia.org/wiki/Wien%27s_displacement_law
* https://en.wikipedia.org/wiki/Rayleigh%E2%80%93Jeans_law
* https://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law
* https://en.wikipedia.org/wiki/Stellar_classification
*
* https://www.fourmilab.ch/documents/specrend/
* https://en.wikipedia.org/wiki/CIE_1931_color_space#Color_matching_functions
*
* Wolfram Alpha for testing and confirming formulas and values.
* https://www.wolframalpha.com/widgets/view.jsp?id=5072e9b72faacd73c9a4e4cb36ad08d
*
* Also found a tool that simulates:
* https://phet.colorado.edu/sims/html/blackbody-spectrum/latest/blackbody-spectrum_en.html
*/
public class Physics {
// ------ Universal Constants ------
// c: Speed of light: 299,792,458 (meters per second)
public static final long speedOfLight = 299792458; //m/s
// h: Planck's constant: 6.626 × 10^-34 (Joule seconds)
public static final double planckConstant = 6.626 * Math.pow(10, -34); //Js
public static final BigDecimal planckBig = new BigDecimal("6.62607015").movePointLeft(34);
// h*c: precalculated planckConstant * speedOfLight = 1.98644586...× 10^−25 J⋅m
public static final double hc = planckConstant * speedOfLight;
public static final BigDecimal hcBig = new BigDecimal("1.98644586").movePointLeft(25);
public static final BigDecimal hcCalculated = planckBig.multiply(new BigDecimal(speedOfLight));
// k: Boltzmann constant: 1.380649 × 10^-23 J⋅K (Joules per Kelvin)
public static final double boltzmannConstant = 1.380649 * Math.pow(10, -23); //JK
public static final BigDecimal boltzmannBig = new BigDecimal("1.380649").movePointLeft(23); //JK
// b: Wien's displacement constant: 2.897771955 × 10−3 m⋅K,[1] or b ≈ 2898 μm⋅K
public static final double wiensConstant = 2.8977719; //mK
// G: Gravitational constant: 6.674×10−11 Nm^2 / kg^2 (newton square meters per kilogram squared)
public static final double gravitationalConstant = 6.674 * Math.pow(10, -11);
// ? : not sure what to call this, but it doesn't change so we can precalculate it
public static final double unnamedConstant = (2 * planckConstant * Math.pow(speedOfLight, 2));
/** Wien's displacement law: λₘT = b
* Hotter things - peak at shorter wavelengths - bluer
* Cooler things - peak at longer wavelengths - redder
* λₘ = The maximum wavelength in nanometers corresponding to peak intensity
* T = The absolute temperature in kelvin
* b = Wein’s Constant: 2.88 x 10-3 m-K or 0.288 cm-K
*/
public static double temperatureToWavelength(double kelvin) {
return wiensConstant / kelvin;
}
/** T = b / λₘ */
public static double wavelengthToTemperature(double wavelength) {
return wiensConstant / wavelength;
}
/** ν = c / λ
* ν = frequency (hertz)
* λ = wavelength (nanometers)
* c = speed of light
*/
public static double wavelengthToFrequency(double wavelength) {
return speedOfLight / wavelength;
}
/** E = (h * c) / λ
* E = energy
* λ = wavelength (nanometers)
* h = planck constant
* c = speed of light
*/
public static double wavelengthToPhotonEnergy(double wavelength) {
//energy = (planckConstant * speedOfLight) / wavelength;
return hc / wavelength;
}
/** E = hv
* E = energy
* v = frequency (hertz)
* h = planck constant
*/
public static double frequencyToPhotonEnergy(double frequency) {
//energy = planckConstant * frequency;
return planckConstant * frequency;
}
/** Rayleigh–Jeans law: uν = (8 * π * (ν^2) * k * T) / (c^2)
* Note: formula fits low frequencies but fails increasingly for higher frequencies.
* see: "ultraviolet catastrophe"
* uν =
* v = frequency (hertz)
* k = Boltzmann's constant
* T = is the absolute temperature of the radiating bod
* c = speed of light
*/
public static double RayleighJeansLaw(int wavelength) {
double frequency = wavelengthToFrequency(wavelength);
double temperature = wavelengthToTemperature(wavelength);
return (8 * Math.PI * Math.pow(frequency, 2) * boltzmannConstant * temperature) / Math.pow(speedOfLight, 2);
}
/** Planck's law of black-body radiation: L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
* L(λ) = spectral radiance as function of wavelength
* λ = wavelength
* T = temperature of the body Kelvin
* h = Planck constant (≈ 6.626×10^-34 J s)
* c = speed of light (≈ 2.998×10^8 m/s)
* k Boltzmann constant (≈ 1.381×10^-23 J/K)
*/
public static double calcSpectralRadiance(int wavelength, double temperature) {
//L(λ) = (2 h c^2) / (λ^5 (e^((h c)/(λ k T)) - 1))
//L = (2 * planckConstant * (speedOfLight ^ 2)) /
//((wavelength ^ 5) * (Math.E ^ ( ((planckConstant * speedOfLight) / (wavelength * boltzmannConstant * temperature)) - 1)));
//break down
//double unnamedConstant = (2.0 * planckConstant * Math.pow(speedOfLight, 2));//(2 h c^2)
//double hc = planckConstant * speedOfLight;
double a = wavelength * boltzmannConstant * temperature;
double b = Math.exp(hc / a) - 1; //(e^((h c)/(λ k T)) - 1)
return unnamedConstant / (Math.pow(wavelength, 5) * b);
}
public static void calculateBlackBody(int wavelengthStart, int wavelengthEnd, double temperature) {
//double temperature = 5772;// wavelengthToTemperature(502);
for (int wavelength = wavelengthStart; wavelength <= wavelengthEnd; wavelength++) {
//we can kinda ignore rayleigh jean as we know it will produce incorrect values, just testing
//double r = RayleighJeansLaw(wavelength);
//Gdx.app.debug("Raleigh Jean ", String.format("%s - %g", wavelength, r));
double spectralRadiance = calcSpectralRadiance(wavelength, temperature);
Gdx.app.debug("spectralRadiance", String.format("%s - %g", wavelength, spectralRadiance));
//just a test: i don't think we have a precision issue...
//BigDecimal spectralBigDecimal = calcSpectralRadianceBig(wavelength);
//Gdx.app.debug("spectral precise", wavelength + " - " + spectralBigDecimal.toPlainString());
}
//expected output: 2.19308090702e+13
// 5772k, 502nm
// Radiant emittance: 6.29403e+07 W/m2
// Radiance: 2.00345e+07 W/m2/sr
// Peak spectral radiance: 2.19308090702e+13 (W*sr-1*m-3)
// 26239737.802334465 (W/m2-sr-um)
// Spectral Radiance: 4207.38 W/m2/sr/µm (5.03412e+19 photons/J)
//
//current broken outputs:
// [Raleigh Jean ] 502 - 7.94834e-30
// [spectralRadiance] 502 - 1.01051e-29
// [spectral precise] 502 - 0.000000000000000000000000000010105
//502 - 1.17864e+13
//1.01051e-29
//7.50587e-28
//7.52394e-22
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm
* Ported from: RGB VALUES FOR VISIBLE WAVELENGTHS by Dan Bruton ([email protected])
* http://www.physics.sfasu.edu/astro/color/spectra.html
*/
public static int[] wavelengthToRGB(double wavelength, double gamma) {
double factor;
double red, green, blue;
if ((wavelength >= 380) && (wavelength < 440)) {
red = -(wavelength - 440) / (440 - 380);
green = 0.0;
blue = 1.0;
} else if ((wavelength >= 440) && (wavelength < 490)) {
red = 0.0;
green = (wavelength - 440) / (490 - 440);
blue = 1.0;
} else if ((wavelength >= 490) && (wavelength < 510)) {
red = 0.0;
green = 1.0;
blue = -(wavelength - 510) / (510 - 490);
} else if ((wavelength >= 510) && (wavelength < 580)) {
red = (wavelength - 510) / (580 - 510);
green = 1.0;
blue = 0.0;
} else if ((wavelength >= 580) && (wavelength < 645)) {
red = 1.0;
green = -(wavelength - 645) / (645 - 580);
blue = 0.0;
} else if ((wavelength >= 645) && (wavelength < 781)) {
red = 1.0;
green = 0.0;
blue = 0.0;
} else {
red = 0.0;
green = 0.0;
blue = 0.0;
}
// Let the intensity fall off near the vision limits
if ((wavelength >= 380) && (wavelength < 420)) {
factor = 0.3 + 0.7 * (wavelength - 380) / (420 - 380);
} else if ((wavelength >= 420) && (wavelength < 701)) {
factor = 1.0;
} else if ((wavelength >= 701) && (wavelength < 781)) {
factor = 0.3 + 0.7 * (780 - wavelength) / (780 - 700);
} else {
factor = 0.0;
}
// Don't want 0^x = 1 for x <> 0
final double intensityMax = 255;
int[] rgb = new int[3];
rgb[0] = red == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(red * factor, gamma));
rgb[1] = green == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(green * factor, gamma));
rgb[2] = blue == 0.0 ? 0 : (int)Math.round(intensityMax * Math.pow(blue * factor, gamma));
return rgb;
}
/** approximate RGB [0-255] values for wavelengths between 380 nm and 780 nm with a default gamma of 0.8 */
public static int[] wavelengthToRGB(double wavelength) {
return wavelengthToRGB(wavelength, 0.8);
}
public static void test() {
/* Black Body Radiation!
* Common color temperatures (Kelvin):
* 1900 Candle flame
* 2000 Sunlight at sunset
* 2800 Tungsten bulb—60 watt
* 2900 Tungsten bulb—200 watt
* 3300 Tungsten/halogen lamp
* 3780 Carbon arc lamp
* 5500 Sunlight plus skylight
* 5772 Sun "effective temperature"
* 6000 Xenon strobe light
* 6500 Overcast sky
* 7500 North sky light
*
* Harvard spectral classification
* O ≥ 33,000 K blue
* B 10,000–33,000 K blue white
* A 7,500–10,000 K white
* F 6,000–7,500 K yellow white
* G 5,200–6,000 K yellow
* K 3,700–5,200 K orange
* M 2,000–3,700 K red
* R 1,300–2,000 K red
* N 1,300–2,000 K red
* S 1,300–2,000 K red
*/
//Known sun values: 5772K | 502nm | 597.2 terahertz | 2.47 eV
double kelvin = Sun.kelvin; //5772
double expectedWavelength = 502;
double expectedFrequency = 597.2;
double expectedEnergy = 2.47;
double calculatedWavelength = temperatureToWavelength(kelvin);
double calculatedTemperature = wavelengthToTemperature(expectedWavelength);
double calculatedFrequency = wavelengthToFrequency(expectedWavelength);
Gdx.app.debug("PhysicsDebug", kelvin + " K = " + MyMath.round(calculatedWavelength * 1000000, 1) + " nm");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedTemperature * 1000000, 1) + " K");
Gdx.app.debug("PhysicsDebug", "temp(wave(" + kelvin + ")) = " + wavelengthToTemperature(calculatedWavelength));
Gdx.app.debug("PhysicsDebug", "wave(temp(" + expectedWavelength +")) = " + temperatureToWavelength(calculatedTemperature));
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + MyMath.round(calculatedFrequency / 1000, 1) + " THz");
Gdx.app.debug("PhysicsDebug", "wavelength expected: " + MathUtils.isEqual((float)calculatedWavelength * 1000000, (float) expectedWavelength, 0.1f));
Gdx.app.debug("PhysicsDebug", "temperature expected: " + MathUtils.isEqual((float)calculatedTemperature * 1000000, (float) kelvin, 0.5f));
//Gdx.app.debug("PhysicsDebug", "frequency expected: " + MathUtils.isEqual((float)calculatedFrequency , (float) expectedFrequency, 0.1f));
//todo: photon energy calculations are returning 3.95706346613546E-28, expecting 2.47 eV
// bug: planck is coming out as -291.54400000000004. expected: 6.626 * (10 ^ -34)
// update, turns out i need to use math.pow, not ^ [^ = Bitwise exclusive OR] ....i'm a little rusty
// have we hit the Double.MIN_EXPONENT...is there a precision bug or is my math wrong?
// frequencyToPhotonEnergy: 502.0 nm = 3.9570634604560330026360810734331607818603515625E-28 eV
// wavelengthToPhotonEnergy: 502.0 nm = 3.95706346613546E-28 eV
// expected: 2.47 eV
// photonEnergy 0.000000000000000000000000198644586 precision: 47 - scale: 74
Gdx.app.debug("PhysicsDebug", "planck double: " + planckConstant);
Gdx.app.debug("PhysicsDebug", "size of double: [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE
+ "] exp: [" + Double.MIN_EXPONENT + " to " + Double.MAX_EXPONENT + "]");
//high precision big decimals
Gdx.app.debug("PhysicsDebug","planck bigdecimal: " + planckBig.toString() + " -> " + planckBig.toPlainString()
+ " | precision: " + planckBig.precision() + " - scale: " + planckBig.scale());
Gdx.app.debug("PhysicsDebug","h * c def: " + hcBig.toPlainString()
+ " | precision: " + hcBig.precision() + " - scale: " + hcBig.scale());
Gdx.app.debug("PhysicsDebug","h * c calc: " + hcCalculated.toString() + " -> " + hcCalculated.toPlainString()
+ " | precision: " + hcCalculated.precision() + " - scale: " + hcCalculated.scale());
//BigDecimal photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
//Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy.toString() + " eV -> " + hcBig.toPlainString() + " | precision: " + photonEnergy.precision() + " - scale: " + photonEnergy.scale());
double photonEnergy = frequencyToPhotonEnergy(calculatedFrequency);
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + photonEnergy + " eV ");
Gdx.app.debug("PhysicsDebug", expectedWavelength + " nm = " + wavelengthToPhotonEnergy(expectedWavelength) + " eV");
/* A typical human eye will respond to wavelengths from about 380 to about 750 nanometers.
* Tristimulus values: The human eye with normal vision has three kinds of cone cells that sense light, having peaks of spectral sensitivity in
* short 420 nm – 440 nm
* middle 530 nm – 540 nm
* long 560 nm – 580 nm
*
* Typical color ranges:
* Color Wavelength(nm) Frequency(THz)
* Red 620-750 484-400
* Orange 590-620 508-484
* Yellow 570-590 526-508
* Green 495-570 606-526
* Blue 450-495 668-606
* Violet 380-450 789-668
*/
double gamma = 0.8;
int red = 650;
int green = 540;
int blue = 470;
Gdx.app.debug("PhysicsDebug", expectedWavelength + " -> " + Arrays.toString(wavelengthToRGB(expectedWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", red + " -> " + Arrays.toString(wavelengthToRGB(red, gamma)));//red-ish
Gdx.app.debug("PhysicsDebug", green + " -> " + Arrays.toString(wavelengthToRGB(green, gamma)));//green-ish
Gdx.app.debug("PhysicsDebug", blue + " -> " + Arrays.toString(wavelengthToRGB(blue, gamma)));//blue-ish
//wavelengthToRGB() approximates 380 nm and 780 nm
int rgbMinWavelength = 380;
int rgbMaxWavelength = 780;
double lowestVisibleTemperature = wavelengthToTemperature(rgbMinWavelength);
double highestVisibleTemperature = wavelengthToTemperature(rgbMaxWavelength);
Gdx.app.debug("PhysicsDebug", "380nm to 780nm = " + MyMath.round(lowestVisibleTemperature * 1000000, 1)
+ "K" + " to " + MyMath.round(highestVisibleTemperature * 1000000, 1) + "K");
Gdx.app.debug("PhysicsDebug", rgbMinWavelength + "nm " + MyMath.round(lowestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMinWavelength, gamma)));
Gdx.app.debug("PhysicsDebug", rgbMaxWavelength + "nm " + MyMath.round(highestVisibleTemperature, 1) + "K -> " + Arrays.toString(wavelengthToRGB(rgbMaxWavelength, gamma)));
//calculateBlackBody(rgbMinWavelength, rgbMaxWavelength, kelvin);
//calculateBlackBody(380, 400);
BlackBodyColorSpectrum.test();
// 5772 K -> xyz 0.3266 0.3359 0.3376 -> rgb 1.000 0.867 0.813
Vector3 spectrum = BlackBodyColorSpectrum.spectrumToXYZ(kelvin);
Vector3 color = BlackBodyColorSpectrum.xyzToRGB(BlackBodyColorSpectrum.SMPTEsystem, spectrum.x, spectrum.y, spectrum.z);
String xyzTemp = String.format(" %5.0f K %.4f %.4f %.4f ", kelvin, spectrum.x, spectrum.y, spectrum.z);
if (BlackBodyColorSpectrum.constrainRGB(color)) {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", normal.x, normal.y, normal.z));
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f (Approximation)", color.z, color.y, color.z));
} else {
Vector3 normal = BlackBodyColorSpectrum.normRGB(color.x, color.y, color.z);
//Gdx.app.log(this.getClass().getSimpleName(), xyzTemp + String.format("%.3f %.3f %.3f", color.x, color.y, color.z));
Gdx.app.log("PhysicsDebug", xyzTemp + String.format("%.3f %.3f %.3f", normal.x, normal.y, normal.z));
}
}
public static class Sun {
public static final String spectralClass = "GV2 (main sequence)";
//mass: nominal solar mass parameter: GM⊙ = 1.3271244 × 10^20 m3 s−2 or 1.9885 × 10^30 kg.
public static final double mass = 1.9885 * Math.pow(10, 30);//kg
//radius: nominal solar radius R⊙ = 6.957 × 10^8 m
public static final double radius = 6.957 * Math.pow(10, 8);//m
//effective temperature
public static final double kelvin = 5772; //K
//5772K<SUF>
public static final double peakWavelength = temperatureToWavelength(kelvin) * 1000000;
//luminosity: 1 sol -> L⊙ = nominal solar luminosity: L⊙ = 3.828 × 10^26 W
public static final double luminosity = 3.828 * Math.pow(10, 26); //Watts
//public static final age = 4.78 billion years
//AU Astronomical unit: roughly the distance from Earth to the Sun ~1.495978707 × 10^11 m
public static final long astronomicalUnit = 149597870700L;
}
}
|
194699_31 | /**
* Mengen nichtnegativer ganzer Zahlen in kompakter
* Speicherrepraesentation: ob eine Zahl in der Menge enthalten
* ist, wird durch EIN BIT im Speicher erfasst!
*
* <br>
* Beispiel:
* <br>
* <code>
* <br>IntSet set = new IntSet(8);
* <br>int a[] = { 1, 3, 4, 5 };
* <br>set.include( a );
* <br>
* <br> ... +---+---+---+---+---+---+---+---+
* <br> ... | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 |
* <br> ... +---+---+---+---+---+---+---+---+
* <br></code>
*/
public class IntSet implements Iterable<Integer> {
private static final int BitsPerWord = Integer.SIZE;
// TODO: Instanzvariablen deklarieren
private int capacity;
/**
* Konstruiert ein leere Zahlenmenge der Kapazitaet <code>n</code>:
* eine Menge, die (nichtnegative ganze) Zahlen im
* Bereich 0 bis n-1 als Elemente enthalten kann.
*
* @param n die Kapazitaet der Menge
*/
public IntSet(int n) {
// TODO: Konstruktor implementieren
capacity = n;
}
/**
* Ermittelt die Kapazitaet der Menge.
*
* @return die Kapazitaet der Menge
*/
public int capacity() {
// TODO: Anzahl potenziell enthaltener Elemente zurueckgeben
return capacity;
}
/**
* Erzeugt aus <code>this</code> eine neue (identisch belegte) Zahlenmenge,
* die Werte im Bereich 0 bis n-1 als Elemente enthalten kann.
*
* Die Originalmenge bleibt unveraendert!
*
* @param n die Kapazitaet der Ergebnismenge
* @return die Ergebnismenge mit veraenderter Kapazitaet
*/
public IntSet resize(int n) {
IntSet s = new IntSet(n);
// TODO: urspruengliche Elemente uebernehmen
return s;
}
/**
* Ermittelt, ob eine nicht-negative ganze Zahl in der Menge enthalten ist.
*
* @param e eine nichtnegative ganze Zahl
* @return ist e in dieser Menge enthalten?
*/
public boolean contains(int e) {
// TODO: Bit an der richtigen Stelle isolieren und zurueckgeben
return false;
}
/**
* Nimmt die Zahl <code>e</code> in diese Menge auf.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void insert(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit setzen
}
/**
* Nimmt alle Elemente aus dem Array <code>es</code> in die Menge auf.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void insert(int es[]) {
// TODO: alle Elemente im Array einfuegen
}
/**
* Entfernt die Zahl <code>e</code> aus dieser Menge.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void remove(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit nullen
}
/**
* Entfernt alle Elemente aus dem Array <code>es</code> aus der Menge.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void remove(int[] es) {
// TODO: alle Elemente aus dem Array entfernen
}
/**
* Berechnet die Komplementaermenge zu dieser Menge: die Menge gleicher
* Kapazitaet, die genau alle Elemente enthaelt, die nicht in
* <code>this</code> enthalten sind.
*
* Originalmenge bleibt unveraendert !
*
* @return die Komplementaermenge
*/
public IntSet complement() {
// TODO: alle Elemente identifizieren, die nicht in dieser Menge enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die Vereinigungsmenge
* <br>
* es wird eine Menge der Kapazitaet der groesseren
* Kapazitaet der beiden Mengen erzeugt
* <br>
* <code>s1</code> und <code>s2</code> bleiben unveraendert !
*
* @param s1 Mengen, die
* @param s2 verknuepft werden sollen
* @return die Vereinigungsmenge
*/
public static IntSet union(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 oder s2 enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die symmetrische
* Differenzmenge.
*
* Die Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die symmetrische Differenzmenge
*/
public static IntSet intersection(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 und s2 enthalten sind
return null;
}
/**
* Erzeugt aus <code>s1</code> und <code>s2</code> die Differenzmenge mit
* der Kapazitaet von s1.
*
* Beide Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die Differenzmenge
*/
public static IntSet difference(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 aber nicht in s2 sind
return null;
}
/**
* Stringrepraesentation der Bits dieser Menge beginnend mit Index 0,
* etwa "01011100".
*
* @return Stringrepraesentation der Bits der Menge
*/
public String bits() {
String bitString = "";
// TODO: Bitstring konstruieren: 1 falls das Element enthalten ist, 0 sonst
return bitString;
}
/**
* Ermittelt die Stringrepraesentation dieser Menge, etwa "{1, 3, 4, 6}".
*
* @return Stringrepraesentation der Menge
*/
@Override
public String toString() {
String s = "{";
// TODO: Indizes aller enthaltenen Elemente kommasepariert ausgeben
return s + "}";
}
/**
* Erzeugt einen Iterator, mit dem ueber die Menge iteriert werden kann:
* <br>
* <code>
* <br>for (IntSet.Iterator it = menge.iterator(); it.hasNext(); )
* <br> { ... it.next() ... }
* </code>
*
* @return ein Iterator auf diese Menge
*/
@Override
public Iterator iterator() {
return new Iterator(this);
}
/**
* IntSet Mengen-Iterator
*/
public class Iterator implements java.util.Iterator<Integer> {
// TODO: Instanzvariablen deklarieren
/**
* Erzeugt einen Iterator ueber <code>s</code>.
*
* @param s die Menge, ueber die iteriert werden soll
*/
public Iterator(IntSet s) {
// TODO: Initialisierung der Instanzvariablen
}
/**
* Ermittelt, ob noch weitere Elemente in der Menge existieren.
*/
@Override
public boolean hasNext() {
// TODO: ermitteln, ob weitere Elemente im IntSet sind
return false;
}
/**
* Gibt das naechste Element zurueck und setzt den Iterator weiter.
*
* @return das naechste Element
*/
@Override
public Integer next() {
// TODO: naechstes (enthaltenes) Element zurueckgeben
return -1;
}
}
}
| 0dentitaet/gdp | gdp/IntSet.java | 2,008 | /**
* IntSet Mengen-Iterator
*/ | block_comment | nl | /**
* Mengen nichtnegativer ganzer Zahlen in kompakter
* Speicherrepraesentation: ob eine Zahl in der Menge enthalten
* ist, wird durch EIN BIT im Speicher erfasst!
*
* <br>
* Beispiel:
* <br>
* <code>
* <br>IntSet set = new IntSet(8);
* <br>int a[] = { 1, 3, 4, 5 };
* <br>set.include( a );
* <br>
* <br> ... +---+---+---+---+---+---+---+---+
* <br> ... | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 |
* <br> ... +---+---+---+---+---+---+---+---+
* <br></code>
*/
public class IntSet implements Iterable<Integer> {
private static final int BitsPerWord = Integer.SIZE;
// TODO: Instanzvariablen deklarieren
private int capacity;
/**
* Konstruiert ein leere Zahlenmenge der Kapazitaet <code>n</code>:
* eine Menge, die (nichtnegative ganze) Zahlen im
* Bereich 0 bis n-1 als Elemente enthalten kann.
*
* @param n die Kapazitaet der Menge
*/
public IntSet(int n) {
// TODO: Konstruktor implementieren
capacity = n;
}
/**
* Ermittelt die Kapazitaet der Menge.
*
* @return die Kapazitaet der Menge
*/
public int capacity() {
// TODO: Anzahl potenziell enthaltener Elemente zurueckgeben
return capacity;
}
/**
* Erzeugt aus <code>this</code> eine neue (identisch belegte) Zahlenmenge,
* die Werte im Bereich 0 bis n-1 als Elemente enthalten kann.
*
* Die Originalmenge bleibt unveraendert!
*
* @param n die Kapazitaet der Ergebnismenge
* @return die Ergebnismenge mit veraenderter Kapazitaet
*/
public IntSet resize(int n) {
IntSet s = new IntSet(n);
// TODO: urspruengliche Elemente uebernehmen
return s;
}
/**
* Ermittelt, ob eine nicht-negative ganze Zahl in der Menge enthalten ist.
*
* @param e eine nichtnegative ganze Zahl
* @return ist e in dieser Menge enthalten?
*/
public boolean contains(int e) {
// TODO: Bit an der richtigen Stelle isolieren und zurueckgeben
return false;
}
/**
* Nimmt die Zahl <code>e</code> in diese Menge auf.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void insert(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit setzen
}
/**
* Nimmt alle Elemente aus dem Array <code>es</code> in die Menge auf.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void insert(int es[]) {
// TODO: alle Elemente im Array einfuegen
}
/**
* Entfernt die Zahl <code>e</code> aus dieser Menge.
*
* @param e eine nichtnegative ganze Zahl zwischen 0 und capacity
*/
public void remove(int e) {
// TODO: Position im IntSet berechnen und entsprechendes Bit nullen
}
/**
* Entfernt alle Elemente aus dem Array <code>es</code> aus der Menge.
*
* @param es ein Array von nichtnegativen ganzen Zahlen
*/
public void remove(int[] es) {
// TODO: alle Elemente aus dem Array entfernen
}
/**
* Berechnet die Komplementaermenge zu dieser Menge: die Menge gleicher
* Kapazitaet, die genau alle Elemente enthaelt, die nicht in
* <code>this</code> enthalten sind.
*
* Originalmenge bleibt unveraendert !
*
* @return die Komplementaermenge
*/
public IntSet complement() {
// TODO: alle Elemente identifizieren, die nicht in dieser Menge enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die Vereinigungsmenge
* <br>
* es wird eine Menge der Kapazitaet der groesseren
* Kapazitaet der beiden Mengen erzeugt
* <br>
* <code>s1</code> und <code>s2</code> bleiben unveraendert !
*
* @param s1 Mengen, die
* @param s2 verknuepft werden sollen
* @return die Vereinigungsmenge
*/
public static IntSet union(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 oder s2 enthalten sind
return null;
}
/**
* Erzeuge aus <code>s1</code> und <code>s2</code> die symmetrische
* Differenzmenge.
*
* Die Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die symmetrische Differenzmenge
*/
public static IntSet intersection(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 und s2 enthalten sind
return null;
}
/**
* Erzeugt aus <code>s1</code> und <code>s2</code> die Differenzmenge mit
* der Kapazitaet von s1.
*
* Beide Eingabemengen bleiben unveraendert!
*
* @param s1 erste Menge
* @param s2 zweite Menge
* @return die Differenzmenge
*/
public static IntSet difference(IntSet s1, IntSet s2) {
// TODO: alle Elemente identifizieren, die in s1 aber nicht in s2 sind
return null;
}
/**
* Stringrepraesentation der Bits dieser Menge beginnend mit Index 0,
* etwa "01011100".
*
* @return Stringrepraesentation der Bits der Menge
*/
public String bits() {
String bitString = "";
// TODO: Bitstring konstruieren: 1 falls das Element enthalten ist, 0 sonst
return bitString;
}
/**
* Ermittelt die Stringrepraesentation dieser Menge, etwa "{1, 3, 4, 6}".
*
* @return Stringrepraesentation der Menge
*/
@Override
public String toString() {
String s = "{";
// TODO: Indizes aller enthaltenen Elemente kommasepariert ausgeben
return s + "}";
}
/**
* Erzeugt einen Iterator, mit dem ueber die Menge iteriert werden kann:
* <br>
* <code>
* <br>for (IntSet.Iterator it = menge.iterator(); it.hasNext(); )
* <br> { ... it.next() ... }
* </code>
*
* @return ein Iterator auf diese Menge
*/
@Override
public Iterator iterator() {
return new Iterator(this);
}
/**
* IntSet<SUF>*/
public class Iterator implements java.util.Iterator<Integer> {
// TODO: Instanzvariablen deklarieren
/**
* Erzeugt einen Iterator ueber <code>s</code>.
*
* @param s die Menge, ueber die iteriert werden soll
*/
public Iterator(IntSet s) {
// TODO: Initialisierung der Instanzvariablen
}
/**
* Ermittelt, ob noch weitere Elemente in der Menge existieren.
*/
@Override
public boolean hasNext() {
// TODO: ermitteln, ob weitere Elemente im IntSet sind
return false;
}
/**
* Gibt das naechste Element zurueck und setzt den Iterator weiter.
*
* @return das naechste Element
*/
@Override
public Integer next() {
// TODO: naechstes (enthaltenes) Element zurueckgeben
return -1;
}
}
}
|
13786_15 | package gameapplication.model;
import gameapplication.model.chess.Board;
import gameapplication.model.chess.piece.Piece;
import gameapplication.model.chess.piece.pieces.Pawn;
import gameapplication.model.chess.piece.pieces.Piecetype;
import gameapplication.model.chess.spot.Spot;
import java.util.ArrayList;
import java.util.List;
/**
* The MoveManager class is used to manage the moves of the pieces. It has a list of spots, which are used to store the
* last spot clicked. It also has a list of moves, which are used to store the moves made
*/
/**
* Given a string of the form "column.row:column.row", return a list of the two spots
*
* @param column the column of the spot that was clicked
* @param row the row of the piece that was clicked on
*/
public class MoveManager {
// This is creating a list of spots, which is used to store the last spot clicked.
private List<Spot> spots = new ArrayList<>();
// This is creating a list of strings, which is used to store the moves made.
private List<String> movesList;
// Creating a reference to the board.
private Board board;
// This is creating a new MoveManager object, and initializing the board and movesList.
public MoveManager(Board board) {
this.board = board;
movesList = new ArrayList<>();
}
/**
* If the first spot in the spots list is empty, add the current spot to the spots list. If the first spot in the spots
* list is not empty, check if the current spot is a valid move for the piece in the first spot. If the current spot is
* a valid move, add the current spot to the spots list. If the current spot is not a valid move, clear the spots list
*
* @param column the column of the spot that was clicked
* @param row the row of the piece that was clicked on
*/
public void addMove(int column, int row) {
// Getting the piece from the spot that was clicked on.
Piece clickedOnPiece = board.getPieceFromSpot(column, row);
// This is checking if the spots list is empty. If it is empty, it means that the first spot has not been clicked
// yet.
if (spots.isEmpty()) {
// Kijk of er op niks geklicked werd, zoja doe niks
if (clickedOnPiece == null) return;
// als er op een andere piece gecklicked werd, doe ook niks.
if (clickedOnPiece.getPieceColor() != board.getLastTurnColor()) return;
// This is adding the spot that was clicked on to the spots list.
spots.add(new Spot(column, row));
return;
}
// The above code is checking if the piece that was clicked on is the same color as the last piece that was moved.
// If it is the same color, it will remove the first spot from the list of spots. If it is not the same color, it
// will add the spot to the list of spots.
if (spots.size() == 1) {
Spot firstSpot = spots.get(0);
Piece pieceFromSpot = board.getPieceFromSpot(firstSpot.getColumn(), firstSpot.getRow());
Piece currentPiece = board.getPieceFromSpot(column, row);
if (board.getPieceFromSpot(column, row) != null && board.getPieceFromSpot(column, row).getPieceType() == Piecetype.KING) {
return;
}
//Als huidige geklickde piece heeft dezelfde kleur als de vorige piece,
if (currentPiece != null && currentPiece.getPieceColor() == board.getLastTurnColor()) {
// verwijder de vorige spot,
spots.remove(0);
//en maak een recursieve oproep naar de addMove methode
addMove(column, row);
} else {
//Als move niet mogelijk is
try {
if (!pieceFromSpot.moveTo(new Spot(column, row))) {
spots.clear();
return;
}
} catch (NullPointerException npe) {
pieceFromSpot.setBoard(getBoard());
if (!pieceFromSpot.moveTo(new Spot(column, row))) {
spots.clear();
return;
}
}
//^De else betekent dat er op een andere Spot met of zonder Piece geklicked werd.
//Nu bekijken we als de 2de spot van de lijst, 1 van de valid moves van de eerste piece is.
for (Spot[] validMove : pieceFromSpot.validMoves(board)) {
for (Spot spot : validMove) {
if (spot != null && spot.getColumn() == column && spot.getRow() == row) {
//zoja, add de 2de spot naar de lijst, en roep de make move methode op.
//Check if next move will cause check, or disable the check.
if (testMove(new Spot(column, row), null)) {
return;
}
//if not in a checked state, or testMove return true
spots.add(new Spot(column, row));
//prepare next turn
makeMove();
}
}
}
}
}
}
//move the piece and prepare next turn
/**
* This function moves a piece from one spot to another
*/
public void makeMove() {
Piece piece = board.getPieceFromSpot(spots.get(0).getColumn(), spots.get(0).getRow());
// Actually move the piece
piece.moveToSpot(board, spots.get(1));
// This is checking if the piece is a pawn. If it is, it will check if it is promotable.
if (piece.getPieceType() == Piecetype.PAWN) {
Pawn pawn = (Pawn) piece;
pawn.checkIfPromotionAvailable();
}
// This is clearing the list of spots, and switching the player.
addMoveToList();
spots.clear();
board.switchPlayer();
// Checking if the current player is in check. If it is, it will check if the player is in checkmate.
board.checkForCheck();
// Switching the player.
board.nextTurn();
}
//Method to check if the next move during check, will evade the check
/**
* This function checks if the move is valid by checking if the king is in check after the move
*
* @param secondSpot the spot where the piece is moving to
* @param firstSpot the spot where the piece is currently located
* @return A boolean value.
*/
public boolean testMove(Spot secondSpot, Spot firstSpot) {
//second parameter to check for checkmate, only available if called from the board
Spot newFirstSpot = firstSpot != null ? firstSpot : spots.get(0);
//create a reference to the old board
Board tempBoard = board;
//create a copy of the old piece, in case there is one on the second spot
Piece oldPiece = tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()];
// get the piece from the first spot
Piece piece = board.getPieceFromSpot(newFirstSpot.getColumn(), newFirstSpot.getRow());
//if there was a piece on the second spot, remove it
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
}
// remove the piece from the first spot
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = null;
// set the piece from the first spot in the second spot
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = piece;
//check if after doing this, the check is still there
if (board.getKing(board.getCurrentPlayer().getColor()).isCheck(tempBoard)) {
//if yes, put everything back in place
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece;
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece;
}
return true;
}
//if not, also put everything back in place
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece;
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece;
}
return false;
}
/**
* Add the move to the list of moves
*/
public void addMoveToList() {
movesList.add(String.format("%s:%s", spots.get(0).getLocationSpotName(), spots.get(1).getLocationSpotName()));
}
/**
* Given a string of the form "column.row:column.row", return a list of the two spots
*
* @param spotString a string that represents a list of spots.
* @return A list of spots.
*/
public List<Spot> getSpotFromString(String spotString) {
String[] twoSpots = spotString.split(":");
List<Spot> spot = new ArrayList<>();
if (twoSpots.length == 0) {
return null;
}
for (String singleSpot : twoSpots) {
String[] columnAndRow = singleSpot.split("\\.");
try {
spot.add(new Spot(Integer.parseInt(columnAndRow[0]), Integer.parseInt(columnAndRow[1])));
} catch (Exception e) {
return null;
}
}
return spot;
}
/**
* Returns the board
*
* @return The board object.
*/
public Board getBoard() {
return board;
}
public List<String> getMovesList() {
return movesList;
}
public List<Spot> getMoves() {
return spots;
}
}
| 0xBienCuit/ChessGame | src/gameapplication/model/MoveManager.java | 2,449 | //Als huidige geklickde piece heeft dezelfde kleur als de vorige piece, | line_comment | nl | package gameapplication.model;
import gameapplication.model.chess.Board;
import gameapplication.model.chess.piece.Piece;
import gameapplication.model.chess.piece.pieces.Pawn;
import gameapplication.model.chess.piece.pieces.Piecetype;
import gameapplication.model.chess.spot.Spot;
import java.util.ArrayList;
import java.util.List;
/**
* The MoveManager class is used to manage the moves of the pieces. It has a list of spots, which are used to store the
* last spot clicked. It also has a list of moves, which are used to store the moves made
*/
/**
* Given a string of the form "column.row:column.row", return a list of the two spots
*
* @param column the column of the spot that was clicked
* @param row the row of the piece that was clicked on
*/
public class MoveManager {
// This is creating a list of spots, which is used to store the last spot clicked.
private List<Spot> spots = new ArrayList<>();
// This is creating a list of strings, which is used to store the moves made.
private List<String> movesList;
// Creating a reference to the board.
private Board board;
// This is creating a new MoveManager object, and initializing the board and movesList.
public MoveManager(Board board) {
this.board = board;
movesList = new ArrayList<>();
}
/**
* If the first spot in the spots list is empty, add the current spot to the spots list. If the first spot in the spots
* list is not empty, check if the current spot is a valid move for the piece in the first spot. If the current spot is
* a valid move, add the current spot to the spots list. If the current spot is not a valid move, clear the spots list
*
* @param column the column of the spot that was clicked
* @param row the row of the piece that was clicked on
*/
public void addMove(int column, int row) {
// Getting the piece from the spot that was clicked on.
Piece clickedOnPiece = board.getPieceFromSpot(column, row);
// This is checking if the spots list is empty. If it is empty, it means that the first spot has not been clicked
// yet.
if (spots.isEmpty()) {
// Kijk of er op niks geklicked werd, zoja doe niks
if (clickedOnPiece == null) return;
// als er op een andere piece gecklicked werd, doe ook niks.
if (clickedOnPiece.getPieceColor() != board.getLastTurnColor()) return;
// This is adding the spot that was clicked on to the spots list.
spots.add(new Spot(column, row));
return;
}
// The above code is checking if the piece that was clicked on is the same color as the last piece that was moved.
// If it is the same color, it will remove the first spot from the list of spots. If it is not the same color, it
// will add the spot to the list of spots.
if (spots.size() == 1) {
Spot firstSpot = spots.get(0);
Piece pieceFromSpot = board.getPieceFromSpot(firstSpot.getColumn(), firstSpot.getRow());
Piece currentPiece = board.getPieceFromSpot(column, row);
if (board.getPieceFromSpot(column, row) != null && board.getPieceFromSpot(column, row).getPieceType() == Piecetype.KING) {
return;
}
//Als h<SUF>
if (currentPiece != null && currentPiece.getPieceColor() == board.getLastTurnColor()) {
// verwijder de vorige spot,
spots.remove(0);
//en maak een recursieve oproep naar de addMove methode
addMove(column, row);
} else {
//Als move niet mogelijk is
try {
if (!pieceFromSpot.moveTo(new Spot(column, row))) {
spots.clear();
return;
}
} catch (NullPointerException npe) {
pieceFromSpot.setBoard(getBoard());
if (!pieceFromSpot.moveTo(new Spot(column, row))) {
spots.clear();
return;
}
}
//^De else betekent dat er op een andere Spot met of zonder Piece geklicked werd.
//Nu bekijken we als de 2de spot van de lijst, 1 van de valid moves van de eerste piece is.
for (Spot[] validMove : pieceFromSpot.validMoves(board)) {
for (Spot spot : validMove) {
if (spot != null && spot.getColumn() == column && spot.getRow() == row) {
//zoja, add de 2de spot naar de lijst, en roep de make move methode op.
//Check if next move will cause check, or disable the check.
if (testMove(new Spot(column, row), null)) {
return;
}
//if not in a checked state, or testMove return true
spots.add(new Spot(column, row));
//prepare next turn
makeMove();
}
}
}
}
}
}
//move the piece and prepare next turn
/**
* This function moves a piece from one spot to another
*/
public void makeMove() {
Piece piece = board.getPieceFromSpot(spots.get(0).getColumn(), spots.get(0).getRow());
// Actually move the piece
piece.moveToSpot(board, spots.get(1));
// This is checking if the piece is a pawn. If it is, it will check if it is promotable.
if (piece.getPieceType() == Piecetype.PAWN) {
Pawn pawn = (Pawn) piece;
pawn.checkIfPromotionAvailable();
}
// This is clearing the list of spots, and switching the player.
addMoveToList();
spots.clear();
board.switchPlayer();
// Checking if the current player is in check. If it is, it will check if the player is in checkmate.
board.checkForCheck();
// Switching the player.
board.nextTurn();
}
//Method to check if the next move during check, will evade the check
/**
* This function checks if the move is valid by checking if the king is in check after the move
*
* @param secondSpot the spot where the piece is moving to
* @param firstSpot the spot where the piece is currently located
* @return A boolean value.
*/
public boolean testMove(Spot secondSpot, Spot firstSpot) {
//second parameter to check for checkmate, only available if called from the board
Spot newFirstSpot = firstSpot != null ? firstSpot : spots.get(0);
//create a reference to the old board
Board tempBoard = board;
//create a copy of the old piece, in case there is one on the second spot
Piece oldPiece = tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()];
// get the piece from the first spot
Piece piece = board.getPieceFromSpot(newFirstSpot.getColumn(), newFirstSpot.getRow());
//if there was a piece on the second spot, remove it
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
}
// remove the piece from the first spot
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = null;
// set the piece from the first spot in the second spot
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = piece;
//check if after doing this, the check is still there
if (board.getKing(board.getCurrentPlayer().getColor()).isCheck(tempBoard)) {
//if yes, put everything back in place
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece;
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece;
}
return true;
}
//if not, also put everything back in place
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = null;
tempBoard.getPieceIntern()[newFirstSpot.getColumn()][newFirstSpot.getRow()] = piece;
if (oldPiece != null) {
tempBoard.getPieceIntern()[secondSpot.getColumn()][secondSpot.getRow()] = oldPiece;
}
return false;
}
/**
* Add the move to the list of moves
*/
public void addMoveToList() {
movesList.add(String.format("%s:%s", spots.get(0).getLocationSpotName(), spots.get(1).getLocationSpotName()));
}
/**
* Given a string of the form "column.row:column.row", return a list of the two spots
*
* @param spotString a string that represents a list of spots.
* @return A list of spots.
*/
public List<Spot> getSpotFromString(String spotString) {
String[] twoSpots = spotString.split(":");
List<Spot> spot = new ArrayList<>();
if (twoSpots.length == 0) {
return null;
}
for (String singleSpot : twoSpots) {
String[] columnAndRow = singleSpot.split("\\.");
try {
spot.add(new Spot(Integer.parseInt(columnAndRow[0]), Integer.parseInt(columnAndRow[1])));
} catch (Exception e) {
return null;
}
}
return spot;
}
/**
* Returns the board
*
* @return The board object.
*/
public Board getBoard() {
return board;
}
public List<String> getMovesList() {
return movesList;
}
public List<Spot> getMoves() {
return spots;
}
}
|
183866_30 | /* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly([email protected]) and Mark Adler([email protected])
* and contributors of zlib.
*/
package com.jcraft.jsch.jzlib;
final class Tree{
static final private int MAX_BITS=15;
static final private int BL_CODES=19;
static final private int D_CODES=30;
static final private int LITERALS=256;
static final private int LENGTH_CODES=29;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
static final private int HEAP_SIZE=(2*L_CODES+1);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS=7;
// end of block literal code
static final int END_BLOCK=256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final int REPZ_11_138=18;
// extra bits for each length code
static final int[] extra_lbits={
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
static final int[] extra_dbits={
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
static final int[] extra_blbits={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
static final byte[] bl_order={
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
static final int Buf_size=8*2;
// see definition of array dist_code below
static final int DIST_CODE_LEN=512;
static final byte[] _dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
static final byte[] _length_code={
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
static final int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
static final int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>>7)]);
}
short[] dyn_tree; // the dynamic tree
int max_code; // largest code with non zero frequency
StaticTree stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
void gen_bitlen(Deflate s){
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int base = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
for(h=s.heap_max+1; h<HEAP_SIZE; h++){
n = s.heap[h];
bits = tree[tree[n*2+1]*2+1] + 1;
if (bits > max_length){ bits = max_length; overflow++; }
tree[n*2+1] = (short)bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code) continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n*2];
s.opt_len += f * (bits + xbits);
if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
}
if (overflow == 0) return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length-1;
while(s.bl_count[bits]==0) bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits+1]+=2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
}
while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) continue;
if (tree[m*2+1] != bits) {
s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2];
tree[m*2+1] = (short)bits;
}
n--;
}
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
void build_tree(Deflate s){
short[] tree=dyn_tree;
short[] stree=stat_desc.static_tree;
int elems=stat_desc.elems;
int n, m; // iterate over heap elements
int max_code=-1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for(n=0; n<elems; n++) {
if(tree[n*2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
}
else{
tree[n*2+1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node*2] = 1;
s.depth[node] = 0;
s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for(n=s.heap_len/2;n>=1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems; // next internal node of the tree
do{
// n = node of least frequency
n=s.heap[1];
s.heap[1]=s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m=s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node*2] = (short)(tree[n*2] + tree[m*2]);
s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1);
tree[n*2+1] = tree[m*2+1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
}
while(s.heap_len>=2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count, s.next_code);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
private final static void gen_codes(
short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count, // number of codes at each bit length
short[] next_code){
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
next_code[0]=0;
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n*2+1];
if (len == 0) continue;
// Now reverse the bits
tree[n*2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
private final static int bi_reverse(
int code, // the value to invert
int len // its bit length
){
int res = 0;
do{
res|=code&1;
code>>>=1;
res<<=1;
}
while(--len>0);
return res>>>1;
}
}
| 0xRustlang/keepass2android | src/java/JavaFileStorage/app/src/main/java/com/jcraft/jsch/jzlib/Tree.java | 7,044 | // bit length | line_comment | nl | /* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly([email protected]) and Mark Adler([email protected])
* and contributors of zlib.
*/
package com.jcraft.jsch.jzlib;
final class Tree{
static final private int MAX_BITS=15;
static final private int BL_CODES=19;
static final private int D_CODES=30;
static final private int LITERALS=256;
static final private int LENGTH_CODES=29;
static final private int L_CODES=(LITERALS+1+LENGTH_CODES);
static final private int HEAP_SIZE=(2*L_CODES+1);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS=7;
// end of block literal code
static final int END_BLOCK=256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final int REP_3_6=16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final int REPZ_3_10=17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final int REPZ_11_138=18;
// extra bits for each length code
static final int[] extra_lbits={
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0
};
// extra bits for each distance code
static final int[] extra_dbits={
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13
};
// extra bits for each bit length code
static final int[] extra_blbits={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7
};
static final byte[] bl_order={
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
static final int Buf_size=8*2;
// see definition of array dist_code below
static final int DIST_CODE_LEN=512;
static final byte[] _dist_code = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
static final byte[] _length_code={
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
static final int[] base_length = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
static final int[] base_dist = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>>7)]);
}
short[] dyn_tree; // the dynamic tree
int max_code; // largest code with non zero frequency
StaticTree stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
void gen_bitlen(Deflate s){
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int base = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit l<SUF>
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1] = 0; // root of the heap
for(h=s.heap_max+1; h<HEAP_SIZE; h++){
n = s.heap[h];
bits = tree[tree[n*2+1]*2+1] + 1;
if (bits > max_length){ bits = max_length; overflow++; }
tree[n*2+1] = (short)bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code) continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n*2];
s.opt_len += f * (bits + xbits);
if (stree!=null) s.static_len += f * (stree[n*2+1] + xbits);
}
if (overflow == 0) return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length-1;
while(s.bl_count[bits]==0) bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits+1]+=2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
}
while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code) continue;
if (tree[m*2+1] != bits) {
s.opt_len += ((long)bits - (long)tree[m*2+1])*(long)tree[m*2];
tree[m*2+1] = (short)bits;
}
n--;
}
}
}
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
void build_tree(Deflate s){
short[] tree=dyn_tree;
short[] stree=stat_desc.static_tree;
int elems=stat_desc.elems;
int n, m; // iterate over heap elements
int max_code=-1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for(n=0; n<elems; n++) {
if(tree[n*2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
}
else{
tree[n*2+1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node*2] = 1;
s.depth[node] = 0;
s.opt_len--; if (stree!=null) s.static_len -= stree[node*2+1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for(n=s.heap_len/2;n>=1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems; // next internal node of the tree
do{
// n = node of least frequency
n=s.heap[1];
s.heap[1]=s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m=s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node*2] = (short)(tree[n*2] + tree[m*2]);
s.depth[node] = (byte)(Math.max(s.depth[n],s.depth[m])+1);
tree[n*2+1] = tree[m*2+1] = (short)node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
}
while(s.heap_len>=2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count, s.next_code);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
private final static void gen_codes(
short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count, // number of codes at each bit length
short[] next_code){
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
next_code[0]=0;
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short)((code + bl_count[bits-1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n*2+1];
if (len == 0) continue;
// Now reverse the bits
tree[n*2] = (short)(bi_reverse(next_code[len]++, len));
}
}
// Reverse the first len bits of a code, using straightforward code (a faster
// method would use a table)
// IN assertion: 1 <= len <= 15
private final static int bi_reverse(
int code, // the value to invert
int len // its bit length
){
int res = 0;
do{
res|=code&1;
code>>>=1;
res<<=1;
}
while(--len>0);
return res>>>1;
}
}
|
23167_20 | package XML;
import Correction.Correction;
import Correction.Corrector;
import java.awt.geom.FlatteningPathIterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class XML_Parser {
public static ArrayList<Measurement> ReadXML(String data) {
data = data.replace("<?xml version=\"1.0\"?>\n", "");
if (!data.trim().startsWith("<WEATHERDATA>")) {
return null;
}
String line;
ArrayList<Measurement> measurements = new ArrayList<Measurement>();
ArrayList<String> XMLstack = new ArrayList<String>();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
data = data.replace(">", ">\n");
data = data.replace("<", "\n<");
data = data.replace("\t", "");
while (data.contains("\n\n")) {
data = data.replace("\n\n", "\n");
}
BufferedReader reader = new BufferedReader(new StringReader(data));
try {
while ((line = reader.readLine()) != null) {
line = line.replace("\n", "");
if (line.isEmpty() || line.contains("?")) { // filter out blank lines and information tags
continue;
}
// System.out.println(line);
if (line.startsWith("<")) { // if true the given line is a tag
line = line.replace("<", "");
line = line.replace(">", "");
if (line.contains("/")) { //it is a closing tag
if (XMLstack.get(XMLstack.size() - 1).equals(line.replace("/", ""))) {
XMLstack.remove(XMLstack.size() -1);
}
else {
System.err.println("Invalid XML");
}
}
else { //it is an opening tag
XMLstack.add(line);
// System.out.println("added to XML_Stack: " + line);
if (line.equals("MEASUREMENT")) {
measurements.add(new Measurement());
}
}
}
else { // the line is not a tag
switch (XMLstack.get(XMLstack.size() -1)) {
case "STN": //Het station waarvan deze gegevens zijn
measurements.get(measurements.size() -1).STN = Integer.parseInt(line);
break;
case "DATE": //Datum van versturen van deze gegevens, formaat: yyyy-mm-dd
try {
measurements.get(measurements.size() - 1).DATETIME = ft.parse(line);
}
catch (ParseException e) {System.err.println("Unable to set DATETIME");}
break;
case "TIME": //Tijd van versturen van deze gegevens, formaat: hh:mm:ss
String s[] = line.split(":");
int time = Integer.parseInt(s[0]) * 3600000;
time += Integer.parseInt(s[1]) * 60000;
time += Integer.parseInt(s[2]) * 1000;
measurements.get(measurements.size() - 1).DATETIME.setTime(measurements.get(measurements.size() - 1).DATETIME.getTime() + time);
break;
case "TEMP": //Temperatuur in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).TEMP = Float.parseFloat(line);
}
break;
case "DEWP": // Dauwpunt in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).DEWP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).DEWP = Float.parseFloat(line);
}
break;
case "STP": //Luchtdruk op stationsniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).STP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).STP = Float.parseFloat(line);
}
break;
case "SLP": //Luchtdruk op zeeniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SLP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SLP = Float.parseFloat(line);
}
break;
case "VISIB": //Zichtbaarheid in kilometers, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).VISIB = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).VISIB = Float.parseFloat(line);
}
break;
case "WDSP": //Windsnelheid in kilometers per uur, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).WDSP = Float.parseFloat(line);
}
break;
case "PRCP": //Neerslag in centimeters, geldige waardes van 0.00 t/m 999.99 met 2 decimalen
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).PRCP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).PRCP = Float.parseFloat(line);
}
break;
case "SNDP": //Gevallen sneeuw in centimeters, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SNDP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SNDP = Float.parseFloat(line);
}
break;
// Gebeurtenissen op deze dag, cummulatief, binair uitgedrukt.
// Opeenvolgend, van meest- naar minst significant:
// Vriezen, geeft aan of het gevroren heeft
// Regen, geeft aan of het geregend heeft.
// Sneeuw, geeft aan of het gesneeuwd heeft.
// Hagel, geeft aan of het gehageld heeft.
// Onweer, geeft aan of er onweer is geweest.
// Tornado/windhoos, geeft aan of er een tornado of windhoos geweest is.
case "FRSHTT":
measurements.get(measurements.size() - 1).FRSHTT = Byte.parseByte(line, 2);
break;
case "CLDC": //Bewolking in procenten, geldige waardes van 0.0 t/m 99.9 met 1 decimaal
measurements.get(measurements.size() - 1).CLDC = Float.parseFloat(line);
break;
case "WNDDIR": //Windrichting in graden, geldige waardes van 0 t/m 359 alleen gehele getallen
measurements.get(measurements.size() - 1).WNDDIR = Short.parseShort(line);
break;
}
}
}
}
catch (IOException ioe) { }
// measurements = Corrector.makeList(measurements);
// Sends all measurments trough the corrector
for (Measurement m: measurements) {
m = Correction.testAndAddMeasurement(m);
}
return measurements;
}
}
| 0xSMN/2.2-Leertaak_3 | Data_Processor/XML/XML_Parser.java | 2,091 | // Vriezen, geeft aan of het gevroren heeft | line_comment | nl | package XML;
import Correction.Correction;
import Correction.Corrector;
import java.awt.geom.FlatteningPathIterator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class XML_Parser {
public static ArrayList<Measurement> ReadXML(String data) {
data = data.replace("<?xml version=\"1.0\"?>\n", "");
if (!data.trim().startsWith("<WEATHERDATA>")) {
return null;
}
String line;
ArrayList<Measurement> measurements = new ArrayList<Measurement>();
ArrayList<String> XMLstack = new ArrayList<String>();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
data = data.replace(">", ">\n");
data = data.replace("<", "\n<");
data = data.replace("\t", "");
while (data.contains("\n\n")) {
data = data.replace("\n\n", "\n");
}
BufferedReader reader = new BufferedReader(new StringReader(data));
try {
while ((line = reader.readLine()) != null) {
line = line.replace("\n", "");
if (line.isEmpty() || line.contains("?")) { // filter out blank lines and information tags
continue;
}
// System.out.println(line);
if (line.startsWith("<")) { // if true the given line is a tag
line = line.replace("<", "");
line = line.replace(">", "");
if (line.contains("/")) { //it is a closing tag
if (XMLstack.get(XMLstack.size() - 1).equals(line.replace("/", ""))) {
XMLstack.remove(XMLstack.size() -1);
}
else {
System.err.println("Invalid XML");
}
}
else { //it is an opening tag
XMLstack.add(line);
// System.out.println("added to XML_Stack: " + line);
if (line.equals("MEASUREMENT")) {
measurements.add(new Measurement());
}
}
}
else { // the line is not a tag
switch (XMLstack.get(XMLstack.size() -1)) {
case "STN": //Het station waarvan deze gegevens zijn
measurements.get(measurements.size() -1).STN = Integer.parseInt(line);
break;
case "DATE": //Datum van versturen van deze gegevens, formaat: yyyy-mm-dd
try {
measurements.get(measurements.size() - 1).DATETIME = ft.parse(line);
}
catch (ParseException e) {System.err.println("Unable to set DATETIME");}
break;
case "TIME": //Tijd van versturen van deze gegevens, formaat: hh:mm:ss
String s[] = line.split(":");
int time = Integer.parseInt(s[0]) * 3600000;
time += Integer.parseInt(s[1]) * 60000;
time += Integer.parseInt(s[2]) * 1000;
measurements.get(measurements.size() - 1).DATETIME.setTime(measurements.get(measurements.size() - 1).DATETIME.getTime() + time);
break;
case "TEMP": //Temperatuur in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).TEMP = Float.parseFloat(line);
}
break;
case "DEWP": // Dauwpunt in graden Celsius, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).DEWP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).DEWP = Float.parseFloat(line);
}
break;
case "STP": //Luchtdruk op stationsniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).STP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).STP = Float.parseFloat(line);
}
break;
case "SLP": //Luchtdruk op zeeniveau in millibar, geldige waardes van 0.0 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SLP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SLP = Float.parseFloat(line);
}
break;
case "VISIB": //Zichtbaarheid in kilometers, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).VISIB = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).VISIB = Float.parseFloat(line);
}
break;
case "WDSP": //Windsnelheid in kilometers per uur, geldige waardes van 0.0 t/m 999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).TEMP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).WDSP = Float.parseFloat(line);
}
break;
case "PRCP": //Neerslag in centimeters, geldige waardes van 0.00 t/m 999.99 met 2 decimalen
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).PRCP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).PRCP = Float.parseFloat(line);
}
break;
case "SNDP": //Gevallen sneeuw in centimeters, geldige waardes van -9999.9 t/m 9999.9 met 1 decimaal
if(line.trim().equals("")){
measurements.get(measurements.size() - 1).SNDP = Float.MIN_NORMAL;
}
else {
measurements.get(measurements.size() - 1).SNDP = Float.parseFloat(line);
}
break;
// Gebeurtenissen op deze dag, cummulatief, binair uitgedrukt.
// Opeenvolgend, van meest- naar minst significant:
// Vriez<SUF>
// Regen, geeft aan of het geregend heeft.
// Sneeuw, geeft aan of het gesneeuwd heeft.
// Hagel, geeft aan of het gehageld heeft.
// Onweer, geeft aan of er onweer is geweest.
// Tornado/windhoos, geeft aan of er een tornado of windhoos geweest is.
case "FRSHTT":
measurements.get(measurements.size() - 1).FRSHTT = Byte.parseByte(line, 2);
break;
case "CLDC": //Bewolking in procenten, geldige waardes van 0.0 t/m 99.9 met 1 decimaal
measurements.get(measurements.size() - 1).CLDC = Float.parseFloat(line);
break;
case "WNDDIR": //Windrichting in graden, geldige waardes van 0 t/m 359 alleen gehele getallen
measurements.get(measurements.size() - 1).WNDDIR = Short.parseShort(line);
break;
}
}
}
}
catch (IOException ioe) { }
// measurements = Corrector.makeList(measurements);
// Sends all measurments trough the corrector
for (Measurement m: measurements) {
m = Correction.testAndAddMeasurement(m);
}
return measurements;
}
}
|
122904_1 | package splashscreen;
import hoofdmenu.ToonHoofdmenu;
import utils.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Bart on 9-4-2014.
*/
public class ToonSplashscreen extends Task {
private JFrame jfSpelFrame;
private Timer timer;
private boolean validate = true;
public ToonSplashscreen(JFrame jfSpelFrame){
this.jfSpelFrame = jfSpelFrame;
}
//Code die uitgevoerd wordt als aan de voorwaarden is voldaan
public void run() {
boolean validate = validate();
if(validate == true)
{
execute();
}
}
private boolean validate() {
new Computer();
return true;
}
private void execute() {
jfSpelFrame.setContentPane(new Splashscreen(jfSpelFrame));
/*
Maak een timer aan voor 3 seconde.
Deze wordt later opgevangen door de actionListener.
Die roept vervolgens het splaschscreen aan.
*/
TimeListener tlTimer = new TimeListener();
timer = new Timer(3000, tlTimer);
timer.start();
validate = true;
}
class TimeListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
/*
Het hoofdmenu wordt hier aangeroepen.
Dit is pas nadat het splashscreen 3 seconde is getoond.
*/
ToonHoofdmenu toonHoofdmenu = new ToonHoofdmenu(jfSpelFrame, validate);
toonHoofdmenu.run();
timer.stop();
}
}
} | 0xbart/QuixoJavaGame | src/splashscreen/ToonSplashscreen.java | 401 | //Code die uitgevoerd wordt als aan de voorwaarden is voldaan | line_comment | nl | package splashscreen;
import hoofdmenu.ToonHoofdmenu;
import utils.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Bart on 9-4-2014.
*/
public class ToonSplashscreen extends Task {
private JFrame jfSpelFrame;
private Timer timer;
private boolean validate = true;
public ToonSplashscreen(JFrame jfSpelFrame){
this.jfSpelFrame = jfSpelFrame;
}
//Code <SUF>
public void run() {
boolean validate = validate();
if(validate == true)
{
execute();
}
}
private boolean validate() {
new Computer();
return true;
}
private void execute() {
jfSpelFrame.setContentPane(new Splashscreen(jfSpelFrame));
/*
Maak een timer aan voor 3 seconde.
Deze wordt later opgevangen door de actionListener.
Die roept vervolgens het splaschscreen aan.
*/
TimeListener tlTimer = new TimeListener();
timer = new Timer(3000, tlTimer);
timer.start();
validate = true;
}
class TimeListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
/*
Het hoofdmenu wordt hier aangeroepen.
Dit is pas nadat het splashscreen 3 seconde is getoond.
*/
ToonHoofdmenu toonHoofdmenu = new ToonHoofdmenu(jfSpelFrame, validate);
toonHoofdmenu.run();
timer.stop();
}
}
} |
185101_1 | package dev.bearz.whattodo;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class events extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://nijdeken.com/wtd/api.php";
// JSON Node names
private static final String TAG_THING = "Thing";
private static final String TAG_PLACE = "Place";
private static final String TAG_TIME = "Time";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
Toast.makeText(getApplicationContext(), "Even geduld, het laden van de informatie kan even duren",
Toast.LENGTH_LONG).show();
Intent in = new Intent(getApplicationContext(),
SingleEventActivity.class);
in.putExtra(TAG_THING, name);
in.putExtra(TAG_PLACE, cost);
in.putExtra(TAG_TIME, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(events.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
// JSONObject jsonObj = new JSONObject(jsonStr);
//
// // Getting JSON Array node
contacts = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String thing = c.getString(TAG_THING);
String place = c.getString(TAG_PLACE);
String time = c.getString(TAG_TIME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_THING, thing);
contact.put(TAG_PLACE, place);
contact.put(TAG_TIME, time);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
events.this, contactList,
R.layout.list_item, new String[] { TAG_THING, TAG_PLACE,
TAG_TIME }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
| 1070rik/What-To-Do | app/src/main/java/dev/bearz/whattodo/events.java | 1,207 | //nijdeken.com/wtd/api.php"; | line_comment | nl | package dev.bearz.whattodo;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class events extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://nijde<SUF>
// JSON Node names
private static final String TAG_THING = "Thing";
private static final String TAG_PLACE = "Place";
private static final String TAG_TIME = "Time";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
Toast.makeText(getApplicationContext(), "Even geduld, het laden van de informatie kan even duren",
Toast.LENGTH_LONG).show();
Intent in = new Intent(getApplicationContext(),
SingleEventActivity.class);
in.putExtra(TAG_THING, name);
in.putExtra(TAG_PLACE, cost);
in.putExtra(TAG_TIME, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(events.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
// JSONObject jsonObj = new JSONObject(jsonStr);
//
// // Getting JSON Array node
contacts = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String thing = c.getString(TAG_THING);
String place = c.getString(TAG_PLACE);
String time = c.getString(TAG_TIME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_THING, thing);
contact.put(TAG_PLACE, place);
contact.put(TAG_TIME, time);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
events.this, contactList,
R.layout.list_item, new String[] { TAG_THING, TAG_PLACE,
TAG_TIME }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
|
142662_3 | package bpp_sim.Functions;
import bpp_sim.Doos;
import bpp_sim.Product;
import java.util.ArrayList;
/*
Onze eigen bedachte functie - FullNFD
Ofwel - Even/uneven-functie
*/
public class FirstFullNFD implements BPP{
@Override
public ArrayList<Doos> berekenOplossing(ArrayList<Product> producten) {
/* Voor elk product, gooi het in een EVEN of ONEVEN-lijst. */
ArrayList<Product> EVEN = new ArrayList<>();
ArrayList<Product> ODD = new ArrayList<>();
for(Product p: producten){
if(p.getSize() % 2 == 0){
EVEN.add(p);
}
else{
ODD.add(p);
}
}
/*
Gooi het in een nieuwe lijst:
EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN.
*/
int j = producten.size();
producten.clear();
for(int i = 0; i < j; i++){
try{producten.add(EVEN.get(i));}catch(Exception ex){}
try{producten.add(ODD.get(i));}catch(Exception ex){}
}
ArrayList<Doos> dozen = new ArrayList<>();
//Voor elk product...
for(Product p: producten){
boolean isPlaced = false;
//Controleer elke doos of er plek is.
for(int i = 0; i < dozen.size(); i++){
if(!isPlaced && dozen.get(i).getFreeSpace() >= p.getSize()){
dozen.get(i).addProduct(p);
isPlaced = true;
}
}
//Maak een nieuwe doos aan als er geen enkele doos was
//die nog plek had.
if(isPlaced == false){
Doos d = new Doos();
d.addProduct(p);
dozen.add(d);
}
}
return dozen;
}
}
| 13r1ckz/KBS-Magazijn | BPP-SIMULATOR/src/bpp_sim/Functions/FirstFullNFD.java | 523 | //Voor elk product... | line_comment | nl | package bpp_sim.Functions;
import bpp_sim.Doos;
import bpp_sim.Product;
import java.util.ArrayList;
/*
Onze eigen bedachte functie - FullNFD
Ofwel - Even/uneven-functie
*/
public class FirstFullNFD implements BPP{
@Override
public ArrayList<Doos> berekenOplossing(ArrayList<Product> producten) {
/* Voor elk product, gooi het in een EVEN of ONEVEN-lijst. */
ArrayList<Product> EVEN = new ArrayList<>();
ArrayList<Product> ODD = new ArrayList<>();
for(Product p: producten){
if(p.getSize() % 2 == 0){
EVEN.add(p);
}
else{
ODD.add(p);
}
}
/*
Gooi het in een nieuwe lijst:
EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN-ONEVEN-EVEN.
*/
int j = producten.size();
producten.clear();
for(int i = 0; i < j; i++){
try{producten.add(EVEN.get(i));}catch(Exception ex){}
try{producten.add(ODD.get(i));}catch(Exception ex){}
}
ArrayList<Doos> dozen = new ArrayList<>();
//Voor <SUF>
for(Product p: producten){
boolean isPlaced = false;
//Controleer elke doos of er plek is.
for(int i = 0; i < dozen.size(); i++){
if(!isPlaced && dozen.get(i).getFreeSpace() >= p.getSize()){
dozen.get(i).addProduct(p);
isPlaced = true;
}
}
//Maak een nieuwe doos aan als er geen enkele doos was
//die nog plek had.
if(isPlaced == false){
Doos d = new Doos();
d.addProduct(p);
dozen.add(d);
}
}
return dozen;
}
}
|
23465_1 | package org.firstinspires.ftc.teamcode.robotparts;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.HardwareMap;
public class Arm {
/** De positie */
public int position = 0;
public int offset = 0;
/** Ben ik al aan het stoppen? */
boolean ikBenAanHetStoppen = false;
public DcMotorEx motor;
public Arm(HardwareMap hardwareMap) {
// Create arm motor.
motor = hardwareMap.get(DcMotorEx.class, "Arm");
// Set accuracy of position.
// todo: 1 is een mooi getal volgens Jeroen. Controleer of dit klopt! was 11
motor.setTargetPositionTolerance(5);
// onzin van bram
motor.setMode(DcMotorEx.RunMode.STOP_AND_RESET_ENCODER);
/** Run all motors with encoders. */
motor.setTargetPosition(0);
motor.setMode(DcMotorEx.RunMode.RUN_TO_POSITION);
}
// Move the arm the up.
public void MoveArmUp() {
motor.setPower(1.0);
motor.setTargetPosition(position+offset);
ikBenAanHetStoppen = false;
position++;
}
// Move the arm the down.
public void MoveArmDown() {
motor.setPower(1.0);
motor.setTargetPosition(position+offset);
ikBenAanHetStoppen = false;
position--;
}
// Stop the arm.
public void StopArm() {
motor.setPower(1.0);
if (ikBenAanHetStoppen) {
motor.setTargetPosition(position+offset);
} else {
position = motor.getCurrentPosition();
ikBenAanHetStoppen = true;
}
}
public void ArmReset(){
offset = motor.getCurrentPosition();
}
public void AutoArmToBoardPosition(){
motor.setPower(0.3);
motor.setTargetPosition(170);
}
public void ArmToLowestPosition(){
motor.setPower(1.0);
position = 0;
motor.setTargetPosition(position+offset);
}
public void ArmToNeutralPosition(){
motor.setPower(1.0);
position = 60 ;
motor.setTargetPosition(position+offset);
}
public void ArmToStageDoorPosition(){
motor.setPower(1.0);
position = 90 ;
motor.setTargetPosition(position+offset);
}
} | 16788-TheEncryptedGentlemen/FtcRobotController | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/robotparts/Arm.java | 631 | /** Ben ik al aan het stoppen? */ | block_comment | nl | package org.firstinspires.ftc.teamcode.robotparts;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.HardwareMap;
public class Arm {
/** De positie */
public int position = 0;
public int offset = 0;
/** Ben ik<SUF>*/
boolean ikBenAanHetStoppen = false;
public DcMotorEx motor;
public Arm(HardwareMap hardwareMap) {
// Create arm motor.
motor = hardwareMap.get(DcMotorEx.class, "Arm");
// Set accuracy of position.
// todo: 1 is een mooi getal volgens Jeroen. Controleer of dit klopt! was 11
motor.setTargetPositionTolerance(5);
// onzin van bram
motor.setMode(DcMotorEx.RunMode.STOP_AND_RESET_ENCODER);
/** Run all motors with encoders. */
motor.setTargetPosition(0);
motor.setMode(DcMotorEx.RunMode.RUN_TO_POSITION);
}
// Move the arm the up.
public void MoveArmUp() {
motor.setPower(1.0);
motor.setTargetPosition(position+offset);
ikBenAanHetStoppen = false;
position++;
}
// Move the arm the down.
public void MoveArmDown() {
motor.setPower(1.0);
motor.setTargetPosition(position+offset);
ikBenAanHetStoppen = false;
position--;
}
// Stop the arm.
public void StopArm() {
motor.setPower(1.0);
if (ikBenAanHetStoppen) {
motor.setTargetPosition(position+offset);
} else {
position = motor.getCurrentPosition();
ikBenAanHetStoppen = true;
}
}
public void ArmReset(){
offset = motor.getCurrentPosition();
}
public void AutoArmToBoardPosition(){
motor.setPower(0.3);
motor.setTargetPosition(170);
}
public void ArmToLowestPosition(){
motor.setPower(1.0);
position = 0;
motor.setTargetPosition(position+offset);
}
public void ArmToNeutralPosition(){
motor.setPower(1.0);
position = 60 ;
motor.setTargetPosition(position+offset);
}
public void ArmToStageDoorPosition(){
motor.setPower(1.0);
position = 90 ;
motor.setTargetPosition(position+offset);
}
} |
126393_16 | import java.util.ArrayList;
import java.util.LinkedList;
public class genrictree {
public static class Node {
int data = 0;
ArrayList<Node> childs;
Node(int data) {
this.data = data;
this.childs = new ArrayList<>();
}
}
// public static int height(Node root) {
// int h = 0;
// for(Node child: root.childs){
// h = Math.max(height(child) + 1,h);
// }
// return h + 1;
// }
public static int height2(Node root) {
int h = -1;
for (Node child : root.childs) {
h = Math.max(height2(child), h);
}
return h + 1;
}
public static int size2(Node root) {
int count = 0;
for (int i = 0; i < root.childs.size(); i++) {
Node child = root.childs.get(i);
count += size2(child);
}
return count + 1;
}
public static int size(Node root) {
int count = 0;
for (Node child : root.childs) {
count += size(child);
}
return count + 1;
}
public static int maximum(Node root) {
int max = root.data;
for (Node child : root.childs) {
max = Math.max(maximum(child), max);
}
return max;
}
public static int minimum(Node root) {
int min = root.data;
for (Node child : root.childs) {
min = Math.max(minimum(child), min);
}
return min;
}
public static int sum(Node root) {
int sum = root.data;
for (Node child : root.childs) {
sum += sum(child);
}
return sum;
}
// for loop basecase ko smhaal lega
// we dont go on null values in genric tree fyda ni hai genric mai
public static boolean find(Node root, int data) { // correct
if (root.data == data) {
return true;
}
boolean res = false;
for (Node child : root.childs) {
res = res || find(child, data);
}
return res;
}
public static boolean find2(Node root, int data) { // not correct
if (root.data == data) {
return true;
}
boolean res = false;
for (Node child : root.childs) {
if (find2(child, data)) {
res = true;
break;
}
}
return res;
}
public static int countleaves(Node root) {
if (root.childs.size() == 0) {
return 1;
}
int count = 0;
for (Node child : root.childs) {
count += countleaves(child);
}
return count;
}
// 1 return types 1 in arugument types
public static boolean nodeToRootPath2(Node root, int data, ArrayList<Node> ans) {
if (root.data == data) {
ans.add(root);
return true;
}
boolean res = false;
for (Node child : root.childs) {
res = res || nodeToRootPath2(child, data, ans);
}
if (res) {
ans.add(root);
}
return res;
}
// using return type
public static ArrayList<Node> nodeToRootPath(Node root, int data) {
if (root.data == data) {
ArrayList<Node> base = new ArrayList<>();
base.add(root);
return base;
}
ArrayList<Node> smallNodes = new ArrayList<>(); // agr nodes k sth kaam krna hai to loop k bahar kro andytha na
// kro
for (Node child : root.childs) { // child k sth kaam krna hai to loop k andr kro wrna mt kro
smallNodes = nodeToRootPath(child, data);
if (smallNodes.size() != 0) {
break;
}
}
if (smallNodes.size() != 0) {
smallNodes.add(root);
}
return smallNodes;
}
public static Node lca(Node root, int d1, int d2) {
ArrayList<Node> list1 = nodeToRootPath(root, d1);
ArrayList<Node> list2 = nodeToRootPath(root, d2);
int i = list1.size() - 1;
int j = list2.size() - 1;
Node Lca = null;
while (i >= 0 && j >= 0) {
if (list1.get(i) != list2.get(j)) {
break;
}
Lca = list1.get(j);
i--;
j--;
}
return Lca;
}
// public static int distanceBetweenNodes(Node root, int d1, int d2){
// Node lcanode = lca(root,d1, d2);
// distanceBetweenNodes(root.right, d1, d2);
// distanceBetweenNodes(root.left, d1, d2);
// }
public static boolean aresimilart(Node n1, Node n2) { //both node are same in lenth and size but not in data
if (n1.childs.size() != n2.childs.size()) { //just cheacking the stucture
return false;
}
boolean res = true;
for (int i = 0; i < n1.childs.size(); i++) {
Node c1 = n1.childs.get(i);
Node c2 = n2.childs.get(i);
res = res && aresimilart(c1, c2);
}
return res;
}
public static boolean aremirror(Node n1, Node n2) { //the both data node are same in mirror shape size and in data too
if (n1.childs.size() != n2.childs.size() && n1.data != n2.data) {
return false;
}
boolean res = true;
int size = n1.childs.size();
for (int i = 0; i < size; i++) {
Node c1 = n1.childs.get(i);
Node c2 = n2.childs.get(size - i - 1);
res = res && aremirror(c1, c2);
}
return res;
}
public static boolean isSymatric(Node node) { //checking the half of data is same as the full tree
return aremirror(node, node);
}
static int ceil;
static int floor;
public static void ceilandfloor_(Node node, int data) { //cheaking the left highest node and right smallest node
if (node.data < data) { //basically cheacking the both nodes which is nearest to the given data
floor = Math.max(floor, node.data);
}
if (node.data > data) {
ceil = Math.min(ceil, node.data);
}
for (Node child : node.childs) {
ceilandfloor_(child, data);
}
}
public static void ceilandfloor(Node node, int data) {
ceil = (int) 1e9;
floor = -(int) 1e9;
ceilandfloor(node, data);
}
public static int floor(Node node, int num){
int maxres = -(int) 1e9; //finding max element on the tree but smaller then num
for(Node child : node.childs){
int largesttillnumber = floor(child,num);
maxres = Math.max(largesttillnumber, maxres);
}
return node.data < num ? Math.max(node.data, maxres) : maxres;
}
public static int kthlargest(Node node, int k ){
int num = (int) 1e9;
for(int i = 0; i < k; i++){
num = floor(node, num);
}
return num;
}
//this treversal technique is called bfs and dfs is normal onces we actually do in
public static void levelOrder(Node root){
LinkedList<Node> que = new LinkedList<>();
que.addLast(root);
int level = 0;
while(que.size() != 0){
int size = que.size();
while(size-- > 0){
Node rn = que.removeFirst();
System.out.print(rn.data + " ");
for(Node child : rn.childs) {
que.addLast(child);
}
}
level++;
}
System.out.print(".");
}
}
| 1dudecoder/DSAlgo | genric tree/genrictree.java | 2,257 | // distanceBetweenNodes(root.left, d1, d2); | line_comment | nl | import java.util.ArrayList;
import java.util.LinkedList;
public class genrictree {
public static class Node {
int data = 0;
ArrayList<Node> childs;
Node(int data) {
this.data = data;
this.childs = new ArrayList<>();
}
}
// public static int height(Node root) {
// int h = 0;
// for(Node child: root.childs){
// h = Math.max(height(child) + 1,h);
// }
// return h + 1;
// }
public static int height2(Node root) {
int h = -1;
for (Node child : root.childs) {
h = Math.max(height2(child), h);
}
return h + 1;
}
public static int size2(Node root) {
int count = 0;
for (int i = 0; i < root.childs.size(); i++) {
Node child = root.childs.get(i);
count += size2(child);
}
return count + 1;
}
public static int size(Node root) {
int count = 0;
for (Node child : root.childs) {
count += size(child);
}
return count + 1;
}
public static int maximum(Node root) {
int max = root.data;
for (Node child : root.childs) {
max = Math.max(maximum(child), max);
}
return max;
}
public static int minimum(Node root) {
int min = root.data;
for (Node child : root.childs) {
min = Math.max(minimum(child), min);
}
return min;
}
public static int sum(Node root) {
int sum = root.data;
for (Node child : root.childs) {
sum += sum(child);
}
return sum;
}
// for loop basecase ko smhaal lega
// we dont go on null values in genric tree fyda ni hai genric mai
public static boolean find(Node root, int data) { // correct
if (root.data == data) {
return true;
}
boolean res = false;
for (Node child : root.childs) {
res = res || find(child, data);
}
return res;
}
public static boolean find2(Node root, int data) { // not correct
if (root.data == data) {
return true;
}
boolean res = false;
for (Node child : root.childs) {
if (find2(child, data)) {
res = true;
break;
}
}
return res;
}
public static int countleaves(Node root) {
if (root.childs.size() == 0) {
return 1;
}
int count = 0;
for (Node child : root.childs) {
count += countleaves(child);
}
return count;
}
// 1 return types 1 in arugument types
public static boolean nodeToRootPath2(Node root, int data, ArrayList<Node> ans) {
if (root.data == data) {
ans.add(root);
return true;
}
boolean res = false;
for (Node child : root.childs) {
res = res || nodeToRootPath2(child, data, ans);
}
if (res) {
ans.add(root);
}
return res;
}
// using return type
public static ArrayList<Node> nodeToRootPath(Node root, int data) {
if (root.data == data) {
ArrayList<Node> base = new ArrayList<>();
base.add(root);
return base;
}
ArrayList<Node> smallNodes = new ArrayList<>(); // agr nodes k sth kaam krna hai to loop k bahar kro andytha na
// kro
for (Node child : root.childs) { // child k sth kaam krna hai to loop k andr kro wrna mt kro
smallNodes = nodeToRootPath(child, data);
if (smallNodes.size() != 0) {
break;
}
}
if (smallNodes.size() != 0) {
smallNodes.add(root);
}
return smallNodes;
}
public static Node lca(Node root, int d1, int d2) {
ArrayList<Node> list1 = nodeToRootPath(root, d1);
ArrayList<Node> list2 = nodeToRootPath(root, d2);
int i = list1.size() - 1;
int j = list2.size() - 1;
Node Lca = null;
while (i >= 0 && j >= 0) {
if (list1.get(i) != list2.get(j)) {
break;
}
Lca = list1.get(j);
i--;
j--;
}
return Lca;
}
// public static int distanceBetweenNodes(Node root, int d1, int d2){
// Node lcanode = lca(root,d1, d2);
// distanceBetweenNodes(root.right, d1, d2);
// dista<SUF>
// }
public static boolean aresimilart(Node n1, Node n2) { //both node are same in lenth and size but not in data
if (n1.childs.size() != n2.childs.size()) { //just cheacking the stucture
return false;
}
boolean res = true;
for (int i = 0; i < n1.childs.size(); i++) {
Node c1 = n1.childs.get(i);
Node c2 = n2.childs.get(i);
res = res && aresimilart(c1, c2);
}
return res;
}
public static boolean aremirror(Node n1, Node n2) { //the both data node are same in mirror shape size and in data too
if (n1.childs.size() != n2.childs.size() && n1.data != n2.data) {
return false;
}
boolean res = true;
int size = n1.childs.size();
for (int i = 0; i < size; i++) {
Node c1 = n1.childs.get(i);
Node c2 = n2.childs.get(size - i - 1);
res = res && aremirror(c1, c2);
}
return res;
}
public static boolean isSymatric(Node node) { //checking the half of data is same as the full tree
return aremirror(node, node);
}
static int ceil;
static int floor;
public static void ceilandfloor_(Node node, int data) { //cheaking the left highest node and right smallest node
if (node.data < data) { //basically cheacking the both nodes which is nearest to the given data
floor = Math.max(floor, node.data);
}
if (node.data > data) {
ceil = Math.min(ceil, node.data);
}
for (Node child : node.childs) {
ceilandfloor_(child, data);
}
}
public static void ceilandfloor(Node node, int data) {
ceil = (int) 1e9;
floor = -(int) 1e9;
ceilandfloor(node, data);
}
public static int floor(Node node, int num){
int maxres = -(int) 1e9; //finding max element on the tree but smaller then num
for(Node child : node.childs){
int largesttillnumber = floor(child,num);
maxres = Math.max(largesttillnumber, maxres);
}
return node.data < num ? Math.max(node.data, maxres) : maxres;
}
public static int kthlargest(Node node, int k ){
int num = (int) 1e9;
for(int i = 0; i < k; i++){
num = floor(node, num);
}
return num;
}
//this treversal technique is called bfs and dfs is normal onces we actually do in
public static void levelOrder(Node root){
LinkedList<Node> que = new LinkedList<>();
que.addLast(root);
int level = 0;
while(que.size() != 0){
int size = que.size();
while(size-- > 0){
Node rn = que.removeFirst();
System.out.print(rn.data + " ");
for(Node child : rn.childs) {
que.addLast(child);
}
}
level++;
}
System.out.print(".");
}
}
|
190714_7 | import java.util.ArrayList;
import java.util.List;
public class Dungeon {
private List<Map> levels;
private int INITIAL_EXP = 100;
private int currentLevelIndex;
public Dungeon(){
levels = new ArrayList<>();
initializeLevels();
currentLevelIndex = 0;
}
private void initializeLevels() {
// Level 1
List<Monster> monsters1 = new ArrayList<>();
monsters1.add(new Monster(
"Kanalisationsratte",
"Diese übergroßen Ratten sind äußerst aggressiv und versperren den Zugang in den Keller des Turms.",
25, 20, 5, 8, 10, 1));
levels.add(new Map(
"Du hast eine Infiltrationsplan zugesteckt bekommen, der dir den idealen Plan des Turmes zeigt," +
" um möglichst wenig Aufmerksamkeit zu erzeugen. \n" +
"Der Weg führt dich durch die Kanalisation... \n" +
"Kanalisationzugang des dunklen Turms (Level 1)"
+ "\n" + "Ein schrecklicher Gestank umgibt die Kanalisation.\n" +
" Du siehst am Ende des Kanalisationszugangs eine Gittertür aus der Licht scheint. \n" +
"Rote und aggressive Augen lurken aus der Dunkleheit hevor und blockieren dir den " +
"Zugang in den Turmkeller." + "\n" + monsters1.get(0).getName() + " greift dich an!",
monsters1,
false
));
// Level 2
List<Monster> monsters2 = new ArrayList<>();
monsters2.add(new Monster(
"Verpennter Gefängniswärter",
"Dieser desorientierte und übermüdete Gefängniswärter kann hinterlistig erledigt werden.",
40, 40, 7, 12, 20, 2));
levels.add(new Map(
"Kerker des dunklen Turms (Level 1)"
+ "\n" + "Die Gittertür quietscht, als du sie hinter dir schließt. \n" +
" Du siehst einige Kerkerzellen mit Monstern die dich im Blick haben. \n" +
"Am Ende des Kerkerkomplexes schläft ein Gefängniswärter auf dem Holzhocker neben einem Sekretärtisch. \n"
+ monsters2.get(0).getName() + " greift dich an!",
monsters2,
false
));
// Level 3
List<Monster> monsters3 = new ArrayList<>();
monsters3.add(new Monster(
"Wachsame Patrouille",
"Patrouilliert den Kellerkomplex. ",
60, 50, 10, 15, 25, 3));
levels.add(new Map(
"Kellerkorridore des dunklen Turms (Level 3)"
+ "\n" + "Du verlässt vorsichtig den Kerker und gelangst in eine Korridorsystem. \n" +
" Tatsächlich befinden sich Richtungspfeile mit Unterschrift unter den Laternen \n" +
"Du siehst das Schild ''Küche'' und vermutest dort weniger gutgepanzerte Gegner. \n" +
"Plötzlich hörst du aus einem Korridor eine Patrouille ''Eindringling!'' schreien und siehst, wie diese auf dich zurennt...\n "
+ monsters3.get(0).getName() + " greift dich an!",
monsters3,
false
));
// Level 4
List<Monster> monsters4 = new ArrayList<>();
monsters4.add(new Monster(
"Besessener Küchenchef",
"Dieser Koch scheint nicht mehr er selbst zu sein, sondern wirkt komplett besessen!",
65, 65, 8, 13, 10, 4));
levels.add(new Map(
"Küche des dunklen Turms (Level 4)"
+ "\n" + "Du betrittst die Küche und hoffst auf Zivilisten oder Angestellte, \n" +
" die dir nicht direkt an den Kragen wollen. \n" +
"Der cholerische Küchenchef hat aber bedrohliche lila leuchtende Augen und wirkt komplett besessen. \n" +
"Er blickt zu dir und schreit ''Eindringling! Aus dir mach ich Gulasch für den Meister!'' \n" +
" und macht sich mit seinem Küchenbeil bereit für den Kampf.\n"
+ monsters4.get(0).getName() + " greift dich an!",
monsters4,
false
));
// Level 5
List<Monster> monsters5 = new ArrayList<>();
monsters5.add(new Monster(
"Unvorbereiteter Jäger",
"Dieser Jäger erholt sich von einer langen Jagdtour und ist nicht vorbereitet für einen Hinterhalt",
80, 75, 6, 14, 20, 5));
levels.add(new Map(
"Jagdraum des dunklen Turms (Level 5)"
+ "\n" + "Die verängstigten Küchenhilfen zeigen mit einem Finger auf eine Holztür " +
"''Da ist der Ausgang - Bitte verschone uns!'' \n " +
" \n In der Tat ist dies die einzige Tür die nach oben führt. Du gehst hindurch und befindest \n" +
" dich in einem Raum für die Jäger. Hier erholen sie sich, wenn sie ihr erlegtes Wild zum Küchenchef bringen. \n" +
" Zum Glück scheint die Jagdtruppe unterwegs zu sein, da nur ein ausruhender Jäger am Kamin überrascht aufspringt. \n" +
" ''Ah, verdammt! Wo ist mein Bogen!?'' - statt zum Bogen greift er zu einem Speer, der dekorativ an der Wand hängt.\n"
+ monsters5.get(0).getName() + " greift dich an!",
monsters5,
false
));
// Level 6
List<Monster> monsters6 = new ArrayList<>();
monsters6.add(new Monster(
"Mutiger Knappe",
"Ein mutiger Knappe, der davon träumt ein Ritter zu werden",
85, 80, 10, 15, 30, 6));
levels.add(new Map(
"Schlafgemach der Ritterkaserne im dunklen Turm (Level 6)"
+ "\n" + "Neben dem Jagdraum befinden sich die Schlafgemächer der Ritter. \n" +
" Ein junger Knappe stellt sich dir entgegen, als du durch das Schlafgemacht schleichen willst!. \n" +
monsters6.get(0).getName() + " greift dich an!",
monsters6,
false
));
// Level 7
List<Monster> monsters7 = new ArrayList<>();
monsters7.add(new Monster(
"Kreuzritter",
"Der Kreuzritter ist Mentor des mutigen Knappen",
95, 90, 10, 15, 35, 7));
levels.add(new Map(
"Bedienstetengänge Teil 1 - (Level 7)"
+ "\n" + "Du durchstreifst eine spezielle Route in den Bedienstetengängen. \n" +
" Hinter dir rennt ein Kreuzritter und stellt sich dir. Es ist der Ausbilder des Knappen. \n" +
"Er will Rache! \n" +
monsters7.get(0).getName() + " greift dich an!",
monsters7,
false
));
// Level 8
List<Monster> monsters8 = new ArrayList<>();
monsters8.add(new Monster(
"Hexenmeister-Akolyth",
"Ein Anfänger der Hexenkunst.",
100, 100, 10, 12, 35, 8));
levels.add(new Map(
"Bedienstetengänge Teil 2 - (Level 8)"
+ "\n" + "Nachdem du auch den Kreuzritter geschlagen hast, rennst du schnell durch den \n" +
" Bedienstetengang zu dem Zugang in Richtung Turmherr \n" +
"Hinter dem Zugang erwartet dich ein junger Hexenmeister und will dich aufhalten \n"
+ monsters8.get(0).getName() + " greift dich an!",
monsters8,
false
));
// Level 9
List<Monster> monsters9 = new ArrayList<>();
monsters9.add(new Monster(
"Kerberos",
"Haustier von Ivan dem Schrecklichen",
130, 125, 11, 15, 25, 9));
levels.add(new Map(
"Vorraum zum Foyer im dunklen Turm (Level 9)"
+ "\n" + " Du sieht einen eindrucksvollen Foyer vor deinen Augen \n" +
" Du sprintest gen Foyer, ehe du von einem Hund mit drei Köpfen angesprungen wirst! \n" +
monsters9.get(0).getName() +" greift dich an!",
monsters9,
false
));
// Level 10
List<Monster> monsters10 = new ArrayList<>();
monsters10.add(new Monster(
"Mamorwächter (Boss Gegner)",
"Ein riesiger Golem, der aus Marmor geschlagen wurde und jeden Eindringling gnadenlos zermalmt.",
200, 200, 15, 20, 40, 10));
levels.add(new Map(
"Eindrucksvolles Foyer im dunklen Turm (Level 10)"
+ "\n" + "Du siehst einen großen Tür, umgeben von Statuen in einem Foyer-ähnlichen Raum \n" +
"\n Du gehst auf die große Tür zu, doch dann erwacht einer der Statuen zum Leben!" +
"''Eli...miniere... Eindringling!'' \n" + monsters10.get(0).getName() + " greift dich an!",
monsters10,
true
));
// Level 11
List<Monster> monsters11 = new ArrayList<>();
monsters11.add(new Monster(
"Banshee",
"Eine schreiende Banshee, die durch die verlorenen " +
"Hallen streift und seit Jahren neue Opfer sucht.",
160, 155, 10, 15, 30, 11));
levels.add(new Map(
"Oberer Teil des Dunklen Turms - Die verlorenen Hallen (Level 11)"
+ "\n" + "Ein kalter Wind weht durch die verlassenen Hallen des dunklen Turms. \n" +
" Nur wenige Fackeln leuchten und du merkst, dass du dich final im oberen Teil des Turms befindest. \n" +
"Eine ohrenbetäubende Frauenstimme sucht dich heim. In der ferne siehst du ein Abbild einer Banshee " +
"in Form einer ausgemergelten Frau!" +
"\n" + monsters10.get(0).getName() + " greift dich an!",
monsters11,
false
));
// Level 12
List<Monster> monsters12 = new ArrayList<>();
monsters12.add(new Monster(
"Mächtiger Hexenmeister",
"Berater und rechte Hand von Ivan dem Schrecklichen!",
180, 190, 17, 20, 30, 12));
levels.add(new Map(
"Dunkler Turm - Turmspitze (Level 12)"
+ "\n" + "Vor einem großen prächtigen Tor flackern bunte Flammen in Feuerschalen. \n" +
"Die Umgebung wirkt fast wie ein Labor eines mächtigen Zauberes. Aus der Dunkelheit \n" +
"taucht ein mächtiger Hexenmeister vor, der bedrohlich lila Flammen zaubern kann \n" +
monsters12.get(0).getName() + " greift dich an!",
monsters12,
false
));
// Level 13
List<Monster> monsters13 = new ArrayList<>();
monsters13.add(new Monster(
"Schattenwesen",
"Ein Wesen aus der Hölle",
180, 190, 17, 20, 30, 13));
levels.add(new Map(
"Dunkler Turm - Turmspitze (Level 13)"
+ "\n" + "Bevor du zum Turmherr gelangst, musst du dich durch weitere schemenhafte Wesen durchkämpfen. \n" +
"Sie tarnen sich in den Schatten und greifen dich hinterhältig an. \n" +
monsters13.get(0).getName() + " greift dich an!",
monsters13,
false
));
// Level 14
List<Monster> monsters14 = new ArrayList<>();
monsters14.add(new Monster(
"Ivan der Schreckliche - Turmherr (Endboss)",
"Vor dir steht der Herrscher des Turms - Ivan der Schreckliche!",
200, 200, 20, 25, 58, 14));
levels.add(new Map(
"Herrschergemächer des dunklen Turms - Spitze des Turms (Endboss)"
+ "\n" + "Nach all den düsteren Gängen erwartet dich ein prächtiger Saal mit Thron. \n" +
" Vor dir steht der Tyrann des Königreichs - Ivan der Schreckliche. \n" +
"Bezwinge Ivan und werde Held des Königreichs!",
monsters14,
true
));
};
public Map getLevel(){
return levels.get(currentLevelIndex);
}
// Method to calculate exp amount based on dungeon level
public int calculateExpForLevel(int levelNumber) {
// check if level is valid
if (levelNumber >= 1 && levelNumber <= levels.size()) {
// exp grows with each level
return INITIAL_EXP * levelNumber;
} else {
throw new IllegalArgumentException("Ungültige Level-Nummer");
}
}
public int getCurrentLevelIndex() {
return currentLevelIndex;
}
public void increaseLevel() {
if (currentLevelIndex < 12){
currentLevelIndex++;
} else {
for (int i = 0; i <= 10; i++){
System.out.println(" "); // Clear the console a bit
}
GameLogic.endgame();
}
}
}
| 2000eBe/SE2024_Textbased_RPG | src/main/java/Dungeon.java | 3,486 | // Level 8 | line_comment | nl | import java.util.ArrayList;
import java.util.List;
public class Dungeon {
private List<Map> levels;
private int INITIAL_EXP = 100;
private int currentLevelIndex;
public Dungeon(){
levels = new ArrayList<>();
initializeLevels();
currentLevelIndex = 0;
}
private void initializeLevels() {
// Level 1
List<Monster> monsters1 = new ArrayList<>();
monsters1.add(new Monster(
"Kanalisationsratte",
"Diese übergroßen Ratten sind äußerst aggressiv und versperren den Zugang in den Keller des Turms.",
25, 20, 5, 8, 10, 1));
levels.add(new Map(
"Du hast eine Infiltrationsplan zugesteckt bekommen, der dir den idealen Plan des Turmes zeigt," +
" um möglichst wenig Aufmerksamkeit zu erzeugen. \n" +
"Der Weg führt dich durch die Kanalisation... \n" +
"Kanalisationzugang des dunklen Turms (Level 1)"
+ "\n" + "Ein schrecklicher Gestank umgibt die Kanalisation.\n" +
" Du siehst am Ende des Kanalisationszugangs eine Gittertür aus der Licht scheint. \n" +
"Rote und aggressive Augen lurken aus der Dunkleheit hevor und blockieren dir den " +
"Zugang in den Turmkeller." + "\n" + monsters1.get(0).getName() + " greift dich an!",
monsters1,
false
));
// Level 2
List<Monster> monsters2 = new ArrayList<>();
monsters2.add(new Monster(
"Verpennter Gefängniswärter",
"Dieser desorientierte und übermüdete Gefängniswärter kann hinterlistig erledigt werden.",
40, 40, 7, 12, 20, 2));
levels.add(new Map(
"Kerker des dunklen Turms (Level 1)"
+ "\n" + "Die Gittertür quietscht, als du sie hinter dir schließt. \n" +
" Du siehst einige Kerkerzellen mit Monstern die dich im Blick haben. \n" +
"Am Ende des Kerkerkomplexes schläft ein Gefängniswärter auf dem Holzhocker neben einem Sekretärtisch. \n"
+ monsters2.get(0).getName() + " greift dich an!",
monsters2,
false
));
// Level 3
List<Monster> monsters3 = new ArrayList<>();
monsters3.add(new Monster(
"Wachsame Patrouille",
"Patrouilliert den Kellerkomplex. ",
60, 50, 10, 15, 25, 3));
levels.add(new Map(
"Kellerkorridore des dunklen Turms (Level 3)"
+ "\n" + "Du verlässt vorsichtig den Kerker und gelangst in eine Korridorsystem. \n" +
" Tatsächlich befinden sich Richtungspfeile mit Unterschrift unter den Laternen \n" +
"Du siehst das Schild ''Küche'' und vermutest dort weniger gutgepanzerte Gegner. \n" +
"Plötzlich hörst du aus einem Korridor eine Patrouille ''Eindringling!'' schreien und siehst, wie diese auf dich zurennt...\n "
+ monsters3.get(0).getName() + " greift dich an!",
monsters3,
false
));
// Level 4
List<Monster> monsters4 = new ArrayList<>();
monsters4.add(new Monster(
"Besessener Küchenchef",
"Dieser Koch scheint nicht mehr er selbst zu sein, sondern wirkt komplett besessen!",
65, 65, 8, 13, 10, 4));
levels.add(new Map(
"Küche des dunklen Turms (Level 4)"
+ "\n" + "Du betrittst die Küche und hoffst auf Zivilisten oder Angestellte, \n" +
" die dir nicht direkt an den Kragen wollen. \n" +
"Der cholerische Küchenchef hat aber bedrohliche lila leuchtende Augen und wirkt komplett besessen. \n" +
"Er blickt zu dir und schreit ''Eindringling! Aus dir mach ich Gulasch für den Meister!'' \n" +
" und macht sich mit seinem Küchenbeil bereit für den Kampf.\n"
+ monsters4.get(0).getName() + " greift dich an!",
monsters4,
false
));
// Level 5
List<Monster> monsters5 = new ArrayList<>();
monsters5.add(new Monster(
"Unvorbereiteter Jäger",
"Dieser Jäger erholt sich von einer langen Jagdtour und ist nicht vorbereitet für einen Hinterhalt",
80, 75, 6, 14, 20, 5));
levels.add(new Map(
"Jagdraum des dunklen Turms (Level 5)"
+ "\n" + "Die verängstigten Küchenhilfen zeigen mit einem Finger auf eine Holztür " +
"''Da ist der Ausgang - Bitte verschone uns!'' \n " +
" \n In der Tat ist dies die einzige Tür die nach oben führt. Du gehst hindurch und befindest \n" +
" dich in einem Raum für die Jäger. Hier erholen sie sich, wenn sie ihr erlegtes Wild zum Küchenchef bringen. \n" +
" Zum Glück scheint die Jagdtruppe unterwegs zu sein, da nur ein ausruhender Jäger am Kamin überrascht aufspringt. \n" +
" ''Ah, verdammt! Wo ist mein Bogen!?'' - statt zum Bogen greift er zu einem Speer, der dekorativ an der Wand hängt.\n"
+ monsters5.get(0).getName() + " greift dich an!",
monsters5,
false
));
// Level 6
List<Monster> monsters6 = new ArrayList<>();
monsters6.add(new Monster(
"Mutiger Knappe",
"Ein mutiger Knappe, der davon träumt ein Ritter zu werden",
85, 80, 10, 15, 30, 6));
levels.add(new Map(
"Schlafgemach der Ritterkaserne im dunklen Turm (Level 6)"
+ "\n" + "Neben dem Jagdraum befinden sich die Schlafgemächer der Ritter. \n" +
" Ein junger Knappe stellt sich dir entgegen, als du durch das Schlafgemacht schleichen willst!. \n" +
monsters6.get(0).getName() + " greift dich an!",
monsters6,
false
));
// Level 7
List<Monster> monsters7 = new ArrayList<>();
monsters7.add(new Monster(
"Kreuzritter",
"Der Kreuzritter ist Mentor des mutigen Knappen",
95, 90, 10, 15, 35, 7));
levels.add(new Map(
"Bedienstetengänge Teil 1 - (Level 7)"
+ "\n" + "Du durchstreifst eine spezielle Route in den Bedienstetengängen. \n" +
" Hinter dir rennt ein Kreuzritter und stellt sich dir. Es ist der Ausbilder des Knappen. \n" +
"Er will Rache! \n" +
monsters7.get(0).getName() + " greift dich an!",
monsters7,
false
));
// Level<SUF>
List<Monster> monsters8 = new ArrayList<>();
monsters8.add(new Monster(
"Hexenmeister-Akolyth",
"Ein Anfänger der Hexenkunst.",
100, 100, 10, 12, 35, 8));
levels.add(new Map(
"Bedienstetengänge Teil 2 - (Level 8)"
+ "\n" + "Nachdem du auch den Kreuzritter geschlagen hast, rennst du schnell durch den \n" +
" Bedienstetengang zu dem Zugang in Richtung Turmherr \n" +
"Hinter dem Zugang erwartet dich ein junger Hexenmeister und will dich aufhalten \n"
+ monsters8.get(0).getName() + " greift dich an!",
monsters8,
false
));
// Level 9
List<Monster> monsters9 = new ArrayList<>();
monsters9.add(new Monster(
"Kerberos",
"Haustier von Ivan dem Schrecklichen",
130, 125, 11, 15, 25, 9));
levels.add(new Map(
"Vorraum zum Foyer im dunklen Turm (Level 9)"
+ "\n" + " Du sieht einen eindrucksvollen Foyer vor deinen Augen \n" +
" Du sprintest gen Foyer, ehe du von einem Hund mit drei Köpfen angesprungen wirst! \n" +
monsters9.get(0).getName() +" greift dich an!",
monsters9,
false
));
// Level 10
List<Monster> monsters10 = new ArrayList<>();
monsters10.add(new Monster(
"Mamorwächter (Boss Gegner)",
"Ein riesiger Golem, der aus Marmor geschlagen wurde und jeden Eindringling gnadenlos zermalmt.",
200, 200, 15, 20, 40, 10));
levels.add(new Map(
"Eindrucksvolles Foyer im dunklen Turm (Level 10)"
+ "\n" + "Du siehst einen großen Tür, umgeben von Statuen in einem Foyer-ähnlichen Raum \n" +
"\n Du gehst auf die große Tür zu, doch dann erwacht einer der Statuen zum Leben!" +
"''Eli...miniere... Eindringling!'' \n" + monsters10.get(0).getName() + " greift dich an!",
monsters10,
true
));
// Level 11
List<Monster> monsters11 = new ArrayList<>();
monsters11.add(new Monster(
"Banshee",
"Eine schreiende Banshee, die durch die verlorenen " +
"Hallen streift und seit Jahren neue Opfer sucht.",
160, 155, 10, 15, 30, 11));
levels.add(new Map(
"Oberer Teil des Dunklen Turms - Die verlorenen Hallen (Level 11)"
+ "\n" + "Ein kalter Wind weht durch die verlassenen Hallen des dunklen Turms. \n" +
" Nur wenige Fackeln leuchten und du merkst, dass du dich final im oberen Teil des Turms befindest. \n" +
"Eine ohrenbetäubende Frauenstimme sucht dich heim. In der ferne siehst du ein Abbild einer Banshee " +
"in Form einer ausgemergelten Frau!" +
"\n" + monsters10.get(0).getName() + " greift dich an!",
monsters11,
false
));
// Level 12
List<Monster> monsters12 = new ArrayList<>();
monsters12.add(new Monster(
"Mächtiger Hexenmeister",
"Berater und rechte Hand von Ivan dem Schrecklichen!",
180, 190, 17, 20, 30, 12));
levels.add(new Map(
"Dunkler Turm - Turmspitze (Level 12)"
+ "\n" + "Vor einem großen prächtigen Tor flackern bunte Flammen in Feuerschalen. \n" +
"Die Umgebung wirkt fast wie ein Labor eines mächtigen Zauberes. Aus der Dunkelheit \n" +
"taucht ein mächtiger Hexenmeister vor, der bedrohlich lila Flammen zaubern kann \n" +
monsters12.get(0).getName() + " greift dich an!",
monsters12,
false
));
// Level 13
List<Monster> monsters13 = new ArrayList<>();
monsters13.add(new Monster(
"Schattenwesen",
"Ein Wesen aus der Hölle",
180, 190, 17, 20, 30, 13));
levels.add(new Map(
"Dunkler Turm - Turmspitze (Level 13)"
+ "\n" + "Bevor du zum Turmherr gelangst, musst du dich durch weitere schemenhafte Wesen durchkämpfen. \n" +
"Sie tarnen sich in den Schatten und greifen dich hinterhältig an. \n" +
monsters13.get(0).getName() + " greift dich an!",
monsters13,
false
));
// Level 14
List<Monster> monsters14 = new ArrayList<>();
monsters14.add(new Monster(
"Ivan der Schreckliche - Turmherr (Endboss)",
"Vor dir steht der Herrscher des Turms - Ivan der Schreckliche!",
200, 200, 20, 25, 58, 14));
levels.add(new Map(
"Herrschergemächer des dunklen Turms - Spitze des Turms (Endboss)"
+ "\n" + "Nach all den düsteren Gängen erwartet dich ein prächtiger Saal mit Thron. \n" +
" Vor dir steht der Tyrann des Königreichs - Ivan der Schreckliche. \n" +
"Bezwinge Ivan und werde Held des Königreichs!",
monsters14,
true
));
};
public Map getLevel(){
return levels.get(currentLevelIndex);
}
// Method to calculate exp amount based on dungeon level
public int calculateExpForLevel(int levelNumber) {
// check if level is valid
if (levelNumber >= 1 && levelNumber <= levels.size()) {
// exp grows with each level
return INITIAL_EXP * levelNumber;
} else {
throw new IllegalArgumentException("Ungültige Level-Nummer");
}
}
public int getCurrentLevelIndex() {
return currentLevelIndex;
}
public void increaseLevel() {
if (currentLevelIndex < 12){
currentLevelIndex++;
} else {
for (int i = 0; i <= 10; i++){
System.out.println(" "); // Clear the console a bit
}
GameLogic.endgame();
}
}
}
|
15219_11 | package com.rs2.world;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import com.rs2.game.npcs.Npc;
import com.rs2.game.players.Player;
import com.rs2.game.players.PlayerHandler;
/**
* @author Andrew (Mr Extremez) - added all the boundaries
* @author Jason http://www.rune-server.org/members/jason - made the system
* @date Mar 2, 2014
*/
public class Boundary {
public int minX, highX, minY, highY, height;
/**
*
* @param minX
* The south-west x coordinate
* @param highX
* The north-east x coordinate
* @param minY
* The south-west y coordinate
* @param highY
* The north-east y coordinate
*/
public Boundary(int minX, int highX, int minY, int highY) {
this.minX = Math.min(minX, highX);
this.highX = Math.max(minX, highX);
this.minY = Math.min(minY, highY);
this.highY = Math.max(minY, highY);
this.height = -1;
}
/**
*
* @param minX
* The south-west x coordinate
* @param highX
* The north-east x coordinate
* @param minY
* The south-west y coordinate
* @param highY
* The north-east y coordinate
* @param height
* The height of the boundary
*/
public Boundary(int minX, int highX, int minY, int highY, int height) {
this.minX = Math.min(minX, highX);
this.highX = Math.max(minX, highX);
this.minY = Math.min(minY, highY);
this.highY = Math.max(minY, highY);
this.height = height;
}
/**
*
* @param player
* The player object
* @param boundaries
* The array of Boundary objects
* @return
*/
public static boolean isIn(Player player, Boundary[] boundaries) {
for (Boundary b : boundaries) {
if (b.height >= 0) {
if (player.getH() != b.height) {
continue;
}
}
if (player.getX() >= b.minX && player.getX() <= b.highX && player.getY() >= b.minY && player.getY() <= b.highY) {
return true;
}
}
return false;
}
/**
*
* @param player
* The player object
* @param boundaries
* The boundary object
* @return
*/
public static boolean isIn(Player player, Boundary boundaries) {
if (boundaries.height >= 0) {
if (player.getH() != boundaries.height) {
return false;
}
}
return player.getX() >= boundaries.minX && player.getX() <= boundaries.highX && player.getY() >= boundaries.minY && player.getY() <= boundaries.highY;
}
/**
*
* @param x
* The x position
* @param y
* The y position
* @param boundaries
* The boundary object
* @return
*/
public static boolean isIn(int x, int y, Boundary boundaries) {
return x >= boundaries.minX && x <= boundaries.highX && y >= boundaries.minY && y <= boundaries.highY;
}
public static boolean isIn(int x, int y, int h, Boundary boundaries) {
if (boundaries.height >= 0) {
if (h != boundaries.height) {
return false;
}
}
return x >= boundaries.minX && x <= boundaries.highX && y >= boundaries.minY && y <= boundaries.highY;
}
/**
*
* @param npc
* The npc object
* @param boundaries
* The boundary object
* @return
*/
public static boolean isIn(Npc npc, Boundary boundaries) {
if (boundaries.height >= 0) {
if (npc.heightLevel != boundaries.height) {
return false;
}
}
return npc.getX() >= boundaries.minX && npc.getX() <= boundaries.highX && npc.getY() >= boundaries.minY && npc.getY() <= boundaries.highY;
}
public static boolean isIn(Npc npc, Boundary[] boundaries) {
for (Boundary boundary : boundaries) {
if (boundary.height >= 0) {
if (npc.heightLevel != boundary.height) {
return false;
}
}
if (npc.getX() >= boundary.minX && npc.getX() <= boundary.highX && npc.getY() >= boundary.minY && npc.getY() <= boundary.highY) {
return true;
}
}
return false;
}
public static boolean isInSameBoundary(Player player1, Player player2, Boundary[] boundaries) {
Optional<Boundary> boundary1 = Arrays.asList(boundaries).stream().filter(b -> isIn(player1, b)).findFirst();
Optional<Boundary> boundary2 = Arrays.asList(boundaries).stream().filter(b -> isIn(player2, b)).findFirst();
if (!boundary1.isPresent() || !boundary2.isPresent()) {
return false;
}
return Objects.equals(boundary1.get(), boundary2.get());
}
public static int entitiesInArea(Boundary boundary) {
int i = 0;
for (Player player : PlayerHandler.players)
if (player != null)
if (isIn(player, boundary))
i++;
return i;
}
/**
* Returns the centre point of a boundary as a {@link Coordinate}
*
* @param boundary The boundary of which we want the centre.
* @return The centre point of the boundary, represented as a {@link Coordinate}.
*/
public static Coordinate centre(Boundary boundary) {
int x = (boundary.minX + boundary.highX) / 2;
int y = (boundary.minY + boundary.highY) / 2;
if (boundary.height >= 0) {
return new Coordinate(x, y, boundary.height);
} else {
return new Coordinate(x, y, 0);
}
}
//low x, high x, low y, high y
public static final Boundary F2P = new Boundary(2944, 3328, 3097, 3515);
public static final Boundary TUTORIAL = new Boundary(3055, 3150, 3054, 3128);
public static final Boundary CRANDOR = new Boundary(2813, 2867, 3226, 3307);
public static final Boundary[] IN_F2P = {F2P, TUTORIAL, CRANDOR };
public static final Boundary LUMBRIDGE = new Boundary(3134, 3266, 3131, 3317);
public static final Boundary WIZARDS_TOWER = new Boundary(3094, 3124, 3141, 3172);
public static final Boundary FALADOR = new Boundary(2945, 3066, 3303, 3390);
public static final Boundary VARROCK = new Boundary(3172, 3289, 3368, 3504);
public static final Boundary DRAYNOR = new Boundary(3079, 3149, 3226, 3382);
public static final Boundary BARB = new Boundary(3072, 3098, 3399, 3445);
public static final Boundary GOBLIN_VILLAGE = new Boundary(2945, 2970, 3475, 3515);
public static final Boundary EDGEVILLE = new Boundary(3072, 3126, 3459, 3517);
public static final Boundary PORT_SARIM = new Boundary(3327, 3423, 3131, 3324);
public static final Boundary RIMMINGTON = new Boundary(3327, 3423, 3131, 3324);
public static final Boundary AL_KHARID = new Boundary(3327, 3423, 3131, 3324);
public static final Boundary[] BANK_AREA = new Boundary[] {
new Boundary(3205, 3212, 3217, 3224, 2), //Lumbridge
new Boundary(3264, 3273, 3160, 3174),//Al Kharid
new Boundary(2436, 2453, 5174, 5186),//TzHaar
new Boundary(2842, 2860, 2950, 2957),//Shilo
new Boundary(3456, 3492, 3200, 3215),//Burgh d rott
new Boundary(3377, 3386, 3266, 3275),//Duel
new Boundary(3087, 3098, 3239, 3248),//Draynor
new Boundary(3248, 3260, 3414, 3423),//Varrock East
new Boundary(3183, 3193, 3432, 3446),//Varrock West
new Boundary(3088, 3100, 3486, 3501),//Edge
new Boundary(3009, 3020, 3352, 3358),//Fally East
new Boundary(2942, 2950, 3365, 3374),//Fally West
new Boundary(2804, 2815, 3438, 3447),//Catherby
new Boundary(2718, 2733, 3485, 3500),//Seers
new Boundary(2610, 2622, 3326, 3338),//North ardougne
new Boundary(2645, 2660, 3281, 3288),//South ardougne
new Boundary(2607, 2618, 3087, 3098),//Yanille
new Boundary(2442, 2444, 3081, 3084),//Castle Wars
new Boundary(2348, 2358, 3159, 3168),//Lleyta
new Boundary(2324, 2334, 3685, 3694),//Piscatoris
new Boundary(2442, 2448, 3420, 3430),//Tree Gnome Stronghold
new Boundary(2440, 2453, 3478, 3491, 1),//Grand Tree Area
new Boundary(3113, 3131, 3118, 3131),//Tut
new Boundary(2885, 2895, 3422, 3433),//Nardah
new Boundary(3685, 3694, 3461, 3473),//Phasmatys
new Boundary(2530, 2550, 4705, 4725),//Mage Bank
new Boundary(2834, 2841, 10204, 10215),//Keldagrim
new Boundary(2379, 2386, 4453, 4462),//Zanaris
new Boundary(2582, 2591, 3417, 3423),//Fishing Guild
new Boundary(3509, 3515, 3475, 3483),//Canifis
new Boundary(3297, 3311, 3115, 3133),//Shantay Pass
new Boundary(3035, 3049, 4967, 4977, 1),//Rogues Den
};
public static final Boundary ZAMMY_WAIT = new Boundary(2409, 2431, 9511, 9535);
public static final Boundary SARA_WAIT = new Boundary(2368, 2392, 9479, 9498);
public static final Boundary[] MULTI = new Boundary[] {
new Boundary(3136, 3327, 3519, 3607), new Boundary(2360, 2445, 5045, 5125), new Boundary(2256, 2287, 4680, 4711),
new Boundary(3190, 3327, 3648, 3839), new Boundary(3200, 3390, 3840, 3967), new Boundary(2992, 3007, 3912, 3967),
new Boundary(2946, 2959, 3816, 3831), new Boundary(3008, 3199, 3856, 3903), new Boundary(3008, 3071, 3600, 3711),
new Boundary(3072, 3327, 3608, 3647), new Boundary(2624, 2690, 2550, 2619), new Boundary(2667, 2685, 3712, 3730),
new Boundary(2371, 2422, 5062, 5117), new Boundary(2896, 2927, 3595, 3630), new Boundary(2892, 2932, 4435, 4464),
new Boundary(3279, 3307, 3156, 3179)
};
//jungle
public static final Boundary[] KARAMAJA = new Boundary[] {
new Boundary(2745, 3007, 2876, 3095), new Boundary(2747, 2944, 3096, 3131)
};
//jungle
public static final Boundary[] MUSA_POINT = new Boundary[] {
new Boundary(2817, 2917, 3192, 3204), new Boundary(2817, 2961, 3131, 3191)
};
//jungle
public static final Boundary BRIMHAVEN = new Boundary(2688, 2815, 3131, 3258);
//desert
public static final Boundary DESERT = new Boundary(3137, 3517, 2747, 3130, 0);
//desert - no heat
public static final Boundary NARDAH = new Boundary(3392, 3455, 2876, 2940);
public static final Boundary BANDIT_CAMP = new Boundary(3151, 3192, 2963, 2986);
public static final Boundary MINING_CAMP = new Boundary(3267, 3311, 3000, 3043);
public static final Boundary BEDABIN = new Boundary(3160, 3187, 3015, 3046);
public static final Boundary UZER = new Boundary(3462, 3503, 3068, 3109);
public static final Boundary AGILITY_PYRAMID = new Boundary(3329, 3391, 2812, 2855);
public static final Boundary PYRAMID = new Boundary(3217, 3250, 2881, 2908);
public static final Boundary SOPHANEM = new Boundary(3273, 3323, 2749, 2806);
public static final Boundary MENAPHOS = new Boundary(3200, 3266, 2749, 2806);
public static final Boundary POLLIVNEACH = new Boundary(3329, 3377, 2936, 3002);
public static final Boundary SHANTAY_PASS = new Boundary(3295, 3311, 3116, 3128);
public static final Boundary[] NO_HEAT = {NARDAH, BANDIT_CAMP, MINING_CAMP, BEDABIN, UZER, AGILITY_PYRAMID, PYRAMID, SOPHANEM, MENAPHOS, POLLIVNEACH, SHANTAY_PASS};
//mortyania
public static final Boundary MORTYANIA = new Boundary(3401, 3773, 3157, 3577);
//wild
public static final Boundary[] WILDERNESS = new Boundary[] { new Boundary(2941, 3392, 3518, 3966), new Boundary(2941, 3392, 9922, 10366) };
public static final Boundary IN_LESSER = new Boundary(3108, 3112, 3156, 3158, 2);
public static final Boundary IN_DUEL = new Boundary(3331, 3391, 3242, 3260);
public static final Boundary[] IN_DUEL_AREA = new Boundary[] { new Boundary(3322, 3394, 3195, 3291), new Boundary(3311, 3323, 3223, 3248) };
public static final Boundary TRAWLER_GAME = new Boundary (2808, 2811, 3415, 3425);
public static final Boundary PITS_WAIT = new Boundary (2394, 2404, 5169, 5175);
public static final Boundary[] LUMB_BUILDING = new Boundary[] { new Boundary(3205, 3216, 3209, 3228), new Boundary(3229, 3233, 3206, 3208), new Boundary(3228, 3233, 3201, 3205), new Boundary(3230, 3237, 3195, 3198), new Boundary(3238, 3229, 3209, 3211),
new Boundary(3240, 3247, 3204, 3215), new Boundary(3247, 3252, 3190, 3195), new Boundary(3227, 3230, 3212, 3216), new Boundary(3227, 3230, 3221, 3225), new Boundary(3229, 3232, 3236, 3241),
new Boundary(3209, 3213, 3243, 3250), new Boundary(3222, 3229, 3252, 3257), new Boundary(3184, 3192, 3270, 3275), new Boundary(3222, 3224, 3292, 3294), new Boundary(3225, 3230, 3287, 3228),
new Boundary(3243, 3248, 3244, 3248), new Boundary(3202, 3205, 3167, 3170), new Boundary(3231, 3238, 3151, 3155), new Boundary(3233, 3234, 3156, 3156), new Boundary(3163, 3170, 3305, 3308),
new Boundary(3165, 3168, 3303, 3310) };
public static final Boundary[] DRAYNOR_BUILDING = new Boundary[] { new Boundary(3097, 3102, 3277, 3281), new Boundary(3088, 3092, 3273, 3276), new Boundary(3096, 3102, 3266, 3270), new Boundary(3089, 3095, 3265, 3268), new Boundary(3083, 3088, 3256, 3261),
new Boundary(3087, 3094, 3251, 3255), new Boundary(3121, 3130, 3240, 3246), new Boundary(3102, 3112, 3162, 3165), new Boundary(3107, 3111, 3166, 3166), new Boundary(3103, 3115, 3157, 3161),
new Boundary(3105, 3114, 3156, 3156), new Boundary(3105, 3113, 3155, 3155), new Boundary(3106, 3112, 3154, 3154), new Boundary(3092, 3097, 3240, 3246) };
public static final Boundary VARROCK_BANK_BASEMENT = new Boundary(3186, 3197, 9817, 9824, 0);
public static final Boundary MAGE_TOWER_CAGE = new Boundary(3108, 3112, 3156, 3158, 2);
public static final Boundary ARDOUGNE_ZOO = new Boundary(2593, 2639, 3265, 3288);
public static final Boundary APE_ATOLL = new Boundary(2694, 2811, 2691, 2805);
public static final Boundary BARROWS = new Boundary(3543, 3584, 3265, 3311);
public static final Boundary BARROWS_UNDERGROUND = new Boundary(3529, 3581, 9673, 9722);
public static final Boundary PC_BOAT = new Boundary(2660, 2663, 2638, 2643);
public static final Boundary PC_GAME = new Boundary(2624, 2690, 2550, 2619);
public static final Boundary FIGHT_CAVES = new Boundary(2360, 2445, 5045, 5125);
public static final Boundary PIRATE_HOUSE = new Boundary(3038, 3044, 3949, 3959);
public static final Boundary[] FIGHT_PITS = new Boundary[] { new Boundary(2378, 3415, 5133, 5167), new Boundary(2394, 2404, 5169, 5174) };
public static final Boundary PARTY_ROOM = new Boundary(2727, 2746, 3460, 3479);
public static final Boundary PARTY_ROOM_TABLE = new Boundary(2735, 2740, 3467, 3468);
public static final Boundary MAGE_TRAINING_ARENA = new Boundary(3330, 3388, 9614, 9727);
public static final Boundary MAGE_TRAINING_ARENA_ENCHANTING = new Boundary(3341, 3386, 9618, 9662, 0);
public static final Boundary MAGE_TRAINING_ARENA_GRAVEYARD = new Boundary(3340, 3386, 9616, 9662, 1);
public static final Boundary MAGE_TRAINING_ARENA_ALCHEMY = new Boundary(3350, 3379, 9616, 9655, 2);
public static final Boundary MAGE_TRAINING_ARENA_TELEKINETIC = new Boundary(3329, 3390, 9665, 9726);
public static final Boundary[] DWARF_NO_FIREMAKING = new Boundary[] { new Boundary(2944, 3072, 3392, 3456), new Boundary(3008, 3072, 3456, 3520), new Boundary(2880, 2944, 3456, 3520) };
} | 2006-Scape/2006Scape | 2006Scape Server/src/main/java/com/rs2/world/Boundary.java | 6,623 | //TzHaar | line_comment | nl | package com.rs2.world;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import com.rs2.game.npcs.Npc;
import com.rs2.game.players.Player;
import com.rs2.game.players.PlayerHandler;
/**
* @author Andrew (Mr Extremez) - added all the boundaries
* @author Jason http://www.rune-server.org/members/jason - made the system
* @date Mar 2, 2014
*/
public class Boundary {
public int minX, highX, minY, highY, height;
/**
*
* @param minX
* The south-west x coordinate
* @param highX
* The north-east x coordinate
* @param minY
* The south-west y coordinate
* @param highY
* The north-east y coordinate
*/
public Boundary(int minX, int highX, int minY, int highY) {
this.minX = Math.min(minX, highX);
this.highX = Math.max(minX, highX);
this.minY = Math.min(minY, highY);
this.highY = Math.max(minY, highY);
this.height = -1;
}
/**
*
* @param minX
* The south-west x coordinate
* @param highX
* The north-east x coordinate
* @param minY
* The south-west y coordinate
* @param highY
* The north-east y coordinate
* @param height
* The height of the boundary
*/
public Boundary(int minX, int highX, int minY, int highY, int height) {
this.minX = Math.min(minX, highX);
this.highX = Math.max(minX, highX);
this.minY = Math.min(minY, highY);
this.highY = Math.max(minY, highY);
this.height = height;
}
/**
*
* @param player
* The player object
* @param boundaries
* The array of Boundary objects
* @return
*/
public static boolean isIn(Player player, Boundary[] boundaries) {
for (Boundary b : boundaries) {
if (b.height >= 0) {
if (player.getH() != b.height) {
continue;
}
}
if (player.getX() >= b.minX && player.getX() <= b.highX && player.getY() >= b.minY && player.getY() <= b.highY) {
return true;
}
}
return false;
}
/**
*
* @param player
* The player object
* @param boundaries
* The boundary object
* @return
*/
public static boolean isIn(Player player, Boundary boundaries) {
if (boundaries.height >= 0) {
if (player.getH() != boundaries.height) {
return false;
}
}
return player.getX() >= boundaries.minX && player.getX() <= boundaries.highX && player.getY() >= boundaries.minY && player.getY() <= boundaries.highY;
}
/**
*
* @param x
* The x position
* @param y
* The y position
* @param boundaries
* The boundary object
* @return
*/
public static boolean isIn(int x, int y, Boundary boundaries) {
return x >= boundaries.minX && x <= boundaries.highX && y >= boundaries.minY && y <= boundaries.highY;
}
public static boolean isIn(int x, int y, int h, Boundary boundaries) {
if (boundaries.height >= 0) {
if (h != boundaries.height) {
return false;
}
}
return x >= boundaries.minX && x <= boundaries.highX && y >= boundaries.minY && y <= boundaries.highY;
}
/**
*
* @param npc
* The npc object
* @param boundaries
* The boundary object
* @return
*/
public static boolean isIn(Npc npc, Boundary boundaries) {
if (boundaries.height >= 0) {
if (npc.heightLevel != boundaries.height) {
return false;
}
}
return npc.getX() >= boundaries.minX && npc.getX() <= boundaries.highX && npc.getY() >= boundaries.minY && npc.getY() <= boundaries.highY;
}
public static boolean isIn(Npc npc, Boundary[] boundaries) {
for (Boundary boundary : boundaries) {
if (boundary.height >= 0) {
if (npc.heightLevel != boundary.height) {
return false;
}
}
if (npc.getX() >= boundary.minX && npc.getX() <= boundary.highX && npc.getY() >= boundary.minY && npc.getY() <= boundary.highY) {
return true;
}
}
return false;
}
public static boolean isInSameBoundary(Player player1, Player player2, Boundary[] boundaries) {
Optional<Boundary> boundary1 = Arrays.asList(boundaries).stream().filter(b -> isIn(player1, b)).findFirst();
Optional<Boundary> boundary2 = Arrays.asList(boundaries).stream().filter(b -> isIn(player2, b)).findFirst();
if (!boundary1.isPresent() || !boundary2.isPresent()) {
return false;
}
return Objects.equals(boundary1.get(), boundary2.get());
}
public static int entitiesInArea(Boundary boundary) {
int i = 0;
for (Player player : PlayerHandler.players)
if (player != null)
if (isIn(player, boundary))
i++;
return i;
}
/**
* Returns the centre point of a boundary as a {@link Coordinate}
*
* @param boundary The boundary of which we want the centre.
* @return The centre point of the boundary, represented as a {@link Coordinate}.
*/
public static Coordinate centre(Boundary boundary) {
int x = (boundary.minX + boundary.highX) / 2;
int y = (boundary.minY + boundary.highY) / 2;
if (boundary.height >= 0) {
return new Coordinate(x, y, boundary.height);
} else {
return new Coordinate(x, y, 0);
}
}
//low x, high x, low y, high y
public static final Boundary F2P = new Boundary(2944, 3328, 3097, 3515);
public static final Boundary TUTORIAL = new Boundary(3055, 3150, 3054, 3128);
public static final Boundary CRANDOR = new Boundary(2813, 2867, 3226, 3307);
public static final Boundary[] IN_F2P = {F2P, TUTORIAL, CRANDOR };
public static final Boundary LUMBRIDGE = new Boundary(3134, 3266, 3131, 3317);
public static final Boundary WIZARDS_TOWER = new Boundary(3094, 3124, 3141, 3172);
public static final Boundary FALADOR = new Boundary(2945, 3066, 3303, 3390);
public static final Boundary VARROCK = new Boundary(3172, 3289, 3368, 3504);
public static final Boundary DRAYNOR = new Boundary(3079, 3149, 3226, 3382);
public static final Boundary BARB = new Boundary(3072, 3098, 3399, 3445);
public static final Boundary GOBLIN_VILLAGE = new Boundary(2945, 2970, 3475, 3515);
public static final Boundary EDGEVILLE = new Boundary(3072, 3126, 3459, 3517);
public static final Boundary PORT_SARIM = new Boundary(3327, 3423, 3131, 3324);
public static final Boundary RIMMINGTON = new Boundary(3327, 3423, 3131, 3324);
public static final Boundary AL_KHARID = new Boundary(3327, 3423, 3131, 3324);
public static final Boundary[] BANK_AREA = new Boundary[] {
new Boundary(3205, 3212, 3217, 3224, 2), //Lumbridge
new Boundary(3264, 3273, 3160, 3174),//Al Kharid
new Boundary(2436, 2453, 5174, 5186),//TzHaa<SUF>
new Boundary(2842, 2860, 2950, 2957),//Shilo
new Boundary(3456, 3492, 3200, 3215),//Burgh d rott
new Boundary(3377, 3386, 3266, 3275),//Duel
new Boundary(3087, 3098, 3239, 3248),//Draynor
new Boundary(3248, 3260, 3414, 3423),//Varrock East
new Boundary(3183, 3193, 3432, 3446),//Varrock West
new Boundary(3088, 3100, 3486, 3501),//Edge
new Boundary(3009, 3020, 3352, 3358),//Fally East
new Boundary(2942, 2950, 3365, 3374),//Fally West
new Boundary(2804, 2815, 3438, 3447),//Catherby
new Boundary(2718, 2733, 3485, 3500),//Seers
new Boundary(2610, 2622, 3326, 3338),//North ardougne
new Boundary(2645, 2660, 3281, 3288),//South ardougne
new Boundary(2607, 2618, 3087, 3098),//Yanille
new Boundary(2442, 2444, 3081, 3084),//Castle Wars
new Boundary(2348, 2358, 3159, 3168),//Lleyta
new Boundary(2324, 2334, 3685, 3694),//Piscatoris
new Boundary(2442, 2448, 3420, 3430),//Tree Gnome Stronghold
new Boundary(2440, 2453, 3478, 3491, 1),//Grand Tree Area
new Boundary(3113, 3131, 3118, 3131),//Tut
new Boundary(2885, 2895, 3422, 3433),//Nardah
new Boundary(3685, 3694, 3461, 3473),//Phasmatys
new Boundary(2530, 2550, 4705, 4725),//Mage Bank
new Boundary(2834, 2841, 10204, 10215),//Keldagrim
new Boundary(2379, 2386, 4453, 4462),//Zanaris
new Boundary(2582, 2591, 3417, 3423),//Fishing Guild
new Boundary(3509, 3515, 3475, 3483),//Canifis
new Boundary(3297, 3311, 3115, 3133),//Shantay Pass
new Boundary(3035, 3049, 4967, 4977, 1),//Rogues Den
};
public static final Boundary ZAMMY_WAIT = new Boundary(2409, 2431, 9511, 9535);
public static final Boundary SARA_WAIT = new Boundary(2368, 2392, 9479, 9498);
public static final Boundary[] MULTI = new Boundary[] {
new Boundary(3136, 3327, 3519, 3607), new Boundary(2360, 2445, 5045, 5125), new Boundary(2256, 2287, 4680, 4711),
new Boundary(3190, 3327, 3648, 3839), new Boundary(3200, 3390, 3840, 3967), new Boundary(2992, 3007, 3912, 3967),
new Boundary(2946, 2959, 3816, 3831), new Boundary(3008, 3199, 3856, 3903), new Boundary(3008, 3071, 3600, 3711),
new Boundary(3072, 3327, 3608, 3647), new Boundary(2624, 2690, 2550, 2619), new Boundary(2667, 2685, 3712, 3730),
new Boundary(2371, 2422, 5062, 5117), new Boundary(2896, 2927, 3595, 3630), new Boundary(2892, 2932, 4435, 4464),
new Boundary(3279, 3307, 3156, 3179)
};
//jungle
public static final Boundary[] KARAMAJA = new Boundary[] {
new Boundary(2745, 3007, 2876, 3095), new Boundary(2747, 2944, 3096, 3131)
};
//jungle
public static final Boundary[] MUSA_POINT = new Boundary[] {
new Boundary(2817, 2917, 3192, 3204), new Boundary(2817, 2961, 3131, 3191)
};
//jungle
public static final Boundary BRIMHAVEN = new Boundary(2688, 2815, 3131, 3258);
//desert
public static final Boundary DESERT = new Boundary(3137, 3517, 2747, 3130, 0);
//desert - no heat
public static final Boundary NARDAH = new Boundary(3392, 3455, 2876, 2940);
public static final Boundary BANDIT_CAMP = new Boundary(3151, 3192, 2963, 2986);
public static final Boundary MINING_CAMP = new Boundary(3267, 3311, 3000, 3043);
public static final Boundary BEDABIN = new Boundary(3160, 3187, 3015, 3046);
public static final Boundary UZER = new Boundary(3462, 3503, 3068, 3109);
public static final Boundary AGILITY_PYRAMID = new Boundary(3329, 3391, 2812, 2855);
public static final Boundary PYRAMID = new Boundary(3217, 3250, 2881, 2908);
public static final Boundary SOPHANEM = new Boundary(3273, 3323, 2749, 2806);
public static final Boundary MENAPHOS = new Boundary(3200, 3266, 2749, 2806);
public static final Boundary POLLIVNEACH = new Boundary(3329, 3377, 2936, 3002);
public static final Boundary SHANTAY_PASS = new Boundary(3295, 3311, 3116, 3128);
public static final Boundary[] NO_HEAT = {NARDAH, BANDIT_CAMP, MINING_CAMP, BEDABIN, UZER, AGILITY_PYRAMID, PYRAMID, SOPHANEM, MENAPHOS, POLLIVNEACH, SHANTAY_PASS};
//mortyania
public static final Boundary MORTYANIA = new Boundary(3401, 3773, 3157, 3577);
//wild
public static final Boundary[] WILDERNESS = new Boundary[] { new Boundary(2941, 3392, 3518, 3966), new Boundary(2941, 3392, 9922, 10366) };
public static final Boundary IN_LESSER = new Boundary(3108, 3112, 3156, 3158, 2);
public static final Boundary IN_DUEL = new Boundary(3331, 3391, 3242, 3260);
public static final Boundary[] IN_DUEL_AREA = new Boundary[] { new Boundary(3322, 3394, 3195, 3291), new Boundary(3311, 3323, 3223, 3248) };
public static final Boundary TRAWLER_GAME = new Boundary (2808, 2811, 3415, 3425);
public static final Boundary PITS_WAIT = new Boundary (2394, 2404, 5169, 5175);
public static final Boundary[] LUMB_BUILDING = new Boundary[] { new Boundary(3205, 3216, 3209, 3228), new Boundary(3229, 3233, 3206, 3208), new Boundary(3228, 3233, 3201, 3205), new Boundary(3230, 3237, 3195, 3198), new Boundary(3238, 3229, 3209, 3211),
new Boundary(3240, 3247, 3204, 3215), new Boundary(3247, 3252, 3190, 3195), new Boundary(3227, 3230, 3212, 3216), new Boundary(3227, 3230, 3221, 3225), new Boundary(3229, 3232, 3236, 3241),
new Boundary(3209, 3213, 3243, 3250), new Boundary(3222, 3229, 3252, 3257), new Boundary(3184, 3192, 3270, 3275), new Boundary(3222, 3224, 3292, 3294), new Boundary(3225, 3230, 3287, 3228),
new Boundary(3243, 3248, 3244, 3248), new Boundary(3202, 3205, 3167, 3170), new Boundary(3231, 3238, 3151, 3155), new Boundary(3233, 3234, 3156, 3156), new Boundary(3163, 3170, 3305, 3308),
new Boundary(3165, 3168, 3303, 3310) };
public static final Boundary[] DRAYNOR_BUILDING = new Boundary[] { new Boundary(3097, 3102, 3277, 3281), new Boundary(3088, 3092, 3273, 3276), new Boundary(3096, 3102, 3266, 3270), new Boundary(3089, 3095, 3265, 3268), new Boundary(3083, 3088, 3256, 3261),
new Boundary(3087, 3094, 3251, 3255), new Boundary(3121, 3130, 3240, 3246), new Boundary(3102, 3112, 3162, 3165), new Boundary(3107, 3111, 3166, 3166), new Boundary(3103, 3115, 3157, 3161),
new Boundary(3105, 3114, 3156, 3156), new Boundary(3105, 3113, 3155, 3155), new Boundary(3106, 3112, 3154, 3154), new Boundary(3092, 3097, 3240, 3246) };
public static final Boundary VARROCK_BANK_BASEMENT = new Boundary(3186, 3197, 9817, 9824, 0);
public static final Boundary MAGE_TOWER_CAGE = new Boundary(3108, 3112, 3156, 3158, 2);
public static final Boundary ARDOUGNE_ZOO = new Boundary(2593, 2639, 3265, 3288);
public static final Boundary APE_ATOLL = new Boundary(2694, 2811, 2691, 2805);
public static final Boundary BARROWS = new Boundary(3543, 3584, 3265, 3311);
public static final Boundary BARROWS_UNDERGROUND = new Boundary(3529, 3581, 9673, 9722);
public static final Boundary PC_BOAT = new Boundary(2660, 2663, 2638, 2643);
public static final Boundary PC_GAME = new Boundary(2624, 2690, 2550, 2619);
public static final Boundary FIGHT_CAVES = new Boundary(2360, 2445, 5045, 5125);
public static final Boundary PIRATE_HOUSE = new Boundary(3038, 3044, 3949, 3959);
public static final Boundary[] FIGHT_PITS = new Boundary[] { new Boundary(2378, 3415, 5133, 5167), new Boundary(2394, 2404, 5169, 5174) };
public static final Boundary PARTY_ROOM = new Boundary(2727, 2746, 3460, 3479);
public static final Boundary PARTY_ROOM_TABLE = new Boundary(2735, 2740, 3467, 3468);
public static final Boundary MAGE_TRAINING_ARENA = new Boundary(3330, 3388, 9614, 9727);
public static final Boundary MAGE_TRAINING_ARENA_ENCHANTING = new Boundary(3341, 3386, 9618, 9662, 0);
public static final Boundary MAGE_TRAINING_ARENA_GRAVEYARD = new Boundary(3340, 3386, 9616, 9662, 1);
public static final Boundary MAGE_TRAINING_ARENA_ALCHEMY = new Boundary(3350, 3379, 9616, 9655, 2);
public static final Boundary MAGE_TRAINING_ARENA_TELEKINETIC = new Boundary(3329, 3390, 9665, 9726);
public static final Boundary[] DWARF_NO_FIREMAKING = new Boundary[] { new Boundary(2944, 3072, 3392, 3456), new Boundary(3008, 3072, 3456, 3520), new Boundary(2880, 2944, 3456, 3520) };
} |
197151_0 | package at.htl.entity;
import javax.persistence.*;
import java.time.LocalDate;
@Entity
public class Auftritt {
//region Fields
@Id
@Column(name = "id", nullable = false)
private Long id;
private String ort;
private int anzahlAnPlattler;
private int verdienst;
private String plattler;
//endregion
//region Constructor
public Auftritt() {
}
public Auftritt(Long id, String ort, int anzahlAnPlattler, int verdienst, String plattler) {
this.id = id;
this.ort = ort;
this.anzahlAnPlattler = anzahlAnPlattler;
this.verdienst = verdienst;
this.plattler = plattler;
}
//endregion
//region Getter and Setter
public String getOrt() {
return ort;
}
public void setOrt(String ort) {
this.ort = ort;
}
public int getAnzahlAnPlattler() {
return anzahlAnPlattler;
}
public void setAnzahlAnPlattler(int anzahlAnPlattler) {
this.anzahlAnPlattler = anzahlAnPlattler;
}
public int getVerdienst() {
return verdienst;
}
public void setVerdienst(int verdienst) {
this.verdienst = verdienst;
}
public String getPlattler() {
return plattler;
}
public void setPlattler(String plattler) {
this.plattler = plattler;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
//endregion
}
| 2122-4ahif-nvs/01-microproject-christophhandel | backend/src/main/java/at/htl/entity/Auftritt.java | 430 | //region Fields | line_comment | nl | package at.htl.entity;
import javax.persistence.*;
import java.time.LocalDate;
@Entity
public class Auftritt {
//regio<SUF>
@Id
@Column(name = "id", nullable = false)
private Long id;
private String ort;
private int anzahlAnPlattler;
private int verdienst;
private String plattler;
//endregion
//region Constructor
public Auftritt() {
}
public Auftritt(Long id, String ort, int anzahlAnPlattler, int verdienst, String plattler) {
this.id = id;
this.ort = ort;
this.anzahlAnPlattler = anzahlAnPlattler;
this.verdienst = verdienst;
this.plattler = plattler;
}
//endregion
//region Getter and Setter
public String getOrt() {
return ort;
}
public void setOrt(String ort) {
this.ort = ort;
}
public int getAnzahlAnPlattler() {
return anzahlAnPlattler;
}
public void setAnzahlAnPlattler(int anzahlAnPlattler) {
this.anzahlAnPlattler = anzahlAnPlattler;
}
public int getVerdienst() {
return verdienst;
}
public void setVerdienst(int verdienst) {
this.verdienst = verdienst;
}
public String getPlattler() {
return plattler;
}
public void setPlattler(String plattler) {
this.plattler = plattler;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
//endregion
}
|
37899_0 | import java.util.ArrayList;
public class Bedrijf {
private ArrayList<Voertuig> voertuigen;
public Bedrijf() {
this.voertuigen = new ArrayList<>();
}
public void add(Voertuig voertuig) {
this.voertuigen.add(voertuig);
}
public double getBelasting() {
double belasting = 0;
for (Voertuig voertuig : voertuigen) {
belasting += voertuig.getBelasting();
}
return belasting;
}
public static void main(String[] args) {
Personenauto w1 = new Personenauto("RET325", "Mercedes", 215, 34000);
Personenauto w2 = new Personenauto("AVF548", "VW", 167, 24000);
Personenauto w3 = new Personenauto("RLN841", "Renault", 104, 18500);
Personenauto w4 = new Personenauto("AFC356", "Renault", 55, 11000);
Personenauto w5 = new Personenauto("DET485", "Renault", 55, 11000);
Vrachtwagen v1 = new Vrachtwagen("YER412", 18.5);
Vrachtwagen v2 = new Vrachtwagen("GTZ652", 8);
Bedrijf b = new Bedrijf();
b.add(w1);
b.add(w2);
b.add(w3);
b.add(w4);
b.add(w5);
b.add(v1);
b.add(v2);
// Op 2 cijfers na de komma afronden met de statische methode format van de klasse String
// %.2f betekent de double b.getBelasting() die volgt na de tekst afronden op 2 cijfers
System.out.printf(String.format ("Totale belasting: %.2f",b.getBelasting()));
}
}
| 22-avo-programmeren-thomasmore/oop-bedrijf | src/Bedrijf.java | 500 | // Op 2 cijfers na de komma afronden met de statische methode format van de klasse String | line_comment | nl | import java.util.ArrayList;
public class Bedrijf {
private ArrayList<Voertuig> voertuigen;
public Bedrijf() {
this.voertuigen = new ArrayList<>();
}
public void add(Voertuig voertuig) {
this.voertuigen.add(voertuig);
}
public double getBelasting() {
double belasting = 0;
for (Voertuig voertuig : voertuigen) {
belasting += voertuig.getBelasting();
}
return belasting;
}
public static void main(String[] args) {
Personenauto w1 = new Personenauto("RET325", "Mercedes", 215, 34000);
Personenauto w2 = new Personenauto("AVF548", "VW", 167, 24000);
Personenauto w3 = new Personenauto("RLN841", "Renault", 104, 18500);
Personenauto w4 = new Personenauto("AFC356", "Renault", 55, 11000);
Personenauto w5 = new Personenauto("DET485", "Renault", 55, 11000);
Vrachtwagen v1 = new Vrachtwagen("YER412", 18.5);
Vrachtwagen v2 = new Vrachtwagen("GTZ652", 8);
Bedrijf b = new Bedrijf();
b.add(w1);
b.add(w2);
b.add(w3);
b.add(w4);
b.add(w5);
b.add(v1);
b.add(v2);
// Op 2 <SUF>
// %.2f betekent de double b.getBelasting() die volgt na de tekst afronden op 2 cijfers
System.out.printf(String.format ("Totale belasting: %.2f",b.getBelasting()));
}
}
|
12293_3 | package be.thomasmore.screeninfo.model;
import java.sql.Date;
import java.time.LocalDate;
import java.time.ZoneId;
public class FestivalItem {
public Integer id;
private String festivalName;
private String festivalImage;
private String backgroundColor;
private String date;
private String festivalLink;
private boolean onGoing; // om manueel te zeggen dat een event bezig is
private String busyness; // om op voorant te berekenen hoe druk he is
// voor positie op map
private float mapLat;
private float mapLng;
private String festivalType;
private Integer maxCapacity;
public FestivalItem(Festival festival){
id = festival.getId();
festivalName = festival.getFestivalName();
festivalImage = festival.getFestivalImage();
backgroundColor = festival.getBackgroundColor();
festivalLink = festival.getFestivalLink();
mapLat = festival.getMapLat();
mapLng = festival.getMapLng();
festivalType = festival.getFestivalType();
maxCapacity = festival.getMaxCapacity();
onGoing = Date.from(java.time.LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()).after(festival.getStartDate());
// voor nu debuggen
date = "";
LocalDate startDate = festival.getStartDate().toLocalDate();
LocalDate endDate = festival.getEndDate().toLocalDate();
if(startDate.getYear() != endDate.getYear()){
date = startDate.getDayOfMonth()+"-"+ startDate.getMonthValue()+"-"+startDate.getYear() + " / ";
}
else if(startDate.getMonth() != endDate.getMonth()){
date = startDate.getDayOfMonth()+"-"+ startDate.getMonthValue() + " / ";
}
else if(startDate.getDayOfMonth() != endDate.getDayOfMonth()){
date = startDate.getDayOfMonth() + " / ";
}
date += endDate.getDayOfMonth()+"-"+endDate.getMonthValue()+"-"+endDate.getYear();
int maxCapacity = festival.getMaxCapacity();
int population = festival.getPopulation();
if(maxCapacity < population){
busyness = "FULL";
}
else if(maxCapacity * 0.75 < population){
busyness = "BUSY";
}
else if(maxCapacity * 0.5 < population){
busyness = "MEDIUM BUSY";
}
else if(maxCapacity * 0.25 < population){
busyness = "CALM";
}
else {
busyness = "EMPTY";
}
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFestivalName() {
return festivalName;
}
public void setFestivalName(String festivalName) {
this.festivalName = festivalName;
}
public String getFestivalImage() {
return festivalImage;
}
public void setFestivalImage(String festivalImage) {
this.festivalImage = festivalImage;
}
public String getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setFestivalLink(String festivalLink) {
this.festivalLink = festivalLink;
}
public String getFestivalLink() {
return festivalLink;
}
public void setOnGoing(boolean onGoing) {
this.onGoing = onGoing;
}
public boolean isOnGoing() {
return onGoing;
}
public String getBusyness() {
return busyness;
}
public void setBusyness(String busyness) {
this.busyness = busyness;
}
public void setMapLat(float mapLat) {
this.mapLat = mapLat;
}
public void setMapLng(float mapLng) {
this.mapLng = mapLng;
}
public float getMapLat() {
return mapLat;
}
public float getMapLng() {
return mapLng;
}
public String getFestivalType() {
return festivalType;
}
public void setFestivalType(String festivalType) {
this.festivalType = festivalType;
}
public Integer getMaxCapacity() {
return maxCapacity;
}
public void setMaxCapacity(Integer maxCapacity) {
this.maxCapacity = maxCapacity;
}
}
| 22-project-programmeren-thomasmore/MechelenFeest | src/main/java/be/thomasmore/screeninfo/model/FestivalItem.java | 1,105 | // voor nu debuggen | line_comment | nl | package be.thomasmore.screeninfo.model;
import java.sql.Date;
import java.time.LocalDate;
import java.time.ZoneId;
public class FestivalItem {
public Integer id;
private String festivalName;
private String festivalImage;
private String backgroundColor;
private String date;
private String festivalLink;
private boolean onGoing; // om manueel te zeggen dat een event bezig is
private String busyness; // om op voorant te berekenen hoe druk he is
// voor positie op map
private float mapLat;
private float mapLng;
private String festivalType;
private Integer maxCapacity;
public FestivalItem(Festival festival){
id = festival.getId();
festivalName = festival.getFestivalName();
festivalImage = festival.getFestivalImage();
backgroundColor = festival.getBackgroundColor();
festivalLink = festival.getFestivalLink();
mapLat = festival.getMapLat();
mapLng = festival.getMapLng();
festivalType = festival.getFestivalType();
maxCapacity = festival.getMaxCapacity();
onGoing = Date.from(java.time.LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()).after(festival.getStartDate());
// voor <SUF>
date = "";
LocalDate startDate = festival.getStartDate().toLocalDate();
LocalDate endDate = festival.getEndDate().toLocalDate();
if(startDate.getYear() != endDate.getYear()){
date = startDate.getDayOfMonth()+"-"+ startDate.getMonthValue()+"-"+startDate.getYear() + " / ";
}
else if(startDate.getMonth() != endDate.getMonth()){
date = startDate.getDayOfMonth()+"-"+ startDate.getMonthValue() + " / ";
}
else if(startDate.getDayOfMonth() != endDate.getDayOfMonth()){
date = startDate.getDayOfMonth() + " / ";
}
date += endDate.getDayOfMonth()+"-"+endDate.getMonthValue()+"-"+endDate.getYear();
int maxCapacity = festival.getMaxCapacity();
int population = festival.getPopulation();
if(maxCapacity < population){
busyness = "FULL";
}
else if(maxCapacity * 0.75 < population){
busyness = "BUSY";
}
else if(maxCapacity * 0.5 < population){
busyness = "MEDIUM BUSY";
}
else if(maxCapacity * 0.25 < population){
busyness = "CALM";
}
else {
busyness = "EMPTY";
}
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFestivalName() {
return festivalName;
}
public void setFestivalName(String festivalName) {
this.festivalName = festivalName;
}
public String getFestivalImage() {
return festivalImage;
}
public void setFestivalImage(String festivalImage) {
this.festivalImage = festivalImage;
}
public String getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setFestivalLink(String festivalLink) {
this.festivalLink = festivalLink;
}
public String getFestivalLink() {
return festivalLink;
}
public void setOnGoing(boolean onGoing) {
this.onGoing = onGoing;
}
public boolean isOnGoing() {
return onGoing;
}
public String getBusyness() {
return busyness;
}
public void setBusyness(String busyness) {
this.busyness = busyness;
}
public void setMapLat(float mapLat) {
this.mapLat = mapLat;
}
public void setMapLng(float mapLng) {
this.mapLng = mapLng;
}
public float getMapLat() {
return mapLat;
}
public float getMapLng() {
return mapLng;
}
public String getFestivalType() {
return festivalType;
}
public void setFestivalType(String festivalType) {
this.festivalType = festivalType;
}
public Integer getMaxCapacity() {
return maxCapacity;
}
public void setMaxCapacity(Integer maxCapacity) {
this.maxCapacity = maxCapacity;
}
}
|
18917_0 | package be.thomasmore.qrace.model;
// de mascottes zijn de verschillende characters binnen QRace
public class Mascot {
private String name;
private String description;
public Mascot(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} | 22-project-programmeren-thomasmore/QRace | src/main/java/be/thomasmore/qrace/model/Mascot.java | 147 | // de mascottes zijn de verschillende characters binnen QRace | line_comment | nl | package be.thomasmore.qrace.model;
// de ma<SUF>
public class Mascot {
private String name;
private String description;
public Mascot(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} |
70177_11 | package frc.robot.subsystems.climber;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import edu.wpi.first.math.MathUtil;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableEntry;
import edu.wpi.first.networktables.NetworkTableInstance;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.Constants.CAN;
import frc.robot.Constants.ClimbSettings;
public class Climber extends SubsystemBase {
// NTs
private NetworkTable table;
private NetworkTableEntry nte_sync_arms;
// command fixes
boolean outerLoopEnabled = false; // use sw position pids to control velocity
// Compensation "syncArms"
boolean syncArmsEnabled; // when true uses differential pos err to compensate
PIDController extCompPID = new PIDController(2.0, 0, 0); // input [in], output [in/s] Kp=[(in/s)/in-err]
PIDController rotCompPID = new PIDController(1.00, 0, 0); // input [deg], output [deg/s] Kp=[(deg/s)/deg-err]
double rot_compensation = 0.0; // [deg/s] from rotCompPID
double ext_compensation = 0.0; // [in/s] from extCompPID
// postion goals - software outer loops for position
PIDController rotPosL = new PIDController(5.0, 0.0, 0.0); // in degs-err out: vel deg/s
PIDController rotPosR = new PIDController(5.0, 0.0, 0.0); // in degs-err out: vel deg/s
PIDController extPosL = new PIDController(8.0, 0.0, 0.0); // in inch-err out vel in/s
PIDController extPosR = new PIDController(8.0, 0.0, 0.0); // in inch-err out vel in/s
private CANSparkMax left_motor_rot = new CANSparkMax(CAN.CMB_LEFT_Rotate, MotorType.kBrushless);
private CANSparkMax right_motor_rot = new CANSparkMax(CAN.CMB_RIGHT_Rotate, MotorType.kBrushless);
private CANSparkMax left_motor_ext = new CANSparkMax(CAN.CMB_LEFT_Extend, MotorType.kBrushless);
private CANSparkMax right_motor_ext = new CANSparkMax(CAN.CMB_RIGHT_Extend, MotorType.kBrushless);
private ArmExtension left_Arm_ext;
private ArmExtension right_Arm_ext;
private ArmRotation left_Arm_rot;
private ArmRotation right_Arm_rot;
public Climber() {
table = NetworkTableInstance.getDefault().getTable("Climber");
nte_sync_arms = table.getEntry("syncArms");
nte_sync_arms.setBoolean(syncArmsEnabled);
// 550 NEO
left_Arm_rot = new ArmRotation(table.getSubTable("left_arm_rotation"), left_motor_rot, true, 0.20);
right_Arm_rot = new ArmRotation(table.getSubTable("right_arm_rotation"), right_motor_rot, false, 0.20);
right_Arm_ext = new ArmExtension(table.getSubTable("right_arm_extension"), right_motor_ext, false);
left_Arm_ext = new ArmExtension(table.getSubTable("left_arm_extension"), left_motor_ext, true);
//Outer loop position tolerance
rotPosL.setTolerance(ClimbSettings.TOLERANCE_ROT, ClimbSettings.TOLERANCE_ROT_RATE);
rotPosR.setTolerance(ClimbSettings.TOLERANCE_ROT, ClimbSettings.TOLERANCE_ROT_RATE);
extPosL.setTolerance(ClimbSettings.TOLERANCE_EXT, ClimbSettings.TOLERANCE_EXT_VEL);
extPosR.setTolerance(ClimbSettings.TOLERANCE_EXT, ClimbSettings.TOLERANCE_EXT_VEL);
//Set min/max integrator range on outerloop position PID (default is 1.0 otherwise)
rotPosL.setIntegratorRange(ClimbSettings.ROT_INTEGRATOR_MIN, ClimbSettings.ROT_INTEGRATOR_MIN);
rotPosR.setIntegratorRange(ClimbSettings.ROT_INTEGRATOR_MIN, ClimbSettings.ROT_INTEGRATOR_MIN);
setArmSync(false);
setOuterLoop(false);
setStartingPos();
// finish hardware limits
setAmperageExtLimit(ClimbSettings.MAX_EXT_AMPS);
setAmperageRotLimit(ClimbSettings.MAX_ROT_AMPS);
}
public void setStartingPos() {
//reset hardware pid
left_Arm_rot.resetPID();
right_Arm_rot.resetPID();
// approx centered
left_Arm_ext.setEncoderPos(0.0);
right_Arm_ext.setEncoderPos(0.0);
// arms vertical
left_Arm_rot.setEncoderPos(0.0);
if (Math.abs(left_Arm_rot.getRotationDegrees()) > 0.0001) {
//System.out.println("warning -->" + left_Arm_rot.getRotationDegrees() +
// " left rot pos not zero!!!!!!!!");
left_Arm_rot.setEncoderPos(0.0);
}
right_Arm_rot.setEncoderPos(0.0);
if (Math.abs(right_Arm_rot.getRotationDegrees()) > 0.0001) {
//System.out.println("warning -->" + right_Arm_rot.getRotationDegrees() +
//" right rot pos not zero!!!!!!!!");
right_Arm_rot.setEncoderPos(0.0);
}
//compensation loop
extCompPID.reset();
rotCompPID.reset();
//clear all position pids
extPosL.reset();
extPosR.reset();
rotPosL.reset();
rotPosR.reset();
// setpoints for sw outer loop
setExtension(0.0);
setRotation(0.0);
}
public boolean readyToClimb() {
// returns if robot is in the right position, and all motors are in place
return false;
}
public String rung() {
return "blank";
}
public boolean readyToTraverse() {
return false;
}
// @param inches from extender absolute position
public void setExtension(double inches) {
extPosL.setSetpoint(inches);
extPosR.setSetpoint(inches);
}
public void setRotation(double rotationDegrees) {
rotPosL.setSetpoint(rotationDegrees);
rotPosR.setSetpoint(rotationDegrees);
}
/**
*
* @param ext_spd [in/s]
*/
public void setExtSpeed(double ext_spd) {
setExtSpeed(ext_spd, ext_spd);
}
public void setExtSpeed(double ext_spdlt, double ext_spdrt) {
//split the sync comp and remove/add a bit
double comp = (syncArmsEnabled) ? ext_compensation/2.0 : 0.0;
left_Arm_ext.setSpeed(ext_spdlt - comp);
right_Arm_ext.setSpeed(ext_spdrt + comp);
}
/**
*
* @param rot_spd [deg/s]
*/
public void setRotSpeed(double rot_spd) {
setRotSpeed(rot_spd, rot_spd);
}
public void setRotSpeed(double rot_spd_lt, double rot_spd_rt) {
double comp = (syncArmsEnabled) ? rot_compensation/2.0 : 0.0;
left_Arm_rot.setRotRate(rot_spd_lt - comp);
right_Arm_rot.setRotRate(rot_spd_rt + comp);
}
public void setArmSync(boolean sync) {
syncArmsEnabled = sync;
nte_sync_arms.setBoolean(syncArmsEnabled);
}
public void hold() {
//hardware stop
setExtSpeed(0.0);
setRotSpeed(0.0);
//clear sw pid states
extPosR.reset();
extPosL.reset();
rotPosL.reset();
rotPosR.reset();
//command where we are, update setpoints with current position
extPosL.setSetpoint(left_Arm_ext.getInches());
extPosR.setSetpoint(right_Arm_ext.getInches());
rotPosL.setSetpoint(left_Arm_rot.getRotationDegrees());
rotPosR.setSetpoint(right_Arm_rot.getRotationDegrees());
//outerloop & syncArms as controled by command
}
@Override
public void periodic() {
// control left with PIDs, rt will follow
double ext_velL = extPosL.calculate(getLeftExtInches());
double rot_velL = rotPosL.calculate(getLeftRotation());
double ext_velR = extPosR.calculate(getRightExtInches());
double rot_velR = rotPosR.calculate(getRightRotation());
ext_velL = MathUtil.clamp(ext_velL, -ClimbSettings.MAX_VELOCITY_EXT, ClimbSettings.MAX_VELOCITY_EXT);
rot_velL = MathUtil.clamp(rot_velL, -ClimbSettings.MAX_VELOCITY_ROT, ClimbSettings.MAX_VELOCITY_ROT);
ext_velR = MathUtil.clamp(ext_velR, -ClimbSettings.MAX_VELOCITY_EXT, ClimbSettings.MAX_VELOCITY_EXT);
rot_velR = MathUtil.clamp(rot_velR, -ClimbSettings.MAX_VELOCITY_ROT, ClimbSettings.MAX_VELOCITY_ROT);
//c
ext_compensation = 0.0;
rot_compensation = 0.0;
if (syncArmsEnabled) {
extCompPID.setSetpoint(getLeftExtInches());
rotCompPID.setSetpoint(getLeftRotation());
ext_compensation = extCompPID.calculate(getRightExtInches());
rot_compensation = rotCompPID.calculate(getRightRotation());
}
// output new speed settings
if (outerLoopEnabled) {
setExtSpeed(ext_velL, ext_velR);
setRotSpeed(rot_velL, rot_velR);
}
left_Arm_ext.periodic();
right_Arm_ext.periodic();
left_Arm_rot.periodic();
right_Arm_rot.periodic();
}
public double getLeftExtInches() {
return left_Arm_ext.getInches();
}
public double getRightExtInches() {
return right_Arm_ext.getInches();
}
public double getLeftRotation() {
return left_Arm_rot.getRotationDegrees();
}
public double getRightRotation() {
return right_Arm_rot.getRotationDegrees();
}
public void setAmperageExtLimit(int limit) {
right_motor_ext.setSmartCurrentLimit(limit);
left_motor_ext.setSmartCurrentLimit(limit);
}
public void setAmperageRotLimit(int limit) {
// brushless only
//right_motor_rot.setSmartCurrentLimit(limit);
//left_motor_rot.setSmartCurrentLimit(limit);
// brushed
right_motor_rot.setSecondaryCurrentLimit(limit);
left_motor_rot.setSecondaryCurrentLimit(limit);
}
public void setOuterLoop(boolean enable) {
outerLoopEnabled = enable;
}
/**
* outerLoopDone checks for rotation,extension, and combined when using
* the software pids for positon control.
* @return
*/
public boolean outerLoopExtDone() {
return extPosL.atSetpoint() && extPosR.atSetpoint();
}
public boolean outerLoopRotDone() {
return rotPosL.atSetpoint() && rotPosR.atSetpoint();
}
public boolean outerLoopDone() {
return outerLoopExtDone() && outerLoopRotDone();
}
/**
* Note - this doesn't check the velocity of the actuatorators.
* Consider using the outerLoop softare pid tests.
*
* @param ext_pos target extension
* @param rot_pos target rotation
* @return
*/
public boolean checkIsFinished(double ext_pos, double rot_pos) {
boolean extDone = (Math.abs(this.getLeftExtInches() - ext_pos) <= ClimbSettings.TOLERANCE_EXT)
&& (Math.abs(this.getRightExtInches() - ext_pos) <= ClimbSettings.TOLERANCE_EXT);
boolean rotDone =
(Math.abs(this.getLeftRotation() - rot_pos) <= Constants.ClimbSettings.TOLERANCE_ROT)
&& (Math.abs(this.getRightRotation() - rot_pos) <= Constants.ClimbSettings.TOLERANCE_ROT);
return (extDone && rotDone);
}
/**
* accessors for rotation and extension objects - used for testing
*
* @return
*/
public ArmRotation getLeftArmRotation() {
return left_Arm_rot;
}
public ArmRotation getRightArmRotation() {
return right_Arm_rot;
}
public ArmExtension getLeftArmExtension() {
return left_Arm_ext;
}
public ArmExtension getRightArmExtension() {
return right_Arm_ext;
}
@Deprecated
public void setPercentOutputRot(double pct_l, double pct_r) {
left_Arm_rot.setPercentOutput(pct_l);
right_Arm_rot.setPercentOutput(pct_r);
}
} | 2202Programming/FRC2022 | src/main/java/frc/robot/subsystems/climber/Climber.java | 3,485 | // in inch-err out vel in/s | line_comment | nl | package frc.robot.subsystems.climber;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import edu.wpi.first.math.MathUtil;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableEntry;
import edu.wpi.first.networktables.NetworkTableInstance;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.Constants.CAN;
import frc.robot.Constants.ClimbSettings;
public class Climber extends SubsystemBase {
// NTs
private NetworkTable table;
private NetworkTableEntry nte_sync_arms;
// command fixes
boolean outerLoopEnabled = false; // use sw position pids to control velocity
// Compensation "syncArms"
boolean syncArmsEnabled; // when true uses differential pos err to compensate
PIDController extCompPID = new PIDController(2.0, 0, 0); // input [in], output [in/s] Kp=[(in/s)/in-err]
PIDController rotCompPID = new PIDController(1.00, 0, 0); // input [deg], output [deg/s] Kp=[(deg/s)/deg-err]
double rot_compensation = 0.0; // [deg/s] from rotCompPID
double ext_compensation = 0.0; // [in/s] from extCompPID
// postion goals - software outer loops for position
PIDController rotPosL = new PIDController(5.0, 0.0, 0.0); // in degs-err out: vel deg/s
PIDController rotPosR = new PIDController(5.0, 0.0, 0.0); // in degs-err out: vel deg/s
PIDController extPosL = new PIDController(8.0, 0.0, 0.0); // in in<SUF>
PIDController extPosR = new PIDController(8.0, 0.0, 0.0); // in inch-err out vel in/s
private CANSparkMax left_motor_rot = new CANSparkMax(CAN.CMB_LEFT_Rotate, MotorType.kBrushless);
private CANSparkMax right_motor_rot = new CANSparkMax(CAN.CMB_RIGHT_Rotate, MotorType.kBrushless);
private CANSparkMax left_motor_ext = new CANSparkMax(CAN.CMB_LEFT_Extend, MotorType.kBrushless);
private CANSparkMax right_motor_ext = new CANSparkMax(CAN.CMB_RIGHT_Extend, MotorType.kBrushless);
private ArmExtension left_Arm_ext;
private ArmExtension right_Arm_ext;
private ArmRotation left_Arm_rot;
private ArmRotation right_Arm_rot;
public Climber() {
table = NetworkTableInstance.getDefault().getTable("Climber");
nte_sync_arms = table.getEntry("syncArms");
nte_sync_arms.setBoolean(syncArmsEnabled);
// 550 NEO
left_Arm_rot = new ArmRotation(table.getSubTable("left_arm_rotation"), left_motor_rot, true, 0.20);
right_Arm_rot = new ArmRotation(table.getSubTable("right_arm_rotation"), right_motor_rot, false, 0.20);
right_Arm_ext = new ArmExtension(table.getSubTable("right_arm_extension"), right_motor_ext, false);
left_Arm_ext = new ArmExtension(table.getSubTable("left_arm_extension"), left_motor_ext, true);
//Outer loop position tolerance
rotPosL.setTolerance(ClimbSettings.TOLERANCE_ROT, ClimbSettings.TOLERANCE_ROT_RATE);
rotPosR.setTolerance(ClimbSettings.TOLERANCE_ROT, ClimbSettings.TOLERANCE_ROT_RATE);
extPosL.setTolerance(ClimbSettings.TOLERANCE_EXT, ClimbSettings.TOLERANCE_EXT_VEL);
extPosR.setTolerance(ClimbSettings.TOLERANCE_EXT, ClimbSettings.TOLERANCE_EXT_VEL);
//Set min/max integrator range on outerloop position PID (default is 1.0 otherwise)
rotPosL.setIntegratorRange(ClimbSettings.ROT_INTEGRATOR_MIN, ClimbSettings.ROT_INTEGRATOR_MIN);
rotPosR.setIntegratorRange(ClimbSettings.ROT_INTEGRATOR_MIN, ClimbSettings.ROT_INTEGRATOR_MIN);
setArmSync(false);
setOuterLoop(false);
setStartingPos();
// finish hardware limits
setAmperageExtLimit(ClimbSettings.MAX_EXT_AMPS);
setAmperageRotLimit(ClimbSettings.MAX_ROT_AMPS);
}
public void setStartingPos() {
//reset hardware pid
left_Arm_rot.resetPID();
right_Arm_rot.resetPID();
// approx centered
left_Arm_ext.setEncoderPos(0.0);
right_Arm_ext.setEncoderPos(0.0);
// arms vertical
left_Arm_rot.setEncoderPos(0.0);
if (Math.abs(left_Arm_rot.getRotationDegrees()) > 0.0001) {
//System.out.println("warning -->" + left_Arm_rot.getRotationDegrees() +
// " left rot pos not zero!!!!!!!!");
left_Arm_rot.setEncoderPos(0.0);
}
right_Arm_rot.setEncoderPos(0.0);
if (Math.abs(right_Arm_rot.getRotationDegrees()) > 0.0001) {
//System.out.println("warning -->" + right_Arm_rot.getRotationDegrees() +
//" right rot pos not zero!!!!!!!!");
right_Arm_rot.setEncoderPos(0.0);
}
//compensation loop
extCompPID.reset();
rotCompPID.reset();
//clear all position pids
extPosL.reset();
extPosR.reset();
rotPosL.reset();
rotPosR.reset();
// setpoints for sw outer loop
setExtension(0.0);
setRotation(0.0);
}
public boolean readyToClimb() {
// returns if robot is in the right position, and all motors are in place
return false;
}
public String rung() {
return "blank";
}
public boolean readyToTraverse() {
return false;
}
// @param inches from extender absolute position
public void setExtension(double inches) {
extPosL.setSetpoint(inches);
extPosR.setSetpoint(inches);
}
public void setRotation(double rotationDegrees) {
rotPosL.setSetpoint(rotationDegrees);
rotPosR.setSetpoint(rotationDegrees);
}
/**
*
* @param ext_spd [in/s]
*/
public void setExtSpeed(double ext_spd) {
setExtSpeed(ext_spd, ext_spd);
}
public void setExtSpeed(double ext_spdlt, double ext_spdrt) {
//split the sync comp and remove/add a bit
double comp = (syncArmsEnabled) ? ext_compensation/2.0 : 0.0;
left_Arm_ext.setSpeed(ext_spdlt - comp);
right_Arm_ext.setSpeed(ext_spdrt + comp);
}
/**
*
* @param rot_spd [deg/s]
*/
public void setRotSpeed(double rot_spd) {
setRotSpeed(rot_spd, rot_spd);
}
public void setRotSpeed(double rot_spd_lt, double rot_spd_rt) {
double comp = (syncArmsEnabled) ? rot_compensation/2.0 : 0.0;
left_Arm_rot.setRotRate(rot_spd_lt - comp);
right_Arm_rot.setRotRate(rot_spd_rt + comp);
}
public void setArmSync(boolean sync) {
syncArmsEnabled = sync;
nte_sync_arms.setBoolean(syncArmsEnabled);
}
public void hold() {
//hardware stop
setExtSpeed(0.0);
setRotSpeed(0.0);
//clear sw pid states
extPosR.reset();
extPosL.reset();
rotPosL.reset();
rotPosR.reset();
//command where we are, update setpoints with current position
extPosL.setSetpoint(left_Arm_ext.getInches());
extPosR.setSetpoint(right_Arm_ext.getInches());
rotPosL.setSetpoint(left_Arm_rot.getRotationDegrees());
rotPosR.setSetpoint(right_Arm_rot.getRotationDegrees());
//outerloop & syncArms as controled by command
}
@Override
public void periodic() {
// control left with PIDs, rt will follow
double ext_velL = extPosL.calculate(getLeftExtInches());
double rot_velL = rotPosL.calculate(getLeftRotation());
double ext_velR = extPosR.calculate(getRightExtInches());
double rot_velR = rotPosR.calculate(getRightRotation());
ext_velL = MathUtil.clamp(ext_velL, -ClimbSettings.MAX_VELOCITY_EXT, ClimbSettings.MAX_VELOCITY_EXT);
rot_velL = MathUtil.clamp(rot_velL, -ClimbSettings.MAX_VELOCITY_ROT, ClimbSettings.MAX_VELOCITY_ROT);
ext_velR = MathUtil.clamp(ext_velR, -ClimbSettings.MAX_VELOCITY_EXT, ClimbSettings.MAX_VELOCITY_EXT);
rot_velR = MathUtil.clamp(rot_velR, -ClimbSettings.MAX_VELOCITY_ROT, ClimbSettings.MAX_VELOCITY_ROT);
//c
ext_compensation = 0.0;
rot_compensation = 0.0;
if (syncArmsEnabled) {
extCompPID.setSetpoint(getLeftExtInches());
rotCompPID.setSetpoint(getLeftRotation());
ext_compensation = extCompPID.calculate(getRightExtInches());
rot_compensation = rotCompPID.calculate(getRightRotation());
}
// output new speed settings
if (outerLoopEnabled) {
setExtSpeed(ext_velL, ext_velR);
setRotSpeed(rot_velL, rot_velR);
}
left_Arm_ext.periodic();
right_Arm_ext.periodic();
left_Arm_rot.periodic();
right_Arm_rot.periodic();
}
public double getLeftExtInches() {
return left_Arm_ext.getInches();
}
public double getRightExtInches() {
return right_Arm_ext.getInches();
}
public double getLeftRotation() {
return left_Arm_rot.getRotationDegrees();
}
public double getRightRotation() {
return right_Arm_rot.getRotationDegrees();
}
public void setAmperageExtLimit(int limit) {
right_motor_ext.setSmartCurrentLimit(limit);
left_motor_ext.setSmartCurrentLimit(limit);
}
public void setAmperageRotLimit(int limit) {
// brushless only
//right_motor_rot.setSmartCurrentLimit(limit);
//left_motor_rot.setSmartCurrentLimit(limit);
// brushed
right_motor_rot.setSecondaryCurrentLimit(limit);
left_motor_rot.setSecondaryCurrentLimit(limit);
}
public void setOuterLoop(boolean enable) {
outerLoopEnabled = enable;
}
/**
* outerLoopDone checks for rotation,extension, and combined when using
* the software pids for positon control.
* @return
*/
public boolean outerLoopExtDone() {
return extPosL.atSetpoint() && extPosR.atSetpoint();
}
public boolean outerLoopRotDone() {
return rotPosL.atSetpoint() && rotPosR.atSetpoint();
}
public boolean outerLoopDone() {
return outerLoopExtDone() && outerLoopRotDone();
}
/**
* Note - this doesn't check the velocity of the actuatorators.
* Consider using the outerLoop softare pid tests.
*
* @param ext_pos target extension
* @param rot_pos target rotation
* @return
*/
public boolean checkIsFinished(double ext_pos, double rot_pos) {
boolean extDone = (Math.abs(this.getLeftExtInches() - ext_pos) <= ClimbSettings.TOLERANCE_EXT)
&& (Math.abs(this.getRightExtInches() - ext_pos) <= ClimbSettings.TOLERANCE_EXT);
boolean rotDone =
(Math.abs(this.getLeftRotation() - rot_pos) <= Constants.ClimbSettings.TOLERANCE_ROT)
&& (Math.abs(this.getRightRotation() - rot_pos) <= Constants.ClimbSettings.TOLERANCE_ROT);
return (extDone && rotDone);
}
/**
* accessors for rotation and extension objects - used for testing
*
* @return
*/
public ArmRotation getLeftArmRotation() {
return left_Arm_rot;
}
public ArmRotation getRightArmRotation() {
return right_Arm_rot;
}
public ArmExtension getLeftArmExtension() {
return left_Arm_ext;
}
public ArmExtension getRightArmExtension() {
return right_Arm_ext;
}
@Deprecated
public void setPercentOutputRot(double pct_l, double pct_r) {
left_Arm_rot.setPercentOutput(pct_l);
right_Arm_rot.setPercentOutput(pct_r);
}
} |
132832_0 | package Shipflex;
import Boat.Boat;
import Boat.Option;
import Customer.CustomCustomer;
import Customer.BusinessCustomer;
import Customer.FoundationCustomer;
import Customer.GovermentCustomer;
import DataInOut.Info;
import DataInOut.Printer;
import java.util.ArrayList;
import java.util.List;
public class Quote {
private Company companyShipbuild;
private CustomCustomer customCustomer;
private BusinessCustomer businessCustomer;
private GovermentCustomer govermentCustomer;
private FoundationCustomer foundationCustomer;
private String date;
private String quoteDate;
private String about;
private double workHoursCost;
private Boat boat;
public Quote(Company companyShipbuild, Boat boat) {
this.companyShipbuild = companyShipbuild;
this.businessCustomer = null;
this.customCustomer = null;
this.govermentCustomer = null;
this.foundationCustomer = null;
this.boat = boat;
}
public void setCustomCustomer(CustomCustomer customCustomer) {
this.customCustomer = customCustomer;
}
public void setBusinessCustomer(BusinessCustomer businessCustomer) {
this.businessCustomer = businessCustomer;
}
public void setGovermentCustomer(GovermentCustomer govermentCustomer) {
this.govermentCustomer = govermentCustomer;
}
public void setFoundationCustomer(FoundationCustomer foundationCustomer) {
this.foundationCustomer = foundationCustomer;
}
public void setAbout(String about) {
this.about = about;
}
public void setDate(String date) {
this.date = date;
}
public void setQuoteDate(String quoteDate) {
this.quoteDate = quoteDate;
}
public void setBoat(Boat boat) {
this.boat = boat;
}
public Boat getBoat() {
return boat;
}
public CustomCustomer getCustomCustomer() {
return customCustomer;
}
public BusinessCustomer getBusinessCustomer() {
return businessCustomer;
}
public GovermentCustomer getGovermentCustomer() {
return govermentCustomer;
}
public FoundationCustomer getFoundationCustomer() {
return foundationCustomer;
}
public void setWorkHoursCost(double workHoursCost) {
this.workHoursCost = workHoursCost;
}
public void printCustomer() {
switch (checkCustomerType()) {
case "goverment":
govermentCustomer.printCustomer();
break;
case "business":
businessCustomer.printCustomer();
break;
case "foundation":
foundationCustomer.printCustomer();
break;
case "customer":
customCustomer.printCustomer();
break;
default:
Printer.getInstance().printLine("Nog geen klant toegevoegd");
break;
}
}
private String checkCustomerType() {
if (govermentCustomer != null) {
return "goverment";
} else if (businessCustomer != null) {
return "business";
} else if (customCustomer != null) {
return "customer";
} else if (foundationCustomer != null) {
return "foundation";
} else {
return "";
}
}
public void printOptions(boolean showIndex) {
for (Option option : this.boat.getOptions()) {
if (showIndex)
Info.printOptionInfo(option, Info.getOptions().indexOf(option));
else
Info.printOptionInfo(option, -1);
Printer.getInstance().emptyLine();
}
}
public void printDate() {
if (this.date != null && !this.date.equals("")) {
Printer.getInstance().printLine("Datum: " + this.date);
} else {
Printer.getInstance().printLine("Datum nog niet ingevuld");
}
if (this.quoteDate != null && !this.quoteDate.equals("")) {
Printer.getInstance().printLine("Geldigsheid datum: " + this.quoteDate);
} else {
Printer.getInstance().printLine("Geldigsheid datum nog niet ingevuld");
}
}
public void printBasicInformation() {
companyShipbuild.printCompany();
Printer.getInstance().emptyLine();
printCustomer();
Printer.getInstance().emptyLine();
printDate();
Printer.getInstance().emptyLine();
if(this.about != null && !this.about.equals("")) {
Printer.getInstance().printLine("Betreft: " + this.about);
}else {
Printer.getInstance().printLine("Betreft is nog niet ingevuld");
}
Printer.getInstance().emptyLine();
}
public void printQuote() {
Printer.getInstance().printCharacters(129, '━');
Printer.getInstance().emptyLine();
this.printBasicInformation();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
boat.printBoat();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
this.printOptions();
Printer.getInstance().emptyLine();
this.printTotal();
Printer.getInstance().emptyLine();
Printer.getInstance().printCharacters(129, '━');
}
public void printOptions() {
List<Option> essentialOptions = new ArrayList<>();
List<Option> extraOptions = new ArrayList<>();
for (Option option : boat.getOptions()) {
if (option.getEssentialForBoatType().contains(boat.getType().toLowerCase()))
essentialOptions.add(option);
else
extraOptions.add(option);
}
printOptionsListFormatted(essentialOptions);
printOptionsListFormatted(extraOptions);
}
private void printOptionsListFormatted(List<Option> options) {
for (Option option : options) {
option.printOptionInfoForBoat(boat.getType());
}
}
public int getDiscount() {
int discount = 0;
switch (checkCustomerType()) {
case "goverment":
discount = govermentCustomer.getDiscount();
break;
case "business":
discount = businessCustomer.getDiscount();
break;
case "foundation":
discount = foundationCustomer.getDiscount();
break;
case "customer":
discount = customCustomer.getDiscount();
break;
}
return 100 - discount;
}
public double calculatePercentage(int percentage, double price) {
return (price / 100) * percentage;
}
public double calculateBoatPrice() {
double price = 0;
price += boat.getBasePrice();
for (Option option : boat.getOptions()) {
price += option.getPrice();
}
return price;
}
public void printTotal() {
Printer.getInstance().emptyLine();
//Totaal prijs boot
double totalPriceBoat = calculateBoatPrice();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaal prijs boot met korting
if (getDiscount() < 100 && getDiscount() > 0) {
totalPriceBoat = calculatePercentage(getDiscount(), totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot met korting:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
}
//prijs arbeids uren
Printer.getInstance().emptyLine();
double workCost = workHoursCost;
Printer.getInstance().printFormatInfo("Prijs arbeids uren:");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
Printer.getInstance().emptyLine();
//prijs arbeids uren incl
workCost = calculatePercentage(109, workCost);
Printer.getInstance().printFormatInfo(String.format("Prijs arbeids uren incl. Btw(9%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
//Totaal prijs boot incl btw
totalPriceBoat = calculatePercentage(121, totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot incl. Btw(21%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaalprijs offerte
totalPriceBoat += workHoursCost;
Printer.getInstance().printSpaces(128);
Printer.getInstance().printCharacters(1,'+');
Printer.getInstance().emptyLine();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs offerte:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
}
} | 22082476/PROJ1-Milkshake | src/Shipflex/Quote.java | 2,270 | //Totaal prijs boot | line_comment | nl | package Shipflex;
import Boat.Boat;
import Boat.Option;
import Customer.CustomCustomer;
import Customer.BusinessCustomer;
import Customer.FoundationCustomer;
import Customer.GovermentCustomer;
import DataInOut.Info;
import DataInOut.Printer;
import java.util.ArrayList;
import java.util.List;
public class Quote {
private Company companyShipbuild;
private CustomCustomer customCustomer;
private BusinessCustomer businessCustomer;
private GovermentCustomer govermentCustomer;
private FoundationCustomer foundationCustomer;
private String date;
private String quoteDate;
private String about;
private double workHoursCost;
private Boat boat;
public Quote(Company companyShipbuild, Boat boat) {
this.companyShipbuild = companyShipbuild;
this.businessCustomer = null;
this.customCustomer = null;
this.govermentCustomer = null;
this.foundationCustomer = null;
this.boat = boat;
}
public void setCustomCustomer(CustomCustomer customCustomer) {
this.customCustomer = customCustomer;
}
public void setBusinessCustomer(BusinessCustomer businessCustomer) {
this.businessCustomer = businessCustomer;
}
public void setGovermentCustomer(GovermentCustomer govermentCustomer) {
this.govermentCustomer = govermentCustomer;
}
public void setFoundationCustomer(FoundationCustomer foundationCustomer) {
this.foundationCustomer = foundationCustomer;
}
public void setAbout(String about) {
this.about = about;
}
public void setDate(String date) {
this.date = date;
}
public void setQuoteDate(String quoteDate) {
this.quoteDate = quoteDate;
}
public void setBoat(Boat boat) {
this.boat = boat;
}
public Boat getBoat() {
return boat;
}
public CustomCustomer getCustomCustomer() {
return customCustomer;
}
public BusinessCustomer getBusinessCustomer() {
return businessCustomer;
}
public GovermentCustomer getGovermentCustomer() {
return govermentCustomer;
}
public FoundationCustomer getFoundationCustomer() {
return foundationCustomer;
}
public void setWorkHoursCost(double workHoursCost) {
this.workHoursCost = workHoursCost;
}
public void printCustomer() {
switch (checkCustomerType()) {
case "goverment":
govermentCustomer.printCustomer();
break;
case "business":
businessCustomer.printCustomer();
break;
case "foundation":
foundationCustomer.printCustomer();
break;
case "customer":
customCustomer.printCustomer();
break;
default:
Printer.getInstance().printLine("Nog geen klant toegevoegd");
break;
}
}
private String checkCustomerType() {
if (govermentCustomer != null) {
return "goverment";
} else if (businessCustomer != null) {
return "business";
} else if (customCustomer != null) {
return "customer";
} else if (foundationCustomer != null) {
return "foundation";
} else {
return "";
}
}
public void printOptions(boolean showIndex) {
for (Option option : this.boat.getOptions()) {
if (showIndex)
Info.printOptionInfo(option, Info.getOptions().indexOf(option));
else
Info.printOptionInfo(option, -1);
Printer.getInstance().emptyLine();
}
}
public void printDate() {
if (this.date != null && !this.date.equals("")) {
Printer.getInstance().printLine("Datum: " + this.date);
} else {
Printer.getInstance().printLine("Datum nog niet ingevuld");
}
if (this.quoteDate != null && !this.quoteDate.equals("")) {
Printer.getInstance().printLine("Geldigsheid datum: " + this.quoteDate);
} else {
Printer.getInstance().printLine("Geldigsheid datum nog niet ingevuld");
}
}
public void printBasicInformation() {
companyShipbuild.printCompany();
Printer.getInstance().emptyLine();
printCustomer();
Printer.getInstance().emptyLine();
printDate();
Printer.getInstance().emptyLine();
if(this.about != null && !this.about.equals("")) {
Printer.getInstance().printLine("Betreft: " + this.about);
}else {
Printer.getInstance().printLine("Betreft is nog niet ingevuld");
}
Printer.getInstance().emptyLine();
}
public void printQuote() {
Printer.getInstance().printCharacters(129, '━');
Printer.getInstance().emptyLine();
this.printBasicInformation();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
boat.printBoat();
Printer.getInstance().printCharacters(78, '﹏');
Printer.getInstance().emptyLine();
this.printOptions();
Printer.getInstance().emptyLine();
this.printTotal();
Printer.getInstance().emptyLine();
Printer.getInstance().printCharacters(129, '━');
}
public void printOptions() {
List<Option> essentialOptions = new ArrayList<>();
List<Option> extraOptions = new ArrayList<>();
for (Option option : boat.getOptions()) {
if (option.getEssentialForBoatType().contains(boat.getType().toLowerCase()))
essentialOptions.add(option);
else
extraOptions.add(option);
}
printOptionsListFormatted(essentialOptions);
printOptionsListFormatted(extraOptions);
}
private void printOptionsListFormatted(List<Option> options) {
for (Option option : options) {
option.printOptionInfoForBoat(boat.getType());
}
}
public int getDiscount() {
int discount = 0;
switch (checkCustomerType()) {
case "goverment":
discount = govermentCustomer.getDiscount();
break;
case "business":
discount = businessCustomer.getDiscount();
break;
case "foundation":
discount = foundationCustomer.getDiscount();
break;
case "customer":
discount = customCustomer.getDiscount();
break;
}
return 100 - discount;
}
public double calculatePercentage(int percentage, double price) {
return (price / 100) * percentage;
}
public double calculateBoatPrice() {
double price = 0;
price += boat.getBasePrice();
for (Option option : boat.getOptions()) {
price += option.getPrice();
}
return price;
}
public void printTotal() {
Printer.getInstance().emptyLine();
//Totaa<SUF>
double totalPriceBoat = calculateBoatPrice();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaal prijs boot met korting
if (getDiscount() < 100 && getDiscount() > 0) {
totalPriceBoat = calculatePercentage(getDiscount(), totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot met korting:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
}
//prijs arbeids uren
Printer.getInstance().emptyLine();
double workCost = workHoursCost;
Printer.getInstance().printFormatInfo("Prijs arbeids uren:");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
Printer.getInstance().emptyLine();
//prijs arbeids uren incl
workCost = calculatePercentage(109, workCost);
Printer.getInstance().printFormatInfo(String.format("Prijs arbeids uren incl. Btw(9%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", workCost));
Printer.getInstance().emptyLine();
//Totaal prijs boot incl btw
totalPriceBoat = calculatePercentage(121, totalPriceBoat);
Printer.getInstance().printFormatInfo(String.format("Totaal prijs boot incl. Btw(21%%):"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
Printer.getInstance().emptyLine();
//Totaalprijs offerte
totalPriceBoat += workHoursCost;
Printer.getInstance().printSpaces(128);
Printer.getInstance().printCharacters(1,'+');
Printer.getInstance().emptyLine();
Printer.getInstance().printFormatInfo(String.format("Totaal prijs offerte:"));
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo("");
Printer.getInstance().printFormatInfo(String.format("%.2f", totalPriceBoat));
}
} |
41830_4 | package com.ebookfrenzy.gametest;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by Maarten on 15/12/15.
*/
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
public int DeviceW;
public int DeviceH;
public static final float widthBackground = 1080;
public static final float heightBackground = 1920;
public int mijnscore = 1;
private Random rand = new Random();
private NewTread Thread;
private Background mijnBackground;
private Beker mijnBeker;
private long snelheid;
private ArrayList<Blokje> blokjesLijst;
public GamePanel(Context context,int Dwidth, int DHight) {
super(context);
DeviceW = Dwidth;
DeviceH = DHight;
getHolder().addCallback(this);
Thread = new NewTread(getHolder(), this);
setFocusable(true);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while(retry) {
try {
Thread.setrunning(false);
Thread.join();
}
catch(InterruptedException e) {
System.out.print(e.getStackTrace());
}
retry = false;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mijnBackground = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.background02));
//mijnBeker = new Beker(BitmapFactory.decodeResource(getResources(), R.drawable.beker03), 160, 230, DeviceW);
mijnBeker = new Beker(BitmapFactory.decodeResource(getResources(),R.drawable.beker04),
100, (DeviceH*3/4 - 50), 100, 144, mijnscore, DeviceW);
blokjesLijst = new ArrayList<Blokje>();
snelheid = 1;
Thread.setrunning(true);
Thread.start();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) { // press down
if (!mijnBeker.getPlaying()) {
mijnBeker.setPlaying(true);
}
else {
mijnBeker.setPress(true);
}
return true;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
mijnBeker.setPress(false);
return true;
}
return super.onTouchEvent(event);
}
public void update() {
snelheid += 1;
if (mijnBeker.getPlaying()) {
mijnBackground.update();
mijnBeker.update();
int moeilijkheid = mijnscore;
if (snelheid % 50 == 0) {
blokjesLijst.add(new Blokje(BitmapFactory.decodeResource(getResources(),R.drawable.blokje02),
(int)(rand.nextDouble()*(widthBackground)), 0, 48, 52, mijnscore, 0));
}
for(int i = 0; i < blokjesLijst.size(); i++) {
blokjesLijst.get(i).update();
// blokje in beker
if (collision(blokjesLijst.get(i), mijnBeker)) {
blokjesLijst.remove(i);
mijnscore += 1;
}
// blokje uit het scherm
if (blokjesLijst.get(i).getX() < - 300) {
blokjesLijst.remove(i);
}
}
}
}
@Override
public void draw(Canvas canvas) {
final float scaleX = getWidth()/widthBackground;
final float scaleY = getWidth()/heightBackground;
float scale1 = (float) (0.5);
float scale2 = (float) (0.5);
super.draw(canvas);
if (canvas != null) {
Log.d("scale", String.valueOf(scaleY));
final int savedState = canvas.save();
canvas.scale(scaleX, scaleY);
mijnBackground.draw(canvas);
canvas.restoreToCount(savedState);
drawText(canvas);
mijnBeker.draw(canvas);
for (int i = 0; i < blokjesLijst.size(); i++) {
blokjesLijst.get(i).draw(canvas);
}
}
}
public boolean collision(Item blokje, Item player) {
/*if (Rect.intersects(blokje.getRectangle(), player.getRectangle())) {
return true;
}
else {
return false;
}
*/
if (blokje.y + 100> player.y && blokje.y + 50 < player.y ) {
if (blokje.x > player.x - 90 && blokje.x < (player.x + player.width + 90)) {
return true;
}
}
return false;
}
public void drawText(Canvas canvas) {
Paint mijnpaint = new Paint();
mijnpaint.setColor(Color.WHITE);
mijnpaint.setTextSize(30);
mijnpaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
canvas.drawText("Blokjes opgevangen: " + (mijnscore - 1), 10, getHeight() - 10, mijnpaint);
}
}
| 2645/integration_multiscreen_groep1_app | gameTestV0.1/app/src/main/java/com/ebookfrenzy/gametest/GamePanel.java | 1,517 | // blokje uit het scherm | line_comment | nl | package com.ebookfrenzy.gametest;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by Maarten on 15/12/15.
*/
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
public int DeviceW;
public int DeviceH;
public static final float widthBackground = 1080;
public static final float heightBackground = 1920;
public int mijnscore = 1;
private Random rand = new Random();
private NewTread Thread;
private Background mijnBackground;
private Beker mijnBeker;
private long snelheid;
private ArrayList<Blokje> blokjesLijst;
public GamePanel(Context context,int Dwidth, int DHight) {
super(context);
DeviceW = Dwidth;
DeviceH = DHight;
getHolder().addCallback(this);
Thread = new NewTread(getHolder(), this);
setFocusable(true);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while(retry) {
try {
Thread.setrunning(false);
Thread.join();
}
catch(InterruptedException e) {
System.out.print(e.getStackTrace());
}
retry = false;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mijnBackground = new Background(BitmapFactory.decodeResource(getResources(), R.drawable.background02));
//mijnBeker = new Beker(BitmapFactory.decodeResource(getResources(), R.drawable.beker03), 160, 230, DeviceW);
mijnBeker = new Beker(BitmapFactory.decodeResource(getResources(),R.drawable.beker04),
100, (DeviceH*3/4 - 50), 100, 144, mijnscore, DeviceW);
blokjesLijst = new ArrayList<Blokje>();
snelheid = 1;
Thread.setrunning(true);
Thread.start();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) { // press down
if (!mijnBeker.getPlaying()) {
mijnBeker.setPlaying(true);
}
else {
mijnBeker.setPress(true);
}
return true;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
mijnBeker.setPress(false);
return true;
}
return super.onTouchEvent(event);
}
public void update() {
snelheid += 1;
if (mijnBeker.getPlaying()) {
mijnBackground.update();
mijnBeker.update();
int moeilijkheid = mijnscore;
if (snelheid % 50 == 0) {
blokjesLijst.add(new Blokje(BitmapFactory.decodeResource(getResources(),R.drawable.blokje02),
(int)(rand.nextDouble()*(widthBackground)), 0, 48, 52, mijnscore, 0));
}
for(int i = 0; i < blokjesLijst.size(); i++) {
blokjesLijst.get(i).update();
// blokje in beker
if (collision(blokjesLijst.get(i), mijnBeker)) {
blokjesLijst.remove(i);
mijnscore += 1;
}
// blokj<SUF>
if (blokjesLijst.get(i).getX() < - 300) {
blokjesLijst.remove(i);
}
}
}
}
@Override
public void draw(Canvas canvas) {
final float scaleX = getWidth()/widthBackground;
final float scaleY = getWidth()/heightBackground;
float scale1 = (float) (0.5);
float scale2 = (float) (0.5);
super.draw(canvas);
if (canvas != null) {
Log.d("scale", String.valueOf(scaleY));
final int savedState = canvas.save();
canvas.scale(scaleX, scaleY);
mijnBackground.draw(canvas);
canvas.restoreToCount(savedState);
drawText(canvas);
mijnBeker.draw(canvas);
for (int i = 0; i < blokjesLijst.size(); i++) {
blokjesLijst.get(i).draw(canvas);
}
}
}
public boolean collision(Item blokje, Item player) {
/*if (Rect.intersects(blokje.getRectangle(), player.getRectangle())) {
return true;
}
else {
return false;
}
*/
if (blokje.y + 100> player.y && blokje.y + 50 < player.y ) {
if (blokje.x > player.x - 90 && blokje.x < (player.x + player.width + 90)) {
return true;
}
}
return false;
}
public void drawText(Canvas canvas) {
Paint mijnpaint = new Paint();
mijnpaint.setColor(Color.WHITE);
mijnpaint.setTextSize(30);
mijnpaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
canvas.drawText("Blokjes opgevangen: " + (mijnscore - 1), 10, getHeight() - 10, mijnpaint);
}
}
|
31177_16 | /*
* $Header$
* $Revision: 1321 $
* $Date: 2008-04-26 17:30:06 -0700 (Sat, 26 Apr 2008) $
*
* ====================================================================
*
* Copyright 2000-2002 bob mcwhirter & James Strachan.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the Jaxen Project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ====================================================================
* This software consists of voluntary contributions made by many
* individuals on behalf of the Jaxen Project and was originally
* created by bob mcwhirter <[email protected]> and
* James Strachan <[email protected]>. For more information on the
* Jaxen Project, please see <http://www.jaxen.org/>.
*
* $Id: ScalesBaseJaxenXPath.java 545 2011-10-22 19:01:04Z chris.twiner $
*/
package scales.xml.jaxen;
import java.io.Serializable;
import java.util.List;
import org.jaxen.expr.Expr;
import org.jaxen.expr.XPathExpr;
import org.jaxen.expr.XPathFactory;
import org.jaxen.function.BooleanFunction;
import org.jaxen.function.NumberFunction;
import org.jaxen.function.StringFunction;
import org.jaxen.saxpath.SAXPathException;
import org.jaxen.saxpath.XPathReader;
import org.jaxen.saxpath.helpers.XPathReaderFactory;
import org.jaxen.util.SingletonList;
import org.jaxen.*;
/** Base functionality for all concrete, implementation-specific XPaths.
*
* <p>
* This class provides generic functionality for further-defined
* implementation-specific XPaths.
* </p>
*
* <p>
* If you want to adapt the Jaxen engine so that it can traverse your own
* object model, then this is a good base class to derive from.
* Typically you only really need to provide your own
* {@link org.jaxen.Navigator} implementation.
* </p>
*
* @see org.jaxen.dom4j.Dom4jXPath XPath for dom4j
* @see org.jaxen.jdom.JDOMXPath XPath for JDOM
* @see org.jaxen.dom.DOMXPath XPath for W3C DOM
*
* @author <a href="mailto:[email protected]">bob mcwhirter</a>
* @author <a href="mailto:[email protected]">James Strachan</a>
*/
public class ScalesBaseJaxenXPath implements XPath, Serializable
{
private static final long serialVersionUID = -1993731281300293168L;
/** Original expression text. */
private final String exprText;
/** the parsed form of the XPath expression */
private final XPathExpr xpath;
/** the support information and function, namespace and variable contexts */
private ContextSupport support;
/** the implementation-specific Navigator for retrieving XML nodes **/
private Navigator navigator;
/** Construct given an XPath expression string.
*
* @param xpathExpr the XPath expression
*
* @throws JaxenException if there is a syntax error while
* parsing the expression
*/
protected ScalesBaseJaxenXPath(String xpathExpr, XPathFactory fact) throws JaxenException
{
try
{
XPathReader reader = XPathReaderFactory.createReader();
JaxenHandler handler = new JaxenHandler();
handler.setXPathFactory( fact ); // override the default one
reader.setXPathHandler( handler );
reader.parse( xpathExpr );
this.xpath = handler.getXPathExpr();
}
catch (org.jaxen.saxpath.XPathSyntaxException e)
{
throw new org.jaxen.XPathSyntaxException( e );
}
catch (SAXPathException e)
{
throw new JaxenException( e );
}
this.exprText = xpathExpr;
}
/** Construct given an XPath expression string.
*
* @param xpathExpr the XPath expression
*
* @param navigator the XML navigator to use
*
* @throws JaxenException if there is a syntax error while
* parsing the expression
*/
public ScalesBaseJaxenXPath(String xpathExpr, XPathFactory fact, Navigator navigator) throws JaxenException
{
this( xpathExpr, fact );
this.navigator = navigator;
}
/** Evaluate this XPath against a given context.
* The context of evaluation may be any object type
* the navigator recognizes as a node.
* The return value is either a <code>String</code>,
* <code>Double</code>, <code>Boolean</code>, or <code>List</code>
* of nodes.
*
* <p>
* When using this method, one must be careful to
* test the class of the returned object. If the returned
* object is a list, then the items in this
* list will be the actual <code>Document</code>,
* <code>Element</code>, <code>Attribute</code>, etc. objects
* as defined by the concrete XML object-model implementation,
* directly from the context document. This method <strong>does
* not return <em>copies</em> of anything</strong>, but merely
* returns references to objects within the source document.
* </p>
*
* @param context the node, node-set or Context object for evaluation.
* This value can be null.
*
* @return the result of evaluating the XPath expression
* against the supplied context
* @throws JaxenException if an XPath error occurs during expression evaluation
* @throws ClassCastException if the context is not a node
*/
public Object evaluate(Object context) throws JaxenException
{
List answer = selectNodes(context);
if ( answer != null
&&
answer.size() == 1 )
{
Object first = answer.get(0);
if ( first instanceof String
||
first instanceof Number
||
first instanceof Boolean )
{
return first;
}
}
return answer;
}
/** Select all nodes that are selected by this XPath
* expression. If multiple nodes match, multiple nodes
* will be returned. Nodes will be returned
* in document-order, as defined by the XPath
* specification. If the expression selects a non-node-set
* (i.e. a number, boolean, or string) then a List
* containing just that one object is returned.
* </p>
*
* @param node the node, node-set or Context object for evaluation.
* This value can be null.
*
* @return the node-set of all items selected
* by this XPath expression
* @throws JaxenException if an XPath error occurs during expression evaluation
*
* @see #selectNodesForContext
*/
public List selectNodes(Object node) throws JaxenException
{
Context context = getContext( node );
return selectNodesForContext( context );
}
/** Select only the first node selected by this XPath
* expression. If multiple nodes match, only one node will be
* returned. The selected node will be the first
* selected node in document-order, as defined by the XPath
* specification.
* </p>
*
* @param node the node, node-set or Context object for evaluation.
* This value can be null.
*
* @return the node-set of all items selected
* by this XPath expression
* @throws JaxenException if an XPath error occurs during expression evaluation
*
* @see #selectNodes
*/
public Object selectSingleNode(Object node) throws JaxenException
{
List results = selectNodes( node );
if ( results.isEmpty() )
{
return null;
}
return results.get( 0 );
}
/**
* Returns the XPath string-value of the argument node.
*
* @param node the node whose value to take
* @return the XPath string value of this node
* @throws JaxenException if an XPath error occurs during expression evaluation
* @deprecated replaced by {@link #stringValueOf}
*/
public String valueOf(Object node) throws JaxenException
{
return stringValueOf( node );
}
/** Retrieves the string-value of the result of
* evaluating this XPath expression when evaluated
* against the specified context.
*
* <p>
* The string-value of the expression is determined per
* the <code>string(..)</code> core function defined
* in the XPath specification. This means that an expression
* that selects zero nodes will return the empty string,
* while an expression that selects one-or-more nodes will
* return the string-value of the first node.
* </p>
*
* @param node the node, node-set or Context object for evaluation. This value can be null.
*
* @return the string-value of the result of evaluating this expression with the specified context node
* @throws JaxenException if an XPath error occurs during expression evaluation
*/
public String stringValueOf(Object node) throws JaxenException
{
Context context = getContext( node );
Object result = selectSingleNodeForContext( context );
if ( result == null )
{
return "";
}
return StringFunction.evaluate( result,
context.getNavigator() );
}
/** Retrieve a boolean-value interpretation of this XPath
* expression when evaluated against a given context.
*
* <p>
* The boolean-value of the expression is determined per
* the <code>boolean(..)</code> function defined
* in the XPath specification. This means that an expression
* that selects zero nodes will return <code>false</code>,
* while an expression that selects one or more nodes will
* return <code>true</code>.
* </p>
*
* @param node the node, node-set or Context object for evaluation. This value can be null.
*
* @return the boolean-value of the result of evaluating this expression with the specified context node
* @throws JaxenException if an XPath error occurs during expression evaluation
*/
public boolean booleanValueOf(Object node) throws JaxenException
{
Context context = getContext( node );
List result = selectNodesForContext( context );
if ( result == null ) return false;
return BooleanFunction.evaluate( result, context.getNavigator() ).booleanValue();
}
/** Retrieve a number-value interpretation of this XPath
* expression when evaluated against a given context.
*
* <p>
* The number-value of the expression is determined per
* the <code>number(..)</code> core function as defined
* in the XPath specification. This means that if this
* expression selects multiple nodes, the number-value
* of the first node is returned.
* </p>
*
* @param node the node, node-set or Context object for evaluation. This value can be null.
*
* @return a <code>Double</code> indicating the numeric value of
* evaluating this expression against the specified context
* @throws JaxenException if an XPath error occurs during expression evaluation
*/
public Number numberValueOf(Object node) throws JaxenException
{
Context context = getContext( node );
Object result = selectSingleNodeForContext( context );
return NumberFunction.evaluate( result,
context.getNavigator() );
}
// Helpers
/** Add a namespace prefix-to-URI mapping for this XPath
* expression.
*
* <p>
* Namespace prefix-to-URI mappings in an XPath are independent
* of those used within any document. Only the mapping explicitly
* added to this XPath will be available for resolving the
* XPath expression.
* </p>
*
* <p>
* This is a convenience method for adding mappings to the
* default {@link NamespaceContext} in place for this XPath.
* If you have installed a custom <code>NamespaceContext</code>
* that is not a <code>SimpleNamespaceContext</code>,
* then this method will throw a <code>JaxenException</code>.
* </p>
*
* @param prefix the namespace prefix
* @param uri the namespace URI
*
* @throws JaxenException if the <code>NamespaceContext</code>
* used by this XPath is not a <code>SimpleNamespaceContext</code>
*/
public void addNamespace(String prefix,
String uri) throws JaxenException
{
NamespaceContext nsContext = getNamespaceContext();
if ( nsContext instanceof SimpleNamespaceContext )
{
((SimpleNamespaceContext)nsContext).addNamespace( prefix,
uri );
return;
}
throw new JaxenException("Operation not permitted while using a non-simple namespace context.");
}
// ------------------------------------------------------------
// ------------------------------------------------------------
// Properties
// ------------------------------------------------------------
// ------------------------------------------------------------
/** Set a <code>NamespaceContext</code> for use with this
* XPath expression.
*
* <p>
* A <code>NamespaceContext</code> is responsible for translating
* namespace prefixes within the expression into namespace URIs.
* </p>
*
* @param namespaceContext the <code>NamespaceContext</code> to
* install for this expression
*
* @see NamespaceContext
* @see NamespaceContext#translateNamespacePrefixToUri
*/
public void setNamespaceContext(NamespaceContext namespaceContext)
{
getContextSupport().setNamespaceContext(namespaceContext);
}
/** Set a <code>FunctionContext</code> for use with this XPath
* expression.
*
* <p>
* A <code>FunctionContext</code> is responsible for resolving
* all function calls used within the expression.
* </p>
*
* @param functionContext the <code>FunctionContext</code> to
* install for this expression
*
* @see FunctionContext
* @see FunctionContext#getFunction
*/
public void setFunctionContext(FunctionContext functionContext)
{
getContextSupport().setFunctionContext(functionContext);
}
/** Set a <code>VariableContext</code> for use with this XPath
* expression.
*
* <p>
* A <code>VariableContext</code> is responsible for resolving
* all variables referenced within the expression.
* </p>
*
* @param variableContext The <code>VariableContext</code> to
* install for this expression
*
* @see VariableContext
* @see VariableContext#getVariableValue
*/
public void setVariableContext(VariableContext variableContext)
{
getContextSupport().setVariableContext(variableContext);
}
/** Retrieve the <code>NamespaceContext</code> used by this XPath
* expression.
*
* <p>
* A <code>NamespaceContext</code> is responsible for mapping
* prefixes used within the expression to namespace URIs.
* </p>
*
* <p>
* If this XPath expression has not previously had a <code>NamespaceContext</code>
* installed, a new default <code>NamespaceContext</code> will be created,
* installed and returned.
* </p>
*
* @return the <code>NamespaceContext</code> used by this expression
*
* @see NamespaceContext
*/
public NamespaceContext getNamespaceContext()
{
return getContextSupport().getNamespaceContext();
}
/** Retrieve the <code>FunctionContext</code> used by this XPath
* expression.
*
* <p>
* A <code>FunctionContext</code> is responsible for resolving
* all function calls used within the expression.
* </p>
*
* <p>
* If this XPath expression has not previously had a <code>FunctionContext</code>
* installed, a new default <code>FunctionContext</code> will be created,
* installed and returned.
* </p>
*
* @return the <code>FunctionContext</code> used by this expression
*
* @see FunctionContext
*/
public FunctionContext getFunctionContext()
{
return getContextSupport().getFunctionContext();
}
/** Retrieve the <code>VariableContext</code> used by this XPath
* expression.
*
* <p>
* A <code>VariableContext</code> is responsible for resolving
* all variables referenced within the expression.
* </p>
*
* <p>
* If this XPath expression has not previously had a <code>VariableContext</code>
* installed, a new default <code>VariableContext</code> will be created,
* installed and returned.
* </p>
*
* @return the <code>VariableContext</code> used by this expression
*
* @see VariableContext
*/
public VariableContext getVariableContext()
{
return getContextSupport().getVariableContext();
}
/** Retrieve the root expression of the internal
* compiled form of this XPath expression.
*
* <p>
* Internally, Jaxen maintains a form of Abstract Syntax
* Tree (AST) to represent the structure of the XPath expression.
* This is normally not required during normal consumer-grade
* usage of Jaxen. This method is provided for hard-core users
* who wish to manipulate or inspect a tree-based version of
* the expression.
* </p>
*
* @return the root of the AST of this expression
*/
public Expr getRootExpr()
{
return xpath.getRootExpr();
}
/** Return the original expression text.
*
* @return the normalized XPath expression string
*/
public String toString()
{
return this.exprText;
}
/** Returns a string representation of the parse tree.
*
* @return a string representation of the parse tree.
*/
public String debug()
{
return this.xpath.toString();
}
// ------------------------------------------------------------
// ------------------------------------------------------------
// Implementation methods
// ------------------------------------------------------------
// ------------------------------------------------------------
/** Create a {@link Context} wrapper for the provided
* implementation-specific object.
*
* @param node the implementation-specific object
* to be used as the context
*
* @return a <code>Context</code> wrapper around the object
*/
protected Context getContext(Object node)
{
if ( node instanceof Context )
{
return (Context) node;
}
Context fullContext = new Context( getContextSupport() );
if ( node instanceof List )
{
fullContext.setNodeSet( (List) node );
}
else
{
List list = new SingletonList(node);
fullContext.setNodeSet( list );
}
return fullContext;
}
/** Retrieve the {@link ContextSupport} aggregation of
* <code>NamespaceContext</code>, <code>FunctionContext</code>,
* <code>VariableContext</code>, and {@link Navigator}.
*
* @return aggregate <code>ContextSupport</code> for this
* XPath expression
*/
protected ContextSupport getContextSupport()
{
if ( support == null )
{
support = new ContextSupport(
createNamespaceContext(),
createFunctionContext(),
createVariableContext(),
getNavigator()
);
}
return support;
}
/** Retrieve the XML object-model-specific {@link Navigator}
* for us in evaluating this XPath expression.
*
* @return the implementation-specific <code>Navigator</code>
*/
public Navigator getNavigator()
{
return navigator;
}
// ------------------------------------------------------------
// ------------------------------------------------------------
// Factory methods for default contexts
// ------------------------------------------------------------
// ------------------------------------------------------------
/** Create a default <code>FunctionContext</code>.
*
* @return a default <code>FunctionContext</code>
*/
protected FunctionContext createFunctionContext()
{
return XPathFunctionContext.getInstance();
}
/** Create a default <code>NamespaceContext</code>.
*
* @return a default <code>NamespaceContext</code> instance
*/
protected NamespaceContext createNamespaceContext()
{
return new SimpleNamespaceContext();
}
/** Create a default <code>VariableContext</code>.
*
* @return a default <code>VariableContext</code> instance
*/
protected VariableContext createVariableContext()
{
return new SimpleVariableContext();
}
/** Select all nodes that match this XPath
* expression on the given Context object.
* If multiple nodes match, multiple nodes
* will be returned in document-order, as defined by the XPath
* specification. If the expression selects a non-node-set
* (i.e. a number, boolean, or string) then a List
* containing just that one object is returned.
* </p>
*
* @param context the Context which gets evaluated
*
* @return the node-set of all items selected
* by this XPath expression
* @throws JaxenException if an XPath error occurs during expression evaluation
*
*/
protected List selectNodesForContext(Context context) throws JaxenException
{
List list = this.xpath.asList( context );
return list;
}
/** Return only the first node that is selected by this XPath
* expression. If multiple nodes match, only one node will be
* returned. The selected node will be the first
* selected node in document-order, as defined by the XPath
* specification. If the XPath expression selects a double,
* String, or boolean, then that object is returned.
* </p>
*
* @param context the Context against which this expression is evaluated
*
* @return the first node in document order of all nodes selected
* by this XPath expression
* @throws JaxenException if an XPath error occurs during expression evaluation
*
* @see #selectNodesForContext
*/
protected Object selectSingleNodeForContext(Context context) throws JaxenException
{
List results = selectNodesForContext( context );
if ( results.isEmpty() )
{
return null;
}
return results.get( 0 );
}
}
| 2chilled/scalesXml | jaxen/src/main/java/scales/xml/jaxen/ScalesBaseJaxenXPath.java | 5,991 | // Helpers | line_comment | nl | /*
* $Header$
* $Revision: 1321 $
* $Date: 2008-04-26 17:30:06 -0700 (Sat, 26 Apr 2008) $
*
* ====================================================================
*
* Copyright 2000-2002 bob mcwhirter & James Strachan.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the Jaxen Project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ====================================================================
* This software consists of voluntary contributions made by many
* individuals on behalf of the Jaxen Project and was originally
* created by bob mcwhirter <[email protected]> and
* James Strachan <[email protected]>. For more information on the
* Jaxen Project, please see <http://www.jaxen.org/>.
*
* $Id: ScalesBaseJaxenXPath.java 545 2011-10-22 19:01:04Z chris.twiner $
*/
package scales.xml.jaxen;
import java.io.Serializable;
import java.util.List;
import org.jaxen.expr.Expr;
import org.jaxen.expr.XPathExpr;
import org.jaxen.expr.XPathFactory;
import org.jaxen.function.BooleanFunction;
import org.jaxen.function.NumberFunction;
import org.jaxen.function.StringFunction;
import org.jaxen.saxpath.SAXPathException;
import org.jaxen.saxpath.XPathReader;
import org.jaxen.saxpath.helpers.XPathReaderFactory;
import org.jaxen.util.SingletonList;
import org.jaxen.*;
/** Base functionality for all concrete, implementation-specific XPaths.
*
* <p>
* This class provides generic functionality for further-defined
* implementation-specific XPaths.
* </p>
*
* <p>
* If you want to adapt the Jaxen engine so that it can traverse your own
* object model, then this is a good base class to derive from.
* Typically you only really need to provide your own
* {@link org.jaxen.Navigator} implementation.
* </p>
*
* @see org.jaxen.dom4j.Dom4jXPath XPath for dom4j
* @see org.jaxen.jdom.JDOMXPath XPath for JDOM
* @see org.jaxen.dom.DOMXPath XPath for W3C DOM
*
* @author <a href="mailto:[email protected]">bob mcwhirter</a>
* @author <a href="mailto:[email protected]">James Strachan</a>
*/
public class ScalesBaseJaxenXPath implements XPath, Serializable
{
private static final long serialVersionUID = -1993731281300293168L;
/** Original expression text. */
private final String exprText;
/** the parsed form of the XPath expression */
private final XPathExpr xpath;
/** the support information and function, namespace and variable contexts */
private ContextSupport support;
/** the implementation-specific Navigator for retrieving XML nodes **/
private Navigator navigator;
/** Construct given an XPath expression string.
*
* @param xpathExpr the XPath expression
*
* @throws JaxenException if there is a syntax error while
* parsing the expression
*/
protected ScalesBaseJaxenXPath(String xpathExpr, XPathFactory fact) throws JaxenException
{
try
{
XPathReader reader = XPathReaderFactory.createReader();
JaxenHandler handler = new JaxenHandler();
handler.setXPathFactory( fact ); // override the default one
reader.setXPathHandler( handler );
reader.parse( xpathExpr );
this.xpath = handler.getXPathExpr();
}
catch (org.jaxen.saxpath.XPathSyntaxException e)
{
throw new org.jaxen.XPathSyntaxException( e );
}
catch (SAXPathException e)
{
throw new JaxenException( e );
}
this.exprText = xpathExpr;
}
/** Construct given an XPath expression string.
*
* @param xpathExpr the XPath expression
*
* @param navigator the XML navigator to use
*
* @throws JaxenException if there is a syntax error while
* parsing the expression
*/
public ScalesBaseJaxenXPath(String xpathExpr, XPathFactory fact, Navigator navigator) throws JaxenException
{
this( xpathExpr, fact );
this.navigator = navigator;
}
/** Evaluate this XPath against a given context.
* The context of evaluation may be any object type
* the navigator recognizes as a node.
* The return value is either a <code>String</code>,
* <code>Double</code>, <code>Boolean</code>, or <code>List</code>
* of nodes.
*
* <p>
* When using this method, one must be careful to
* test the class of the returned object. If the returned
* object is a list, then the items in this
* list will be the actual <code>Document</code>,
* <code>Element</code>, <code>Attribute</code>, etc. objects
* as defined by the concrete XML object-model implementation,
* directly from the context document. This method <strong>does
* not return <em>copies</em> of anything</strong>, but merely
* returns references to objects within the source document.
* </p>
*
* @param context the node, node-set or Context object for evaluation.
* This value can be null.
*
* @return the result of evaluating the XPath expression
* against the supplied context
* @throws JaxenException if an XPath error occurs during expression evaluation
* @throws ClassCastException if the context is not a node
*/
public Object evaluate(Object context) throws JaxenException
{
List answer = selectNodes(context);
if ( answer != null
&&
answer.size() == 1 )
{
Object first = answer.get(0);
if ( first instanceof String
||
first instanceof Number
||
first instanceof Boolean )
{
return first;
}
}
return answer;
}
/** Select all nodes that are selected by this XPath
* expression. If multiple nodes match, multiple nodes
* will be returned. Nodes will be returned
* in document-order, as defined by the XPath
* specification. If the expression selects a non-node-set
* (i.e. a number, boolean, or string) then a List
* containing just that one object is returned.
* </p>
*
* @param node the node, node-set or Context object for evaluation.
* This value can be null.
*
* @return the node-set of all items selected
* by this XPath expression
* @throws JaxenException if an XPath error occurs during expression evaluation
*
* @see #selectNodesForContext
*/
public List selectNodes(Object node) throws JaxenException
{
Context context = getContext( node );
return selectNodesForContext( context );
}
/** Select only the first node selected by this XPath
* expression. If multiple nodes match, only one node will be
* returned. The selected node will be the first
* selected node in document-order, as defined by the XPath
* specification.
* </p>
*
* @param node the node, node-set or Context object for evaluation.
* This value can be null.
*
* @return the node-set of all items selected
* by this XPath expression
* @throws JaxenException if an XPath error occurs during expression evaluation
*
* @see #selectNodes
*/
public Object selectSingleNode(Object node) throws JaxenException
{
List results = selectNodes( node );
if ( results.isEmpty() )
{
return null;
}
return results.get( 0 );
}
/**
* Returns the XPath string-value of the argument node.
*
* @param node the node whose value to take
* @return the XPath string value of this node
* @throws JaxenException if an XPath error occurs during expression evaluation
* @deprecated replaced by {@link #stringValueOf}
*/
public String valueOf(Object node) throws JaxenException
{
return stringValueOf( node );
}
/** Retrieves the string-value of the result of
* evaluating this XPath expression when evaluated
* against the specified context.
*
* <p>
* The string-value of the expression is determined per
* the <code>string(..)</code> core function defined
* in the XPath specification. This means that an expression
* that selects zero nodes will return the empty string,
* while an expression that selects one-or-more nodes will
* return the string-value of the first node.
* </p>
*
* @param node the node, node-set or Context object for evaluation. This value can be null.
*
* @return the string-value of the result of evaluating this expression with the specified context node
* @throws JaxenException if an XPath error occurs during expression evaluation
*/
public String stringValueOf(Object node) throws JaxenException
{
Context context = getContext( node );
Object result = selectSingleNodeForContext( context );
if ( result == null )
{
return "";
}
return StringFunction.evaluate( result,
context.getNavigator() );
}
/** Retrieve a boolean-value interpretation of this XPath
* expression when evaluated against a given context.
*
* <p>
* The boolean-value of the expression is determined per
* the <code>boolean(..)</code> function defined
* in the XPath specification. This means that an expression
* that selects zero nodes will return <code>false</code>,
* while an expression that selects one or more nodes will
* return <code>true</code>.
* </p>
*
* @param node the node, node-set or Context object for evaluation. This value can be null.
*
* @return the boolean-value of the result of evaluating this expression with the specified context node
* @throws JaxenException if an XPath error occurs during expression evaluation
*/
public boolean booleanValueOf(Object node) throws JaxenException
{
Context context = getContext( node );
List result = selectNodesForContext( context );
if ( result == null ) return false;
return BooleanFunction.evaluate( result, context.getNavigator() ).booleanValue();
}
/** Retrieve a number-value interpretation of this XPath
* expression when evaluated against a given context.
*
* <p>
* The number-value of the expression is determined per
* the <code>number(..)</code> core function as defined
* in the XPath specification. This means that if this
* expression selects multiple nodes, the number-value
* of the first node is returned.
* </p>
*
* @param node the node, node-set or Context object for evaluation. This value can be null.
*
* @return a <code>Double</code> indicating the numeric value of
* evaluating this expression against the specified context
* @throws JaxenException if an XPath error occurs during expression evaluation
*/
public Number numberValueOf(Object node) throws JaxenException
{
Context context = getContext( node );
Object result = selectSingleNodeForContext( context );
return NumberFunction.evaluate( result,
context.getNavigator() );
}
// Helpe<SUF>
/** Add a namespace prefix-to-URI mapping for this XPath
* expression.
*
* <p>
* Namespace prefix-to-URI mappings in an XPath are independent
* of those used within any document. Only the mapping explicitly
* added to this XPath will be available for resolving the
* XPath expression.
* </p>
*
* <p>
* This is a convenience method for adding mappings to the
* default {@link NamespaceContext} in place for this XPath.
* If you have installed a custom <code>NamespaceContext</code>
* that is not a <code>SimpleNamespaceContext</code>,
* then this method will throw a <code>JaxenException</code>.
* </p>
*
* @param prefix the namespace prefix
* @param uri the namespace URI
*
* @throws JaxenException if the <code>NamespaceContext</code>
* used by this XPath is not a <code>SimpleNamespaceContext</code>
*/
public void addNamespace(String prefix,
String uri) throws JaxenException
{
NamespaceContext nsContext = getNamespaceContext();
if ( nsContext instanceof SimpleNamespaceContext )
{
((SimpleNamespaceContext)nsContext).addNamespace( prefix,
uri );
return;
}
throw new JaxenException("Operation not permitted while using a non-simple namespace context.");
}
// ------------------------------------------------------------
// ------------------------------------------------------------
// Properties
// ------------------------------------------------------------
// ------------------------------------------------------------
/** Set a <code>NamespaceContext</code> for use with this
* XPath expression.
*
* <p>
* A <code>NamespaceContext</code> is responsible for translating
* namespace prefixes within the expression into namespace URIs.
* </p>
*
* @param namespaceContext the <code>NamespaceContext</code> to
* install for this expression
*
* @see NamespaceContext
* @see NamespaceContext#translateNamespacePrefixToUri
*/
public void setNamespaceContext(NamespaceContext namespaceContext)
{
getContextSupport().setNamespaceContext(namespaceContext);
}
/** Set a <code>FunctionContext</code> for use with this XPath
* expression.
*
* <p>
* A <code>FunctionContext</code> is responsible for resolving
* all function calls used within the expression.
* </p>
*
* @param functionContext the <code>FunctionContext</code> to
* install for this expression
*
* @see FunctionContext
* @see FunctionContext#getFunction
*/
public void setFunctionContext(FunctionContext functionContext)
{
getContextSupport().setFunctionContext(functionContext);
}
/** Set a <code>VariableContext</code> for use with this XPath
* expression.
*
* <p>
* A <code>VariableContext</code> is responsible for resolving
* all variables referenced within the expression.
* </p>
*
* @param variableContext The <code>VariableContext</code> to
* install for this expression
*
* @see VariableContext
* @see VariableContext#getVariableValue
*/
public void setVariableContext(VariableContext variableContext)
{
getContextSupport().setVariableContext(variableContext);
}
/** Retrieve the <code>NamespaceContext</code> used by this XPath
* expression.
*
* <p>
* A <code>NamespaceContext</code> is responsible for mapping
* prefixes used within the expression to namespace URIs.
* </p>
*
* <p>
* If this XPath expression has not previously had a <code>NamespaceContext</code>
* installed, a new default <code>NamespaceContext</code> will be created,
* installed and returned.
* </p>
*
* @return the <code>NamespaceContext</code> used by this expression
*
* @see NamespaceContext
*/
public NamespaceContext getNamespaceContext()
{
return getContextSupport().getNamespaceContext();
}
/** Retrieve the <code>FunctionContext</code> used by this XPath
* expression.
*
* <p>
* A <code>FunctionContext</code> is responsible for resolving
* all function calls used within the expression.
* </p>
*
* <p>
* If this XPath expression has not previously had a <code>FunctionContext</code>
* installed, a new default <code>FunctionContext</code> will be created,
* installed and returned.
* </p>
*
* @return the <code>FunctionContext</code> used by this expression
*
* @see FunctionContext
*/
public FunctionContext getFunctionContext()
{
return getContextSupport().getFunctionContext();
}
/** Retrieve the <code>VariableContext</code> used by this XPath
* expression.
*
* <p>
* A <code>VariableContext</code> is responsible for resolving
* all variables referenced within the expression.
* </p>
*
* <p>
* If this XPath expression has not previously had a <code>VariableContext</code>
* installed, a new default <code>VariableContext</code> will be created,
* installed and returned.
* </p>
*
* @return the <code>VariableContext</code> used by this expression
*
* @see VariableContext
*/
public VariableContext getVariableContext()
{
return getContextSupport().getVariableContext();
}
/** Retrieve the root expression of the internal
* compiled form of this XPath expression.
*
* <p>
* Internally, Jaxen maintains a form of Abstract Syntax
* Tree (AST) to represent the structure of the XPath expression.
* This is normally not required during normal consumer-grade
* usage of Jaxen. This method is provided for hard-core users
* who wish to manipulate or inspect a tree-based version of
* the expression.
* </p>
*
* @return the root of the AST of this expression
*/
public Expr getRootExpr()
{
return xpath.getRootExpr();
}
/** Return the original expression text.
*
* @return the normalized XPath expression string
*/
public String toString()
{
return this.exprText;
}
/** Returns a string representation of the parse tree.
*
* @return a string representation of the parse tree.
*/
public String debug()
{
return this.xpath.toString();
}
// ------------------------------------------------------------
// ------------------------------------------------------------
// Implementation methods
// ------------------------------------------------------------
// ------------------------------------------------------------
/** Create a {@link Context} wrapper for the provided
* implementation-specific object.
*
* @param node the implementation-specific object
* to be used as the context
*
* @return a <code>Context</code> wrapper around the object
*/
protected Context getContext(Object node)
{
if ( node instanceof Context )
{
return (Context) node;
}
Context fullContext = new Context( getContextSupport() );
if ( node instanceof List )
{
fullContext.setNodeSet( (List) node );
}
else
{
List list = new SingletonList(node);
fullContext.setNodeSet( list );
}
return fullContext;
}
/** Retrieve the {@link ContextSupport} aggregation of
* <code>NamespaceContext</code>, <code>FunctionContext</code>,
* <code>VariableContext</code>, and {@link Navigator}.
*
* @return aggregate <code>ContextSupport</code> for this
* XPath expression
*/
protected ContextSupport getContextSupport()
{
if ( support == null )
{
support = new ContextSupport(
createNamespaceContext(),
createFunctionContext(),
createVariableContext(),
getNavigator()
);
}
return support;
}
/** Retrieve the XML object-model-specific {@link Navigator}
* for us in evaluating this XPath expression.
*
* @return the implementation-specific <code>Navigator</code>
*/
public Navigator getNavigator()
{
return navigator;
}
// ------------------------------------------------------------
// ------------------------------------------------------------
// Factory methods for default contexts
// ------------------------------------------------------------
// ------------------------------------------------------------
/** Create a default <code>FunctionContext</code>.
*
* @return a default <code>FunctionContext</code>
*/
protected FunctionContext createFunctionContext()
{
return XPathFunctionContext.getInstance();
}
/** Create a default <code>NamespaceContext</code>.
*
* @return a default <code>NamespaceContext</code> instance
*/
protected NamespaceContext createNamespaceContext()
{
return new SimpleNamespaceContext();
}
/** Create a default <code>VariableContext</code>.
*
* @return a default <code>VariableContext</code> instance
*/
protected VariableContext createVariableContext()
{
return new SimpleVariableContext();
}
/** Select all nodes that match this XPath
* expression on the given Context object.
* If multiple nodes match, multiple nodes
* will be returned in document-order, as defined by the XPath
* specification. If the expression selects a non-node-set
* (i.e. a number, boolean, or string) then a List
* containing just that one object is returned.
* </p>
*
* @param context the Context which gets evaluated
*
* @return the node-set of all items selected
* by this XPath expression
* @throws JaxenException if an XPath error occurs during expression evaluation
*
*/
protected List selectNodesForContext(Context context) throws JaxenException
{
List list = this.xpath.asList( context );
return list;
}
/** Return only the first node that is selected by this XPath
* expression. If multiple nodes match, only one node will be
* returned. The selected node will be the first
* selected node in document-order, as defined by the XPath
* specification. If the XPath expression selects a double,
* String, or boolean, then that object is returned.
* </p>
*
* @param context the Context against which this expression is evaluated
*
* @return the first node in document order of all nodes selected
* by this XPath expression
* @throws JaxenException if an XPath error occurs during expression evaluation
*
* @see #selectNodesForContext
*/
protected Object selectSingleNodeForContext(Context context) throws JaxenException
{
List results = selectNodesForContext( context );
if ( results.isEmpty() )
{
return null;
}
return results.get( 0 );
}
}
|
32107_6 | package view;
import java.awt.Color;
import java.util.HashMap;
import java.awt.Graphics;
import javax.swing.JPanel;
import logic.Counter;
/**
* The Class represent the population of actors in a piechart
*/
public class PieChart extends JPanel
{
// width of the frame
private int width;
// height of the frame
private int height;
// hashmap die hoeveelheid per kleur bij houdt
private HashMap<Color, Counter> stats;
/**
* leeg constructor
*/
public PieChart()
{
}
/**
* stats wordt toegewezen
* @param stats populate stats
*/
public void stats(HashMap<Color, Counter> stats)
{
this.stats = stats;
}
/**
* bepaald de frame grote van de piechart
* @param width
* @param height
*/
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
/**
* maak de piechart
* @param g Graphic component
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// totaal hoeveelheid van alle kleuren
int total = 0;
int startAngle = 0;
int arcAngle = 0;
for (Color color: stats.keySet())
{
// teller van alle kleuren worden bij elkaar opgeteld
total += stats.get(color).getCount();
}
// kleurt de piechart
for (Color color : stats.keySet())
{
if (stats.get(color).getCount() > 0)
{
// teller van een kleeur delen door de totaal en keer 360 graden
arcAngle = (stats.get(color).getCount() * 360/ total) ;
g.setColor(color);
// draw de piechart
g.fillArc(50, 50, width, height, startAngle, arcAngle);
// start angle van de volgende kleur
startAngle += arcAngle + 1;
}
}
// paint de outline van de piechart
g.setColor(Color.BLACK);
g.drawArc(50, 50, width, height, 0, 360);
}
} | 2ntense/foxes-and-rabbits-v2 | src/view/PieChart.java | 608 | /**
* bepaald de frame grote van de piechart
* @param width
* @param height
*/ | block_comment | nl | package view;
import java.awt.Color;
import java.util.HashMap;
import java.awt.Graphics;
import javax.swing.JPanel;
import logic.Counter;
/**
* The Class represent the population of actors in a piechart
*/
public class PieChart extends JPanel
{
// width of the frame
private int width;
// height of the frame
private int height;
// hashmap die hoeveelheid per kleur bij houdt
private HashMap<Color, Counter> stats;
/**
* leeg constructor
*/
public PieChart()
{
}
/**
* stats wordt toegewezen
* @param stats populate stats
*/
public void stats(HashMap<Color, Counter> stats)
{
this.stats = stats;
}
/**
* bepaal<SUF>*/
public void setSize(int width, int height)
{
this.width = width;
this.height = height;
}
/**
* maak de piechart
* @param g Graphic component
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// totaal hoeveelheid van alle kleuren
int total = 0;
int startAngle = 0;
int arcAngle = 0;
for (Color color: stats.keySet())
{
// teller van alle kleuren worden bij elkaar opgeteld
total += stats.get(color).getCount();
}
// kleurt de piechart
for (Color color : stats.keySet())
{
if (stats.get(color).getCount() > 0)
{
// teller van een kleeur delen door de totaal en keer 360 graden
arcAngle = (stats.get(color).getCount() * 360/ total) ;
g.setColor(color);
// draw de piechart
g.fillArc(50, 50, width, height, startAngle, arcAngle);
// start angle van de volgende kleur
startAngle += arcAngle + 1;
}
}
// paint de outline van de piechart
g.setColor(Color.BLACK);
g.drawArc(50, 50, width, height, 0, 360);
}
} |
137242_0 | package com.example.snackapp.Views;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.snackapp.Model.DatabaseHelper;
import com.example.snackapp.Model.MainActivity;
import com.example.snackapp.Model.User;
import com.example.snackapp.R;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SignupActivity extends AppCompatActivity {
private DatabaseHelper Database;
private ExecutorService executorService;
private EditText emailEditText, passwordEditText, confirmPasswordEditText,
firstNameEditText, lastNameEditText, phoneNumberEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
// Vind de invoervelden door hun id's
emailEditText = findViewById(R.id.signup_email);
passwordEditText = findViewById(R.id.signup_password);
confirmPasswordEditText = findViewById(R.id.signup_confirm);
firstNameEditText = findViewById(R.id.signup_firstName);
lastNameEditText = findViewById(R.id.signup_lastName);
phoneNumberEditText = findViewById(R.id.signup_phoneNumber);
Button signupButton = findViewById(R.id.signup_button);
signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Hier zal het registratieproces worden gestart
registerUser();
}
});
TextView loginRedirectText = findViewById(R.id.loginRedirectText);
loginRedirectText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigateToLogin(); // Functie om naar de loginpagina te navigeren
}
});
}
private void registerUser() {
// Haal gegevens op uit de invoervelden
Database = DatabaseHelper.getInstance(getApplicationContext());
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
String firstName = firstNameEditText.getText().toString();
String lastName = lastNameEditText.getText().toString();
String phoneNumber = phoneNumberEditText.getText().toString();
// Controleer of alle velden zijn ingevuld voordat je doorgaat met registreren
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)
|| TextUtils.isEmpty(firstName) || TextUtils.isEmpty(lastName) || TextUtils.isEmpty(phoneNumber)) {
Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show();
return;
}
// Controleer of de wachtwoorden overeenkomen
if (password.equals(confirmPassword)) {
// Maak een User-object aan met de ingevoerde gegevens
User newUser = new User(email, password, firstName, lastName, phoneNumber);
executorService = Executors.newFixedThreadPool(2);
executorService.execute(()-> {
Database.getUserDao().insertUser(newUser);
});
Toast.makeText(this, "Registration successful!", Toast.LENGTH_SHORT).show();
// Start MainActivity na succesvolle registratie
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
finish(); // Sluit de SignupActivity om terugkeren te voorkomen
} else {
// Geef een foutmelding als de wachtwoorden niet overeenkomen
Toast.makeText(this, "Passwords do not match!", Toast.LENGTH_SHORT).show();
}
}
private void navigateToLogin() {
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
finish(); // Sluit de huidige activiteit (SignupActivity) na navigatie
}
}
| 2speef10/SnackApp | app/src/main/java/com/example/snackapp/Views/SignupActivity.java | 959 | // Vind de invoervelden door hun id's | line_comment | nl | package com.example.snackapp.Views;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.snackapp.Model.DatabaseHelper;
import com.example.snackapp.Model.MainActivity;
import com.example.snackapp.Model.User;
import com.example.snackapp.R;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SignupActivity extends AppCompatActivity {
private DatabaseHelper Database;
private ExecutorService executorService;
private EditText emailEditText, passwordEditText, confirmPasswordEditText,
firstNameEditText, lastNameEditText, phoneNumberEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
// Vind <SUF>
emailEditText = findViewById(R.id.signup_email);
passwordEditText = findViewById(R.id.signup_password);
confirmPasswordEditText = findViewById(R.id.signup_confirm);
firstNameEditText = findViewById(R.id.signup_firstName);
lastNameEditText = findViewById(R.id.signup_lastName);
phoneNumberEditText = findViewById(R.id.signup_phoneNumber);
Button signupButton = findViewById(R.id.signup_button);
signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Hier zal het registratieproces worden gestart
registerUser();
}
});
TextView loginRedirectText = findViewById(R.id.loginRedirectText);
loginRedirectText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigateToLogin(); // Functie om naar de loginpagina te navigeren
}
});
}
private void registerUser() {
// Haal gegevens op uit de invoervelden
Database = DatabaseHelper.getInstance(getApplicationContext());
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
String firstName = firstNameEditText.getText().toString();
String lastName = lastNameEditText.getText().toString();
String phoneNumber = phoneNumberEditText.getText().toString();
// Controleer of alle velden zijn ingevuld voordat je doorgaat met registreren
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)
|| TextUtils.isEmpty(firstName) || TextUtils.isEmpty(lastName) || TextUtils.isEmpty(phoneNumber)) {
Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show();
return;
}
// Controleer of de wachtwoorden overeenkomen
if (password.equals(confirmPassword)) {
// Maak een User-object aan met de ingevoerde gegevens
User newUser = new User(email, password, firstName, lastName, phoneNumber);
executorService = Executors.newFixedThreadPool(2);
executorService.execute(()-> {
Database.getUserDao().insertUser(newUser);
});
Toast.makeText(this, "Registration successful!", Toast.LENGTH_SHORT).show();
// Start MainActivity na succesvolle registratie
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
finish(); // Sluit de SignupActivity om terugkeren te voorkomen
} else {
// Geef een foutmelding als de wachtwoorden niet overeenkomen
Toast.makeText(this, "Passwords do not match!", Toast.LENGTH_SHORT).show();
}
}
private void navigateToLogin() {
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
finish(); // Sluit de huidige activiteit (SignupActivity) na navigatie
}
}
|
137241_1 | package com.example.villoapp.Views;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.villoapp.Model.DatabaseHelper;
import com.example.villoapp.Model.MainActivity;
import com.example.villoapp.R;
import com.example.villoapp.Model.User;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SignupActivity extends AppCompatActivity {
private DatabaseHelper Database;
private ExecutorService executorService;
private EditText emailEditText, passwordEditText, confirmPasswordEditText,
firstNameEditText, lastNameEditText, phoneNumberEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
// Vind de invoervelden door hun id's
emailEditText = findViewById(R.id.signup_email);
passwordEditText = findViewById(R.id.signup_password);
confirmPasswordEditText = findViewById(R.id.signup_confirm);
firstNameEditText = findViewById(R.id.signup_firstName);
lastNameEditText = findViewById(R.id.signup_lastName);
phoneNumberEditText = findViewById(R.id.signup_phoneNumber);
Button signupButton = findViewById(R.id.signup_button);
signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Hier zal het registratieproces worden gestart
registerUser();
}
});
TextView loginRedirectText = findViewById(R.id.loginRedirectText);
loginRedirectText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigateToLogin(); // Functie om naar de loginpagina te navigeren
}
});
}
private void registerUser() {
// Haal gegevens op uit de invoervelden
Database = DatabaseHelper.getInstance(getApplicationContext());
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
String firstName = firstNameEditText.getText().toString();
String lastName = lastNameEditText.getText().toString();
String phoneNumber = phoneNumberEditText.getText().toString();
// Controleer of alle velden zijn ingevuld voordat je doorgaat met registreren
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)
|| TextUtils.isEmpty(firstName) || TextUtils.isEmpty(lastName) || TextUtils.isEmpty(phoneNumber)) {
Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show();
return;
}
// Controleer of de wachtwoorden overeenkomen
if (password.equals(confirmPassword)) {
// Maak een User-object aan met de ingevoerde gegevens
User newUser = new User(email, password, firstName, lastName, phoneNumber);
executorService = Executors.newFixedThreadPool(2);
executorService.execute(()-> {
Database.getUserDao().insertUser(newUser);
});
Toast.makeText(this, "Registration successful!", Toast.LENGTH_SHORT).show();
// Start MainActivity na succesvolle registratie
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
finish(); // Sluit de SignupActivity om terugkeren te voorkomen
} else {
// Geef een foutmelding als de wachtwoorden niet overeenkomen
Toast.makeText(this, "Passwords do not match!", Toast.LENGTH_SHORT).show();
}
}
private void navigateToLogin() {
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
finish(); // Sluit de huidige activiteit (SignupActivity) na navigatie
}
}
| 2speef10/VilloApp | app/src/main/java/com/example/villoapp/Views/SignupActivity.java | 964 | // Hier zal het registratieproces worden gestart | line_comment | nl | package com.example.villoapp.Views;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.villoapp.Model.DatabaseHelper;
import com.example.villoapp.Model.MainActivity;
import com.example.villoapp.R;
import com.example.villoapp.Model.User;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SignupActivity extends AppCompatActivity {
private DatabaseHelper Database;
private ExecutorService executorService;
private EditText emailEditText, passwordEditText, confirmPasswordEditText,
firstNameEditText, lastNameEditText, phoneNumberEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
// Vind de invoervelden door hun id's
emailEditText = findViewById(R.id.signup_email);
passwordEditText = findViewById(R.id.signup_password);
confirmPasswordEditText = findViewById(R.id.signup_confirm);
firstNameEditText = findViewById(R.id.signup_firstName);
lastNameEditText = findViewById(R.id.signup_lastName);
phoneNumberEditText = findViewById(R.id.signup_phoneNumber);
Button signupButton = findViewById(R.id.signup_button);
signupButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Hier <SUF>
registerUser();
}
});
TextView loginRedirectText = findViewById(R.id.loginRedirectText);
loginRedirectText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigateToLogin(); // Functie om naar de loginpagina te navigeren
}
});
}
private void registerUser() {
// Haal gegevens op uit de invoervelden
Database = DatabaseHelper.getInstance(getApplicationContext());
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
String firstName = firstNameEditText.getText().toString();
String lastName = lastNameEditText.getText().toString();
String phoneNumber = phoneNumberEditText.getText().toString();
// Controleer of alle velden zijn ingevuld voordat je doorgaat met registreren
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)
|| TextUtils.isEmpty(firstName) || TextUtils.isEmpty(lastName) || TextUtils.isEmpty(phoneNumber)) {
Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show();
return;
}
// Controleer of de wachtwoorden overeenkomen
if (password.equals(confirmPassword)) {
// Maak een User-object aan met de ingevoerde gegevens
User newUser = new User(email, password, firstName, lastName, phoneNumber);
executorService = Executors.newFixedThreadPool(2);
executorService.execute(()-> {
Database.getUserDao().insertUser(newUser);
});
Toast.makeText(this, "Registration successful!", Toast.LENGTH_SHORT).show();
// Start MainActivity na succesvolle registratie
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
finish(); // Sluit de SignupActivity om terugkeren te voorkomen
} else {
// Geef een foutmelding als de wachtwoorden niet overeenkomen
Toast.makeText(this, "Passwords do not match!", Toast.LENGTH_SHORT).show();
}
}
private void navigateToLogin() {
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
finish(); // Sluit de huidige activiteit (SignupActivity) na navigatie
}
}
|
10427_14 | package controller;
import java.util.Calendar;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import model.PrIS;
import model.klas.Klas;
import model.persoon.Student;
import server.Conversation;
import server.Handler;
public class MedestudentenController implements Handler {
private PrIS informatieSysteem;
/**
* De StudentController klasse moet alle student-gerelateerde aanvragen
* afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat
* dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI
* een nieuwe methode schrijven.
*
* @param infoSys - het toegangspunt tot het domeinmodel
*/
public MedestudentenController(PrIS infoSys) {
informatieSysteem = infoSys;
}
public void handle(Conversation conversation) {
if (conversation.getRequestedURI().startsWith("/student/medestudenten/ophalen")) {
ophalen(conversation);
} else {
opslaan(conversation);
}
}
/**
* Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden
* de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden
* dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/
private void ophalen(Conversation conversation) {
JsonObject lJsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String lGebruikersnaam = lJsonObjectIn.getString("username");
Student lStudentZelf = informatieSysteem.getStudent(lGebruikersnaam);
String lGroepIdZelf = lStudentZelf.getGroepId();
Klas lKlas = informatieSysteem.getKlasVanStudent(lStudentZelf); // klas van de student opzoeken
List<Student> lStudentenVanKlas = lKlas.getStudenten(); // medestudenten opzoeken
JsonArrayBuilder lJsonArrayBuilder = Json.createArrayBuilder(); // Uiteindelijk gaat er een array...
for (Student lMedeStudent : lStudentenVanKlas) { // met daarin voor elke medestudent een JSON-object...
if (lMedeStudent == lStudentZelf) // behalve de student zelf...
continue;
else {
String lGroepIdAnder = lMedeStudent.getGroepId();
boolean lZelfdeGroep = ((lGroepIdZelf != "") && (lGroepIdAnder==lGroepIdZelf));
JsonObjectBuilder lJsonObjectBuilderVoorStudent = Json.createObjectBuilder(); // maak het JsonObject voor een student
String lLastName = lMedeStudent.getVolledigeAchternaam();
lJsonObjectBuilderVoorStudent
.add("id", lMedeStudent.getStudentNummer()) //vul het JsonObject
.add("firstName", lMedeStudent.getVoornaam())
.add("lastName", lLastName)
.add("sameGroup", lZelfdeGroep);
lJsonArrayBuilder.add(lJsonObjectBuilderVoorStudent); //voeg het JsonObject aan het array toe
}
}
String lJsonOutStr = lJsonArrayBuilder.build().toString(); // maak er een string van
conversation.sendJSONMessage(lJsonOutStr); // string gaat terug naar de Polymer-GUI!
}
/**
* Deze methode haalt eerst de opgestuurde JSON-data op. Op basis van deze gegevens
* het domeinmodel gewijzigd. Een eventuele errorcode wordt tenslotte
* weer (als JSON) teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/
private void opslaan(Conversation conversation) {
JsonObject lJsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String lGebruikersnaam = lJsonObjectIn.getString("username");
Student lStudent = informatieSysteem.getStudent(lGebruikersnaam);
//Het lJsonObjectIn bevat niet enkel strings maar ook een heel (Json) array van Json-objecten.
// in dat Json-object zijn telkens het studentnummer en een indicatie of de student
// tot het zelfde team hoort opgenomen.
//Het Json-array heeft als naam: "groupMembers"
JsonArray lGroepMembers_jArray = lJsonObjectIn.getJsonArray("groupMembers");
if (lGroepMembers_jArray != null) {
// bepaal op basis van de huidige tijd een unieke string
Calendar lCal = Calendar.getInstance();
long lMilliSeconds = lCal.getTimeInMillis();
String lGroepId = String.valueOf(lMilliSeconds);
lStudent.setGroepId(lGroepId);
for (int i=0;i<lGroepMembers_jArray.size();i++){
JsonObject lGroepMember_jsonObj = lGroepMembers_jArray.getJsonObject(i );
int lStudentNummer = lGroepMember_jsonObj.getInt("id");
boolean lZelfdeGroep = lGroepMember_jsonObj.getBoolean("sameGroup");
if (lZelfdeGroep) {
Student lGroepStudent = informatieSysteem.getStudent(lStudentNummer);
lGroepStudent.setGroepId(lGroepId);
}
}
}
JsonObjectBuilder lJob = Json.createObjectBuilder();
lJob.add("errorcode", 0);
//nothing to return use only errorcode to signal: ready!
String lJsonOutStr = lJob.build().toString();
conversation.sendJSONMessage(lJsonOutStr); // terug naar de Polymer-GUI!
}
}
| 3YH/GP_Startapplicatie | src/controller/MedestudentenController.java | 1,446 | // in dat Json-object zijn telkens het studentnummer en een indicatie of de student | line_comment | nl | package controller;
import java.util.Calendar;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import model.PrIS;
import model.klas.Klas;
import model.persoon.Student;
import server.Conversation;
import server.Handler;
public class MedestudentenController implements Handler {
private PrIS informatieSysteem;
/**
* De StudentController klasse moet alle student-gerelateerde aanvragen
* afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat
* dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI
* een nieuwe methode schrijven.
*
* @param infoSys - het toegangspunt tot het domeinmodel
*/
public MedestudentenController(PrIS infoSys) {
informatieSysteem = infoSys;
}
public void handle(Conversation conversation) {
if (conversation.getRequestedURI().startsWith("/student/medestudenten/ophalen")) {
ophalen(conversation);
} else {
opslaan(conversation);
}
}
/**
* Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden
* de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden
* dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/
private void ophalen(Conversation conversation) {
JsonObject lJsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String lGebruikersnaam = lJsonObjectIn.getString("username");
Student lStudentZelf = informatieSysteem.getStudent(lGebruikersnaam);
String lGroepIdZelf = lStudentZelf.getGroepId();
Klas lKlas = informatieSysteem.getKlasVanStudent(lStudentZelf); // klas van de student opzoeken
List<Student> lStudentenVanKlas = lKlas.getStudenten(); // medestudenten opzoeken
JsonArrayBuilder lJsonArrayBuilder = Json.createArrayBuilder(); // Uiteindelijk gaat er een array...
for (Student lMedeStudent : lStudentenVanKlas) { // met daarin voor elke medestudent een JSON-object...
if (lMedeStudent == lStudentZelf) // behalve de student zelf...
continue;
else {
String lGroepIdAnder = lMedeStudent.getGroepId();
boolean lZelfdeGroep = ((lGroepIdZelf != "") && (lGroepIdAnder==lGroepIdZelf));
JsonObjectBuilder lJsonObjectBuilderVoorStudent = Json.createObjectBuilder(); // maak het JsonObject voor een student
String lLastName = lMedeStudent.getVolledigeAchternaam();
lJsonObjectBuilderVoorStudent
.add("id", lMedeStudent.getStudentNummer()) //vul het JsonObject
.add("firstName", lMedeStudent.getVoornaam())
.add("lastName", lLastName)
.add("sameGroup", lZelfdeGroep);
lJsonArrayBuilder.add(lJsonObjectBuilderVoorStudent); //voeg het JsonObject aan het array toe
}
}
String lJsonOutStr = lJsonArrayBuilder.build().toString(); // maak er een string van
conversation.sendJSONMessage(lJsonOutStr); // string gaat terug naar de Polymer-GUI!
}
/**
* Deze methode haalt eerst de opgestuurde JSON-data op. Op basis van deze gegevens
* het domeinmodel gewijzigd. Een eventuele errorcode wordt tenslotte
* weer (als JSON) teruggestuurd naar de Polymer-GUI!
*
* @param conversation - alle informatie over het request
*/
private void opslaan(Conversation conversation) {
JsonObject lJsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
String lGebruikersnaam = lJsonObjectIn.getString("username");
Student lStudent = informatieSysteem.getStudent(lGebruikersnaam);
//Het lJsonObjectIn bevat niet enkel strings maar ook een heel (Json) array van Json-objecten.
// in da<SUF>
// tot het zelfde team hoort opgenomen.
//Het Json-array heeft als naam: "groupMembers"
JsonArray lGroepMembers_jArray = lJsonObjectIn.getJsonArray("groupMembers");
if (lGroepMembers_jArray != null) {
// bepaal op basis van de huidige tijd een unieke string
Calendar lCal = Calendar.getInstance();
long lMilliSeconds = lCal.getTimeInMillis();
String lGroepId = String.valueOf(lMilliSeconds);
lStudent.setGroepId(lGroepId);
for (int i=0;i<lGroepMembers_jArray.size();i++){
JsonObject lGroepMember_jsonObj = lGroepMembers_jArray.getJsonObject(i );
int lStudentNummer = lGroepMember_jsonObj.getInt("id");
boolean lZelfdeGroep = lGroepMember_jsonObj.getBoolean("sameGroup");
if (lZelfdeGroep) {
Student lGroepStudent = informatieSysteem.getStudent(lStudentNummer);
lGroepStudent.setGroepId(lGroepId);
}
}
}
JsonObjectBuilder lJob = Json.createObjectBuilder();
lJob.add("errorcode", 0);
//nothing to return use only errorcode to signal: ready!
String lJsonOutStr = lJob.build().toString();
conversation.sendJSONMessage(lJsonOutStr); // terug naar de Polymer-GUI!
}
}
|
135543_0 | package com.yannickhj.ohwdash.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Date;
//Aanmaken entiteit en dmv. Hibernate annotaties aanmaken in de database
@Entity
@Table(name = "signs")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class Sign {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
@NotBlank
private String locatienummer;
private String soort;
private String grootte;
private String biestekst;
private String plaats;
private String gemeente;
private String straatnaam;
private String route;
private int xcord;
private int ycord;
private Boolean onderhoud=false;
private String controleur;
private String acties;
@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLocatienummer() {
return locatienummer;
}
public void setLocatienummer(String locatienummer) {
this.locatienummer = locatienummer;
}
public String getSoort() {
return soort;
}
public void setSoort(String soort) {
this.soort = soort;
}
public String getGrootte() {
return grootte;
}
public void setGrootte(String grootte) {
this.grootte = grootte;
}
public String getBiestekst() {
return biestekst;
}
public void setBiestekst(String biestekst) {
this.biestekst = biestekst;
}
public String getPlaats() {
return plaats;
}
public void setPlaats(String plaats) {
this.plaats = plaats;
}
public String getGemeente() {
return gemeente;
}
public void setGemeente(String gemeente) {
this.gemeente = gemeente;
}
public String getStraatnaam() {
return straatnaam;
}
public void setStraatnaam(String straatnaam) {
this.straatnaam = straatnaam;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public int getXcord() {
return xcord;
}
public void setXcord(int xcord) {
this.xcord = xcord;
}
public int getYcord() {
return ycord;
}
public void setYcord(int ycord) {
this.ycord = ycord;
}
public Boolean getOnderhoud() {
return onderhoud;
}
public void setOnderhoud(Boolean onderhoud) {
this.onderhoud = onderhoud;
}
public String getControleur() {
return controleur;
}
public void setControleur(String controleur) {
this.controleur = controleur;
}
public String getActies() {
return acties;
}
public void setActies(String acties) {
this.acties = acties;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
| 3YH/ohw_dashboard | src/main/java/com/yannickhj/ohwdash/model/Sign.java | 1,036 | //Aanmaken entiteit en dmv. Hibernate annotaties aanmaken in de database | line_comment | nl | package com.yannickhj.ohwdash.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Date;
//Aanma<SUF>
@Entity
@Table(name = "signs")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class Sign {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
@NotBlank
private String locatienummer;
private String soort;
private String grootte;
private String biestekst;
private String plaats;
private String gemeente;
private String straatnaam;
private String route;
private int xcord;
private int ycord;
private Boolean onderhoud=false;
private String controleur;
private String acties;
@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLocatienummer() {
return locatienummer;
}
public void setLocatienummer(String locatienummer) {
this.locatienummer = locatienummer;
}
public String getSoort() {
return soort;
}
public void setSoort(String soort) {
this.soort = soort;
}
public String getGrootte() {
return grootte;
}
public void setGrootte(String grootte) {
this.grootte = grootte;
}
public String getBiestekst() {
return biestekst;
}
public void setBiestekst(String biestekst) {
this.biestekst = biestekst;
}
public String getPlaats() {
return plaats;
}
public void setPlaats(String plaats) {
this.plaats = plaats;
}
public String getGemeente() {
return gemeente;
}
public void setGemeente(String gemeente) {
this.gemeente = gemeente;
}
public String getStraatnaam() {
return straatnaam;
}
public void setStraatnaam(String straatnaam) {
this.straatnaam = straatnaam;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public int getXcord() {
return xcord;
}
public void setXcord(int xcord) {
this.xcord = xcord;
}
public int getYcord() {
return ycord;
}
public void setYcord(int ycord) {
this.ycord = ycord;
}
public Boolean getOnderhoud() {
return onderhoud;
}
public void setOnderhoud(Boolean onderhoud) {
this.onderhoud = onderhoud;
}
public String getControleur() {
return controleur;
}
public void setControleur(String controleur) {
this.controleur = controleur;
}
public String getActies() {
return acties;
}
public void setActies(String acties) {
this.acties = acties;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
|
59316_7 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.1 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2018.11.18 um 03:45:53 PM CET
//
package net.opengis.kml._2;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für LineStringType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="LineStringType">
* <complexContent>
* <extension base="{http://www.opengis.net/kml/2.2}AbstractGeometryType">
* <sequence>
* <element ref="{http://www.opengis.net/kml/2.2}extrude" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}tessellate" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}altitudeModeGroup" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}coordinates" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}LineStringSimpleExtensionGroup" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}LineStringObjectExtensionGroup" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LineStringType", propOrder = {
"extrude",
"tessellate",
"altitudeModeGroup",
"coordinates",
"lineStringSimpleExtensionGroup",
"lineStringObjectExtensionGroup"
})
public class LineStringType
extends AbstractGeometryType
{
@XmlElement(defaultValue = "0")
protected Boolean extrude;
@XmlElement(defaultValue = "0")
protected Boolean tessellate;
@XmlElementRef(name = "altitudeModeGroup", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false)
protected JAXBElement<?> altitudeModeGroup;
@XmlList
protected List<String> coordinates;
@XmlElement(name = "LineStringSimpleExtensionGroup")
protected List<Object> lineStringSimpleExtensionGroup;
@XmlElement(name = "LineStringObjectExtensionGroup")
protected List<AbstractObjectType> lineStringObjectExtensionGroup;
/**
* Ruft den Wert der extrude-Eigenschaft ab.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isExtrude() {
return extrude;
}
/**
* Legt den Wert der extrude-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setExtrude(Boolean value) {
this.extrude = value;
}
public boolean isSetExtrude() {
return (this.extrude!= null);
}
/**
* Ruft den Wert der tessellate-Eigenschaft ab.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTessellate() {
return tessellate;
}
/**
* Legt den Wert der tessellate-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTessellate(Boolean value) {
this.tessellate = value;
}
public boolean isSetTessellate() {
return (this.tessellate!= null);
}
/**
* Ruft den Wert der altitudeModeGroup-Eigenschaft ab.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link AltitudeModeEnumType }{@code >}
* {@link JAXBElement }{@code <}{@link Object }{@code >}
*
*/
public JAXBElement<?> getAltitudeModeGroup() {
return altitudeModeGroup;
}
/**
* Legt den Wert der altitudeModeGroup-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link AltitudeModeEnumType }{@code >}
* {@link JAXBElement }{@code <}{@link Object }{@code >}
*
*/
public void setAltitudeModeGroup(JAXBElement<?> value) {
this.altitudeModeGroup = value;
}
public boolean isSetAltitudeModeGroup() {
return (this.altitudeModeGroup!= null);
}
/**
* Gets the value of the coordinates property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the coordinates property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCoordinates().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getCoordinates() {
if (coordinates == null) {
coordinates = new ArrayList<String>();
}
return this.coordinates;
}
public boolean isSetCoordinates() {
return ((this.coordinates!= null)&&(!this.coordinates.isEmpty()));
}
public void unsetCoordinates() {
this.coordinates = null;
}
/**
* Gets the value of the lineStringSimpleExtensionGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineStringSimpleExtensionGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineStringSimpleExtensionGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Object }
*
*
*/
public List<Object> getLineStringSimpleExtensionGroup() {
if (lineStringSimpleExtensionGroup == null) {
lineStringSimpleExtensionGroup = new ArrayList<Object>();
}
return this.lineStringSimpleExtensionGroup;
}
public boolean isSetLineStringSimpleExtensionGroup() {
return ((this.lineStringSimpleExtensionGroup!= null)&&(!this.lineStringSimpleExtensionGroup.isEmpty()));
}
public void unsetLineStringSimpleExtensionGroup() {
this.lineStringSimpleExtensionGroup = null;
}
/**
* Gets the value of the lineStringObjectExtensionGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineStringObjectExtensionGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineStringObjectExtensionGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AbstractObjectType }
*
*
*/
public List<AbstractObjectType> getLineStringObjectExtensionGroup() {
if (lineStringObjectExtensionGroup == null) {
lineStringObjectExtensionGroup = new ArrayList<AbstractObjectType>();
}
return this.lineStringObjectExtensionGroup;
}
public boolean isSetLineStringObjectExtensionGroup() {
return ((this.lineStringObjectExtensionGroup!= null)&&(!this.lineStringObjectExtensionGroup.isEmpty()));
}
public void unsetLineStringObjectExtensionGroup() {
this.lineStringObjectExtensionGroup = null;
}
public void setCoordinates(List<String> value) {
this.coordinates = value;
}
public void setLineStringSimpleExtensionGroup(List<Object> value) {
this.lineStringSimpleExtensionGroup = value;
}
public void setLineStringObjectExtensionGroup(List<AbstractObjectType> value) {
this.lineStringObjectExtensionGroup = value;
}
}
| 3dcitydb/importer-exporter | impexp-vis-plugin/src-gen/main/java/net/opengis/kml/_2/LineStringType.java | 2,447 | /**
* Legt den Wert der extrude-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/ | block_comment | nl | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.1 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2018.11.18 um 03:45:53 PM CET
//
package net.opengis.kml._2;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für LineStringType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="LineStringType">
* <complexContent>
* <extension base="{http://www.opengis.net/kml/2.2}AbstractGeometryType">
* <sequence>
* <element ref="{http://www.opengis.net/kml/2.2}extrude" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}tessellate" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}altitudeModeGroup" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}coordinates" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}LineStringSimpleExtensionGroup" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://www.opengis.net/kml/2.2}LineStringObjectExtensionGroup" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LineStringType", propOrder = {
"extrude",
"tessellate",
"altitudeModeGroup",
"coordinates",
"lineStringSimpleExtensionGroup",
"lineStringObjectExtensionGroup"
})
public class LineStringType
extends AbstractGeometryType
{
@XmlElement(defaultValue = "0")
protected Boolean extrude;
@XmlElement(defaultValue = "0")
protected Boolean tessellate;
@XmlElementRef(name = "altitudeModeGroup", namespace = "http://www.opengis.net/kml/2.2", type = JAXBElement.class, required = false)
protected JAXBElement<?> altitudeModeGroup;
@XmlList
protected List<String> coordinates;
@XmlElement(name = "LineStringSimpleExtensionGroup")
protected List<Object> lineStringSimpleExtensionGroup;
@XmlElement(name = "LineStringObjectExtensionGroup")
protected List<AbstractObjectType> lineStringObjectExtensionGroup;
/**
* Ruft den Wert der extrude-Eigenschaft ab.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isExtrude() {
return extrude;
}
/**
* Legt d<SUF>*/
public void setExtrude(Boolean value) {
this.extrude = value;
}
public boolean isSetExtrude() {
return (this.extrude!= null);
}
/**
* Ruft den Wert der tessellate-Eigenschaft ab.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTessellate() {
return tessellate;
}
/**
* Legt den Wert der tessellate-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTessellate(Boolean value) {
this.tessellate = value;
}
public boolean isSetTessellate() {
return (this.tessellate!= null);
}
/**
* Ruft den Wert der altitudeModeGroup-Eigenschaft ab.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link AltitudeModeEnumType }{@code >}
* {@link JAXBElement }{@code <}{@link Object }{@code >}
*
*/
public JAXBElement<?> getAltitudeModeGroup() {
return altitudeModeGroup;
}
/**
* Legt den Wert der altitudeModeGroup-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link AltitudeModeEnumType }{@code >}
* {@link JAXBElement }{@code <}{@link Object }{@code >}
*
*/
public void setAltitudeModeGroup(JAXBElement<?> value) {
this.altitudeModeGroup = value;
}
public boolean isSetAltitudeModeGroup() {
return (this.altitudeModeGroup!= null);
}
/**
* Gets the value of the coordinates property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the coordinates property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCoordinates().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getCoordinates() {
if (coordinates == null) {
coordinates = new ArrayList<String>();
}
return this.coordinates;
}
public boolean isSetCoordinates() {
return ((this.coordinates!= null)&&(!this.coordinates.isEmpty()));
}
public void unsetCoordinates() {
this.coordinates = null;
}
/**
* Gets the value of the lineStringSimpleExtensionGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineStringSimpleExtensionGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineStringSimpleExtensionGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Object }
*
*
*/
public List<Object> getLineStringSimpleExtensionGroup() {
if (lineStringSimpleExtensionGroup == null) {
lineStringSimpleExtensionGroup = new ArrayList<Object>();
}
return this.lineStringSimpleExtensionGroup;
}
public boolean isSetLineStringSimpleExtensionGroup() {
return ((this.lineStringSimpleExtensionGroup!= null)&&(!this.lineStringSimpleExtensionGroup.isEmpty()));
}
public void unsetLineStringSimpleExtensionGroup() {
this.lineStringSimpleExtensionGroup = null;
}
/**
* Gets the value of the lineStringObjectExtensionGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineStringObjectExtensionGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineStringObjectExtensionGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AbstractObjectType }
*
*
*/
public List<AbstractObjectType> getLineStringObjectExtensionGroup() {
if (lineStringObjectExtensionGroup == null) {
lineStringObjectExtensionGroup = new ArrayList<AbstractObjectType>();
}
return this.lineStringObjectExtensionGroup;
}
public boolean isSetLineStringObjectExtensionGroup() {
return ((this.lineStringObjectExtensionGroup!= null)&&(!this.lineStringObjectExtensionGroup.isEmpty()));
}
public void unsetLineStringObjectExtensionGroup() {
this.lineStringObjectExtensionGroup = null;
}
public void setCoordinates(List<String> value) {
this.coordinates = value;
}
public void setLineStringSimpleExtensionGroup(List<Object> value) {
this.lineStringSimpleExtensionGroup = value;
}
public void setLineStringObjectExtensionGroup(List<AbstractObjectType> value) {
this.lineStringObjectExtensionGroup = value;
}
}
|
105013_3 | public class KiwiTester
{
public static void main(String[] args)
{
// testing both null and normal constructor
KiwiBird kiwi1 = new KiwiBird();
KiwiBird kiwi2 = new KiwiBird("Alexa", 15.0, "Brown Kiwi", "Male", "Coromandel", 10.0, 4);
// testing all accessors
System.out.println("kiwi1 name should be default: " + kiwi1.getName() );
System.out.println("kiwi1 species should be default: " + kiwi1.getSpecies() );
System.out.println("kiwi1 size should be default: " + kiwi1.getSize() );
System.out.println("kiwi1 gender should be default: " + kiwi1.getGender());
System.out.println("kiwi1 subSpecies should be default: " + kiwi1.getSubSpecies());
System.out.println("kiwi1 wingSize should be default: " + kiwi1.getWingSize());
System.out.println("kiwi1 beakSize should be default: " + kiwi1.getBeakSize());
// testing all mutators
System.out.println("Setting kiwi1's name to be John...");
kiwi1.setName("John");
System.out.println("kiwi1's name is now " + kiwi1.getName() );
System.out.println("Setting kiwi1's gender to be female...");
kiwi1.setGender("Female");
System.out.println("kiwi1's gender is now " + kiwi1.getGender() );
System.out.println("Setting kiwi1's species to be Tokoeka Kiwi...");
kiwi1.setSpecies("Tokoeka Kiwi");
System.out.println("kiwi1's species is now " + kiwi1.getSpecies() );
System.out.println("Setting kiwi1's subspecies to be Haast...");
kiwi1.setSubSpecies("Haast");
System.out.println("kiwi1's subspecies is now " + kiwi1.getSubSpecies() );
System.out.println("Setting kiwi1's size to be 27.0...");
kiwi1.setSize(27);
System.out.println("kiwi1's size is now " + kiwi1.getSize() );
System.out.println("Unreasonable value -7 being inputted into size, beakSize, and wingSize...");
kiwi1.setSize(-7);
kiwi1.setBeakSize(-7);
kiwi1.setWingSize(-7);
System.out.println("kiwi1's size, beak size, and wingsize are now " + kiwi1.getSize() + ", " + kiwi1.getWingSize() +
", " + kiwi1.getBeakSize());
System.out.println("Empty string name being inputted...");
kiwi1.setName("");
System.out.println("kiwi1's name is now " + kiwi1.getName() );
// testing void methods
System.out.println("Testing eat, makeSound, and layEgg methods...");
System.out.println(kiwi1.getName() + ", eat!");
kiwi1.eat();
System.out.println(kiwi1.getName() + ", Speak!");
kiwi1.makeSound();
System.out.println("Testing makeSound(4)...");
kiwi1.makeSound(4);
System.out.println(kiwi1.getName() + ", lay an egg!");
kiwi1.layEgg();
System.out.println("Testing toString()...");
System.out.println(kiwi1);
System.out.println("\nTesting Kiwi2\n");
System.out.println("kiwi2 name should be \"Alexa\": " + kiwi2.getName() );
System.out.println("kiwi2 species should be \"Brown Kiwi\": " + kiwi2.getSpecies() );
System.out.println("kiwi2 size should be 15.0: " + kiwi2.getSize() );
System.out.println("kiwi2 gender should be male: " + kiwi2.getGender());
System.out.println("kiwi2 subSpecies should be \"Coromandel\": " + kiwi2.getSubSpecies());
System.out.println("kiwi2 wingSize should be 10.0: " + kiwi2.getWingSize());
System.out.println("kiwi2 beakSize should be 4: " + kiwi2.getBeakSize());
System.out.println("Testing eat, makeSound, and layEgg methods...");
System.out.println(kiwi2.getName() + ", eat!");
kiwi2.eat();
System.out.println(kiwi2.getName() + ", Speak!");
kiwi2.makeSound();
System.out.println("Testing makeSound(4)...");
kiwi2.makeSound(4);
System.out.println(kiwi2.getName() + ", lay an egg!");
kiwi2.layEgg();
System.out.println("Testing toString()...");
System.out.println(kiwi2);
}
}
| 3zachm/APCS-Misc | Pre-AP/KiwiBird/KiwiTester.java | 1,196 | // testing void methods | line_comment | nl | public class KiwiTester
{
public static void main(String[] args)
{
// testing both null and normal constructor
KiwiBird kiwi1 = new KiwiBird();
KiwiBird kiwi2 = new KiwiBird("Alexa", 15.0, "Brown Kiwi", "Male", "Coromandel", 10.0, 4);
// testing all accessors
System.out.println("kiwi1 name should be default: " + kiwi1.getName() );
System.out.println("kiwi1 species should be default: " + kiwi1.getSpecies() );
System.out.println("kiwi1 size should be default: " + kiwi1.getSize() );
System.out.println("kiwi1 gender should be default: " + kiwi1.getGender());
System.out.println("kiwi1 subSpecies should be default: " + kiwi1.getSubSpecies());
System.out.println("kiwi1 wingSize should be default: " + kiwi1.getWingSize());
System.out.println("kiwi1 beakSize should be default: " + kiwi1.getBeakSize());
// testing all mutators
System.out.println("Setting kiwi1's name to be John...");
kiwi1.setName("John");
System.out.println("kiwi1's name is now " + kiwi1.getName() );
System.out.println("Setting kiwi1's gender to be female...");
kiwi1.setGender("Female");
System.out.println("kiwi1's gender is now " + kiwi1.getGender() );
System.out.println("Setting kiwi1's species to be Tokoeka Kiwi...");
kiwi1.setSpecies("Tokoeka Kiwi");
System.out.println("kiwi1's species is now " + kiwi1.getSpecies() );
System.out.println("Setting kiwi1's subspecies to be Haast...");
kiwi1.setSubSpecies("Haast");
System.out.println("kiwi1's subspecies is now " + kiwi1.getSubSpecies() );
System.out.println("Setting kiwi1's size to be 27.0...");
kiwi1.setSize(27);
System.out.println("kiwi1's size is now " + kiwi1.getSize() );
System.out.println("Unreasonable value -7 being inputted into size, beakSize, and wingSize...");
kiwi1.setSize(-7);
kiwi1.setBeakSize(-7);
kiwi1.setWingSize(-7);
System.out.println("kiwi1's size, beak size, and wingsize are now " + kiwi1.getSize() + ", " + kiwi1.getWingSize() +
", " + kiwi1.getBeakSize());
System.out.println("Empty string name being inputted...");
kiwi1.setName("");
System.out.println("kiwi1's name is now " + kiwi1.getName() );
// testi<SUF>
System.out.println("Testing eat, makeSound, and layEgg methods...");
System.out.println(kiwi1.getName() + ", eat!");
kiwi1.eat();
System.out.println(kiwi1.getName() + ", Speak!");
kiwi1.makeSound();
System.out.println("Testing makeSound(4)...");
kiwi1.makeSound(4);
System.out.println(kiwi1.getName() + ", lay an egg!");
kiwi1.layEgg();
System.out.println("Testing toString()...");
System.out.println(kiwi1);
System.out.println("\nTesting Kiwi2\n");
System.out.println("kiwi2 name should be \"Alexa\": " + kiwi2.getName() );
System.out.println("kiwi2 species should be \"Brown Kiwi\": " + kiwi2.getSpecies() );
System.out.println("kiwi2 size should be 15.0: " + kiwi2.getSize() );
System.out.println("kiwi2 gender should be male: " + kiwi2.getGender());
System.out.println("kiwi2 subSpecies should be \"Coromandel\": " + kiwi2.getSubSpecies());
System.out.println("kiwi2 wingSize should be 10.0: " + kiwi2.getWingSize());
System.out.println("kiwi2 beakSize should be 4: " + kiwi2.getBeakSize());
System.out.println("Testing eat, makeSound, and layEgg methods...");
System.out.println(kiwi2.getName() + ", eat!");
kiwi2.eat();
System.out.println(kiwi2.getName() + ", Speak!");
kiwi2.makeSound();
System.out.println("Testing makeSound(4)...");
kiwi2.makeSound(4);
System.out.println(kiwi2.getName() + ", lay an egg!");
kiwi2.layEgg();
System.out.println("Testing toString()...");
System.out.println(kiwi2);
}
}
|
16743_1 | /* Voorraadbeheer maakt alle objecten van Medicijn aan.
* Note: De aangemaakte medicijn objecten hebben geen naam. Ze worden binnen
* een arraylist aangemaakt, dus we gebruiken steeds de index om een object van Medicijn
* te benaderen.
* Het geeft wel vele voordelen zoals bijvoorbeeld iteratief een lijst van objecten
* te doorlopen.
*
* Voorraadbeheer houdt ook een lijst van bestellingen bij. De lijst met te bestellen medicijnen wordt
* voor ieder nieuw object van Bestelling aangemaakt. Dit maakt het eenvoudiger om de medicijnen te men
* bestelt te groeperen en bewerkingen op uit te voeren.
*
* Zie commentaar bij methodes voor details.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Voorraadbeheer {
static ArrayList<Medicijn> medlist = new ArrayList<Medicijn>();
static ArrayList<Bestelling> beslist = new ArrayList<Bestelling>();
static int besIndex; //In welk bestellingsobject binnen 'beslist' moet het volgend medicijn komen?
static Apotheker ap;
public Voorraadbeheer(){
}
//voegMedicijnToe voegt een nieuw object van Medicijn toe aan de lijst.
public static void voegMedicijnToe(String merknaam, String stofnaam, int aantal, int gewensteAantal, int minimaAantal, String fabrikant, int prijs, int kast, String houdbaarheid){
boolean isAanwezig=false;
for(int i=0; i<Voorraadbeheer.medlist.size();i++){
if (Voorraadbeheer.medlist.get(i).merknaam.equalsIgnoreCase(merknaam)){
Log.print();
System.out.println(merknaam+ " bestaat al en is niet toegevoegd.");
isAanwezig = true;
}
}
if(isAanwezig==false){
Voorraadbeheer.medlist.add(new Medicijn(merknaam, stofnaam, aantal, gewensteAantal, minimaAantal, fabrikant, prijs, kast, houdbaarheid));
Log.print();
System.out.println(merknaam + " is toegevoegd aan 'medlist'.");
}
}
//verwijderMedicijn zoekt naar overeenkomstige merknamen (in principe één hit max) en verwijdert dit object.
public static void verwijderMedicijn(String merknaam){
boolean gevonden=false;
for(int i=0; i<Voorraadbeheer.medlist.size();i++){
if (Voorraadbeheer.medlist.get(i).geefMerknaam().equalsIgnoreCase(merknaam))
Voorraadbeheer.medlist.remove(i);
gevonden=true;
}
if (gevonden==false)
Log.print();
System.out.println("Te verwijderen medicijn niet gevonden.");
}
//voegBestellingToe voegt een nieuw object van Bestelling toe aan de lijst.
public static void voegBestellingToe(){
Voorraadbeheer.beslist.add(new Bestelling());
Log.print();
System.out.println("Nieuw open bestelling toegevoegd.");
}
/*controleerOpTeBestellen zoekt op hoeveel medicijnen er te bestellen zijn en houdt rekening met het aantal dat reeds
besteld is en zich in een of ander bestellijst bevindt (dat nog niet is aangekomen).
*/
public static void controleerOpTeBestellen() throws ParseException, OrderException{
//Controleer al eerst eens of er een geschikt bestellingsobject bestaat om een medicijn in te plaatsen
//Op deze manier hoeven er geen meerdere bestellingen 'open' te staan.
if (Voorraadbeheer.controleerOpOpenBestelling()==1337){ //1337 is een arbitrair gekozen nummer. Int is nodig om de juiste bestellingslijstindex door te geven.
Log.print();
throw new OrderException("Geen open bestelling beschikbaar.");
}
besIndex= Voorraadbeheer.controleerOpOpenBestelling();
boolean ietsTeBestellen=false;
int controle=0;
int i;
for(i=0; i<Voorraadbeheer.medlist.size();i++){
controle=Voorraadbeheer.medlist.get(i).controleerOpBeide();
if(controle>0){
//we voegen medicijn toe indien attributen het toestaan. Verdere controle in methodes.
if(medlist.get(i).alGewaarschuwd==false && medlist.get(i).besteld==false){
ietsTeBestellen=true;
Voorraadbeheer.beslist.get(besIndex).voegMedicijnToe(besIndex, medlist.get(i).geefMerknaam(), controle, medlist.get(i).prijs);
medlist.get(i).besteld=true;
medlist.get(i).alGewaarschuwd=true;
}
}
}
if (ietsTeBestellen==false){
Log.print();
System.out.println("Er zijn geen nieuwe bestellingsitems toegevoegd.");
}
}
public static int controleerOpOpenBestelling() {
int i=1337;
for(int j=0; j<Voorraadbeheer.beslist.size();j++){
if (Voorraadbeheer.beslist.get(j).isBesteld()!=true && Voorraadbeheer.beslist.get(j).isBesteld()!=true)
i=j;
}
return i;
}
public static void importMedicijnen() throws FileNotFoundException{
String filename = "medicijnen.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
while (in.hasNextLine())
{
//1 Person per line
String line = in.nextLine();
// Make a Scanner object to break up this line into parts
Scanner lineBreaker = new Scanner(line);
try{
String merknaam = lineBreaker.next();
String stofnaam = lineBreaker.next();
int aantal = lineBreaker.nextInt();
int gewensteAantal = lineBreaker.nextInt();
int minimaAantal = lineBreaker.nextInt();
String fabrikant = lineBreaker.next();
int prijs = lineBreaker.nextInt();
int kast = lineBreaker.nextInt();
String houdbaarheid = lineBreaker.next();
lineBreaker.close();
Voorraadbeheer.voegMedicijnToe(merknaam, stofnaam, aantal, gewensteAantal, minimaAantal, fabrikant, prijs, kast, houdbaarheid);
}
catch (InputMismatchException e){
System.out.println("Onjuiste parametertype in medicijnen.txt");
}
catch (NoSuchElementException e){
System.out.println("File not found2");
}
}
in.close();
}
public static void writeToTXT(){
String filename= "medicijnen.txt";
try{
PrintWriter outputStream = new PrintWriter(filename);
for (int i =0;i<medlist.size();i++){
outputStream.print(medlist.get(i).merknaam+" ");
outputStream.print(medlist.get(i).stofnaam+" ");
outputStream.print(medlist.get(i).aantal+" ");
outputStream.print(medlist.get(i).gewensteAantal+" ");
outputStream.print(medlist.get(i).minimumAantal+" ");
outputStream.print(medlist.get(i).fabrikant+" ");
outputStream.print(medlist.get(i).prijs+" ");
outputStream.print(medlist.get(i).kastID+" ");
outputStream.println(medlist.get(i).houdbaarheid);
}
outputStream.close();
}catch (FileNotFoundException e){
}
}
}
| 4SDDeMeyerKaya/Voorraadbeheer4SD | src/Voorraadbeheer.java | 2,034 | //In welk bestellingsobject binnen 'beslist' moet het volgend medicijn komen?
| line_comment | nl | /* Voorraadbeheer maakt alle objecten van Medicijn aan.
* Note: De aangemaakte medicijn objecten hebben geen naam. Ze worden binnen
* een arraylist aangemaakt, dus we gebruiken steeds de index om een object van Medicijn
* te benaderen.
* Het geeft wel vele voordelen zoals bijvoorbeeld iteratief een lijst van objecten
* te doorlopen.
*
* Voorraadbeheer houdt ook een lijst van bestellingen bij. De lijst met te bestellen medicijnen wordt
* voor ieder nieuw object van Bestelling aangemaakt. Dit maakt het eenvoudiger om de medicijnen te men
* bestelt te groeperen en bewerkingen op uit te voeren.
*
* Zie commentaar bij methodes voor details.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Voorraadbeheer {
static ArrayList<Medicijn> medlist = new ArrayList<Medicijn>();
static ArrayList<Bestelling> beslist = new ArrayList<Bestelling>();
static int besIndex; //In we<SUF>
static Apotheker ap;
public Voorraadbeheer(){
}
//voegMedicijnToe voegt een nieuw object van Medicijn toe aan de lijst.
public static void voegMedicijnToe(String merknaam, String stofnaam, int aantal, int gewensteAantal, int minimaAantal, String fabrikant, int prijs, int kast, String houdbaarheid){
boolean isAanwezig=false;
for(int i=0; i<Voorraadbeheer.medlist.size();i++){
if (Voorraadbeheer.medlist.get(i).merknaam.equalsIgnoreCase(merknaam)){
Log.print();
System.out.println(merknaam+ " bestaat al en is niet toegevoegd.");
isAanwezig = true;
}
}
if(isAanwezig==false){
Voorraadbeheer.medlist.add(new Medicijn(merknaam, stofnaam, aantal, gewensteAantal, minimaAantal, fabrikant, prijs, kast, houdbaarheid));
Log.print();
System.out.println(merknaam + " is toegevoegd aan 'medlist'.");
}
}
//verwijderMedicijn zoekt naar overeenkomstige merknamen (in principe één hit max) en verwijdert dit object.
public static void verwijderMedicijn(String merknaam){
boolean gevonden=false;
for(int i=0; i<Voorraadbeheer.medlist.size();i++){
if (Voorraadbeheer.medlist.get(i).geefMerknaam().equalsIgnoreCase(merknaam))
Voorraadbeheer.medlist.remove(i);
gevonden=true;
}
if (gevonden==false)
Log.print();
System.out.println("Te verwijderen medicijn niet gevonden.");
}
//voegBestellingToe voegt een nieuw object van Bestelling toe aan de lijst.
public static void voegBestellingToe(){
Voorraadbeheer.beslist.add(new Bestelling());
Log.print();
System.out.println("Nieuw open bestelling toegevoegd.");
}
/*controleerOpTeBestellen zoekt op hoeveel medicijnen er te bestellen zijn en houdt rekening met het aantal dat reeds
besteld is en zich in een of ander bestellijst bevindt (dat nog niet is aangekomen).
*/
public static void controleerOpTeBestellen() throws ParseException, OrderException{
//Controleer al eerst eens of er een geschikt bestellingsobject bestaat om een medicijn in te plaatsen
//Op deze manier hoeven er geen meerdere bestellingen 'open' te staan.
if (Voorraadbeheer.controleerOpOpenBestelling()==1337){ //1337 is een arbitrair gekozen nummer. Int is nodig om de juiste bestellingslijstindex door te geven.
Log.print();
throw new OrderException("Geen open bestelling beschikbaar.");
}
besIndex= Voorraadbeheer.controleerOpOpenBestelling();
boolean ietsTeBestellen=false;
int controle=0;
int i;
for(i=0; i<Voorraadbeheer.medlist.size();i++){
controle=Voorraadbeheer.medlist.get(i).controleerOpBeide();
if(controle>0){
//we voegen medicijn toe indien attributen het toestaan. Verdere controle in methodes.
if(medlist.get(i).alGewaarschuwd==false && medlist.get(i).besteld==false){
ietsTeBestellen=true;
Voorraadbeheer.beslist.get(besIndex).voegMedicijnToe(besIndex, medlist.get(i).geefMerknaam(), controle, medlist.get(i).prijs);
medlist.get(i).besteld=true;
medlist.get(i).alGewaarschuwd=true;
}
}
}
if (ietsTeBestellen==false){
Log.print();
System.out.println("Er zijn geen nieuwe bestellingsitems toegevoegd.");
}
}
public static int controleerOpOpenBestelling() {
int i=1337;
for(int j=0; j<Voorraadbeheer.beslist.size();j++){
if (Voorraadbeheer.beslist.get(j).isBesteld()!=true && Voorraadbeheer.beslist.get(j).isBesteld()!=true)
i=j;
}
return i;
}
public static void importMedicijnen() throws FileNotFoundException{
String filename = "medicijnen.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
while (in.hasNextLine())
{
//1 Person per line
String line = in.nextLine();
// Make a Scanner object to break up this line into parts
Scanner lineBreaker = new Scanner(line);
try{
String merknaam = lineBreaker.next();
String stofnaam = lineBreaker.next();
int aantal = lineBreaker.nextInt();
int gewensteAantal = lineBreaker.nextInt();
int minimaAantal = lineBreaker.nextInt();
String fabrikant = lineBreaker.next();
int prijs = lineBreaker.nextInt();
int kast = lineBreaker.nextInt();
String houdbaarheid = lineBreaker.next();
lineBreaker.close();
Voorraadbeheer.voegMedicijnToe(merknaam, stofnaam, aantal, gewensteAantal, minimaAantal, fabrikant, prijs, kast, houdbaarheid);
}
catch (InputMismatchException e){
System.out.println("Onjuiste parametertype in medicijnen.txt");
}
catch (NoSuchElementException e){
System.out.println("File not found2");
}
}
in.close();
}
public static void writeToTXT(){
String filename= "medicijnen.txt";
try{
PrintWriter outputStream = new PrintWriter(filename);
for (int i =0;i<medlist.size();i++){
outputStream.print(medlist.get(i).merknaam+" ");
outputStream.print(medlist.get(i).stofnaam+" ");
outputStream.print(medlist.get(i).aantal+" ");
outputStream.print(medlist.get(i).gewensteAantal+" ");
outputStream.print(medlist.get(i).minimumAantal+" ");
outputStream.print(medlist.get(i).fabrikant+" ");
outputStream.print(medlist.get(i).prijs+" ");
outputStream.print(medlist.get(i).kastID+" ");
outputStream.println(medlist.get(i).houdbaarheid);
}
outputStream.close();
}catch (FileNotFoundException e){
}
}
}
|
26270_2 | package main;
import java.io.*;
import java.util.*;
class CurrentNotes {
private Vector currentNotes = null;
private PatchData patchData = null;
CurrentNotes (PatchData patchData){
Note note;
currentNotes = new Vector();
// Wil er standaard 2
note = new Note(64, 0, 0);
currentNotes.add(note);
note = new Note(64, 0, 0);
currentNotes.add(note);
this.patchData = patchData;
}
// Setters
public void addNotes(String params) {
Note note;
String[] paramArray = new String[4];
currentNotes.clear();
int newNote, newAttack, newRelease;
do {
paramArray = params.split(" ", 4);
newNote = Integer.parseInt(paramArray[0]);
newAttack = Integer.parseInt(paramArray[1]);
newRelease = Integer.parseInt(paramArray[2]);
params = paramArray[3];
note = new Note(newNote, newAttack, newRelease);
currentNotes.add(note);
} while (params.trim().length() > 0); // trim, omdat en nog een ' ' achter komt.
// Bij het compleet inlezen halen we de laatste weer weg. Deze wordt extra opgeslagen door de Clavia editor
currentNotes.removeElement(currentNotes.lastElement());
}
// Getters
public int getCurrentNoteSize() {
return currentNotes.size();
}
public Note getNote(int index) {
// Note note;
return (Note) currentNotes.get(index);
}
// Inlezen patch gegevens.
public void readCurrentNoteDump(BufferedReader pchFile) {
// String dummy;
try {
addNotes(pchFile.readLine());
}
catch(Exception e) {
System.out.println(e + " in readCurrentNoteDump");
}
}
// Creeren patch gegevens.
public StringBuffer createCurrentNoteDump(StringBuffer result) {
Note note = null;
// if (getCurrentNoteSize() > 0) {
result.append("[CurrentNoteDump]\r\n");
for (int i=0; i < getCurrentNoteSize(); i++) {
note = getNote(i);
result.append("" + note.getNote() + ' ' + note.getAttack() + ' ' + note.getRelease() + ' ');
}
// We herhalen de eerste... of moeten we de laatste herhalen om consistent te zijn met de CurrentNoteDump bug?
note = getNote(0);
result.append("" + note.getNote() + ' ' + note.getAttack() + ' ' + note.getRelease() + ' ');
result.append("\r\n[/CurrentNoteDump]\r\n");
// }
return result;
}
}
| 4c0n/4c0nmedit | jMod/src/main/CurrentNotes.java | 739 | // trim, omdat en nog een ' ' achter komt.
| line_comment | nl | package main;
import java.io.*;
import java.util.*;
class CurrentNotes {
private Vector currentNotes = null;
private PatchData patchData = null;
CurrentNotes (PatchData patchData){
Note note;
currentNotes = new Vector();
// Wil er standaard 2
note = new Note(64, 0, 0);
currentNotes.add(note);
note = new Note(64, 0, 0);
currentNotes.add(note);
this.patchData = patchData;
}
// Setters
public void addNotes(String params) {
Note note;
String[] paramArray = new String[4];
currentNotes.clear();
int newNote, newAttack, newRelease;
do {
paramArray = params.split(" ", 4);
newNote = Integer.parseInt(paramArray[0]);
newAttack = Integer.parseInt(paramArray[1]);
newRelease = Integer.parseInt(paramArray[2]);
params = paramArray[3];
note = new Note(newNote, newAttack, newRelease);
currentNotes.add(note);
} while (params.trim().length() > 0); // trim,<SUF>
// Bij het compleet inlezen halen we de laatste weer weg. Deze wordt extra opgeslagen door de Clavia editor
currentNotes.removeElement(currentNotes.lastElement());
}
// Getters
public int getCurrentNoteSize() {
return currentNotes.size();
}
public Note getNote(int index) {
// Note note;
return (Note) currentNotes.get(index);
}
// Inlezen patch gegevens.
public void readCurrentNoteDump(BufferedReader pchFile) {
// String dummy;
try {
addNotes(pchFile.readLine());
}
catch(Exception e) {
System.out.println(e + " in readCurrentNoteDump");
}
}
// Creeren patch gegevens.
public StringBuffer createCurrentNoteDump(StringBuffer result) {
Note note = null;
// if (getCurrentNoteSize() > 0) {
result.append("[CurrentNoteDump]\r\n");
for (int i=0; i < getCurrentNoteSize(); i++) {
note = getNote(i);
result.append("" + note.getNote() + ' ' + note.getAttack() + ' ' + note.getRelease() + ' ');
}
// We herhalen de eerste... of moeten we de laatste herhalen om consistent te zijn met de CurrentNoteDump bug?
note = getNote(0);
result.append("" + note.getNote() + ' ' + note.getAttack() + ' ' + note.getRelease() + ' ');
result.append("\r\n[/CurrentNoteDump]\r\n");
// }
return result;
}
}
|
6100_2 | package com.twitter.elephantbird.util;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hadoop.compression.lzo.LzoIndex;
import com.hadoop.compression.lzo.LzoIndexer;
import com.hadoop.compression.lzo.LzopCodec;
/**
* Miscellaneous lzo related utilities.
*/
public class LzoUtils {
public static final Logger LOG = LoggerFactory.getLogger(LzoUtils.class);
public static final String LZO_OUTPUT_INDEXABLE_MINSIZE =
"elephantbird.lzo.output.indexable.minsize";
public static final String LZO_OUTPUT_INDEX = "elephantbird.lzo.output.index";
/**
* A work-around to support environments with older versions of LzopCodec.
* It might not be feasible for to select right version of hadoop-lzo
* in some cases. This should be removed latest by EB-3.0.
*/
private static boolean isLzopIndexSupported = false;
static {
try {
isLzopIndexSupported =
null != LzopCodec.class.getMethod("createIndexedOutputStream",
OutputStream.class,
DataOutputStream.class);
} catch (Exception e) {
// older version of hadoop-lzo.
}
}
/**
* Creates an lzop output stream. The index for the lzop is
* also written to another at the same time if
* <code>elephantbird.lzo.output.index</code> is set in configuration. <p>
*
* If the file size at closing is not larger than a single block,
* the index file is deleted (in line with {@link LzoIndexer} behavior).
*/
public static DataOutputStream
getIndexedLzoOutputStream(Configuration conf, Path path) throws IOException {
LzopCodec codec = new LzopCodec();
codec.setConf(conf);
final Path file = path;
final FileSystem fs = file.getFileSystem(conf);
FSDataOutputStream fileOut = fs.create(file, false);
FSDataOutputStream indexOut = null;
if (conf.getBoolean(LZO_OUTPUT_INDEX, false)) {
if ( isLzopIndexSupported ) {
Path indexPath = file.suffix(LzoIndex.LZO_TMP_INDEX_SUFFIX);
indexOut = fs.create(indexPath, false);
} else {
LOG.warn("elephantbird.lzo.output.index is enabled, but LzopCodec "
+ "does not have createIndexedOutputStream method. "
+ "Please upgrade hadoop-lzo.");
}
}
final boolean isIndexed = indexOut != null;
final long minIndexableSize = conf.getLong(LZO_OUTPUT_INDEXABLE_MINSIZE,
-1L);
OutputStream out = ( isIndexed ?
codec.createIndexedOutputStream(fileOut, indexOut) :
codec.createOutputStream(fileOut) );
return new DataOutputStream(out) {
// override close() to handle renaming index file.
public void close() throws IOException {
super.close();
if ( isIndexed ) {
// rename or remove the index file based on file size.
Path tmpPath = file.suffix(LzoIndex.LZO_TMP_INDEX_SUFFIX);
FileStatus stat = fs.getFileStatus(file);
final long minSizeToIndex = minIndexableSize < 0
? stat.getBlockSize()
: minIndexableSize;
if (stat.getLen() <= minSizeToIndex) {
fs.delete(tmpPath, false);
} else {
fs.rename(tmpPath, file.suffix(LzoIndex.LZO_INDEX_SUFFIX));
}
}
}
};
}
}
| 50onRed/elephant-bird | core/src/main/java/com/twitter/elephantbird/util/LzoUtils.java | 999 | // older version of hadoop-lzo. | line_comment | nl | package com.twitter.elephantbird.util;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hadoop.compression.lzo.LzoIndex;
import com.hadoop.compression.lzo.LzoIndexer;
import com.hadoop.compression.lzo.LzopCodec;
/**
* Miscellaneous lzo related utilities.
*/
public class LzoUtils {
public static final Logger LOG = LoggerFactory.getLogger(LzoUtils.class);
public static final String LZO_OUTPUT_INDEXABLE_MINSIZE =
"elephantbird.lzo.output.indexable.minsize";
public static final String LZO_OUTPUT_INDEX = "elephantbird.lzo.output.index";
/**
* A work-around to support environments with older versions of LzopCodec.
* It might not be feasible for to select right version of hadoop-lzo
* in some cases. This should be removed latest by EB-3.0.
*/
private static boolean isLzopIndexSupported = false;
static {
try {
isLzopIndexSupported =
null != LzopCodec.class.getMethod("createIndexedOutputStream",
OutputStream.class,
DataOutputStream.class);
} catch (Exception e) {
// older<SUF>
}
}
/**
* Creates an lzop output stream. The index for the lzop is
* also written to another at the same time if
* <code>elephantbird.lzo.output.index</code> is set in configuration. <p>
*
* If the file size at closing is not larger than a single block,
* the index file is deleted (in line with {@link LzoIndexer} behavior).
*/
public static DataOutputStream
getIndexedLzoOutputStream(Configuration conf, Path path) throws IOException {
LzopCodec codec = new LzopCodec();
codec.setConf(conf);
final Path file = path;
final FileSystem fs = file.getFileSystem(conf);
FSDataOutputStream fileOut = fs.create(file, false);
FSDataOutputStream indexOut = null;
if (conf.getBoolean(LZO_OUTPUT_INDEX, false)) {
if ( isLzopIndexSupported ) {
Path indexPath = file.suffix(LzoIndex.LZO_TMP_INDEX_SUFFIX);
indexOut = fs.create(indexPath, false);
} else {
LOG.warn("elephantbird.lzo.output.index is enabled, but LzopCodec "
+ "does not have createIndexedOutputStream method. "
+ "Please upgrade hadoop-lzo.");
}
}
final boolean isIndexed = indexOut != null;
final long minIndexableSize = conf.getLong(LZO_OUTPUT_INDEXABLE_MINSIZE,
-1L);
OutputStream out = ( isIndexed ?
codec.createIndexedOutputStream(fileOut, indexOut) :
codec.createOutputStream(fileOut) );
return new DataOutputStream(out) {
// override close() to handle renaming index file.
public void close() throws IOException {
super.close();
if ( isIndexed ) {
// rename or remove the index file based on file size.
Path tmpPath = file.suffix(LzoIndex.LZO_TMP_INDEX_SUFFIX);
FileStatus stat = fs.getFileStatus(file);
final long minSizeToIndex = minIndexableSize < 0
? stat.getBlockSize()
: minIndexableSize;
if (stat.getLen() <= minSizeToIndex) {
fs.delete(tmpPath, false);
} else {
fs.rename(tmpPath, file.suffix(LzoIndex.LZO_INDEX_SUFFIX));
}
}
}
};
}
}
|
54049_67 | /*
* Copyright (C) 2012-2022 52°North Spatial Information Research GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/
package org.n52.sos.netcdf;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Point;
import org.n52.shetland.ogc.gml.AbstractFeature;
import org.n52.shetland.ogc.gml.time.Time;
import org.n52.shetland.ogc.gml.time.TimePeriod;
import org.n52.shetland.ogc.om.AbstractPhenomenon;
import org.n52.shetland.ogc.om.NamedValue;
import org.n52.shetland.ogc.om.ObservationStream;
import org.n52.shetland.ogc.om.ObservationValue;
import org.n52.shetland.ogc.om.OmCompositePhenomenon;
import org.n52.shetland.ogc.om.OmConstants;
import org.n52.shetland.ogc.om.OmObservableProperty;
import org.n52.shetland.ogc.om.OmObservation;
import org.n52.shetland.ogc.om.OmObservationConstellation;
import org.n52.shetland.ogc.om.SingleObservationValue;
import org.n52.shetland.ogc.om.StreamingValue;
import org.n52.shetland.ogc.om.features.samplingFeatures.AbstractSamplingFeature;
import org.n52.shetland.ogc.om.values.GeometryValue;
import org.n52.shetland.ogc.om.values.QuantityValue;
import org.n52.shetland.ogc.om.values.Value;
import org.n52.shetland.ogc.ows.exception.OwsExceptionReport;
import org.n52.sos.netcdf.data.dataset.IdentifierDatasetSensor;
import org.n52.sos.netcdf.data.dataset.TimeSeriesProfileSensorDataset;
import org.n52.sos.netcdf.data.dataset.TimeSeriesSensorDataset;
import org.n52.sos.netcdf.data.dataset.TrajectoryProfileSensorDataset;
import org.n52.sos.netcdf.data.dataset.TrajectorySensorDataset;
import org.n52.sos.netcdf.data.subsensor.BinProfileSubSensor;
import org.n52.sos.netcdf.data.subsensor.PointProfileSubSensor;
import org.n52.sos.netcdf.data.subsensor.SubSensor;
import org.n52.sos.netcdf.feature.FeatureUtil;
import org.n52.sos.netcdf.om.NetCDFObservation;
import org.n52.sos.util.GeometryHandler;
import org.n52.svalbard.encode.exception.EncodingException;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import ucar.nc2.constants.CF;
/**
* Utility class for netCDF encoding.
*
* @author <a href="mailto:[email protected]">Shane StClair</a>
* @author <a href="mailto:[email protected]">Carsten Hollmann</a>
* @since 4.4.0
*
*/
public interface NetCDFUtil {
GeometryHandler getGeometryHandler();
NetcdfHelper getNetcdfHelper();
/**
* Organizes OmObservation collection into a list of NetCDFObservation
* blocks, each of which contain a single feature type
*
* @param omObservations
* The collection of observations to transform
* @return List<NetCDFObservation> ready for encoding
* @throws EncodingException
* if an error occurs
*/
default List<NetCDFObservation> createNetCDFSosObservations(ObservationStream omObservations)
throws EncodingException, OwsExceptionReport {
// the main map of observation value strings by asset, time, phenomenon,
// and subsensor (height, profile bin, etc)
Map<String, Map<Time, Map<OmObservableProperty, Map<SubSensor, Value<?>>>>> obsValuesMap = new HashMap<>();
SetMultimap<String, OmObservableProperty> sensorPhens = HashMultimap.create();
Map<String, AbstractFeature> sensorProcedure = Maps.newHashMap();
// Map<StationAsset,TimePeriod> stationPeriodMap = new
// HashMap<StationAsset,TimePeriod>();
// maps to keep track of unique dimension values by sensor (these may or
// may not vary, determining the feature type)
SetMultimap<String, Double> sensorLngs = HashMultimap.create();
SetMultimap<String, Double> sensorLats = HashMultimap.create();
SetMultimap<String, Double> sensorHeights = HashMultimap.create();
while (omObservations.hasNext()) {
OmObservation sosObs = omObservations.next();
if (sosObs.getValue() instanceof StreamingValue<?>) {
StreamingValue<?> streaming = (StreamingValue<?>) sosObs.getValue();
while (streaming.hasNext()) {
processObservation(streaming.next(), sensorPhens, sensorProcedure, sensorLngs, sensorLats,
sensorHeights, obsValuesMap);
}
} else {
processObservation(sosObs, sensorPhens, sensorProcedure, sensorLngs, sensorLats, sensorHeights,
obsValuesMap);
}
}
// now we know about each station's dimensions, sort into CF feature
// types
// sampling time periods
// TimePeriod pointSamplingTimePeriod = new TimePeriod();
TimePeriod timeSeriesSamplingTimePeriod = new TimePeriod();
// TimePeriod profileSamplingTimePeriod = new TimePeriod();
TimePeriod timeSeriesProfileSamplingTimePeriod = new TimePeriod();
TimePeriod trajectorySamplingTimePeriod = new TimePeriod();
TimePeriod trajectoryProfileSamplingTimePeriod = new TimePeriod();
// station datasets
// Map<SensorAsset,PointSensorDataset> pointSensorDatasets =
// new HashMap<SensorAsset,PointSensorDataset>();
Map<String, TimeSeriesSensorDataset> timeSeriesSensorDatasets = new HashMap<>();
// Map<SensorAsset,ProfileSensorDataset> profileSensorDatasets =
// new HashMap<SensorAsset,ProfileSensorDataset>();
Map<String, TimeSeriesProfileSensorDataset> timeSeriesProfileSensorDatasets = new HashMap<>();
Map<String, TrajectorySensorDataset> trajectorySensorDatasets = new HashMap<>();
Map<String, TrajectoryProfileSensorDataset> trajectoryProfileSensorDatasets = new HashMap<>();
// phenomena
// Set<OmObservableProperty> pointPhenomena = new
// HashSet<OmObservableProperty>();
Set<OmObservableProperty> timeSeriesPhenomena = new HashSet<>();
// Set<OmObservableProperty> profilePhenomena = new
// HashSet<OmObservableProperty>();
Set<OmObservableProperty> timeSeriesProfilePhenomena = new HashSet<>();
Set<OmObservableProperty> trajectoryPhenomena = new HashSet<>();
Set<OmObservableProperty> trajectoryProfilePhenomena = new HashSet<>();
// envelopes
// Envelope pointEnvelope = new Envelope();
Envelope timeSeriesEnvelope = new Envelope();
// Envelope profileEnvelope = new Envelope();
Envelope timeSeriesProfileEnvelope = new Envelope();
Envelope trajectoryEnvelope = new Envelope();
Envelope trajectoryProfileEnvelope = new Envelope();
for (Map.Entry<String, Map<Time, Map<OmObservableProperty,
Map<SubSensor, Value<?>>>>> obsValuesEntry : obsValuesMap
.entrySet()) {
IdentifierDatasetSensor datasetSensor = new IdentifierDatasetSensor(obsValuesEntry.getKey());
String sensor = datasetSensor.getSensorIdentifier();
Set<Time> sensorTimes = obsValuesEntry.getValue().keySet();
int lngCount = sensorLngs.get(sensor).size();
int latCount = sensorLats.get(sensor).size();
int heightCount = sensorHeights.get(sensor).size();
// int timeCount = sensorTimes.size();
boolean locationVaries = lngCount > 0 && latCount > 0 && (lngCount > 1 || latCount > 1);
boolean heightVaries = heightCount > 1;
// boolean timeVaries = timeCount > 1;
// set static dimension values where applicable
Double staticLng = null;
Double staticLat = null;
Double staticHeight = null;
// Time staticTime = null;
if (!locationVaries) {
if (!sensorLngs.get(sensor).isEmpty()) {
staticLng = sensorLngs.get(sensor).iterator().next();
}
if (!sensorLats.get(sensor).isEmpty()) {
staticLat = sensorLats.get(sensor).iterator().next();
}
}
if (!heightVaries) {
if (!sensorHeights.get(sensor).isEmpty()) {
staticHeight = sensorHeights.get(sensor).iterator().next();
}
}
// if( !timeVaries ){
// if( !sensorTimes.isEmpty() ){
// staticTime = sensorTimes.iterator().next();
// }
// }
// put data on applicable feature type maps
// if( !locationVaries && !heightVaries && !timeVaries ){
// //point
// pointSamplingTimePeriod.extendToContain( sensorTimes );
// pointSensorDatasets.put( sensor, new PointSensorDataset( sensor,
// staticLng, staticLat,
// staticHeight, staticTime, obsValuesEntry.getValue() ) );
// pointPhenomena.addAll( sensorPhens.get( sensor ) );
// if( staticLng != null && staticLat != null ){
// pointEnvelope.expandToInclude( staticLng, staticLat );
// }
// pointStationPoints.putAll( station, stationPoints.get( station )
// );
// if( sensorHeights.get( sensor ) != null ){
// pointSensorHeights.putAll( sensor, sensorHeights.get( sensor ) );
// }
// } else if( !locationVaries && !heightVaries && timeVaries){
if (!locationVaries && !heightVaries) {
// time series
timeSeriesSamplingTimePeriod.extendToContain(sensorTimes);
timeSeriesSensorDatasets.put(sensor, new TimeSeriesSensorDataset(datasetSensor, staticLng, staticLat,
staticHeight, obsValuesEntry.getValue(), sensorProcedure.get(sensor)));
timeSeriesPhenomena.addAll(sensorPhens.get(sensor));
if (staticLng != null && staticLat != null) {
timeSeriesEnvelope.expandToInclude(staticLng, staticLat);
}
} else if (!locationVaries && heightVaries) {
// time series profile
timeSeriesProfileSamplingTimePeriod.extendToContain(sensorTimes);
timeSeriesProfileSensorDatasets.put(sensor, new TimeSeriesProfileSensorDataset(datasetSensor,
staticLng, staticLat, obsValuesEntry.getValue(), sensorProcedure.get(sensor)));
timeSeriesProfilePhenomena.addAll(sensorPhens.get(sensor));
if (staticLng != null && staticLat != null) {
timeSeriesProfileEnvelope.expandToInclude(staticLng, staticLat);
}
} else if (locationVaries && !heightVaries) {
// trajectory
trajectorySamplingTimePeriod.extendToContain(sensorTimes);
trajectorySensorDatasets.put(sensor, new TrajectorySensorDataset(datasetSensor, staticHeight,
obsValuesEntry.getValue(), sensorProcedure.get(sensor)));
trajectoryPhenomena.addAll(sensorPhens.get(sensor));
expandEnvelopeToInclude(trajectoryEnvelope, sensorLngs.get(sensor), sensorLats.get(sensor));
} else if (locationVaries && heightVaries) {
// trajectory profile
trajectoryProfileSamplingTimePeriod.extendToContain(sensorTimes);
trajectoryProfileSensorDatasets.put(sensor, new TrajectoryProfileSensorDataset(datasetSensor,
obsValuesEntry.getValue(), sensorProcedure.get(sensor)));
trajectoryProfilePhenomena.addAll(sensorPhens.get(sensor));
expandEnvelopeToInclude(trajectoryProfileEnvelope, sensorLngs.get(sensor), sensorLats.get(sensor));
}
}
// build NetCDFObservations
List<NetCDFObservation> iSosObsList =
new ArrayList<>(timeSeriesSensorDatasets.size() + timeSeriesProfileSensorDatasets.size()
+ trajectorySensorDatasets.size() + trajectoryProfileSensorDatasets.size());
// timeSeries
if (timeSeriesSensorDatasets.size() > 0) {
iSosObsList.add(new NetCDFObservation(CF.FeatureType.timeSeries, timeSeriesSamplingTimePeriod,
timeSeriesSensorDatasets, timeSeriesPhenomena, timeSeriesEnvelope));
}
// time series profile
if (timeSeriesProfileSensorDatasets.size() > 0) {
iSosObsList
.add(new NetCDFObservation(CF.FeatureType.timeSeriesProfile, timeSeriesProfileSamplingTimePeriod,
timeSeriesProfileSensorDatasets, timeSeriesProfilePhenomena, timeSeriesProfileEnvelope));
}
// trajectory
if (trajectorySensorDatasets.size() > 0) {
iSosObsList.add(new NetCDFObservation(CF.FeatureType.trajectory, trajectorySamplingTimePeriod,
trajectorySensorDatasets, trajectoryPhenomena, trajectoryEnvelope));
}
// trajectoryProfile
if (trajectoryProfileSensorDatasets.size() > 0) {
iSosObsList
.add(new NetCDFObservation(CF.FeatureType.trajectoryProfile, trajectoryProfileSamplingTimePeriod,
trajectoryProfileSensorDatasets, trajectoryProfilePhenomena, trajectoryProfileEnvelope));
}
return iSosObsList;
}
default void processObservation(OmObservation sosObs, SetMultimap<String, OmObservableProperty> sensorPhens,
Map<String, AbstractFeature> sensorProcedure, SetMultimap<String, Double> sensorLngs,
SetMultimap<String, Double> sensorLats, SetMultimap<String, Double> sensorHeights,
Map<String, Map<Time, Map<OmObservableProperty, Map<SubSensor, Value<?>>>>> obsValuesMap)
throws EncodingException {
OmObservationConstellation obsConst = sosObs.getObservationConstellation();
// first, resolve the procId to an asset type
String sensor = obsConst.getProcedure().getIdentifier();
if (!sensorProcedure.containsKey(sensor)) {
sensorProcedure.put(sensor, obsConst.getProcedure());
}
AbstractPhenomenon absPhen = obsConst.getObservableProperty();
Map<String, OmObservableProperty> phenomenaMap = new HashMap<>();
if (absPhen instanceof OmCompositePhenomenon) {
for (OmObservableProperty phen : ((OmCompositePhenomenon) absPhen).getPhenomenonComponents()) {
// TODO should the unit be set like this? seems sketchy
if (phen.getUnit() == null && sosObs.getValue() != null && sosObs.getValue().getValue() != null
&& sosObs.getValue().getValue().getUnit() != null) {
phen.setUnit(sosObs.getValue().getValue().getUnit());
}
phenomenaMap.put(phen.getIdentifier(), phen);
}
} else {
OmObservableProperty phen = (OmObservableProperty) absPhen;
// TODO should the unit be set like this? seems sketchy
if (phen.getUnit() == null && sosObs.getValue() != null && sosObs.getValue().getValue() != null
&& sosObs.getValue().getValue().getUnit() != null) {
phen.setUnit(sosObs.getValue().getValue().getUnit());
}
phenomenaMap.put(phen.getIdentifier(), phen);
}
List<OmObservableProperty> phenomena = new ArrayList<>(phenomenaMap.values());
sensorPhens.putAll(sensor, phenomena);
// get foi
AbstractFeature aFoi = obsConst.getFeatureOfInterest();
if (!(aFoi instanceof AbstractSamplingFeature)) {
throw new EncodingException("Encountered a feature which isn't a SamplingFeature");
}
AbstractSamplingFeature foi = (AbstractSamplingFeature) aFoi;
for (Point point : FeatureUtil.getFeaturePoints(foi)) {
try {
// TODO is this correct?
Point p = (Point) getGeometryHandler().switchCoordinateAxisFromToDatasourceIfNeeded(point);
sensorLngs.put(sensor, p.getX());
sensorLats.put(sensor, p.getY());
} catch (OwsExceptionReport e) {
throw new EncodingException("Exception while normalizing feature coordinate axis order.", e);
}
}
Set<Double> featureHeights = FeatureUtil.getFeatureHeights(foi);
sensorHeights.putAll(sensor, featureHeights);
String phenId = obsConst.getObservableProperty().getIdentifier();
ObservationValue<?> iObsValue = sosObs.getValue();
if (!(iObsValue instanceof SingleObservationValue)) {
throw new EncodingException("Only SingleObservationValues are supported.");
}
SingleObservationValue<?> singleObsValue = (SingleObservationValue<?>) iObsValue;
Time obsTime = singleObsValue.getPhenomenonTime();
// TODO Quality
Value<?> obsValue = singleObsValue.getValue();
if (!(obsValue instanceof QuantityValue)) {
throw new EncodingException("Only QuantityValues are supported.");
}
QuantityValue quantityValue = (QuantityValue) obsValue;
// axes shouldn't be composite phenomena
if (phenomena.size() == 1) {
OmObservableProperty phenomenon = phenomena.get(0);
// add dimensional values to procedure dimension tracking maps
if (isLng(phenomenon.getIdentifier())) {
sensorLngs.get(sensor).add(quantityValue.getValue().doubleValue());
}
if (isLat(phenomenon.getIdentifier())) {
sensorLats.get(sensor).add(quantityValue.getValue().doubleValue());
}
if (isZ(phenomenon.getIdentifier())) {
Double zValue = quantityValue.getValue().doubleValue();
sensorHeights.get(sensor).add(zValue);
}
}
// check for samplingGeometry in observation
if (sosObs.isSetParameter()) {
if (sosObs.isSetHeightDepthParameter()) {
if (sosObs.isSetHeightParameter()) {
sensorHeights.get(sensor).add(sosObs.getHeightParameter().getValue().getValue().doubleValue());
} else if (sosObs.isSetDepthParameter()) {
sensorHeights.get(sensor).add(sosObs.getDepthParameter().getValue().getValue().doubleValue());
}
}
if (hasSamplingGeometry(sosObs)) {
Geometry geometry = getSamplingGeometryGeometry(sosObs);
Set<Point> points = FeatureUtil.getPoints(geometry);
for (Point point : points) {
try {
Point p = (Point) getGeometryHandler().switchCoordinateAxisFromToDatasourceIfNeeded(point);
sensorLngs.put(sensor, p.getX());
sensorLats.put(sensor, p.getY());
} catch (OwsExceptionReport e) {
throw new EncodingException(
"Exception while normalizing sampling geometry coordinate axis order.");
}
}
sensorHeights.putAll(sensor, FeatureUtil.getHeights(points));
}
}
// get the sensor's data map
Map<Time, Map<OmObservableProperty, Map<SubSensor, Value<?>>>> sensorObsMap = obsValuesMap.get(sensor);
if (sensorObsMap == null) {
sensorObsMap = new HashMap<>();
obsValuesMap.put(sensor, sensorObsMap);
}
// get the map of the asset's phenomena by time
Map<OmObservableProperty, Map<SubSensor, Value<?>>> obsPropMap = sensorObsMap.get(obsTime);
if (obsPropMap == null) {
obsPropMap = new HashMap<>();
sensorObsMap.put(obsTime, obsPropMap);
}
OmObservableProperty phen = phenomenaMap.get(phenId);
Map<SubSensor, Value<?>> subSensorMap = obsPropMap.get(phen);
if (subSensorMap == null) {
subSensorMap = new HashMap<>();
obsPropMap.put(phen, subSensorMap);
}
// add obs value to subsensor map (null subsensors are ok)
if (sosObs.isSetParameter() && hasSamplingGeometry(sosObs)) {
subSensorMap.put(createSubSensor(sensor, getSamplingGeometryGeometry(sosObs)), obsValue);
} else {
subSensorMap.put(createSubSensor(sensor, foi), obsValue);
}
}
default void expandEnvelopeToInclude(Envelope env, Set<Double> lngs, Set<Double> lats) {
lngs.stream().forEach(lng -> env.expandToInclude(lng, env.getMinY()));
lats.stream().forEach(lat -> env.expandToInclude(env.getMinX(), lat));
}
default Envelope createEnvelope(Collection<OmObservation> observationCollection) {
Envelope envelope = null;
for (OmObservation sosObservation : observationCollection) {
sosObservation.getObservationConstellation().getFeatureOfInterest();
AbstractSamplingFeature samplingFeature =
(AbstractSamplingFeature) sosObservation.getObservationConstellation().getFeatureOfInterest();
if (samplingFeature != null && samplingFeature.getGeometry() != null) {
if (envelope == null) {
envelope = samplingFeature.getGeometry().getEnvelopeInternal();
} else {
envelope.expandToInclude(samplingFeature.getGeometry().getEnvelopeInternal());
}
}
}
return envelope;
}
default Envelope swapEnvelopeAxisOrder(Envelope envelope) {
if (envelope == null) {
return null;
}
return new Envelope(envelope.getMinY(), envelope.getMaxY(), envelope.getMinX(), envelope.getMaxX());
}
// default void checkSrid( int srid, Logger logger ) throws
// InvalidParameterValueException{
// if( !Ioos52nConstants.ALLOWED_EPSGS.contains( srid ) ){
// throw new InvalidParameterValueException("EPSG", Integer.toString( srid )
// );
// }
// }
default SubSensor createSubSensor(String sensor, AbstractSamplingFeature foi) {
// return null if sensor or station id is same as foi
if (sensor.equals(foi.getIdentifierCodeWithAuthority().getValue())) {
return null;
}
return createSubSensor(sensor, foi.getGeometry());
}
// default void checkSrid( int srid, Logger logger ) throws
// InvalidParameterValueException{
// if( !Ioos52nConstants.ALLOWED_EPSGS.contains( srid ) ){
// throw new InvalidParameterValueException("EPSG", Integer.toString( srid )
// );
// }
// }
// default void checkSrid( int srid, Logger logger ) throws
// InvalidParameterValueException{
// if( !Ioos52nConstants.ALLOWED_EPSGS.contains( srid ) ){
// throw new InvalidParameterValueException("EPSG", Integer.toString( srid )
// );
// }
// }
default SubSensor createSubSensor(String sensor, Geometry geom) {
SubSensor subSensor = null;
if (geom instanceof Point) {
Point point = (Point) geom;
// profile height
if (!Double.isNaN(point.getCoordinate().getZ())) {
subSensor = new PointProfileSubSensor(point.getCoordinate().getZ());
} else {
subSensor = new PointProfileSubSensor(0.0);
}
} else if (geom instanceof LineString) {
LineString lineString = (LineString) geom;
// profile bin
if (lineString.getNumPoints() == 2) {
Point topPoint = lineString.getPointN(0);
Point bottomPoint = lineString.getPointN(1);
if (FeatureUtil.equal2d(topPoint, bottomPoint) && !Double.isNaN(topPoint.getCoordinate().getZ())
&& !Double.isNaN(bottomPoint.getCoordinate().getZ())) {
double topHeight = Math.max(topPoint.getCoordinate().getZ(), bottomPoint.getCoordinate().getZ());
double bottomHeight =
Math.min(topPoint.getCoordinate().getZ(), bottomPoint.getCoordinate().getZ());
subSensor = new BinProfileSubSensor(topHeight, bottomHeight);
}
}
}
return subSensor;
}
default boolean isLng(String phenomenon) {
return getNetcdfHelper().getLatitude().contains(phenomenon.toLowerCase(Locale.ROOT));
}
default boolean isLat(String phenomenon) {
return getNetcdfHelper().getLongitude().contains(phenomenon.toLowerCase(Locale.ROOT));
}
default boolean isZ(String phenomenon) {
return getNetcdfHelper().getZ().contains(phenomenon.toLowerCase(Locale.ROOT));
}
default boolean hasSamplingGeometry(OmObservation sosObs) {
return getSamplingGeometryGeometry(sosObs) != null;
}
default Geometry getSamplingGeometryGeometry(OmObservation sosObs) {
for (NamedValue<?> parameter : sosObs.getParameter()) {
if (parameter.isSetName() && parameter.getName().isSetHref()
&& OmConstants.PARAM_NAME_SAMPLING_GEOMETRY.equals(parameter.getName().getHref())
&& parameter.isSetValue() && parameter.getValue() instanceof GeometryValue
&& parameter.getValue().isSetValue()) {
return (Geometry) parameter.getValue().getValue();
}
}
return null;
}
}
| 52North/SOS | coding/netcdf/api/src/main/java/org/n52/sos/netcdf/NetCDFUtil.java | 6,479 | // default void checkSrid( int srid, Logger logger ) throws | line_comment | nl | /*
* Copyright (C) 2012-2022 52°North Spatial Information Research GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/
package org.n52.sos.netcdf;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Point;
import org.n52.shetland.ogc.gml.AbstractFeature;
import org.n52.shetland.ogc.gml.time.Time;
import org.n52.shetland.ogc.gml.time.TimePeriod;
import org.n52.shetland.ogc.om.AbstractPhenomenon;
import org.n52.shetland.ogc.om.NamedValue;
import org.n52.shetland.ogc.om.ObservationStream;
import org.n52.shetland.ogc.om.ObservationValue;
import org.n52.shetland.ogc.om.OmCompositePhenomenon;
import org.n52.shetland.ogc.om.OmConstants;
import org.n52.shetland.ogc.om.OmObservableProperty;
import org.n52.shetland.ogc.om.OmObservation;
import org.n52.shetland.ogc.om.OmObservationConstellation;
import org.n52.shetland.ogc.om.SingleObservationValue;
import org.n52.shetland.ogc.om.StreamingValue;
import org.n52.shetland.ogc.om.features.samplingFeatures.AbstractSamplingFeature;
import org.n52.shetland.ogc.om.values.GeometryValue;
import org.n52.shetland.ogc.om.values.QuantityValue;
import org.n52.shetland.ogc.om.values.Value;
import org.n52.shetland.ogc.ows.exception.OwsExceptionReport;
import org.n52.sos.netcdf.data.dataset.IdentifierDatasetSensor;
import org.n52.sos.netcdf.data.dataset.TimeSeriesProfileSensorDataset;
import org.n52.sos.netcdf.data.dataset.TimeSeriesSensorDataset;
import org.n52.sos.netcdf.data.dataset.TrajectoryProfileSensorDataset;
import org.n52.sos.netcdf.data.dataset.TrajectorySensorDataset;
import org.n52.sos.netcdf.data.subsensor.BinProfileSubSensor;
import org.n52.sos.netcdf.data.subsensor.PointProfileSubSensor;
import org.n52.sos.netcdf.data.subsensor.SubSensor;
import org.n52.sos.netcdf.feature.FeatureUtil;
import org.n52.sos.netcdf.om.NetCDFObservation;
import org.n52.sos.util.GeometryHandler;
import org.n52.svalbard.encode.exception.EncodingException;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import ucar.nc2.constants.CF;
/**
* Utility class for netCDF encoding.
*
* @author <a href="mailto:[email protected]">Shane StClair</a>
* @author <a href="mailto:[email protected]">Carsten Hollmann</a>
* @since 4.4.0
*
*/
public interface NetCDFUtil {
GeometryHandler getGeometryHandler();
NetcdfHelper getNetcdfHelper();
/**
* Organizes OmObservation collection into a list of NetCDFObservation
* blocks, each of which contain a single feature type
*
* @param omObservations
* The collection of observations to transform
* @return List<NetCDFObservation> ready for encoding
* @throws EncodingException
* if an error occurs
*/
default List<NetCDFObservation> createNetCDFSosObservations(ObservationStream omObservations)
throws EncodingException, OwsExceptionReport {
// the main map of observation value strings by asset, time, phenomenon,
// and subsensor (height, profile bin, etc)
Map<String, Map<Time, Map<OmObservableProperty, Map<SubSensor, Value<?>>>>> obsValuesMap = new HashMap<>();
SetMultimap<String, OmObservableProperty> sensorPhens = HashMultimap.create();
Map<String, AbstractFeature> sensorProcedure = Maps.newHashMap();
// Map<StationAsset,TimePeriod> stationPeriodMap = new
// HashMap<StationAsset,TimePeriod>();
// maps to keep track of unique dimension values by sensor (these may or
// may not vary, determining the feature type)
SetMultimap<String, Double> sensorLngs = HashMultimap.create();
SetMultimap<String, Double> sensorLats = HashMultimap.create();
SetMultimap<String, Double> sensorHeights = HashMultimap.create();
while (omObservations.hasNext()) {
OmObservation sosObs = omObservations.next();
if (sosObs.getValue() instanceof StreamingValue<?>) {
StreamingValue<?> streaming = (StreamingValue<?>) sosObs.getValue();
while (streaming.hasNext()) {
processObservation(streaming.next(), sensorPhens, sensorProcedure, sensorLngs, sensorLats,
sensorHeights, obsValuesMap);
}
} else {
processObservation(sosObs, sensorPhens, sensorProcedure, sensorLngs, sensorLats, sensorHeights,
obsValuesMap);
}
}
// now we know about each station's dimensions, sort into CF feature
// types
// sampling time periods
// TimePeriod pointSamplingTimePeriod = new TimePeriod();
TimePeriod timeSeriesSamplingTimePeriod = new TimePeriod();
// TimePeriod profileSamplingTimePeriod = new TimePeriod();
TimePeriod timeSeriesProfileSamplingTimePeriod = new TimePeriod();
TimePeriod trajectorySamplingTimePeriod = new TimePeriod();
TimePeriod trajectoryProfileSamplingTimePeriod = new TimePeriod();
// station datasets
// Map<SensorAsset,PointSensorDataset> pointSensorDatasets =
// new HashMap<SensorAsset,PointSensorDataset>();
Map<String, TimeSeriesSensorDataset> timeSeriesSensorDatasets = new HashMap<>();
// Map<SensorAsset,ProfileSensorDataset> profileSensorDatasets =
// new HashMap<SensorAsset,ProfileSensorDataset>();
Map<String, TimeSeriesProfileSensorDataset> timeSeriesProfileSensorDatasets = new HashMap<>();
Map<String, TrajectorySensorDataset> trajectorySensorDatasets = new HashMap<>();
Map<String, TrajectoryProfileSensorDataset> trajectoryProfileSensorDatasets = new HashMap<>();
// phenomena
// Set<OmObservableProperty> pointPhenomena = new
// HashSet<OmObservableProperty>();
Set<OmObservableProperty> timeSeriesPhenomena = new HashSet<>();
// Set<OmObservableProperty> profilePhenomena = new
// HashSet<OmObservableProperty>();
Set<OmObservableProperty> timeSeriesProfilePhenomena = new HashSet<>();
Set<OmObservableProperty> trajectoryPhenomena = new HashSet<>();
Set<OmObservableProperty> trajectoryProfilePhenomena = new HashSet<>();
// envelopes
// Envelope pointEnvelope = new Envelope();
Envelope timeSeriesEnvelope = new Envelope();
// Envelope profileEnvelope = new Envelope();
Envelope timeSeriesProfileEnvelope = new Envelope();
Envelope trajectoryEnvelope = new Envelope();
Envelope trajectoryProfileEnvelope = new Envelope();
for (Map.Entry<String, Map<Time, Map<OmObservableProperty,
Map<SubSensor, Value<?>>>>> obsValuesEntry : obsValuesMap
.entrySet()) {
IdentifierDatasetSensor datasetSensor = new IdentifierDatasetSensor(obsValuesEntry.getKey());
String sensor = datasetSensor.getSensorIdentifier();
Set<Time> sensorTimes = obsValuesEntry.getValue().keySet();
int lngCount = sensorLngs.get(sensor).size();
int latCount = sensorLats.get(sensor).size();
int heightCount = sensorHeights.get(sensor).size();
// int timeCount = sensorTimes.size();
boolean locationVaries = lngCount > 0 && latCount > 0 && (lngCount > 1 || latCount > 1);
boolean heightVaries = heightCount > 1;
// boolean timeVaries = timeCount > 1;
// set static dimension values where applicable
Double staticLng = null;
Double staticLat = null;
Double staticHeight = null;
// Time staticTime = null;
if (!locationVaries) {
if (!sensorLngs.get(sensor).isEmpty()) {
staticLng = sensorLngs.get(sensor).iterator().next();
}
if (!sensorLats.get(sensor).isEmpty()) {
staticLat = sensorLats.get(sensor).iterator().next();
}
}
if (!heightVaries) {
if (!sensorHeights.get(sensor).isEmpty()) {
staticHeight = sensorHeights.get(sensor).iterator().next();
}
}
// if( !timeVaries ){
// if( !sensorTimes.isEmpty() ){
// staticTime = sensorTimes.iterator().next();
// }
// }
// put data on applicable feature type maps
// if( !locationVaries && !heightVaries && !timeVaries ){
// //point
// pointSamplingTimePeriod.extendToContain( sensorTimes );
// pointSensorDatasets.put( sensor, new PointSensorDataset( sensor,
// staticLng, staticLat,
// staticHeight, staticTime, obsValuesEntry.getValue() ) );
// pointPhenomena.addAll( sensorPhens.get( sensor ) );
// if( staticLng != null && staticLat != null ){
// pointEnvelope.expandToInclude( staticLng, staticLat );
// }
// pointStationPoints.putAll( station, stationPoints.get( station )
// );
// if( sensorHeights.get( sensor ) != null ){
// pointSensorHeights.putAll( sensor, sensorHeights.get( sensor ) );
// }
// } else if( !locationVaries && !heightVaries && timeVaries){
if (!locationVaries && !heightVaries) {
// time series
timeSeriesSamplingTimePeriod.extendToContain(sensorTimes);
timeSeriesSensorDatasets.put(sensor, new TimeSeriesSensorDataset(datasetSensor, staticLng, staticLat,
staticHeight, obsValuesEntry.getValue(), sensorProcedure.get(sensor)));
timeSeriesPhenomena.addAll(sensorPhens.get(sensor));
if (staticLng != null && staticLat != null) {
timeSeriesEnvelope.expandToInclude(staticLng, staticLat);
}
} else if (!locationVaries && heightVaries) {
// time series profile
timeSeriesProfileSamplingTimePeriod.extendToContain(sensorTimes);
timeSeriesProfileSensorDatasets.put(sensor, new TimeSeriesProfileSensorDataset(datasetSensor,
staticLng, staticLat, obsValuesEntry.getValue(), sensorProcedure.get(sensor)));
timeSeriesProfilePhenomena.addAll(sensorPhens.get(sensor));
if (staticLng != null && staticLat != null) {
timeSeriesProfileEnvelope.expandToInclude(staticLng, staticLat);
}
} else if (locationVaries && !heightVaries) {
// trajectory
trajectorySamplingTimePeriod.extendToContain(sensorTimes);
trajectorySensorDatasets.put(sensor, new TrajectorySensorDataset(datasetSensor, staticHeight,
obsValuesEntry.getValue(), sensorProcedure.get(sensor)));
trajectoryPhenomena.addAll(sensorPhens.get(sensor));
expandEnvelopeToInclude(trajectoryEnvelope, sensorLngs.get(sensor), sensorLats.get(sensor));
} else if (locationVaries && heightVaries) {
// trajectory profile
trajectoryProfileSamplingTimePeriod.extendToContain(sensorTimes);
trajectoryProfileSensorDatasets.put(sensor, new TrajectoryProfileSensorDataset(datasetSensor,
obsValuesEntry.getValue(), sensorProcedure.get(sensor)));
trajectoryProfilePhenomena.addAll(sensorPhens.get(sensor));
expandEnvelopeToInclude(trajectoryProfileEnvelope, sensorLngs.get(sensor), sensorLats.get(sensor));
}
}
// build NetCDFObservations
List<NetCDFObservation> iSosObsList =
new ArrayList<>(timeSeriesSensorDatasets.size() + timeSeriesProfileSensorDatasets.size()
+ trajectorySensorDatasets.size() + trajectoryProfileSensorDatasets.size());
// timeSeries
if (timeSeriesSensorDatasets.size() > 0) {
iSosObsList.add(new NetCDFObservation(CF.FeatureType.timeSeries, timeSeriesSamplingTimePeriod,
timeSeriesSensorDatasets, timeSeriesPhenomena, timeSeriesEnvelope));
}
// time series profile
if (timeSeriesProfileSensorDatasets.size() > 0) {
iSosObsList
.add(new NetCDFObservation(CF.FeatureType.timeSeriesProfile, timeSeriesProfileSamplingTimePeriod,
timeSeriesProfileSensorDatasets, timeSeriesProfilePhenomena, timeSeriesProfileEnvelope));
}
// trajectory
if (trajectorySensorDatasets.size() > 0) {
iSosObsList.add(new NetCDFObservation(CF.FeatureType.trajectory, trajectorySamplingTimePeriod,
trajectorySensorDatasets, trajectoryPhenomena, trajectoryEnvelope));
}
// trajectoryProfile
if (trajectoryProfileSensorDatasets.size() > 0) {
iSosObsList
.add(new NetCDFObservation(CF.FeatureType.trajectoryProfile, trajectoryProfileSamplingTimePeriod,
trajectoryProfileSensorDatasets, trajectoryProfilePhenomena, trajectoryProfileEnvelope));
}
return iSosObsList;
}
default void processObservation(OmObservation sosObs, SetMultimap<String, OmObservableProperty> sensorPhens,
Map<String, AbstractFeature> sensorProcedure, SetMultimap<String, Double> sensorLngs,
SetMultimap<String, Double> sensorLats, SetMultimap<String, Double> sensorHeights,
Map<String, Map<Time, Map<OmObservableProperty, Map<SubSensor, Value<?>>>>> obsValuesMap)
throws EncodingException {
OmObservationConstellation obsConst = sosObs.getObservationConstellation();
// first, resolve the procId to an asset type
String sensor = obsConst.getProcedure().getIdentifier();
if (!sensorProcedure.containsKey(sensor)) {
sensorProcedure.put(sensor, obsConst.getProcedure());
}
AbstractPhenomenon absPhen = obsConst.getObservableProperty();
Map<String, OmObservableProperty> phenomenaMap = new HashMap<>();
if (absPhen instanceof OmCompositePhenomenon) {
for (OmObservableProperty phen : ((OmCompositePhenomenon) absPhen).getPhenomenonComponents()) {
// TODO should the unit be set like this? seems sketchy
if (phen.getUnit() == null && sosObs.getValue() != null && sosObs.getValue().getValue() != null
&& sosObs.getValue().getValue().getUnit() != null) {
phen.setUnit(sosObs.getValue().getValue().getUnit());
}
phenomenaMap.put(phen.getIdentifier(), phen);
}
} else {
OmObservableProperty phen = (OmObservableProperty) absPhen;
// TODO should the unit be set like this? seems sketchy
if (phen.getUnit() == null && sosObs.getValue() != null && sosObs.getValue().getValue() != null
&& sosObs.getValue().getValue().getUnit() != null) {
phen.setUnit(sosObs.getValue().getValue().getUnit());
}
phenomenaMap.put(phen.getIdentifier(), phen);
}
List<OmObservableProperty> phenomena = new ArrayList<>(phenomenaMap.values());
sensorPhens.putAll(sensor, phenomena);
// get foi
AbstractFeature aFoi = obsConst.getFeatureOfInterest();
if (!(aFoi instanceof AbstractSamplingFeature)) {
throw new EncodingException("Encountered a feature which isn't a SamplingFeature");
}
AbstractSamplingFeature foi = (AbstractSamplingFeature) aFoi;
for (Point point : FeatureUtil.getFeaturePoints(foi)) {
try {
// TODO is this correct?
Point p = (Point) getGeometryHandler().switchCoordinateAxisFromToDatasourceIfNeeded(point);
sensorLngs.put(sensor, p.getX());
sensorLats.put(sensor, p.getY());
} catch (OwsExceptionReport e) {
throw new EncodingException("Exception while normalizing feature coordinate axis order.", e);
}
}
Set<Double> featureHeights = FeatureUtil.getFeatureHeights(foi);
sensorHeights.putAll(sensor, featureHeights);
String phenId = obsConst.getObservableProperty().getIdentifier();
ObservationValue<?> iObsValue = sosObs.getValue();
if (!(iObsValue instanceof SingleObservationValue)) {
throw new EncodingException("Only SingleObservationValues are supported.");
}
SingleObservationValue<?> singleObsValue = (SingleObservationValue<?>) iObsValue;
Time obsTime = singleObsValue.getPhenomenonTime();
// TODO Quality
Value<?> obsValue = singleObsValue.getValue();
if (!(obsValue instanceof QuantityValue)) {
throw new EncodingException("Only QuantityValues are supported.");
}
QuantityValue quantityValue = (QuantityValue) obsValue;
// axes shouldn't be composite phenomena
if (phenomena.size() == 1) {
OmObservableProperty phenomenon = phenomena.get(0);
// add dimensional values to procedure dimension tracking maps
if (isLng(phenomenon.getIdentifier())) {
sensorLngs.get(sensor).add(quantityValue.getValue().doubleValue());
}
if (isLat(phenomenon.getIdentifier())) {
sensorLats.get(sensor).add(quantityValue.getValue().doubleValue());
}
if (isZ(phenomenon.getIdentifier())) {
Double zValue = quantityValue.getValue().doubleValue();
sensorHeights.get(sensor).add(zValue);
}
}
// check for samplingGeometry in observation
if (sosObs.isSetParameter()) {
if (sosObs.isSetHeightDepthParameter()) {
if (sosObs.isSetHeightParameter()) {
sensorHeights.get(sensor).add(sosObs.getHeightParameter().getValue().getValue().doubleValue());
} else if (sosObs.isSetDepthParameter()) {
sensorHeights.get(sensor).add(sosObs.getDepthParameter().getValue().getValue().doubleValue());
}
}
if (hasSamplingGeometry(sosObs)) {
Geometry geometry = getSamplingGeometryGeometry(sosObs);
Set<Point> points = FeatureUtil.getPoints(geometry);
for (Point point : points) {
try {
Point p = (Point) getGeometryHandler().switchCoordinateAxisFromToDatasourceIfNeeded(point);
sensorLngs.put(sensor, p.getX());
sensorLats.put(sensor, p.getY());
} catch (OwsExceptionReport e) {
throw new EncodingException(
"Exception while normalizing sampling geometry coordinate axis order.");
}
}
sensorHeights.putAll(sensor, FeatureUtil.getHeights(points));
}
}
// get the sensor's data map
Map<Time, Map<OmObservableProperty, Map<SubSensor, Value<?>>>> sensorObsMap = obsValuesMap.get(sensor);
if (sensorObsMap == null) {
sensorObsMap = new HashMap<>();
obsValuesMap.put(sensor, sensorObsMap);
}
// get the map of the asset's phenomena by time
Map<OmObservableProperty, Map<SubSensor, Value<?>>> obsPropMap = sensorObsMap.get(obsTime);
if (obsPropMap == null) {
obsPropMap = new HashMap<>();
sensorObsMap.put(obsTime, obsPropMap);
}
OmObservableProperty phen = phenomenaMap.get(phenId);
Map<SubSensor, Value<?>> subSensorMap = obsPropMap.get(phen);
if (subSensorMap == null) {
subSensorMap = new HashMap<>();
obsPropMap.put(phen, subSensorMap);
}
// add obs value to subsensor map (null subsensors are ok)
if (sosObs.isSetParameter() && hasSamplingGeometry(sosObs)) {
subSensorMap.put(createSubSensor(sensor, getSamplingGeometryGeometry(sosObs)), obsValue);
} else {
subSensorMap.put(createSubSensor(sensor, foi), obsValue);
}
}
default void expandEnvelopeToInclude(Envelope env, Set<Double> lngs, Set<Double> lats) {
lngs.stream().forEach(lng -> env.expandToInclude(lng, env.getMinY()));
lats.stream().forEach(lat -> env.expandToInclude(env.getMinX(), lat));
}
default Envelope createEnvelope(Collection<OmObservation> observationCollection) {
Envelope envelope = null;
for (OmObservation sosObservation : observationCollection) {
sosObservation.getObservationConstellation().getFeatureOfInterest();
AbstractSamplingFeature samplingFeature =
(AbstractSamplingFeature) sosObservation.getObservationConstellation().getFeatureOfInterest();
if (samplingFeature != null && samplingFeature.getGeometry() != null) {
if (envelope == null) {
envelope = samplingFeature.getGeometry().getEnvelopeInternal();
} else {
envelope.expandToInclude(samplingFeature.getGeometry().getEnvelopeInternal());
}
}
}
return envelope;
}
default Envelope swapEnvelopeAxisOrder(Envelope envelope) {
if (envelope == null) {
return null;
}
return new Envelope(envelope.getMinY(), envelope.getMaxY(), envelope.getMinX(), envelope.getMaxX());
}
// defau<SUF>
// InvalidParameterValueException{
// if( !Ioos52nConstants.ALLOWED_EPSGS.contains( srid ) ){
// throw new InvalidParameterValueException("EPSG", Integer.toString( srid )
// );
// }
// }
default SubSensor createSubSensor(String sensor, AbstractSamplingFeature foi) {
// return null if sensor or station id is same as foi
if (sensor.equals(foi.getIdentifierCodeWithAuthority().getValue())) {
return null;
}
return createSubSensor(sensor, foi.getGeometry());
}
// default void checkSrid( int srid, Logger logger ) throws
// InvalidParameterValueException{
// if( !Ioos52nConstants.ALLOWED_EPSGS.contains( srid ) ){
// throw new InvalidParameterValueException("EPSG", Integer.toString( srid )
// );
// }
// }
// default void checkSrid( int srid, Logger logger ) throws
// InvalidParameterValueException{
// if( !Ioos52nConstants.ALLOWED_EPSGS.contains( srid ) ){
// throw new InvalidParameterValueException("EPSG", Integer.toString( srid )
// );
// }
// }
default SubSensor createSubSensor(String sensor, Geometry geom) {
SubSensor subSensor = null;
if (geom instanceof Point) {
Point point = (Point) geom;
// profile height
if (!Double.isNaN(point.getCoordinate().getZ())) {
subSensor = new PointProfileSubSensor(point.getCoordinate().getZ());
} else {
subSensor = new PointProfileSubSensor(0.0);
}
} else if (geom instanceof LineString) {
LineString lineString = (LineString) geom;
// profile bin
if (lineString.getNumPoints() == 2) {
Point topPoint = lineString.getPointN(0);
Point bottomPoint = lineString.getPointN(1);
if (FeatureUtil.equal2d(topPoint, bottomPoint) && !Double.isNaN(topPoint.getCoordinate().getZ())
&& !Double.isNaN(bottomPoint.getCoordinate().getZ())) {
double topHeight = Math.max(topPoint.getCoordinate().getZ(), bottomPoint.getCoordinate().getZ());
double bottomHeight =
Math.min(topPoint.getCoordinate().getZ(), bottomPoint.getCoordinate().getZ());
subSensor = new BinProfileSubSensor(topHeight, bottomHeight);
}
}
}
return subSensor;
}
default boolean isLng(String phenomenon) {
return getNetcdfHelper().getLatitude().contains(phenomenon.toLowerCase(Locale.ROOT));
}
default boolean isLat(String phenomenon) {
return getNetcdfHelper().getLongitude().contains(phenomenon.toLowerCase(Locale.ROOT));
}
default boolean isZ(String phenomenon) {
return getNetcdfHelper().getZ().contains(phenomenon.toLowerCase(Locale.ROOT));
}
default boolean hasSamplingGeometry(OmObservation sosObs) {
return getSamplingGeometryGeometry(sosObs) != null;
}
default Geometry getSamplingGeometryGeometry(OmObservation sosObs) {
for (NamedValue<?> parameter : sosObs.getParameter()) {
if (parameter.isSetName() && parameter.getName().isSetHref()
&& OmConstants.PARAM_NAME_SAMPLING_GEOMETRY.equals(parameter.getName().getHref())
&& parameter.isSetValue() && parameter.getValue() instanceof GeometryValue
&& parameter.getValue().isSetValue()) {
return (Geometry) parameter.getValue().getValue();
}
}
return null;
}
}
|
96344_12 | /**
* Copyright (C) 2007-2015 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0.
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* icense version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* Contact: Benno Schmidt & Martin May, 52 North Initiative for Geospatial Open Source
* Software GmbH, Martin-Luther-King-Weg 24, 48155 Muenster, Germany, [email protected]
*/
package org.n52.v3d.triturus.gisimplm;
import java.util.Vector;
import org.n52.v3d.triturus.core.T3dProcMapper;
/**
* @deprecated
* todo: Diese Sachen sollten in die Klasse FltTINPolygonAssembler wandern!
* Mapper Klasse zur Verschneidung eines TINs mit einem Polygon.
* @author Martin May, Ilja Abramovic
*/
public class MpTinPolygon extends T3dProcMapper
{
private GmSimpleTINGeometry tin;
private GmPolygon pol;
/**
* Constructor.
* @param tin TIN
* @param pol Polygon
*/
public MpTinPolygon(GmSimpleTINGeometry tin, GmPolygon pol) {
this.tin = tin;
this.pol = pol;
}
public String log() {
// TODO Auto-generated method stub
return null;
}
/**
* returns the TIN that results from the intersection performed.
* @return TIN-geometry
*/
public GmSimpleTINGeometry intersect() {
GmSimpleTINGeometry result =
new GmSimpleTINGeometry(
tin.numberOfPoints() + 100,
tin.numberOfTriangles() + 300);
return result;
}
/**
* Liefert ein Array mit Indizien der Vertices, die im Polygon liegen.
* @return ^^^^^^^^
*/
private int[] verticesInPolygonIndices() {
int[] result = {};
//Create jts polygon:
// PrecisionModel pm = new PrecisionModel();
// int numPolPoints = pol.numberOfVertices();
// Coordinate[] polPoints = new Coordinate[numPolPoints];
// for (int i = 0; i < polPoints.length; i++) {
// polPoints[i] =
// new Coordinate(pol.getVertex(i).getX(), pol.getVertex(i).getY());
// }
// LinearRing sh = new LinearRing(polPoints, pm, 0);
//
// //Polygon jtsPol = new Polygon(sh, pm, 0);
//
// Vector v = new Vector(); //help var
// //
// // create MCPointInRing algorithm
// MCPointInRing alg = new MCPointInRing(sh);
// //hole ein Vertex aus TIN und pr�fe, ob in Polygon
// int numTinPoints = tin.numberOfPoints();
// for (int i = 0; i < numTinPoints; i++) {
// VgPoint p = tin.getPoint(i);
// Coordinate tinPointAsJtsCoord = new Coordinate(p.getX(), p.getY());
// if (alg.isInside(tinPointAsJtsCoord))
// v.add(new Integer(i));
// }
// result = new int[v.size()];
// for (int i = 0; i < result.length; i++) {
// result[i] = ((Integer) v.elementAt(i)).intValue();
// }
return result;
}
/**
* liefert ein Vector mit Indizien der Vertices, die die Kanten bilden, die den Polygon schneiden. Ein Element im
* Vector ist ein zweielementiges <i>int</i> Array.
* @param vertInPol Array mit Indizien der Vertices, die im Polygon liegen.
* @return
*/
private Vector involvedEdgesAsVertexPairsIndices(int[] vertInPol) {
GmSimpleMesh mesh = tin.getMesh();
Vector v = new Vector(); //help var
boolean[][] aMatrix = mesh.getAdjMatrix();
for (int i = 0; i < vertInPol.length; i++) {//i - index eines inneren Vertex
for (int j = 0; j < mesh.getNumberOfPoints(); j++) {
if (aMatrix[vertInPol[i]][j] || i!=j) {
int[] edge = {i,j};
v.add(edge);
}
}
}
return v;
}
}
| 52North/triturus | src/main/java/org/n52/v3d/triturus/gisimplm/MpTinPolygon.java | 1,338 | // new Coordinate(pol.getVertex(i).getX(), pol.getVertex(i).getY()); | line_comment | nl | /**
* Copyright (C) 2007-2015 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0.
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* icense version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* Contact: Benno Schmidt & Martin May, 52 North Initiative for Geospatial Open Source
* Software GmbH, Martin-Luther-King-Weg 24, 48155 Muenster, Germany, [email protected]
*/
package org.n52.v3d.triturus.gisimplm;
import java.util.Vector;
import org.n52.v3d.triturus.core.T3dProcMapper;
/**
* @deprecated
* todo: Diese Sachen sollten in die Klasse FltTINPolygonAssembler wandern!
* Mapper Klasse zur Verschneidung eines TINs mit einem Polygon.
* @author Martin May, Ilja Abramovic
*/
public class MpTinPolygon extends T3dProcMapper
{
private GmSimpleTINGeometry tin;
private GmPolygon pol;
/**
* Constructor.
* @param tin TIN
* @param pol Polygon
*/
public MpTinPolygon(GmSimpleTINGeometry tin, GmPolygon pol) {
this.tin = tin;
this.pol = pol;
}
public String log() {
// TODO Auto-generated method stub
return null;
}
/**
* returns the TIN that results from the intersection performed.
* @return TIN-geometry
*/
public GmSimpleTINGeometry intersect() {
GmSimpleTINGeometry result =
new GmSimpleTINGeometry(
tin.numberOfPoints() + 100,
tin.numberOfTriangles() + 300);
return result;
}
/**
* Liefert ein Array mit Indizien der Vertices, die im Polygon liegen.
* @return ^^^^^^^^
*/
private int[] verticesInPolygonIndices() {
int[] result = {};
//Create jts polygon:
// PrecisionModel pm = new PrecisionModel();
// int numPolPoints = pol.numberOfVertices();
// Coordinate[] polPoints = new Coordinate[numPolPoints];
// for (int i = 0; i < polPoints.length; i++) {
// polPoints[i] =
// new C<SUF>
// }
// LinearRing sh = new LinearRing(polPoints, pm, 0);
//
// //Polygon jtsPol = new Polygon(sh, pm, 0);
//
// Vector v = new Vector(); //help var
// //
// // create MCPointInRing algorithm
// MCPointInRing alg = new MCPointInRing(sh);
// //hole ein Vertex aus TIN und pr�fe, ob in Polygon
// int numTinPoints = tin.numberOfPoints();
// for (int i = 0; i < numTinPoints; i++) {
// VgPoint p = tin.getPoint(i);
// Coordinate tinPointAsJtsCoord = new Coordinate(p.getX(), p.getY());
// if (alg.isInside(tinPointAsJtsCoord))
// v.add(new Integer(i));
// }
// result = new int[v.size()];
// for (int i = 0; i < result.length; i++) {
// result[i] = ((Integer) v.elementAt(i)).intValue();
// }
return result;
}
/**
* liefert ein Vector mit Indizien der Vertices, die die Kanten bilden, die den Polygon schneiden. Ein Element im
* Vector ist ein zweielementiges <i>int</i> Array.
* @param vertInPol Array mit Indizien der Vertices, die im Polygon liegen.
* @return
*/
private Vector involvedEdgesAsVertexPairsIndices(int[] vertInPol) {
GmSimpleMesh mesh = tin.getMesh();
Vector v = new Vector(); //help var
boolean[][] aMatrix = mesh.getAdjMatrix();
for (int i = 0; i < vertInPol.length; i++) {//i - index eines inneren Vertex
for (int j = 0; j < mesh.getNumberOfPoints(); j++) {
if (aMatrix[vertInPol[i]][j] || i!=j) {
int[] edge = {i,j};
v.add(edge);
}
}
}
return v;
}
}
|
174733_6 | package org.khan.solver.cubesolver.processor;
import java.util.ArrayList;
import java.util.List;
import org.khan.solver.cubesolver.puzzle.CompatabilityChecker;
import org.khan.solver.cubesolver.puzzle.PuzzlePiece;
import org.khan.solver.cubesolver.puzzle.cube.Cube;
/**
* Abstract puzzle solver class to act as a template for cube solving algorithm, Wil ease
* the task to add more algorithms if required in future.
*
* @author SDK
*
*/
public abstract class AbstractPuzzleSolver implements Strategy{
// compatability checker
protected CompatabilityChecker compatabilityChecker;
// list to save cubes
protected List<Cube> cubesList;
public AbstractPuzzleSolver(CompatabilityChecker compatabilityChecker){
this.compatabilityChecker = compatabilityChecker;
cubesList = new ArrayList<Cube>();
}
/**
* Try different combinations to find cubes, Everytime start with a new cube assuming it as
* bottom face.
*/
public void solvePuzzle(List<PuzzlePiece> pieces, boolean allcubes) {
// trying every cube as a fix bottom cube, to try different possible combinations
// PuzzlePiece []pieceArray = new PuzzlePiece[6];
// int j=0;
// for(PuzzlePiece piece : pieces){
// pieceArray[j] = piece;
// j++;
// }
// List<List<PuzzlePiece>> possiblePermutaions = new ArrayList<List<PuzzlePiece>>();
// permute(pieceArray,0,possiblePermutaions);
// boolean cubeFound;
// int size = pieces.size();
//
// for(List<PuzzlePiece> puzzlePieceList : possiblePermutaions){
// PuzzlePiece assumedBottomPiece = puzzlePieceList.remove(0);
// cubeFound = createCubes(assumedBottomPiece, puzzlePieceList, allcubes);
// if(!allcubes && cubeFound)
// break;
// }
boolean cubeFound;
int size = pieces.size();
for(int i=0;i<size;i++) {
List<PuzzlePiece> restOfPieces = getCopyOfList(pieces);
PuzzlePiece assumedBottomPiece = restOfPieces.remove(i);
cubeFound = createCubes(assumedBottomPiece, restOfPieces, allcubes);
if(!allcubes && cubeFound)
break;
}
}
/**
*
* @param pieces
* @return
*/
private List<PuzzlePiece> getCopyOfList(List<PuzzlePiece> pieces){
List<PuzzlePiece> piecesList = new ArrayList<PuzzlePiece>();
for(PuzzlePiece piece : pieces){
PuzzlePiece copyPiece = new PuzzlePiece(piece);
piecesList.add(copyPiece);
}
return piecesList;
}
/**
* Method to be implemented that will contain main logic to traverse pieces and find cubes
*
* @param bottomPiece
* @param pieces
* @param allcubes
* @return
*/
public abstract boolean createCubes(PuzzlePiece bottomPiece, List<PuzzlePiece> pieces, boolean allcubes);
/**
*
* @return
*/
public List<Cube> getCubeList(){
return cubesList;
}
public void permute(PuzzlePiece[] a, int k, List<List<PuzzlePiece>> puzzlePieceCombinations)
{
if (k == a.length)
{
List<PuzzlePiece> list = new ArrayList<PuzzlePiece>();
for (int i = 0; i < a.length; i++)
{
list.add(new PuzzlePiece(a[i]));
//System.out.print(" [" + a[i] + "] ");
}
puzzlePieceCombinations.add(list);
}
else
{
for (int i = k; i < a.length; i++)
{
PuzzlePiece temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1,puzzlePieceCombinations);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
}
| 5331k/CubeSolver | cubesolver/src/main/java/org/khan/solver/cubesolver/processor/AbstractPuzzleSolver.java | 1,106 | // int j=0;
| line_comment | nl | package org.khan.solver.cubesolver.processor;
import java.util.ArrayList;
import java.util.List;
import org.khan.solver.cubesolver.puzzle.CompatabilityChecker;
import org.khan.solver.cubesolver.puzzle.PuzzlePiece;
import org.khan.solver.cubesolver.puzzle.cube.Cube;
/**
* Abstract puzzle solver class to act as a template for cube solving algorithm, Wil ease
* the task to add more algorithms if required in future.
*
* @author SDK
*
*/
public abstract class AbstractPuzzleSolver implements Strategy{
// compatability checker
protected CompatabilityChecker compatabilityChecker;
// list to save cubes
protected List<Cube> cubesList;
public AbstractPuzzleSolver(CompatabilityChecker compatabilityChecker){
this.compatabilityChecker = compatabilityChecker;
cubesList = new ArrayList<Cube>();
}
/**
* Try different combinations to find cubes, Everytime start with a new cube assuming it as
* bottom face.
*/
public void solvePuzzle(List<PuzzlePiece> pieces, boolean allcubes) {
// trying every cube as a fix bottom cube, to try different possible combinations
// PuzzlePiece []pieceArray = new PuzzlePiece[6];
// int j<SUF>
// for(PuzzlePiece piece : pieces){
// pieceArray[j] = piece;
// j++;
// }
// List<List<PuzzlePiece>> possiblePermutaions = new ArrayList<List<PuzzlePiece>>();
// permute(pieceArray,0,possiblePermutaions);
// boolean cubeFound;
// int size = pieces.size();
//
// for(List<PuzzlePiece> puzzlePieceList : possiblePermutaions){
// PuzzlePiece assumedBottomPiece = puzzlePieceList.remove(0);
// cubeFound = createCubes(assumedBottomPiece, puzzlePieceList, allcubes);
// if(!allcubes && cubeFound)
// break;
// }
boolean cubeFound;
int size = pieces.size();
for(int i=0;i<size;i++) {
List<PuzzlePiece> restOfPieces = getCopyOfList(pieces);
PuzzlePiece assumedBottomPiece = restOfPieces.remove(i);
cubeFound = createCubes(assumedBottomPiece, restOfPieces, allcubes);
if(!allcubes && cubeFound)
break;
}
}
/**
*
* @param pieces
* @return
*/
private List<PuzzlePiece> getCopyOfList(List<PuzzlePiece> pieces){
List<PuzzlePiece> piecesList = new ArrayList<PuzzlePiece>();
for(PuzzlePiece piece : pieces){
PuzzlePiece copyPiece = new PuzzlePiece(piece);
piecesList.add(copyPiece);
}
return piecesList;
}
/**
* Method to be implemented that will contain main logic to traverse pieces and find cubes
*
* @param bottomPiece
* @param pieces
* @param allcubes
* @return
*/
public abstract boolean createCubes(PuzzlePiece bottomPiece, List<PuzzlePiece> pieces, boolean allcubes);
/**
*
* @return
*/
public List<Cube> getCubeList(){
return cubesList;
}
public void permute(PuzzlePiece[] a, int k, List<List<PuzzlePiece>> puzzlePieceCombinations)
{
if (k == a.length)
{
List<PuzzlePiece> list = new ArrayList<PuzzlePiece>();
for (int i = 0; i < a.length; i++)
{
list.add(new PuzzlePiece(a[i]));
//System.out.print(" [" + a[i] + "] ");
}
puzzlePieceCombinations.add(list);
}
else
{
for (int i = k; i < a.length; i++)
{
PuzzlePiece temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1,puzzlePieceCombinations);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
}
|
50735_8 | package Application.Edit;
import data.FestivalPlan;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class EditStage {
public EditStage(FestivalPlan festivalPlan) {
Stage stage = new Stage();// maakt een nieuwe stage
ChoiceBox<data.Stage> stages = new ChoiceBox<>(); // Maakt een nieuwe choicebox
stages.getItems().addAll(festivalPlan.getStages()); // Vult de choicebox met alle stages uit festivalPlan
Button editStage = new Button("Edit"); // Maakt een edit button
Button cancelButton = new Button("Cancel"); // Maakt een cancel button
HBox buttons = new HBox(); // Maakt een hbox
buttons.getChildren().addAll(editStage, cancelButton); // Vult de hbox met de buttons
VBox vBox = new VBox(); // Maakt een vbox
vBox.getChildren().addAll(stages, buttons); // Vult de vbox met de choicebox en de buttons
vBox.setSpacing(10); // Zet de spatie tussen de elementen
Scene scene = new Scene(vBox); // Maakt de scene aan
stage.setScene(scene); // Zet de scene van de stage
stage.setHeight(500); // Zet de hoogte van de stage
stage.setWidth(750); // Zet de breedte van de stage
stage.show(); // Toont de stage
//buttons
cancelButton.setOnAction(event -> { // Als de cancel button wordt aangeklikt
stage.close(); // Sluit de stage
});
editStage.setOnAction(event -> { // Handel de actie af wanneer op de bewerkingsknop wordt geklikt
if (stages.getItems().isEmpty()) { // Controleer of de lijst met podia leeg is
Alert error = new Alert(Alert.AlertType.ERROR); // Toon een foutmelding
error.getDialogPane().setContent(new Label("Selecteer alstublieft een podium om te bewerken!")); // Stel de foutmelding in
error.show(); // Toon de foutmelding
} else { // Als de lijst met podia niet leeg is
stage.close(); // Sluit het huidige venster
Stage artistStage = new Stage(); // Creëer een nieuw venster voor het bewerken van podia
TextField stageName = new TextField(); // Maak een tekstveld voor de podiumnaam
Label stageNameLabel = new Label("Voer alstublieft de nieuwe podiumnaam in."); // Label voor het tekstveld
Button editButton = new Button("Bewerk"); // Knop voor bewerken
Button cancelButtonPopup = new Button("Annuleren"); // Knop voor annuleren
HBox buttonsBox = new HBox(); // Horizontale box voor knoppen
buttonsBox.setSpacing(10); // spatie tussen knoppen
buttonsBox.getChildren().addAll(editButton, cancelButtonPopup); // Voeg knoppen toe aan de box
VBox artistAdd = new VBox(); // Verticale box voor de interface
artistAdd.setSpacing(10); // spatie tussen elementen
artistAdd.getChildren().addAll(stageNameLabel, stageName, buttonsBox); // Voeg label, tekstveld en knoppen toe
cancelButtonPopup.setOnAction(event1 -> { // Handel de actie af wanneer op de annuleringsknop wordt geklikt
artistStage.close(); // Sluit het venster
});
editButton.setOnAction(event1 -> { // Handel de actie af wanneer op de bewerkingsknop wordt geklikt
if (stageName.getText().isEmpty()) { // Controleer of het tekstveld leeg is
Alert alert = new Alert(Alert.AlertType.WARNING); // Toon een waarschuwing
alert.getDialogPane().setContent(new Label("Het tekstveld is leeg, voer alstublieft een naam in.")); // Stel de waarschuwing in
alert.show(); // Toon de waarschuwing
} else { // Als het tekstveld niet leeg is
stages.getSelectionModel().getSelectedItem().setName(stageName.getText()); // Bewerk de geselecteerde podiumnaam
Alert confirmation = new Alert(Alert.AlertType.INFORMATION); // Toon een bevestiging
confirmation.setHeaderText("Succes!"); // Stel de kop van de bevestiging in
confirmation.setContentText("Het podium is succesvol bewerkt!"); // Stel de inhoud van de bevestiging in
confirmation.showAndWait(); // Toon de bevestiging en wacht tot deze wordt gesloten
artistStage.close(); // Sluit het venster voor het bewerken van podia
}
});
Scene stageScene = new Scene(artistAdd); // Maak een scene voor het venster
artistStage.setScene(stageScene); // Stel de scene in voor het venster
artistStage.setWidth(750); // Stel de breedte van het venster in
artistStage.setHeight(500); // Stel de hoogte van het venster in
artistStage.setTitle("Artiest"); // Stel de titel van het venster in
artistStage.show(); // Toon het venster
}
});
}
}
| 589Hours/FestivalPlanner | src/Application/Edit/EditStage.java | 1,182 | // Vult de vbox met de choicebox en de buttons | line_comment | nl | package Application.Edit;
import data.FestivalPlan;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class EditStage {
public EditStage(FestivalPlan festivalPlan) {
Stage stage = new Stage();// maakt een nieuwe stage
ChoiceBox<data.Stage> stages = new ChoiceBox<>(); // Maakt een nieuwe choicebox
stages.getItems().addAll(festivalPlan.getStages()); // Vult de choicebox met alle stages uit festivalPlan
Button editStage = new Button("Edit"); // Maakt een edit button
Button cancelButton = new Button("Cancel"); // Maakt een cancel button
HBox buttons = new HBox(); // Maakt een hbox
buttons.getChildren().addAll(editStage, cancelButton); // Vult de hbox met de buttons
VBox vBox = new VBox(); // Maakt een vbox
vBox.getChildren().addAll(stages, buttons); // Vult <SUF>
vBox.setSpacing(10); // Zet de spatie tussen de elementen
Scene scene = new Scene(vBox); // Maakt de scene aan
stage.setScene(scene); // Zet de scene van de stage
stage.setHeight(500); // Zet de hoogte van de stage
stage.setWidth(750); // Zet de breedte van de stage
stage.show(); // Toont de stage
//buttons
cancelButton.setOnAction(event -> { // Als de cancel button wordt aangeklikt
stage.close(); // Sluit de stage
});
editStage.setOnAction(event -> { // Handel de actie af wanneer op de bewerkingsknop wordt geklikt
if (stages.getItems().isEmpty()) { // Controleer of de lijst met podia leeg is
Alert error = new Alert(Alert.AlertType.ERROR); // Toon een foutmelding
error.getDialogPane().setContent(new Label("Selecteer alstublieft een podium om te bewerken!")); // Stel de foutmelding in
error.show(); // Toon de foutmelding
} else { // Als de lijst met podia niet leeg is
stage.close(); // Sluit het huidige venster
Stage artistStage = new Stage(); // Creëer een nieuw venster voor het bewerken van podia
TextField stageName = new TextField(); // Maak een tekstveld voor de podiumnaam
Label stageNameLabel = new Label("Voer alstublieft de nieuwe podiumnaam in."); // Label voor het tekstveld
Button editButton = new Button("Bewerk"); // Knop voor bewerken
Button cancelButtonPopup = new Button("Annuleren"); // Knop voor annuleren
HBox buttonsBox = new HBox(); // Horizontale box voor knoppen
buttonsBox.setSpacing(10); // spatie tussen knoppen
buttonsBox.getChildren().addAll(editButton, cancelButtonPopup); // Voeg knoppen toe aan de box
VBox artistAdd = new VBox(); // Verticale box voor de interface
artistAdd.setSpacing(10); // spatie tussen elementen
artistAdd.getChildren().addAll(stageNameLabel, stageName, buttonsBox); // Voeg label, tekstveld en knoppen toe
cancelButtonPopup.setOnAction(event1 -> { // Handel de actie af wanneer op de annuleringsknop wordt geklikt
artistStage.close(); // Sluit het venster
});
editButton.setOnAction(event1 -> { // Handel de actie af wanneer op de bewerkingsknop wordt geklikt
if (stageName.getText().isEmpty()) { // Controleer of het tekstveld leeg is
Alert alert = new Alert(Alert.AlertType.WARNING); // Toon een waarschuwing
alert.getDialogPane().setContent(new Label("Het tekstveld is leeg, voer alstublieft een naam in.")); // Stel de waarschuwing in
alert.show(); // Toon de waarschuwing
} else { // Als het tekstveld niet leeg is
stages.getSelectionModel().getSelectedItem().setName(stageName.getText()); // Bewerk de geselecteerde podiumnaam
Alert confirmation = new Alert(Alert.AlertType.INFORMATION); // Toon een bevestiging
confirmation.setHeaderText("Succes!"); // Stel de kop van de bevestiging in
confirmation.setContentText("Het podium is succesvol bewerkt!"); // Stel de inhoud van de bevestiging in
confirmation.showAndWait(); // Toon de bevestiging en wacht tot deze wordt gesloten
artistStage.close(); // Sluit het venster voor het bewerken van podia
}
});
Scene stageScene = new Scene(artistAdd); // Maak een scene voor het venster
artistStage.setScene(stageScene); // Stel de scene in voor het venster
artistStage.setWidth(750); // Stel de breedte van het venster in
artistStage.setHeight(500); // Stel de hoogte van het venster in
artistStage.setTitle("Artiest"); // Stel de titel van het venster in
artistStage.show(); // Toon het venster
}
});
}
}
|
73669_5 | /* Tencent is pleased to support the open source community by making Hippy available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.renderer.node;
import static com.tencent.renderer.NativeRenderException.ExceptionCode.REUSE_VIEW_HAS_ABANDONED_NODE_ERR;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.openhippy.pool.BasePool.PoolType;
import com.tencent.mtt.hippy.dom.node.NodeProps;
import com.tencent.mtt.hippy.uimanager.ControllerManager;
import com.tencent.mtt.hippy.uimanager.RenderManager;
import com.tencent.mtt.hippy.utils.LogUtils;
import com.tencent.mtt.hippy.views.view.HippyViewGroupController;
import com.tencent.renderer.NativeRender;
import com.tencent.renderer.NativeRenderException;
import com.tencent.renderer.component.Component;
import com.tencent.renderer.component.ComponentController;
import com.tencent.renderer.component.image.ImageComponent;
import com.tencent.renderer.component.image.ImageComponentController;
import com.tencent.renderer.utils.DiffUtils;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RenderNode {
private static final String TAG = "RenderNode";
/**
* Mark the layout information of the node to be updated.
*/
public static final int FLAG_UPDATE_LAYOUT = 0x00000001;
/**
* Mark has new extra props of the text node, such as {@link android.text.Layout}
*/
public static final int FLAG_UPDATE_EXTRA = 0x00000002;
/**
* Mark there are new events registered of the node.
*/
public static final int FLAG_UPDATE_EVENT = 0x00000004;
/**
* Mark node need to update node attributes.
*/
public static final int FLAG_UPDATE_TOTAL_PROPS = 0x00000008;
/**
* Mark node has been deleted.
*/
public static final int FLAG_ALREADY_DELETED = 0x00000010;
/**
* Mark node attributes has been updated.
*/
public static final int FLAG_ALREADY_UPDATED = 0x00000020;
/**
* Mark node lazy create host view, such as recycle view item sub views.
*/
public static final int FLAG_LAZY_LOAD = 0x00000040;
/**
* Mark node has attach to host view.
*/
public static final int FLAG_HAS_ATTACHED = 0x00000080;
/**
* Mark should update children drawing order.
*/
public static final int FLAG_UPDATE_DRAWING_ORDER = 0x00000100;
private int mNodeFlags = 0;
private PoolType mPoolInUse = PoolType.NONE;
protected int mX;
protected int mY;
protected int mWidth;
protected int mHeight;
protected final int mId;
protected final int mRootId;
protected final String mClassName;
protected final ArrayList<RenderNode> mChildren = new ArrayList<>();
protected final ArrayList<RenderNode> mChildrenUnattached = new ArrayList<>();
protected final ControllerManager mControllerManager;
@Nullable
protected ArrayList<RenderNode> mDrawingOrder;
@Nullable
protected Map<String, Object> mProps;
@Nullable
protected Map<String, Object> mPropsToUpdate;
@Nullable
protected Map<String, Object> mEvents;
@Nullable
protected RenderNode mParent;
@Nullable
protected Object mExtra;
@Nullable
protected List<RenderNode> mMoveNodes;
@Nullable
protected SparseIntArray mDeletedChildren;
@Nullable
protected Component mComponent;
@Nullable
protected WeakReference<View> mHostViewRef;
public RenderNode(int rootId, int id, @NonNull String className,
@NonNull ControllerManager controllerManager) {
mId = id;
mRootId = rootId;
mClassName = className;
mControllerManager = controllerManager;
}
public RenderNode(int rootId, int id, @Nullable Map<String, Object> props,
@NonNull String className, @NonNull ControllerManager controllerManager,
boolean isLazyLoad) {
mId = id;
mClassName = className;
mRootId = rootId;
mControllerManager = controllerManager;
mProps = props;
mPropsToUpdate = null;
if (isLazyLoad) {
setNodeFlag(FLAG_LAZY_LOAD);
}
}
public int getRootId() {
return mRootId;
}
public int getId() {
return mId;
}
public int getZIndex() {
return mComponent != null ? mComponent.getZIndex() : 0;
}
@NonNull
public ArrayList<RenderNode> getDrawingOrder() {
return mDrawingOrder == null ? mChildren : mDrawingOrder;
}
@Nullable
public Component getComponent() {
return mComponent;
}
@NonNull
public NativeRender getNativeRender() {
return mControllerManager.getNativeRender();
}
@Nullable
public Component ensureComponentIfNeeded(Class<?> cls) {
if (cls == ComponentController.class) {
if (mComponent == null) {
mComponent = new Component(this);
}
} else if (cls == ImageComponentController.class) {
if (mComponent == null) {
mComponent = new ImageComponent(this);
} else if (!(mComponent instanceof ImageComponent)) {
mComponent = new ImageComponent(this, mComponent);
}
}
return mComponent;
}
@Nullable
public RenderNode getParent() {
return mParent;
}
@Nullable
public Object getExtra() {
return mExtra;
}
@Nullable
public Map<String, Object> getProps() {
return mProps;
}
@Nullable
public Map<String, Object> getEvents() {
return mEvents;
}
@NonNull
public String getClassName() {
return mClassName;
}
public int getX() {
return mX;
}
public int getY() {
return mY;
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
public int getChildDrawingOrder(@NonNull RenderNode child) {
return (mDrawingOrder != null) ? mDrawingOrder.indexOf(child) : mChildren.indexOf(child);
}
public int indexFromParent() {
return (mParent != null) ? mParent.mChildren.indexOf(this) : 0;
}
public int indexOfDrawingOrder() {
return (mParent != null) ? mParent.getChildDrawingOrder(this) : 0;
}
protected boolean isRoot() {
return false;
}
public void removeChild(int index) {
try {
removeChild(mChildren.get(index));
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public void resetChildIndex(RenderNode child, int index) {
if (mChildren.contains(child)) {
removeChild(child);
addChild(child, index);
}
}
public boolean removeChild(@Nullable RenderNode node) {
if (node != null) {
node.mParent = null;
if (mDrawingOrder != null) {
mDrawingOrder.remove(node);
}
return mChildren.remove(node);
}
return false;
}
public void addChild(@NonNull RenderNode node) {
addChild(node, mChildren.size());
}
public void addChild(@NonNull RenderNode node, int index) {
index = (index < 0) ? 0 : Math.min(index, mChildren.size());
mChildren.add(index, node);
node.mParent = this;
// If has set z index in the child nodes, the rendering order needs to be rearranged
// after adding nodes
if (mDrawingOrder != null) {
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
}
public void setLazy(boolean isLazy) {
if (isLazy) {
setNodeFlag(FLAG_LAZY_LOAD);
} else {
resetNodeFlag(FLAG_LAZY_LOAD);
}
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null) {
child.setLazy(isLazy);
}
}
}
public void addDeleteChild(@NonNull RenderNode node) {
if (node.hasView()) {
if (mDeletedChildren == null) {
mDeletedChildren = new SparseIntArray();
}
int index = mChildren.indexOf(node);
if (index >= 0) {
mDeletedChildren.put(node.getId(), mChildren.indexOf(node));
}
}
}
@Nullable
public RenderNode getChildAt(int index) {
try {
return mChildren.get(index);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
public int getChildCount() {
return mChildren.size();
}
public void deleteSubviewIfNeeded() {
if (mClassName.equals(NodeProps.ROOT_NODE) && checkNodeFlag(FLAG_ALREADY_DELETED)) {
mControllerManager.deleteRootView(mId);
return;
}
if (mDeletedChildren == null) {
return;
}
for (int i = 0; i < mDeletedChildren.size(); i++) {
mControllerManager
.deleteChild(mRootId, mId, mDeletedChildren.keyAt(i), false);
}
mDeletedChildren.clear();
}
public void setHostView(@Nullable View view) {
if (view == null) {
mHostViewRef = null;
} else {
View current = getHostView();
if (current != view) {
mHostViewRef = new WeakReference<>(view);
}
}
}
@Nullable
public View getHostView() {
return (mHostViewRef != null) ? mHostViewRef.get() : null;
}
public void onHostViewAttachedToWindow() {
LogUtils.d(TAG, "onHostViewAttachedToWindow: id " + mId + ", class name " + mClassName);
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null && child.getHostView() == null) {
Component component = child.getComponent();
if (component != null) {
component.onHostViewAttachedToWindow();
}
}
}
if (mComponent != null) {
mComponent.onHostViewAttachedToWindow();
}
}
public void onHostViewRemoved() {
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null && child.getHostView() == null) {
child.onHostViewRemoved();
}
}
setHostView(null);
if (mComponent != null) {
mComponent.onHostViewRemoved();
}
}
protected void checkHostViewReused() throws NativeRenderException {
View view = getHostView();
if (view == null) {
return;
}
final int oldId = view.getId();
if (oldId == mId) {
return;
}
mControllerManager.replaceId(mRootId, view, mId, false);
RenderNode fromNode = RenderManager.getRenderNode(mRootId, oldId);
if (fromNode == null || fromNode.isDeleted()) {
throw new NativeRenderException(REUSE_VIEW_HAS_ABANDONED_NODE_ERR,
"Reuse view has invalid node id=" + oldId);
}
Map<String, Object> diffProps = checkPropsShouldReset(fromNode);
mControllerManager.updateProps(this, null, null, diffProps, true);
}
@Nullable
public View prepareHostView(boolean skipComponentProps, PoolType poolType) {
if (isLazyLoad()) {
return null;
}
mPoolInUse = poolType;
createView(false);
updateProps(skipComponentProps);
if (poolType == PoolType.RECYCLE_VIEW) {
try {
checkHostViewReused();
} catch (NativeRenderException e) {
mControllerManager.getNativeRender().handleRenderException(e);
}
}
mPoolInUse = PoolType.NONE;
return getHostView();
}
@Nullable
public View createView(boolean createNow) {
deleteSubviewIfNeeded();
if (shouldCreateView() && !TextUtils.equals(NodeProps.ROOT_NODE, mClassName)
&& mParent != null) {
if (mPropsToUpdate == null) {
mPropsToUpdate = getProps();
}
// Do not need to create a view if both self and parent node support flattening
// and no child nodes.
// TODO: Resolve the issue of flattened view node add child
// Add child nodes to flattened view nodes, in some scenes may have issues with the
// page not being able to refresh. Therefore, temporarily turn off flattening the
// regular view node.
if (createNow || !mControllerManager.checkFlatten(mClassName)
|| !mParent.getClassName().equals(HippyViewGroupController.CLASS_NAME)
|| getChildCount() > 0 || checkGestureEnable()) {
mParent.addChildToPendingList(this);
View view = mControllerManager.createView(this, mPoolInUse);
setHostView(view);
return view;
}
}
return null;
}
@Nullable
public View prepareHostViewRecursive() {
boolean skipComponentProps = checkNodeFlag(FLAG_ALREADY_UPDATED);
mPropsToUpdate = getProps();
setNodeFlag(FLAG_UPDATE_LAYOUT | FLAG_UPDATE_EVENT);
View view = prepareHostView(skipComponentProps, PoolType.RECYCLE_VIEW);
for (RenderNode renderNode : mChildren) {
renderNode.prepareHostViewRecursive();
}
return view;
}
public void mountHostViewRecursive() {
mountHostView();
for (RenderNode renderNode : mChildren) {
renderNode.mountHostViewRecursive();
}
}
public boolean shouldSticky() {
return false;
}
@Nullable
protected Map<String, Object> checkPropsShouldReset(@NonNull RenderNode fromNode) {
Map<String, Object> total = null;
Map<String, Object> resetProps = DiffUtils.findResetProps(fromNode.getProps(), mProps);
Map<String, Object> resetEvents = DiffUtils.findResetProps(fromNode.getEvents(), mEvents);
try {
if (resetProps != null) {
total = new HashMap<>(resetProps);
}
if (resetEvents != null) {
if (total == null) {
total = new HashMap<>(resetEvents);
} else {
total.putAll(resetEvents);
}
}
} catch (Exception e) {
LogUtils.w(TAG, "checkNonExistentProps: " + e.getMessage());
}
return total;
}
public void updateProps(boolean skipComponentProps) {
Map<String, Object> events = null;
if (mEvents != null && checkNodeFlag(FLAG_UPDATE_EVENT)) {
events = mEvents;
resetNodeFlag(FLAG_UPDATE_EVENT);
}
mControllerManager.updateProps(this, mPropsToUpdate, events, null, skipComponentProps);
mPropsToUpdate = null;
resetNodeFlag(FLAG_UPDATE_TOTAL_PROPS);
}
private boolean shouldCreateView() {
return !isDeleted() && !isLazyLoad() && !hasView();
}
private boolean hasView() {
return mControllerManager.hasView(mRootId, mId);
}
protected void addChildToPendingList(RenderNode child) {
if (!mChildrenUnattached.contains(child)) {
mChildrenUnattached.add(child);
}
}
public boolean checkNodeFlag(int flag) {
return (mNodeFlags & flag) == flag;
}
public void resetNodeFlag(int flag) {
mNodeFlags &= ~flag;
}
public void setNodeFlag(int flag) {
mNodeFlags |= flag;
}
public void mountHostView() {
// Before mounting child views, if there is a change in the Z index of the child nodes,
// it is necessary to reorder the child nodes to ensure the correct mounting order.
updateDrawingOrderIfNeeded();
if (!mChildrenUnattached.isEmpty()) {
Collections.sort(mChildrenUnattached, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode n1, RenderNode n2) {
return n1.getZIndex() - n2.getZIndex();
}
});
for (int i = 0; i < mChildrenUnattached.size(); i++) {
RenderNode node = mChildrenUnattached.get(i);
mControllerManager.addChild(mRootId, mId, node);
node.setNodeFlag(FLAG_HAS_ATTACHED);
}
mChildrenUnattached.clear();
}
if (mMoveNodes != null && !mMoveNodes.isEmpty()) {
Collections.sort(mMoveNodes, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode o1, RenderNode o2) {
return o1.indexFromParent() < o2.indexFromParent() ? -1 : 0;
}
});
for (RenderNode moveNode : mMoveNodes) {
mControllerManager.moveView(mRootId, moveNode.getId(), mId,
getChildDrawingOrder(moveNode));
}
mMoveNodes.clear();
}
if (checkNodeFlag(FLAG_UPDATE_LAYOUT) && !TextUtils
.equals(NodeProps.ROOT_NODE, mClassName)) {
mControllerManager.updateLayout(mClassName, mRootId, mId, mX, mY, mWidth, mHeight);
resetNodeFlag(FLAG_UPDATE_LAYOUT);
}
if (checkNodeFlag(FLAG_UPDATE_EXTRA)) {
mControllerManager.updateExtra(mRootId, mId, mClassName, mExtra);
resetNodeFlag(FLAG_UPDATE_EXTRA);
}
}
public static void resetProps(@NonNull Map<String, Object> props,
@Nullable Map<String, Object> diffProps,
@Nullable List<Object> delProps) {
try {
if (diffProps != null) {
props.putAll(diffProps);
}
if (delProps != null) {
for (Object key : delProps) {
props.remove(key.toString());
}
}
} catch (Exception e) {
LogUtils.e(TAG, "updateProps error:" + e.getMessage());
}
}
public void checkPropsToUpdate(@Nullable Map<String, Object> diffProps,
@Nullable List<Object> delProps) {
if (mProps == null) {
mProps = new HashMap<>();
}
resetProps(mProps, diffProps, delProps);
if (!checkNodeFlag(FLAG_UPDATE_TOTAL_PROPS)) {
if (mPropsToUpdate == null) {
mPropsToUpdate = diffProps;
} else {
if (diffProps != null) {
mPropsToUpdate.putAll(diffProps);
}
}
if (delProps != null) {
if (mPropsToUpdate == null) {
mPropsToUpdate = new HashMap<>();
}
for (Object key : delProps) {
mPropsToUpdate.put(key.toString(), null);
}
}
} else {
mPropsToUpdate = mProps;
}
}
public void updateEventListener(@NonNull Map<String, Object> newEvents) {
mEvents = newEvents;
setNodeFlag(FLAG_UPDATE_EVENT);
}
public void updateLayout(int x, int y, int w, int h) {
mX = x;
mY = y;
mWidth = w;
mHeight = h;
setNodeFlag(FLAG_UPDATE_LAYOUT);
}
public void addMoveNodes(@NonNull List<RenderNode> moveNodes) {
if (mMoveNodes == null) {
mMoveNodes = new ArrayList<>();
}
mMoveNodes.addAll(moveNodes);
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
public void updateExtra(@Nullable Object object) {
Component component = ensureComponentIfNeeded(ComponentController.class);
if (component != null && object != null) {
component.setTextLayout(object);
setNodeFlag(FLAG_UPDATE_EXTRA);
}
}
public boolean isDeleted() {
return checkNodeFlag(FLAG_ALREADY_DELETED);
}
public boolean isLazyLoad() {
return checkNodeFlag(FLAG_LAZY_LOAD);
}
public boolean checkRegisteredEvent(@NonNull String eventName) {
if (mEvents != null && mEvents.containsKey(eventName)) {
Object value = mEvents.get(eventName);
if (value instanceof Boolean) {
return (boolean) value;
}
}
return false;
}
public void onDeleted() {
if (mComponent != null) {
mComponent.clear();
}
}
public void requireUpdateDrawingOrder(@NonNull RenderNode child) {
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
addChildToPendingList(child);
}
public void onZIndexChanged() {
if (mParent != null) {
View hostView = getHostView();
if (hostView != null) {
ViewParent parent = hostView.getParent();
if (parent != null) {
((ViewGroup) parent).removeView(hostView);
}
}
mParent.requireUpdateDrawingOrder(this);
}
}
public void updateDrawingOrderIfNeeded() {
if (checkNodeFlag(FLAG_UPDATE_DRAWING_ORDER)) {
mDrawingOrder = (ArrayList<RenderNode>) mChildren.clone();
Collections.sort(mDrawingOrder, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode n1, RenderNode n2) {
return n1.getZIndex() - n2.getZIndex();
}
});
resetNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
}
public void batchStart() {
if (!isDeleted() && !isLazyLoad()) {
mControllerManager.onBatchStart(mRootId, mId, mClassName);
}
}
public void batchComplete() {
if (!isDeleted() && !isLazyLoad()) {
mControllerManager.onBatchComplete(mRootId, mId, mClassName);
if (mHostViewRef == null || mHostViewRef.get() == null) {
invalidate();
}
}
}
@Nullable
private View findNearestHostView() {
View view = mControllerManager.findView(mRootId, mId);
if (view == null && mParent != null) {
view = mControllerManager.findView(mParent.getRootId(), mParent.getId());
}
return view;
}
public void postInvalidateDelayed(long delayMilliseconds) {
View view = findNearestHostView();
if (view != null) {
view.postInvalidateDelayed(delayMilliseconds);
}
}
public void invalidate() {
View view = findNearestHostView();
if (view != null) {
view.invalidate();
}
}
public boolean checkGestureEnable() {
return mComponent != null && mComponent.getGestureEnable();
}
}
| 5l1v3r1/Hippy | renderer/native/android/src/main/java/com/tencent/renderer/node/RenderNode.java | 6,223 | /**
* Mark node has been deleted.
*/ | block_comment | nl | /* Tencent is pleased to support the open source community by making Hippy available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.renderer.node;
import static com.tencent.renderer.NativeRenderException.ExceptionCode.REUSE_VIEW_HAS_ABANDONED_NODE_ERR;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.openhippy.pool.BasePool.PoolType;
import com.tencent.mtt.hippy.dom.node.NodeProps;
import com.tencent.mtt.hippy.uimanager.ControllerManager;
import com.tencent.mtt.hippy.uimanager.RenderManager;
import com.tencent.mtt.hippy.utils.LogUtils;
import com.tencent.mtt.hippy.views.view.HippyViewGroupController;
import com.tencent.renderer.NativeRender;
import com.tencent.renderer.NativeRenderException;
import com.tencent.renderer.component.Component;
import com.tencent.renderer.component.ComponentController;
import com.tencent.renderer.component.image.ImageComponent;
import com.tencent.renderer.component.image.ImageComponentController;
import com.tencent.renderer.utils.DiffUtils;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RenderNode {
private static final String TAG = "RenderNode";
/**
* Mark the layout information of the node to be updated.
*/
public static final int FLAG_UPDATE_LAYOUT = 0x00000001;
/**
* Mark has new extra props of the text node, such as {@link android.text.Layout}
*/
public static final int FLAG_UPDATE_EXTRA = 0x00000002;
/**
* Mark there are new events registered of the node.
*/
public static final int FLAG_UPDATE_EVENT = 0x00000004;
/**
* Mark node need to update node attributes.
*/
public static final int FLAG_UPDATE_TOTAL_PROPS = 0x00000008;
/**
* Mark n<SUF>*/
public static final int FLAG_ALREADY_DELETED = 0x00000010;
/**
* Mark node attributes has been updated.
*/
public static final int FLAG_ALREADY_UPDATED = 0x00000020;
/**
* Mark node lazy create host view, such as recycle view item sub views.
*/
public static final int FLAG_LAZY_LOAD = 0x00000040;
/**
* Mark node has attach to host view.
*/
public static final int FLAG_HAS_ATTACHED = 0x00000080;
/**
* Mark should update children drawing order.
*/
public static final int FLAG_UPDATE_DRAWING_ORDER = 0x00000100;
private int mNodeFlags = 0;
private PoolType mPoolInUse = PoolType.NONE;
protected int mX;
protected int mY;
protected int mWidth;
protected int mHeight;
protected final int mId;
protected final int mRootId;
protected final String mClassName;
protected final ArrayList<RenderNode> mChildren = new ArrayList<>();
protected final ArrayList<RenderNode> mChildrenUnattached = new ArrayList<>();
protected final ControllerManager mControllerManager;
@Nullable
protected ArrayList<RenderNode> mDrawingOrder;
@Nullable
protected Map<String, Object> mProps;
@Nullable
protected Map<String, Object> mPropsToUpdate;
@Nullable
protected Map<String, Object> mEvents;
@Nullable
protected RenderNode mParent;
@Nullable
protected Object mExtra;
@Nullable
protected List<RenderNode> mMoveNodes;
@Nullable
protected SparseIntArray mDeletedChildren;
@Nullable
protected Component mComponent;
@Nullable
protected WeakReference<View> mHostViewRef;
public RenderNode(int rootId, int id, @NonNull String className,
@NonNull ControllerManager controllerManager) {
mId = id;
mRootId = rootId;
mClassName = className;
mControllerManager = controllerManager;
}
public RenderNode(int rootId, int id, @Nullable Map<String, Object> props,
@NonNull String className, @NonNull ControllerManager controllerManager,
boolean isLazyLoad) {
mId = id;
mClassName = className;
mRootId = rootId;
mControllerManager = controllerManager;
mProps = props;
mPropsToUpdate = null;
if (isLazyLoad) {
setNodeFlag(FLAG_LAZY_LOAD);
}
}
public int getRootId() {
return mRootId;
}
public int getId() {
return mId;
}
public int getZIndex() {
return mComponent != null ? mComponent.getZIndex() : 0;
}
@NonNull
public ArrayList<RenderNode> getDrawingOrder() {
return mDrawingOrder == null ? mChildren : mDrawingOrder;
}
@Nullable
public Component getComponent() {
return mComponent;
}
@NonNull
public NativeRender getNativeRender() {
return mControllerManager.getNativeRender();
}
@Nullable
public Component ensureComponentIfNeeded(Class<?> cls) {
if (cls == ComponentController.class) {
if (mComponent == null) {
mComponent = new Component(this);
}
} else if (cls == ImageComponentController.class) {
if (mComponent == null) {
mComponent = new ImageComponent(this);
} else if (!(mComponent instanceof ImageComponent)) {
mComponent = new ImageComponent(this, mComponent);
}
}
return mComponent;
}
@Nullable
public RenderNode getParent() {
return mParent;
}
@Nullable
public Object getExtra() {
return mExtra;
}
@Nullable
public Map<String, Object> getProps() {
return mProps;
}
@Nullable
public Map<String, Object> getEvents() {
return mEvents;
}
@NonNull
public String getClassName() {
return mClassName;
}
public int getX() {
return mX;
}
public int getY() {
return mY;
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
public int getChildDrawingOrder(@NonNull RenderNode child) {
return (mDrawingOrder != null) ? mDrawingOrder.indexOf(child) : mChildren.indexOf(child);
}
public int indexFromParent() {
return (mParent != null) ? mParent.mChildren.indexOf(this) : 0;
}
public int indexOfDrawingOrder() {
return (mParent != null) ? mParent.getChildDrawingOrder(this) : 0;
}
protected boolean isRoot() {
return false;
}
public void removeChild(int index) {
try {
removeChild(mChildren.get(index));
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public void resetChildIndex(RenderNode child, int index) {
if (mChildren.contains(child)) {
removeChild(child);
addChild(child, index);
}
}
public boolean removeChild(@Nullable RenderNode node) {
if (node != null) {
node.mParent = null;
if (mDrawingOrder != null) {
mDrawingOrder.remove(node);
}
return mChildren.remove(node);
}
return false;
}
public void addChild(@NonNull RenderNode node) {
addChild(node, mChildren.size());
}
public void addChild(@NonNull RenderNode node, int index) {
index = (index < 0) ? 0 : Math.min(index, mChildren.size());
mChildren.add(index, node);
node.mParent = this;
// If has set z index in the child nodes, the rendering order needs to be rearranged
// after adding nodes
if (mDrawingOrder != null) {
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
}
public void setLazy(boolean isLazy) {
if (isLazy) {
setNodeFlag(FLAG_LAZY_LOAD);
} else {
resetNodeFlag(FLAG_LAZY_LOAD);
}
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null) {
child.setLazy(isLazy);
}
}
}
public void addDeleteChild(@NonNull RenderNode node) {
if (node.hasView()) {
if (mDeletedChildren == null) {
mDeletedChildren = new SparseIntArray();
}
int index = mChildren.indexOf(node);
if (index >= 0) {
mDeletedChildren.put(node.getId(), mChildren.indexOf(node));
}
}
}
@Nullable
public RenderNode getChildAt(int index) {
try {
return mChildren.get(index);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
return null;
}
}
public int getChildCount() {
return mChildren.size();
}
public void deleteSubviewIfNeeded() {
if (mClassName.equals(NodeProps.ROOT_NODE) && checkNodeFlag(FLAG_ALREADY_DELETED)) {
mControllerManager.deleteRootView(mId);
return;
}
if (mDeletedChildren == null) {
return;
}
for (int i = 0; i < mDeletedChildren.size(); i++) {
mControllerManager
.deleteChild(mRootId, mId, mDeletedChildren.keyAt(i), false);
}
mDeletedChildren.clear();
}
public void setHostView(@Nullable View view) {
if (view == null) {
mHostViewRef = null;
} else {
View current = getHostView();
if (current != view) {
mHostViewRef = new WeakReference<>(view);
}
}
}
@Nullable
public View getHostView() {
return (mHostViewRef != null) ? mHostViewRef.get() : null;
}
public void onHostViewAttachedToWindow() {
LogUtils.d(TAG, "onHostViewAttachedToWindow: id " + mId + ", class name " + mClassName);
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null && child.getHostView() == null) {
Component component = child.getComponent();
if (component != null) {
component.onHostViewAttachedToWindow();
}
}
}
if (mComponent != null) {
mComponent.onHostViewAttachedToWindow();
}
}
public void onHostViewRemoved() {
for (int i = 0; i < getChildCount(); i++) {
RenderNode child = getChildAt(i);
if (child != null && child.getHostView() == null) {
child.onHostViewRemoved();
}
}
setHostView(null);
if (mComponent != null) {
mComponent.onHostViewRemoved();
}
}
protected void checkHostViewReused() throws NativeRenderException {
View view = getHostView();
if (view == null) {
return;
}
final int oldId = view.getId();
if (oldId == mId) {
return;
}
mControllerManager.replaceId(mRootId, view, mId, false);
RenderNode fromNode = RenderManager.getRenderNode(mRootId, oldId);
if (fromNode == null || fromNode.isDeleted()) {
throw new NativeRenderException(REUSE_VIEW_HAS_ABANDONED_NODE_ERR,
"Reuse view has invalid node id=" + oldId);
}
Map<String, Object> diffProps = checkPropsShouldReset(fromNode);
mControllerManager.updateProps(this, null, null, diffProps, true);
}
@Nullable
public View prepareHostView(boolean skipComponentProps, PoolType poolType) {
if (isLazyLoad()) {
return null;
}
mPoolInUse = poolType;
createView(false);
updateProps(skipComponentProps);
if (poolType == PoolType.RECYCLE_VIEW) {
try {
checkHostViewReused();
} catch (NativeRenderException e) {
mControllerManager.getNativeRender().handleRenderException(e);
}
}
mPoolInUse = PoolType.NONE;
return getHostView();
}
@Nullable
public View createView(boolean createNow) {
deleteSubviewIfNeeded();
if (shouldCreateView() && !TextUtils.equals(NodeProps.ROOT_NODE, mClassName)
&& mParent != null) {
if (mPropsToUpdate == null) {
mPropsToUpdate = getProps();
}
// Do not need to create a view if both self and parent node support flattening
// and no child nodes.
// TODO: Resolve the issue of flattened view node add child
// Add child nodes to flattened view nodes, in some scenes may have issues with the
// page not being able to refresh. Therefore, temporarily turn off flattening the
// regular view node.
if (createNow || !mControllerManager.checkFlatten(mClassName)
|| !mParent.getClassName().equals(HippyViewGroupController.CLASS_NAME)
|| getChildCount() > 0 || checkGestureEnable()) {
mParent.addChildToPendingList(this);
View view = mControllerManager.createView(this, mPoolInUse);
setHostView(view);
return view;
}
}
return null;
}
@Nullable
public View prepareHostViewRecursive() {
boolean skipComponentProps = checkNodeFlag(FLAG_ALREADY_UPDATED);
mPropsToUpdate = getProps();
setNodeFlag(FLAG_UPDATE_LAYOUT | FLAG_UPDATE_EVENT);
View view = prepareHostView(skipComponentProps, PoolType.RECYCLE_VIEW);
for (RenderNode renderNode : mChildren) {
renderNode.prepareHostViewRecursive();
}
return view;
}
public void mountHostViewRecursive() {
mountHostView();
for (RenderNode renderNode : mChildren) {
renderNode.mountHostViewRecursive();
}
}
public boolean shouldSticky() {
return false;
}
@Nullable
protected Map<String, Object> checkPropsShouldReset(@NonNull RenderNode fromNode) {
Map<String, Object> total = null;
Map<String, Object> resetProps = DiffUtils.findResetProps(fromNode.getProps(), mProps);
Map<String, Object> resetEvents = DiffUtils.findResetProps(fromNode.getEvents(), mEvents);
try {
if (resetProps != null) {
total = new HashMap<>(resetProps);
}
if (resetEvents != null) {
if (total == null) {
total = new HashMap<>(resetEvents);
} else {
total.putAll(resetEvents);
}
}
} catch (Exception e) {
LogUtils.w(TAG, "checkNonExistentProps: " + e.getMessage());
}
return total;
}
public void updateProps(boolean skipComponentProps) {
Map<String, Object> events = null;
if (mEvents != null && checkNodeFlag(FLAG_UPDATE_EVENT)) {
events = mEvents;
resetNodeFlag(FLAG_UPDATE_EVENT);
}
mControllerManager.updateProps(this, mPropsToUpdate, events, null, skipComponentProps);
mPropsToUpdate = null;
resetNodeFlag(FLAG_UPDATE_TOTAL_PROPS);
}
private boolean shouldCreateView() {
return !isDeleted() && !isLazyLoad() && !hasView();
}
private boolean hasView() {
return mControllerManager.hasView(mRootId, mId);
}
protected void addChildToPendingList(RenderNode child) {
if (!mChildrenUnattached.contains(child)) {
mChildrenUnattached.add(child);
}
}
public boolean checkNodeFlag(int flag) {
return (mNodeFlags & flag) == flag;
}
public void resetNodeFlag(int flag) {
mNodeFlags &= ~flag;
}
public void setNodeFlag(int flag) {
mNodeFlags |= flag;
}
public void mountHostView() {
// Before mounting child views, if there is a change in the Z index of the child nodes,
// it is necessary to reorder the child nodes to ensure the correct mounting order.
updateDrawingOrderIfNeeded();
if (!mChildrenUnattached.isEmpty()) {
Collections.sort(mChildrenUnattached, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode n1, RenderNode n2) {
return n1.getZIndex() - n2.getZIndex();
}
});
for (int i = 0; i < mChildrenUnattached.size(); i++) {
RenderNode node = mChildrenUnattached.get(i);
mControllerManager.addChild(mRootId, mId, node);
node.setNodeFlag(FLAG_HAS_ATTACHED);
}
mChildrenUnattached.clear();
}
if (mMoveNodes != null && !mMoveNodes.isEmpty()) {
Collections.sort(mMoveNodes, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode o1, RenderNode o2) {
return o1.indexFromParent() < o2.indexFromParent() ? -1 : 0;
}
});
for (RenderNode moveNode : mMoveNodes) {
mControllerManager.moveView(mRootId, moveNode.getId(), mId,
getChildDrawingOrder(moveNode));
}
mMoveNodes.clear();
}
if (checkNodeFlag(FLAG_UPDATE_LAYOUT) && !TextUtils
.equals(NodeProps.ROOT_NODE, mClassName)) {
mControllerManager.updateLayout(mClassName, mRootId, mId, mX, mY, mWidth, mHeight);
resetNodeFlag(FLAG_UPDATE_LAYOUT);
}
if (checkNodeFlag(FLAG_UPDATE_EXTRA)) {
mControllerManager.updateExtra(mRootId, mId, mClassName, mExtra);
resetNodeFlag(FLAG_UPDATE_EXTRA);
}
}
public static void resetProps(@NonNull Map<String, Object> props,
@Nullable Map<String, Object> diffProps,
@Nullable List<Object> delProps) {
try {
if (diffProps != null) {
props.putAll(diffProps);
}
if (delProps != null) {
for (Object key : delProps) {
props.remove(key.toString());
}
}
} catch (Exception e) {
LogUtils.e(TAG, "updateProps error:" + e.getMessage());
}
}
public void checkPropsToUpdate(@Nullable Map<String, Object> diffProps,
@Nullable List<Object> delProps) {
if (mProps == null) {
mProps = new HashMap<>();
}
resetProps(mProps, diffProps, delProps);
if (!checkNodeFlag(FLAG_UPDATE_TOTAL_PROPS)) {
if (mPropsToUpdate == null) {
mPropsToUpdate = diffProps;
} else {
if (diffProps != null) {
mPropsToUpdate.putAll(diffProps);
}
}
if (delProps != null) {
if (mPropsToUpdate == null) {
mPropsToUpdate = new HashMap<>();
}
for (Object key : delProps) {
mPropsToUpdate.put(key.toString(), null);
}
}
} else {
mPropsToUpdate = mProps;
}
}
public void updateEventListener(@NonNull Map<String, Object> newEvents) {
mEvents = newEvents;
setNodeFlag(FLAG_UPDATE_EVENT);
}
public void updateLayout(int x, int y, int w, int h) {
mX = x;
mY = y;
mWidth = w;
mHeight = h;
setNodeFlag(FLAG_UPDATE_LAYOUT);
}
public void addMoveNodes(@NonNull List<RenderNode> moveNodes) {
if (mMoveNodes == null) {
mMoveNodes = new ArrayList<>();
}
mMoveNodes.addAll(moveNodes);
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
public void updateExtra(@Nullable Object object) {
Component component = ensureComponentIfNeeded(ComponentController.class);
if (component != null && object != null) {
component.setTextLayout(object);
setNodeFlag(FLAG_UPDATE_EXTRA);
}
}
public boolean isDeleted() {
return checkNodeFlag(FLAG_ALREADY_DELETED);
}
public boolean isLazyLoad() {
return checkNodeFlag(FLAG_LAZY_LOAD);
}
public boolean checkRegisteredEvent(@NonNull String eventName) {
if (mEvents != null && mEvents.containsKey(eventName)) {
Object value = mEvents.get(eventName);
if (value instanceof Boolean) {
return (boolean) value;
}
}
return false;
}
public void onDeleted() {
if (mComponent != null) {
mComponent.clear();
}
}
public void requireUpdateDrawingOrder(@NonNull RenderNode child) {
setNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
addChildToPendingList(child);
}
public void onZIndexChanged() {
if (mParent != null) {
View hostView = getHostView();
if (hostView != null) {
ViewParent parent = hostView.getParent();
if (parent != null) {
((ViewGroup) parent).removeView(hostView);
}
}
mParent.requireUpdateDrawingOrder(this);
}
}
public void updateDrawingOrderIfNeeded() {
if (checkNodeFlag(FLAG_UPDATE_DRAWING_ORDER)) {
mDrawingOrder = (ArrayList<RenderNode>) mChildren.clone();
Collections.sort(mDrawingOrder, new Comparator<RenderNode>() {
@Override
public int compare(RenderNode n1, RenderNode n2) {
return n1.getZIndex() - n2.getZIndex();
}
});
resetNodeFlag(FLAG_UPDATE_DRAWING_ORDER);
}
}
public void batchStart() {
if (!isDeleted() && !isLazyLoad()) {
mControllerManager.onBatchStart(mRootId, mId, mClassName);
}
}
public void batchComplete() {
if (!isDeleted() && !isLazyLoad()) {
mControllerManager.onBatchComplete(mRootId, mId, mClassName);
if (mHostViewRef == null || mHostViewRef.get() == null) {
invalidate();
}
}
}
@Nullable
private View findNearestHostView() {
View view = mControllerManager.findView(mRootId, mId);
if (view == null && mParent != null) {
view = mControllerManager.findView(mParent.getRootId(), mParent.getId());
}
return view;
}
public void postInvalidateDelayed(long delayMilliseconds) {
View view = findNearestHostView();
if (view != null) {
view.postInvalidateDelayed(delayMilliseconds);
}
}
public void invalidate() {
View view = findNearestHostView();
if (view != null) {
view.invalidate();
}
}
public boolean checkGestureEnable() {
return mComponent != null && mComponent.getGestureEnable();
}
}
|
160594_12 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.decrypter;
import java.util.ArrayList;
import jd.PluginWrapper;
import jd.controlling.ProgressController;
import jd.http.Browser;
import jd.nutils.encoding.Encoding;
import jd.plugins.CryptedLink;
import jd.plugins.DecrypterPlugin;
import jd.plugins.DownloadLink;
import jd.plugins.FilePackage;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForDecrypt;
@DecrypterPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "voirfilms.ec" }, urls = { "https?://(?:\\w+\\.)?voirfilms\\.ec/[^/]+\\.html?" })
public class VoirFilms extends PluginForDecrypt {
public VoirFilms(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception {
final ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
final String parameter = param.toString();
// Load page
br.setFollowRedirects(true);
br.getPage(parameter);
final String fpName = br.getRegex("<title>(?:\\s*film\\s+)?([^<]+)(?:\\s+streaming vf\\s*)").getMatch(0);
final String[] links = br.getRegex("(?:href|data-src)\\s*=\\s*\"((?!javascript)[^\"]+)\"[^>]+target\\s*=\\s*\"filmPlayer").getColumn(0);
if (links != null && links.length > 0) {
for (String link : links) {
link = Encoding.htmlDecode(link);
if (link.contains("/video.php?")) {
final Browser brc = br.cloneBrowser();
brc.setFollowRedirects(false);
brc.getPage(link);
final String redirect = brc.getRedirectLocation();
if (redirect != null) {
decryptedLinks.add(createDownloadlink(redirect));
} else {
final String refresh = brc.getRegex("<META\\s*HTTP-EQUIV\\s*=\\s*\"Refresh\"\\s*CONTENT\\s*=\"\\d+;\\s*URL\\s*=\\s*(https?://[^<>\"']+)\"").getMatch(0);
if (refresh != null) {
decryptedLinks.add(createDownloadlink(refresh));
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
} else {
decryptedLinks.add(createDownloadlink(link));
}
}
}
if (fpName != null) {
final FilePackage filePackage = FilePackage.getInstance();
filePackage.setName(Encoding.htmlDecode(fpName));
filePackage.addLinks(decryptedLinks);
}
return decryptedLinks;
}
} | 5l1v3r1/jdownloader | src/jd/plugins/decrypter/VoirFilms.java | 905 | //(?:\\w+\\.)?voirfilms\\.ec/[^/]+\\.html?" })
| line_comment | nl | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.decrypter;
import java.util.ArrayList;
import jd.PluginWrapper;
import jd.controlling.ProgressController;
import jd.http.Browser;
import jd.nutils.encoding.Encoding;
import jd.plugins.CryptedLink;
import jd.plugins.DecrypterPlugin;
import jd.plugins.DownloadLink;
import jd.plugins.FilePackage;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForDecrypt;
@DecrypterPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "voirfilms.ec" }, urls = { "https?://(?:\\<SUF>
public class VoirFilms extends PluginForDecrypt {
public VoirFilms(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception {
final ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
final String parameter = param.toString();
// Load page
br.setFollowRedirects(true);
br.getPage(parameter);
final String fpName = br.getRegex("<title>(?:\\s*film\\s+)?([^<]+)(?:\\s+streaming vf\\s*)").getMatch(0);
final String[] links = br.getRegex("(?:href|data-src)\\s*=\\s*\"((?!javascript)[^\"]+)\"[^>]+target\\s*=\\s*\"filmPlayer").getColumn(0);
if (links != null && links.length > 0) {
for (String link : links) {
link = Encoding.htmlDecode(link);
if (link.contains("/video.php?")) {
final Browser brc = br.cloneBrowser();
brc.setFollowRedirects(false);
brc.getPage(link);
final String redirect = brc.getRedirectLocation();
if (redirect != null) {
decryptedLinks.add(createDownloadlink(redirect));
} else {
final String refresh = brc.getRegex("<META\\s*HTTP-EQUIV\\s*=\\s*\"Refresh\"\\s*CONTENT\\s*=\"\\d+;\\s*URL\\s*=\\s*(https?://[^<>\"']+)\"").getMatch(0);
if (refresh != null) {
decryptedLinks.add(createDownloadlink(refresh));
} else {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
} else {
decryptedLinks.add(createDownloadlink(link));
}
}
}
if (fpName != null) {
final FilePackage filePackage = FilePackage.getInstance();
filePackage.setName(Encoding.htmlDecode(fpName));
filePackage.addLinks(decryptedLinks);
}
return decryptedLinks;
}
} |
81329_34 | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.data;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.util.NumberFormatUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
* Provides static methods for saving data to files.
*
* @author Joseph Ramsey
*/
public final class DataWriter {
/**
* Writes a dataset to file. The dataset may have continuous and/or discrete
* columns. Note that <code>out</code> is not closed by this method, so
* the close method on <code>out</code> will need to be called externally.
*
* @param dataSet The data set to save.
* @param out The writer to write the output to.
* @param separator The character separating fields, usually '\t' or ','.
* @throws IOException If there is some problem dealing with the writer.
*/
public static void writeRectangularData(DataSet dataSet,
Writer out, char separator) throws IOException {
NumberFormat nf = NumberFormatUtil.getInstance().getNumberFormat();
StringBuilder buf = new StringBuilder();
// boolean isCaseMultipliersCollapsed = dataSet.isMulipliersCollapsed();
// if (false) {
// buf.append("MULT").append(separator);
// }
for (int col = 0; col < dataSet.getNumColumns(); col++) {
String name = dataSet.getVariable(col).getName();
if (name.trim().equals("")) {
name = "C" + (col - 1);
}
buf.append(name);
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
}
for (int row = 0; row < dataSet.getNumRows(); row++) {
buf.append("\n");
// if (isCaseMultipliersCollapsed) {
// int multiplier = dataSet.getMultiplier(row);
// buf.append(multiplier).append(separator);
// }
for (int col = 0; col < dataSet.getNumColumns(); col++) {
Node variable = dataSet.getVariable(col);
if (variable instanceof ContinuousVariable) {
double value = dataSet.getDouble(row, col);
if (ContinuousVariable.isDoubleMissingValue(value)) {
buf.append("*");
} else {
buf.append(nf.format(value));
}
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
} else if (variable instanceof DiscreteVariable) {
Object obj = dataSet.getObject(row, col);
String val = ((obj == null) ? "" : obj.toString());
buf.append(val);
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
}
}
}
buf.append("\n");
out.write(buf.toString());
out.close();
}
// /**
// * Writes a dataset to file. The dataset may have continuous and/or discrete
// * columns. Note that <code>out</code> is not closed by this method, so
// * the close method on <code>out</code> will need to be called externally.
// *
// * @param dataSet The data set to save.
// * @param out The writer to write the output to.
// * @param separator The character separating fields, usually '\t' or ','.
// */
// public static void writeRectangularDataALittleFaster(DataSet dataSet,
// PrintWriter out, char separator) {
// NumberFormat nf = new DecimalFormat("0.0000");
//// StringBuilder buf = new StringBuilder();
//
// for (int col = 0; col < dataSet.getNumColumns(); col++) {
// String name = dataSet.getVariable(col).getNode();
//
// if (name.trim().equals("")) {
// name = "C" + (col - 1);
// }
//
// out.append(name);
//
// if (col < dataSet.getNumColumns() - 1) {
// out.append(separator);
// }
// }
//
// for (int row = 0; row < dataSet.getNumRows(); row++) {
// out.append("\n");
//
// for (int col = 0; col < dataSet.getNumColumns(); col++) {
// Node variable = dataSet.getVariable(col);
//
// if (variable instanceof ContinuousVariable) {
// double value = dataSet.getDouble(row, col);
//
// if (ContinuousVariable.isDoubleMissingValue(value)) {
// out.print("*");
// } else {
// out.print(nf.format(value));
//// out.print(value);
// }
//
// if (col < dataSet.getNumColumns() - 1) {
// out.print(separator);
// }
// } else if (variable instanceof DiscreteVariable) {
// Object obj = dataSet.getObject(row, col);
// String val = ((obj == null) ? "" : obj.toString());
//
// out.print(val);
//
// if (col < dataSet.getNumColumns() - 1) {
// out.print(separator);
// }
// }
// }
// }
//
// out.print("\n");
// out.close();
// }
/**
* Writes the lower triangle of a covariance matrix to file. Note that
* <code>out</code> is not closed by this method, so the close method on
* <code>out</code> will need to be called externally.
*
* @param out The writer to write the output to.
*/
public static void writeCovMatrix(ICovarianceMatrix covMatrix,
PrintWriter out, NumberFormat nf) {
// out.println("/Covariance");
out.println(covMatrix.getSampleSize());
List<String> variables = covMatrix.getVariableNames();
int numVars = variables.size();
int varCount = 0;
for (String variable : variables) {
varCount++;
if (varCount < numVars) {
out.print(variable);
out.print("\t");
} else {
out.println(variable);
}
}
for (int j = 0; j < numVars; j++) {
for (int i = 0; i <= j; i++) {
double value = covMatrix.getValue(i, j);
if (Double.isNaN(value)) {
out.print("*");
} else {
out.print(nf.format(value));
}
out.print((i < j) ? "\t" : "\n");
}
}
out.flush();
out.close();
}
public static void saveKnowledge(IKnowledge knowledge, Writer out) throws IOException {
StringBuilder buf = new StringBuilder();
buf.append("/knowledge");
buf.append("\naddtemporal\n");
for (int i = 0; i < knowledge.getNumTiers(); i++) {
String forbiddenWithin = knowledge.isTierForbiddenWithin(i) ? "*" : "";
String onlyCanCauseNextTier = knowledge.isOnlyCanCauseNextTier(i) ? "-" : "";
buf.append("\n").append(i+1).append(forbiddenWithin).append(onlyCanCauseNextTier).append(" ");
List<String> tier = knowledge.getTier(i);
if (!(tier == null || tier.isEmpty())) {
buf.append(" ");
buf.append(tier.stream().collect(Collectors.joining(" ")));
}
}
buf.append("\n\nforbiddirect");
for (Iterator<KnowledgeEdge> i
= knowledge.forbiddenEdgesIterator(); i.hasNext();) {
KnowledgeEdge pair = i.next();
String from = pair.getFrom();
String to = pair.getTo();
if (knowledge.isForbiddenByTiers(from, to)) {
continue;
}
buf.append("\n").append(from).append(" ").append(to);
}
buf.append("\n\nrequiredirect");
for (Iterator<KnowledgeEdge> i
= knowledge.requiredEdgesIterator(); i.hasNext();) {
KnowledgeEdge pair = i.next();
String from = pair.getFrom();
String to = pair.getTo();
buf.append("\n").append(from).append(" ").append(to);
}
out.write(buf.toString());
out.flush();
}
}
| 777Rebecca/tetrad | tetrad-lib/src/main/java/edu/cmu/tetrad/data/DataWriter.java | 2,484 | // String name = dataSet.getVariable(col).getNode(); | line_comment | nl | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.data;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.util.NumberFormatUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
* Provides static methods for saving data to files.
*
* @author Joseph Ramsey
*/
public final class DataWriter {
/**
* Writes a dataset to file. The dataset may have continuous and/or discrete
* columns. Note that <code>out</code> is not closed by this method, so
* the close method on <code>out</code> will need to be called externally.
*
* @param dataSet The data set to save.
* @param out The writer to write the output to.
* @param separator The character separating fields, usually '\t' or ','.
* @throws IOException If there is some problem dealing with the writer.
*/
public static void writeRectangularData(DataSet dataSet,
Writer out, char separator) throws IOException {
NumberFormat nf = NumberFormatUtil.getInstance().getNumberFormat();
StringBuilder buf = new StringBuilder();
// boolean isCaseMultipliersCollapsed = dataSet.isMulipliersCollapsed();
// if (false) {
// buf.append("MULT").append(separator);
// }
for (int col = 0; col < dataSet.getNumColumns(); col++) {
String name = dataSet.getVariable(col).getName();
if (name.trim().equals("")) {
name = "C" + (col - 1);
}
buf.append(name);
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
}
for (int row = 0; row < dataSet.getNumRows(); row++) {
buf.append("\n");
// if (isCaseMultipliersCollapsed) {
// int multiplier = dataSet.getMultiplier(row);
// buf.append(multiplier).append(separator);
// }
for (int col = 0; col < dataSet.getNumColumns(); col++) {
Node variable = dataSet.getVariable(col);
if (variable instanceof ContinuousVariable) {
double value = dataSet.getDouble(row, col);
if (ContinuousVariable.isDoubleMissingValue(value)) {
buf.append("*");
} else {
buf.append(nf.format(value));
}
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
} else if (variable instanceof DiscreteVariable) {
Object obj = dataSet.getObject(row, col);
String val = ((obj == null) ? "" : obj.toString());
buf.append(val);
if (col < dataSet.getNumColumns() - 1) {
buf.append(separator);
}
}
}
}
buf.append("\n");
out.write(buf.toString());
out.close();
}
// /**
// * Writes a dataset to file. The dataset may have continuous and/or discrete
// * columns. Note that <code>out</code> is not closed by this method, so
// * the close method on <code>out</code> will need to be called externally.
// *
// * @param dataSet The data set to save.
// * @param out The writer to write the output to.
// * @param separator The character separating fields, usually '\t' or ','.
// */
// public static void writeRectangularDataALittleFaster(DataSet dataSet,
// PrintWriter out, char separator) {
// NumberFormat nf = new DecimalFormat("0.0000");
//// StringBuilder buf = new StringBuilder();
//
// for (int col = 0; col < dataSet.getNumColumns(); col++) {
// Strin<SUF>
//
// if (name.trim().equals("")) {
// name = "C" + (col - 1);
// }
//
// out.append(name);
//
// if (col < dataSet.getNumColumns() - 1) {
// out.append(separator);
// }
// }
//
// for (int row = 0; row < dataSet.getNumRows(); row++) {
// out.append("\n");
//
// for (int col = 0; col < dataSet.getNumColumns(); col++) {
// Node variable = dataSet.getVariable(col);
//
// if (variable instanceof ContinuousVariable) {
// double value = dataSet.getDouble(row, col);
//
// if (ContinuousVariable.isDoubleMissingValue(value)) {
// out.print("*");
// } else {
// out.print(nf.format(value));
//// out.print(value);
// }
//
// if (col < dataSet.getNumColumns() - 1) {
// out.print(separator);
// }
// } else if (variable instanceof DiscreteVariable) {
// Object obj = dataSet.getObject(row, col);
// String val = ((obj == null) ? "" : obj.toString());
//
// out.print(val);
//
// if (col < dataSet.getNumColumns() - 1) {
// out.print(separator);
// }
// }
// }
// }
//
// out.print("\n");
// out.close();
// }
/**
* Writes the lower triangle of a covariance matrix to file. Note that
* <code>out</code> is not closed by this method, so the close method on
* <code>out</code> will need to be called externally.
*
* @param out The writer to write the output to.
*/
public static void writeCovMatrix(ICovarianceMatrix covMatrix,
PrintWriter out, NumberFormat nf) {
// out.println("/Covariance");
out.println(covMatrix.getSampleSize());
List<String> variables = covMatrix.getVariableNames();
int numVars = variables.size();
int varCount = 0;
for (String variable : variables) {
varCount++;
if (varCount < numVars) {
out.print(variable);
out.print("\t");
} else {
out.println(variable);
}
}
for (int j = 0; j < numVars; j++) {
for (int i = 0; i <= j; i++) {
double value = covMatrix.getValue(i, j);
if (Double.isNaN(value)) {
out.print("*");
} else {
out.print(nf.format(value));
}
out.print((i < j) ? "\t" : "\n");
}
}
out.flush();
out.close();
}
public static void saveKnowledge(IKnowledge knowledge, Writer out) throws IOException {
StringBuilder buf = new StringBuilder();
buf.append("/knowledge");
buf.append("\naddtemporal\n");
for (int i = 0; i < knowledge.getNumTiers(); i++) {
String forbiddenWithin = knowledge.isTierForbiddenWithin(i) ? "*" : "";
String onlyCanCauseNextTier = knowledge.isOnlyCanCauseNextTier(i) ? "-" : "";
buf.append("\n").append(i+1).append(forbiddenWithin).append(onlyCanCauseNextTier).append(" ");
List<String> tier = knowledge.getTier(i);
if (!(tier == null || tier.isEmpty())) {
buf.append(" ");
buf.append(tier.stream().collect(Collectors.joining(" ")));
}
}
buf.append("\n\nforbiddirect");
for (Iterator<KnowledgeEdge> i
= knowledge.forbiddenEdgesIterator(); i.hasNext();) {
KnowledgeEdge pair = i.next();
String from = pair.getFrom();
String to = pair.getTo();
if (knowledge.isForbiddenByTiers(from, to)) {
continue;
}
buf.append("\n").append(from).append(" ").append(to);
}
buf.append("\n\nrequiredirect");
for (Iterator<KnowledgeEdge> i
= knowledge.requiredEdgesIterator(); i.hasNext();) {
KnowledgeEdge pair = i.next();
String from = pair.getFrom();
String to = pair.getTo();
buf.append("\n").append(from).append(" ").append(to);
}
out.write(buf.toString());
out.flush();
}
}
|
48050_4 | package view;
import controller.GameController;
import model.Cell;
import model.ChessPiece;
import model.Chessboard;
import model.ChessboardPoint;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import static model.Constant.CHESSBOARD_COL_SIZE;
import static model.Constant.CHESSBOARD_ROW_SIZE;
/**
* This class represents the checkerboard component object on the panel
*/
public class ChessboardComponent extends JComponent {
private static CellComponent[][] gridComponents = new CellComponent[CHESSBOARD_ROW_SIZE.getNum()][CHESSBOARD_COL_SIZE.getNum()];
private final int CHESS_SIZE;
private static int theme = 0;
public final static Set<ChessboardPoint> riverCell = new HashSet<>();
public final static Set<ChessboardPoint> blueTrapCell = new HashSet<>();
public final static Set<ChessboardPoint> redTrapCell = new HashSet<>();
public final static Set<ChessboardPoint> blueDenCell = new HashSet<>();
public final static Set<ChessboardPoint> redDenCell = new HashSet<>();
private GameController gameController;
public ChessboardComponent(int chessSize) {
CHESS_SIZE = chessSize;
int width = CHESS_SIZE * 7;
int height = CHESS_SIZE * 9;
enableEvents(AWTEvent.MOUSE_EVENT_MASK);// Allow mouse events to occur
setLayout(null); // Use absolute layout.
setSize(width, height);
System.out.printf("chessboard width, height = [%d : %d], chess size = %d\n", width, height, CHESS_SIZE);
initiateGridComponents();
}
/**
* This method represents how to initiate ChessComponent
* according to Chessboard information
*/
public void initiateChessComponent(Chessboard chessboard) {
Cell[][] grid = chessboard.getGrid();
//gridComponents = new CellComponent[CHESSBOARD_ROW_SIZE.getNum()][CHESSBOARD_COL_SIZE.getNum()];
for (int i = 0; i < CHESSBOARD_ROW_SIZE.getNum(); i++) {
for (int j = 0; j < CHESSBOARD_COL_SIZE.getNum(); j++) {
gridComponents[i][j].removeAll();
gridComponents[i][j].rigisterChessboardComponent(this);
if (grid[i][j].getPiece() != null) {
ChessPiece chessPiece = grid[i][j].getPiece();
System.out.println(chessPiece.getName());
if (gridComponents[i][j].getComponents().length==0){
gridComponents[i][j].add(
new ChessComponent(
chessPiece.getOwner(),
CHESS_SIZE,chessJudge(chessPiece)));
}
}
}
}
}
private String chessJudge(ChessPiece chess){
if(chess.getName() == "Elephant")
return "象";
else if(chess.getName() == "Lion")
return "狮";
else if(chess.getName() == "Tiger")
return "虎";
else if(chess.getName() == "Leopard")
return "豹";
else if(chess.getName() == "Wolf")
return "狼";
else if(chess.getName() == "Dog")
return "狗";
else if(chess.getName() == "Cat")
return "猫";
else
return "鼠";
}
public void renderPossibleMove(ArrayList<ChessboardPoint> possibleMovePoint){
for (int i = 0; i < CHESSBOARD_ROW_SIZE.getNum(); i++) {
for (int j = 0; j < CHESSBOARD_COL_SIZE.getNum(); j++) {
if(possibleMovePoint.contains(new ChessboardPoint(i,j))){
if(gridComponents[i][j].getComponents().length!=0){
gridComponents[i][j].moveable = 2;
}else{
gridComponents[i][j].moveable = 1;
}
}
}
}
repaint();
}
public void removePossibleMove(){
for (int i = 0; i < CHESSBOARD_ROW_SIZE.getNum(); i++) {
for (int j = 0; j < CHESSBOARD_COL_SIZE.getNum(); j++) {
if(gridComponents[i][j].moveable != 0){
gridComponents[i][j].moveable = 0;
}
}
}
repaint();
}
public void initiateGridComponents() {
riverCell.add(new ChessboardPoint(3,1));
riverCell.add(new ChessboardPoint(3,2));
riverCell.add(new ChessboardPoint(4,1));
riverCell.add(new ChessboardPoint(4,2));
riverCell.add(new ChessboardPoint(5,1));
riverCell.add(new ChessboardPoint(5,2));
riverCell.add(new ChessboardPoint(3,4));
riverCell.add(new ChessboardPoint(3,5));
riverCell.add(new ChessboardPoint(4,4));
riverCell.add(new ChessboardPoint(4,5));
riverCell.add(new ChessboardPoint(5,4));
riverCell.add(new ChessboardPoint(5,5));
blueTrapCell.add(new ChessboardPoint(0,2));
blueTrapCell.add(new ChessboardPoint(0,4));
blueTrapCell.add(new ChessboardPoint(1,3));
redTrapCell.add(new ChessboardPoint(8,2));
redTrapCell.add(new ChessboardPoint(8,4));
redTrapCell.add(new ChessboardPoint(7,3));
blueDenCell.add(new ChessboardPoint(0,3));
redDenCell.add(new ChessboardPoint(8,3));
for (int i = 0; i < CHESSBOARD_ROW_SIZE.getNum(); i++) {
for (int j = 0; j < CHESSBOARD_COL_SIZE.getNum(); j++) {
ChessboardPoint temp = new ChessboardPoint(i, j);
CellComponent cell;
if (riverCell.contains(temp)) {
cell = new CellComponent(Color.CYAN, calculatePoint(i, j), CHESS_SIZE);
this.add(cell);
} else if (redTrapCell.contains(temp)||blueTrapCell.contains(temp)) {
cell = new CellComponent(Color.ORANGE, calculatePoint(i, j), CHESS_SIZE);
this.add(cell);
} else if (blueDenCell.contains(temp)) {
cell = new CellComponent(Color.BLUE, calculatePoint(i, j), CHESS_SIZE);
this.add(cell);
}else if(redDenCell.contains(temp)){
cell = new CellComponent(Color.RED, calculatePoint(i, j), CHESS_SIZE);
this.add(cell);
} else
{
cell = new CellComponent(Color.LIGHT_GRAY, calculatePoint(i, j), CHESS_SIZE);
this.add(cell);
}
gridComponents[i][j] = cell;
}
}
}
public void registerController(GameController gameController) {
this.gameController = gameController;
}
public void setChessComponentAtGrid(ChessboardPoint point, ChessComponent chess) {
getGridComponentAt(point).add(chess);
}
public ChessComponent removeChessComponentAtGrid(ChessboardPoint point) {
// Note re-validation is required after remove / removeAll.
ChessComponent chess = (ChessComponent) getGridComponentAt(point).getComponents()[0];
getGridComponentAt(point).removeAll();
getGridComponentAt(point).revalidate();
chess.setSelected(false);
return chess;
}
public ChessComponent addChessComponent(ChessboardPoint point, ChessPiece piece){
ChessComponent chess = new ChessComponent(
piece.getOwner(),
CHESS_SIZE,chessJudge(piece));
gridComponents[point.getRow()][point.getCol()].add(chess);
return chess;
}
private CellComponent getGridComponentAt(ChessboardPoint point) {
return gridComponents[point.getRow()][point.getCol()];
}
private ChessboardPoint getChessboardPoint(Point point) {
System.out.println("[" + point.y/CHESS_SIZE + ", " +point.x/CHESS_SIZE + "] Clicked");
return new ChessboardPoint(point.y/CHESS_SIZE, point.x/CHESS_SIZE);
}
private Point calculatePoint(int row, int col) {
return new Point(col * CHESS_SIZE, row * CHESS_SIZE);
}
public static void changeTheme(){
for (int i = 0; i < CHESSBOARD_ROW_SIZE.getNum(); i++) {
for (int j = 0; j < CHESSBOARD_COL_SIZE.getNum(); j++) {
if(theme == 0){
gridComponents[i][j].changeTheme(1);
}
else{
gridComponents[i][j].changeTheme(0);
}
}
}
theme = 1 - theme;
System.out.println("Theme changed");
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
super.validate();
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
@Override
protected void processMouseEvent(MouseEvent e) {
//因为写了个鼠标悬停cell变大,引起了一些未知错误,所以这一段实质已经被弃用了,新的在下面
System.out.println(e.getX() +" "+ e.getY());
JComponent clickedComponent = (JComponent) getComponentAt(e.getX(), e.getY());
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
if (clickedComponent.getComponentCount() == 0) {
System.out.print("None chess here and ");
gameController.onPlayerClickCell(getChessboardPoint(e.getPoint()), (CellComponent) clickedComponent);
} else {
System.out.print("One chess here and ");
gameController.onPlayerClickChessPiece(getChessboardPoint(e.getPoint()), (ChessComponent) clickedComponent.getComponents()[0]);
}
}
}
public void MousePress(Point location) {
JComponent clickedComponent = (JComponent) getComponentAt(location);
if (clickedComponent.getComponentCount() == 0) {
System.out.print("None chess here and ");
gameController.onPlayerClickCell(getChessboardPoint(location), (CellComponent) clickedComponent);
} else {
System.out.print("One chess here and ");
gameController.onPlayerClickChessPiece(getChessboardPoint(location), (ChessComponent) clickedComponent.getComponents()[0]);
}
}
}
| 7Sageer/Battle-Longevity-Chess | src/view/ChessboardComponent.java | 2,738 | //gridComponents = new CellComponent[CHESSBOARD_ROW_SIZE.getNum()][CHESSBOARD_COL_SIZE.getNum()]; | line_comment | nl | package view;
import controller.GameController;
import model.Cell;
import model.ChessPiece;
import model.Chessboard;
import model.ChessboardPoint;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import static model.Constant.CHESSBOARD_COL_SIZE;
import static model.Constant.CHESSBOARD_ROW_SIZE;
/**
* This class represents the checkerboard component object on the panel
*/
public class ChessboardComponent extends JComponent {
private static CellComponent[][] gridComponents = new CellComponent[CHESSBOARD_ROW_SIZE.getNum()][CHESSBOARD_COL_SIZE.getNum()];
private final int CHESS_SIZE;
private static int theme = 0;
public final static Set<ChessboardPoint> riverCell = new HashSet<>();
public final static Set<ChessboardPoint> blueTrapCell = new HashSet<>();
public final static Set<ChessboardPoint> redTrapCell = new HashSet<>();
public final static Set<ChessboardPoint> blueDenCell = new HashSet<>();
public final static Set<ChessboardPoint> redDenCell = new HashSet<>();
private GameController gameController;
public ChessboardComponent(int chessSize) {
CHESS_SIZE = chessSize;
int width = CHESS_SIZE * 7;
int height = CHESS_SIZE * 9;
enableEvents(AWTEvent.MOUSE_EVENT_MASK);// Allow mouse events to occur
setLayout(null); // Use absolute layout.
setSize(width, height);
System.out.printf("chessboard width, height = [%d : %d], chess size = %d\n", width, height, CHESS_SIZE);
initiateGridComponents();
}
/**
* This method represents how to initiate ChessComponent
* according to Chessboard information
*/
public void initiateChessComponent(Chessboard chessboard) {
Cell[][] grid = chessboard.getGrid();
//gridC<SUF>
for (int i = 0; i < CHESSBOARD_ROW_SIZE.getNum(); i++) {
for (int j = 0; j < CHESSBOARD_COL_SIZE.getNum(); j++) {
gridComponents[i][j].removeAll();
gridComponents[i][j].rigisterChessboardComponent(this);
if (grid[i][j].getPiece() != null) {
ChessPiece chessPiece = grid[i][j].getPiece();
System.out.println(chessPiece.getName());
if (gridComponents[i][j].getComponents().length==0){
gridComponents[i][j].add(
new ChessComponent(
chessPiece.getOwner(),
CHESS_SIZE,chessJudge(chessPiece)));
}
}
}
}
}
private String chessJudge(ChessPiece chess){
if(chess.getName() == "Elephant")
return "象";
else if(chess.getName() == "Lion")
return "狮";
else if(chess.getName() == "Tiger")
return "虎";
else if(chess.getName() == "Leopard")
return "豹";
else if(chess.getName() == "Wolf")
return "狼";
else if(chess.getName() == "Dog")
return "狗";
else if(chess.getName() == "Cat")
return "猫";
else
return "鼠";
}
public void renderPossibleMove(ArrayList<ChessboardPoint> possibleMovePoint){
for (int i = 0; i < CHESSBOARD_ROW_SIZE.getNum(); i++) {
for (int j = 0; j < CHESSBOARD_COL_SIZE.getNum(); j++) {
if(possibleMovePoint.contains(new ChessboardPoint(i,j))){
if(gridComponents[i][j].getComponents().length!=0){
gridComponents[i][j].moveable = 2;
}else{
gridComponents[i][j].moveable = 1;
}
}
}
}
repaint();
}
public void removePossibleMove(){
for (int i = 0; i < CHESSBOARD_ROW_SIZE.getNum(); i++) {
for (int j = 0; j < CHESSBOARD_COL_SIZE.getNum(); j++) {
if(gridComponents[i][j].moveable != 0){
gridComponents[i][j].moveable = 0;
}
}
}
repaint();
}
public void initiateGridComponents() {
riverCell.add(new ChessboardPoint(3,1));
riverCell.add(new ChessboardPoint(3,2));
riverCell.add(new ChessboardPoint(4,1));
riverCell.add(new ChessboardPoint(4,2));
riverCell.add(new ChessboardPoint(5,1));
riverCell.add(new ChessboardPoint(5,2));
riverCell.add(new ChessboardPoint(3,4));
riverCell.add(new ChessboardPoint(3,5));
riverCell.add(new ChessboardPoint(4,4));
riverCell.add(new ChessboardPoint(4,5));
riverCell.add(new ChessboardPoint(5,4));
riverCell.add(new ChessboardPoint(5,5));
blueTrapCell.add(new ChessboardPoint(0,2));
blueTrapCell.add(new ChessboardPoint(0,4));
blueTrapCell.add(new ChessboardPoint(1,3));
redTrapCell.add(new ChessboardPoint(8,2));
redTrapCell.add(new ChessboardPoint(8,4));
redTrapCell.add(new ChessboardPoint(7,3));
blueDenCell.add(new ChessboardPoint(0,3));
redDenCell.add(new ChessboardPoint(8,3));
for (int i = 0; i < CHESSBOARD_ROW_SIZE.getNum(); i++) {
for (int j = 0; j < CHESSBOARD_COL_SIZE.getNum(); j++) {
ChessboardPoint temp = new ChessboardPoint(i, j);
CellComponent cell;
if (riverCell.contains(temp)) {
cell = new CellComponent(Color.CYAN, calculatePoint(i, j), CHESS_SIZE);
this.add(cell);
} else if (redTrapCell.contains(temp)||blueTrapCell.contains(temp)) {
cell = new CellComponent(Color.ORANGE, calculatePoint(i, j), CHESS_SIZE);
this.add(cell);
} else if (blueDenCell.contains(temp)) {
cell = new CellComponent(Color.BLUE, calculatePoint(i, j), CHESS_SIZE);
this.add(cell);
}else if(redDenCell.contains(temp)){
cell = new CellComponent(Color.RED, calculatePoint(i, j), CHESS_SIZE);
this.add(cell);
} else
{
cell = new CellComponent(Color.LIGHT_GRAY, calculatePoint(i, j), CHESS_SIZE);
this.add(cell);
}
gridComponents[i][j] = cell;
}
}
}
public void registerController(GameController gameController) {
this.gameController = gameController;
}
public void setChessComponentAtGrid(ChessboardPoint point, ChessComponent chess) {
getGridComponentAt(point).add(chess);
}
public ChessComponent removeChessComponentAtGrid(ChessboardPoint point) {
// Note re-validation is required after remove / removeAll.
ChessComponent chess = (ChessComponent) getGridComponentAt(point).getComponents()[0];
getGridComponentAt(point).removeAll();
getGridComponentAt(point).revalidate();
chess.setSelected(false);
return chess;
}
public ChessComponent addChessComponent(ChessboardPoint point, ChessPiece piece){
ChessComponent chess = new ChessComponent(
piece.getOwner(),
CHESS_SIZE,chessJudge(piece));
gridComponents[point.getRow()][point.getCol()].add(chess);
return chess;
}
private CellComponent getGridComponentAt(ChessboardPoint point) {
return gridComponents[point.getRow()][point.getCol()];
}
private ChessboardPoint getChessboardPoint(Point point) {
System.out.println("[" + point.y/CHESS_SIZE + ", " +point.x/CHESS_SIZE + "] Clicked");
return new ChessboardPoint(point.y/CHESS_SIZE, point.x/CHESS_SIZE);
}
private Point calculatePoint(int row, int col) {
return new Point(col * CHESS_SIZE, row * CHESS_SIZE);
}
public static void changeTheme(){
for (int i = 0; i < CHESSBOARD_ROW_SIZE.getNum(); i++) {
for (int j = 0; j < CHESSBOARD_COL_SIZE.getNum(); j++) {
if(theme == 0){
gridComponents[i][j].changeTheme(1);
}
else{
gridComponents[i][j].changeTheme(0);
}
}
}
theme = 1 - theme;
System.out.println("Theme changed");
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
super.validate();
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
@Override
protected void processMouseEvent(MouseEvent e) {
//因为写了个鼠标悬停cell变大,引起了一些未知错误,所以这一段实质已经被弃用了,新的在下面
System.out.println(e.getX() +" "+ e.getY());
JComponent clickedComponent = (JComponent) getComponentAt(e.getX(), e.getY());
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
if (clickedComponent.getComponentCount() == 0) {
System.out.print("None chess here and ");
gameController.onPlayerClickCell(getChessboardPoint(e.getPoint()), (CellComponent) clickedComponent);
} else {
System.out.print("One chess here and ");
gameController.onPlayerClickChessPiece(getChessboardPoint(e.getPoint()), (ChessComponent) clickedComponent.getComponents()[0]);
}
}
}
public void MousePress(Point location) {
JComponent clickedComponent = (JComponent) getComponentAt(location);
if (clickedComponent.getComponentCount() == 0) {
System.out.print("None chess here and ");
gameController.onPlayerClickCell(getChessboardPoint(location), (CellComponent) clickedComponent);
} else {
System.out.print("One chess here and ");
gameController.onPlayerClickChessPiece(getChessboardPoint(location), (ChessComponent) clickedComponent.getComponents()[0]);
}
}
}
|
174752_43 | package id.radityo.moviedatabase;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.makeramen.roundedimageview.RoundedImageView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import id.radityo.moviedatabase.Database.MovieModel;
import id.radityo.moviedatabase.Database.RealmHelper;
import id.radityo.moviedatabase.Review.ReviewAdapter;
import id.radityo.moviedatabase.Review.Reviewer;
import id.radityo.moviedatabase.Trailer.Quicktime.QuicktimeAdapter;
import id.radityo.moviedatabase.Trailer.Quicktime.Quicktimes;
import id.radityo.moviedatabase.Trailer.Youtube.YoutubeAdapter;
import id.radityo.moviedatabase.Trailer.Youtube.Youtubes;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmList;
import io.realm.RealmResults;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DetailActivity extends AppCompatActivity {
public final String API_KEY = "ce64212de916313a39e9490b889fb667";
private static final String TAG = "movie";
TextView tvYear, tvDuration, tvRating, tvSinopsis, tvNoTrailer, tvTitle, tvNoReview;
RoundedImageView rivImage;
Button addFavorite;
ProgressBar progressBarReview, progressBarTrailer;
RecyclerView rvReview, rvYoutube, rvQuicktime;
List<Reviewer> reviewsList = new ArrayList<>(); // TODO: perubahan dari list ke realmlist
ReviewAdapter reviewAdapter;
List<Youtubes> youtubesList = new ArrayList<>(); //youtube's List
YoutubeAdapter youtubeAdapter;
List<Quicktimes> quicktimesList = new ArrayList<>(); //quicktime's List
QuicktimeAdapter quicktimeAdapter;
RealmList<Reviewer> reviewers;
List<Reviewer> list;
RealmResults<Reviewer> results;
RealmResults<Youtubes> resultsYoutube;
RealmResults<Quicktimes> resultsQuicktime;
Realm realm;
MovieModel movieModel = new MovieModel();
RealmHelper realmHelper;
public int movieId;
public String name;
private boolean ada = movieModel.isExisting();
//AdapterFavorit adapterFavorit = new AdapterFavorit(new Or, true, quicktimesList, this);
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//Realm
Realm.init(DetailActivity.this);
RealmConfiguration configuration = new RealmConfiguration.Builder().build();
realm = Realm.getInstance(configuration);
realmHelper = new RealmHelper(realm);
//Getting intent
final String title = getIntent().getStringExtra("title");
final String posterPath = getIntent().getStringExtra("poster_path");
final String year = getIntent().getStringExtra("year");
final String sinopsis = getIntent().getStringExtra("sinopsis");
final float rate = getIntent().getFloatExtra("rate", 0);
movieId = getIntent().getIntExtra("movie_id", 0);
//Logging
Log.e(TAG, "###movieId: " + movieId);
Log.e(TAG, "###title: " + title);
Log.e(TAG, "###year: " + year);
Log.e(TAG, "###rate: " + rate);
Log.e(TAG, "###posterPath: " + posterPath);
//Customize action bar
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("Detail");
getSupportActionBar().setElevation(0f);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp);
LinearLayout llNggantung = findViewById(R.id.ll_nggantung);
llNggantung.setElevation(5f);
//Finding view
tvTitle = findViewById(R.id.tv_title_detail);
tvDuration = findViewById(R.id.tv_duration_detail);
tvRating = findViewById(R.id.tv_rate_detail);
tvSinopsis = findViewById(R.id.tv_sinopsis_detail);
tvYear = findViewById(R.id.tv_year_detail);
tvNoReview = findViewById(R.id.tv_no_review);
tvNoTrailer = findViewById(R.id.tv_no_trailer);
rivImage = findViewById(R.id.iv_image_detail);
addFavorite = findViewById(R.id.bt_add_favorite);
rvReview = findViewById(R.id.rv_review);
rvYoutube = findViewById(R.id.rv_youtube);
rvQuicktime = findViewById(R.id.rv_quicktime);
progressBarReview = findViewById(R.id.progress_bar_review);
progressBarTrailer = findViewById(R.id.progress_bar_trailer);
tvNoTrailer.setVisibility(View.GONE);
tvNoReview.setVisibility(View.GONE);
rvReview.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvReview.setHasFixedSize(true);
rvYoutube.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvYoutube.setHasFixedSize(true);
rvQuicktime.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvQuicktime.setHasFixedSize(true);
// reviewsList = realmHelper.getAllReviews();
// youtubesList = realmHelper.ge
if (!reviewsList.isEmpty()) {
progressBarReview.setVisibility(View.GONE);
}
if (!youtubesList.isEmpty() || !quicktimesList.isEmpty()) {
progressBarTrailer.setVisibility(View.GONE);
}
//Realm Result
results = realm.where(Reviewer.class).equalTo("movieId", movieId).findAll();
results.load();
resultsYoutube = realm.where(Youtubes.class).equalTo("movieId", movieId).findAll();
resultsYoutube.load();
resultsQuicktime = realm.where(Quicktimes.class).equalTo("movieId", movieId).findAll();
resultsQuicktime.load();
hitReviewsItem(API_KEY); //hit review
hitTrailersItem(API_KEY); //hit trailer
hitDetailsItem(API_KEY); //hit details
reviewsList.addAll(realmHelper.findAll(Reviewer.class, "movieId", movieId));
youtubesList.addAll(realmHelper.findAllTrailers(Youtubes.class, "name", name));
quicktimesList.addAll(realmHelper.findAllTrailers(Quicktimes.class, "name", name));
//Checking Condition and OnClick
/**Jika movieId ternyata ada
di database button dan aksinya diubah**/
if (realm.where(MovieModel.class).equalTo("movieId", movieId).count() > 0) {
movieModel.setExisting(true);
addFavorite.setText(getString(R.string.del_from_favorite));
addFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (movieModel.isExisting()) {
realmHelper.delete(movieId);
movieModel.setExisting(false);
addFavorite.setText(getString(R.string.add_to_favorite));
Log.e(TAG, "### delete");
Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
} else {
if (!title.isEmpty() && movieId != 0) {
movieModel.setMovieId(movieId);
movieModel.setTitle(title);
movieModel.setYear(year);
movieModel.setPosterPath(posterPath);
movieModel.setSinopsis(sinopsis);
movieModel.setRating(rate);
movieModel.setExisting(true);
realmHelper.save(movieModel);
realmHelper.saveObject(reviewsList);
realmHelper.saveObject(youtubesList);
realmHelper.saveObject(quicktimesList);
addFavorite.setText(getString(R.string.del_from_favorite));
Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
Log.e("movie", "### saveObject reviews : " + reviewsList);
Log.e("movie", "### saveObject youtube : " + youtubesList);
Log.e("movie", "### saveObject quicktime : " + quicktimesList);
} else {
Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
}
}
}
});
} else {
movieModel.setExisting(false);
addFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!movieModel.isExisting()) {
if (!title.isEmpty() && movieId != 0) {
movieModel.setMovieId(movieId);
movieModel.setTitle(title);
movieModel.setYear(year);
movieModel.setPosterPath(posterPath);
movieModel.setSinopsis(sinopsis);
movieModel.setRating(rate);
movieModel.setExisting(true);
realmHelper.save(movieModel);
realmHelper.saveObject(reviewsList);
realmHelper.saveObject(youtubesList);
realmHelper.saveObject(quicktimesList);
addFavorite.setText(getString(R.string.del_from_favorite));
Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
Log.e(TAG, "### add");
Log.e("movie", "### saveObject reviews : " + reviewsList);
Log.e("movie", "### saveObject youtube : " + youtubesList);
Log.e("movie", "### saveObject quicktime : " + quicktimesList);
} else {
Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
}
} else {
realmHelper.delete(movieId);
movieModel.setExisting(false);
addFavorite.setText(getString(R.string.add_to_favorite));
Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
}
}
});
}
// addFavorite.setText(getString(R.string.del_from_favorite));
// addFavorite.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (movieModel.isExisting()) { // jika sudah ada
// realmHelper.delete(movieId);
// movieModel.setExisting(false);
// addFavorite.setText(getString(R.string.add_to_favorite));
// Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
// Log.e(TAG, "###" + title + " dihapus dari favorit");
// } else {
// if (!title.isEmpty() && movieId != 0) {
// movieModel.setMovieId(movieId);
// movieModel.setTitle(title);
// movieModel.setYear(year);
// movieModel.setPosterPath(posterPath);
// movieModel.setSinopsis(sinopsis);
// movieModel.setRating(rate);
// movieModel.setExisting(true);
//
// realmHelper.save(movieModel);
// realmHelper.saveObject(reviewsList);
// realmHelper.saveObject(youtubesList);
// realmHelper.saveObject(quicktimesList);
// addFavorite.setText(getString(R.string.add_to_favorite));
// Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
// Log.e(TAG, "###" + title + " ditambahkan ke favorit");
// Log.e("movie", "### saveObject reviews : " + reviewsList);
// Log.e("movie", "### saveObject youtube : " + youtubesList);
// Log.e("movie", "### saveObject quicktime : " + quicktimesList);
// } else {
// Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
// }
// }
// }
// });
Picasso.get()
.load(posterPath)
.placeholder(R.drawable.ic_photo_black_24dp)
.into(rivImage);
tvTitle.setText(title);
tvYear.setText(year.substring(0, 4));
String rating = String.valueOf(rate) + "/10";
tvRating.setText(rating);
tvSinopsis.setText(sinopsis);
// if (movieModel.getReviewsList() != null) {
//// if (_movieModel.getReviewsList().size() != 0) {
// Log.e(TAG, "### List from MovieModel : NOT NULL");
//// list = _movieModel.getReviewsList();
//// reviewAdapter = new ReviewAdapter(list, DetailActivity.this);
//// rvReview.setAdapter(reviewAdapter);
//// reviewAdapter.notifyDataSetChanged();
//// } else {
//// Log.e(TAG, "### List from MovieModel : SIZE IS 0");
//// Log.e(TAG, "### List from MovieModel : " + _movieModel.getReviewsList());
//// reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
//// rvReview.setAdapter(reviewAdapter);
//// reviewAdapter.notifyDataSetChanged();
//// }
// } else {
// Log.e(TAG, "### List from MovieModel : IS NULL");
// }
}
private void hitReviewsItem(String apiKey) {
APIInterface service = ApiClient.getReviews(movieId);
Call<ResponseBody> call = service.reviewItem(apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
rvReview.setAdapter(reviewAdapter); // TODO: perpindahan dari atas ke bawah
progressBarReview.setVisibility(View.GONE);
try {
reviewsList.clear();
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
//saving
int movieId = object1.getInt("id");
int page = object1.getInt("page");
JSONArray array = object1.getJSONArray("results");
if (array.length() == 0) {
tvNoReview.setVisibility(View.VISIBLE);
}
for (int p = 0; p < array.length(); p++) {
JSONObject object2 = array.getJSONObject(p);
//saving
String author = object2.getString("author");
String content = object2.getString("content");
String id = object2.getString("id");
String url = object2.getString("url");
//setting
// TODO: set reviews to model
Reviewer review = new Reviewer();
review.setAuthor(author);
review.setContent(content);
review.setId(id);
review.setUrl(url);
review.setMovieId(movieId);
reviewsList.add(review);
}
// reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
reviewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
reviewAdapter = new ReviewAdapter(results, DetailActivity.this);
rvReview.setAdapter(reviewAdapter);
reviewAdapter.notifyDataSetChanged();
progressBarReview.setVisibility(View.GONE);
Log.e(TAG, "###respon message from review : " + response.message());
Log.e(TAG, "###respon errorBody from review : " + response.errorBody());
//reviewAdapter.notifyDataSetChanged();
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
reviewAdapter = new ReviewAdapter(results, DetailActivity.this);
rvReview.setAdapter(reviewAdapter);
reviewAdapter.notifyDataSetChanged();
progressBarReview.setVisibility(View.GONE);
Toast.makeText(DetailActivity.this, getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
Log.e(TAG, "NO INTERNET CONNECTION");
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
}
});
}
private void hitTrailersItem(String apiKey) {
APIInterface service = ApiClient.getTrailers(movieId);
Call<ResponseBody> call = service.trailersItem(apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
youtubeAdapter = new YoutubeAdapter(youtubesList, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
quicktimeAdapter = new QuicktimeAdapter(quicktimesList, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
Log.e(TAG, "### RESPONSE IS SUCCESSFUL GAN");
progressBarTrailer.setVisibility(View.GONE);
try {
youtubesList.clear();
quicktimesList.clear();
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
JSONArray qucktimeArray = object1.getJSONArray("quicktime");
JSONArray youtubeArray = object1.getJSONArray("youtube");
Log.e(TAG, "youtubeArray GAN!!! : " + youtubeArray);
if (qucktimeArray.length() == 0 && youtubeArray.length() == 0) {
tvNoTrailer.setVisibility(View.VISIBLE);
}
if (qucktimeArray.length() == 0) {
Log.e(TAG, "Quicktime array is NULL");
/*do nothing*/
} else {
for (int p = 0; p < qucktimeArray.length(); p++) {
JSONObject objectQ = qucktimeArray.getJSONObject(p);
name = objectQ.getString("name");
String size = objectQ.getString("size");
String source = objectQ.getString("source");
String type = objectQ.getString("type");
// TODO: set trailers to model
Quicktimes trailerQ = new Quicktimes();
trailerQ.setName(name);
trailerQ.setType(type);
trailerQ.setSource(source);
trailerQ.setSize(size);
trailerQ.setMovieId(movieId);
quicktimesList.add(trailerQ);
}
quicktimeAdapter.notifyDataSetChanged();
}
if (youtubeArray.length() == 0) {
Log.e(TAG, "Youtube array is NULL");
/*do nothing*/
} else {
for (int p = 0; p < youtubeArray.length(); p++) {
JSONObject objectY = youtubeArray.getJSONObject(p);
name = objectY.getString("name");
String size = objectY.getString("size");
String source = objectY.getString("source");
String type = objectY.getString("type");
Youtubes trailerY = new Youtubes();
trailerY.setName(name);
trailerY.setSize(size);
trailerY.setSource(source);
trailerY.setType(type);
trailerY.setMovieId(movieId);
youtubesList.add(trailerY);
}
youtubeAdapter.notifyDataSetChanged();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
youtubeAdapter = new YoutubeAdapter(resultsYoutube, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
youtubeAdapter.notifyDataSetChanged();
quicktimeAdapter = new QuicktimeAdapter(resultsQuicktime, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
quicktimeAdapter.notifyDataSetChanged();
Log.e(TAG, "###respon message from trailer : " + response.message());
Log.e(TAG, "###respon errorBody from trailer : " + response.errorBody());
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
youtubeAdapter = new YoutubeAdapter(resultsYoutube, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
youtubeAdapter.notifyDataSetChanged();
quicktimeAdapter = new QuicktimeAdapter(resultsQuicktime, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
quicktimeAdapter.notifyDataSetChanged();
progressBarTrailer.setVisibility(View.GONE);
Log.e(TAG, "NO INTERNET CONNECTION");
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
onFailToConnect();
}
});
}
private void hitDetailsItem(String apiKey) {
APIInterface service = ApiClient.getDetails(movieId);
Call<ResponseBody> call = service.detailsItem(movieId, apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
int duration = object1.getInt("runtime");
String dur = String.valueOf(duration) + " Min";
tvDuration.setText(dur);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Log.e(TAG, "###response from details not success \n"
+ response.errorBody().string()
+ "\n" + response.message());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
// onFailToConnect();
}
});
}
private void onFailToConnect() {
progressBarTrailer.setVisibility(View.GONE);
progressBarReview.setVisibility(View.GONE);
/*relativeLayout.setVisibility(View.VISIBLE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hitPopularItem(API_KEY);
}
});*/
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
@Override
protected void onRestart() {
super.onRestart();
}
}
| 7dp/Movie-DB | ayoGAN35/app/src/main/java/id/radityo/moviedatabase/DetailActivity.java | 5,914 | // Log.e("movie", "### saveObject reviews : " + reviewsList);
| line_comment | nl | package id.radityo.moviedatabase;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.makeramen.roundedimageview.RoundedImageView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import id.radityo.moviedatabase.Database.MovieModel;
import id.radityo.moviedatabase.Database.RealmHelper;
import id.radityo.moviedatabase.Review.ReviewAdapter;
import id.radityo.moviedatabase.Review.Reviewer;
import id.radityo.moviedatabase.Trailer.Quicktime.QuicktimeAdapter;
import id.radityo.moviedatabase.Trailer.Quicktime.Quicktimes;
import id.radityo.moviedatabase.Trailer.Youtube.YoutubeAdapter;
import id.radityo.moviedatabase.Trailer.Youtube.Youtubes;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmList;
import io.realm.RealmResults;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DetailActivity extends AppCompatActivity {
public final String API_KEY = "ce64212de916313a39e9490b889fb667";
private static final String TAG = "movie";
TextView tvYear, tvDuration, tvRating, tvSinopsis, tvNoTrailer, tvTitle, tvNoReview;
RoundedImageView rivImage;
Button addFavorite;
ProgressBar progressBarReview, progressBarTrailer;
RecyclerView rvReview, rvYoutube, rvQuicktime;
List<Reviewer> reviewsList = new ArrayList<>(); // TODO: perubahan dari list ke realmlist
ReviewAdapter reviewAdapter;
List<Youtubes> youtubesList = new ArrayList<>(); //youtube's List
YoutubeAdapter youtubeAdapter;
List<Quicktimes> quicktimesList = new ArrayList<>(); //quicktime's List
QuicktimeAdapter quicktimeAdapter;
RealmList<Reviewer> reviewers;
List<Reviewer> list;
RealmResults<Reviewer> results;
RealmResults<Youtubes> resultsYoutube;
RealmResults<Quicktimes> resultsQuicktime;
Realm realm;
MovieModel movieModel = new MovieModel();
RealmHelper realmHelper;
public int movieId;
public String name;
private boolean ada = movieModel.isExisting();
//AdapterFavorit adapterFavorit = new AdapterFavorit(new Or, true, quicktimesList, this);
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//Realm
Realm.init(DetailActivity.this);
RealmConfiguration configuration = new RealmConfiguration.Builder().build();
realm = Realm.getInstance(configuration);
realmHelper = new RealmHelper(realm);
//Getting intent
final String title = getIntent().getStringExtra("title");
final String posterPath = getIntent().getStringExtra("poster_path");
final String year = getIntent().getStringExtra("year");
final String sinopsis = getIntent().getStringExtra("sinopsis");
final float rate = getIntent().getFloatExtra("rate", 0);
movieId = getIntent().getIntExtra("movie_id", 0);
//Logging
Log.e(TAG, "###movieId: " + movieId);
Log.e(TAG, "###title: " + title);
Log.e(TAG, "###year: " + year);
Log.e(TAG, "###rate: " + rate);
Log.e(TAG, "###posterPath: " + posterPath);
//Customize action bar
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("Detail");
getSupportActionBar().setElevation(0f);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp);
LinearLayout llNggantung = findViewById(R.id.ll_nggantung);
llNggantung.setElevation(5f);
//Finding view
tvTitle = findViewById(R.id.tv_title_detail);
tvDuration = findViewById(R.id.tv_duration_detail);
tvRating = findViewById(R.id.tv_rate_detail);
tvSinopsis = findViewById(R.id.tv_sinopsis_detail);
tvYear = findViewById(R.id.tv_year_detail);
tvNoReview = findViewById(R.id.tv_no_review);
tvNoTrailer = findViewById(R.id.tv_no_trailer);
rivImage = findViewById(R.id.iv_image_detail);
addFavorite = findViewById(R.id.bt_add_favorite);
rvReview = findViewById(R.id.rv_review);
rvYoutube = findViewById(R.id.rv_youtube);
rvQuicktime = findViewById(R.id.rv_quicktime);
progressBarReview = findViewById(R.id.progress_bar_review);
progressBarTrailer = findViewById(R.id.progress_bar_trailer);
tvNoTrailer.setVisibility(View.GONE);
tvNoReview.setVisibility(View.GONE);
rvReview.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvReview.setHasFixedSize(true);
rvYoutube.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvYoutube.setHasFixedSize(true);
rvQuicktime.setLayoutManager(new LinearLayoutManager(this, 1, false));
rvQuicktime.setHasFixedSize(true);
// reviewsList = realmHelper.getAllReviews();
// youtubesList = realmHelper.ge
if (!reviewsList.isEmpty()) {
progressBarReview.setVisibility(View.GONE);
}
if (!youtubesList.isEmpty() || !quicktimesList.isEmpty()) {
progressBarTrailer.setVisibility(View.GONE);
}
//Realm Result
results = realm.where(Reviewer.class).equalTo("movieId", movieId).findAll();
results.load();
resultsYoutube = realm.where(Youtubes.class).equalTo("movieId", movieId).findAll();
resultsYoutube.load();
resultsQuicktime = realm.where(Quicktimes.class).equalTo("movieId", movieId).findAll();
resultsQuicktime.load();
hitReviewsItem(API_KEY); //hit review
hitTrailersItem(API_KEY); //hit trailer
hitDetailsItem(API_KEY); //hit details
reviewsList.addAll(realmHelper.findAll(Reviewer.class, "movieId", movieId));
youtubesList.addAll(realmHelper.findAllTrailers(Youtubes.class, "name", name));
quicktimesList.addAll(realmHelper.findAllTrailers(Quicktimes.class, "name", name));
//Checking Condition and OnClick
/**Jika movieId ternyata ada
di database button dan aksinya diubah**/
if (realm.where(MovieModel.class).equalTo("movieId", movieId).count() > 0) {
movieModel.setExisting(true);
addFavorite.setText(getString(R.string.del_from_favorite));
addFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (movieModel.isExisting()) {
realmHelper.delete(movieId);
movieModel.setExisting(false);
addFavorite.setText(getString(R.string.add_to_favorite));
Log.e(TAG, "### delete");
Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
} else {
if (!title.isEmpty() && movieId != 0) {
movieModel.setMovieId(movieId);
movieModel.setTitle(title);
movieModel.setYear(year);
movieModel.setPosterPath(posterPath);
movieModel.setSinopsis(sinopsis);
movieModel.setRating(rate);
movieModel.setExisting(true);
realmHelper.save(movieModel);
realmHelper.saveObject(reviewsList);
realmHelper.saveObject(youtubesList);
realmHelper.saveObject(quicktimesList);
addFavorite.setText(getString(R.string.del_from_favorite));
Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
Log.e("movie", "### saveObject reviews : " + reviewsList);
Log.e("movie", "### saveObject youtube : " + youtubesList);
Log.e("movie", "### saveObject quicktime : " + quicktimesList);
} else {
Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
}
}
}
});
} else {
movieModel.setExisting(false);
addFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!movieModel.isExisting()) {
if (!title.isEmpty() && movieId != 0) {
movieModel.setMovieId(movieId);
movieModel.setTitle(title);
movieModel.setYear(year);
movieModel.setPosterPath(posterPath);
movieModel.setSinopsis(sinopsis);
movieModel.setRating(rate);
movieModel.setExisting(true);
realmHelper.save(movieModel);
realmHelper.saveObject(reviewsList);
realmHelper.saveObject(youtubesList);
realmHelper.saveObject(quicktimesList);
addFavorite.setText(getString(R.string.del_from_favorite));
Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
Log.e(TAG, "### add");
Log.e("movie", "### saveObject reviews : " + reviewsList);
Log.e("movie", "### saveObject youtube : " + youtubesList);
Log.e("movie", "### saveObject quicktime : " + quicktimesList);
} else {
Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
}
} else {
realmHelper.delete(movieId);
movieModel.setExisting(false);
addFavorite.setText(getString(R.string.add_to_favorite));
Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
}
}
});
}
// addFavorite.setText(getString(R.string.del_from_favorite));
// addFavorite.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (movieModel.isExisting()) { // jika sudah ada
// realmHelper.delete(movieId);
// movieModel.setExisting(false);
// addFavorite.setText(getString(R.string.add_to_favorite));
// Snackbar.make(v, title + " dihapus dari favorit", Snackbar.LENGTH_LONG).show();
// Log.e(TAG, "###" + title + " dihapus dari favorit");
// } else {
// if (!title.isEmpty() && movieId != 0) {
// movieModel.setMovieId(movieId);
// movieModel.setTitle(title);
// movieModel.setYear(year);
// movieModel.setPosterPath(posterPath);
// movieModel.setSinopsis(sinopsis);
// movieModel.setRating(rate);
// movieModel.setExisting(true);
//
// realmHelper.save(movieModel);
// realmHelper.saveObject(reviewsList);
// realmHelper.saveObject(youtubesList);
// realmHelper.saveObject(quicktimesList);
// addFavorite.setText(getString(R.string.add_to_favorite));
// Snackbar.make(v, title + " ditambahkan ke favorit", Snackbar.LENGTH_LONG).show();
// Log.e(TAG, "###" + title + " ditambahkan ke favorit");
// Log.e<SUF>
// Log.e("movie", "### saveObject youtube : " + youtubesList);
// Log.e("movie", "### saveObject quicktime : " + quicktimesList);
// } else {
// Toast.makeText(DetailActivity.this, "Tidak dapat menambahkan", Toast.LENGTH_SHORT).show();
// }
// }
// }
// });
Picasso.get()
.load(posterPath)
.placeholder(R.drawable.ic_photo_black_24dp)
.into(rivImage);
tvTitle.setText(title);
tvYear.setText(year.substring(0, 4));
String rating = String.valueOf(rate) + "/10";
tvRating.setText(rating);
tvSinopsis.setText(sinopsis);
// if (movieModel.getReviewsList() != null) {
//// if (_movieModel.getReviewsList().size() != 0) {
// Log.e(TAG, "### List from MovieModel : NOT NULL");
//// list = _movieModel.getReviewsList();
//// reviewAdapter = new ReviewAdapter(list, DetailActivity.this);
//// rvReview.setAdapter(reviewAdapter);
//// reviewAdapter.notifyDataSetChanged();
//// } else {
//// Log.e(TAG, "### List from MovieModel : SIZE IS 0");
//// Log.e(TAG, "### List from MovieModel : " + _movieModel.getReviewsList());
//// reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
//// rvReview.setAdapter(reviewAdapter);
//// reviewAdapter.notifyDataSetChanged();
//// }
// } else {
// Log.e(TAG, "### List from MovieModel : IS NULL");
// }
}
private void hitReviewsItem(String apiKey) {
APIInterface service = ApiClient.getReviews(movieId);
Call<ResponseBody> call = service.reviewItem(apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
rvReview.setAdapter(reviewAdapter); // TODO: perpindahan dari atas ke bawah
progressBarReview.setVisibility(View.GONE);
try {
reviewsList.clear();
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
//saving
int movieId = object1.getInt("id");
int page = object1.getInt("page");
JSONArray array = object1.getJSONArray("results");
if (array.length() == 0) {
tvNoReview.setVisibility(View.VISIBLE);
}
for (int p = 0; p < array.length(); p++) {
JSONObject object2 = array.getJSONObject(p);
//saving
String author = object2.getString("author");
String content = object2.getString("content");
String id = object2.getString("id");
String url = object2.getString("url");
//setting
// TODO: set reviews to model
Reviewer review = new Reviewer();
review.setAuthor(author);
review.setContent(content);
review.setId(id);
review.setUrl(url);
review.setMovieId(movieId);
reviewsList.add(review);
}
// reviewAdapter = new ReviewAdapter(reviewsList, DetailActivity.this);
reviewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
reviewAdapter = new ReviewAdapter(results, DetailActivity.this);
rvReview.setAdapter(reviewAdapter);
reviewAdapter.notifyDataSetChanged();
progressBarReview.setVisibility(View.GONE);
Log.e(TAG, "###respon message from review : " + response.message());
Log.e(TAG, "###respon errorBody from review : " + response.errorBody());
//reviewAdapter.notifyDataSetChanged();
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
reviewAdapter = new ReviewAdapter(results, DetailActivity.this);
rvReview.setAdapter(reviewAdapter);
reviewAdapter.notifyDataSetChanged();
progressBarReview.setVisibility(View.GONE);
Toast.makeText(DetailActivity.this, getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
Log.e(TAG, "NO INTERNET CONNECTION");
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
}
});
}
private void hitTrailersItem(String apiKey) {
APIInterface service = ApiClient.getTrailers(movieId);
Call<ResponseBody> call = service.trailersItem(apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
youtubeAdapter = new YoutubeAdapter(youtubesList, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
quicktimeAdapter = new QuicktimeAdapter(quicktimesList, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
Log.e(TAG, "### RESPONSE IS SUCCESSFUL GAN");
progressBarTrailer.setVisibility(View.GONE);
try {
youtubesList.clear();
quicktimesList.clear();
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
JSONArray qucktimeArray = object1.getJSONArray("quicktime");
JSONArray youtubeArray = object1.getJSONArray("youtube");
Log.e(TAG, "youtubeArray GAN!!! : " + youtubeArray);
if (qucktimeArray.length() == 0 && youtubeArray.length() == 0) {
tvNoTrailer.setVisibility(View.VISIBLE);
}
if (qucktimeArray.length() == 0) {
Log.e(TAG, "Quicktime array is NULL");
/*do nothing*/
} else {
for (int p = 0; p < qucktimeArray.length(); p++) {
JSONObject objectQ = qucktimeArray.getJSONObject(p);
name = objectQ.getString("name");
String size = objectQ.getString("size");
String source = objectQ.getString("source");
String type = objectQ.getString("type");
// TODO: set trailers to model
Quicktimes trailerQ = new Quicktimes();
trailerQ.setName(name);
trailerQ.setType(type);
trailerQ.setSource(source);
trailerQ.setSize(size);
trailerQ.setMovieId(movieId);
quicktimesList.add(trailerQ);
}
quicktimeAdapter.notifyDataSetChanged();
}
if (youtubeArray.length() == 0) {
Log.e(TAG, "Youtube array is NULL");
/*do nothing*/
} else {
for (int p = 0; p < youtubeArray.length(); p++) {
JSONObject objectY = youtubeArray.getJSONObject(p);
name = objectY.getString("name");
String size = objectY.getString("size");
String source = objectY.getString("source");
String type = objectY.getString("type");
Youtubes trailerY = new Youtubes();
trailerY.setName(name);
trailerY.setSize(size);
trailerY.setSource(source);
trailerY.setType(type);
trailerY.setMovieId(movieId);
youtubesList.add(trailerY);
}
youtubeAdapter.notifyDataSetChanged();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
youtubeAdapter = new YoutubeAdapter(resultsYoutube, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
youtubeAdapter.notifyDataSetChanged();
quicktimeAdapter = new QuicktimeAdapter(resultsQuicktime, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
quicktimeAdapter.notifyDataSetChanged();
Log.e(TAG, "###respon message from trailer : " + response.message());
Log.e(TAG, "###respon errorBody from trailer : " + response.errorBody());
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
youtubeAdapter = new YoutubeAdapter(resultsYoutube, DetailActivity.this);
rvYoutube.setAdapter(youtubeAdapter);
youtubeAdapter.notifyDataSetChanged();
quicktimeAdapter = new QuicktimeAdapter(resultsQuicktime, DetailActivity.this);
rvQuicktime.setAdapter(quicktimeAdapter);
quicktimeAdapter.notifyDataSetChanged();
progressBarTrailer.setVisibility(View.GONE);
Log.e(TAG, "NO INTERNET CONNECTION");
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
onFailToConnect();
}
});
}
private void hitDetailsItem(String apiKey) {
APIInterface service = ApiClient.getDetails(movieId);
Call<ResponseBody> call = service.detailsItem(movieId, apiKey);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String respon = response.body().string();
JSONObject object1 = new JSONObject(respon);
int duration = object1.getInt("runtime");
String dur = String.valueOf(duration) + " Min";
tvDuration.setText(dur);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Log.e(TAG, "###response from details not success \n"
+ response.errorBody().string()
+ "\n" + response.message());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.getLocalizedMessage();
t.getMessage();
t.printStackTrace();
// onFailToConnect();
}
});
}
private void onFailToConnect() {
progressBarTrailer.setVisibility(View.GONE);
progressBarReview.setVisibility(View.GONE);
/*relativeLayout.setVisibility(View.VISIBLE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hitPopularItem(API_KEY);
}
});*/
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
@Override
protected void onRestart() {
super.onRestart();
}
}
|
147454_13 | package GA;
import com.sun.xml.internal.ws.server.provider.SyncProviderInvokerTube;
import util.WorkStation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GenAlgorithm {
//初始列表
private static List<Chromosome> population = new ArrayList<>();
//种群列表
private static List<Chromosome> populationList=new ArrayList<>();
private int popSize = 30;//种群数量
private int maxIterNum ;//最大迭代次数
private int generation = 1;//当前遗传到第几代
private int multiple=3;//倍数
private int someTime=500;//种群中最优解出现相同的时间解集 退出循环
private double bestTime;//最好时间 局部
private double averageTime;//平均时间
private Chromosome good;//历史种群中最好的AGV调度
private int geneI;//种群中最好的AGV调度 所在代数
public void genStart(WorkStation workStation){
//生成随机的第一代种群
population.clear();
for (int i = 0; i <30; i++) {
population.add(Chromosome.Create(workStation));
}
// for (int i = 0; i < 30; i++) {
// Decode.code(workStation,population.get(i));
// }
// for (int i = 0; i < popSize; i++) {
// System.out.println("``````````````````````````````````````````````````");
// System.out.println(population.get(i).getDNA().size());
// System.out.println(population.get(i).getDNA().get(0).getJopList().size());
// System.out.println(population.get(i).getDNA().get(1).getJopList().size());
// System.out.println(population.get(i).getDNA().get(2).getJopList().size());
// }
//排序
Collections.sort(population);
List<Chromosome> Best=new ArrayList<>();
boolean allSame=false;
int e=0;
//当出现相同的解及最短的时间 迭代结束
while (!allSame){
generation++;
// System.out.println(generation+"迭代次数");
// System.out.println(generation);
populationList.clear();
//杂交 变异得到新的种群3*30=90
for (int i = 0; i <multiple ; i++) {
for (int j = 0; j < population.size(); j++) {
//杂交*************
Chromosome newCH=population.get(j).cross(population.get(j));
//变异*************
newCH.variation(newCH);
populationList.add(newCH);
}
}
//解码 计算时间
for (Chromosome c :
populationList) {
Decode.code(workStation,c);
}
//将上一代加入到种群
for (int i = 0; i < population.size(); i++) {
populationList.add(population.get(i));
}
//对种群排序
Collections.sort(population);
Collections.sort(populationList);
//选取最优的为新种群
for (int i = 0; i < population.size(); i++) {
population.set(i,populationList.get(i));
}
//将每一代最优解 存储
Best.add(population.get(0));
//连续出现相同的解大于最有数
if (Best.size()+1>=someTime){
Best.remove(0);
}
//循环终止的条件 出现10次相同的数据 及停止
allSame=true;
for (int i = 0; i < Best.size(); i++) {
if (!(Best.get(0).getTime()==Best.get(i).getTime())){
allSame=false;
}else {
continue;
}
}
//+1 ************************************
if (Best.size()<someTime+1) allSame=false;
// for (int i = 0; i < Best.size(); i++) {
// System.out.println(Best.get(i).getTime());
// }
if (Best.get(0).getTime()<179){
int beest=Best.get(0).getTime();
}
System.out.println(Best.get(0).getTime());
//
List<Chromosome> ch=new ArrayList<>();
// if (generation%500==0){
// ch.add(Best.get(0));
// }
// if (ch.size()>2)
// if (ch.get(e).getTime()==ch.get(e++).getTime())
}
// System.out.println("===============================================================");
// System.out.println(good);
good=Best.get(0);System.out.println(generation);
System.out.println(good.getTime());
for (int i = 0; i < good.getDNA().size(); i++) {
System.out.print("第"+i+"车AGV"+"目标:");
System.out.println("执行个数"+good.getDNA().get(i).getJopList().size());
for (int j = 0; j < good.getDNA().get(i).getJopList().size(); j++) {
for (int k = 0; k <good.getDNA().get(i).getJopList().get(j).getProcessList().size() ; k++) {
System.out.print("="+good.getDNA().get(i).getJopList().get(j).getProcessList().get(k).getMachine().getName()+"=");
}
}
}
// System.out.println(good.getDNA().get(0).getJopList().size());
// System.out.println("===============================================================");
}
private int geneSize;//基因最大长度
private double crossRate = 0.6;
private double mutationRate = 0.01;//基因变异的概率
private int maxMutationNum = 3;//最大变异次数
}
| 7lldevelopers/FJSP-AGV | src/main/java/GA/GenAlgorithm.java | 1,522 | // System.out.println(population.get(i).getDNA().get(1).getJopList().size()); | line_comment | nl | package GA;
import com.sun.xml.internal.ws.server.provider.SyncProviderInvokerTube;
import util.WorkStation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GenAlgorithm {
//初始列表
private static List<Chromosome> population = new ArrayList<>();
//种群列表
private static List<Chromosome> populationList=new ArrayList<>();
private int popSize = 30;//种群数量
private int maxIterNum ;//最大迭代次数
private int generation = 1;//当前遗传到第几代
private int multiple=3;//倍数
private int someTime=500;//种群中最优解出现相同的时间解集 退出循环
private double bestTime;//最好时间 局部
private double averageTime;//平均时间
private Chromosome good;//历史种群中最好的AGV调度
private int geneI;//种群中最好的AGV调度 所在代数
public void genStart(WorkStation workStation){
//生成随机的第一代种群
population.clear();
for (int i = 0; i <30; i++) {
population.add(Chromosome.Create(workStation));
}
// for (int i = 0; i < 30; i++) {
// Decode.code(workStation,population.get(i));
// }
// for (int i = 0; i < popSize; i++) {
// System.out.println("``````````````````````````````````````````````````");
// System.out.println(population.get(i).getDNA().size());
// System.out.println(population.get(i).getDNA().get(0).getJopList().size());
// Syste<SUF>
// System.out.println(population.get(i).getDNA().get(2).getJopList().size());
// }
//排序
Collections.sort(population);
List<Chromosome> Best=new ArrayList<>();
boolean allSame=false;
int e=0;
//当出现相同的解及最短的时间 迭代结束
while (!allSame){
generation++;
// System.out.println(generation+"迭代次数");
// System.out.println(generation);
populationList.clear();
//杂交 变异得到新的种群3*30=90
for (int i = 0; i <multiple ; i++) {
for (int j = 0; j < population.size(); j++) {
//杂交*************
Chromosome newCH=population.get(j).cross(population.get(j));
//变异*************
newCH.variation(newCH);
populationList.add(newCH);
}
}
//解码 计算时间
for (Chromosome c :
populationList) {
Decode.code(workStation,c);
}
//将上一代加入到种群
for (int i = 0; i < population.size(); i++) {
populationList.add(population.get(i));
}
//对种群排序
Collections.sort(population);
Collections.sort(populationList);
//选取最优的为新种群
for (int i = 0; i < population.size(); i++) {
population.set(i,populationList.get(i));
}
//将每一代最优解 存储
Best.add(population.get(0));
//连续出现相同的解大于最有数
if (Best.size()+1>=someTime){
Best.remove(0);
}
//循环终止的条件 出现10次相同的数据 及停止
allSame=true;
for (int i = 0; i < Best.size(); i++) {
if (!(Best.get(0).getTime()==Best.get(i).getTime())){
allSame=false;
}else {
continue;
}
}
//+1 ************************************
if (Best.size()<someTime+1) allSame=false;
// for (int i = 0; i < Best.size(); i++) {
// System.out.println(Best.get(i).getTime());
// }
if (Best.get(0).getTime()<179){
int beest=Best.get(0).getTime();
}
System.out.println(Best.get(0).getTime());
//
List<Chromosome> ch=new ArrayList<>();
// if (generation%500==0){
// ch.add(Best.get(0));
// }
// if (ch.size()>2)
// if (ch.get(e).getTime()==ch.get(e++).getTime())
}
// System.out.println("===============================================================");
// System.out.println(good);
good=Best.get(0);System.out.println(generation);
System.out.println(good.getTime());
for (int i = 0; i < good.getDNA().size(); i++) {
System.out.print("第"+i+"车AGV"+"目标:");
System.out.println("执行个数"+good.getDNA().get(i).getJopList().size());
for (int j = 0; j < good.getDNA().get(i).getJopList().size(); j++) {
for (int k = 0; k <good.getDNA().get(i).getJopList().get(j).getProcessList().size() ; k++) {
System.out.print("="+good.getDNA().get(i).getJopList().get(j).getProcessList().get(k).getMachine().getName()+"=");
}
}
}
// System.out.println(good.getDNA().get(0).getJopList().size());
// System.out.println("===============================================================");
}
private int geneSize;//基因最大长度
private double crossRate = 0.6;
private double mutationRate = 0.01;//基因变异的概率
private int maxMutationNum = 3;//最大变异次数
}
|
106606_8 | /*
* AGCDialog.java
*
* Created on 12 May 2008, 10:37
*/
package radio;
import javax.swing.SpinnerNumberModel;
/**
*
* @author jm57878
*/
public class AGCDialog extends javax.swing.JDialog {
/** Creates new form AGCDialog */
public AGCDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
setTitle("java-sdr: AGC Configuration");
}
public void setup(AGCListener listener) {
this.listener=listener;
}
public void setAgc(AGCs agc) {
switch(agc) {
case FIXED:
case SLOW:
case MEDIUM:
case FAST:
case OFF:
break;
case CUSTOM:
break;
}
}
public void setAgcSlope(int slope) {
this.slope.getModel().setValue(slope);
}
public void setAgcMaxGain(int gain) {
this.maxGain.getModel().setValue(gain);
}
public void setAgcAttack(int attack) {
this.attack.getModel().setValue(attack);
}
public void setAgcDecay(int decay) {
this.decay.getModel().setValue(decay);
}
public void setAgcHang(int hang) {
this.hang.getModel().setValue(hang);
}
public void setAgcFixedGain(int gain) {
this.fixedGain.getModel().setValue(gain);
}
public void setAgcHangThreshold(int threshold) {
this.hangThreshold.setValue(threshold);
}
/** 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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
slope = new javax.swing.JSpinner();
maxGain = new javax.swing.JSpinner();
attack = new javax.swing.JSpinner();
decay = new javax.swing.JSpinner();
hang = new javax.swing.JSpinner();
hangThreshold = new javax.swing.JSlider();
fixedGain = new javax.swing.JSpinner();
close = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Slope (dB):");
jLabel2.setText("Max Gain (dB):");
jLabel3.setText("Attack (ms):");
jLabel4.setText("Decay (ms):");
jLabel5.setText("Hang (ms):");
jLabel6.setText("Hang Threshold:");
jLabel7.setText("Fixed Gain (dB):");
slope.setModel(new javax.swing.SpinnerNumberModel(0, 0, 10, 1));
slope.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
slopeStateChanged(evt);
}
});
maxGain.setModel(new javax.swing.SpinnerNumberModel(60, -20, 120, 1));
maxGain.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
maxGainStateChanged(evt);
}
});
attack.setModel(new javax.swing.SpinnerNumberModel(2, 1, 10, 1));
attack.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
attackStateChanged(evt);
}
});
decay.setModel(new javax.swing.SpinnerNumberModel(2000, 10, 5000, 1));
decay.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
decayStateChanged(evt);
}
});
hang.setModel(new javax.swing.SpinnerNumberModel(750, 10, 5000, 1));
hang.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
hangStateChanged(evt);
}
});
hangThreshold.setMajorTickSpacing(10);
hangThreshold.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
hangThresholdStateChanged(evt);
}
});
fixedGain.setModel(new javax.swing.SpinnerNumberModel(20, -20, 120, 1));
fixedGain.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
fixedGainStateChanged(evt);
}
});
close.setText("Close");
close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeActionPerformed(evt);
}
});
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.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(maxGain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(slope, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(hang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(decay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(attack, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(18, 18, 18)
.addComponent(fixedGain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(hangThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(98, 98, 98)
.addComponent(close)))
.addContainerGap(28, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(slope, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(maxGain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(attack, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(decay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(hang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hangThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(fixedGain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(close)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeActionPerformed
this.setVisible(false);
}//GEN-LAST:event_closeActionPerformed
private void slopeStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_slopeStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)slope.getModel();
Integer value=(Integer)slope.getValue();
listener.setAgcSlope(value.intValue());
}//GEN-LAST:event_slopeStateChanged
private void maxGainStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_maxGainStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)maxGain.getModel();
Integer value=(Integer)maxGain.getValue();
listener.setAgcMaxGain(value.intValue());
}//GEN-LAST:event_maxGainStateChanged
private void attackStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_attackStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)attack.getModel();
Integer value=(Integer)attack.getValue();
listener.setAgcAttack(value.intValue());
}//GEN-LAST:event_attackStateChanged
private void decayStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_decayStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)decay.getModel();
Integer value=(Integer)decay.getValue();
listener.setAgcDecay(value.intValue());
}//GEN-LAST:event_decayStateChanged
private void hangStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_hangStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)hang.getModel();
Integer value=(Integer)hang.getValue();
listener.setAgcHang(value.intValue());
}//GEN-LAST:event_hangStateChanged
private void hangThresholdStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_hangThresholdStateChanged
listener.setAgcHangThreshold(hangThreshold.getValue());
}//GEN-LAST:event_hangThresholdStateChanged
private void fixedGainStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_fixedGainStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)fixedGain.getModel();
Integer value=(Integer)fixedGain.getValue();
listener.setAgcFixedGain(value.intValue());
}//GEN-LAST:event_fixedGainStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JSpinner attack;
private javax.swing.JButton close;
private javax.swing.JSpinner decay;
private javax.swing.JSpinner fixedGain;
private javax.swing.JSpinner hang;
private javax.swing.JSlider hangThreshold;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JSpinner maxGain;
private javax.swing.JSpinner slope;
// End of variables declaration//GEN-END:variables
private AGCListener listener;
}
| 8cH9azbsFifZ/java-sdr | src/radio/AGCDialog.java | 3,490 | //GEN-FIRST:event_slopeStateChanged | line_comment | nl | /*
* AGCDialog.java
*
* Created on 12 May 2008, 10:37
*/
package radio;
import javax.swing.SpinnerNumberModel;
/**
*
* @author jm57878
*/
public class AGCDialog extends javax.swing.JDialog {
/** Creates new form AGCDialog */
public AGCDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
setTitle("java-sdr: AGC Configuration");
}
public void setup(AGCListener listener) {
this.listener=listener;
}
public void setAgc(AGCs agc) {
switch(agc) {
case FIXED:
case SLOW:
case MEDIUM:
case FAST:
case OFF:
break;
case CUSTOM:
break;
}
}
public void setAgcSlope(int slope) {
this.slope.getModel().setValue(slope);
}
public void setAgcMaxGain(int gain) {
this.maxGain.getModel().setValue(gain);
}
public void setAgcAttack(int attack) {
this.attack.getModel().setValue(attack);
}
public void setAgcDecay(int decay) {
this.decay.getModel().setValue(decay);
}
public void setAgcHang(int hang) {
this.hang.getModel().setValue(hang);
}
public void setAgcFixedGain(int gain) {
this.fixedGain.getModel().setValue(gain);
}
public void setAgcHangThreshold(int threshold) {
this.hangThreshold.setValue(threshold);
}
/** 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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
slope = new javax.swing.JSpinner();
maxGain = new javax.swing.JSpinner();
attack = new javax.swing.JSpinner();
decay = new javax.swing.JSpinner();
hang = new javax.swing.JSpinner();
hangThreshold = new javax.swing.JSlider();
fixedGain = new javax.swing.JSpinner();
close = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Slope (dB):");
jLabel2.setText("Max Gain (dB):");
jLabel3.setText("Attack (ms):");
jLabel4.setText("Decay (ms):");
jLabel5.setText("Hang (ms):");
jLabel6.setText("Hang Threshold:");
jLabel7.setText("Fixed Gain (dB):");
slope.setModel(new javax.swing.SpinnerNumberModel(0, 0, 10, 1));
slope.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
slopeStateChanged(evt);
}
});
maxGain.setModel(new javax.swing.SpinnerNumberModel(60, -20, 120, 1));
maxGain.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
maxGainStateChanged(evt);
}
});
attack.setModel(new javax.swing.SpinnerNumberModel(2, 1, 10, 1));
attack.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
attackStateChanged(evt);
}
});
decay.setModel(new javax.swing.SpinnerNumberModel(2000, 10, 5000, 1));
decay.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
decayStateChanged(evt);
}
});
hang.setModel(new javax.swing.SpinnerNumberModel(750, 10, 5000, 1));
hang.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
hangStateChanged(evt);
}
});
hangThreshold.setMajorTickSpacing(10);
hangThreshold.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
hangThresholdStateChanged(evt);
}
});
fixedGain.setModel(new javax.swing.SpinnerNumberModel(20, -20, 120, 1));
fixedGain.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
fixedGainStateChanged(evt);
}
});
close.setText("Close");
close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeActionPerformed(evt);
}
});
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.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(maxGain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(slope, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(hang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(decay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(attack, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(18, 18, 18)
.addComponent(fixedGain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(hangThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(98, 98, 98)
.addComponent(close)))
.addContainerGap(28, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(slope, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(maxGain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(attack, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(decay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(hang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hangThreshold, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(fixedGain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(close)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeActionPerformed
this.setVisible(false);
}//GEN-LAST:event_closeActionPerformed
private void slopeStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-F<SUF>
SpinnerNumberModel model=(SpinnerNumberModel)slope.getModel();
Integer value=(Integer)slope.getValue();
listener.setAgcSlope(value.intValue());
}//GEN-LAST:event_slopeStateChanged
private void maxGainStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_maxGainStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)maxGain.getModel();
Integer value=(Integer)maxGain.getValue();
listener.setAgcMaxGain(value.intValue());
}//GEN-LAST:event_maxGainStateChanged
private void attackStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_attackStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)attack.getModel();
Integer value=(Integer)attack.getValue();
listener.setAgcAttack(value.intValue());
}//GEN-LAST:event_attackStateChanged
private void decayStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_decayStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)decay.getModel();
Integer value=(Integer)decay.getValue();
listener.setAgcDecay(value.intValue());
}//GEN-LAST:event_decayStateChanged
private void hangStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_hangStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)hang.getModel();
Integer value=(Integer)hang.getValue();
listener.setAgcHang(value.intValue());
}//GEN-LAST:event_hangStateChanged
private void hangThresholdStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_hangThresholdStateChanged
listener.setAgcHangThreshold(hangThreshold.getValue());
}//GEN-LAST:event_hangThresholdStateChanged
private void fixedGainStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_fixedGainStateChanged
SpinnerNumberModel model=(SpinnerNumberModel)fixedGain.getModel();
Integer value=(Integer)fixedGain.getValue();
listener.setAgcFixedGain(value.intValue());
}//GEN-LAST:event_fixedGainStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JSpinner attack;
private javax.swing.JButton close;
private javax.swing.JSpinner decay;
private javax.swing.JSpinner fixedGain;
private javax.swing.JSpinner hang;
private javax.swing.JSlider hangThreshold;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JSpinner maxGain;
private javax.swing.JSpinner slope;
// End of variables declaration//GEN-END:variables
private AGCListener listener;
}
|
109127_5 | package com.example.cinsects;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.cinsects.HttpRequests.VolleyBasedPinning.VolleyHttpRequest;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private EditText hardcodedPw;
private EditText sharedPrefPw;
private EditText logcatPw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = getApplicationContext();
// Create Requests queues
final VolleyHttpRequest volleyHttpRequest = new VolleyHttpRequest(context);
// Shared Preference
SharedPreferences sharedPref = context.getSharedPreferences("INSEKTEN_SP", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("GeheimesSharedPref", UUID.randomUUID().toString());
editor.apply();
// Access views
hardcodedPw = findViewById(R.id.hardcodedPWTextField);
sharedPrefPw = findViewById(R.id.sharedPrefPWTextField);
logcatPw = findViewById(R.id.logcatPWTextField);
Button httpRequestButton = findViewById(R.id.httpRequestButton);
Button httpsRequestButton = findViewById(R.id.httpsRequstButton);
Button httpsPinningRequestButton = findViewById(R.id.httpsPinningRequestButton);
hardcodedPw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().equals("superinsekt")) {
Log.d(TAG, "Hardcoded Done!");
Toast.makeText(getApplicationContext(), "Hardcoded Done!", Toast.LENGTH_LONG).show();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
final String sharedPrefPassword = sharedPref.getString("GeheimesSharedPref", "a");
sharedPrefPw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().equals(sharedPrefPassword)) {
Log.d(TAG, "SharedPref Done!");
Toast.makeText(getApplicationContext(), "SharedPref Done!", Toast.LENGTH_LONG).show();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
final String logcatPassword = UUID.randomUUID().toString();
logcatPw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().equals(logcatPassword)) {
Toast.makeText(getApplicationContext(), "Logcat Done!", Toast.LENGTH_LONG).show();
} else {
Log.d(TAG, "onTextChanged: Wrong password. Password should be " + logcatPassword);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
httpRequestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StringRequest stringRequest = generateHttpGetRequest("http://httpbin.org/get");
volleyHttpRequest.addToRequestQueue(stringRequest, false);
}
});
httpsRequestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StringRequest stringRequest = generateHttpGetRequest("https://httpbin.org/get");
volleyHttpRequest.addToRequestQueue(stringRequest, false);
}
});
httpsPinningRequestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StringRequest stringRequest = generateHttpGetRequest("https://httpbin.org/get");
volleyHttpRequest.addToRequestQueue(stringRequest, true);
}
});
}
private StringRequest generateHttpGetRequest(final String url) {
return new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), "Response for " + url + " seems valid - did you see the request?", Toast.LENGTH_LONG).show();
Log.d(TAG, "onResponse: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Response for " + url + " seems NOT valid", Toast.LENGTH_LONG).show();
Log.e(TAG, "onErrorResponse: ", error);
}
});
}
}
| 8mas/InsecureApp | app/src/main/java/com/example/cinsects/MainActivity.java | 1,351 | //httpbin.org/get"); | line_comment | nl | package com.example.cinsects;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.cinsects.HttpRequests.VolleyBasedPinning.VolleyHttpRequest;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private EditText hardcodedPw;
private EditText sharedPrefPw;
private EditText logcatPw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = getApplicationContext();
// Create Requests queues
final VolleyHttpRequest volleyHttpRequest = new VolleyHttpRequest(context);
// Shared Preference
SharedPreferences sharedPref = context.getSharedPreferences("INSEKTEN_SP", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("GeheimesSharedPref", UUID.randomUUID().toString());
editor.apply();
// Access views
hardcodedPw = findViewById(R.id.hardcodedPWTextField);
sharedPrefPw = findViewById(R.id.sharedPrefPWTextField);
logcatPw = findViewById(R.id.logcatPWTextField);
Button httpRequestButton = findViewById(R.id.httpRequestButton);
Button httpsRequestButton = findViewById(R.id.httpsRequstButton);
Button httpsPinningRequestButton = findViewById(R.id.httpsPinningRequestButton);
hardcodedPw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().equals("superinsekt")) {
Log.d(TAG, "Hardcoded Done!");
Toast.makeText(getApplicationContext(), "Hardcoded Done!", Toast.LENGTH_LONG).show();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
final String sharedPrefPassword = sharedPref.getString("GeheimesSharedPref", "a");
sharedPrefPw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().equals(sharedPrefPassword)) {
Log.d(TAG, "SharedPref Done!");
Toast.makeText(getApplicationContext(), "SharedPref Done!", Toast.LENGTH_LONG).show();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
final String logcatPassword = UUID.randomUUID().toString();
logcatPw.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().equals(logcatPassword)) {
Toast.makeText(getApplicationContext(), "Logcat Done!", Toast.LENGTH_LONG).show();
} else {
Log.d(TAG, "onTextChanged: Wrong password. Password should be " + logcatPassword);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
httpRequestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StringRequest stringRequest = generateHttpGetRequest("http://httpbin.org/get");
volleyHttpRequest.addToRequestQueue(stringRequest, false);
}
});
httpsRequestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StringRequest stringRequest = generateHttpGetRequest("https://httpbin.org/get");
volleyHttpRequest.addToRequestQueue(stringRequest, false);
}
});
httpsPinningRequestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StringRequest stringRequest = generateHttpGetRequest("https://httpb<SUF>
volleyHttpRequest.addToRequestQueue(stringRequest, true);
}
});
}
private StringRequest generateHttpGetRequest(final String url) {
return new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), "Response for " + url + " seems valid - did you see the request?", Toast.LENGTH_LONG).show();
Log.d(TAG, "onResponse: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Response for " + url + " seems NOT valid", Toast.LENGTH_LONG).show();
Log.e(TAG, "onErrorResponse: ", error);
}
});
}
}
|
34122_6 | package voetbalmanager.model;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import voetbalmanager.XMLLoader;
public class CompetitieTest {
Team Ajax, Feyenoord, PSV, AZ;
Competitie eredivisie,competitie;
@Before
public void voorElkeTest() {
Ajax = new Team("Ajax", true);
Feyenoord = new Team("Feyenoord", false);
PSV = new Team("PSV", false);
AZ = new Team("AZ", false);
eredivisie = new Competitie("Eredivisie");
eredivisie.addTeam(Ajax);
eredivisie.addTeam(Feyenoord);
eredivisie.addTeam(PSV);
eredivisie.addTeam(AZ);
}
@Test
public void testGetSpelerTeam() {
assertEquals(eredivisie.getSpelerTeam(), Ajax);
assertNotEquals(eredivisie.getSpelerTeam(), PSV);
competitie = new Competitie("competitie");
competitie.addTeam(Feyenoord);
assertNotEquals(competitie.getSpelerTeam(),Ajax);
}
@Test
public void testEquals() {
Competitie competitie2 = new Competitie("Eredivisie");
competitie2.addTeam(Ajax);
competitie2.addTeam(Feyenoord);
competitie2.addTeam(PSV);
assertNotEquals(competitie2,eredivisie);
assertNotEquals(competitie2,("A"));
competitie2.addTeam(AZ);
assertEquals(competitie2,eredivisie);
Competitie competitie3 = new Competitie("Eerdivisie");
assertNotEquals(eredivisie,competitie3);
}
@Test
public void testSorteren(){
Competitie competitie = new Competitie("Eredivisie");
competitie.addTeam(PSV);
competitie.addTeam(AZ);
competitie.addTeam(Feyenoord);
competitie.addTeam(Ajax);
competitie.Sorteren("Naam");
assertEquals(competitie.getTeams().get(0),AZ);
assertNotEquals(competitie.getTeams().get(0),PSV);
// System.out.println(competitie.getTeams().get(0).toString());
Wedstrijd x = new Wedstrijd(PSV,Ajax);
Wedstrijd y = new Wedstrijd(Feyenoord,AZ);
x.maakUitslag(5,1);
y.maakUitslag(3,3);
x.kenPuntenToe();
y.kenPuntenToe();
x.maakUitslag(5,1);
x.kenPuntenToe();
competitie.Sorteren("Punten");
assertEquals(competitie.getTeams().get(0),PSV);
assertEquals(competitie.getTeams().get(3),Ajax);
assertNotEquals(competitie.getTeams().get(0),Ajax);
competitie.Sorteren("Punkten");
assertEquals(competitie.getTeams().get(0),PSV);
assertEquals(competitie.getTeams().get(3),Ajax);
assertNotEquals(competitie.getTeams().get(0),Ajax);
Wedstrijd w = new Wedstrijd(Ajax,AZ);
w.maakUitslag(2,1);
w.kenPuntenToe();
competitie.Sorteren("Punten");
assertEquals(competitie.getTeams().get(3),Feyenoord);
w.maakUitslag(8,2);
w.kenPuntenToe();
competitie.Sorteren("Punten");
assertNotEquals(competitie.getTeams().get(0),AZ);
assertEquals(competitie.getTeams().get(0),Ajax);
}
@Test
public void testMaakSpeelschema(){
Speelschema a = eredivisie.maakSpeelSchema();
assertTrue(a.allContainTeams(eredivisie.getTeams()));
assertEquals(a.getSchema().size(),(eredivisie.getTeams().size()*2-2));
}
@Test
public void testSetSpelerTeam(){
assertTrue(Feyenoord.isComputerGestuurd());
eredivisie.setSpelerTeam(Feyenoord);
assertTrue(Feyenoord.isSpelerBestuurd());
assertFalse(Feyenoord.isComputerGestuurd());
eredivisie.setSpelerTeam(Feyenoord);
assertFalse(Feyenoord.isComputerGestuurd());
assertTrue(Feyenoord.isSpelerBestuurd());
}
@Test
public void testGetNaam(){
Competitie a = new Competitie("COMP");
assertEquals(a.getNaam(),"COMP");
assertNotEquals(a.getNaam(),"a");
}
@Test
public void testSetNaam(){
assertNotEquals(eredivisie.getNaam(),"Competitie");
eredivisie.setNaam("Competitie");
assertEquals(eredivisie.getNaam(),"Competitie");
}
@Test
public void testAddTeam(){
Competitie a = new Competitie("Full");
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(Feyenoord);
a.addTeam(PSV);
assertNotEquals(a.getTeams().size(),20);
assertEquals(a.getTeams().size(),19);
assertFalse(a.getTeams().contains(PSV));
assertTrue(a.getTeams().contains(Feyenoord));
}
@Test
public void testGetSchema(){
Competitie a = new Competitie("Naam");
a.addTeam(AZ);
a.addTeam(Feyenoord);
a.addTeam(Ajax);
a.addTeam(PSV);
a.getSchema();
assertNotEquals(a.getSchema().getSchema().size(),0);
}
@Test
public void testZoekTeam() {
Competitie c = XMLLoader.creeerCompetitie("Heh");
assertNull(c.zoekTeam("Wilfried"));
Team t = c.getTeams().get(0);
assertEquals(t, c.zoekTeam(t.getNaam()));
}
@Test
public void testToString() {
Competitie c = XMLLoader.creeerCompetitie("Heh");
assertNotNull(c.toString());
assertTrue(c.toString().startsWith("Competitie"));
}
@Test
public void testSpeel() {
//De for loop runt een complete competitie 32 ronden, dus als je 25 keer een competitie wil testen moet je
//de comments even weghalen ^^.
for(int j=0;j<25;++j){
Competitie c = XMLLoader.creeerCompetitie("Heh");
c.getSchema();
for(int i=0; i<35; ++i){
c.startSpeelronde();
}
System.out.println(c.Sorteren("Punten").toString());
}
}
@Test
public void testGetSpelerWedstrijd(){
Competitie c = XMLLoader.creeerCompetitie("HA");
c.setSpelerTeam(c.getTeams().get(0));
// System.out.println(c.getSpelerTeam());
c.getSchema();
c.startSpeelronde();
// System.out.println(c.getWeek());
// System.out.println(c.getSchema().getSchema().get(0).getWedstrijden().get(0));
// System.out.println(c.getSpelerWedstrijd());
ArrayList<Wedstrijd> a = c.getSchema().getSchema().get(0).getWedstrijden();
Wedstrijd j=null;
for(Wedstrijd w : a){
if(w.getSpelerWedstrijd()){
j = w;
}
}
assertEquals(c.getSpelerWedstrijd(),j);
c.getSpelerTeam().setGebruikerTeam(false);
assertEquals(c.getSpelerWedstrijd(),new Wedstrijd(new Team("geenSpelerWedstrijd", false),new Team("geenSpelerWedstrijd", false)));
}
@Test
public void testVolgendeRonde(){
Competitie c = XMLLoader.creeerCompetitie("Yay");
c.getSchema();
assertEquals(c.volgendeRonde(),c.getSchema().getSchema().get(0).getWedstrijden());
}
@Test
public void testHuidigeResultaten(){
Competitie c = XMLLoader.creeerCompetitie("WAUW");
c.getSchema();
assertEquals(c.huidigeResultaten(),c.getSchema().getSchema().get(0).getWedstrijden());
c.startSpeelronde();
assertEquals(c.huidigeResultaten(), c.getSchema().getSchema().get(0).getWedstrijden());
}
@After
public void naAlleTests() {
Ajax = null;
Feyenoord = null;
PSV = null;
AZ = null;
eredivisie = null;
}
}
| 8uurg/OOP-Project-6.2 | src/voetbalmanager/model/CompetitieTest.java | 2,425 | // System.out.println(c.getSpelerWedstrijd()); | line_comment | nl | package voetbalmanager.model;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import voetbalmanager.XMLLoader;
public class CompetitieTest {
Team Ajax, Feyenoord, PSV, AZ;
Competitie eredivisie,competitie;
@Before
public void voorElkeTest() {
Ajax = new Team("Ajax", true);
Feyenoord = new Team("Feyenoord", false);
PSV = new Team("PSV", false);
AZ = new Team("AZ", false);
eredivisie = new Competitie("Eredivisie");
eredivisie.addTeam(Ajax);
eredivisie.addTeam(Feyenoord);
eredivisie.addTeam(PSV);
eredivisie.addTeam(AZ);
}
@Test
public void testGetSpelerTeam() {
assertEquals(eredivisie.getSpelerTeam(), Ajax);
assertNotEquals(eredivisie.getSpelerTeam(), PSV);
competitie = new Competitie("competitie");
competitie.addTeam(Feyenoord);
assertNotEquals(competitie.getSpelerTeam(),Ajax);
}
@Test
public void testEquals() {
Competitie competitie2 = new Competitie("Eredivisie");
competitie2.addTeam(Ajax);
competitie2.addTeam(Feyenoord);
competitie2.addTeam(PSV);
assertNotEquals(competitie2,eredivisie);
assertNotEquals(competitie2,("A"));
competitie2.addTeam(AZ);
assertEquals(competitie2,eredivisie);
Competitie competitie3 = new Competitie("Eerdivisie");
assertNotEquals(eredivisie,competitie3);
}
@Test
public void testSorteren(){
Competitie competitie = new Competitie("Eredivisie");
competitie.addTeam(PSV);
competitie.addTeam(AZ);
competitie.addTeam(Feyenoord);
competitie.addTeam(Ajax);
competitie.Sorteren("Naam");
assertEquals(competitie.getTeams().get(0),AZ);
assertNotEquals(competitie.getTeams().get(0),PSV);
// System.out.println(competitie.getTeams().get(0).toString());
Wedstrijd x = new Wedstrijd(PSV,Ajax);
Wedstrijd y = new Wedstrijd(Feyenoord,AZ);
x.maakUitslag(5,1);
y.maakUitslag(3,3);
x.kenPuntenToe();
y.kenPuntenToe();
x.maakUitslag(5,1);
x.kenPuntenToe();
competitie.Sorteren("Punten");
assertEquals(competitie.getTeams().get(0),PSV);
assertEquals(competitie.getTeams().get(3),Ajax);
assertNotEquals(competitie.getTeams().get(0),Ajax);
competitie.Sorteren("Punkten");
assertEquals(competitie.getTeams().get(0),PSV);
assertEquals(competitie.getTeams().get(3),Ajax);
assertNotEquals(competitie.getTeams().get(0),Ajax);
Wedstrijd w = new Wedstrijd(Ajax,AZ);
w.maakUitslag(2,1);
w.kenPuntenToe();
competitie.Sorteren("Punten");
assertEquals(competitie.getTeams().get(3),Feyenoord);
w.maakUitslag(8,2);
w.kenPuntenToe();
competitie.Sorteren("Punten");
assertNotEquals(competitie.getTeams().get(0),AZ);
assertEquals(competitie.getTeams().get(0),Ajax);
}
@Test
public void testMaakSpeelschema(){
Speelschema a = eredivisie.maakSpeelSchema();
assertTrue(a.allContainTeams(eredivisie.getTeams()));
assertEquals(a.getSchema().size(),(eredivisie.getTeams().size()*2-2));
}
@Test
public void testSetSpelerTeam(){
assertTrue(Feyenoord.isComputerGestuurd());
eredivisie.setSpelerTeam(Feyenoord);
assertTrue(Feyenoord.isSpelerBestuurd());
assertFalse(Feyenoord.isComputerGestuurd());
eredivisie.setSpelerTeam(Feyenoord);
assertFalse(Feyenoord.isComputerGestuurd());
assertTrue(Feyenoord.isSpelerBestuurd());
}
@Test
public void testGetNaam(){
Competitie a = new Competitie("COMP");
assertEquals(a.getNaam(),"COMP");
assertNotEquals(a.getNaam(),"a");
}
@Test
public void testSetNaam(){
assertNotEquals(eredivisie.getNaam(),"Competitie");
eredivisie.setNaam("Competitie");
assertEquals(eredivisie.getNaam(),"Competitie");
}
@Test
public void testAddTeam(){
Competitie a = new Competitie("Full");
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(AZ);
a.addTeam(Feyenoord);
a.addTeam(PSV);
assertNotEquals(a.getTeams().size(),20);
assertEquals(a.getTeams().size(),19);
assertFalse(a.getTeams().contains(PSV));
assertTrue(a.getTeams().contains(Feyenoord));
}
@Test
public void testGetSchema(){
Competitie a = new Competitie("Naam");
a.addTeam(AZ);
a.addTeam(Feyenoord);
a.addTeam(Ajax);
a.addTeam(PSV);
a.getSchema();
assertNotEquals(a.getSchema().getSchema().size(),0);
}
@Test
public void testZoekTeam() {
Competitie c = XMLLoader.creeerCompetitie("Heh");
assertNull(c.zoekTeam("Wilfried"));
Team t = c.getTeams().get(0);
assertEquals(t, c.zoekTeam(t.getNaam()));
}
@Test
public void testToString() {
Competitie c = XMLLoader.creeerCompetitie("Heh");
assertNotNull(c.toString());
assertTrue(c.toString().startsWith("Competitie"));
}
@Test
public void testSpeel() {
//De for loop runt een complete competitie 32 ronden, dus als je 25 keer een competitie wil testen moet je
//de comments even weghalen ^^.
for(int j=0;j<25;++j){
Competitie c = XMLLoader.creeerCompetitie("Heh");
c.getSchema();
for(int i=0; i<35; ++i){
c.startSpeelronde();
}
System.out.println(c.Sorteren("Punten").toString());
}
}
@Test
public void testGetSpelerWedstrijd(){
Competitie c = XMLLoader.creeerCompetitie("HA");
c.setSpelerTeam(c.getTeams().get(0));
// System.out.println(c.getSpelerTeam());
c.getSchema();
c.startSpeelronde();
// System.out.println(c.getWeek());
// System.out.println(c.getSchema().getSchema().get(0).getWedstrijden().get(0));
// Syste<SUF>
ArrayList<Wedstrijd> a = c.getSchema().getSchema().get(0).getWedstrijden();
Wedstrijd j=null;
for(Wedstrijd w : a){
if(w.getSpelerWedstrijd()){
j = w;
}
}
assertEquals(c.getSpelerWedstrijd(),j);
c.getSpelerTeam().setGebruikerTeam(false);
assertEquals(c.getSpelerWedstrijd(),new Wedstrijd(new Team("geenSpelerWedstrijd", false),new Team("geenSpelerWedstrijd", false)));
}
@Test
public void testVolgendeRonde(){
Competitie c = XMLLoader.creeerCompetitie("Yay");
c.getSchema();
assertEquals(c.volgendeRonde(),c.getSchema().getSchema().get(0).getWedstrijden());
}
@Test
public void testHuidigeResultaten(){
Competitie c = XMLLoader.creeerCompetitie("WAUW");
c.getSchema();
assertEquals(c.huidigeResultaten(),c.getSchema().getSchema().get(0).getWedstrijden());
c.startSpeelronde();
assertEquals(c.huidigeResultaten(), c.getSchema().getSchema().get(0).getWedstrijden());
}
@After
public void naAlleTests() {
Ajax = null;
Feyenoord = null;
PSV = null;
AZ = null;
eredivisie = null;
}
}
|
56069_24 | package org.rastalion.chapter14_geneste_en_anonieme_klassen.demo2;
public class Car {
//Start with only price as property
int price;
//initiate after you made the innerclasses.
Engine engine;
Interior interior;
Exterior exterior;
//Only this constructor empty add beginning.
public Car() {
engine = new Engine();
interior = new Interior();
exterior = new Exterior();
this.price = interior.price + exterior.price;
}
public void move() {
//To use some engine methods
engine.start();
engine.run();
engine.stop();
}
//Generate after you finished all the other classes
@Override
public String toString () {
return "Car{" +
"price=" + price +
", engine=" + engine +
", interior=" + interior +
", exterior=" + exterior +
'}';
}
//First inner class everything private except the methods
private class Engine {
//Declare some class properties
private int hp;
private int capacity;
private int price;
//Private constructor
private Engine() {
this(75,70, 4000);
}
//Second private constructor
private Engine (int hp, int capacity, int price) {
this.hp = hp;
this.capacity = capacity;
this.price = price;
}
//Run method only sysout
public void run() {
System.out.println("Engine is running.\n");
}
//Stop method only sysout
public void stop() {
System.out.println("Engine is stopping.\n");
}
//Start method only sysout
public void start() {
System.out.println("Starting the engine.\nVroom - vroom...\n");
}
//GETTERS AND SETTERS NOT GENERATED
public int getHp () {
return hp;
}
public void setHp (int hp) {
this.hp = hp;
}
public int getCapacity () {
return capacity;
}
public void setCapacity (int capacity) {
this.capacity = capacity;
}
@Override
public String toString () {
return "Engine[" +
"hp:" + hp +
", capacity:" + capacity +
", price:" + price +
']';
}
}
protected class Interior {
//Only protected property price
protected int price;
//protected constructor
protected Interior() {
this(5000);
}
//second constructor also protected acces modifier
protected Interior (int price) {
this.price = price;
}
//Getters and setters when time
@Override
public String toString () {
return "Price of the Interior: " + price;
}
}
//Almost the same as Interior class except the acces moddifiers are //default
class Exterior {
int price;
Exterior() {
this(7000);
}
Exterior (int price) {
this.price = price;
}
@Override
public String toString () {
return "Price of the Exterior: " + price;
}
}
//In the same class main method
public static void main (String[] args) {
//Deze eerst maken
Car nissan = new Car();
//De twee manieren tonen eerst de bovenste
Engine engine = new Car().new Engine();
//Dan tonen aan de hand van de instantie nissan
Engine engine1 = nissan.new Engine();
//Tonen dat dit dus ook kan vragen of dit toebehoort aan //nissan
Interior interior = nissan.new Interior();
Exterior exterior = nissan.new Exterior();
//Enkele setters gebruiken op engine instantie
engine.setHp(88);
engine.setCapacity(85);
//Daarna alle instanties afprinten naar de console
System.out.println(engine);
System.out.println(engine1);
System.out.println(nissan);
System.out.println(interior);
System.out.println(exterior);
}
}
| 93design/Java_Basis_Opl | extraOefeningenOplossing/14 nested classes/Car.java | 1,022 | //Daarna alle instanties afprinten naar de console | line_comment | nl | package org.rastalion.chapter14_geneste_en_anonieme_klassen.demo2;
public class Car {
//Start with only price as property
int price;
//initiate after you made the innerclasses.
Engine engine;
Interior interior;
Exterior exterior;
//Only this constructor empty add beginning.
public Car() {
engine = new Engine();
interior = new Interior();
exterior = new Exterior();
this.price = interior.price + exterior.price;
}
public void move() {
//To use some engine methods
engine.start();
engine.run();
engine.stop();
}
//Generate after you finished all the other classes
@Override
public String toString () {
return "Car{" +
"price=" + price +
", engine=" + engine +
", interior=" + interior +
", exterior=" + exterior +
'}';
}
//First inner class everything private except the methods
private class Engine {
//Declare some class properties
private int hp;
private int capacity;
private int price;
//Private constructor
private Engine() {
this(75,70, 4000);
}
//Second private constructor
private Engine (int hp, int capacity, int price) {
this.hp = hp;
this.capacity = capacity;
this.price = price;
}
//Run method only sysout
public void run() {
System.out.println("Engine is running.\n");
}
//Stop method only sysout
public void stop() {
System.out.println("Engine is stopping.\n");
}
//Start method only sysout
public void start() {
System.out.println("Starting the engine.\nVroom - vroom...\n");
}
//GETTERS AND SETTERS NOT GENERATED
public int getHp () {
return hp;
}
public void setHp (int hp) {
this.hp = hp;
}
public int getCapacity () {
return capacity;
}
public void setCapacity (int capacity) {
this.capacity = capacity;
}
@Override
public String toString () {
return "Engine[" +
"hp:" + hp +
", capacity:" + capacity +
", price:" + price +
']';
}
}
protected class Interior {
//Only protected property price
protected int price;
//protected constructor
protected Interior() {
this(5000);
}
//second constructor also protected acces modifier
protected Interior (int price) {
this.price = price;
}
//Getters and setters when time
@Override
public String toString () {
return "Price of the Interior: " + price;
}
}
//Almost the same as Interior class except the acces moddifiers are //default
class Exterior {
int price;
Exterior() {
this(7000);
}
Exterior (int price) {
this.price = price;
}
@Override
public String toString () {
return "Price of the Exterior: " + price;
}
}
//In the same class main method
public static void main (String[] args) {
//Deze eerst maken
Car nissan = new Car();
//De twee manieren tonen eerst de bovenste
Engine engine = new Car().new Engine();
//Dan tonen aan de hand van de instantie nissan
Engine engine1 = nissan.new Engine();
//Tonen dat dit dus ook kan vragen of dit toebehoort aan //nissan
Interior interior = nissan.new Interior();
Exterior exterior = nissan.new Exterior();
//Enkele setters gebruiken op engine instantie
engine.setHp(88);
engine.setCapacity(85);
//Daarn<SUF>
System.out.println(engine);
System.out.println(engine1);
System.out.println(nissan);
System.out.println(interior);
System.out.println(exterior);
}
}
|
11805_3 | /*
* 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 henkapp;
import java.net.URL;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import javafx.beans.InvalidationListener;
import javafx.beans.binding.Bindings;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import static javafx.collections.FXCollections.observableArrayList;
import javafx.collections.ObservableList;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
/**
* FXML Controller class
*
* @author Bas
*/
public class HenkController implements Initializable {
@FXML
Button btnAdd;
@FXML
TreeView tvTree;
@FXML
TableView tvTable;
@FXML
TextField txtNaam;
@FXML
TextField txtPlaats;
@FXML
TextField txtTelefoonnummer;
/*////*/// Geef hier het aantal personen in: /*////*////*////*////*////*////*////*////*///
/*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*///
/*////*/ int aantal_personen = 10000; /*////*////*////*////*////*////*////*////*////*///
/*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*///
// 1000000 duurt 4 seconden om te genereren maar wordt niet zichtbaar in de treeview binnen een normale tijd.
// 100000 duurt 0.3 seconden om te genereren en 29 seconden om de treeview te maken/vullen.
// 50000 duurt 0.2 seconden om te genereren en 8.3 seconden om de treeview te maken/vullen.
// 25000 duurt 0.2 seconden om te genereren en 2 seconden om de treeview te maken/vullen.
// 10000 duurt 0.1 seconden om te genereren en 0.3 seconden om de treeview te maken/vullen.
// 5000 duurt 0.1 seconden om te genereren en 0.2 seconden om de treeview te maken/vullen.
// 1000 duurt 0.0 seconden om te genereren en 0.0 seconden om de treeview te maken/vullen.
public ObservableList<Persoon> personen;
public Set<Persoon> mensen;
private TableColumn naamCol;
private TableColumn plaatsCol;
private TableColumn telefoonCol;
private TreeItem<Persoon> root = new TreeItem<Persoon>(new Persoon("Mensen", "", ""));
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
mensen = new TreeSet();
personen = observableArrayList();
ObservableSet obvSet = FXCollections.observableSet(mensen);
///*
mensen.add(new Persoon("Arie", "Amsterdam", "020"));
mensen.add(new Persoon("Arie", "Amsterdam", "020"));
mensen.add(new Persoon("Arie", "Amsterdam", "010"));
mensen.add(new Persoon("AArie", "Amsterdam", "020"));
mensen.add(new Persoon("ACrie", "Amsterdam", "020"));
mensen.add(new Persoon("ABrie", "Amsterdam", "020"));
//*/
///*
long startTime = System.nanoTime();
Random rand = new Random();
List<String> plaatsen = new ArrayList<>(aantal_personen/10);
for(int i = 0; i<aantal_personen/10;i++){
plaatsen.add(UUID.randomUUID().toString());
}
List<Persoon> mensenArray = new ArrayList<>(aantal_personen);
for(int i = 0; i<aantal_personen;i++){
mensenArray.add(new Persoon(UUID.randomUUID().toString(),plaatsen.get((int) (Math.random() * aantal_personen/10)),UUID.randomUUID().toString()));
}
mensen.addAll(mensenArray);
long endTime = System.nanoTime();
System.out.println("Tijd genereren:" + ((endTime - startTime)*0.000000001));
//*/
createTreeView();
tvTree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<Persoon>>() {
@Override
public void changed(ObservableValue<? extends TreeItem<Persoon>> observable, TreeItem<Persoon> oldValue, TreeItem<Persoon> newValue) {
try {
personen.clear();
if (newValue.getValue().getNaam().equals("Mensen")) {
personen.addAll(mensen);
} else if (newValue.getChildren().size() != 0) {
for (Persoon p : mensen) {
if (p.getPlaats().equals(newValue.getValue().getNaam())) {
personen.add(p);
}
}
} else {
personen.add(newValue.getValue());
System.out.print(newValue.getValue().getNaam());
}
} catch (Exception e) {
}
}
});
tvTable.setEditable(true);
naamCol = new TableColumn("Naam");
naamCol.setMinWidth(170.0);
plaatsCol = new TableColumn("Plaats");
plaatsCol.setMinWidth(170.0);
telefoonCol = new TableColumn("Telefoon");
telefoonCol.setMinWidth(170.0);
naamCol.setCellValueFactory(new PropertyValueFactory<Persoon, String>("naam"));
plaatsCol.setCellValueFactory(new PropertyValueFactory<Persoon, String>("plaats"));
telefoonCol.setCellValueFactory(new PropertyValueFactory<Persoon, String>("telefoon"));
naamCol.setCellFactory(TextFieldTableCell.forTableColumn());
naamCol.setOnEditCommit(
new EventHandler<CellEditEvent<Persoon, String>>() {
@Override
public void handle(CellEditEvent<Persoon, String> t) {
t.getRowValue().setNaam(t.getNewValue());
createTreeView();
}
}
);
naamCol.setComparator((naam1, naam2) -> naam1.toString().compareTo(naam2.toString()));
plaatsCol.setCellFactory(TextFieldTableCell.forTableColumn());
plaatsCol.setOnEditCommit(
new EventHandler<CellEditEvent<Persoon, String>>() {
@Override
public void handle(CellEditEvent<Persoon, String> t) {
t.getRowValue().setPlaats(t.getNewValue());
createTreeView();
}
}
);
plaatsCol.setComparator((plts1, plts2) -> plts1.toString().compareTo(plts2.toString()));
telefoonCol.setCellFactory(TextFieldTableCell.forTableColumn());
telefoonCol.setOnEditCommit(
new EventHandler<CellEditEvent<Persoon, String>>() {
@Override
public void handle(CellEditEvent<Persoon, String> t) {
t.getRowValue().setTelefoon(t.getNewValue());
createTreeView();
}
}
);
telefoonCol.setComparator((tel1, tel2) -> tel1.toString().compareTo(tel2.toString()));
tvTable.setItems(personen);
tvTable.getColumns().addAll(naamCol, plaatsCol, telefoonCol);
}
public void btnAddClick(Event e) {
personen.add(new Persoon(txtNaam.getText(), txtPlaats.getText(), txtTelefoonnummer.getText()));
mensen.add(new Persoon(txtNaam.getText(), txtPlaats.getText(), txtTelefoonnummer.getText()));
createTreeView();
}
private void createTreeView() {
long startTime = System.nanoTime();
root = new TreeItem<Persoon>(new Persoon("Mensen", "", ""));
ArrayList<Persoon> plaatsen = new ArrayList<Persoon>();
boolean found = false;
for (Persoon p : mensen) { // for in een for in een for
TreeItem<Persoon> persLeaf = new TreeItem<Persoon>(p);
found = false;
for (Persoon plaats : plaatsen) {
if (p.getPlaats().equals(plaats.getNaam())) {
for (TreeItem<Persoon> plaatsNode : root.getChildren()) {
if (plaatsNode.getValue().equals(plaats)) {
plaatsNode.getChildren().add(persLeaf);
found = true;
break;
}
if (found) {
break;
}
}
}
}
if (!found) {
Persoon pers = new Persoon(persLeaf.getValue().getPlaats(), "", "");
plaatsen.add(pers);
TreeItem<Persoon> plaatsNode = new TreeItem<Persoon>(pers);
root.getChildren().add(plaatsNode);
plaatsNode.getChildren().add(persLeaf);
}
}
tvTree.setRoot(root);
root.setExpanded(true);
long endTime = System.nanoTime();
System.out.println("Tijd Treeview maken:" + ((endTime - startTime)*0.000000001));
}
}
| 94BasMulder/JCF4MitStijn | HenkApp/src/henkapp/HenkController.java | 2,613 | // 1000000 duurt 4 seconden om te genereren maar wordt niet zichtbaar in de treeview binnen een normale tijd.
| line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package henkapp;
import java.net.URL;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import javafx.beans.InvalidationListener;
import javafx.beans.binding.Bindings;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import static javafx.collections.FXCollections.observableArrayList;
import javafx.collections.ObservableList;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
/**
* FXML Controller class
*
* @author Bas
*/
public class HenkController implements Initializable {
@FXML
Button btnAdd;
@FXML
TreeView tvTree;
@FXML
TableView tvTable;
@FXML
TextField txtNaam;
@FXML
TextField txtPlaats;
@FXML
TextField txtTelefoonnummer;
/*////*/// Geef hier het aantal personen in: /*////*////*////*////*////*////*////*////*///
/*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*///
/*////*/ int aantal_personen = 10000; /*////*////*////*////*////*////*////*////*////*///
/*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*////*///
// 10000<SUF>
// 100000 duurt 0.3 seconden om te genereren en 29 seconden om de treeview te maken/vullen.
// 50000 duurt 0.2 seconden om te genereren en 8.3 seconden om de treeview te maken/vullen.
// 25000 duurt 0.2 seconden om te genereren en 2 seconden om de treeview te maken/vullen.
// 10000 duurt 0.1 seconden om te genereren en 0.3 seconden om de treeview te maken/vullen.
// 5000 duurt 0.1 seconden om te genereren en 0.2 seconden om de treeview te maken/vullen.
// 1000 duurt 0.0 seconden om te genereren en 0.0 seconden om de treeview te maken/vullen.
public ObservableList<Persoon> personen;
public Set<Persoon> mensen;
private TableColumn naamCol;
private TableColumn plaatsCol;
private TableColumn telefoonCol;
private TreeItem<Persoon> root = new TreeItem<Persoon>(new Persoon("Mensen", "", ""));
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
mensen = new TreeSet();
personen = observableArrayList();
ObservableSet obvSet = FXCollections.observableSet(mensen);
///*
mensen.add(new Persoon("Arie", "Amsterdam", "020"));
mensen.add(new Persoon("Arie", "Amsterdam", "020"));
mensen.add(new Persoon("Arie", "Amsterdam", "010"));
mensen.add(new Persoon("AArie", "Amsterdam", "020"));
mensen.add(new Persoon("ACrie", "Amsterdam", "020"));
mensen.add(new Persoon("ABrie", "Amsterdam", "020"));
//*/
///*
long startTime = System.nanoTime();
Random rand = new Random();
List<String> plaatsen = new ArrayList<>(aantal_personen/10);
for(int i = 0; i<aantal_personen/10;i++){
plaatsen.add(UUID.randomUUID().toString());
}
List<Persoon> mensenArray = new ArrayList<>(aantal_personen);
for(int i = 0; i<aantal_personen;i++){
mensenArray.add(new Persoon(UUID.randomUUID().toString(),plaatsen.get((int) (Math.random() * aantal_personen/10)),UUID.randomUUID().toString()));
}
mensen.addAll(mensenArray);
long endTime = System.nanoTime();
System.out.println("Tijd genereren:" + ((endTime - startTime)*0.000000001));
//*/
createTreeView();
tvTree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<Persoon>>() {
@Override
public void changed(ObservableValue<? extends TreeItem<Persoon>> observable, TreeItem<Persoon> oldValue, TreeItem<Persoon> newValue) {
try {
personen.clear();
if (newValue.getValue().getNaam().equals("Mensen")) {
personen.addAll(mensen);
} else if (newValue.getChildren().size() != 0) {
for (Persoon p : mensen) {
if (p.getPlaats().equals(newValue.getValue().getNaam())) {
personen.add(p);
}
}
} else {
personen.add(newValue.getValue());
System.out.print(newValue.getValue().getNaam());
}
} catch (Exception e) {
}
}
});
tvTable.setEditable(true);
naamCol = new TableColumn("Naam");
naamCol.setMinWidth(170.0);
plaatsCol = new TableColumn("Plaats");
plaatsCol.setMinWidth(170.0);
telefoonCol = new TableColumn("Telefoon");
telefoonCol.setMinWidth(170.0);
naamCol.setCellValueFactory(new PropertyValueFactory<Persoon, String>("naam"));
plaatsCol.setCellValueFactory(new PropertyValueFactory<Persoon, String>("plaats"));
telefoonCol.setCellValueFactory(new PropertyValueFactory<Persoon, String>("telefoon"));
naamCol.setCellFactory(TextFieldTableCell.forTableColumn());
naamCol.setOnEditCommit(
new EventHandler<CellEditEvent<Persoon, String>>() {
@Override
public void handle(CellEditEvent<Persoon, String> t) {
t.getRowValue().setNaam(t.getNewValue());
createTreeView();
}
}
);
naamCol.setComparator((naam1, naam2) -> naam1.toString().compareTo(naam2.toString()));
plaatsCol.setCellFactory(TextFieldTableCell.forTableColumn());
plaatsCol.setOnEditCommit(
new EventHandler<CellEditEvent<Persoon, String>>() {
@Override
public void handle(CellEditEvent<Persoon, String> t) {
t.getRowValue().setPlaats(t.getNewValue());
createTreeView();
}
}
);
plaatsCol.setComparator((plts1, plts2) -> plts1.toString().compareTo(plts2.toString()));
telefoonCol.setCellFactory(TextFieldTableCell.forTableColumn());
telefoonCol.setOnEditCommit(
new EventHandler<CellEditEvent<Persoon, String>>() {
@Override
public void handle(CellEditEvent<Persoon, String> t) {
t.getRowValue().setTelefoon(t.getNewValue());
createTreeView();
}
}
);
telefoonCol.setComparator((tel1, tel2) -> tel1.toString().compareTo(tel2.toString()));
tvTable.setItems(personen);
tvTable.getColumns().addAll(naamCol, plaatsCol, telefoonCol);
}
public void btnAddClick(Event e) {
personen.add(new Persoon(txtNaam.getText(), txtPlaats.getText(), txtTelefoonnummer.getText()));
mensen.add(new Persoon(txtNaam.getText(), txtPlaats.getText(), txtTelefoonnummer.getText()));
createTreeView();
}
private void createTreeView() {
long startTime = System.nanoTime();
root = new TreeItem<Persoon>(new Persoon("Mensen", "", ""));
ArrayList<Persoon> plaatsen = new ArrayList<Persoon>();
boolean found = false;
for (Persoon p : mensen) { // for in een for in een for
TreeItem<Persoon> persLeaf = new TreeItem<Persoon>(p);
found = false;
for (Persoon plaats : plaatsen) {
if (p.getPlaats().equals(plaats.getNaam())) {
for (TreeItem<Persoon> plaatsNode : root.getChildren()) {
if (plaatsNode.getValue().equals(plaats)) {
plaatsNode.getChildren().add(persLeaf);
found = true;
break;
}
if (found) {
break;
}
}
}
}
if (!found) {
Persoon pers = new Persoon(persLeaf.getValue().getPlaats(), "", "");
plaatsen.add(pers);
TreeItem<Persoon> plaatsNode = new TreeItem<Persoon>(pers);
root.getChildren().add(plaatsNode);
plaatsNode.getChildren().add(persLeaf);
}
}
tvTree.setRoot(root);
root.setExpanded(true);
long endTime = System.nanoTime();
System.out.println("Tijd Treeview maken:" + ((endTime - startTime)*0.000000001));
}
}
|
101441_30 | /* Class: ReadItem
* Parent class: Item
* Purpose: To temporarily store info about the read words of a sentence
* Version: Thinknowlogy 2018r4 (New Science)
*************************************************************************/
/* Copyright (C) 2009-2018, Menno Mafait. Your suggestions, modifications,
* corrections and bug reports are welcome at http://mafait.org/contact/
*************************************************************************/
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*************************************************************************/
package org.mafait.thinknowlogy;
class ReadItem extends Item
{
// Private initialized variables
private boolean isUncountableGeneralizationNoun_ = false;
private short wordOrderNr_ = Constants.NO_ORDER_NR;
private short wordParameter_ = Constants.NO_WORD_PARAMETER;
private short wordTypeNr_ = Constants.NO_WORD_TYPE_NR;
private WordItem readWordItem_ = null;
// Protected constructed variables
protected boolean hasWordPassedIntegrityCheckOfStoredUserSentence = false;
protected boolean isMarkedBySetGrammarParameter = false;
protected short grammarParameter = Constants.NO_GRAMMAR_PARAMETER;
protected GrammarItem definitionGrammarItem = null;
// Protected initialized variables
protected String readString = null;
// Constructor
protected ReadItem( boolean isUncountableGeneralizationNoun, short wordOrderNr, short wordParameter, short wordTypeNr, int readStringLength, String _readString, WordItem readWordItem, List myList, WordItem myWordItem )
{
initializeItemVariables( Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, myList, myWordItem );
// Private initialized variables
isUncountableGeneralizationNoun_ = isUncountableGeneralizationNoun;
wordOrderNr_ = wordOrderNr;
wordParameter_ = wordParameter;
wordTypeNr_ = wordTypeNr;
readWordItem_ = readWordItem;
// Protected initialized variables
readString = ( _readString != null ?
_readString.substring( 0, readStringLength ) : null );
}
// Protected virtual methods
protected void displayString( boolean isReturnQueryToPosition )
{
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
if( readString != null )
{
if( GlobalVariables.hasFoundQuery )
GlobalVariables.queryStringBuffer.append( isReturnQueryToPosition ? Constants.NEW_LINE_STRING : Constants.QUERY_SEPARATOR_SPACE_STRING );
// Display status if not active
if( !isActiveItem() )
GlobalVariables.queryStringBuffer.append( statusChar() );
GlobalVariables.hasFoundQuery = true;
GlobalVariables.queryStringBuffer.append( readString );
}
}
protected void displayWordReferences( boolean isReturnQueryToPosition )
{
String wordString;
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
if( readWordItem_ != null &&
( wordString = readWordItem_.wordTypeString( true, wordTypeNr_ ) ) != null )
{
if( GlobalVariables.hasFoundQuery )
GlobalVariables.queryStringBuffer.append( isReturnQueryToPosition ? Constants.NEW_LINE_STRING : Constants.QUERY_SEPARATOR_SPACE_STRING );
// Display status if not active
if( !isActiveItem() )
GlobalVariables.queryStringBuffer.append( statusChar() );
GlobalVariables.hasFoundQuery = true;
GlobalVariables.queryStringBuffer.append( wordString );
}
}
protected boolean hasParameter( int queryParameter )
{
return ( grammarParameter == queryParameter ||
wordOrderNr_ == queryParameter ||
wordParameter_ == queryParameter ||
( queryParameter == Constants.MAX_QUERY_PARAMETER &&
( grammarParameter > Constants.NO_GRAMMAR_PARAMETER ||
wordOrderNr_ > Constants.NO_ORDER_NR ||
wordParameter_ > Constants.NO_WORD_PARAMETER ) ) );
}
protected boolean hasReferenceItemById( int querySentenceNr, int queryItemNr )
{
return ( ( readWordItem_ == null ? false :
( querySentenceNr == Constants.NO_SENTENCE_NR ? true : readWordItem_.creationSentenceNr() == querySentenceNr ) &&
( queryItemNr == Constants.NO_ITEM_NR ? true : readWordItem_.itemNr() == queryItemNr ) ) ||
( definitionGrammarItem == null ? false :
( querySentenceNr == Constants.NO_SENTENCE_NR ? true : definitionGrammarItem.creationSentenceNr() == querySentenceNr ) &&
( queryItemNr == Constants.NO_ITEM_NR ? true : definitionGrammarItem.itemNr() == queryItemNr ) ) );
}
protected boolean hasWordType( short queryWordTypeNr )
{
return ( wordTypeNr_ == queryWordTypeNr );
}
protected boolean isSorted( Item nextSortItem )
{
ReadItem nextSortReadItem = (ReadItem)nextSortItem;
// Remark: All read items should have the same creationSentenceNr
return ( nextSortItem != null &&
// 1) Ascending wordOrderNr_
( wordOrderNr_ < nextSortReadItem.wordOrderNr_ ||
// 2) Descending wordTypeNr_
( wordOrderNr_ == nextSortReadItem.wordOrderNr_ &&
wordTypeNr_ > nextSortReadItem.wordTypeNr_ ) ) );
}
protected String itemString()
{
return readString;
}
protected StringBuffer itemToStringBuffer( short queryWordTypeNr )
{
StringBuffer queryStringBuffer;
String wordString;
String wordTypeString = myWordItem().wordTypeNameString( wordTypeNr_ );
itemBaseToStringBuffer( queryWordTypeNr );
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
queryStringBuffer = GlobalVariables.queryStringBuffer;
if( hasWordPassedIntegrityCheckOfStoredUserSentence )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "hasWordPassedIntegrityCheckOfStoredUserSentence" );
if( isMarkedBySetGrammarParameter )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "isMarkedBySetGrammarParameter" );
if( wordOrderNr_ > Constants.NO_ORDER_NR )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordOrderNr:" + wordOrderNr_ );
if( wordParameter_ > Constants.NO_WORD_PARAMETER )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordParameter:" + wordParameter_ );
if( grammarParameter > Constants.NO_GRAMMAR_PARAMETER )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "grammarParameter:" + grammarParameter );
if( readString != null )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "readString:" + Constants.QUERY_STRING_START_CHAR + readString + Constants.QUERY_STRING_END_CHAR );
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordType:" + ( wordTypeString == null ? Constants.EMPTY_STRING : wordTypeString ) + Constants.QUERY_WORD_TYPE_STRING + wordTypeNr_ );
if( readWordItem_ != null )
{
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "readWordItem" + Constants.QUERY_REF_ITEM_START_CHAR + readWordItem_.creationSentenceNr() + Constants.QUERY_SEPARATOR_CHAR + readWordItem_.itemNr() + Constants.QUERY_REF_ITEM_END_CHAR );
if( ( wordString = readWordItem_.wordTypeString( true, wordTypeNr_ ) ) != null )
queryStringBuffer.append( Constants.QUERY_WORD_REFERENCE_START_CHAR + wordString + Constants.QUERY_WORD_REFERENCE_END_CHAR );
}
if( definitionGrammarItem != null )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "definitionGrammarItem" + Constants.QUERY_REF_ITEM_START_CHAR + definitionGrammarItem.creationSentenceNr() + Constants.QUERY_SEPARATOR_CHAR + definitionGrammarItem.itemNr() + Constants.QUERY_REF_ITEM_END_CHAR );
return queryStringBuffer;
}
protected BoolResultType findMatchingWordReferenceString( String queryString )
{
if( readWordItem_ != null )
return readWordItem_.findMatchingWordReferenceString( queryString );
return new BoolResultType();
}
// Protected methods
protected boolean hasFoundRelationWordInThisList( WordItem relationWordItem )
{
ReadItem searchReadItem = this;
if( relationWordItem != null )
{
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() &&
searchReadItem.readWordItem() == relationWordItem )
return true;
searchReadItem = searchReadItem.nextReadItem();
}
}
return false;
}
protected boolean isAdjectiveAssigned()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_ASSIGNED );
}
protected boolean isAdjectiveAssignedOrEmpty()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_ASSIGNED ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EMPTY );
}
protected boolean isAdjectiveEvery()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EVERY_NEUTRAL ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EVERY_FEMININE_MASCULINE );
}
protected boolean isAdjectivePrevious()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_PREVIOUS_NEUTRAL ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_PREVIOUS_FEMININE_MASCULINE );
}
protected boolean isArticle()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_ARTICLE );
}
protected boolean isChineseReversedImperativeNoun()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_NUMBER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_VALUE );
}
protected boolean isConjunction()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_CONJUNCTION );
}
protected boolean isDeterminerOrPronoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_SINGULAR_SUBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_SINGULAR_OBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_PRONOUN_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_SUBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_OBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_PLURAL ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_PRONOUN_PLURAL );
}
protected boolean isFrenchPreposition()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_FRENCH_A );
}
protected boolean isGeneralizationWord()
{
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_WORD );
}
protected boolean isImperativeNoun()
{
return ( wordParameter_ == Constants.NO_WORD_PARAMETER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_LANGUAGE ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_MIND ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_NUMBER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_USER );
}
protected boolean isMatchingReadWordTypeNr( short wordTypeNr )
{
return isMatchingWordType( wordTypeNr_, wordTypeNr );
}
protected boolean isNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NOUN_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_NOUN_PLURAL );
}
protected boolean isNonChineseNumeral()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NUMERAL &&
wordParameter_ != Constants.WORD_PARAMETER_NUMERAL_CHINESE_ALL );
}
protected boolean isNumeralBoth()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NUMERAL_BOTH );
}
protected boolean isNegative()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_NO ||
wordParameter_ == Constants.WORD_PARAMETER_ADVERB_NOT ||
wordParameter_ == Constants.WORD_PARAMETER_ADVERB_FRENCH_PAS );
}
protected boolean isNounHeadOrTail()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL );
}
protected boolean isNounValue()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_VALUE );
}
protected boolean isNounValueAhead()
{
ReadItem lookingAheadReadItem;
return ( ( lookingAheadReadItem = this.nextReadItem() ) != null &&
( lookingAheadReadItem = lookingAheadReadItem.nextReadItem() ) != null &&
lookingAheadReadItem.isNounValue() );
}
protected boolean isNounPartOf()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_PART );
}
protected boolean isPossessiveDeterminer()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_PLURAL );
}
protected boolean isPreposition()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PREPOSITION );
}
protected boolean isProperNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PROPER_NOUN );
}
protected boolean isQuestionMark()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_QUESTION_MARK );
}
protected boolean isRelationWord()
{
// To avoid triggering on the article before a proper noun preceded by defined article
return ( wordTypeNr_ != Constants.WORD_TYPE_ARTICLE &&
grammarParameter == Constants.GRAMMAR_RELATION_WORD );
}
protected boolean isSeparator()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_COMMA ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_COLON ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_EXCLAMATION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_QUESTION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_SPANISH_INVERTED_EXCLAMATION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_SPANISH_INVERTED_QUESTION_MARK );
}
protected boolean isSingularNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NOUN_SINGULAR );
}
protected boolean isSkippingChineseIntegrityCheckWords()
{
switch( wordTypeNr_ )
{
case Constants.WORD_TYPE_SYMBOL:
case Constants.WORD_TYPE_PREPOSITION:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION );
case Constants.WORD_TYPE_NUMERAL:
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_ARTICLE:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART );
case Constants.WORD_TYPE_CONJUNCTION:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART ||
grammarParameter == Constants.GRAMMAR_EXCLUSIVE_SPECIFICATION_CONJUNCTION );
case Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_SUBJECTIVE:
return ( grammarParameter == Constants.GRAMMAR_RELATION_PART );
}
return false;
}
protected boolean isSkippingIntegrityCheckWords()
{
switch( wordTypeNr_ )
{
case Constants.WORD_TYPE_SYMBOL:
// Skip extra comma in sentence that isn't written.
// See grammar file for: '( symbolComma )'
// Example: "A creature is an animal, fungus, human-being, micro-organism, or plant."
return ( grammarParameter == Constants.GRAMMAR_EXCLUSIVE_SPECIFICATION_CONJUNCTION ||
grammarParameter == Constants.GRAMMAR_SENTENCE_CONJUNCTION );
case Constants.WORD_TYPE_NUMERAL:
// Skip on different order of specification words with a numeral
// Example: "John has 2 sons and a daughter"
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION );
case Constants.WORD_TYPE_ADJECTIVE:
// Typical for Spanish
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD ||
// Typical for French
grammarParameter == Constants.GRAMMAR_RELATION_PART );
case Constants.WORD_TYPE_ADVERB:
// Skip mismatch in uncertainty
return ( grammarParameter == Constants.GRAMMAR_VERB );
case Constants.WORD_TYPE_ARTICLE:
// Skip missing indefinite article, because of a plural noun
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION ||
// Skip wrong indefinite article
// Example: "An horse is incorrect."
grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART ||
// Typical for Dutch
// Skip wrong definite article
// Example: "De paard is onjuist."
grammarParameter == Constants.GRAMMAR_GENERALIZATION_ASSIGNMENT );
case Constants.WORD_TYPE_CONJUNCTION:
// Skip question entered with singular verb, but written with plural verb
// Example: "Expert is a user and his password is expert123."
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION ||
// Skip linked conjunctions
// Example: "Guest is a user and has no password."
grammarParameter == Constants.GRAMMAR_LINKED_GENERALIZATION_CONJUNCTION ||
// Skip sentence conjunctions
// Example: "Expert is a user and his password is expert123."
grammarParameter == Constants.GRAMMAR_SENTENCE_CONJUNCTION );
case Constants.WORD_TYPE_NOUN_SINGULAR:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_WORD ||
grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_NOUN_PLURAL:
// Skip plural noun if singular noun is entered
// Example: entered: "Is Joe a child?", written: "Are Paul and Joe children?"
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_VERB_SINGULAR:
return ( grammarParameter == Constants.GRAMMAR_VERB );
case Constants.WORD_TYPE_VERB_PLURAL:
// Skip plural question verb if singular verb is entered
// Example: entered: "Is Joe a child?", written: "Are Paul and Joe children?"
return ( grammarParameter == Constants.GRAMMAR_QUESTION_VERB );
}
return false;
}
protected boolean isSpecificationWord()
{
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
}
protected boolean isSymbol()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_SYMBOL );
}
protected boolean isUncountableGeneralizationNoun()
{
return isUncountableGeneralizationNoun_;
}
protected boolean isVerb()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_VERB_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_VERB_PLURAL );
}
protected boolean isVirtualListPreposition()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_FROM ||
wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_TO ||
wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_OF );
}
protected boolean isText()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_TEXT );
}
protected short readAheadChineseImperativeVerbParameter()
{
ReadItem searchReadItem = this;
if( wordParameter_ == Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_CHINESE_PUT )
{
while( ( searchReadItem = searchReadItem.nextReadItem() ) != null )
{
switch( searchReadItem.wordParameter() )
{
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_ADD:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_ADD;
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_MOVE:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_MOVE;
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_REMOVE:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_REMOVE;
}
}
}
return Constants.NO_WORD_PARAMETER;
}
protected short wordOrderNr()
{
return wordOrderNr_;
}
protected short wordParameter()
{
return wordParameter_;
}
protected short wordTypeNr()
{
return wordTypeNr_;
}
protected byte changeReadWord( short newWordTypeNr, WordItem newReadWordItem )
{
if( newReadWordItem == null )
return startError( 1, null, "The given new read word item is undefined" );
wordTypeNr_ = newWordTypeNr;
readWordItem_ = newReadWordItem;
return Constants.RESULT_OK;
}
protected String readWordTypeString()
{
return ( readWordItem_ != null ?
readWordItem_.activeWordTypeString( wordTypeNr_ ) : null );
}
protected ReadItem firstRelationWordReadItem()
{
ReadItem searchReadItem = this;
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() )
return searchReadItem;
searchReadItem = searchReadItem.nextReadItem();
}
return null;
}
protected ReadItem nextReadItem()
{
return (ReadItem)nextItem;
}
protected WordItem lookAheadRelationWordItem()
{
ReadItem searchReadItem = this;
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() )
return searchReadItem.readWordItem();
searchReadItem = searchReadItem.nextReadItem();
}
return null;
}
protected WordItem readWordItem()
{
return readWordItem_;
}
protected WordTypeItem activeReadWordTypeItem()
{
return ( readWordItem_ != null ?
readWordItem_.activeWordTypeItem( true, wordTypeNr_ ) : null );
}
};
/*************************************************************************
* "The godly will see these things and be glad,
* while the wicked are struck in silent." (Psalm 107:42)
*************************************************************************/
| 980f/Thinknowlogy | source/Java/org/mafait/thinknowlogy/ReadItem.java | 5,914 | // Example: "De paard is onjuist." | line_comment | nl | /* Class: ReadItem
* Parent class: Item
* Purpose: To temporarily store info about the read words of a sentence
* Version: Thinknowlogy 2018r4 (New Science)
*************************************************************************/
/* Copyright (C) 2009-2018, Menno Mafait. Your suggestions, modifications,
* corrections and bug reports are welcome at http://mafait.org/contact/
*************************************************************************/
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*************************************************************************/
package org.mafait.thinknowlogy;
class ReadItem extends Item
{
// Private initialized variables
private boolean isUncountableGeneralizationNoun_ = false;
private short wordOrderNr_ = Constants.NO_ORDER_NR;
private short wordParameter_ = Constants.NO_WORD_PARAMETER;
private short wordTypeNr_ = Constants.NO_WORD_TYPE_NR;
private WordItem readWordItem_ = null;
// Protected constructed variables
protected boolean hasWordPassedIntegrityCheckOfStoredUserSentence = false;
protected boolean isMarkedBySetGrammarParameter = false;
protected short grammarParameter = Constants.NO_GRAMMAR_PARAMETER;
protected GrammarItem definitionGrammarItem = null;
// Protected initialized variables
protected String readString = null;
// Constructor
protected ReadItem( boolean isUncountableGeneralizationNoun, short wordOrderNr, short wordParameter, short wordTypeNr, int readStringLength, String _readString, WordItem readWordItem, List myList, WordItem myWordItem )
{
initializeItemVariables( Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, Constants.NO_SENTENCE_NR, myList, myWordItem );
// Private initialized variables
isUncountableGeneralizationNoun_ = isUncountableGeneralizationNoun;
wordOrderNr_ = wordOrderNr;
wordParameter_ = wordParameter;
wordTypeNr_ = wordTypeNr;
readWordItem_ = readWordItem;
// Protected initialized variables
readString = ( _readString != null ?
_readString.substring( 0, readStringLength ) : null );
}
// Protected virtual methods
protected void displayString( boolean isReturnQueryToPosition )
{
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
if( readString != null )
{
if( GlobalVariables.hasFoundQuery )
GlobalVariables.queryStringBuffer.append( isReturnQueryToPosition ? Constants.NEW_LINE_STRING : Constants.QUERY_SEPARATOR_SPACE_STRING );
// Display status if not active
if( !isActiveItem() )
GlobalVariables.queryStringBuffer.append( statusChar() );
GlobalVariables.hasFoundQuery = true;
GlobalVariables.queryStringBuffer.append( readString );
}
}
protected void displayWordReferences( boolean isReturnQueryToPosition )
{
String wordString;
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
if( readWordItem_ != null &&
( wordString = readWordItem_.wordTypeString( true, wordTypeNr_ ) ) != null )
{
if( GlobalVariables.hasFoundQuery )
GlobalVariables.queryStringBuffer.append( isReturnQueryToPosition ? Constants.NEW_LINE_STRING : Constants.QUERY_SEPARATOR_SPACE_STRING );
// Display status if not active
if( !isActiveItem() )
GlobalVariables.queryStringBuffer.append( statusChar() );
GlobalVariables.hasFoundQuery = true;
GlobalVariables.queryStringBuffer.append( wordString );
}
}
protected boolean hasParameter( int queryParameter )
{
return ( grammarParameter == queryParameter ||
wordOrderNr_ == queryParameter ||
wordParameter_ == queryParameter ||
( queryParameter == Constants.MAX_QUERY_PARAMETER &&
( grammarParameter > Constants.NO_GRAMMAR_PARAMETER ||
wordOrderNr_ > Constants.NO_ORDER_NR ||
wordParameter_ > Constants.NO_WORD_PARAMETER ) ) );
}
protected boolean hasReferenceItemById( int querySentenceNr, int queryItemNr )
{
return ( ( readWordItem_ == null ? false :
( querySentenceNr == Constants.NO_SENTENCE_NR ? true : readWordItem_.creationSentenceNr() == querySentenceNr ) &&
( queryItemNr == Constants.NO_ITEM_NR ? true : readWordItem_.itemNr() == queryItemNr ) ) ||
( definitionGrammarItem == null ? false :
( querySentenceNr == Constants.NO_SENTENCE_NR ? true : definitionGrammarItem.creationSentenceNr() == querySentenceNr ) &&
( queryItemNr == Constants.NO_ITEM_NR ? true : definitionGrammarItem.itemNr() == queryItemNr ) ) );
}
protected boolean hasWordType( short queryWordTypeNr )
{
return ( wordTypeNr_ == queryWordTypeNr );
}
protected boolean isSorted( Item nextSortItem )
{
ReadItem nextSortReadItem = (ReadItem)nextSortItem;
// Remark: All read items should have the same creationSentenceNr
return ( nextSortItem != null &&
// 1) Ascending wordOrderNr_
( wordOrderNr_ < nextSortReadItem.wordOrderNr_ ||
// 2) Descending wordTypeNr_
( wordOrderNr_ == nextSortReadItem.wordOrderNr_ &&
wordTypeNr_ > nextSortReadItem.wordTypeNr_ ) ) );
}
protected String itemString()
{
return readString;
}
protected StringBuffer itemToStringBuffer( short queryWordTypeNr )
{
StringBuffer queryStringBuffer;
String wordString;
String wordTypeString = myWordItem().wordTypeNameString( wordTypeNr_ );
itemBaseToStringBuffer( queryWordTypeNr );
if( GlobalVariables.queryStringBuffer == null )
GlobalVariables.queryStringBuffer = new StringBuffer();
queryStringBuffer = GlobalVariables.queryStringBuffer;
if( hasWordPassedIntegrityCheckOfStoredUserSentence )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "hasWordPassedIntegrityCheckOfStoredUserSentence" );
if( isMarkedBySetGrammarParameter )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "isMarkedBySetGrammarParameter" );
if( wordOrderNr_ > Constants.NO_ORDER_NR )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordOrderNr:" + wordOrderNr_ );
if( wordParameter_ > Constants.NO_WORD_PARAMETER )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordParameter:" + wordParameter_ );
if( grammarParameter > Constants.NO_GRAMMAR_PARAMETER )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "grammarParameter:" + grammarParameter );
if( readString != null )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "readString:" + Constants.QUERY_STRING_START_CHAR + readString + Constants.QUERY_STRING_END_CHAR );
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "wordType:" + ( wordTypeString == null ? Constants.EMPTY_STRING : wordTypeString ) + Constants.QUERY_WORD_TYPE_STRING + wordTypeNr_ );
if( readWordItem_ != null )
{
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "readWordItem" + Constants.QUERY_REF_ITEM_START_CHAR + readWordItem_.creationSentenceNr() + Constants.QUERY_SEPARATOR_CHAR + readWordItem_.itemNr() + Constants.QUERY_REF_ITEM_END_CHAR );
if( ( wordString = readWordItem_.wordTypeString( true, wordTypeNr_ ) ) != null )
queryStringBuffer.append( Constants.QUERY_WORD_REFERENCE_START_CHAR + wordString + Constants.QUERY_WORD_REFERENCE_END_CHAR );
}
if( definitionGrammarItem != null )
queryStringBuffer.append( Constants.QUERY_SEPARATOR_STRING + "definitionGrammarItem" + Constants.QUERY_REF_ITEM_START_CHAR + definitionGrammarItem.creationSentenceNr() + Constants.QUERY_SEPARATOR_CHAR + definitionGrammarItem.itemNr() + Constants.QUERY_REF_ITEM_END_CHAR );
return queryStringBuffer;
}
protected BoolResultType findMatchingWordReferenceString( String queryString )
{
if( readWordItem_ != null )
return readWordItem_.findMatchingWordReferenceString( queryString );
return new BoolResultType();
}
// Protected methods
protected boolean hasFoundRelationWordInThisList( WordItem relationWordItem )
{
ReadItem searchReadItem = this;
if( relationWordItem != null )
{
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() &&
searchReadItem.readWordItem() == relationWordItem )
return true;
searchReadItem = searchReadItem.nextReadItem();
}
}
return false;
}
protected boolean isAdjectiveAssigned()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_ASSIGNED );
}
protected boolean isAdjectiveAssignedOrEmpty()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_ASSIGNED ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EMPTY );
}
protected boolean isAdjectiveEvery()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EVERY_NEUTRAL ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_EVERY_FEMININE_MASCULINE );
}
protected boolean isAdjectivePrevious()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_PREVIOUS_NEUTRAL ||
wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_PREVIOUS_FEMININE_MASCULINE );
}
protected boolean isArticle()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_ARTICLE );
}
protected boolean isChineseReversedImperativeNoun()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_NUMBER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_VALUE );
}
protected boolean isConjunction()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_CONJUNCTION );
}
protected boolean isDeterminerOrPronoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_SINGULAR_SUBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_SINGULAR_OBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_PRONOUN_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_SUBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_OBJECTIVE ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_PLURAL ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_PRONOUN_PLURAL );
}
protected boolean isFrenchPreposition()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_FRENCH_A );
}
protected boolean isGeneralizationWord()
{
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_WORD );
}
protected boolean isImperativeNoun()
{
return ( wordParameter_ == Constants.NO_WORD_PARAMETER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_LANGUAGE ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_MIND ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_NUMBER ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_USER );
}
protected boolean isMatchingReadWordTypeNr( short wordTypeNr )
{
return isMatchingWordType( wordTypeNr_, wordTypeNr );
}
protected boolean isNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NOUN_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_NOUN_PLURAL );
}
protected boolean isNonChineseNumeral()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NUMERAL &&
wordParameter_ != Constants.WORD_PARAMETER_NUMERAL_CHINESE_ALL );
}
protected boolean isNumeralBoth()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NUMERAL_BOTH );
}
protected boolean isNegative()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_ADJECTIVE_NO ||
wordParameter_ == Constants.WORD_PARAMETER_ADVERB_NOT ||
wordParameter_ == Constants.WORD_PARAMETER_ADVERB_FRENCH_PAS );
}
protected boolean isNounHeadOrTail()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_HEAD ||
wordParameter_ == Constants.WORD_PARAMETER_NOUN_TAIL );
}
protected boolean isNounValue()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_VALUE );
}
protected boolean isNounValueAhead()
{
ReadItem lookingAheadReadItem;
return ( ( lookingAheadReadItem = this.nextReadItem() ) != null &&
( lookingAheadReadItem = lookingAheadReadItem.nextReadItem() ) != null &&
lookingAheadReadItem.isNounValue() );
}
protected boolean isNounPartOf()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_NOUN_PART );
}
protected boolean isPossessiveDeterminer()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_POSSESSIVE_DETERMINER_PLURAL );
}
protected boolean isPreposition()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PREPOSITION );
}
protected boolean isProperNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_PROPER_NOUN );
}
protected boolean isQuestionMark()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_QUESTION_MARK );
}
protected boolean isRelationWord()
{
// To avoid triggering on the article before a proper noun preceded by defined article
return ( wordTypeNr_ != Constants.WORD_TYPE_ARTICLE &&
grammarParameter == Constants.GRAMMAR_RELATION_WORD );
}
protected boolean isSeparator()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_COMMA ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_COLON ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_EXCLAMATION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_QUESTION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_SPANISH_INVERTED_EXCLAMATION_MARK ||
wordParameter_ == Constants.WORD_PARAMETER_SYMBOL_SPANISH_INVERTED_QUESTION_MARK );
}
protected boolean isSingularNoun()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_NOUN_SINGULAR );
}
protected boolean isSkippingChineseIntegrityCheckWords()
{
switch( wordTypeNr_ )
{
case Constants.WORD_TYPE_SYMBOL:
case Constants.WORD_TYPE_PREPOSITION:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION );
case Constants.WORD_TYPE_NUMERAL:
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_ARTICLE:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART );
case Constants.WORD_TYPE_CONJUNCTION:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART ||
grammarParameter == Constants.GRAMMAR_EXCLUSIVE_SPECIFICATION_CONJUNCTION );
case Constants.WORD_TYPE_PERSONAL_PRONOUN_PLURAL_SUBJECTIVE:
return ( grammarParameter == Constants.GRAMMAR_RELATION_PART );
}
return false;
}
protected boolean isSkippingIntegrityCheckWords()
{
switch( wordTypeNr_ )
{
case Constants.WORD_TYPE_SYMBOL:
// Skip extra comma in sentence that isn't written.
// See grammar file for: '( symbolComma )'
// Example: "A creature is an animal, fungus, human-being, micro-organism, or plant."
return ( grammarParameter == Constants.GRAMMAR_EXCLUSIVE_SPECIFICATION_CONJUNCTION ||
grammarParameter == Constants.GRAMMAR_SENTENCE_CONJUNCTION );
case Constants.WORD_TYPE_NUMERAL:
// Skip on different order of specification words with a numeral
// Example: "John has 2 sons and a daughter"
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION );
case Constants.WORD_TYPE_ADJECTIVE:
// Typical for Spanish
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD ||
// Typical for French
grammarParameter == Constants.GRAMMAR_RELATION_PART );
case Constants.WORD_TYPE_ADVERB:
// Skip mismatch in uncertainty
return ( grammarParameter == Constants.GRAMMAR_VERB );
case Constants.WORD_TYPE_ARTICLE:
// Skip missing indefinite article, because of a plural noun
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION ||
// Skip wrong indefinite article
// Example: "An horse is incorrect."
grammarParameter == Constants.GRAMMAR_GENERALIZATION_PART ||
// Typical for Dutch
// Skip wrong definite article
// Examp<SUF>
grammarParameter == Constants.GRAMMAR_GENERALIZATION_ASSIGNMENT );
case Constants.WORD_TYPE_CONJUNCTION:
// Skip question entered with singular verb, but written with plural verb
// Example: "Expert is a user and his password is expert123."
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_SPECIFICATION ||
// Skip linked conjunctions
// Example: "Guest is a user and has no password."
grammarParameter == Constants.GRAMMAR_LINKED_GENERALIZATION_CONJUNCTION ||
// Skip sentence conjunctions
// Example: "Expert is a user and his password is expert123."
grammarParameter == Constants.GRAMMAR_SENTENCE_CONJUNCTION );
case Constants.WORD_TYPE_NOUN_SINGULAR:
return ( grammarParameter == Constants.GRAMMAR_GENERALIZATION_WORD ||
grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_NOUN_PLURAL:
// Skip plural noun if singular noun is entered
// Example: entered: "Is Joe a child?", written: "Are Paul and Joe children?"
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
case Constants.WORD_TYPE_VERB_SINGULAR:
return ( grammarParameter == Constants.GRAMMAR_VERB );
case Constants.WORD_TYPE_VERB_PLURAL:
// Skip plural question verb if singular verb is entered
// Example: entered: "Is Joe a child?", written: "Are Paul and Joe children?"
return ( grammarParameter == Constants.GRAMMAR_QUESTION_VERB );
}
return false;
}
protected boolean isSpecificationWord()
{
return ( grammarParameter == Constants.GRAMMAR_SPECIFICATION_WORD );
}
protected boolean isSymbol()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_SYMBOL );
}
protected boolean isUncountableGeneralizationNoun()
{
return isUncountableGeneralizationNoun_;
}
protected boolean isVerb()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_VERB_SINGULAR ||
wordTypeNr_ == Constants.WORD_TYPE_VERB_PLURAL );
}
protected boolean isVirtualListPreposition()
{
return ( wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_FROM ||
wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_TO ||
wordParameter_ == Constants.WORD_PARAMETER_PREPOSITION_OF );
}
protected boolean isText()
{
return ( wordTypeNr_ == Constants.WORD_TYPE_TEXT );
}
protected short readAheadChineseImperativeVerbParameter()
{
ReadItem searchReadItem = this;
if( wordParameter_ == Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_CHINESE_PUT )
{
while( ( searchReadItem = searchReadItem.nextReadItem() ) != null )
{
switch( searchReadItem.wordParameter() )
{
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_ADD:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_ADD;
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_MOVE:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_MOVE;
case Constants.WORD_PARAMETER_PREPOSITION_CHINESE_VERB_REMOVE:
return Constants.WORD_PARAMETER_SINGULAR_VERB_IMPERATIVE_REMOVE;
}
}
}
return Constants.NO_WORD_PARAMETER;
}
protected short wordOrderNr()
{
return wordOrderNr_;
}
protected short wordParameter()
{
return wordParameter_;
}
protected short wordTypeNr()
{
return wordTypeNr_;
}
protected byte changeReadWord( short newWordTypeNr, WordItem newReadWordItem )
{
if( newReadWordItem == null )
return startError( 1, null, "The given new read word item is undefined" );
wordTypeNr_ = newWordTypeNr;
readWordItem_ = newReadWordItem;
return Constants.RESULT_OK;
}
protected String readWordTypeString()
{
return ( readWordItem_ != null ?
readWordItem_.activeWordTypeString( wordTypeNr_ ) : null );
}
protected ReadItem firstRelationWordReadItem()
{
ReadItem searchReadItem = this;
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() )
return searchReadItem;
searchReadItem = searchReadItem.nextReadItem();
}
return null;
}
protected ReadItem nextReadItem()
{
return (ReadItem)nextItem;
}
protected WordItem lookAheadRelationWordItem()
{
ReadItem searchReadItem = this;
while( searchReadItem != null )
{
if( searchReadItem.isRelationWord() )
return searchReadItem.readWordItem();
searchReadItem = searchReadItem.nextReadItem();
}
return null;
}
protected WordItem readWordItem()
{
return readWordItem_;
}
protected WordTypeItem activeReadWordTypeItem()
{
return ( readWordItem_ != null ?
readWordItem_.activeWordTypeItem( true, wordTypeNr_ ) : null );
}
};
/*************************************************************************
* "The godly will see these things and be glad,
* while the wicked are struck in silent." (Psalm 107:42)
*************************************************************************/
|
129371_11 | package Map;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
//Een TreeMap maken en elementen toevoegen
TreeMap<String,Integer> treeMap=new TreeMap<>();
treeMap.put("Apple",10);
treeMap.put("Banana",5);
treeMap.put("orange",8);
//Een element opzoeken en de waarde afdrukken
int quantityOfApple=treeMap.get("Apple");
System.out.println("Aantal appels:"+quantityOfApple); // Aantal appels:10
//Controleren of een sleutel aanwezig is in de TreeMap
boolean containsBanana=treeMap.containsKey("Banana");
System.out.println("Bevat banaan?"+containsBanana); //Bevat banaan?true
//De grootte van de TreeMap opvragen
int size =treeMap.size();
System.out.println("Grootte van de TreeMap:"+size); //Grootte van de TreeMap:3
//Alle sleutels van de TreeMap afdrukken
for(String key : treeMap.keySet()){
System.out.println("Sleutel:"+key); //Sleutel:Apple // Sleutel:Banana //Sleutel:orange
}
//Alle waarden van de TreeMap afdruken
for(int value:treeMap.values()){
System.out.println("Waarde:"+value); //Waarde:10 // Waarde:5 // Waarde:8
}
//De TreeMap leegmaken
treeMap.clear();
boolean isEmpty=treeMap.isEmpty();
System.out.println("Is de TreeMap leeg?"+isEmpty); //Is de TreeMap leeg?true
}
}
| 9elmaz9/Java_Fundamentals | Chapter13_Collections/src/Map/TreeMapExample.java | 408 | //De TreeMap leegmaken | line_comment | nl | package Map;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
//Een TreeMap maken en elementen toevoegen
TreeMap<String,Integer> treeMap=new TreeMap<>();
treeMap.put("Apple",10);
treeMap.put("Banana",5);
treeMap.put("orange",8);
//Een element opzoeken en de waarde afdrukken
int quantityOfApple=treeMap.get("Apple");
System.out.println("Aantal appels:"+quantityOfApple); // Aantal appels:10
//Controleren of een sleutel aanwezig is in de TreeMap
boolean containsBanana=treeMap.containsKey("Banana");
System.out.println("Bevat banaan?"+containsBanana); //Bevat banaan?true
//De grootte van de TreeMap opvragen
int size =treeMap.size();
System.out.println("Grootte van de TreeMap:"+size); //Grootte van de TreeMap:3
//Alle sleutels van de TreeMap afdrukken
for(String key : treeMap.keySet()){
System.out.println("Sleutel:"+key); //Sleutel:Apple // Sleutel:Banana //Sleutel:orange
}
//Alle waarden van de TreeMap afdruken
for(int value:treeMap.values()){
System.out.println("Waarde:"+value); //Waarde:10 // Waarde:5 // Waarde:8
}
//De Tr<SUF>
treeMap.clear();
boolean isEmpty=treeMap.isEmpty();
System.out.println("Is de TreeMap leeg?"+isEmpty); //Is de TreeMap leeg?true
}
}
|
150156_20 |
package org.CrossApp.lib;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView.OnEditorActionListener;
@SuppressLint("UseSparseArrays")
public class CrossAppTextField {
private EditText textField = null;
private static FrameLayout layout = null;
private static CrossAppActivity context = null;
private static Handler handler = null;
private static HashMap<Integer, CrossAppTextField> dict = null;
private int mykey = -1;
private ByteBuffer imageData = null;
private Bitmap bmp = null;
private Button clearButton = null;
private int keyboardheight = 0;
private int keyboardheightTemp = 0;
private int leftMargin = 10;
private int rightMargin = 10;
private int inputType = InputType.TYPE_CLASS_TEXT;
private int fontSize = 20;
private String placeHolder = "";
private int placeHolderColor = Color.GRAY;
private String textFieldText = "";
private int textFieldTextColor = Color.BLACK;
private int contentSizeW = 800;
private int contentSizeH = 200;
private boolean secureTextEntry = false;
private boolean showClearButton = false;
private int keyBoardReturnType = EditorInfo.IME_ACTION_DONE;
private int gravity = (Gravity.LEFT | Gravity.CENTER_VERTICAL);
private TextWatcher textWatcher = null;
private OnEditorActionListener onEditorActionListener = null;
private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = null;
private boolean isSetText = false;
private String beforeTextString = "";
private int selection = 0;
private boolean isFocus = false;
private boolean isFocusAction = false;
public static void initWithHandler() {
if (dict == null) {
dict = new HashMap<Integer, CrossAppTextField>();
}
CrossAppTextField.reload();
}
public static void reload() {
handler = new Handler(Looper.myLooper());
context = (CrossAppActivity) CrossAppActivity.getContext();
layout = CrossAppActivity.getFrameLayout();
Set<Integer> keys = (Set<Integer>) dict.keySet();
Iterator<Integer> iterator = keys.iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
CrossAppTextField textField = dict.get(key);
textField.initWithTextField(key);
}
}
public static boolean isShowKeyboard() {
boolean showKeyboard = false;
Iterator<Entry<Integer, CrossAppTextField>> iter = dict.entrySet().iterator();
while (iter.hasNext()) {
HashMap.Entry entry = (HashMap.Entry) iter.next();
CrossAppTextField val = (CrossAppTextField) entry.getValue();
if (val.textField != null && val.textField.isFocused()) {
showKeyboard = true;
break;
}
}
return showKeyboard;
}
//keyBoard return call back
private static native void keyBoardReturnCallBack(int key);
private static native boolean textChange(int key, String before, String change, int arg0, int arg1);
private static native void didTextChanged(int key);
private static native void text(int key, byte[] text, int lenght);
public void init(int key) {
mykey = key;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
initWithTextField(mykey);
}
});
}
//keyboard height
private static native void keyBoardHeightReturn(int key, int height);
private static native void resignFirstResponder(int key);
public int getKeyBoardHeight() {
onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
Rect r = new Rect();
layout.getWindowVisibleDisplayFrame(r);
int screenHeight = layout.getRootView().getHeight();
keyboardheightTemp = screenHeight - r.bottom;
if (keyboardheightTemp != keyboardheight) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (keyboardheightTemp < 1 && isFocus == true) {
//hide
isFocus = false;
context.runOnGLThread(new Runnable() {
@Override
public void run() {
resignFirstResponder(mykey);
}
});
}
if (isFocusAction) {
context.runOnGLThread(new Runnable() {
@Override
public void run() {
keyBoardHeightReturn(mykey, keyboardheightTemp);
}
});
isFocusAction = false;
}
}
});
}
keyboardheight = keyboardheightTemp;
}
};
layout.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
return keyboardheight;
}
public void setFontSize(final int size) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
fontSize = size;
textField.setTextSize(size);
}
});
}
//placeholder text
public void setTextFieldPlacHolder(final String text) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
placeHolder = text;
textField.setHint(text);
}
});
}
public void setTextFieldText(final String text) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
isSetText = true;
textFieldText = text;
textField.setText(text);
textField.setSelection(textField.getText().length());
isSetText = false;
}
});
}
//placeholder color
public void setTextFieldPlacHolderColor(final int color) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
placeHolderColor = color;
textField.setHintTextColor(color);
}
});
}
//textfield color
public void setTextFieldTextColor(final int color) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
textFieldTextColor = color;
textField.setTextColor(color);
}
});
}
//keyboard type
public void setKeyBoardType(final int type) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
switch (type) {
case 0:
//default
inputType = InputType.TYPE_CLASS_TEXT;
break;
case 1:
//NumbersAndPunctuation
inputType = InputType.TYPE_NUMBER_VARIATION_NORMAL;
break;
case 2:
//URL
inputType = InputType.TYPE_TEXT_VARIATION_URI;
break;
case 3:
//NumberPad
inputType = InputType.TYPE_CLASS_NUMBER;
break;
case 4:
//PhonePad
inputType = InputType.TYPE_CLASS_PHONE;
break;
case 5:
//NamePhonePad
inputType = InputType.TYPE_TEXT_VARIATION_PERSON_NAME;
break;
case 6:
//EmailAddress
inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
default:
break;
}
textField.setInputType(inputType);
}
});
}
//textField Algin
public void setTextFieldAlgin(final int var) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
switch (var) {
case 0:
//center
gravity = (Gravity.LEFT | Gravity.CENTER_VERTICAL);
break;
case 1:
//left
gravity = (Gravity.CENTER | Gravity.CENTER_VERTICAL);
break;
case 2:
//right
gravity = (Gravity.RIGHT | Gravity.CENTER_VERTICAL);
break;
default:
break;
}
textField.setGravity(gravity);
}
});
}
//text field return type
public void setKeyBoardReturnType(final int type) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
String string = type + "";
Log.d("android", string);
switch (type) {
case 0:
keyBoardReturnType = EditorInfo.IME_ACTION_DONE;
break;
case 1:
keyBoardReturnType = EditorInfo.IME_ACTION_GO;
break;
case 2:
keyBoardReturnType = EditorInfo.IME_ACTION_NEXT;
break;
case 3:
keyBoardReturnType = EditorInfo.IME_ACTION_SEARCH;
break;
case 4:
keyBoardReturnType = EditorInfo.IME_ACTION_SEND;
break;
default:
keyBoardReturnType = EditorInfo.IME_ACTION_DONE;
break;
}
textField.setImeOptions(keyBoardReturnType);
}
});
}
//margins right length
public void setMarginsDis(final int left, final int right, final int top, final int bottom) {
leftMargin = left;
rightMargin = right;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
textField.setPadding(left, 0, right, 0);
}
});
}
//margins left image
public void setMarginLeftImage(final String filePath) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
//margins right image
public void setMarginRightImage(final String filePath) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
//clearButton
public void showClearButton() {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
showClearButton = true;
clearButton = new Button(context);
clearButton.setBackgroundColor(0);
// clearButton.setHighlightColor(Color.YELLOW);
FrameLayout.LayoutParams btnParams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
btnParams.width = 20;
btnParams.height = 20;
btnParams.rightMargin = -1000;
btnParams.topMargin = -1000;
layout.addView(clearButton, btnParams);
clearButton.setVisibility(View.GONE);
clearButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textField.setText("");
textField.setSelection(textField.getText().length());
}
});
}
});
}
public void setTextFieldPoint(final int x, final int y) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) textField.getLayoutParams();
params.leftMargin = x;
params.topMargin = y;
textField.setLayoutParams(params);
textField.requestLayout();
if (clearButton != null) {
FrameLayout.LayoutParams btnParams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
btnParams.width = params.height;
btnParams.height = params.height;
btnParams.leftMargin = params.leftMargin + params.width - btnParams.width;
btnParams.topMargin = params.topMargin;
clearButton.setLayoutParams(btnParams);
clearButton.requestLayout();
}
}
});
}
public void setTextFieldSize(final int width, final int height) {
contentSizeW = width;
contentSizeH = height;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) textField.getLayoutParams();
params.width = contentSizeW;
params.height = contentSizeH;
textField.setLayoutParams(params);
textField.requestLayout();
TimerTask task = new TimerTask() {
public void run() {
getImage();
}
};
Timer timer = new Timer();
timer.schedule(task, (long) 100);
}
});
}
public void setSecureTextEntry(int var) {
if (var == 0) {
secureTextEntry = false;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
textField.setInputType(inputType);
}
});
} else {
secureTextEntry = true;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
if (inputType == InputType.TYPE_CLASS_NUMBER) {
textField.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
} else {
textField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
}
});
}
}
private static native void onByte(int key, byte[] buf, int wdith, int height);
public void getImage() {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
bmp = textField.getDrawingCache();
if (bmp != null && imageData == null) {
imageData = ByteBuffer.allocate(bmp.getRowBytes() * bmp.getHeight());
bmp.copyPixelsToBuffer(imageData);
context.runOnGLThread(new Runnable() {
@Override
public void run() {
onByte(mykey, imageData.array(), bmp.getWidth(), bmp.getHeight());
imageData = null;
}
});
}
}
});
}
private static native void hideImageView(int key);
public void becomeFirstResponder() {
CrossAppActivity.setSingleTextField(this);
context.runOnUiThread(new Runnable() {
@Override
public void run() {
isFocus = true;
isFocusAction = true;
//show
textField.requestFocus();
Editable etext = textField.getText();
textField.setSelection(etext.length());
TimerTask task = new TimerTask() {
public void run() {
if (CrossAppTextField.isShowKeyboard() || CrossAppTextView.isShowKeyboard()) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textField, 0);
}
}
};
Timer timer = new Timer();
timer.schedule(task, (long) 20);
if (clearButton != null) {
clearButton.setVisibility(View.VISIBLE);
textField.setPadding(leftMargin, 0, rightMargin, 0);
}
context.runOnGLThread(new Runnable() {
@Override
public void run() {
hideImageView(mykey);
}
});
}
});
}
private static native void showImageView(int key);
public void resignFirstResponder() {
CrossAppActivity.setSingleTextField(null);
context.runOnUiThread(new Runnable() {
@Override
public void run() {
isFocus = false;
isFocusAction = true;
//show
if (clearButton != null) {
clearButton.setVisibility(View.GONE);
textField.setPadding(leftMargin, 0, 10, 0);
}
textField.clearFocus();
TimerTask task = new TimerTask() {
public void run() {
if (!CrossAppTextField.isShowKeyboard() && !CrossAppTextView.isShowKeyboard()) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(textField.getWindowToken(), 0);
}
}
};
Timer timer = new Timer();
timer.schedule(task, (long) 20);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) textField.getLayoutParams();
params.leftMargin = -10000;
params.topMargin = 0;
textField.setLayoutParams(params);
bmp = textField.getDrawingCache();
if (bmp != null && imageData == null) {
imageData = ByteBuffer.allocate(bmp.getRowBytes() * bmp.getHeight());
bmp.copyPixelsToBuffer(imageData);
context.runOnGLThread(new Runnable() {
@Override
public void run() {
onByte(mykey, imageData.array(), bmp.getWidth(), bmp.getHeight());
showImageView(mykey);
imageData = null;
}
});
}
}
});
}
public void setMaxLength(final int var) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
textField.setFilters(new InputFilter[]{new InputFilter.LengthFilter(var)});
}
});
}
@TargetApi(16)
public void removeThis() {
textField.removeTextChangedListener(textWatcher);
layout.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
layout.removeView(textField);
}
static public CrossAppTextField getTextField(final int key) {
CrossAppTextField var = dict.get(key);
if (var != null) return var;
return null;
}
static public void createTextField(final int key) {
CrossAppTextField text = new CrossAppTextField();
dict.put(key, text);
text.init(key);
}
static public void removeTextField(final int key) {
final CrossAppTextField var = dict.get(key);
dict.remove(key);
if (var != null) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
var.removeThis();
}
});
}
}
public void initWithTextField(int key) {
if (textField != null) {
layout.removeView(textField);
textField = null;
}
textField = new EditText(context);
textField.setMaxLines(1);
textField.setSingleLine(true);
textField.setGravity(gravity);
textField.setBackgroundColor(0);
textField.setFocusable(true);
textField.setDrawingCacheEnabled(true);
textField.setTextSize(fontSize);
textField.setInputType(inputType);
textField.setHint(placeHolder);
textField.setHintTextColor(placeHolderColor);
textField.setText(textFieldText);
textField.setSelection(textField.getText().length());
textField.setTextColor(textFieldTextColor);
textField.setImeOptions(keyBoardReturnType);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.leftMargin = -10000;
params.topMargin = 0;
params.width = contentSizeW;
params.height = contentSizeH;
layout.addView(textField, params);
textField.setPadding(leftMargin, 0, rightMargin, 0);
if (secureTextEntry == true) {
setSecureTextEntry(1);
}
if (showClearButton == true) {
showClearButton();
}
textWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
if (isSetText) {
return;
}
String string = arg0.toString();
String changedText = "";
if (arg3 > 0) {
changedText = string.substring(arg1, arg1 + arg3);
} else {
changedText = "";
}
if (!textChange(mykey, beforeTextString, changedText, arg1, arg2)) {
if (isSetText == false) {
isSetText = true;
textField.setText(beforeTextString);
textField.setSelection(selection);
isSetText = false;
}
} else {
if (isSetText == false) {
isSetText = true;
// textField.setText(string);
// textField.setSelection(selection - arg2 + arg3);
}
final ByteBuffer textBuffer = ByteBuffer.wrap(textField.getText().toString().getBytes());
context.runOnGLThread(new Runnable() {
@Override
public void run() {
text(mykey, textBuffer.array(), textBuffer.array().length);
didTextChanged(mykey);
}
});
isSetText = false;
}
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
if (isSetText) {
return;
}
// TODO Auto-generated method stub
beforeTextString = arg0.toString();
selection = textField.getSelectionStart();
}
@Override
public void afterTextChanged(Editable arg0) {
// textField.setFocusable(true);
// textField.setFocusableInTouchMode(true);
// textField.requestFocus();
// textField.setSelection(textField.getText().length());
if (isSetText) {
return;
}
// TODO Auto-generated method stub
}
};
textField.addTextChangedListener(textWatcher);
onEditorActionListener = new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
context.runOnGLThread(new Runnable() {
@Override
public void run() {
keyBoardReturnCallBack(mykey);
}
});
return true;
}
};
textField.setOnEditorActionListener(onEditorActionListener);
getKeyBoardHeight();
}
public void resume() {
TimerTask task = new TimerTask() {
public void run() {
context.runOnGLThread(new Runnable() {
@Override
public void run() {
resignFirstResponder(mykey);
}
});
}
};
Timer timer = new Timer();
timer.schedule(task, (long) 100);
}
}
| 9miao/CrossApp | CrossApp/proj.android/src/org/CrossApp/lib/CrossAppTextField.java | 5,759 | //textField Algin | line_comment | nl |
package org.CrossApp.lib;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView.OnEditorActionListener;
@SuppressLint("UseSparseArrays")
public class CrossAppTextField {
private EditText textField = null;
private static FrameLayout layout = null;
private static CrossAppActivity context = null;
private static Handler handler = null;
private static HashMap<Integer, CrossAppTextField> dict = null;
private int mykey = -1;
private ByteBuffer imageData = null;
private Bitmap bmp = null;
private Button clearButton = null;
private int keyboardheight = 0;
private int keyboardheightTemp = 0;
private int leftMargin = 10;
private int rightMargin = 10;
private int inputType = InputType.TYPE_CLASS_TEXT;
private int fontSize = 20;
private String placeHolder = "";
private int placeHolderColor = Color.GRAY;
private String textFieldText = "";
private int textFieldTextColor = Color.BLACK;
private int contentSizeW = 800;
private int contentSizeH = 200;
private boolean secureTextEntry = false;
private boolean showClearButton = false;
private int keyBoardReturnType = EditorInfo.IME_ACTION_DONE;
private int gravity = (Gravity.LEFT | Gravity.CENTER_VERTICAL);
private TextWatcher textWatcher = null;
private OnEditorActionListener onEditorActionListener = null;
private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = null;
private boolean isSetText = false;
private String beforeTextString = "";
private int selection = 0;
private boolean isFocus = false;
private boolean isFocusAction = false;
public static void initWithHandler() {
if (dict == null) {
dict = new HashMap<Integer, CrossAppTextField>();
}
CrossAppTextField.reload();
}
public static void reload() {
handler = new Handler(Looper.myLooper());
context = (CrossAppActivity) CrossAppActivity.getContext();
layout = CrossAppActivity.getFrameLayout();
Set<Integer> keys = (Set<Integer>) dict.keySet();
Iterator<Integer> iterator = keys.iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
CrossAppTextField textField = dict.get(key);
textField.initWithTextField(key);
}
}
public static boolean isShowKeyboard() {
boolean showKeyboard = false;
Iterator<Entry<Integer, CrossAppTextField>> iter = dict.entrySet().iterator();
while (iter.hasNext()) {
HashMap.Entry entry = (HashMap.Entry) iter.next();
CrossAppTextField val = (CrossAppTextField) entry.getValue();
if (val.textField != null && val.textField.isFocused()) {
showKeyboard = true;
break;
}
}
return showKeyboard;
}
//keyBoard return call back
private static native void keyBoardReturnCallBack(int key);
private static native boolean textChange(int key, String before, String change, int arg0, int arg1);
private static native void didTextChanged(int key);
private static native void text(int key, byte[] text, int lenght);
public void init(int key) {
mykey = key;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
initWithTextField(mykey);
}
});
}
//keyboard height
private static native void keyBoardHeightReturn(int key, int height);
private static native void resignFirstResponder(int key);
public int getKeyBoardHeight() {
onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
Rect r = new Rect();
layout.getWindowVisibleDisplayFrame(r);
int screenHeight = layout.getRootView().getHeight();
keyboardheightTemp = screenHeight - r.bottom;
if (keyboardheightTemp != keyboardheight) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if (keyboardheightTemp < 1 && isFocus == true) {
//hide
isFocus = false;
context.runOnGLThread(new Runnable() {
@Override
public void run() {
resignFirstResponder(mykey);
}
});
}
if (isFocusAction) {
context.runOnGLThread(new Runnable() {
@Override
public void run() {
keyBoardHeightReturn(mykey, keyboardheightTemp);
}
});
isFocusAction = false;
}
}
});
}
keyboardheight = keyboardheightTemp;
}
};
layout.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
return keyboardheight;
}
public void setFontSize(final int size) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
fontSize = size;
textField.setTextSize(size);
}
});
}
//placeholder text
public void setTextFieldPlacHolder(final String text) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
placeHolder = text;
textField.setHint(text);
}
});
}
public void setTextFieldText(final String text) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
isSetText = true;
textFieldText = text;
textField.setText(text);
textField.setSelection(textField.getText().length());
isSetText = false;
}
});
}
//placeholder color
public void setTextFieldPlacHolderColor(final int color) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
placeHolderColor = color;
textField.setHintTextColor(color);
}
});
}
//textfield color
public void setTextFieldTextColor(final int color) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
textFieldTextColor = color;
textField.setTextColor(color);
}
});
}
//keyboard type
public void setKeyBoardType(final int type) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
switch (type) {
case 0:
//default
inputType = InputType.TYPE_CLASS_TEXT;
break;
case 1:
//NumbersAndPunctuation
inputType = InputType.TYPE_NUMBER_VARIATION_NORMAL;
break;
case 2:
//URL
inputType = InputType.TYPE_TEXT_VARIATION_URI;
break;
case 3:
//NumberPad
inputType = InputType.TYPE_CLASS_NUMBER;
break;
case 4:
//PhonePad
inputType = InputType.TYPE_CLASS_PHONE;
break;
case 5:
//NamePhonePad
inputType = InputType.TYPE_TEXT_VARIATION_PERSON_NAME;
break;
case 6:
//EmailAddress
inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
default:
break;
}
textField.setInputType(inputType);
}
});
}
//textF<SUF>
public void setTextFieldAlgin(final int var) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
switch (var) {
case 0:
//center
gravity = (Gravity.LEFT | Gravity.CENTER_VERTICAL);
break;
case 1:
//left
gravity = (Gravity.CENTER | Gravity.CENTER_VERTICAL);
break;
case 2:
//right
gravity = (Gravity.RIGHT | Gravity.CENTER_VERTICAL);
break;
default:
break;
}
textField.setGravity(gravity);
}
});
}
//text field return type
public void setKeyBoardReturnType(final int type) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
String string = type + "";
Log.d("android", string);
switch (type) {
case 0:
keyBoardReturnType = EditorInfo.IME_ACTION_DONE;
break;
case 1:
keyBoardReturnType = EditorInfo.IME_ACTION_GO;
break;
case 2:
keyBoardReturnType = EditorInfo.IME_ACTION_NEXT;
break;
case 3:
keyBoardReturnType = EditorInfo.IME_ACTION_SEARCH;
break;
case 4:
keyBoardReturnType = EditorInfo.IME_ACTION_SEND;
break;
default:
keyBoardReturnType = EditorInfo.IME_ACTION_DONE;
break;
}
textField.setImeOptions(keyBoardReturnType);
}
});
}
//margins right length
public void setMarginsDis(final int left, final int right, final int top, final int bottom) {
leftMargin = left;
rightMargin = right;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
textField.setPadding(left, 0, right, 0);
}
});
}
//margins left image
public void setMarginLeftImage(final String filePath) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
//margins right image
public void setMarginRightImage(final String filePath) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
//clearButton
public void showClearButton() {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
showClearButton = true;
clearButton = new Button(context);
clearButton.setBackgroundColor(0);
// clearButton.setHighlightColor(Color.YELLOW);
FrameLayout.LayoutParams btnParams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
btnParams.width = 20;
btnParams.height = 20;
btnParams.rightMargin = -1000;
btnParams.topMargin = -1000;
layout.addView(clearButton, btnParams);
clearButton.setVisibility(View.GONE);
clearButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textField.setText("");
textField.setSelection(textField.getText().length());
}
});
}
});
}
public void setTextFieldPoint(final int x, final int y) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) textField.getLayoutParams();
params.leftMargin = x;
params.topMargin = y;
textField.setLayoutParams(params);
textField.requestLayout();
if (clearButton != null) {
FrameLayout.LayoutParams btnParams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
btnParams.width = params.height;
btnParams.height = params.height;
btnParams.leftMargin = params.leftMargin + params.width - btnParams.width;
btnParams.topMargin = params.topMargin;
clearButton.setLayoutParams(btnParams);
clearButton.requestLayout();
}
}
});
}
public void setTextFieldSize(final int width, final int height) {
contentSizeW = width;
contentSizeH = height;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) textField.getLayoutParams();
params.width = contentSizeW;
params.height = contentSizeH;
textField.setLayoutParams(params);
textField.requestLayout();
TimerTask task = new TimerTask() {
public void run() {
getImage();
}
};
Timer timer = new Timer();
timer.schedule(task, (long) 100);
}
});
}
public void setSecureTextEntry(int var) {
if (var == 0) {
secureTextEntry = false;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
textField.setInputType(inputType);
}
});
} else {
secureTextEntry = true;
context.runOnUiThread(new Runnable() {
@Override
public void run() {
if (inputType == InputType.TYPE_CLASS_NUMBER) {
textField.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
} else {
textField.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
}
});
}
}
private static native void onByte(int key, byte[] buf, int wdith, int height);
public void getImage() {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
bmp = textField.getDrawingCache();
if (bmp != null && imageData == null) {
imageData = ByteBuffer.allocate(bmp.getRowBytes() * bmp.getHeight());
bmp.copyPixelsToBuffer(imageData);
context.runOnGLThread(new Runnable() {
@Override
public void run() {
onByte(mykey, imageData.array(), bmp.getWidth(), bmp.getHeight());
imageData = null;
}
});
}
}
});
}
private static native void hideImageView(int key);
public void becomeFirstResponder() {
CrossAppActivity.setSingleTextField(this);
context.runOnUiThread(new Runnable() {
@Override
public void run() {
isFocus = true;
isFocusAction = true;
//show
textField.requestFocus();
Editable etext = textField.getText();
textField.setSelection(etext.length());
TimerTask task = new TimerTask() {
public void run() {
if (CrossAppTextField.isShowKeyboard() || CrossAppTextView.isShowKeyboard()) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textField, 0);
}
}
};
Timer timer = new Timer();
timer.schedule(task, (long) 20);
if (clearButton != null) {
clearButton.setVisibility(View.VISIBLE);
textField.setPadding(leftMargin, 0, rightMargin, 0);
}
context.runOnGLThread(new Runnable() {
@Override
public void run() {
hideImageView(mykey);
}
});
}
});
}
private static native void showImageView(int key);
public void resignFirstResponder() {
CrossAppActivity.setSingleTextField(null);
context.runOnUiThread(new Runnable() {
@Override
public void run() {
isFocus = false;
isFocusAction = true;
//show
if (clearButton != null) {
clearButton.setVisibility(View.GONE);
textField.setPadding(leftMargin, 0, 10, 0);
}
textField.clearFocus();
TimerTask task = new TimerTask() {
public void run() {
if (!CrossAppTextField.isShowKeyboard() && !CrossAppTextView.isShowKeyboard()) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(textField.getWindowToken(), 0);
}
}
};
Timer timer = new Timer();
timer.schedule(task, (long) 20);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) textField.getLayoutParams();
params.leftMargin = -10000;
params.topMargin = 0;
textField.setLayoutParams(params);
bmp = textField.getDrawingCache();
if (bmp != null && imageData == null) {
imageData = ByteBuffer.allocate(bmp.getRowBytes() * bmp.getHeight());
bmp.copyPixelsToBuffer(imageData);
context.runOnGLThread(new Runnable() {
@Override
public void run() {
onByte(mykey, imageData.array(), bmp.getWidth(), bmp.getHeight());
showImageView(mykey);
imageData = null;
}
});
}
}
});
}
public void setMaxLength(final int var) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
textField.setFilters(new InputFilter[]{new InputFilter.LengthFilter(var)});
}
});
}
@TargetApi(16)
public void removeThis() {
textField.removeTextChangedListener(textWatcher);
layout.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
layout.removeView(textField);
}
static public CrossAppTextField getTextField(final int key) {
CrossAppTextField var = dict.get(key);
if (var != null) return var;
return null;
}
static public void createTextField(final int key) {
CrossAppTextField text = new CrossAppTextField();
dict.put(key, text);
text.init(key);
}
static public void removeTextField(final int key) {
final CrossAppTextField var = dict.get(key);
dict.remove(key);
if (var != null) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
var.removeThis();
}
});
}
}
public void initWithTextField(int key) {
if (textField != null) {
layout.removeView(textField);
textField = null;
}
textField = new EditText(context);
textField.setMaxLines(1);
textField.setSingleLine(true);
textField.setGravity(gravity);
textField.setBackgroundColor(0);
textField.setFocusable(true);
textField.setDrawingCacheEnabled(true);
textField.setTextSize(fontSize);
textField.setInputType(inputType);
textField.setHint(placeHolder);
textField.setHintTextColor(placeHolderColor);
textField.setText(textFieldText);
textField.setSelection(textField.getText().length());
textField.setTextColor(textFieldTextColor);
textField.setImeOptions(keyBoardReturnType);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.leftMargin = -10000;
params.topMargin = 0;
params.width = contentSizeW;
params.height = contentSizeH;
layout.addView(textField, params);
textField.setPadding(leftMargin, 0, rightMargin, 0);
if (secureTextEntry == true) {
setSecureTextEntry(1);
}
if (showClearButton == true) {
showClearButton();
}
textWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
if (isSetText) {
return;
}
String string = arg0.toString();
String changedText = "";
if (arg3 > 0) {
changedText = string.substring(arg1, arg1 + arg3);
} else {
changedText = "";
}
if (!textChange(mykey, beforeTextString, changedText, arg1, arg2)) {
if (isSetText == false) {
isSetText = true;
textField.setText(beforeTextString);
textField.setSelection(selection);
isSetText = false;
}
} else {
if (isSetText == false) {
isSetText = true;
// textField.setText(string);
// textField.setSelection(selection - arg2 + arg3);
}
final ByteBuffer textBuffer = ByteBuffer.wrap(textField.getText().toString().getBytes());
context.runOnGLThread(new Runnable() {
@Override
public void run() {
text(mykey, textBuffer.array(), textBuffer.array().length);
didTextChanged(mykey);
}
});
isSetText = false;
}
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
if (isSetText) {
return;
}
// TODO Auto-generated method stub
beforeTextString = arg0.toString();
selection = textField.getSelectionStart();
}
@Override
public void afterTextChanged(Editable arg0) {
// textField.setFocusable(true);
// textField.setFocusableInTouchMode(true);
// textField.requestFocus();
// textField.setSelection(textField.getText().length());
if (isSetText) {
return;
}
// TODO Auto-generated method stub
}
};
textField.addTextChangedListener(textWatcher);
onEditorActionListener = new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
context.runOnGLThread(new Runnable() {
@Override
public void run() {
keyBoardReturnCallBack(mykey);
}
});
return true;
}
};
textField.setOnEditorActionListener(onEditorActionListener);
getKeyBoardHeight();
}
public void resume() {
TimerTask task = new TimerTask() {
public void run() {
context.runOnGLThread(new Runnable() {
@Override
public void run() {
resignFirstResponder(mykey);
}
});
}
};
Timer timer = new Timer();
timer.schedule(task, (long) 100);
}
}
|
53166_0 | package com.amaze.quit.app;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
public class Progress extends Fragment {
static int position;
private UserVisibilityEvent uservisibilityevent;
private UpdateStats updatestats = new UpdateStats(getActivity());
String message;
public static final Progress newInstance(int i) {
Progress f = new Progress();
Bundle bdl = new Bundle(1);
f.setArguments(bdl);
position = i;
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_progress, container, false);
return v;
}
/*update als je op scherm komt*/
@Override
public void onResume() {
super.onResume();
updateVooruitgang();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//implements the main method what every fragment should do when it's visible
uservisibilityevent.viewIsVisible(getActivity(), position, "red", "title_activity_progress");
updateVooruitgang();
}
}
/* update van progress als het scherm gemaakt wordt */
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
updateVooruitgang();
}
/* update functie */
private void updateVooruitgang() {
TextView dayProgress;
TextView moneyInTheBank;
TextView extraDagen;
TextView level;
extraDagen = (TextView) getActivity().findViewById(R.id.tvExtraDagen);
dayProgress = (TextView) getActivity().findViewById(R.id.tvDagenZonderRoken);
moneyInTheBank = (TextView) getActivity().findViewById(R.id.tvBespaardeGeld);
TextView nietGerookt = (TextView) getActivity().findViewById(R.id.tvNietGerookteSigaretten);
// level = (TextView) getActivity().findViewById(R.id.tvLevel);
TextView levelDesc = (TextView) getActivity().findViewById(R.id.tvLevel);
long days = updatestats.getDaysQuit();
//catches the nullpointerexception
try {
dayProgress.setText(days + " Dagen");
float bespaardeMoneys = updatestats.getSavedMoney();
String bespaardeMoneysString = String.format("%.2f",bespaardeMoneys);
moneyInTheBank.setText("€" + bespaardeMoneysString); // bespaarde geld.
DatabaseHandler db = new DatabaseHandler(getActivity());
float extraDagenTeLeven = updatestats.getExtraDagenTeLeven();
extraDagen.setText((int) extraDagenTeLeven + " extra dagen te leven");
int userLevel = updatestats.getUserLevel();
//level.setText("Level " + userLevel);
String Titel = db.getLevel(userLevel).getTitel();
levelDesc.setText(Titel);
int nietGerooktSig = (int) days * db.getUser(1).getPerDag();
nietGerookt.setText("" + nietGerooktSig);
socialMedia(days, bespaardeMoneysString,nietGerooktSig);
} catch (NullPointerException e) {
}
}
private void socialMedia(long days, String bespaardeMoney, int nietGerooktSig){
message = "Ik heb al " + days + " dagen niet gerookt. Dit zijn " + nietGerooktSig + " niet gerookte sigaretten en heeft me €" + bespaardeMoney + " bespaard! &hashtags=12Quit";
ImageButton tweet = (ImageButton) getActivity().findViewById(R.id.twitter_share);
tweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tweetUrl = "https://twitter.com/intent/tweet?text=" + message;
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
}
}
| A-Maze/Quit | app/src/main/java/com/amaze/quit/app/Progress.java | 1,068 | /*update als je op scherm komt*/ | block_comment | nl | package com.amaze.quit.app;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
public class Progress extends Fragment {
static int position;
private UserVisibilityEvent uservisibilityevent;
private UpdateStats updatestats = new UpdateStats(getActivity());
String message;
public static final Progress newInstance(int i) {
Progress f = new Progress();
Bundle bdl = new Bundle(1);
f.setArguments(bdl);
position = i;
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_progress, container, false);
return v;
}
/*update<SUF>*/
@Override
public void onResume() {
super.onResume();
updateVooruitgang();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//implements the main method what every fragment should do when it's visible
uservisibilityevent.viewIsVisible(getActivity(), position, "red", "title_activity_progress");
updateVooruitgang();
}
}
/* update van progress als het scherm gemaakt wordt */
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
updateVooruitgang();
}
/* update functie */
private void updateVooruitgang() {
TextView dayProgress;
TextView moneyInTheBank;
TextView extraDagen;
TextView level;
extraDagen = (TextView) getActivity().findViewById(R.id.tvExtraDagen);
dayProgress = (TextView) getActivity().findViewById(R.id.tvDagenZonderRoken);
moneyInTheBank = (TextView) getActivity().findViewById(R.id.tvBespaardeGeld);
TextView nietGerookt = (TextView) getActivity().findViewById(R.id.tvNietGerookteSigaretten);
// level = (TextView) getActivity().findViewById(R.id.tvLevel);
TextView levelDesc = (TextView) getActivity().findViewById(R.id.tvLevel);
long days = updatestats.getDaysQuit();
//catches the nullpointerexception
try {
dayProgress.setText(days + " Dagen");
float bespaardeMoneys = updatestats.getSavedMoney();
String bespaardeMoneysString = String.format("%.2f",bespaardeMoneys);
moneyInTheBank.setText("€" + bespaardeMoneysString); // bespaarde geld.
DatabaseHandler db = new DatabaseHandler(getActivity());
float extraDagenTeLeven = updatestats.getExtraDagenTeLeven();
extraDagen.setText((int) extraDagenTeLeven + " extra dagen te leven");
int userLevel = updatestats.getUserLevel();
//level.setText("Level " + userLevel);
String Titel = db.getLevel(userLevel).getTitel();
levelDesc.setText(Titel);
int nietGerooktSig = (int) days * db.getUser(1).getPerDag();
nietGerookt.setText("" + nietGerooktSig);
socialMedia(days, bespaardeMoneysString,nietGerooktSig);
} catch (NullPointerException e) {
}
}
private void socialMedia(long days, String bespaardeMoney, int nietGerooktSig){
message = "Ik heb al " + days + " dagen niet gerookt. Dit zijn " + nietGerooktSig + " niet gerookte sigaretten en heeft me €" + bespaardeMoney + " bespaard! &hashtags=12Quit";
ImageButton tweet = (ImageButton) getActivity().findViewById(R.id.twitter_share);
tweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tweetUrl = "https://twitter.com/intent/tweet?text=" + message;
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
});
}
}
|
40737_1 | package fr.loria.synalp.jtrans.markup.out;
import fr.loria.synalp.jtrans.project.Token;
import fr.loria.synalp.jtrans.project.Phrase;
import fr.loria.synalp.jtrans.project.Project;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import static fr.loria.synalp.jtrans.utils.FileUtils.getUTF8Writer;
import static fr.loria.synalp.jtrans.markup.out.TextGridSaverHelper.*;
/**
* To interface with: http://sldr.org/voir_depot.php?id=526
*/
public class TextGridAnonSaver implements MarkupSaver {
public static void savePraatAnonTier(Project p, File f) throws IOException {
final int frameCount = (int) p.audioSourceTotalFrames;
StringBuilder anonSB = new StringBuilder();
int anonCount = 0;
for (int i = 0; i < p.speakerCount(); i++) {
Iterator<Phrase> itr = p.phraseIterator(i);
while (itr.hasNext()) {
Phrase phrase = itr.next();
for (Token token: phrase) {
if (token.isAligned() && token.shouldBeAnonymized()) {
praatInterval(
anonSB,
anonCount + 1,
token.getSegment().getStartFrame(),
token.getSegment().getEndFrame(),
"buzz");
anonCount++;
}
}
}
}
Writer w = getUTF8Writer(f);
praatFileHeader(w, frameCount, 1);
praatTierHeader(w, 1, "ANON", anonCount, frameCount);
w.write(anonSB.toString());
w.close();
}
public void save(Project project, File file) throws IOException {
savePraatAnonTier(project, file);
}
public String getFormat() {
return "Praat TextGrid anonymization tier for " +
"http://sldr.org/voir_depot.php?id=526";
}
public String getExt() {
return ".anon.textgrid";
}
}
| AAmoukrane/jtrans | src/fr/loria/synalp/jtrans/markup/out/TextGridAnonSaver.java | 545 | //sldr.org/voir_depot.php?id=526"; | line_comment | nl | package fr.loria.synalp.jtrans.markup.out;
import fr.loria.synalp.jtrans.project.Token;
import fr.loria.synalp.jtrans.project.Phrase;
import fr.loria.synalp.jtrans.project.Project;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import static fr.loria.synalp.jtrans.utils.FileUtils.getUTF8Writer;
import static fr.loria.synalp.jtrans.markup.out.TextGridSaverHelper.*;
/**
* To interface with: http://sldr.org/voir_depot.php?id=526
*/
public class TextGridAnonSaver implements MarkupSaver {
public static void savePraatAnonTier(Project p, File f) throws IOException {
final int frameCount = (int) p.audioSourceTotalFrames;
StringBuilder anonSB = new StringBuilder();
int anonCount = 0;
for (int i = 0; i < p.speakerCount(); i++) {
Iterator<Phrase> itr = p.phraseIterator(i);
while (itr.hasNext()) {
Phrase phrase = itr.next();
for (Token token: phrase) {
if (token.isAligned() && token.shouldBeAnonymized()) {
praatInterval(
anonSB,
anonCount + 1,
token.getSegment().getStartFrame(),
token.getSegment().getEndFrame(),
"buzz");
anonCount++;
}
}
}
}
Writer w = getUTF8Writer(f);
praatFileHeader(w, frameCount, 1);
praatTierHeader(w, 1, "ANON", anonCount, frameCount);
w.write(anonSB.toString());
w.close();
}
public void save(Project project, File file) throws IOException {
savePraatAnonTier(project, file);
}
public String getFormat() {
return "Praat TextGrid anonymization tier for " +
"http://sldr.<SUF>
}
public String getExt() {
return ".anon.textgrid";
}
}
|
10057_13 | package nl.ou.fresnelforms.view;
import java.awt.Cursor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import javax.swing.SwingUtilities;
/**
* Mouse listener for all actions performed on lens boxes and property labels.
*/
public class LensDiagramMouseAdapter extends MouseAdapter {
private LensDiagram diagram;
private int x = 0;
private int y = 0;
private LensDiagramComponent selected = null;
/**
* Constructor.
* @param diagram lens diagram to listen to
*/
public LensDiagramMouseAdapter(LensDiagram diagram) {
this.diagram = diagram;
}
/**
* Checks for mouse overs on lens boxes and property labels and mouse exits from menus.
* @param e the mouseevent
*/
public void mouseMoved(MouseEvent e) {
double x = e.getX();
double y = e.getY();
Point2D p = new Point2D.Double(x, y);
for (LensBox lb: diagram.getLensBoxes()) {
if (!lb.isMouseOver() && lb.contains(p)) {
lb.setMouseOver(true);
doRepaint();
} else if (lb.isMouseOver() && !lb.contains(p)){
lb.setMouseOver(false);
doRepaint();
}
}
}
/**
* Checks for mouse clicks on menu options, lens boxes and property labels.
* @param e the mousevent
*/
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
Point2D p = new Point2D.Double(x, y);
for (LensBox lb: diagram.getLensBoxes()) {
if (lb.contains(p)) {
//The click is on the lensbox
//Check for click on a property label
for (PropertyLabel pl: lb.getPropertyLabels()) {
if (pl.contains(p)) {
if (SwingUtilities.isLeftMouseButton(e)) {
pl.getPropertyBinding().setShown(!pl.getPropertyBinding().isShown());
doRepaint();
return;
} else if (SwingUtilities.isRightMouseButton(e)) {
PropertyLabelRightClickMenu menu = new PropertyLabelRightClickMenu(pl);
menu.show(e.getComponent(), x, y);
doRepaint();
return;
}
}
}
//The mouseclick is on the lens and not on a property label
if (SwingUtilities.isLeftMouseButton(e)) {
//With the left mouse button the lensbox is selected or deselected
lb.setSelected(! lb.isSelected());
doRepaint();
return;
} else if (SwingUtilities.isRightMouseButton(e)) {
//With the right mouse button the popup menus for the lensbox is activated
LensBoxRightClickMenu menu = new LensBoxRightClickMenu(lb);
menu.show(e.getComponent(), x, y);
doRepaint();
return;
}
}
}
//No lensbox clicked so it must be the diagram.
if (SwingUtilities.isRightMouseButton(e)) {
//Activate the right mousebutton popup menu for the diagram
LensDiagramRightClickMenu menu = new LensDiagramRightClickMenu(diagram);
menu.show(e.getComponent(), x, y);
doRepaint();
}
}
/**
* The mouse pressed event handler.
* @param e the mouse event
*/
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
/**
* Checks for dragging lens boxes and property labels.
* @param e the mouse event
*/
public void mouseDragged(MouseEvent e) {
int dx = e.getX() - x;
int dy = e.getY() - y;
if (selected == null) {
//selecteer een lensbox of property label
for (LensBox lb: diagram.getLensBoxes()) {
if (lb.contains(x, y)) {
//in ieder geval lensbox geselecteerd, maar misschien ook wel property label
selected = lb;
lb.setZIndex(diagram.getMaxZIndex()+1);
for (PropertyLabel pl: lb.getPropertyLabels()) {
if (pl.contains(x, y)) {
selected = pl;
}
}
}
}
}
if (selected != null) {
double newx = selected.getX() + dx;
double newy = selected.getY() + dy;
selected.setPosition(new Point2D.Double(newx, newy));
doRepaint();
}
x = e.getX();
y = e.getY();
}
/**
* Checks for dragging lens boxes and property labels.
* @param e the mouse event
*/
public void mouseReleased(MouseEvent e) {
if (selected instanceof PropertyLabel) {
PropertyLabel pl = (PropertyLabel) selected;
pl.changeIndex();
doRepaint();
}
else if (selected instanceof LensBox){
LensBox lb = (LensBox) selected;
diagram.arrangeOverlap(lb);
doRepaint();
}
selected = null;
doRepaint();
}
/**
* repaint the diagram.
*/
private void doRepaint() {
try {
setBusyCursor();
diagram.getParent().repaint();
diagram.draw();
} finally {
setDefaultCursor();
}
}
/**
* this method sets a busy cursor
*/
private void setBusyCursor(){
diagram.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
/**
* this method sets the default cursor
*/
private void setDefaultCursor(){
diagram.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
| ABI-Team-30/Fresnel-Forms | src/main/java/nl/ou/fresnelforms/view/LensDiagramMouseAdapter.java | 1,612 | //selecteer een lensbox of property label
| line_comment | nl | package nl.ou.fresnelforms.view;
import java.awt.Cursor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import javax.swing.SwingUtilities;
/**
* Mouse listener for all actions performed on lens boxes and property labels.
*/
public class LensDiagramMouseAdapter extends MouseAdapter {
private LensDiagram diagram;
private int x = 0;
private int y = 0;
private LensDiagramComponent selected = null;
/**
* Constructor.
* @param diagram lens diagram to listen to
*/
public LensDiagramMouseAdapter(LensDiagram diagram) {
this.diagram = diagram;
}
/**
* Checks for mouse overs on lens boxes and property labels and mouse exits from menus.
* @param e the mouseevent
*/
public void mouseMoved(MouseEvent e) {
double x = e.getX();
double y = e.getY();
Point2D p = new Point2D.Double(x, y);
for (LensBox lb: diagram.getLensBoxes()) {
if (!lb.isMouseOver() && lb.contains(p)) {
lb.setMouseOver(true);
doRepaint();
} else if (lb.isMouseOver() && !lb.contains(p)){
lb.setMouseOver(false);
doRepaint();
}
}
}
/**
* Checks for mouse clicks on menu options, lens boxes and property labels.
* @param e the mousevent
*/
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
Point2D p = new Point2D.Double(x, y);
for (LensBox lb: diagram.getLensBoxes()) {
if (lb.contains(p)) {
//The click is on the lensbox
//Check for click on a property label
for (PropertyLabel pl: lb.getPropertyLabels()) {
if (pl.contains(p)) {
if (SwingUtilities.isLeftMouseButton(e)) {
pl.getPropertyBinding().setShown(!pl.getPropertyBinding().isShown());
doRepaint();
return;
} else if (SwingUtilities.isRightMouseButton(e)) {
PropertyLabelRightClickMenu menu = new PropertyLabelRightClickMenu(pl);
menu.show(e.getComponent(), x, y);
doRepaint();
return;
}
}
}
//The mouseclick is on the lens and not on a property label
if (SwingUtilities.isLeftMouseButton(e)) {
//With the left mouse button the lensbox is selected or deselected
lb.setSelected(! lb.isSelected());
doRepaint();
return;
} else if (SwingUtilities.isRightMouseButton(e)) {
//With the right mouse button the popup menus for the lensbox is activated
LensBoxRightClickMenu menu = new LensBoxRightClickMenu(lb);
menu.show(e.getComponent(), x, y);
doRepaint();
return;
}
}
}
//No lensbox clicked so it must be the diagram.
if (SwingUtilities.isRightMouseButton(e)) {
//Activate the right mousebutton popup menu for the diagram
LensDiagramRightClickMenu menu = new LensDiagramRightClickMenu(diagram);
menu.show(e.getComponent(), x, y);
doRepaint();
}
}
/**
* The mouse pressed event handler.
* @param e the mouse event
*/
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
/**
* Checks for dragging lens boxes and property labels.
* @param e the mouse event
*/
public void mouseDragged(MouseEvent e) {
int dx = e.getX() - x;
int dy = e.getY() - y;
if (selected == null) {
//selec<SUF>
for (LensBox lb: diagram.getLensBoxes()) {
if (lb.contains(x, y)) {
//in ieder geval lensbox geselecteerd, maar misschien ook wel property label
selected = lb;
lb.setZIndex(diagram.getMaxZIndex()+1);
for (PropertyLabel pl: lb.getPropertyLabels()) {
if (pl.contains(x, y)) {
selected = pl;
}
}
}
}
}
if (selected != null) {
double newx = selected.getX() + dx;
double newy = selected.getY() + dy;
selected.setPosition(new Point2D.Double(newx, newy));
doRepaint();
}
x = e.getX();
y = e.getY();
}
/**
* Checks for dragging lens boxes and property labels.
* @param e the mouse event
*/
public void mouseReleased(MouseEvent e) {
if (selected instanceof PropertyLabel) {
PropertyLabel pl = (PropertyLabel) selected;
pl.changeIndex();
doRepaint();
}
else if (selected instanceof LensBox){
LensBox lb = (LensBox) selected;
diagram.arrangeOverlap(lb);
doRepaint();
}
selected = null;
doRepaint();
}
/**
* repaint the diagram.
*/
private void doRepaint() {
try {
setBusyCursor();
diagram.getParent().repaint();
diagram.draw();
} finally {
setDefaultCursor();
}
}
/**
* this method sets a busy cursor
*/
private void setBusyCursor(){
diagram.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
/**
* this method sets the default cursor
*/
private void setDefaultCursor(){
diagram.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
|
52261_80 | /*
* ALMA - Atacama Large Millimiter Array (c) European Southern Observatory, 2004
* Copyright by ESO (in the framework of the ALMA collaboration), All rights
* reserved
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
*
*/
package alma.acs.nc;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.omg.CORBA.Any;
import org.omg.CORBA.TCKind;
import org.omg.CORBA.TypeCode;
import org.omg.CORBA.TypeCodePackage.BadKind;
import org.omg.CORBA.portable.IDLEntity;
import alma.ACS.booleanSeqHelper;
import alma.ACS.doubleSeqHelper;
import alma.ACS.floatSeqHelper;
import alma.ACS.longSeqHelper;
import alma.ACS.stringSeqHelper;
import alma.ACS.uLongLongSeqHelper;
import alma.ACS.uLongSeqHelper;
import alma.ACSErrTypeCommon.wrappers.AcsJBadParameterEx;
import alma.ACSErrTypeCommon.wrappers.AcsJUnexpectedExceptionEx;
import alma.ACSErrTypeJavaNative.wrappers.AcsJJavaAnyEx;
import alma.acs.container.ContainerServicesBase;
import alma.acs.exceptions.AcsJException;
/**
* Intended to be used as an aide to developers working with CORBA anys. If
* there's some method you think should be added to this class to ease
* developers' lives, please send this suggestion to the [email protected]
* or [email protected] mailing lists.
*
* @author dfugate
* @version $Id$
*/
class AnyAide {
/** reference to the container services */
private final ContainerServicesBase m_containerServices;
/** our own logger */
private final Logger m_logger;
/**
* Standard constructor.
*
* @param cs
* Container services reference of the component.
*/
public AnyAide(ContainerServicesBase cs) {
// save a local reference
m_containerServices = cs;
// just copy the reference
m_logger = cs.getLogger();
}
/**
* Moved here from method arrayToCorbaAny (deleted in ACS 9.0).
*/
protected Any internalArrayToCorbaAny(Object objs) throws AcsJException {
// class object for the array
Class cl = objs.getClass();
if (!cl.isArray()) {
Throwable cause = new Throwable("Object of type " + cl.getName() + " is not an array.");
throw new AcsJJavaAnyEx(cause);
}
// class object for the array elements
Class objClass = cl.getComponentType();
int length = Array.getLength(objs);
// doubleSeq
if (objClass.equals(double.class)) {
double[] values = new double[length];
System.arraycopy(objs, 0, values, 0, length);
return doubleArrayToCorbaAny(values);
}
// longSeq
else if (objClass.equals(int.class)) {
int[] values = new int[length];
System.arraycopy(objs, 0, values, 0, length);
return intArrayToCorbaAny(values);
}
// stringSeq
else if (objClass.equals(String.class)) {
String[] values = new String[length];
System.arraycopy(objs, 0, values, 0, length);
return stringArrayToCorbaAny(values);
}
// floatSeq
else if (objClass.equals(float.class)) {
float[] values = new float[length];
System.arraycopy(objs, 0, values, 0, length);
return floatArrayToCorbaAny(values);
}
else {
// if we do not know what it is, there's not much we can
// do.
Throwable cause = new Throwable(cl.getName() + " not supported!");
throw new AcsJJavaAnyEx(cause);
}
}
public Any doubleArrayToCorbaAny(double[] doubles) {
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
doubleSeqHelper.insert(retVal, doubles);
return retVal;
}
public Any floatArrayToCorbaAny(float[] floats) {
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
floatSeqHelper.insert(retVal, floats);
return retVal;
}
public Any intArrayToCorbaAny(int[] ints) {
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
longSeqHelper.insert(retVal, ints);
return retVal;
}
public Any stringArrayToCorbaAny(String[] strings) {
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
stringSeqHelper.insert(retVal, strings);
return retVal;
}
/**
* Converts a generic Java object to a CORBA Any. May fail.
*
* @param obj
* Object to be converted to a CORBA any
* @return A CORBA any with obj's data embedded within it.
* @throws AcsJException
* Thrown if there's some problem converting the object to an
* any. TODO: make sure this works with enumerations.
*/
public Any objectToCorbaAny(Object obj) throws AcsJException {
if (obj != null && obj.getClass().isArray()) {
return internalArrayToCorbaAny(obj);
}
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
// null case
if (obj == null) {
retVal.insert_Object(null);
}
// check against string
else if (obj instanceof String) {
retVal.insert_string((String) obj);
}
// check against double
else if (obj instanceof Double) {
double value = ((Double) obj).doubleValue();
retVal.insert_double(value);
}
// check against long - CORBA long long and unsigned long long
else if (obj instanceof Long) {
long value = ((Long) obj).longValue();
retVal.insert_longlong(value);
}
// check against integer - CORBA long or unsigned long
else if (obj instanceof Integer) {
int value = ((Integer) obj).intValue();
retVal.insert_long(value);
}
// check against float
else if (obj instanceof Float) {
float value = ((Float) obj).floatValue();
retVal.insert_float(value);
}
else if (obj instanceof IDLEntity) {
// as a last ditch attempt, we assume the object
// is some sort of complex IDL struct/union/etc
// and that this method will work.
return complexObjectToCorbaAny((IDLEntity) obj);
}
else {
Throwable cause = new Throwable("Bad arg of type " + obj.getClass().getName());
throw new AcsJBadParameterEx(cause);
}
return retVal;
}
/**
* Converts a complex CORBA-based object to a CORBA any.
*
* @param obj
* A complex CORBA-based object such as a user-defined IDL struct.
* @return A CORBA any containing obj.
* @throws AcsJException
* if any problem occurs with the conversion.
*/
public Any complexObjectToCorbaAny(IDLEntity obj) throws AcsJException {
if (obj == null) {
Throwable cause = new Throwable("Method arg 'obj' was null");
throw new AcsJBadParameterEx(cause);
}
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
// ------
Class structHelperClass = null;
// first double-check that the Java Object they are attempting to
// actually looks like a CORBA type.
try {
// This is the CORBA helper class which is capable of inserting/extracting data from CORBA Anys.
structHelperClass = Class.forName(obj.getClass().getName() + "Helper");
}
catch (Exception e) {
// If what's above fails...then the developer has specified a native Java
// class which has nothing to do with CORBA.
String msg = "The non-CORBA class '" + obj.getClass().getName()
+ "' cannot be converted to a CORBA Any.";
Throwable cause = new Throwable(msg);
m_logger.warning(msg);
throw new alma.ACSErrTypeCommon.wrappers.AcsJTypeNotFoundEx(cause);
}
try {
// get at the static insert method defined for all IDL structures and sequences.
// TODO: Cache it in a struct - method map, perhaps using weak references.
Method insert = structHelperClass.getMethod("insert", new Class[] { Any.class, obj.getClass() });
// arguments to insert method are just the newly created Any and the
// IDL struct instance passed to this method.
Object[] args = { retVal, obj };
insert.invoke(null, args);
return retVal;
}
catch (NoSuchMethodException e) {
// we got a Helper class, but it seems to be not the CORBA-generated kind
Throwable cause = new Throwable("Class '" + structHelperClass.getName()
+ "' associated with the given object of type '" + obj.getClass().getName()
+ "' is incompatiable with CORBA: " + e.getMessage());
throw new AcsJBadParameterEx(cause);
}
catch (java.lang.reflect.InvocationTargetException e) {
Throwable realEx = e.getCause();
String reason = "Failed to insert the given CORBA object into a CORBA Any: the helper class insert method threw an exception.";
m_logger.log(Level.FINE, reason, realEx);
Throwable cause = new Throwable(reason + realEx.getMessage());
throw new alma.ACSErrTypeJavaNative.wrappers.AcsJJavaLangEx(cause); // todo: NC-specific exception type
}
catch (Throwable thr) {
String reason = "Failed to insert the given CORBA object into a CORBA Any.";
m_logger.log(Level.FINE, reason, thr);
Throwable cause = new Throwable(reason + thr.getMessage());
throw new AcsJUnexpectedExceptionEx(cause);
}
}
/**
* Method which attempts to (and under normal circumstances should succeed)
* convert a CORBA any object to the corresponding Java object. For simple
* CORBA types such as long, this method will extract the long and embed it
* within a java.lang.Long object. In the event of failure, a null object is
* returned.
* <p>
* Sequences / arrays are only supported for string, float, double, long and boolean
* when using the typedefs from acscommon.idl such as "typedef sequence <float> floatSeq"
*
* @param any
* A CORBA any containing some sort of CORBA object
* @return the CORBA any converted into the corresponding Java type, or <code>null</code> if it failed.
*/
public Object corbaAnyToObject(Any any) {
// @TODO check any==null
// initialize the return value
Object returnValue = null;
// get the CORBA typecode enum.
// we need this to deal with the simple types
org.omg.CORBA.TCKind anyKind = any.type().kind();
// within this switch block, returnValue is set
// to be some real (native) Java object rather
// than a CORBA any type. at this time, ACS only
// support "BACI Value types" defined within
// $ACSROOT/include/baciValue.h (the "Type" enum).
switch (anyKind.value()) {
case org.omg.CORBA.TCKind._tk_null:
// this case is quite simple. A null CORBA reference is null in Java as well
returnValue = null;
break;
case org.omg.CORBA.TCKind._tk_string:
// simple type in which we have an extract method
returnValue = any.extract_string();
break;
case org.omg.CORBA.TCKind._tk_double:
// simple type in which we have an extract method
returnValue = new Double(any.extract_double());
break;
case org.omg.CORBA.TCKind._tk_long:
// simple type in which we have an extract method
returnValue = new Integer(any.extract_long());
break;
case org.omg.CORBA.TCKind._tk_alias:
String id = null;
try {
id = any.type().id();
} catch (BadKind ex) {
// should never happen for a tk_alias
}
switch (id) {
case "IDL:alma/ACS/longSeq:1.0":
returnValue = longSeqHelper.extract(any);
break;
case "IDL:alma/ACS/uLongSeq:1.0":
returnValue = uLongSeqHelper.extract(any);
break;
case "IDL:alma/ACS/uLongLongSeq:1.0":
returnValue = uLongLongSeqHelper.extract(any);
break;
case "IDL:alma/ACS/floatSeq:1.0":
returnValue = floatSeqHelper.extract(any);
break;
case "IDL:alma/ACS/doubleSeq:1.0":
returnValue = doubleSeqHelper.extract(any);
break;
case "IDL:alma/ACS/stringSeq:1.0":
returnValue = stringSeqHelper.extract(any);
break;
case "IDL:alma/ACS/booleanSeq:1.0":
returnValue = booleanSeqHelper.extract(any);
break;
default:
// who knows if there could be "IDL:alma/ACS/patternSeq:1.0" etc
m_logger.severe("Got an unexpected tk_alias with id=" + id);
}
break;
case org.omg.CORBA.TCKind._tk_ulong:
// simple type in which we have an extract method
returnValue = new Integer(any.extract_ulong());
break;
case org.omg.CORBA.TCKind._tk_longlong:
// simple type in which we have an extract method
returnValue = new Long(any.extract_longlong());
break;
case org.omg.CORBA.TCKind._tk_ulonglong:
// simple type in which we have an extract method
returnValue = new Long(any.extract_ulonglong());
break;
case org.omg.CORBA.TCKind._tk_float:
// simple type in which we have an extract method
returnValue = new Float(any.extract_float());
break;
// not yet ported for jacorb 3.4, where any.type().toString() has changed. Let's see if we need it.
// case org.omg.CORBA.TCKind._tk_enum:
// // very special case. at the moment,
// // we just support enumerations defined within
// // the uppermost IDL module
// try {
// String localHelperName = anyType + "Helper";
// localHelperName = localHelperName.replaceAll("::", ".");
// Class localHelper = Class.forName(localHelperName);
//
// // Extract method of helper class
// // Need access to this to convert an Any to the Java language
// // type.
// Method extract = localHelper.getMethod("extract", new Class[] { Any.class });
// Object[] args = { any };
// returnValue = extract.invoke(null, args);
// } catch (Exception ex) {
// m_logger.log(Level.SEVERE, "Failed to extract enum!", ex);
// }
// break;
// pretty bad if we get this far!
default:
m_logger.severe("Could not extract an any of type " + any.type().toString());
break;
}
return returnValue;
}
/**
* Extracts from a Corba Any the embedded user-defined event data.
* The returned data can be either
* <ol>
* <li>a class implementing <code>IDLEntity</code> if an IDL-defined struct was sent, or
* <li>an array of IDL-defined structs
* </ol>
* Other non-IDL defined classes or primitive types are not allowed as event data
* (not totally sure but it seems like that, HSO 2006-12).
*
* @param any CORBA Any containing a complex, user-defined object within it
* @return the CORBA Any parameter converted to an object of the
* corresponding Java type, or <code>null</code> if the conversion failed.
*/
public Object complexAnyToObject(Any any)
{
// initialize the return value
Object retValue = null;
Class localHelper = null;
// Create the IDL struct helper class
// With Java Anys, we can extract the name of the underlying object
// instance and from that all that needs to be done is to concatenate "Helper"
// to get.
String qualHelperClassName = null;
try {
org.omg.CORBA.TCKind kind = any.type().kind();
if (kind.equals(org.omg.CORBA.TCKind.tk_sequence)) {
// the event data is a sequence instead of a single value or struct. Need to get the underlying type
org.omg.CORBA.TypeCode sequenceType = any.type().content_type();
// @TODO check if the following applies also for sequences of primitive types,
// or if there is a rule that we always must have structs as event data
// (which is implied by always calling complexAnyToObject in push_structured_event)
// Derive the Java package from the id.
// First assume that the type is not defined nested inside an interface
qualHelperClassName = corbaStructToJavaClass(sequenceType, false) + "SeqHelper";
try {
localHelper = Class.forName(qualHelperClassName);
} catch (ClassNotFoundException ex) {
// it could be that we are dealing with a sequence of nested structs
qualHelperClassName = corbaStructToJavaClass(sequenceType, true) + "SeqHelper";
localHelper = Class.forName(qualHelperClassName);
}
}
else {
// First assume that the type is not defined nested inside an interface
qualHelperClassName = corbaStructToJavaClass(any.type(), false) + "Helper";
try {
localHelper = Class.forName(qualHelperClassName);
} catch(ClassNotFoundException ex) {
// it could be that we are dealing with a nested struct
qualHelperClassName = corbaStructToJavaClass(any.type(), true) + "Helper";
localHelper = Class.forName(qualHelperClassName);
}
}
// Extract method of helper class
// Need access to this to convert an Any to the Java language type.
// TODO: Cache it in a struct - method map, perhaps using weak references.
Method extract = localHelper.getMethod("extract", new Class[] { Any.class });
Object[] args = { any };
retValue = extract.invoke(null, args);
}
catch (ClassNotFoundException e) {
// should never happen...
String msg = "Failed to extract the event struct data from a CORBA Any because the helper class '"
+ qualHelperClassName + "' does not exist.";
m_logger.log(Level.WARNING, msg, e);
}
catch (NoSuchMethodException e) {
// should never happen...
String msg = "Failed to process an any because the helper class '" + qualHelperClassName + "' does not provide the 'extract' method.";
m_logger.log(Level.WARNING, msg, e);
}
// catch (ClassCastException e) {
// // should never happen...
// String msg = "Failed to process an any because the contained data does not seem to come from an IDL struct.";
// m_logger.log(Level.WARNING, msg, e);
// }
catch (Throwable thr) { // IllegalAccessException, InvocationTargetException, TypeCodePackage.BadKind or any other throwable
// should never happen...
String msg = "Failed to process an any because of unexpected problem.";
m_logger.log(Level.WARNING, msg, thr);
}
return retValue;
}
/**
* Derives the qualified Java class name for an IDL-defined struct from the Corba ID of that struct.
* See also jacorb-specific method "TypeCode#idlTypeName"
*
* @param isNestedStruct if true, "Package" will be inserted according to
* <i>"IDL to Java LanguageMapping Specification" version 1.2: 1.17 Mapping for Certain Nested Types</i> apply.
*/
protected String corbaStructToJavaClass(TypeCode tc, boolean isNestedStruct)
throws IllegalArgumentException
{
String qualName = null;
if (tc.kind() == TCKind.tk_struct) {
String prefix = "IDL:";
String suffix = ":1.0";
try {
String id = tc.id();
if (!id.startsWith(prefix) || !id.endsWith(suffix)) {
throw new IllegalArgumentException("Struct ID is expected to start with 'IDL:' and end with ':1.0'");
}
String qualNameWithSlashes = id.substring(prefix.length(), id.length() - suffix.length());
qualName = qualNameWithSlashes.replace('/', '.');
} catch (BadKind ex) {
// should never happen since we call it only for tk_struct
throw new IllegalArgumentException(ex);
}
if (isNestedStruct) {
int lastDotIndex = qualName.lastIndexOf('.');
if (lastDotIndex > 0) {
String className = qualName.substring(lastDotIndex + 1);
String jPackage = qualName.substring(0, lastDotIndex);
jPackage += "Package."; // defined in IDL-Java mapping spec
qualName = jPackage + className;
}
}
return qualName;
}
else {
throw new IllegalArgumentException("Expected TypeCode for a struct, but got TypeCode #" + tc.kind().value());
}
}
}
| ACS-Community/ACS | LGPL/CommonSoftware/jcontnc/src/alma/acs/nc/AnyAide.java | 5,642 | // to get. | line_comment | nl | /*
* ALMA - Atacama Large Millimiter Array (c) European Southern Observatory, 2004
* Copyright by ESO (in the framework of the ALMA collaboration), All rights
* reserved
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library 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 this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
*
*/
package alma.acs.nc;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.omg.CORBA.Any;
import org.omg.CORBA.TCKind;
import org.omg.CORBA.TypeCode;
import org.omg.CORBA.TypeCodePackage.BadKind;
import org.omg.CORBA.portable.IDLEntity;
import alma.ACS.booleanSeqHelper;
import alma.ACS.doubleSeqHelper;
import alma.ACS.floatSeqHelper;
import alma.ACS.longSeqHelper;
import alma.ACS.stringSeqHelper;
import alma.ACS.uLongLongSeqHelper;
import alma.ACS.uLongSeqHelper;
import alma.ACSErrTypeCommon.wrappers.AcsJBadParameterEx;
import alma.ACSErrTypeCommon.wrappers.AcsJUnexpectedExceptionEx;
import alma.ACSErrTypeJavaNative.wrappers.AcsJJavaAnyEx;
import alma.acs.container.ContainerServicesBase;
import alma.acs.exceptions.AcsJException;
/**
* Intended to be used as an aide to developers working with CORBA anys. If
* there's some method you think should be added to this class to ease
* developers' lives, please send this suggestion to the [email protected]
* or [email protected] mailing lists.
*
* @author dfugate
* @version $Id$
*/
class AnyAide {
/** reference to the container services */
private final ContainerServicesBase m_containerServices;
/** our own logger */
private final Logger m_logger;
/**
* Standard constructor.
*
* @param cs
* Container services reference of the component.
*/
public AnyAide(ContainerServicesBase cs) {
// save a local reference
m_containerServices = cs;
// just copy the reference
m_logger = cs.getLogger();
}
/**
* Moved here from method arrayToCorbaAny (deleted in ACS 9.0).
*/
protected Any internalArrayToCorbaAny(Object objs) throws AcsJException {
// class object for the array
Class cl = objs.getClass();
if (!cl.isArray()) {
Throwable cause = new Throwable("Object of type " + cl.getName() + " is not an array.");
throw new AcsJJavaAnyEx(cause);
}
// class object for the array elements
Class objClass = cl.getComponentType();
int length = Array.getLength(objs);
// doubleSeq
if (objClass.equals(double.class)) {
double[] values = new double[length];
System.arraycopy(objs, 0, values, 0, length);
return doubleArrayToCorbaAny(values);
}
// longSeq
else if (objClass.equals(int.class)) {
int[] values = new int[length];
System.arraycopy(objs, 0, values, 0, length);
return intArrayToCorbaAny(values);
}
// stringSeq
else if (objClass.equals(String.class)) {
String[] values = new String[length];
System.arraycopy(objs, 0, values, 0, length);
return stringArrayToCorbaAny(values);
}
// floatSeq
else if (objClass.equals(float.class)) {
float[] values = new float[length];
System.arraycopy(objs, 0, values, 0, length);
return floatArrayToCorbaAny(values);
}
else {
// if we do not know what it is, there's not much we can
// do.
Throwable cause = new Throwable(cl.getName() + " not supported!");
throw new AcsJJavaAnyEx(cause);
}
}
public Any doubleArrayToCorbaAny(double[] doubles) {
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
doubleSeqHelper.insert(retVal, doubles);
return retVal;
}
public Any floatArrayToCorbaAny(float[] floats) {
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
floatSeqHelper.insert(retVal, floats);
return retVal;
}
public Any intArrayToCorbaAny(int[] ints) {
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
longSeqHelper.insert(retVal, ints);
return retVal;
}
public Any stringArrayToCorbaAny(String[] strings) {
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
stringSeqHelper.insert(retVal, strings);
return retVal;
}
/**
* Converts a generic Java object to a CORBA Any. May fail.
*
* @param obj
* Object to be converted to a CORBA any
* @return A CORBA any with obj's data embedded within it.
* @throws AcsJException
* Thrown if there's some problem converting the object to an
* any. TODO: make sure this works with enumerations.
*/
public Any objectToCorbaAny(Object obj) throws AcsJException {
if (obj != null && obj.getClass().isArray()) {
return internalArrayToCorbaAny(obj);
}
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
// null case
if (obj == null) {
retVal.insert_Object(null);
}
// check against string
else if (obj instanceof String) {
retVal.insert_string((String) obj);
}
// check against double
else if (obj instanceof Double) {
double value = ((Double) obj).doubleValue();
retVal.insert_double(value);
}
// check against long - CORBA long long and unsigned long long
else if (obj instanceof Long) {
long value = ((Long) obj).longValue();
retVal.insert_longlong(value);
}
// check against integer - CORBA long or unsigned long
else if (obj instanceof Integer) {
int value = ((Integer) obj).intValue();
retVal.insert_long(value);
}
// check against float
else if (obj instanceof Float) {
float value = ((Float) obj).floatValue();
retVal.insert_float(value);
}
else if (obj instanceof IDLEntity) {
// as a last ditch attempt, we assume the object
// is some sort of complex IDL struct/union/etc
// and that this method will work.
return complexObjectToCorbaAny((IDLEntity) obj);
}
else {
Throwable cause = new Throwable("Bad arg of type " + obj.getClass().getName());
throw new AcsJBadParameterEx(cause);
}
return retVal;
}
/**
* Converts a complex CORBA-based object to a CORBA any.
*
* @param obj
* A complex CORBA-based object such as a user-defined IDL struct.
* @return A CORBA any containing obj.
* @throws AcsJException
* if any problem occurs with the conversion.
*/
public Any complexObjectToCorbaAny(IDLEntity obj) throws AcsJException {
if (obj == null) {
Throwable cause = new Throwable("Method arg 'obj' was null");
throw new AcsJBadParameterEx(cause);
}
Any retVal = m_containerServices.getAdvancedContainerServices().getAny();
// ------
Class structHelperClass = null;
// first double-check that the Java Object they are attempting to
// actually looks like a CORBA type.
try {
// This is the CORBA helper class which is capable of inserting/extracting data from CORBA Anys.
structHelperClass = Class.forName(obj.getClass().getName() + "Helper");
}
catch (Exception e) {
// If what's above fails...then the developer has specified a native Java
// class which has nothing to do with CORBA.
String msg = "The non-CORBA class '" + obj.getClass().getName()
+ "' cannot be converted to a CORBA Any.";
Throwable cause = new Throwable(msg);
m_logger.warning(msg);
throw new alma.ACSErrTypeCommon.wrappers.AcsJTypeNotFoundEx(cause);
}
try {
// get at the static insert method defined for all IDL structures and sequences.
// TODO: Cache it in a struct - method map, perhaps using weak references.
Method insert = structHelperClass.getMethod("insert", new Class[] { Any.class, obj.getClass() });
// arguments to insert method are just the newly created Any and the
// IDL struct instance passed to this method.
Object[] args = { retVal, obj };
insert.invoke(null, args);
return retVal;
}
catch (NoSuchMethodException e) {
// we got a Helper class, but it seems to be not the CORBA-generated kind
Throwable cause = new Throwable("Class '" + structHelperClass.getName()
+ "' associated with the given object of type '" + obj.getClass().getName()
+ "' is incompatiable with CORBA: " + e.getMessage());
throw new AcsJBadParameterEx(cause);
}
catch (java.lang.reflect.InvocationTargetException e) {
Throwable realEx = e.getCause();
String reason = "Failed to insert the given CORBA object into a CORBA Any: the helper class insert method threw an exception.";
m_logger.log(Level.FINE, reason, realEx);
Throwable cause = new Throwable(reason + realEx.getMessage());
throw new alma.ACSErrTypeJavaNative.wrappers.AcsJJavaLangEx(cause); // todo: NC-specific exception type
}
catch (Throwable thr) {
String reason = "Failed to insert the given CORBA object into a CORBA Any.";
m_logger.log(Level.FINE, reason, thr);
Throwable cause = new Throwable(reason + thr.getMessage());
throw new AcsJUnexpectedExceptionEx(cause);
}
}
/**
* Method which attempts to (and under normal circumstances should succeed)
* convert a CORBA any object to the corresponding Java object. For simple
* CORBA types such as long, this method will extract the long and embed it
* within a java.lang.Long object. In the event of failure, a null object is
* returned.
* <p>
* Sequences / arrays are only supported for string, float, double, long and boolean
* when using the typedefs from acscommon.idl such as "typedef sequence <float> floatSeq"
*
* @param any
* A CORBA any containing some sort of CORBA object
* @return the CORBA any converted into the corresponding Java type, or <code>null</code> if it failed.
*/
public Object corbaAnyToObject(Any any) {
// @TODO check any==null
// initialize the return value
Object returnValue = null;
// get the CORBA typecode enum.
// we need this to deal with the simple types
org.omg.CORBA.TCKind anyKind = any.type().kind();
// within this switch block, returnValue is set
// to be some real (native) Java object rather
// than a CORBA any type. at this time, ACS only
// support "BACI Value types" defined within
// $ACSROOT/include/baciValue.h (the "Type" enum).
switch (anyKind.value()) {
case org.omg.CORBA.TCKind._tk_null:
// this case is quite simple. A null CORBA reference is null in Java as well
returnValue = null;
break;
case org.omg.CORBA.TCKind._tk_string:
// simple type in which we have an extract method
returnValue = any.extract_string();
break;
case org.omg.CORBA.TCKind._tk_double:
// simple type in which we have an extract method
returnValue = new Double(any.extract_double());
break;
case org.omg.CORBA.TCKind._tk_long:
// simple type in which we have an extract method
returnValue = new Integer(any.extract_long());
break;
case org.omg.CORBA.TCKind._tk_alias:
String id = null;
try {
id = any.type().id();
} catch (BadKind ex) {
// should never happen for a tk_alias
}
switch (id) {
case "IDL:alma/ACS/longSeq:1.0":
returnValue = longSeqHelper.extract(any);
break;
case "IDL:alma/ACS/uLongSeq:1.0":
returnValue = uLongSeqHelper.extract(any);
break;
case "IDL:alma/ACS/uLongLongSeq:1.0":
returnValue = uLongLongSeqHelper.extract(any);
break;
case "IDL:alma/ACS/floatSeq:1.0":
returnValue = floatSeqHelper.extract(any);
break;
case "IDL:alma/ACS/doubleSeq:1.0":
returnValue = doubleSeqHelper.extract(any);
break;
case "IDL:alma/ACS/stringSeq:1.0":
returnValue = stringSeqHelper.extract(any);
break;
case "IDL:alma/ACS/booleanSeq:1.0":
returnValue = booleanSeqHelper.extract(any);
break;
default:
// who knows if there could be "IDL:alma/ACS/patternSeq:1.0" etc
m_logger.severe("Got an unexpected tk_alias with id=" + id);
}
break;
case org.omg.CORBA.TCKind._tk_ulong:
// simple type in which we have an extract method
returnValue = new Integer(any.extract_ulong());
break;
case org.omg.CORBA.TCKind._tk_longlong:
// simple type in which we have an extract method
returnValue = new Long(any.extract_longlong());
break;
case org.omg.CORBA.TCKind._tk_ulonglong:
// simple type in which we have an extract method
returnValue = new Long(any.extract_ulonglong());
break;
case org.omg.CORBA.TCKind._tk_float:
// simple type in which we have an extract method
returnValue = new Float(any.extract_float());
break;
// not yet ported for jacorb 3.4, where any.type().toString() has changed. Let's see if we need it.
// case org.omg.CORBA.TCKind._tk_enum:
// // very special case. at the moment,
// // we just support enumerations defined within
// // the uppermost IDL module
// try {
// String localHelperName = anyType + "Helper";
// localHelperName = localHelperName.replaceAll("::", ".");
// Class localHelper = Class.forName(localHelperName);
//
// // Extract method of helper class
// // Need access to this to convert an Any to the Java language
// // type.
// Method extract = localHelper.getMethod("extract", new Class[] { Any.class });
// Object[] args = { any };
// returnValue = extract.invoke(null, args);
// } catch (Exception ex) {
// m_logger.log(Level.SEVERE, "Failed to extract enum!", ex);
// }
// break;
// pretty bad if we get this far!
default:
m_logger.severe("Could not extract an any of type " + any.type().toString());
break;
}
return returnValue;
}
/**
* Extracts from a Corba Any the embedded user-defined event data.
* The returned data can be either
* <ol>
* <li>a class implementing <code>IDLEntity</code> if an IDL-defined struct was sent, or
* <li>an array of IDL-defined structs
* </ol>
* Other non-IDL defined classes or primitive types are not allowed as event data
* (not totally sure but it seems like that, HSO 2006-12).
*
* @param any CORBA Any containing a complex, user-defined object within it
* @return the CORBA Any parameter converted to an object of the
* corresponding Java type, or <code>null</code> if the conversion failed.
*/
public Object complexAnyToObject(Any any)
{
// initialize the return value
Object retValue = null;
Class localHelper = null;
// Create the IDL struct helper class
// With Java Anys, we can extract the name of the underlying object
// instance and from that all that needs to be done is to concatenate "Helper"
// to ge<SUF>
String qualHelperClassName = null;
try {
org.omg.CORBA.TCKind kind = any.type().kind();
if (kind.equals(org.omg.CORBA.TCKind.tk_sequence)) {
// the event data is a sequence instead of a single value or struct. Need to get the underlying type
org.omg.CORBA.TypeCode sequenceType = any.type().content_type();
// @TODO check if the following applies also for sequences of primitive types,
// or if there is a rule that we always must have structs as event data
// (which is implied by always calling complexAnyToObject in push_structured_event)
// Derive the Java package from the id.
// First assume that the type is not defined nested inside an interface
qualHelperClassName = corbaStructToJavaClass(sequenceType, false) + "SeqHelper";
try {
localHelper = Class.forName(qualHelperClassName);
} catch (ClassNotFoundException ex) {
// it could be that we are dealing with a sequence of nested structs
qualHelperClassName = corbaStructToJavaClass(sequenceType, true) + "SeqHelper";
localHelper = Class.forName(qualHelperClassName);
}
}
else {
// First assume that the type is not defined nested inside an interface
qualHelperClassName = corbaStructToJavaClass(any.type(), false) + "Helper";
try {
localHelper = Class.forName(qualHelperClassName);
} catch(ClassNotFoundException ex) {
// it could be that we are dealing with a nested struct
qualHelperClassName = corbaStructToJavaClass(any.type(), true) + "Helper";
localHelper = Class.forName(qualHelperClassName);
}
}
// Extract method of helper class
// Need access to this to convert an Any to the Java language type.
// TODO: Cache it in a struct - method map, perhaps using weak references.
Method extract = localHelper.getMethod("extract", new Class[] { Any.class });
Object[] args = { any };
retValue = extract.invoke(null, args);
}
catch (ClassNotFoundException e) {
// should never happen...
String msg = "Failed to extract the event struct data from a CORBA Any because the helper class '"
+ qualHelperClassName + "' does not exist.";
m_logger.log(Level.WARNING, msg, e);
}
catch (NoSuchMethodException e) {
// should never happen...
String msg = "Failed to process an any because the helper class '" + qualHelperClassName + "' does not provide the 'extract' method.";
m_logger.log(Level.WARNING, msg, e);
}
// catch (ClassCastException e) {
// // should never happen...
// String msg = "Failed to process an any because the contained data does not seem to come from an IDL struct.";
// m_logger.log(Level.WARNING, msg, e);
// }
catch (Throwable thr) { // IllegalAccessException, InvocationTargetException, TypeCodePackage.BadKind or any other throwable
// should never happen...
String msg = "Failed to process an any because of unexpected problem.";
m_logger.log(Level.WARNING, msg, thr);
}
return retValue;
}
/**
* Derives the qualified Java class name for an IDL-defined struct from the Corba ID of that struct.
* See also jacorb-specific method "TypeCode#idlTypeName"
*
* @param isNestedStruct if true, "Package" will be inserted according to
* <i>"IDL to Java LanguageMapping Specification" version 1.2: 1.17 Mapping for Certain Nested Types</i> apply.
*/
protected String corbaStructToJavaClass(TypeCode tc, boolean isNestedStruct)
throws IllegalArgumentException
{
String qualName = null;
if (tc.kind() == TCKind.tk_struct) {
String prefix = "IDL:";
String suffix = ":1.0";
try {
String id = tc.id();
if (!id.startsWith(prefix) || !id.endsWith(suffix)) {
throw new IllegalArgumentException("Struct ID is expected to start with 'IDL:' and end with ':1.0'");
}
String qualNameWithSlashes = id.substring(prefix.length(), id.length() - suffix.length());
qualName = qualNameWithSlashes.replace('/', '.');
} catch (BadKind ex) {
// should never happen since we call it only for tk_struct
throw new IllegalArgumentException(ex);
}
if (isNestedStruct) {
int lastDotIndex = qualName.lastIndexOf('.');
if (lastDotIndex > 0) {
String className = qualName.substring(lastDotIndex + 1);
String jPackage = qualName.substring(0, lastDotIndex);
jPackage += "Package."; // defined in IDL-Java mapping spec
qualName = jPackage + className;
}
}
return qualName;
}
else {
throw new IllegalArgumentException("Expected TypeCode for a struct, but got TypeCode #" + tc.kind().value());
}
}
}
|
182790_0 | package be.zetta.logisticsdesktop.gui.magazijnier;
import be.zetta.logisticsdesktop.domain.order.entity.OrderStatus;
import be.zetta.logisticsdesktop.domain.order.entity.dto.CustomerOrderDto;
import be.zetta.logisticsdesktop.domain.order.entity.dto.OrderLineDto;
import be.zetta.logisticsdesktop.domain.packaging.entity.dto.PackagingDto;
import be.zetta.logisticsdesktop.domain.transport.entity.dto.TransportDto;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import java.util.EnumSet;
public class BestellingenModel {
// String properties zijn bidirectioneel verbonden met de text velden in de controller
private final StringProperty trackAndTraceProperty ;
private final StringProperty orderStatusProperty;
private final StringProperty orderDateProperty;
private final StringProperty orderIdProperty;
private final StringProperty customerNameProperty;
private final StringProperty purchaserNameProperty;
private final StringProperty purchaserEmailProperty;
private final StringProperty totalSumProperty;
private final StringProperty deliveryAddressProperty;
private final ObjectProperty<TransportDto> transportDtoObjectProperty;
private final ListProperty<PackagingDto> packagingListProperty;
private final ListProperty<OrderLineDto> orderLinesProperty;
private CustomerOrderDto orderDto;
private CustomerOrderDto orderDtoBefore;
public BestellingenModel(CustomerOrderDto orderDto) {
this.orderDto = orderDto;
this.orderDtoBefore = orderDto;
trackAndTraceProperty = new SimpleStringProperty(orderDto.getTrackTraceCode());
orderStatusProperty = new SimpleStringProperty(orderDto.getStatus().name());
orderDateProperty = new SimpleStringProperty(orderDto.getOrderDate().toString());
transportDtoObjectProperty = new SimpleObjectProperty<>(orderDto.getTransport());
orderIdProperty = new SimpleStringProperty(orderDto.getOrderId());
customerNameProperty = new SimpleStringProperty(orderDto.getCustomer().getName());
purchaserNameProperty = new SimpleStringProperty(orderDto.getPurchaser().getFirstName() + " " + orderDto.getPurchaser().getLastName());
purchaserEmailProperty = new SimpleStringProperty(orderDto.getPurchaser().getEmail());
packagingListProperty = new SimpleListProperty<>(FXCollections.observableArrayList(orderDto.getPackaging()));
totalSumProperty = new SimpleStringProperty(Double.toString(orderDto.getOrderLines()
.stream()
.mapToDouble(l -> l.getQuantityOrdered() * l.getUnitPriceOrderLine()).sum()));
deliveryAddressProperty = new SimpleStringProperty(orderDto.getDeliveryAddress().getStreet()
+ " " + orderDto.getDeliveryAddress().getHouseNumber()
+ "\n" + orderDto.getDeliveryAddress().getCountry()
+ " " + orderDto.getDeliveryAddress().getPostalCode());
orderLinesProperty = new SimpleListProperty<>(FXCollections.observableArrayList(orderDto.getOrderLines()));
// Listeners are needed to change the value in the DTO when user made changes
trackAndTraceProperty.addListener((observableValue, s, t1) -> this.orderDto.setTrackTraceCode(t1));
orderStatusProperty.addListener((observableValue, s, t1) -> {
if(EnumSet.allOf(OrderStatus.class)
.stream()
.anyMatch(e -> e.name().equals(t1))){
this.orderDto.setStatus(OrderStatus.valueOf(t1));
}
});
transportDtoObjectProperty.addListener((observableValue, transportDto, t1) -> this.orderDto.setTransport(t1));
purchaserEmailProperty.addListener((observableValue, s, t1) -> this.orderDto.getPurchaser().setEmail(t1));
}
public CustomerOrderDto getUpdatedOrder() {
return this.orderDto;
}
public void revertChanges() {
updateCustomerOrderModel(orderDtoBefore);
}
public void updateCustomerOrderModel(CustomerOrderDto orderDto){
// This method is needed to update the FE when data was changed in the BE
this.orderDto = orderDto;
this.orderDtoBefore = orderDto;
trackAndTraceProperty.set(orderDto.getTrackTraceCode());
orderStatusProperty.set(orderDto.getStatus().name());
orderDateProperty.set(orderDto.getOrderDate().toString());
transportDtoObjectProperty.set(orderDto.getTransport());
orderIdProperty.set(orderDto.getOrderId());
customerNameProperty.set(orderDto.getCustomer().getName());
purchaserNameProperty.set(orderDto.getPurchaser().getFirstName() + " " + orderDto.getPurchaser().getLastName());
purchaserEmailProperty.set(orderDto.getPurchaser().getEmail());
packagingListProperty.set(FXCollections.observableArrayList(orderDto.getPackaging()));
totalSumProperty.set(Double.toString(orderDto.getOrderLines()
.stream()
.mapToDouble(l -> l.getQuantityOrdered() * l.getUnitPriceOrderLine()).sum()));
deliveryAddressProperty.set(orderDto.getDeliveryAddress().getStreet()
+ " " + orderDto.getDeliveryAddress().getHouseNumber()
+ "\n" + orderDto.getDeliveryAddress().getCountry()
+ " " + orderDto.getDeliveryAddress().getPostalCode());
orderLinesProperty.set(FXCollections.observableArrayList(orderDto.getOrderLines()));
}
public ListProperty<OrderLineDto> orderLinesProperty() {
return orderLinesProperty;
}
public ObjectProperty<TransportDto> getTransportDtoObjectProperty() {
return transportDtoObjectProperty;
}
public StringProperty getTrackAndTraceProperty() {
return trackAndTraceProperty;
}
public StringProperty getOrderStatusProperty() {
return orderStatusProperty;
}
public StringProperty getOrderDateProperty() {
return orderDateProperty;
}
public StringProperty getOrderIdProperty() {
return orderIdProperty;
}
public StringProperty getCustomerNameProperty() {
return customerNameProperty;
}
public StringProperty getPurchaserNameProperty() {
return purchaserNameProperty;
}
public StringProperty getPurchaserEmailProperty() {
return purchaserEmailProperty;
}
public StringProperty getDeliveryAddressProperty() {
return deliveryAddressProperty;
}
public StringProperty getTotalSumProperty() {
return totalSumProperty;
}
public ListProperty<PackagingDto> getPackagingListProperty() {
return packagingListProperty;
}
}
| AFIRO/logistics-desktop | src/main/java/be/zetta/logisticsdesktop/gui/magazijnier/BestellingenModel.java | 1,534 | // String properties zijn bidirectioneel verbonden met de text velden in de controller | line_comment | nl | package be.zetta.logisticsdesktop.gui.magazijnier;
import be.zetta.logisticsdesktop.domain.order.entity.OrderStatus;
import be.zetta.logisticsdesktop.domain.order.entity.dto.CustomerOrderDto;
import be.zetta.logisticsdesktop.domain.order.entity.dto.OrderLineDto;
import be.zetta.logisticsdesktop.domain.packaging.entity.dto.PackagingDto;
import be.zetta.logisticsdesktop.domain.transport.entity.dto.TransportDto;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import java.util.EnumSet;
public class BestellingenModel {
// Strin<SUF>
private final StringProperty trackAndTraceProperty ;
private final StringProperty orderStatusProperty;
private final StringProperty orderDateProperty;
private final StringProperty orderIdProperty;
private final StringProperty customerNameProperty;
private final StringProperty purchaserNameProperty;
private final StringProperty purchaserEmailProperty;
private final StringProperty totalSumProperty;
private final StringProperty deliveryAddressProperty;
private final ObjectProperty<TransportDto> transportDtoObjectProperty;
private final ListProperty<PackagingDto> packagingListProperty;
private final ListProperty<OrderLineDto> orderLinesProperty;
private CustomerOrderDto orderDto;
private CustomerOrderDto orderDtoBefore;
public BestellingenModel(CustomerOrderDto orderDto) {
this.orderDto = orderDto;
this.orderDtoBefore = orderDto;
trackAndTraceProperty = new SimpleStringProperty(orderDto.getTrackTraceCode());
orderStatusProperty = new SimpleStringProperty(orderDto.getStatus().name());
orderDateProperty = new SimpleStringProperty(orderDto.getOrderDate().toString());
transportDtoObjectProperty = new SimpleObjectProperty<>(orderDto.getTransport());
orderIdProperty = new SimpleStringProperty(orderDto.getOrderId());
customerNameProperty = new SimpleStringProperty(orderDto.getCustomer().getName());
purchaserNameProperty = new SimpleStringProperty(orderDto.getPurchaser().getFirstName() + " " + orderDto.getPurchaser().getLastName());
purchaserEmailProperty = new SimpleStringProperty(orderDto.getPurchaser().getEmail());
packagingListProperty = new SimpleListProperty<>(FXCollections.observableArrayList(orderDto.getPackaging()));
totalSumProperty = new SimpleStringProperty(Double.toString(orderDto.getOrderLines()
.stream()
.mapToDouble(l -> l.getQuantityOrdered() * l.getUnitPriceOrderLine()).sum()));
deliveryAddressProperty = new SimpleStringProperty(orderDto.getDeliveryAddress().getStreet()
+ " " + orderDto.getDeliveryAddress().getHouseNumber()
+ "\n" + orderDto.getDeliveryAddress().getCountry()
+ " " + orderDto.getDeliveryAddress().getPostalCode());
orderLinesProperty = new SimpleListProperty<>(FXCollections.observableArrayList(orderDto.getOrderLines()));
// Listeners are needed to change the value in the DTO when user made changes
trackAndTraceProperty.addListener((observableValue, s, t1) -> this.orderDto.setTrackTraceCode(t1));
orderStatusProperty.addListener((observableValue, s, t1) -> {
if(EnumSet.allOf(OrderStatus.class)
.stream()
.anyMatch(e -> e.name().equals(t1))){
this.orderDto.setStatus(OrderStatus.valueOf(t1));
}
});
transportDtoObjectProperty.addListener((observableValue, transportDto, t1) -> this.orderDto.setTransport(t1));
purchaserEmailProperty.addListener((observableValue, s, t1) -> this.orderDto.getPurchaser().setEmail(t1));
}
public CustomerOrderDto getUpdatedOrder() {
return this.orderDto;
}
public void revertChanges() {
updateCustomerOrderModel(orderDtoBefore);
}
public void updateCustomerOrderModel(CustomerOrderDto orderDto){
// This method is needed to update the FE when data was changed in the BE
this.orderDto = orderDto;
this.orderDtoBefore = orderDto;
trackAndTraceProperty.set(orderDto.getTrackTraceCode());
orderStatusProperty.set(orderDto.getStatus().name());
orderDateProperty.set(orderDto.getOrderDate().toString());
transportDtoObjectProperty.set(orderDto.getTransport());
orderIdProperty.set(orderDto.getOrderId());
customerNameProperty.set(orderDto.getCustomer().getName());
purchaserNameProperty.set(orderDto.getPurchaser().getFirstName() + " " + orderDto.getPurchaser().getLastName());
purchaserEmailProperty.set(orderDto.getPurchaser().getEmail());
packagingListProperty.set(FXCollections.observableArrayList(orderDto.getPackaging()));
totalSumProperty.set(Double.toString(orderDto.getOrderLines()
.stream()
.mapToDouble(l -> l.getQuantityOrdered() * l.getUnitPriceOrderLine()).sum()));
deliveryAddressProperty.set(orderDto.getDeliveryAddress().getStreet()
+ " " + orderDto.getDeliveryAddress().getHouseNumber()
+ "\n" + orderDto.getDeliveryAddress().getCountry()
+ " " + orderDto.getDeliveryAddress().getPostalCode());
orderLinesProperty.set(FXCollections.observableArrayList(orderDto.getOrderLines()));
}
public ListProperty<OrderLineDto> orderLinesProperty() {
return orderLinesProperty;
}
public ObjectProperty<TransportDto> getTransportDtoObjectProperty() {
return transportDtoObjectProperty;
}
public StringProperty getTrackAndTraceProperty() {
return trackAndTraceProperty;
}
public StringProperty getOrderStatusProperty() {
return orderStatusProperty;
}
public StringProperty getOrderDateProperty() {
return orderDateProperty;
}
public StringProperty getOrderIdProperty() {
return orderIdProperty;
}
public StringProperty getCustomerNameProperty() {
return customerNameProperty;
}
public StringProperty getPurchaserNameProperty() {
return purchaserNameProperty;
}
public StringProperty getPurchaserEmailProperty() {
return purchaserEmailProperty;
}
public StringProperty getDeliveryAddressProperty() {
return deliveryAddressProperty;
}
public StringProperty getTotalSumProperty() {
return totalSumProperty;
}
public ListProperty<PackagingDto> getPackagingListProperty() {
return packagingListProperty;
}
}
|
128058_28 | package eu.linkedeodata.geotriples.geotiff;
//package org.locationtech.jtsexample.io.gml2;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.CoordinateSequenceFactory;
import org.locationtech.jts.geom.CoordinateSequences;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.WKTWriter;
import org.locationtech.jts.io.gml2.GMLConstants;
import org.locationtech.jts.io.gml2.GMLHandler;
import org.locationtech.jts.io.gml2.GMLWriter;
/**
* An example of using the {@link GMLHandler} class to read geometry data out of
* KML files.
*
* @author mbdavis
*
*/
public class GeoTiffReaderExample {
public static void main(String[] args) throws Exception {
String filename = "/Users/Admin/Downloads/states.kml";
GeoTiffReader2 rdr = new GeoTiffReader2(filename,"R2RMLPrimaryKey");
rdr.read();
}
}
class GeoTiffReader2 {
private String filename;
private String primarykey;
private List<GeoTiffResultRow> results=new ArrayList<GeoTiffResultRow>();
public GeoTiffReader2(String filename,String primarykey) {
this.filename = filename;
this.primarykey=primarykey;
}
public List<GeoTiffResultRow> getResults()
{
return results;
}
public void read() throws IOException, SAXException {
XMLReader xr;
xr = new org.apache.xerces.parsers.SAXParser();
KMLHandler kmlHandler = new KMLHandler();
xr.setContentHandler(kmlHandler);
xr.setErrorHandler(kmlHandler);
Reader r = new BufferedReader(new FileReader(filename));
LineNumberReader myReader = new LineNumberReader(r);
xr.parse(new InputSource(myReader));
// List geoms = kmlHandler.getGeometries();
}
private class KMLHandler extends DefaultHandler {
GeoTiffResultRow row;
public final String[] SET_VALUES = new String[] { "name", "address",
"phonenumber", "visibility", "open", "description", "LookAt",
"Style", "Region", "Geometry" , "MultiGeometry"};
public final Set<String> LEGALNAMES = new HashSet<String>(
Arrays.asList(SET_VALUES));
@SuppressWarnings("rawtypes")
private List geoms = new ArrayList();;
private GMLHandler currGeomHandler;
private String lastEltName = null;
private String lastEltData = "";
private GeometryFactory fact = new FixingGeometryFactory();
private boolean placemarkactive = false;
private Set<String> visits = new HashSet<String>();
public KMLHandler() {
super();
}
@SuppressWarnings({ "unused", "rawtypes" })
public List getGeometries() {
return geoms;
}
/**
* SAX handler. Handle state and state transitions based on an element
* starting.
*
* @param uri
* Description of the Parameter
* @param name
* Description of the Parameter
* @param qName
* Description of the Parameter
* @param atts
* Description of the Parameter
* @exception SAXException
* Description of the Exception
*/
public void startElement(String uri, String name, String qName,
Attributes atts) throws SAXException {
if (name.equals("Placemark")) {
placemarkactive = true;
row=new GeoTiffResultRow(); //new row result;
}
visits.add(name);
if (placemarkactive && !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()) {
//if (name.equalsIgnoreCase(GMLConstants.GML_POLYGON)
// || name.equalsIgnoreCase(GMLConstants.GML_POINT)
//|| name.equalsIgnoreCase(GMLConstants.GML_MULTI_GEOMETRY)) {
if (name.equalsIgnoreCase(GMLConstants.GML_MULTI_GEOMETRY)) {
currGeomHandler = new GMLHandler(fact, null);
}
if (currGeomHandler != null)
currGeomHandler.startElement(uri, name, qName, atts);
if (currGeomHandler == null) {
lastEltName = name;
// System.out.println(name);
}
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if (placemarkactive
&& !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()) {
if (currGeomHandler != null) {
currGeomHandler.characters(ch, start, length);
} else {
String content = new String(ch, start, length).trim();
if (content.length() > 0) {
lastEltData+=content;
//System.out.println(lastEltName + "= " + content);
}
}
}
}
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
if (currGeomHandler != null)
currGeomHandler.ignorableWhitespace(ch, start, length);
}
/**
* SAX handler - handle state information and transitions based on ending
* elements.
*
* @param uri
* Description of the Parameter
* @param name
* Description of the Parameter
* @param qName
* Description of the Parameter
* @exception SAXException
* Description of the Exception
*/
@SuppressWarnings({ "unused", "unchecked" })
public void endElement(String uri, String name, String qName)
throws SAXException {
// System.out.println("/" + name);
//System.out.println("the ena name="+name);
if (placemarkactive && !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()
&& currGeomHandler==null && !lastEltData.isEmpty()) {
//System.out.println(lastEltName + " " + lastEltData);
row.addPair(lastEltName, lastEltData);
}
lastEltData="";
if (name.equals("Placemark")) {
placemarkactive = false;
try {
row.addPair(GeoTiffReader2.this.primarykey, KeyGenerator.Generate());
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
GeoTiffReader2.this.results.add(row);
}
visits.remove(name);
if (currGeomHandler != null) {
currGeomHandler.endElement(uri, name, qName);
if (currGeomHandler.isGeometryComplete()) {
Geometry g = currGeomHandler.getGeometry();
WKTWriter wkt_writer=new WKTWriter();
GMLWriter gml_writer = new GMLWriter();
if (g.getClass().equals(org.locationtech.jts.geom.Point.class)) {
Point geometry = (org.locationtech.jts.geom.Point) g;
row.addPair("isEmpty", geometry.isEmpty());
row.addPair("isSimple", geometry.isSimple());
row.addPair("dimension",
geometry.getCoordinates().length);
row.addPair("coordinateDimension",
geometry.getCoordinates().length);
row.addPair("spatialDimension", geometry.getDimension()); // spatialdimension
// <=
// dimension
// System.out.println(geometry.getCoordinate().x + " "
// +geometry.getCoordinate().z);
// System.out.println(geometry.get .getSRID());
// CRS.
String crs="2311";
if (crs == null) {
System.err.println("No SRID specified. Aborting...");
System.exit(-1);
}
row.addPair("asWKT",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
row.addPair("hasSerialization",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
// newrow.addPair("hasSerialization",
// wkt_writer.write(geometry));
gml_writer.setSrsName(crs);
row.addPair("asGML", gml_writer.write(geometry)
.replaceAll("\n", " "));
row.addPair("is3D", geometry.getDimension() == 3);
} else {
GeometryCollection geometry = (GeometryCollection) g;
row.addPair("isEmpty", geometry.isEmpty());
row.addPair("isSimple", geometry.isSimple());
row.addPair("dimension",
geometry.getCoordinates().length);
row.addPair("coordinateDimension",
geometry.getCoordinates().length);
row.addPair("spatialDimension", geometry.getDimension()); // spatialdimension
// <=
// dimension
// System.out.println(geometry.getCoordinate().x + " "
// +geometry.getCoordinate().z);
// System.out.println(geometry.get .getSRID());
// CRS.
String crs="2323";
if (crs == null) {
System.err.println("No SRID specified. Aborting...");
System.exit(-1);
}
// geometry.getNumPoints();
// TODO spatialDimension??????
// TODO coordinateDimension??????
// Geometry geometry1=
// (Geometry)sourceGeometryAttribute.getValue();
// geometry1.transform(arg0, arg1)
// sourceGeometryAttribute.ge
row.addPair("asWKT",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
row.addPair("hasSerialization",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
// newrow.addPair("hasSerialization",
// wkt_writer.write(geometry));
gml_writer
.setSrsName("http://www.opengis.net/def/crs/EPSG/0/"
+ crs);
row.addPair("asGML", gml_writer.write(geometry)
.replaceAll("\n", " "));
row.addPair("is3D", geometry.getDimension() == 3);
}
//System.out.println(g);
//System.out.println(ww.write(g));
geoms.add(g);
// reset to indicate no longer parsing geometry
currGeomHandler = null;
}
}
}
}
}
/**
* A GeometryFactory extension which fixes structurally bad coordinate sequences
* used to create LinearRings.
*
* @author mbdavis
*
*/
@SuppressWarnings("serial")
class FixingGeometryFactory extends GeometryFactory {
public LinearRing createLinearRing(CoordinateSequence cs) {
if (cs.getCoordinate(0).equals(cs.getCoordinate(cs.size() - 1)))
return super.createLinearRing(cs);
// add a new coordinate to close the ring
CoordinateSequenceFactory csFact = getCoordinateSequenceFactory();
CoordinateSequence csNew = csFact.create(cs.size() + 1,
cs.getDimension());
CoordinateSequences.copy(cs, 0, csNew, 0, cs.size());
CoordinateSequences.copyCoord(csNew, 0, csNew, csNew.size() - 1);
return super.createLinearRing(csNew);
}
}
| AI-team-UoA/GeoTriples | geotriples-processors/geotriples-r2rml/src/main/java/eu/linkedeodata/geotriples/geotiff/GeoTiffReaderExample.java | 3,267 | // geometry.getNumPoints();
| line_comment | nl | package eu.linkedeodata.geotriples.geotiff;
//package org.locationtech.jtsexample.io.gml2;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.CoordinateSequenceFactory;
import org.locationtech.jts.geom.CoordinateSequences;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.WKTWriter;
import org.locationtech.jts.io.gml2.GMLConstants;
import org.locationtech.jts.io.gml2.GMLHandler;
import org.locationtech.jts.io.gml2.GMLWriter;
/**
* An example of using the {@link GMLHandler} class to read geometry data out of
* KML files.
*
* @author mbdavis
*
*/
public class GeoTiffReaderExample {
public static void main(String[] args) throws Exception {
String filename = "/Users/Admin/Downloads/states.kml";
GeoTiffReader2 rdr = new GeoTiffReader2(filename,"R2RMLPrimaryKey");
rdr.read();
}
}
class GeoTiffReader2 {
private String filename;
private String primarykey;
private List<GeoTiffResultRow> results=new ArrayList<GeoTiffResultRow>();
public GeoTiffReader2(String filename,String primarykey) {
this.filename = filename;
this.primarykey=primarykey;
}
public List<GeoTiffResultRow> getResults()
{
return results;
}
public void read() throws IOException, SAXException {
XMLReader xr;
xr = new org.apache.xerces.parsers.SAXParser();
KMLHandler kmlHandler = new KMLHandler();
xr.setContentHandler(kmlHandler);
xr.setErrorHandler(kmlHandler);
Reader r = new BufferedReader(new FileReader(filename));
LineNumberReader myReader = new LineNumberReader(r);
xr.parse(new InputSource(myReader));
// List geoms = kmlHandler.getGeometries();
}
private class KMLHandler extends DefaultHandler {
GeoTiffResultRow row;
public final String[] SET_VALUES = new String[] { "name", "address",
"phonenumber", "visibility", "open", "description", "LookAt",
"Style", "Region", "Geometry" , "MultiGeometry"};
public final Set<String> LEGALNAMES = new HashSet<String>(
Arrays.asList(SET_VALUES));
@SuppressWarnings("rawtypes")
private List geoms = new ArrayList();;
private GMLHandler currGeomHandler;
private String lastEltName = null;
private String lastEltData = "";
private GeometryFactory fact = new FixingGeometryFactory();
private boolean placemarkactive = false;
private Set<String> visits = new HashSet<String>();
public KMLHandler() {
super();
}
@SuppressWarnings({ "unused", "rawtypes" })
public List getGeometries() {
return geoms;
}
/**
* SAX handler. Handle state and state transitions based on an element
* starting.
*
* @param uri
* Description of the Parameter
* @param name
* Description of the Parameter
* @param qName
* Description of the Parameter
* @param atts
* Description of the Parameter
* @exception SAXException
* Description of the Exception
*/
public void startElement(String uri, String name, String qName,
Attributes atts) throws SAXException {
if (name.equals("Placemark")) {
placemarkactive = true;
row=new GeoTiffResultRow(); //new row result;
}
visits.add(name);
if (placemarkactive && !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()) {
//if (name.equalsIgnoreCase(GMLConstants.GML_POLYGON)
// || name.equalsIgnoreCase(GMLConstants.GML_POINT)
//|| name.equalsIgnoreCase(GMLConstants.GML_MULTI_GEOMETRY)) {
if (name.equalsIgnoreCase(GMLConstants.GML_MULTI_GEOMETRY)) {
currGeomHandler = new GMLHandler(fact, null);
}
if (currGeomHandler != null)
currGeomHandler.startElement(uri, name, qName, atts);
if (currGeomHandler == null) {
lastEltName = name;
// System.out.println(name);
}
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
if (placemarkactive
&& !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()) {
if (currGeomHandler != null) {
currGeomHandler.characters(ch, start, length);
} else {
String content = new String(ch, start, length).trim();
if (content.length() > 0) {
lastEltData+=content;
//System.out.println(lastEltName + "= " + content);
}
}
}
}
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
if (currGeomHandler != null)
currGeomHandler.ignorableWhitespace(ch, start, length);
}
/**
* SAX handler - handle state information and transitions based on ending
* elements.
*
* @param uri
* Description of the Parameter
* @param name
* Description of the Parameter
* @param qName
* Description of the Parameter
* @exception SAXException
* Description of the Exception
*/
@SuppressWarnings({ "unused", "unchecked" })
public void endElement(String uri, String name, String qName)
throws SAXException {
// System.out.println("/" + name);
//System.out.println("the ena name="+name);
if (placemarkactive && !CollectionUtils.intersection(visits, LEGALNAMES).isEmpty()
&& currGeomHandler==null && !lastEltData.isEmpty()) {
//System.out.println(lastEltName + " " + lastEltData);
row.addPair(lastEltName, lastEltData);
}
lastEltData="";
if (name.equals("Placemark")) {
placemarkactive = false;
try {
row.addPair(GeoTiffReader2.this.primarykey, KeyGenerator.Generate());
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
GeoTiffReader2.this.results.add(row);
}
visits.remove(name);
if (currGeomHandler != null) {
currGeomHandler.endElement(uri, name, qName);
if (currGeomHandler.isGeometryComplete()) {
Geometry g = currGeomHandler.getGeometry();
WKTWriter wkt_writer=new WKTWriter();
GMLWriter gml_writer = new GMLWriter();
if (g.getClass().equals(org.locationtech.jts.geom.Point.class)) {
Point geometry = (org.locationtech.jts.geom.Point) g;
row.addPair("isEmpty", geometry.isEmpty());
row.addPair("isSimple", geometry.isSimple());
row.addPair("dimension",
geometry.getCoordinates().length);
row.addPair("coordinateDimension",
geometry.getCoordinates().length);
row.addPair("spatialDimension", geometry.getDimension()); // spatialdimension
// <=
// dimension
// System.out.println(geometry.getCoordinate().x + " "
// +geometry.getCoordinate().z);
// System.out.println(geometry.get .getSRID());
// CRS.
String crs="2311";
if (crs == null) {
System.err.println("No SRID specified. Aborting...");
System.exit(-1);
}
row.addPair("asWKT",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
row.addPair("hasSerialization",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
// newrow.addPair("hasSerialization",
// wkt_writer.write(geometry));
gml_writer.setSrsName(crs);
row.addPair("asGML", gml_writer.write(geometry)
.replaceAll("\n", " "));
row.addPair("is3D", geometry.getDimension() == 3);
} else {
GeometryCollection geometry = (GeometryCollection) g;
row.addPair("isEmpty", geometry.isEmpty());
row.addPair("isSimple", geometry.isSimple());
row.addPair("dimension",
geometry.getCoordinates().length);
row.addPair("coordinateDimension",
geometry.getCoordinates().length);
row.addPair("spatialDimension", geometry.getDimension()); // spatialdimension
// <=
// dimension
// System.out.println(geometry.getCoordinate().x + " "
// +geometry.getCoordinate().z);
// System.out.println(geometry.get .getSRID());
// CRS.
String crs="2323";
if (crs == null) {
System.err.println("No SRID specified. Aborting...");
System.exit(-1);
}
// geome<SUF>
// TODO spatialDimension??????
// TODO coordinateDimension??????
// Geometry geometry1=
// (Geometry)sourceGeometryAttribute.getValue();
// geometry1.transform(arg0, arg1)
// sourceGeometryAttribute.ge
row.addPair("asWKT",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
row.addPair("hasSerialization",
"<http://www.opengis.net/def/crs/EPSG/0/" + crs
+ ">" + wkt_writer.write(geometry));
// newrow.addPair("hasSerialization",
// wkt_writer.write(geometry));
gml_writer
.setSrsName("http://www.opengis.net/def/crs/EPSG/0/"
+ crs);
row.addPair("asGML", gml_writer.write(geometry)
.replaceAll("\n", " "));
row.addPair("is3D", geometry.getDimension() == 3);
}
//System.out.println(g);
//System.out.println(ww.write(g));
geoms.add(g);
// reset to indicate no longer parsing geometry
currGeomHandler = null;
}
}
}
}
}
/**
* A GeometryFactory extension which fixes structurally bad coordinate sequences
* used to create LinearRings.
*
* @author mbdavis
*
*/
@SuppressWarnings("serial")
class FixingGeometryFactory extends GeometryFactory {
public LinearRing createLinearRing(CoordinateSequence cs) {
if (cs.getCoordinate(0).equals(cs.getCoordinate(cs.size() - 1)))
return super.createLinearRing(cs);
// add a new coordinate to close the ring
CoordinateSequenceFactory csFact = getCoordinateSequenceFactory();
CoordinateSequence csNew = csFact.create(cs.size() + 1,
cs.getDimension());
CoordinateSequences.copy(cs, 0, csNew, 0, cs.size());
CoordinateSequences.copyCoord(csNew, 0, csNew, csNew.size() - 1);
return super.createLinearRing(csNew);
}
}
|
17481_2 | package nl.han.aim.bewd.wsstringkata;
public class StringKata {
/**
* In deze main worden alle "tests" uitgevoerd die aantonen dat de string calculator naar behoren werkt.
* @param args standaard-args voor uitvoeren vanaf de commandline.
*/
public static void main(String[] args) {
StringCalculator calc = new StringCalculator();
if(calc.add("") != 0) {
System.out.println("FOUT: lege string levert geen nul op.");
}
if(calc.add("129") != 129) {
System.out.println("FOUT: string met één getal levert geen getal op.");
}
if(calc.add("12, 91") != 103) {
System.out.println("FOUT: string met komma levert niet het juiste resultaat op.");
}
if(calc.add("\n12, 91") != 103) {
System.out.println("FOUT: string met komma en extra witruimte levert niet het juiste resultaat op.");
}
if(calc.add("1, 2, 3, 4, 25") != 35) {
System.out.println("FOUT: string met meerdere getallen levert niet het juiste resultaat op.");
}
if(calc.add("1, 2, 3, 4\n 25") != 35) {
System.out.println("FOUT: string met meerdere getallen en delimiters levert niet het juiste resultaat op.");
}
if(calc.add("//%!%\n12 %!% 91") != 103) {
System.out.println("FOUT: string met custom delimiter (1) levert niet het juiste resultaat op.");
}
if(calc.add("2, 1001") != 2 && calc.add("1001") != 0) {
System.out.println("FOUT: getallen groter dan 1000 worden niet genegeerd.");
}
if(calc.add("//[abc][def][ghijk]\n1abc 2 ghijk 3 def 4") != 10) {
System.out.println("FOUT: string met meerdere custom delimiters levert niet het juiste resultaat op.");
}
if(calc.add("//[*][%]\n1*2%3") != 6) {
System.out.println("FOUT: string met meerdere custom delimiters met daarin speciale tekens levert niet het juiste resultaat op.");
}
System.out.println("Klaar met testen.");
}
}
| AIM-CNP/bewd-workshop-string-kata-uitwerking | src/main/java/nl/han/aim/bewd/wsstringkata/StringKata.java | 637 | //[abc][def][ghijk]\n1abc 2 ghijk 3 def 4") != 10) { | line_comment | nl | package nl.han.aim.bewd.wsstringkata;
public class StringKata {
/**
* In deze main worden alle "tests" uitgevoerd die aantonen dat de string calculator naar behoren werkt.
* @param args standaard-args voor uitvoeren vanaf de commandline.
*/
public static void main(String[] args) {
StringCalculator calc = new StringCalculator();
if(calc.add("") != 0) {
System.out.println("FOUT: lege string levert geen nul op.");
}
if(calc.add("129") != 129) {
System.out.println("FOUT: string met één getal levert geen getal op.");
}
if(calc.add("12, 91") != 103) {
System.out.println("FOUT: string met komma levert niet het juiste resultaat op.");
}
if(calc.add("\n12, 91") != 103) {
System.out.println("FOUT: string met komma en extra witruimte levert niet het juiste resultaat op.");
}
if(calc.add("1, 2, 3, 4, 25") != 35) {
System.out.println("FOUT: string met meerdere getallen levert niet het juiste resultaat op.");
}
if(calc.add("1, 2, 3, 4\n 25") != 35) {
System.out.println("FOUT: string met meerdere getallen en delimiters levert niet het juiste resultaat op.");
}
if(calc.add("//%!%\n12 %!% 91") != 103) {
System.out.println("FOUT: string met custom delimiter (1) levert niet het juiste resultaat op.");
}
if(calc.add("2, 1001") != 2 && calc.add("1001") != 0) {
System.out.println("FOUT: getallen groter dan 1000 worden niet genegeerd.");
}
if(calc.add("//[abc]<SUF>
System.out.println("FOUT: string met meerdere custom delimiters levert niet het juiste resultaat op.");
}
if(calc.add("//[*][%]\n1*2%3") != 6) {
System.out.println("FOUT: string met meerdere custom delimiters met daarin speciale tekens levert niet het juiste resultaat op.");
}
System.out.println("Klaar met testen.");
}
}
|
65821_6 | package aimene.doex.bestelling.controller;
import aimene.doex.bestelling.model.Bestelling;
import aimene.doex.bestelling.model.Geld;
import aimene.doex.bestelling.model.Product;
import aimene.doex.bestelling.model.Valuta;
import aimene.doex.bestelling.repository.ProductRepository;
import aimene.doex.bestelling.repository.BestellingRepository;
import org.springframework.data.jdbc.core.mapping.AggregateReference;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@RestController
@RequestMapping("/producten")
public class ProductController {
private final ProductRepository productRepository;
private final BestellingRepository bestellingRepository;
public ProductController(ProductRepository productRepository, BestellingRepository bestellingRepository) {
this.productRepository = productRepository;
this.bestellingRepository = bestellingRepository;
}
@GetMapping
public Iterable<Product> findAll() {
return productRepository.findAll();
}
@GetMapping("{id}")
public Product findById(@PathVariable("id") Product product) {
return product;
}
@PatchMapping("{id}/prijs")
public void veranderPrijs(@PathVariable("id") Product product,
@RequestBody Map<String, Object> requestBody) {
/* ******************************************************************** */
// Geef in het sequentiediagram wel expliciet aan dat je het product
// ophaalt uit de repository met een findById(productId)
// daarmee wordt het makkelijker te zien wanneer er een
// optimistic lock exception kan optreden
// (zie voorbeeld in het sequentiediagram)
/* ******************************************************************** */
/* ******************************************************************** */
// Deze regel hoef je niet op te nemen in het sequentiediagram
// Je kunt ervan uitgaan dat de nieuwePrijs wordt meegegeven door de
// actor bij aanroep van de methode veranderPrijs van deze controller
Geld nieuwePrijs = new Geld((int) requestBody.get("nieuwe_prijs"), Valuta.EUR);
/* ******************************************************************** */
/* ******************************************************************** */
// Geef deze regel in het sequentiediagram aan met een rnote
// (zie voorbeeld in het sequentiediagram)
product.veranderPrijs(nieuwePrijs);
/* ******************************************************************** */
productRepository.save(product);
/* ******************************************************************** */
// Deze regel hoef je niet op te nemen in het sequentiediagram
AggregateReference<Product, Integer> productRef =
AggregateReference.to(product.getId());
/* ******************************************************************** */
/* ******************************************************************** */
// Vind alle bestellingen die het product bevatten waarvan de prijs is veranderd
// Dit kan beter met een sql-query, maar dat doen we volgende week
// In het Sequentiediagram kun je ervan uitgaan dat er een methode bestaat
// bestellingRepository.findAllMetProduct(productId) die dit voor je doet;
Iterable<Bestelling> bestellingen = bestellingRepository.findAll();
List<Bestelling> bestellingenMetProduct = StreamSupport.stream(bestellingen.spliterator(), false)
.filter(bestelling -> bestelling.bevatBestellingProduct(productRef))
.collect(Collectors.toList());
/* ******************************************************************** */
/* ******************************************************************** */
// Geef dit in het sequentiediagram aan met een rnote
// Verander de stukprijs van het product in de eerder gevonden bestellingen
bestellingenMetProduct.forEach(bestelling -> bestelling.veranderStukPrijs(productRef, nieuwePrijs));
/* ******************************************************************** */
bestellingRepository.saveAll(bestellingenMetProduct);
}
}
| AIM-ENE/doex-opdracht-3 | oefeningen/les-3/voorbereiding/onderdeel2/bestelling/src/main/java/aimene/doex/bestelling/controller/ProductController.java | 932 | // Je kunt ervan uitgaan dat de nieuwePrijs wordt meegegeven door de | line_comment | nl | package aimene.doex.bestelling.controller;
import aimene.doex.bestelling.model.Bestelling;
import aimene.doex.bestelling.model.Geld;
import aimene.doex.bestelling.model.Product;
import aimene.doex.bestelling.model.Valuta;
import aimene.doex.bestelling.repository.ProductRepository;
import aimene.doex.bestelling.repository.BestellingRepository;
import org.springframework.data.jdbc.core.mapping.AggregateReference;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@RestController
@RequestMapping("/producten")
public class ProductController {
private final ProductRepository productRepository;
private final BestellingRepository bestellingRepository;
public ProductController(ProductRepository productRepository, BestellingRepository bestellingRepository) {
this.productRepository = productRepository;
this.bestellingRepository = bestellingRepository;
}
@GetMapping
public Iterable<Product> findAll() {
return productRepository.findAll();
}
@GetMapping("{id}")
public Product findById(@PathVariable("id") Product product) {
return product;
}
@PatchMapping("{id}/prijs")
public void veranderPrijs(@PathVariable("id") Product product,
@RequestBody Map<String, Object> requestBody) {
/* ******************************************************************** */
// Geef in het sequentiediagram wel expliciet aan dat je het product
// ophaalt uit de repository met een findById(productId)
// daarmee wordt het makkelijker te zien wanneer er een
// optimistic lock exception kan optreden
// (zie voorbeeld in het sequentiediagram)
/* ******************************************************************** */
/* ******************************************************************** */
// Deze regel hoef je niet op te nemen in het sequentiediagram
// Je ku<SUF>
// actor bij aanroep van de methode veranderPrijs van deze controller
Geld nieuwePrijs = new Geld((int) requestBody.get("nieuwe_prijs"), Valuta.EUR);
/* ******************************************************************** */
/* ******************************************************************** */
// Geef deze regel in het sequentiediagram aan met een rnote
// (zie voorbeeld in het sequentiediagram)
product.veranderPrijs(nieuwePrijs);
/* ******************************************************************** */
productRepository.save(product);
/* ******************************************************************** */
// Deze regel hoef je niet op te nemen in het sequentiediagram
AggregateReference<Product, Integer> productRef =
AggregateReference.to(product.getId());
/* ******************************************************************** */
/* ******************************************************************** */
// Vind alle bestellingen die het product bevatten waarvan de prijs is veranderd
// Dit kan beter met een sql-query, maar dat doen we volgende week
// In het Sequentiediagram kun je ervan uitgaan dat er een methode bestaat
// bestellingRepository.findAllMetProduct(productId) die dit voor je doet;
Iterable<Bestelling> bestellingen = bestellingRepository.findAll();
List<Bestelling> bestellingenMetProduct = StreamSupport.stream(bestellingen.spliterator(), false)
.filter(bestelling -> bestelling.bevatBestellingProduct(productRef))
.collect(Collectors.toList());
/* ******************************************************************** */
/* ******************************************************************** */
// Geef dit in het sequentiediagram aan met een rnote
// Verander de stukprijs van het product in de eerder gevonden bestellingen
bestellingenMetProduct.forEach(bestelling -> bestelling.veranderStukPrijs(productRef, nieuwePrijs));
/* ******************************************************************** */
bestellingRepository.saveAll(bestellingenMetProduct);
}
}
|
64399_29 | package app;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
public class Tabela {
// ~~ nazwaKolumny, zawartoscTejKolumny ~~ tabela
private Map<String, List<String>> tabela;
public Tabela() {
tabela = new TreeMap<>();
}
// SPRAWNE - nie dotykać
public void dodajKolumne(String nazwaKolumny) {
// sprawdz czy taka juz nie istnieje
boolean czyIstnieje = sprawdzCzyJuzIstniejeKolumna(nazwaKolumny);
if (czyIstnieje) {
System.out.println("Kolumna o podanej nazwie: " + nazwaKolumny + " już istnieje!");
}
// nie istnieje
// dodaj nową kolumnę i pustą zawartość
List<String> zawartoscKolumny = new ArrayList<>();
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
// SPRAWNE - nie dotykać
public void dodajWartoscDoKolumny(String nazwaKolumny, String wartosc) throws Exception {
boolean znalezionoKolumne = znajdzKolumne(nazwaKolumny);
boolean zawartoscKolumnyJestPusta = czyZawartoscKolumnyJestPusta(nazwaKolumny);
List<String> zawartoscKolumny = new ArrayList<>();
if (znalezionoKolumne) {
if (zawartoscKolumnyJestPusta) {
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
} else {
zawartoscKolumny = tabela.get(nazwaKolumny);
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
} else {
throw new Exception("Nie znaleziono kolumny: " + nazwaKolumny);
}
}
public void dodajWartosciDoKolumn(String[] zbiorWartosci) {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
int i = 0;
for (Entry<String, List<String>> entry : tabela.entrySet()) {
// dla kazdej kolumny, wez i wstaw, jezeli nie masz co wstawic, wstaw ""
List<String> lista = entry.getValue();
if (i == zbiorWartosci.length)
lista.add("");
while (i < zbiorWartosci.length) {
lista.add(zbiorWartosci[i]);
i++;
break;
}
tabela.put(entry.getKey(), lista);
}
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunKolumne(String nazwaKolumny) {
if (znajdzKolumne(nazwaKolumny)) {
// znaleziono
tabela.remove(nazwaKolumny);
return this.tabela;
}
// nie znaleziono -> wyjatek
System.out.println("Nie znaleziono kolumny" + nazwaKolumny);
return this.tabela;
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunWartoscZKolumny(String nazwaKolumny, int index) {
boolean znalezionoKolumneOrazCzyNieJestPusta;
try {
znalezionoKolumneOrazCzyNieJestPusta = czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
} catch (Exception e) {
System.out.println(e.getMessage());
znalezionoKolumneOrazCzyNieJestPusta = false;
}
if (znalezionoKolumneOrazCzyNieJestPusta) {
List<String> zawartoscKolumny = tabela.get(nazwaKolumny);
try {
zawartoscKolumny.remove(index);
tabela.put(nazwaKolumny, zawartoscKolumny);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
return this.tabela;
}
public void usunWartosciZKolumn() {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.clear();
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
public void usunWiersz(String kolumna, String wartosc) throws Exception {
boolean istnieje = sprawdzCzyJuzIstniejeKolumna(kolumna);
if (istnieje == false)
throw new Exception("Nie istnieje taka kolumna " + kolumna);
boolean zawiera = false;
int indexOfValue = 0;
List<String> zawartoscKolumny = tabela.get(kolumna);
for (String string : zawartoscKolumny) {
if (string.equals(wartosc)) {
zawiera = true;
break;
}
indexOfValue++;
}
if (zawiera == true) {
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.remove(indexOfValue);
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
}
// SPRAWNE - nie dotykać
public void wypiszWszystkieKolumny() {
System.out.println("Wszystkie dostępne kolumny");
Set<String> tabelaKeys = this.tabela.keySet();
System.out.println(tabelaKeys);
}
public void wypiszWszystkieKolumnyWrazZZawaroscia() {
Set<Entry<String, List<String>>> entires = tabela.entrySet();
for (Entry<String, List<String>> ent : entires) {
System.out.println(ent.getKey() + " ==> " + ent.getValue());
}
}
// SPRAWNE - nie dotykać
public void wypiszZawartoscKolumny(String nazwaKolumny) {
try {
czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
// znaleziono i nie jest pusta
List<String> zawartoscKolumny;
zawartoscKolumny = tabela.get(nazwaKolumny);
// zawartoscKolumny;
if (zawartoscKolumny.size() != 0) {
System.out.println("Zawartosc kolumny " + nazwaKolumny + " to:");
for (int i = 0; i < zawartoscKolumny.size(); i++)
System.out.println("Indeks " + i + ": " + zawartoscKolumny.get(i));
} else
System.out.println("Zawartosc kolumny " + nazwaKolumny + " jest pusta!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void wypiszKolumnyZTablicyGdzieKolumnaSpelniaWarunek(String[] zbiorKolumn, String[] warunekKolumnaWartosc) {
// wcale nie robię niezrozumiałych zagnieżdżeń
boolean wypiszWszystkieKolumny = false;
for (String kolumna : zbiorKolumn) {
if (kolumna.equals("*")) {
wypiszWszystkieKolumny = true;
break;
}
}
if (wypiszWszystkieKolumny == true) {
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
// for (String kolumna : zbiorKolumn) {
// kolumny
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() + " ==> " + ent.getValue());
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
}
// }
} else {
// wypisz TYLKO poszczegolne KOLUMNY oraz RZEDY
// lalalalalalaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
for (String kolumna : zbiorKolumn) {
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() + " ==> " + ent.getValue());
// wypisz WYBRANE kolumny, ale tylko rzad gdzie wystapil ten ... warunek
// lalala.
if (ent.getKey().equals(kolumna))
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
// index++;
}
}
}
}
// SPRAWNE - nie dotykać
public boolean znajdzKolumne(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
return true;
}
}
return false;
}
// SPRAWNE - nie dotykać
private boolean sprawdzCzyJuzIstniejeKolumna(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
int counter = 0;
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
counter = counter + 1;
}
}
if (counter > 0)
return true; // wystapil duplikat
else
return false; // nie ma duplikatu
}
// SPRAWNE - nie dotykać
private boolean czyZawartoscKolumnyJestPusta(String nazwaKolumny) {
if (tabela.get(nazwaKolumny) == null)
return true;
else
return false;
}
// SPRAWNE - nie dotykać
public boolean czyZnalezionoKolumneOrazCzyNieJestPusta(String nazwaKolumny) throws Exception {
// znaleziono ale jest pusta
if (znajdzKolumne(nazwaKolumny) && czyZawartoscKolumnyJestPusta(nazwaKolumny))
throw new Exception("Zawartosc kolumny " + nazwaKolumny + " jest akutalnie pusta");
// nie znaleziono
if (!znajdzKolumne(nazwaKolumny))
throw new Exception("Nie znaleziono kolumny " + nazwaKolumny);
// znaleziono
return true;
}
} | AKrupaa/Simple-database-in-Java | src/app/Tabela.java | 3,358 | // System.out.println(ent.getKey() + " ==> " + ent.getValue()); | line_comment | nl | package app;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
public class Tabela {
// ~~ nazwaKolumny, zawartoscTejKolumny ~~ tabela
private Map<String, List<String>> tabela;
public Tabela() {
tabela = new TreeMap<>();
}
// SPRAWNE - nie dotykać
public void dodajKolumne(String nazwaKolumny) {
// sprawdz czy taka juz nie istnieje
boolean czyIstnieje = sprawdzCzyJuzIstniejeKolumna(nazwaKolumny);
if (czyIstnieje) {
System.out.println("Kolumna o podanej nazwie: " + nazwaKolumny + " już istnieje!");
}
// nie istnieje
// dodaj nową kolumnę i pustą zawartość
List<String> zawartoscKolumny = new ArrayList<>();
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
// SPRAWNE - nie dotykać
public void dodajWartoscDoKolumny(String nazwaKolumny, String wartosc) throws Exception {
boolean znalezionoKolumne = znajdzKolumne(nazwaKolumny);
boolean zawartoscKolumnyJestPusta = czyZawartoscKolumnyJestPusta(nazwaKolumny);
List<String> zawartoscKolumny = new ArrayList<>();
if (znalezionoKolumne) {
if (zawartoscKolumnyJestPusta) {
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
} else {
zawartoscKolumny = tabela.get(nazwaKolumny);
zawartoscKolumny.add(wartosc);
this.tabela.put(nazwaKolumny, zawartoscKolumny);
}
} else {
throw new Exception("Nie znaleziono kolumny: " + nazwaKolumny);
}
}
public void dodajWartosciDoKolumn(String[] zbiorWartosci) {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
int i = 0;
for (Entry<String, List<String>> entry : tabela.entrySet()) {
// dla kazdej kolumny, wez i wstaw, jezeli nie masz co wstawic, wstaw ""
List<String> lista = entry.getValue();
if (i == zbiorWartosci.length)
lista.add("");
while (i < zbiorWartosci.length) {
lista.add(zbiorWartosci[i]);
i++;
break;
}
tabela.put(entry.getKey(), lista);
}
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunKolumne(String nazwaKolumny) {
if (znajdzKolumne(nazwaKolumny)) {
// znaleziono
tabela.remove(nazwaKolumny);
return this.tabela;
}
// nie znaleziono -> wyjatek
System.out.println("Nie znaleziono kolumny" + nazwaKolumny);
return this.tabela;
}
// SPRAWNE - nie dotykać
public Map<String, List<String>> usunWartoscZKolumny(String nazwaKolumny, int index) {
boolean znalezionoKolumneOrazCzyNieJestPusta;
try {
znalezionoKolumneOrazCzyNieJestPusta = czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
} catch (Exception e) {
System.out.println(e.getMessage());
znalezionoKolumneOrazCzyNieJestPusta = false;
}
if (znalezionoKolumneOrazCzyNieJestPusta) {
List<String> zawartoscKolumny = tabela.get(nazwaKolumny);
try {
zawartoscKolumny.remove(index);
tabela.put(nazwaKolumny, zawartoscKolumny);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
return this.tabela;
}
public void usunWartosciZKolumn() {
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.clear();
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
public void usunWiersz(String kolumna, String wartosc) throws Exception {
boolean istnieje = sprawdzCzyJuzIstniejeKolumna(kolumna);
if (istnieje == false)
throw new Exception("Nie istnieje taka kolumna " + kolumna);
boolean zawiera = false;
int indexOfValue = 0;
List<String> zawartoscKolumny = tabela.get(kolumna);
for (String string : zawartoscKolumny) {
if (string.equals(wartosc)) {
zawiera = true;
break;
}
indexOfValue++;
}
if (zawiera == true) {
for (Entry<String, List<String>> entry : tabela.entrySet()) {
List<String> nowaZawartoscKolumny = entry.getValue();
nowaZawartoscKolumny.remove(indexOfValue);
tabela.put(entry.getKey(), nowaZawartoscKolumny);
}
}
}
// SPRAWNE - nie dotykać
public void wypiszWszystkieKolumny() {
System.out.println("Wszystkie dostępne kolumny");
Set<String> tabelaKeys = this.tabela.keySet();
System.out.println(tabelaKeys);
}
public void wypiszWszystkieKolumnyWrazZZawaroscia() {
Set<Entry<String, List<String>>> entires = tabela.entrySet();
for (Entry<String, List<String>> ent : entires) {
System.out.println(ent.getKey() + " ==> " + ent.getValue());
}
}
// SPRAWNE - nie dotykać
public void wypiszZawartoscKolumny(String nazwaKolumny) {
try {
czyZnalezionoKolumneOrazCzyNieJestPusta(nazwaKolumny);
// znaleziono i nie jest pusta
List<String> zawartoscKolumny;
zawartoscKolumny = tabela.get(nazwaKolumny);
// zawartoscKolumny;
if (zawartoscKolumny.size() != 0) {
System.out.println("Zawartosc kolumny " + nazwaKolumny + " to:");
for (int i = 0; i < zawartoscKolumny.size(); i++)
System.out.println("Indeks " + i + ": " + zawartoscKolumny.get(i));
} else
System.out.println("Zawartosc kolumny " + nazwaKolumny + " jest pusta!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void wypiszKolumnyZTablicyGdzieKolumnaSpelniaWarunek(String[] zbiorKolumn, String[] warunekKolumnaWartosc) {
// wcale nie robię niezrozumiałych zagnieżdżeń
boolean wypiszWszystkieKolumny = false;
for (String kolumna : zbiorKolumn) {
if (kolumna.equals("*")) {
wypiszWszystkieKolumny = true;
break;
}
}
if (wypiszWszystkieKolumny == true) {
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
// for (String kolumna : zbiorKolumn) {
// kolumny
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// Syste<SUF>
// wypisz wszystkie kolumny, ale tylko rzad gdzie wystapil ten ... warunek
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
}
// }
} else {
// wypisz TYLKO poszczegolne KOLUMNY oraz RZEDY
// lalalalalalaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
String warunekKolumna = warunekKolumnaWartosc[0];
String warunekWartosc = warunekKolumnaWartosc[1];
// poszczegolne kolumny do wypisania
for (String kolumna : zbiorKolumn) {
if (tabela.containsKey(warunekKolumna)) {
// posiada taka kolumne gdzie nalezy sprawdzic warunek
// pobierz zawartosc kolumny
List<String> zawartoscKolumny = tabela.get(warunekKolumna);
int index = 0;
// dopoki nie wyszedles ze ZBIORU WARTOSCI DANEJ KOLUMNY
while (index < zawartoscKolumny.size())
// jezeli kolumna Y posiada wartosc X ( Imie ?= Arkadiusz )
// na miejscu index
if (zawartoscKolumny.get(index).equals(warunekWartosc)) {
// wypisz teraz wszystkie rzedy, wlacznie z nazwami ... kolumn
// Set<Entry<String, List<String>>> entry = tabela.entrySet();
for (Entry<String, List<String>> ent : tabela.entrySet()) {
// System.out.println(ent.getKey() + " ==> " + ent.getValue());
// wypisz WYBRANE kolumny, ale tylko rzad gdzie wystapil ten ... warunek
// lalala.
if (ent.getKey().equals(kolumna))
System.out.println("Kolumna: " + ent.getKey() + " ==> " + ent.getValue().get(index));
}
index++;
}
// index++;
}
}
}
}
// SPRAWNE - nie dotykać
public boolean znajdzKolumne(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
return true;
}
}
return false;
}
// SPRAWNE - nie dotykać
private boolean sprawdzCzyJuzIstniejeKolumna(String nazwaKolumny) {
Set<String> tabelaKeys = this.tabela.keySet();
int counter = 0;
for (String tabelaKey : tabelaKeys) {
if (tabelaKey.compareTo(nazwaKolumny) == 0) {
counter = counter + 1;
}
}
if (counter > 0)
return true; // wystapil duplikat
else
return false; // nie ma duplikatu
}
// SPRAWNE - nie dotykać
private boolean czyZawartoscKolumnyJestPusta(String nazwaKolumny) {
if (tabela.get(nazwaKolumny) == null)
return true;
else
return false;
}
// SPRAWNE - nie dotykać
public boolean czyZnalezionoKolumneOrazCzyNieJestPusta(String nazwaKolumny) throws Exception {
// znaleziono ale jest pusta
if (znajdzKolumne(nazwaKolumny) && czyZawartoscKolumnyJestPusta(nazwaKolumny))
throw new Exception("Zawartosc kolumny " + nazwaKolumny + " jest akutalnie pusta");
// nie znaleziono
if (!znajdzKolumne(nazwaKolumny))
throw new Exception("Nie znaleziono kolumny " + nazwaKolumny);
// znaleziono
return true;
}
} |
199913_35 |
class Customer{
int id,qno,arrivetime,departtime=0,depcountertime,state=0,burgers,leftburgers;
int ht;
Customer left,right;
queue que;
}
class qnode{
int size=0;
int qid;
queue q=new queue();
int qind;
}
class events{
int t=0,priority=0;
Customer c;
int prevburgers=0;
Object info;
}
public class MMBurgers implements MMBurgersInterface {
int M=0,K=0,t=0,prevt=0,currm=0,griddlewaiting=0,delwait=0;
int previd=0;
int totalcustomers=0,totalcustwaittime=0;
minheapwaiting qwait=new minheapwaiting();
minheap h1=new minheap();
Customer [] Custlist=new Customer[100];
// Customer AVLR=new Customer();
// AVL T = new AVL();
qnode [] B=new qnode[1];
// minheap Events=new minheap();
minheapevents E=new minheapevents();
public boolean isEmpty(){
{if(E.sizeh()==0)
return true;}
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
return false;
}
public void setK(int k) throws IllegalNumberException{
if(k<=0) throw new IllegalNumberException("invalid k");
else{
K=k;
qnode [] A=new qnode[K+1];
for(int i=1;i<=K;i++){
qnode t=new qnode();
// if(i==1) t.size=1;
t.qid=i;
h1.inserth(t);
A[i]=t;
// A[i].qid=i;
// System.out.println(h1.sizeh());
// System.out.println(h1.findmin().qid);
}
// System.out.println(h1.sizeh());
// System.out.println(h1.findmin().qid);
B=A;
// System.out.println(A.length);
// h1.buildminheap(B);
// for(int i=1;i<=K;i++) System.out.println(A[i].qid);
}
// System.out.println(qwait.sizeh());
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
}
public void setM(int m) throws IllegalNumberException{
if(m<=0) throw new IllegalNumberException("invalid k");
else{
M=m;
}
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
}
public void advanceTime(int t) throws IllegalNumberException{
if(t<0) throw new IllegalNumberException("");
if(t<prevt) return;
prevt=t;
if(E.sizeh()==0) return;
// System.out.println("E not empty");
events e=E.findmin();
if(e==null) return;
while (e!=null&&e.t<=t){
if(e.priority==1){
// System.out.println(e.c.id+"hi"+"p="+e.priority);
E.deletemin();
B[e.c.qno].q.dequeue(e.c);
B[e.c.qno].size--;
h1.percup(B[e.c.qno].qind, B[e.c.qno]);
// System.out.println(h1.findmin().size);
//h1.percup(i, x);
// qwait.enqueue(e.c);
if(qwait.sizeh()==0){
if(currm<M){
if(M-currm>=e.c.burgers){
currm+=e.c.burgers;
e.prevburgers=e.c.burgers;
e.c.leftburgers=0;
events r=new events();
r.t=e.t+10;
r.priority=2;
r.prevburgers=e.c.burgers;
r.c=e.c;
E.inserth(r);
}
else{
qwait.inserth(e.c);
// System.out.println(e.c.id+"inserted in queue at"+e.t+" "+e.c.leftburgers);
e.c.leftburgers=e.c.burgers-(M-currm);
// System.out.println(e.c.id+"inserted in queue at"+e.t+" "+e.c.leftburgers);
int prevburgers=M-currm;
griddlewaiting+=e.c.leftburgers;
currm=M;
events r=new events();
r.t=e.t+10;
r.priority=3;
r.prevburgers=prevburgers;
r.c=e.c;
E.inserth(r);
}
}
else{
// System.out.println(e.c.id+"inserted in queue at"+e.t+" "+e.c.leftburgers+" qsize=0");
qwait.inserth(e.c);
griddlewaiting+=e.c.burgers;
}
}
else{
// System.out.println(qwait.sizeh()+"qwait size");
// System.out.println(e.c.id+"inserted in queue at"+e.t+" "+e.c.leftburgers+"no pan space");
qwait.inserth(e.c);
griddlewaiting+=e.c.burgers;
}
}
else if(e.priority==2){
// System.out.println(e.c.id+"hi"+"p="+e.priority);
E.deletemin();
//qwait.deletemin();
// System.out.println(currm+" hi");
currm-=e.prevburgers;
// System.out.println(currm+" hi1");
events r=new events();
r.t=e.t+1;
r.priority=5;
r.c=e.c;
E.inserth(r);
if(E.sizeh()==0) return;
events s=E.findmin();
while((s.priority==2||s.priority==3)&&(s.t==e.t)){
// System.out.println(s.c.id+" same time");
E.deletemin();
currm-=s.prevburgers;
//System.out.println(currm+" hi");
if(s.priority==2){
events z=new events();
z.t=e.t+1;
z.priority=5;
z.c=s.c;
E.inserth(z);
}
// E.deletemin();
if(E.sizeh()==0) return;
s=E.findmin();
}
if(currm<M){
while(qwait.sizeh()!=0){
Customer c=qwait.findmin();
// System.out.println(c.id+" qmin");
if(currm<M){
if(M-currm>=c.leftburgers){
qwait.deletemin();
currm+=c.leftburgers;
int prevburgers=c.leftburgers;
griddlewaiting-=c.leftburgers;
c.leftburgers=0;
// System.out.println(c.id+" inserted in E for p=2 at"+e.t+" "+c.leftburgers+" "+currm);
events l=new events();
l.t=e.t+10;
l.priority=2;
l.prevburgers=prevburgers;
l.c=c;
E.inserth(l);
}
else{
// qwait.inserth(e.c);
if(currm<M){
c.leftburgers-=(M-currm);
int prevburgers=M-currm;
griddlewaiting-=M-currm;
currm=M;
// System.out.println(c.id+" inserted in E for p=3 at"+e.t+" "+c.leftburgers);
events l=new events();
l.t=e.t+10;
l.priority=3;
l.prevburgers=prevburgers;
l.c=c;
E.inserth(l);
}
}
}
if(currm==M) break;
}
}
}
else if(e.priority==3){
// System.out.println(e.c.id+"hi"+"p="+e.priority);
// qwait.deletemin();
E.deletemin();
currm-=e.prevburgers;
// System.out.println(currm);
/* events r=new events();
r.t=e.t+1;
r.priority=5;
E.inserth(r);*/
if(E.sizeh()==0) return;
events s=E.findmin();
// System.out.println("Hiiicheck");
while((s.priority==2||s.priority==3)&&(s.t==e.t)){
currm-=s.prevburgers;
if(s.priority==2){
events z=new events();
z.t=e.t+1;
z.priority=5;
z.c=s.c;
E.inserth(z);
}
E.deletemin();
if(E.sizeh()==0) return;
s=E.findmin();
}
if(currm<M){
while(qwait.sizeh()!=0){
Customer c=qwait.findmin();
// if(c.leftburgers==0) continue;
// System.out.println(c.id+" kkk");
if(currm<M){
if(M-currm>=c.leftburgers){
qwait.deletemin();
currm+=c.leftburgers;
int prevburgers=c.leftburgers;
griddlewaiting-=c.leftburgers;
c.leftburgers=0;
// System.out.println(c.id+"insertd in E for p=2 at"+e.t+" "+c.leftburgers);
// griddlewaiting-=c.leftburgers;
events l=new events();
l.t=e.t+10;
l.priority=2;
l.prevburgers=prevburgers;
l.c=c;
E.inserth(l);
}
else{
if(currm!=M){
// qwait.inserth(e.c);
c.leftburgers-=(M-currm);
int prevburgers=M-currm;
griddlewaiting-=M-currm;
currm=M;
// System.out.println(c.id+"insertd in E for p=3 at"+e.t+" "+c.leftburgers);
events l=new events();
l.t=e.t+10;
l.priority=3;
l.prevburgers=prevburgers;
l.c=c;
E.inserth(l);
}
}
}
if(currm==M) break;
}
}
}
else if(e.priority==4){
// System.out.println(e.c.id+"hi"+"p="+e.priority+" "+e.t);
E.deletemin();
// System.out.println(E.sizeh());
qnode w=h1.findmin();
e.c.qno=w.qid;
e.c.que=w.q;
//System.out.println(w.qid);
// System.out.println(e.c.qno+" "+w.qid);
h1.findmin().q.enqueue(e.c);
// h1.findmin().size++;
// System.out.println(h1.findmin().qid);
// System.out.println(h1.findmin().q.front().id);
h1.findmin().size++;
if(h1.findmin().q.front()==e.c){
e.c.depcountertime=t+e.c.qno;
}
else e.c.depcountertime=h1.findmin().q.front().depcountertime+(h1.findmin().size-1)*e.c.qno;
// System.out.println(+e.c.depcountertime+" "+e.c.qno);
// h1.findmin().size++;
h1.percdown(1,h1.findmin());
// System.out.println(h1.findmin().qid);
e. c.state=e.c.qno;
events r=new events();
r.t=e.c.depcountertime;
r.priority=1;
r.c=e.c;
E.inserth(r);
}
else if(e.priority==5){
// System.out.println(e.c.id+"hi"+"p="+e.priority);
E.deletemin();
// System.out.println(e.c.id);
e.c.departtime=e.t;
totalcustwaittime+=e.c.departtime-e.c.arrivetime;
totalcustomers++;
// System.out.println(totalcustomers);
// System.out.println(e.c.arrivetime+" "+e.c.departtime);
}
if(E.sizeh()==0) break;
e=E.findmin();
if(e==null) break;
}
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
}
public void arriveCustomer(int id, int t, int numb) throws IllegalNumberException{
if(id<=0||t<prevt||numb<1||id<=previd) throw new IllegalNumberException("invalid customer");
else{
prevt=t;
Customer c= new Customer();
c.id=id;
c.arrivetime=t;
c.burgers=numb;
c.leftburgers=numb;
if(id>=Custlist.length){
Customer []arr=new Customer[2*Custlist.length];
for(int i=1;i<Custlist.length;i++){
arr[i]=Custlist[i];
}
Custlist=arr;
}
Custlist[id]=c;
previd=id;
// AVLR=T.insert(AVLR,id,c);
events x=new events();
x.t=t;
x.priority=4;
x.c=c;
E.inserth(x);
// System.out.println(E.sizeh());
/* qnode w=h1.findmin();
c.qno=w.qid;
c.que=w.q;
// System.out.println(c.qno);
h1.findmin().q.enqueue(c);
// System.out.println(h1.findmin().qid);
// System.out.println(h1.findmin().q.front().id);
if(h1.findmin().q.front()==c){
c.depcountertime=t+c.qno;
}
else c.depcountertime=t+h1.findmin().q.front().departtime+h1.findmin().q.sizeq()*c.qno;
h1.findmin().size++;
h1.percdown(1,h1.findmin());
c.state=c.qno;
// System.out.println(c.state);
//catch(Exception e){*/
// System.out.println(E.findmin().c.id+" "+E.findmin().priority+" "+E.findmin().t);
advanceTime(t);
// System.out.println(c.depcountertime);
}
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
}
public int customerState(int id, int t) throws IllegalNumberException{
if(id<=0||t<prevt) throw new IllegalNumberException("invalid id");
if( id>previd) return 0;
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
prevt=t;
advanceTime(t);
Customer v=Custlist[id];
// System.out.println(v.id+" "+v.depcountertime);
if(t<v.depcountertime) return v.qno;
if(v.departtime!=0&&t>=v.departtime) {
// System.out.println("hii");
return K+2;}
if(t>=v.depcountertime) return K+1;
// if(t>=v.depcountertime&&t<v.departtime) return K;
return 0;
}
public int griddleState(int t) throws IllegalNumberException{
if(t<prevt) throw new IllegalNumberException("");
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
prevt=t;
advanceTime(t);
return currm;
}
public int griddleWait(int t) throws IllegalNumberException{
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
if(t<0) throw new IllegalNumberException("");
prevt=t;
advanceTime(t);
return griddlewaiting;
}
public int customerWaitTime(int id) throws IllegalNumberException{
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
// System.out.println("hi");
// System.out.println(Custlist[id].depcountertime);
// System.err.println(Custlist[id].departtime+" "+Custlist[id].depcountertime+" "+ Custlist[id].arrivetime);
// System.out.println( (Custlist[id].departtime- Custlist[id].arrivetime));
if(id<0) throw new IllegalNumberException("");
prevt=t;
return (Custlist[id].departtime- Custlist[id].arrivetime);
}
public float avgWaitTime(){
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
float x=(float)totalcustwaittime;
float y=(float)totalcustomers;
// System.out.println(x);
// System.out.println(totalcustomers);
float z=x/y;
// System.out.println(z);
return z;
}
}
| ALKRIS-55/McMAHON-S-BURGERS | MMBurgers.java | 4,907 | // E.deletemin();
| line_comment | nl |
class Customer{
int id,qno,arrivetime,departtime=0,depcountertime,state=0,burgers,leftburgers;
int ht;
Customer left,right;
queue que;
}
class qnode{
int size=0;
int qid;
queue q=new queue();
int qind;
}
class events{
int t=0,priority=0;
Customer c;
int prevburgers=0;
Object info;
}
public class MMBurgers implements MMBurgersInterface {
int M=0,K=0,t=0,prevt=0,currm=0,griddlewaiting=0,delwait=0;
int previd=0;
int totalcustomers=0,totalcustwaittime=0;
minheapwaiting qwait=new minheapwaiting();
minheap h1=new minheap();
Customer [] Custlist=new Customer[100];
// Customer AVLR=new Customer();
// AVL T = new AVL();
qnode [] B=new qnode[1];
// minheap Events=new minheap();
minheapevents E=new minheapevents();
public boolean isEmpty(){
{if(E.sizeh()==0)
return true;}
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
return false;
}
public void setK(int k) throws IllegalNumberException{
if(k<=0) throw new IllegalNumberException("invalid k");
else{
K=k;
qnode [] A=new qnode[K+1];
for(int i=1;i<=K;i++){
qnode t=new qnode();
// if(i==1) t.size=1;
t.qid=i;
h1.inserth(t);
A[i]=t;
// A[i].qid=i;
// System.out.println(h1.sizeh());
// System.out.println(h1.findmin().qid);
}
// System.out.println(h1.sizeh());
// System.out.println(h1.findmin().qid);
B=A;
// System.out.println(A.length);
// h1.buildminheap(B);
// for(int i=1;i<=K;i++) System.out.println(A[i].qid);
}
// System.out.println(qwait.sizeh());
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
}
public void setM(int m) throws IllegalNumberException{
if(m<=0) throw new IllegalNumberException("invalid k");
else{
M=m;
}
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
}
public void advanceTime(int t) throws IllegalNumberException{
if(t<0) throw new IllegalNumberException("");
if(t<prevt) return;
prevt=t;
if(E.sizeh()==0) return;
// System.out.println("E not empty");
events e=E.findmin();
if(e==null) return;
while (e!=null&&e.t<=t){
if(e.priority==1){
// System.out.println(e.c.id+"hi"+"p="+e.priority);
E.deletemin();
B[e.c.qno].q.dequeue(e.c);
B[e.c.qno].size--;
h1.percup(B[e.c.qno].qind, B[e.c.qno]);
// System.out.println(h1.findmin().size);
//h1.percup(i, x);
// qwait.enqueue(e.c);
if(qwait.sizeh()==0){
if(currm<M){
if(M-currm>=e.c.burgers){
currm+=e.c.burgers;
e.prevburgers=e.c.burgers;
e.c.leftburgers=0;
events r=new events();
r.t=e.t+10;
r.priority=2;
r.prevburgers=e.c.burgers;
r.c=e.c;
E.inserth(r);
}
else{
qwait.inserth(e.c);
// System.out.println(e.c.id+"inserted in queue at"+e.t+" "+e.c.leftburgers);
e.c.leftburgers=e.c.burgers-(M-currm);
// System.out.println(e.c.id+"inserted in queue at"+e.t+" "+e.c.leftburgers);
int prevburgers=M-currm;
griddlewaiting+=e.c.leftburgers;
currm=M;
events r=new events();
r.t=e.t+10;
r.priority=3;
r.prevburgers=prevburgers;
r.c=e.c;
E.inserth(r);
}
}
else{
// System.out.println(e.c.id+"inserted in queue at"+e.t+" "+e.c.leftburgers+" qsize=0");
qwait.inserth(e.c);
griddlewaiting+=e.c.burgers;
}
}
else{
// System.out.println(qwait.sizeh()+"qwait size");
// System.out.println(e.c.id+"inserted in queue at"+e.t+" "+e.c.leftburgers+"no pan space");
qwait.inserth(e.c);
griddlewaiting+=e.c.burgers;
}
}
else if(e.priority==2){
// System.out.println(e.c.id+"hi"+"p="+e.priority);
E.deletemin();
//qwait.deletemin();
// System.out.println(currm+" hi");
currm-=e.prevburgers;
// System.out.println(currm+" hi1");
events r=new events();
r.t=e.t+1;
r.priority=5;
r.c=e.c;
E.inserth(r);
if(E.sizeh()==0) return;
events s=E.findmin();
while((s.priority==2||s.priority==3)&&(s.t==e.t)){
// System.out.println(s.c.id+" same time");
E.deletemin();
currm-=s.prevburgers;
//System.out.println(currm+" hi");
if(s.priority==2){
events z=new events();
z.t=e.t+1;
z.priority=5;
z.c=s.c;
E.inserth(z);
}
// E.del<SUF>
if(E.sizeh()==0) return;
s=E.findmin();
}
if(currm<M){
while(qwait.sizeh()!=0){
Customer c=qwait.findmin();
// System.out.println(c.id+" qmin");
if(currm<M){
if(M-currm>=c.leftburgers){
qwait.deletemin();
currm+=c.leftburgers;
int prevburgers=c.leftburgers;
griddlewaiting-=c.leftburgers;
c.leftburgers=0;
// System.out.println(c.id+" inserted in E for p=2 at"+e.t+" "+c.leftburgers+" "+currm);
events l=new events();
l.t=e.t+10;
l.priority=2;
l.prevburgers=prevburgers;
l.c=c;
E.inserth(l);
}
else{
// qwait.inserth(e.c);
if(currm<M){
c.leftburgers-=(M-currm);
int prevburgers=M-currm;
griddlewaiting-=M-currm;
currm=M;
// System.out.println(c.id+" inserted in E for p=3 at"+e.t+" "+c.leftburgers);
events l=new events();
l.t=e.t+10;
l.priority=3;
l.prevburgers=prevburgers;
l.c=c;
E.inserth(l);
}
}
}
if(currm==M) break;
}
}
}
else if(e.priority==3){
// System.out.println(e.c.id+"hi"+"p="+e.priority);
// qwait.deletemin();
E.deletemin();
currm-=e.prevburgers;
// System.out.println(currm);
/* events r=new events();
r.t=e.t+1;
r.priority=5;
E.inserth(r);*/
if(E.sizeh()==0) return;
events s=E.findmin();
// System.out.println("Hiiicheck");
while((s.priority==2||s.priority==3)&&(s.t==e.t)){
currm-=s.prevburgers;
if(s.priority==2){
events z=new events();
z.t=e.t+1;
z.priority=5;
z.c=s.c;
E.inserth(z);
}
E.deletemin();
if(E.sizeh()==0) return;
s=E.findmin();
}
if(currm<M){
while(qwait.sizeh()!=0){
Customer c=qwait.findmin();
// if(c.leftburgers==0) continue;
// System.out.println(c.id+" kkk");
if(currm<M){
if(M-currm>=c.leftburgers){
qwait.deletemin();
currm+=c.leftburgers;
int prevburgers=c.leftburgers;
griddlewaiting-=c.leftburgers;
c.leftburgers=0;
// System.out.println(c.id+"insertd in E for p=2 at"+e.t+" "+c.leftburgers);
// griddlewaiting-=c.leftburgers;
events l=new events();
l.t=e.t+10;
l.priority=2;
l.prevburgers=prevburgers;
l.c=c;
E.inserth(l);
}
else{
if(currm!=M){
// qwait.inserth(e.c);
c.leftburgers-=(M-currm);
int prevburgers=M-currm;
griddlewaiting-=M-currm;
currm=M;
// System.out.println(c.id+"insertd in E for p=3 at"+e.t+" "+c.leftburgers);
events l=new events();
l.t=e.t+10;
l.priority=3;
l.prevburgers=prevburgers;
l.c=c;
E.inserth(l);
}
}
}
if(currm==M) break;
}
}
}
else if(e.priority==4){
// System.out.println(e.c.id+"hi"+"p="+e.priority+" "+e.t);
E.deletemin();
// System.out.println(E.sizeh());
qnode w=h1.findmin();
e.c.qno=w.qid;
e.c.que=w.q;
//System.out.println(w.qid);
// System.out.println(e.c.qno+" "+w.qid);
h1.findmin().q.enqueue(e.c);
// h1.findmin().size++;
// System.out.println(h1.findmin().qid);
// System.out.println(h1.findmin().q.front().id);
h1.findmin().size++;
if(h1.findmin().q.front()==e.c){
e.c.depcountertime=t+e.c.qno;
}
else e.c.depcountertime=h1.findmin().q.front().depcountertime+(h1.findmin().size-1)*e.c.qno;
// System.out.println(+e.c.depcountertime+" "+e.c.qno);
// h1.findmin().size++;
h1.percdown(1,h1.findmin());
// System.out.println(h1.findmin().qid);
e. c.state=e.c.qno;
events r=new events();
r.t=e.c.depcountertime;
r.priority=1;
r.c=e.c;
E.inserth(r);
}
else if(e.priority==5){
// System.out.println(e.c.id+"hi"+"p="+e.priority);
E.deletemin();
// System.out.println(e.c.id);
e.c.departtime=e.t;
totalcustwaittime+=e.c.departtime-e.c.arrivetime;
totalcustomers++;
// System.out.println(totalcustomers);
// System.out.println(e.c.arrivetime+" "+e.c.departtime);
}
if(E.sizeh()==0) break;
e=E.findmin();
if(e==null) break;
}
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
}
public void arriveCustomer(int id, int t, int numb) throws IllegalNumberException{
if(id<=0||t<prevt||numb<1||id<=previd) throw new IllegalNumberException("invalid customer");
else{
prevt=t;
Customer c= new Customer();
c.id=id;
c.arrivetime=t;
c.burgers=numb;
c.leftburgers=numb;
if(id>=Custlist.length){
Customer []arr=new Customer[2*Custlist.length];
for(int i=1;i<Custlist.length;i++){
arr[i]=Custlist[i];
}
Custlist=arr;
}
Custlist[id]=c;
previd=id;
// AVLR=T.insert(AVLR,id,c);
events x=new events();
x.t=t;
x.priority=4;
x.c=c;
E.inserth(x);
// System.out.println(E.sizeh());
/* qnode w=h1.findmin();
c.qno=w.qid;
c.que=w.q;
// System.out.println(c.qno);
h1.findmin().q.enqueue(c);
// System.out.println(h1.findmin().qid);
// System.out.println(h1.findmin().q.front().id);
if(h1.findmin().q.front()==c){
c.depcountertime=t+c.qno;
}
else c.depcountertime=t+h1.findmin().q.front().departtime+h1.findmin().q.sizeq()*c.qno;
h1.findmin().size++;
h1.percdown(1,h1.findmin());
c.state=c.qno;
// System.out.println(c.state);
//catch(Exception e){*/
// System.out.println(E.findmin().c.id+" "+E.findmin().priority+" "+E.findmin().t);
advanceTime(t);
// System.out.println(c.depcountertime);
}
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
}
public int customerState(int id, int t) throws IllegalNumberException{
if(id<=0||t<prevt) throw new IllegalNumberException("invalid id");
if( id>previd) return 0;
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
prevt=t;
advanceTime(t);
Customer v=Custlist[id];
// System.out.println(v.id+" "+v.depcountertime);
if(t<v.depcountertime) return v.qno;
if(v.departtime!=0&&t>=v.departtime) {
// System.out.println("hii");
return K+2;}
if(t>=v.depcountertime) return K+1;
// if(t>=v.depcountertime&&t<v.departtime) return K;
return 0;
}
public int griddleState(int t) throws IllegalNumberException{
if(t<prevt) throw new IllegalNumberException("");
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
prevt=t;
advanceTime(t);
return currm;
}
public int griddleWait(int t) throws IllegalNumberException{
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
if(t<0) throw new IllegalNumberException("");
prevt=t;
advanceTime(t);
return griddlewaiting;
}
public int customerWaitTime(int id) throws IllegalNumberException{
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
// System.out.println("hi");
// System.out.println(Custlist[id].depcountertime);
// System.err.println(Custlist[id].departtime+" "+Custlist[id].depcountertime+" "+ Custlist[id].arrivetime);
// System.out.println( (Custlist[id].departtime- Custlist[id].arrivetime));
if(id<0) throw new IllegalNumberException("");
prevt=t;
return (Custlist[id].departtime- Custlist[id].arrivetime);
}
public float avgWaitTime(){
//your implementation
//throw new java.lang.UnsupportedOperationException("Not implemented yet.");
float x=(float)totalcustwaittime;
float y=(float)totalcustomers;
// System.out.println(x);
// System.out.println(totalcustomers);
float z=x/y;
// System.out.println(z);
return z;
}
}
|
140661_27 | /*
* Copyright (C) 2014 Trillian Mobile AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.robovm.apple.coremedia;
/*<imports>*/
import java.io.*;
import java.nio.*;
import java.util.*;
import org.robovm.objc.*;
import org.robovm.objc.annotation.*;
import org.robovm.objc.block.*;
import org.robovm.rt.*;
import org.robovm.rt.bro.*;
import org.robovm.rt.bro.annotation.*;
import org.robovm.rt.bro.ptr.*;
import org.robovm.apple.foundation.*;
import org.robovm.apple.corefoundation.*;
import org.robovm.apple.dispatch.*;
import org.robovm.apple.coreaudio.*;
import org.robovm.apple.coreanimation.*;
import org.robovm.apple.coregraphics.*;
import org.robovm.apple.corevideo.*;
import org.robovm.apple.audiotoolbox.*;
/*</imports>*/
/*<javadoc>*/
/*</javadoc>*/
/*<annotations>*/@Library("CoreMedia")/*</annotations>*/
/*<visibility>*/public/*</visibility>*/ class /*<name>*/CMTimeRange/*</name>*/
extends /*<extends>*/Struct<CMTimeRange>/*</extends>*/
/*<implements>*//*</implements>*/ {
public static class AsValuedListMarshaler {
@SuppressWarnings("unchecked")
@MarshalsPointer
public static List<CMTimeRange> toObject(Class<? extends NSObject> cls, long handle, long flags) {
NSArray<NSValue> o = (NSArray<NSValue>) NSObject.Marshaler.toObject(cls, handle, flags);
if (o == null) {
return null;
}
List<CMTimeRange> list = new ArrayList<>();
for (NSValue v : o) {
list.add(v.timeRangeValue());
}
return list;
}
@MarshalsPointer
public static long toNative(List<CMTimeRange> l, long flags) {
if (l == null) {
return 0L;
}
NSMutableArray<NSValue> array = new NSMutableArray<>();
for (CMTimeRange i : l) {
array.add(NSValue.valueOf(i));
}
return NSObject.Marshaler.toNative(array, flags);
}
}
/*<ptr>*/public static class CMTimeRangePtr extends Ptr<CMTimeRange, CMTimeRangePtr> {}/*</ptr>*/
/*<bind>*/static { Bro.bind(CMTimeRange.class); }/*</bind>*/
/*<constants>*//*</constants>*/
/*<constructors>*/
public CMTimeRange() {}
public CMTimeRange(CMTime start, CMTime duration) {
this.setStart(start);
this.setDuration(duration);
}
/*</constructors>*/
/*<properties>*//*</properties>*/
/*<members>*/
@StructMember(0) public native @ByVal CMTime getStart();
@StructMember(0) public native CMTimeRange setStart(@ByVal CMTime start);
@StructMember(1) public native @ByVal CMTime getDuration();
@StructMember(1) public native CMTimeRange setDuration(@ByVal CMTime duration);
/*</members>*/
@Override
public String toString() {
return getDescription(null, this);
}
/*<methods>*/
/**
* @since Available in iOS 4.0 and later.
*/
@GlobalValue(symbol="kCMTimeRangeZero", optional=true)
public static native @ByVal CMTimeRange Zero();
/**
* @since Available in iOS 4.0 and later.
*/
@GlobalValue(symbol="kCMTimeRangeInvalid", optional=true)
public static native @ByVal CMTimeRange Invalid();
/**
* @since Available in iOS 4.0 and later.
*/
@Bridge(symbol="CMTimeRangeMake", optional=true)
public static native @ByVal CMTimeRange create(@ByVal CMTime start, @ByVal CMTime duration);
/**
* @since Available in iOS 4.0 and later.
*/
public CMTimeRange union(CMTimeRange range2) { return union(this, range2); }
@Bridge(symbol="CMTimeRangeGetUnion", optional=true)
private static native @ByVal CMTimeRange union(@ByVal CMTimeRange range1, @ByVal CMTimeRange range2);
/**
* @since Available in iOS 4.0 and later.
*/
public CMTimeRange intersection(CMTimeRange range2) { return intersection(this, range2); }
@Bridge(symbol="CMTimeRangeGetIntersection", optional=true)
private static native @ByVal CMTimeRange intersection(@ByVal CMTimeRange range1, @ByVal CMTimeRange range2);
/**
* @since Available in iOS 4.0 and later.
*/
public boolean equals(CMTimeRange range2) { return equals(this, range2); }
@Bridge(symbol="CMTimeRangeEqual", optional=true)
private static native boolean equals(@ByVal CMTimeRange range1, @ByVal CMTimeRange range2);
/**
* @since Available in iOS 4.0 and later.
*/
public boolean containsTime(CMTime time) { return containsTime(this, time); }
@Bridge(symbol="CMTimeRangeContainsTime", optional=true)
private static native boolean containsTime(@ByVal CMTimeRange range, @ByVal CMTime time);
/**
* @since Available in iOS 4.0 and later.
*/
public boolean containsTimeRange(CMTimeRange range2) { return containsTimeRange(this, range2); }
@Bridge(symbol="CMTimeRangeContainsTimeRange", optional=true)
private static native boolean containsTimeRange(@ByVal CMTimeRange range1, @ByVal CMTimeRange range2);
/**
* @since Available in iOS 4.0 and later.
*/
public CMTime getEnd() { return getEnd(this); }
@Bridge(symbol="CMTimeRangeGetEnd", optional=true)
private static native @ByVal CMTime getEnd(@ByVal CMTimeRange range);
/**
* @since Available in iOS 4.0 and later.
*/
@Bridge(symbol="CMTimeRangeFromTimeToTime", optional=true)
public static native @ByVal CMTimeRange fromTimeToTime(@ByVal CMTime start, @ByVal CMTime end);
/**
* @since Available in iOS 4.0 and later.
*/
public NSDictionary<?, ?> asDictionary(CFAllocator allocator) { return asDictionary(this, allocator); }
@Bridge(symbol="CMTimeRangeCopyAsDictionary", optional=true)
private static native NSDictionary<?, ?> asDictionary(@ByVal CMTimeRange range, CFAllocator allocator);
/**
* @since Available in iOS 4.0 and later.
*/
@Bridge(symbol="CMTimeRangeMakeFromDictionary", optional=true)
public static native @ByVal CMTimeRange create(NSDictionary<?, ?> dict);
/**
* @since Available in iOS 4.0 and later.
*/
@Bridge(symbol="CMTimeRangeCopyDescription", optional=true)
private static native String getDescription(CFAllocator allocator, @ByVal CMTimeRange range);
/**
* @since Available in iOS 4.0 and later.
*/
public void show() { show(this); }
@Bridge(symbol="CMTimeRangeShow", optional=true)
private static native void show(@ByVal CMTimeRange range);
/*</methods>*/
}
| AMONCHO/robovm | cocoatouch/src/main/java/org/robovm/apple/coremedia/CMTimeRange.java | 1,972 | /*<methods>*/ | block_comment | nl | /*
* Copyright (C) 2014 Trillian Mobile AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.robovm.apple.coremedia;
/*<imports>*/
import java.io.*;
import java.nio.*;
import java.util.*;
import org.robovm.objc.*;
import org.robovm.objc.annotation.*;
import org.robovm.objc.block.*;
import org.robovm.rt.*;
import org.robovm.rt.bro.*;
import org.robovm.rt.bro.annotation.*;
import org.robovm.rt.bro.ptr.*;
import org.robovm.apple.foundation.*;
import org.robovm.apple.corefoundation.*;
import org.robovm.apple.dispatch.*;
import org.robovm.apple.coreaudio.*;
import org.robovm.apple.coreanimation.*;
import org.robovm.apple.coregraphics.*;
import org.robovm.apple.corevideo.*;
import org.robovm.apple.audiotoolbox.*;
/*</imports>*/
/*<javadoc>*/
/*</javadoc>*/
/*<annotations>*/@Library("CoreMedia")/*</annotations>*/
/*<visibility>*/public/*</visibility>*/ class /*<name>*/CMTimeRange/*</name>*/
extends /*<extends>*/Struct<CMTimeRange>/*</extends>*/
/*<implements>*//*</implements>*/ {
public static class AsValuedListMarshaler {
@SuppressWarnings("unchecked")
@MarshalsPointer
public static List<CMTimeRange> toObject(Class<? extends NSObject> cls, long handle, long flags) {
NSArray<NSValue> o = (NSArray<NSValue>) NSObject.Marshaler.toObject(cls, handle, flags);
if (o == null) {
return null;
}
List<CMTimeRange> list = new ArrayList<>();
for (NSValue v : o) {
list.add(v.timeRangeValue());
}
return list;
}
@MarshalsPointer
public static long toNative(List<CMTimeRange> l, long flags) {
if (l == null) {
return 0L;
}
NSMutableArray<NSValue> array = new NSMutableArray<>();
for (CMTimeRange i : l) {
array.add(NSValue.valueOf(i));
}
return NSObject.Marshaler.toNative(array, flags);
}
}
/*<ptr>*/public static class CMTimeRangePtr extends Ptr<CMTimeRange, CMTimeRangePtr> {}/*</ptr>*/
/*<bind>*/static { Bro.bind(CMTimeRange.class); }/*</bind>*/
/*<constants>*//*</constants>*/
/*<constructors>*/
public CMTimeRange() {}
public CMTimeRange(CMTime start, CMTime duration) {
this.setStart(start);
this.setDuration(duration);
}
/*</constructors>*/
/*<properties>*//*</properties>*/
/*<members>*/
@StructMember(0) public native @ByVal CMTime getStart();
@StructMember(0) public native CMTimeRange setStart(@ByVal CMTime start);
@StructMember(1) public native @ByVal CMTime getDuration();
@StructMember(1) public native CMTimeRange setDuration(@ByVal CMTime duration);
/*</members>*/
@Override
public String toString() {
return getDescription(null, this);
}
/*<metho<SUF>*/
/**
* @since Available in iOS 4.0 and later.
*/
@GlobalValue(symbol="kCMTimeRangeZero", optional=true)
public static native @ByVal CMTimeRange Zero();
/**
* @since Available in iOS 4.0 and later.
*/
@GlobalValue(symbol="kCMTimeRangeInvalid", optional=true)
public static native @ByVal CMTimeRange Invalid();
/**
* @since Available in iOS 4.0 and later.
*/
@Bridge(symbol="CMTimeRangeMake", optional=true)
public static native @ByVal CMTimeRange create(@ByVal CMTime start, @ByVal CMTime duration);
/**
* @since Available in iOS 4.0 and later.
*/
public CMTimeRange union(CMTimeRange range2) { return union(this, range2); }
@Bridge(symbol="CMTimeRangeGetUnion", optional=true)
private static native @ByVal CMTimeRange union(@ByVal CMTimeRange range1, @ByVal CMTimeRange range2);
/**
* @since Available in iOS 4.0 and later.
*/
public CMTimeRange intersection(CMTimeRange range2) { return intersection(this, range2); }
@Bridge(symbol="CMTimeRangeGetIntersection", optional=true)
private static native @ByVal CMTimeRange intersection(@ByVal CMTimeRange range1, @ByVal CMTimeRange range2);
/**
* @since Available in iOS 4.0 and later.
*/
public boolean equals(CMTimeRange range2) { return equals(this, range2); }
@Bridge(symbol="CMTimeRangeEqual", optional=true)
private static native boolean equals(@ByVal CMTimeRange range1, @ByVal CMTimeRange range2);
/**
* @since Available in iOS 4.0 and later.
*/
public boolean containsTime(CMTime time) { return containsTime(this, time); }
@Bridge(symbol="CMTimeRangeContainsTime", optional=true)
private static native boolean containsTime(@ByVal CMTimeRange range, @ByVal CMTime time);
/**
* @since Available in iOS 4.0 and later.
*/
public boolean containsTimeRange(CMTimeRange range2) { return containsTimeRange(this, range2); }
@Bridge(symbol="CMTimeRangeContainsTimeRange", optional=true)
private static native boolean containsTimeRange(@ByVal CMTimeRange range1, @ByVal CMTimeRange range2);
/**
* @since Available in iOS 4.0 and later.
*/
public CMTime getEnd() { return getEnd(this); }
@Bridge(symbol="CMTimeRangeGetEnd", optional=true)
private static native @ByVal CMTime getEnd(@ByVal CMTimeRange range);
/**
* @since Available in iOS 4.0 and later.
*/
@Bridge(symbol="CMTimeRangeFromTimeToTime", optional=true)
public static native @ByVal CMTimeRange fromTimeToTime(@ByVal CMTime start, @ByVal CMTime end);
/**
* @since Available in iOS 4.0 and later.
*/
public NSDictionary<?, ?> asDictionary(CFAllocator allocator) { return asDictionary(this, allocator); }
@Bridge(symbol="CMTimeRangeCopyAsDictionary", optional=true)
private static native NSDictionary<?, ?> asDictionary(@ByVal CMTimeRange range, CFAllocator allocator);
/**
* @since Available in iOS 4.0 and later.
*/
@Bridge(symbol="CMTimeRangeMakeFromDictionary", optional=true)
public static native @ByVal CMTimeRange create(NSDictionary<?, ?> dict);
/**
* @since Available in iOS 4.0 and later.
*/
@Bridge(symbol="CMTimeRangeCopyDescription", optional=true)
private static native String getDescription(CFAllocator allocator, @ByVal CMTimeRange range);
/**
* @since Available in iOS 4.0 and later.
*/
public void show() { show(this); }
@Bridge(symbol="CMTimeRangeShow", optional=true)
private static native void show(@ByVal CMTimeRange range);
/*</methods>*/
}
|
200238_33 | /**
* Copyright (c) 2010-2013, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
//in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
//in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
//in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in german Massentrom
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
};
/** Represents the heatpump command as it will be used in *.items configuration */
String command;
Class<? extends Item> itemClass;
public String getCommand() {
return command;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
*
* @param bindingConfig command string e.g. state, temperature_solar_storage,..
* @param itemClass class to validate
* @return true if item class can bound to heatpumpCommand
*/
public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) {
boolean ret = false;
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(bindingConfig.getCommand())
&& c.getItemClass().equals(itemClass)) {
ret = true;
break;
}
}
return ret;
}
public static HeatpumpCommandType fromString(String heatpumpCommand) {
if ("".equals(heatpumpCommand)) {
return null;
}
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(heatpumpCommand)) {
return c;
}
}
throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '"
+ heatpumpCommand + "'");
}
} | ANierbeck/openhab | bundles/binding/org.openhab.binding.novelanheatpump/src/main/java/org/openhab/binding/novelanheatpump/HeatpumpCommandType.java | 2,279 | // in german Massentrom | line_comment | nl | /**
* Copyright (c) 2010-2013, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.novelanheatpump;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
/**
* Represents all valid commands which could be processed by this binding
*
* @author Jan-Philipp Bolle
* @since 1.0.0
*/
public enum HeatpumpCommandType {
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE {
{
command = "temperature_outside";
itemClass = NumberItem.class;
}
},
//in german Außentemperatur
TYPE_TEMPERATURE_OUTSIDE_AVG {
{
command = "temperature_outside_avg";
itemClass = NumberItem.class;
}
},
//in german Rücklauf
TYPE_TEMPERATURE_RETURN {
{
command = "temperature_return";
itemClass = NumberItem.class;
}
},
//in german Rücklauf Soll
TYPE_TEMPERATURE_REFERENCE_RETURN {
{
command = "temperature_reference_return";
itemClass = NumberItem.class;
}
},
//in german Vorlauf
TYPE_TEMPERATURE_SUPPLAY {
{
command = "temperature_supplay";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Soll
TYPE_TEMPERATURE_SERVICEWATER_REFERENCE {
{
command = "temperature_servicewater_reference";
itemClass = NumberItem.class;
}
},
// in german Brauchwasser Ist
TYPE_TEMPERATURE_SERVICEWATER {
{
command = "temperature_servicewater";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_STATE {
{
command = "state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_EXTENDED_STATE {
{
command = "extended_state";
itemClass = StringItem.class;
}
},
TYPE_HEATPUMP_SOLAR_COLLECTOR {
{
command = "temperature_solar_collector";
itemClass = NumberItem.class;
}
},
// in german Temperatur Heissgas
TYPE_TEMPERATURE_HOT_GAS {
{
command = "temperature_hot_gas";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Eingang
TYPE_TEMPERATURE_PROBE_IN {
{
command = "temperature_probe_in";
itemClass = NumberItem.class;
}
},
// in german Sondentemperatur WP Ausgang
TYPE_TEMPERATURE_PROBE_OUT {
{
command = "temperature_probe_out";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK1 {
{
command = "temperature_mk1";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK1_REFERENCE {
{
command = "temperature_mk1_reference";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 IST
TYPE_TEMPERATURE_MK2 {
{
command = "temperature_mk2";
itemClass = NumberItem.class;
}
},
// in german Vorlauftemperatur MK1 SOLL
TYPE_TEMPERATURE_MK2_REFERENCE {
{
command = "temperature_mk2_reference";
itemClass = NumberItem.class;
}
},
// in german Temperatur externe Energiequelle
TYPE_TEMPERATURE_EXTERNAL_SOURCE {
{
command = "temperature_external_source";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter1
TYPE_HOURS_COMPRESSOR1 {
{
command = "hours_compressor1";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 1
TYPE_STARTS_COMPRESSOR1 {
{
command = "starts_compressor1";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden Verdichter2
TYPE_HOURS_COMPRESSOR2 {
{
command = "hours_compressor2";
itemClass = StringItem.class;
}
},
// in german Impulse (Starts) Verdichter 2
TYPE_STARTS_COMPRESSOR2 {
{
command = "starts_compressor2";
itemClass = NumberItem.class;
}
},
// Temperatur_TRL_ext
TYPE_TEMPERATURE_OUT_EXTERNAL {
{
command = "temperature_out_external";
itemClass = NumberItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE1 {
{
command = "hours_zwe1";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE2 {
{
command = "hours_zwe2";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden ZWE1
TYPE_HOURS_ZWE3 {
{
command = "hours_zwe3";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Wärmepumpe
TYPE_HOURS_HETPUMP {
{
command = "hours_heatpump";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Heizung
TYPE_HOURS_HEATING {
{
command = "hours_heating";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_WARMWATER {
{
command = "hours_warmwater";
itemClass = StringItem.class;
}
},
// in german Betriebsstunden Brauchwasser
TYPE_HOURS_COOLING {
{
command = "hours_cooling";
itemClass = StringItem.class;
}
},
// in german Waermemenge Heizung
TYPE_THERMALENERGY_HEATING {
{
command = "thermalenergy_heating";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Brauchwasser
TYPE_THERMALENERGY_WARMWATER {
{
command = "thermalenergy_warmwater";
itemClass = NumberItem.class;
}
},
// in german Waermemenge Schwimmbad
TYPE_THERMALENERGY_POOL {
{
command = "thermalenergy_pool";
itemClass = NumberItem.class;
}
},
// in german Waermemenge gesamt seit Reset
TYPE_THERMALENERGY_TOTAL {
{
command = "thermalenergy_total";
itemClass = NumberItem.class;
}
},
// in ge<SUF>
TYPE_MASSFLOW {
{
command = "massflow";
itemClass = NumberItem.class;
}
},
TYPE_HEATPUMP_SOLAR_STORAGE {
{
command = "temperature_solar_storage";
itemClass = NumberItem.class;
}
};
/** Represents the heatpump command as it will be used in *.items configuration */
String command;
Class<? extends Item> itemClass;
public String getCommand() {
return command;
}
public Class<? extends Item> getItemClass() {
return itemClass;
}
/**
*
* @param bindingConfig command string e.g. state, temperature_solar_storage,..
* @param itemClass class to validate
* @return true if item class can bound to heatpumpCommand
*/
public static boolean validateBinding(HeatpumpCommandType bindingConfig, Class<? extends Item> itemClass) {
boolean ret = false;
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(bindingConfig.getCommand())
&& c.getItemClass().equals(itemClass)) {
ret = true;
break;
}
}
return ret;
}
public static HeatpumpCommandType fromString(String heatpumpCommand) {
if ("".equals(heatpumpCommand)) {
return null;
}
for (HeatpumpCommandType c : HeatpumpCommandType.values()) {
if (c.getCommand().equals(heatpumpCommand)) {
return c;
}
}
throw new IllegalArgumentException("cannot find novelanHeatpumpCommand for '"
+ heatpumpCommand + "'");
}
} |
78594_26 | package cloudapplications.citycheck.Activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import cloudapplications.citycheck.APIService.NetworkManager;
import cloudapplications.citycheck.APIService.NetworkResponseListener;
import cloudapplications.citycheck.Goals;
import cloudapplications.citycheck.IntersectCalculator;
import cloudapplications.citycheck.Models.Antwoord;
import cloudapplications.citycheck.Models.GameDoel;
import cloudapplications.citycheck.Models.Locatie;
import cloudapplications.citycheck.Models.StringReturn;
import cloudapplications.citycheck.Models.Team;
import cloudapplications.citycheck.Models.Vraag;
import cloudapplications.citycheck.MyTeam;
import cloudapplications.citycheck.OtherTeams;
import cloudapplications.citycheck.R;
public class GameActivity extends FragmentActivity implements OnMapReadyCallback {
// Kaart vars
private GoogleMap kaart;
private MyTeam myTeam;
private OtherTeams otherTeams;
private Goals goals;
private NetworkManager service;
private IntersectCalculator calc;
private FloatingActionButton myLocation;
// Variabelen om teams
private TextView teamNameTextView;
private TextView scoreTextView;
private String teamNaam;
private int gamecode;
private int score;
// Vragen beantwoorden
private String[] antwoorden;
private String vraag;
private int correctAntwoordIndex;
private int gekozenAntwoordIndex;
private boolean isClaiming;
// Timer vars
private TextView timerTextView;
private ProgressBar timerProgressBar;
private int progress;
//screen time out
private int defTimeOut=0;
// Afstand
private float[] afstandResult;
private float treshHoldAfstand = 50; //(meter)
// Geluiden
private MediaPlayer mpTrace;
private MediaPlayer mpClaimed;
private MediaPlayer mpBonusCorrect;
private MediaPlayer mpBonusWrong;
private MediaPlayer mpGameStarted;
// Callbacks
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
Objects.requireNonNull(mapFragment).getMapAsync(this);
calc = new IntersectCalculator();
service = NetworkManager.getInstance();
gamecode = Integer.parseInt(Objects.requireNonNull(Objects.requireNonNull(getIntent().getExtras()).getString("gameCode")));
// AfstandTreshold
treshHoldAfstand = 15; //(meter)
// Claiming naar false
isClaiming = false;
//myLocation
myLocation = findViewById(R.id.myLoc);
//txt views
teamNameTextView = findViewById(R.id.text_view_team_name);
timerTextView = findViewById(R.id.text_view_timer);
timerProgressBar = findViewById(R.id.progress_bar_timer);
teamNaam = getIntent().getExtras().getString("teamNaam");
teamNameTextView.setText(teamNaam);
gameTimer();
// Een vraag stellen als ik op de naam klik (Dit is tijdelijk om een vraag toch te kunnen tonen)
teamNameTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
claimLocatie(1, 1);
}
});
myLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(myTeam.newLocation != null){
LatLng positie = new LatLng(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude());
kaart.moveCamera(CameraUpdateFactory.newLatLng(positie));
}
}
});
// Score
scoreTextView = findViewById(R.id.text_view_points);
score = 0;
setScore(30);
// Geluiden
mpTrace = MediaPlayer.create(this, R.raw.trace_crossed);
mpClaimed = MediaPlayer.create(this, R.raw.claimed);
mpBonusCorrect = MediaPlayer.create(this, R.raw.bonus_correct);
mpBonusWrong = MediaPlayer.create(this, R.raw.bonus_wrong);
mpGameStarted = MediaPlayer.create(this, R.raw.game_started);
mpGameStarted.start();
ImageView pointsImageView = findViewById(R.id.image_view_points);
pointsImageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
endGame();
return false;
}
});
}
@Override
protected void onResume() {
super.onResume();
if (myTeam != null)
myTeam.StartConnection();
}
@Override
public void onMapReady(GoogleMap googleMap) {
kaart = googleMap;
kaart.getUiSettings().setMapToolbarEnabled(false);
// Alles ivm locatie van het eigen team
myTeam = new MyTeam(this, kaart, gamecode, teamNaam);
myTeam.StartConnection();
// Move the camera to Antwerp
LatLng Antwerpen = new LatLng(51.2194, 4.4025);
kaart.moveCamera(CameraUpdateFactory.newLatLngZoom(Antwerpen, 15));
// Locaties van andere teams
otherTeams = new OtherTeams(gamecode, teamNaam, kaart, GameActivity.this);
otherTeams.GetTeamsOnMap();
// Alles ivm doellocaties
goals = new Goals(gamecode, kaart, GameActivity.this);
}
@Override
public void onBackPressed() {
}
// Private helper methoden
/*
private void showDoelLocaties(List<DoelLocation> newDoelLocaties) {
// Place a marker on the locations
for (int i = 0; i < newDoelLocaties.size(); i++) {
DoelLocation doellocatie = newDoelLocaties.get(i);
LatLng Locatie = new LatLng(doellocatie.getLocatie().getLat(), doellocatie.getLocatie().getLong());
kaart.addMarker(new MarkerOptions().position(Locatie).title("Naam locatie").snippet("500").icon(BitmapDescriptorFactory.fromResource(R.drawable.coin_small)));
}
}
*/
private void everythingThatNeedsToHappenEvery3s(long verstrekentijd) {
int tijd = (int) (verstrekentijd / 1000);
if (tijd % 3 == 0) {
goals.RemoveCaimedLocations();
if (myTeam.newLocation != null) {
myTeam.HandleNewLocation(new Locatie(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude()), tijd);
calculateIntersect();
}
otherTeams.GetTeamsOnMap();
}
// Controleren op doellocatie triggers om te kunnen claimen
// Huidige locaties van de doelen ophalen
if (goals.currentGoals != null && myTeam.Traces.size() > 0 && !isClaiming) {
Locatie loc1 = goals.currentGoals.get(0).getDoel().getLocatie();
Locatie loc2 = goals.currentGoals.get(1).getDoel().getLocatie();
Locatie loc3 = goals.currentGoals.get(2).getDoel().getLocatie();
Locatie[] locs = {loc1, loc2, loc3};
// Mijn huidige locatie ophalen
int tempTraceSize = myTeam.Traces.size();
double tempLat = myTeam.Traces.get(tempTraceSize - 1).getLat();
double tempLong = myTeam.Traces.get(tempTraceSize - 1).getLong();
// Kijken of er een hit is met een locatie
int tempIndex = 0;
for (Locatie loc : locs) {
berekenAfstand(loc, tempLat, tempLong, goals.currentGoals.get(tempIndex));
tempIndex++;
}
}
}
private void berekenAfstand(Locatie doelLoc, double tempLat, double tempLong, GameDoel goal) {
afstandResult = new float[1];
Location.distanceBetween(doelLoc.getLat(), doelLoc.getLong(), tempLat, tempLong, afstandResult);
if (afstandResult[0] < treshHoldAfstand && !goal.getClaimed()) {
// GameDoelID en doellocID ophalen
int GD = goal.getId();
int LC = goal.getDoel().getId();
// Locatie claim triggeren
claimLocatie(GD, LC);
goal.setClaimed(true);
// Claimen instellen zolang we bezig zijn met claimen
isClaiming = true;
//Claim medelen via toast
Toast.makeText(GameActivity.this, "Locatie Geclaimed: " + goal.getDoel().getTitel(), Toast.LENGTH_LONG).show();
}
}
private void setMultiChoice(final String[] antwoorden, int CorrectIndex, String vraag) {
// Alertdialog aanmaken
AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this);
// Single choice dialog met de antwoorden
builder.setSingleChoiceItems(antwoorden, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Notify the current action
Toast.makeText(GameActivity.this, "Antwoord: " + antwoorden[i], Toast.LENGTH_LONG).show();
gekozenAntwoordIndex = i;
}
});
// Specify the dialog is not cancelable
builder.setCancelable(true);
// Set a title for alert dialog
builder.setTitle(vraag);
// Set the positive/yes button click listener
builder.setPositiveButton("Kies!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do something when click positive button
// Toast.makeText(GameActivity.this, "data: "+gekozenAntwoordIndex, Toast.LENGTH_LONG).show();
// Antwoord controleren
checkAnswer(gekozenAntwoordIndex, correctAntwoordIndex);
}
});
AlertDialog dialog = builder.create();
// Display the alert dialog on interface
dialog.show();
}
private void checkAnswer(int gekozenInd, int correctInd) {
// Klopt de gekozen index met het correcte antwoord index
if (gekozenInd == correctInd) {
mpBonusCorrect.start();
Toast.makeText(GameActivity.this, "Correct!", Toast.LENGTH_LONG).show();
// X aantal punten toevoegen bij de gebruiker
// Nieuwe score tonen en doorpushen naar de db
setScore(20);
isClaiming = false;
} else {
mpBonusWrong.start();
Toast.makeText(GameActivity.this, "Helaas!", Toast.LENGTH_LONG).show();
setScore(5);
isClaiming = false;
}
}
private void setScore(int newScore) {
score += newScore;
scoreTextView.setText(String.valueOf(score));
service.setTeamScore(gamecode, teamNaam, score, new NetworkResponseListener<Integer>() {
@Override
public void onResponseReceived(Integer score) {
// Score ok
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to set the new score", Toast.LENGTH_SHORT).show();
}
});
}
private void claimLocatie(final int locId, final int doellocID) {
mpClaimed.start();
// locid => gamelocaties ID, doellocID => id van de daadwerkelijke doellocatie
// Een team een locatie laten claimen als ze op deze plek zijn.
service.claimDoelLocatie(gamecode, locId, new NetworkResponseListener<StringReturn>() {
@Override
public void onResponseReceived(StringReturn rtrn) {
//response verwerken
try {
String waarde = rtrn.getWaarde();
Toast.makeText(GameActivity.this, waarde, Toast.LENGTH_SHORT).show();
} catch (Throwable err) {
Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show();
}
});
// Dialog tonen met de vraag claim of bonus vraag
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Claimen of bonus vraag(risico) oplossen?")
// Niet cancel-baar
.setCancelable(false)
.setPositiveButton("Claim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mpBonusCorrect.start();
// De location alleen claimen zonder bonusvraag
setScore(10);
isClaiming = false;
}
})
.setNegativeButton("Bonus vraag", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Random vraag bij deze locatie ophalen uit de backend
service.getDoelLocatieVraag(doellocID, new NetworkResponseListener<Vraag>() {
@Override
public void onResponseReceived(Vraag newVraag) {
// Response verwerken
// Vraagtitel bewaren
vraag = newVraag.getVraagZin();
//3 Antwoorden bewaren
ArrayList<Antwoord> allAnswers = newVraag.getAntwoorden();
antwoorden = new String[3];
for (int i = 0; i < 3; i++) {
antwoorden[i] = allAnswers.get(i).getAntwoordzin();
if (allAnswers.get(i).isCorrectBool()) {
correctAntwoordIndex = i;
}
}
//Vraag stellen
askQuestion();
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to get the question", Toast.LENGTH_SHORT).show();
}
});
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void askQuestion() {
// Instellen van een vraag en deze stellen + controleren
// Vraag tonen
setMultiChoice(antwoorden, correctAntwoordIndex, vraag);
}
private void gameTimer() {
String chosenGameTime = Objects.requireNonNull(getIntent().getExtras()).getString("gameTime");
long millisStarted = Long.parseLong(Objects.requireNonNull(getIntent().getExtras().getString("millisStarted")));
int gameTimeInMillis = Integer.parseInt(Objects.requireNonNull(chosenGameTime)) * 3600000;
// Het verschil tussen de tijd van nu en de tijd van wanneer de game is gestart
long differenceFromMillisStarted = System.currentTimeMillis() - millisStarted;
// Hoe lang dat de timer moet doorlopen
long timerMillis = gameTimeInMillis - differenceFromMillisStarted;
//screen time out
try{
if(Settings.System.canWrite(this)){
defTimeOut = Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 0);
android.provider.Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, (int)timerMillis);
}
} catch (NoSuchMethodError err){
err.printStackTrace();
}
// De progress begint op de juiste plek, dus niet altijd vanaf 0
progress = (int) ((gameTimeInMillis - timerMillis) / 1000);
timerProgressBar.setProgress(progress);
if (timerMillis > 0) {
final int finalGameTimeInMillis = gameTimeInMillis;
new CountDownTimer(timerMillis, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60;
int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
timerTextView.setText("Time remaining: " + hours + ":" + minutes + ":" + seconds);
everythingThatNeedsToHappenEvery3s(finalGameTimeInMillis - millisUntilFinished);
getNewGoalsAfterInterval((finalGameTimeInMillis - millisUntilFinished), 900);
progress++;
timerProgressBar.setProgress(progress * 100 / (finalGameTimeInMillis / 1000));
}
public void onFinish() {
progress++;
timerProgressBar.setProgress(100);
endGame();
}
}.start();
} else {
endGame();
}
}
private void endGame() {
try{
if(Settings.System.canWrite(this)) {
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut);
}
} catch (NoSuchMethodError err) {
err.printStackTrace();
}
Intent i = new Intent(GameActivity.this, EndGameActivity.class);
if (myTeam != null)
myTeam.StopConnection();
if (Objects.requireNonNull(getIntent().getExtras()).getBoolean("gameCreator"))
i.putExtra("gameCreator", true);
else
i.putExtra("gameCreator", false);
i.putExtra("gameCode", Integer.toString(gamecode));
startActivity(i);
}
private void calculateIntersect() {
if (myTeam.Traces.size() > 2) {
service.getAllTeamTraces(gamecode, new NetworkResponseListener<List<Team>>() {
@Override
public void onResponseReceived(List<Team> teams) {
if(myTeam.Traces.size() > 2) {
Locatie start = myTeam.Traces.get(myTeam.Traces.size() - 2);
Locatie einde = myTeam.Traces.get(myTeam.Traces.size() - 1);
for (Team team : teams) {
if (!team.getTeamNaam().equals(teamNaam)) {
Log.d("intersect", "size: " + team.getTeamTrace().size());
for (int i = 0; i < team.getTeamTrace().size(); i++) {
if ((i + 1) < team.getTeamTrace().size()) {
if (calc.doLineSegmentsIntersect(start, einde, team.getTeamTrace().get(i).getLocatie(), team.getTeamTrace().get(i + 1).getLocatie())) {
mpTrace.start();
Log.d("intersect", team.getTeamNaam() + " kruist");
setScore(-5);
Toast.makeText(GameActivity.this, "Oh oohw you crossed another team's path, bye bye 5 points", Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Er ging iets mis bij het opvragen van de teamtraces", Toast.LENGTH_SHORT);
}
});
}
}
private void getNewGoalsAfterInterval(Long verstrekenTijd, int interval) {
int tijd = (int) (verstrekenTijd / 1000);
// interval meegeven in seconden
goals.GetNewGoals(tijd, interval);
//traces op map clearen bij elk interval
if (tijd % interval == 0) {
service.deleteTeamtraces(gamecode, new NetworkResponseListener<Boolean>() {
@Override
public void onResponseReceived(Boolean cleared) {
Log.d("clearTraces", "cleared: " +cleared);
myTeam.ClearTraces();
otherTeams.ClearTraces();
}
@Override
public void onError() {
}
});
}
}
}
| AP-IT-GH/CA1819-CityCheck | src/CityCheckApp/app/src/main/java/cloudapplications/citycheck/Activities/GameActivity.java | 5,094 | // Kijken of er een hit is met een locatie | line_comment | nl | package cloudapplications.citycheck.Activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import cloudapplications.citycheck.APIService.NetworkManager;
import cloudapplications.citycheck.APIService.NetworkResponseListener;
import cloudapplications.citycheck.Goals;
import cloudapplications.citycheck.IntersectCalculator;
import cloudapplications.citycheck.Models.Antwoord;
import cloudapplications.citycheck.Models.GameDoel;
import cloudapplications.citycheck.Models.Locatie;
import cloudapplications.citycheck.Models.StringReturn;
import cloudapplications.citycheck.Models.Team;
import cloudapplications.citycheck.Models.Vraag;
import cloudapplications.citycheck.MyTeam;
import cloudapplications.citycheck.OtherTeams;
import cloudapplications.citycheck.R;
public class GameActivity extends FragmentActivity implements OnMapReadyCallback {
// Kaart vars
private GoogleMap kaart;
private MyTeam myTeam;
private OtherTeams otherTeams;
private Goals goals;
private NetworkManager service;
private IntersectCalculator calc;
private FloatingActionButton myLocation;
// Variabelen om teams
private TextView teamNameTextView;
private TextView scoreTextView;
private String teamNaam;
private int gamecode;
private int score;
// Vragen beantwoorden
private String[] antwoorden;
private String vraag;
private int correctAntwoordIndex;
private int gekozenAntwoordIndex;
private boolean isClaiming;
// Timer vars
private TextView timerTextView;
private ProgressBar timerProgressBar;
private int progress;
//screen time out
private int defTimeOut=0;
// Afstand
private float[] afstandResult;
private float treshHoldAfstand = 50; //(meter)
// Geluiden
private MediaPlayer mpTrace;
private MediaPlayer mpClaimed;
private MediaPlayer mpBonusCorrect;
private MediaPlayer mpBonusWrong;
private MediaPlayer mpGameStarted;
// Callbacks
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
Objects.requireNonNull(mapFragment).getMapAsync(this);
calc = new IntersectCalculator();
service = NetworkManager.getInstance();
gamecode = Integer.parseInt(Objects.requireNonNull(Objects.requireNonNull(getIntent().getExtras()).getString("gameCode")));
// AfstandTreshold
treshHoldAfstand = 15; //(meter)
// Claiming naar false
isClaiming = false;
//myLocation
myLocation = findViewById(R.id.myLoc);
//txt views
teamNameTextView = findViewById(R.id.text_view_team_name);
timerTextView = findViewById(R.id.text_view_timer);
timerProgressBar = findViewById(R.id.progress_bar_timer);
teamNaam = getIntent().getExtras().getString("teamNaam");
teamNameTextView.setText(teamNaam);
gameTimer();
// Een vraag stellen als ik op de naam klik (Dit is tijdelijk om een vraag toch te kunnen tonen)
teamNameTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
claimLocatie(1, 1);
}
});
myLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(myTeam.newLocation != null){
LatLng positie = new LatLng(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude());
kaart.moveCamera(CameraUpdateFactory.newLatLng(positie));
}
}
});
// Score
scoreTextView = findViewById(R.id.text_view_points);
score = 0;
setScore(30);
// Geluiden
mpTrace = MediaPlayer.create(this, R.raw.trace_crossed);
mpClaimed = MediaPlayer.create(this, R.raw.claimed);
mpBonusCorrect = MediaPlayer.create(this, R.raw.bonus_correct);
mpBonusWrong = MediaPlayer.create(this, R.raw.bonus_wrong);
mpGameStarted = MediaPlayer.create(this, R.raw.game_started);
mpGameStarted.start();
ImageView pointsImageView = findViewById(R.id.image_view_points);
pointsImageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
endGame();
return false;
}
});
}
@Override
protected void onResume() {
super.onResume();
if (myTeam != null)
myTeam.StartConnection();
}
@Override
public void onMapReady(GoogleMap googleMap) {
kaart = googleMap;
kaart.getUiSettings().setMapToolbarEnabled(false);
// Alles ivm locatie van het eigen team
myTeam = new MyTeam(this, kaart, gamecode, teamNaam);
myTeam.StartConnection();
// Move the camera to Antwerp
LatLng Antwerpen = new LatLng(51.2194, 4.4025);
kaart.moveCamera(CameraUpdateFactory.newLatLngZoom(Antwerpen, 15));
// Locaties van andere teams
otherTeams = new OtherTeams(gamecode, teamNaam, kaart, GameActivity.this);
otherTeams.GetTeamsOnMap();
// Alles ivm doellocaties
goals = new Goals(gamecode, kaart, GameActivity.this);
}
@Override
public void onBackPressed() {
}
// Private helper methoden
/*
private void showDoelLocaties(List<DoelLocation> newDoelLocaties) {
// Place a marker on the locations
for (int i = 0; i < newDoelLocaties.size(); i++) {
DoelLocation doellocatie = newDoelLocaties.get(i);
LatLng Locatie = new LatLng(doellocatie.getLocatie().getLat(), doellocatie.getLocatie().getLong());
kaart.addMarker(new MarkerOptions().position(Locatie).title("Naam locatie").snippet("500").icon(BitmapDescriptorFactory.fromResource(R.drawable.coin_small)));
}
}
*/
private void everythingThatNeedsToHappenEvery3s(long verstrekentijd) {
int tijd = (int) (verstrekentijd / 1000);
if (tijd % 3 == 0) {
goals.RemoveCaimedLocations();
if (myTeam.newLocation != null) {
myTeam.HandleNewLocation(new Locatie(myTeam.newLocation.getLatitude(), myTeam.newLocation.getLongitude()), tijd);
calculateIntersect();
}
otherTeams.GetTeamsOnMap();
}
// Controleren op doellocatie triggers om te kunnen claimen
// Huidige locaties van de doelen ophalen
if (goals.currentGoals != null && myTeam.Traces.size() > 0 && !isClaiming) {
Locatie loc1 = goals.currentGoals.get(0).getDoel().getLocatie();
Locatie loc2 = goals.currentGoals.get(1).getDoel().getLocatie();
Locatie loc3 = goals.currentGoals.get(2).getDoel().getLocatie();
Locatie[] locs = {loc1, loc2, loc3};
// Mijn huidige locatie ophalen
int tempTraceSize = myTeam.Traces.size();
double tempLat = myTeam.Traces.get(tempTraceSize - 1).getLat();
double tempLong = myTeam.Traces.get(tempTraceSize - 1).getLong();
// Kijke<SUF>
int tempIndex = 0;
for (Locatie loc : locs) {
berekenAfstand(loc, tempLat, tempLong, goals.currentGoals.get(tempIndex));
tempIndex++;
}
}
}
private void berekenAfstand(Locatie doelLoc, double tempLat, double tempLong, GameDoel goal) {
afstandResult = new float[1];
Location.distanceBetween(doelLoc.getLat(), doelLoc.getLong(), tempLat, tempLong, afstandResult);
if (afstandResult[0] < treshHoldAfstand && !goal.getClaimed()) {
// GameDoelID en doellocID ophalen
int GD = goal.getId();
int LC = goal.getDoel().getId();
// Locatie claim triggeren
claimLocatie(GD, LC);
goal.setClaimed(true);
// Claimen instellen zolang we bezig zijn met claimen
isClaiming = true;
//Claim medelen via toast
Toast.makeText(GameActivity.this, "Locatie Geclaimed: " + goal.getDoel().getTitel(), Toast.LENGTH_LONG).show();
}
}
private void setMultiChoice(final String[] antwoorden, int CorrectIndex, String vraag) {
// Alertdialog aanmaken
AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this);
// Single choice dialog met de antwoorden
builder.setSingleChoiceItems(antwoorden, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Notify the current action
Toast.makeText(GameActivity.this, "Antwoord: " + antwoorden[i], Toast.LENGTH_LONG).show();
gekozenAntwoordIndex = i;
}
});
// Specify the dialog is not cancelable
builder.setCancelable(true);
// Set a title for alert dialog
builder.setTitle(vraag);
// Set the positive/yes button click listener
builder.setPositiveButton("Kies!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do something when click positive button
// Toast.makeText(GameActivity.this, "data: "+gekozenAntwoordIndex, Toast.LENGTH_LONG).show();
// Antwoord controleren
checkAnswer(gekozenAntwoordIndex, correctAntwoordIndex);
}
});
AlertDialog dialog = builder.create();
// Display the alert dialog on interface
dialog.show();
}
private void checkAnswer(int gekozenInd, int correctInd) {
// Klopt de gekozen index met het correcte antwoord index
if (gekozenInd == correctInd) {
mpBonusCorrect.start();
Toast.makeText(GameActivity.this, "Correct!", Toast.LENGTH_LONG).show();
// X aantal punten toevoegen bij de gebruiker
// Nieuwe score tonen en doorpushen naar de db
setScore(20);
isClaiming = false;
} else {
mpBonusWrong.start();
Toast.makeText(GameActivity.this, "Helaas!", Toast.LENGTH_LONG).show();
setScore(5);
isClaiming = false;
}
}
private void setScore(int newScore) {
score += newScore;
scoreTextView.setText(String.valueOf(score));
service.setTeamScore(gamecode, teamNaam, score, new NetworkResponseListener<Integer>() {
@Override
public void onResponseReceived(Integer score) {
// Score ok
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to set the new score", Toast.LENGTH_SHORT).show();
}
});
}
private void claimLocatie(final int locId, final int doellocID) {
mpClaimed.start();
// locid => gamelocaties ID, doellocID => id van de daadwerkelijke doellocatie
// Een team een locatie laten claimen als ze op deze plek zijn.
service.claimDoelLocatie(gamecode, locId, new NetworkResponseListener<StringReturn>() {
@Override
public void onResponseReceived(StringReturn rtrn) {
//response verwerken
try {
String waarde = rtrn.getWaarde();
Toast.makeText(GameActivity.this, waarde, Toast.LENGTH_SHORT).show();
} catch (Throwable err) {
Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to claim the location", Toast.LENGTH_SHORT).show();
}
});
// Dialog tonen met de vraag claim of bonus vraag
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Claimen of bonus vraag(risico) oplossen?")
// Niet cancel-baar
.setCancelable(false)
.setPositiveButton("Claim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mpBonusCorrect.start();
// De location alleen claimen zonder bonusvraag
setScore(10);
isClaiming = false;
}
})
.setNegativeButton("Bonus vraag", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Random vraag bij deze locatie ophalen uit de backend
service.getDoelLocatieVraag(doellocID, new NetworkResponseListener<Vraag>() {
@Override
public void onResponseReceived(Vraag newVraag) {
// Response verwerken
// Vraagtitel bewaren
vraag = newVraag.getVraagZin();
//3 Antwoorden bewaren
ArrayList<Antwoord> allAnswers = newVraag.getAntwoorden();
antwoorden = new String[3];
for (int i = 0; i < 3; i++) {
antwoorden[i] = allAnswers.get(i).getAntwoordzin();
if (allAnswers.get(i).isCorrectBool()) {
correctAntwoordIndex = i;
}
}
//Vraag stellen
askQuestion();
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Error while trying to get the question", Toast.LENGTH_SHORT).show();
}
});
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void askQuestion() {
// Instellen van een vraag en deze stellen + controleren
// Vraag tonen
setMultiChoice(antwoorden, correctAntwoordIndex, vraag);
}
private void gameTimer() {
String chosenGameTime = Objects.requireNonNull(getIntent().getExtras()).getString("gameTime");
long millisStarted = Long.parseLong(Objects.requireNonNull(getIntent().getExtras().getString("millisStarted")));
int gameTimeInMillis = Integer.parseInt(Objects.requireNonNull(chosenGameTime)) * 3600000;
// Het verschil tussen de tijd van nu en de tijd van wanneer de game is gestart
long differenceFromMillisStarted = System.currentTimeMillis() - millisStarted;
// Hoe lang dat de timer moet doorlopen
long timerMillis = gameTimeInMillis - differenceFromMillisStarted;
//screen time out
try{
if(Settings.System.canWrite(this)){
defTimeOut = Settings.System.getInt(getContentResolver(),Settings.System.SCREEN_OFF_TIMEOUT, 0);
android.provider.Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, (int)timerMillis);
}
} catch (NoSuchMethodError err){
err.printStackTrace();
}
// De progress begint op de juiste plek, dus niet altijd vanaf 0
progress = (int) ((gameTimeInMillis - timerMillis) / 1000);
timerProgressBar.setProgress(progress);
if (timerMillis > 0) {
final int finalGameTimeInMillis = gameTimeInMillis;
new CountDownTimer(timerMillis, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60;
int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
timerTextView.setText("Time remaining: " + hours + ":" + minutes + ":" + seconds);
everythingThatNeedsToHappenEvery3s(finalGameTimeInMillis - millisUntilFinished);
getNewGoalsAfterInterval((finalGameTimeInMillis - millisUntilFinished), 900);
progress++;
timerProgressBar.setProgress(progress * 100 / (finalGameTimeInMillis / 1000));
}
public void onFinish() {
progress++;
timerProgressBar.setProgress(100);
endGame();
}
}.start();
} else {
endGame();
}
}
private void endGame() {
try{
if(Settings.System.canWrite(this)) {
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, defTimeOut);
}
} catch (NoSuchMethodError err) {
err.printStackTrace();
}
Intent i = new Intent(GameActivity.this, EndGameActivity.class);
if (myTeam != null)
myTeam.StopConnection();
if (Objects.requireNonNull(getIntent().getExtras()).getBoolean("gameCreator"))
i.putExtra("gameCreator", true);
else
i.putExtra("gameCreator", false);
i.putExtra("gameCode", Integer.toString(gamecode));
startActivity(i);
}
private void calculateIntersect() {
if (myTeam.Traces.size() > 2) {
service.getAllTeamTraces(gamecode, new NetworkResponseListener<List<Team>>() {
@Override
public void onResponseReceived(List<Team> teams) {
if(myTeam.Traces.size() > 2) {
Locatie start = myTeam.Traces.get(myTeam.Traces.size() - 2);
Locatie einde = myTeam.Traces.get(myTeam.Traces.size() - 1);
for (Team team : teams) {
if (!team.getTeamNaam().equals(teamNaam)) {
Log.d("intersect", "size: " + team.getTeamTrace().size());
for (int i = 0; i < team.getTeamTrace().size(); i++) {
if ((i + 1) < team.getTeamTrace().size()) {
if (calc.doLineSegmentsIntersect(start, einde, team.getTeamTrace().get(i).getLocatie(), team.getTeamTrace().get(i + 1).getLocatie())) {
mpTrace.start();
Log.d("intersect", team.getTeamNaam() + " kruist");
setScore(-5);
Toast.makeText(GameActivity.this, "Oh oohw you crossed another team's path, bye bye 5 points", Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
}
@Override
public void onError() {
Toast.makeText(GameActivity.this, "Er ging iets mis bij het opvragen van de teamtraces", Toast.LENGTH_SHORT);
}
});
}
}
private void getNewGoalsAfterInterval(Long verstrekenTijd, int interval) {
int tijd = (int) (verstrekenTijd / 1000);
// interval meegeven in seconden
goals.GetNewGoals(tijd, interval);
//traces op map clearen bij elk interval
if (tijd % interval == 0) {
service.deleteTeamtraces(gamecode, new NetworkResponseListener<Boolean>() {
@Override
public void onResponseReceived(Boolean cleared) {
Log.d("clearTraces", "cleared: " +cleared);
myTeam.ClearTraces();
otherTeams.ClearTraces();
}
@Override
public void onError() {
}
});
}
}
}
|
17870_19 | package be.ap.eaict.geocapture;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import be.ap.eaict.geocapture.Model.CaptureLocatie;
import be.ap.eaict.geocapture.Model.Locatie;
import be.ap.eaict.geocapture.Model.Puzzel;
import be.ap.eaict.geocapture.Model.Team;
import be.ap.eaict.geocapture.Model.User;
import cz.msebera.android.httpclient.Header;
public class MapActivity extends AppCompatActivity
implements
OnMyLocationButtonClickListener,
OnMyLocationClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
GameService _gameservice = new GameService();
private static final String TAG = "MapActivity";
/**
* Request code for location permission request.
*
* @see #onRequestPermissionsResult(int, String[], int[])
*/
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
/**
* Flag indicating whether a requested permission has been denied after returning in
* {@link #onRequestPermissionsResult(int, String[], int[])}.
*/
private boolean mPermissionDenied = false;
private GoogleMap mMap;
private GameService _gameService = new GameService();
TextView gameTime;
TextView bestTeamTxt;
private Location _locatie;
HashMap<Integer, Marker> locatieMarkers = new HashMap<Integer, Marker>() {};
List<Marker> teamMarkers = new ArrayList<Marker>() {};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
gameTime = (TextView) findViewById(R.id.gametime);
bestTeamTxt = (TextView) findViewById(R.id.bestTeamTxt);
initializeGameTime();
keepGameUpToDate();
}
@Override
public void onMapReady(GoogleMap googleMap){
List<Locatie> locaties = _gameService.game.getEnabledLocaties();
float centerlat = 0;
float centerlng = 0;
LatLng center = new LatLng(0, 0);
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.grey_dot)).getBitmap();
Bitmap greymarker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(Locatie locatie:locaties){
LatLng latLng = new LatLng(locatie.getLat(), locatie.getLng());
centerlat = centerlat + locatie.getLat();
centerlng = centerlng + locatie.getLng();
//center = new LatLng(center.latitude + locatie.getLat(),center.longitude + locatie.getLng());
locatieMarkers.put(
locatie.id,
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(greymarker))
)
);
}
if(locaties.size()>0)
center = new LatLng(centerlat/locaties.size(), centerlng/locaties.size());
b =((BitmapDrawable)getResources().getDrawable(R.drawable.green_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 27, 27, false);
List<User> users = _gameService.game.teams.get(GameService.team).users;
Log.d(TAG, "onMapReady: " + users);
for(User lid:users){
if(lid.id != _gameService.userId)
{
MarkerOptions a = new MarkerOptions()
.position(new LatLng(lid.lat, lid.lng))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker));
Marker m = googleMap.addMarker(a);
teamMarkers.add(m);
}
}
/* //testmarker:
MarkerOptions a = new MarkerOptions()
.position(new LatLng(5,5))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker));
Marker m = googleMap.addMarker(a);*/
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center,14));
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
enableMyLocation();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
_locatie = location;
}
});
}
@Override
protected void onDestroy() {
SyncAPICall.delete("Game/deleteplayerlocatie/"+Integer.toString(_gameservice.lobbyId)+"/"+Integer.toString(_gameservice.team)+"/"+ Integer.toString(_gameservice.userId), null, new AsyncHttpResponseHandler() {
@Override
public void onSuccess (int statusCode, Header[] headers, byte[] res ) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
});
super.onDestroy();
}
/**
* Enables the My Location layer if the fine location permission has been granted.
*/
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
}
else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
Log.d(TAG, "onabcxyz lng: "+ location.getLongitude() + " lat: " + location.getLatitude());
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
private void keepGameUpToDate() {
new CountDownTimer(_gameService.game.getRegio().getTijd()*60, 2000) {
public void onTick(long millisUntilFinished) {
//update player locatie, returns game
if(_locatie != null)
_gameService.UpdatePlayerLocatie(new LatLng(_locatie.getLatitude(), _locatie.getLongitude()));
//update other players locaties
for (Marker marker : teamMarkers)
{
marker.remove();
}
List<User> users = _gameService.game.teams.get(GameService.team).users; // update player locaties op de map
for(User user : users)
if(user.id != _gameService.userId)
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.green_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 30, 30, false);
teamMarkers.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(user.lat, user.lng))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker))));
}
//update locatie locaties op de map
for(Team team : _gameService.game.teams)
{
if(team.capturedLocaties.size()>0)
{
if(team.id == _gameService.game.teams.get(_gameService.team).id)
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.captured_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(CaptureLocatie captureLocatie : team.capturedLocaties)
locatieMarkers.get(captureLocatie.locatie.id).setIcon(BitmapDescriptorFactory.fromBitmap(marker));
}
else
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.enemycapture_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(CaptureLocatie captureLocatie : team.capturedLocaties)
locatieMarkers.get(captureLocatie.locatie.id).setIcon(BitmapDescriptorFactory.fromBitmap(marker));
}
}
}
bestTeam();//laat het beste team zien in de balk onderaan in het scherm
int l = canCapture();//kijk of er een locatie is dat men kan capturen
if(l != 0 && l != lastl && !_gameService.puzzelactive)//roep de vragenactivity op wanneer mogelijk
{
lastl = l;
Intent intent = new Intent(MapActivity.this , VragenActivity.class);
_gameService.puzzels = new ArrayList<>();
for(Team team : _gameService.game.teams)
for(CaptureLocatie captureLocatie : team.capturedLocaties)
if(captureLocatie.locatie.id == l )
{
int maxpoints = 0;
for(Puzzel puzzel : captureLocatie.locatie.puzzels)
maxpoints+= puzzel.points;
Toast.makeText(MapActivity.this, "CaptureStrength: "+ captureLocatie.score+ "/"+maxpoints, Toast.LENGTH_SHORT).show();
l = 0; // kill capture 'ability'
}
for(final Locatie locatie : _gameService.game.regio.locaties)
if(locatie.id == l)
{
for(Puzzel puzzel : locatie.puzzels)
_gameService.puzzels.add(new Puzzel(puzzel.id,puzzel.vraag, null));
_gameService.locationid = l;
startActivity(intent);
}
}
}
public int lastl = 0;
public void onFinish() {
Intent Leaderboard = new Intent(MapActivity.this, LeaderboardActivity.class);
startActivity(Leaderboard);
}
}.start();
}
//gametime wordt via de app met internet tijd geregeld zodat iedereen gelijk loopt.
private void initializeGameTime(){
int tijd = _gameService.game.getRegio().getTijd()*60 - (int)(System.currentTimeMillis() - _gameService.game.starttijd);
new CountDownTimer(tijd, 1000) {
public void onTick(long millisUntilFinished) {
String timer = String.format(Locale.getDefault(), "%02d:%02d:%02d remaining",
TimeUnit.MILLISECONDS.toHours(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
gameTime.setText(timer);
}
public void onFinish() {
gameTime.setText("einde game");
}
}.start();
}
public void bestTeam(){
List<Team> teams = _gameService.game.teams;
int bestteamid = 999;
int bestscore = 0;
//checken of er score zijn gemaakt om het beste team te updaten.
for(Team team : teams) {
int score = 0;
for(CaptureLocatie loc : team.getCapturedLocaties())
score += loc.score;
if (score > bestscore){
bestscore = score;
bestteamid = team.id;
}
}
if (bestteamid == 999){
bestTeamTxt.setText("Best Team: -" );
}else {
bestTeamTxt.setText("Best Team: " + String.valueOf(bestteamid) + " score: " + bestscore);
}
int score = 0;
for(CaptureLocatie loc : teams.get(_gameService.team).capturedLocaties )
score += loc.score;
bestTeamTxt.setText(bestTeamTxt.getText() + "\nMy teamId: "+ teams.get(_gameService.team).id + " score: " + score);
}
private int canCapture(){
List<Locatie> locaties = _gameService.game.getEnabledLocaties();
List<Locatie> capturedlocaties = new ArrayList<>();
for(CaptureLocatie captureLocatie : _gameService.game.teams.get(_gameService.team).capturedLocaties)
capturedlocaties.add(captureLocatie.locatie);
//controleren of je binnen een straal van 30m bent om te kunnen capturen.
if(_locatie != null)
for (int i = 0; i < locaties.size(); i++) {
double x = _locatie.getLongitude() - locaties.get(i).lng;
double y = _locatie.getLatitude() - locaties.get(i).lat;
x = x * x;
y = y * y;
double afstand = Math.sqrt(x+y);
//0.00026949458 is 30m in graden op de wereld
if (afstand < 0.00026949458){
boolean contains = false;
for(Locatie ll : capturedlocaties)
{
if(ll.id == locaties.get(i).id)
contains = true;
}
if(contains == false)
{
int send = locaties.get(i).id;
return send;
}
}
}
return 0;
}
}
| AP-IT-GH/CA1819-HansAnders | MobApp/app/src/main/java/be/ap/eaict/geocapture/MapActivity.java | 4,115 | //laat het beste team zien in de balk onderaan in het scherm | line_comment | nl | package be.ap.eaict.geocapture;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import be.ap.eaict.geocapture.Model.CaptureLocatie;
import be.ap.eaict.geocapture.Model.Locatie;
import be.ap.eaict.geocapture.Model.Puzzel;
import be.ap.eaict.geocapture.Model.Team;
import be.ap.eaict.geocapture.Model.User;
import cz.msebera.android.httpclient.Header;
public class MapActivity extends AppCompatActivity
implements
OnMyLocationButtonClickListener,
OnMyLocationClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
GameService _gameservice = new GameService();
private static final String TAG = "MapActivity";
/**
* Request code for location permission request.
*
* @see #onRequestPermissionsResult(int, String[], int[])
*/
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
/**
* Flag indicating whether a requested permission has been denied after returning in
* {@link #onRequestPermissionsResult(int, String[], int[])}.
*/
private boolean mPermissionDenied = false;
private GoogleMap mMap;
private GameService _gameService = new GameService();
TextView gameTime;
TextView bestTeamTxt;
private Location _locatie;
HashMap<Integer, Marker> locatieMarkers = new HashMap<Integer, Marker>() {};
List<Marker> teamMarkers = new ArrayList<Marker>() {};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
gameTime = (TextView) findViewById(R.id.gametime);
bestTeamTxt = (TextView) findViewById(R.id.bestTeamTxt);
initializeGameTime();
keepGameUpToDate();
}
@Override
public void onMapReady(GoogleMap googleMap){
List<Locatie> locaties = _gameService.game.getEnabledLocaties();
float centerlat = 0;
float centerlng = 0;
LatLng center = new LatLng(0, 0);
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.grey_dot)).getBitmap();
Bitmap greymarker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(Locatie locatie:locaties){
LatLng latLng = new LatLng(locatie.getLat(), locatie.getLng());
centerlat = centerlat + locatie.getLat();
centerlng = centerlng + locatie.getLng();
//center = new LatLng(center.latitude + locatie.getLat(),center.longitude + locatie.getLng());
locatieMarkers.put(
locatie.id,
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(greymarker))
)
);
}
if(locaties.size()>0)
center = new LatLng(centerlat/locaties.size(), centerlng/locaties.size());
b =((BitmapDrawable)getResources().getDrawable(R.drawable.green_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 27, 27, false);
List<User> users = _gameService.game.teams.get(GameService.team).users;
Log.d(TAG, "onMapReady: " + users);
for(User lid:users){
if(lid.id != _gameService.userId)
{
MarkerOptions a = new MarkerOptions()
.position(new LatLng(lid.lat, lid.lng))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker));
Marker m = googleMap.addMarker(a);
teamMarkers.add(m);
}
}
/* //testmarker:
MarkerOptions a = new MarkerOptions()
.position(new LatLng(5,5))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker));
Marker m = googleMap.addMarker(a);*/
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center,14));
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
enableMyLocation();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
_locatie = location;
}
});
}
@Override
protected void onDestroy() {
SyncAPICall.delete("Game/deleteplayerlocatie/"+Integer.toString(_gameservice.lobbyId)+"/"+Integer.toString(_gameservice.team)+"/"+ Integer.toString(_gameservice.userId), null, new AsyncHttpResponseHandler() {
@Override
public void onSuccess (int statusCode, Header[] headers, byte[] res ) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
});
super.onDestroy();
}
/**
* Enables the My Location layer if the fine location permission has been granted.
*/
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
}
else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
Log.d(TAG, "onabcxyz lng: "+ location.getLongitude() + " lat: " + location.getLatitude());
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
private void keepGameUpToDate() {
new CountDownTimer(_gameService.game.getRegio().getTijd()*60, 2000) {
public void onTick(long millisUntilFinished) {
//update player locatie, returns game
if(_locatie != null)
_gameService.UpdatePlayerLocatie(new LatLng(_locatie.getLatitude(), _locatie.getLongitude()));
//update other players locaties
for (Marker marker : teamMarkers)
{
marker.remove();
}
List<User> users = _gameService.game.teams.get(GameService.team).users; // update player locaties op de map
for(User user : users)
if(user.id != _gameService.userId)
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.green_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 30, 30, false);
teamMarkers.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(user.lat, user.lng))
.alpha(0.7f)
.icon(BitmapDescriptorFactory.fromBitmap(marker))));
}
//update locatie locaties op de map
for(Team team : _gameService.game.teams)
{
if(team.capturedLocaties.size()>0)
{
if(team.id == _gameService.game.teams.get(_gameService.team).id)
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.captured_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(CaptureLocatie captureLocatie : team.capturedLocaties)
locatieMarkers.get(captureLocatie.locatie.id).setIcon(BitmapDescriptorFactory.fromBitmap(marker));
}
else
{
Bitmap b =((BitmapDrawable)getResources().getDrawable(R.drawable.enemycapture_dot)).getBitmap();
Bitmap marker = Bitmap.createScaledBitmap(b, 40, 40, false);
for(CaptureLocatie captureLocatie : team.capturedLocaties)
locatieMarkers.get(captureLocatie.locatie.id).setIcon(BitmapDescriptorFactory.fromBitmap(marker));
}
}
}
bestTeam();//laat <SUF>
int l = canCapture();//kijk of er een locatie is dat men kan capturen
if(l != 0 && l != lastl && !_gameService.puzzelactive)//roep de vragenactivity op wanneer mogelijk
{
lastl = l;
Intent intent = new Intent(MapActivity.this , VragenActivity.class);
_gameService.puzzels = new ArrayList<>();
for(Team team : _gameService.game.teams)
for(CaptureLocatie captureLocatie : team.capturedLocaties)
if(captureLocatie.locatie.id == l )
{
int maxpoints = 0;
for(Puzzel puzzel : captureLocatie.locatie.puzzels)
maxpoints+= puzzel.points;
Toast.makeText(MapActivity.this, "CaptureStrength: "+ captureLocatie.score+ "/"+maxpoints, Toast.LENGTH_SHORT).show();
l = 0; // kill capture 'ability'
}
for(final Locatie locatie : _gameService.game.regio.locaties)
if(locatie.id == l)
{
for(Puzzel puzzel : locatie.puzzels)
_gameService.puzzels.add(new Puzzel(puzzel.id,puzzel.vraag, null));
_gameService.locationid = l;
startActivity(intent);
}
}
}
public int lastl = 0;
public void onFinish() {
Intent Leaderboard = new Intent(MapActivity.this, LeaderboardActivity.class);
startActivity(Leaderboard);
}
}.start();
}
//gametime wordt via de app met internet tijd geregeld zodat iedereen gelijk loopt.
private void initializeGameTime(){
int tijd = _gameService.game.getRegio().getTijd()*60 - (int)(System.currentTimeMillis() - _gameService.game.starttijd);
new CountDownTimer(tijd, 1000) {
public void onTick(long millisUntilFinished) {
String timer = String.format(Locale.getDefault(), "%02d:%02d:%02d remaining",
TimeUnit.MILLISECONDS.toHours(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % 60,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % 60);
gameTime.setText(timer);
}
public void onFinish() {
gameTime.setText("einde game");
}
}.start();
}
public void bestTeam(){
List<Team> teams = _gameService.game.teams;
int bestteamid = 999;
int bestscore = 0;
//checken of er score zijn gemaakt om het beste team te updaten.
for(Team team : teams) {
int score = 0;
for(CaptureLocatie loc : team.getCapturedLocaties())
score += loc.score;
if (score > bestscore){
bestscore = score;
bestteamid = team.id;
}
}
if (bestteamid == 999){
bestTeamTxt.setText("Best Team: -" );
}else {
bestTeamTxt.setText("Best Team: " + String.valueOf(bestteamid) + " score: " + bestscore);
}
int score = 0;
for(CaptureLocatie loc : teams.get(_gameService.team).capturedLocaties )
score += loc.score;
bestTeamTxt.setText(bestTeamTxt.getText() + "\nMy teamId: "+ teams.get(_gameService.team).id + " score: " + score);
}
private int canCapture(){
List<Locatie> locaties = _gameService.game.getEnabledLocaties();
List<Locatie> capturedlocaties = new ArrayList<>();
for(CaptureLocatie captureLocatie : _gameService.game.teams.get(_gameService.team).capturedLocaties)
capturedlocaties.add(captureLocatie.locatie);
//controleren of je binnen een straal van 30m bent om te kunnen capturen.
if(_locatie != null)
for (int i = 0; i < locaties.size(); i++) {
double x = _locatie.getLongitude() - locaties.get(i).lng;
double y = _locatie.getLatitude() - locaties.get(i).lat;
x = x * x;
y = y * y;
double afstand = Math.sqrt(x+y);
//0.00026949458 is 30m in graden op de wereld
if (afstand < 0.00026949458){
boolean contains = false;
for(Locatie ll : capturedlocaties)
{
if(ll.id == locaties.get(i).id)
contains = true;
}
if(contains == false)
{
int send = locaties.get(i).id;
return send;
}
}
}
return 0;
}
}
|
37741_1 | package com.example.midasvg.pilgrim;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
public class EndActivity extends AppCompatActivity {
TextView gameTime;
TextView txtDistance;
//TextView txtPoints;
float distance;
int count;
int hints;
int penalty;
int totalsecs;
long startTime;
public int msg;
String UID;
Location[] locations = new Location[0];
Location loc1 = new Location() {
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_end);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Finished </font>"));
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646")));
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UID = user.getUid();
//Tijd aanroepen van de vorige intent
String timeSpent = getIntent().getStringExtra("Time");
distance = getIntent().getFloatExtra("distance", 0);
count = getIntent().getIntExtra("timerCount", 0);
hints = getIntent().getIntExtra("totalHintCount", 0);
startTime = getIntent().getLongExtra("StartTime", 0);
penalty = 30 * hints;
gameTime = (TextView) findViewById(R.id.txtSpent);
totalsecs = count + penalty;
int seconds = totalsecs%60;
int temp = totalsecs - (totalsecs%60);
int minutestotal = temp/60;
int minutes = minutestotal%60;
int temp2 = minutestotal - (minutestotal%60);
int hours = temp2/60;
String timeString;
if(hours == 0 && minutes ==0){
timeString = String.valueOf(seconds) + " seconds";
}else if(hours == 0){
timeString = String.valueOf(minutes) + " minutes " + String.valueOf(seconds) + "seconds";
}else{
timeString = String.format("%02d", hours) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds);
}
gameTime.setText(timeString);
txtDistance = (TextView) findViewById(R.id.txtDistance);
txtDistance.setText("" + new DecimalFormat("##.##").format(distance / 1000) + " Km");
/*
txtPoints = (TextView) findViewById(R.id.txtPoints);
txtPoints.setText("" + count);
int s = (count + penalty) % 60;
int min = (count + penalty) / 60;
int hour = min % 60;
min = min / 60;
txtPoints.setText(min + "h" + hour + "m" + s + "s");*/
final Button Leaderboard = (Button) findViewById(R.id.bttnLeaderboard) ;
Leaderboard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(EndActivity.this, LeaderboardActivity.class);
startActivity(intent);
}
});
final Button backToMain = (Button) findViewById(R.id.bttnMain);
backToMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(EndActivity.this, MainActivity.class);
startActivity(intent);
}
});
//API aanspreken
sendPost();
}
public void sendPost() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://capilgrim.azurewebsites.net/api/pilgrimages");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonObject = new JSONObject();
jsonObject.put("FireBaseID", UID);
jsonObject.put("username", "temp");
jsonObject.put("StartTime", startTime);
jsonObject.put("Time", totalsecs);
JSONArray jarr = new JSONArray();
jsonObject.put("Locations", jarr);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonObject.toString());
Log.d("Post", jsonObject.toString());
os.flush();
os.close();
msg = conn.getResponseCode();
conn.disconnect();
Log.d("Post", String.valueOf(msg));
if (msg == 200) {
Toast.makeText(getBaseContext(), "Succes. ",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Something failed. Try again",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
| AP-IT-GH/CA1819-Pilgrim | src/AndroidApp/app/src/main/java/com/example/midasvg/pilgrim/EndActivity.java | 1,502 | //Tijd aanroepen van de vorige intent | line_comment | nl | package com.example.midasvg.pilgrim;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
public class EndActivity extends AppCompatActivity {
TextView gameTime;
TextView txtDistance;
//TextView txtPoints;
float distance;
int count;
int hints;
int penalty;
int totalsecs;
long startTime;
public int msg;
String UID;
Location[] locations = new Location[0];
Location loc1 = new Location() {
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_end);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Finished </font>"));
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646")));
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UID = user.getUid();
//Tijd <SUF>
String timeSpent = getIntent().getStringExtra("Time");
distance = getIntent().getFloatExtra("distance", 0);
count = getIntent().getIntExtra("timerCount", 0);
hints = getIntent().getIntExtra("totalHintCount", 0);
startTime = getIntent().getLongExtra("StartTime", 0);
penalty = 30 * hints;
gameTime = (TextView) findViewById(R.id.txtSpent);
totalsecs = count + penalty;
int seconds = totalsecs%60;
int temp = totalsecs - (totalsecs%60);
int minutestotal = temp/60;
int minutes = minutestotal%60;
int temp2 = minutestotal - (minutestotal%60);
int hours = temp2/60;
String timeString;
if(hours == 0 && minutes ==0){
timeString = String.valueOf(seconds) + " seconds";
}else if(hours == 0){
timeString = String.valueOf(minutes) + " minutes " + String.valueOf(seconds) + "seconds";
}else{
timeString = String.format("%02d", hours) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds);
}
gameTime.setText(timeString);
txtDistance = (TextView) findViewById(R.id.txtDistance);
txtDistance.setText("" + new DecimalFormat("##.##").format(distance / 1000) + " Km");
/*
txtPoints = (TextView) findViewById(R.id.txtPoints);
txtPoints.setText("" + count);
int s = (count + penalty) % 60;
int min = (count + penalty) / 60;
int hour = min % 60;
min = min / 60;
txtPoints.setText(min + "h" + hour + "m" + s + "s");*/
final Button Leaderboard = (Button) findViewById(R.id.bttnLeaderboard) ;
Leaderboard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(EndActivity.this, LeaderboardActivity.class);
startActivity(intent);
}
});
final Button backToMain = (Button) findViewById(R.id.bttnMain);
backToMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(EndActivity.this, MainActivity.class);
startActivity(intent);
}
});
//API aanspreken
sendPost();
}
public void sendPost() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://capilgrim.azurewebsites.net/api/pilgrimages");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonObject = new JSONObject();
jsonObject.put("FireBaseID", UID);
jsonObject.put("username", "temp");
jsonObject.put("StartTime", startTime);
jsonObject.put("Time", totalsecs);
JSONArray jarr = new JSONArray();
jsonObject.put("Locations", jarr);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonObject.toString());
Log.d("Post", jsonObject.toString());
os.flush();
os.close();
msg = conn.getResponseCode();
conn.disconnect();
Log.d("Post", String.valueOf(msg));
if (msg == 200) {
Toast.makeText(getBaseContext(), "Succes. ",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Something failed. Try again",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
|
172731_16 | package com.ap.brecht.guitool;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.Random;
/**
* Created by hannelore on 22/04/2015.
*/
public class StopwatchFragment extends Fragment implements View.OnClickListener, SensorEventListener {
//Sensor variables
private Sensor mSensor;
private SensorManager mSensorManager;
private AcceleroFilter xFilter = new AcceleroFilter();
private AcceleroFilter yFilter = new AcceleroFilter();
private AcceleroFilter zFilter = new AcceleroFilter();
private double xFiltered;
private double yFiltered;
private double zFiltered;
private float[] orientationValues = new float[3];
private float rotation[] = new float[16];
private double startTime;
private double elapsedTime;
private double oldElapsedTime;
private double velocity = 0;
private double oldVelocity = 0;
private double noVelocityCounter = 0;
private double correctedVelocity;
private double oldCorrectedVelocity = Double.NaN;
private double oldOldCorrectedVelocity = Double.NaN;
private double height;
private double oldHeight;
//Chrono variables
private Chronometer chrono;
long timeWhenStopped = 0;
long elapsedMillis;
int secs, currentmin, lastmin;
//GUI
private View view;
private ImageButton startButton;
private TextView txtStart;
private ImageButton pauzeButton;
private TextView txtPauze;
private ImageButton stopButton;
private TextView txtStop;
private ImageButton resetButton;
private TextView txtReset;
private TextView txtHeight;
private TextView txtSnelheid;
private String locatie;
private String descriptie;
private String Uid;
JSONObject jsonResponse;
private TextToSpeech SayTime;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_stopwatch, container, false);
chrono = (Chronometer) view.findViewById(R.id.timer);
startButton = (ImageButton) view.findViewById(R.id.btnStart);
startButton.setOnClickListener(this);
stopButton = (ImageButton) view.findViewById(R.id.btnStop);
stopButton.setOnClickListener(this);
pauzeButton = (ImageButton) view.findViewById(R.id.btnPauze);
pauzeButton.setOnClickListener(this);
resetButton = (ImageButton) view.findViewById(R.id.btnReset);
resetButton.setOnClickListener(this);
txtStart = (TextView) view.findViewById(R.id.txtStart);
txtReset = (TextView) view.findViewById(R.id.txtReset);
txtPauze = (TextView) view.findViewById(R.id.txtPauze);
txtStop = (TextView) view.findViewById(R.id.txtStop);
txtHeight = (TextView) view.findViewById(R.id.txtHeight);
txtHeight.setText("21m");
//txtSnelheid= (TextView) view.findViewById(R.id.SpeedStop);
SayTime = new TextToSpeech(getActivity().getApplicationContext(),
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
SayTime.setLanguage(Locale.US);
}
}
});
//Set start text to agreed notation
chrono.setText("00:00:00");
chrono.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer c) {
elapsedMillis = SystemClock.elapsedRealtime() - c.getBase();
if (elapsedMillis > 3600000L) {
c.setFormat("0%s");
} else {
c.setFormat("00:%s");
}
secs = ((int) (elapsedMillis)) / 1000;
currentmin = secs / 60;
//Check if we need to speak the minutes
//@ the moment it's every minute
String alertTime = ((SessionActivity) getActivity()).AlertTime;
if (alertTime.equals("30s")) {
if (secs % 30 == 0) {
speakText();
}
} else if (alertTime.equals("1m")) {
if (lastmin != currentmin || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
} else if (alertTime.equals("5m")) {
if ((lastmin != currentmin && (currentmin % 5) == 0) || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
} else if (alertTime.equals("10m")) {
if ((lastmin != currentmin && (currentmin % 10) == 0) || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
}
}
});
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
chrono.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
chrono.start();
showStopButton();
break;
case R.id.btnPauze:
timeWhenStopped = chrono.getBase() - SystemClock.elapsedRealtime();
chrono.stop();
hideStopButton();
break;
case R.id.btnStop:
QustomDialogBuilder stopAlert = new QustomDialogBuilder(v.getContext(), AlertDialog.THEME_HOLO_DARK);
stopAlert.setMessage(Html.fromHtml("<font color=#" + Integer.toHexString(getActivity().getResources().getColor(R.color.white) & 0x00ffffff) + ">Do you want to quit your session?"));
stopAlert.setTitle("ClimbUP");
stopAlert.setTitleColor("#" + Integer.toHexString(getResources().getColor(R.color.Orange) & 0x00ffffff));
stopAlert.setDividerColor("#" + Integer.toHexString(getResources().getColor(R.color.Orange) & 0x00ffffff));
stopAlert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
stopAlert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
chrono.stop();
if (mSensorManager != null) {
mSensorManager.unregisterListener(StopwatchFragment.this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION));
mSensorManager.unregisterListener(StopwatchFragment.this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR));
}
savePicture();
new MyAsyncTask().execute();
}
});
stopAlert.create().show();
break;
case R.id.btnReset:
chrono.setBase(SystemClock.elapsedRealtime());
timeWhenStopped = 0;
chrono.stop();
break;
}
}
private void showStopButton() {
StartSensor();
startButton.setVisibility(View.GONE);
txtStart.setVisibility(View.GONE);
resetButton.setVisibility(View.GONE);
txtReset.setVisibility(View.GONE);
pauzeButton.setVisibility(View.VISIBLE);
txtPauze.setVisibility(View.VISIBLE);
stopButton.setVisibility(View.VISIBLE);
txtStop.setVisibility(View.VISIBLE);
}
private void hideStopButton() {
startButton.setVisibility(View.VISIBLE);
txtStart.setVisibility(View.VISIBLE);
resetButton.setVisibility(View.VISIBLE);
txtReset.setVisibility(View.VISIBLE);
pauzeButton.setVisibility(View.GONE);
txtPauze.setVisibility(View.GONE);
stopButton.setVisibility(View.GONE);
txtStop.setVisibility(View.GONE);
}
private void StartSensor()
{
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR) != null){
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), SensorManager.SENSOR_DELAY_GAME);
}
else {
//DO SHIT
}
startTime = System.currentTimeMillis() / 1000;
}
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
public void onSensorChanged(SensorEvent event)
{
mSensor = event.sensor;
if (mSensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
xFiltered = xFilter.Filter(event.values[0]);
yFiltered = yFilter.Filter(event.values[1]);
zFiltered = zFilter.Filter(event.values[2]);
}
else if(mSensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
{
SensorManager.getRotationMatrixFromVector(rotation, event.values);
SensorManager.getOrientation(rotation, orientationValues);
double azimuth = Math.toDegrees(orientationValues[0]);
double pitch = Math.toDegrees(orientationValues[1]);
double roll = Math.toDegrees(orientationValues[2]);
double ax = xFiltered * Math.cos(Math.toRadians(roll)) + yFiltered * Math.cos(Math.toRadians(90) - Math.toRadians(roll));
double ay = yFiltered * Math.cos(Math.toRadians(90) + Math.toRadians(pitch)) + xFiltered * Math.cos(Math.toRadians(90) + Math.toRadians(roll)) + zFiltered * Math.cos(Math.toRadians(pitch)) * Math.cos(Math.toRadians(roll));
elapsedTime = (System.currentTimeMillis() / 1000.0) - startTime;
velocity = oldVelocity + (ay * (elapsedTime - oldElapsedTime));
if(ay < 0.6 && ay > -0.6 && velocity != 0)
noVelocityCounter++;
else
noVelocityCounter = 0;
if((noVelocityCounter > 2 && oldOldCorrectedVelocity < 0.5 && oldOldCorrectedVelocity > -0.5) || Math.abs(oldOldCorrectedVelocity) > 2 || Double.isNaN(oldOldCorrectedVelocity))
correctedVelocity = 0;
else
correctedVelocity = oldCorrectedVelocity + (ay * (elapsedTime - oldElapsedTime)) * 1.2;
if (correctedVelocity > 2 || correctedVelocity < - 2)
correctedVelocity = 0;
height = oldHeight + (correctedVelocity * (elapsedTime - oldElapsedTime));
oldElapsedTime = elapsedTime;
oldVelocity = velocity;
oldOldCorrectedVelocity = oldCorrectedVelocity;
oldCorrectedVelocity = correctedVelocity;
oldHeight= height;
//tvVelocity.setText(String.valueOf(velocity));
txtHeight.setText(String.format("%.2f", height) + "m");
}
}
private void speakText() {
String toSpeak = "";
if (secs == 0 && currentmin == 0) {
Random r = new Random();
int fun = r.nextInt(7);//random number from 0-6
switch (fun) {
case 0:
toSpeak = "Happy Climbing";
break;
case 1:
toSpeak = "Have fun climbing";
break;
case 2:
toSpeak = "Let's climb";
break;
case 3:
toSpeak = "Enjoy your climb";
break;
case 4:
toSpeak = "You will climb and I will follow";
break;
case 5:
toSpeak = "Let's go";
break;
case 6:
toSpeak = "Go hard, or go home";
default:
break;
}
} else if (secs % 30 == 0 && secs % 60 != 0) {
if (currentmin == 0) {
toSpeak = "You have been climbing for " + "30" + " seconds";
} else if (currentmin == 1) {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minute and " + "30" + " seconds";
} else
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minutes and " + "30" + " seconds";
} else if (currentmin == 1) {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minute";
} else {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minutes";
}
SayTime.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
private void savePicture() {
locatie = DescriptionFragmentSession.getLocation();
descriptie = DescriptionFragmentSession.getDescription();
try {
if (DatabaseData.PhotoString == null)
return;
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeFile(DatabaseData.PhotoString).copy(Bitmap.Config.RGB_565, true);
Typeface tf = Typeface.create("sans-serif-condensed", Typeface.BOLD);
int x = 50;
int y = 75;
int size = 32;
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE); // Text Color
paint.setTypeface(tf);
paint.setTextSize(convertToPixels(getActivity().getApplicationContext(), size));
String text = locatie;
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
String text2 = descriptie;
Rect textRect2 = new Rect();
paint.getTextBounds(text2, 0, text2.length(), textRect2);
String text3 = String.format("%.2f", height) + "m";
canvas.drawText(text, x, y, paint);
canvas.drawText(text2, x, y + textRect.height(), paint);
canvas.drawText(text3, x, y + textRect.height() + textRect2.height(), paint);
//Add outline to text!
Paint stkPaint = new Paint();
stkPaint.setTypeface(tf);
stkPaint.setStyle(Paint.Style.STROKE);
stkPaint.setStrokeWidth(size / 10);
stkPaint.setColor(Color.BLACK);
stkPaint.setTextSize(convertToPixels(getActivity().getApplicationContext(), size));
canvas.drawText(text, x, y, stkPaint);
canvas.drawText(text2, x, y + textRect.height(), stkPaint);
canvas.drawText(text3, x, y + textRect.height() + textRect2.height(), stkPaint);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, arrayOutputStream);
byte[] imageArray = arrayOutputStream.toByteArray();
DatabaseData.PhotoString = Base64.encodeToString(imageArray, Base64.DEFAULT);
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Unable to edit picture", Toast.LENGTH_SHORT).show();
}
}
//Method used from someone else!
private int convertToPixels(Context context, int nDP) {
final float conversionScale = context.getResources().getDisplayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f);
}
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog = new ProgressDialog(getActivity());
protected void onPreExecute() {
progressDialog.setMessage("Adding to database");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
//locatie = DescriptionFragmentSession.getLocation();
//descriptie = DescriptionFragmentSession.getDescription();
}
@Override
protected Void doInBackground(Void... params) {
try {
Uid = DatabaseData.userData.getString("uid");
} catch (JSONException e) {
e.printStackTrace();
}
if (WelcomeActivity.Username == null) {
try {
WelcomeActivity.Username = String.valueOf(DatabaseData.userData.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
} else {//gewoon zo laten :)
}
DatabaseComClass.Session(Uid, locatie, descriptie, Math.round(height * 100.0) / 100.0 ,String.valueOf(elapsedMillis), DatabaseData.PhotoString, progressDialog);
return null;
}
protected void onPostExecute(Void v) {
try {
//Close the progressDialog!
this.progressDialog.dismiss();
if (DatabaseData.userData.optString("success").toString().equals("1")) {
super.onPostExecute(v);
Toast.makeText(getActivity(), "Saved data to database", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), WelcomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(intent);
} else if (DatabaseData.userData.optString("error").toString().equals("1")) {
Toast.makeText(getActivity(), jsonResponse.optString("error_msg").toString(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onCancelled() {
Toast.makeText(getView().getContext(), "Can't login", Toast.LENGTH_SHORT).show();
}
}
}
| AP-IT-GH/GuiTool | app/src/main/java/com/ap/brecht/guitool/StopwatchFragment.java | 4,743 | //gewoon zo laten :) | line_comment | nl | package com.ap.brecht.guitool;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.Random;
/**
* Created by hannelore on 22/04/2015.
*/
public class StopwatchFragment extends Fragment implements View.OnClickListener, SensorEventListener {
//Sensor variables
private Sensor mSensor;
private SensorManager mSensorManager;
private AcceleroFilter xFilter = new AcceleroFilter();
private AcceleroFilter yFilter = new AcceleroFilter();
private AcceleroFilter zFilter = new AcceleroFilter();
private double xFiltered;
private double yFiltered;
private double zFiltered;
private float[] orientationValues = new float[3];
private float rotation[] = new float[16];
private double startTime;
private double elapsedTime;
private double oldElapsedTime;
private double velocity = 0;
private double oldVelocity = 0;
private double noVelocityCounter = 0;
private double correctedVelocity;
private double oldCorrectedVelocity = Double.NaN;
private double oldOldCorrectedVelocity = Double.NaN;
private double height;
private double oldHeight;
//Chrono variables
private Chronometer chrono;
long timeWhenStopped = 0;
long elapsedMillis;
int secs, currentmin, lastmin;
//GUI
private View view;
private ImageButton startButton;
private TextView txtStart;
private ImageButton pauzeButton;
private TextView txtPauze;
private ImageButton stopButton;
private TextView txtStop;
private ImageButton resetButton;
private TextView txtReset;
private TextView txtHeight;
private TextView txtSnelheid;
private String locatie;
private String descriptie;
private String Uid;
JSONObject jsonResponse;
private TextToSpeech SayTime;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_stopwatch, container, false);
chrono = (Chronometer) view.findViewById(R.id.timer);
startButton = (ImageButton) view.findViewById(R.id.btnStart);
startButton.setOnClickListener(this);
stopButton = (ImageButton) view.findViewById(R.id.btnStop);
stopButton.setOnClickListener(this);
pauzeButton = (ImageButton) view.findViewById(R.id.btnPauze);
pauzeButton.setOnClickListener(this);
resetButton = (ImageButton) view.findViewById(R.id.btnReset);
resetButton.setOnClickListener(this);
txtStart = (TextView) view.findViewById(R.id.txtStart);
txtReset = (TextView) view.findViewById(R.id.txtReset);
txtPauze = (TextView) view.findViewById(R.id.txtPauze);
txtStop = (TextView) view.findViewById(R.id.txtStop);
txtHeight = (TextView) view.findViewById(R.id.txtHeight);
txtHeight.setText("21m");
//txtSnelheid= (TextView) view.findViewById(R.id.SpeedStop);
SayTime = new TextToSpeech(getActivity().getApplicationContext(),
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
SayTime.setLanguage(Locale.US);
}
}
});
//Set start text to agreed notation
chrono.setText("00:00:00");
chrono.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer c) {
elapsedMillis = SystemClock.elapsedRealtime() - c.getBase();
if (elapsedMillis > 3600000L) {
c.setFormat("0%s");
} else {
c.setFormat("00:%s");
}
secs = ((int) (elapsedMillis)) / 1000;
currentmin = secs / 60;
//Check if we need to speak the minutes
//@ the moment it's every minute
String alertTime = ((SessionActivity) getActivity()).AlertTime;
if (alertTime.equals("30s")) {
if (secs % 30 == 0) {
speakText();
}
} else if (alertTime.equals("1m")) {
if (lastmin != currentmin || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
} else if (alertTime.equals("5m")) {
if ((lastmin != currentmin && (currentmin % 5) == 0) || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
} else if (alertTime.equals("10m")) {
if ((lastmin != currentmin && (currentmin % 10) == 0) || (currentmin==0 && secs==0)) {
speakText();
}
lastmin = currentmin;
}
}
});
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
chrono.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
chrono.start();
showStopButton();
break;
case R.id.btnPauze:
timeWhenStopped = chrono.getBase() - SystemClock.elapsedRealtime();
chrono.stop();
hideStopButton();
break;
case R.id.btnStop:
QustomDialogBuilder stopAlert = new QustomDialogBuilder(v.getContext(), AlertDialog.THEME_HOLO_DARK);
stopAlert.setMessage(Html.fromHtml("<font color=#" + Integer.toHexString(getActivity().getResources().getColor(R.color.white) & 0x00ffffff) + ">Do you want to quit your session?"));
stopAlert.setTitle("ClimbUP");
stopAlert.setTitleColor("#" + Integer.toHexString(getResources().getColor(R.color.Orange) & 0x00ffffff));
stopAlert.setDividerColor("#" + Integer.toHexString(getResources().getColor(R.color.Orange) & 0x00ffffff));
stopAlert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
stopAlert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
chrono.stop();
if (mSensorManager != null) {
mSensorManager.unregisterListener(StopwatchFragment.this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION));
mSensorManager.unregisterListener(StopwatchFragment.this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR));
}
savePicture();
new MyAsyncTask().execute();
}
});
stopAlert.create().show();
break;
case R.id.btnReset:
chrono.setBase(SystemClock.elapsedRealtime());
timeWhenStopped = 0;
chrono.stop();
break;
}
}
private void showStopButton() {
StartSensor();
startButton.setVisibility(View.GONE);
txtStart.setVisibility(View.GONE);
resetButton.setVisibility(View.GONE);
txtReset.setVisibility(View.GONE);
pauzeButton.setVisibility(View.VISIBLE);
txtPauze.setVisibility(View.VISIBLE);
stopButton.setVisibility(View.VISIBLE);
txtStop.setVisibility(View.VISIBLE);
}
private void hideStopButton() {
startButton.setVisibility(View.VISIBLE);
txtStart.setVisibility(View.VISIBLE);
resetButton.setVisibility(View.VISIBLE);
txtReset.setVisibility(View.VISIBLE);
pauzeButton.setVisibility(View.GONE);
txtPauze.setVisibility(View.GONE);
stopButton.setVisibility(View.GONE);
txtStop.setVisibility(View.GONE);
}
private void StartSensor()
{
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR) != null){
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_GAME);
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), SensorManager.SENSOR_DELAY_GAME);
}
else {
//DO SHIT
}
startTime = System.currentTimeMillis() / 1000;
}
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
public void onSensorChanged(SensorEvent event)
{
mSensor = event.sensor;
if (mSensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
xFiltered = xFilter.Filter(event.values[0]);
yFiltered = yFilter.Filter(event.values[1]);
zFiltered = zFilter.Filter(event.values[2]);
}
else if(mSensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
{
SensorManager.getRotationMatrixFromVector(rotation, event.values);
SensorManager.getOrientation(rotation, orientationValues);
double azimuth = Math.toDegrees(orientationValues[0]);
double pitch = Math.toDegrees(orientationValues[1]);
double roll = Math.toDegrees(orientationValues[2]);
double ax = xFiltered * Math.cos(Math.toRadians(roll)) + yFiltered * Math.cos(Math.toRadians(90) - Math.toRadians(roll));
double ay = yFiltered * Math.cos(Math.toRadians(90) + Math.toRadians(pitch)) + xFiltered * Math.cos(Math.toRadians(90) + Math.toRadians(roll)) + zFiltered * Math.cos(Math.toRadians(pitch)) * Math.cos(Math.toRadians(roll));
elapsedTime = (System.currentTimeMillis() / 1000.0) - startTime;
velocity = oldVelocity + (ay * (elapsedTime - oldElapsedTime));
if(ay < 0.6 && ay > -0.6 && velocity != 0)
noVelocityCounter++;
else
noVelocityCounter = 0;
if((noVelocityCounter > 2 && oldOldCorrectedVelocity < 0.5 && oldOldCorrectedVelocity > -0.5) || Math.abs(oldOldCorrectedVelocity) > 2 || Double.isNaN(oldOldCorrectedVelocity))
correctedVelocity = 0;
else
correctedVelocity = oldCorrectedVelocity + (ay * (elapsedTime - oldElapsedTime)) * 1.2;
if (correctedVelocity > 2 || correctedVelocity < - 2)
correctedVelocity = 0;
height = oldHeight + (correctedVelocity * (elapsedTime - oldElapsedTime));
oldElapsedTime = elapsedTime;
oldVelocity = velocity;
oldOldCorrectedVelocity = oldCorrectedVelocity;
oldCorrectedVelocity = correctedVelocity;
oldHeight= height;
//tvVelocity.setText(String.valueOf(velocity));
txtHeight.setText(String.format("%.2f", height) + "m");
}
}
private void speakText() {
String toSpeak = "";
if (secs == 0 && currentmin == 0) {
Random r = new Random();
int fun = r.nextInt(7);//random number from 0-6
switch (fun) {
case 0:
toSpeak = "Happy Climbing";
break;
case 1:
toSpeak = "Have fun climbing";
break;
case 2:
toSpeak = "Let's climb";
break;
case 3:
toSpeak = "Enjoy your climb";
break;
case 4:
toSpeak = "You will climb and I will follow";
break;
case 5:
toSpeak = "Let's go";
break;
case 6:
toSpeak = "Go hard, or go home";
default:
break;
}
} else if (secs % 30 == 0 && secs % 60 != 0) {
if (currentmin == 0) {
toSpeak = "You have been climbing for " + "30" + " seconds";
} else if (currentmin == 1) {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minute and " + "30" + " seconds";
} else
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minutes and " + "30" + " seconds";
} else if (currentmin == 1) {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minute";
} else {
toSpeak = "You have been climbing for " + String.valueOf(currentmin) + " minutes";
}
SayTime.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
private void savePicture() {
locatie = DescriptionFragmentSession.getLocation();
descriptie = DescriptionFragmentSession.getDescription();
try {
if (DatabaseData.PhotoString == null)
return;
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeFile(DatabaseData.PhotoString).copy(Bitmap.Config.RGB_565, true);
Typeface tf = Typeface.create("sans-serif-condensed", Typeface.BOLD);
int x = 50;
int y = 75;
int size = 32;
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE); // Text Color
paint.setTypeface(tf);
paint.setTextSize(convertToPixels(getActivity().getApplicationContext(), size));
String text = locatie;
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
String text2 = descriptie;
Rect textRect2 = new Rect();
paint.getTextBounds(text2, 0, text2.length(), textRect2);
String text3 = String.format("%.2f", height) + "m";
canvas.drawText(text, x, y, paint);
canvas.drawText(text2, x, y + textRect.height(), paint);
canvas.drawText(text3, x, y + textRect.height() + textRect2.height(), paint);
//Add outline to text!
Paint stkPaint = new Paint();
stkPaint.setTypeface(tf);
stkPaint.setStyle(Paint.Style.STROKE);
stkPaint.setStrokeWidth(size / 10);
stkPaint.setColor(Color.BLACK);
stkPaint.setTextSize(convertToPixels(getActivity().getApplicationContext(), size));
canvas.drawText(text, x, y, stkPaint);
canvas.drawText(text2, x, y + textRect.height(), stkPaint);
canvas.drawText(text3, x, y + textRect.height() + textRect2.height(), stkPaint);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, arrayOutputStream);
byte[] imageArray = arrayOutputStream.toByteArray();
DatabaseData.PhotoString = Base64.encodeToString(imageArray, Base64.DEFAULT);
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Unable to edit picture", Toast.LENGTH_SHORT).show();
}
}
//Method used from someone else!
private int convertToPixels(Context context, int nDP) {
final float conversionScale = context.getResources().getDisplayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f);
}
class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog = new ProgressDialog(getActivity());
protected void onPreExecute() {
progressDialog.setMessage("Adding to database");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
//locatie = DescriptionFragmentSession.getLocation();
//descriptie = DescriptionFragmentSession.getDescription();
}
@Override
protected Void doInBackground(Void... params) {
try {
Uid = DatabaseData.userData.getString("uid");
} catch (JSONException e) {
e.printStackTrace();
}
if (WelcomeActivity.Username == null) {
try {
WelcomeActivity.Username = String.valueOf(DatabaseData.userData.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
} else {//gewoo<SUF>
}
DatabaseComClass.Session(Uid, locatie, descriptie, Math.round(height * 100.0) / 100.0 ,String.valueOf(elapsedMillis), DatabaseData.PhotoString, progressDialog);
return null;
}
protected void onPostExecute(Void v) {
try {
//Close the progressDialog!
this.progressDialog.dismiss();
if (DatabaseData.userData.optString("success").toString().equals("1")) {
super.onPostExecute(v);
Toast.makeText(getActivity(), "Saved data to database", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), WelcomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(intent);
} else if (DatabaseData.userData.optString("error").toString().equals("1")) {
Toast.makeText(getActivity(), jsonResponse.optString("error_msg").toString(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onCancelled() {
Toast.makeText(getView().getContext(), "Can't login", Toast.LENGTH_SHORT).show();
}
}
}
|
57273_24 | package be.eaict.stretchalyzer2;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
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.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GridLabelRenderer;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import be.eaict.stretchalyzer2.DOM.FBRepository;
import be.eaict.stretchalyzer2.DOM.GlobalData;
import be.eaict.stretchalyzer2.DOM.fxDatapoint;
/**
* Created by Cé on 4/11/2018.
*/
public class ExerciseActivity extends AppCompatActivity implements SensorEventListener {
//declaration sensor
Sensor accSensor;
// graph declarations
private LineGraphSeries<DataPoint> series;
private int mSec;
private double angle;
//timer
private TextView countdown;
private CountDownTimer timer;
private long mTimeLeftInMillis = GlobalData.startTime;
//database declarations
DatabaseReference databaseFXDatapoint;
List<Double> angles = new ArrayList<>();
FBRepository fbrepo = new FBRepository();
//oncreate method
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_exercise );
this.setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
createAccelerometer();
createGraphview();
changePics();
counter();
databaseFXDatapoint = fbrepo.instantiate();
}
//timer
public void counter(){
countdown = findViewById(R.id.countdown);
timer = new CountDownTimer(mTimeLeftInMillis,1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis= millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
if(GlobalData.Sensor){
fbrepo.SaveToDatabase( mSec, angles );
}
finish();
}
}.start();
}
//update timer text
public void updateCountDownText(){
int minutes =(int) (mTimeLeftInMillis/1000) /60;
int seconds = (int) (mTimeLeftInMillis/1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d",minutes,seconds);
countdown.setText(timeLeftFormatted);
}
//method accelerometer
public void createAccelerometer() {
//permission
SensorManager sensorManager = (SensorManager) getSystemService( Context.SENSOR_SERVICE );
// accelerometer waarde geven
accSensor = sensorManager.getDefaultSensor( Sensor.TYPE_ACCELEROMETER );
// eventlistener
sensorManager.registerListener( ExerciseActivity.this, accSensor, SensorManager.SENSOR_DELAY_NORMAL );
}
//veranderen van kleur aan de hand van settings met globale variable
private void changePics(){
ImageView bol1, bol2;
bol1 = findViewById( R.id.btnbol1 );
bol2 = findViewById( R.id.btnbol2 );
if (GlobalData.Sensor) {
bol1.setImageResource(R.drawable.groen);
bol2.setImageResource(R.drawable.rood);
}else {
bol1.setImageResource(R.drawable.rood);
bol2.setImageResource( R.drawable.groen);}
}
//method graphview
private void createGraphview() {
// graphvieuw aanmaken
GraphView graph = (GraphView) findViewById( R.id.graph2 );
series = new LineGraphSeries<DataPoint>();
graph.addSeries( series );
//vertical axsis title
graph.getGridLabelRenderer().setVerticalAxisTitle( "Angle" );
graph.getGridLabelRenderer().setVerticalAxisTitleColor( Color.BLUE );
graph.getGridLabelRenderer().setVerticalAxisTitleTextSize( 40 );
//layout grafiek
graph.getGridLabelRenderer().setGridColor( Color.BLACK );
graph.getGridLabelRenderer().setHighlightZeroLines( true );
graph.getGridLabelRenderer().setVerticalLabelsColor( Color.BLACK );
graph.getGridLabelRenderer().setGridStyle( GridLabelRenderer.GridStyle.HORIZONTAL );
graph.getViewport().setBackgroundColor( Color.WHITE );
//miliseconds zichtbaar
graph.getGridLabelRenderer().setHorizontalLabelsVisible( true );
// vieuwport waarde instellen
graph.getViewport().setYAxisBoundsManual( true );
graph.getViewport().setMinY(-180);
graph.getViewport().setMaxY(150 );
// vieuwport waarde tussen 0 en maxvalue array (ms) x-as
graph.getViewport().setXAxisBoundsManual( true );
graph.getViewport().setMinX( -2500 );
graph.getViewport().setMaxX( 2500 );
//layout data
series.setTitle( "Stretching" );
series.setColor( Color.RED );
series.setDrawDataPoints( true );
series.setDataPointsRadius( 6 );
series.setThickness( 4 );
}
//onResume nodig voor live data
@Override
protected void onResume() {
super.onResume();
if (GlobalData.Sensor) {
// simulate real time met thread
new Thread( new Runnable() {
@Override
public void run() {
//(12000 komt van 10 minuten * 60 seconden * 20(1 seconde om de 50miliseconden)
for (int i = 0; i < 12000; i++) {
runOnUiThread( new Runnable() {
@Override
public void run() {
addDatapoints();
}
} );
// sleep om de livedata te vertragen tot op ingegeven waarde
try {
Thread.sleep( 50);
} catch (InterruptedException e) {
// errors
}
}
}
} ).start();
}
}
//datapoints toevoegen aan runnable
private void addDatapoints() {
//(12000 komt van 10 minuten * 60 seconden * 20(om de 50 miliseconden)
series.appendData( new DataPoint( mSec += 50, angle ), true, 12000 );
if (Double.isNaN( angle )) {
angle = 0;
}
angles.add( angle );
}
//sensorEventlistener override method
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
//sensorEventlistener override method
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
//formule angle acc (werkt niet)
angle = Math.asin( sensorEvent.values[1] / 9.81 ) / Math.PI * 180;
}
@Override
public void onBackPressed() {
}
//terug knop
public void onClickToHome(View view) {
if(GlobalData.Sensor){
fbrepo.SaveToDatabase( mSec, angles );
}
super.onBackPressed();
}
} | AP-IT-GH/IP18-StretchAnalyzer02 | app/src/main/java/be/eaict/stretchalyzer2/ExerciseActivity.java | 2,030 | //datapoints toevoegen aan runnable | line_comment | nl | package be.eaict.stretchalyzer2;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
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.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GridLabelRenderer;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import be.eaict.stretchalyzer2.DOM.FBRepository;
import be.eaict.stretchalyzer2.DOM.GlobalData;
import be.eaict.stretchalyzer2.DOM.fxDatapoint;
/**
* Created by Cé on 4/11/2018.
*/
public class ExerciseActivity extends AppCompatActivity implements SensorEventListener {
//declaration sensor
Sensor accSensor;
// graph declarations
private LineGraphSeries<DataPoint> series;
private int mSec;
private double angle;
//timer
private TextView countdown;
private CountDownTimer timer;
private long mTimeLeftInMillis = GlobalData.startTime;
//database declarations
DatabaseReference databaseFXDatapoint;
List<Double> angles = new ArrayList<>();
FBRepository fbrepo = new FBRepository();
//oncreate method
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_exercise );
this.setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
createAccelerometer();
createGraphview();
changePics();
counter();
databaseFXDatapoint = fbrepo.instantiate();
}
//timer
public void counter(){
countdown = findViewById(R.id.countdown);
timer = new CountDownTimer(mTimeLeftInMillis,1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis= millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
if(GlobalData.Sensor){
fbrepo.SaveToDatabase( mSec, angles );
}
finish();
}
}.start();
}
//update timer text
public void updateCountDownText(){
int minutes =(int) (mTimeLeftInMillis/1000) /60;
int seconds = (int) (mTimeLeftInMillis/1000) % 60;
String timeLeftFormatted = String.format(Locale.getDefault(),"%02d:%02d",minutes,seconds);
countdown.setText(timeLeftFormatted);
}
//method accelerometer
public void createAccelerometer() {
//permission
SensorManager sensorManager = (SensorManager) getSystemService( Context.SENSOR_SERVICE );
// accelerometer waarde geven
accSensor = sensorManager.getDefaultSensor( Sensor.TYPE_ACCELEROMETER );
// eventlistener
sensorManager.registerListener( ExerciseActivity.this, accSensor, SensorManager.SENSOR_DELAY_NORMAL );
}
//veranderen van kleur aan de hand van settings met globale variable
private void changePics(){
ImageView bol1, bol2;
bol1 = findViewById( R.id.btnbol1 );
bol2 = findViewById( R.id.btnbol2 );
if (GlobalData.Sensor) {
bol1.setImageResource(R.drawable.groen);
bol2.setImageResource(R.drawable.rood);
}else {
bol1.setImageResource(R.drawable.rood);
bol2.setImageResource( R.drawable.groen);}
}
//method graphview
private void createGraphview() {
// graphvieuw aanmaken
GraphView graph = (GraphView) findViewById( R.id.graph2 );
series = new LineGraphSeries<DataPoint>();
graph.addSeries( series );
//vertical axsis title
graph.getGridLabelRenderer().setVerticalAxisTitle( "Angle" );
graph.getGridLabelRenderer().setVerticalAxisTitleColor( Color.BLUE );
graph.getGridLabelRenderer().setVerticalAxisTitleTextSize( 40 );
//layout grafiek
graph.getGridLabelRenderer().setGridColor( Color.BLACK );
graph.getGridLabelRenderer().setHighlightZeroLines( true );
graph.getGridLabelRenderer().setVerticalLabelsColor( Color.BLACK );
graph.getGridLabelRenderer().setGridStyle( GridLabelRenderer.GridStyle.HORIZONTAL );
graph.getViewport().setBackgroundColor( Color.WHITE );
//miliseconds zichtbaar
graph.getGridLabelRenderer().setHorizontalLabelsVisible( true );
// vieuwport waarde instellen
graph.getViewport().setYAxisBoundsManual( true );
graph.getViewport().setMinY(-180);
graph.getViewport().setMaxY(150 );
// vieuwport waarde tussen 0 en maxvalue array (ms) x-as
graph.getViewport().setXAxisBoundsManual( true );
graph.getViewport().setMinX( -2500 );
graph.getViewport().setMaxX( 2500 );
//layout data
series.setTitle( "Stretching" );
series.setColor( Color.RED );
series.setDrawDataPoints( true );
series.setDataPointsRadius( 6 );
series.setThickness( 4 );
}
//onResume nodig voor live data
@Override
protected void onResume() {
super.onResume();
if (GlobalData.Sensor) {
// simulate real time met thread
new Thread( new Runnable() {
@Override
public void run() {
//(12000 komt van 10 minuten * 60 seconden * 20(1 seconde om de 50miliseconden)
for (int i = 0; i < 12000; i++) {
runOnUiThread( new Runnable() {
@Override
public void run() {
addDatapoints();
}
} );
// sleep om de livedata te vertragen tot op ingegeven waarde
try {
Thread.sleep( 50);
} catch (InterruptedException e) {
// errors
}
}
}
} ).start();
}
}
//datap<SUF>
private void addDatapoints() {
//(12000 komt van 10 minuten * 60 seconden * 20(om de 50 miliseconden)
series.appendData( new DataPoint( mSec += 50, angle ), true, 12000 );
if (Double.isNaN( angle )) {
angle = 0;
}
angles.add( angle );
}
//sensorEventlistener override method
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
//sensorEventlistener override method
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
//formule angle acc (werkt niet)
angle = Math.asin( sensorEvent.values[1] / 9.81 ) / Math.PI * 180;
}
@Override
public void onBackPressed() {
}
//terug knop
public void onClickToHome(View view) {
if(GlobalData.Sensor){
fbrepo.SaveToDatabase( mSec, angles );
}
super.onBackPressed();
}
} |
83139_13 | package com.example.loginregister;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.loginregister.ui.dashboard.DashboardFragment;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.storage.StorageReference;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static java.lang.Integer.parseInt;
import static java.util.logging.Logger.global;
public class ScanActivity extends AppCompatActivity {
//public static final int CAMERA_PERMISSION_CODE = 100;
private SurfaceView surfaceView;
CameraSource cameraSource;
private TextView textView;
private BarcodeDetector barcodeDetector;
//private Button camera;
private Button addGrowbox;
String wegschrijven;
// firebaseshizzle
DatabaseReference reff;
FirebaseUser muser;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
String userID, _naam, _growing, _url,_uname,_phone,_image,_email,_currentGrow,_Coverimage,_amountH,_amountB;
int amount, amount2;
Map<String, Object> box = new HashMap<>();
Map<String, Object> userd = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
surfaceView = findViewById(R.id.camera);
textView = findViewById(R.id.textScan);
//camera = findViewById(R.id.ScanCamera);
addGrowbox = findViewById(R.id.AddGrowbox);
addGrowbox.setVisibility(View.INVISIBLE);
barcodeDetector = new BarcodeDetector.Builder(getApplicationContext()).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource = new CameraSource.Builder(getApplicationContext(),barcodeDetector).setRequestedPreviewSize(640,480).build();
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
muser = FirebaseAuth.getInstance().getCurrentUser();
userID = muser.getUid();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try{
cameraSource.start(holder);
}catch (IOException e){
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
@Override
public void release() {
}
@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcode = detections.getDetectedItems();
if(qrcode.size()!=0){
textView.post(new Runnable() {
@Override
public void run() {
textView.setText(qrcode.valueAt(0).displayValue);
addGrowbox.setVisibility(View.VISIBLE);
}
});
}
}
});
addGrowbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle=new Bundle();
String valueToegevoegd = textView.getText().toString();
setAddGrowbox(valueToegevoegd);
//set Fragmentclass Arguments
// DashboardFragment fragobj=new DashboardFragment();
// fragobj.setArguments(bundle);
// FragmentManager fm= getSupportFragmentManager();
// DashboardFragment fragment = new DashboardFragment();
surfaceView.setVisibility(View.INVISIBLE);
textView.setVisibility(View.INVISIBLE);
addGrowbox.setVisibility(View.INVISIBLE);
// fm.beginTransaction().replace(R.id.scanActivity,fragment).commit();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
},5000);
}
});
}
// growbox toevoegen in de database -->
private void setAddGrowbox(String naam){
Log.d("growboxnaam", naam);
DocumentReference documentReference = mStore.collection("Growboxes").document(naam);
documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
_naam = value.getString("naam");
_growing = value.getString("growing");
// _growing= "iets";
_url = value.getString("url");
int amount = getAmountGrowboxes();
amount2 = amount+=2;
Log.d("AMOUNTBOXES", "value" + amount);
String aantal = String.valueOf(amount);
// onderstaande moet van realtime growbox worden gehaald
box.put("naam",naam);
box.put("url", _url);
box.put("growing", _growing);
DocumentReference documentref = mStore.collection("Users").document(userID);
documentref.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
_uname = value.getString("uname");
_amountH = value.getString("amountHarvests");
_Coverimage = value.getString("coverImage");
_phone = value.getString("phone");
_image = value.getString("image");
_email = value.getString("email");
DocumentReference dr = mStore.collection("Users").document(userID);
wegschrijven = String.valueOf(amount2);
userd.put("amountBoxes", wegschrijven);
userd.put("currentGrowbox", naam);
userd.put("uname", _uname);
userd.put("amountHarvests", _amountH);
userd.put("phone", _phone);
userd.put("image", _image);
userd.put("email", _email);
userd.put("coverImage", _Coverimage);
dr.set(userd);
}
});
documentref.collection("0").document(aantal).set(box);
addGrowbox.setVisibility(View.INVISIBLE);
}
});
}
// verkrijgen van het aantal growboxes van de user
private int getAmountGrowboxes(){
DocumentReference documentReference = mStore.collection("Users").document(userID);
documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException error) {
String _amountBoxes = documentSnapshot.getString("amountBoxes");
amount = Integer.parseInt(_amountBoxes);
}
});
Log.d("amountboxes", String.valueOf(amount));
return amount;
}
// verkrijgen info growbox die gescant is --> krijgen van de realtime database.
private String[] getGrowboxdata(String naam){
final String[] _naam = new String[1];
final String[] _currentGrow = new String[1];
final String[] _url = new String[1];
final String[] _data = new String[3];
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child(naam).child("naam");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
_data[0] = dataSnapshot.getValue(String.class);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
mDatabase = FirebaseDatabase.getInstance().getReference().child(naam).child("CurrentGrowShedule");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
_data[1] = dataSnapshot.getValue(String.class);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
mDatabase = FirebaseDatabase.getInstance().getReference().child(naam).child("url");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
_data[2] = dataSnapshot.getValue(String.class);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
return _data;
}
} | AP-IT-GH/ap-valley-20-21-apv02 | app/src/main/java/com/example/loginregister/ScanActivity.java | 2,472 | // verkrijgen van het aantal growboxes van de user | line_comment | nl | package com.example.loginregister;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.loginregister.ui.dashboard.DashboardFragment;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.storage.StorageReference;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static java.lang.Integer.parseInt;
import static java.util.logging.Logger.global;
public class ScanActivity extends AppCompatActivity {
//public static final int CAMERA_PERMISSION_CODE = 100;
private SurfaceView surfaceView;
CameraSource cameraSource;
private TextView textView;
private BarcodeDetector barcodeDetector;
//private Button camera;
private Button addGrowbox;
String wegschrijven;
// firebaseshizzle
DatabaseReference reff;
FirebaseUser muser;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
String userID, _naam, _growing, _url,_uname,_phone,_image,_email,_currentGrow,_Coverimage,_amountH,_amountB;
int amount, amount2;
Map<String, Object> box = new HashMap<>();
Map<String, Object> userd = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
surfaceView = findViewById(R.id.camera);
textView = findViewById(R.id.textScan);
//camera = findViewById(R.id.ScanCamera);
addGrowbox = findViewById(R.id.AddGrowbox);
addGrowbox.setVisibility(View.INVISIBLE);
barcodeDetector = new BarcodeDetector.Builder(getApplicationContext()).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource = new CameraSource.Builder(getApplicationContext(),barcodeDetector).setRequestedPreviewSize(640,480).build();
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
muser = FirebaseAuth.getInstance().getCurrentUser();
userID = muser.getUid();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try{
cameraSource.start(holder);
}catch (IOException e){
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
@Override
public void release() {
}
@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcode = detections.getDetectedItems();
if(qrcode.size()!=0){
textView.post(new Runnable() {
@Override
public void run() {
textView.setText(qrcode.valueAt(0).displayValue);
addGrowbox.setVisibility(View.VISIBLE);
}
});
}
}
});
addGrowbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle=new Bundle();
String valueToegevoegd = textView.getText().toString();
setAddGrowbox(valueToegevoegd);
//set Fragmentclass Arguments
// DashboardFragment fragobj=new DashboardFragment();
// fragobj.setArguments(bundle);
// FragmentManager fm= getSupportFragmentManager();
// DashboardFragment fragment = new DashboardFragment();
surfaceView.setVisibility(View.INVISIBLE);
textView.setVisibility(View.INVISIBLE);
addGrowbox.setVisibility(View.INVISIBLE);
// fm.beginTransaction().replace(R.id.scanActivity,fragment).commit();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
},5000);
}
});
}
// growbox toevoegen in de database -->
private void setAddGrowbox(String naam){
Log.d("growboxnaam", naam);
DocumentReference documentReference = mStore.collection("Growboxes").document(naam);
documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
_naam = value.getString("naam");
_growing = value.getString("growing");
// _growing= "iets";
_url = value.getString("url");
int amount = getAmountGrowboxes();
amount2 = amount+=2;
Log.d("AMOUNTBOXES", "value" + amount);
String aantal = String.valueOf(amount);
// onderstaande moet van realtime growbox worden gehaald
box.put("naam",naam);
box.put("url", _url);
box.put("growing", _growing);
DocumentReference documentref = mStore.collection("Users").document(userID);
documentref.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
_uname = value.getString("uname");
_amountH = value.getString("amountHarvests");
_Coverimage = value.getString("coverImage");
_phone = value.getString("phone");
_image = value.getString("image");
_email = value.getString("email");
DocumentReference dr = mStore.collection("Users").document(userID);
wegschrijven = String.valueOf(amount2);
userd.put("amountBoxes", wegschrijven);
userd.put("currentGrowbox", naam);
userd.put("uname", _uname);
userd.put("amountHarvests", _amountH);
userd.put("phone", _phone);
userd.put("image", _image);
userd.put("email", _email);
userd.put("coverImage", _Coverimage);
dr.set(userd);
}
});
documentref.collection("0").document(aantal).set(box);
addGrowbox.setVisibility(View.INVISIBLE);
}
});
}
// verkr<SUF>
private int getAmountGrowboxes(){
DocumentReference documentReference = mStore.collection("Users").document(userID);
documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException error) {
String _amountBoxes = documentSnapshot.getString("amountBoxes");
amount = Integer.parseInt(_amountBoxes);
}
});
Log.d("amountboxes", String.valueOf(amount));
return amount;
}
// verkrijgen info growbox die gescant is --> krijgen van de realtime database.
private String[] getGrowboxdata(String naam){
final String[] _naam = new String[1];
final String[] _currentGrow = new String[1];
final String[] _url = new String[1];
final String[] _data = new String[3];
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child(naam).child("naam");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
_data[0] = dataSnapshot.getValue(String.class);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
mDatabase = FirebaseDatabase.getInstance().getReference().child(naam).child("CurrentGrowShedule");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
_data[1] = dataSnapshot.getValue(String.class);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
mDatabase = FirebaseDatabase.getInstance().getReference().child(naam).child("url");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
_data[2] = dataSnapshot.getValue(String.class);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
return _data;
}
} |
155819_36 | package com.interproject.piago;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gms.common.annotation.KeepForSdkWithFieldsAndMethods;
import org.billthefarmer.mididriver.MidiDriver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class PlayPiago extends AppCompatActivity {
public String Instrument;
//For playing piano with different instruments in midi-player
private MidiDriver midiDriver;
public PiagoMidiDriver piagoMidiDriver;
private int[] config;
public Button instrumentButton;
//BLUETOOTH STUFF
private Handler mHandler;
private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
private ConnectedThread mConnectedThread;
private BluetoothAdapter mBTAdapter;
private Button mButtonAutoCnct;
// #defines for identifying shared types between calling functions
private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update
private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier
public String ReceivedBluetoothSignal;
public String CheckReceived;
public OctaveSelector octaveSelector;
//LearnSongs
public Boolean songStarted = false;
public LearnSongs learn = new LearnSongs();
public Integer noteNumber = 0;
public Button tileToPress;
public Boolean noteIsShown = false;
SignalCheckerThread sChecker;
PreviewSongThread previewSongThread;
public Boolean LearningMode = false;
public Switch learnToggle;
//Buttons
Button previewButton;
Button startButton;
Button octaveHigher;
Button octaveLower;
Button selectSong;
TextView activeSong;
byte[] activeSongByteArray = new byte[]{};
int[] activeSongIntArray = new int[]{};
AlertDialogBuilder alertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_piago);
mButtonAutoCnct = (Button) findViewById(R.id.button_autocnct);
mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
mButtonAutoCnct.setBackgroundColor(Color.RED);
mButtonAutoCnct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread() {
public void run() {
boolean fail = false;
// Change adress to static MAC adress
// BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
BluetoothDevice device = mBTAdapter.getRemoteDevice("98:D3:31:FD:17:0A");
//DEVICE FINLAND
//BluetoothDevice device = mBTAdapter.getRemoteDevice("B4:E6:2D:DF:4B:83");
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection.
try {
mBTSocket.connect();
} catch (IOException e) {
try {
fail = true;
mBTSocket.close();
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
if (fail == false) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mButtonAutoCnct.setBackgroundColor(Color.GREEN);
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, "Piago Keyboard")
.sendToTarget();
}
}
}.start();
}
});
mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == MESSAGE_READ) {
String readMessage = null;
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
CheckReceived = "1";
ReceivedBluetoothSignal = (readMessage.substring(0, 5));
Log.d("BTRECEIVED", "handleMessage: receiving msg from arduino" + ReceivedBluetoothSignal);
}
}
};
ReceivedBluetoothSignal = null;
CheckReceived = null;
Instrument = "piano";
//Midi-player
midiDriver = new MidiDriver();
piagoMidiDriver = new PiagoMidiDriver(midiDriver);
instrumentButton = findViewById(R.id.button_change_instrument);
//Lower / Higher notes
octaveSelector = new OctaveSelector();
//Learning
tileToPress = findViewById(R.id.tile_white_0);
sChecker = new SignalCheckerThread(this);
learnToggle = findViewById(R.id.switch_piago);
learnToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
LearningMode = true;
octaveSelector.SetOctaveLearn();
} else {
LearningMode = false;
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
}
ModeSwitcher(LearningMode);
}
});
//Buttons
previewButton = findViewById(R.id.button_preview);
startButton = findViewById(R.id.button_start_song);
octaveHigher = findViewById(R.id.button_octave_higher);
octaveLower = findViewById(R.id.button_octave_lower);
selectSong = findViewById(R.id.button_change_song);
activeSong = findViewById(R.id.textView_active_song);
activeSongByteArray = learn.FatherJacob;
activeSongIntArray = learn.FatherJacobTiming;
alertDialog = new AlertDialogBuilder();
}
@Override
protected void onResume() {
super.onResume();
midiDriver.start();
config = midiDriver.config();
learnToggle.setChecked(false);
sChecker.start();
}
@Override
protected void onPause() {
super.onPause();
midiDriver.stop();
}
Button pressedTile;
public void playSound(String sound) {
if (ReceivedBluetoothSignal != null) {
switch (sound) {
case "00000": {
pressedTile = findViewById(R.id.tile_white_0);
PlayNotePause(octaveSelector.ActiveOctaveArray[0], pressedTile);
break;
}
case "00010": {
pressedTile = findViewById(R.id.tile_white_1);
PlayNotePause(octaveSelector.ActiveOctaveArray[2], pressedTile);
break;
}
case "00100": {
pressedTile = findViewById(R.id.tile_white_2);
PlayNotePause(octaveSelector.ActiveOctaveArray[4], pressedTile);
break;
}
case "00110": {
pressedTile = findViewById(R.id.tile_white_3);
PlayNotePause(octaveSelector.ActiveOctaveArray[6], pressedTile);
break;
}
case "00111": {
pressedTile = findViewById(R.id.tile_white_4);
PlayNotePause(octaveSelector.ActiveOctaveArray[7], pressedTile);
break;
}
case "01001": {
pressedTile = findViewById(R.id.tile_white_5);
PlayNotePause(octaveSelector.ActiveOctaveArray[9], pressedTile);
break;
}
case "01011": {
pressedTile = findViewById(R.id.tile_white_6);
PlayNotePause(octaveSelector.ActiveOctaveArray[11], pressedTile);
break;
}
case "01100": {
pressedTile = findViewById(R.id.tile_white_7);
PlayNotePause(octaveSelector.ActiveOctaveArray[12], pressedTile);
break;
}
case "01110": {
pressedTile = findViewById(R.id.tile_white_8);
PlayNotePause(octaveSelector.ActiveOctaveArray[14], pressedTile);
break;
}
case "10000": {
pressedTile = findViewById(R.id.tile_white_9);
PlayNotePause(octaveSelector.ActiveOctaveArray[16], pressedTile);
break;
}
case "10010": {
pressedTile = findViewById(R.id.tile_white_10);
PlayNotePause(octaveSelector.ActiveOctaveArray[18], pressedTile);
break;
}
case "10011": {
pressedTile = findViewById(R.id.tile_white_11);
PlayNotePause(octaveSelector.ActiveOctaveArray[19], pressedTile);
break;
}
case "10101": {
pressedTile = findViewById(R.id.tile_white_12);
PlayNotePause(octaveSelector.ActiveOctaveArray[21], pressedTile);
break;
}
case "10111": {
pressedTile = findViewById(R.id.tile_white_13);
PlayNotePause(octaveSelector.ActiveOctaveArray[23], pressedTile);
break;
}
case "11000": {
pressedTile = findViewById(R.id.tile_white_14);
PlayNotePause(octaveSelector.ActiveOctaveArray[24], pressedTile);
break;
}
case "11010": {
pressedTile = findViewById(R.id.tile_white_15);
PlayNotePause(octaveSelector.ActiveOctaveArray[26], pressedTile);
break;
}
case "11100": {
pressedTile = findViewById(R.id.tile_white_16);
PlayNotePause(octaveSelector.ActiveOctaveArray[28], pressedTile);
break;
}
case "11110": {
pressedTile = findViewById(R.id.tile_white_17);
PlayNotePause(octaveSelector.ActiveOctaveArray[30], pressedTile);
break;
}
case "00001": {
pressedTile = findViewById(R.id.tile_black_0);
PlayNotePause(octaveSelector.ActiveOctaveArray[1], pressedTile);
break;
}
case "00011": {
pressedTile = findViewById(R.id.tile_black_1);
PlayNotePause(octaveSelector.ActiveOctaveArray[3], pressedTile);
break;
}
case "00101": {
pressedTile = findViewById(R.id.tile_black_2);
PlayNotePause(octaveSelector.ActiveOctaveArray[5], pressedTile);
break;
}
case "01000": {
pressedTile = findViewById(R.id.tile_black_3);
PlayNotePause(octaveSelector.ActiveOctaveArray[8], pressedTile);
break;
}
case "01010": {
pressedTile = findViewById(R.id.tile_black_4);
PlayNotePause(octaveSelector.ActiveOctaveArray[10], pressedTile);
break;
}
case "01101": {
pressedTile = findViewById(R.id.tile_black_5);
PlayNotePause(octaveSelector.ActiveOctaveArray[13], pressedTile);
break;
}
case "01111": {
pressedTile = findViewById(R.id.tile_black_6);
PlayNotePause(octaveSelector.ActiveOctaveArray[15], pressedTile);
break;
}
case "10001": {
pressedTile = findViewById(R.id.tile_black_7);
PlayNotePause(octaveSelector.ActiveOctaveArray[17], pressedTile);
break;
}
case "10100": {
pressedTile = findViewById(R.id.tile_black_8);
PlayNotePause(octaveSelector.ActiveOctaveArray[20], pressedTile);
break;
}
case "10110": {
pressedTile = findViewById(R.id.tile_black_9);
PlayNotePause(octaveSelector.ActiveOctaveArray[22], pressedTile);
break;
}
case "11001": {
pressedTile = findViewById(R.id.tile_black_10);
PlayNotePause(octaveSelector.ActiveOctaveArray[25], pressedTile);
break;
}
case "11011": {
pressedTile = findViewById(R.id.tile_black_11);
PlayNotePause(octaveSelector.ActiveOctaveArray[27], pressedTile);
break;
}
case "11101": {
pressedTile = findViewById(R.id.tile_black_12);
PlayNotePause(octaveSelector.ActiveOctaveArray[29], pressedTile);
break;
}
default:
break;
}
ReceivedBluetoothSignal = null;
}
}
//Test method
public void playSoundNow(View view) {
EditText eT = (EditText) findViewById(R.id.testValue);
if (eT.getText().toString().equals("11111")) {
CorrectNotePlayer correctNotePlayer = new CorrectNotePlayer(this);
correctNotePlayer.start();
} else {
ReceivedBluetoothSignal = eT.getText().toString();
}
}
private void PauseMethod(final Button pressedTile) {
pressedTile.setBackgroundResource(R.drawable.tile_pressed);
new CountDownTimer(200, 100) {
public void onFinish() {
pressedTile.setBackground(OriginalBackground(pressedTile.getId()));
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
public void PlayNotePause(byte note, final Button pressedTile) {
piagoMidiDriver.playNote(note);
Log.i("Debugkey", "_______________Note played through PlayNotePause");
PauseMethod(pressedTile);
}
public void changeInstrument(View view) {
alertDialog.showAlertDialogInstrument(PlayPiago.this, instrumentButton, piagoMidiDriver);
}
public void changeSong(View view) {
alertDialog.showAlertDialogSong(PlayPiago.this, this);
}
public void octaveLower(View view) {
octaveSelector.OctaveDown();
}
public void octaveHigher(View view) {
octaveSelector.OctaveUp();
}
// BLUETOOTH STUFF
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connection with BT device using UUID
}
public void previewSong(View view) {
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
songStarted = false;
noteNumber = 0;
previewSongThread = new PreviewSongThread(this, activeSongByteArray, activeSongIntArray);
previewSongThread.start();
}
public void startSong(View view) {
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
noteNumber = 0;
ShowCurrentNote(activeSongByteArray);
songStarted = true;
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if (bytes != 0) {
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
//bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(MESSAGE_READ, bytes, 1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String input) {
byte[] bytes = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
public Boolean notePlayed = false;
//Learn
public void LearnSong(byte[] noteArray) {
if (!noteIsShown) {
ShowCurrentNote(noteArray);
}
if (!notePlayed) {
CheckNotePlayed(noteArray);
}
if (noteNumber >= noteArray.length) {
noteNumber = 0;
songStarted = false;
}
}
private void PauseMethodLearn(final Button pressedTile, final int backgGroundStatus, final byte[] array) {
pressedTile.setBackgroundResource(backgGroundStatus);
Log.i("Debugkey", "Key pressedTile BG set to green or red");
new CountDownTimer(200, 100) {
public void onFinish() {
pressedTile.setBackground(OriginalBackground(pressedTile.getId()));
Log.i("Debugkey", "PressedTile BG back to original");
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
Log.i("Debugkey", "TileToPress BG back to original");
ShowCurrentNote(array);
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
//Laat de noot zien die gespeeld moet worden
public void ShowCurrentNote(byte[] noteArray) {
Integer noteIndex = 0;
for (int i = 0; i < octaveSelector.ActiveOctaveArray.length; i++) {
if (noteArray[noteNumber] == octaveSelector.ActiveOctaveArray[i])
noteIndex = i;
}
tileToPress = findViewById(learn.KeyArray[noteIndex]);
tileToPress.setBackgroundResource(R.drawable.tile_to_press);
Log.i("Debugkey", "Key tileToPress is set to Blue, key index " + noteIndex);
noteIsShown = true;
notePlayed = false;
Log.i("Debugkey", "ShowCurrentNote() executed");
}
//Check of er een bluetoothsignaal is, zo ja check of het overeenkomt met hetgene dat nodig is
public void CheckNotePlayed(final byte[] array) {
if (ReceivedBluetoothSignal != null) {
playSound(ReceivedBluetoothSignal);
Log.i("Debugkey", "Sound played through checknoteplayed()");
if (pressedTile == tileToPress) {
//Is de noot correct, laat dan een groene background kort zien
PauseMethodLearn(pressedTile, R.drawable.tile_pressed, array);
//Log.i("BT", "Correct key");
noteNumber++;
} else {
//is de noot incorrect, laat dan een rode achtergrond zien
PauseMethodLearn(pressedTile, R.drawable.tile_pressed_fault, array);
}
notePlayed = true;
Log.i("Debugkey", "ChecknotePlayed() executed");
}
}
private void ModeSwitcher(boolean learnModeOn) {
if (learnModeOn) {
octaveLower.setVisibility(View.GONE);
octaveHigher.setVisibility(View.GONE);
previewButton.setVisibility(View.VISIBLE);
startButton.setVisibility(View.VISIBLE);
} else {
previewButton.setVisibility(View.GONE);
startButton.setVisibility(View.GONE);
octaveLower.setVisibility(View.VISIBLE);
octaveHigher.setVisibility(View.VISIBLE);
}
}
public Drawable OriginalBackground(int tileResource) {
return BGHandler.Original(tileResource, this);
}
} | AP-IT-GH/intprojectrepo-piago | PiaGOApp/app/src/main/java/com/interproject/piago/PlayPiago.java | 5,518 | //Laat de noot zien die gespeeld moet worden | line_comment | nl | package com.interproject.piago;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gms.common.annotation.KeepForSdkWithFieldsAndMethods;
import org.billthefarmer.mididriver.MidiDriver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class PlayPiago extends AppCompatActivity {
public String Instrument;
//For playing piano with different instruments in midi-player
private MidiDriver midiDriver;
public PiagoMidiDriver piagoMidiDriver;
private int[] config;
public Button instrumentButton;
//BLUETOOTH STUFF
private Handler mHandler;
private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
private ConnectedThread mConnectedThread;
private BluetoothAdapter mBTAdapter;
private Button mButtonAutoCnct;
// #defines for identifying shared types between calling functions
private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update
private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier
public String ReceivedBluetoothSignal;
public String CheckReceived;
public OctaveSelector octaveSelector;
//LearnSongs
public Boolean songStarted = false;
public LearnSongs learn = new LearnSongs();
public Integer noteNumber = 0;
public Button tileToPress;
public Boolean noteIsShown = false;
SignalCheckerThread sChecker;
PreviewSongThread previewSongThread;
public Boolean LearningMode = false;
public Switch learnToggle;
//Buttons
Button previewButton;
Button startButton;
Button octaveHigher;
Button octaveLower;
Button selectSong;
TextView activeSong;
byte[] activeSongByteArray = new byte[]{};
int[] activeSongIntArray = new int[]{};
AlertDialogBuilder alertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_piago);
mButtonAutoCnct = (Button) findViewById(R.id.button_autocnct);
mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
mButtonAutoCnct.setBackgroundColor(Color.RED);
mButtonAutoCnct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread() {
public void run() {
boolean fail = false;
// Change adress to static MAC adress
// BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
BluetoothDevice device = mBTAdapter.getRemoteDevice("98:D3:31:FD:17:0A");
//DEVICE FINLAND
//BluetoothDevice device = mBTAdapter.getRemoteDevice("B4:E6:2D:DF:4B:83");
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection.
try {
mBTSocket.connect();
} catch (IOException e) {
try {
fail = true;
mBTSocket.close();
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
if (fail == false) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mButtonAutoCnct.setBackgroundColor(Color.GREEN);
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, "Piago Keyboard")
.sendToTarget();
}
}
}.start();
}
});
mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == MESSAGE_READ) {
String readMessage = null;
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
CheckReceived = "1";
ReceivedBluetoothSignal = (readMessage.substring(0, 5));
Log.d("BTRECEIVED", "handleMessage: receiving msg from arduino" + ReceivedBluetoothSignal);
}
}
};
ReceivedBluetoothSignal = null;
CheckReceived = null;
Instrument = "piano";
//Midi-player
midiDriver = new MidiDriver();
piagoMidiDriver = new PiagoMidiDriver(midiDriver);
instrumentButton = findViewById(R.id.button_change_instrument);
//Lower / Higher notes
octaveSelector = new OctaveSelector();
//Learning
tileToPress = findViewById(R.id.tile_white_0);
sChecker = new SignalCheckerThread(this);
learnToggle = findViewById(R.id.switch_piago);
learnToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
LearningMode = true;
octaveSelector.SetOctaveLearn();
} else {
LearningMode = false;
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
}
ModeSwitcher(LearningMode);
}
});
//Buttons
previewButton = findViewById(R.id.button_preview);
startButton = findViewById(R.id.button_start_song);
octaveHigher = findViewById(R.id.button_octave_higher);
octaveLower = findViewById(R.id.button_octave_lower);
selectSong = findViewById(R.id.button_change_song);
activeSong = findViewById(R.id.textView_active_song);
activeSongByteArray = learn.FatherJacob;
activeSongIntArray = learn.FatherJacobTiming;
alertDialog = new AlertDialogBuilder();
}
@Override
protected void onResume() {
super.onResume();
midiDriver.start();
config = midiDriver.config();
learnToggle.setChecked(false);
sChecker.start();
}
@Override
protected void onPause() {
super.onPause();
midiDriver.stop();
}
Button pressedTile;
public void playSound(String sound) {
if (ReceivedBluetoothSignal != null) {
switch (sound) {
case "00000": {
pressedTile = findViewById(R.id.tile_white_0);
PlayNotePause(octaveSelector.ActiveOctaveArray[0], pressedTile);
break;
}
case "00010": {
pressedTile = findViewById(R.id.tile_white_1);
PlayNotePause(octaveSelector.ActiveOctaveArray[2], pressedTile);
break;
}
case "00100": {
pressedTile = findViewById(R.id.tile_white_2);
PlayNotePause(octaveSelector.ActiveOctaveArray[4], pressedTile);
break;
}
case "00110": {
pressedTile = findViewById(R.id.tile_white_3);
PlayNotePause(octaveSelector.ActiveOctaveArray[6], pressedTile);
break;
}
case "00111": {
pressedTile = findViewById(R.id.tile_white_4);
PlayNotePause(octaveSelector.ActiveOctaveArray[7], pressedTile);
break;
}
case "01001": {
pressedTile = findViewById(R.id.tile_white_5);
PlayNotePause(octaveSelector.ActiveOctaveArray[9], pressedTile);
break;
}
case "01011": {
pressedTile = findViewById(R.id.tile_white_6);
PlayNotePause(octaveSelector.ActiveOctaveArray[11], pressedTile);
break;
}
case "01100": {
pressedTile = findViewById(R.id.tile_white_7);
PlayNotePause(octaveSelector.ActiveOctaveArray[12], pressedTile);
break;
}
case "01110": {
pressedTile = findViewById(R.id.tile_white_8);
PlayNotePause(octaveSelector.ActiveOctaveArray[14], pressedTile);
break;
}
case "10000": {
pressedTile = findViewById(R.id.tile_white_9);
PlayNotePause(octaveSelector.ActiveOctaveArray[16], pressedTile);
break;
}
case "10010": {
pressedTile = findViewById(R.id.tile_white_10);
PlayNotePause(octaveSelector.ActiveOctaveArray[18], pressedTile);
break;
}
case "10011": {
pressedTile = findViewById(R.id.tile_white_11);
PlayNotePause(octaveSelector.ActiveOctaveArray[19], pressedTile);
break;
}
case "10101": {
pressedTile = findViewById(R.id.tile_white_12);
PlayNotePause(octaveSelector.ActiveOctaveArray[21], pressedTile);
break;
}
case "10111": {
pressedTile = findViewById(R.id.tile_white_13);
PlayNotePause(octaveSelector.ActiveOctaveArray[23], pressedTile);
break;
}
case "11000": {
pressedTile = findViewById(R.id.tile_white_14);
PlayNotePause(octaveSelector.ActiveOctaveArray[24], pressedTile);
break;
}
case "11010": {
pressedTile = findViewById(R.id.tile_white_15);
PlayNotePause(octaveSelector.ActiveOctaveArray[26], pressedTile);
break;
}
case "11100": {
pressedTile = findViewById(R.id.tile_white_16);
PlayNotePause(octaveSelector.ActiveOctaveArray[28], pressedTile);
break;
}
case "11110": {
pressedTile = findViewById(R.id.tile_white_17);
PlayNotePause(octaveSelector.ActiveOctaveArray[30], pressedTile);
break;
}
case "00001": {
pressedTile = findViewById(R.id.tile_black_0);
PlayNotePause(octaveSelector.ActiveOctaveArray[1], pressedTile);
break;
}
case "00011": {
pressedTile = findViewById(R.id.tile_black_1);
PlayNotePause(octaveSelector.ActiveOctaveArray[3], pressedTile);
break;
}
case "00101": {
pressedTile = findViewById(R.id.tile_black_2);
PlayNotePause(octaveSelector.ActiveOctaveArray[5], pressedTile);
break;
}
case "01000": {
pressedTile = findViewById(R.id.tile_black_3);
PlayNotePause(octaveSelector.ActiveOctaveArray[8], pressedTile);
break;
}
case "01010": {
pressedTile = findViewById(R.id.tile_black_4);
PlayNotePause(octaveSelector.ActiveOctaveArray[10], pressedTile);
break;
}
case "01101": {
pressedTile = findViewById(R.id.tile_black_5);
PlayNotePause(octaveSelector.ActiveOctaveArray[13], pressedTile);
break;
}
case "01111": {
pressedTile = findViewById(R.id.tile_black_6);
PlayNotePause(octaveSelector.ActiveOctaveArray[15], pressedTile);
break;
}
case "10001": {
pressedTile = findViewById(R.id.tile_black_7);
PlayNotePause(octaveSelector.ActiveOctaveArray[17], pressedTile);
break;
}
case "10100": {
pressedTile = findViewById(R.id.tile_black_8);
PlayNotePause(octaveSelector.ActiveOctaveArray[20], pressedTile);
break;
}
case "10110": {
pressedTile = findViewById(R.id.tile_black_9);
PlayNotePause(octaveSelector.ActiveOctaveArray[22], pressedTile);
break;
}
case "11001": {
pressedTile = findViewById(R.id.tile_black_10);
PlayNotePause(octaveSelector.ActiveOctaveArray[25], pressedTile);
break;
}
case "11011": {
pressedTile = findViewById(R.id.tile_black_11);
PlayNotePause(octaveSelector.ActiveOctaveArray[27], pressedTile);
break;
}
case "11101": {
pressedTile = findViewById(R.id.tile_black_12);
PlayNotePause(octaveSelector.ActiveOctaveArray[29], pressedTile);
break;
}
default:
break;
}
ReceivedBluetoothSignal = null;
}
}
//Test method
public void playSoundNow(View view) {
EditText eT = (EditText) findViewById(R.id.testValue);
if (eT.getText().toString().equals("11111")) {
CorrectNotePlayer correctNotePlayer = new CorrectNotePlayer(this);
correctNotePlayer.start();
} else {
ReceivedBluetoothSignal = eT.getText().toString();
}
}
private void PauseMethod(final Button pressedTile) {
pressedTile.setBackgroundResource(R.drawable.tile_pressed);
new CountDownTimer(200, 100) {
public void onFinish() {
pressedTile.setBackground(OriginalBackground(pressedTile.getId()));
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
public void PlayNotePause(byte note, final Button pressedTile) {
piagoMidiDriver.playNote(note);
Log.i("Debugkey", "_______________Note played through PlayNotePause");
PauseMethod(pressedTile);
}
public void changeInstrument(View view) {
alertDialog.showAlertDialogInstrument(PlayPiago.this, instrumentButton, piagoMidiDriver);
}
public void changeSong(View view) {
alertDialog.showAlertDialogSong(PlayPiago.this, this);
}
public void octaveLower(View view) {
octaveSelector.OctaveDown();
}
public void octaveHigher(View view) {
octaveSelector.OctaveUp();
}
// BLUETOOTH STUFF
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connection with BT device using UUID
}
public void previewSong(View view) {
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
songStarted = false;
noteNumber = 0;
previewSongThread = new PreviewSongThread(this, activeSongByteArray, activeSongIntArray);
previewSongThread.start();
}
public void startSong(View view) {
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
noteNumber = 0;
ShowCurrentNote(activeSongByteArray);
songStarted = true;
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if (bytes != 0) {
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
//bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(MESSAGE_READ, bytes, 1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String input) {
byte[] bytes = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(bytes);
} catch (IOException e) {
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
public Boolean notePlayed = false;
//Learn
public void LearnSong(byte[] noteArray) {
if (!noteIsShown) {
ShowCurrentNote(noteArray);
}
if (!notePlayed) {
CheckNotePlayed(noteArray);
}
if (noteNumber >= noteArray.length) {
noteNumber = 0;
songStarted = false;
}
}
private void PauseMethodLearn(final Button pressedTile, final int backgGroundStatus, final byte[] array) {
pressedTile.setBackgroundResource(backgGroundStatus);
Log.i("Debugkey", "Key pressedTile BG set to green or red");
new CountDownTimer(200, 100) {
public void onFinish() {
pressedTile.setBackground(OriginalBackground(pressedTile.getId()));
Log.i("Debugkey", "PressedTile BG back to original");
tileToPress.setBackground(OriginalBackground(tileToPress.getId()));
Log.i("Debugkey", "TileToPress BG back to original");
ShowCurrentNote(array);
}
public void onTick(long millisUntilFinished) {
}
}.start();
}
//Laat <SUF>
public void ShowCurrentNote(byte[] noteArray) {
Integer noteIndex = 0;
for (int i = 0; i < octaveSelector.ActiveOctaveArray.length; i++) {
if (noteArray[noteNumber] == octaveSelector.ActiveOctaveArray[i])
noteIndex = i;
}
tileToPress = findViewById(learn.KeyArray[noteIndex]);
tileToPress.setBackgroundResource(R.drawable.tile_to_press);
Log.i("Debugkey", "Key tileToPress is set to Blue, key index " + noteIndex);
noteIsShown = true;
notePlayed = false;
Log.i("Debugkey", "ShowCurrentNote() executed");
}
//Check of er een bluetoothsignaal is, zo ja check of het overeenkomt met hetgene dat nodig is
public void CheckNotePlayed(final byte[] array) {
if (ReceivedBluetoothSignal != null) {
playSound(ReceivedBluetoothSignal);
Log.i("Debugkey", "Sound played through checknoteplayed()");
if (pressedTile == tileToPress) {
//Is de noot correct, laat dan een groene background kort zien
PauseMethodLearn(pressedTile, R.drawable.tile_pressed, array);
//Log.i("BT", "Correct key");
noteNumber++;
} else {
//is de noot incorrect, laat dan een rode achtergrond zien
PauseMethodLearn(pressedTile, R.drawable.tile_pressed_fault, array);
}
notePlayed = true;
Log.i("Debugkey", "ChecknotePlayed() executed");
}
}
private void ModeSwitcher(boolean learnModeOn) {
if (learnModeOn) {
octaveLower.setVisibility(View.GONE);
octaveHigher.setVisibility(View.GONE);
previewButton.setVisibility(View.VISIBLE);
startButton.setVisibility(View.VISIBLE);
} else {
previewButton.setVisibility(View.GONE);
startButton.setVisibility(View.GONE);
octaveLower.setVisibility(View.VISIBLE);
octaveHigher.setVisibility(View.VISIBLE);
}
}
public Drawable OriginalBackground(int tileResource) {
return BGHandler.Original(tileResource, this);
}
} |
169774_9 | package com.app.vinnie.myapplication;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.SetOptions;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;
import static com.google.firebase.storage.FirebaseStorage.getInstance;
public class Profile extends AppCompatActivity {
BottomNavigationView mBottomnavigation;
Button mdeleteButton;
TextView mUsername, mPhone, mEmail;
ImageView mProfilepic;
FloatingActionButton mfab;
ProgressDialog pd;
//farebase
FirebaseUser muser;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
DatabaseReference mDatabaseref;
FirebaseDatabase mdatabase;
//storage
StorageReference storageReference;
//path where images of user profile will be stored
String storagePath = "Users_Profile_Imgs/";
String userID;
//uri of picked image
Uri image_uri;
//
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;
//arrays of permission to be requested
String cameraPermissions[];
String storagePermissions[];
//TRY
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//TRY
//init firebase
muser = FirebaseAuth.getInstance().getCurrentUser();
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
storageReference = getInstance().getReference(); //fbase stor ref
//views
mdeleteButton = findViewById(R.id.ButtonDelete);
mBottomnavigation = findViewById(R.id.bottom_navigation);
mUsername = findViewById(R.id.username_Textview);
mPhone = findViewById(R.id.phonenumber_Textview);
mEmail = findViewById(R.id.userEmail_Textview);
mProfilepic = findViewById(R.id.Profilepic);
mfab = findViewById(R.id.fab);
//init progress dialog
pd = new ProgressDialog(getApplication());
//init arrays of permissons
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
//referentie naar de userTest deel en vervolgens adhv USERID de momenteel ingelogde user
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
//userinfo uit database halen en in textviews zetten
mPhone.setText(documentSnapshot.getString("phone"));
mUsername.setText(documentSnapshot.getString("uname"));
mEmail.setText(documentSnapshot.getString("email"));
String image = documentSnapshot.getString("image");
try {
Picasso.get().load(image).into(mProfilepic);
}
catch (Exception d){
Picasso.get().load(R.drawable.ic_user_name).into(mProfilepic);
}
}
});
//set profile selected
mBottomnavigation.setSelectedItemId(R.id.profile);
//fab onclicklist
mfab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditProfileDialog();
}
});
//perform itemSelectedListner
mBottomnavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
return true;
case R.id.settings:
startActivity(new Intent(getApplicationContext(), Settings.class));
overridePendingTransition(0,0);
return true;
case R.id.saunaList:
startActivity(new Intent(getApplicationContext(), SaunaList.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
mdeleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder dialog = new AlertDialog.Builder(Profile.this);
dialog.setTitle("Are you sure you want to delete your account?");
dialog.setMessage("Deleting your account is permanent and will remove all content including comments, avatars and profile settings. ");
dialog.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
muser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
deleteUser(userID);
Toast.makeText(Profile.this, "Account deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
else{
String errormessage = task.getException().getMessage();
Toast.makeText(Profile.this,"error acquired" + errormessage,Toast.LENGTH_LONG).show();
}
}
});
}
});
dialog.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
});
}
private boolean checkStoragePermission(){
boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestStoragePermission(){
//min api verhogen
requestPermissions(storagePermissions ,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission(){
boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
//min api verhogen
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestCameraPermission(){
requestPermissions(cameraPermissions ,CAMERA_REQUEST_CODE);
}
private void showEditProfileDialog() {
//show dialog options
//edit profile picture, name, phone number
String options[]= {"Edit profile picture", "Edit name", "Edit phone number"};
//alert
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
//set title
builder.setTitle("Choose Action");
// set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle dialog item clicks
switch (which){
case 0:
pd.setMessage("Updating profile picture");
showImagePicDialog();
break;
case 1:
pd.setMessage("Updating username");
showNamePhoneUpdateDialog("uname");
break;
case 2:
pd.setMessage("Updating phone number");
showNamePhoneUpdateDialog("phone");
break;
}
}
});
//create and show dialog
builder.create();
builder.show();
}
private void showNamePhoneUpdateDialog(final String key) {
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setTitle("update"+ key);
//set layout of dialog
LinearLayout linearLayout = new LinearLayout(getApplication());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10,10,10,10);
//add edit text
final EditText editText = new EditText(getApplication());
editText.setHint("Enter"+key); //edit update name or photo
linearLayout.addView(editText);
builder.setView(linearLayout);
builder.setPositiveButton("update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//input text from edit text
String value = editText.getText().toString().trim();
if (!TextUtils.isEmpty(value)){
HashMap<String, Object> result = new HashMap<>();
result.put(key, value);
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.update(key, value);
}
else {
Toast.makeText(Profile.this, "please enter"+key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//create and show dialog
builder.create();
builder.show();
}
private void showImagePicDialog() {
//show dialog options
//Camera, choose from gallery
String options[]= {"Open camera", "Choose from gallery"};
//alert
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
//set title
builder.setTitle("Pick image from:");
// set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle dialog item clicks
switch (which){
case 0:
//pd.setMessage("Camera");
// showImagePicDialog();
if(!checkCameraPermission()){
requestCameraPermission();
}
else {
pickFromCamera();
}
break;
case 1:
if(!checkStoragePermission()){
requestStoragePermission();
}
else {
requestStoragePermission();
}
// pd.setMessage("Choose from gallery");
break;
}
}
});
//create and show dialog
builder.create();
builder.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//deze methode wordt aangeroepen wanneer de user Allow of Deny kiest van de dialog
//deze keuze wordt hier afgehandeld
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
//checken of we toegang hebben tot camera
boolean cameraAccepted =grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && writeStorageAccepted){
pickFromCamera();
}
}
else {
//toegang geweigerd
Toast.makeText(Profile.this, "please enalble camera & storage permission", Toast.LENGTH_SHORT).show();
}
}
break;
case STORAGE_REQUEST_CODE:{
//van gallerij: eerst checkn of we hiervoor toestemming hebben
if (grantResults.length>0){
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(writeStorageAccepted){
pickFromGallery();
}
}
else {
//toegang geweigerd
Toast.makeText(Profile.this, "please enalble storage permission", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//deze methode wordt opgeroepne na het nemen van een foto van camera of gallerij
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
//abeelding gekozen vanuit de gallerij --> verkrijgen van uri van de image
image_uri = data.getData();
uploadProfileCoverphoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//afbeelding gekozen met camera
uploadProfileCoverphoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverphoto(final Uri uri) {
//path and name of image t be stored in firebase storage
String filePathandName = storagePath+ "" + "image" + "_"+ userID;
StorageReference storageReference2 = storageReference.child(filePathandName);
storageReference2.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUti = uriTask.getResult();
//check if image is dowloaded or not
if (uriTask.isSuccessful()){
//image upload
//add/update url in users database
HashMap<String, Object> results = new HashMap<>();
results.put("image", downloadUti.toString());
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.update("image", downloadUti.toString());
}
else {
//error
Toast.makeText(Profile.this, "Some error occured", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(Profile.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
//intent of picking image from device camera
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
//put image uri
image_uri = Profile.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//intent to start camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
//check
private void pickFromGallery(){
//pick from gallery
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
//logout voor ap --> terug naar login activity
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(Profile.this, Login.class));
this.finish();
}
public void deleteUser(String userid){
mStore.collection("usersTest").document(userid).delete();
}
}
| AP-IT-GH/intprojectrepo-thermo-team | thermo-sauna/app/src/main/java/com/app/vinnie/myapplication/Profile.java | 4,214 | //referentie naar de userTest deel en vervolgens adhv USERID de momenteel ingelogde user | line_comment | nl | package com.app.vinnie.myapplication;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.SetOptions;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;
import static com.google.firebase.storage.FirebaseStorage.getInstance;
public class Profile extends AppCompatActivity {
BottomNavigationView mBottomnavigation;
Button mdeleteButton;
TextView mUsername, mPhone, mEmail;
ImageView mProfilepic;
FloatingActionButton mfab;
ProgressDialog pd;
//farebase
FirebaseUser muser;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
DatabaseReference mDatabaseref;
FirebaseDatabase mdatabase;
//storage
StorageReference storageReference;
//path where images of user profile will be stored
String storagePath = "Users_Profile_Imgs/";
String userID;
//uri of picked image
Uri image_uri;
//
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;
//arrays of permission to be requested
String cameraPermissions[];
String storagePermissions[];
//TRY
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//TRY
//init firebase
muser = FirebaseAuth.getInstance().getCurrentUser();
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
storageReference = getInstance().getReference(); //fbase stor ref
//views
mdeleteButton = findViewById(R.id.ButtonDelete);
mBottomnavigation = findViewById(R.id.bottom_navigation);
mUsername = findViewById(R.id.username_Textview);
mPhone = findViewById(R.id.phonenumber_Textview);
mEmail = findViewById(R.id.userEmail_Textview);
mProfilepic = findViewById(R.id.Profilepic);
mfab = findViewById(R.id.fab);
//init progress dialog
pd = new ProgressDialog(getApplication());
//init arrays of permissons
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
//refer<SUF>
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
//userinfo uit database halen en in textviews zetten
mPhone.setText(documentSnapshot.getString("phone"));
mUsername.setText(documentSnapshot.getString("uname"));
mEmail.setText(documentSnapshot.getString("email"));
String image = documentSnapshot.getString("image");
try {
Picasso.get().load(image).into(mProfilepic);
}
catch (Exception d){
Picasso.get().load(R.drawable.ic_user_name).into(mProfilepic);
}
}
});
//set profile selected
mBottomnavigation.setSelectedItemId(R.id.profile);
//fab onclicklist
mfab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditProfileDialog();
}
});
//perform itemSelectedListner
mBottomnavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
return true;
case R.id.settings:
startActivity(new Intent(getApplicationContext(), Settings.class));
overridePendingTransition(0,0);
return true;
case R.id.saunaList:
startActivity(new Intent(getApplicationContext(), SaunaList.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
mdeleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder dialog = new AlertDialog.Builder(Profile.this);
dialog.setTitle("Are you sure you want to delete your account?");
dialog.setMessage("Deleting your account is permanent and will remove all content including comments, avatars and profile settings. ");
dialog.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
muser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
deleteUser(userID);
Toast.makeText(Profile.this, "Account deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
else{
String errormessage = task.getException().getMessage();
Toast.makeText(Profile.this,"error acquired" + errormessage,Toast.LENGTH_LONG).show();
}
}
});
}
});
dialog.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
});
}
private boolean checkStoragePermission(){
boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestStoragePermission(){
//min api verhogen
requestPermissions(storagePermissions ,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission(){
boolean result = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(Profile.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
//min api verhogen
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestCameraPermission(){
requestPermissions(cameraPermissions ,CAMERA_REQUEST_CODE);
}
private void showEditProfileDialog() {
//show dialog options
//edit profile picture, name, phone number
String options[]= {"Edit profile picture", "Edit name", "Edit phone number"};
//alert
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
//set title
builder.setTitle("Choose Action");
// set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle dialog item clicks
switch (which){
case 0:
pd.setMessage("Updating profile picture");
showImagePicDialog();
break;
case 1:
pd.setMessage("Updating username");
showNamePhoneUpdateDialog("uname");
break;
case 2:
pd.setMessage("Updating phone number");
showNamePhoneUpdateDialog("phone");
break;
}
}
});
//create and show dialog
builder.create();
builder.show();
}
private void showNamePhoneUpdateDialog(final String key) {
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
builder.setTitle("update"+ key);
//set layout of dialog
LinearLayout linearLayout = new LinearLayout(getApplication());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10,10,10,10);
//add edit text
final EditText editText = new EditText(getApplication());
editText.setHint("Enter"+key); //edit update name or photo
linearLayout.addView(editText);
builder.setView(linearLayout);
builder.setPositiveButton("update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//input text from edit text
String value = editText.getText().toString().trim();
if (!TextUtils.isEmpty(value)){
HashMap<String, Object> result = new HashMap<>();
result.put(key, value);
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.update(key, value);
}
else {
Toast.makeText(Profile.this, "please enter"+key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//create and show dialog
builder.create();
builder.show();
}
private void showImagePicDialog() {
//show dialog options
//Camera, choose from gallery
String options[]= {"Open camera", "Choose from gallery"};
//alert
AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
//set title
builder.setTitle("Pick image from:");
// set items to dialog
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//handle dialog item clicks
switch (which){
case 0:
//pd.setMessage("Camera");
// showImagePicDialog();
if(!checkCameraPermission()){
requestCameraPermission();
}
else {
pickFromCamera();
}
break;
case 1:
if(!checkStoragePermission()){
requestStoragePermission();
}
else {
requestStoragePermission();
}
// pd.setMessage("Choose from gallery");
break;
}
}
});
//create and show dialog
builder.create();
builder.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//deze methode wordt aangeroepen wanneer de user Allow of Deny kiest van de dialog
//deze keuze wordt hier afgehandeld
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
//checken of we toegang hebben tot camera
boolean cameraAccepted =grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && writeStorageAccepted){
pickFromCamera();
}
}
else {
//toegang geweigerd
Toast.makeText(Profile.this, "please enalble camera & storage permission", Toast.LENGTH_SHORT).show();
}
}
break;
case STORAGE_REQUEST_CODE:{
//van gallerij: eerst checkn of we hiervoor toestemming hebben
if (grantResults.length>0){
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(writeStorageAccepted){
pickFromGallery();
}
}
else {
//toegang geweigerd
Toast.makeText(Profile.this, "please enalble storage permission", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//deze methode wordt opgeroepne na het nemen van een foto van camera of gallerij
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
//abeelding gekozen vanuit de gallerij --> verkrijgen van uri van de image
image_uri = data.getData();
uploadProfileCoverphoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//afbeelding gekozen met camera
uploadProfileCoverphoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverphoto(final Uri uri) {
//path and name of image t be stored in firebase storage
String filePathandName = storagePath+ "" + "image" + "_"+ userID;
StorageReference storageReference2 = storageReference.child(filePathandName);
storageReference2.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUti = uriTask.getResult();
//check if image is dowloaded or not
if (uriTask.isSuccessful()){
//image upload
//add/update url in users database
HashMap<String, Object> results = new HashMap<>();
results.put("image", downloadUti.toString());
DocumentReference documentReference = mStore.collection("usersTest").document(userID);
documentReference.update("image", downloadUti.toString());
}
else {
//error
Toast.makeText(Profile.this, "Some error occured", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(Profile.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
//intent of picking image from device camera
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
//put image uri
image_uri = Profile.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//intent to start camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
//check
private void pickFromGallery(){
//pick from gallery
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
//logout voor ap --> terug naar login activity
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(Profile.this, Login.class));
this.finish();
}
public void deleteUser(String userid){
mStore.collection("usersTest").document(userid).delete();
}
}
|
40747_1 | package powerrangers.zordon;
import android.content.Context;
import android.media.MediaPlayer;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Connection;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.util.Strings;
import java.io.UnsupportedEncodingException;
import static android.R.attr.content;
public class MainActivity extends AppCompatActivity {
MqttAndroidClient client;
String server = "ssl://m21.cloudmqtt.com:22452";
String username = "xnkcayag";
String password = "DtCGtuL2kVfk";
String topic = "Android/#";
String kitchentopic = "Android";
String[] topics = {"Android/#", "kitchen"};
String newmessage;
int qos = 1;
String clientId = MqttClient.generateClientId();
String Manueelsend = "test";
private Adapter mAdapter;
private ListView lv;
String[] Places = {"keuken", "slaapkamer", "berging", "badkamer", "deur"};;
protected static final int RESULT_SPEECH = 1;
private ImageButton PraatButton;
private TextView GesprokenZin;
private TextView LatestMessage;
private TextView KamerTemp;
private TextView weight;
private TextView ConnectStatus;
private Button Devices;
private ToggleButton Verwarming;
private TextToSpeech tts;
Boolean send = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSendMsg = (Button) findViewById(R.id.SendMessage);
GesprokenZin = (TextView) findViewById(R.id.GesprokenZin);
PraatButton = (ImageButton) findViewById(R.id.PraatButton);
ConnectStatus = (TextView) findViewById(R.id.StatusLabel);
lv = (ListView) findViewById(R.id.lv);
tts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
}
}
});
//String[] array = getIntent().getStringArrayExtra("lijst");
//Speech To Text API
PraatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault());
try {
startActivityForResult(intent, RESULT_SPEECH);
GesprokenZin.setText("");
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT).show();
}
}
});
//Connect to Mqtt
client = new MqttAndroidClient(this.getApplicationContext(), server, clientId);
client.setCallback(new MqttCallbackExtended() {
@Override
public void connectComplete(boolean reconnect, String server) {
if (reconnect) {
addToHistory("Reconnected to: " + server);
ConnectStatus.setText("Status: Connected");
SubscribeToTopic();
} else {
addToHistory("Connected to: " + server);
ConnectStatus.setText("Status: Connected");
}
}
@Override
public void connectionLost(Throwable cause) {
addToHistory("The connection was lost.");
ConnectStatus.setText("Status: Disconnected");
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
addToHistory("Incoming message: " + new String(message.getPayload()));
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setConnectionTimeout(240000);
mqttConnectOptions.setPassword(password.toCharArray());
try {
client.connect(mqttConnectOptions, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
client.setBufferOpts(disconnectedBufferOptions);
SubscribeToTopic();
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
addToHistory("failed to connect to: " + server);
}
});
} catch (MqttException ex) {
ex.printStackTrace();
}
}
private void addToHistory(String mainText){
System.out.println("LOG: " + mainText);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
@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
return super.onOptionsItemSelected(item);
}
public void SubscribeToTopic(){
try {
//Subscribe to all topics on Android
final MediaPlayer mp = MediaPlayer.create(this, R.raw.bell3);
final MediaPlayer weightSound = MediaPlayer.create(this, R.raw.weightdetected);
client.subscribe(topic, 0, new IMqttMessageListener() {
@Override
public void messageArrived(final String topic, MqttMessage message) throws Exception {
final MqttMessage test = message;
System.out.println("Message: " + "Android/#" + " : " + new String(message.getPayload()));
runOnUiThread(new Runnable() {
@Override
public void run() {
//sensor
KamerTemp = (TextView) findViewById(R.id.KamerTemp);
KamerTemp.setText("Kamertemperatuur: " + new String(test.getPayload()));
if(new String(test.getPayload()).contains("bel")){
mp.start();
}
if(new String(test.getPayload()).contains("dit weegt")) {
weight = (TextView) findViewById(R.id.weight);
weight.setText("Gewicht: " + new String(test.getPayload()));
tts.speak(new String(test.getPayload()), TextToSpeech.QUEUE_FLUSH, null);
}
if(new String(test.getPayload()).contains("heavy")) {
tts.speak("Welkom", TextToSpeech.QUEUE_FLUSH, null);
}
if(new String(test.getPayload()).contains("light")) {
tts.speak("Houdoe", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
}
});
client.subscribe(kitchentopic, 0, new IMqttMessageListener() {
@Override
public void messageArrived(final String topic, MqttMessage message) throws Exception {
final MqttMessage test = message;
System.out.println("Message: " + "kitchen" + " : " + new String(message.getPayload()));
runOnUiThread(new Runnable() {
@Override
public void run() {
//Stopcontact
LatestMessage = (TextView) findViewById(R.id.SubMessage);
LatestMessage.setText("Latest message: "+ new String(test.getPayload()));
ImageView image = (ImageView) findViewById(R.id.imageView);
if(new String(test.getPayload()).contains("kitchen on"))
image.setImageResource(R.mipmap.on);
if(new String(test.getPayload()).contains("kitchen off"))
image.setImageResource(R.mipmap.pixelbulbart);
}
});
}
});
} catch (MqttException ex){
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
public void publishMessage(){
try {
MqttMessage message = new MqttMessage();
message.setPayload(Manueelsend.getBytes());
client.publish(topic, message);
addToHistory("Message Published");
if(!client.isConnected()){
addToHistory(client.getBufferedMessageCount() + " messages in buffer.");
}
} catch (MqttException e) {
System.err.println("Error Publishing: " + e.getMessage());
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
GesprokenZin.setText(text.get(0));
String gesprokenpublish = GesprokenZin.getText().toString();
if (gesprokenpublish.contains(Places[0])) {topic = "kitchen"; send = true;}
else if (gesprokenpublish.contains(Places[1])) {topic = "Android/slaapkamer"; send = true;}
else if (gesprokenpublish.contains(Places[2])) {topic = "Android/berging"; send = true;}
else if (gesprokenpublish.contains(Places[3])) {topic = "Android/badkamer"; send = true;}
else if (gesprokenpublish.contains(Places[4])) {topic = "Android/Deurslot"; send = true;}
else{topic ="Not understood"; newmessage="Not understood"; send = false;}
if (gesprokenpublish.contains("aan")) {newmessage = "on"; send = true;}
else if (gesprokenpublish.contains("uit")) { newmessage = "off"; send = true;}
else if (gesprokenpublish.contains("vast")) { newmessage = "vast"; send = true;}
else if (gesprokenpublish.contains("los")) { newmessage = "los"; send = true;}
else{topic ="Not understood"; newmessage="Not understood"; send = false;}
if(send){
MqttMessage message = new MqttMessage(newmessage.getBytes());
message.setQos(qos);
message.setRetained(false);
try {
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
break;
}
}
}
public void SendMessage(View view) throws MqttException {
publishMessage();
}
public void Devices(View view) {
startActivity(new Intent(MainActivity.this, devices.class));
}
public void calibrateScale(View view) {
try {
MqttMessage message = new MqttMessage("calibrate".getBytes());
client.publish("scale", message);
} catch (MqttException e) {
e.printStackTrace();
}
}
} | AP-IT-GH/iot16-zordon | src/Android/Zordon/app/src/main/java/powerrangers/zordon/MainActivity.java | 3,216 | //String[] array = getIntent().getStringArrayExtra("lijst"); | line_comment | nl | package powerrangers.zordon;
import android.content.Context;
import android.media.MediaPlayer;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Connection;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.util.Strings;
import java.io.UnsupportedEncodingException;
import static android.R.attr.content;
public class MainActivity extends AppCompatActivity {
MqttAndroidClient client;
String server = "ssl://m21.cloudmqtt.com:22452";
String username = "xnkcayag";
String password = "DtCGtuL2kVfk";
String topic = "Android/#";
String kitchentopic = "Android";
String[] topics = {"Android/#", "kitchen"};
String newmessage;
int qos = 1;
String clientId = MqttClient.generateClientId();
String Manueelsend = "test";
private Adapter mAdapter;
private ListView lv;
String[] Places = {"keuken", "slaapkamer", "berging", "badkamer", "deur"};;
protected static final int RESULT_SPEECH = 1;
private ImageButton PraatButton;
private TextView GesprokenZin;
private TextView LatestMessage;
private TextView KamerTemp;
private TextView weight;
private TextView ConnectStatus;
private Button Devices;
private ToggleButton Verwarming;
private TextToSpeech tts;
Boolean send = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSendMsg = (Button) findViewById(R.id.SendMessage);
GesprokenZin = (TextView) findViewById(R.id.GesprokenZin);
PraatButton = (ImageButton) findViewById(R.id.PraatButton);
ConnectStatus = (TextView) findViewById(R.id.StatusLabel);
lv = (ListView) findViewById(R.id.lv);
tts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
}
}
});
//Strin<SUF>
//Speech To Text API
PraatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault());
try {
startActivityForResult(intent, RESULT_SPEECH);
GesprokenZin.setText("");
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT).show();
}
}
});
//Connect to Mqtt
client = new MqttAndroidClient(this.getApplicationContext(), server, clientId);
client.setCallback(new MqttCallbackExtended() {
@Override
public void connectComplete(boolean reconnect, String server) {
if (reconnect) {
addToHistory("Reconnected to: " + server);
ConnectStatus.setText("Status: Connected");
SubscribeToTopic();
} else {
addToHistory("Connected to: " + server);
ConnectStatus.setText("Status: Connected");
}
}
@Override
public void connectionLost(Throwable cause) {
addToHistory("The connection was lost.");
ConnectStatus.setText("Status: Disconnected");
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
addToHistory("Incoming message: " + new String(message.getPayload()));
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setConnectionTimeout(240000);
mqttConnectOptions.setPassword(password.toCharArray());
try {
client.connect(mqttConnectOptions, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
client.setBufferOpts(disconnectedBufferOptions);
SubscribeToTopic();
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
addToHistory("failed to connect to: " + server);
}
});
} catch (MqttException ex) {
ex.printStackTrace();
}
}
private void addToHistory(String mainText){
System.out.println("LOG: " + mainText);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
@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
return super.onOptionsItemSelected(item);
}
public void SubscribeToTopic(){
try {
//Subscribe to all topics on Android
final MediaPlayer mp = MediaPlayer.create(this, R.raw.bell3);
final MediaPlayer weightSound = MediaPlayer.create(this, R.raw.weightdetected);
client.subscribe(topic, 0, new IMqttMessageListener() {
@Override
public void messageArrived(final String topic, MqttMessage message) throws Exception {
final MqttMessage test = message;
System.out.println("Message: " + "Android/#" + " : " + new String(message.getPayload()));
runOnUiThread(new Runnable() {
@Override
public void run() {
//sensor
KamerTemp = (TextView) findViewById(R.id.KamerTemp);
KamerTemp.setText("Kamertemperatuur: " + new String(test.getPayload()));
if(new String(test.getPayload()).contains("bel")){
mp.start();
}
if(new String(test.getPayload()).contains("dit weegt")) {
weight = (TextView) findViewById(R.id.weight);
weight.setText("Gewicht: " + new String(test.getPayload()));
tts.speak(new String(test.getPayload()), TextToSpeech.QUEUE_FLUSH, null);
}
if(new String(test.getPayload()).contains("heavy")) {
tts.speak("Welkom", TextToSpeech.QUEUE_FLUSH, null);
}
if(new String(test.getPayload()).contains("light")) {
tts.speak("Houdoe", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
}
});
client.subscribe(kitchentopic, 0, new IMqttMessageListener() {
@Override
public void messageArrived(final String topic, MqttMessage message) throws Exception {
final MqttMessage test = message;
System.out.println("Message: " + "kitchen" + " : " + new String(message.getPayload()));
runOnUiThread(new Runnable() {
@Override
public void run() {
//Stopcontact
LatestMessage = (TextView) findViewById(R.id.SubMessage);
LatestMessage.setText("Latest message: "+ new String(test.getPayload()));
ImageView image = (ImageView) findViewById(R.id.imageView);
if(new String(test.getPayload()).contains("kitchen on"))
image.setImageResource(R.mipmap.on);
if(new String(test.getPayload()).contains("kitchen off"))
image.setImageResource(R.mipmap.pixelbulbart);
}
});
}
});
} catch (MqttException ex){
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
public void publishMessage(){
try {
MqttMessage message = new MqttMessage();
message.setPayload(Manueelsend.getBytes());
client.publish(topic, message);
addToHistory("Message Published");
if(!client.isConnected()){
addToHistory(client.getBufferedMessageCount() + " messages in buffer.");
}
} catch (MqttException e) {
System.err.println("Error Publishing: " + e.getMessage());
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
GesprokenZin.setText(text.get(0));
String gesprokenpublish = GesprokenZin.getText().toString();
if (gesprokenpublish.contains(Places[0])) {topic = "kitchen"; send = true;}
else if (gesprokenpublish.contains(Places[1])) {topic = "Android/slaapkamer"; send = true;}
else if (gesprokenpublish.contains(Places[2])) {topic = "Android/berging"; send = true;}
else if (gesprokenpublish.contains(Places[3])) {topic = "Android/badkamer"; send = true;}
else if (gesprokenpublish.contains(Places[4])) {topic = "Android/Deurslot"; send = true;}
else{topic ="Not understood"; newmessage="Not understood"; send = false;}
if (gesprokenpublish.contains("aan")) {newmessage = "on"; send = true;}
else if (gesprokenpublish.contains("uit")) { newmessage = "off"; send = true;}
else if (gesprokenpublish.contains("vast")) { newmessage = "vast"; send = true;}
else if (gesprokenpublish.contains("los")) { newmessage = "los"; send = true;}
else{topic ="Not understood"; newmessage="Not understood"; send = false;}
if(send){
MqttMessage message = new MqttMessage(newmessage.getBytes());
message.setQos(qos);
message.setRetained(false);
try {
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
break;
}
}
}
public void SendMessage(View view) throws MqttException {
publishMessage();
}
public void Devices(View view) {
startActivity(new Intent(MainActivity.this, devices.class));
}
public void calibrateScale(View view) {
try {
MqttMessage message = new MqttMessage("calibrate".getBytes());
client.publish("scale", message);
} catch (MqttException e) {
e.printStackTrace();
}
}
} |
124933_1 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.device;
import java.util.TimeZone;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.provider.Settings;
public class Device extends CordovaPlugin {
public static final String TAG = "Device";
public static String platform; // Device OS
public static String uuid; // Device UUID
private static final String ANDROID_PLATFORM = "Android";
private static final String AMAZON_PLATFORM = "amazon-fireos";
private static final String AMAZON_DEVICE = "Amazon";
/**
* Constructor.
*/
public Device() {
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Device.uuid = getUuid();
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback id used when calling back into JavaScript.
* @return True if the action was valid, false if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("getDeviceInfo".equals(action)) {
JSONObject r = new JSONObject();
r.put("uuid", Device.uuid);
r.put("version", this.getOSVersion());
r.put("platform", this.getPlatform());
r.put("model", this.getModel());
r.put("manufacturer", this.getManufacturer());
r.put("isVirtual", this.isVirtual());
r.put("serial", this.getSerialNumber());
callbackContext.success(r);
}
else {
return false;
}
return true;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Get the OS name.
*
* @return
*/
public String getPlatform() {
String platform;
if (isAmazonDevice()) {
platform = AMAZON_PLATFORM;
} else {
platform = ANDROID_PLATFORM;
}
return platform;
}
/**
* Get the device's Universally Unique Identifier (UUID).
*
* @return
*/
public String getUuid() {
String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
return uuid;
}
public String getModel() {
String model = android.os.Build.MODEL;
return model;
}
public String getProductName() {
String productname = android.os.Build.PRODUCT;
return productname;
}
public String getManufacturer() {
String manufacturer = android.os.Build.MANUFACTURER;
return manufacturer;
}
public String getSerialNumber() {
String serial = android.os.Build.SERIAL;
return serial;
}
/**
* Get the OS version.
*
* @return
*/
public String getOSVersion() {
String osversion = android.os.Build.VERSION.RELEASE;
return osversion;
}
public String getSDKVersion() {
@SuppressWarnings("deprecation")
String sdkversion = android.os.Build.VERSION.SDK;
return sdkversion;
}
public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault();
return (tz.getID());
}
/**
* Function to check if the device is manufactured by Amazon
*
* @return
*/
public boolean isAmazonDevice() {
if (android.os.Build.MANUFACTURER.equals(AMAZON_DEVICE)) {
return true;
}
return false;
}
public boolean isVirtual() {
return android.os.Build.FINGERPRINT.contains("generic") ||
android.os.Build.PRODUCT.contains("sdk");
}
}
| AP-IT-GH/jp19-luwb | src/visualisatie/lijn tekenen (angular)/plugins/cordova-plugin-device/src/android/Device.java | 1,276 | // Device OS | line_comment | nl | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.device;
import java.util.TimeZone;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.provider.Settings;
public class Device extends CordovaPlugin {
public static final String TAG = "Device";
public static String platform; // Devic<SUF>
public static String uuid; // Device UUID
private static final String ANDROID_PLATFORM = "Android";
private static final String AMAZON_PLATFORM = "amazon-fireos";
private static final String AMAZON_DEVICE = "Amazon";
/**
* Constructor.
*/
public Device() {
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Device.uuid = getUuid();
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback id used when calling back into JavaScript.
* @return True if the action was valid, false if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("getDeviceInfo".equals(action)) {
JSONObject r = new JSONObject();
r.put("uuid", Device.uuid);
r.put("version", this.getOSVersion());
r.put("platform", this.getPlatform());
r.put("model", this.getModel());
r.put("manufacturer", this.getManufacturer());
r.put("isVirtual", this.isVirtual());
r.put("serial", this.getSerialNumber());
callbackContext.success(r);
}
else {
return false;
}
return true;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Get the OS name.
*
* @return
*/
public String getPlatform() {
String platform;
if (isAmazonDevice()) {
platform = AMAZON_PLATFORM;
} else {
platform = ANDROID_PLATFORM;
}
return platform;
}
/**
* Get the device's Universally Unique Identifier (UUID).
*
* @return
*/
public String getUuid() {
String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
return uuid;
}
public String getModel() {
String model = android.os.Build.MODEL;
return model;
}
public String getProductName() {
String productname = android.os.Build.PRODUCT;
return productname;
}
public String getManufacturer() {
String manufacturer = android.os.Build.MANUFACTURER;
return manufacturer;
}
public String getSerialNumber() {
String serial = android.os.Build.SERIAL;
return serial;
}
/**
* Get the OS version.
*
* @return
*/
public String getOSVersion() {
String osversion = android.os.Build.VERSION.RELEASE;
return osversion;
}
public String getSDKVersion() {
@SuppressWarnings("deprecation")
String sdkversion = android.os.Build.VERSION.SDK;
return sdkversion;
}
public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault();
return (tz.getID());
}
/**
* Function to check if the device is manufactured by Amazon
*
* @return
*/
public boolean isAmazonDevice() {
if (android.os.Build.MANUFACTURER.equals(AMAZON_DEVICE)) {
return true;
}
return false;
}
public boolean isVirtual() {
return android.os.Build.FINGERPRINT.contains("generic") ||
android.os.Build.PRODUCT.contains("sdk");
}
}
|
43930_0 | package be.ap.teamrap.teamrap;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
public class MainActivity extends AppCompatActivity {
//Dit is een zeer mooie comment
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@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 == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| AP-IT-GH/sprint-ci-cd-in-team-pm_teamrap | app/src/main/java/be/ap/teamrap/teamrap/MainActivity.java | 471 | //Dit is een zeer mooie comment | line_comment | nl | package be.ap.teamrap.teamrap;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
public class MainActivity extends AppCompatActivity {
//Dit i<SUF>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@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 == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
55101_56 | package gr.grnet.eseal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.europa.esig.dss.service.http.commons.CommonsDataLoader;
import gr.grnet.eseal.dto.SignedDocument;
import gr.grnet.eseal.dto.ValidateDocumentRequestDto;
import gr.grnet.eseal.exception.APIError;
import gr.grnet.eseal.service.ValidateDocumentService;
import gr.grnet.eseal.validation.DocumentValidatorLOTL;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class DocumentValidationTests {
@Autowired private MockMvc mockMvc;
private final String validationPath = "/api/v1/validation/validateDocument";
private ObjectMapper objectMapper = new ObjectMapper();
@Autowired ValidateDocumentService validateDocumentService;
@Autowired DocumentValidatorLOTL documentValidatorLOTL;
// @Test
// void ValidateDocumentSuccess() throws Exception {
//
// InputStream isSignedPDF =
// DocumentValidationTests.class.getResourceAsStream(
// "/validation/".concat("signed-lta-b64-pdf.txt"));
//
// String signedLTAPDF =
// new BufferedReader(new InputStreamReader(isSignedPDF, StandardCharsets.UTF_8))
// .lines()
// .collect(Collectors.joining("\n"));
//
// // Valid request body but with empty bytes field
// ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
// SignedDocument signedDocument = new SignedDocument();
// signedDocument.setBytes(signedLTAPDF);
// signedDocument.setName("random-name");
// validateDocumentRequestDto.setSignedDocument(signedDocument);
//
// MockHttpServletResponse resp =
// this.mockMvc
// .perform(
// post(this.validationPath)
// .content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
// .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
// .accept(MediaType.APPLICATION_JSON))
// .andReturn()
// .getResponse();
//
// assertThat(resp.getStatus()).isEqualTo(HttpStatus.OK.value());
//
// WSReportsDTO wsReportsDTO =
// this.validateDocumentService.validateDocument(
// validateDocumentRequestDto.getSignedDocument().getBytes(),
// validateDocumentRequestDto.getSignedDocument().getName());
//
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().size()).isEqualTo(1);
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getIndication())
// .isEqualTo(Indication.INDETERMINATE);
//
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getSubIndication())
// .isEqualTo(SubIndication.NO_CERTIFICATE_CHAIN_FOUND);
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getErrors())
// .isEqualTo(
// Arrays.asList(
// "Unable to build a certificate chain until a trusted list!",
// "The result of the LTV validation process is not acceptable to continue the
// process!",
// "The certificate chain for signature is not trusted, it does not contain a trust
// anchor."));
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getWarnings())
// .isEqualTo(Arrays.asList("The signature/seal is an INDETERMINATE AdES digital
// signature!"));
// }
@Test
void ValidateDocumentEmptyOrMissingBytes() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("");
signedDocument.setName("random-name");
validateDocumentRequestDto.setSignedDocument(signedDocument);
List<MockHttpServletResponse> errorResponses = new ArrayList<>();
MockHttpServletResponse responseEmptyField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseEmptyField);
// case where the bytes field is not present
signedDocument.setBytes(null);
MockHttpServletResponse responseMissingField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseMissingField);
for (MockHttpServletResponse response : errorResponses) {
APIError apiError =
this.objectMapper.readValue(response.getContentAsString(), APIError.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field signedDocument.bytes cannot be empty");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
}
@Test
void ValidateDocumentEmptyOrMissingName() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("b");
signedDocument.setName("");
validateDocumentRequestDto.setSignedDocument(signedDocument);
List<MockHttpServletResponse> errorResponses = new ArrayList<>();
MockHttpServletResponse responseEmptyField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseEmptyField);
// case where the bytes field is not present
signedDocument.setName(null);
MockHttpServletResponse responseMissingField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseMissingField);
for (MockHttpServletResponse response : errorResponses) {
APIError apiError =
this.objectMapper.readValue(response.getContentAsString(), APIError.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field signedDocument.name cannot be empty");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
}
@Test
void ValidateDocumentInvalidBASE64Bytes() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("b");
signedDocument.setName("random-name");
validateDocumentRequestDto.setSignedDocument(signedDocument);
MockHttpServletResponse resp =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
APIError apiError = this.objectMapper.readValue(resp.getContentAsString(), APIError.class);
assertThat(resp.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field toSignDocument.bytes should be encoded in base64 format");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void LOTLOnlineDataLoaderAccessSuccess() throws Exception {
// Make sure the data loader can at least access all the following urls
this.documentValidatorLOTL
.onlineLOTLDataLoader()
.get("https://ec.europa.eu/tools/lotl/eu-lotl.xml");
CommonsDataLoader r = this.documentValidatorLOTL.onlineLOTLDataLoader();
r.setSslProtocol("TLSv1.3");
r.get("https://ssi.gouv.fr/uploads/tl-fr.xml");
//
// NOT ACCESSIBLE ANYMORE
// this.documentValidatorLOTL
// .onlineLOTLDataLoader()
// .get("https://sede.minetur.gob.es/Prestadores/TSL/TSL.xml");
this.documentValidatorLOTL
.onlineLOTLDataLoader()
.get(
"https://www.agentschaptelecom.nl/binaries/agentschap-telecom/documenten/publicaties/2018/januari/01/digitale-statuslijst-van-vertrouwensdiensten/current-tsl.xml");
}
}
| ARGOeu/gr.grnet.eseal | eseal/src/test/java/gr/grnet/eseal/DocumentValidationTests.java | 2,538 | //www.agentschaptelecom.nl/binaries/agentschap-telecom/documenten/publicaties/2018/januari/01/digitale-statuslijst-van-vertrouwensdiensten/current-tsl.xml"); | line_comment | nl | package gr.grnet.eseal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.europa.esig.dss.service.http.commons.CommonsDataLoader;
import gr.grnet.eseal.dto.SignedDocument;
import gr.grnet.eseal.dto.ValidateDocumentRequestDto;
import gr.grnet.eseal.exception.APIError;
import gr.grnet.eseal.service.ValidateDocumentService;
import gr.grnet.eseal.validation.DocumentValidatorLOTL;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
class DocumentValidationTests {
@Autowired private MockMvc mockMvc;
private final String validationPath = "/api/v1/validation/validateDocument";
private ObjectMapper objectMapper = new ObjectMapper();
@Autowired ValidateDocumentService validateDocumentService;
@Autowired DocumentValidatorLOTL documentValidatorLOTL;
// @Test
// void ValidateDocumentSuccess() throws Exception {
//
// InputStream isSignedPDF =
// DocumentValidationTests.class.getResourceAsStream(
// "/validation/".concat("signed-lta-b64-pdf.txt"));
//
// String signedLTAPDF =
// new BufferedReader(new InputStreamReader(isSignedPDF, StandardCharsets.UTF_8))
// .lines()
// .collect(Collectors.joining("\n"));
//
// // Valid request body but with empty bytes field
// ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
// SignedDocument signedDocument = new SignedDocument();
// signedDocument.setBytes(signedLTAPDF);
// signedDocument.setName("random-name");
// validateDocumentRequestDto.setSignedDocument(signedDocument);
//
// MockHttpServletResponse resp =
// this.mockMvc
// .perform(
// post(this.validationPath)
// .content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
// .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
// .accept(MediaType.APPLICATION_JSON))
// .andReturn()
// .getResponse();
//
// assertThat(resp.getStatus()).isEqualTo(HttpStatus.OK.value());
//
// WSReportsDTO wsReportsDTO =
// this.validateDocumentService.validateDocument(
// validateDocumentRequestDto.getSignedDocument().getBytes(),
// validateDocumentRequestDto.getSignedDocument().getName());
//
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().size()).isEqualTo(1);
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getIndication())
// .isEqualTo(Indication.INDETERMINATE);
//
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getSubIndication())
// .isEqualTo(SubIndication.NO_CERTIFICATE_CHAIN_FOUND);
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getErrors())
// .isEqualTo(
// Arrays.asList(
// "Unable to build a certificate chain until a trusted list!",
// "The result of the LTV validation process is not acceptable to continue the
// process!",
// "The certificate chain for signature is not trusted, it does not contain a trust
// anchor."));
// assertThat(wsReportsDTO.getSimpleReport().getSignatureOrTimestamp().get(0).getWarnings())
// .isEqualTo(Arrays.asList("The signature/seal is an INDETERMINATE AdES digital
// signature!"));
// }
@Test
void ValidateDocumentEmptyOrMissingBytes() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("");
signedDocument.setName("random-name");
validateDocumentRequestDto.setSignedDocument(signedDocument);
List<MockHttpServletResponse> errorResponses = new ArrayList<>();
MockHttpServletResponse responseEmptyField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseEmptyField);
// case where the bytes field is not present
signedDocument.setBytes(null);
MockHttpServletResponse responseMissingField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseMissingField);
for (MockHttpServletResponse response : errorResponses) {
APIError apiError =
this.objectMapper.readValue(response.getContentAsString(), APIError.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field signedDocument.bytes cannot be empty");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
}
@Test
void ValidateDocumentEmptyOrMissingName() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("b");
signedDocument.setName("");
validateDocumentRequestDto.setSignedDocument(signedDocument);
List<MockHttpServletResponse> errorResponses = new ArrayList<>();
MockHttpServletResponse responseEmptyField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseEmptyField);
// case where the bytes field is not present
signedDocument.setName(null);
MockHttpServletResponse responseMissingField =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
errorResponses.add(responseMissingField);
for (MockHttpServletResponse response : errorResponses) {
APIError apiError =
this.objectMapper.readValue(response.getContentAsString(), APIError.class);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field signedDocument.name cannot be empty");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
}
@Test
void ValidateDocumentInvalidBASE64Bytes() throws Exception {
// Valid request body but with empty bytes field
ValidateDocumentRequestDto validateDocumentRequestDto = new ValidateDocumentRequestDto();
SignedDocument signedDocument = new SignedDocument();
signedDocument.setBytes("b");
signedDocument.setName("random-name");
validateDocumentRequestDto.setSignedDocument(signedDocument);
MockHttpServletResponse resp =
this.mockMvc
.perform(
post(this.validationPath)
.content(this.objectMapper.writeValueAsBytes(validateDocumentRequestDto))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andReturn()
.getResponse();
APIError apiError = this.objectMapper.readValue(resp.getContentAsString(), APIError.class);
assertThat(resp.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody()).isNotNull();
assertThat(apiError.getApiErrorBody().getMessage())
.isEqualTo("Field toSignDocument.bytes should be encoded in base64 format");
assertThat(apiError.getApiErrorBody().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(apiError.getApiErrorBody().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void LOTLOnlineDataLoaderAccessSuccess() throws Exception {
// Make sure the data loader can at least access all the following urls
this.documentValidatorLOTL
.onlineLOTLDataLoader()
.get("https://ec.europa.eu/tools/lotl/eu-lotl.xml");
CommonsDataLoader r = this.documentValidatorLOTL.onlineLOTLDataLoader();
r.setSslProtocol("TLSv1.3");
r.get("https://ssi.gouv.fr/uploads/tl-fr.xml");
//
// NOT ACCESSIBLE ANYMORE
// this.documentValidatorLOTL
// .onlineLOTLDataLoader()
// .get("https://sede.minetur.gob.es/Prestadores/TSL/TSL.xml");
this.documentValidatorLOTL
.onlineLOTLDataLoader()
.get(
"https://www.a<SUF>
}
}
|
24946_22 | package qamatcher;
import java.io.IOException;
import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* DomDialogParser is created with an xml file that contains the specification
* of questions and answer pairs.
* The file is stored in the resources/qamatcher direcotory
* which should be on the class path
* The DialogStore can be obtained by the method getDialogStore()
*/
public class DomDialogsParser{
DialogStore myDialogs;
Document dom;
String xmlFileName;
/**
* create a new and load a DialogStore
* @param fn the xml file name
*/
public DomDialogsParser(String fn){
//create a store to hold the Dialog objects
xmlFileName = fn;
myDialogs = new DialogStore();
loadStore();
}
public DomDialogsParser(String fn, String df){
//create a store to hold the Dialog objects
xmlFileName = fn;
myDialogs = new DialogStore(df);
loadStore();
}
/**
* @return the DialogStore
*/
public DialogStore getDialogStore(){
return myDialogs;
}
public void loadStore() {
//parse the xml file and get the dom object
parseXmlFile(xmlFileName);
//get each dialog element and create a Dialog object
// and add this to the DialogStore
parseDocument();
}
private void parseXmlFile(String fileName){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = db.parse(getXMLFile(fileName));
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
public File getXMLFile(String filename){
// File f =null;
// try{
// java.net.URL fileURL = DomDialogsParser.class.getResource(filename);
// System.out.println("fileURL="+fileURL);
// if (fileURL != null) {
// java.net.URI fileURI = fileURL.toURI();
// f = new File(fileURI);
// } else {
// System.err.println("Couldn't find file: " + filename);
// }
// }catch(URISyntaxException exc){
// System.out.println(exc.getMessage());
// }
// return f;
File f = null;
if(filename != null) {
f = new File(filename);
} else {
System.err.println("Couldn't find file: " + filename);
}
return f;
}
private void parseDocument(){
//get the root elememt
Element docEle = dom.getDocumentElement();
//get a nodelist of <dialog> elements
NodeList nl = docEle.getElementsByTagName("dialog");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the dialog element
Element el = (Element)nl.item(i);
//get the Dialog object
Dialog d = getDialog(el);
//add it to list
myDialogs.add(d);
}
}
}
/**
* take an dialog element and read the values in, create
* a Dialog object and return it
* @param el
* @return
*/
private Dialog getDialog(Element el) {
//for each <dialog> element get text or int values of id
String id = el.getAttribute("id");
//Create a new Dialog with the values read from the xml nodes
Dialog d = new Dialog(id);
Element answerlistelement=null;
NodeList nl = el.getElementsByTagName("answerlist");
if(nl != null && nl.getLength() > 0) {
answerlistelement = (Element)nl.item(0);
getAnswerList(answerlistelement,d);
}
Element questionlistelement = null;
NodeList nl2 = el.getElementsByTagName("questionlist");
if(nl2 != null && nl2.getLength() > 0) {
questionlistelement = (Element)nl2.item(0);
getQuestionList(questionlistelement,d);
}
return d;
}
// create and add AnswersType objects to dialog d
private void getAnswerList(Element el, Dialog d){
NodeList nl = el.getElementsByTagName("answer");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the answer element
Element ela = (Element)nl.item(i);
//get the AnswerType object
AnswerType ans = getAnswerType(ela);
//add it to dialog
d.addAnswer(ans);
}
}
}
private AnswerType getAnswerType(Element ela){
AnswerType ans = new AnswerType();
String anstype = ela.getAttribute("type");
String attname = "type";
String attvalue = anstype;
ans.addAttribute(attname,attvalue);
String text = ela.getFirstChild().getNodeValue();
ans.setText(text);
return ans;
}
// create and add questions string to dialog d
private void getQuestionList(Element el, Dialog d){
//get a nodelist of <question> elements
NodeList nl = el.getElementsByTagName("question");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the question element
Element elq = (Element)nl.item(i);
//String question = getTextValue(elq,"question");
//String question = getString(elq,"question");
String question = elq.getFirstChild().getNodeValue().toLowerCase();
//add it to dialog
//System.out.println(question);
d.addQuestion(question);
}
}
}
private String getString(Element element, String tagName) {
NodeList list = element.getElementsByTagName(tagName);
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes();
if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeValue();
}
}
return null;
}
/**
* I take a xml element and the tag name, look for the tag and get
* the text content
* i.e for <employee><name>John</name></employee> xml snippet if
* the Element points to employee node and tagName is name I will return John
* @param ele
* @param tagName
* @return
*/
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
/**
* Calls getTextValue and returns a int value
* @param ele
* @param tagName
* @return
*/
private int getIntValue(Element ele, String tagName) {
//in production application you would catch the exception
return Integer.parseInt(getTextValue(ele,tagName));
}
/**
* Print the DialogStore to console
*/
private void printStore(){
System.out.println("No of Dialogs '" + myDialogs.size() + "'.");
System.out.println(myDialogs.xml());
}
public static void main(String[] args){
String fileName = "vragen.xml";
DomDialogsParser dpe = new DomDialogsParser(fileName);
dpe.printStore();
}
}
| ARIA-VALUSPA/AVP | Agent-Core-Final/DM_Tools/QAM/src/main/java/qamatcher/DomDialogsParser.java | 2,099 | //get the root elememt | line_comment | nl | package qamatcher;
import java.io.IOException;
import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* DomDialogParser is created with an xml file that contains the specification
* of questions and answer pairs.
* The file is stored in the resources/qamatcher direcotory
* which should be on the class path
* The DialogStore can be obtained by the method getDialogStore()
*/
public class DomDialogsParser{
DialogStore myDialogs;
Document dom;
String xmlFileName;
/**
* create a new and load a DialogStore
* @param fn the xml file name
*/
public DomDialogsParser(String fn){
//create a store to hold the Dialog objects
xmlFileName = fn;
myDialogs = new DialogStore();
loadStore();
}
public DomDialogsParser(String fn, String df){
//create a store to hold the Dialog objects
xmlFileName = fn;
myDialogs = new DialogStore(df);
loadStore();
}
/**
* @return the DialogStore
*/
public DialogStore getDialogStore(){
return myDialogs;
}
public void loadStore() {
//parse the xml file and get the dom object
parseXmlFile(xmlFileName);
//get each dialog element and create a Dialog object
// and add this to the DialogStore
parseDocument();
}
private void parseXmlFile(String fileName){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = db.parse(getXMLFile(fileName));
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
public File getXMLFile(String filename){
// File f =null;
// try{
// java.net.URL fileURL = DomDialogsParser.class.getResource(filename);
// System.out.println("fileURL="+fileURL);
// if (fileURL != null) {
// java.net.URI fileURI = fileURL.toURI();
// f = new File(fileURI);
// } else {
// System.err.println("Couldn't find file: " + filename);
// }
// }catch(URISyntaxException exc){
// System.out.println(exc.getMessage());
// }
// return f;
File f = null;
if(filename != null) {
f = new File(filename);
} else {
System.err.println("Couldn't find file: " + filename);
}
return f;
}
private void parseDocument(){
//get t<SUF>
Element docEle = dom.getDocumentElement();
//get a nodelist of <dialog> elements
NodeList nl = docEle.getElementsByTagName("dialog");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the dialog element
Element el = (Element)nl.item(i);
//get the Dialog object
Dialog d = getDialog(el);
//add it to list
myDialogs.add(d);
}
}
}
/**
* take an dialog element and read the values in, create
* a Dialog object and return it
* @param el
* @return
*/
private Dialog getDialog(Element el) {
//for each <dialog> element get text or int values of id
String id = el.getAttribute("id");
//Create a new Dialog with the values read from the xml nodes
Dialog d = new Dialog(id);
Element answerlistelement=null;
NodeList nl = el.getElementsByTagName("answerlist");
if(nl != null && nl.getLength() > 0) {
answerlistelement = (Element)nl.item(0);
getAnswerList(answerlistelement,d);
}
Element questionlistelement = null;
NodeList nl2 = el.getElementsByTagName("questionlist");
if(nl2 != null && nl2.getLength() > 0) {
questionlistelement = (Element)nl2.item(0);
getQuestionList(questionlistelement,d);
}
return d;
}
// create and add AnswersType objects to dialog d
private void getAnswerList(Element el, Dialog d){
NodeList nl = el.getElementsByTagName("answer");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the answer element
Element ela = (Element)nl.item(i);
//get the AnswerType object
AnswerType ans = getAnswerType(ela);
//add it to dialog
d.addAnswer(ans);
}
}
}
private AnswerType getAnswerType(Element ela){
AnswerType ans = new AnswerType();
String anstype = ela.getAttribute("type");
String attname = "type";
String attvalue = anstype;
ans.addAttribute(attname,attvalue);
String text = ela.getFirstChild().getNodeValue();
ans.setText(text);
return ans;
}
// create and add questions string to dialog d
private void getQuestionList(Element el, Dialog d){
//get a nodelist of <question> elements
NodeList nl = el.getElementsByTagName("question");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the question element
Element elq = (Element)nl.item(i);
//String question = getTextValue(elq,"question");
//String question = getString(elq,"question");
String question = elq.getFirstChild().getNodeValue().toLowerCase();
//add it to dialog
//System.out.println(question);
d.addQuestion(question);
}
}
}
private String getString(Element element, String tagName) {
NodeList list = element.getElementsByTagName(tagName);
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes();
if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeValue();
}
}
return null;
}
/**
* I take a xml element and the tag name, look for the tag and get
* the text content
* i.e for <employee><name>John</name></employee> xml snippet if
* the Element points to employee node and tagName is name I will return John
* @param ele
* @param tagName
* @return
*/
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
/**
* Calls getTextValue and returns a int value
* @param ele
* @param tagName
* @return
*/
private int getIntValue(Element ele, String tagName) {
//in production application you would catch the exception
return Integer.parseInt(getTextValue(ele,tagName));
}
/**
* Print the DialogStore to console
*/
private void printStore(){
System.out.println("No of Dialogs '" + myDialogs.size() + "'.");
System.out.println(myDialogs.xml());
}
public static void main(String[] args){
String fileName = "vragen.xml";
DomDialogsParser dpe = new DomDialogsParser(fileName);
dpe.printStore();
}
}
|
38342_8 | package mergeSort;
import Main.NamedList;
public class MergeNSort {
public MergeNSort(Integer[] a, Integer N) {
mergeSort(a, 0, a.length, getMax(a)+1, N);
}
public void mergeSort(Integer[] a, int start, int end, Integer INF, Integer N) {
Integer l=end-start;
if(l<N) {
Merge3Sort.mergeSort(a,start,end,INF);
} else {
Integer factor = (end-start)/N;
//generate mids
NamedList<Integer> mids=new NamedList<Integer>();
mids.add(start+factor);
for(Integer i=1; i<N-1; i++)
mids.add(mids.getByIndex(i-1)+factor);
//call (recursive) mergesort
mergeSort(a, start, mids.getByIndex(0), INF, N);
for(Integer i=1; i<N-1; i++)
mergeSort(a, mids.getByIndex(i-1), mids.getByIndex(i), INF, N);
mergeSort(a, mids.getByIndex(N-2), end, INF, N);
//call to merge
merge(a, start, mids, end, INF, N);
}
}
private void merge(Integer[] a, Integer start, NamedList<Integer> mids, Integer end, Integer INF, Integer N) {
NamedList<Integer[]> arrays=new NamedList<Integer[]>();
//create arrays
arrays.add("a0",new Integer[mids.getByIndex(0)-start + 1]);
for(Integer i=1; i<N-1; i++)
arrays.add("a"+Integer.toString(i), new Integer[mids.getByIndex(i) - mids.getByIndex(i-1) + 1]);
arrays.add("a"+Integer.toString(N-1), new Integer[end - mids.getByIndex(N-2) + 1]);
//copy arrays
copyMergeNSortArr(a, arrays.getByIndex(0), start, mids.getByIndex(0));
for(Integer i=1; i<N-1; i++)
copyMergeNSortArr(a, arrays.getByIndex(i), mids.getByIndex(i-1), mids.getByIndex(i));
copyMergeNSortArr(a, arrays.getByIndex(N-1), mids.getByIndex(N-2), end);
//add INFs
arrays.getByIndex(0)[mids.getByIndex(0)-start] = INF;
for(Integer i=1; i<N-1; i++)
arrays.getByIndex(i)[mids.getByIndex(i)-mids.getByIndex(i-1)] = INF;
arrays.getByIndex(N-1)[end - mids.getByIndex(N-2)] = INF;
//create pointers
Integer[] point=new Integer[N];
for(Integer i=0; i<N; i++)
point[i]=0;
//merge
for(Integer i=start; i<end; i++) {
//elements of each array
Integer[] element=new Integer[N];
for(Integer j=0; j<N; j++)
element[j] = arrays.getByIndex(j)[point[j]];
//get min
Integer pos=0, min=element[0];
for(Integer j=0; j<N; j++)
if(min>element[j]) {
min = element[j];
pos = j;
}
//set min
point[pos]++;
a[i] = min;
}
}
private void copyMergeNSortArr(Integer[] a, Integer[] a1, Integer start, Integer end) {
for(Integer i=start; i<end; i++) {
a1[i-start] = a[i];
}
}
public Integer getMax(Integer[] a) {
Integer max = a[0];
for(Integer i=1;i<a.length;i++) {
if(max < a[i]) {
max = a[i];
}
}
return max;
}
public void displayMergeNSortArr(Integer[] a) {
System.out.print("[");
for(Integer i=0; i<a.length-1; i++) {
System.out.print(a[i]+", ");
} System.out.print(a[a.length-1]+"]");
System.out.println();
}
}
| ATGupta/IIITV-LI-Algorithms-Design-and-Analysis | mergeSort/MergeNSort.java | 1,141 | //get min | line_comment | nl | package mergeSort;
import Main.NamedList;
public class MergeNSort {
public MergeNSort(Integer[] a, Integer N) {
mergeSort(a, 0, a.length, getMax(a)+1, N);
}
public void mergeSort(Integer[] a, int start, int end, Integer INF, Integer N) {
Integer l=end-start;
if(l<N) {
Merge3Sort.mergeSort(a,start,end,INF);
} else {
Integer factor = (end-start)/N;
//generate mids
NamedList<Integer> mids=new NamedList<Integer>();
mids.add(start+factor);
for(Integer i=1; i<N-1; i++)
mids.add(mids.getByIndex(i-1)+factor);
//call (recursive) mergesort
mergeSort(a, start, mids.getByIndex(0), INF, N);
for(Integer i=1; i<N-1; i++)
mergeSort(a, mids.getByIndex(i-1), mids.getByIndex(i), INF, N);
mergeSort(a, mids.getByIndex(N-2), end, INF, N);
//call to merge
merge(a, start, mids, end, INF, N);
}
}
private void merge(Integer[] a, Integer start, NamedList<Integer> mids, Integer end, Integer INF, Integer N) {
NamedList<Integer[]> arrays=new NamedList<Integer[]>();
//create arrays
arrays.add("a0",new Integer[mids.getByIndex(0)-start + 1]);
for(Integer i=1; i<N-1; i++)
arrays.add("a"+Integer.toString(i), new Integer[mids.getByIndex(i) - mids.getByIndex(i-1) + 1]);
arrays.add("a"+Integer.toString(N-1), new Integer[end - mids.getByIndex(N-2) + 1]);
//copy arrays
copyMergeNSortArr(a, arrays.getByIndex(0), start, mids.getByIndex(0));
for(Integer i=1; i<N-1; i++)
copyMergeNSortArr(a, arrays.getByIndex(i), mids.getByIndex(i-1), mids.getByIndex(i));
copyMergeNSortArr(a, arrays.getByIndex(N-1), mids.getByIndex(N-2), end);
//add INFs
arrays.getByIndex(0)[mids.getByIndex(0)-start] = INF;
for(Integer i=1; i<N-1; i++)
arrays.getByIndex(i)[mids.getByIndex(i)-mids.getByIndex(i-1)] = INF;
arrays.getByIndex(N-1)[end - mids.getByIndex(N-2)] = INF;
//create pointers
Integer[] point=new Integer[N];
for(Integer i=0; i<N; i++)
point[i]=0;
//merge
for(Integer i=start; i<end; i++) {
//elements of each array
Integer[] element=new Integer[N];
for(Integer j=0; j<N; j++)
element[j] = arrays.getByIndex(j)[point[j]];
//get m<SUF>
Integer pos=0, min=element[0];
for(Integer j=0; j<N; j++)
if(min>element[j]) {
min = element[j];
pos = j;
}
//set min
point[pos]++;
a[i] = min;
}
}
private void copyMergeNSortArr(Integer[] a, Integer[] a1, Integer start, Integer end) {
for(Integer i=start; i<end; i++) {
a1[i-start] = a[i];
}
}
public Integer getMax(Integer[] a) {
Integer max = a[0];
for(Integer i=1;i<a.length;i++) {
if(max < a[i]) {
max = a[i];
}
}
return max;
}
public void displayMergeNSortArr(Integer[] a) {
System.out.print("[");
for(Integer i=0; i<a.length-1; i++) {
System.out.print(a[i]+", ");
} System.out.print(a[a.length-1]+"]");
System.out.println();
}
}
|
12436_3 | public class TuinDomotica {
private Boolean daglicht;
private Boolean regen;
private Schakelaar slimmeschakelaar;
private int tijdstip;
tijdstip = 21;
public TuinDomotica() {
super();
slimmeschakelaar = Schakelaar.AUTOMATISCH;
}
public Aansturing() {
// Als de schakelaar op AAN staat zal de verlichting worden aangezet samen met de sproeier
// Als de schakelaar op UIT staat zal de verlichting worden uitgezet samen met de sproeier
// Als de schakelaar op AUTOMATISCH staat zal de verlichting aan gaan tussen 20:00 en 05:00, en de sproeier tussen 20:00 en 05:00 als het niet regent.
}
public Boolean getDaglicht() {
return daglicht;
}
public Boolean getRegen() {
return regen;
}
public void setRegen(Boolean regen) {
this.regen = regen;
}
public Schakelaar getSlimmeschakelaar() {
return slimmeschakelaar;
}
public void setSlimmeschakelaar(schakelaar slimmeschakelaar) {
this.slimmeschakelaar = slimmeschakelaar;
}
public void verlichting() {
//als domotica status op automatisch staat zet dan de verlichting aan tussen 20:00 en 5:00
}
}
| AVANS-SWEN2/tuinieren-wk1-tuinieren-anas-daan | TuinDomotica.java | 369 | //als domotica status op automatisch staat zet dan de verlichting aan tussen 20:00 en 5:00 | line_comment | nl | public class TuinDomotica {
private Boolean daglicht;
private Boolean regen;
private Schakelaar slimmeschakelaar;
private int tijdstip;
tijdstip = 21;
public TuinDomotica() {
super();
slimmeschakelaar = Schakelaar.AUTOMATISCH;
}
public Aansturing() {
// Als de schakelaar op AAN staat zal de verlichting worden aangezet samen met de sproeier
// Als de schakelaar op UIT staat zal de verlichting worden uitgezet samen met de sproeier
// Als de schakelaar op AUTOMATISCH staat zal de verlichting aan gaan tussen 20:00 en 05:00, en de sproeier tussen 20:00 en 05:00 als het niet regent.
}
public Boolean getDaglicht() {
return daglicht;
}
public Boolean getRegen() {
return regen;
}
public void setRegen(Boolean regen) {
this.regen = regen;
}
public Schakelaar getSlimmeschakelaar() {
return slimmeschakelaar;
}
public void setSlimmeschakelaar(schakelaar slimmeschakelaar) {
this.slimmeschakelaar = slimmeschakelaar;
}
public void verlichting() {
//als d<SUF>
}
}
|
25179_6 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.awt.event.ActionListener;
/**
* A graphical view of the simulation grid.
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined using the
* setColor method.
*
* @author Adriaan van Elk, Eric Gunnink & Jelmer Postma
* @version 27-1-2015
*/
public class SimulatorView extends JFrame implements ActionListener
{
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
private JPanel linkerMenu;
private FieldView fieldView;
public JButton oneStepButton = new JButton("1 stap");
public JButton oneHundredStepButton = new JButton("100 stappen");
// A map for storing colors for participants in the simulation
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private FieldStats stats;
private Simulator theSimulator;
/**
* Create a view of the given width and height.
* @param height The simulation's height.
* @param width The simulation's width.
*/
public SimulatorView(int height, int width, Simulator simulator)
{
stats = new FieldStats();
colors = new LinkedHashMap<Class, Color>();
setTitle("Fox and Rabbit Simulation");
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
linkerMenu = new JPanel(new GridLayout(2,1));
theSimulator = simulator;
setLocation(100, 50);
fieldView = new FieldView(height, width);
Container contents = getContentPane();
contents.add(stepLabel, BorderLayout.NORTH);
contents.add(fieldView, BorderLayout.CENTER);
contents.add(population, BorderLayout.SOUTH);
contents.add(linkerMenu, BorderLayout.WEST);
addButton();
pack();
setVisible(true);
}
private void addButton()
{
linkerMenu.add(oneStepButton);
linkerMenu.add(oneHundredStepButton);
oneStepButton.addActionListener(this);
oneHundredStepButton.addActionListener(this);
}
/**
* Methode om een actie uit te voeren wanneer er op een knop wordt geklikt
*/
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("1 stap"))
{
theSimulator.simulateOneStep();
}
if(command.equals("100 stappen"))
{
theSimulator.simulate(100);
}
}
/**
* Define a color to be used for a given class of animal.
* @param animalClass The animal's Class object.
* @param color The color to be used for the given class.
*/
public void setColor(Class animalClass, Color color)
{
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
private Color getColor(Class animalClass)
{
Color col = colors.get(animalClass);
if(col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
}
else {
return col;
}
}
/**
* Show the current status of the field.
* @param step Which iteration step it is.
* @param field The field whose status is to be displayed.
*/
public void showStatus(int step, Field field)
{
if(!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if(animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
}
else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));
fieldView.repaint();
}
/**
* Determine whether the simulation should continue to run.
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field)
{
return stats.isViable(field);
}
/**
* Provide a graphical view of a rectangular field. This is
* a nested class (a class defined inside a class) which
* defines a custom component for the user interface. This
* component displays the field.
* This is rather advanced GUI stuff - you can ignore this
* for your project if you like.
*/
private class FieldView extends JPanel
{
private final int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Dimension size;
private Graphics g;
private Image fieldImage;
/**
* Create a new FieldView component.
*/
public FieldView(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Dimension(0, 0);
}
/**
* Tell the GUI manager how big we would like to be.
*/
public Dimension getPreferredSize()
{
return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
/**
* Prepare for a new round of painting. Since the component
* may be resized, compute the scaling factor again.
*/
public void preparePaint()
{
if(! size.equals(getSize())) { // if the size has changed...
size = getSize();
fieldImage = fieldView.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if(xScale < 1) {
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if(yScale < 1) {
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
/**
* Paint on grid location on this field in a given color.
*/
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);
}
/**
* The field view component needs to be redisplayed. Copy the
* internal image to screen.
*/
public void paintComponent(Graphics g)
{
if(fieldImage != null) {
Dimension currentSize = getSize();
if(size.equals(currentSize)) {
g.drawImage(fieldImage, 0, 0, null);
}
else {
// Rescale the previous image.
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
| AVEHD/fox_bunny | SimulatorView.java | 1,967 | /**
* Methode om een actie uit te voeren wanneer er op een knop wordt geklikt
*/ | block_comment | nl | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.awt.event.ActionListener;
/**
* A graphical view of the simulation grid.
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined using the
* setColor method.
*
* @author Adriaan van Elk, Eric Gunnink & Jelmer Postma
* @version 27-1-2015
*/
public class SimulatorView extends JFrame implements ActionListener
{
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
private JPanel linkerMenu;
private FieldView fieldView;
public JButton oneStepButton = new JButton("1 stap");
public JButton oneHundredStepButton = new JButton("100 stappen");
// A map for storing colors for participants in the simulation
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private FieldStats stats;
private Simulator theSimulator;
/**
* Create a view of the given width and height.
* @param height The simulation's height.
* @param width The simulation's width.
*/
public SimulatorView(int height, int width, Simulator simulator)
{
stats = new FieldStats();
colors = new LinkedHashMap<Class, Color>();
setTitle("Fox and Rabbit Simulation");
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
linkerMenu = new JPanel(new GridLayout(2,1));
theSimulator = simulator;
setLocation(100, 50);
fieldView = new FieldView(height, width);
Container contents = getContentPane();
contents.add(stepLabel, BorderLayout.NORTH);
contents.add(fieldView, BorderLayout.CENTER);
contents.add(population, BorderLayout.SOUTH);
contents.add(linkerMenu, BorderLayout.WEST);
addButton();
pack();
setVisible(true);
}
private void addButton()
{
linkerMenu.add(oneStepButton);
linkerMenu.add(oneHundredStepButton);
oneStepButton.addActionListener(this);
oneHundredStepButton.addActionListener(this);
}
/**
* Method<SUF>*/
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("1 stap"))
{
theSimulator.simulateOneStep();
}
if(command.equals("100 stappen"))
{
theSimulator.simulate(100);
}
}
/**
* Define a color to be used for a given class of animal.
* @param animalClass The animal's Class object.
* @param color The color to be used for the given class.
*/
public void setColor(Class animalClass, Color color)
{
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
private Color getColor(Class animalClass)
{
Color col = colors.get(animalClass);
if(col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
}
else {
return col;
}
}
/**
* Show the current status of the field.
* @param step Which iteration step it is.
* @param field The field whose status is to be displayed.
*/
public void showStatus(int step, Field field)
{
if(!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if(animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
}
else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));
fieldView.repaint();
}
/**
* Determine whether the simulation should continue to run.
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field)
{
return stats.isViable(field);
}
/**
* Provide a graphical view of a rectangular field. This is
* a nested class (a class defined inside a class) which
* defines a custom component for the user interface. This
* component displays the field.
* This is rather advanced GUI stuff - you can ignore this
* for your project if you like.
*/
private class FieldView extends JPanel
{
private final int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Dimension size;
private Graphics g;
private Image fieldImage;
/**
* Create a new FieldView component.
*/
public FieldView(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Dimension(0, 0);
}
/**
* Tell the GUI manager how big we would like to be.
*/
public Dimension getPreferredSize()
{
return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
/**
* Prepare for a new round of painting. Since the component
* may be resized, compute the scaling factor again.
*/
public void preparePaint()
{
if(! size.equals(getSize())) { // if the size has changed...
size = getSize();
fieldImage = fieldView.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if(xScale < 1) {
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if(yScale < 1) {
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
/**
* Paint on grid location on this field in a given color.
*/
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);
}
/**
* The field view component needs to be redisplayed. Copy the
* internal image to screen.
*/
public void paintComponent(Graphics g)
{
if(fieldImage != null) {
Dimension currentSize = getSize();
if(size.equals(currentSize)) {
g.drawImage(fieldImage, 0, 0, null);
}
else {
// Rescale the previous image.
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
|
160626_27 | package doom;
import static data.Defines.*;
import static data.Limits.*;
import data.mapthing_t;
import defines.*;
import demo.IDoomDemo;
import f.Finale;
import static g.Signals.ScanCode.*;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.stream.Stream;
import m.Settings;
import mochadoom.Engine;
import p.mobj_t;
/**
* We need globally shared data structures, for defining the global state
* variables. MAES: in pure OO style, this should be a global "Doom state"
* object to be passed along various modules. No ugly globals here!!! Now, some
* of the variables that appear here were actually defined in separate modules.
* Pretty much, whatever needs to be shared with other modules was placed here,
* either as a local definition, or as an extern share. The very least, I'll
* document where everything is supposed to come from/reside.
*/
public abstract class DoomStatus<T,V> {
public static final int BGCOLOR= 7;
public static final int FGCOLOR =8;
public static int RESENDCOUNT =10;
public static int PL_DRONE =0x80; // bit flag in doomdata->player
public String[] wadfiles=new String[MAXWADFILES];
boolean drone;
/** Command line parametersm, actually defined in d_main.c */
public boolean nomonsters; // checkparm of -nomonsters
public boolean respawnparm; // checkparm of -respawn
public boolean fastparm; // checkparm of -fast
public boolean devparm; // DEBUG: launched with -devparm
// MAES: declared as "extern", shared with Menu.java
public boolean inhelpscreens;
boolean advancedemo;
/////////// Local to doomstat.c ////////////
// TODO: hide those behind getters
/** Game Mode - identify IWAD as shareware, retail etc.
* This is now hidden behind getters so some cases like plutonia
* etc. can be handled more cleanly.
* */
private GameMode gamemode;
public void setGameMode(GameMode mode){
this.gamemode=mode;
}
public GameMode getGameMode(){
return gamemode;
}
public boolean isShareware(){
return (gamemode== GameMode.shareware);
}
/** Commercial means Doom 2, Plutonia, TNT, and possibly others like XBLA.
*
* @return
*/
public boolean isCommercial(){
return (gamemode== GameMode.commercial ||
gamemode== GameMode.pack_plut ||
gamemode== GameMode.pack_tnt ||
gamemode== GameMode.pack_xbla ||
gamemode== GameMode.freedoom2 ||
gamemode== GameMode.freedm);
}
/** Retail means Ultimate.
*
* @return
*/
public boolean isRetail(){
return (gamemode== GameMode.retail || gamemode == GameMode.freedoom1 );
}
/** Registered is a subset of Ultimate
*
* @return
*/
public boolean isRegistered(){
return (gamemode== GameMode.registered || gamemode== GameMode.retail || gamemode == GameMode.freedoom1 );
}
public GameMission_t gamemission;
/** Language. */
public Language_t language;
// /////////// Normally found in d_main.c ///////////////
// Selected skill type, map etc.
/** Defaults for menu, methinks. */
public skill_t startskill;
public int startepisode;
public int startmap;
public boolean autostart;
/** Selected by user */
public skill_t gameskill;
public int gameepisode;
public int gamemap;
/** Nightmare mode flag, single player. */
public boolean respawnmonsters;
/** Netgame? Only true if >1 player. */
public boolean netgame;
/**
* Flag: true only if started as net deathmatch. An enum might handle
* altdeath/cooperative better. Use altdeath for the "2" value
*/
public boolean deathmatch;
/** Use this instead of "deathmatch=2" which is bullshit. */
public boolean altdeath;
//////////// STUFF SHARED WITH THE RENDERER ///////////////
// -------------------------
// Status flags for refresh.
//
public boolean nodrawers;
public boolean noblit;
public boolean viewactive;
// Player taking events, and displaying.
public int consoleplayer;
public int displayplayer;
// Depending on view size - no status bar?
// Note that there is no way to disable the
// status bar explicitely.
public boolean statusbaractive;
public boolean automapactive; // In AutoMap mode?
public boolean menuactive; // Menu overlayed?
public boolean mousecaptured = true;
public boolean paused; // Game Pause?
// -------------------------
// Internal parameters for sound rendering.
// These have been taken from the DOS version,
// but are not (yet) supported with Linux
// (e.g. no sound volume adjustment with menu.
// These are not used, but should be (menu).
// From m_menu.c:
// Sound FX volume has default, 0 - 15
// Music volume has default, 0 - 15
// These are multiplied by 8.
/** maximum volume for sound */
public int snd_SfxVolume;
/** maximum volume for music */
public int snd_MusicVolume;
/** Maximum number of sound channels */
public int numChannels;
// Current music/sfx card - index useless
// w/o a reference LUT in a sound module.
// Ideally, this would use indices found
// in: /usr/include/linux/soundcard.h
public int snd_MusicDevice;
public int snd_SfxDevice;
// Config file? Same disclaimer as above.
public int snd_DesiredMusicDevice;
public int snd_DesiredSfxDevice;
// -------------------------------------
// Scores, rating.
// Statistics on a given map, for intermission.
//
public int totalkills;
public int totalitems;
public int totalsecret;
/** TNTHOM "cheat" for flashing HOM-detecting BG */
public boolean flashing_hom;
// Added for prBoom+ code
public int totallive;
// Timer, for scores.
public int levelstarttic; // gametic at level start
public int leveltime; // tics in game play for par
// --------------------------------------
// DEMO playback/recording related stuff.
// No demo, there is a human player in charge?
// Disable save/end game?
public boolean usergame;
// ?
public boolean demoplayback;
public boolean demorecording;
// Quit after playing a demo from cmdline.
public boolean singledemo;
public boolean mapstrobe;
/**
* Set this to GS_DEMOSCREEN upon init, else it will be null
* Good Sign at 2017/03/21: I hope it is no longer true info, since I've checked its assignment by NetBeans
*/
public gamestate_t gamestate = gamestate_t.GS_DEMOSCREEN;
// -----------------------------
// Internal parameters, fixed.
// These are set by the engine, and not changed
// according to user inputs. Partly load from
// WAD, partly set at startup time.
public int gametic;
// Alive? Disconnected?
public boolean[] playeringame = new boolean[MAXPLAYERS];
public mapthing_t[] deathmatchstarts = new mapthing_t[MAX_DM_STARTS];
/** pointer into deathmatchstarts */
public int deathmatch_p;
/** Player spawn spots. */
public mapthing_t[] playerstarts = new mapthing_t[MAXPLAYERS];
/** Intermission stats.
Parameters for world map / intermission. */
public wbstartstruct_t wminfo;
/** LUT of ammunition limits for each kind.
This doubles with BackPack powerup item.
NOTE: this "maxammo" is treated like a global.
*/
public final static int[] maxammo = {200, 50, 300, 50};
// -----------------------------------------
// Internal parameters, used for engine.
//
// File handling stuff.
public OutputStreamWriter debugfile;
// if true, load all graphics at level load
public boolean precache;
// wipegamestate can be set to -1
// to force a wipe on the next draw
// wipegamestate can be set to -1 to force a wipe on the next draw
public gamestate_t wipegamestate = gamestate_t.GS_DEMOSCREEN;
public int mouseSensitivity = 5; // AX: Fix wrong defaut mouseSensitivity
/** Set if homebrew PWAD stuff has been added. */
public boolean modifiedgame = false;
/** debug flag to cancel adaptiveness set to true during timedemos. */
public boolean singletics = false;
/* A "fastdemo" is a demo with a clock that tics as
* fast as possible, yet it maintains adaptiveness and doesn't
* try to render everything at all costs.
*/
protected boolean fastdemo;
protected boolean normaldemo;
protected String loaddemo = null;
public int bodyqueslot;
// Needed to store the number of the dummy sky flat.
// Used for rendering,
// as well as tracking projectiles etc.
//public int skyflatnum;
// TODO: Netgame stuff (buffers and pointers, i.e. indices).
// TODO: This is ???
public doomcom_t doomcom;
// TODO: This points inside doomcom.
public doomdata_t netbuffer;
public ticcmd_t[] localcmds = new ticcmd_t[BACKUPTICS];
public int rndindex;
public ticcmd_t[][] netcmds;// [MAXPLAYERS][BACKUPTICS];
/** MAES: this WAS NOT in the original.
* Remember to call it!
*/
protected final void initNetGameStuff() {
//this.netbuffer = new doomdata_t();
this.doomcom = new doomcom_t();
this.netcmds = new ticcmd_t[MAXPLAYERS][BACKUPTICS];
Arrays.setAll(localcmds, i -> new ticcmd_t());
for (int i = 0; i < MAXPLAYERS; i++) {
Arrays.setAll(netcmds[i], j -> new ticcmd_t());
}
}
// Fields used for selecting variable BPP implementations.
protected abstract Finale<T> selectFinale();
// MAES: Fields specific to DoomGame. A lot of them were
// duplicated/externalized
// in d_game.c and d_game.h, so it makes sense adopting a more unified
// approach.
protected gameaction_t gameaction=gameaction_t.ga_nothing;
public boolean sendpause; // send a pause event next tic
protected boolean sendsave; // send a save event next tic
protected int starttime;
protected boolean timingdemo; // if true, exit with report on completion
public boolean getPaused() {
return paused;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
// ////////// DEMO SPECIFIC STUFF/////////////
protected String demoname;
protected boolean netdemo;
//protected IDemoTicCmd[] demobuffer;
protected IDoomDemo demobuffer;
/** pointers */
// USELESS protected int demo_p;
// USELESS protected int demoend;
protected short[][] consistancy = new short[MAXPLAYERS][BACKUPTICS];
protected byte[] savebuffer;
/* TODO Proper reconfigurable controls. Defaults hardcoded for now. T3h h4x, d00d. */
public int key_right = SC_NUMKEY6.ordinal();
public int key_left = SC_NUMKEY4.ordinal();
public int key_up = SC_W.ordinal();
public int key_down = SC_S.ordinal();
public int key_strafeleft = SC_A.ordinal();
public int key_straferight = SC_D.ordinal();
public int key_fire = SC_LCTRL.ordinal();
public int key_use = SC_SPACE.ordinal();
public int key_strafe = SC_LALT.ordinal();
public int key_speed = SC_RSHIFT.ordinal();
public boolean vanillaKeyBehavior;
public int key_recordstop = SC_Q.ordinal();
public int[] key_numbers = Stream.of(SC_1, SC_2, SC_3, SC_4, SC_5, SC_6, SC_7, SC_8, SC_9, SC_0)
.mapToInt(Enum::ordinal).toArray();
// Heretic stuff
public int key_lookup = SC_PGUP.ordinal();
public int key_lookdown = SC_PGDOWN.ordinal();
public int key_lookcenter = SC_END.ordinal();
public int mousebfire = 0;
public int mousebstrafe = 2; // AX: Fixed - Now we use the right mouse buttons
public int mousebforward = 1; // AX: Fixed - Now we use the right mouse buttons
public int joybfire;
public int joybstrafe;
public int joybuse;
public int joybspeed;
/** Cancel vertical mouse movement by default */
protected boolean novert=false; // AX: The good default
protected int MAXPLMOVE() {
return forwardmove[1];
}
protected static final int TURBOTHRESHOLD = 0x32;
/** fixed_t */
protected final int[] forwardmove = { 0x19, 0x32 }; // + slow turn
protected final int[] sidemove = { 0x18, 0x28 };
protected final int[] angleturn = { 640, 1280, 320 };
protected static final int SLOWTURNTICS = 6;
protected static final int NUMKEYS = 256;
protected boolean[] gamekeydown = new boolean[NUMKEYS];
protected boolean keysCleared;
public boolean alwaysrun;
protected int turnheld; // for accelerative turning
protected int lookheld; // for accelerative looking?
protected boolean[] mousearray = new boolean[4];
/** This is an alias for mousearray [1+i] */
protected boolean mousebuttons(int i) {
return mousearray[1 + i]; // allow [-1]
}
protected void mousebuttons(int i, boolean value) {
mousearray[1 + i] = value; // allow [-1]
}
protected void mousebuttons(int i, int value) {
mousearray[1 + i] = value != 0; // allow [-1]
}
/** mouse values are used once */
protected int mousex, mousey;
protected int dclicktime;
protected int dclickstate;
protected int dclicks;
protected int dclicktime2, dclickstate2, dclicks2;
/** joystick values are repeated */
protected int joyxmove, joyymove;
protected boolean[] joyarray = new boolean[5];
protected boolean joybuttons(int i) {
return joyarray[1 + i]; // allow [-1]
}
protected void joybuttons(int i, boolean value) {
joyarray[1 + i] = value; // allow [-1]
}
protected void joybuttons(int i, int value) {
joyarray[1 + i] = value != 0; // allow [-1]
}
protected int savegameslot;
protected String savedescription;
protected static final int BODYQUESIZE = 32;
protected mobj_t[] bodyque = new mobj_t[BODYQUESIZE];
public String statcopy; // for statistics driver
/** Not documented/used in linuxdoom. I supposed it could be used to
* ignore mouse input?
*/
public boolean use_mouse,use_joystick;
/** More prBoom+ stuff. Used mostly for code uhm..reuse, rather
* than to actually change the way stuff works.
*
*/
public static int compatibility_level;
public final ConfigManager CM = Engine.getConfig();
public DoomStatus() {
this.wminfo=new wbstartstruct_t();
initNetGameStuff();
}
public void update() {
this.snd_SfxVolume = CM.getValue(Settings.sfx_volume, Integer.class);
this.snd_MusicVolume = CM.getValue(Settings.music_volume, Integer.class);
this.alwaysrun = CM.equals(Settings.alwaysrun, Boolean.TRUE);
// Keys...
this.key_right = CM.getValue(Settings.key_right, Integer.class);
this.key_left = CM.getValue(Settings.key_left, Integer.class);
this.key_up = CM.getValue(Settings.key_up, Integer.class);
this.key_down = CM.getValue(Settings.key_down, Integer.class);
this.key_strafeleft = CM.getValue(Settings.key_strafeleft, Integer.class);
this.key_straferight = CM.getValue(Settings.key_straferight, Integer.class);
this.key_fire = CM.getValue(Settings.key_fire, Integer.class);
this.key_use = CM.getValue(Settings.key_use, Integer.class);
this.key_strafe = CM.getValue(Settings.key_strafe, Integer.class);
this.key_speed = CM.getValue(Settings.key_speed, Integer.class);
// Mouse buttons
this.use_mouse = CM.equals(Settings.use_mouse, 1);
this.mousebfire = CM.getValue(Settings.mouseb_fire, Integer.class);
this.mousebstrafe = CM.getValue(Settings.mouseb_strafe, Integer.class);
this.mousebforward = CM.getValue(Settings.mouseb_forward, Integer.class);
// Joystick
this.use_joystick = CM.equals(Settings.use_joystick, 1);
this.joybfire = CM.getValue(Settings.joyb_fire, Integer.class);
this.joybstrafe = CM.getValue(Settings.joyb_strafe, Integer.class);
this.joybuse = CM.getValue(Settings.joyb_use, Integer.class);
this.joybspeed = CM.getValue(Settings.joyb_speed, Integer.class);
// Sound
this.numChannels = CM.getValue(Settings.snd_channels, Integer.class);
// Map strobe
this.mapstrobe = CM.equals(Settings.vestrobe, Boolean.TRUE);
// Mouse sensitivity
this.mouseSensitivity = CM.getValue(Settings.mouse_sensitivity, Integer.class);
// This should indicate keyboard behavior should be as close as possible to vanilla
this.vanillaKeyBehavior = CM.equals(Settings.vanilla_key_behavior, Boolean.TRUE);
}
public void commit() {
CM.update(Settings.sfx_volume, this.snd_SfxVolume);
CM.update(Settings.music_volume, this.snd_MusicVolume);
CM.update(Settings.alwaysrun, this.alwaysrun);
// Keys...
CM.update(Settings.key_right, this.key_right);
CM.update(Settings.key_left, this.key_left);
CM.update(Settings.key_up, this.key_up);
CM.update(Settings.key_down, this.key_down);
CM.update(Settings.key_strafeleft, this.key_strafeleft);
CM.update(Settings.key_straferight, this.key_straferight);
CM.update(Settings.key_fire, this.key_fire);
CM.update(Settings.key_use, this.key_use);
CM.update(Settings.key_strafe, this.key_strafe);
CM.update(Settings.key_speed, this.key_speed);
// Mouse buttons
CM.update(Settings.use_mouse, this.use_mouse ? 1 : 0);
CM.update(Settings.mouseb_fire, this.mousebfire);
CM.update(Settings.mouseb_strafe, this.mousebstrafe);
CM.update(Settings.mouseb_forward, this.mousebforward);
// Joystick
CM.update(Settings.use_joystick, this.use_joystick ? 1 : 0);
CM.update(Settings.joyb_fire, this.joybfire);
CM.update(Settings.joyb_strafe, this.joybstrafe);
CM.update(Settings.joyb_use, this.joybuse);
CM.update(Settings.joyb_speed, this.joybspeed);
// Sound
CM.update(Settings.snd_channels, this.numChannels);
// Map strobe
CM.update(Settings.vestrobe, this.mapstrobe);
// Mouse sensitivity
CM.update(Settings.mouse_sensitivity, this.mouseSensitivity);
}
}
// $Log: DoomStatus.java,v $
// Revision 1.36 2012/11/06 16:04:58 velktron
// Variables manager less tightly integrated.
//
// Revision 1.35 2012/09/24 17:16:22 velktron
// Massive merge between HiColor and HEAD. There's no difference from now on, and development continues on HEAD.
//
// Revision 1.34.2.3 2012/09/24 16:58:06 velktron
// TrueColor, Generics.
//
// Revision 1.34.2.2 2012/09/20 14:25:13 velktron
// Unified DOOM!!!
//
// Revision 1.34.2.1 2012/09/17 16:06:52 velktron
// Now handling updates of all variables, though those specific to some subsystems should probably be moved???
//
// Revision 1.34 2011/11/01 23:48:10 velktron
// Added tnthom stuff.
//
// Revision 1.33 2011/10/24 02:11:27 velktron
// Stream compliancy
//
// Revision 1.32 2011/10/07 16:01:16 velktron
// Added freelook stuff, using Keys.
//
// Revision 1.31 2011/09/27 16:01:41 velktron
// -complevel_t
//
// Revision 1.30 2011/09/27 15:54:51 velktron
// Added some more prBoom+ stuff.
//
// Revision 1.29 2011/07/28 17:07:04 velktron
// Added always run hack.
//
// Revision 1.28 2011/07/16 10:57:50 velktron
// Merged finnw's changes for enabling polling of ?_LOCK keys.
//
// Revision 1.27 2011/06/14 20:59:47 velktron
// Channel settings now read from default.cfg. Changes in sound creation order.
//
// Revision 1.26 2011/06/04 11:04:25 velktron
// Fixed registered/ultimate identification.
//
// Revision 1.25 2011/06/01 17:35:56 velktron
// Techdemo v1.4a level. Default novert and experimental mochaevents interface.
//
// Revision 1.24 2011/06/01 00:37:58 velktron
// Changed default keys to WASD.
//
// Revision 1.23 2011/05/31 21:45:51 velktron
// Added XBLA version as explicitly supported.
//
// Revision 1.22 2011/05/30 15:50:42 velktron
// Changed to work with new Abstract classes
//
// Revision 1.21 2011/05/26 17:52:11 velktron
// Now using ICommandLineManager
//
// Revision 1.20 2011/05/26 13:39:52 velktron
// Now using ICommandLineManager
//
// Revision 1.19 2011/05/25 17:56:52 velktron
// Introduced some fixes for mousebuttons etc.
//
// Revision 1.18 2011/05/24 17:44:37 velktron
// usemouse added for defaults
// | AXDOOMER/mochadoom | src/doom/DoomStatus.java | 6,293 | // Depending on view size - no status bar? | line_comment | nl | package doom;
import static data.Defines.*;
import static data.Limits.*;
import data.mapthing_t;
import defines.*;
import demo.IDoomDemo;
import f.Finale;
import static g.Signals.ScanCode.*;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.stream.Stream;
import m.Settings;
import mochadoom.Engine;
import p.mobj_t;
/**
* We need globally shared data structures, for defining the global state
* variables. MAES: in pure OO style, this should be a global "Doom state"
* object to be passed along various modules. No ugly globals here!!! Now, some
* of the variables that appear here were actually defined in separate modules.
* Pretty much, whatever needs to be shared with other modules was placed here,
* either as a local definition, or as an extern share. The very least, I'll
* document where everything is supposed to come from/reside.
*/
public abstract class DoomStatus<T,V> {
public static final int BGCOLOR= 7;
public static final int FGCOLOR =8;
public static int RESENDCOUNT =10;
public static int PL_DRONE =0x80; // bit flag in doomdata->player
public String[] wadfiles=new String[MAXWADFILES];
boolean drone;
/** Command line parametersm, actually defined in d_main.c */
public boolean nomonsters; // checkparm of -nomonsters
public boolean respawnparm; // checkparm of -respawn
public boolean fastparm; // checkparm of -fast
public boolean devparm; // DEBUG: launched with -devparm
// MAES: declared as "extern", shared with Menu.java
public boolean inhelpscreens;
boolean advancedemo;
/////////// Local to doomstat.c ////////////
// TODO: hide those behind getters
/** Game Mode - identify IWAD as shareware, retail etc.
* This is now hidden behind getters so some cases like plutonia
* etc. can be handled more cleanly.
* */
private GameMode gamemode;
public void setGameMode(GameMode mode){
this.gamemode=mode;
}
public GameMode getGameMode(){
return gamemode;
}
public boolean isShareware(){
return (gamemode== GameMode.shareware);
}
/** Commercial means Doom 2, Plutonia, TNT, and possibly others like XBLA.
*
* @return
*/
public boolean isCommercial(){
return (gamemode== GameMode.commercial ||
gamemode== GameMode.pack_plut ||
gamemode== GameMode.pack_tnt ||
gamemode== GameMode.pack_xbla ||
gamemode== GameMode.freedoom2 ||
gamemode== GameMode.freedm);
}
/** Retail means Ultimate.
*
* @return
*/
public boolean isRetail(){
return (gamemode== GameMode.retail || gamemode == GameMode.freedoom1 );
}
/** Registered is a subset of Ultimate
*
* @return
*/
public boolean isRegistered(){
return (gamemode== GameMode.registered || gamemode== GameMode.retail || gamemode == GameMode.freedoom1 );
}
public GameMission_t gamemission;
/** Language. */
public Language_t language;
// /////////// Normally found in d_main.c ///////////////
// Selected skill type, map etc.
/** Defaults for menu, methinks. */
public skill_t startskill;
public int startepisode;
public int startmap;
public boolean autostart;
/** Selected by user */
public skill_t gameskill;
public int gameepisode;
public int gamemap;
/** Nightmare mode flag, single player. */
public boolean respawnmonsters;
/** Netgame? Only true if >1 player. */
public boolean netgame;
/**
* Flag: true only if started as net deathmatch. An enum might handle
* altdeath/cooperative better. Use altdeath for the "2" value
*/
public boolean deathmatch;
/** Use this instead of "deathmatch=2" which is bullshit. */
public boolean altdeath;
//////////// STUFF SHARED WITH THE RENDERER ///////////////
// -------------------------
// Status flags for refresh.
//
public boolean nodrawers;
public boolean noblit;
public boolean viewactive;
// Player taking events, and displaying.
public int consoleplayer;
public int displayplayer;
// Depen<SUF>
// Note that there is no way to disable the
// status bar explicitely.
public boolean statusbaractive;
public boolean automapactive; // In AutoMap mode?
public boolean menuactive; // Menu overlayed?
public boolean mousecaptured = true;
public boolean paused; // Game Pause?
// -------------------------
// Internal parameters for sound rendering.
// These have been taken from the DOS version,
// but are not (yet) supported with Linux
// (e.g. no sound volume adjustment with menu.
// These are not used, but should be (menu).
// From m_menu.c:
// Sound FX volume has default, 0 - 15
// Music volume has default, 0 - 15
// These are multiplied by 8.
/** maximum volume for sound */
public int snd_SfxVolume;
/** maximum volume for music */
public int snd_MusicVolume;
/** Maximum number of sound channels */
public int numChannels;
// Current music/sfx card - index useless
// w/o a reference LUT in a sound module.
// Ideally, this would use indices found
// in: /usr/include/linux/soundcard.h
public int snd_MusicDevice;
public int snd_SfxDevice;
// Config file? Same disclaimer as above.
public int snd_DesiredMusicDevice;
public int snd_DesiredSfxDevice;
// -------------------------------------
// Scores, rating.
// Statistics on a given map, for intermission.
//
public int totalkills;
public int totalitems;
public int totalsecret;
/** TNTHOM "cheat" for flashing HOM-detecting BG */
public boolean flashing_hom;
// Added for prBoom+ code
public int totallive;
// Timer, for scores.
public int levelstarttic; // gametic at level start
public int leveltime; // tics in game play for par
// --------------------------------------
// DEMO playback/recording related stuff.
// No demo, there is a human player in charge?
// Disable save/end game?
public boolean usergame;
// ?
public boolean demoplayback;
public boolean demorecording;
// Quit after playing a demo from cmdline.
public boolean singledemo;
public boolean mapstrobe;
/**
* Set this to GS_DEMOSCREEN upon init, else it will be null
* Good Sign at 2017/03/21: I hope it is no longer true info, since I've checked its assignment by NetBeans
*/
public gamestate_t gamestate = gamestate_t.GS_DEMOSCREEN;
// -----------------------------
// Internal parameters, fixed.
// These are set by the engine, and not changed
// according to user inputs. Partly load from
// WAD, partly set at startup time.
public int gametic;
// Alive? Disconnected?
public boolean[] playeringame = new boolean[MAXPLAYERS];
public mapthing_t[] deathmatchstarts = new mapthing_t[MAX_DM_STARTS];
/** pointer into deathmatchstarts */
public int deathmatch_p;
/** Player spawn spots. */
public mapthing_t[] playerstarts = new mapthing_t[MAXPLAYERS];
/** Intermission stats.
Parameters for world map / intermission. */
public wbstartstruct_t wminfo;
/** LUT of ammunition limits for each kind.
This doubles with BackPack powerup item.
NOTE: this "maxammo" is treated like a global.
*/
public final static int[] maxammo = {200, 50, 300, 50};
// -----------------------------------------
// Internal parameters, used for engine.
//
// File handling stuff.
public OutputStreamWriter debugfile;
// if true, load all graphics at level load
public boolean precache;
// wipegamestate can be set to -1
// to force a wipe on the next draw
// wipegamestate can be set to -1 to force a wipe on the next draw
public gamestate_t wipegamestate = gamestate_t.GS_DEMOSCREEN;
public int mouseSensitivity = 5; // AX: Fix wrong defaut mouseSensitivity
/** Set if homebrew PWAD stuff has been added. */
public boolean modifiedgame = false;
/** debug flag to cancel adaptiveness set to true during timedemos. */
public boolean singletics = false;
/* A "fastdemo" is a demo with a clock that tics as
* fast as possible, yet it maintains adaptiveness and doesn't
* try to render everything at all costs.
*/
protected boolean fastdemo;
protected boolean normaldemo;
protected String loaddemo = null;
public int bodyqueslot;
// Needed to store the number of the dummy sky flat.
// Used for rendering,
// as well as tracking projectiles etc.
//public int skyflatnum;
// TODO: Netgame stuff (buffers and pointers, i.e. indices).
// TODO: This is ???
public doomcom_t doomcom;
// TODO: This points inside doomcom.
public doomdata_t netbuffer;
public ticcmd_t[] localcmds = new ticcmd_t[BACKUPTICS];
public int rndindex;
public ticcmd_t[][] netcmds;// [MAXPLAYERS][BACKUPTICS];
/** MAES: this WAS NOT in the original.
* Remember to call it!
*/
protected final void initNetGameStuff() {
//this.netbuffer = new doomdata_t();
this.doomcom = new doomcom_t();
this.netcmds = new ticcmd_t[MAXPLAYERS][BACKUPTICS];
Arrays.setAll(localcmds, i -> new ticcmd_t());
for (int i = 0; i < MAXPLAYERS; i++) {
Arrays.setAll(netcmds[i], j -> new ticcmd_t());
}
}
// Fields used for selecting variable BPP implementations.
protected abstract Finale<T> selectFinale();
// MAES: Fields specific to DoomGame. A lot of them were
// duplicated/externalized
// in d_game.c and d_game.h, so it makes sense adopting a more unified
// approach.
protected gameaction_t gameaction=gameaction_t.ga_nothing;
public boolean sendpause; // send a pause event next tic
protected boolean sendsave; // send a save event next tic
protected int starttime;
protected boolean timingdemo; // if true, exit with report on completion
public boolean getPaused() {
return paused;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
// ////////// DEMO SPECIFIC STUFF/////////////
protected String demoname;
protected boolean netdemo;
//protected IDemoTicCmd[] demobuffer;
protected IDoomDemo demobuffer;
/** pointers */
// USELESS protected int demo_p;
// USELESS protected int demoend;
protected short[][] consistancy = new short[MAXPLAYERS][BACKUPTICS];
protected byte[] savebuffer;
/* TODO Proper reconfigurable controls. Defaults hardcoded for now. T3h h4x, d00d. */
public int key_right = SC_NUMKEY6.ordinal();
public int key_left = SC_NUMKEY4.ordinal();
public int key_up = SC_W.ordinal();
public int key_down = SC_S.ordinal();
public int key_strafeleft = SC_A.ordinal();
public int key_straferight = SC_D.ordinal();
public int key_fire = SC_LCTRL.ordinal();
public int key_use = SC_SPACE.ordinal();
public int key_strafe = SC_LALT.ordinal();
public int key_speed = SC_RSHIFT.ordinal();
public boolean vanillaKeyBehavior;
public int key_recordstop = SC_Q.ordinal();
public int[] key_numbers = Stream.of(SC_1, SC_2, SC_3, SC_4, SC_5, SC_6, SC_7, SC_8, SC_9, SC_0)
.mapToInt(Enum::ordinal).toArray();
// Heretic stuff
public int key_lookup = SC_PGUP.ordinal();
public int key_lookdown = SC_PGDOWN.ordinal();
public int key_lookcenter = SC_END.ordinal();
public int mousebfire = 0;
public int mousebstrafe = 2; // AX: Fixed - Now we use the right mouse buttons
public int mousebforward = 1; // AX: Fixed - Now we use the right mouse buttons
public int joybfire;
public int joybstrafe;
public int joybuse;
public int joybspeed;
/** Cancel vertical mouse movement by default */
protected boolean novert=false; // AX: The good default
protected int MAXPLMOVE() {
return forwardmove[1];
}
protected static final int TURBOTHRESHOLD = 0x32;
/** fixed_t */
protected final int[] forwardmove = { 0x19, 0x32 }; // + slow turn
protected final int[] sidemove = { 0x18, 0x28 };
protected final int[] angleturn = { 640, 1280, 320 };
protected static final int SLOWTURNTICS = 6;
protected static final int NUMKEYS = 256;
protected boolean[] gamekeydown = new boolean[NUMKEYS];
protected boolean keysCleared;
public boolean alwaysrun;
protected int turnheld; // for accelerative turning
protected int lookheld; // for accelerative looking?
protected boolean[] mousearray = new boolean[4];
/** This is an alias for mousearray [1+i] */
protected boolean mousebuttons(int i) {
return mousearray[1 + i]; // allow [-1]
}
protected void mousebuttons(int i, boolean value) {
mousearray[1 + i] = value; // allow [-1]
}
protected void mousebuttons(int i, int value) {
mousearray[1 + i] = value != 0; // allow [-1]
}
/** mouse values are used once */
protected int mousex, mousey;
protected int dclicktime;
protected int dclickstate;
protected int dclicks;
protected int dclicktime2, dclickstate2, dclicks2;
/** joystick values are repeated */
protected int joyxmove, joyymove;
protected boolean[] joyarray = new boolean[5];
protected boolean joybuttons(int i) {
return joyarray[1 + i]; // allow [-1]
}
protected void joybuttons(int i, boolean value) {
joyarray[1 + i] = value; // allow [-1]
}
protected void joybuttons(int i, int value) {
joyarray[1 + i] = value != 0; // allow [-1]
}
protected int savegameslot;
protected String savedescription;
protected static final int BODYQUESIZE = 32;
protected mobj_t[] bodyque = new mobj_t[BODYQUESIZE];
public String statcopy; // for statistics driver
/** Not documented/used in linuxdoom. I supposed it could be used to
* ignore mouse input?
*/
public boolean use_mouse,use_joystick;
/** More prBoom+ stuff. Used mostly for code uhm..reuse, rather
* than to actually change the way stuff works.
*
*/
public static int compatibility_level;
public final ConfigManager CM = Engine.getConfig();
public DoomStatus() {
this.wminfo=new wbstartstruct_t();
initNetGameStuff();
}
public void update() {
this.snd_SfxVolume = CM.getValue(Settings.sfx_volume, Integer.class);
this.snd_MusicVolume = CM.getValue(Settings.music_volume, Integer.class);
this.alwaysrun = CM.equals(Settings.alwaysrun, Boolean.TRUE);
// Keys...
this.key_right = CM.getValue(Settings.key_right, Integer.class);
this.key_left = CM.getValue(Settings.key_left, Integer.class);
this.key_up = CM.getValue(Settings.key_up, Integer.class);
this.key_down = CM.getValue(Settings.key_down, Integer.class);
this.key_strafeleft = CM.getValue(Settings.key_strafeleft, Integer.class);
this.key_straferight = CM.getValue(Settings.key_straferight, Integer.class);
this.key_fire = CM.getValue(Settings.key_fire, Integer.class);
this.key_use = CM.getValue(Settings.key_use, Integer.class);
this.key_strafe = CM.getValue(Settings.key_strafe, Integer.class);
this.key_speed = CM.getValue(Settings.key_speed, Integer.class);
// Mouse buttons
this.use_mouse = CM.equals(Settings.use_mouse, 1);
this.mousebfire = CM.getValue(Settings.mouseb_fire, Integer.class);
this.mousebstrafe = CM.getValue(Settings.mouseb_strafe, Integer.class);
this.mousebforward = CM.getValue(Settings.mouseb_forward, Integer.class);
// Joystick
this.use_joystick = CM.equals(Settings.use_joystick, 1);
this.joybfire = CM.getValue(Settings.joyb_fire, Integer.class);
this.joybstrafe = CM.getValue(Settings.joyb_strafe, Integer.class);
this.joybuse = CM.getValue(Settings.joyb_use, Integer.class);
this.joybspeed = CM.getValue(Settings.joyb_speed, Integer.class);
// Sound
this.numChannels = CM.getValue(Settings.snd_channels, Integer.class);
// Map strobe
this.mapstrobe = CM.equals(Settings.vestrobe, Boolean.TRUE);
// Mouse sensitivity
this.mouseSensitivity = CM.getValue(Settings.mouse_sensitivity, Integer.class);
// This should indicate keyboard behavior should be as close as possible to vanilla
this.vanillaKeyBehavior = CM.equals(Settings.vanilla_key_behavior, Boolean.TRUE);
}
public void commit() {
CM.update(Settings.sfx_volume, this.snd_SfxVolume);
CM.update(Settings.music_volume, this.snd_MusicVolume);
CM.update(Settings.alwaysrun, this.alwaysrun);
// Keys...
CM.update(Settings.key_right, this.key_right);
CM.update(Settings.key_left, this.key_left);
CM.update(Settings.key_up, this.key_up);
CM.update(Settings.key_down, this.key_down);
CM.update(Settings.key_strafeleft, this.key_strafeleft);
CM.update(Settings.key_straferight, this.key_straferight);
CM.update(Settings.key_fire, this.key_fire);
CM.update(Settings.key_use, this.key_use);
CM.update(Settings.key_strafe, this.key_strafe);
CM.update(Settings.key_speed, this.key_speed);
// Mouse buttons
CM.update(Settings.use_mouse, this.use_mouse ? 1 : 0);
CM.update(Settings.mouseb_fire, this.mousebfire);
CM.update(Settings.mouseb_strafe, this.mousebstrafe);
CM.update(Settings.mouseb_forward, this.mousebforward);
// Joystick
CM.update(Settings.use_joystick, this.use_joystick ? 1 : 0);
CM.update(Settings.joyb_fire, this.joybfire);
CM.update(Settings.joyb_strafe, this.joybstrafe);
CM.update(Settings.joyb_use, this.joybuse);
CM.update(Settings.joyb_speed, this.joybspeed);
// Sound
CM.update(Settings.snd_channels, this.numChannels);
// Map strobe
CM.update(Settings.vestrobe, this.mapstrobe);
// Mouse sensitivity
CM.update(Settings.mouse_sensitivity, this.mouseSensitivity);
}
}
// $Log: DoomStatus.java,v $
// Revision 1.36 2012/11/06 16:04:58 velktron
// Variables manager less tightly integrated.
//
// Revision 1.35 2012/09/24 17:16:22 velktron
// Massive merge between HiColor and HEAD. There's no difference from now on, and development continues on HEAD.
//
// Revision 1.34.2.3 2012/09/24 16:58:06 velktron
// TrueColor, Generics.
//
// Revision 1.34.2.2 2012/09/20 14:25:13 velktron
// Unified DOOM!!!
//
// Revision 1.34.2.1 2012/09/17 16:06:52 velktron
// Now handling updates of all variables, though those specific to some subsystems should probably be moved???
//
// Revision 1.34 2011/11/01 23:48:10 velktron
// Added tnthom stuff.
//
// Revision 1.33 2011/10/24 02:11:27 velktron
// Stream compliancy
//
// Revision 1.32 2011/10/07 16:01:16 velktron
// Added freelook stuff, using Keys.
//
// Revision 1.31 2011/09/27 16:01:41 velktron
// -complevel_t
//
// Revision 1.30 2011/09/27 15:54:51 velktron
// Added some more prBoom+ stuff.
//
// Revision 1.29 2011/07/28 17:07:04 velktron
// Added always run hack.
//
// Revision 1.28 2011/07/16 10:57:50 velktron
// Merged finnw's changes for enabling polling of ?_LOCK keys.
//
// Revision 1.27 2011/06/14 20:59:47 velktron
// Channel settings now read from default.cfg. Changes in sound creation order.
//
// Revision 1.26 2011/06/04 11:04:25 velktron
// Fixed registered/ultimate identification.
//
// Revision 1.25 2011/06/01 17:35:56 velktron
// Techdemo v1.4a level. Default novert and experimental mochaevents interface.
//
// Revision 1.24 2011/06/01 00:37:58 velktron
// Changed default keys to WASD.
//
// Revision 1.23 2011/05/31 21:45:51 velktron
// Added XBLA version as explicitly supported.
//
// Revision 1.22 2011/05/30 15:50:42 velktron
// Changed to work with new Abstract classes
//
// Revision 1.21 2011/05/26 17:52:11 velktron
// Now using ICommandLineManager
//
// Revision 1.20 2011/05/26 13:39:52 velktron
// Now using ICommandLineManager
//
// Revision 1.19 2011/05/25 17:56:52 velktron
// Introduced some fixes for mousebuttons etc.
//
// Revision 1.18 2011/05/24 17:44:37 velktron
// usemouse added for defaults
// |
18061_2 | package edu.umich.eecs.soar.props.editors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import edu.umich.eecs.soar.propsutil.LearnConfig;
import edu.umich.eecs.soar.propsutil.PROPsEnvironment;
public class EditorsWorld extends PROPsEnvironment {
private static double STD_MOTOR_TIME = 0.25,
STD_VISUAL_TIME = 0.25;
private ETask ed_task;
private Report rep;
//private int task_count; // The index of edit_tasks to use next
private String task_name;
private List<ArrayList<String[]>> edit_tasks;
private String[] numbers;
public boolean inDebug = false;
EditorsWorld() {
String proj_dir = "/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/domains/editors/";
String props_dir = "/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/PROPsAgent/";
this.setAgentName("EditorsAgent");
this.setPropsDir(props_dir);
this.setCondChunkFile(proj_dir + "editors_agent_condspread_chunks.soar");
this.setAddressChunkFile(proj_dir + "editors_agent_L1_chunks.soar");
this.setFetchSeqFile(proj_dir + "editors_agent_fetch_procedures.soar");
this.setInstructionsFile(proj_dir + "editors_agent_instructions.soar");
this.setSoarAgentFile(proj_dir + "editors_agent.soar");
this.setIOSize(4, 3);
this.setUserAgentFiles(Arrays.asList("/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/domains/lib_actransfer_interface.soar",
proj_dir + "editors_agent_smem.soar"));
this.edit_tasks = new LinkedList<ArrayList<String[]>>();
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(0).add(new String[]{"replace-word", "vader", "moeder", "one"});
edit_tasks.get(0).add(new String[]{"insert-word", "inhoud", "nieuwe", "three"});
edit_tasks.get(0).add(new String[]{"delete-word", "slome", "", "five"});
edit_tasks.get(0).add(new String[]{"replace-line", "ebooks en sociale medi", "electronisch boeken en andere vormen van sociale media", "eight"});
edit_tasks.get(0).add(new String[]{"delete-line", "of the rings trilogie", "", "fifteen"});
edit_tasks.get(0).add(new String[]{"insert-line", "Oscar of niet Rowling zal er niet om rouwen want de buit is al binnen", "net zo groot als tien jaar geleden", "eighteen"});
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(1).add(new String[]{"insert-word", "pers", "muskieten", "two"});
edit_tasks.get(1).add(new String[]{"replace-line", "fans mochten een blik op de inhoud werpen onder voorwaarde van strikte geheimhouding", "fans hadden de gelegenheid om alvast een kijkje te nemen", "three"});
edit_tasks.get(1).add(new String[]{"replace-word", "medi", "media", "eight"});
edit_tasks.get(1).add(new String[]{"delete-word", "eindelijk", "", "fourteen"});
edit_tasks.get(1).add(new String[]{"delete-line", "We all know what happened in the end but", "", "sixteen"});
edit_tasks.get(1).add(new String[]{"insert-line", "kassucces De spanning is daarom groot dit jaar", "succes Het zal Roling waarschijnlijk een worst wezen", "seventeen"});
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(2).add(new String[]{"replace-line", "Geestelijk vader van de tovenaarsleerling JK Rowling lanceert morgen de site pottermorecom", "Wederom is het tijd voor een nieuwe website over harry potter maar deze keer van Rowling zelf", "one"});
edit_tasks.get(2).add(new String[]{"insert-word", "paar", "klein", "two"});
edit_tasks.get(2).add(new String[]{"delete-word", "nieuwe", "", "five"});
edit_tasks.get(2).add(new String[]{"delete-line", "Op dit moment staat de laatste film in de serie op het punt om in de bioscoop", "", "twelve"});
edit_tasks.get(2).add(new String[]{"replace-word", "Oscar", "prijs", "thirteen"});
edit_tasks.get(2).add(new String[]{"insert-line", "kassucces De spanning is daarom groot dit jaar", "And here we have another meaningless line that makes this text een more unreadable", "seventeen"});
numbers = new String[]{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"};
}
public void runEditorsDebug(String task, int taskNum, LearnConfig config) {
String taskSeq = task + "_" + (taskNum+1);
task_name = task;
//task_count = taskNum;
inDebug = true;
this.runDebug(task, taskSeq, config);
inDebug = false;
}
private int getEditTaskIndex(String taskSeq) {
if (taskSeq.contains("_1")) {
return 0;
}
else if (taskSeq.contains("_2")) {
return 1;
}
else if (taskSeq.contains("_3")) {
return 2;
}
else return -1; // Error, shouldn't happen
}
// Helper functions specifically for the Editors environment
private void determine_v() {
List<String> L = ed_task.text.get(ed_task.line_pos);
String line = numbers[ed_task.line_pos];
String word;
if (L.size() <= ed_task.cursor_pos)
word = "eol";
else
word = ed_task.text.get(ed_task.line_pos).get(ed_task.cursor_pos);
ed_task.set_vlist("word", word, "nil", line);
}
private List<String> substitute_insert(String old_element, String new_element, List<String> l) {
if (l == null || l.size() == 0)
return l;
return new LinkedList<String>(Arrays.asList(String.join(" ", l).replaceFirst(old_element, new_element).split("\\s+")));
}
@Override
protected void user_outputListener(List<String> outputs) {
// Get the output
String action = outputs.get(0);
String val2 = outputs.get(1);
String val3 = outputs.get(2);
double latency = 0.05;
// Generate the corresponding input
int iTemp;
String sTemp;
List<String> temp;
switch (rep.state) {
case "ll-noread":
if (action.equals("read-instruction")) {
rep.state = "ll";
rep.task = ed_task.edits.get(0)[0];
}
else {
System.out.println("Something went wrong...");
}
break;
case "ll":
if (action.equals("number-p") || action.equals("enter") || action.equals("t-word")) {
rep.ll = System.nanoTime() - rep.strt;
rep.state = "ll-motor";
}
if (action.equals("read-instruction") && ed_task.edits.get(0)[3].equals(numbers[ed_task.line_pos])) {
if (rep.state.equals("ll")) {
rep.ll = System.nanoTime()-rep.strt;
rep.state = "mt";
rep.temp = System.nanoTime();
}
}
break;
case "ll-motor":
if (action.equals("read-instruction")) {
rep.state = "mt";
rep.temp = System.nanoTime();
}
break;
case "mt":
temp = new ArrayList<String>(Arrays.asList("substitute-ed", "substitute-edt", "insert-ed", "insert-edt",
"period-d", "type-text", "type-text-enter", "d", "control-k", "control-k-twice", "esc-d"));
if (temp.contains(action)) {
rep.state = "mt-motor";
rep.mt = System.nanoTime() - rep.temp;
}
break;
case "mt-motor":
if (action.equals("next-instruction")) {
rep.state = "ll";
//rep.addLatency(STD_VISUAL_TIME); // Could move latency for 'next-instruction' here so it ends up in the report, but Taatgen doesn't?
this.addReport(rep.toString());
if (ed_task.edits.size() <= 1)
rep.task = "nil";
else
rep.task = ed_task.edits.get(1)[0];
rep.strt = System.nanoTime();
rep.latencies = 0.0;
}
break;
case "end":
break; // Do nothing (not in original lisp code - never gets called anyway)
}
switch (action) {
case "enter": case "control-n":
ed_task.line_pos++;
ed_task.cursor_pos = 0;
latency = (action.equals("enter")) ? (STD_MOTOR_TIME + STD_VISUAL_TIME) : STD_MOTOR_TIME;
determine_v();
break;
case "esc-f": case "move-attention-right":
latency = (action.equals("esc-f")) ? (2.0 * STD_MOTOR_TIME) : STD_VISUAL_TIME;
ed_task.cursor_pos++;
determine_v();
break;
case "read-screen":
determine_v();
latency = STD_VISUAL_TIME;
break;
case "read-instruction":
ed_task.set_vlist(ed_task.edits.get(0));
latency = STD_VISUAL_TIME;
break;
case "next-instruction":
if (ed_task.edits.size() == 0)
break; // end
ed_task.edits.remove(0);
if (ed_task.edits.size() > 0) {
ed_task.set_vlist(ed_task.edits.get(0));
}
else {
ed_task.set_vlist("end", "end2", "end3", "end4");
rep.state = "end";
}
latency = STD_VISUAL_TIME;
break;
case "focus-on-word": case "focus-on-next-word":
if (action.equals("focus-on-word")) {
ed_task.line = new LinkedList<String>(Arrays.asList(ed_task.edits.get(0)[1].split("\\s")));
}
sTemp = "short";
if (ed_task.line.size() == 1 || ed_task.line.get(0).length() > 4) // If the word in the line is longer than 4 characters
sTemp = "long";
ed_task.set_vlist("single-word", ed_task.line.get(0), sTemp, "");
ed_task.line.remove(0);
latency = STD_VISUAL_TIME;
break;
case "esc-d": // Delete an element in the line
ed_task.text.get(ed_task.line_pos).remove(ed_task.cursor_pos);
latency = STD_MOTOR_TIME;
determine_v();
break;
case "type-text": case "type-text-enter": case "period-a": case "i": // Insert text into the line
if (!action.equals("type-text")) {
int pos = ed_task.line_pos;
for (int i=0; i<19-pos; ++i) {
ed_task.text.set(19-i, ed_task.text.get(18-i));
}
ed_task.text.set(pos, new LinkedList<String>());
}
else {
latency = val2.length() * STD_MOTOR_TIME;
}
if (!action.equals("period-a") && !action.equals("i")) {
List<String> text = ed_task.text.get(ed_task.line_pos);
temp = new LinkedList<String>(text.subList(0, ed_task.cursor_pos));
temp.addAll(Arrays.asList(val2.split("\\s")));
temp.addAll(text.subList(ed_task.cursor_pos, text.size()));
ed_task.text.set(ed_task.line_pos, temp);
if (action.equals("type-text-enter")) {
ed_task.cursor_pos = 0;
latency = (1 + val2.length()) * STD_MOTOR_TIME;
}
}
else {
latency = STD_VISUAL_TIME + ((action.equals("period-a") ? 3.0 : 2.0) * STD_MOTOR_TIME);
}
determine_v();
break;
case "substitute-ed": case "substitute-edt":
ed_task.text.set(ed_task.line_pos, substitute_insert(val2, val3, ed_task.text.get(ed_task.line_pos)));
latency = (val2.length() + val3.length() + (action.equals("substitute-ed") ? 5.0 : 4.0)) * STD_MOTOR_TIME;
ed_task.cursor_pos = 0;
determine_v();
break;
case "insert-ed": case "insert-edt":
sTemp = val3 + " " + val2;
ed_task.text.set(ed_task.line_pos, substitute_insert(val2, sTemp, ed_task.text.get(ed_task.line_pos)));
latency = (2.0*val2.length() + val3.length() + 1.0 + (action.equals("insert-ed") ? 5.0 : 4.0)) * STD_MOTOR_TIME;
ed_task.cursor_pos = 0;
determine_v();
break;
case "period-d": case "d": case "control-k-twice": case "control-k":
boolean wasEmpty = ed_task.text.get(ed_task.line_pos).size() == 0;
if (!action.equals("control-k") || wasEmpty) {
iTemp = ed_task.line_pos;
for (int i=0; i<19-iTemp; ++i) {
ed_task.text.set(i+iTemp, ed_task.text.get(i+iTemp+1));
}
ed_task.cursor_pos = 0;
}
if (action.equals("control-k") && wasEmpty) {
ed_task.text.set(ed_task.line_pos, new LinkedList<String>());
}
latency = action.equals("control-k") ? STD_MOTOR_TIME :
(action.equals("control-k-twice") ? (2.0 * STD_MOTOR_TIME) : (STD_VISUAL_TIME + (action.equals("period-d") ? 3.0 : 2.0) * STD_MOTOR_TIME));
determine_v();
break;
case "period-c": case "r":
ed_task.text.set(ed_task.line_pos, new LinkedList<String>());
latency = STD_VISUAL_TIME + ((action.equals("period-c") ? 3.0 : 2.0) * STD_MOTOR_TIME);
determine_v();
break;
case "period": case "control-z":
latency = STD_VISUAL_TIME + ((action.equals("period") ? 2.0 : 1.0) * STD_MOTOR_TIME);
break;
case "number-p":
ed_task.line_pos = Arrays.asList(numbers).indexOf(val2);
ed_task.cursor_pos = 0;
determine_v();
latency = STD_VISUAL_TIME + (2.0 * STD_MOTOR_TIME);
break;
case "t-word":
iTemp = ed_task.line_pos;
while (ed_task.text.get(iTemp).indexOf(val2) < 0) {
iTemp++;
}
ed_task.line_pos = iTemp;
ed_task.cursor_pos = 0;
latency = (5.0 + val2.length()) * STD_MOTOR_TIME;
determine_v();
break;
}
rep.addLatency(latency); // When a report ends from next-instruction, does not include the latency for next-instruction
for (int i=0; i<ed_task.vlist.length; ++i) {
try {
this.setInput(i,ed_task.vlist[i]);
} catch (Exception e) {
System.err.println("Wrong index....");
}
}
}
@Override
protected void user_createAgent() {
// Called from initAgent() and runDebug(), when the agent is created
ed_task = new ETask();//(1,1,current_sample);
rep = new Report();
this.clearReports();
}
@Override
protected void user_doExperiment() {
List<SaCondition> sa_conditions = new ArrayList<SaCondition>();
sa_conditions.add(new SaCondition("ED-ED-EMACS", new String[]{"ed", "ed", "emacs"}, new int[]{115, 54, 44, 42, 43, 28}));
sa_conditions.add(new SaCondition("EDT-EDT-EMACS", new String[]{"edt", "edt", "emacs"}, new int[]{115, 54, 55, 49, 43, 28}));
sa_conditions.add(new SaCondition("ED-EDT-EMACS", new String[]{"ed", "edt", "emacs"}, new int[]{115, 54, 63, 44, 41, 26}));
sa_conditions.add(new SaCondition("EDT-ED-EMACS", new String[]{"edt", "ed", "emacs"}, new int[]{115, 54, 46, 37, 41, 26}));
sa_conditions.add(new SaCondition("EMACS-EMACS-EMACS", new String[]{"emacs", "emacs", "emacs"}, new int[]{77, 37, 29, 23, 23, 21}));
for (SaCondition sac : sa_conditions) {
if (!this.initAgent())
break;
int task_count = 0;
rep.taskSetName = sac.name;
for (int i=0; i<1 && !this.hasError(); ++i) { // Each subject comes in for 6 'days'
int j = (int)(1800.0 / (double)sac.trials[i] + 0.5); // How many trials can fit into the 'day'
String condition = sac.conditions[i/2];
for (int k=0; k<j && !this.hasError(); ++k) {
task_name = condition;
this.setTask(task_name, task_name + "_" + Integer.toString(task_count + 1));
// Init report
rep.init();
rep.taskName = task_name;
rep.trialNum = i+1;
rep.editNum = k+1;
this.runAgent(); // Run until receiving the finish command
task_count = (task_count + 1) % 3;
if (!this.hasError()) { // abort potentially gets set in the updateEventHandler method
this.printReports();
System.out.println("Done: " + sac.name + ", " + condition + " " + Integer.toString(i+1) + "," + Integer.toString(k+1));
}
else {
System.out.println("ERROR RETURNED BY AGENT FOR " + condition + " " + Integer.toString(i+1) + "," + Integer.toString(k+1) + "!");
break;
}
}
}
if (this.hasError())
break;
}
//agent.ExecuteCommandLine("clog -c");
//this.agentError = false;
}
@Override
protected void user_errorListener(String arg0) {
System.err.println("ERROR DETECTED!");
}
@Override
protected void user_agentStart() {
// Init
//ed_task.init();
//int taskInd = getEditTaskIndex(this.taskSequenceName);
//if (taskInd != -1)
// ed_task.edits = new ArrayList<String[]>(edit_tasks.get(taskInd));
this.clearReports();
rep.init();
determine_v();
}
@Override
protected void user_agentStop() {
// Increment the task
if (inDebug) {
int currTaskInd = getEditTaskIndex(this.getTaskInstance());
currTaskInd = (currTaskInd + 1) % 3;
this.setTask(this.getTask(), this.getTask() + "_" + Integer.toString(currTaskInd + 1));
}
else {
user_updateTask();
}
}
@Override
protected void user_updateTask() {
ed_task.init(); // Resets the text to be edited
ed_task.edits = new ArrayList<String[]>(edit_tasks.get(getEditTaskIndex(this.getTaskInstance())));
}
}
| AaronCWacker/PROPs | domains/editors/workspace/EditorsEnvironment/src/edu/umich/eecs/soar/props/editors/EditorsWorld.java | 5,764 | // Error, shouldn't happen
| line_comment | nl | package edu.umich.eecs.soar.props.editors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import edu.umich.eecs.soar.propsutil.LearnConfig;
import edu.umich.eecs.soar.propsutil.PROPsEnvironment;
public class EditorsWorld extends PROPsEnvironment {
private static double STD_MOTOR_TIME = 0.25,
STD_VISUAL_TIME = 0.25;
private ETask ed_task;
private Report rep;
//private int task_count; // The index of edit_tasks to use next
private String task_name;
private List<ArrayList<String[]>> edit_tasks;
private String[] numbers;
public boolean inDebug = false;
EditorsWorld() {
String proj_dir = "/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/domains/editors/";
String props_dir = "/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/PROPsAgent/";
this.setAgentName("EditorsAgent");
this.setPropsDir(props_dir);
this.setCondChunkFile(proj_dir + "editors_agent_condspread_chunks.soar");
this.setAddressChunkFile(proj_dir + "editors_agent_L1_chunks.soar");
this.setFetchSeqFile(proj_dir + "editors_agent_fetch_procedures.soar");
this.setInstructionsFile(proj_dir + "editors_agent_instructions.soar");
this.setSoarAgentFile(proj_dir + "editors_agent.soar");
this.setIOSize(4, 3);
this.setUserAgentFiles(Arrays.asList("/home/bryan/Documents/GitHub_Bryan-Stearns/PROPs/domains/lib_actransfer_interface.soar",
proj_dir + "editors_agent_smem.soar"));
this.edit_tasks = new LinkedList<ArrayList<String[]>>();
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(0).add(new String[]{"replace-word", "vader", "moeder", "one"});
edit_tasks.get(0).add(new String[]{"insert-word", "inhoud", "nieuwe", "three"});
edit_tasks.get(0).add(new String[]{"delete-word", "slome", "", "five"});
edit_tasks.get(0).add(new String[]{"replace-line", "ebooks en sociale medi", "electronisch boeken en andere vormen van sociale media", "eight"});
edit_tasks.get(0).add(new String[]{"delete-line", "of the rings trilogie", "", "fifteen"});
edit_tasks.get(0).add(new String[]{"insert-line", "Oscar of niet Rowling zal er niet om rouwen want de buit is al binnen", "net zo groot als tien jaar geleden", "eighteen"});
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(1).add(new String[]{"insert-word", "pers", "muskieten", "two"});
edit_tasks.get(1).add(new String[]{"replace-line", "fans mochten een blik op de inhoud werpen onder voorwaarde van strikte geheimhouding", "fans hadden de gelegenheid om alvast een kijkje te nemen", "three"});
edit_tasks.get(1).add(new String[]{"replace-word", "medi", "media", "eight"});
edit_tasks.get(1).add(new String[]{"delete-word", "eindelijk", "", "fourteen"});
edit_tasks.get(1).add(new String[]{"delete-line", "We all know what happened in the end but", "", "sixteen"});
edit_tasks.get(1).add(new String[]{"insert-line", "kassucces De spanning is daarom groot dit jaar", "succes Het zal Roling waarschijnlijk een worst wezen", "seventeen"});
this.edit_tasks.add(new ArrayList<String[]>(6));
edit_tasks.get(2).add(new String[]{"replace-line", "Geestelijk vader van de tovenaarsleerling JK Rowling lanceert morgen de site pottermorecom", "Wederom is het tijd voor een nieuwe website over harry potter maar deze keer van Rowling zelf", "one"});
edit_tasks.get(2).add(new String[]{"insert-word", "paar", "klein", "two"});
edit_tasks.get(2).add(new String[]{"delete-word", "nieuwe", "", "five"});
edit_tasks.get(2).add(new String[]{"delete-line", "Op dit moment staat de laatste film in de serie op het punt om in de bioscoop", "", "twelve"});
edit_tasks.get(2).add(new String[]{"replace-word", "Oscar", "prijs", "thirteen"});
edit_tasks.get(2).add(new String[]{"insert-line", "kassucces De spanning is daarom groot dit jaar", "And here we have another meaningless line that makes this text een more unreadable", "seventeen"});
numbers = new String[]{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"};
}
public void runEditorsDebug(String task, int taskNum, LearnConfig config) {
String taskSeq = task + "_" + (taskNum+1);
task_name = task;
//task_count = taskNum;
inDebug = true;
this.runDebug(task, taskSeq, config);
inDebug = false;
}
private int getEditTaskIndex(String taskSeq) {
if (taskSeq.contains("_1")) {
return 0;
}
else if (taskSeq.contains("_2")) {
return 1;
}
else if (taskSeq.contains("_3")) {
return 2;
}
else return -1; // Error<SUF>
}
// Helper functions specifically for the Editors environment
private void determine_v() {
List<String> L = ed_task.text.get(ed_task.line_pos);
String line = numbers[ed_task.line_pos];
String word;
if (L.size() <= ed_task.cursor_pos)
word = "eol";
else
word = ed_task.text.get(ed_task.line_pos).get(ed_task.cursor_pos);
ed_task.set_vlist("word", word, "nil", line);
}
private List<String> substitute_insert(String old_element, String new_element, List<String> l) {
if (l == null || l.size() == 0)
return l;
return new LinkedList<String>(Arrays.asList(String.join(" ", l).replaceFirst(old_element, new_element).split("\\s+")));
}
@Override
protected void user_outputListener(List<String> outputs) {
// Get the output
String action = outputs.get(0);
String val2 = outputs.get(1);
String val3 = outputs.get(2);
double latency = 0.05;
// Generate the corresponding input
int iTemp;
String sTemp;
List<String> temp;
switch (rep.state) {
case "ll-noread":
if (action.equals("read-instruction")) {
rep.state = "ll";
rep.task = ed_task.edits.get(0)[0];
}
else {
System.out.println("Something went wrong...");
}
break;
case "ll":
if (action.equals("number-p") || action.equals("enter") || action.equals("t-word")) {
rep.ll = System.nanoTime() - rep.strt;
rep.state = "ll-motor";
}
if (action.equals("read-instruction") && ed_task.edits.get(0)[3].equals(numbers[ed_task.line_pos])) {
if (rep.state.equals("ll")) {
rep.ll = System.nanoTime()-rep.strt;
rep.state = "mt";
rep.temp = System.nanoTime();
}
}
break;
case "ll-motor":
if (action.equals("read-instruction")) {
rep.state = "mt";
rep.temp = System.nanoTime();
}
break;
case "mt":
temp = new ArrayList<String>(Arrays.asList("substitute-ed", "substitute-edt", "insert-ed", "insert-edt",
"period-d", "type-text", "type-text-enter", "d", "control-k", "control-k-twice", "esc-d"));
if (temp.contains(action)) {
rep.state = "mt-motor";
rep.mt = System.nanoTime() - rep.temp;
}
break;
case "mt-motor":
if (action.equals("next-instruction")) {
rep.state = "ll";
//rep.addLatency(STD_VISUAL_TIME); // Could move latency for 'next-instruction' here so it ends up in the report, but Taatgen doesn't?
this.addReport(rep.toString());
if (ed_task.edits.size() <= 1)
rep.task = "nil";
else
rep.task = ed_task.edits.get(1)[0];
rep.strt = System.nanoTime();
rep.latencies = 0.0;
}
break;
case "end":
break; // Do nothing (not in original lisp code - never gets called anyway)
}
switch (action) {
case "enter": case "control-n":
ed_task.line_pos++;
ed_task.cursor_pos = 0;
latency = (action.equals("enter")) ? (STD_MOTOR_TIME + STD_VISUAL_TIME) : STD_MOTOR_TIME;
determine_v();
break;
case "esc-f": case "move-attention-right":
latency = (action.equals("esc-f")) ? (2.0 * STD_MOTOR_TIME) : STD_VISUAL_TIME;
ed_task.cursor_pos++;
determine_v();
break;
case "read-screen":
determine_v();
latency = STD_VISUAL_TIME;
break;
case "read-instruction":
ed_task.set_vlist(ed_task.edits.get(0));
latency = STD_VISUAL_TIME;
break;
case "next-instruction":
if (ed_task.edits.size() == 0)
break; // end
ed_task.edits.remove(0);
if (ed_task.edits.size() > 0) {
ed_task.set_vlist(ed_task.edits.get(0));
}
else {
ed_task.set_vlist("end", "end2", "end3", "end4");
rep.state = "end";
}
latency = STD_VISUAL_TIME;
break;
case "focus-on-word": case "focus-on-next-word":
if (action.equals("focus-on-word")) {
ed_task.line = new LinkedList<String>(Arrays.asList(ed_task.edits.get(0)[1].split("\\s")));
}
sTemp = "short";
if (ed_task.line.size() == 1 || ed_task.line.get(0).length() > 4) // If the word in the line is longer than 4 characters
sTemp = "long";
ed_task.set_vlist("single-word", ed_task.line.get(0), sTemp, "");
ed_task.line.remove(0);
latency = STD_VISUAL_TIME;
break;
case "esc-d": // Delete an element in the line
ed_task.text.get(ed_task.line_pos).remove(ed_task.cursor_pos);
latency = STD_MOTOR_TIME;
determine_v();
break;
case "type-text": case "type-text-enter": case "period-a": case "i": // Insert text into the line
if (!action.equals("type-text")) {
int pos = ed_task.line_pos;
for (int i=0; i<19-pos; ++i) {
ed_task.text.set(19-i, ed_task.text.get(18-i));
}
ed_task.text.set(pos, new LinkedList<String>());
}
else {
latency = val2.length() * STD_MOTOR_TIME;
}
if (!action.equals("period-a") && !action.equals("i")) {
List<String> text = ed_task.text.get(ed_task.line_pos);
temp = new LinkedList<String>(text.subList(0, ed_task.cursor_pos));
temp.addAll(Arrays.asList(val2.split("\\s")));
temp.addAll(text.subList(ed_task.cursor_pos, text.size()));
ed_task.text.set(ed_task.line_pos, temp);
if (action.equals("type-text-enter")) {
ed_task.cursor_pos = 0;
latency = (1 + val2.length()) * STD_MOTOR_TIME;
}
}
else {
latency = STD_VISUAL_TIME + ((action.equals("period-a") ? 3.0 : 2.0) * STD_MOTOR_TIME);
}
determine_v();
break;
case "substitute-ed": case "substitute-edt":
ed_task.text.set(ed_task.line_pos, substitute_insert(val2, val3, ed_task.text.get(ed_task.line_pos)));
latency = (val2.length() + val3.length() + (action.equals("substitute-ed") ? 5.0 : 4.0)) * STD_MOTOR_TIME;
ed_task.cursor_pos = 0;
determine_v();
break;
case "insert-ed": case "insert-edt":
sTemp = val3 + " " + val2;
ed_task.text.set(ed_task.line_pos, substitute_insert(val2, sTemp, ed_task.text.get(ed_task.line_pos)));
latency = (2.0*val2.length() + val3.length() + 1.0 + (action.equals("insert-ed") ? 5.0 : 4.0)) * STD_MOTOR_TIME;
ed_task.cursor_pos = 0;
determine_v();
break;
case "period-d": case "d": case "control-k-twice": case "control-k":
boolean wasEmpty = ed_task.text.get(ed_task.line_pos).size() == 0;
if (!action.equals("control-k") || wasEmpty) {
iTemp = ed_task.line_pos;
for (int i=0; i<19-iTemp; ++i) {
ed_task.text.set(i+iTemp, ed_task.text.get(i+iTemp+1));
}
ed_task.cursor_pos = 0;
}
if (action.equals("control-k") && wasEmpty) {
ed_task.text.set(ed_task.line_pos, new LinkedList<String>());
}
latency = action.equals("control-k") ? STD_MOTOR_TIME :
(action.equals("control-k-twice") ? (2.0 * STD_MOTOR_TIME) : (STD_VISUAL_TIME + (action.equals("period-d") ? 3.0 : 2.0) * STD_MOTOR_TIME));
determine_v();
break;
case "period-c": case "r":
ed_task.text.set(ed_task.line_pos, new LinkedList<String>());
latency = STD_VISUAL_TIME + ((action.equals("period-c") ? 3.0 : 2.0) * STD_MOTOR_TIME);
determine_v();
break;
case "period": case "control-z":
latency = STD_VISUAL_TIME + ((action.equals("period") ? 2.0 : 1.0) * STD_MOTOR_TIME);
break;
case "number-p":
ed_task.line_pos = Arrays.asList(numbers).indexOf(val2);
ed_task.cursor_pos = 0;
determine_v();
latency = STD_VISUAL_TIME + (2.0 * STD_MOTOR_TIME);
break;
case "t-word":
iTemp = ed_task.line_pos;
while (ed_task.text.get(iTemp).indexOf(val2) < 0) {
iTemp++;
}
ed_task.line_pos = iTemp;
ed_task.cursor_pos = 0;
latency = (5.0 + val2.length()) * STD_MOTOR_TIME;
determine_v();
break;
}
rep.addLatency(latency); // When a report ends from next-instruction, does not include the latency for next-instruction
for (int i=0; i<ed_task.vlist.length; ++i) {
try {
this.setInput(i,ed_task.vlist[i]);
} catch (Exception e) {
System.err.println("Wrong index....");
}
}
}
@Override
protected void user_createAgent() {
// Called from initAgent() and runDebug(), when the agent is created
ed_task = new ETask();//(1,1,current_sample);
rep = new Report();
this.clearReports();
}
@Override
protected void user_doExperiment() {
List<SaCondition> sa_conditions = new ArrayList<SaCondition>();
sa_conditions.add(new SaCondition("ED-ED-EMACS", new String[]{"ed", "ed", "emacs"}, new int[]{115, 54, 44, 42, 43, 28}));
sa_conditions.add(new SaCondition("EDT-EDT-EMACS", new String[]{"edt", "edt", "emacs"}, new int[]{115, 54, 55, 49, 43, 28}));
sa_conditions.add(new SaCondition("ED-EDT-EMACS", new String[]{"ed", "edt", "emacs"}, new int[]{115, 54, 63, 44, 41, 26}));
sa_conditions.add(new SaCondition("EDT-ED-EMACS", new String[]{"edt", "ed", "emacs"}, new int[]{115, 54, 46, 37, 41, 26}));
sa_conditions.add(new SaCondition("EMACS-EMACS-EMACS", new String[]{"emacs", "emacs", "emacs"}, new int[]{77, 37, 29, 23, 23, 21}));
for (SaCondition sac : sa_conditions) {
if (!this.initAgent())
break;
int task_count = 0;
rep.taskSetName = sac.name;
for (int i=0; i<1 && !this.hasError(); ++i) { // Each subject comes in for 6 'days'
int j = (int)(1800.0 / (double)sac.trials[i] + 0.5); // How many trials can fit into the 'day'
String condition = sac.conditions[i/2];
for (int k=0; k<j && !this.hasError(); ++k) {
task_name = condition;
this.setTask(task_name, task_name + "_" + Integer.toString(task_count + 1));
// Init report
rep.init();
rep.taskName = task_name;
rep.trialNum = i+1;
rep.editNum = k+1;
this.runAgent(); // Run until receiving the finish command
task_count = (task_count + 1) % 3;
if (!this.hasError()) { // abort potentially gets set in the updateEventHandler method
this.printReports();
System.out.println("Done: " + sac.name + ", " + condition + " " + Integer.toString(i+1) + "," + Integer.toString(k+1));
}
else {
System.out.println("ERROR RETURNED BY AGENT FOR " + condition + " " + Integer.toString(i+1) + "," + Integer.toString(k+1) + "!");
break;
}
}
}
if (this.hasError())
break;
}
//agent.ExecuteCommandLine("clog -c");
//this.agentError = false;
}
@Override
protected void user_errorListener(String arg0) {
System.err.println("ERROR DETECTED!");
}
@Override
protected void user_agentStart() {
// Init
//ed_task.init();
//int taskInd = getEditTaskIndex(this.taskSequenceName);
//if (taskInd != -1)
// ed_task.edits = new ArrayList<String[]>(edit_tasks.get(taskInd));
this.clearReports();
rep.init();
determine_v();
}
@Override
protected void user_agentStop() {
// Increment the task
if (inDebug) {
int currTaskInd = getEditTaskIndex(this.getTaskInstance());
currTaskInd = (currTaskInd + 1) % 3;
this.setTask(this.getTask(), this.getTask() + "_" + Integer.toString(currTaskInd + 1));
}
else {
user_updateTask();
}
}
@Override
protected void user_updateTask() {
ed_task.init(); // Resets the text to be edited
ed_task.edits = new ArrayList<String[]>(edit_tasks.get(getEditTaskIndex(this.getTaskInstance())));
}
}
|
18953_7 | package models;
/**
* Deze klasse maakt een competitie aan
*
* @author Abdul Vahip Zor
*/
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
public class Competitie implements Serializable {
private String naam;
private ArrayList<Wedstrijd> wedstrijden;
private ArrayList<Team> teams;
/**
* @param naam de naam van de competitie
*/
public Competitie(String naam) {
this.naam = naam;
wedstrijden = new ArrayList<>();
teams = new ArrayList<>();
}
/**
* @return de naam van de competitie
*/
public String getNaam() {
return naam;
}
/**
* @param naam de nieuwe naam van de competitie
*/
public void setNaam(String naam) {
this.naam = naam;
}
// Wedstrijden
/**
* haal een wedstrijd op en voeg die in de wedstrijden
*
* @param wedstrijd een wedstrijd
*/
public void setWedstrijd(Wedstrijd wedstrijd) {
wedstrijden.add(wedstrijd);
}
/**
* @return de ArrayList waar de wedstrijden in zitten
*/
public ArrayList<Wedstrijd> getWedstrijden() {
return wedstrijden;
}
/**
* @param index de index van welke wedstrijd gevraagd wordt uit de ArrayList
* @return de wedstrijd
*/
public Wedstrijd getWedstrijd(int index) {
return wedstrijden.get(index);
}
// Teams
/**
* haal een team op en voeg die in de teams
*
* @param team het team object dat toegevoegd moet worden
*/
public void setTeam(Team team) {
teams.add(team);
}
/**
* @return de teams in de competitie
*/
public ArrayList<Team> getTeams() {
return teams;
}
/**
* @param index de index van welke team gevraagd wordt uit de ArrayList
* @return het team object
*/
public Team getTeam(int index) {
return teams.get(index);
}
/**
* @return alle wedstrijden met hun info
*/
@Override
public String toString() {
return naam;
}
/**
* @return alle gespeelde wedstrijden in de competitie
*/
public String toonWedstrijden() {
StringBuilder competitieInfo = new StringBuilder(naam + ":\n");
for (int i = 0; i < wedstrijden.size(); i++) {
Collections.sort(wedstrijden);
competitieInfo.append(wedstrijden.get(i) + "\n");
}
return competitieInfo + "\n";
}
/**
* Toon de competitiestand van de competitie
*/
public void toonCompetitiestand() {
StringBuilder competitieStand = new StringBuilder();
Collections.sort(teams);
for (int i = 0; i < teams.size(); i++) {
competitieStand.append(String.format("%-9s %s", i + 1, teams.get(i)) + "\n");
}
System.out.printf("%-10s%-10s %s\n", "Plaats", "Team", "Punten");
System.out.println(competitieStand);
}
}
| AbdulZor/Competition-Management | src/models/Competitie.java | 824 | /**
* @param index de index van welke wedstrijd gevraagd wordt uit de ArrayList
* @return de wedstrijd
*/ | block_comment | nl | package models;
/**
* Deze klasse maakt een competitie aan
*
* @author Abdul Vahip Zor
*/
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
public class Competitie implements Serializable {
private String naam;
private ArrayList<Wedstrijd> wedstrijden;
private ArrayList<Team> teams;
/**
* @param naam de naam van de competitie
*/
public Competitie(String naam) {
this.naam = naam;
wedstrijden = new ArrayList<>();
teams = new ArrayList<>();
}
/**
* @return de naam van de competitie
*/
public String getNaam() {
return naam;
}
/**
* @param naam de nieuwe naam van de competitie
*/
public void setNaam(String naam) {
this.naam = naam;
}
// Wedstrijden
/**
* haal een wedstrijd op en voeg die in de wedstrijden
*
* @param wedstrijd een wedstrijd
*/
public void setWedstrijd(Wedstrijd wedstrijd) {
wedstrijden.add(wedstrijd);
}
/**
* @return de ArrayList waar de wedstrijden in zitten
*/
public ArrayList<Wedstrijd> getWedstrijden() {
return wedstrijden;
}
/**
* @param<SUF>*/
public Wedstrijd getWedstrijd(int index) {
return wedstrijden.get(index);
}
// Teams
/**
* haal een team op en voeg die in de teams
*
* @param team het team object dat toegevoegd moet worden
*/
public void setTeam(Team team) {
teams.add(team);
}
/**
* @return de teams in de competitie
*/
public ArrayList<Team> getTeams() {
return teams;
}
/**
* @param index de index van welke team gevraagd wordt uit de ArrayList
* @return het team object
*/
public Team getTeam(int index) {
return teams.get(index);
}
/**
* @return alle wedstrijden met hun info
*/
@Override
public String toString() {
return naam;
}
/**
* @return alle gespeelde wedstrijden in de competitie
*/
public String toonWedstrijden() {
StringBuilder competitieInfo = new StringBuilder(naam + ":\n");
for (int i = 0; i < wedstrijden.size(); i++) {
Collections.sort(wedstrijden);
competitieInfo.append(wedstrijden.get(i) + "\n");
}
return competitieInfo + "\n";
}
/**
* Toon de competitiestand van de competitie
*/
public void toonCompetitiestand() {
StringBuilder competitieStand = new StringBuilder();
Collections.sort(teams);
for (int i = 0; i < teams.size(); i++) {
competitieStand.append(String.format("%-9s %s", i + 1, teams.get(i)) + "\n");
}
System.out.printf("%-10s%-10s %s\n", "Plaats", "Team", "Punten");
System.out.println(competitieStand);
}
}
|
2268_91 | /**
* %SVN.HEADER%
*/
package net.sf.javaml.clustering;
import java.util.Vector;
import net.sf.javaml.core.Dataset;
import net.sf.javaml.core.DefaultDataset;
import net.sf.javaml.core.DenseInstance;
import net.sf.javaml.core.Instance;
import net.sf.javaml.distance.DistanceMeasure;
import net.sf.javaml.distance.EuclideanDistance;
import net.sf.javaml.utils.GammaFunction;
import net.sf.javaml.utils.MathUtils;
import org.apache.commons.math.stat.descriptive.moment.Mean;
import org.apache.commons.math.stat.descriptive.moment.StandardDeviation;
/**
*
* This class implements the Adaptive Quality-based Clustering Algorithm, based
* on the implementation in MATLAB by De Smet et al., ESAT - SCD (SISTA),
* K.U.Leuven, Belgium.
*
* @author Thomas Abeel
*/
public class AQBC implements Clusterer {
private double RADNW;
private int E;
class TaggedInstance {
Instance inst;
private static final long serialVersionUID = 8990262697388049283L;
private int tag;
TaggedInstance(Instance i, int tag) {
this.inst = i;
this.tag = tag;
}
public int getTag() {
return tag;
}
}
private Dataset data;
private boolean normalize;
/**
* XXX write doc
*
* FIXME remove output on the console
*/
public Dataset[] cluster(Dataset data) {
this.data = data;
// dm=new NormalizedEuclideanDistance(data);
dm = new EuclideanDistance();
// Filter filter=new NormalizeMean();
// data=filter.filterDataset(data);
Vector<TaggedInstance> SP;
if (normalize)
SP = normalize(data);
else
SP = dontnormalize(data);
System.out.println("Remaining datapoints = " + SP.size());
// Vector<Instance> SP = new Vector<Instance>();
// for (int i = 0; i < norm.size(); i++) {
// SP.add(data.getInstance(i));
// }
int NRNOCONV = 0;
int maxNRNOCONV = 2;
int TOOFEWPOINTS = 0;
int TFPTH = 10;
int BPR = 0;
int RRES = 0;
int BPRTH = 10;
double REITERTHR = 0.1;
E = data.noAttributes();
if (E > 170)
throw new RuntimeException("AQBC is unable to work for more than 170 dimensions! This is a limitation of the Gamma function");
// int D = E - 2;
double R = Math.sqrt(E - 1);
double EXTTRESH = R / 2.0f;
int MINNRGENES = 2;
int cluster = 0;
while (NRNOCONV < maxNRNOCONV && TOOFEWPOINTS < TFPTH && BPR < BPRTH && RRES < 2) {
// determine cluster center
boolean clusterLocalisationConverged = wan_shr_adap(SP, EXTTRESH);
if (clusterLocalisationConverged) {
System.out.println("Found cluster -> EM");
// System.out.println("EXTTRESH2 = "+EXTTRESH2);
// optimize cluster quality
System.out.println("Starting EM");
boolean emConverged = exp_max(SP, ME, EXTTRESH2, S);
if (emConverged) {
System.out.println("EM converged, predicting radius...");
// System.exit(-1);
NRNOCONV = 0;
if (Math.abs(RADNW - EXTTRESH) / EXTTRESH < REITERTHR) {
Vector<TaggedInstance> Q = retrieveInstances(SP, ME, RADNW);
if (Q.size() == 0) {
System.err.println("Significance level not reached");
}
if (Q.size() > MINNRGENES) {
cluster++;
outputCluster(Q, cluster);
removeInstances(SP, Q);
TOOFEWPOINTS = 0;
EXTTRESH = RADNW;
} else {
removeInstances(SP, Q);
TOOFEWPOINTS++;
}
} else {
EXTTRESH = RADNW;
BPR++;
if (BPR == BPRTH) {
System.out.println("Radius cannot be predicted!");
} else {
System.out.println("Trying new radius...");
}
}
} else {
NRNOCONV++;
if (NRNOCONV < maxNRNOCONV) {
EXTTRESH = R / 2;
RRES++;
System.out.println("Resetting radius to: " + EXTTRESH);
if (RRES == 2) {
System.out.println("No convergence: Algorithm aborted - RRES exceeded!");
break;
} else {
BPR = 0;
}
} else {
System.out.println("No convergence: Algorithm aborted - NRNOCONV exceeded!");
break;
}
}
if (TOOFEWPOINTS == TFPTH) {
System.out.println("No more significant clusters found: Algorithms aborted!");
break;
}
}
}
Dataset[] output = new Dataset[clusters.size()];
for (int i = 0; i < clusters.size(); i++) {
output[i] = clusters.get(i);
}
return output;
}
/**
* Normalizes the data to mean 0 and standard deviation 1. This method
* discards all instances that cannot be normalized, i.e. they have the same
* value for all attributes.
*
* @param data
* @return
*/
private Vector<TaggedInstance> dontnormalize(Dataset data) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (int i = 0; i < data.size(); i++) {
// Double[] old = data.instance(i).values().toArray(new Double[0]);
// double[] conv = new double[old.length];
// for (int j = 0; j < old.length; j++) {
// conv[j] = old[j];
// }
//
// Mean m = new Mean();
//
// double MU = m.evaluate(conv);
// // System.out.println("MU = "+MU);
// StandardDeviation std = new StandardDeviation();
// double SIGM = std.evaluate(conv, MU);
// System.out.println("SIGM = "+SIGM);
// if (!MathUtils.eq(SIGM, 0)) {
// double[] val = new double[old.length];
// for (int j = 0; j < old.length; j++) {
// val[j] = (float) ((old[j] - MU) / SIGM);
//
// }
// System.out.println("VAL "+i+" = "+Arrays.toString(val));
out.add(new TaggedInstance(data.instance(i), i));
// }
}
// System.out.println("FIRST = "+out.get(0));
return out;
}
/**
* Normalizes the data to mean 0 and standard deviation 1. This method
* discards all instances that cannot be normalized, i.e. they have the same
* value for all attributes.
*
* @param data
* @return
*/
private Vector<TaggedInstance> normalize(Dataset data) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (int i = 0; i < data.size(); i++) {
Double[] old = data.instance(i).values().toArray(new Double[0]);
double[] conv = new double[old.length];
for (int j = 0; j < old.length; j++) {
conv[j] = old[j];
}
Mean m = new Mean();
double MU = m.evaluate(conv);
// System.out.println("MU = "+MU);
StandardDeviation std = new StandardDeviation();
double SIGM = std.evaluate(conv, MU);
// System.out.println("SIGM = "+SIGM);
if (!MathUtils.eq(SIGM, 0)) {
double[] val = new double[old.length];
for (int j = 0; j < old.length; j++) {
val[j] = (float) ((old[j] - MU) / SIGM);
}
// System.out.println("VAL "+i+" = "+Arrays.toString(val));
out.add(new TaggedInstance(new DenseInstance(val, data.instance(i).classValue()), i));
}
}
// System.out.println("FIRST = "+out.get(0));
return out;
}
/**
* Remove the instances in q from sp
*
* @param sp
* @param q
*/
private void removeInstances(Vector<TaggedInstance> sp, Vector<TaggedInstance> q) {
sp.removeAll(q);
}
/**
* XXX write doc
*
* @param significance
*/
public AQBC(double significance) {
this(significance, true);
}
/**
* XXX write doc
*
* default constructor
*/
public AQBC() {
this(0.95);
}
public AQBC(double sig, boolean normalize) {
this.normalize = normalize;
this.S = sig;
}
private Vector<Dataset> clusters = new Vector<Dataset>();
/**
* output all the instances in q as a single cluster with the given index
*
* The index is ignored.
*
* @param q
* @param cluster
*/
private void outputCluster(Vector<TaggedInstance> q, int index) {
Dataset tmp = new DefaultDataset();
for (TaggedInstance i : q) {
tmp.add(data.instance(i.getTag()));
}
clusters.add(tmp);
}
private DistanceMeasure dm;
private Vector<TaggedInstance> retrieveInstances(Vector<TaggedInstance> sp, double[] me2, double radnw2) {
Instance tmp = new DenseInstance(me2);
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (TaggedInstance inst : sp) {
if (dm.measure(inst.inst, tmp) < radnw2)
out.add(inst);
}
return out;
}
// modifies: RADNW
private boolean exp_max(Vector<TaggedInstance> AS, double[] CK, double QUAL, double S) {
double D = E - 2;
double R = Math.sqrt(E - 1);
// System.out.println("CK= "+Arrays.toString(CK));
double[] RD = calculateDistances(AS, CK);
// System.out.println("RD = "+Arrays.toString(RD));
int samples = RD.length;
int MAXITER = 500;
double CDIF = 0.001;
double count = 0;// float sum = 0;
for (int i = 0; i < RD.length; i++) {
if (RD[i] < QUAL) {
count++;
// sum += RD[i];
}
}
// System.out.println("count = "+count);
// System.out.println("RD.length = "+RD.length);
double PC = count / RD.length;// sum / RD.length;
double PB = 1 - PC;
// System.out.println("PC = "+PC);
// System.out.println("PB = "+PB);
double tmpVAR = 0;
// double sum=0;
for (int i = 0; i < RD.length; i++) {
if (RD[i] < QUAL) {
// sum += RD[i];
tmpVAR += RD[i] * RD[i];
}
}
// System.out.println("sum = "+sum);
// System.out.println("tmpVAR = "+tmpVAR);
double VAR = (1 / D) * tmpVAR / count;
boolean CONV = false;
for (int i = 0; i < MAXITER && !CONV; i++) {
// System.out.println("\tEM iteration: "+i);
// System.out.println("\tVAR = "+VAR);
double[] prc = clusterdistrib(RD, VAR, D, R);
// System.out.println("PRC = "+Arrays.toString(prc));
double[] prb = background(RD, D, R);
double[] prcpc = new double[prc.length];
for (int j = 0; j < prc.length; j++) {
prcpc[j] = prc[j] * PC;
}
double[] prbpb = new double[prb.length];
for (int j = 0; j < prb.length; j++) {
prbpb[j] = prb[j] * PB;
}
double[] pr = new double[prcpc.length];
for (int j = 0; j < prc.length; j++) {
pr[j] = prcpc[j] + prbpb[j];
}
double[] pcr = new double[prcpc.length];
for (int j = 0; j < prc.length; j++) {
pcr[j] = prcpc[j] / pr[j];
}
double SM = 0;
for (int j = 0; j < prc.length; j++) {
SM += pcr[j];
}
// System.out.println("\tSM = "+SM);
if (MathUtils.eq(SM, 0) || Double.isInfinite(SM)) {
i = MAXITER;// will return from loop
}
float tmpVAR_new = 0;
for (int j = 0; j < prc.length; j++) {
tmpVAR_new += RD[j] * RD[j] * pcr[j];
}
// System.out.println("tmpVAR_new = "+tmpVAR_new);
double VAR_new = (1 / D) * tmpVAR_new / SM;
// System.out.println("PCR = "+Arrays.toString(pcr));
// System.out.println("\tVAR_new = "+VAR_new);
// System.out.println("\tPC = "+PC);
double PC_new = SM / samples;
// System.out.println("\tPC_new = "+PC_new);
double PB_new = 1 - PC_new;
if (Math.abs(VAR_new - VAR) < CDIF && Math.abs(PC_new - PC) < CDIF) {
CONV = true;
}
PC = PC_new;
PB = PB_new;
VAR = VAR_new;
}
if (CONV) {
if (MathUtils.eq(PC, 0) || MathUtils.eq(PB, 0)) {
System.out.println("EM: No or incorrect convergence! - PC==0 || PB==0");
CONV = false;
RADNW = 0;
return false;
}
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double SD1 = (2 * Math.pow(Math.PI, (D + 1) / 2)) / (GammaFunction.gamma((D + 1) / 2));
// System.out.println("SD = "+SD);
// System.out.println("SD1 = "+SD1);
double CC = SD * (1 / (Math.pow(2 * Math.PI * VAR, D / 2)));
double CB = (SD / (SD1 * Math.pow(Math.sqrt(D + 1), D)));
double LO = (S / (1 - S)) * ((PB * CB) / (PC * CC));
// System.out.println("PB = "+PB);
// System.out.println("PC = "+PC);
// System.out.println("S = "+S);
// System.out.println("CC = "+CC);
// System.out.println("CB = "+CB);
// System.out.println("LO = "+LO);
if (LO <= 0) {
System.out.println("EM: Impossible to calculate radius - LO<0!");
return false;
}
double DIS = -2 * VAR * Math.log(LO);
// System.out.println("DIS = "+DIS);
if (DIS <= 0) {
System.out.println("EM: Impossible to calculate radius - DIS<0!");
System.out.println();
return false;
}
RADNW = (float) Math.sqrt(DIS);
return true;
} else {
System.out.println("EM: No or incorrect convergence! Probably not enough iterations for EM");
return false;
}
}
/**
* implements background.m
*
* @param r
* @param D
* @param R
* @return
*/
private double[] background(double[] r, double D, double R) {
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double SD1 = (2 * Math.pow(Math.PI, (D + 1) / 2)) / (GammaFunction.gamma((D + 1) / 2));
double[] out = new double[r.length];
for (int i = 0; i < out.length; i++) {
out[i] = ((SD / (SD1 * (Math.pow(R, D)))) * (Math.pow(r[i], D - 1)));
}
return out;
}
/**
* implements clusterdistrib
*
* @param r
* @param VAR
* @param D
* @param R
* @return
*/
private double[] clusterdistrib(double[] r, double VAR, double D, double R) {
// System.out.println("\t\tCD:VAR = "+VAR);
// System.out.println("\t\tCD:D = "+D);
// System.out.println("\t\tCD:R = "+R);
// System.out.println("\t\tCD:r = "+Arrays.toString(r));
double[] out = new double[r.length];
if (MathUtils.eq(VAR, 0)) {
// System.out.println("\t\tCD: VAR is considered ZERO !!!");
for (int i = 0; i < r.length; i++) {
if (MathUtils.eq(r[i], 0)) {
out[i] = Float.POSITIVE_INFINITY;
}
}
} else {
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double tmp_piVAR = 2 * Math.PI * VAR;
double tmp_piVARpow = Math.pow(tmp_piVAR, D / 2);
double tmp_piVARpowINV = 1 / tmp_piVARpow;
// System.out.println("\t\tCD:SD = "+SD);
// System.out.println("\t\tCD:tmp_piVAR = "+tmp_piVAR);
// System.out.println("\t\tCD:tmp_piVARpow = "+tmp_piVARpow);
// System.out.println("\t\tCD:tmp_piVARpowINV = "+tmp_piVARpowINV);
for (int i = 0; i < r.length; i++) {
double tmp_exp = -((r[i] * r[i]) / (2 * VAR));
// System.out.println("\t\tMath.pow(r[i],D-1) =
// "+Math.pow(r[i],D-1));
// System.out.println("\t\tCD:tmp_exp = "+tmp_exp);
// System.out.println("\t\tCD:exp(tmp_exp) =
// "+Math.exp(tmp_exp));
out[i] = (float) (SD * tmp_piVARpowINV * Math.pow(r[i], D - 1) * Math.exp(tmp_exp));
}
for (int i = 0; i < r.length; i++) {
if (MathUtils.eq(r[i], 0))
out[i] = 1;
}
}
return out;
}
/**
* Comparable to dist_misval
*
* Calculates the distance between each instance and the instance given as a
* float array.
*
* @param as
* @param ck
* @return
*/
private double[] calculateDistances(Vector<TaggedInstance> as, double[] ck) {
// voor elke instance van AS, trek er CK van af
// return de sqrt van de som de kwadraten van de attributen van het
// verschil
double[] out = new double[as.size()];
for (int i = 0; i < as.size(); i++) {
Double[] values = as.get(i).inst.values().toArray(new Double[0]);
// float[]dif=new float[values.length];
float sum = 0;
for (int j = 0; j < values.length; j++) {
// dif[j]=
double dif = values[j] - ck[j];
sum += dif * dif;
}
out[i] = Math.sqrt(sum);
}
// Instance tmp=new SimpleInstance(ck);
// float[]out=new float[as.size()];
// for(int i=0;i<as.size();i++){
// out[i]=(float)dm.calculateDistance(tmp,as.get(i));
// }
return out;
}
// Significance level
private double S = 0.95f;
private double EXTTRESH2;
private double[] ME;
// modifies: CE,ME,EXTTRESH2
/**
* returns true if this step converged
*/
private boolean wan_shr_adap(Vector<TaggedInstance> A, double EXTTRESH) {
int samples = A.size();
double[] CE = new double[samples];
int MAXITER = 100;
double NRWAN = 30;
// System.out.println("FIRSTA = "+A.get(0));
double[] ME1 = mean(A);
// System.out.println("A = "+A);
// System.out.println("ME1 = " + Arrays.toString(ME1));
// System.out.println("EXTTRESH = "+EXTTRESH);
double[] DMI = calculateDistances(A, ME1);
// System.out.println("DMI = "+Arrays.toString(DMI));
double maxDMI = DMI[0];
double minDMI = DMI[0];
for (int i = 1; i < DMI.length; i++) {
if (DMI[i] > maxDMI)
maxDMI = DMI[i];
if (DMI[i] < minDMI)
minDMI = DMI[i];
}
EXTTRESH2 = maxDMI;
double MDIS = minDMI;
if (MathUtils.eq(MDIS, EXTTRESH2)) {
ME = ME1;
for (int i = 0; i < CE.length; i++)
CE[i] = 1;
EXTTRESH2 += 0.000001;
System.out.println("Cluster center localisation did not reach preliminary estimate of radius!");
return true;// TODO check if it should really be true, false is more
// logical
}
double DELTARAD = (EXTTRESH2 - EXTTRESH) / NRWAN;
double RADPR = EXTTRESH2;
EXTTRESH2 = EXTTRESH2 - DELTARAD;
if (EXTTRESH2 <= MDIS) {
EXTTRESH2 = (RADPR + MDIS) / 2;
}
Vector<Integer> Q = findLower(DMI, EXTTRESH2);
for (int i = 0; Q.size() != 0 && i < MAXITER; i++) {
double[] ME2 = mean(select(A, Q));
if (MathUtils.eq(ME1, ME2) && MathUtils.eq(RADPR, EXTTRESH2)) {
ME = ME2;
for (Integer index : Q) {
CE[index] = 1;
}
return true;
}
RADPR = EXTTRESH2;
DMI = calculateDistances(A, ME2);
if (EXTTRESH2 > EXTTRESH) {
EXTTRESH2 = Math.max(EXTTRESH, EXTTRESH2 - DELTARAD);
if (EXTTRESH2 < MathUtils.min(DMI)) {
EXTTRESH2 = RADPR;
}
}
Q = findLower(DMI, EXTTRESH2);
ME1 = ME2;
}
System.out.println("Preliminary cluster location did not converge");
// System.out.println("\t DMI = "+Arrays.toString(DMI));
System.out.println("\t EXTTRESH2 = " + EXTTRESH2);
return false;
}
/**
* return all the indices that are lower that the threshold
*
* @param array
* @param thres
* @return
*/
private Vector<Integer> findLower(double[] array, double threshold) {
Vector<Integer> out = new Vector<Integer>();
for (int i = 0; i < array.length; i++) {
if (array[i] < threshold)
out.add(i);
}
return out;
}
/**
* Return a vector with all instances that have their index in the indices
* vector.
*
* @param instances
* @param indices
* @return
*/
private Vector<TaggedInstance> select(Vector<TaggedInstance> instances, Vector<Integer> indices) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (Integer index : indices) {
out.add(instances.get(index));
}
return out;
}
private double[] mean(Vector<TaggedInstance> a) {
double[] out = new double[a.get(0).inst.noAttributes()];
for (int i = 0; i < a.size(); i++) {
// System.out.println("Instance "+i+" = "+a.get(i));
for (int j = 0; j < a.get(0).inst.noAttributes(); j++)
out[j] += a.get(i).inst.value(j);
}
// System.out.println("OUT = "+Arrays.toString(out));
for (int j = 0; j < a.get(0).inst.noAttributes(); j++) {
out[j] /= a.size();
}
return out;
}
}
| AbeelLab/javaml | src/net/sf/javaml/clustering/AQBC.java | 6,851 | // return de sqrt van de som de kwadraten van de attributen van het | line_comment | nl | /**
* %SVN.HEADER%
*/
package net.sf.javaml.clustering;
import java.util.Vector;
import net.sf.javaml.core.Dataset;
import net.sf.javaml.core.DefaultDataset;
import net.sf.javaml.core.DenseInstance;
import net.sf.javaml.core.Instance;
import net.sf.javaml.distance.DistanceMeasure;
import net.sf.javaml.distance.EuclideanDistance;
import net.sf.javaml.utils.GammaFunction;
import net.sf.javaml.utils.MathUtils;
import org.apache.commons.math.stat.descriptive.moment.Mean;
import org.apache.commons.math.stat.descriptive.moment.StandardDeviation;
/**
*
* This class implements the Adaptive Quality-based Clustering Algorithm, based
* on the implementation in MATLAB by De Smet et al., ESAT - SCD (SISTA),
* K.U.Leuven, Belgium.
*
* @author Thomas Abeel
*/
public class AQBC implements Clusterer {
private double RADNW;
private int E;
class TaggedInstance {
Instance inst;
private static final long serialVersionUID = 8990262697388049283L;
private int tag;
TaggedInstance(Instance i, int tag) {
this.inst = i;
this.tag = tag;
}
public int getTag() {
return tag;
}
}
private Dataset data;
private boolean normalize;
/**
* XXX write doc
*
* FIXME remove output on the console
*/
public Dataset[] cluster(Dataset data) {
this.data = data;
// dm=new NormalizedEuclideanDistance(data);
dm = new EuclideanDistance();
// Filter filter=new NormalizeMean();
// data=filter.filterDataset(data);
Vector<TaggedInstance> SP;
if (normalize)
SP = normalize(data);
else
SP = dontnormalize(data);
System.out.println("Remaining datapoints = " + SP.size());
// Vector<Instance> SP = new Vector<Instance>();
// for (int i = 0; i < norm.size(); i++) {
// SP.add(data.getInstance(i));
// }
int NRNOCONV = 0;
int maxNRNOCONV = 2;
int TOOFEWPOINTS = 0;
int TFPTH = 10;
int BPR = 0;
int RRES = 0;
int BPRTH = 10;
double REITERTHR = 0.1;
E = data.noAttributes();
if (E > 170)
throw new RuntimeException("AQBC is unable to work for more than 170 dimensions! This is a limitation of the Gamma function");
// int D = E - 2;
double R = Math.sqrt(E - 1);
double EXTTRESH = R / 2.0f;
int MINNRGENES = 2;
int cluster = 0;
while (NRNOCONV < maxNRNOCONV && TOOFEWPOINTS < TFPTH && BPR < BPRTH && RRES < 2) {
// determine cluster center
boolean clusterLocalisationConverged = wan_shr_adap(SP, EXTTRESH);
if (clusterLocalisationConverged) {
System.out.println("Found cluster -> EM");
// System.out.println("EXTTRESH2 = "+EXTTRESH2);
// optimize cluster quality
System.out.println("Starting EM");
boolean emConverged = exp_max(SP, ME, EXTTRESH2, S);
if (emConverged) {
System.out.println("EM converged, predicting radius...");
// System.exit(-1);
NRNOCONV = 0;
if (Math.abs(RADNW - EXTTRESH) / EXTTRESH < REITERTHR) {
Vector<TaggedInstance> Q = retrieveInstances(SP, ME, RADNW);
if (Q.size() == 0) {
System.err.println("Significance level not reached");
}
if (Q.size() > MINNRGENES) {
cluster++;
outputCluster(Q, cluster);
removeInstances(SP, Q);
TOOFEWPOINTS = 0;
EXTTRESH = RADNW;
} else {
removeInstances(SP, Q);
TOOFEWPOINTS++;
}
} else {
EXTTRESH = RADNW;
BPR++;
if (BPR == BPRTH) {
System.out.println("Radius cannot be predicted!");
} else {
System.out.println("Trying new radius...");
}
}
} else {
NRNOCONV++;
if (NRNOCONV < maxNRNOCONV) {
EXTTRESH = R / 2;
RRES++;
System.out.println("Resetting radius to: " + EXTTRESH);
if (RRES == 2) {
System.out.println("No convergence: Algorithm aborted - RRES exceeded!");
break;
} else {
BPR = 0;
}
} else {
System.out.println("No convergence: Algorithm aborted - NRNOCONV exceeded!");
break;
}
}
if (TOOFEWPOINTS == TFPTH) {
System.out.println("No more significant clusters found: Algorithms aborted!");
break;
}
}
}
Dataset[] output = new Dataset[clusters.size()];
for (int i = 0; i < clusters.size(); i++) {
output[i] = clusters.get(i);
}
return output;
}
/**
* Normalizes the data to mean 0 and standard deviation 1. This method
* discards all instances that cannot be normalized, i.e. they have the same
* value for all attributes.
*
* @param data
* @return
*/
private Vector<TaggedInstance> dontnormalize(Dataset data) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (int i = 0; i < data.size(); i++) {
// Double[] old = data.instance(i).values().toArray(new Double[0]);
// double[] conv = new double[old.length];
// for (int j = 0; j < old.length; j++) {
// conv[j] = old[j];
// }
//
// Mean m = new Mean();
//
// double MU = m.evaluate(conv);
// // System.out.println("MU = "+MU);
// StandardDeviation std = new StandardDeviation();
// double SIGM = std.evaluate(conv, MU);
// System.out.println("SIGM = "+SIGM);
// if (!MathUtils.eq(SIGM, 0)) {
// double[] val = new double[old.length];
// for (int j = 0; j < old.length; j++) {
// val[j] = (float) ((old[j] - MU) / SIGM);
//
// }
// System.out.println("VAL "+i+" = "+Arrays.toString(val));
out.add(new TaggedInstance(data.instance(i), i));
// }
}
// System.out.println("FIRST = "+out.get(0));
return out;
}
/**
* Normalizes the data to mean 0 and standard deviation 1. This method
* discards all instances that cannot be normalized, i.e. they have the same
* value for all attributes.
*
* @param data
* @return
*/
private Vector<TaggedInstance> normalize(Dataset data) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (int i = 0; i < data.size(); i++) {
Double[] old = data.instance(i).values().toArray(new Double[0]);
double[] conv = new double[old.length];
for (int j = 0; j < old.length; j++) {
conv[j] = old[j];
}
Mean m = new Mean();
double MU = m.evaluate(conv);
// System.out.println("MU = "+MU);
StandardDeviation std = new StandardDeviation();
double SIGM = std.evaluate(conv, MU);
// System.out.println("SIGM = "+SIGM);
if (!MathUtils.eq(SIGM, 0)) {
double[] val = new double[old.length];
for (int j = 0; j < old.length; j++) {
val[j] = (float) ((old[j] - MU) / SIGM);
}
// System.out.println("VAL "+i+" = "+Arrays.toString(val));
out.add(new TaggedInstance(new DenseInstance(val, data.instance(i).classValue()), i));
}
}
// System.out.println("FIRST = "+out.get(0));
return out;
}
/**
* Remove the instances in q from sp
*
* @param sp
* @param q
*/
private void removeInstances(Vector<TaggedInstance> sp, Vector<TaggedInstance> q) {
sp.removeAll(q);
}
/**
* XXX write doc
*
* @param significance
*/
public AQBC(double significance) {
this(significance, true);
}
/**
* XXX write doc
*
* default constructor
*/
public AQBC() {
this(0.95);
}
public AQBC(double sig, boolean normalize) {
this.normalize = normalize;
this.S = sig;
}
private Vector<Dataset> clusters = new Vector<Dataset>();
/**
* output all the instances in q as a single cluster with the given index
*
* The index is ignored.
*
* @param q
* @param cluster
*/
private void outputCluster(Vector<TaggedInstance> q, int index) {
Dataset tmp = new DefaultDataset();
for (TaggedInstance i : q) {
tmp.add(data.instance(i.getTag()));
}
clusters.add(tmp);
}
private DistanceMeasure dm;
private Vector<TaggedInstance> retrieveInstances(Vector<TaggedInstance> sp, double[] me2, double radnw2) {
Instance tmp = new DenseInstance(me2);
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (TaggedInstance inst : sp) {
if (dm.measure(inst.inst, tmp) < radnw2)
out.add(inst);
}
return out;
}
// modifies: RADNW
private boolean exp_max(Vector<TaggedInstance> AS, double[] CK, double QUAL, double S) {
double D = E - 2;
double R = Math.sqrt(E - 1);
// System.out.println("CK= "+Arrays.toString(CK));
double[] RD = calculateDistances(AS, CK);
// System.out.println("RD = "+Arrays.toString(RD));
int samples = RD.length;
int MAXITER = 500;
double CDIF = 0.001;
double count = 0;// float sum = 0;
for (int i = 0; i < RD.length; i++) {
if (RD[i] < QUAL) {
count++;
// sum += RD[i];
}
}
// System.out.println("count = "+count);
// System.out.println("RD.length = "+RD.length);
double PC = count / RD.length;// sum / RD.length;
double PB = 1 - PC;
// System.out.println("PC = "+PC);
// System.out.println("PB = "+PB);
double tmpVAR = 0;
// double sum=0;
for (int i = 0; i < RD.length; i++) {
if (RD[i] < QUAL) {
// sum += RD[i];
tmpVAR += RD[i] * RD[i];
}
}
// System.out.println("sum = "+sum);
// System.out.println("tmpVAR = "+tmpVAR);
double VAR = (1 / D) * tmpVAR / count;
boolean CONV = false;
for (int i = 0; i < MAXITER && !CONV; i++) {
// System.out.println("\tEM iteration: "+i);
// System.out.println("\tVAR = "+VAR);
double[] prc = clusterdistrib(RD, VAR, D, R);
// System.out.println("PRC = "+Arrays.toString(prc));
double[] prb = background(RD, D, R);
double[] prcpc = new double[prc.length];
for (int j = 0; j < prc.length; j++) {
prcpc[j] = prc[j] * PC;
}
double[] prbpb = new double[prb.length];
for (int j = 0; j < prb.length; j++) {
prbpb[j] = prb[j] * PB;
}
double[] pr = new double[prcpc.length];
for (int j = 0; j < prc.length; j++) {
pr[j] = prcpc[j] + prbpb[j];
}
double[] pcr = new double[prcpc.length];
for (int j = 0; j < prc.length; j++) {
pcr[j] = prcpc[j] / pr[j];
}
double SM = 0;
for (int j = 0; j < prc.length; j++) {
SM += pcr[j];
}
// System.out.println("\tSM = "+SM);
if (MathUtils.eq(SM, 0) || Double.isInfinite(SM)) {
i = MAXITER;// will return from loop
}
float tmpVAR_new = 0;
for (int j = 0; j < prc.length; j++) {
tmpVAR_new += RD[j] * RD[j] * pcr[j];
}
// System.out.println("tmpVAR_new = "+tmpVAR_new);
double VAR_new = (1 / D) * tmpVAR_new / SM;
// System.out.println("PCR = "+Arrays.toString(pcr));
// System.out.println("\tVAR_new = "+VAR_new);
// System.out.println("\tPC = "+PC);
double PC_new = SM / samples;
// System.out.println("\tPC_new = "+PC_new);
double PB_new = 1 - PC_new;
if (Math.abs(VAR_new - VAR) < CDIF && Math.abs(PC_new - PC) < CDIF) {
CONV = true;
}
PC = PC_new;
PB = PB_new;
VAR = VAR_new;
}
if (CONV) {
if (MathUtils.eq(PC, 0) || MathUtils.eq(PB, 0)) {
System.out.println("EM: No or incorrect convergence! - PC==0 || PB==0");
CONV = false;
RADNW = 0;
return false;
}
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double SD1 = (2 * Math.pow(Math.PI, (D + 1) / 2)) / (GammaFunction.gamma((D + 1) / 2));
// System.out.println("SD = "+SD);
// System.out.println("SD1 = "+SD1);
double CC = SD * (1 / (Math.pow(2 * Math.PI * VAR, D / 2)));
double CB = (SD / (SD1 * Math.pow(Math.sqrt(D + 1), D)));
double LO = (S / (1 - S)) * ((PB * CB) / (PC * CC));
// System.out.println("PB = "+PB);
// System.out.println("PC = "+PC);
// System.out.println("S = "+S);
// System.out.println("CC = "+CC);
// System.out.println("CB = "+CB);
// System.out.println("LO = "+LO);
if (LO <= 0) {
System.out.println("EM: Impossible to calculate radius - LO<0!");
return false;
}
double DIS = -2 * VAR * Math.log(LO);
// System.out.println("DIS = "+DIS);
if (DIS <= 0) {
System.out.println("EM: Impossible to calculate radius - DIS<0!");
System.out.println();
return false;
}
RADNW = (float) Math.sqrt(DIS);
return true;
} else {
System.out.println("EM: No or incorrect convergence! Probably not enough iterations for EM");
return false;
}
}
/**
* implements background.m
*
* @param r
* @param D
* @param R
* @return
*/
private double[] background(double[] r, double D, double R) {
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double SD1 = (2 * Math.pow(Math.PI, (D + 1) / 2)) / (GammaFunction.gamma((D + 1) / 2));
double[] out = new double[r.length];
for (int i = 0; i < out.length; i++) {
out[i] = ((SD / (SD1 * (Math.pow(R, D)))) * (Math.pow(r[i], D - 1)));
}
return out;
}
/**
* implements clusterdistrib
*
* @param r
* @param VAR
* @param D
* @param R
* @return
*/
private double[] clusterdistrib(double[] r, double VAR, double D, double R) {
// System.out.println("\t\tCD:VAR = "+VAR);
// System.out.println("\t\tCD:D = "+D);
// System.out.println("\t\tCD:R = "+R);
// System.out.println("\t\tCD:r = "+Arrays.toString(r));
double[] out = new double[r.length];
if (MathUtils.eq(VAR, 0)) {
// System.out.println("\t\tCD: VAR is considered ZERO !!!");
for (int i = 0; i < r.length; i++) {
if (MathUtils.eq(r[i], 0)) {
out[i] = Float.POSITIVE_INFINITY;
}
}
} else {
double SD = (2 * Math.pow(Math.PI, D / 2)) / (GammaFunction.gamma(D / 2));
double tmp_piVAR = 2 * Math.PI * VAR;
double tmp_piVARpow = Math.pow(tmp_piVAR, D / 2);
double tmp_piVARpowINV = 1 / tmp_piVARpow;
// System.out.println("\t\tCD:SD = "+SD);
// System.out.println("\t\tCD:tmp_piVAR = "+tmp_piVAR);
// System.out.println("\t\tCD:tmp_piVARpow = "+tmp_piVARpow);
// System.out.println("\t\tCD:tmp_piVARpowINV = "+tmp_piVARpowINV);
for (int i = 0; i < r.length; i++) {
double tmp_exp = -((r[i] * r[i]) / (2 * VAR));
// System.out.println("\t\tMath.pow(r[i],D-1) =
// "+Math.pow(r[i],D-1));
// System.out.println("\t\tCD:tmp_exp = "+tmp_exp);
// System.out.println("\t\tCD:exp(tmp_exp) =
// "+Math.exp(tmp_exp));
out[i] = (float) (SD * tmp_piVARpowINV * Math.pow(r[i], D - 1) * Math.exp(tmp_exp));
}
for (int i = 0; i < r.length; i++) {
if (MathUtils.eq(r[i], 0))
out[i] = 1;
}
}
return out;
}
/**
* Comparable to dist_misval
*
* Calculates the distance between each instance and the instance given as a
* float array.
*
* @param as
* @param ck
* @return
*/
private double[] calculateDistances(Vector<TaggedInstance> as, double[] ck) {
// voor elke instance van AS, trek er CK van af
// retur<SUF>
// verschil
double[] out = new double[as.size()];
for (int i = 0; i < as.size(); i++) {
Double[] values = as.get(i).inst.values().toArray(new Double[0]);
// float[]dif=new float[values.length];
float sum = 0;
for (int j = 0; j < values.length; j++) {
// dif[j]=
double dif = values[j] - ck[j];
sum += dif * dif;
}
out[i] = Math.sqrt(sum);
}
// Instance tmp=new SimpleInstance(ck);
// float[]out=new float[as.size()];
// for(int i=0;i<as.size();i++){
// out[i]=(float)dm.calculateDistance(tmp,as.get(i));
// }
return out;
}
// Significance level
private double S = 0.95f;
private double EXTTRESH2;
private double[] ME;
// modifies: CE,ME,EXTTRESH2
/**
* returns true if this step converged
*/
private boolean wan_shr_adap(Vector<TaggedInstance> A, double EXTTRESH) {
int samples = A.size();
double[] CE = new double[samples];
int MAXITER = 100;
double NRWAN = 30;
// System.out.println("FIRSTA = "+A.get(0));
double[] ME1 = mean(A);
// System.out.println("A = "+A);
// System.out.println("ME1 = " + Arrays.toString(ME1));
// System.out.println("EXTTRESH = "+EXTTRESH);
double[] DMI = calculateDistances(A, ME1);
// System.out.println("DMI = "+Arrays.toString(DMI));
double maxDMI = DMI[0];
double minDMI = DMI[0];
for (int i = 1; i < DMI.length; i++) {
if (DMI[i] > maxDMI)
maxDMI = DMI[i];
if (DMI[i] < minDMI)
minDMI = DMI[i];
}
EXTTRESH2 = maxDMI;
double MDIS = minDMI;
if (MathUtils.eq(MDIS, EXTTRESH2)) {
ME = ME1;
for (int i = 0; i < CE.length; i++)
CE[i] = 1;
EXTTRESH2 += 0.000001;
System.out.println("Cluster center localisation did not reach preliminary estimate of radius!");
return true;// TODO check if it should really be true, false is more
// logical
}
double DELTARAD = (EXTTRESH2 - EXTTRESH) / NRWAN;
double RADPR = EXTTRESH2;
EXTTRESH2 = EXTTRESH2 - DELTARAD;
if (EXTTRESH2 <= MDIS) {
EXTTRESH2 = (RADPR + MDIS) / 2;
}
Vector<Integer> Q = findLower(DMI, EXTTRESH2);
for (int i = 0; Q.size() != 0 && i < MAXITER; i++) {
double[] ME2 = mean(select(A, Q));
if (MathUtils.eq(ME1, ME2) && MathUtils.eq(RADPR, EXTTRESH2)) {
ME = ME2;
for (Integer index : Q) {
CE[index] = 1;
}
return true;
}
RADPR = EXTTRESH2;
DMI = calculateDistances(A, ME2);
if (EXTTRESH2 > EXTTRESH) {
EXTTRESH2 = Math.max(EXTTRESH, EXTTRESH2 - DELTARAD);
if (EXTTRESH2 < MathUtils.min(DMI)) {
EXTTRESH2 = RADPR;
}
}
Q = findLower(DMI, EXTTRESH2);
ME1 = ME2;
}
System.out.println("Preliminary cluster location did not converge");
// System.out.println("\t DMI = "+Arrays.toString(DMI));
System.out.println("\t EXTTRESH2 = " + EXTTRESH2);
return false;
}
/**
* return all the indices that are lower that the threshold
*
* @param array
* @param thres
* @return
*/
private Vector<Integer> findLower(double[] array, double threshold) {
Vector<Integer> out = new Vector<Integer>();
for (int i = 0; i < array.length; i++) {
if (array[i] < threshold)
out.add(i);
}
return out;
}
/**
* Return a vector with all instances that have their index in the indices
* vector.
*
* @param instances
* @param indices
* @return
*/
private Vector<TaggedInstance> select(Vector<TaggedInstance> instances, Vector<Integer> indices) {
Vector<TaggedInstance> out = new Vector<TaggedInstance>();
for (Integer index : indices) {
out.add(instances.get(index));
}
return out;
}
private double[] mean(Vector<TaggedInstance> a) {
double[] out = new double[a.get(0).inst.noAttributes()];
for (int i = 0; i < a.size(); i++) {
// System.out.println("Instance "+i+" = "+a.get(i));
for (int j = 0; j < a.get(0).inst.noAttributes(); j++)
out[j] += a.get(i).inst.value(j);
}
// System.out.println("OUT = "+Arrays.toString(out));
for (int j = 0; j < a.get(0).inst.noAttributes(); j++) {
out[j] /= a.size();
}
return out;
}
}
|
148168_3 | /*
* This file is part of dependency-check-core.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2019 Jason Dillon. All Rights Reserved.
*/
package org.owasp.dependencycheck.data.ossindex;
import java.io.File;
import org.sonatype.goodies.packageurl.RenderFlavor;
import org.sonatype.ossindex.service.client.OssindexClient;
import org.sonatype.ossindex.service.client.OssindexClientConfiguration;
import org.sonatype.ossindex.service.client.marshal.Marshaller;
import org.sonatype.ossindex.service.client.marshal.GsonMarshaller;
import org.sonatype.ossindex.service.client.internal.OssindexClientImpl;
import org.sonatype.ossindex.service.client.transport.Transport;
import org.sonatype.ossindex.service.client.transport.UserAgentSupplier;
import org.owasp.dependencycheck.utils.Settings;
import java.io.IOException;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.ossindex.service.client.cache.DirectoryCache;
import org.sonatype.ossindex.service.client.transport.AuthConfiguration;
/**
* Produces {@link OssindexClient} instances.
*
* @author Jason Dillon
* @since 5.0.0
*/
public final class OssindexClientFactory {
/**
* Static logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(OssindexClientFactory.class);
static {
// prefer pkg scheme vs scheme-less variant
RenderFlavor.setDefault(RenderFlavor.SCHEME);
}
/**
* Private constructor for utility class.
*/
private OssindexClientFactory() {
//private constructor for utility class
}
/**
* Constructs a new OSS Index Client.
*
* @param settings the configured settings
* @return a new OSS Index Client
*/
public static OssindexClient create(final Settings settings) {
final OssindexClientConfiguration config = new OssindexClientConfiguration();
final String baseUrl = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_URL, null);
if (baseUrl != null) {
config.setBaseUrl(baseUrl);
}
final String username = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_USER);
final String password = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_PASSWORD);
if (username != null && password != null) {
final AuthConfiguration auth = new AuthConfiguration(username, password);
config.setAuthConfiguration(auth);
}
final int batchSize = settings.getInt(Settings.KEYS.ANALYZER_OSSINDEX_BATCH_SIZE, OssindexClientConfiguration.DEFAULT_BATCH_SIZE);
config.setBatchSize(batchSize);
// proxy likely does not need to be configured here as we are using the
// URLConnectionFactory#createHttpURLConnection() which automatically configures
// the proxy on the connection.
// ProxyConfiguration proxy = new ProxyConfiguration();
// settings.getString(Settings.KEYS.PROXY_PASSWORD);
// config.setProxyConfiguration(proxy);
if (settings.getBoolean(Settings.KEYS.ANALYZER_OSSINDEX_USE_CACHE, true)) {
final DirectoryCache.Configuration cache = new DirectoryCache.Configuration();
final File data;
try {
data = settings.getDataDirectory();
final File cacheDir = new File(data, "oss_cache");
if (cacheDir.isDirectory() || cacheDir.mkdirs()) {
cache.setBaseDir(cacheDir.toPath());
cache.setExpireAfter(Duration.standardHours(24));
config.setCacheConfiguration(cache);
LOGGER.debug("OSS Index Cache: " + cache);
} else {
LOGGER.warn("Unable to use a cache for the OSS Index");
}
} catch (IOException ex) {
LOGGER.warn("Unable to use a cache for the OSS Index", ex);
}
}
// customize User-Agent for use with dependency-check
final UserAgentSupplier userAgent = new UserAgentSupplier(
"dependency-check",
settings.getString(Settings.KEYS.APPLICATION_VERSION, "unknown")
);
final Transport transport = new ODCConnectionTransport(settings, config, userAgent);
final Marshaller marshaller = new GsonMarshaller();
return new OssindexClientImpl(config, transport, marshaller);
}
}
| Abinash-Seth/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/data/ossindex/OssindexClientFactory.java | 1,206 | // prefer pkg scheme vs scheme-less variant | line_comment | nl | /*
* This file is part of dependency-check-core.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2019 Jason Dillon. All Rights Reserved.
*/
package org.owasp.dependencycheck.data.ossindex;
import java.io.File;
import org.sonatype.goodies.packageurl.RenderFlavor;
import org.sonatype.ossindex.service.client.OssindexClient;
import org.sonatype.ossindex.service.client.OssindexClientConfiguration;
import org.sonatype.ossindex.service.client.marshal.Marshaller;
import org.sonatype.ossindex.service.client.marshal.GsonMarshaller;
import org.sonatype.ossindex.service.client.internal.OssindexClientImpl;
import org.sonatype.ossindex.service.client.transport.Transport;
import org.sonatype.ossindex.service.client.transport.UserAgentSupplier;
import org.owasp.dependencycheck.utils.Settings;
import java.io.IOException;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.ossindex.service.client.cache.DirectoryCache;
import org.sonatype.ossindex.service.client.transport.AuthConfiguration;
/**
* Produces {@link OssindexClient} instances.
*
* @author Jason Dillon
* @since 5.0.0
*/
public final class OssindexClientFactory {
/**
* Static logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(OssindexClientFactory.class);
static {
// prefe<SUF>
RenderFlavor.setDefault(RenderFlavor.SCHEME);
}
/**
* Private constructor for utility class.
*/
private OssindexClientFactory() {
//private constructor for utility class
}
/**
* Constructs a new OSS Index Client.
*
* @param settings the configured settings
* @return a new OSS Index Client
*/
public static OssindexClient create(final Settings settings) {
final OssindexClientConfiguration config = new OssindexClientConfiguration();
final String baseUrl = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_URL, null);
if (baseUrl != null) {
config.setBaseUrl(baseUrl);
}
final String username = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_USER);
final String password = settings.getString(Settings.KEYS.ANALYZER_OSSINDEX_PASSWORD);
if (username != null && password != null) {
final AuthConfiguration auth = new AuthConfiguration(username, password);
config.setAuthConfiguration(auth);
}
final int batchSize = settings.getInt(Settings.KEYS.ANALYZER_OSSINDEX_BATCH_SIZE, OssindexClientConfiguration.DEFAULT_BATCH_SIZE);
config.setBatchSize(batchSize);
// proxy likely does not need to be configured here as we are using the
// URLConnectionFactory#createHttpURLConnection() which automatically configures
// the proxy on the connection.
// ProxyConfiguration proxy = new ProxyConfiguration();
// settings.getString(Settings.KEYS.PROXY_PASSWORD);
// config.setProxyConfiguration(proxy);
if (settings.getBoolean(Settings.KEYS.ANALYZER_OSSINDEX_USE_CACHE, true)) {
final DirectoryCache.Configuration cache = new DirectoryCache.Configuration();
final File data;
try {
data = settings.getDataDirectory();
final File cacheDir = new File(data, "oss_cache");
if (cacheDir.isDirectory() || cacheDir.mkdirs()) {
cache.setBaseDir(cacheDir.toPath());
cache.setExpireAfter(Duration.standardHours(24));
config.setCacheConfiguration(cache);
LOGGER.debug("OSS Index Cache: " + cache);
} else {
LOGGER.warn("Unable to use a cache for the OSS Index");
}
} catch (IOException ex) {
LOGGER.warn("Unable to use a cache for the OSS Index", ex);
}
}
// customize User-Agent for use with dependency-check
final UserAgentSupplier userAgent = new UserAgentSupplier(
"dependency-check",
settings.getString(Settings.KEYS.APPLICATION_VERSION, "unknown")
);
final Transport transport = new ODCConnectionTransport(settings, config, userAgent);
final Marshaller marshaller = new GsonMarshaller();
return new OssindexClientImpl(config, transport, marshaller);
}
}
|
163837_0 | package org.example;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;
import org.example.domain.Book;
import java.util.List;
import java.util.Scanner;
public class DatabaseHelper {
String persistenceUnitName = "jpa-hiber-postgres-pu";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
public void populateDatabase() {
String persistenceUnitName = "jpa-hiber-postgres-pu";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(new Book("Gebroeders Leeuwenhart", "Astrid Lindgren", 5));
em.persist(new Book("De Brief voor de Koning", "Tonke Dragt", 6));
em.persist(new Book("Koning van Katoren", "Jan Terlouw", 7));
tx.commit();
}
public void printLibrary(List<Book> books) {
int columnSizeBookTitle = getColumnSize("Book title");
int columnSizeAuthor = getColumnSize("Author");
int columnSizeQuantity = getColumnSize("Quantity");
int totalSize = 17 + columnSizeBookTitle + columnSizeAuthor + columnSizeQuantity;
System.out.println("-".repeat(Math.max(0, totalSize)));
String secondLineSectionOne = " ".repeat(Math.max(0, (totalSize - 14) / 2));
if (totalSize % 2 != 0) {
String secondLineSectionTwo = " ".repeat(Math.max(0, (totalSize - 14) / 2) + 1);
System.out.println("|" + secondLineSectionOne + "List - Books" + secondLineSectionTwo + "|");
} else {
System.out.println("|" + secondLineSectionOne + "List - Books" + secondLineSectionOne + "|");
}
System.out.println("" + "-".repeat((Math.max(0, totalSize ))) + "");
String fourthLineBookTitleSectionOne = " ".repeat(Math.max(0, (columnSizeBookTitle - 10 + 2) / 2));
String fourthLineBookTitleSectionTwo = " ".repeat(Math.max(0, (columnSizeBookTitle - 10 + 2) / 2));
if (columnSizeBookTitle % 2 != 0) {
fourthLineBookTitleSectionTwo = " ".repeat(Math.max(0, (columnSizeBookTitle - 10 + 2) / 2) + 1);
}
String fourthLineAuthorSectionOne = " ".repeat(Math.max(0, (columnSizeAuthor - 6 + 2) / 2));
String fourthLineAuthorSectionTwo = " ".repeat(Math.max(0, (columnSizeAuthor - 6 + 2) / 2));
if (columnSizeAuthor % 2 != 0) {
fourthLineAuthorSectionTwo = " ".repeat(Math.max(0, (columnSizeAuthor - 6 + 2) / 2) + 1);
}
String fourthLineQuantitySectionOne = " ".repeat(Math.max(0, (columnSizeQuantity - 8 + 2) / 2));
String fourthLineQuantitySectionTwo = " ".repeat(Math.max(0, (columnSizeQuantity - 8 + 2) / 2));
if (columnSizeQuantity % 2 != 0) {
fourthLineQuantitySectionTwo = " ".repeat(Math.max(0, (columnSizeQuantity - 8 + 2) / 2) + 1);
}
System.out.println("| ID |" + fourthLineBookTitleSectionOne + "Book title" + fourthLineBookTitleSectionTwo + "|"
+ fourthLineAuthorSectionOne + "Author" + fourthLineAuthorSectionTwo + "|"
+ fourthLineQuantitySectionOne + "Quantity" + fourthLineQuantitySectionTwo + "|");
System.out.println("-".repeat(Math.max(0, totalSize)));
for (Book book : books) {
long serialNumber = book.getSerialNumber();
String bookTitle = book.getBookTitle();
String authorName = book.getAuthorName();
int bookQuantity = book.getBookQuantity();
System.out.println("| " + " ".repeat(Math.max(0, 4 - Integer.toString((int) serialNumber).length()))
+ serialNumber + " | " + bookTitle + " ".repeat(Math.max(0, (columnSizeBookTitle - bookTitle.length()))) + " | "
+ authorName + " ".repeat(Math.max(0, (columnSizeAuthor - authorName.length()))) + " | "
+ bookQuantity + " ".repeat(Math.max(0, (columnSizeQuantity - Integer.toString(bookQuantity).length()))) + " |");
}
System.out.println("-".repeat(Math.max(0, totalSize)));
}
private int getColumnSize(String columnName) throws RuntimeException {
String sqlQuery = "";
switch (columnName) {
case "Book title":
sqlQuery = "SELECT bookTitle FROM Book b";
break;
case "Author":
sqlQuery = "SELECT authorName FROM Book b";
break;
case "Quantity":
sqlQuery = "SELECT bookQuantity FROM Book b";
break;
default:
throw new RuntimeException("Invalid.");
}
List column = em.createQuery(sqlQuery).getResultList();
int size = 0;
for (int i = 0; i < column.size(); i++) {
int tempValue = column.get(i).toString().length();
if (tempValue > size) {
size = tempValue;
}
}
if (columnName.length() > size) {
return columnName.length();
} else {
return size;
}
}
public void clearDatabase() {
String sqlQuery = "DELETE Book";
tx.begin();
em.createQuery(sqlQuery).executeUpdate();
tx.commit();
}
public void deleteBook() {
Scanner serialNrInput = new Scanner(System.in);
System.out.println("Please type the serial number of the to be deleted book: ");
long inputSerialNr = serialNrInput.nextLong();
String sqlQuery = "DELETE FROM Book WHERE serialNumber = " + inputSerialNr;
tx.begin();
em.createQuery(sqlQuery).executeUpdate();
tx.commit();
System.out.println("Book with serial number: ' " + inputSerialNr + " ' has been removed from library.");
}
//drop methode
public int compareBookObjects(Book b1, Book b2) {
if (b1.bookTitle.equalsIgnoreCase(b2.bookTitle)) {
System.out.println("Book with this name already exists.");
return 0;
}
if (b1.serialNumber == b2.serialNumber) {
System.out.println("Book with this serial number already exists.");
return 0;
}
return 1;
}
}
| Abrikoos/LibraryProject | Library/src/main/java/org/example/DatabaseHelper.java | 1,741 | //drop methode | line_comment | nl | package org.example;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;
import org.example.domain.Book;
import java.util.List;
import java.util.Scanner;
public class DatabaseHelper {
String persistenceUnitName = "jpa-hiber-postgres-pu";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
public void populateDatabase() {
String persistenceUnitName = "jpa-hiber-postgres-pu";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(new Book("Gebroeders Leeuwenhart", "Astrid Lindgren", 5));
em.persist(new Book("De Brief voor de Koning", "Tonke Dragt", 6));
em.persist(new Book("Koning van Katoren", "Jan Terlouw", 7));
tx.commit();
}
public void printLibrary(List<Book> books) {
int columnSizeBookTitle = getColumnSize("Book title");
int columnSizeAuthor = getColumnSize("Author");
int columnSizeQuantity = getColumnSize("Quantity");
int totalSize = 17 + columnSizeBookTitle + columnSizeAuthor + columnSizeQuantity;
System.out.println("-".repeat(Math.max(0, totalSize)));
String secondLineSectionOne = " ".repeat(Math.max(0, (totalSize - 14) / 2));
if (totalSize % 2 != 0) {
String secondLineSectionTwo = " ".repeat(Math.max(0, (totalSize - 14) / 2) + 1);
System.out.println("|" + secondLineSectionOne + "List - Books" + secondLineSectionTwo + "|");
} else {
System.out.println("|" + secondLineSectionOne + "List - Books" + secondLineSectionOne + "|");
}
System.out.println("" + "-".repeat((Math.max(0, totalSize ))) + "");
String fourthLineBookTitleSectionOne = " ".repeat(Math.max(0, (columnSizeBookTitle - 10 + 2) / 2));
String fourthLineBookTitleSectionTwo = " ".repeat(Math.max(0, (columnSizeBookTitle - 10 + 2) / 2));
if (columnSizeBookTitle % 2 != 0) {
fourthLineBookTitleSectionTwo = " ".repeat(Math.max(0, (columnSizeBookTitle - 10 + 2) / 2) + 1);
}
String fourthLineAuthorSectionOne = " ".repeat(Math.max(0, (columnSizeAuthor - 6 + 2) / 2));
String fourthLineAuthorSectionTwo = " ".repeat(Math.max(0, (columnSizeAuthor - 6 + 2) / 2));
if (columnSizeAuthor % 2 != 0) {
fourthLineAuthorSectionTwo = " ".repeat(Math.max(0, (columnSizeAuthor - 6 + 2) / 2) + 1);
}
String fourthLineQuantitySectionOne = " ".repeat(Math.max(0, (columnSizeQuantity - 8 + 2) / 2));
String fourthLineQuantitySectionTwo = " ".repeat(Math.max(0, (columnSizeQuantity - 8 + 2) / 2));
if (columnSizeQuantity % 2 != 0) {
fourthLineQuantitySectionTwo = " ".repeat(Math.max(0, (columnSizeQuantity - 8 + 2) / 2) + 1);
}
System.out.println("| ID |" + fourthLineBookTitleSectionOne + "Book title" + fourthLineBookTitleSectionTwo + "|"
+ fourthLineAuthorSectionOne + "Author" + fourthLineAuthorSectionTwo + "|"
+ fourthLineQuantitySectionOne + "Quantity" + fourthLineQuantitySectionTwo + "|");
System.out.println("-".repeat(Math.max(0, totalSize)));
for (Book book : books) {
long serialNumber = book.getSerialNumber();
String bookTitle = book.getBookTitle();
String authorName = book.getAuthorName();
int bookQuantity = book.getBookQuantity();
System.out.println("| " + " ".repeat(Math.max(0, 4 - Integer.toString((int) serialNumber).length()))
+ serialNumber + " | " + bookTitle + " ".repeat(Math.max(0, (columnSizeBookTitle - bookTitle.length()))) + " | "
+ authorName + " ".repeat(Math.max(0, (columnSizeAuthor - authorName.length()))) + " | "
+ bookQuantity + " ".repeat(Math.max(0, (columnSizeQuantity - Integer.toString(bookQuantity).length()))) + " |");
}
System.out.println("-".repeat(Math.max(0, totalSize)));
}
private int getColumnSize(String columnName) throws RuntimeException {
String sqlQuery = "";
switch (columnName) {
case "Book title":
sqlQuery = "SELECT bookTitle FROM Book b";
break;
case "Author":
sqlQuery = "SELECT authorName FROM Book b";
break;
case "Quantity":
sqlQuery = "SELECT bookQuantity FROM Book b";
break;
default:
throw new RuntimeException("Invalid.");
}
List column = em.createQuery(sqlQuery).getResultList();
int size = 0;
for (int i = 0; i < column.size(); i++) {
int tempValue = column.get(i).toString().length();
if (tempValue > size) {
size = tempValue;
}
}
if (columnName.length() > size) {
return columnName.length();
} else {
return size;
}
}
public void clearDatabase() {
String sqlQuery = "DELETE Book";
tx.begin();
em.createQuery(sqlQuery).executeUpdate();
tx.commit();
}
public void deleteBook() {
Scanner serialNrInput = new Scanner(System.in);
System.out.println("Please type the serial number of the to be deleted book: ");
long inputSerialNr = serialNrInput.nextLong();
String sqlQuery = "DELETE FROM Book WHERE serialNumber = " + inputSerialNr;
tx.begin();
em.createQuery(sqlQuery).executeUpdate();
tx.commit();
System.out.println("Book with serial number: ' " + inputSerialNr + " ' has been removed from library.");
}
//drop <SUF>
public int compareBookObjects(Book b1, Book b2) {
if (b1.bookTitle.equalsIgnoreCase(b2.bookTitle)) {
System.out.println("Book with this name already exists.");
return 0;
}
if (b1.serialNumber == b2.serialNumber) {
System.out.println("Book with this serial number already exists.");
return 0;
}
return 1;
}
}
|
3978_10 | package edu.mit.ll.graphulo.apply;
import com.google.common.collect.Iterators;
import edu.mit.ll.graphulo.skvi.RemoteSourceIterator;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.IteratorEnvironment;
import org.apache.accumulo.core.iterators.IteratorUtil;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.hadoop.io.Text;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Applies <tt>J_ij = J_ij / (d_i + d_j - J_ij)</tt>.
* <p>
* Only runs on scan and full major compactions,
* because JaccardDegreeApply must see all entries for a given key in order to correctly apply.
* Idempotent by a clever trick: JaccardDegreeApply will not touch values that have a decimal point '.'.
* It will run on values that do not have a decimal point, and it will always produce a decimal point when applied.
* <p>
* Possible future optimization: only need to scan the part of the degree table
* that is after the seek range's beginning trow. For example, if seeked to [v3,v5),
* we should scan the degree table on (v3,+inf) and load those degrees into a Map.
* <p>
* Preserves keys.
*/
public class JaccardDegreeApply implements ApplyOp {
private static final Logger log = LogManager.getLogger(JaccardDegreeApply.class);
/** Setup with {@link edu.mit.ll.graphulo.Graphulo#basicRemoteOpts(String, String, String, Authorizations)}
* basicRemoteOpts(ApplyIterator.APPLYOP + GraphuloUtil.OPT_SUFFIX, ADeg, null, Aauthorizations)
* options for RemoteSourceIterator. */
public static IteratorSetting iteratorSetting(int priority, Map<String,String> remoteOpts) {
IteratorSetting JDegApply = new IteratorSetting(priority, ApplyIterator.class, remoteOpts);
JDegApply.addOption(ApplyIterator.APPLYOP, JaccardDegreeApply.class.getName());
return JDegApply;
}
private RemoteSourceIterator remoteDegTable;
private Map<String,Double> degMap;
@Override
public void init(Map<String, String> options, IteratorEnvironment env) throws IOException {
// only run on scan or full major compaction
if (!env.getIteratorScope().equals(IteratorUtil.IteratorScope.scan)
&& !(env.getIteratorScope().equals(IteratorUtil.IteratorScope.majc) && env.isFullMajorCompaction())) {
remoteDegTable = null;
degMap = null;
return;
}
remoteDegTable = new RemoteSourceIterator();
remoteDegTable.init(null, options, env);
degMap = new HashMap<>();
scanDegreeTable();
}
private void scanDegreeTable() throws IOException {
remoteDegTable.seek(new Range(), Collections.<ByteSequence>emptySet(), false);
Text rowHolder = new Text();
while (remoteDegTable.hasTop()) {
degMap.put(remoteDegTable.getTopKey().getRow(rowHolder).toString(),
Double.valueOf(remoteDegTable.getTopValue().toString()));
remoteDegTable.next();
}
}
// for debugging:
// private static final Text t1 = new Text("1"), t10 = new Text("10");
// private Text trow = new Text(), tcol = new Text();
@Override
public Iterator<? extends Map.Entry<Key, Value>> apply(final Key k, Value v) {
// if (k.getRow(trow).equals(t1) && k.getColumnQualifier(tcol).equals(t10))
// log.warn("On k="+k.toStringNoTime()+" v="+new String(v.get()));
// check to make sure we're running on scan or full major compaction
if (remoteDegTable == null)
return Iterators.singletonIterator(new AbstractMap.SimpleImmutableEntry<>(k, v));
// Period indicates already processed Double value. No period indicates unprocessed Long value.
String vstr = v.toString();
if (vstr.contains("."))
return Iterators.singletonIterator(new AbstractMap.SimpleImmutableEntry<>(k, v));
long Jij_long = Long.parseLong(vstr);
if (Jij_long == 0)
return null; // no need to keep entries with value zero
double Jij = Jij_long;
String row = k.getRow().toString(), col = k.getColumnQualifier().toString();
Double rowDeg = degMap.get(row), colDeg = degMap.get(col);
// if (trow.equals(t1) && tcol.equals(t10))
// log.warn("On k="+k.toStringNoTime()+" v="+new String(v.get())+" do with rowDeg="+rowDeg+" and colDeg="+colDeg+" for: "+(Jij / (rowDeg+colDeg-Jij)));
if (rowDeg == null)
throw new IllegalStateException("Cannot find rowDeg in degree table:" +row);
if (colDeg == null)
throw new IllegalStateException("Cannot find colDeg in degree table:" +col);
return Iterators.singletonIterator( new AbstractMap.SimpleImmutableEntry<>(k,
new Value(Double.toString(Jij / (rowDeg+colDeg-Jij)).getBytes(StandardCharsets.UTF_8))
));
}
@Override
public void seekApplyOp(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException {
}
}
| Accla/graphulo | src/main/java/edu/mit/ll/graphulo/apply/JaccardDegreeApply.java | 1,496 | // no need to keep entries with value zero | line_comment | nl | package edu.mit.ll.graphulo.apply;
import com.google.common.collect.Iterators;
import edu.mit.ll.graphulo.skvi.RemoteSourceIterator;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.IteratorEnvironment;
import org.apache.accumulo.core.iterators.IteratorUtil;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.hadoop.io.Text;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Applies <tt>J_ij = J_ij / (d_i + d_j - J_ij)</tt>.
* <p>
* Only runs on scan and full major compactions,
* because JaccardDegreeApply must see all entries for a given key in order to correctly apply.
* Idempotent by a clever trick: JaccardDegreeApply will not touch values that have a decimal point '.'.
* It will run on values that do not have a decimal point, and it will always produce a decimal point when applied.
* <p>
* Possible future optimization: only need to scan the part of the degree table
* that is after the seek range's beginning trow. For example, if seeked to [v3,v5),
* we should scan the degree table on (v3,+inf) and load those degrees into a Map.
* <p>
* Preserves keys.
*/
public class JaccardDegreeApply implements ApplyOp {
private static final Logger log = LogManager.getLogger(JaccardDegreeApply.class);
/** Setup with {@link edu.mit.ll.graphulo.Graphulo#basicRemoteOpts(String, String, String, Authorizations)}
* basicRemoteOpts(ApplyIterator.APPLYOP + GraphuloUtil.OPT_SUFFIX, ADeg, null, Aauthorizations)
* options for RemoteSourceIterator. */
public static IteratorSetting iteratorSetting(int priority, Map<String,String> remoteOpts) {
IteratorSetting JDegApply = new IteratorSetting(priority, ApplyIterator.class, remoteOpts);
JDegApply.addOption(ApplyIterator.APPLYOP, JaccardDegreeApply.class.getName());
return JDegApply;
}
private RemoteSourceIterator remoteDegTable;
private Map<String,Double> degMap;
@Override
public void init(Map<String, String> options, IteratorEnvironment env) throws IOException {
// only run on scan or full major compaction
if (!env.getIteratorScope().equals(IteratorUtil.IteratorScope.scan)
&& !(env.getIteratorScope().equals(IteratorUtil.IteratorScope.majc) && env.isFullMajorCompaction())) {
remoteDegTable = null;
degMap = null;
return;
}
remoteDegTable = new RemoteSourceIterator();
remoteDegTable.init(null, options, env);
degMap = new HashMap<>();
scanDegreeTable();
}
private void scanDegreeTable() throws IOException {
remoteDegTable.seek(new Range(), Collections.<ByteSequence>emptySet(), false);
Text rowHolder = new Text();
while (remoteDegTable.hasTop()) {
degMap.put(remoteDegTable.getTopKey().getRow(rowHolder).toString(),
Double.valueOf(remoteDegTable.getTopValue().toString()));
remoteDegTable.next();
}
}
// for debugging:
// private static final Text t1 = new Text("1"), t10 = new Text("10");
// private Text trow = new Text(), tcol = new Text();
@Override
public Iterator<? extends Map.Entry<Key, Value>> apply(final Key k, Value v) {
// if (k.getRow(trow).equals(t1) && k.getColumnQualifier(tcol).equals(t10))
// log.warn("On k="+k.toStringNoTime()+" v="+new String(v.get()));
// check to make sure we're running on scan or full major compaction
if (remoteDegTable == null)
return Iterators.singletonIterator(new AbstractMap.SimpleImmutableEntry<>(k, v));
// Period indicates already processed Double value. No period indicates unprocessed Long value.
String vstr = v.toString();
if (vstr.contains("."))
return Iterators.singletonIterator(new AbstractMap.SimpleImmutableEntry<>(k, v));
long Jij_long = Long.parseLong(vstr);
if (Jij_long == 0)
return null; // no ne<SUF>
double Jij = Jij_long;
String row = k.getRow().toString(), col = k.getColumnQualifier().toString();
Double rowDeg = degMap.get(row), colDeg = degMap.get(col);
// if (trow.equals(t1) && tcol.equals(t10))
// log.warn("On k="+k.toStringNoTime()+" v="+new String(v.get())+" do with rowDeg="+rowDeg+" and colDeg="+colDeg+" for: "+(Jij / (rowDeg+colDeg-Jij)));
if (rowDeg == null)
throw new IllegalStateException("Cannot find rowDeg in degree table:" +row);
if (colDeg == null)
throw new IllegalStateException("Cannot find colDeg in degree table:" +col);
return Iterators.singletonIterator( new AbstractMap.SimpleImmutableEntry<>(k,
new Value(Double.toString(Jij / (rowDeg+colDeg-Jij)).getBytes(StandardCharsets.UTF_8))
));
}
@Override
public void seekApplyOp(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException {
}
}
|
30843_17 | /* **************************
* 1-dim arrays
* **************************
*/
// - vaste grootte
// - efficient raadplegen en wegschrijven van en naar index
// - Kan objecten en primitieve types bevatten
// - iets andere syntax
// - toevoegen en verwijderen betekent eigenlijk overschrijven
// Declareren -> variabelen verwijzen naar null
Persoon[] personen;
double[] temperaturen;
int[] getallen;
// Initialiseren
personen = new Persoon[10]; // object - alle waardes in array == null
temperaturen = new double[100]; // prim type - alle waardes in array default value
getallen = new int[]{4,9,2,4,8,3,1};
// Declareren en initialiseren ineen
double[] gemiddelden = {1.2, 1.7, 1.9, 0.8};
// Toevoegen
temperaturen[0] = 7.53; // 0-index-based
personen[9] = new Persoon("Joe");
// Aanpassen
temperaturen[0] = 8.53;
personen[9] = new Persoon("Jack");
personen[9].setFirstName("William");
// Verwijderen (cel 'leeg' maken)
personen[9] = null;
// een element in een array van primitieve types verwijderen kan niet
// een primitief type kan niet null zijn
getallen[0] = 0;
getallen[1] = 0;
// Opvragen
double temp = temperaturen[0];
Persoon joe = personen[9];
// De lengte van de array opvragen
// .length -> Geen methode (geen haakjes)
int grootteArray = temperaturen.length;
String[] woorden = new String[10];
woorden[0] = "one";
woorden[3] = "four";
woorden[4] = "five";
System.out.println(woorden.length); // ?????
// Overlopen
// - for-loop
for(int i = 0; i<personen.length; i++){
Persoon persoon = personen[i];
if(persoon != null){
persoon.addCredits(5);
}
else {
personen[i] = new Persoon();
}
}
for(int i = 0; i<getallen.length; i++){
int straal = getallen[i];
int oppervlakte = straal * straal * Math.PI;
getallen[i] = oppervlakte;
}
// - for-each -> enkel gebruiken om op te vragen
for(Persoon persoon : personen){
System.out.println(persoon.getName());
}
// - while-lus: vroegtijdig stoppen
int i = 0;
while(i < temperaturen.length && temperaruren[i] <= 20){
i++;
}
double eersteTempBoven20 = temperaturen[i];
// Exceptions?
// - ArrayIndexOutOfBoundsException
// -> index >= 0 && index < array.length
// Enkele (static) utility methodes in de klasse Arrays
Arrays.sort(getallen);
String tekst = Arrays.toString(getallen); // [1,2,3,4,4,8,9]
/* **************************
* 2-dim arrays
* **************************
*/
// Declareren
String[][] speelveld;
Persoon[][] personen;
double[][] temperaturen;
int[][] getallen;
// Initialiseren
speelveld = new String[10][10]; // object - alle waardes in array == null
personen = new Persoon[10][50];
temperaturen = new double[52][7]; // prim type - alle waardes in array default value
getallen = {{4,9,2],{4,8,3},{1,7,6}};
String[][] woorden = new String[30]; // 30 regels op een blad
woorden[0] = new String[7]; // 7 woorden op regel 1
woorden[1] = new String[11]; // 11 woorden op regel 2
woorden[2] = new String[14]; // 14 woorden op regel 3
// ...
woorden[29] = new String[12]; // 12 woorden op regel 29
// Toevoegen
temperaturen[0][0] = 7.53; // 0-index-based
speelveld[4][6] = "^";
personen[7][13] = new Persoon("Joe");
// Aanpassen
temperaturen[0][0] = 8.53;
speelveld[4][6] = "*";
personen[7][13] = new Persoon("Jack");
personen[7][13].setFirstName("William");
// Verwijderen (cel 'leeg' maken)
personen[7][13] = null;
// een element in een array van primitieve types verwijderen kan niet
// een primitief type kan niet null zijn
temperaturen[0][0] = 0;
temperaturen[0][1] = 0;
// Opvragen
double temp = temperaturen[0][0];
Persoon persoon = personen[7][13];
Persoon[] rijPersonen = persoon[5]; // een 1-dim array
// De lengte van de array opvragen (#rijen)
int aantalRijen = temperaturen.length
// De lengte van een rij opvragen (#kolommen)
int aantalKolommenInRijNul = temperaturen[0].length
// Overlopen
// for-loop: volledig overlopen
for(int i = 0; i<personen.length; i++){
for(int j = 0; i<personen[i].length; j++){
Persoon persoon = personen[i][j];
if(persoon != null){
persoon.setCredits(5);
}
else {
personen[i][j] = new Persoon();
}
}
}
| AchielC123/examens-toegepaste-informatica | Examenperiode januari 2022/11-1 Fundamentals of Programming/Arrays.java | 1,397 | // Opvragen | line_comment | nl | /* **************************
* 1-dim arrays
* **************************
*/
// - vaste grootte
// - efficient raadplegen en wegschrijven van en naar index
// - Kan objecten en primitieve types bevatten
// - iets andere syntax
// - toevoegen en verwijderen betekent eigenlijk overschrijven
// Declareren -> variabelen verwijzen naar null
Persoon[] personen;
double[] temperaturen;
int[] getallen;
// Initialiseren
personen = new Persoon[10]; // object - alle waardes in array == null
temperaturen = new double[100]; // prim type - alle waardes in array default value
getallen = new int[]{4,9,2,4,8,3,1};
// Declareren en initialiseren ineen
double[] gemiddelden = {1.2, 1.7, 1.9, 0.8};
// Toevoegen
temperaturen[0] = 7.53; // 0-index-based
personen[9] = new Persoon("Joe");
// Aanpassen
temperaturen[0] = 8.53;
personen[9] = new Persoon("Jack");
personen[9].setFirstName("William");
// Verwijderen (cel 'leeg' maken)
personen[9] = null;
// een element in een array van primitieve types verwijderen kan niet
// een primitief type kan niet null zijn
getallen[0] = 0;
getallen[1] = 0;
// Opvra<SUF>
double temp = temperaturen[0];
Persoon joe = personen[9];
// De lengte van de array opvragen
// .length -> Geen methode (geen haakjes)
int grootteArray = temperaturen.length;
String[] woorden = new String[10];
woorden[0] = "one";
woorden[3] = "four";
woorden[4] = "five";
System.out.println(woorden.length); // ?????
// Overlopen
// - for-loop
for(int i = 0; i<personen.length; i++){
Persoon persoon = personen[i];
if(persoon != null){
persoon.addCredits(5);
}
else {
personen[i] = new Persoon();
}
}
for(int i = 0; i<getallen.length; i++){
int straal = getallen[i];
int oppervlakte = straal * straal * Math.PI;
getallen[i] = oppervlakte;
}
// - for-each -> enkel gebruiken om op te vragen
for(Persoon persoon : personen){
System.out.println(persoon.getName());
}
// - while-lus: vroegtijdig stoppen
int i = 0;
while(i < temperaturen.length && temperaruren[i] <= 20){
i++;
}
double eersteTempBoven20 = temperaturen[i];
// Exceptions?
// - ArrayIndexOutOfBoundsException
// -> index >= 0 && index < array.length
// Enkele (static) utility methodes in de klasse Arrays
Arrays.sort(getallen);
String tekst = Arrays.toString(getallen); // [1,2,3,4,4,8,9]
/* **************************
* 2-dim arrays
* **************************
*/
// Declareren
String[][] speelveld;
Persoon[][] personen;
double[][] temperaturen;
int[][] getallen;
// Initialiseren
speelveld = new String[10][10]; // object - alle waardes in array == null
personen = new Persoon[10][50];
temperaturen = new double[52][7]; // prim type - alle waardes in array default value
getallen = {{4,9,2],{4,8,3},{1,7,6}};
String[][] woorden = new String[30]; // 30 regels op een blad
woorden[0] = new String[7]; // 7 woorden op regel 1
woorden[1] = new String[11]; // 11 woorden op regel 2
woorden[2] = new String[14]; // 14 woorden op regel 3
// ...
woorden[29] = new String[12]; // 12 woorden op regel 29
// Toevoegen
temperaturen[0][0] = 7.53; // 0-index-based
speelveld[4][6] = "^";
personen[7][13] = new Persoon("Joe");
// Aanpassen
temperaturen[0][0] = 8.53;
speelveld[4][6] = "*";
personen[7][13] = new Persoon("Jack");
personen[7][13].setFirstName("William");
// Verwijderen (cel 'leeg' maken)
personen[7][13] = null;
// een element in een array van primitieve types verwijderen kan niet
// een primitief type kan niet null zijn
temperaturen[0][0] = 0;
temperaturen[0][1] = 0;
// Opvragen
double temp = temperaturen[0][0];
Persoon persoon = personen[7][13];
Persoon[] rijPersonen = persoon[5]; // een 1-dim array
// De lengte van de array opvragen (#rijen)
int aantalRijen = temperaturen.length
// De lengte van een rij opvragen (#kolommen)
int aantalKolommenInRijNul = temperaturen[0].length
// Overlopen
// for-loop: volledig overlopen
for(int i = 0; i<personen.length; i++){
for(int j = 0; i<personen[i].length; j++){
Persoon persoon = personen[i][j];
if(persoon != null){
persoon.setCredits(5);
}
else {
personen[i][j] = new Persoon();
}
}
}
|
188662_3 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.keyguard;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
import static android.provider.Settings.Global.ONE_HANDED_KEYGUARD_SIDE;
import static android.provider.Settings.Global.ONE_HANDED_KEYGUARD_SIDE_LEFT;
import static android.provider.Settings.Global.ONE_HANDED_KEYGUARD_SIDE_RIGHT;
import static android.view.WindowInsets.Type.ime;
import static android.view.WindowInsets.Type.systemBars;
import static androidx.constraintlayout.widget.ConstraintSet.CHAIN_SPREAD;
import static androidx.constraintlayout.widget.ConstraintSet.MATCH_CONSTRAINT;
import static androidx.constraintlayout.widget.ConstraintSet.PARENT_ID;
import static androidx.constraintlayout.widget.ConstraintSet.WRAP_CONTENT;
import static com.android.keyguard.KeyguardSecurityContainer.MODE_DEFAULT;
import static com.android.keyguard.KeyguardSecurityContainer.MODE_ONE_HANDED;
import static com.android.keyguard.KeyguardSecurityContainer.MODE_USER_SWITCHER;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.pm.UserInfo;
import android.content.res.Configuration;
import android.graphics.Insets;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.window.BackEvent;
import android.window.OnBackAnimationCallback;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.test.filters.SmallTest;
import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.classifier.FalsingA11yDelegate;
import com.android.systemui.plugins.FalsingManager;
import com.android.systemui.statusbar.policy.UserSwitcherController;
import com.android.systemui.user.data.source.UserRecord;
import com.android.systemui.util.settings.GlobalSettings;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.util.ArrayList;
@SmallTest
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper()
public class KeyguardSecurityContainerTest extends SysuiTestCase {
private static final int VIEW_WIDTH = 1600;
private static final int VIEW_HEIGHT = 900;
@Rule
public MockitoRule mRule = MockitoJUnit.rule();
private KeyguardSecurityViewFlipper mSecurityViewFlipper;
@Mock
private GlobalSettings mGlobalSettings;
@Mock
private FalsingManager mFalsingManager;
@Mock
private UserSwitcherController mUserSwitcherController;
@Mock
private FalsingA11yDelegate mFalsingA11yDelegate;
private KeyguardSecurityContainer mKeyguardSecurityContainer;
@Before
public void setup() {
// Needed here, otherwise when mKeyguardSecurityContainer is created below, it'll cache
// the real references (rather than the TestableResources that this call creates).
mContext.ensureTestableResources();
mSecurityViewFlipper = new KeyguardSecurityViewFlipper(getContext());
mSecurityViewFlipper.setId(View.generateViewId());
mKeyguardSecurityContainer = new KeyguardSecurityContainer(getContext());
mKeyguardSecurityContainer.setRight(VIEW_WIDTH);
mKeyguardSecurityContainer.setLeft(0);
mKeyguardSecurityContainer.setTop(0);
mKeyguardSecurityContainer.setBottom(VIEW_HEIGHT);
mKeyguardSecurityContainer.setId(View.generateViewId());
mKeyguardSecurityContainer.mSecurityViewFlipper = mSecurityViewFlipper;
mKeyguardSecurityContainer.addView(mSecurityViewFlipper, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
when(mUserSwitcherController.getCurrentUserName()).thenReturn("Test User");
when(mUserSwitcherController.isKeyguardShowing()).thenReturn(true);
}
@Test
public void testOnApplyWindowInsets() {
int paddingBottom = getContext().getResources()
.getDimensionPixelSize(R.dimen.keyguard_security_view_bottom_margin);
int imeInsetAmount = paddingBottom + 1;
int systemBarInsetAmount = 0;
initMode(MODE_DEFAULT);
Insets imeInset = Insets.of(0, 0, 0, imeInsetAmount);
Insets systemBarInset = Insets.of(0, 0, 0, systemBarInsetAmount);
WindowInsets insets = new WindowInsets.Builder()
.setInsets(ime(), imeInset)
.setInsetsIgnoringVisibility(systemBars(), systemBarInset)
.build();
mKeyguardSecurityContainer.onApplyWindowInsets(insets);
assertThat(mKeyguardSecurityContainer.getPaddingBottom()).isEqualTo(imeInsetAmount);
}
@Test
public void testOnApplyWindowInsets_largerSystembar() {
int imeInsetAmount = 0;
int paddingBottom = getContext().getResources()
.getDimensionPixelSize(R.dimen.keyguard_security_view_bottom_margin);
int systemBarInsetAmount = paddingBottom + 1;
initMode(MODE_DEFAULT);
Insets imeInset = Insets.of(0, 0, 0, imeInsetAmount);
Insets systemBarInset = Insets.of(0, 0, 0, systemBarInsetAmount);
WindowInsets insets = new WindowInsets.Builder()
.setInsets(ime(), imeInset)
.setInsetsIgnoringVisibility(systemBars(), systemBarInset)
.build();
mKeyguardSecurityContainer.onApplyWindowInsets(insets);
assertThat(mKeyguardSecurityContainer.getPaddingBottom()).isEqualTo(systemBarInsetAmount);
}
@Test
public void testOnApplyWindowInsets_disappearAnimation_paddingNotSet() {
int paddingBottom = getContext().getResources()
.getDimensionPixelSize(R.dimen.keyguard_security_view_bottom_margin);
int imeInsetAmount = paddingBottom + 1;
int systemBarInsetAmount = 0;
initMode(MODE_DEFAULT);
Insets imeInset = Insets.of(0, 0, 0, imeInsetAmount);
Insets systemBarInset = Insets.of(0, 0, 0, systemBarInsetAmount);
WindowInsets insets = new WindowInsets.Builder()
.setInsets(ime(), imeInset)
.setInsetsIgnoringVisibility(systemBars(), systemBarInset)
.build();
ensureViewFlipperIsMocked();
mKeyguardSecurityContainer.startDisappearAnimation(
KeyguardSecurityModel.SecurityMode.Password);
mKeyguardSecurityContainer.onApplyWindowInsets(insets);
assertThat(mKeyguardSecurityContainer.getPaddingBottom()).isNotEqualTo(imeInsetAmount);
}
@Test
public void testDefaultViewMode() {
initMode(MODE_ONE_HANDED);
initMode(MODE_DEFAULT);
ConstraintSet.Constraint viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.startToStart).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.endToEnd).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.bottomToBottom).isEqualTo(PARENT_ID);
}
@Test
public void updatePosition_movesKeyguard() {
setupForUpdateKeyguardPosition(/* oneHandedMode= */ true);
mKeyguardSecurityContainer.updatePositionByTouchX(
mKeyguardSecurityContainer.getWidth() - 1f);
verify(mGlobalSettings).putInt(ONE_HANDED_KEYGUARD_SIDE, ONE_HANDED_KEYGUARD_SIDE_RIGHT);
ConstraintSet.Constraint viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.widthPercent).isEqualTo(0.5f);
assertThat(viewFlipperConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(-1);
mKeyguardSecurityContainer.updatePositionByTouchX(1f);
verify(mGlobalSettings).putInt(ONE_HANDED_KEYGUARD_SIDE, ONE_HANDED_KEYGUARD_SIDE_LEFT);
viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.widthPercent).isEqualTo(0.5f);
assertThat(viewFlipperConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(-1);
}
@Test
public void updatePosition_doesntMoveTwoHandedKeyguard() {
setupForUpdateKeyguardPosition(/* oneHandedMode= */ false);
mKeyguardSecurityContainer.updatePositionByTouchX(
mKeyguardSecurityContainer.getWidth() - 1f);
ConstraintSet.Constraint viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(-1);
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(-1);
mKeyguardSecurityContainer.updatePositionByTouchX(1f);
viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(-1);
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(-1);
}
@Test
public void testUserSwitcherModeViewPositionLandscape() {
// GIVEN one user has been setup and in landscape
when(mUserSwitcherController.getUsers()).thenReturn(buildUserRecords(1));
Configuration landscapeConfig = configuration(ORIENTATION_LANDSCAPE);
when(getContext().getResources().getConfiguration()).thenReturn(landscapeConfig);
// WHEN UserSwitcherViewMode is initialized and config has changed
setupUserSwitcher();
mKeyguardSecurityContainer.onConfigurationChanged(landscapeConfig);
ConstraintSet.Constraint viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
ConstraintSet.Constraint userSwitcherConstraint =
getViewConstraint(R.id.keyguard_bouncer_user_switcher);
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.leftToRight).isEqualTo(
R.id.keyguard_bouncer_user_switcher);
assertThat(userSwitcherConstraint.layout.leftToLeft).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.rightToLeft).isEqualTo(
mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.bottomToBottom).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.bottomToBottom).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.horizontalChainStyle).isEqualTo(CHAIN_SPREAD);
assertThat(userSwitcherConstraint.layout.horizontalChainStyle).isEqualTo(CHAIN_SPREAD);
assertThat(viewFlipperConstraint.layout.mHeight).isEqualTo(MATCH_CONSTRAINT);
assertThat(userSwitcherConstraint.layout.mHeight).isEqualTo(MATCH_CONSTRAINT);
}
@Test
public void testUserSwitcherModeViewPositionPortrait() {
// GIVEN one user has been setup and in landscape
when(mUserSwitcherController.getUsers()).thenReturn(buildUserRecords(1));
Configuration portraitConfig = configuration(ORIENTATION_PORTRAIT);
when(getContext().getResources().getConfiguration()).thenReturn(portraitConfig);
// WHEN UserSwitcherViewMode is initialized and config has changed
setupUserSwitcher();
mKeyguardSecurityContainer.onConfigurationChanged(portraitConfig);
ConstraintSet.Constraint viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
ConstraintSet.Constraint userSwitcherConstraint =
getViewConstraint(R.id.keyguard_bouncer_user_switcher);
assertThat(viewFlipperConstraint.layout.topToBottom).isEqualTo(
R.id.keyguard_bouncer_user_switcher);
assertThat(viewFlipperConstraint.layout.bottomToBottom).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.bottomToTop).isEqualTo(
mSecurityViewFlipper.getId());
assertThat(userSwitcherConstraint.layout.topMargin).isEqualTo(
getContext().getResources().getDimensionPixelSize(
R.dimen.bouncer_user_switcher_y_trans));
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.leftToLeft).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.rightToRight).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.verticalChainStyle).isEqualTo(CHAIN_SPREAD);
assertThat(userSwitcherConstraint.layout.verticalChainStyle).isEqualTo(CHAIN_SPREAD);
assertThat(viewFlipperConstraint.layout.mHeight).isEqualTo(MATCH_CONSTRAINT);
assertThat(userSwitcherConstraint.layout.mHeight).isEqualTo(WRAP_CONTENT);
assertThat(userSwitcherConstraint.layout.mWidth).isEqualTo(WRAP_CONTENT);
}
@Test
public void testLessThanTwoUsersDoesNotAllowDropDown() {
// GIVEN one user has been setup
when(mUserSwitcherController.getUsers()).thenReturn(buildUserRecords(1));
// WHEN UserSwitcherViewMode is initialized
setupUserSwitcher();
// THEN the UserSwitcher anchor should not be clickable
ViewGroup anchor = mKeyguardSecurityContainer.findViewById(R.id.user_switcher_anchor);
assertThat(anchor.isClickable()).isFalse();
}
@Test
public void testTwoOrMoreUsersDoesAllowDropDown() {
// GIVEN one user has been setup
ArrayList<UserRecord> records = buildUserRecords(2);
when(mUserSwitcherController.getCurrentUserRecord()).thenReturn(records.get(0));
when(mUserSwitcherController.getUsers()).thenReturn(records);
// WHEN UserSwitcherViewMode is initialized
setupUserSwitcher();
// THEN the UserSwitcher anchor should not be clickable
ViewGroup anchor = mKeyguardSecurityContainer.findViewById(R.id.user_switcher_anchor);
assertThat(anchor.isClickable()).isTrue();
}
@Test
public void testOnDensityOrFontScaleChanged() {
setupUserSwitcher();
View oldUserSwitcher = mKeyguardSecurityContainer.findViewById(
R.id.keyguard_bouncer_user_switcher);
mKeyguardSecurityContainer.onDensityOrFontScaleChanged();
View newUserSwitcher = mKeyguardSecurityContainer.findViewById(
R.id.keyguard_bouncer_user_switcher);
assertThat(oldUserSwitcher).isNotEqualTo(newUserSwitcher);
}
@Test
public void testTouchesAreRecognizedAsBeingOnTheOtherSideOfSecurity() {
setupUserSwitcher();
setViewWidth(VIEW_WIDTH);
// security is on the right side by default
assertThat(mKeyguardSecurityContainer.isTouchOnTheOtherSideOfSecurity(
touchEventLeftSide())).isTrue();
assertThat(mKeyguardSecurityContainer.isTouchOnTheOtherSideOfSecurity(
touchEventRightSide())).isFalse();
// move security to the left side
when(mGlobalSettings.getInt(any(), anyInt())).thenReturn(ONE_HANDED_KEYGUARD_SIDE_LEFT);
mKeyguardSecurityContainer.onConfigurationChanged(new Configuration());
assertThat(mKeyguardSecurityContainer.isTouchOnTheOtherSideOfSecurity(
touchEventLeftSide())).isFalse();
assertThat(mKeyguardSecurityContainer.isTouchOnTheOtherSideOfSecurity(
touchEventRightSide())).isTrue();
}
@Test
public void testSecuritySwitchesSidesInLandscapeUserSwitcherMode() {
when(getContext().getResources().getConfiguration())
.thenReturn(configuration(ORIENTATION_LANDSCAPE));
setupUserSwitcher();
// switch sides
when(mGlobalSettings.getInt(any(), anyInt())).thenReturn(ONE_HANDED_KEYGUARD_SIDE_LEFT);
mKeyguardSecurityContainer.onConfigurationChanged(new Configuration());
ConstraintSet.Constraint viewFlipperConstraint = getViewConstraint(
mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(PARENT_ID);
}
@Test
public void testPlayBackAnimation() {
OnBackAnimationCallback backCallback = mKeyguardSecurityContainer.getBackCallback();
backCallback.onBackStarted(createBackEvent(0, 0));
mKeyguardSecurityContainer.getBackCallback().onBackProgressed(
createBackEvent(0, 1));
assertThat(mKeyguardSecurityContainer.getScaleX()).isEqualTo(
KeyguardSecurityContainer.MIN_BACK_SCALE);
assertThat(mKeyguardSecurityContainer.getScaleY()).isEqualTo(
KeyguardSecurityContainer.MIN_BACK_SCALE);
// reset scale
mKeyguardSecurityContainer.resetScale();
assertThat(mKeyguardSecurityContainer.getScaleX()).isEqualTo(1);
assertThat(mKeyguardSecurityContainer.getScaleY()).isEqualTo(1);
}
@Test
public void testDisappearAnimationPassword() {
ensureViewFlipperIsMocked();
KeyguardPasswordView keyguardPasswordView = mock(KeyguardPasswordView.class);
when(mSecurityViewFlipper.getSecurityView()).thenReturn(keyguardPasswordView);
mKeyguardSecurityContainer
.startDisappearAnimation(KeyguardSecurityModel.SecurityMode.Password);
verify(keyguardPasswordView).setDisappearAnimationListener(any());
}
private BackEvent createBackEvent(float touchX, float progress) {
return new BackEvent(0, 0, progress, BackEvent.EDGE_LEFT);
}
private Configuration configuration(@Configuration.Orientation int orientation) {
Configuration config = new Configuration();
config.orientation = orientation;
return config;
}
private void setViewWidth(int width) {
mKeyguardSecurityContainer.setRight(width);
mKeyguardSecurityContainer.setLeft(0);
}
private MotionEvent touchEventLeftSide() {
return MotionEvent.obtain(
/* downTime= */0,
/* eventTime= */0,
MotionEvent.ACTION_DOWN,
/* x= */VIEW_WIDTH / 3f,
/* y= */0,
/* metaState= */0);
}
private MotionEvent touchEventRightSide() {
return MotionEvent.obtain(
/* downTime= */0,
/* eventTime= */0,
MotionEvent.ACTION_DOWN,
/* x= */(VIEW_WIDTH / 3f) * 2,
/* y= */0,
/* metaState= */0);
}
private void setupUserSwitcher() {
when(mGlobalSettings.getInt(any(), anyInt())).thenReturn(ONE_HANDED_KEYGUARD_SIDE_RIGHT);
initMode(MODE_USER_SWITCHER);
}
private ArrayList<UserRecord> buildUserRecords(int count) {
ArrayList<UserRecord> users = new ArrayList<>();
for (int i = 0; i < count; ++i) {
UserInfo info = new UserInfo(i /* id */, "Name: " + i, null /* iconPath */,
0 /* flags */);
users.add(new UserRecord(info, null, false /* isGuest */, false /* isCurrent */,
false /* isAddUser */, false /* isRestricted */, true /* isSwitchToEnabled */,
false /* isAddSupervisedUser */, null /* enforcedAdmin */,
false /* isManageUsers */));
}
return users;
}
private void setupForUpdateKeyguardPosition(boolean oneHandedMode) {
int mode = oneHandedMode ? MODE_ONE_HANDED : MODE_DEFAULT;
initMode(mode);
}
/** Get the ConstraintLayout constraint of the view. */
private ConstraintSet.Constraint getViewConstraint(int viewId) {
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(mKeyguardSecurityContainer);
return constraintSet.getConstraint(viewId);
}
private void initMode(int mode) {
mKeyguardSecurityContainer.initMode(mode, mGlobalSettings, mFalsingManager,
mUserSwitcherController, () -> {
}, mFalsingA11yDelegate);
}
private void ensureViewFlipperIsMocked() {
mSecurityViewFlipper = mock(KeyguardSecurityViewFlipper.class);
KeyguardPasswordView keyguardPasswordView = mock(KeyguardPasswordView.class);
when(mSecurityViewFlipper.getSecurityView()).thenReturn(keyguardPasswordView);
mKeyguardSecurityContainer.mSecurityViewFlipper = mSecurityViewFlipper;
}
}
| AcmeUI/android_frameworks_base | packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerTest.java | 5,333 | /* oneHandedMode= */ | block_comment | nl | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.keyguard;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
import static android.provider.Settings.Global.ONE_HANDED_KEYGUARD_SIDE;
import static android.provider.Settings.Global.ONE_HANDED_KEYGUARD_SIDE_LEFT;
import static android.provider.Settings.Global.ONE_HANDED_KEYGUARD_SIDE_RIGHT;
import static android.view.WindowInsets.Type.ime;
import static android.view.WindowInsets.Type.systemBars;
import static androidx.constraintlayout.widget.ConstraintSet.CHAIN_SPREAD;
import static androidx.constraintlayout.widget.ConstraintSet.MATCH_CONSTRAINT;
import static androidx.constraintlayout.widget.ConstraintSet.PARENT_ID;
import static androidx.constraintlayout.widget.ConstraintSet.WRAP_CONTENT;
import static com.android.keyguard.KeyguardSecurityContainer.MODE_DEFAULT;
import static com.android.keyguard.KeyguardSecurityContainer.MODE_ONE_HANDED;
import static com.android.keyguard.KeyguardSecurityContainer.MODE_USER_SWITCHER;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.pm.UserInfo;
import android.content.res.Configuration;
import android.graphics.Insets;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowInsets;
import android.window.BackEvent;
import android.window.OnBackAnimationCallback;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.test.filters.SmallTest;
import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.classifier.FalsingA11yDelegate;
import com.android.systemui.plugins.FalsingManager;
import com.android.systemui.statusbar.policy.UserSwitcherController;
import com.android.systemui.user.data.source.UserRecord;
import com.android.systemui.util.settings.GlobalSettings;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.util.ArrayList;
@SmallTest
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper()
public class KeyguardSecurityContainerTest extends SysuiTestCase {
private static final int VIEW_WIDTH = 1600;
private static final int VIEW_HEIGHT = 900;
@Rule
public MockitoRule mRule = MockitoJUnit.rule();
private KeyguardSecurityViewFlipper mSecurityViewFlipper;
@Mock
private GlobalSettings mGlobalSettings;
@Mock
private FalsingManager mFalsingManager;
@Mock
private UserSwitcherController mUserSwitcherController;
@Mock
private FalsingA11yDelegate mFalsingA11yDelegate;
private KeyguardSecurityContainer mKeyguardSecurityContainer;
@Before
public void setup() {
// Needed here, otherwise when mKeyguardSecurityContainer is created below, it'll cache
// the real references (rather than the TestableResources that this call creates).
mContext.ensureTestableResources();
mSecurityViewFlipper = new KeyguardSecurityViewFlipper(getContext());
mSecurityViewFlipper.setId(View.generateViewId());
mKeyguardSecurityContainer = new KeyguardSecurityContainer(getContext());
mKeyguardSecurityContainer.setRight(VIEW_WIDTH);
mKeyguardSecurityContainer.setLeft(0);
mKeyguardSecurityContainer.setTop(0);
mKeyguardSecurityContainer.setBottom(VIEW_HEIGHT);
mKeyguardSecurityContainer.setId(View.generateViewId());
mKeyguardSecurityContainer.mSecurityViewFlipper = mSecurityViewFlipper;
mKeyguardSecurityContainer.addView(mSecurityViewFlipper, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
when(mUserSwitcherController.getCurrentUserName()).thenReturn("Test User");
when(mUserSwitcherController.isKeyguardShowing()).thenReturn(true);
}
@Test
public void testOnApplyWindowInsets() {
int paddingBottom = getContext().getResources()
.getDimensionPixelSize(R.dimen.keyguard_security_view_bottom_margin);
int imeInsetAmount = paddingBottom + 1;
int systemBarInsetAmount = 0;
initMode(MODE_DEFAULT);
Insets imeInset = Insets.of(0, 0, 0, imeInsetAmount);
Insets systemBarInset = Insets.of(0, 0, 0, systemBarInsetAmount);
WindowInsets insets = new WindowInsets.Builder()
.setInsets(ime(), imeInset)
.setInsetsIgnoringVisibility(systemBars(), systemBarInset)
.build();
mKeyguardSecurityContainer.onApplyWindowInsets(insets);
assertThat(mKeyguardSecurityContainer.getPaddingBottom()).isEqualTo(imeInsetAmount);
}
@Test
public void testOnApplyWindowInsets_largerSystembar() {
int imeInsetAmount = 0;
int paddingBottom = getContext().getResources()
.getDimensionPixelSize(R.dimen.keyguard_security_view_bottom_margin);
int systemBarInsetAmount = paddingBottom + 1;
initMode(MODE_DEFAULT);
Insets imeInset = Insets.of(0, 0, 0, imeInsetAmount);
Insets systemBarInset = Insets.of(0, 0, 0, systemBarInsetAmount);
WindowInsets insets = new WindowInsets.Builder()
.setInsets(ime(), imeInset)
.setInsetsIgnoringVisibility(systemBars(), systemBarInset)
.build();
mKeyguardSecurityContainer.onApplyWindowInsets(insets);
assertThat(mKeyguardSecurityContainer.getPaddingBottom()).isEqualTo(systemBarInsetAmount);
}
@Test
public void testOnApplyWindowInsets_disappearAnimation_paddingNotSet() {
int paddingBottom = getContext().getResources()
.getDimensionPixelSize(R.dimen.keyguard_security_view_bottom_margin);
int imeInsetAmount = paddingBottom + 1;
int systemBarInsetAmount = 0;
initMode(MODE_DEFAULT);
Insets imeInset = Insets.of(0, 0, 0, imeInsetAmount);
Insets systemBarInset = Insets.of(0, 0, 0, systemBarInsetAmount);
WindowInsets insets = new WindowInsets.Builder()
.setInsets(ime(), imeInset)
.setInsetsIgnoringVisibility(systemBars(), systemBarInset)
.build();
ensureViewFlipperIsMocked();
mKeyguardSecurityContainer.startDisappearAnimation(
KeyguardSecurityModel.SecurityMode.Password);
mKeyguardSecurityContainer.onApplyWindowInsets(insets);
assertThat(mKeyguardSecurityContainer.getPaddingBottom()).isNotEqualTo(imeInsetAmount);
}
@Test
public void testDefaultViewMode() {
initMode(MODE_ONE_HANDED);
initMode(MODE_DEFAULT);
ConstraintSet.Constraint viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.startToStart).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.endToEnd).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.bottomToBottom).isEqualTo(PARENT_ID);
}
@Test
public void updatePosition_movesKeyguard() {
setupForUpdateKeyguardPosition(/* oneHan<SUF>*/ true);
mKeyguardSecurityContainer.updatePositionByTouchX(
mKeyguardSecurityContainer.getWidth() - 1f);
verify(mGlobalSettings).putInt(ONE_HANDED_KEYGUARD_SIDE, ONE_HANDED_KEYGUARD_SIDE_RIGHT);
ConstraintSet.Constraint viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.widthPercent).isEqualTo(0.5f);
assertThat(viewFlipperConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(-1);
mKeyguardSecurityContainer.updatePositionByTouchX(1f);
verify(mGlobalSettings).putInt(ONE_HANDED_KEYGUARD_SIDE, ONE_HANDED_KEYGUARD_SIDE_LEFT);
viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.widthPercent).isEqualTo(0.5f);
assertThat(viewFlipperConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(-1);
}
@Test
public void updatePosition_doesntMoveTwoHandedKeyguard() {
setupForUpdateKeyguardPosition(/* oneHandedMode= */ false);
mKeyguardSecurityContainer.updatePositionByTouchX(
mKeyguardSecurityContainer.getWidth() - 1f);
ConstraintSet.Constraint viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(-1);
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(-1);
mKeyguardSecurityContainer.updatePositionByTouchX(1f);
viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(-1);
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(-1);
}
@Test
public void testUserSwitcherModeViewPositionLandscape() {
// GIVEN one user has been setup and in landscape
when(mUserSwitcherController.getUsers()).thenReturn(buildUserRecords(1));
Configuration landscapeConfig = configuration(ORIENTATION_LANDSCAPE);
when(getContext().getResources().getConfiguration()).thenReturn(landscapeConfig);
// WHEN UserSwitcherViewMode is initialized and config has changed
setupUserSwitcher();
mKeyguardSecurityContainer.onConfigurationChanged(landscapeConfig);
ConstraintSet.Constraint viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
ConstraintSet.Constraint userSwitcherConstraint =
getViewConstraint(R.id.keyguard_bouncer_user_switcher);
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.leftToRight).isEqualTo(
R.id.keyguard_bouncer_user_switcher);
assertThat(userSwitcherConstraint.layout.leftToLeft).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.rightToLeft).isEqualTo(
mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.bottomToBottom).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.bottomToBottom).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.horizontalChainStyle).isEqualTo(CHAIN_SPREAD);
assertThat(userSwitcherConstraint.layout.horizontalChainStyle).isEqualTo(CHAIN_SPREAD);
assertThat(viewFlipperConstraint.layout.mHeight).isEqualTo(MATCH_CONSTRAINT);
assertThat(userSwitcherConstraint.layout.mHeight).isEqualTo(MATCH_CONSTRAINT);
}
@Test
public void testUserSwitcherModeViewPositionPortrait() {
// GIVEN one user has been setup and in landscape
when(mUserSwitcherController.getUsers()).thenReturn(buildUserRecords(1));
Configuration portraitConfig = configuration(ORIENTATION_PORTRAIT);
when(getContext().getResources().getConfiguration()).thenReturn(portraitConfig);
// WHEN UserSwitcherViewMode is initialized and config has changed
setupUserSwitcher();
mKeyguardSecurityContainer.onConfigurationChanged(portraitConfig);
ConstraintSet.Constraint viewFlipperConstraint =
getViewConstraint(mSecurityViewFlipper.getId());
ConstraintSet.Constraint userSwitcherConstraint =
getViewConstraint(R.id.keyguard_bouncer_user_switcher);
assertThat(viewFlipperConstraint.layout.topToBottom).isEqualTo(
R.id.keyguard_bouncer_user_switcher);
assertThat(viewFlipperConstraint.layout.bottomToBottom).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.topToTop).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.bottomToTop).isEqualTo(
mSecurityViewFlipper.getId());
assertThat(userSwitcherConstraint.layout.topMargin).isEqualTo(
getContext().getResources().getDimensionPixelSize(
R.dimen.bouncer_user_switcher_y_trans));
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.rightToRight).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.leftToLeft).isEqualTo(PARENT_ID);
assertThat(userSwitcherConstraint.layout.rightToRight).isEqualTo(PARENT_ID);
assertThat(viewFlipperConstraint.layout.verticalChainStyle).isEqualTo(CHAIN_SPREAD);
assertThat(userSwitcherConstraint.layout.verticalChainStyle).isEqualTo(CHAIN_SPREAD);
assertThat(viewFlipperConstraint.layout.mHeight).isEqualTo(MATCH_CONSTRAINT);
assertThat(userSwitcherConstraint.layout.mHeight).isEqualTo(WRAP_CONTENT);
assertThat(userSwitcherConstraint.layout.mWidth).isEqualTo(WRAP_CONTENT);
}
@Test
public void testLessThanTwoUsersDoesNotAllowDropDown() {
// GIVEN one user has been setup
when(mUserSwitcherController.getUsers()).thenReturn(buildUserRecords(1));
// WHEN UserSwitcherViewMode is initialized
setupUserSwitcher();
// THEN the UserSwitcher anchor should not be clickable
ViewGroup anchor = mKeyguardSecurityContainer.findViewById(R.id.user_switcher_anchor);
assertThat(anchor.isClickable()).isFalse();
}
@Test
public void testTwoOrMoreUsersDoesAllowDropDown() {
// GIVEN one user has been setup
ArrayList<UserRecord> records = buildUserRecords(2);
when(mUserSwitcherController.getCurrentUserRecord()).thenReturn(records.get(0));
when(mUserSwitcherController.getUsers()).thenReturn(records);
// WHEN UserSwitcherViewMode is initialized
setupUserSwitcher();
// THEN the UserSwitcher anchor should not be clickable
ViewGroup anchor = mKeyguardSecurityContainer.findViewById(R.id.user_switcher_anchor);
assertThat(anchor.isClickable()).isTrue();
}
@Test
public void testOnDensityOrFontScaleChanged() {
setupUserSwitcher();
View oldUserSwitcher = mKeyguardSecurityContainer.findViewById(
R.id.keyguard_bouncer_user_switcher);
mKeyguardSecurityContainer.onDensityOrFontScaleChanged();
View newUserSwitcher = mKeyguardSecurityContainer.findViewById(
R.id.keyguard_bouncer_user_switcher);
assertThat(oldUserSwitcher).isNotEqualTo(newUserSwitcher);
}
@Test
public void testTouchesAreRecognizedAsBeingOnTheOtherSideOfSecurity() {
setupUserSwitcher();
setViewWidth(VIEW_WIDTH);
// security is on the right side by default
assertThat(mKeyguardSecurityContainer.isTouchOnTheOtherSideOfSecurity(
touchEventLeftSide())).isTrue();
assertThat(mKeyguardSecurityContainer.isTouchOnTheOtherSideOfSecurity(
touchEventRightSide())).isFalse();
// move security to the left side
when(mGlobalSettings.getInt(any(), anyInt())).thenReturn(ONE_HANDED_KEYGUARD_SIDE_LEFT);
mKeyguardSecurityContainer.onConfigurationChanged(new Configuration());
assertThat(mKeyguardSecurityContainer.isTouchOnTheOtherSideOfSecurity(
touchEventLeftSide())).isFalse();
assertThat(mKeyguardSecurityContainer.isTouchOnTheOtherSideOfSecurity(
touchEventRightSide())).isTrue();
}
@Test
public void testSecuritySwitchesSidesInLandscapeUserSwitcherMode() {
when(getContext().getResources().getConfiguration())
.thenReturn(configuration(ORIENTATION_LANDSCAPE));
setupUserSwitcher();
// switch sides
when(mGlobalSettings.getInt(any(), anyInt())).thenReturn(ONE_HANDED_KEYGUARD_SIDE_LEFT);
mKeyguardSecurityContainer.onConfigurationChanged(new Configuration());
ConstraintSet.Constraint viewFlipperConstraint = getViewConstraint(
mSecurityViewFlipper.getId());
assertThat(viewFlipperConstraint.layout.leftToLeft).isEqualTo(PARENT_ID);
}
@Test
public void testPlayBackAnimation() {
OnBackAnimationCallback backCallback = mKeyguardSecurityContainer.getBackCallback();
backCallback.onBackStarted(createBackEvent(0, 0));
mKeyguardSecurityContainer.getBackCallback().onBackProgressed(
createBackEvent(0, 1));
assertThat(mKeyguardSecurityContainer.getScaleX()).isEqualTo(
KeyguardSecurityContainer.MIN_BACK_SCALE);
assertThat(mKeyguardSecurityContainer.getScaleY()).isEqualTo(
KeyguardSecurityContainer.MIN_BACK_SCALE);
// reset scale
mKeyguardSecurityContainer.resetScale();
assertThat(mKeyguardSecurityContainer.getScaleX()).isEqualTo(1);
assertThat(mKeyguardSecurityContainer.getScaleY()).isEqualTo(1);
}
@Test
public void testDisappearAnimationPassword() {
ensureViewFlipperIsMocked();
KeyguardPasswordView keyguardPasswordView = mock(KeyguardPasswordView.class);
when(mSecurityViewFlipper.getSecurityView()).thenReturn(keyguardPasswordView);
mKeyguardSecurityContainer
.startDisappearAnimation(KeyguardSecurityModel.SecurityMode.Password);
verify(keyguardPasswordView).setDisappearAnimationListener(any());
}
private BackEvent createBackEvent(float touchX, float progress) {
return new BackEvent(0, 0, progress, BackEvent.EDGE_LEFT);
}
private Configuration configuration(@Configuration.Orientation int orientation) {
Configuration config = new Configuration();
config.orientation = orientation;
return config;
}
private void setViewWidth(int width) {
mKeyguardSecurityContainer.setRight(width);
mKeyguardSecurityContainer.setLeft(0);
}
private MotionEvent touchEventLeftSide() {
return MotionEvent.obtain(
/* downTime= */0,
/* eventTime= */0,
MotionEvent.ACTION_DOWN,
/* x= */VIEW_WIDTH / 3f,
/* y= */0,
/* metaState= */0);
}
private MotionEvent touchEventRightSide() {
return MotionEvent.obtain(
/* downTime= */0,
/* eventTime= */0,
MotionEvent.ACTION_DOWN,
/* x= */(VIEW_WIDTH / 3f) * 2,
/* y= */0,
/* metaState= */0);
}
private void setupUserSwitcher() {
when(mGlobalSettings.getInt(any(), anyInt())).thenReturn(ONE_HANDED_KEYGUARD_SIDE_RIGHT);
initMode(MODE_USER_SWITCHER);
}
private ArrayList<UserRecord> buildUserRecords(int count) {
ArrayList<UserRecord> users = new ArrayList<>();
for (int i = 0; i < count; ++i) {
UserInfo info = new UserInfo(i /* id */, "Name: " + i, null /* iconPath */,
0 /* flags */);
users.add(new UserRecord(info, null, false /* isGuest */, false /* isCurrent */,
false /* isAddUser */, false /* isRestricted */, true /* isSwitchToEnabled */,
false /* isAddSupervisedUser */, null /* enforcedAdmin */,
false /* isManageUsers */));
}
return users;
}
private void setupForUpdateKeyguardPosition(boolean oneHandedMode) {
int mode = oneHandedMode ? MODE_ONE_HANDED : MODE_DEFAULT;
initMode(mode);
}
/** Get the ConstraintLayout constraint of the view. */
private ConstraintSet.Constraint getViewConstraint(int viewId) {
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(mKeyguardSecurityContainer);
return constraintSet.getConstraint(viewId);
}
private void initMode(int mode) {
mKeyguardSecurityContainer.initMode(mode, mGlobalSettings, mFalsingManager,
mUserSwitcherController, () -> {
}, mFalsingA11yDelegate);
}
private void ensureViewFlipperIsMocked() {
mSecurityViewFlipper = mock(KeyguardSecurityViewFlipper.class);
KeyguardPasswordView keyguardPasswordView = mock(KeyguardPasswordView.class);
when(mSecurityViewFlipper.getSecurityView()).thenReturn(keyguardPasswordView);
mKeyguardSecurityContainer.mSecurityViewFlipper = mSecurityViewFlipper;
}
}
|
126537_37 | package b1_sync_stock;
import java.io.IOException;
import java.sql.Connection;
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.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONObject;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
public class ODBCConnector extends AbstractMessageTransformer {
private static final Logger LOG = Logger.getLogger("jmc_java.log");
@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
// Define DB Login Information from FlowVars
String user = message.getInvocationProperty("DBUser");
String password = message.getInvocationProperty("DBPass");
String connectionString = message.getInvocationProperty("DBConnection");
// Create a connection manager with all the info
ODBCManager manager = new ODBCManager(user, password, connectionString);
// Connect to DB
Connection connect = manager.connect();
if (connect == null) {
return "Error Connecting to DB. Check Logs";
} else {
System.out.println("Connection to HANA successful!");
}
try {
// Create a statement to call
Statement query1St = manager.createStatement();
// Decide which database we're hitting
String destination = message.getInvocationProperty("Destination");
String origin = message.getInvocationProperty("Origin");
String fullDestination = destination;
String warehouseMatch = message.getInvocationProperty("warehouseMatch");
HashMap<String, String> destinationMap = message.getInvocationProperty("TableDestinations");
// Check which Items are Inventory enabled from Destination and Holding
String query1 = "SELECT \"ItemCode\",\"InvntItem\" FROM " + destination + ".OITM";
String query2 = "SELECT \"ItemCode\",\"InvntItem\" FROM " + origin + ".OITM";
LOG.info("Item Info Q: " + query1);
LOG.info("Item Info Q2: " + query2);
ResultSet stockEnabled = query1St.executeQuery(query1);
// Save a HashMap of all the Items that are inventory enabled
HashMap<String, Boolean> invItems = parseInventoryResults(stockEnabled);
Statement query2St = manager.createStatement();
ResultSet stockEnabledHolding = query2St.executeQuery(query2);
String queryLote = "SELECT \"ItemCode\", \"WhsCode\", \"OnHand\" FROM "
+ origin + ".OITW WHERE \"WhsCode\" in " + warehouseMatch + ""
+ " AND \"OnHand\" > 0";
LOG.info("Item Count Q: "+queryLote);
Statement queryLoteSt = manager.createStatement();
ResultSet parseStockLoteVentas = queryLoteSt.executeQuery(queryLote);
// Save a HashMap of all the Items that are inventory enabled
HashMap<String, Boolean> invItemsHolding = parseInventoryResults(stockEnabledHolding);
HashMap<String, Object> stockLoteVentas = parseStockLoteVentas(parseStockLoteVentas);
// Dont syncronize if the item is not enabled in holding, will cause an error.
// Also, if the item doesnt exist
for (String val : invItems.keySet()) {
if (invItems.get(val)) { // Dont bother if item is not set to syncronzie anyway
if (invItemsHolding.containsKey(val)) { // Check if item exists in holding
if (!invItemsHolding.get(val)) { // Check if item is enabled in holding
invItems.put(val, false);
}
} else {
invItems.put(val, false);
}
}
}
// for (String value : invItemsHolding.keySet()) {
// if (invItems.get(value)) {
// //LOG.info("Disabled from holding: "+value);
// }
// }
// Get the last updated Date YYYY-MM-DD
String updateDate = message.getInvocationProperty("updateDate");
String updateTime = message.getInvocationProperty("updateTime");
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HH-mm-ss");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("HHmm");
DateTime dateTime = inputFormatter.parseDateTime(updateTime);
String formattedUpdateTime = outputFormatter.print(dateTime.getMillis());
// Get all Item Stocks from DB
// Full STR
// https://stackoverflow.com/questions/58507324/filtering-out-duplicate-entires-for-older-rows
// SELECT * FROM (SELECT T0.\"ItemCode\", T0.\"WhsCode\", T0.\"OnHand\",
// T0.\"IsCommited\", T0.\"OnOrder\", T1.\"DocDate\", T1.\"DocTime\",
// ROW_NUMBER() OVER (PARTITION BY T0.\"ItemCode\" ORDER BY T1.\"DocTime\" DESC)
// AS RN FROM KA_DEV6.OITW T0JOIN KA_DEV6.OINM T1 ON T0.\"WhsCode\" = '01' AND
// T0.\"ItemCode\" = T1.\"ItemCode\" WHERE T1.\"DocDate\" > '2019-10-20' OR
// (T1.\"DocDate\" = '2019-10-20' AND T1.\"DocTime\" >= '1025')) X WHERE RN = 1
String str = "SELECT * FROM " + "("
+ "SELECT T0.\"ItemCode\", T0.\"WhsCode\", T0.\"OnHand\", T0.\"IsCommited\", T0.\"OnOrder\", T1.\"DocDate\", T1.\"DocTime\", T2.\"LastPurPrc\", "
+ " ROW_NUMBER() OVER (PARTITION BY T0.\"ItemCode\" "
+ "ORDER BY T1.\"DocDate\",T1.\"DocTime\" DESC) AS RN " + "FROM " + destination + ".OITW T0 JOIN "
+ destination + ".OINM T1 " + "ON T0.\"WhsCode\" = '01' AND T0.\"ItemCode\" = T1.\"ItemCode\" "
+ "JOIN " + destination + ".OITM T2 ON T0.\"ItemCode\" = T2.\"ItemCode\" "
+ "WHERE T1.\"DocDate\" > '" + updateDate + "' OR (T1.\"DocDate\" = '" + updateDate
+ "' AND T1.\"DocTime\" >= '" + formattedUpdateTime + "')" + ") X WHERE RN = 1 "
+ "ORDER BY \"DocDate\", \"DocTime\" DESC";
LOG.info("Query: " + str);
ResultSet Items = manager.executeQuery(str);
// Parse results as array list ordered by date from oldest (top) to newest
// (bottom)
ArrayList<HashMap<String, Object>> results = parseItemSelect(Items);
HashMap<String, String> newest = getNewestDate(results);
if (newest != null) {
try {
CurrentTimeSaver.setUpdateTime("STOCK_" + destination, newest.get("Time"), newest.get("Date"));
} catch (IOException e) {
e.printStackTrace();
}
}
destination = destinationMap.get(destination);
String UoMEntryQuery = "SELECT \"IUoMEntry\",\"ItemCode\" FROM " + fullDestination + ".OITM";
// System.out.println("Query: " + UoMEntryQuery);
ResultSet querySet = manager.executeQuery(UoMEntryQuery);
HashMap<String, Integer> UoMEntryCodes = parseUoMList(querySet);
String UoMCodeQuery = "SELECT \"UomCode\", \"UomEntry\" FROM " + fullDestination + ".OUOM";
System.out.println("Query: " + UoMCodeQuery);
ResultSet UoMCodeSet = manager.executeQuery(UoMCodeQuery);
HashMap<Integer, String> UoMCode = parseUoMCodeList(UoMCodeSet);
// LOG.info("Parsing done!");
HashMap<String, String> UoMCodeTable = new HashMap<>();
for (String invCode : UoMEntryCodes.keySet()) {
UoMCodeTable.put(invCode, UoMCode.get(UoMEntryCodes.get(invCode)));
}
ArrayList<HashMap<String, Object>> resultsWithUoM = parseItemSelect(Items);
for (HashMap<String, Object> itemMap : results) {
if (UoMEntryCodes.get((String) itemMap.get("ItemCode")) != -1) {
itemMap.put("UoMCode", UoMCodeTable.get(itemMap.get("ItemCode")));
// System.out.println("ItemCode: " + itemMap.get("ItemCode") + " - "+
// UoMCodeTable.get(itemMap.get("ItemCode")));
resultsWithUoM.add(itemMap);
} else {
resultsWithUoM.add(itemMap);
}
}
// Create a hashmap to hold the arraylist
LOG.info("Total results: " + resultsWithUoM.size());
// System.out.println(message);
LOG.info("Result returned!");
// LOG.info(""+StringToJSON.javaToJSONToString(result));
List<List<HashMap<String, Object>>> arraySplit = splitArray(resultsWithUoM, 300);
ArrayList<String> Documents = new ArrayList<String>();
for (List<HashMap<String, Object>> array : arraySplit) {
JSONObject doc = arrayToDocument(array, destination, invItems, stockLoteVentas);
if (doc != null) {
Documents.add(doc.toString());
}
}
return Documents;
} catch (SQLException | NumberFormatException | ParseException e) {
e.printStackTrace();
return e;
}
}
private HashMap<String, Object> parseStockLoteVentas(ResultSet set) throws SQLException {
HashMap<String, Object> cantidadStock = new HashMap<>();
while (set.next() != false) {
if (cantidadStock.containsKey(set.getString("ItemCode"))) {
HashMap<String, Object> stockMap = (HashMap<String, Object>) cantidadStock
.get(set.getString("ItemCode"));
stockMap.put(set.getString("WhsCode"), set.getDouble("OnHand"));
cantidadStock.put(set.getString("ItemCode"), stockMap);
} else {
HashMap<String, Object> stockMap = new HashMap<>();
stockMap.put(set.getString("WhsCode"), set.getDouble("OnHand"));
cantidadStock.put(set.getString("ItemCode"), stockMap);
}
}
return cantidadStock;
}
public HashMap<String, Integer> parseUoMList(ResultSet set) throws SQLException {
int rows = 0;
HashMap<String, Integer> results = new HashMap<>();
while (set.next() != false) {
results.put(set.getString("ItemCode"), set.getInt("IUoMEntry"));
// System.out.println(rowResult);
rows++;
}
if (rows == 0) {
return null;
}
return results;
}
public HashMap<Integer, String> parseUoMCodeList(ResultSet set) throws SQLException {
int rows = 0;
HashMap<Integer, String> results = new HashMap<>();
while (set.next() != false) {
results.put(set.getInt("UomEntry"), set.getString("UomCode"));
// System.out.println(rowResult);
rows++;
}
if (rows == 0) {
return null;
}
return results;
}
public static HashMap<String, String> getNewestDate(ArrayList<HashMap<String, Object>> results) {
Calendar cal = null;
for (HashMap<String, Object> map : results) {
Calendar calendar = (Calendar) map.get("calendar");
if (cal != null) {
if (calendar.after(cal)) {
cal = calendar;
LOG.info("Date " + getDateFromCalendar(calendar) + " is newer than " + getDateFromCalendar(cal));
}
} else {
cal = calendar;
LOG.info("Date doesnt exist, date set: " + getDateFromCalendar(calendar));
LOG.info("Time doesnt exist, date set: " + getTimeFromCalendar(calendar));
}
}
if (cal == null) {
return null;
}
HashMap<String, String> returnInfo = new HashMap<>();
returnInfo.put("Date", getDateFromCalendar(cal));
returnInfo.put("Time", getTimeFromCalendar(cal));
LOG.info(returnInfo.toString());
return returnInfo;
}
public static String getTimeFromCalendar(Calendar cal) {
LOG.info("Hour: " + cal.get(Calendar.HOUR_OF_DAY));
LOG.info("Minute: " + (cal.get(Calendar.MINUTE)));
LOG.info("FormatH: " + String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)));
return String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)) + "-"
+ String.format("%02d", (cal.get(Calendar.MINUTE))) + "-" + "00";
}
public static String getDateFromCalendar(Calendar cal) {
return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH);
}
@SuppressWarnings("unchecked")
public static JSONObject arrayToDocument(List<HashMap<String, Object>> inputArray, String destination,
HashMap<String, Boolean> invItems, HashMap<String, Object> stockVentas) {
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
LOG.info("New Document");
int i = 1;
for (HashMap<String, Object> map : inputArray) {
// System.out.println(((Calendar) map.get("calendar")).getTime());
JSONObject jsonMap = new JSONObject();
jsonMap.put("LineNumber", i);
jsonMap.put("ItemCode", (String) map.get("ItemCode"));
if (map.get("UoMCode") != null) {
jsonMap.put("UoMCode", (String) map.get("UoMCode"));
}
jsonMap.put("Price", map.get("Price"));
jsonMap.put("WarehouseCode", destination + "_" + (String) map.get("WharehouseCode"));
double count = 0;
count = (Double) map.get("CountedQuantity");
jsonMap.put("CountedQuantity", count);
if (invItems.get((String) map.get("ItemCode"))) {
// LOG.info("Line number: " + i);
Double cantidadDisponible = 0.0;
if (stockVentas.containsKey((String) map.get("ItemCode"))) {
if (((HashMap<String, Object>) stockVentas.get((String) map.get("ItemCode"))).containsKey(destination + "_" + (String) map.get("WharehouseCode"))) {
cantidadDisponible = (Double) ((HashMap<String, Object>) stockVentas
.get((String) map.get("ItemCode"))).get(destination + "_" + (String) map.get("WharehouseCode"));
}
}
JSONArray BatchNumbers = new JSONArray();
JSONObject batchLine = new JSONObject();
batchLine.put("BatchNumber", "ventas");
batchLine.put("Quantity", count - cantidadDisponible);
batchLine.put("BaseLineNumber", i);
BatchNumbers.put(batchLine);
jsonMap.put("InventoryPostingBatchNumbers", BatchNumbers);
if (Double.valueOf((String) map.get("Price")) > 0) {
array.put(jsonMap);
i++;
}
}
}
obj.put("InventoryPostingLines", array);
if (i == 1) {
return null;
}
return obj;
}
public static List<List<HashMap<String, Object>>> splitArray(ArrayList<HashMap<String, Object>> arrayToSplit,
int chunkSize) {
if (chunkSize <= 0) {
return null; // just in case :)
}
// editado de
// https://stackoverflow.com/questions/27857011/how-to-split-a-string-array-into-small-chunk-arrays-in-java
// first we have to check if the array can be split in multiple
// arrays of equal 'chunk' size
int rest = arrayToSplit.size() % chunkSize; // if rest>0 then our last array will have less elements than the
// others
// then we check in how many arrays we can split our input array
int chunks = arrayToSplit.size() / chunkSize + (rest > 0 ? 1 : 0); // we may have to add an additional array for
// the 'rest'
// now we know how many arrays we need and create our result array
List<List<HashMap<String, Object>>> arrays = new ArrayList<List<HashMap<String, Object>>>();
// we create our resulting arrays by copying the corresponding
// part from the input array. If we have a rest (rest>0), then
// the last array will have less elements than the others. This
// needs to be handled separately, so we iterate 1 times less.
for (int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++) {
// this copies 'chunk' times 'chunkSize' elements into a new array
List<HashMap<String, Object>> array = arrayToSplit.subList(i * chunkSize, i * chunkSize + chunkSize);
arrays.add(array);
}
if (rest > 0) { // only when we have a rest
// we copy the remaining elements into the last chunk
// arrays[chunks - 1] = Arrays.copyOfRange(arrayToSplit, (chunks - 1) *
// chunkSize, (chunks - 1) * chunkSize + rest);
List<HashMap<String, Object>> array = arrayToSplit.subList((chunks - 1) * chunkSize,
(chunks - 1) * chunkSize + rest);
arrays.add(array);
}
return arrays; // that's it
}
public HashMap<String, Boolean> parseInventoryResults(ResultSet set) throws SQLException {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
while (set.next() != false) {
String ItemCode = set.getString("ItemCode");
String Inventory = set.getString("InvntItem");
if (Inventory.equals("Y")) { // Enabled
map.put(ItemCode, true);
} else // Not Enabled
{
map.put(ItemCode, false);
}
}
return map;
}
public ArrayList<HashMap<String, Object>> parseItemSelect(ResultSet set)
throws NumberFormatException, SQLException, ParseException {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
while (set.next() != false) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemCode", set.getString("ItemCode"));
map.put("WharehouseCode", set.getString("WhsCode"));
double count = 0;
count = (Double.valueOf((String) set.getString("OnHand")))
- (Double.valueOf((String) set.getString("IsCommited")))
+ (Double.valueOf((String) set.getString("OnOrder")));
map.put("CountedQuantity", Math.max(count, 0.0));
map.put("Price", set.getString("LastPurPrc"));
String date = (String) set.getString("DocDate");
int milTime = set.getInt("DocTime");
String rawTimestamp = String.format("%04d", milTime);
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HHmm");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("HH:mm");
DateTime dateTime = inputFormatter.parseDateTime(rawTimestamp);
String formattedTimestamp = outputFormatter.print(dateTime.getMillis());
LOG.info("formatted Time: " + formattedTimestamp);
// System.out.println("Time: " + formattedTimestamp);
if (date != null) {
// System.out.println(date);
// 2019-09-30 00:00:00.000000000
String time = date.substring(0, 10);
time = time + " " + formattedTimestamp + ":00.000000000";
LOG.info("Time: " + time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss.SSSSSSSSS");
Date dateObj = sdf.parse(time);
Calendar calendar = new GregorianCalendar();
calendar.setTime(dateObj);
map.put("calendar", calendar);
}
list.add(map);
}
ArrayList<HashMap<String, Object>> sortedList = DateTimeSaver.orderByDate(list);
return sortedList;
}
}
| AcquaNet/JMC-Integracion | b1_sync_stock/src/main/java/b1_sync_stock/ODBCConnector.java | 5,232 | // System.out.println(((Calendar) map.get("calendar")).getTime()); | line_comment | nl | package b1_sync_stock;
import java.io.IOException;
import java.sql.Connection;
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.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONObject;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
public class ODBCConnector extends AbstractMessageTransformer {
private static final Logger LOG = Logger.getLogger("jmc_java.log");
@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
// Define DB Login Information from FlowVars
String user = message.getInvocationProperty("DBUser");
String password = message.getInvocationProperty("DBPass");
String connectionString = message.getInvocationProperty("DBConnection");
// Create a connection manager with all the info
ODBCManager manager = new ODBCManager(user, password, connectionString);
// Connect to DB
Connection connect = manager.connect();
if (connect == null) {
return "Error Connecting to DB. Check Logs";
} else {
System.out.println("Connection to HANA successful!");
}
try {
// Create a statement to call
Statement query1St = manager.createStatement();
// Decide which database we're hitting
String destination = message.getInvocationProperty("Destination");
String origin = message.getInvocationProperty("Origin");
String fullDestination = destination;
String warehouseMatch = message.getInvocationProperty("warehouseMatch");
HashMap<String, String> destinationMap = message.getInvocationProperty("TableDestinations");
// Check which Items are Inventory enabled from Destination and Holding
String query1 = "SELECT \"ItemCode\",\"InvntItem\" FROM " + destination + ".OITM";
String query2 = "SELECT \"ItemCode\",\"InvntItem\" FROM " + origin + ".OITM";
LOG.info("Item Info Q: " + query1);
LOG.info("Item Info Q2: " + query2);
ResultSet stockEnabled = query1St.executeQuery(query1);
// Save a HashMap of all the Items that are inventory enabled
HashMap<String, Boolean> invItems = parseInventoryResults(stockEnabled);
Statement query2St = manager.createStatement();
ResultSet stockEnabledHolding = query2St.executeQuery(query2);
String queryLote = "SELECT \"ItemCode\", \"WhsCode\", \"OnHand\" FROM "
+ origin + ".OITW WHERE \"WhsCode\" in " + warehouseMatch + ""
+ " AND \"OnHand\" > 0";
LOG.info("Item Count Q: "+queryLote);
Statement queryLoteSt = manager.createStatement();
ResultSet parseStockLoteVentas = queryLoteSt.executeQuery(queryLote);
// Save a HashMap of all the Items that are inventory enabled
HashMap<String, Boolean> invItemsHolding = parseInventoryResults(stockEnabledHolding);
HashMap<String, Object> stockLoteVentas = parseStockLoteVentas(parseStockLoteVentas);
// Dont syncronize if the item is not enabled in holding, will cause an error.
// Also, if the item doesnt exist
for (String val : invItems.keySet()) {
if (invItems.get(val)) { // Dont bother if item is not set to syncronzie anyway
if (invItemsHolding.containsKey(val)) { // Check if item exists in holding
if (!invItemsHolding.get(val)) { // Check if item is enabled in holding
invItems.put(val, false);
}
} else {
invItems.put(val, false);
}
}
}
// for (String value : invItemsHolding.keySet()) {
// if (invItems.get(value)) {
// //LOG.info("Disabled from holding: "+value);
// }
// }
// Get the last updated Date YYYY-MM-DD
String updateDate = message.getInvocationProperty("updateDate");
String updateTime = message.getInvocationProperty("updateTime");
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HH-mm-ss");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("HHmm");
DateTime dateTime = inputFormatter.parseDateTime(updateTime);
String formattedUpdateTime = outputFormatter.print(dateTime.getMillis());
// Get all Item Stocks from DB
// Full STR
// https://stackoverflow.com/questions/58507324/filtering-out-duplicate-entires-for-older-rows
// SELECT * FROM (SELECT T0.\"ItemCode\", T0.\"WhsCode\", T0.\"OnHand\",
// T0.\"IsCommited\", T0.\"OnOrder\", T1.\"DocDate\", T1.\"DocTime\",
// ROW_NUMBER() OVER (PARTITION BY T0.\"ItemCode\" ORDER BY T1.\"DocTime\" DESC)
// AS RN FROM KA_DEV6.OITW T0JOIN KA_DEV6.OINM T1 ON T0.\"WhsCode\" = '01' AND
// T0.\"ItemCode\" = T1.\"ItemCode\" WHERE T1.\"DocDate\" > '2019-10-20' OR
// (T1.\"DocDate\" = '2019-10-20' AND T1.\"DocTime\" >= '1025')) X WHERE RN = 1
String str = "SELECT * FROM " + "("
+ "SELECT T0.\"ItemCode\", T0.\"WhsCode\", T0.\"OnHand\", T0.\"IsCommited\", T0.\"OnOrder\", T1.\"DocDate\", T1.\"DocTime\", T2.\"LastPurPrc\", "
+ " ROW_NUMBER() OVER (PARTITION BY T0.\"ItemCode\" "
+ "ORDER BY T1.\"DocDate\",T1.\"DocTime\" DESC) AS RN " + "FROM " + destination + ".OITW T0 JOIN "
+ destination + ".OINM T1 " + "ON T0.\"WhsCode\" = '01' AND T0.\"ItemCode\" = T1.\"ItemCode\" "
+ "JOIN " + destination + ".OITM T2 ON T0.\"ItemCode\" = T2.\"ItemCode\" "
+ "WHERE T1.\"DocDate\" > '" + updateDate + "' OR (T1.\"DocDate\" = '" + updateDate
+ "' AND T1.\"DocTime\" >= '" + formattedUpdateTime + "')" + ") X WHERE RN = 1 "
+ "ORDER BY \"DocDate\", \"DocTime\" DESC";
LOG.info("Query: " + str);
ResultSet Items = manager.executeQuery(str);
// Parse results as array list ordered by date from oldest (top) to newest
// (bottom)
ArrayList<HashMap<String, Object>> results = parseItemSelect(Items);
HashMap<String, String> newest = getNewestDate(results);
if (newest != null) {
try {
CurrentTimeSaver.setUpdateTime("STOCK_" + destination, newest.get("Time"), newest.get("Date"));
} catch (IOException e) {
e.printStackTrace();
}
}
destination = destinationMap.get(destination);
String UoMEntryQuery = "SELECT \"IUoMEntry\",\"ItemCode\" FROM " + fullDestination + ".OITM";
// System.out.println("Query: " + UoMEntryQuery);
ResultSet querySet = manager.executeQuery(UoMEntryQuery);
HashMap<String, Integer> UoMEntryCodes = parseUoMList(querySet);
String UoMCodeQuery = "SELECT \"UomCode\", \"UomEntry\" FROM " + fullDestination + ".OUOM";
System.out.println("Query: " + UoMCodeQuery);
ResultSet UoMCodeSet = manager.executeQuery(UoMCodeQuery);
HashMap<Integer, String> UoMCode = parseUoMCodeList(UoMCodeSet);
// LOG.info("Parsing done!");
HashMap<String, String> UoMCodeTable = new HashMap<>();
for (String invCode : UoMEntryCodes.keySet()) {
UoMCodeTable.put(invCode, UoMCode.get(UoMEntryCodes.get(invCode)));
}
ArrayList<HashMap<String, Object>> resultsWithUoM = parseItemSelect(Items);
for (HashMap<String, Object> itemMap : results) {
if (UoMEntryCodes.get((String) itemMap.get("ItemCode")) != -1) {
itemMap.put("UoMCode", UoMCodeTable.get(itemMap.get("ItemCode")));
// System.out.println("ItemCode: " + itemMap.get("ItemCode") + " - "+
// UoMCodeTable.get(itemMap.get("ItemCode")));
resultsWithUoM.add(itemMap);
} else {
resultsWithUoM.add(itemMap);
}
}
// Create a hashmap to hold the arraylist
LOG.info("Total results: " + resultsWithUoM.size());
// System.out.println(message);
LOG.info("Result returned!");
// LOG.info(""+StringToJSON.javaToJSONToString(result));
List<List<HashMap<String, Object>>> arraySplit = splitArray(resultsWithUoM, 300);
ArrayList<String> Documents = new ArrayList<String>();
for (List<HashMap<String, Object>> array : arraySplit) {
JSONObject doc = arrayToDocument(array, destination, invItems, stockLoteVentas);
if (doc != null) {
Documents.add(doc.toString());
}
}
return Documents;
} catch (SQLException | NumberFormatException | ParseException e) {
e.printStackTrace();
return e;
}
}
private HashMap<String, Object> parseStockLoteVentas(ResultSet set) throws SQLException {
HashMap<String, Object> cantidadStock = new HashMap<>();
while (set.next() != false) {
if (cantidadStock.containsKey(set.getString("ItemCode"))) {
HashMap<String, Object> stockMap = (HashMap<String, Object>) cantidadStock
.get(set.getString("ItemCode"));
stockMap.put(set.getString("WhsCode"), set.getDouble("OnHand"));
cantidadStock.put(set.getString("ItemCode"), stockMap);
} else {
HashMap<String, Object> stockMap = new HashMap<>();
stockMap.put(set.getString("WhsCode"), set.getDouble("OnHand"));
cantidadStock.put(set.getString("ItemCode"), stockMap);
}
}
return cantidadStock;
}
public HashMap<String, Integer> parseUoMList(ResultSet set) throws SQLException {
int rows = 0;
HashMap<String, Integer> results = new HashMap<>();
while (set.next() != false) {
results.put(set.getString("ItemCode"), set.getInt("IUoMEntry"));
// System.out.println(rowResult);
rows++;
}
if (rows == 0) {
return null;
}
return results;
}
public HashMap<Integer, String> parseUoMCodeList(ResultSet set) throws SQLException {
int rows = 0;
HashMap<Integer, String> results = new HashMap<>();
while (set.next() != false) {
results.put(set.getInt("UomEntry"), set.getString("UomCode"));
// System.out.println(rowResult);
rows++;
}
if (rows == 0) {
return null;
}
return results;
}
public static HashMap<String, String> getNewestDate(ArrayList<HashMap<String, Object>> results) {
Calendar cal = null;
for (HashMap<String, Object> map : results) {
Calendar calendar = (Calendar) map.get("calendar");
if (cal != null) {
if (calendar.after(cal)) {
cal = calendar;
LOG.info("Date " + getDateFromCalendar(calendar) + " is newer than " + getDateFromCalendar(cal));
}
} else {
cal = calendar;
LOG.info("Date doesnt exist, date set: " + getDateFromCalendar(calendar));
LOG.info("Time doesnt exist, date set: " + getTimeFromCalendar(calendar));
}
}
if (cal == null) {
return null;
}
HashMap<String, String> returnInfo = new HashMap<>();
returnInfo.put("Date", getDateFromCalendar(cal));
returnInfo.put("Time", getTimeFromCalendar(cal));
LOG.info(returnInfo.toString());
return returnInfo;
}
public static String getTimeFromCalendar(Calendar cal) {
LOG.info("Hour: " + cal.get(Calendar.HOUR_OF_DAY));
LOG.info("Minute: " + (cal.get(Calendar.MINUTE)));
LOG.info("FormatH: " + String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)));
return String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)) + "-"
+ String.format("%02d", (cal.get(Calendar.MINUTE))) + "-" + "00";
}
public static String getDateFromCalendar(Calendar cal) {
return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH);
}
@SuppressWarnings("unchecked")
public static JSONObject arrayToDocument(List<HashMap<String, Object>> inputArray, String destination,
HashMap<String, Boolean> invItems, HashMap<String, Object> stockVentas) {
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
LOG.info("New Document");
int i = 1;
for (HashMap<String, Object> map : inputArray) {
// Syste<SUF>
JSONObject jsonMap = new JSONObject();
jsonMap.put("LineNumber", i);
jsonMap.put("ItemCode", (String) map.get("ItemCode"));
if (map.get("UoMCode") != null) {
jsonMap.put("UoMCode", (String) map.get("UoMCode"));
}
jsonMap.put("Price", map.get("Price"));
jsonMap.put("WarehouseCode", destination + "_" + (String) map.get("WharehouseCode"));
double count = 0;
count = (Double) map.get("CountedQuantity");
jsonMap.put("CountedQuantity", count);
if (invItems.get((String) map.get("ItemCode"))) {
// LOG.info("Line number: " + i);
Double cantidadDisponible = 0.0;
if (stockVentas.containsKey((String) map.get("ItemCode"))) {
if (((HashMap<String, Object>) stockVentas.get((String) map.get("ItemCode"))).containsKey(destination + "_" + (String) map.get("WharehouseCode"))) {
cantidadDisponible = (Double) ((HashMap<String, Object>) stockVentas
.get((String) map.get("ItemCode"))).get(destination + "_" + (String) map.get("WharehouseCode"));
}
}
JSONArray BatchNumbers = new JSONArray();
JSONObject batchLine = new JSONObject();
batchLine.put("BatchNumber", "ventas");
batchLine.put("Quantity", count - cantidadDisponible);
batchLine.put("BaseLineNumber", i);
BatchNumbers.put(batchLine);
jsonMap.put("InventoryPostingBatchNumbers", BatchNumbers);
if (Double.valueOf((String) map.get("Price")) > 0) {
array.put(jsonMap);
i++;
}
}
}
obj.put("InventoryPostingLines", array);
if (i == 1) {
return null;
}
return obj;
}
public static List<List<HashMap<String, Object>>> splitArray(ArrayList<HashMap<String, Object>> arrayToSplit,
int chunkSize) {
if (chunkSize <= 0) {
return null; // just in case :)
}
// editado de
// https://stackoverflow.com/questions/27857011/how-to-split-a-string-array-into-small-chunk-arrays-in-java
// first we have to check if the array can be split in multiple
// arrays of equal 'chunk' size
int rest = arrayToSplit.size() % chunkSize; // if rest>0 then our last array will have less elements than the
// others
// then we check in how many arrays we can split our input array
int chunks = arrayToSplit.size() / chunkSize + (rest > 0 ? 1 : 0); // we may have to add an additional array for
// the 'rest'
// now we know how many arrays we need and create our result array
List<List<HashMap<String, Object>>> arrays = new ArrayList<List<HashMap<String, Object>>>();
// we create our resulting arrays by copying the corresponding
// part from the input array. If we have a rest (rest>0), then
// the last array will have less elements than the others. This
// needs to be handled separately, so we iterate 1 times less.
for (int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++) {
// this copies 'chunk' times 'chunkSize' elements into a new array
List<HashMap<String, Object>> array = arrayToSplit.subList(i * chunkSize, i * chunkSize + chunkSize);
arrays.add(array);
}
if (rest > 0) { // only when we have a rest
// we copy the remaining elements into the last chunk
// arrays[chunks - 1] = Arrays.copyOfRange(arrayToSplit, (chunks - 1) *
// chunkSize, (chunks - 1) * chunkSize + rest);
List<HashMap<String, Object>> array = arrayToSplit.subList((chunks - 1) * chunkSize,
(chunks - 1) * chunkSize + rest);
arrays.add(array);
}
return arrays; // that's it
}
public HashMap<String, Boolean> parseInventoryResults(ResultSet set) throws SQLException {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
while (set.next() != false) {
String ItemCode = set.getString("ItemCode");
String Inventory = set.getString("InvntItem");
if (Inventory.equals("Y")) { // Enabled
map.put(ItemCode, true);
} else // Not Enabled
{
map.put(ItemCode, false);
}
}
return map;
}
public ArrayList<HashMap<String, Object>> parseItemSelect(ResultSet set)
throws NumberFormatException, SQLException, ParseException {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
while (set.next() != false) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemCode", set.getString("ItemCode"));
map.put("WharehouseCode", set.getString("WhsCode"));
double count = 0;
count = (Double.valueOf((String) set.getString("OnHand")))
- (Double.valueOf((String) set.getString("IsCommited")))
+ (Double.valueOf((String) set.getString("OnOrder")));
map.put("CountedQuantity", Math.max(count, 0.0));
map.put("Price", set.getString("LastPurPrc"));
String date = (String) set.getString("DocDate");
int milTime = set.getInt("DocTime");
String rawTimestamp = String.format("%04d", milTime);
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HHmm");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("HH:mm");
DateTime dateTime = inputFormatter.parseDateTime(rawTimestamp);
String formattedTimestamp = outputFormatter.print(dateTime.getMillis());
LOG.info("formatted Time: " + formattedTimestamp);
// System.out.println("Time: " + formattedTimestamp);
if (date != null) {
// System.out.println(date);
// 2019-09-30 00:00:00.000000000
String time = date.substring(0, 10);
time = time + " " + formattedTimestamp + ":00.000000000";
LOG.info("Time: " + time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss.SSSSSSSSS");
Date dateObj = sdf.parse(time);
Calendar calendar = new GregorianCalendar();
calendar.setTime(dateObj);
map.put("calendar", calendar);
}
list.add(map);
}
ArrayList<HashMap<String, Object>> sortedList = DateTimeSaver.orderByDate(list);
return sortedList;
}
}
|
26807_26 | /*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.impl.util.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONObject, and to covert a JSONObject into an XML text.
*
* @version 2009-12-12
*/
public class XML {
/** The Character '&'. */
public static final Character AMP = Character.valueOf('&');
/** The Character '''. */
public static final Character APOS = Character.valueOf('\'');
/** The Character '!'. */
public static final Character BANG = Character.valueOf('!');
/** The Character '='. */
public static final Character EQ = Character.valueOf('=');
/** The Character '>'. */
public static final Character GT = Character.valueOf('>');
/** The Character '<'. */
public static final Character LT = Character.valueOf('<');
/** The Character '?'. */
public static final Character QUEST = Character.valueOf('?');
/** The Character '"'. */
public static final Character QUOT = Character.valueOf('"');
/** The Character '/'. */
public static final Character SLASH = Character.valueOf('/');
/**
* Replace special characters with XML escapes:
*
* <pre>
* & <small>(ampersand)</small> is replaced by &amp;
* < <small>(less than)</small> is replaced by &lt;
* > <small>(greater than)</small> is replaced by &gt;
* " <small>(double quote)</small> is replaced by &quot;
* </pre>
*
* @param string
* The string to be escaped.
* @return The escaped string.
*/
public static String escape(String string) {
StringBuilder sb = new StringBuilder();
for (int i = 0, len = string.length(); i < len; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* Throw an exception if the string contains whitespace. Whitespace is not allowed in tagNames and attributes.
*
* @param string
* @throws JSONException
*/
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string + "' contains a space character.");
}
}
}
/**
* Scan the content following the named tag, attaching it to the context.
*
* @param x
* The XMLTokener containing the source string.
* @param context
* The JSONObject that will include the new material.
* @param name
* The tag name.
* @return true if the close tag is processed.
* @throws JSONException
*/
private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException {
char c;
int i;
String n;
JSONObject o = null;
String s;
Object t;
// Test for and skip past these forms:
// <!-- ... -->
// <! ... >
// <![ ... ]]>
// <? ... ?>
// Report errors for these forms:
// <>
// <=
// <<
t = x.nextToken();
// <!
if (t == BANG) {
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
return false;
}
x.back();
} else if (c == '[') {
t = x.nextToken();
if (t.equals("CDATA")) {
if (x.next() == '[') {
s = x.nextCDATA();
if (s.length() > 0) {
context.accumulate("content", s);
}
return false;
}
}
throw x.syntaxError("Expected 'CDATA['");
}
i = 1;
do {
t = x.nextMeta();
if (t == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (t == LT) {
i += 1;
} else if (t == GT) {
i -= 1;
}
} while (i > 0);
return false;
} else if (t == QUEST) {
// <?
x.skipPast("?>");
return false;
} else if (t == SLASH) {
// Close tag </
t = x.nextToken();
if (name == null) {
throw x.syntaxError("Mismatched close tag" + t);
}
if (!t.equals(name)) {
throw x.syntaxError("Mismatched " + name + " and " + t);
}
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped close tag");
}
return true;
} else if (t instanceof Character) {
throw x.syntaxError("Misshaped tag");
// Open tag <
} else {
n = (String) t;
t = null;
o = new JSONObject();
for (;;) {
if (t == null) {
t = x.nextToken();
}
// attribute = value
if (t instanceof String) {
s = (String) t;
t = x.nextToken();
if (t == EQ) {
t = x.nextToken();
if (!(t instanceof String)) {
throw x.syntaxError("Missing value");
}
o.accumulate(s, JSONObject.stringToValue((String) t));
t = null;
} else {
o.accumulate(s, "");
}
// Empty tag <.../>
} else if (t == SLASH) {
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag");
}
context.accumulate(n, "");
return false;
// Content, between <...> and </...>
} else if (t == GT) {
for (;;) {
t = x.nextContent();
if (t == null) {
if (n != null) {
throw x.syntaxError("Unclosed tag " + n);
}
return false;
} else if (t instanceof String) {
s = (String) t;
if (s.length() > 0) {
o.accumulate("content", JSONObject.stringToValue(s));
}
// Nested element
} else if (t == LT) {
if (parse(x, o, n)) {
if (o.length() == 0) {
context.accumulate(n, "");
} else if (o.length() == 1 && o.opt("content") != null) {
context.accumulate(n, o.opt("content"));
} else {
context.accumulate(n, o);
}
return false;
}
}
}
} else {
throw x.syntaxError("Misshaped tag");
}
}
}
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a JSONObject. Some information may be lost in this transformation because JSON is a signalData format and XML is a document
* format. XML uses elements, attributes, and content text, while JSON uses unordered collections of name/value pairs and arrays of values. JSON does not does not like to distinguish between
* elements and attributes. Sequences of similar elements are represented as JSONArrays. Content text may be placed in a "content" member. Comments, prologs, DTDs, and <code><[ [ ]]></code> are
* ignored.
*
* @param string
* The source string.
* @return A JSONObject containing the structured signalData from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject o = new JSONObject();
XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) {
parse(x, o, null);
}
return o;
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param o
* A JSONObject.
* @return A string.
* @throws JSONException
*/
public static String toString(Object o) throws JSONException {
return toString(o, null);
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param o
* A JSONObject.
* @param tagName
* The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object o, String tagName) throws JSONException {
StringBuilder b = new StringBuilder();
int i;
JSONArray ja;
JSONObject jo;
String k;
Iterator keys;
int len;
String s;
Object v;
if (o instanceof JSONObject) {
// Emit <tagName>
if (tagName != null) {
b.append('<');
b.append(tagName);
b.append('>');
}
// Loop thru the keys.
jo = (JSONObject) o;
keys = jo.keys();
while (keys.hasNext()) {
k = keys.next().toString();
v = jo.opt(k);
if (v == null) {
v = "";
}
if (v instanceof String) {
s = (String) v;
} else {
s = null;
}
// Emit content in body
if (k.equals("content")) {
if (v instanceof JSONArray) {
ja = (JSONArray) v;
len = ja.length();
for (i = 0; i < len; i += 1) {
if (i > 0) {
b.append('\n');
}
b.append(escape(ja.get(i).toString()));
}
} else {
b.append(escape(v.toString()));
}
// Emit an array of similar keys
} else if (v instanceof JSONArray) {
ja = (JSONArray) v;
len = ja.length();
for (i = 0; i < len; i += 1) {
v = ja.get(i);
if (v instanceof JSONArray) {
b.append('<');
b.append(k);
b.append('>');
b.append(toString(v));
b.append("</");
b.append(k);
b.append('>');
} else {
b.append(toString(v, k));
}
}
} else if (v.equals("")) {
b.append('<');
b.append(k);
b.append("/>");
// Emit a new tag <k>
} else {
b.append(toString(v, k));
}
}
if (tagName != null) {
// Emit the </tagname> close tag
b.append("</");
b.append(tagName);
b.append('>');
}
return b.toString();
// XML does not have good support for arrays. If an array appears in
// a place
// where XML is lacking, synthesize an <array> element.
} else if (o instanceof JSONArray) {
ja = (JSONArray) o;
len = ja.length();
for (i = 0; i < len; ++i) {
v = ja.opt(i);
b.append(toString(v, (tagName == null) ? "array" : tagName));
}
return b.toString();
} else {
s = (o == null) ? "null" : escape(o.toString());
return (tagName == null) ? "\"" + s + "\"" : (s.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + s + "</" + tagName + ">";
}
}
}
| Activiti/Activiti | activiti-core/activiti-engine/src/main/java/org/activiti/engine/impl/util/json/XML.java | 3,513 | // Nested element | line_comment | nl | /*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.impl.util.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONObject, and to covert a JSONObject into an XML text.
*
* @version 2009-12-12
*/
public class XML {
/** The Character '&'. */
public static final Character AMP = Character.valueOf('&');
/** The Character '''. */
public static final Character APOS = Character.valueOf('\'');
/** The Character '!'. */
public static final Character BANG = Character.valueOf('!');
/** The Character '='. */
public static final Character EQ = Character.valueOf('=');
/** The Character '>'. */
public static final Character GT = Character.valueOf('>');
/** The Character '<'. */
public static final Character LT = Character.valueOf('<');
/** The Character '?'. */
public static final Character QUEST = Character.valueOf('?');
/** The Character '"'. */
public static final Character QUOT = Character.valueOf('"');
/** The Character '/'. */
public static final Character SLASH = Character.valueOf('/');
/**
* Replace special characters with XML escapes:
*
* <pre>
* & <small>(ampersand)</small> is replaced by &amp;
* < <small>(less than)</small> is replaced by &lt;
* > <small>(greater than)</small> is replaced by &gt;
* " <small>(double quote)</small> is replaced by &quot;
* </pre>
*
* @param string
* The string to be escaped.
* @return The escaped string.
*/
public static String escape(String string) {
StringBuilder sb = new StringBuilder();
for (int i = 0, len = string.length(); i < len; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* Throw an exception if the string contains whitespace. Whitespace is not allowed in tagNames and attributes.
*
* @param string
* @throws JSONException
*/
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string + "' contains a space character.");
}
}
}
/**
* Scan the content following the named tag, attaching it to the context.
*
* @param x
* The XMLTokener containing the source string.
* @param context
* The JSONObject that will include the new material.
* @param name
* The tag name.
* @return true if the close tag is processed.
* @throws JSONException
*/
private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException {
char c;
int i;
String n;
JSONObject o = null;
String s;
Object t;
// Test for and skip past these forms:
// <!-- ... -->
// <! ... >
// <![ ... ]]>
// <? ... ?>
// Report errors for these forms:
// <>
// <=
// <<
t = x.nextToken();
// <!
if (t == BANG) {
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
return false;
}
x.back();
} else if (c == '[') {
t = x.nextToken();
if (t.equals("CDATA")) {
if (x.next() == '[') {
s = x.nextCDATA();
if (s.length() > 0) {
context.accumulate("content", s);
}
return false;
}
}
throw x.syntaxError("Expected 'CDATA['");
}
i = 1;
do {
t = x.nextMeta();
if (t == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (t == LT) {
i += 1;
} else if (t == GT) {
i -= 1;
}
} while (i > 0);
return false;
} else if (t == QUEST) {
// <?
x.skipPast("?>");
return false;
} else if (t == SLASH) {
// Close tag </
t = x.nextToken();
if (name == null) {
throw x.syntaxError("Mismatched close tag" + t);
}
if (!t.equals(name)) {
throw x.syntaxError("Mismatched " + name + " and " + t);
}
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped close tag");
}
return true;
} else if (t instanceof Character) {
throw x.syntaxError("Misshaped tag");
// Open tag <
} else {
n = (String) t;
t = null;
o = new JSONObject();
for (;;) {
if (t == null) {
t = x.nextToken();
}
// attribute = value
if (t instanceof String) {
s = (String) t;
t = x.nextToken();
if (t == EQ) {
t = x.nextToken();
if (!(t instanceof String)) {
throw x.syntaxError("Missing value");
}
o.accumulate(s, JSONObject.stringToValue((String) t));
t = null;
} else {
o.accumulate(s, "");
}
// Empty tag <.../>
} else if (t == SLASH) {
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag");
}
context.accumulate(n, "");
return false;
// Content, between <...> and </...>
} else if (t == GT) {
for (;;) {
t = x.nextContent();
if (t == null) {
if (n != null) {
throw x.syntaxError("Unclosed tag " + n);
}
return false;
} else if (t instanceof String) {
s = (String) t;
if (s.length() > 0) {
o.accumulate("content", JSONObject.stringToValue(s));
}
// Neste<SUF>
} else if (t == LT) {
if (parse(x, o, n)) {
if (o.length() == 0) {
context.accumulate(n, "");
} else if (o.length() == 1 && o.opt("content") != null) {
context.accumulate(n, o.opt("content"));
} else {
context.accumulate(n, o);
}
return false;
}
}
}
} else {
throw x.syntaxError("Misshaped tag");
}
}
}
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a JSONObject. Some information may be lost in this transformation because JSON is a signalData format and XML is a document
* format. XML uses elements, attributes, and content text, while JSON uses unordered collections of name/value pairs and arrays of values. JSON does not does not like to distinguish between
* elements and attributes. Sequences of similar elements are represented as JSONArrays. Content text may be placed in a "content" member. Comments, prologs, DTDs, and <code><[ [ ]]></code> are
* ignored.
*
* @param string
* The source string.
* @return A JSONObject containing the structured signalData from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject o = new JSONObject();
XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) {
parse(x, o, null);
}
return o;
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param o
* A JSONObject.
* @return A string.
* @throws JSONException
*/
public static String toString(Object o) throws JSONException {
return toString(o, null);
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
* @param o
* A JSONObject.
* @param tagName
* The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object o, String tagName) throws JSONException {
StringBuilder b = new StringBuilder();
int i;
JSONArray ja;
JSONObject jo;
String k;
Iterator keys;
int len;
String s;
Object v;
if (o instanceof JSONObject) {
// Emit <tagName>
if (tagName != null) {
b.append('<');
b.append(tagName);
b.append('>');
}
// Loop thru the keys.
jo = (JSONObject) o;
keys = jo.keys();
while (keys.hasNext()) {
k = keys.next().toString();
v = jo.opt(k);
if (v == null) {
v = "";
}
if (v instanceof String) {
s = (String) v;
} else {
s = null;
}
// Emit content in body
if (k.equals("content")) {
if (v instanceof JSONArray) {
ja = (JSONArray) v;
len = ja.length();
for (i = 0; i < len; i += 1) {
if (i > 0) {
b.append('\n');
}
b.append(escape(ja.get(i).toString()));
}
} else {
b.append(escape(v.toString()));
}
// Emit an array of similar keys
} else if (v instanceof JSONArray) {
ja = (JSONArray) v;
len = ja.length();
for (i = 0; i < len; i += 1) {
v = ja.get(i);
if (v instanceof JSONArray) {
b.append('<');
b.append(k);
b.append('>');
b.append(toString(v));
b.append("</");
b.append(k);
b.append('>');
} else {
b.append(toString(v, k));
}
}
} else if (v.equals("")) {
b.append('<');
b.append(k);
b.append("/>");
// Emit a new tag <k>
} else {
b.append(toString(v, k));
}
}
if (tagName != null) {
// Emit the </tagname> close tag
b.append("</");
b.append(tagName);
b.append('>');
}
return b.toString();
// XML does not have good support for arrays. If an array appears in
// a place
// where XML is lacking, synthesize an <array> element.
} else if (o instanceof JSONArray) {
ja = (JSONArray) o;
len = ja.length();
for (i = 0; i < len; ++i) {
v = ja.opt(i);
b.append(toString(v, (tagName == null) ? "array" : tagName));
}
return b.toString();
} else {
s = (o == null) ? "null" : escape(o.toString());
return (tagName == null) ? "\"" + s + "\"" : (s.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + s + "</" + tagName + ">";
}
}
}
|
109505_11 | package org.adaway.ui.hosts;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import org.adaway.R;
import org.adaway.db.entity.HostsSource;
import java.time.Duration;
import java.time.ZonedDateTime;
/**
* This class is a the {@link RecyclerView.Adapter} for the hosts sources view.
*
* @author Bruce BUJON (bruce.bujon(at)gmail(dot)com)
*/
class HostsSourcesAdapter extends ListAdapter<HostsSource, HostsSourcesAdapter.ViewHolder> {
/**
* This callback is use to compare hosts sources.
*/
private static final DiffUtil.ItemCallback<HostsSource> DIFF_CALLBACK =
new DiffUtil.ItemCallback<HostsSource>() {
@Override
public boolean areItemsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) {
return oldSource.getUrl().equals(newSource.getUrl());
}
@Override
public boolean areContentsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) {
// NOTE: if you use equals, your object must properly override Object#equals()
// Incorrectly returning false here will result in too many animations.
return oldSource.equals(newSource);
}
};
/**
* This callback is use to call view actions.
*/
@NonNull
private final HostsSourcesViewCallback viewCallback;
private static final String[] QUANTITY_PREFIXES = new String[]{"k", "M", "G"};
/**
* Constructor.
*
* @param viewCallback The view callback.
*/
HostsSourcesAdapter(@NonNull HostsSourcesViewCallback viewCallback) {
super(DIFF_CALLBACK);
this.viewCallback = viewCallback;
}
/**
* Get the approximate delay from a date to now.
*
* @param context The application context.
* @param from The date from which computes the delay.
* @return The approximate delay.
*/
private static String getApproximateDelay(Context context, ZonedDateTime from) {
// Get resource for plurals
Resources resources = context.getResources();
// Get current date in UTC timezone
ZonedDateTime now = ZonedDateTime.now();
// Get delay between from and now in minutes
long delay = Duration.between(from, now).toMinutes();
// Check if delay is lower than an hour
if (delay < 60) {
return resources.getString(R.string.hosts_source_few_minutes);
}
// Get delay in hours
delay /= 60;
// Check if delay is lower than a day
if (delay < 24) {
int hours = (int) delay;
return resources.getQuantityString(R.plurals.hosts_source_hours, hours, hours);
}
// Get delay in days
delay /= 24;
// Check if delay is lower than a month
if (delay < 30) {
int days = (int) delay;
return resources.getQuantityString(R.plurals.hosts_source_days, days, days);
}
// Get delay in months
int months = (int) delay / 30;
return resources.getQuantityString(R.plurals.hosts_source_months, months, months);
}
@NonNull
@Override
public HostsSourcesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.hosts_sources_card, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
HostsSource source = this.getItem(position);
holder.enabledCheckBox.setChecked(source.isEnabled());
holder.enabledCheckBox.setOnClickListener(view -> viewCallback.toggleEnabled(source));
holder.labelTextView.setText(source.getLabel());
holder.urlTextView.setText(source.getUrl());
holder.updateTextView.setText(getUpdateText(source));
holder.sizeTextView.setText(getHostCount(source));
holder.itemView.setOnClickListener(view -> viewCallback.edit(source));
}
private String getUpdateText(HostsSource source) {
// Get context
Context context = this.viewCallback.getContext();
// Check if source is enabled
if (!source.isEnabled()) {
return context.getString(R.string.hosts_source_disabled);
}
// Check modification dates
boolean lastOnlineModificationDefined = source.getOnlineModificationDate() != null;
boolean lastLocalModificationDefined = source.getLocalModificationDate() != null;
// Declare update text
String updateText;
// Check if last online modification date is known
if (lastOnlineModificationDefined) {
// Get last online modification delay
String approximateDelay = getApproximateDelay(context, source.getOnlineModificationDate());
if (!lastLocalModificationDefined) {
updateText = context.getString(R.string.hosts_source_last_update, approximateDelay);
} else if (source.getOnlineModificationDate().isAfter(source.getLocalModificationDate())) {
updateText = context.getString(R.string.hosts_source_need_update, approximateDelay);
} else {
updateText = context.getString(R.string.hosts_source_up_to_date, approximateDelay);
}
} else {
if (lastLocalModificationDefined) {
String approximateDelay = getApproximateDelay(context, source.getLocalModificationDate());
updateText = context.getString(R.string.hosts_source_installed, approximateDelay);
} else {
updateText = context.getString(R.string.hosts_source_unknown_status);
}
}
return updateText;
}
private String getHostCount(HostsSource source) {
// Note: NumberFormat.getCompactNumberInstance is Java 12 only
// Check empty source
int size = source.getSize();
if (size <= 0 || !source.isEnabled()) {
return "";
}
// Compute size decimal length
int length = 1;
while (size > 10) {
size /= 10;
length++;
}
// Compute prefix to use
int prefixIndex = (length - 1) / 3 - 1;
// Return formatted count
Context context = this.viewCallback.getContext();
size = source.getSize();
if (prefixIndex < 0) {
return context.getString(R.string.hosts_count, Integer.toString(size));
} else if (prefixIndex >= QUANTITY_PREFIXES.length) {
prefixIndex = QUANTITY_PREFIXES.length - 1;
size = 13;
}
size = Math.toIntExact(Math.round(size / Math.pow(10, (prefixIndex + 1) * 3D)));
return context.getString(R.string.hosts_count, size + QUANTITY_PREFIXES[prefixIndex]);
}
/**
* This class is a the {@link RecyclerView.ViewHolder} for the hosts sources view.
*
* @author Bruce BUJON (bruce.bujon(at)gmail(dot)com)
*/
static class ViewHolder extends RecyclerView.ViewHolder {
final CheckBox enabledCheckBox;
final TextView labelTextView;
final TextView urlTextView;
final TextView updateTextView;
final TextView sizeTextView;
/**
* Constructor.
*
* @param itemView The hosts sources view.
*/
ViewHolder(View itemView) {
super(itemView);
this.enabledCheckBox = itemView.findViewById(R.id.sourceEnabledCheckBox);
this.labelTextView = itemView.findViewById(R.id.sourceLabelTextView);
this.urlTextView = itemView.findViewById(R.id.sourceUrlTextView);
this.updateTextView = itemView.findViewById(R.id.sourceUpdateTextView);
this.sizeTextView = itemView.findViewById(R.id.sourceSizeTextView);
}
}
}
| AdAway/AdAway | app/src/main/java/org/adaway/ui/hosts/HostsSourcesAdapter.java | 2,015 | // Get delay in hours | line_comment | nl | package org.adaway.ui.hosts;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import org.adaway.R;
import org.adaway.db.entity.HostsSource;
import java.time.Duration;
import java.time.ZonedDateTime;
/**
* This class is a the {@link RecyclerView.Adapter} for the hosts sources view.
*
* @author Bruce BUJON (bruce.bujon(at)gmail(dot)com)
*/
class HostsSourcesAdapter extends ListAdapter<HostsSource, HostsSourcesAdapter.ViewHolder> {
/**
* This callback is use to compare hosts sources.
*/
private static final DiffUtil.ItemCallback<HostsSource> DIFF_CALLBACK =
new DiffUtil.ItemCallback<HostsSource>() {
@Override
public boolean areItemsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) {
return oldSource.getUrl().equals(newSource.getUrl());
}
@Override
public boolean areContentsTheSame(@NonNull HostsSource oldSource, @NonNull HostsSource newSource) {
// NOTE: if you use equals, your object must properly override Object#equals()
// Incorrectly returning false here will result in too many animations.
return oldSource.equals(newSource);
}
};
/**
* This callback is use to call view actions.
*/
@NonNull
private final HostsSourcesViewCallback viewCallback;
private static final String[] QUANTITY_PREFIXES = new String[]{"k", "M", "G"};
/**
* Constructor.
*
* @param viewCallback The view callback.
*/
HostsSourcesAdapter(@NonNull HostsSourcesViewCallback viewCallback) {
super(DIFF_CALLBACK);
this.viewCallback = viewCallback;
}
/**
* Get the approximate delay from a date to now.
*
* @param context The application context.
* @param from The date from which computes the delay.
* @return The approximate delay.
*/
private static String getApproximateDelay(Context context, ZonedDateTime from) {
// Get resource for plurals
Resources resources = context.getResources();
// Get current date in UTC timezone
ZonedDateTime now = ZonedDateTime.now();
// Get delay between from and now in minutes
long delay = Duration.between(from, now).toMinutes();
// Check if delay is lower than an hour
if (delay < 60) {
return resources.getString(R.string.hosts_source_few_minutes);
}
// Get d<SUF>
delay /= 60;
// Check if delay is lower than a day
if (delay < 24) {
int hours = (int) delay;
return resources.getQuantityString(R.plurals.hosts_source_hours, hours, hours);
}
// Get delay in days
delay /= 24;
// Check if delay is lower than a month
if (delay < 30) {
int days = (int) delay;
return resources.getQuantityString(R.plurals.hosts_source_days, days, days);
}
// Get delay in months
int months = (int) delay / 30;
return resources.getQuantityString(R.plurals.hosts_source_months, months, months);
}
@NonNull
@Override
public HostsSourcesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.hosts_sources_card, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
HostsSource source = this.getItem(position);
holder.enabledCheckBox.setChecked(source.isEnabled());
holder.enabledCheckBox.setOnClickListener(view -> viewCallback.toggleEnabled(source));
holder.labelTextView.setText(source.getLabel());
holder.urlTextView.setText(source.getUrl());
holder.updateTextView.setText(getUpdateText(source));
holder.sizeTextView.setText(getHostCount(source));
holder.itemView.setOnClickListener(view -> viewCallback.edit(source));
}
private String getUpdateText(HostsSource source) {
// Get context
Context context = this.viewCallback.getContext();
// Check if source is enabled
if (!source.isEnabled()) {
return context.getString(R.string.hosts_source_disabled);
}
// Check modification dates
boolean lastOnlineModificationDefined = source.getOnlineModificationDate() != null;
boolean lastLocalModificationDefined = source.getLocalModificationDate() != null;
// Declare update text
String updateText;
// Check if last online modification date is known
if (lastOnlineModificationDefined) {
// Get last online modification delay
String approximateDelay = getApproximateDelay(context, source.getOnlineModificationDate());
if (!lastLocalModificationDefined) {
updateText = context.getString(R.string.hosts_source_last_update, approximateDelay);
} else if (source.getOnlineModificationDate().isAfter(source.getLocalModificationDate())) {
updateText = context.getString(R.string.hosts_source_need_update, approximateDelay);
} else {
updateText = context.getString(R.string.hosts_source_up_to_date, approximateDelay);
}
} else {
if (lastLocalModificationDefined) {
String approximateDelay = getApproximateDelay(context, source.getLocalModificationDate());
updateText = context.getString(R.string.hosts_source_installed, approximateDelay);
} else {
updateText = context.getString(R.string.hosts_source_unknown_status);
}
}
return updateText;
}
private String getHostCount(HostsSource source) {
// Note: NumberFormat.getCompactNumberInstance is Java 12 only
// Check empty source
int size = source.getSize();
if (size <= 0 || !source.isEnabled()) {
return "";
}
// Compute size decimal length
int length = 1;
while (size > 10) {
size /= 10;
length++;
}
// Compute prefix to use
int prefixIndex = (length - 1) / 3 - 1;
// Return formatted count
Context context = this.viewCallback.getContext();
size = source.getSize();
if (prefixIndex < 0) {
return context.getString(R.string.hosts_count, Integer.toString(size));
} else if (prefixIndex >= QUANTITY_PREFIXES.length) {
prefixIndex = QUANTITY_PREFIXES.length - 1;
size = 13;
}
size = Math.toIntExact(Math.round(size / Math.pow(10, (prefixIndex + 1) * 3D)));
return context.getString(R.string.hosts_count, size + QUANTITY_PREFIXES[prefixIndex]);
}
/**
* This class is a the {@link RecyclerView.ViewHolder} for the hosts sources view.
*
* @author Bruce BUJON (bruce.bujon(at)gmail(dot)com)
*/
static class ViewHolder extends RecyclerView.ViewHolder {
final CheckBox enabledCheckBox;
final TextView labelTextView;
final TextView urlTextView;
final TextView updateTextView;
final TextView sizeTextView;
/**
* Constructor.
*
* @param itemView The hosts sources view.
*/
ViewHolder(View itemView) {
super(itemView);
this.enabledCheckBox = itemView.findViewById(R.id.sourceEnabledCheckBox);
this.labelTextView = itemView.findViewById(R.id.sourceLabelTextView);
this.urlTextView = itemView.findViewById(R.id.sourceUrlTextView);
this.updateTextView = itemView.findViewById(R.id.sourceUpdateTextView);
this.sizeTextView = itemView.findViewById(R.id.sourceSizeTextView);
}
}
}
|
149424_4 | package eu.adampacholski.miniOffice.pdfGenerator;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import eu.adampacholski.miniOffice.invoice.Invoice;
import eu.adampacholski.miniOffice.invoice.InvoiceService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.awt.*;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class PdfGeneratorService {
private final InvoiceService invoiceService;
public PdfGeneratorService(InvoiceService invoiceService) {
this.invoiceService = invoiceService;
}
public PdfPTable export(HttpServletResponse response, Long id) throws IOException {
// PdfPTable table = null;
response.setContentType("application/pdf");
Invoice invoice = invoiceService.getById(id);
Document document = new Document(PageSize.A4, 36, 36, 65, 36);
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
writer.setPageEvent(new HeaderAndFooterPageEventHelper());
document.open();
Font fontInvoiseType = FontFactory.getFont(FontFactory.HELVETICA_BOLD);
fontInvoiseType.setSize(18);
Paragraph invoiceTitle = new Paragraph(invoice.getInvoiceType().getType(), fontInvoiseType);
invoiceTitle.setAlignment(Paragraph.ALIGN_RIGHT);
document.add(invoiceTitle);
Font fontCustomer = FontFactory.getFont(FontFactory.HELVETICA);
fontCustomer.setSize(16);
Paragraph customerNameParagraph = new Paragraph(invoice.getCustomer().getName(), fontCustomer);
customerNameParagraph.setAlignment(Paragraph.ALIGN_LEFT);
document.add(customerNameParagraph);
fontCustomer.setSize(12);
Paragraph customerStreetParagraph = new Paragraph(invoice.getCustomer().getStreet() + ",", fontCustomer);
document.add(customerStreetParagraph);
Paragraph customerCityParagraph = new Paragraph(invoice.getCustomer().getPostCode() + " " + invoice.getCustomer().getCity(), fontCustomer);
document.add(customerCityParagraph);
PdfPTable empty = new PdfPTable(1);
empty.getDefaultCell().setBorder(Rectangle.NO_BORDER);
empty.getDefaultCell().setMinimumHeight(70);
empty.addCell("");
document.add(empty);
// info tabela
PdfPTable box = new PdfPTable(1);
box.setTotalWidth(PageSize.A4.getWidth() - 50);
box.getDefaultCell().setBorder(Rectangle.TOP | Rectangle.BOTTOM);
box.setLockedWidth(true);
PdfPTable infoTable = new PdfPTable(3);
infoTable.setTotalWidth(PageSize.A4.getWidth() - 50);
infoTable.setLockedWidth(true);
infoTable.setWidths(new int[]{33, 34, 33});
infoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
// infoTable.getDefaultCell().setPaddingTop(5);
infoTable.getDefaultCell().setPaddingBottom(5);
Font fontTableInfo = FontFactory.getFont(FontFactory.HELVETICA);
fontTableInfo.setSize(8);
Font fontTableInfo_2 = FontFactory.getFont(FontFactory.HELVETICA);
fontTableInfo_2.setSize(12);
fontTableInfo_2.setColor(Color.RED);
Font fontTableInfo_3 = FontFactory.getFont(FontFactory.HELVETICA);
fontTableInfo_3.setSize(12);
fontTableInfo_3.setColor(Color.BLACK);
String data = String.valueOf(invoice.getRisedDate().getDayOfMonth() + "." + invoice.getRisedDate().getMonthValue() + "." + invoice.getRisedDate().getYear());
Paragraph paragraphTableInfo = new Paragraph("Nr rachunku", fontTableInfo);
infoTable.addCell(paragraphTableInfo);
paragraphTableInfo = new Paragraph("Data wystawienia", fontTableInfo);
infoTable.addCell(paragraphTableInfo);
paragraphTableInfo = new Paragraph("Termin płatności", fontTableInfo);
infoTable.addCell(paragraphTableInfo);
paragraphTableInfo = new Paragraph(invoice.getInvoiceNumber(), fontTableInfo_2);
infoTable.addCell(paragraphTableInfo);
paragraphTableInfo = new Paragraph(data, fontTableInfo_3);
infoTable.addCell(paragraphTableInfo);
data = String.valueOf(invoice.getTerminDate().getDayOfMonth() + "." + invoice.getTerminDate().getMonthValue() + "." + invoice.getTerminDate().getYear());
paragraphTableInfo = new Paragraph(data, fontTableInfo_3);
infoTable.addCell(paragraphTableInfo);
infoTable.addCell(paragraphTableInfo);
box.addCell(infoTable);
document.add(box);
//lista produktów
//Header
PdfPTable produktTable = new PdfPTable(7);
produktTable.setTotalWidth(PageSize.A4.getWidth() - 50);
produktTable.setLockedWidth(true);
produktTable.setWidths(new int[]{5, 42,3, 8, 8, 17, 17});
produktTable.getDefaultCell().setMinimumHeight(25);
produktTable.getDefaultCell().setBackgroundColor(Color.LIGHT_GRAY);
produktTable.getDefaultCell().setBorder(Rectangle.BOTTOM);
produktTable.getDefaultCell().setPaddingLeft(4);
produktTable.getDefaultCell().setPaddingBottom(4);
produktTable.getDefaultCell().setPaddingTop(4);
produktTable.addCell("LP");
produktTable.addCell("Nazwa produktu");
produktTable.addCell("");
produktTable.addCell("Ilość");
produktTable.addCell("VAT %");
produktTable.addCell("Netto [zł]");
produktTable.addCell("Brutto [zł]");
//produkty
produktTable.getDefaultCell().setBackgroundColor(Color.WHITE);
for (int i = 0; i < invoice.getProductLists().size(); i++) {
produktTable.addCell(String.valueOf(i+1));
produktTable.addCell(invoice.getProductLists().get(i).getItem().getName());
produktTable.addCell("");
produktTable.addCell(String.valueOf(invoice.getProductLists().get(i).getAmount()));
produktTable.addCell(String.valueOf(invoice.getProductLists().get(i).getTax()));
produktTable.addCell(String.valueOf(invoice.getProductLists().get(i).getSumNetto()));
produktTable.addCell(String.valueOf(invoice.getProductLists().get(i).getSumBrutto()));
}
document.add(produktTable);
// suma
PdfPTable empty_2 = new PdfPTable(1);
empty_2.getDefaultCell().setBorder(Rectangle.NO_BORDER);
empty_2.getDefaultCell().setMinimumHeight(20);
empty_2.addCell("");
document.add(empty_2);
PdfPTable table = new PdfPTable(4);
table.setTotalWidth(PageSize.A4.getWidth() - 50);
table.setLockedWidth(true);
table.setWidths(new int[]{50, 10, 20, 20});
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.addCell("");
table.addCell("");
table.addCell("Netto");
table.addCell("Brutto");
table.addCell("");
Font sumaF = FontFactory.getFont(FontFactory.HELVETICA);
Paragraph sumaP = new Paragraph("Suma:",sumaF);
sumaP.setAlignment(Paragraph.ALIGN_RIGHT);
table.addCell(sumaP);
table.addCell(String.valueOf(invoice.getSumNetto())+" zł");
table.addCell(String.valueOf(invoice.getSumBrutto())+" zł");
document.add(table);
document.close();
writer.close();
return table;
}
}
class HeaderAndFooterPageEventHelper extends PdfPageEventHelper {
@Override
public void onEndPage(PdfWriter writer, Document document) {
/* Footer */
PdfPTable box = new PdfPTable(1);
box.setTotalWidth(PageSize.A4.getWidth() - 50);
box.getDefaultCell().setBorder(Rectangle.TOP);
box.setLockedWidth(true);
PdfPTable table = new PdfPTable(3);
table.setTotalWidth(510);
table.setWidths(new int[]{33, 34, 33});
// Magic about default cell - if you add styling to default cell it will apply to all cells except cells added using addCell(PdfPCell) method.
table.getDefaultCell().setPaddingBottom(5);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
Font fontFactory = FontFactory.getFont(FontFactory.HELVETICA_BOLD);
fontFactory.setSize(10);
Font fontFactory2 = FontFactory.getFont(FontFactory.HELVETICA);
fontFactory.setSize(10);
Paragraph title = new Paragraph("Adam Pacholski", fontFactory);
table.addCell(title);
Paragraph kontakt = new Paragraph("Kontakt", fontFactory);
table.addCell(kontakt);
Paragraph bank = new Paragraph("Bank", fontFactory);
table.addCell(bank);
title = new Paragraph("Am Bahndamm 10",fontFactory2);
table.addCell(title);
kontakt = new Paragraph("+4901783466541",fontFactory2);
table.addCell(kontakt);
bank = new Paragraph("Bank: Volksbank Vechta eG", fontFactory2);
table.addCell(bank);
title = new Paragraph("26197 Großenkneten",fontFactory2);
table.addCell(title);
kontakt = new Paragraph("[email protected]",fontFactory2);
table.addCell(kontakt);
bank = new Paragraph("DE15 2806 4179 0150 9730 00", fontFactory2);
table.addCell(bank);
table.addCell("");
table.addCell("");
Paragraph pageNumberText = new Paragraph("Strona " + document.getPageNumber(), new Font(Font.HELVETICA, 10));
PdfPCell strona = new PdfPCell(pageNumberText);
strona.setHorizontalAlignment(Element.ALIGN_RIGHT);
strona.setBorder(Rectangle.NO_BORDER);
strona.setPaddingTop(10);
table.addCell(strona);
box.addCell(table);
// write the table on PDF
box.writeSelectedRows(0, -1, 34, 100, writer.getDirectContent());
}
}
| Adam-Pacholski/miniOffice | src/main/java/eu/adampacholski/miniOffice/pdfGenerator/PdfGeneratorService.java | 2,613 | //Header | line_comment | nl | package eu.adampacholski.miniOffice.pdfGenerator;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import eu.adampacholski.miniOffice.invoice.Invoice;
import eu.adampacholski.miniOffice.invoice.InvoiceService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.awt.*;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class PdfGeneratorService {
private final InvoiceService invoiceService;
public PdfGeneratorService(InvoiceService invoiceService) {
this.invoiceService = invoiceService;
}
public PdfPTable export(HttpServletResponse response, Long id) throws IOException {
// PdfPTable table = null;
response.setContentType("application/pdf");
Invoice invoice = invoiceService.getById(id);
Document document = new Document(PageSize.A4, 36, 36, 65, 36);
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
writer.setPageEvent(new HeaderAndFooterPageEventHelper());
document.open();
Font fontInvoiseType = FontFactory.getFont(FontFactory.HELVETICA_BOLD);
fontInvoiseType.setSize(18);
Paragraph invoiceTitle = new Paragraph(invoice.getInvoiceType().getType(), fontInvoiseType);
invoiceTitle.setAlignment(Paragraph.ALIGN_RIGHT);
document.add(invoiceTitle);
Font fontCustomer = FontFactory.getFont(FontFactory.HELVETICA);
fontCustomer.setSize(16);
Paragraph customerNameParagraph = new Paragraph(invoice.getCustomer().getName(), fontCustomer);
customerNameParagraph.setAlignment(Paragraph.ALIGN_LEFT);
document.add(customerNameParagraph);
fontCustomer.setSize(12);
Paragraph customerStreetParagraph = new Paragraph(invoice.getCustomer().getStreet() + ",", fontCustomer);
document.add(customerStreetParagraph);
Paragraph customerCityParagraph = new Paragraph(invoice.getCustomer().getPostCode() + " " + invoice.getCustomer().getCity(), fontCustomer);
document.add(customerCityParagraph);
PdfPTable empty = new PdfPTable(1);
empty.getDefaultCell().setBorder(Rectangle.NO_BORDER);
empty.getDefaultCell().setMinimumHeight(70);
empty.addCell("");
document.add(empty);
// info tabela
PdfPTable box = new PdfPTable(1);
box.setTotalWidth(PageSize.A4.getWidth() - 50);
box.getDefaultCell().setBorder(Rectangle.TOP | Rectangle.BOTTOM);
box.setLockedWidth(true);
PdfPTable infoTable = new PdfPTable(3);
infoTable.setTotalWidth(PageSize.A4.getWidth() - 50);
infoTable.setLockedWidth(true);
infoTable.setWidths(new int[]{33, 34, 33});
infoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
// infoTable.getDefaultCell().setPaddingTop(5);
infoTable.getDefaultCell().setPaddingBottom(5);
Font fontTableInfo = FontFactory.getFont(FontFactory.HELVETICA);
fontTableInfo.setSize(8);
Font fontTableInfo_2 = FontFactory.getFont(FontFactory.HELVETICA);
fontTableInfo_2.setSize(12);
fontTableInfo_2.setColor(Color.RED);
Font fontTableInfo_3 = FontFactory.getFont(FontFactory.HELVETICA);
fontTableInfo_3.setSize(12);
fontTableInfo_3.setColor(Color.BLACK);
String data = String.valueOf(invoice.getRisedDate().getDayOfMonth() + "." + invoice.getRisedDate().getMonthValue() + "." + invoice.getRisedDate().getYear());
Paragraph paragraphTableInfo = new Paragraph("Nr rachunku", fontTableInfo);
infoTable.addCell(paragraphTableInfo);
paragraphTableInfo = new Paragraph("Data wystawienia", fontTableInfo);
infoTable.addCell(paragraphTableInfo);
paragraphTableInfo = new Paragraph("Termin płatności", fontTableInfo);
infoTable.addCell(paragraphTableInfo);
paragraphTableInfo = new Paragraph(invoice.getInvoiceNumber(), fontTableInfo_2);
infoTable.addCell(paragraphTableInfo);
paragraphTableInfo = new Paragraph(data, fontTableInfo_3);
infoTable.addCell(paragraphTableInfo);
data = String.valueOf(invoice.getTerminDate().getDayOfMonth() + "." + invoice.getTerminDate().getMonthValue() + "." + invoice.getTerminDate().getYear());
paragraphTableInfo = new Paragraph(data, fontTableInfo_3);
infoTable.addCell(paragraphTableInfo);
infoTable.addCell(paragraphTableInfo);
box.addCell(infoTable);
document.add(box);
//lista produktów
//Heade<SUF>
PdfPTable produktTable = new PdfPTable(7);
produktTable.setTotalWidth(PageSize.A4.getWidth() - 50);
produktTable.setLockedWidth(true);
produktTable.setWidths(new int[]{5, 42,3, 8, 8, 17, 17});
produktTable.getDefaultCell().setMinimumHeight(25);
produktTable.getDefaultCell().setBackgroundColor(Color.LIGHT_GRAY);
produktTable.getDefaultCell().setBorder(Rectangle.BOTTOM);
produktTable.getDefaultCell().setPaddingLeft(4);
produktTable.getDefaultCell().setPaddingBottom(4);
produktTable.getDefaultCell().setPaddingTop(4);
produktTable.addCell("LP");
produktTable.addCell("Nazwa produktu");
produktTable.addCell("");
produktTable.addCell("Ilość");
produktTable.addCell("VAT %");
produktTable.addCell("Netto [zł]");
produktTable.addCell("Brutto [zł]");
//produkty
produktTable.getDefaultCell().setBackgroundColor(Color.WHITE);
for (int i = 0; i < invoice.getProductLists().size(); i++) {
produktTable.addCell(String.valueOf(i+1));
produktTable.addCell(invoice.getProductLists().get(i).getItem().getName());
produktTable.addCell("");
produktTable.addCell(String.valueOf(invoice.getProductLists().get(i).getAmount()));
produktTable.addCell(String.valueOf(invoice.getProductLists().get(i).getTax()));
produktTable.addCell(String.valueOf(invoice.getProductLists().get(i).getSumNetto()));
produktTable.addCell(String.valueOf(invoice.getProductLists().get(i).getSumBrutto()));
}
document.add(produktTable);
// suma
PdfPTable empty_2 = new PdfPTable(1);
empty_2.getDefaultCell().setBorder(Rectangle.NO_BORDER);
empty_2.getDefaultCell().setMinimumHeight(20);
empty_2.addCell("");
document.add(empty_2);
PdfPTable table = new PdfPTable(4);
table.setTotalWidth(PageSize.A4.getWidth() - 50);
table.setLockedWidth(true);
table.setWidths(new int[]{50, 10, 20, 20});
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.addCell("");
table.addCell("");
table.addCell("Netto");
table.addCell("Brutto");
table.addCell("");
Font sumaF = FontFactory.getFont(FontFactory.HELVETICA);
Paragraph sumaP = new Paragraph("Suma:",sumaF);
sumaP.setAlignment(Paragraph.ALIGN_RIGHT);
table.addCell(sumaP);
table.addCell(String.valueOf(invoice.getSumNetto())+" zł");
table.addCell(String.valueOf(invoice.getSumBrutto())+" zł");
document.add(table);
document.close();
writer.close();
return table;
}
}
class HeaderAndFooterPageEventHelper extends PdfPageEventHelper {
@Override
public void onEndPage(PdfWriter writer, Document document) {
/* Footer */
PdfPTable box = new PdfPTable(1);
box.setTotalWidth(PageSize.A4.getWidth() - 50);
box.getDefaultCell().setBorder(Rectangle.TOP);
box.setLockedWidth(true);
PdfPTable table = new PdfPTable(3);
table.setTotalWidth(510);
table.setWidths(new int[]{33, 34, 33});
// Magic about default cell - if you add styling to default cell it will apply to all cells except cells added using addCell(PdfPCell) method.
table.getDefaultCell().setPaddingBottom(5);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
Font fontFactory = FontFactory.getFont(FontFactory.HELVETICA_BOLD);
fontFactory.setSize(10);
Font fontFactory2 = FontFactory.getFont(FontFactory.HELVETICA);
fontFactory.setSize(10);
Paragraph title = new Paragraph("Adam Pacholski", fontFactory);
table.addCell(title);
Paragraph kontakt = new Paragraph("Kontakt", fontFactory);
table.addCell(kontakt);
Paragraph bank = new Paragraph("Bank", fontFactory);
table.addCell(bank);
title = new Paragraph("Am Bahndamm 10",fontFactory2);
table.addCell(title);
kontakt = new Paragraph("+4901783466541",fontFactory2);
table.addCell(kontakt);
bank = new Paragraph("Bank: Volksbank Vechta eG", fontFactory2);
table.addCell(bank);
title = new Paragraph("26197 Großenkneten",fontFactory2);
table.addCell(title);
kontakt = new Paragraph("[email protected]",fontFactory2);
table.addCell(kontakt);
bank = new Paragraph("DE15 2806 4179 0150 9730 00", fontFactory2);
table.addCell(bank);
table.addCell("");
table.addCell("");
Paragraph pageNumberText = new Paragraph("Strona " + document.getPageNumber(), new Font(Font.HELVETICA, 10));
PdfPCell strona = new PdfPCell(pageNumberText);
strona.setHorizontalAlignment(Element.ALIGN_RIGHT);
strona.setBorder(Rectangle.NO_BORDER);
strona.setPaddingTop(10);
table.addCell(strona);
box.addCell(table);
// write the table on PDF
box.writeSelectedRows(0, -1, 34, 100, writer.getDirectContent());
}
}
|
192646_8 | package com.rydeit.view;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.NetworkImageView;
import com.avast.android.dialogs.fragment.SimpleDialogFragment;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.rydeit.R;
import com.rydeit.api.ola.OlaCallback;
import com.rydeit.api.uber.UberCallback;
import com.rydeit.cab.service.ola.OlaAPIConstants;
import com.rydeit.cab.service.ola.OlaSandBox;
import com.rydeit.database.DatabaseUtil;
import com.rydeit.database.GenericRydeState;
import com.rydeit.model.common.MapPoint;
import com.rydeit.model.common.MyBooking;
import com.rydeit.model.ola.CancelResponse;
import com.rydeit.model.ola.TrackRide;
import com.rydeit.model.uber.Requests.ErrorResponses.Error;
import com.rydeit.model.uber.Requests.ErrorResponses.ErrorResponse;
import com.rydeit.model.uber.Requests.UberStatus;
import com.rydeit.model.uber.RideRequest;
import com.rydeit.provider.CabApiClientFactory;
import com.rydeit.uilibrary.BaseActivityActionBar;
import com.rydeit.util.Constants;
import com.rydeit.util.JavaUtil;
import com.rydeit.util.Log;
import com.rydeit.volley.VolleySingleton;
import java.util.HashMap;
import java.util.List;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* Created by Prakhyath on 11/10/2015.
*/
public class TrackMyRideActivity extends BaseActivityActionBar implements OnMapReadyCallback {
private static final String TAG = TrackMyRideActivity.class.getSimpleName();
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
LatLngBounds.Builder mLatLngBuilder = new LatLngBounds.Builder();
NetworkImageView chauffeurImage;
TextView tvDriverName;
TextView tvCarModel;
TextView tvCarRegNo;
LinearLayout ll_Calldriver;
LinearLayout ll_sharedetails;
LinearLayout ll_cancelride;
MyBooking mMyBooking;
TrackRide mTrackRide;//OLA
private String booking_status_previous;
String AccessToken=ConfirmBookingActivity.AccessToken;
String TokenType=ConfirmBookingActivity.TokenType;
private int ACTIVE_DIALOG_ID = 0;
private boolean dialogIsRunning = false;
private String globalMessage = "";
//String mPickUpAddress;
boolean isNewBooking=false;
boolean bIsRefreshBooking=false;
private static final int TRACKPAGE_REFRESH_TIME=30000;
private static final int MSG_SIMULATE_OLA_COMPLETION = 9999;
private static final int MSG_SIMULATE_OLA_CLIENT_LOCATED = 9998;
private static final int MSG_SIMULATE_OLA_IN_PROGRESS = 9997;
private static final int MSG_SIMULATE_OLA_CALL_DRIVER=9996;
// no need to create handler here use handler in base calss
// private Handler mHandler = new Handler();
private boolean mForceStopTimer=false;
@Override
public void onCreate(Bundle savedInstanceState) {
setHomeDisabled(true);
super.onCreate(savedInstanceState);
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
setTitle(getString(R.string.trackride));
//getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.splash_yellow)));
getSupportActionBar().setHomeAsUpIndicator(R.drawable.left_arrow_white1);
}
/*if(getIntent().hasExtra("PickUpAddress"))
mPickUpAddress=getIntent().getStringExtra("PickUpAddress");*/
if(getIntent().hasExtra("TrackRideInProgress")){
mMyBooking=(MyBooking)getIntent().getSerializableExtra("TrackRideInProgress");
Log.d(TAG,"BOOKING DETAILS: "+mMyBooking.toString());
}
else
Log.e(TAG,"Invalid Booking");
if(getIntent().hasExtra("isNewBooking")){
isNewBooking=true;
}
setContentView(R.layout.activity_trackmyride);
initViews();
updateBookingDetails();
setUpMapIfNeeded();
}
void initViews(){
chauffeurImage=(NetworkImageView)findViewById(R.id.chauffeur_image);
tvDriverName=(TextView)findViewById(R.id.drivername);
tvCarModel=(TextView)findViewById(R.id.carmodel);
tvCarRegNo=(TextView)findViewById(R.id.carregno);
ll_Calldriver=(LinearLayout)findViewById(R.id.ll_calldriver);
ll_sharedetails=(LinearLayout)findViewById(R.id.ll_sharedetails);
ll_cancelride=(LinearLayout)findViewById(R.id.ll_cancelride);
ll_cancelride.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showCustomDialog(DIALOG_CONFIRM_CANCELLATION, "");
}
});
ll_Calldriver.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
callDriver(mMyBooking.driver_number);
}
});
ll_sharedetails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "I would like to share my cab ride details with you" + mMyBooking.printCustom());
shareIntent.setType("text/plain");
TrackMyRideActivity.this.startActivity(shareIntent);
}
});
}
void CancelBooking(){
if(mMyBooking!=null && mMyBooking.cabCompany.equalsIgnoreCase(Constants.CAB_GLOBAL.UBER.toString())){
cancelUberBooking();
}else if(mMyBooking!=null && mMyBooking.cabCompany.equalsIgnoreCase(Constants.CAB_INDIA.OLA.toString())){
cancelOlaBooking();
}
}
private final int DIALOG_NO_CONNECTIVITY = 102;
private final int DIALOG_CONFIRM_CANCELLATION = 103;
private final String DIALOG_TAG = "DIALOG_TAG";
private final int DIALOG_CANCEL_FAILED = 104;
private final int MSG_UBER_CANCEL_SUCCESS = 201;
private final int MSG_OLA_CANCEL_SUCCESS = 202;
public static final int DIALOG_RIDE_COMPLETED = 1017;
public static final int DIALOG_RIDE_TRACKING_NOT_VALID = 1018;
/**
* Public api to show different dialogs
* @param id
*/
public void showCustomDialog(int id, String message) {
SimpleDialogFragment.SimpleDialogBuilder builder = SimpleDialogFragment.createBuilder(this
, this.getSupportFragmentManager());
dismissProgressDialog(this.getSupportFragmentManager());
switch (id) {
case DIALOG_NO_CONNECTIVITY:
builder.setTitle("No Network");
builder.setMessage("You are not connected to internet");
builder.setPositiveButtonText("OK");
builder.setCancelableOnTouchOutside(false);
break;
case DIALOG_CONFIRM_CANCELLATION:
builder.setTitle("Cancel Ride");
builder.setMessage("Are you sure you want to Cancel Booking?");
builder.setPositiveButtonText("OK");
builder.setNegativeButtonText("CANCEL");
builder.setCancelableOnTouchOutside(false);
break;
case DIALOG_CANCEL_FAILED:
builder.setTitle("Cancellation Failed=");
builder.setMessage(message);
builder.setPositiveButtonText("OK");
break;
case DIALOG_RIDE_TRACKING_NOT_VALID:
builder.setTitle("Not a valid Ride");
builder.setMessage("This ride is already Cancelled or Completed. Thanks you.");
builder.setPositiveButtonText("OK");
break;
case DIALOG_RIDE_COMPLETED:
builder.setTitle("Ride Completed");
if(message != null && !message.isEmpty())
{
builder.setMessage(message);
}
else
builder.setMessage("Your Ride is completed. \n Kindly check your email for receipt.");
builder.setPositiveButtonText("OK");
builder.setCancelableOnTouchOutside(false);
break;
}
if (mIsRunning) {
builder.setRequestCode(id).setTag(DIALOG_TAG).show();
ACTIVE_DIALOG_ID = id;
globalMessage = message;
}
else
android.util.Log.e(TAG, "Not able to show dialog here :-( with id " + id);
}
void cancelOlaBooking(){
if(mMyBooking!=null && mMyBooking.crn!=null) {
// OlaAPIClient.getOlaV1APIClient().cancelRide(OlaAPIConstants.getOlaXAppToken(this),
// TokenType + " " + AccessToken,
// mMyBooking.crn,
CabApiClientFactory.getCabProvider(CabApiClientFactory.PROVIDER_OLA).cancelRide(mMyBooking.crn,TokenType,AccessToken,
new OlaCallback<CancelResponse>() {
@Override
public void success(CancelResponse cancelResponse, Response response) {
Toast.makeText(TrackMyRideActivity.this, "Booking is Cancelled", Toast.LENGTH_SHORT).show();
ContentValues cv = new ContentValues();
cv.put("BOOKING_STATUS", GenericRydeState.CANCELLED);
try {
DatabaseUtil.updateRideStatus(TrackMyRideActivity.this, cv, mMyBooking.crn);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (mActivityHandler != null)
mActivityHandler.sendMessage(mActivityHandler.obtainMessage(MSG_OLA_CANCEL_SUCCESS));
}
@Override
public void failure(RetrofitError error) {
Log.d(TAG, "CANCEL BOOKING: errro:" + error.getResponse());
showCustomDialog(DIALOG_CANCEL_FAILED, error.getMessage());
super.failure(error);
}
}
);
}
else{
Toast.makeText(this,"Invalid Booking ID, Cannot be cancelled",Toast.LENGTH_LONG).show();
}
}
void cancelUberBooking(){
if(mMyBooking!=null && mMyBooking.crn!=null) {
// UberAPIClient.getUberV1APIClient().deleteRequest(CabTracker.getInstance().getAccessToken(Constants.CAB_GLOBAL.UBER),
// mMyBooking.crn,
CabApiClientFactory.getCabProvider(CabApiClientFactory.PROVIDER_UBER).cancelRide(mMyBooking.crn ,"","",
new UberCallback<Response>() {
@Override
public void success(Response response, Response response2) {
Log.d(TAG,"CANCEL BOOKING: status:"+response.getStatus());
Toast.makeText(TrackMyRideActivity.this,"Booking is Cancelled",Toast.LENGTH_SHORT).show();
//Updating DB post cancellation ride status has to be updated to Cancelled?
ContentValues cv = new ContentValues();
cv.put("BOOKING_STATUS","CANCELLED");
try {
DatabaseUtil.updateRideStatus(TrackMyRideActivity.this, cv, mMyBooking.crn);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if(mActivityHandler!=null)
mActivityHandler.sendMessage(mActivityHandler.obtainMessage(MSG_UBER_CANCEL_SUCCESS));
}
@Override
public void failure(RetrofitError error) {
Log.d(TAG,"CANCEL BOOKING: errro:"+error.getResponse());
showCustomDialog(DIALOG_CANCEL_FAILED, error.getMessage());
super.failure(error);
}
});
}
else{
Toast.makeText(this, "Invalid Booking ID, Cannot be cancelled", Toast.LENGTH_LONG).show();
}
}
boolean doubleBackToExitPressedOnce = false;
private final int MSG_BACK_EXIT = 1010;
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click back again to exit", Toast.LENGTH_SHORT).show();
if(mActivityHandler != null)
mActivityHandler.sendMessageDelayed(mActivityHandler.obtainMessage(MSG_BACK_EXIT), 2000);
}
void callDriver(String phoneno){
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phoneno));
startActivity(intent);
}
void updateBookingDetails(){
if(mMyBooking!=null){
tvDriverName.setText(mMyBooking.driver_name);
tvCarModel.setText(mMyBooking.car_model);
tvCarRegNo.setText(mMyBooking.cab_number);
if(mMyBooking.chauffeurImageUrl!=null)
chauffeurImage.setImageUrl(mMyBooking.chauffeurImageUrl, VolleySingleton.getInstance().getImageLoader());
else
chauffeurImage.setDefaultImageResId(R.drawable.chauffeur_icon);
//We are hardcoding to OLA lets make sure that
}
}
void trackMyBooking(){
if(mMyBooking!=null && mMyBooking.cabCompany.equalsIgnoreCase(Constants.CAB_GLOBAL.UBER.toString())){
// CabTracker.getInstance().trackUberBooking(mMyBooking.crn, callbackRideRequest);
CabApiClientFactory.getCabProvider(CabApiClientFactory.PROVIDER_UBER).getRideStatus(mMyBooking.crn,callbackRideRequest);
}else if(mMyBooking!=null && mMyBooking.cabCompany.equalsIgnoreCase(Constants.CAB_INDIA.OLA.toString())){
trackOlaBooking();
}
}
void trackOlaBooking(){
if(Constants.SIMULATE_BOOKING || (mMyBooking!=null && mMyBooking.booking_status!=null
&& mMyBooking.booking_status.equals("SIMULATION"))){
Log.d(TAG, "SIMULATION MODE: TRACK CAB");
if(booking_status_previous==null) {
mTrackRide = OlaSandBox.getSimulatedClientLocated();
olaCallback.success(mTrackRide, null);
}else if(booking_status_previous.equals((OlaAPIConstants.BOOKING_STATUS.CLIENT_LOCATED))) {
mActivityHandler.sendMessageDelayed(mActivityHandler.obtainMessage(MSG_SIMULATE_OLA_CALL_DRIVER), 1000);
}else if(booking_status_previous.equals((OlaAPIConstants.BOOKING_STATUS.CALL_DRIVER))) {
mActivityHandler.sendMessageDelayed(mActivityHandler.obtainMessage(MSG_SIMULATE_OLA_IN_PROGRESS), 1000);
}else if(booking_status_previous.equals((OlaAPIConstants.BOOKING_STATUS.IN_PROGRESS)))
mActivityHandler.sendMessageDelayed(mActivityHandler.obtainMessage(MSG_SIMULATE_OLA_COMPLETION), 1000);
/*if(isNewBooking) {
insertBookingInfo();
isNewBooking=false;
}*/
return;
}
CabApiClientFactory.getCabProvider(CabApiClientFactory.PROVIDER_OLA).getRideStatus(null, olaCallback);
//CabTracker.getInstance().trackOlaBooking(olaCallback, AccessToken, TokenType);
}
private OlaCallback<TrackRide> olaCallback = new OlaCallback<TrackRide>() {
@Override
public void success(TrackRide trackRide, Response response) {
if (trackRide != null && trackRide.duration != null && Constants.ENABLE_DEBUG_TOAST)
Toast.makeText(TrackMyRideActivity.this, "Status:\"+trackRide.status+\"\n" +
" Booking Status:" + trackRide.booking_status + "+ \nCar Arrival Time:" + trackRide.duration.value, Toast.LENGTH_LONG).show();
else if (trackRide != null && Constants.ENABLE_DEBUG_TOAST)
Toast.makeText(TrackMyRideActivity.this, "Status:" + trackRide.status + "\n Booking Status:" + trackRide.booking_status, Toast.LENGTH_LONG).show();
//proper shallow copy
mTrackRide = (TrackRide) trackRide.clone();
Log.d(TAG, "TRACK RIDE Details: " + mTrackRide.toString());
if (mTrackRide.booking_status.equals(OlaAPIConstants.BOOKING_STATUS.NO_BOOKING)){
showCustomDialog(DIALOG_RIDE_TRACKING_NOT_VALID, null);
}else if (mTrackRide.booking_status.equals(OlaAPIConstants.BOOKING_STATUS.COMPLETED)){
String displayBill = " Total amount is Rs :" + trackRide.trip_info.amount + "\n Ola cash balance :"+ trackRide.ola_money_balance + "\n Payable amount :"+ trackRide.trip_info.payable_amount;
showCustomDialog(DIALOG_RIDE_COMPLETED, displayBill);
ll_cancelride.setVisibility(View.INVISIBLE);
}else if (mTrackRide.booking_status.equals(OlaAPIConstants.BOOKING_STATUS.IN_PROGRESS)){
ll_cancelride.setVisibility(View.INVISIBLE);
if(booking_status_previous==null || booking_status_previous.equals(OlaAPIConstants.BOOKING_STATUS.CLIENT_LOCATED))
Toast.makeText(TrackMyRideActivity.this,"Have a pleasant Ride",Toast.LENGTH_LONG).show();
}else if (mTrackRide.booking_status.equals(OlaAPIConstants.BOOKING_STATUS.CLIENT_LOCATED)
|| mTrackRide.booking_status.equals(OlaAPIConstants.BOOKING_STATUS.CALL_DRIVER)){
ll_cancelride.setVisibility(View.VISIBLE);
}else
ll_cancelride.setVisibility(View.INVISIBLE);
booking_status_previous=mTrackRide.booking_status;
Log.d(TAG, "DRIVER POSITION: lat:" + mTrackRide.driver_lat + " log:" + mTrackRide.driver_lng);
setUpMap();
}
};
private UberCallback<RideRequest> callbackRideRequest = new UberCallback<RideRequest>()
{
@Override
public void success(RideRequest rideRequest, Response response) {
dismissProgressDialog(TrackMyRideActivity.this.getSupportFragmentManager());
if(rideRequest==null && Constants.ENABLE_DEBUG_TOAST){
Toast.makeText(TrackMyRideActivity.this, "RESPONSE: RideRequest is null", Toast.LENGTH_LONG).show();
return;
}
if(rideRequest!=null && rideRequest.getRequest_id()!=null) {
if (rideRequest.getStatus().equalsIgnoreCase(UberStatus.PROCESSING.toString())
|| rideRequest.getStatus().equalsIgnoreCase(UberStatus.ARRIVING.value().toString())
|| rideRequest.getStatus().equalsIgnoreCase(UberStatus.ACCEPTED.value().toString())
|| rideRequest.getStatus().equalsIgnoreCase(UberStatus.IN_PROGRESS.value().toString())
|| rideRequest.getStatus().equalsIgnoreCase(UberStatus.RIDER_CANCELED.value().toString())) {
if (rideRequest.getStatus().equalsIgnoreCase(UberStatus.ARRIVING.toString()))
Toast.makeText(TrackMyRideActivity.this, "Your cab has arrived", Toast.LENGTH_LONG).show();
Log.d(TAG, "REQUEST ID: " + rideRequest.getRequest_id());
if(Constants.ENABLE_DEBUG_TOAST)
Toast.makeText(TrackMyRideActivity.this, "TRACK BOOKING SUCCESS\n"+rideRequest.toString(), Toast.LENGTH_SHORT).show();
JavaUtil.printHTTPResponse(response);
mTrackRide=new TrackRide();//TODO FIXME IMPLEMENT COMMON MODEL CLASS
if(rideRequest.getLocation()!=null) {
mTrackRide.driver_lat = rideRequest.getLocation().latitude;
mTrackRide.driver_lng = rideRequest.getLocation().longitude;
}
adaptUberMyBooking(rideRequest);
updateBookingDetails();
setUpMap();
}else if (rideRequest.getStatus().equalsIgnoreCase(UberStatus.COMPLETED.toString())){
Toast.makeText(TrackMyRideActivity.this,"Your Ride is completed. Kindly check your email :"+rideRequest.getRequest_id() , Toast.LENGTH_LONG).show();
showCustomDialog(DIALOG_RIDE_COMPLETED,null);
}
}
else{
Toast.makeText(TrackMyRideActivity.this,"rideRequest Request Id Id is null" , Toast.LENGTH_LONG).show();
}
}
@Override
public void failure(RetrofitError error) {
dismissProgressDialog(TrackMyRideActivity.this.getSupportFragmentManager());
Log.e(TAG,"MESSAGE="+error.toString());
Log.e(TAG,"MESSAGE RESPONSE="+error.getResponse());
ErrorResponse errorRideResponse=null;
List<Error> errors=null;
try {
errorRideResponse=(ErrorResponse)error.getBodyAs(ErrorResponse.class);
errors=errorRideResponse.getErrors();
} catch (Exception e) {
e.printStackTrace();
}
//TODO THESE ERROS NEED NOT BE HANDLED HERE
//TODO HANDLE RIDE TRACKING STATUS HERE
if (errors!=null && errors.size()>0){
Error responseError=errors.get(0);
if(responseError!=null && responseError.getCode().contains("insufficient_balance")){
//showCustomDialog(DIALOG_NO_FUNDS);
}
}
if(Constants.ENABLE_DEBUG_TOAST)
Toast.makeText(TrackMyRideActivity.this, error.getBody().toString(), Toast.LENGTH_LONG).show();
}
};
private void adaptUberMyBooking(RideRequest rideRequest){
if(mMyBooking==null)
mMyBooking=new MyBooking();
if(rideRequest!=null) {
mMyBooking.crn = rideRequest.getRequest_id();
if (rideRequest.getDriver() != null) {
mMyBooking.driver_name = rideRequest.getDriver().name;
mMyBooking.cab_number = rideRequest.getDriver().phone_number;
}
if (rideRequest.getVehicle() != null) {
mMyBooking.cab_type = rideRequest.getVehicle().make;//TODO CORRECT THIS
mMyBooking.cab_number = rideRequest.getVehicle().license_plate;
mMyBooking.car_model = rideRequest.getVehicle().model;
} else
mMyBooking.cab_type = "SEDAN";//TODO CORRECT THIS
if (rideRequest.getLocation() != null)
mMyBooking.driverLocation=new MapPoint(rideRequest.getLocation().latitude, rideRequest.getLocation().longitude);
if(rideRequest.getDriver()!=null) {
if(rideRequest.getDriver().picture_url!=null)
mMyBooking.chauffeurImageUrl = rideRequest.getDriver().picture_url;
if(rideRequest.getDriver().phone_number!=null && !rideRequest.getDriver().phone_number.equals(""))
mMyBooking.driver_number=rideRequest.getDriver().phone_number;
}
mMyBooking.eta=rideRequest.getEta();
mMyBooking.booking_status=rideRequest.getStatus();//TODO INSERT CORRECT DISPLAY STRING
}
mMyBooking.cabCompany= Constants.CAB_GLOBAL.UBER.toString();
Log.d(TAG, "Uber: Mybooking=" + mMyBooking.toString());
}
private void initRefreshTrackPageTimer(){
mForceStopTimer=false;
Runnable mRunnableTimer = new Runnable() {
@Override
public void run() {
if(mForceStopTimer)
return;
bIsRefreshBooking=true;
trackMyBooking();
mActivityHandler.postDelayed(this, TRACKPAGE_REFRESH_TIME);
}
};
mActivityHandler.postDelayed(mRunnableTimer, 0);
}
private void stopRefreshTrackPageTimer(){
mForceStopTimer=true;
if(mActivityHandler!=null)
mActivityHandler.removeCallbacks(null);
}
@Override
public void onMapReady(GoogleMap googleMap) {
if (mMap == null)
setUpMapIfNeeded();
else
setUpMap();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {@link #setUpMap()} once when {@link #mMap} is not null.
* <p/>
* If it isn't installed {@link com.google.android.gms.maps.SupportMapFragment} (and
* {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
* method in {@link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {@link #mMap} is not null.
*/
private void setUpMap() {
if(mMap==null)
return;
mMap.clear();;
mLatLngBuilder=new LatLngBounds.Builder();
if(mMyBooking!=null && mMyBooking.pickupLoction!=null) {
LatLng latLng = new LatLng(mMyBooking.pickupLoction.getLattitude(), mMyBooking.pickupLoction.getLongitude());
mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.pin))
.position(latLng));
if(!bIsRefreshBooking)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng ,14.0f) );
mLatLngBuilder.include(latLng);
}
if(mTrackRide!=null) {
mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.cab_tracking))
.position(new LatLng(mTrackRide.driver_lat, mTrackRide.driver_lng)));
mLatLngBuilder.include(new LatLng(mTrackRide.driver_lat, mTrackRide.driver_lng));
}
Log.d(TAG, "MAP DRAWING: mMyBooking:"+mMyBooking.toString());
if(mTrackRide!=null)
Log.d(TAG, "MAP DRAWING: mTrackRide:"+mTrackRide.toString());
fixZoom();
}
private void fixZoom() {
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
//mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mLatLngBuilder.build(), 50));
if (mMap == null || mLatLngBuilder.build() == null)
return;
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(mLatLngBuilder.build(), 150));
}
});
}
@Override
public int getActionBarMenuId() {
return INVALID_MENU;
}
@Override
public HashMap<Integer, MenuItem> getMenuItems() {
return null;
}
@Override
public void onDialogTimedOut(int reqCode) {
}
@Override
public void processCustomMessage(Message msg) {
switch (msg.what)
{
case MSG_OLA_CANCEL_SUCCESS:
case MSG_UBER_CANCEL_SUCCESS:
finish();
break;
case MSG_BACK_EXIT:
doubleBackToExitPressedOnce=false;
break;
case MSG_SIMULATE_OLA_COMPLETION:
olaCallback.success(OlaSandBox.getSimulatedTripEnded(), null);
break;
case MSG_SIMULATE_OLA_CLIENT_LOCATED:
olaCallback.success(OlaSandBox.getSimulatedClientLocated(), null);
break;
case MSG_SIMULATE_OLA_CALL_DRIVER:
olaCallback.success(OlaSandBox.getSimulatedCallDriver(), null);
break;
case MSG_SIMULATE_OLA_IN_PROGRESS:
olaCallback.success(OlaSandBox.getSimulatedRideTrackObject(), null);
break;
}
}
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
super.onNewIntent(intent);
}
@Override
protected void onResume() {
super.onResume();
if (dialogIsRunning) {
showCustomDialog(ACTIVE_DIALOG_ID, globalMessage);
}
initRefreshTrackPageTimer();
}
@Override
protected void onPause() {
super.onPause();
DialogFragment df = (DialogFragment) getSupportFragmentManager().findFragmentByTag(DIALOG_TAG);
if (df != null) {
df.dismissAllowingStateLoss();
dialogIsRunning = true;
}
stopRefreshTrackPageTimer();
}
@Override
public void onDestroy() {
super.onDestroy();
stopRefreshTrackPageTimer();
}
@Override
public void onPositiveButtonClicked(int reqCode) {
ACTIVE_DIALOG_ID = 0;
dialogIsRunning = false;
if(reqCode == DIALOG_CONFIRM_CANCELLATION)
CancelBooking();
else if (reqCode == DIALOG_RIDE_COMPLETED){
updateOnCompletion();
finish();
}else if (reqCode == DIALOG_RIDE_TRACKING_NOT_VALID){
try {
if(mMyBooking!=null && mMyBooking.crn!=null)
DatabaseUtil.deleteRydeInfo(TrackMyRideActivity.this, mMyBooking.crn.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
finish();
}
super.onPositiveButtonClicked(reqCode);
}
@Override
public void onNegativeButtonClicked(int reqCode) {
ACTIVE_DIALOG_ID = 0;
dialogIsRunning = false;
super.onNegativeButtonClicked(reqCode);
}
private void updateOnCompletion()
{
ContentValues cv = new ContentValues();
cv.put("BOOKING_STATUS","COMPLETED");
try {
DatabaseUtil.updateRideStatus(TrackMyRideActivity.this, cv, mMyBooking.crn);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
| Aditya-Khambampati81/rydeit | RydeIT/app/src/main/java/com/rydeit/view/TrackMyRideActivity.java | 7,754 | // OlaAPIClient.getOlaV1APIClient().cancelRide(OlaAPIConstants.getOlaXAppToken(this), | line_comment | nl | package com.rydeit.view;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.NetworkImageView;
import com.avast.android.dialogs.fragment.SimpleDialogFragment;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.rydeit.R;
import com.rydeit.api.ola.OlaCallback;
import com.rydeit.api.uber.UberCallback;
import com.rydeit.cab.service.ola.OlaAPIConstants;
import com.rydeit.cab.service.ola.OlaSandBox;
import com.rydeit.database.DatabaseUtil;
import com.rydeit.database.GenericRydeState;
import com.rydeit.model.common.MapPoint;
import com.rydeit.model.common.MyBooking;
import com.rydeit.model.ola.CancelResponse;
import com.rydeit.model.ola.TrackRide;
import com.rydeit.model.uber.Requests.ErrorResponses.Error;
import com.rydeit.model.uber.Requests.ErrorResponses.ErrorResponse;
import com.rydeit.model.uber.Requests.UberStatus;
import com.rydeit.model.uber.RideRequest;
import com.rydeit.provider.CabApiClientFactory;
import com.rydeit.uilibrary.BaseActivityActionBar;
import com.rydeit.util.Constants;
import com.rydeit.util.JavaUtil;
import com.rydeit.util.Log;
import com.rydeit.volley.VolleySingleton;
import java.util.HashMap;
import java.util.List;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* Created by Prakhyath on 11/10/2015.
*/
public class TrackMyRideActivity extends BaseActivityActionBar implements OnMapReadyCallback {
private static final String TAG = TrackMyRideActivity.class.getSimpleName();
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
LatLngBounds.Builder mLatLngBuilder = new LatLngBounds.Builder();
NetworkImageView chauffeurImage;
TextView tvDriverName;
TextView tvCarModel;
TextView tvCarRegNo;
LinearLayout ll_Calldriver;
LinearLayout ll_sharedetails;
LinearLayout ll_cancelride;
MyBooking mMyBooking;
TrackRide mTrackRide;//OLA
private String booking_status_previous;
String AccessToken=ConfirmBookingActivity.AccessToken;
String TokenType=ConfirmBookingActivity.TokenType;
private int ACTIVE_DIALOG_ID = 0;
private boolean dialogIsRunning = false;
private String globalMessage = "";
//String mPickUpAddress;
boolean isNewBooking=false;
boolean bIsRefreshBooking=false;
private static final int TRACKPAGE_REFRESH_TIME=30000;
private static final int MSG_SIMULATE_OLA_COMPLETION = 9999;
private static final int MSG_SIMULATE_OLA_CLIENT_LOCATED = 9998;
private static final int MSG_SIMULATE_OLA_IN_PROGRESS = 9997;
private static final int MSG_SIMULATE_OLA_CALL_DRIVER=9996;
// no need to create handler here use handler in base calss
// private Handler mHandler = new Handler();
private boolean mForceStopTimer=false;
@Override
public void onCreate(Bundle savedInstanceState) {
setHomeDisabled(true);
super.onCreate(savedInstanceState);
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
setTitle(getString(R.string.trackride));
//getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.splash_yellow)));
getSupportActionBar().setHomeAsUpIndicator(R.drawable.left_arrow_white1);
}
/*if(getIntent().hasExtra("PickUpAddress"))
mPickUpAddress=getIntent().getStringExtra("PickUpAddress");*/
if(getIntent().hasExtra("TrackRideInProgress")){
mMyBooking=(MyBooking)getIntent().getSerializableExtra("TrackRideInProgress");
Log.d(TAG,"BOOKING DETAILS: "+mMyBooking.toString());
}
else
Log.e(TAG,"Invalid Booking");
if(getIntent().hasExtra("isNewBooking")){
isNewBooking=true;
}
setContentView(R.layout.activity_trackmyride);
initViews();
updateBookingDetails();
setUpMapIfNeeded();
}
void initViews(){
chauffeurImage=(NetworkImageView)findViewById(R.id.chauffeur_image);
tvDriverName=(TextView)findViewById(R.id.drivername);
tvCarModel=(TextView)findViewById(R.id.carmodel);
tvCarRegNo=(TextView)findViewById(R.id.carregno);
ll_Calldriver=(LinearLayout)findViewById(R.id.ll_calldriver);
ll_sharedetails=(LinearLayout)findViewById(R.id.ll_sharedetails);
ll_cancelride=(LinearLayout)findViewById(R.id.ll_cancelride);
ll_cancelride.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showCustomDialog(DIALOG_CONFIRM_CANCELLATION, "");
}
});
ll_Calldriver.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
callDriver(mMyBooking.driver_number);
}
});
ll_sharedetails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "I would like to share my cab ride details with you" + mMyBooking.printCustom());
shareIntent.setType("text/plain");
TrackMyRideActivity.this.startActivity(shareIntent);
}
});
}
void CancelBooking(){
if(mMyBooking!=null && mMyBooking.cabCompany.equalsIgnoreCase(Constants.CAB_GLOBAL.UBER.toString())){
cancelUberBooking();
}else if(mMyBooking!=null && mMyBooking.cabCompany.equalsIgnoreCase(Constants.CAB_INDIA.OLA.toString())){
cancelOlaBooking();
}
}
private final int DIALOG_NO_CONNECTIVITY = 102;
private final int DIALOG_CONFIRM_CANCELLATION = 103;
private final String DIALOG_TAG = "DIALOG_TAG";
private final int DIALOG_CANCEL_FAILED = 104;
private final int MSG_UBER_CANCEL_SUCCESS = 201;
private final int MSG_OLA_CANCEL_SUCCESS = 202;
public static final int DIALOG_RIDE_COMPLETED = 1017;
public static final int DIALOG_RIDE_TRACKING_NOT_VALID = 1018;
/**
* Public api to show different dialogs
* @param id
*/
public void showCustomDialog(int id, String message) {
SimpleDialogFragment.SimpleDialogBuilder builder = SimpleDialogFragment.createBuilder(this
, this.getSupportFragmentManager());
dismissProgressDialog(this.getSupportFragmentManager());
switch (id) {
case DIALOG_NO_CONNECTIVITY:
builder.setTitle("No Network");
builder.setMessage("You are not connected to internet");
builder.setPositiveButtonText("OK");
builder.setCancelableOnTouchOutside(false);
break;
case DIALOG_CONFIRM_CANCELLATION:
builder.setTitle("Cancel Ride");
builder.setMessage("Are you sure you want to Cancel Booking?");
builder.setPositiveButtonText("OK");
builder.setNegativeButtonText("CANCEL");
builder.setCancelableOnTouchOutside(false);
break;
case DIALOG_CANCEL_FAILED:
builder.setTitle("Cancellation Failed=");
builder.setMessage(message);
builder.setPositiveButtonText("OK");
break;
case DIALOG_RIDE_TRACKING_NOT_VALID:
builder.setTitle("Not a valid Ride");
builder.setMessage("This ride is already Cancelled or Completed. Thanks you.");
builder.setPositiveButtonText("OK");
break;
case DIALOG_RIDE_COMPLETED:
builder.setTitle("Ride Completed");
if(message != null && !message.isEmpty())
{
builder.setMessage(message);
}
else
builder.setMessage("Your Ride is completed. \n Kindly check your email for receipt.");
builder.setPositiveButtonText("OK");
builder.setCancelableOnTouchOutside(false);
break;
}
if (mIsRunning) {
builder.setRequestCode(id).setTag(DIALOG_TAG).show();
ACTIVE_DIALOG_ID = id;
globalMessage = message;
}
else
android.util.Log.e(TAG, "Not able to show dialog here :-( with id " + id);
}
void cancelOlaBooking(){
if(mMyBooking!=null && mMyBooking.crn!=null) {
// OlaAP<SUF>
// TokenType + " " + AccessToken,
// mMyBooking.crn,
CabApiClientFactory.getCabProvider(CabApiClientFactory.PROVIDER_OLA).cancelRide(mMyBooking.crn,TokenType,AccessToken,
new OlaCallback<CancelResponse>() {
@Override
public void success(CancelResponse cancelResponse, Response response) {
Toast.makeText(TrackMyRideActivity.this, "Booking is Cancelled", Toast.LENGTH_SHORT).show();
ContentValues cv = new ContentValues();
cv.put("BOOKING_STATUS", GenericRydeState.CANCELLED);
try {
DatabaseUtil.updateRideStatus(TrackMyRideActivity.this, cv, mMyBooking.crn);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (mActivityHandler != null)
mActivityHandler.sendMessage(mActivityHandler.obtainMessage(MSG_OLA_CANCEL_SUCCESS));
}
@Override
public void failure(RetrofitError error) {
Log.d(TAG, "CANCEL BOOKING: errro:" + error.getResponse());
showCustomDialog(DIALOG_CANCEL_FAILED, error.getMessage());
super.failure(error);
}
}
);
}
else{
Toast.makeText(this,"Invalid Booking ID, Cannot be cancelled",Toast.LENGTH_LONG).show();
}
}
void cancelUberBooking(){
if(mMyBooking!=null && mMyBooking.crn!=null) {
// UberAPIClient.getUberV1APIClient().deleteRequest(CabTracker.getInstance().getAccessToken(Constants.CAB_GLOBAL.UBER),
// mMyBooking.crn,
CabApiClientFactory.getCabProvider(CabApiClientFactory.PROVIDER_UBER).cancelRide(mMyBooking.crn ,"","",
new UberCallback<Response>() {
@Override
public void success(Response response, Response response2) {
Log.d(TAG,"CANCEL BOOKING: status:"+response.getStatus());
Toast.makeText(TrackMyRideActivity.this,"Booking is Cancelled",Toast.LENGTH_SHORT).show();
//Updating DB post cancellation ride status has to be updated to Cancelled?
ContentValues cv = new ContentValues();
cv.put("BOOKING_STATUS","CANCELLED");
try {
DatabaseUtil.updateRideStatus(TrackMyRideActivity.this, cv, mMyBooking.crn);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if(mActivityHandler!=null)
mActivityHandler.sendMessage(mActivityHandler.obtainMessage(MSG_UBER_CANCEL_SUCCESS));
}
@Override
public void failure(RetrofitError error) {
Log.d(TAG,"CANCEL BOOKING: errro:"+error.getResponse());
showCustomDialog(DIALOG_CANCEL_FAILED, error.getMessage());
super.failure(error);
}
});
}
else{
Toast.makeText(this, "Invalid Booking ID, Cannot be cancelled", Toast.LENGTH_LONG).show();
}
}
boolean doubleBackToExitPressedOnce = false;
private final int MSG_BACK_EXIT = 1010;
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click back again to exit", Toast.LENGTH_SHORT).show();
if(mActivityHandler != null)
mActivityHandler.sendMessageDelayed(mActivityHandler.obtainMessage(MSG_BACK_EXIT), 2000);
}
void callDriver(String phoneno){
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phoneno));
startActivity(intent);
}
void updateBookingDetails(){
if(mMyBooking!=null){
tvDriverName.setText(mMyBooking.driver_name);
tvCarModel.setText(mMyBooking.car_model);
tvCarRegNo.setText(mMyBooking.cab_number);
if(mMyBooking.chauffeurImageUrl!=null)
chauffeurImage.setImageUrl(mMyBooking.chauffeurImageUrl, VolleySingleton.getInstance().getImageLoader());
else
chauffeurImage.setDefaultImageResId(R.drawable.chauffeur_icon);
//We are hardcoding to OLA lets make sure that
}
}
void trackMyBooking(){
if(mMyBooking!=null && mMyBooking.cabCompany.equalsIgnoreCase(Constants.CAB_GLOBAL.UBER.toString())){
// CabTracker.getInstance().trackUberBooking(mMyBooking.crn, callbackRideRequest);
CabApiClientFactory.getCabProvider(CabApiClientFactory.PROVIDER_UBER).getRideStatus(mMyBooking.crn,callbackRideRequest);
}else if(mMyBooking!=null && mMyBooking.cabCompany.equalsIgnoreCase(Constants.CAB_INDIA.OLA.toString())){
trackOlaBooking();
}
}
void trackOlaBooking(){
if(Constants.SIMULATE_BOOKING || (mMyBooking!=null && mMyBooking.booking_status!=null
&& mMyBooking.booking_status.equals("SIMULATION"))){
Log.d(TAG, "SIMULATION MODE: TRACK CAB");
if(booking_status_previous==null) {
mTrackRide = OlaSandBox.getSimulatedClientLocated();
olaCallback.success(mTrackRide, null);
}else if(booking_status_previous.equals((OlaAPIConstants.BOOKING_STATUS.CLIENT_LOCATED))) {
mActivityHandler.sendMessageDelayed(mActivityHandler.obtainMessage(MSG_SIMULATE_OLA_CALL_DRIVER), 1000);
}else if(booking_status_previous.equals((OlaAPIConstants.BOOKING_STATUS.CALL_DRIVER))) {
mActivityHandler.sendMessageDelayed(mActivityHandler.obtainMessage(MSG_SIMULATE_OLA_IN_PROGRESS), 1000);
}else if(booking_status_previous.equals((OlaAPIConstants.BOOKING_STATUS.IN_PROGRESS)))
mActivityHandler.sendMessageDelayed(mActivityHandler.obtainMessage(MSG_SIMULATE_OLA_COMPLETION), 1000);
/*if(isNewBooking) {
insertBookingInfo();
isNewBooking=false;
}*/
return;
}
CabApiClientFactory.getCabProvider(CabApiClientFactory.PROVIDER_OLA).getRideStatus(null, olaCallback);
//CabTracker.getInstance().trackOlaBooking(olaCallback, AccessToken, TokenType);
}
private OlaCallback<TrackRide> olaCallback = new OlaCallback<TrackRide>() {
@Override
public void success(TrackRide trackRide, Response response) {
if (trackRide != null && trackRide.duration != null && Constants.ENABLE_DEBUG_TOAST)
Toast.makeText(TrackMyRideActivity.this, "Status:\"+trackRide.status+\"\n" +
" Booking Status:" + trackRide.booking_status + "+ \nCar Arrival Time:" + trackRide.duration.value, Toast.LENGTH_LONG).show();
else if (trackRide != null && Constants.ENABLE_DEBUG_TOAST)
Toast.makeText(TrackMyRideActivity.this, "Status:" + trackRide.status + "\n Booking Status:" + trackRide.booking_status, Toast.LENGTH_LONG).show();
//proper shallow copy
mTrackRide = (TrackRide) trackRide.clone();
Log.d(TAG, "TRACK RIDE Details: " + mTrackRide.toString());
if (mTrackRide.booking_status.equals(OlaAPIConstants.BOOKING_STATUS.NO_BOOKING)){
showCustomDialog(DIALOG_RIDE_TRACKING_NOT_VALID, null);
}else if (mTrackRide.booking_status.equals(OlaAPIConstants.BOOKING_STATUS.COMPLETED)){
String displayBill = " Total amount is Rs :" + trackRide.trip_info.amount + "\n Ola cash balance :"+ trackRide.ola_money_balance + "\n Payable amount :"+ trackRide.trip_info.payable_amount;
showCustomDialog(DIALOG_RIDE_COMPLETED, displayBill);
ll_cancelride.setVisibility(View.INVISIBLE);
}else if (mTrackRide.booking_status.equals(OlaAPIConstants.BOOKING_STATUS.IN_PROGRESS)){
ll_cancelride.setVisibility(View.INVISIBLE);
if(booking_status_previous==null || booking_status_previous.equals(OlaAPIConstants.BOOKING_STATUS.CLIENT_LOCATED))
Toast.makeText(TrackMyRideActivity.this,"Have a pleasant Ride",Toast.LENGTH_LONG).show();
}else if (mTrackRide.booking_status.equals(OlaAPIConstants.BOOKING_STATUS.CLIENT_LOCATED)
|| mTrackRide.booking_status.equals(OlaAPIConstants.BOOKING_STATUS.CALL_DRIVER)){
ll_cancelride.setVisibility(View.VISIBLE);
}else
ll_cancelride.setVisibility(View.INVISIBLE);
booking_status_previous=mTrackRide.booking_status;
Log.d(TAG, "DRIVER POSITION: lat:" + mTrackRide.driver_lat + " log:" + mTrackRide.driver_lng);
setUpMap();
}
};
private UberCallback<RideRequest> callbackRideRequest = new UberCallback<RideRequest>()
{
@Override
public void success(RideRequest rideRequest, Response response) {
dismissProgressDialog(TrackMyRideActivity.this.getSupportFragmentManager());
if(rideRequest==null && Constants.ENABLE_DEBUG_TOAST){
Toast.makeText(TrackMyRideActivity.this, "RESPONSE: RideRequest is null", Toast.LENGTH_LONG).show();
return;
}
if(rideRequest!=null && rideRequest.getRequest_id()!=null) {
if (rideRequest.getStatus().equalsIgnoreCase(UberStatus.PROCESSING.toString())
|| rideRequest.getStatus().equalsIgnoreCase(UberStatus.ARRIVING.value().toString())
|| rideRequest.getStatus().equalsIgnoreCase(UberStatus.ACCEPTED.value().toString())
|| rideRequest.getStatus().equalsIgnoreCase(UberStatus.IN_PROGRESS.value().toString())
|| rideRequest.getStatus().equalsIgnoreCase(UberStatus.RIDER_CANCELED.value().toString())) {
if (rideRequest.getStatus().equalsIgnoreCase(UberStatus.ARRIVING.toString()))
Toast.makeText(TrackMyRideActivity.this, "Your cab has arrived", Toast.LENGTH_LONG).show();
Log.d(TAG, "REQUEST ID: " + rideRequest.getRequest_id());
if(Constants.ENABLE_DEBUG_TOAST)
Toast.makeText(TrackMyRideActivity.this, "TRACK BOOKING SUCCESS\n"+rideRequest.toString(), Toast.LENGTH_SHORT).show();
JavaUtil.printHTTPResponse(response);
mTrackRide=new TrackRide();//TODO FIXME IMPLEMENT COMMON MODEL CLASS
if(rideRequest.getLocation()!=null) {
mTrackRide.driver_lat = rideRequest.getLocation().latitude;
mTrackRide.driver_lng = rideRequest.getLocation().longitude;
}
adaptUberMyBooking(rideRequest);
updateBookingDetails();
setUpMap();
}else if (rideRequest.getStatus().equalsIgnoreCase(UberStatus.COMPLETED.toString())){
Toast.makeText(TrackMyRideActivity.this,"Your Ride is completed. Kindly check your email :"+rideRequest.getRequest_id() , Toast.LENGTH_LONG).show();
showCustomDialog(DIALOG_RIDE_COMPLETED,null);
}
}
else{
Toast.makeText(TrackMyRideActivity.this,"rideRequest Request Id Id is null" , Toast.LENGTH_LONG).show();
}
}
@Override
public void failure(RetrofitError error) {
dismissProgressDialog(TrackMyRideActivity.this.getSupportFragmentManager());
Log.e(TAG,"MESSAGE="+error.toString());
Log.e(TAG,"MESSAGE RESPONSE="+error.getResponse());
ErrorResponse errorRideResponse=null;
List<Error> errors=null;
try {
errorRideResponse=(ErrorResponse)error.getBodyAs(ErrorResponse.class);
errors=errorRideResponse.getErrors();
} catch (Exception e) {
e.printStackTrace();
}
//TODO THESE ERROS NEED NOT BE HANDLED HERE
//TODO HANDLE RIDE TRACKING STATUS HERE
if (errors!=null && errors.size()>0){
Error responseError=errors.get(0);
if(responseError!=null && responseError.getCode().contains("insufficient_balance")){
//showCustomDialog(DIALOG_NO_FUNDS);
}
}
if(Constants.ENABLE_DEBUG_TOAST)
Toast.makeText(TrackMyRideActivity.this, error.getBody().toString(), Toast.LENGTH_LONG).show();
}
};
private void adaptUberMyBooking(RideRequest rideRequest){
if(mMyBooking==null)
mMyBooking=new MyBooking();
if(rideRequest!=null) {
mMyBooking.crn = rideRequest.getRequest_id();
if (rideRequest.getDriver() != null) {
mMyBooking.driver_name = rideRequest.getDriver().name;
mMyBooking.cab_number = rideRequest.getDriver().phone_number;
}
if (rideRequest.getVehicle() != null) {
mMyBooking.cab_type = rideRequest.getVehicle().make;//TODO CORRECT THIS
mMyBooking.cab_number = rideRequest.getVehicle().license_plate;
mMyBooking.car_model = rideRequest.getVehicle().model;
} else
mMyBooking.cab_type = "SEDAN";//TODO CORRECT THIS
if (rideRequest.getLocation() != null)
mMyBooking.driverLocation=new MapPoint(rideRequest.getLocation().latitude, rideRequest.getLocation().longitude);
if(rideRequest.getDriver()!=null) {
if(rideRequest.getDriver().picture_url!=null)
mMyBooking.chauffeurImageUrl = rideRequest.getDriver().picture_url;
if(rideRequest.getDriver().phone_number!=null && !rideRequest.getDriver().phone_number.equals(""))
mMyBooking.driver_number=rideRequest.getDriver().phone_number;
}
mMyBooking.eta=rideRequest.getEta();
mMyBooking.booking_status=rideRequest.getStatus();//TODO INSERT CORRECT DISPLAY STRING
}
mMyBooking.cabCompany= Constants.CAB_GLOBAL.UBER.toString();
Log.d(TAG, "Uber: Mybooking=" + mMyBooking.toString());
}
private void initRefreshTrackPageTimer(){
mForceStopTimer=false;
Runnable mRunnableTimer = new Runnable() {
@Override
public void run() {
if(mForceStopTimer)
return;
bIsRefreshBooking=true;
trackMyBooking();
mActivityHandler.postDelayed(this, TRACKPAGE_REFRESH_TIME);
}
};
mActivityHandler.postDelayed(mRunnableTimer, 0);
}
private void stopRefreshTrackPageTimer(){
mForceStopTimer=true;
if(mActivityHandler!=null)
mActivityHandler.removeCallbacks(null);
}
@Override
public void onMapReady(GoogleMap googleMap) {
if (mMap == null)
setUpMapIfNeeded();
else
setUpMap();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {@link #setUpMap()} once when {@link #mMap} is not null.
* <p/>
* If it isn't installed {@link com.google.android.gms.maps.SupportMapFragment} (and
* {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
* method in {@link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {@link #mMap} is not null.
*/
private void setUpMap() {
if(mMap==null)
return;
mMap.clear();;
mLatLngBuilder=new LatLngBounds.Builder();
if(mMyBooking!=null && mMyBooking.pickupLoction!=null) {
LatLng latLng = new LatLng(mMyBooking.pickupLoction.getLattitude(), mMyBooking.pickupLoction.getLongitude());
mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.pin))
.position(latLng));
if(!bIsRefreshBooking)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng ,14.0f) );
mLatLngBuilder.include(latLng);
}
if(mTrackRide!=null) {
mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.cab_tracking))
.position(new LatLng(mTrackRide.driver_lat, mTrackRide.driver_lng)));
mLatLngBuilder.include(new LatLng(mTrackRide.driver_lat, mTrackRide.driver_lng));
}
Log.d(TAG, "MAP DRAWING: mMyBooking:"+mMyBooking.toString());
if(mTrackRide!=null)
Log.d(TAG, "MAP DRAWING: mTrackRide:"+mTrackRide.toString());
fixZoom();
}
private void fixZoom() {
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
//mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mLatLngBuilder.build(), 50));
if (mMap == null || mLatLngBuilder.build() == null)
return;
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(mLatLngBuilder.build(), 150));
}
});
}
@Override
public int getActionBarMenuId() {
return INVALID_MENU;
}
@Override
public HashMap<Integer, MenuItem> getMenuItems() {
return null;
}
@Override
public void onDialogTimedOut(int reqCode) {
}
@Override
public void processCustomMessage(Message msg) {
switch (msg.what)
{
case MSG_OLA_CANCEL_SUCCESS:
case MSG_UBER_CANCEL_SUCCESS:
finish();
break;
case MSG_BACK_EXIT:
doubleBackToExitPressedOnce=false;
break;
case MSG_SIMULATE_OLA_COMPLETION:
olaCallback.success(OlaSandBox.getSimulatedTripEnded(), null);
break;
case MSG_SIMULATE_OLA_CLIENT_LOCATED:
olaCallback.success(OlaSandBox.getSimulatedClientLocated(), null);
break;
case MSG_SIMULATE_OLA_CALL_DRIVER:
olaCallback.success(OlaSandBox.getSimulatedCallDriver(), null);
break;
case MSG_SIMULATE_OLA_IN_PROGRESS:
olaCallback.success(OlaSandBox.getSimulatedRideTrackObject(), null);
break;
}
}
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
super.onNewIntent(intent);
}
@Override
protected void onResume() {
super.onResume();
if (dialogIsRunning) {
showCustomDialog(ACTIVE_DIALOG_ID, globalMessage);
}
initRefreshTrackPageTimer();
}
@Override
protected void onPause() {
super.onPause();
DialogFragment df = (DialogFragment) getSupportFragmentManager().findFragmentByTag(DIALOG_TAG);
if (df != null) {
df.dismissAllowingStateLoss();
dialogIsRunning = true;
}
stopRefreshTrackPageTimer();
}
@Override
public void onDestroy() {
super.onDestroy();
stopRefreshTrackPageTimer();
}
@Override
public void onPositiveButtonClicked(int reqCode) {
ACTIVE_DIALOG_ID = 0;
dialogIsRunning = false;
if(reqCode == DIALOG_CONFIRM_CANCELLATION)
CancelBooking();
else if (reqCode == DIALOG_RIDE_COMPLETED){
updateOnCompletion();
finish();
}else if (reqCode == DIALOG_RIDE_TRACKING_NOT_VALID){
try {
if(mMyBooking!=null && mMyBooking.crn!=null)
DatabaseUtil.deleteRydeInfo(TrackMyRideActivity.this, mMyBooking.crn.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
finish();
}
super.onPositiveButtonClicked(reqCode);
}
@Override
public void onNegativeButtonClicked(int reqCode) {
ACTIVE_DIALOG_ID = 0;
dialogIsRunning = false;
super.onNegativeButtonClicked(reqCode);
}
private void updateOnCompletion()
{
ContentValues cv = new ContentValues();
cv.put("BOOKING_STATUS","COMPLETED");
try {
DatabaseUtil.updateRideStatus(TrackMyRideActivity.this, cv, mMyBooking.crn);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
|
24426_2 | package nl.hsleiden.iipsen.firebase_observable;
import java.io.IOException;
import com.google.cloud.firestore.DocumentReference;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.EventListener;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreException;
import com.google.firebase.database.annotations.Nullable;
/**
* Demonstratie van cloud firestore met eventlistener.
*
*/
public class App
{
public App() throws IOException, InterruptedException {
Database setup = new Database();
Firestore db = setup.getFirestoreDatabase();
DocumentReference docRef = db.collection("sampleData").document("inspiration");
// De listener
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirestoreException error) {
if (error != null) {
System.err.println("Listen failed: " + error);
return;
}
if (snapshot != null && snapshot.exists()) {
System.out.println("Current data: " + snapshot.getData());
} else {
System.out.print("Current data: null");
}
}
});
this.waitForFirebaseObservable(100000);
}
public static void main( String[] args ) throws IOException, InterruptedException
{
new App();
}
public synchronized void waitForFirebaseObservable(int ms) throws InterruptedException {
// Deze methode gebruiken we alleen om het programma niet te laten beeïndigen.
// Zodat we kunnen 'luisteren' naar de updates.
int counter = 0;
for (int i = 0; i < ms; i++) {
if(counter % 1000 == 0) {
System.out.println("waiting for: " + counter + "ms");
}
this.wait(1);
counter++;
}
System.out.println("Exiting program");
}
}
| Admiraal/iipsen | firebase_observable/src/main/java/nl/hsleiden/iipsen/firebase_observable/App.java | 536 | // Deze methode gebruiken we alleen om het programma niet te laten beeïndigen. | line_comment | nl | package nl.hsleiden.iipsen.firebase_observable;
import java.io.IOException;
import com.google.cloud.firestore.DocumentReference;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.EventListener;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreException;
import com.google.firebase.database.annotations.Nullable;
/**
* Demonstratie van cloud firestore met eventlistener.
*
*/
public class App
{
public App() throws IOException, InterruptedException {
Database setup = new Database();
Firestore db = setup.getFirestoreDatabase();
DocumentReference docRef = db.collection("sampleData").document("inspiration");
// De listener
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirestoreException error) {
if (error != null) {
System.err.println("Listen failed: " + error);
return;
}
if (snapshot != null && snapshot.exists()) {
System.out.println("Current data: " + snapshot.getData());
} else {
System.out.print("Current data: null");
}
}
});
this.waitForFirebaseObservable(100000);
}
public static void main( String[] args ) throws IOException, InterruptedException
{
new App();
}
public synchronized void waitForFirebaseObservable(int ms) throws InterruptedException {
// Deze <SUF>
// Zodat we kunnen 'luisteren' naar de updates.
int counter = 0;
for (int i = 0; i < ms; i++) {
if(counter % 1000 == 0) {
System.out.println("waiting for: " + counter + "ms");
}
this.wait(1);
counter++;
}
System.out.println("Exiting program");
}
}
|
213743_6 | package cui;
public class Voorbeeld1DimArray {
public static void main(String[] args) {
new Voorbeeld1DimArray().start();
}
private void start() {
// declaratie
int[] a;
// creatie
a = new int[5];
// declaratie en creatie
int[] b = new int[10];
//Elk element van de array wordt
//automatisch geïnitialiseerd bij de creatie van de array.
weergeven(a);
weergeven(b);
System.out.printf("lengte van array a is %d%n", a.length);
System.out.printf("lengte van array b is %d%n", b.length);
// Het eerste element van a opvullen met 5
// Het laatste element van a opvullen met 20
//weergeven(a);
// Initialisatie van de array-elementen
/*int[] array = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
weergeven(array);
*/
//Enhanced for
//vb elementen van array doorlopen, som bepalen
/*int som = 0;
for( ){
som += getal;
}
System.out.println(som);
*/
//Enhanced for kan geen elementen van een array opvullen
//Enhanced for kan enkel de array doorlopen (niet wijzigen)
//WERKT NIET:
/*
System.out.println( );
for (int element: a)
{
element = 2;
}
System.out.println( Arrays.toString(a));
*/
//Nodig voor de oefeningen: strings concateneren d.m.v.
//String.format werkt zoals een printf
double[] decGetallen = {2.4, 5.689, 8.45, 9.7};
String zin = "";
for (double element: decGetallen)
zin += String.format("%.2f ", element);
//System.out.println(zin);
}
private void weergeven(int[] array) {
System.out.printf("%s%8s%n", "Index", "Value");
for (int index = 0; index < array.length; index++) {
System.out.printf("%5d%8d%n", index, array[index]);
}
System.out.println();
}
}
| AdrenalineGhost/Projects | java/H4/Theory/Theory/src/cui/Voorbeeld1DimArray.java | 661 | // Het laatste element van a opvullen met 20 | line_comment | nl | package cui;
public class Voorbeeld1DimArray {
public static void main(String[] args) {
new Voorbeeld1DimArray().start();
}
private void start() {
// declaratie
int[] a;
// creatie
a = new int[5];
// declaratie en creatie
int[] b = new int[10];
//Elk element van de array wordt
//automatisch geïnitialiseerd bij de creatie van de array.
weergeven(a);
weergeven(b);
System.out.printf("lengte van array a is %d%n", a.length);
System.out.printf("lengte van array b is %d%n", b.length);
// Het eerste element van a opvullen met 5
// Het l<SUF>
//weergeven(a);
// Initialisatie van de array-elementen
/*int[] array = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
weergeven(array);
*/
//Enhanced for
//vb elementen van array doorlopen, som bepalen
/*int som = 0;
for( ){
som += getal;
}
System.out.println(som);
*/
//Enhanced for kan geen elementen van een array opvullen
//Enhanced for kan enkel de array doorlopen (niet wijzigen)
//WERKT NIET:
/*
System.out.println( );
for (int element: a)
{
element = 2;
}
System.out.println( Arrays.toString(a));
*/
//Nodig voor de oefeningen: strings concateneren d.m.v.
//String.format werkt zoals een printf
double[] decGetallen = {2.4, 5.689, 8.45, 9.7};
String zin = "";
for (double element: decGetallen)
zin += String.format("%.2f ", element);
//System.out.println(zin);
}
private void weergeven(int[] array) {
System.out.printf("%s%8s%n", "Index", "Value");
for (int index = 0; index < array.length; index++) {
System.out.printf("%5d%8d%n", index, array[index]);
}
System.out.println();
}
}
|
113361_19 | package Main;
import model.*;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import persistence.HibernateUtil;
import persistence.TestData;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
Scanner scanner = new Scanner(System.in);
static Session session;
static Transaction tx;
public static void main(String[] args) throws ParseException {
Main me = new Main();
me.askTestData();
//session and transaction placed here because if you do want testdata you will open 2 session which is not allowed by hibernate
session = HibernateUtil.getSessionFactory().getCurrentSession();
tx = session.beginTransaction();
me.runConsole();
tx.commit();
}
//ask for testdata
private void askTestData() {
System.out.println("Wilt u de testdata laden? (y/n)");
if (scanner.next().equals("y")) {
TestData td = new TestData();
td.runTestData();
}
}
//start and run console app
private void runConsole() throws ParseException {
//init menu
int menu = getOptionMainMenu();
while (menu != 5) {
//print menu and returns the chosen option
switch (menu) {
case 1:
//maak festivalganger
System.out.println("Geef je naam:");
FestivalGanger buyer = new FestivalGanger();
buyer.setNaam(scanner.nextLine());
//getFestival
Festival festival = getFestival();
//maak ticketverkoop
TicketVerkoop sale = new TicketVerkoop();
sale.setFestivalGanger(buyer);
sale.setTimestamp(new Date());
sale.setType(TicketVerkoop.VerkoopsType.WEB);
sale.setFestival(festival);
//get tickettypes
System.out.println("Welk tickettype wil je?");
Query getticketTypes = session.createQuery("from TicketType where naam like :festivalname");
String festivalname = "%" + festival.getName() + "%";
getticketTypes.setString("festivalname", festivalname);
List ticketTypes = getticketTypes.list();
//kies tickettype
System.out.println("Kies je tickettype:");
for (int i = 0; i < ticketTypes.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((TicketType) ticketTypes.get(i)).getNaam());
}
int typeChoice = scanner.nextInt();
scanner.nextLine();
TicketType tt = (TicketType) ticketTypes.get(typeChoice - 1);
//kies aantal
System.out.println("Hoeveel tickets wil je?:");
int aantalTickets = scanner.nextInt();
scanner.nextLine();
//maak tickets
session.saveOrUpdate(buyer);
session.saveOrUpdate(sale);
for (int i = 0; i < aantalTickets; i++) {
Ticket ticket = new Ticket();
ticket.setTicketType(tt);
ticket.setTicketVerkoop(sale);
session.saveOrUpdate(ticket);
}
System.out.print("Het totaal bedraagt:");
System.out.println("€" + (tt.getPrijs() * aantalTickets));
break;
case 2:
//getfestival
Festival festival2 = getFestival();
//getZone
Zone zone = getZone(festival2);
//in out?
System.out.println("In or out? (in = 1 / out = 0)");
int isInInt = scanner.nextInt();
scanner.nextLine();
Boolean isIn;
//isIn = true if isInInt = 1 else false
isIn = isInInt == 1;
//poslbandID
System.out.println("Geef de polsbandId:");
int polsbandID = scanner.nextInt();
scanner.nextLine();
//gentracking
Tracking tracking = new Tracking();
tracking.setZone(zone);
tracking.setTimestamp(new Date());
tracking.setDirection(isIn);
tracking.setPolsbandId(polsbandID);
session.saveOrUpdate(tracking);
break;
case 3:
//get festivals
Festival festival3 = getFestival();
//get zones
Zone zone2 = getZone(festival3);
//get date
Query getDates = session.createQuery("select op.startTime from FestivalDag fd, Optreden op where fd.festival = :festival and op.festivalDag = fd");
getDates.setParameter("festival", festival3);
List dates = getDates.list();
System.out.println("Kies de datum:");
for (int i = 0; i < dates.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println((dates.get(i)).toString());
}
int datePick = scanner.nextInt();
scanner.nextLine();
//get optredens in zone where startdate < date > enddate
Query getOptredens = session.createQuery("from Optreden op where :date > op.startTime and :date < op.endTime and op.zone = :zone");
//add 1 min
Calendar cal = Calendar.getInstance();
cal.setTime((Date) dates.get(datePick - 1));
cal.add(Calendar.MINUTE, 1);
getOptredens.setParameter("date", cal.getTime());
getOptredens.setParameter("zone", zone2);
List optredens = getOptredens.list();
//output
System.out.println("");
System.out.println("Optreden: ");
for (Object o : optredens) {
System.out.println(((Optreden) o).getArtiest().getNaam());
}
break;
case 4:
//get artiests
Query getArtiests = session.createQuery("from Artiest");
List artiests = getArtiests.list();
System.out.println("Kies je artiest");
for (int i = 0; i < artiests.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Artiest) artiests.get(i)).getNaam());
}
int artiestPick = scanner.nextInt();
scanner.nextLine();
//get dates
SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy");
System.out.println("Geef datum 1 (mm/dd/yyyy):");
String date1 = scanner.next();
System.out.println("Geeft datum 2 (mm/dd/yyyy)");
String date2 = scanner.next();
Date d1 = df.parse(date1.trim());
Date d2 = df.parse(date2.trim());
//get festivals
Query getFestivalDaysFromArtiest = session.createQuery("select o.festivalDag from Optreden o where o.artiest = :artiest ");
getFestivalDaysFromArtiest.setParameter("artiest", artiests.get(artiestPick - 1));
List festivaldays = getFestivalDaysFromArtiest.list();
Set<Festival> setFestival = new HashSet<>();
for (Object festivalday1 : festivaldays) {
FestivalDag festivalday = (FestivalDag) festivalday1;
Query getFestivals = session.createQuery("select fd.festival from FestivalDag fd, Optreden o where fd = :festivaldag AND fd.date BETWEEN :date1 AND :date2");
getFestivals.setParameter("festivaldag", festivalday);
getFestivals.setDate("date1", d1);
getFestivals.setDate("date2", d2);
setFestival.addAll(getFestivals.list());
}
System.out.println("Festivals: ");
for (Festival f : setFestival) {
System.out.println(f.getName());
}
break;
}
//gives the menu again
menu = getOptionMainMenu();
}
}
private int getOptionMainMenu() {
System.out.println("");
System.out.println("Kies welke opdracht je wilt uitvoeren:");
//options
System.out.println("1: Registratie van een verkoop");
System.out.println("2: Opslaan passage");
System.out.println("3: Zoeken otreden");
System.out.println("4: Zoeken festival");
System.out.println("5: Stoppen");
int result = scanner.nextInt();
scanner.nextLine();
return result;
}
private Festival getFestival() {
//get festivals
Query getFestivals = session.createQuery("from Festival");
List festivals = getFestivals.list();
//kies festival
System.out.println("Kies je festival:");
for (int i = 0; i < festivals.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Festival) festivals.get(i)).getName());
}
int festivalChoice = scanner.nextInt();
scanner.nextLine();
return (Festival) festivals.get(festivalChoice - 1);
}
private Zone getZone(Festival festival) {
//getzones
Query getZones = session.createQuery("from Zone zone where zone.festival = :festival and zone.naam like '%Stage%' ");
getZones.setParameter("festival", festival);
List zones = getZones.list();
//select zone
System.out.println("Welke zone?");
for (int i = 0; i < zones.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Zone) zones.get(i)).getNaam());
}
int zone = scanner.nextInt();
scanner.nextLine();
return (Zone) zones.get(zone - 1);
}
}
| AdriVanHoudt/D-M-Project | Project Deel 1/src/Main/Main.java | 2,401 | //get zones | line_comment | nl | package Main;
import model.*;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import persistence.HibernateUtil;
import persistence.TestData;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
Scanner scanner = new Scanner(System.in);
static Session session;
static Transaction tx;
public static void main(String[] args) throws ParseException {
Main me = new Main();
me.askTestData();
//session and transaction placed here because if you do want testdata you will open 2 session which is not allowed by hibernate
session = HibernateUtil.getSessionFactory().getCurrentSession();
tx = session.beginTransaction();
me.runConsole();
tx.commit();
}
//ask for testdata
private void askTestData() {
System.out.println("Wilt u de testdata laden? (y/n)");
if (scanner.next().equals("y")) {
TestData td = new TestData();
td.runTestData();
}
}
//start and run console app
private void runConsole() throws ParseException {
//init menu
int menu = getOptionMainMenu();
while (menu != 5) {
//print menu and returns the chosen option
switch (menu) {
case 1:
//maak festivalganger
System.out.println("Geef je naam:");
FestivalGanger buyer = new FestivalGanger();
buyer.setNaam(scanner.nextLine());
//getFestival
Festival festival = getFestival();
//maak ticketverkoop
TicketVerkoop sale = new TicketVerkoop();
sale.setFestivalGanger(buyer);
sale.setTimestamp(new Date());
sale.setType(TicketVerkoop.VerkoopsType.WEB);
sale.setFestival(festival);
//get tickettypes
System.out.println("Welk tickettype wil je?");
Query getticketTypes = session.createQuery("from TicketType where naam like :festivalname");
String festivalname = "%" + festival.getName() + "%";
getticketTypes.setString("festivalname", festivalname);
List ticketTypes = getticketTypes.list();
//kies tickettype
System.out.println("Kies je tickettype:");
for (int i = 0; i < ticketTypes.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((TicketType) ticketTypes.get(i)).getNaam());
}
int typeChoice = scanner.nextInt();
scanner.nextLine();
TicketType tt = (TicketType) ticketTypes.get(typeChoice - 1);
//kies aantal
System.out.println("Hoeveel tickets wil je?:");
int aantalTickets = scanner.nextInt();
scanner.nextLine();
//maak tickets
session.saveOrUpdate(buyer);
session.saveOrUpdate(sale);
for (int i = 0; i < aantalTickets; i++) {
Ticket ticket = new Ticket();
ticket.setTicketType(tt);
ticket.setTicketVerkoop(sale);
session.saveOrUpdate(ticket);
}
System.out.print("Het totaal bedraagt:");
System.out.println("€" + (tt.getPrijs() * aantalTickets));
break;
case 2:
//getfestival
Festival festival2 = getFestival();
//getZone
Zone zone = getZone(festival2);
//in out?
System.out.println("In or out? (in = 1 / out = 0)");
int isInInt = scanner.nextInt();
scanner.nextLine();
Boolean isIn;
//isIn = true if isInInt = 1 else false
isIn = isInInt == 1;
//poslbandID
System.out.println("Geef de polsbandId:");
int polsbandID = scanner.nextInt();
scanner.nextLine();
//gentracking
Tracking tracking = new Tracking();
tracking.setZone(zone);
tracking.setTimestamp(new Date());
tracking.setDirection(isIn);
tracking.setPolsbandId(polsbandID);
session.saveOrUpdate(tracking);
break;
case 3:
//get festivals
Festival festival3 = getFestival();
//get z<SUF>
Zone zone2 = getZone(festival3);
//get date
Query getDates = session.createQuery("select op.startTime from FestivalDag fd, Optreden op where fd.festival = :festival and op.festivalDag = fd");
getDates.setParameter("festival", festival3);
List dates = getDates.list();
System.out.println("Kies de datum:");
for (int i = 0; i < dates.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println((dates.get(i)).toString());
}
int datePick = scanner.nextInt();
scanner.nextLine();
//get optredens in zone where startdate < date > enddate
Query getOptredens = session.createQuery("from Optreden op where :date > op.startTime and :date < op.endTime and op.zone = :zone");
//add 1 min
Calendar cal = Calendar.getInstance();
cal.setTime((Date) dates.get(datePick - 1));
cal.add(Calendar.MINUTE, 1);
getOptredens.setParameter("date", cal.getTime());
getOptredens.setParameter("zone", zone2);
List optredens = getOptredens.list();
//output
System.out.println("");
System.out.println("Optreden: ");
for (Object o : optredens) {
System.out.println(((Optreden) o).getArtiest().getNaam());
}
break;
case 4:
//get artiests
Query getArtiests = session.createQuery("from Artiest");
List artiests = getArtiests.list();
System.out.println("Kies je artiest");
for (int i = 0; i < artiests.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Artiest) artiests.get(i)).getNaam());
}
int artiestPick = scanner.nextInt();
scanner.nextLine();
//get dates
SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy");
System.out.println("Geef datum 1 (mm/dd/yyyy):");
String date1 = scanner.next();
System.out.println("Geeft datum 2 (mm/dd/yyyy)");
String date2 = scanner.next();
Date d1 = df.parse(date1.trim());
Date d2 = df.parse(date2.trim());
//get festivals
Query getFestivalDaysFromArtiest = session.createQuery("select o.festivalDag from Optreden o where o.artiest = :artiest ");
getFestivalDaysFromArtiest.setParameter("artiest", artiests.get(artiestPick - 1));
List festivaldays = getFestivalDaysFromArtiest.list();
Set<Festival> setFestival = new HashSet<>();
for (Object festivalday1 : festivaldays) {
FestivalDag festivalday = (FestivalDag) festivalday1;
Query getFestivals = session.createQuery("select fd.festival from FestivalDag fd, Optreden o where fd = :festivaldag AND fd.date BETWEEN :date1 AND :date2");
getFestivals.setParameter("festivaldag", festivalday);
getFestivals.setDate("date1", d1);
getFestivals.setDate("date2", d2);
setFestival.addAll(getFestivals.list());
}
System.out.println("Festivals: ");
for (Festival f : setFestival) {
System.out.println(f.getName());
}
break;
}
//gives the menu again
menu = getOptionMainMenu();
}
}
private int getOptionMainMenu() {
System.out.println("");
System.out.println("Kies welke opdracht je wilt uitvoeren:");
//options
System.out.println("1: Registratie van een verkoop");
System.out.println("2: Opslaan passage");
System.out.println("3: Zoeken otreden");
System.out.println("4: Zoeken festival");
System.out.println("5: Stoppen");
int result = scanner.nextInt();
scanner.nextLine();
return result;
}
private Festival getFestival() {
//get festivals
Query getFestivals = session.createQuery("from Festival");
List festivals = getFestivals.list();
//kies festival
System.out.println("Kies je festival:");
for (int i = 0; i < festivals.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Festival) festivals.get(i)).getName());
}
int festivalChoice = scanner.nextInt();
scanner.nextLine();
return (Festival) festivals.get(festivalChoice - 1);
}
private Zone getZone(Festival festival) {
//getzones
Query getZones = session.createQuery("from Zone zone where zone.festival = :festival and zone.naam like '%Stage%' ");
getZones.setParameter("festival", festival);
List zones = getZones.list();
//select zone
System.out.println("Welke zone?");
for (int i = 0; i < zones.size(); i++) {
System.out.print((i + 1) + ": ");
System.out.println(((Zone) zones.get(i)).getNaam());
}
int zone = scanner.nextInt();
scanner.nextLine();
return (Zone) zones.get(zone - 1);
}
}
|
127863_1 | package be.kdg.patterns.model;
import be.kdg.patterns.data.User;
/**
* Vul aan waar nodig (security proxy pattern)
*/
public class KlantProxy implements Klant {
private final KlantImpl klant;
/**
* Deze constructor maakt een KlantImpl object aan, maar alleen
* als het rekeningnummer bestaat en het bijhorende wachtwoord correct
* wordt ingegeven (anders wordt een foutmelding gegeven en wordt de uitvoering
* van het programma via System.exit(1) afgebroken.
* Maakt gebruik van de methode autenticate (zie verder).
*
* @param naam De naam van de klant
* @param rekeningNummer Het rekeningnummer van de klant
*/
public KlantProxy(String naam, String rekeningNummer) {
if (!autenticate(rekeningNummer)) {
System.out.println("Login fout, geen toegang!");
System.exit(1);
}
klant = new KlantImpl(naam, rekeningNummer);
}
public double getSaldo() {
return 0; // vul aan
}
public void doeStorting(double bedrag) {
// vul aan
}
public void haalAf(double bedrag) {
// vul aan
}
public void schrijfOver(double bedrag, String rekeningNummer) {
// vul aan
}
/**
* Deze methode haalt uit Users eerst het user object op met het overeenstemmende
* rekeningnummer. Indien dit gevonden wordt dan wordt het wachtwoord gevraagd
* (via de overeenstemmende methode in de klasse User).
*
* @param rekeningNummer Het rekeningnummer van de klant.
* @return true als de user bestaat en het juiste wachtwoord ingegeven heeft.
*/
private boolean autenticate(String rekeningNummer) {
return false; // vul aan
}
private User getUser(String rekeningNummer) {
// vul aan, roep deze methode op bij de methode autenticate
return null;
}
public void wijzigWachtwoord() {
// vul aan
}
}
| AdriVanHoudt/School | KdG12-13/Java/Oef/Week5.ProxyProtection/src/be/kdg/patterns/model/KlantProxy.java | 508 | /**
* Deze constructor maakt een KlantImpl object aan, maar alleen
* als het rekeningnummer bestaat en het bijhorende wachtwoord correct
* wordt ingegeven (anders wordt een foutmelding gegeven en wordt de uitvoering
* van het programma via System.exit(1) afgebroken.
* Maakt gebruik van de methode autenticate (zie verder).
*
* @param naam De naam van de klant
* @param rekeningNummer Het rekeningnummer van de klant
*/ | block_comment | nl | package be.kdg.patterns.model;
import be.kdg.patterns.data.User;
/**
* Vul aan waar nodig (security proxy pattern)
*/
public class KlantProxy implements Klant {
private final KlantImpl klant;
/**
* Deze c<SUF>*/
public KlantProxy(String naam, String rekeningNummer) {
if (!autenticate(rekeningNummer)) {
System.out.println("Login fout, geen toegang!");
System.exit(1);
}
klant = new KlantImpl(naam, rekeningNummer);
}
public double getSaldo() {
return 0; // vul aan
}
public void doeStorting(double bedrag) {
// vul aan
}
public void haalAf(double bedrag) {
// vul aan
}
public void schrijfOver(double bedrag, String rekeningNummer) {
// vul aan
}
/**
* Deze methode haalt uit Users eerst het user object op met het overeenstemmende
* rekeningnummer. Indien dit gevonden wordt dan wordt het wachtwoord gevraagd
* (via de overeenstemmende methode in de klasse User).
*
* @param rekeningNummer Het rekeningnummer van de klant.
* @return true als de user bestaat en het juiste wachtwoord ingegeven heeft.
*/
private boolean autenticate(String rekeningNummer) {
return false; // vul aan
}
private User getUser(String rekeningNummer) {
// vul aan, roep deze methode op bij de methode autenticate
return null;
}
public void wijzigWachtwoord() {
// vul aan
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.