I would create free app for muslims which will notify pray time ( namaz time).
I dont know quite a few how to measure pray time (Namaz time).
I saw some example code, but these codes were wrong for My Country (UZBEKISTAN ).
Please, show or explain how to measure Namaz time for Uzbekistan or any country depending on geolocation.
import 'dart:collection';
import 'dart:math' as math;
import 'dart:core';
void main() {
double latitude = 41.311081;
double longitude = 69.240562;
double timezone = 5;
// Test Prayer times here
// PrayTime prayers = new PrayTime();
PrayerTime prayers = new PrayerTime();
prayers.setTimeFormat(prayers.getTime24());
prayers.setCalcMethod(prayers.getISNA());
prayers.setAsrJuristic(prayers.getHanafi());
prayers.setAdjustHighLats(prayers.getAdjustHighLats());
List<int>offsets = [0, 0, 0, 0, 0, 0, 0]; // {Fajr,Sunrise,Dhuhr,Asr,Sunset,Maghrib,Isha}
prayers.tune(offsets);
List<String> prayerTimes = prayers.getPrayerTimes(DateTime.now(),
latitude, longitude, timezone);
List<String> prayerNames = prayers.getTimeNames();
for (int i = 0; i < prayerTimes.length; i++) {
print(prayerNames[i] + " - " + prayerTimes[i]);
}
}
class PrayerTime {
// ---------------------- Global Variables --------------------
int _calcMethod; // caculation method
int _asrJuristic; // Juristic method for Asr
int _dhuhrMinutes; // minutes after mid-day for Dhuhr
int _adjustHighLats; // adjusting method for higher latitudes
int _timeFormat; // time format
double _lat; // latitude
double _lng; // longitude
double _timeZone; // time-zone
double _jDate; // Julian date
// ------------------------------------------------------------
// Calculation Methods
int _jafri; // Ithna Ashari
int _karachi; // University of Islamic Sciences, Karachi
int _iSNA; // Islamic Society of North America (ISNA)
int _mWL; // Muslim World League (MWL)
int _makkah; // Umm al-Qura, Makkah
int _egypt; // Egyptian General Authority of Survey
int _custom; // Custom Setting
int _tehran; // Institute of Geophysics, University of Tehran
// Juristic Methods
int _shaffi; // Shafii (standard)
int _hanafi; // Hanafi
// Adjusting Methods for Higher Latitudes
int _none; // No adjustment
int _midNight; // middle of night
int _oneSeventh; // 1/7th of night
int _angleBased; // angle/60th of night
// Time Formats
int _time24; // 24-hour format
int _time12; // 12-hour format
int _time12Ns; // 12-hour format with no suffix
int _floating; // floating point number
// Time Names
List<String> _timeNames;
String _invalidTime; // The string used for invalid times
// --------------------- Technical Settings --------------------
int _numIterations;
// ------------------- Calc Method Parameters --------------------
Map<int, List<double>> _methodParams;
/*
* this.methodParams[methodNum] = new Array(fa, ms, mv, is, iv);
*
* fa : fajr angle ms : maghrib selector (0 = angle; 1 = minutes after
* sunset) mv : maghrib parameter value (in angle or minutes) is : isha
* selector (0 = angle; 1 = minutes after maghrib) iv : isha parameter value
* (in angle or minutes)
*/
List<double> _prayerTimesCurrent;
List<int> _offsets;
PrayerTime() {
this.setCalcMethod(0);
this.setAsrJuristic(0);
this.setDhuhrMinutes(0);
this.setAdjustHighLats(1);
this.setTimeFormat(0);
// Calculation Methods
this.setJafari(0); // Ithna Ashari
this.setKarachi(1); // University of Islamic Sciences, Karachi
this.setISNA(2); // Islamic Society of North America (ISNA)
this.setMWL(3); // Muslim World League (MWL)
this.setMakkah(4); // Umm al-Qura, Makkah
this.setEgypt(5); // Egyptian General Authority of Survey
this.setTehran(6); // Institute of Geophysics, University of Tehran
this.setCustom(7); // Custom Setting
// Juristic Methods
this.setShafii(0); // Shafii (standard)
this.setHanafi(1); // Hanafi
// Adjusting Methods for Higher Latitudes
this.setNone(0); // No adjustment
this.setMidNight(1); // middle of night
this.setOneSeventh(2); // 1/7th of night
this.setAngleBased(3); // angle/60th of night
// Time Formats
this.setTime24(0); // 24-hour format
this.setTime12(1); // 12-hour format
this.setTime12NS(2); // 12-hour format with no suffix
this.setFloating(3); // floating point number
// Time Names
_timeNames = new List<String>();
_timeNames.add("Fajr");
_timeNames.add("Sunrise");
_timeNames.add("Dhuhr");
_timeNames.add("Asr");
_timeNames.add("Sunset");
_timeNames.add("Maghrib");
_timeNames.add("Isha");
_invalidTime = "-----"; // The string used for invalid times
// --------------------- Technical Settings --------------------
this.setNumIterations(1); // number of iterations needed to compute
// times
// ------------------- Calc Method Parameters --------------------
// Tuning offsets {fajr, sunrise, dhuhr, asr, sunset, maghrib, isha}
_offsets = new List<int>(7);
_offsets[0] = 0;
_offsets[1] = 0;
_offsets[2] = 0;
_offsets[3] = 0;
_offsets[4] = 0;
_offsets[5] = 0;
_offsets[6] = 0;
/*
*
* fa : fajr angle ms : maghrib selector (0 = angle; 1 = minutes after
* sunset) mv : maghrib parameter value (in angle or minutes) is : isha
* selector (0 = angle; 1 = minutes after maghrib) iv : isha parameter
* value (in angle or minutes)
*/
_methodParams = new HashMap<int, List<double>>();
// Jafari
List<double> _jValues = [16, 0, 4, 0, 14];
_methodParams[this.getJafari()] = _jValues;
// Karachi
List<double> _kValues = [18, 1, 0, 0, 18];
_methodParams[this.getKarachi()] = _kValues;
// ISNA
List<double> _iValues = [15, 1, 0, 0, 15];
_methodParams[this.getISNA()] = _iValues;
// MWL
List<double> _mwValues = [18, 1, 0, 0, 17];
_methodParams[this.getMWL()] = _mwValues;
// Makkah
List<double> _mkValues = [18.5, 1, 0, 1, 90];
_methodParams[this.getMakkah()] = _mkValues;
// Egypt
List<double> _eValues = [19.5, 1, 0, 0, 17.5];
_methodParams[this.getEgypt()] = _eValues;
// Tehran
List<double> _tValues = [17.7, 0, 4.5, 0, 14];
_methodParams[this.getTehran()] = _tValues;
// Custom
List<double> _cValues = [18, 1, 0, 0, 17];
_methodParams[this.getCustom()] = _cValues;
}
// ---------------------- Trigonometric Functions -----------------------
// range reduce angle in degrees.
double _fixAngle(double a) {
a = a - (360 * ((a / 360.0).floor()));
a = a < 0 ? (a + 360) : a;
return a;
}
//range reduce hours to 0..23
double _fixHour(double a) {
a = a - 24.0 * (a / 24.0).floor();
a = a < 0 ? (a + 24) : a;
return a;
}
// radian to degree
double _radiansToDegrees(double alpha) {
return ((alpha * 180.0) / math.pi);
}
// deree to radian
double _degreesToRadians(double alpha) {
return ((alpha * math.pi) / 180.0);
}
// degree sin
double _dsin(double d) {
return (math.sin(_degreesToRadians(d)));
}
// degree cos
double _dcos(double d) {
return (math.cos(_degreesToRadians(d)));
}
// degree tan
double _dtan(double d) {
return (math.tan(_degreesToRadians(d)));
}
// degree arcsin
double _darcsin(double x) {
double val = math.asin(x);
return _radiansToDegrees(val);
}
// degree arccos
double darccos(double x) {
double val = math.acos(x);
return _radiansToDegrees(val);
}
// degree arctan
double _darctan(double x) {
double val = math.atan(x);
return _radiansToDegrees(val);
}
// degree arctan2
double _darctan2(double y, double x) {
double val = math.atan2(y, x);
return _radiansToDegrees(val);
}
// degree arccot
double darccot(double x) {
double val = math.atan2(1.0, x);
return _radiansToDegrees(val);
}
// ---------------------- Time-Zone Functions -----------------------
// compute local time-zone for a specific date
/* getTimeZone1() {
TimeZone timez = TimeZone.;
double hoursDiff = (timez.getRawOffset() / 1000.0) / 3600;
return hoursDiff;
}
// compute base time-zone of the system
getBaseTimeZone() {
TimeZone timez = TimeZone.getDefault();
double hoursDiff = (timez.getRawOffset() / 1000.0) / 3600;
return hoursDiff;
}
// detect daylight saving in a given date
detectDaylightSaving() {
TimeZone timez = TimeZone.UTC;
double hoursDiff = timez.getDSTSavings();
return hoursDiff;
}*/
// ---------------------- Julian Date Functions -----------------------
// calculate julian date from a calendar date
julianDate(int year, int month, int day) {
if (month <= 2) {
year -= 1;
month += 12;
}
double A = (year / 100.0).floorToDouble();
double B = 2 - A + (A / 4.0).floor();
double JD = (365.25 * (year + 4716)).floor() +
(30.6001 * (month + 1)).floor() +
day +
B -
1524.5;
return JD;
}
/*// convert a calendar date to julian date (second method)
calcJD(int year, int month, int day) {
double J1970 = 2440588.0;
Date date = new Date(year, month - 1, day);
double ms = date.getTime(); // # of milliseconds since midnight Jan 1,
// 1970
double days = (ms / (1000.0 * 60.0 * 60.0 * 24.0)).floorToDouble();
return J1970 + days - 0.5;
}*/
//
// ---------------------- Calculation Functions -----------------------
// ---------------------- Calculation Functions -----------------------
// References:
// http://www.ummah.net/astronomy/saltime
// http://aa.usno.navy.mil/faq/docs/SunApprox.html
// compute declination angle of sun and equation of time
List<double> sunPosition(double jd) {
double D = jd - 2451545;
double g = _fixAngle(357.529 + 0.98560028 * D);
double q = _fixAngle(280.459 + 0.98564736 * D);
double L = _fixAngle(q + (1.915 * _dsin(g)) + (0.020 * _dsin(2 * g)));
// double R = 1.00014 - 0.01671 * [self dcos:g] - 0.00014 * [self dcos:
// (2*g)];
double e = 23.439 - (0.00000036 * D);
double d = _darcsin(_dsin(e) * _dsin(L));
double RA = (_darctan2((_dcos(e) * _dsin(L)), (_dcos(L)))) / 15.0;
RA = _fixHour(RA);
double EqT = q / 15.0 - RA;
List<double> sPosition = new List(2);
sPosition[0] = d;
sPosition[1] = EqT;
return sPosition;
}
// compute equation of time
double equationOfTime(double jd) {
double eq = sunPosition(jd)[1];
return eq;
}
// compute declination angle of sun
double sunDeclination(double jd) {
double d = sunPosition(jd)[0];
return d;
}
// compute mid-day (Dhuhr, Zawal) time
double computeMidDay(double t) {
double T = equationOfTime(this.getJDate() + t);
double Z = _fixHour(12 - T);
return Z;
}
// compute time for a given angle G
double computeTime(double G, double t) {
double D = sunDeclination(this.getJDate() + t);
double Z = computeMidDay(t);
double Beg = -_dsin(G) - _dsin(D) * _dsin(this.getLat());
double Mid = _dcos(D) * _dcos(this.getLat());
double V = darccos(Beg / Mid) / 15.0;
return Z + (G > 90 ? -V : V);
}
// compute the time of Asr
// Shafii: step=1, Hanafi: step=2
double computeAsr(double step, double t) {
double D = sunDeclination(this.getJDate() + t);
double G = -darccot(step + _dtan((this.getLat() - D).abs()));
return computeTime(G, t);
}
// ---------------------- Misc Functions -----------------------
// compute the difference between two times
double timeDiff(double time1, double time2) {
return _fixHour(time2 - time1);
}
// -------------------- Interface Functions --------------------
// return prayer times for a given date
List<String> getDatePrayerTimes(int year, int month, int day, double latitude,
double longitude, double tZone) {
this.setLat(latitude);
this.setLng(longitude);
this.setTimeZone(tZone);
this.setJDate(julianDate(year, month, day));
double lonDiff = longitude / (15.0 * 24.0);
this.setJDate(this.getJDate() - lonDiff);
return computeDayTimes();
}
// return prayer times for a given date
List<String> getPrayerTimes(
DateTime date, double latitude, double longitude, double tZone) {
int year = date.year;
int month = date.month;
int day = date.day;
return getDatePrayerTimes(year, month, day, latitude, longitude, tZone);
}
// set custom values for calculation parameters
void setCustomParams(List<double> params) {
for (int i = 0; i < 5; i++) {
if (params[i] == null) {
params[i] = _methodParams[this._calcMethod][i];
_methodParams[this.getCustom()] = params;
} else {
_methodParams[this.getCustom()][i] = params[i];
}
}
this.setCalcMethod(this.getCustom());
}
// set the angle for calculating Fajr
void setFajrAngle(double angle) {
List<double> params = [angle, -1, -1, -1, -1];
setCustomParams(params);
}
// set the angle for calculating Maghrib
void setMaghribAngle(double angle) {
List<double> params = [-1, 0, angle, -1, -1];
setCustomParams(params);
}
// set the angle for calculating Isha
void setIshaAngle(double angle) {
List<double> params = [-1, -1, -1, 0, angle];
setCustomParams(params);
}
// set the minutes after Sunset for calculating Maghrib
void setMaghribMinutes(double minutes) {
List<double> params = [-1, 1, minutes, -1, -1];
setCustomParams(params);
}
// set the minutes after Maghrib for calculating Isha
void setIshaMinutes(double minutes) {
List<double> params = [-1, -1, -1, 1, minutes];
setCustomParams(params);
}
// convert double hours to 24h format
String floatToTime24(double time) {
String result;
if (time == double.nan) {
return _invalidTime;
}
time = _fixHour(time + 0.5 / 60.0); // add 0.5 minutes to round
int hours = time.floor();
double minutes = ((time - hours) * 60.0).floorToDouble();
if ((hours >= 0 && hours <= 9) && (minutes >= 0 && minutes <= 9)) {
result = "0" + hours.toString() + ":0" + (minutes).round().toString();
} else if ((hours >= 0 && hours <= 9)) {
result = "0" + hours.toString() + ":" + (minutes).round().toString();
} else if ((minutes >= 0 && minutes <= 9)) {
result = hours.toString() + ":0" + (minutes).round().toString();
} else {
result = hours.toString() + ":" + (minutes).round().toString();
}
return result;
}
// convert double hours to 12h format
String floatToTime12(double time, bool noSuffix) {
if (time == double.nan) {
return _invalidTime;
}
time = _fixHour(time + 0.5 / 60); // add 0.5 minutes to round
int hours = (time).floor();
double minutes = ((time - hours) * 60).floorToDouble();
String suffix, result;
if (hours >= 12) {
suffix = "PM";
} else {
suffix = "AM";
}
hours = ((((hours + 12) - 1) % (12)) + 1);
/*hours = (hours + 12) - 1;
int hrs = (int) hours % 12;
hrs += 1;*/
if (noSuffix == false) {
if ((hours >= 0 && hours <= 9) && (minutes >= 0 && minutes <= 9)) {
result = "0" +
hours.toString() +
":0" +
(minutes).round().toString() +
" " +
suffix;
} else if ((hours >= 0 && hours <= 9)) {
result = "0" +
hours.toString() +
":" +
(minutes).round().toString() +
" " +
suffix;
} else if ((minutes >= 0 && minutes <= 9)) {
result = hours.toString() +
":0" +
(minutes).round().toString() +
" " +
suffix;
} else {
result = hours.toString() +
":" +
(minutes).round().toString() +
" " +
suffix;
}
} else {
if ((hours >= 0 && hours <= 9) && (minutes >= 0 && minutes <= 9)) {
result = "0" + hours.toString() + ":0" + (minutes).round().toString();
} else if ((hours >= 0 && hours <= 9)) {
result = "0" + hours.toString() + ":" + (minutes).round().toString();
} else if ((minutes >= 0 && minutes <= 9)) {
result = hours.toString() + ":0" + (minutes).round().toString();
} else {
result = hours.toString() + ":" + (minutes).round().toString();
}
}
return result;
}
// convert double hours to 12h format with no suffix
String floatToTime12NS(double time) {
return floatToTime12(time, true);
}
// ---------------------- Compute Prayer Times -----------------------
// compute prayer times at given julian date
List<double> computeTimes(List<double> times) {
List<double> t = dayPortion(times);
double Fajr =
this.computeTime(180 - _methodParams[this.getCalcMethod()][0], t[0]);
double Sunrise = this.computeTime(180 - 0.833, t[1]);
double Dhuhr = this.computeMidDay(t[2]);
double Asr = this.computeAsr((1 + this.getAsrJuristic()).toDouble(), t[3]);
double Sunset = this.computeTime(0.833, t[4]);
double Maghrib =
this.computeTime(_methodParams[this.getCalcMethod()][2], t[5]);
double Isha =
this.computeTime(_methodParams[this.getCalcMethod()][4], t[6]);
List<double> CTimes = [Fajr, Sunrise, Dhuhr, Asr, Sunset, Maghrib, Isha];
return CTimes;
}
// compute prayer times at given julian date
List<String> computeDayTimes() {
List<double> times = [5, 6, 12, 13, 18, 18, 18]; // default times
for (int i = 1; i <= this.getNumIterations(); i++) {
times = computeTimes(times);
}
times = adjustTimes(times);
times = tuneTimes(times);
return adjustTimesFormat(times);
}
// adjust times in a prayer time array
List<double> adjustTimes(List<double> times) {
for (int i = 0; i < times.length; i++) {
times[i] += this.getTimeZone() - this.getLng() / 15;
}
times[2] += this.getDhuhrMinutes() / 60; // Dhuhr
if (_methodParams[this.getCalcMethod()][1] == 1) {
times[5] = times[4] + _methodParams[this.getCalcMethod()][2] / 60;
}
if (_methodParams[this.getCalcMethod()][3] == 1) {
times[6] = times[5] + _methodParams[this.getCalcMethod()][4] / 60;
}
if (this.getAdjustHighLats() != this.getNone()) {
times = adjustHighLatTimes(times);
}
return times;
}
// convert times array to given time format
List<String> adjustTimesFormat(List<double> times) {
List<String> result = new List<String>();
if (this.getTimeFormat() == this.getFloating()) {
for (double time in times) {
result.add(time.toString());
}
return result;
}
for (int i = 0; i < 7; i++) {
if (this.getTimeFormat() == this.getTime12()) {
result.add(floatToTime12(times[i], false));
} else if (this.getTimeFormat() == this.getTime12NS()) {
result.add(floatToTime12(times[i], true));
} else {
result.add(floatToTime24(times[i]));
}
}
return result;
}
// adjust Fajr, Isha and Maghrib for locations in higher latitudes
List<double> adjustHighLatTimes(List<double> times) {
double nightTime = timeDiff(times[4], times[1]); // sunset to sunrise
// Adjust Fajr
double FajrDiff =
nightPortion(_methodParams[this.getCalcMethod()][0]) * nightTime;
if (times[0] == double.nan || timeDiff(times[0], times[1]) > FajrDiff) {
times[0] = times[1] - FajrDiff;
}
// Adjust Isha
double IshaAngle = (_methodParams[this.getCalcMethod()][3] == 0)
? _methodParams[this.getCalcMethod()][4]
: 18;
double IshaDiff = this.nightPortion(IshaAngle) * nightTime;
if (times[6] == double.nan ||
this.timeDiff(times[4], times[6]) > IshaDiff) {
times[6] = times[4] + IshaDiff;
}
// Adjust Maghrib
double MaghribAngle = (_methodParams[this.getCalcMethod()][1] == 0)
? _methodParams[(this.getCalcMethod())][2]
: 4;
double MaghribDiff = nightPortion(MaghribAngle) * nightTime;
if (times[5] == double.nan ||
this.timeDiff(times[4], times[5]) > MaghribDiff) {
times[5] = times[4] + MaghribDiff;
}
return times;
}
// the night portion used for adjusting times in higher latitudes
double nightPortion(double angle) {
double calc = 0;
if (_adjustHighLats == _angleBased)
calc = (angle) / 60.0;
else if (_adjustHighLats == _midNight)
calc = 0.5;
else if (_adjustHighLats == _oneSeventh) calc = 0.14286;
return calc;
}
// convert hours to day portions
List<double> dayPortion(List<double> times) {
for (int i = 0; i < 7; i++) {
times[i] /= 24;
}
return times;
}
// Tune timings for adjustments
// Set time offsets
void tune(List<int> offsetTimes) {
for (int i = 0; i < offsetTimes.length; i++) {
// offsetTimes length
// should be 7 in order
// of Fajr, Sunrise,
// Dhuhr, Asr, Sunset,
// Maghrib, Isha
this._offsets[i] = offsetTimes[i];
}
}
List<double> tuneTimes(List<double> times) {
for (int i = 0; i < times.length; i++) {
times[i] = times[i] + this._offsets[i] / 60.0;
}
return times;
}
int getCalcMethod() {
return _calcMethod;
}
void setCalcMethod(int calcMethod) {
_calcMethod = calcMethod;
}
int getAsrJuristic() {
return _asrJuristic;
}
void setAsrJuristic(int asrJuristic) {
_asrJuristic = asrJuristic;
}
int getDhuhrMinutes() {
return _dhuhrMinutes;
}
void setDhuhrMinutes(int dhuhrMinutes) {
_dhuhrMinutes = dhuhrMinutes;
}
int getAdjustHighLats() {
return _adjustHighLats;
}
void setAdjustHighLats(int adjustHighLats) {
_adjustHighLats = adjustHighLats;
}
int getTimeFormat() {
return _timeFormat;
}
setTimeFormat(int timeFormat) {
_timeFormat = timeFormat;
}
double getLat() {
return _lat;
}
void setLat(double lat) {
_lat = lat;
}
double getLng() {
return _lng;
}
void setLng(double lng) {
_lng = lng;
}
double getTimeZone() {
return _timeZone;
}
void setTimeZone(double timeZone) {
_timeZone = timeZone;
}
double getJDate() {
return _jDate;
}
void setJDate(double jDate) {
_jDate = jDate;
}
int getJafari() {
return _jafri;
}
void setJafari(int jafari) {
_jafri = jafari;
}
int getKarachi() {
return _karachi;
}
void setKarachi(int karachi) {
_karachi = karachi;
}
int getISNA() {
return _iSNA;
}
void setISNA(int iSNA) {
_iSNA = iSNA;
}
int getMWL() {
return _mWL;
}
void setMWL(int mWL) {
_mWL = mWL;
}
int getMakkah() {
return _makkah;
}
void setMakkah(int makkah) {
_makkah = makkah;
}
int getEgypt() {
return _egypt;
}
void setEgypt(int egypt) {
_egypt = egypt;
}
int getCustom() {
return _custom;
}
void setCustom(int custom) {
_custom = custom;
}
int getTehran() {
return _tehran;
}
void setTehran(int tehran) {
_tehran = tehran;
}
int getShafii() {
return _shaffi;
}
void setShafii(int shafii) {
_shaffi = shafii;
}
int getHanafi() {
return _hanafi;
}
void setHanafi(int hanafi) {
_hanafi = hanafi;
}
int getNone() {
return _none;
}
void setNone(int none) {
_none = none;
}
int getMidNight() {
return _midNight;
}
void setMidNight(int midNight) {
_midNight = midNight;
}
int getOneSeventh() {
return _oneSeventh;
}
void setOneSeventh(int oneSeventh) {
_oneSeventh = oneSeventh;
}
int getAngleBased() {
return _angleBased;
}
void setAngleBased(int angleBased) {
_angleBased = angleBased;
}
int getTime24() {
return _time24;
}
void setTime24(int time24) {
_time24 = time24;
}
int getTime12() {
return _time12;
}
void setTime12(int time12) {
_time12 = time12;
}
int getTime12NS() {
return _time12Ns;
}
void setTime12NS(int time12ns) {
_time12Ns = time12ns;
}
int getFloating() {
return _floating;
}
void setFloating(int floating) {
_floating = floating;
}
int getNumIterations() {
return _numIterations;
}
void setNumIterations(int numIterations) {
_numIterations = numIterations;
}
List<String> getTimeNames() {
return _timeNames;
}
}```
I am writing code for apriori algorithm in data mining my code takes as long as 60 seconds for a pretty small dataset which is solved by other code i got from internet in just 2 seconds but i am not getting where am i doing wrong, can someone tell me why the other code is fast over mine.
My code:
import java.util.*;
import java.io.*;
public class Apriori_p {
double support;
ArrayList<String> trans;
Map<String, Integer> map;
long start;
void print(ArrayList<String> temp) {
for (int i = 0; i < temp.size(); i++) {
System.out.println(temp.get(i));
}
System.out.println("Count :" + temp.size());
}
void run() throws FileNotFoundException {
start = System.currentTimeMillis();
trans = new ArrayList<>();
ArrayList<String> temp = new ArrayList<>();
map = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter support %");
support = sc.nextDouble();
System.out.println("Enter file name");
String file = sc.next();
sc = new Scanner(new File(file));
int lines = 0;
while (sc.hasNextLine()) {
String s = sc.nextLine();
if (s.matches("\\s*")) {
continue;
}
lines++;
String[] spl = s.split("\\s+");
ArrayList<Integer> elem = new ArrayList<>();
for (int i = 0; i < spl.length; i++) {
String cand;
int n = Integer.parseInt(spl[i]);
cand = spl[i].trim();
if (!elem.contains(n)) {
elem.add(n);
}
if (map.containsKey(cand)) {
int count = map.get(cand);
map.put(cand, count + 1);
} else {
map.put(cand, 1);
}
}
Collections.sort(elem);
String con = " ";
for (int i = 0; i < elem.size(); i++) {
con = con + elem.get(i) + " ";
String s1 = String.valueOf(elem.get(i)).trim();
if(!temp.contains(s1))
temp.add(s1);
}
trans.add(con);
}
support = (support * lines) / 100;
System.out.println(System.currentTimeMillis() - start);
apriori(temp, 1);
}
public static void main(String[] args) throws FileNotFoundException {
new Apriori_p().run();
}
public void apriori(ArrayList<String> temp, int m) {
Set<String> diff = null;
if (m == 1) {
diff = new HashSet<>();
}
for (int i = 0; i < temp.size(); i++) {
if (map.get(temp.get(i)) < support) {
if (m == 1) {
diff.add(temp.get(i));
}
temp.remove(i);
i--;
}
}
for (int i = 0; i < trans.size() && m == 1; i++) {
for (String j : diff) {
String rep = " " + j + " ";
trans.get(i).replace(rep, " ");
}
}
if (temp.size() == 0) {
return;
}
System.out.println("Size " + m + " :");
print(temp);
ArrayList<String> ntemp = new ArrayList<>();
int n = temp.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
StringTokenizer st1 = new StringTokenizer(temp.get(i), " ");
StringTokenizer st2 = new StringTokenizer(temp.get(j), " ");
String str1 = "", str2 = "";
for (int s = 0; s < m - 2; s++) {
str1 = str1 + " " + st1.nextToken();
str2 = str2 + " " + st2.nextToken();
}
if (str2.compareToIgnoreCase(str1) == 0) {
int s1 = Integer.parseInt(st1.nextToken()), s2 = Integer.parseInt(st2.nextToken());
String s3;
if (s1 <= s2) {
s3 = (str1 + " " + s1 + " " + s2).trim();
} else {
s3 = (str1 + " " + s2 + " " + s1).trim();
}
if(!ntemp.contains(s3)){
ntemp.add(s3);
}
}
}
}
temp.clear();
for (int j = 0; j < ntemp.size(); j++) {
int c = 0;
for (int i = 0; i < trans.size(); i++) {
int check = 0;
String tr = trans.get(i);
StringTokenizer st1 = new StringTokenizer(ntemp.get(j)," ");
while(st1.hasMoreElements()){
String str = st1.nextToken();
if(!tr.contains(" " + str + " ")){
check = 1;
break;
}
}
if(check == 0){
c= 1;
if (map.containsKey(ntemp.get(j))) {
int count = map.get(ntemp.get(j));
map.put(ntemp.get(j), count + 1);
} else {
map.put(ntemp.get(j), 1);
}
}
}
if (c == 0) {
ntemp.remove(j);
j--;
}
}
apriori(ntemp, m + 1);
}
}
Fast code:
import java.io.*;
import java.util.*;
public class Apriori3{
public static void main(String[] args) throws Exception {
Apriori3 ap = new Apriori3(args);
}
private List<int[]> itemsets;
private String transaFile;
private int numItems;
private int numTransactions;
private double minSup;
private boolean usedAsLibrary = false;
public Apriori3(String[] args) throws Exception {
configure(args);
go();
}
private void go() throws Exception {
long start = System.currentTimeMillis();
createItemsetsOfSize1();
int itemsetNumber = 1;
int nbFrequentSets = 0;
while (itemsets.size() > 0) {
calculateFrequentItemsets();
if (itemsets.size() != 0) {
nbFrequentSets += itemsets.size();
log("Found " + itemsets.size() + " frequent itemsets of size " + itemsetNumber + " (with support " + (minSup * 100) + "%)");;
createNewItemsetsFromPreviousOnes();
}
itemsetNumber++;
}
long end = System.currentTimeMillis();
log("Execution time is: " + ((double) (end - start) / 1000) + " seconds.");
log("Found " + nbFrequentSets + " frequents sets for support " + (minSup * 100) + "% (absolute " + Math.round(numTransactions * minSup) + ")");
log("Done");
}
private void foundFrequentItemSet(int[] itemset, int support) {
if (usedAsLibrary) {
} else {
System.out.println(Arrays.toString(itemset) + " (" + ((support / (double) numTransactions)) + " " + support + ")");
}
}
private void log(String message) {
if (!usedAsLibrary) {
System.err.println(message);
}
}
private void configure(String[] args) throws Exception {
if (args.length != 0) {
transaFile = args[0];
} else {
transaFile = "chess.dat"; // default
}
if (args.length >= 2) {
minSup = (Double.valueOf(args[1]).doubleValue());
} else {
minSup = .8;
}
if (minSup > 1 || minSup < 0) {
throw new Exception("minSup: bad value");
}
numItems = 0;
numTransactions = 0;
BufferedReader data_in = new BufferedReader(new FileReader(transaFile));
while (data_in.ready()) {
String line = data_in.readLine();
if (line.matches("\\s*")) {
continue;
}
numTransactions++;
StringTokenizer t = new StringTokenizer(line, " ");
while (t.hasMoreTokens()) {
int x = Integer.parseInt(t.nextToken());
if (x + 1 > numItems) {
numItems = x + 1;
}
}
}
outputConfig();
}
private void outputConfig() {
log("Input configuration: " + numItems + " items, " + numTransactions + " transactions, ");
log("minsup = " + minSup + "%");
}
private void createItemsetsOfSize1() {
itemsets = new ArrayList<int[]>();
for (int i = 0; i < numItems; i++) {
int[] cand = {i};
itemsets.add(cand);
}
}
private void createNewItemsetsFromPreviousOnes() {
int currentSizeOfItemsets = itemsets.get(0).length;
log("Creating itemsets of size " + (currentSizeOfItemsets + 1) + " based on " + itemsets.size() + " itemsets of size " + currentSizeOfItemsets);
HashMap<String, int[]> tempCandidates = new HashMap<String, int[]>(); //temporary candidates
for (int i = 0; i < itemsets.size(); i++) {
for (int j = i + 1; j < itemsets.size(); j++) {
int[] X = itemsets.get(i);
int[] Y = itemsets.get(j);
assert (X.length == Y.length);
int[] newCand = new int[currentSizeOfItemsets + 1];
for (int s = 0; s < newCand.length - 1; s++) {
newCand[s] = X[s];
}
int ndifferent = 0;
for (int s1 = 0; s1 < Y.length; s1++) {
boolean found = false;
for (int s2 = 0; s2 < X.length; s2++) {
if (X[s2] == Y[s1]) {
found = true;
break;
}
}
if (!found) {
ndifferent++;
newCand[newCand.length - 1] = Y[s1];
}
}
assert (ndifferent > 0);
if (ndifferent == 1) {
Arrays.sort(newCand);
tempCandidates.put(Arrays.toString(newCand), newCand);
}
}
}
itemsets = new ArrayList<int[]>(tempCandidates.values());
log("Created " + itemsets.size() + " unique itemsets of size " + (currentSizeOfItemsets + 1));
}
private void line2booleanArray(String line, boolean[] trans) {
Arrays.fill(trans, false);
StringTokenizer stFile = new StringTokenizer(line, " ");
while (stFile.hasMoreTokens()) {
int parsedVal = Integer.parseInt(stFile.nextToken());
trans[parsedVal] = true;
}
}
private void calculateFrequentItemsets() throws Exception {
log("Passing through the data to compute the frequency of " + itemsets.size() + " itemsets of size " + itemsets.get(0).length);
List<int[]> frequentCandidates = new ArrayList<int[]>();
boolean match;
int count[] = new int[itemsets.size()];
BufferedReader data_in = new BufferedReader(new InputStreamReader(new FileInputStream(transaFile)));
boolean[] trans = new boolean[numItems];
for (int i = 0; i < numTransactions; i++) {
String line = data_in.readLine();
line2booleanArray(line, trans);
for (int c = 0; c < itemsets.size(); c++) {
match = true;
int[] cand = itemsets.get(c);
for (int xx : cand) {
if (trans[xx] == false) {
match = false;
break;
}
}
if (match) {
count[c]++;
}
}
}
data_in.close();
for (int i = 0; i < itemsets.size(); i++) {
if ((count[i] / (double) (numTransactions)) >= minSup) {
foundFrequentItemSet(itemsets.get(i), count[i]);
frequentCandidates.add(itemsets.get(i));
}
}
itemsets = frequentCandidates;
}
}
Is it possible to perform blurring of a whole scene of AndEngine? I would like to blur a whole scene but not to blur a child scene. Da you have any suggestions?
public class MyScene extends Scene {
private Sprite backgroundSprite;
private Sprite playerSprite;
private Sprite enemySprite;
public void create() {
attachChild(backgroundSprite);
attachChild(playerSprite);
attachChild(enemySprite);
}
public void openChildScene() {
// PERFORM BLURRING of a scene
CameraScene childScene = new CameraScene(camera);
// attach children
.
.
.
childScene.setBackgroundEnabled(false);
setChildScene(childScene);
}
}
This is absolutely possible. Take a look at the Shader example in the AndEngineExamples project. You basically have to render the scene to an (empty) Texture and then use a shader on it.
RadialBlur Example:
package org.andengine.examples;
import org.andengine.engine.Engine;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.sprite.UncoloredSprite;
import org.andengine.entity.util.FPSLogger;
import org.andengine.input.touch.TouchEvent;
import org.andengine.input.touch.detector.ClickDetector;
import org.andengine.input.touch.detector.ClickDetector.IClickDetectorListener;
import org.andengine.opengl.shader.PositionTextureCoordinatesShaderProgram;
import org.andengine.opengl.shader.ShaderProgram;
import org.andengine.opengl.shader.constants.ShaderProgramConstants;
import org.andengine.opengl.shader.exception.ShaderProgramException;
import org.andengine.opengl.shader.exception.ShaderProgramLinkException;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.opengl.texture.render.RenderTexture;
import org.andengine.opengl.util.GLState;
import org.andengine.opengl.vbo.attribute.VertexBufferObjectAttributes;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import android.opengl.GLES20;
/**
* (c) Zynga 2011
*
* #author Nicolas Gramlich <ngramlich#zynga.com>
* #since 16:55:18 - 06.11.2011
*/
public class RadialBlurExample extends SimpleBaseGameActivity implements IOnSceneTouchListener, IClickDetectorListener {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private ITextureRegion mFaceTextureRegion;
private boolean mRadialBlurring = true;
private float mRadialBlurCenterX = 0.5f;
private float mRadialBlurCenterY = 0.5f;
private ClickDetector mClickDetector;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
public EngineOptions onCreateEngineOptions() {
this.mCamera = new Camera(0, 0, RadialBlurExample.CAMERA_WIDTH, RadialBlurExample.CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(RadialBlurExample.CAMERA_WIDTH, RadialBlurExample.CAMERA_HEIGHT), this.mCamera);
}
#Override
public Engine onCreateEngine(EngineOptions pEngineOptions) {
return new Engine(pEngineOptions) {
private boolean mRenderTextureInitialized;
private RenderTexture mRenderTexture;
private UncoloredSprite mRenderTextureSprite;
#Override
public void onDrawFrame(final GLState pGLState) throws InterruptedException {
final boolean firstFrame = !this.mRenderTextureInitialized;
if(firstFrame) {
this.initRenderTextures(pGLState);
this.mRenderTextureInitialized = true;
}
final int surfaceWidth = this.mCamera.getSurfaceWidth();
final int surfaceHeight = this.mCamera.getSurfaceHeight();
this.mRenderTexture.begin(pGLState);
{
/* Draw current frame. */
super.onDrawFrame(pGLState);
}
this.mRenderTexture.end(pGLState);
/* Draw rendered texture with custom shader. */
{
pGLState.pushProjectionGLMatrix();
pGLState.orthoProjectionGLMatrixf(0, surfaceWidth, 0, surfaceHeight, -1, 1);
{
this.mRenderTextureSprite.onDraw(pGLState, this.mCamera);
}
pGLState.popProjectionGLMatrix();
}
}
private void initRenderTextures(final GLState pGLState) {
final int surfaceWidth = this.mCamera.getSurfaceWidth();
final int surfaceHeight = this.mCamera.getSurfaceHeight();
this.mRenderTexture = new RenderTexture(RadialBlurExample.this.getTextureManager(), surfaceWidth, surfaceHeight);
this.mRenderTexture.init(pGLState);
final ITextureRegion renderTextureTextureRegion = TextureRegionFactory.extractFromTexture(this.mRenderTexture);
this.mRenderTextureSprite = new UncoloredSprite(0, 0, renderTextureTextureRegion, this.getVertexBufferObjectManager()) {
#Override
protected void preDraw(final GLState pGLState, final Camera pCamera) {
if(RadialBlurExample.this.mRadialBlurring) {
this.setShaderProgram(RadialBlurShaderProgram.getInstance());
} else {
this.setShaderProgram(PositionTextureCoordinatesShaderProgram.getInstance());
}
super.preDraw(pGLState, pCamera);
GLES20.glUniform2f(RadialBlurShaderProgram.sUniformRadialBlurCenterLocation, RadialBlurExample.this.mRadialBlurCenterX, 1 - RadialBlurExample.this.mRadialBlurCenterY);
}
};
}
};
}
#Override
public void onCreateResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 512, 512);
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "badge_large.png", 0, 0);
this.mBitmapTextureAtlas.load();
this.getShaderProgramManager().loadShaderProgram(RadialBlurShaderProgram.getInstance());
}
#Override
public Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
/* Calculate the coordinates for the face, so its centered on the camera. */
final float centerX = (RadialBlurExample.CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final float centerY = (RadialBlurExample.CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
/* Create the face and add it to the scene. */
final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion, this.getVertexBufferObjectManager());
// face.setScale(3);
scene.attachChild(face);
/* TouchListener */
this.mClickDetector = new ClickDetector(this);
scene.setOnSceneTouchListener(this);
return scene;
}
#Override
public void onClick(final ClickDetector pClickDetector, final int pPointerID, final float pSceneX, final float pSceneY) {
this.mRadialBlurring = !this.mRadialBlurring;
}
#Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
this.mClickDetector.onSceneTouchEvent(pScene, pSceneTouchEvent);
this.mRadialBlurCenterX = pSceneTouchEvent.getMotionEvent().getX() / this.mCamera.getSurfaceWidth();
this.mRadialBlurCenterY = pSceneTouchEvent.getMotionEvent().getY() / this.mCamera.getSurfaceHeight();
return true;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static class RadialBlurShaderProgram extends ShaderProgram {
// ===========================================================
// Constants
// ===========================================================
private static RadialBlurShaderProgram INSTANCE;
public static final String VERTEXSHADER =
"uniform mat4 " + ShaderProgramConstants.UNIFORM_MODELVIEWPROJECTIONMATRIX + ";\n" +
"attribute vec4 " + ShaderProgramConstants.ATTRIBUTE_POSITION + ";\n" +
"attribute vec2 " + ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES + ";\n" +
"varying vec2 " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + ";\n" +
"void main() {\n" +
" " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " = " + ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES + ";\n" +
" gl_Position = " + ShaderProgramConstants.UNIFORM_MODELVIEWPROJECTIONMATRIX + " * " + ShaderProgramConstants.ATTRIBUTE_POSITION + ";\n" +
"}";
private static final String UNIFORM_RADIALBLUR_CENTER = "u_radialblur_center";
public static final String FRAGMENTSHADER =
"precision lowp float;\n" +
"uniform sampler2D " + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ";\n" +
"varying mediump vec2 " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + ";\n" +
"uniform vec2 " + RadialBlurShaderProgram.UNIFORM_RADIALBLUR_CENTER + ";\n" +
"const float sampleShare = (1.0 / 11.0);\n" +
"const float sampleDist = 1.0;\n" +
"const float sampleStrength = 1.25;\n" +
"void main() {\n" +
/* The actual (unburred) sample. */
" vec4 color = texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + ");\n" +
/* Calculate direction towards center of the blur. */
" vec2 direction = " + RadialBlurShaderProgram.UNIFORM_RADIALBLUR_CENTER + " - " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + ";\n" +
/* Calculate the distance to the center of the blur. */
" float distance = sqrt(direction.x * direction.x + direction.y * direction.y);\n" +
/* Normalize the direction (reuse the distance). */
" direction = direction / distance;\n" +
" vec4 sum = color * sampleShare;\n" +
/* Take 10 additional samples along the direction towards the center of the blur. */
" vec2 directionSampleDist = direction * sampleDist;\n" +
" sum += texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " - 0.08 * directionSampleDist) * sampleShare;\n" +
" sum += texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " - 0.05 * directionSampleDist) * sampleShare;\n" +
" sum += texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " - 0.03 * directionSampleDist) * sampleShare;\n" +
" sum += texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " - 0.02 * directionSampleDist) * sampleShare;\n" +
" sum += texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " - 0.01 * directionSampleDist) * sampleShare;\n" +
" sum += texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " + 0.01 * directionSampleDist) * sampleShare;\n" +
" sum += texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " + 0.02 * directionSampleDist) * sampleShare;\n" +
" sum += texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " + 0.03 * directionSampleDist) * sampleShare;\n" +
" sum += texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " + 0.05 * directionSampleDist) * sampleShare;\n" +
" sum += texture2D(" + ShaderProgramConstants.UNIFORM_TEXTURE_0 + ", " + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " + 0.08 * directionSampleDist) * sampleShare;\n" +
/* Weighten the blur effect with the distance to the center of the blur (further out is blurred more). */
" float t = sqrt(distance) * sampleStrength;\n" +
" t = clamp(t, 0.0, 1.0);\n" + // 0 <= t >= 1
/* Blend the original color with the averaged pixels. */
" gl_FragColor = mix(color, sum, t);\n" +
"}";
// ===========================================================
// Fields
// ===========================================================
public static int sUniformModelViewPositionMatrixLocation = ShaderProgramConstants.LOCATION_INVALID;
public static int sUniformTexture0Location = ShaderProgramConstants.LOCATION_INVALID;
public static int sUniformRadialBlurCenterLocation = ShaderProgramConstants.LOCATION_INVALID;
// ===========================================================
// Constructors
// ===========================================================
private RadialBlurShaderProgram() {
super(RadialBlurShaderProgram.VERTEXSHADER, RadialBlurShaderProgram.FRAGMENTSHADER);
}
public static RadialBlurShaderProgram getInstance() {
if(RadialBlurShaderProgram.INSTANCE == null) {
RadialBlurShaderProgram.INSTANCE = new RadialBlurShaderProgram();
}
return RadialBlurShaderProgram.INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
protected void link(final GLState pGLState) throws ShaderProgramLinkException {
GLES20.glBindAttribLocation(this.mProgramID, ShaderProgramConstants.ATTRIBUTE_POSITION_LOCATION, ShaderProgramConstants.ATTRIBUTE_POSITION);
GLES20.glBindAttribLocation(this.mProgramID, ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES_LOCATION, ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES);
super.link(pGLState);
RadialBlurShaderProgram.sUniformModelViewPositionMatrixLocation = this.getUniformLocation(ShaderProgramConstants.UNIFORM_MODELVIEWPROJECTIONMATRIX);
RadialBlurShaderProgram.sUniformTexture0Location = this.getUniformLocation(ShaderProgramConstants.UNIFORM_TEXTURE_0);
RadialBlurShaderProgram.sUniformRadialBlurCenterLocation = this.getUniformLocation(RadialBlurShaderProgram.UNIFORM_RADIALBLUR_CENTER);
}
#Override
public void bind(final GLState pGLState, final VertexBufferObjectAttributes pVertexBufferObjectAttributes) {
GLES20.glDisableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION);
super.bind(pGLState, pVertexBufferObjectAttributes);
GLES20.glUniformMatrix4fv(RadialBlurShaderProgram.sUniformModelViewPositionMatrixLocation, 1, false, pGLState.getModelViewProjectionGLMatrix(), 0);
GLES20.glUniform1i(RadialBlurShaderProgram.sUniformTexture0Location, 0);
}
#Override
public void unbind(final GLState pGLState) throws ShaderProgramException {
GLES20.glEnableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION);
super.unbind(pGLState);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
I am trying to group segments of the XBee output into a variable that joins them. I am using Processing to code and compile. The issue I am having is that the output (println) is skipping every other byte (maybe that's the wrong term). So XBee output for i = 4 though 11 should look like this:
0,19,162,0,64,121,230,206 (this is the XBee address converted from hex).
But the println shows this:
19,0,121,206,125,1,0,3 (which starts getting into other segments of the output).
Later, I tried a different route by using an array. It still skips every other entry and I've found that it has to do with my check for i == 126. Is there an alternate way of doing a check like this?
Substitute this draw section for the one below. It's simpler to follow. This was a test with same results...
void draw() {
if (myPort.available() > 21) {
int[] XBeeAddr = new int[22];
for (int i=0; i<22; i++) {
XBeeAddr[i] = myPort.read();
if (myPort.read == 126) {
i=0;
}
println(XBeeAddr[0] + "," + XBeeAddr[1] + "," + XBeeAddr[2]);
}
}
Original code
import processing.serial.*;
import de.bezier.data.sql.*; // For SQLite database
SQLite db; // For SQLite database
Serial myPort;
void setup() {
println(Serial.list());
myPort = new Serial(this, Serial.list()[0],9600);
// For SQLite database...
size( 100, 100 );
db = new SQLite( this, "test.db" ); // Open database file
if ( db.connect() ) {
String[] tableNames = db.getTableNames();
db.query( "SELECT * FROM %s", tableNames[0] );
while (db.next()) {
TableOne t = new TableOne();
db.setFromRow( t );
println( t );
}
}
}
// For SQLite database
class TableOne {
public String fieldOne;
public int fieldTwo;
public String toString () {
return String.format("fieldOne: %s fieldTwo: %d", fieldOne, fieldTwo);
}
}
void draw() {
if (myPort.available() > 21) {
int XBeeAddr1 = 0;
int XBeeAddr2 = 0;
int XBeeAddr3 = 0;
int XBeeAddr4 = 0;
int XBeeAddr5 = 0;
int XBeeAddr6 = 0;
int XBeeAddr7 = 0;
int XBeeAddr8 = 0;
for (int i=0; i<22; i++) {
int inByte = myPort.read();
if (inByte == 126) {
i=0; // This resets the counter if XBee data was incomplete on the last run.
}
if (i == 4) {
XBeeAddr1 = myPort.read();
}
if (i == 5) {
XBeeAddr2 = myPort.read();
}
if (i == 6) {
XBeeAddr3 = myPort.read();
}
if (i == 7) {
XBeeAddr4 = myPort.read();
}
if (i == 8) {
XBeeAddr5 = myPort.read();
}
if (i == 9) {
XBeeAddr6 = myPort.read();
}
if (i == 10) {
XBeeAddr7 = myPort.read();
}
if (i == 11) {
XBeeAddr8 = myPort.read();
}
String XBeeAddrAll = XBeeAddr1 + "," +
XBeeAddr2 + "," +
XBeeAddr3 + "," +
XBeeAddr4 + "," +
XBeeAddr5 + "," +
XBeeAddr6 + "," +
XBeeAddr7 + "," +
XBeeAddr8;
println(XBeeAddrAll);
}
}
}
It was fixed by changing myPort.read == 126 to if XBeeAddr[0] != 126, break. Then later I did an if XBeeAddr[0] == 126 println.