util.cs 48.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * This file is part of ChronoJump
 *
 * ChronoJump 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.
 *    
 * ChronoJump 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
 *
18
 *  Copyright (C) 2004-2015   Xavier de Blas <xaviblas@gmail.com> 
19 20 21
 */

using System;
Xavier de Blas's avatar
Xavier de Blas committed
22
//using System.Data;
23
using System.Text; //StringBuilder
24
using System.Collections; //ArrayList
25
using System.Collections.Generic; //List<T>
26 27 28
using System.Diagnostics; 	//for detect OS
using System.IO; 		//for detect OS

29 30 31
//this class tries to be a space for methods that are used in different classes
public class Util
{
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
	//all numbers are saved in database with '.' as decimal separator (method for numbers)
	public static string ConvertToPoint (double myDouble)
	{
		StringBuilder myStringBuilder = new StringBuilder(myDouble.ToString());
		myStringBuilder.Replace(",", ".");
		return myStringBuilder.ToString();
	}
	
	//all numbers are saved in database with '.' as decimal separator
	//method for the tvString, tcString, and runIntervalTimesString
	public static string ConvertToPoint (string myString)
	{
		StringBuilder myStringBuilder = new StringBuilder(myString);
		myStringBuilder.Replace(",", ".");
		return myStringBuilder.ToString();
	}
48 49 50 51 52 53 54 55
	
	public static string ConvertToComma (string myString)
	{
		StringBuilder myStringBuilder = new StringBuilder(myString);
		myStringBuilder.Replace(".", ",");
		return myStringBuilder.ToString();
	}

56 57 58 59 60 61 62 63 64 65 66 67 68 69

	//when we do a query to the server, it returns avg as "0,54" because it's latin localized
	//if client is on english machine, need to convert this to "0.54"
	public static string ConvertToPointIfNeeded (string myString)
	{
		System.Globalization.NumberFormatInfo localeInfo = new System.Globalization.NumberFormatInfo();
		localeInfo = System.Globalization.NumberFormatInfo.CurrentInfo;
		
		StringBuilder myStringBuilder = new StringBuilder(myString);
		if(localeInfo.NumberDecimalSeparator == ".") {
			myStringBuilder.Replace(",", localeInfo.NumberDecimalSeparator);
		}
		return myStringBuilder.ToString();
	}
70
	
71 72 73
	//this is only used to define a preferences configuration
	//to send to R and export csv,  gui/encoder.cs uses CSVExportDecimalSeparator variable that is read from preferences SQL
	public static string GetDecimalSeparatorFromLocale() {
74 75 76 77 78 79 80 81 82 83
		System.Globalization.NumberFormatInfo localeInfo = new System.Globalization.NumberFormatInfo();
		localeInfo = System.Globalization.NumberFormatInfo.CurrentInfo;

		if(localeInfo.NumberDecimalSeparator == ".")
			return("POINT");
		else if(localeInfo.NumberDecimalSeparator == ",")
			return("COMMA");
		else 
			return("OTHER");
	}
84 85 86 87
	
	//used for load from the database all numbers with correct decimal separator (locale defined)
	//used also for the tvString, tcString, and runIntervalTimesString
	public static string ChangeDecimalSeparator(string myString) {
88 89 90
		if(myString == "") {
			return "0";
		}
91 92 93 94 95 96 97 98 99 100
		System.Globalization.NumberFormatInfo localeInfo = new System.Globalization.NumberFormatInfo();
		localeInfo = System.Globalization.NumberFormatInfo.CurrentInfo;
		
		StringBuilder myStringBuilder = new StringBuilder(myString);
		if(localeInfo.NumberDecimalSeparator != ".") {
			myStringBuilder.Replace(".", localeInfo.NumberDecimalSeparator);
		}
		return myStringBuilder.ToString();
	}

101 102 103
	public static string TrimDecimals (double time, int prefsDigitsNumber) {
		return Math.Round(time, prefsDigitsNumber).ToString();
	}
104

105
	public static string TrimDecimals (string time, int prefsDigitsNumber) {
Xavier de Blas's avatar
Xavier de Blas committed
106 107 108
		if(time == "-1") 
			return "-1";
		else if(time == "-") 
109
			return "-";
Xavier de Blas's avatar
Xavier de Blas committed
110
		else 
111
			return Math.Round(Convert.ToDouble(time), prefsDigitsNumber).ToString();
112
	}
113

114 115 116 117 118 119 120 121 122 123 124 125
	public static double GetMax (string values)
	{
		string [] myStringFull = values.Split(new char[] {'='});
		double max = 0;
		foreach (string jump in myStringFull) {
			if ( Convert.ToDouble(jump) > max ) {
				max = Convert.ToDouble(jump);
			}
		}
		return max ; 
	}
	
Xavier de Blas's avatar
Xavier de Blas committed
126 127 128 129 130 131 132 133 134 135 136 137 138
	//don't use if there are no jumps, then the big value 999999999 could return
	public static double GetMin (string values)
	{
		string [] myStringFull = values.Split(new char[] {'='});
		double min = 999999999999;
		foreach (string jump in myStringFull) {
			if ( Convert.ToDouble(jump) < min ) {
				min = Convert.ToDouble(jump);
			}
		}
		return min ; 
	}
	
139 140
	public static double GetAverage (string values)
	{
Xavier de Blas's avatar
Xavier de Blas committed
141 142
		if(values.Length == 0)
			return 0;
143 144 145
		string [] myStringFull = values.Split(new char[] {'='});
		double myAverage = 0;
		double myCount = 0;
Xavier de Blas's avatar
Xavier de Blas committed
146 147 148 149

		//if(myStringFull[0] == "-1") {
		//	return 0;
		//}
150
		foreach (string jump in myStringFull) {
151 152 153 154 155
			//if there's a -1 value, should not be counted in the averages
			if(Convert.ToDouble(jump) != -1) {
				myAverage = myAverage + Convert.ToDouble(jump);
				myCount ++;
			}
156
		}
Xavier de Blas's avatar
Xavier de Blas committed
157 158
		if (myAverage == 0 || myCount == 0) { return 0; } //fixes problems when processing only a -1
		else { return myAverage / myCount ; }
159 160
	}

161 162 163 164 165 166 167 168 169 170
	public static double GetLast (string values)
	{
		string [] myStringFull = values.Split(new char[] {'='});
		double lastSubEvent = 0;
		foreach (string myString in myStringFull) 
			lastSubEvent = Convert.ToDouble(myString);
			
		return lastSubEvent; 
	}
	
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
	public static int GetPosMax (string values)
	{
		string [] myStringFull = values.Split(new char[] {'='});
		double max = 0;
		int count = 0;
		int countMax = 0;
		foreach (string myEvent in myStringFull) {
			if ( Convert.ToDouble(myEvent) > max ) {
				max = Convert.ToDouble(myEvent);
				countMax = count;
			}
			count ++;
		}
		return countMax ; 
	}
	
	//don't use if there are no jumps, then the big value 999999999 could return
	public static int GetPosMin (string values)
	{
		string [] myStringFull = values.Split(new char[] {'='});
		double min = 999999999999;
		int count = 0;
		int countMin = 0;
		foreach (string myEvent in myStringFull) {
			if ( Convert.ToDouble(myEvent) < min ) {
				min = Convert.ToDouble(myEvent);
				countMin = count;
			}
			count ++;
		}
		return countMin ; 
	}
203

204
	
205 206 207 208 209 210 211 212 213 214 215 216
	public static double CalculateSD(string valuesList, double sumValues, int count) {
		if(count >1) {
			/*	  
			 * std = SQRT( Σ(Xi-Xavg)² /n )
			 * stdSample = SQRT(n / n-1) * std
			 */

			double avg = sumValues / count;
			double summatory = 0;
			string [] valuesListFull = valuesList.Split(new char[] {':'});
			
			for(int i=0; i<count; i++) {
217
				summatory += Math.Pow ( (Convert.ToDouble(valuesListFull[i]) - avg), 2);
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
			}

			/*
			 * things inside the sqrt have an "(Double)" for not being returned a truncated number (without comma). 
			 * Eg: 
			 * System.Math.Sqrt(10/9) = 1 
			 * System.Math.Sqrt(10/(Double)9) = 1,05409255338946
			 */
			
			double std = System.Math.Sqrt(summatory / (Double)count);
			double stdSample = System.Math.Sqrt( count/(Double)(count-1) ) * std;

			return stdSample;
		} else {
			return -1;
		}
	}
Xavier de Blas's avatar
Xavier de Blas committed
235 236 237 238 239 240

	public static int CalculateJumpAngle(double height, int distance) {
		if(distance == 0)
			return 90;
		else
			return Convert.ToInt32(System.Math.Atan(height / (distance * 1.0)) 
241
				* 180 / System.Math.PI);
Xavier de Blas's avatar
Xavier de Blas committed
242
	}
243
	
244 245 246 247 248 249 250 251 252 253
	//useful for jumpType and jumpRjType, because the third value is the same
	public static bool HasWeight(string [] jumpTypes, string myType) {
		foreach (string myString in jumpTypes) {
			string [] myStringFull = myString.Split(new char[] {':'});
			if(myStringFull[1] == myType) {
				if(myStringFull[3] == "1") { return true;
				} else { return false;
				}
			}
		}
254
		LogB.Error(string.Format("Error, myType: {0} not found", myType));
255 256 257 258 259 260 261 262 263 264 265 266 267
		return false;
	}
	
	//useful for jumpType and jumpRjType, because the second value is the same
	public static bool HasFall(string [] jumpTypes, string myType) {
		foreach (string myString in jumpTypes) {
			string [] myStringFull = myString.Split(new char[] {':'});
			if(myStringFull[1] == myType) {
				if(myStringFull[2] == "0") { return true;
				} else { return false;
				}
			}
		}
268
		LogB.Error(string.Format("Error, myType: {0} not found", myType));
269 270 271 272 273 274
		return false;
	}

	public static string RemoveTilde(string myString) 
	{
		StringBuilder myStringBuilder = new StringBuilder(myString);
275
		myStringBuilder.Replace("'", " ");
276 277 278 279 280 281
		return myStringBuilder.ToString();
	}
	
	public static string RemoveTildeAndColon(string myString) 
	{
		StringBuilder myStringBuilder = new StringBuilder(myString);
282 283
		myStringBuilder.Replace("'", " ");
		myStringBuilder.Replace(":", " ");
284 285
		return myStringBuilder.ToString();
	}
286 287 288 289 290
	
	//dot is used for separating sex in stats names (cannot be used for a new jumpType)
	public static string RemoveTildeAndColonAndDot(string myString) 
	{
		StringBuilder myStringBuilder = new StringBuilder(myString);
291 292 293
		myStringBuilder.Replace("'", " ");
		myStringBuilder.Replace(":", " ");
		myStringBuilder.Replace(".", " ");
294 295
		return myStringBuilder.ToString();
	}
296
	
297 298 299 300 301 302 303
	public static string RemoveTab(string myString) 
	{
		StringBuilder myStringBuilder = new StringBuilder(myString);
		myStringBuilder.Replace("\t", " ");
		return myStringBuilder.ToString();
	}

304
	public static string RemoveNewLine(string myString, bool changeBySpace) 
305 306
	{
		StringBuilder myStringBuilder = new StringBuilder(myString);
307 308 309 310
		if(changeBySpace)
			myStringBuilder.Replace("\n", " ");
		else
			myStringBuilder.Replace("\n", "");
311 312
		return myStringBuilder.ToString();
	}
Xavier de Blas's avatar
Xavier de Blas committed
313

314 315 316 317 318 319 320 321
	//needed for encoder R files
	public static string RemoveBackSlash(string myString)
	{
		StringBuilder myStringBuilder = new StringBuilder(myString);
		myStringBuilder.Replace("\\", " ");
		return myStringBuilder.ToString();
	}

322 323 324 325 326 327 328 329
	//use this!!!	
	public static string RemoveChar(string s, char c) 
	{
		StringBuilder myStringBuilder = new StringBuilder(s);
		myStringBuilder.Replace(c,' ');
		return myStringBuilder.ToString();
	}

Xavier de Blas's avatar
Xavier de Blas committed
330 331 332 333 334 335 336
	public static string RemoveZeroOrMinus(string myString) 
	{
		if(myString == "0" || myString == "-")
			return "";
		else
			return myString;
	}
337 338 339 340 341 342 343 344 345 346 347 348 349 350
	
	public static string RemoveMarkup(string s) 
	{
		bool done = false;
		while(! done) {
			int tagStart = s.IndexOf('<');
			int tagEnd = s.IndexOf('>');
			if(tagStart != -1 && tagEnd != -1 && tagEnd > tagStart) 
				s = s.Remove(tagStart, tagEnd-tagStart+1);
			else
				done = true;
		}
		return s;
	}
Xavier de Blas's avatar
Xavier de Blas committed
351

352 353 354 355 356 357
	public static string ChangeEqualForColon(string myString) 
	{
		StringBuilder myStringBuilder = new StringBuilder(myString);
		myStringBuilder.Replace("=", ":");
		return myStringBuilder.ToString();
	}
358

359
	public static string ChangeSpaceAndMinusForUnderscore(string myString) 
360 361 362
	{
		StringBuilder myStringBuilder = new StringBuilder(myString);
		myStringBuilder.Replace(" ", "_");
363
		myStringBuilder.Replace("-", "_");
364 365
		return myStringBuilder.ToString();
	}
366
	
367 368 369 370 371 372 373 374
	public static string ChangeChars(string str, string charIni, string charEnd) 
	{
		StringBuilder myStringBuilder = new StringBuilder(str);
		myStringBuilder.Replace(charIni, charEnd);
		return myStringBuilder.ToString();
	}

	
Xavier de Blas's avatar
Xavier de Blas committed
375
	public static string GetHeightInCentimeters (string time) {
376
		// s = 4.9 * (tv/2)^2
377
		double timeAsDouble = Convert.ToDouble(time);
Xavier de Blas's avatar
Xavier de Blas committed
378
		double height = 100 * 4.9 * Math.Pow( timeAsDouble / 2.0 , 2 );
379 380 381 382

		return height.ToString();
	}
	
383 384 385 386 387 388 389 390
	public static double WeightFromKgToPercent (double jumpKg, double personKg) {
		return (double) jumpKg *100 / (double) personKg;
	}

	public static double WeightFromPercentToKg (double jumpPercent, double personKg) {
		return (double) jumpPercent * personKg / (double) 100;
	}

Xavier de Blas's avatar
Xavier de Blas committed
391
	public static int GetNumberOfJumps(string myString, bool countMinus)
392 393 394 395 396
	{
		if(myString.Length > 0) {
			string [] jumpsSeparated = myString.Split(new char[] {'='});
			int count = 0;
			foreach (string temp in jumpsSeparated) {
Xavier de Blas's avatar
Xavier de Blas committed
397
				if(countMinus || temp != "-1")
398
					count++;
399 400 401 402 403 404 405 406 407
			}
			if(count == 0) { count =1; }
			
			return count;
		} else { 
			return 0;
		}
	}
	
408
	public static double GetTotalTime (string stringTC, string stringTF)
409
	{
410
		if(stringTC.Length > 0 && stringTF.Length > 0) {
411
			string [] tc = stringTC.Split(new char[] {'='});
412
			string [] tv = stringTF.Split(new char[] {'='});
413 414 415 416

			double totalTime = 0;

			foreach (string jump in tc) {
417 418
				if(jump != "-1") 
					totalTime = totalTime + Convert.ToDouble(jump);
419 420
			}
			foreach (string jump in tv) {
421 422
				if(jump != "-1") 
					totalTime = totalTime + Convert.ToDouble(jump);
423 424 425 426 427 428 429 430
			}

			return totalTime ;
		} else {
			return 0;
		}
	}
	
Xavier de Blas's avatar
Xavier de Blas committed
431 432
	public static double GetTotalTime (string timeString)
	{
433 434 435
		try{
			if(timeString.Length > 0) {
				string [] time= timeString.Split(new char[] {'='});
Xavier de Blas's avatar
Xavier de Blas committed
436

437
				double totalTime = 0;
Xavier de Blas's avatar
Xavier de Blas committed
438

439 440 441
				foreach (string temp in time) 
					if(temp != "-1") 
						totalTime = totalTime + Convert.ToDouble(temp);
442 443 444 445 446 447 448 449

				return totalTime ;
			} else {
				return 0;
			}
		}
		//it seems in runInterval, sometimes intervalTimesString is not defined. Check this, now just return a 0, like if it's idefined but is 0-length
		catch {
Xavier de Blas's avatar
Xavier de Blas committed
450 451 452
			return 0;
		}
	}
Xavier de Blas's avatar
Xavier de Blas committed
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

	//we cannot count with GetNumberOfJumps because that method doesn't count the -1
	//here we want to know if there's more tc data than tv and remove this tc not needed
	//there's no need to record a las tc (currently)
	public static string DeleteLastTcIfNeeded (string tcString, string tvString)
	{
		string [] tcFull = tcString.Split(new char[] {'='});
		string [] tvFull = tvString.Split(new char[] {'='});

		if(tcFull.Length > tvFull.Length) {
			int lastEqualPos = tcString.LastIndexOf('=');
			return tcString.Substring(0, lastEqualPos -1);
		} else {
			return tcString;
		}
	}
469 470 471 472 473 474 475 476
				
	
	public static string [] DeleteFirstStrings(string [] str, int maxStrings) {
		string [] str2 = new String [maxStrings];
		for(int i=str.Length - maxStrings, j=0; i < str.Length; i++, j++) 
			str2[j] = str [i];
		return str2;
	}
Xavier de Blas's avatar
Xavier de Blas committed
477
	
478 479 480 481 482 483 484 485
	public static string [] DeleteString(string [] initial, string delete) {
		string [] final = new String [initial.Length -1];
		int count = 0;
		foreach(string str in initial)
			if(str != delete)
				final[count++] = str;
		return final;
	}
486 487 488 489 490 491 492 493 494 495 496 497

	public static string [] DeleteStringAtPosition(string [] initial, int pos) {
		string [] final = new String [initial.Length -1];
		int count = 0;
		foreach(string str in initial) {
			if(count != pos)
				final[count] = str;
			count ++;
		}

		return final;
	}
498 499
	
	
500 501 502 503 504 505 506 507 508 509 510 511 512
	//called from jumpRj.Write() and from interval
	//when we mark that jump should finish by time, chronopic thread is probably capturing data
	//check if it captured more than date limit, and if it has done, delete last(s) jump(s)
	//also have in mind that allowFinishAfterTime exist
	public static bool EventPassedFromMaxTime(
			string tcString, string tvString, double timeLimit, bool allowFinishAfterTime) 
	{
		if(Util.GetTotalTime(tcString, tvString) > timeLimit) {
			if(allowFinishAfterTime) {
				//if allowFinishAfterTime, know if there's one event with part of the tv after time (ok) or more (bad)
				if(Util.GetTotalTime(tcString, tvString) - Util.GetLast(tvString) > timeLimit)
					return true;	//eventsTime are higher than timeLimit and allowFinish... 
							//and without the lastTv it exceeds, then one ore more exceeds 
Xavier de Blas's avatar
Xavier de Blas committed
513
				else 
514 515 516 517 518 519 520 521 522
					return false;	//eventsTime are higher than timeLimit and allowFinish... 
							//but without the lastTv no exceeds, then no problem
			} 
			else
				return true;		//eventsTime are higher than timeLimit and !allowFinish... one ore more exceeds 
		}
		else
			return false;			//eventsTime are lower than timeLimit: no problem
	}
523 524 525 526 527

	//also for runInterval (simple and without allowFinish...
	public static bool EventPassedFromMaxTime(
			string timesString, double timeLimit) 
	{
528 529 530
		//Absolute value because timesString can start with a '-' if run limited by time and
		//first subRun has arrived later than maximum for the whole run
		if(Math.Abs(Util.GetTotalTime(timesString)) > timeLimit) 
531 532 533 534
			return true;	//eventsTime are higher than timeLimit: one ore more exceeds 
		else
			return false;	//eventsTime are lower than timeLimit: no problem
	}
535
	
536 537 538 539 540 541 542 543 544 545
	public static string DeleteFirstSubEvent (string myString)
	{
		int firstEqualPos = myString.IndexOf('=');
		if(firstEqualPos > 0) {
			return myString.Substring(firstEqualPos +1);
		} else
			return myString;
	}

	
546 547 548
	public static string DeleteLastSubEvent (string myString)
	{
		int lastEqualPos = myString.LastIndexOf('=');
549 550 551 552 553 554 555 556
		if(lastEqualPos > 0) {
			return myString.Substring(0, lastEqualPos);
		}
		else
			//probably string has only one subEvent, then we cannot delete last
			//imagine a runInterval where we only have 10 seconds for go, return, go... n times. And imagine, going is like 20 seconds, then 
			//runInterval write will try to delete last subEvent, but this is the only one
			//then return the time in negative (-) as a mark, and caller will show the time late in a popup win
557 558 559 560 561 562
		
			//but maybe the mark has added first because this was called on tempTable iteration and later on final SQL write iteration
			if( ! myString.StartsWith("-") )
				myString = "-" + myString;
				
			return myString;
563 564 565
	}


566 567
	//public static string GetSpeed (string distance, string time) {
	public static string GetSpeed (string distance, string time, bool metersSecondsPreferred) {
Xavier de Blas's avatar
Xavier de Blas committed
568 569 570
		double distanceAsDouble = Convert.ToDouble(distance);
		double timeAsDouble = Convert.ToDouble(time);

571 572 573 574
		if(metersSecondsPreferred)
			return (distanceAsDouble / timeAsDouble).ToString();
		else
			return (3.6 * distanceAsDouble / timeAsDouble).ToString();
Xavier de Blas's avatar
Xavier de Blas committed
575 576 577
	}
					
	
578
	public static int FetchID (string text)
579
	{
580
		if (text.Length == 0) {
581
			return -1;
582
		}
583
		string [] myStringFull = text.Split(new char[] {':'});
584 585 586 587

		for (int i=0; i < myStringFull[0].Length; i++)
			    {
				    if( ! Char.IsNumber(myStringFull[0], i)) {
588
					    return -1;
589 590
				    }
			    }
591
		return Convert.ToInt32(myStringFull[0]);
592 593 594 595 596 597 598 599
	}
	
	public static string FetchName (string text)
	{
		//"id: name" (return only name)
		bool found = false;
		int i;
		for (i=0; ! found ; i++) {
600
			if(text[i] == ':') {
601 602 603 604 605
				found = true;
			}
		}
		return text.Substring(i);
	}
Xavier de Blas's avatar
Xavier de Blas committed
606

607 608
	public static double GetStiffness(double personMassInKg, double extraMass, double tv, double tc) 
	{
609 610
		//LogB.Warning("AT GetStiffness");
		//LogB.Warning("1: " + personMassInKg.ToString() +  " 2: " + extraMass.ToString() + " 3: " + tv.ToString() + " 4: " + tc.ToString());
611 612 613
		double totalMass = personMassInKg + extraMass;
		
		//return if mass is zero or there's no contact time
614
		if( totalMass == 0 || tv <= 0 || tc <= 0)
615 616 617 618 619 620 621 622 623 624 625 626 627
			return 0;

		double stiffness;
		try {
			stiffness = totalMass * Math.PI * ( tv + tc ) / ( Math.Pow(tc,2) * ( (tv+tc)/Math.PI - tc/4 ) );
		} catch { 
			return 0;
		}

		return stiffness;
	}
	

628
	public static string GetInitialSpeed (string time, bool metersSecondsPreferred) 
629
	{
630 631
		double height = Convert.ToDouble( GetHeightInCentimeters(time) );
		height = height / 100; //in meters
632 633 634
		
		// Vo = sqrt(2gh)
		double initialSpeed = System.Math.Sqrt ( 2 * 9.81 * height ); 
635

636 637 638
		if(! metersSecondsPreferred)
			initialSpeed *= 3.6;

639 640
		return initialSpeed.ToString();
	}
Xavier de Blas's avatar
Xavier de Blas committed
641
	
642
	public static double GetDjPower (double tc, double tf, double mass, double fallHeight) 
Xavier de Blas's avatar
Xavier de Blas committed
643
	{
644 645
		/*
		 * old method
Xavier de Blas's avatar
Xavier de Blas committed
646 647 648 649 650 651 652
		//relative potency in Watts/Kg
		//Bosco. Pendent to find if published

		//P = 24.6 * (TotalTime + FlightTime) / ContactTime

		double tt = tc + tf; //totalTime

653
		return 24.6 * ( tt + tf ) / (Double)tc;
654 655 656 657
		*/

		//new method (proposal by Xavier Padullés)
		//Calcule the potential energies before (mass * g * fallHeight) and after the jump (mass * g * tv^2 * 1.226)
658
		//and divide by the time during force is applied
659 660 661 662 663
		double g = 9.81;
		double tt = tc + tf; //totalTime
		fallHeight = fallHeight / 100.0; //cm -> m
		
		return mass * g * ( fallHeight + 1.226 * Math.Pow(tf,2) ) / (Double)tt;
Xavier de Blas's avatar
Xavier de Blas committed
664
	}
665 666 667 668 669 670 671 672 673 674 675 676
				
	//only Lewis now
	public static double GetPower (double tf, double bodyWeight, double extraWeightKg) 
	{
		//Log.WriteLine("tf: " + tf + ", bodyWeight: " + bodyWeight + ", extra: " + extraWeightKg);
		double pw = System.Math.Sqrt ( 4.9 ) * 9.8 * (bodyWeight + extraWeightKg) *
			System.Math.Sqrt(
				       Convert.ToDouble(GetHeightInCentimeters(tf.ToString()))/100);
		//Log.WriteLine("pw: " + pw);
		return pw;

	}
Xavier de Blas's avatar
Xavier de Blas committed
677

678

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
	public static double GetQIndex (double tv, double tc) 
	{
		if(tv == 0 || tc == 0)
			return 0;
		
		if(tv == -1 || tc == -1)
			return 0;
		
		return tv/tc;
	}

	public static double GetDjIndex (double tv, double tc) 
	{
		if(tv == 0 || tc == 0)
			return 0;
		
		if(tv == -1 || tc == -1)
			return 0;
		
		return 100 * (tv-tc)/tc;
	}

701 702 703 704 705 706 707 708
	public static string GetReportDirectoryName (string fileName) {
		//gets exportfile.html or exportfile.htm and returns exportfile_files
		int posOfDot = fileName.LastIndexOf('.');
		string directoryName = fileName.Substring(0,posOfDot);
		directoryName += "_files";
		return directoryName;
	}

709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
	public static string GetLastPartOfPath (string fileName) {
		//gets a complete url with report directory path and return only last part of path
		//useful for linking images as relative and not absolute in export to HTML
		//works on win and linux
		int temp1 = fileName.LastIndexOf('\\');
		int temp2 = fileName.LastIndexOf('/');
		int posOfBar = 0;
		if(temp1>temp2)
			posOfBar = temp1;
		else
			posOfBar = temp2;

		string lastPartOfPath = fileName.Substring(posOfBar+1, fileName.Length - posOfBar -1);
		return lastPartOfPath;
	}

725 726 727
	//gets a string and returns if all the chars are numbers or the decimal point in current localization
	//there should be also only one decimal point
	//method made because i didn't find it in mono
728 729 730
	//ATTENTTION ONLY WORKS FOR POSITIVES
	//before changing this method, better create another method for all numbers, 
	//and call that method on possible negative numbers
731
	public static bool IsNumber(string myString, bool canBeDecimal) {
732 733 734 735 736 737 738 739 740 741 742 743
		System.Globalization.NumberFormatInfo localeInfo = new System.Globalization.NumberFormatInfo();
		localeInfo = System.Globalization.NumberFormatInfo.CurrentInfo;
		
		int countDecimals = 0;
		foreach(char myChar in myString) {
			if( ! System.Char.IsNumber(myChar) && myChar.ToString() != localeInfo.NumberDecimalSeparator ) {
				return false;
			}
			if( myChar.ToString() == localeInfo.NumberDecimalSeparator ) {
				countDecimals ++;
			}
		}
744
		if(countDecimals > 0 && !canBeDecimal) { return false; }
745 746
		if(countDecimals > 1) { return false; }

747
		//false if it's blank, or it's only a decimal "."
748 749 750 751 752
		if(myString.Length == 0 || (myString.Length == 1 && countDecimals == 1)) { 
			return false; }
				
		return true;
	}
753

754 755 756 757 758 759
	public static bool IsEven(string myString) {
		return IsEven(Convert.ToInt32(myString));
	}
	public static bool IsEven(int myInt) {
		return (myInt % 2 == 0); //check if it's even (in spanish "par")
	}
760 761 762 763
	
	/********** start of LocalApplicationData path ************/
	
	//parent of database, multimedia and encoder
764 765 766
	//if withFinalSeparator, then return a '\' or '/' at the end
	public static string GetParentDir(bool withFinalSeparator) {
		string path = Path.Combine(
767 768
				Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
				"Chronojump");
769 770 771 772 773

		if(withFinalSeparator)
			path += Path.DirectorySeparatorChar;

		return path;
774 775 776 777 778
	}
	
	/********** end of LocalApplicationData path ************/
	
	/********** start of database paths ************/
779

780
	public static string GetReallyOldDatabaseDir() {
781
		return Environment.GetEnvironmentVariable("HOME")+ Path.DirectorySeparatorChar + ".chronojump";
782 783
	}
	
784
	public static string GetOldDatabaseDir() {
785 786 787 788
		//we are on:
		//Chronojump/chronojump-x.y/data/
		//we have to go to
		//Chronojump/database/
Xavier de Blas's avatar
Xavier de Blas committed
789
		
790 791
		return ".." + Path.DirectorySeparatorChar + ".." + Path.DirectorySeparatorChar + "database";
	}
792

793
	public static string GetDatabaseDir() {
Xavier de Blas's avatar
Xavier de Blas committed
794 795 796 797
		//fixing:
		//http://lists.ximian.com/pipermail/mono-list/2008-November/040480.html
		return Path.Combine(
				Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
Xavier de Blas's avatar
Xavier de Blas committed
798
				"Chronojump" + Path.DirectorySeparatorChar + "database");
Xavier de Blas's avatar
Xavier de Blas committed
799 800 801 802 803
	}
	
	//if database dir has illegal characters, use this temp dir and remember to copy db at end, or to restore if chrashed
	public static string GetDatabaseTempDir() {
		return Path.Combine(Path.GetTempPath(), "Chronojump");
804
	}
805

806
	/********** end of database paths ************/
Xavier de Blas's avatar
Xavier de Blas committed
807 808

	/*	
809
	public static string GetChronojumpNetworksFile() {
Xavier de Blas's avatar
Xavier de Blas committed
810 811
		return Path.Combine(
				Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
812
				"Chronojump" + Path.DirectorySeparatorChar + "chronojump_networks.txt");
Xavier de Blas's avatar
Xavier de Blas committed
813
	}
Xavier de Blas's avatar
Xavier de Blas committed
814
	*/
Xavier de Blas's avatar
Xavier de Blas committed
815
	
816

817 818 819 820 821 822 823 824
	/********** start of multimedia paths ************/

	public static string GetMultimediaDir() {
		return Path.Combine(
				Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
				"Chronojump" + Path.DirectorySeparatorChar + "multimedia");
	}
	
825 826 827 828 829
	public static string GetPhotosDir(bool small) {
		string smallDir = "";
		if(small)
			smallDir = Path.DirectorySeparatorChar + Constants.SmallPhotoDir; 

830 831 832
		return Path.Combine(
				Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
				"Chronojump" + Path.DirectorySeparatorChar + "multimedia" +
833
				Path.DirectorySeparatorChar + "photos") + smallDir;
834 835 836 837 838 839 840 841
	}
	
	public static string GetVideosDir() {
		return Path.Combine(
				Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
				"Chronojump" + Path.DirectorySeparatorChar + "multimedia" +
				Path.DirectorySeparatorChar + "videos");
	}
842
	
843 844 845

	//to store user videos and photos
	public static void CreateMultimediaDirsIfNeeded () {
846
		string [] dirs = { GetMultimediaDir(), GetPhotosDir(false), GetPhotosDir(true), GetVideosDir() }; 
847 848 849
		foreach (string d in dirs) {
			if( ! Directory.Exists(d)) {
				Directory.CreateDirectory (d);
850
				LogB.Information ("created dir:", d);
851 852 853 854
			}
		}
	}
	
855 856 857 858 859 860 861
	//videos ar organized by sessions. Photos no.	
	public static string GetVideoSessionDir (int sessionID) {
		return GetVideosDir() + Path.DirectorySeparatorChar + sessionID.ToString();
	}
	
	public static void CreateVideoSessionDirIfNeeded (int sessionID) {
		string sessionDir = GetVideoSessionDir(sessionID);
862 863
		if( ! Directory.Exists(sessionDir)) {
			Directory.CreateDirectory (sessionDir);
864
			LogB.Information ("created dir:", sessionDir);
865 866 867
		}
	}

868
	//returns absolute path, but in encoder this URL is stored in database as relative to be able to move data between computers
869
	//see SqliteEncoder.removeURLpath
870 871 872 873
	public static string GetVideoFileName (int sessionID, Constants.TestTypes testType, int uniqueID) {
		return GetVideoSessionDir(sessionID) + Path.DirectorySeparatorChar + 
			testType.ToString() + "-" + uniqueID.ToString() +
			GetMultimediaExtension(Constants.MultimediaItems.VIDEO);
874
	}
875 876 877 878 879 880 881
	public static string GetVideoFileNameOnlyName (Constants.TestTypes testType, int uniqueID) {
		return testType.ToString() + "-" + uniqueID.ToString() +
			GetMultimediaExtension(Constants.MultimediaItems.VIDEO);
	}
	public static string GetVideoFileNameOnlyFolder (int sessionID) {
		return GetVideoSessionDir(sessionID);
	}
882
	
883 884 885 886 887
	public static string GetPhotoFileName (bool small, int uniqueID) {
		return GetPhotosDir(small) + Path.DirectorySeparatorChar + uniqueID.ToString() +
			GetMultimediaExtension(Constants.MultimediaItems.PHOTO);
	}
	
Xavier de Blas's avatar
Xavier de Blas committed
888 889 890 891 892 893
	public static string GetVideoTempFileName() {
		return Path.Combine(
				Path.GetTempPath(), Constants.VideoTemp + 
				GetMultimediaExtension(Constants.MultimediaItems.VIDEO));
	}
	
894 895 896 897 898 899 900 901 902
	public static string GetPhotoTempFileName(bool small) {
		string fileName = Constants.PhotoTemp;
		if(small)
			fileName = Constants.PhotoSmallTemp;

		return Path.Combine(
				Path.GetTempPath(), fileName + GetMultimediaExtension(Constants.MultimediaItems.PHOTO));
	}
	
903 904 905 906 907 908
	public static string GetMultimediaExtension (Constants.MultimediaItems multimediaItem) {
		if(multimediaItem == Constants.MultimediaItems.VIDEO)
			return Constants.ExtensionVideo;
		else //multimediaItem = Constants.MultimediaItems.PHOTO
			return Constants.ExtensionPhoto;
	}
Xavier de Blas's avatar
Xavier de Blas committed
909
			
910
	public static bool CopyTempVideo(int sessionID, Constants.TestTypes type, int uniqueID) {
911 912
		string origin = GetVideoTempFileName();
		string destination = GetVideoFileName(sessionID, type, uniqueID);
913
		if(File.Exists(origin)) {
Xavier de Blas's avatar
Xavier de Blas committed
914
			CreateVideoSessionDirIfNeeded(sessionID);
915 916
			/*
			 * no more move it, just copy it, because maybe is still being recorded
917
			try {
918
				File.Move(origin, destination);
919
			} catch {
920 921 922
			*/
				File.Copy(origin, destination, true); //can be overwritten
			//}
923 924 925
			return true;
		} else
			return false;
Xavier de Blas's avatar
Xavier de Blas committed
926
	}
927 928 929 930 931 932 933
	
	public static void DeleteVideo(int sessionID, Constants.TestTypes type, int uniqueID) {
		string fileName = GetVideoFileName(sessionID, type, uniqueID);
		if(File.Exists(fileName)) 
			File.Delete(fileName);
	}

Xavier de Blas's avatar
Xavier de Blas committed
934
	/********** end of multimedia paths ************/
935 936 937



938 939
	public static string GetManualDir() {
		//we are on:
Andoni Morales's avatar
Andoni Morales committed
940
		//lib/chronojump/ (Unix) or bin/ (win32)
941
		//we have to go to
Andoni Morales's avatar
Andoni Morales committed
942
		//share/doc/chronojump
943 944
		return System.IO.Path.Combine(Util.GetPrefixDir(),
			"share" + Path.DirectorySeparatorChar + "doc" + Path.DirectorySeparatorChar + "chronojump");
Andoni Morales's avatar
Andoni Morales committed
945 946 947
	}

	public static string GetPrefixDir(){
948
		string baseDirectory = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "..");
Xavier de Blas's avatar
Xavier de Blas committed
949
		if (! Directory.Exists(Path.Combine(baseDirectory, "lib" + Path.DirectorySeparatorChar + "chronojump"))) {
950 951 952
			baseDirectory = System.IO.Path.Combine(baseDirectory, "..");
		}
		return baseDirectory;
953 954
	}

Xavier de Blas's avatar
Xavier de Blas committed
955
	public static string GetDataDir(){
956 957
		return System.IO.Path.Combine(GetPrefixDir(),
			"share" + Path.DirectorySeparatorChar + "chronojump");
958
	}
959

960
	public static string GetImagesDir(){
Xavier de Blas's avatar
Xavier de Blas committed
961
		return System.IO.Path.Combine(GetDataDir(),"images");
962
	}
963

964
	public static string GetCssDir(){
Xavier de Blas's avatar
Xavier de Blas committed
965
		return GetDataDir();
966
	}
967 968 969 970 971 972

	//currently sounds are inside images folder	
	public static string GetSoundsDir(){
		return GetImagesDir();
	}
	
973
	
974
	public static void BackupDirCreateIfNeeded () {
975
		string backupDir = GetDatabaseDir() + Path.DirectorySeparatorChar + "backup";
976 977
		if( ! Directory.Exists(backupDir)) {
			Directory.CreateDirectory (backupDir);
978
			LogB.Information ("created backup dir");
979 980
		}
	}
981 982 983

	public static void BackupDatabase () {
		string homeDir = GetDatabaseDir();
984
		string backupDir = homeDir + Path.DirectorySeparatorChar + "backup";
985
		
986
		string dateParsed = UtilDate.ToFile(DateTime.Now);
987 988 989

		if(File.Exists(System.IO.Path.Combine(homeDir, "chronojump.db")))
			File.Copy(System.IO.Path.Combine(homeDir, "chronojump.db"), 
990
				System.IO.Path.Combine(backupDir, "chronojump_" + dateParsed + ".db"));
991
		else {
992
			LogB.Error("Error, chronojump.db file doesn't exist!");
993 994
		}
	}
995 996 997 998 999 1000 1001 1002 1003

	//http://stackoverflow.com/a/58779	
	public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) {
		foreach (DirectoryInfo dir in source.GetDirectories())
			CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
		foreach (FileInfo file in source.GetFiles())
			file.CopyTo(Path.Combine(target.FullName, file.Name));
	}

1004 1005 1006
	public static bool FileDelete(string fileName) 
	{
		LogB.Information("Checking if this filename exists: " + fileName);
1007 1008
		try {
			if(File.Exists(fileName)) {
1009
				LogB.Information("Deleting " + fileName + " ...");
1010
				File.Delete(fileName);
1011
				LogB.Information("Deleted");
1012 1013
				return true;
			}
1014
		} catch {
1015
			LogB.Error("Problem deleting");
1016
		}
1017 1018
		return false;
	}
1019
	
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
	public static bool FileMove(string path, string filenameOrigin, string filenameDestination) {
		try {
			File.Move(
					path + Path.DirectorySeparatorChar + filenameOrigin, 
					path + Path.DirectorySeparatorChar + filenameDestination
					);
			return true;
		} catch {}
		return false;
	}
	
1031 1032 1033
	public static bool FileExists(string fileName){
		return File.Exists(fileName);
	}
1034

1035
	//not recommended, better use below method. Better for bigger files
1036
	public static string ReadFile(string fileName, bool removeEOL)
1037 1038 1039 1040 1041
	{
		try {
			StreamReader reader = File.OpenText(fileName);
			string contents = reader.ReadToEnd ();
			reader.Close();
1042 1043 1044 1045 1046
			
			//delete the '\n' that ReaderToEnd() has put
			if(removeEOL)
				contents = contents.TrimEnd(new char[1] {'\n'});
			
1047 1048 1049 1050 1051
			return contents;
		} catch {
			return null;
		}
	}
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
	//recommended method
	public static List<string> ReadFileAsStringList(string fileName)
	{
		try {
			List<string> lines = new List<string>();
			using (var sr = new StreamReader(fileName))
			{
				while (sr.Peek() >= 0)
				{
					lines.Add(sr.ReadLine());
				}
			}
			return(lines);
		} catch {
			return null;
		}
	}

1070

1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
	//returns int [] of encoder signal or curve
	//currently used on db conversion 1.05 -> 1.06
	public static int [] ReadFileAsInts(string fileName)
	{
		string contents;
		try {
			StreamReader reader = File.OpenText(fileName);
			contents = reader.ReadToEnd ();
			reader.Close();
		} catch {
			return new int [] {};
		}
	
		//create ints file bigger enought to hold all possible values 	
		int [] ints = new int [contents.Length];
		int count = 0;
		for(int i=0; i < contents.Length; i++) {
			if(Char.IsDigit(contents[i])) {
				ints[count] = Convert.ToInt32(contents[i]);
				if(i > 0 && contents[i-1] == '-')
					ints[count] *= -1;
				
				count ++;
			}
		}
		
		//create int [] with the needed sized
		int [] intsCut = new int [count];
		for(int i=0; i < count; i ++)
			intsCut[i] = ints[i];

		return intsCut;
	}

Xavier de Blas's avatar
Xavier de Blas committed
1105

1106
	public static void RunRScript(string rScript){
Xavier de Blas's avatar
Xavier de Blas committed
1107
		//CancelRScript = false;
1108

1109
		ProcessStartInfo pinfo;
Xavier de Blas's avatar
Xavier de Blas committed
1110
	        Process r;
1111 1112 1113
		string rBin="R";
		//If output file is not given, R will try to write in the running folder
		//in which we may haven't got permissions
1114 1115 1116 1117
		string outputFile = rScript+".Rout";
		
		if (File.Exists(outputFile))
			File.Delete(outputFile);
1118
 
1119
		if (UtilAll.IsWindows())
1120 1121 1122 1123
			rBin=System.IO.Path.Combine(GetPrefixDir(), "bin/R.exe");

		pinfo = new ProcessStartInfo();
		pinfo.FileName=rBin;
1124
		pinfo.Arguments ="CMD BATCH --no-save " + rScript +" " + outputFile;
1125 1126
		pinfo.CreateNoWindow = true;
		pinfo.UseShellExecute = false;
1127
	
1128 1129 1130 1131 1132 1133 1134 1135
		try {	
			r = new Process();
				r.StartInfo = pinfo;
				r.Start();
			r.WaitForExit();
			//while ( ! ( File.Exists(outputFile) || CancelRScript) );
			while ( ! ( File.Exists(outputFile) ) );
		} catch {
1136
			//maybe R is not installed
1137
		}
1138
	}
Xavier de Blas's avatar
Xavier de Blas committed
1139
	
Xavier de Blas's avatar
Xavier de Blas committed
1140

1141 1142 1143
/*
 * currently not used, we copy the assemblies now
 *
1144
	public static void CopyArchivesOninstallation(string fileName) {
1145
		string homeDir = GetDatabaseDir();
1146 1147 1148 1149 1150
		//copy files, and continue if already exists or if origin file doesn't exist
		try {
			File.Copy(fileName , homeDir + "/" + fileName );
		} catch {}
	}
1151
*/
1152
	
1153 1154 1155
	//public static void PlaySound (System.Media.SystemSounds mySound, bool volumeOn) {
	public static void PlaySound (Constants.SoundTypes mySound, bool volumeOn) {
		if(volumeOn) {
1156 1157
			//TODO: this try/catch still doesn't work in my laptop with sound problems
			try {
1158 1159
				if(UtilAll.GetOSEnum() == UtilAll.OperatingSystems.LINUX) 
				{
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
					string fileName = "";
					switch(mySound) {
						case Constants.SoundTypes.CAN_START:
							fileName = "123804__kendallbear__kendallklap1.wav";
							//author: kendallbear
							//https://www.freesound.org/people/kendallbear/sounds/123804/
							break;
						case Constants.SoundTypes.GOOD:
							fileName = "135936__bradwesson__collectcoin.wav";
							//author: bradwesson
							//https://www.freesound.org/people/bradwesson/sounds/135936/
							break;
						case Constants.SoundTypes.BAD:
							fileName = "142608__autistic-lucario__error.wav";
							//author: Autistic Lucario
							//https://www.freesound.org/people/Autistic%20Lucario/sounds/142608/
							break;
					}
							
					fileName = Util.GetSoundsDir() + Path.DirectorySeparatorChar + fileName;
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

					if(! File.Exists(fileName)) {
						LogB.Warning("Cannot found this sound file: " + fileName);
						return;
					}
					
					ProcessStartInfo pinfo = new ProcessStartInfo();
					string pBin="gst-launch-0.10";
		
					pinfo.FileName=pBin;
					pinfo.Arguments = "playbin " + @"uri=file://" + fileName;
					LogB.Information("Arguments:", pinfo.Arguments);
					pinfo.CreateNoWindow = true;
					pinfo.UseShellExecute = false;

					Process p = new Process();
					p.StartInfo = pinfo;
					p.Start();
				}
				else {
					switch(mySound) {
						case Constants.SoundTypes.CAN_START:
							System.Media.SystemSounds.Question.Play();
							break;
						case Constants.SoundTypes.GOOD:
							System.Media.SystemSounds.Asterisk.Play();
							break;
						case Constants.SoundTypes.BAD:
							//System.Media.SystemSounds.Beep.Play();
							System.Media.SystemSounds.Hand.Play();
							break;
					}
1212
				}
1213
			} catch {}
1214 1215
		}
	}
1216

1217 1218 1219

	public static string GetImagePath(bool mini) {
		string returnString = "";
1220
		if (UtilAll.IsWindows()) {
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
			if (mini) {
				returnString = Constants.ImagesMiniWindows;
			} else {
				returnString = Constants.ImagesWindows;
			}
		} else {
			if (mini) {
				returnString = Constants.ImagesMiniLinux;
			} else {
				returnString = Constants.ImagesLinux;
			}
		}
		return returnString;
	}
1235
		
1236
	public static string GetGladePath() {
1237
		if (UtilAll.IsWindows())
1238 1239 1240 1241
			return Constants.GladeWindows;
		else
			return Constants.GladeLinux;
	}
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

		
	//do this for showing the Limited with selected decimals and without loosing the end letter: 'J' or 'T'
	//called by treeview_jump, treeview_run and gui/jump_edit and gui/run_edit?
	public static string GetLimitedRounded(string limitedString, int pDN) {
		string myLimitedWithoutLetter = limitedString.Substring(0, limitedString.Length -1);
		string myLimitedLetter = limitedString.Substring(limitedString.Length -1, 1);

		return TrimDecimals(myLimitedWithoutLetter, pDN) + myLimitedLetter;
	}

1253 1254 1255 1256 1257 1258 1259
	public static string [] AddArrayString(string [] initialString, string [] addString) {
		string [] returnString = new string[initialString.Length + addString.Length];
		int i;
		int j;
		for (i=0 ; i < initialString.Length; i ++)
			returnString[i] = initialString[i];
		for (j=0 ; j < addString.Length; j ++)
1260
			returnString[i+j] = addString[j];
1261 1262 1263

		return returnString;
	}
1264

Xavier de Blas's avatar
Xavier de Blas committed
1265 1266
	//bool firstOrLast: true means first
	public static string [] AddArrayString(string [] initialString, string addString, bool firstOrLast) {
1267
		string [] returnString = new string[initialString.Length + 1];
Xavier de Blas's avatar
Xavier de Blas committed
1268

1269
		int i;
Xavier de Blas's avatar
Xavier de Blas committed
1270 1271
		if(firstOrLast) {
			returnString[0] = addString;
1272
			
Xavier de Blas's avatar
Xavier de Blas committed
1273 1274 1275 1276 1277 1278 1279 1280
			for (i=0 ; i < initialString.Length; i ++)
				returnString[i+1] = initialString[i];
		} else {
			for (i=0 ; i < initialString.Length; i ++)
				returnString[i] = initialString[i];

			returnString[i] = addString;
		}
1281 1282 1283 1284

		return returnString;
	}

1285
	public static string [] ArrayListToString (ArrayList myArrayList) {
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
		//if myArrayList is not defined, return with an empty string
		try { 
			string [] myString = new String[myArrayList.Count];
			int i=0;
			foreach (string str in myArrayList) 
				myString[i++] = str;
		
			return myString;
		}
		catch {
			string [] myString = new String[0];
			return myString;
		}
1299 1300
	}
			
Xavier de Blas's avatar
Xavier de Blas committed
1301
	public static string ArrayListToSingleString (ArrayList myArrayList, string sep) {
1302
		string myString = "";
Xavier de Blas's avatar
Xavier de Blas committed
1303 1304 1305 1306 1307
		string sepUsed = "";
		foreach (string str in myArrayList) { 
			myString += sepUsed + str;
			sepUsed =  sep;
		}
1308 1309 1310 1311

		return myString;
	}
			
1312
	public static ArrayList AddToArrayListIfNotExist(ArrayList myArrayList, string str) {
1313 1314 1315 1316 1317 1318 1319
	 	bool found = FoundInArrayList(myArrayList, str);
		if(!found)
			myArrayList.Add(str);

		return myArrayList;
	}

1320 1321
	public static bool FoundInArrayList(ArrayList a, string str) {
		foreach (string str2 in a)
1322
			if(str2 == str)
1323
				return true;
1324

1325
		return false;
1326
	}
1327

1328 1329 1330 1331 1332 1333 1334
	public static bool FoundInArrayList(ArrayList a, int i) {
		foreach (int j in a)
			if(i == j)
				return true;

		return false;
	}
1335 1336 1337 1338 1339 1340 1341 1342 1343
	
	public static bool FoundInStringArray(string [] a, string str) {
		foreach (string str2 in a)
			if(str2 == str)
				return true;

		return false;
	}

1344 1345 1346 1347 1348 1349 1350
	public static ArrayList RemoveLastArrayElement(ArrayList a) {
		if(a.Count > 0)
			a.RemoveAt(a.Count - 1);

		return a;
	}

1351

1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
	/*
	//delete a row of and arraylist of string[] if the string[0] is the value coming from startsWith
	public static ArrayList DeleteFromArrayList(ArrayList firstArrayList, string startsWith, char delimited) {
		ArrayList secondArrayList = new ArrayList();
		foreach (string str2 in firstArrayList) {
			string [] strFull = str2.Split(new char[] {delimited});
			if(strFull[0] != startsWith)
				secondArrayList.Add(str2);
		}

		return secondArrayList;
	}
*/
	public static string StringArrayToString (string [] myFullString