Search Results

Search found 6374 results on 255 pages for 'double underscore'.

Page 45/255 | < Previous Page | 41 42 43 44 45 46 47 48 49 50 51 52  | Next Page >

  • Java data structure suggestion.

    - by techoverflow
    Hi folks, I am a newbie in this field so please excuse my silly mistakes :) So the issue I am facing is: On my webpage, I am displaying a table. For now my issue is concerned with three columns of the table. First is : Area Code Second is : Zone Code Third is: Value The relationship between these three is: 1 Area Code has 6 different Zone code's and all those 6 Zone codes have corresponding "Value" I need a data structer that would give me the flexibility to get a "Value" for a Zone code, which falls under a particular Area code. I have the same zone codes for all the Area codes: Zone codes are: 111, 222, 333, 444, 555, 666 After surfing your stackoverflow, I thought I can go with this structure: Map<Integer, Map<Integer, Double>> retailPrices = new HashMap<Integer, Map<Integer, Double>>(); Map<Integer, Double> codes = new HashMap<Integer, Double>(); where reatailPrices would hold an Area Code and a Map of Zone code as Key and "Value" as Value. but when I am trying to populate this through a SQL resultset, I am getting the following error: The method put(Integer, Map<Integer,Double>) in the type Map is not applicable for the arguments (Integer, Double) on line: `while(oResult.next()) retailPrices.put((new Integer(oResult.getString("AREA"))), (pegPlPrices.put(new Integer(oResult.getString("ZONE_CODE")), new Double(oResult.getString("VALUE"))))); }` please help me figure out this problem. Am I following the right approach?

    Read the article

  • Interesting Scala typing solution, doesn't work in 2.7.7?

    - by djc
    I'm trying to build some image algebra code that can work with images (basically a linear pixel buffer + dimensions) that have different types for the pixel. To get this to work, I've defined a parametrized Pixel trait with a few methods that should be able to get used with any Pixel subclass. (For now, I'm only interested in operations that work on the same Pixel type.) Here it is: trait Pixel[T <: Pixel[T]] { def mul(v: Double): T def max(v: T): T def div(v: Double): T def div(v: T): T } Now I define a single Pixel type that has storage based on three doubles (basically RGB 0.0-1.0), I've called it TripleDoublePixel: class TripleDoublePixel(v: Array[Double]) extends Pixel[TripleDoublePixel] { var data: Array[Double] = v def this() = this(Array(0.0, 0.0, 0.0)) def toString(): String = { "(" + data(0) + ", " + data(1) + ", " + data(2) + ")" } def increment(v: TripleDoublePixel) { data(0) += v.data(0) data(1) += v.data(1) data(2) += v.data(2) } def mul(v: Double): TripleDoublePixel = { new TripleDoublePixel(data.map(x => x * v)) } def div(v: Double): TripleDoublePixel = { new TripleDoublePixel(data.map(x => x / v)) } def div(v: TripleDoublePixel): TripleDoublePixel = { var tmp = new Array[Double](3) tmp(0) = data(0) / v.data(0) tmp(1) = data(1) / v.data(1) tmp(2) = data(2) / v.data(2) new TripleDoublePixel(tmp) } def max(v: TripleDoublePixel): TripleDoublePixel = { val lv = data(0) * data(0) + data(1) * data(1) + data(2) * data(2) val vv = v.data(0) * v.data(0) + v.data(1) * v.data(1) + v.data(2) * v.data(2) if (lv > vv) (this) else v } } Now I want to write code to use this, that doesn't have to know what type the pixels are. For example: def idiv[T](a: Image[T], b: Image[T]) { for (i <- 0 until a.data.size) { a.data(i) = a.data(i).div(b.data(i)) } } Unfortunately, this doesn't compile: (fragment of lindet-gen.scala):145: error: value div is not a member of T a.data(i) = a.data(i).div(b.data(i)) I was told in #scala that this worked for someone else, but that was on 2.8. I've tried to get 2.8-rc1 going, but it doesn't compile for me. Is there any way to get this to work in 2.7.7?

    Read the article

  • Dynamic Array of Objects Sans Vector Class

    - by Connor Black
    I am doing a homework assignment for my summer OO class and we need to write two classes. One is called Sale and the other is called Register. I've written my Sale class; here's the .h file: enum ItemType {BOOK, DVD, SOFTWARE, CREDIT}; class Sale { public: Sale(); // default constructor, // sets numerical member data to 0 void MakeSale(ItemType x, double amt); ItemType Item(); // Returns the type of item in the sale double Price(); // Returns the price of the sale double Tax(); // Returns the amount of tax on the sale double Total(); // Returns the total price of the sale void Display(); // outputs sale info private: double price; // price of item or amount of credit double tax; // amount of sales tax double total; // final price once tax is added in. ItemType item; // transaction type }; For the Register class we need to include a dynamic array of Sale objects in our member data. We cannot use the vector class. How is this done? Here's my 'Register' '.h' class Register{ public: Register(int ident, int amount); ~Register(); int GetID(){return identification;} int GetAmount(){return amountMoney;} void RingUpSale(ItemType item, int basePrice); void ShowLast(); void ShowAll(); void Cancel(); int SalesTax(int n); private: int identification; int amountMoney; };

    Read the article

  • Pointers to a typed variable in C#: Interfase, Generic, object or Class? (Boxing/Unboxing)

    - by PaulG
    First of all, I apologize if this has been asked a thousand times. I read my C# book, I googled it, but I can't seem to find the answer I am looking for, or I am missing the point big time. I am very confused with the whole boxing/unboxing issue. Say I have fields of different classes, all returning typed variables (e.g. 'double') and I would like to have a variable point to any of these fields. In plain old C I would do something like: double * newVar; newVar = &oldVar; newVar = &anotherVar; ... In C#, it seems I could do an interfase, but would require that all fields be properties and named the same. Breaks apart when one of the properties doesn't have the same name or is not a property. I could also create a generic class returning double, but seems a bit absurd to create a class to represent a 'double', when a 'double' class already exists. If I am not mistaken, it doesn't even need to be generic, could be a simple class returning double. I could create an object and box the typed variable to the newly created object, but then I would have to cast every time I use it. Of course, I always have the unsafe option... but afraid of getting to unknown memory space, divide by zero and bring an end to this world. None of these seem to be the same as the old simple 'double * variable'. Am I missing something here?

    Read the article

  • Why is this giving me an infinite loop?

    - by Chase Yuan
    I was going through a code used to calculate investments until it has doubled and I received an infinite loop that I can't seem to solve. Can anyone figure out why this is giving me an infinite loop? I've gone through myself but I can't seem to find the problem. The "period" referred is how many times per year the interest is compounded. double account = 0; //declares the variables to be used double base = 0; double interest = 0; double rate = 0; double result = 0; double times = 0; int years = 0; int j; System.out.println("This is a program that calculates interest."); Scanner kbReader = new Scanner(System.in); //enters in all data System.out.print("Enter account balance: "); account = kbReader.nextDouble(); System.out.print("Enter interest rate (as decimal): "); rate = kbReader.nextDouble(); System.out.println(" " + "Years to double" + " " + "Ending balance"); base = account; result = account; for (j=0; j<3; j++){ System.out.print("Enter period: "); times = kbReader.nextDouble(); while (account < base*2){ interest = account * rate / times; account = interest + base; years++; } account = (((int)(account * 100))/100.0); //results System.out.print(" " + i + " " + account + "\n"); account = result; } The code should ask for three "periods", or three different times the entered data is compounded per year (ex annually, monthly, daily etc.) Thanks a lot!

    Read the article

  • Calling a constructor from method within the same class

    - by Nathan
    I'm new to java and I'm learning about creating object classes. One of my homework assignment requires that I call the constructor at least once within a method of the same object class. I'm getting an error that says The method DoubleMatrix(double[][]) is undefined for the type DoubleMatrix Here's my constructor: public DoubleMatrix(double[][] tempArray) { // Declaration int flag = 0; int cnt; // Statement // check to see if doubArray isn't null and has more than 0 rows if(tempArray == null || tempArray.length < 0) { flag++; } // check to see if each row has the same length if(flag == 0) { for(cnt = 0; cnt <= tempArray.length - 1 || flag != 1; cnt++) { if(tempArray[cnt + 1].length != tempArray[0].length) { flag++; } } } else if(flag == 1) { makeDoubMatrix(1, 1);// call makeDoubMatrix method } }// end constructor 2 Here's the method where I try and call the constructor: public double[][] addMatrix(double[][] tempDoub) { // Declaration double[][] newMatrix; int rCnt, cCnt; //Statement // checking to see if both are of same dimension if(doubMatrix.length == tempDoub.length && doubMatrix[0].length == tempDoub[0].length) { newMatrix = new double[doubMatrix.length][doubMatrix[0].length]; // for loop to add matrix to a new one for(rCnt = 0; rCnt <= doubMatrix.length; rCnt++) { for(cCnt = 0; cCnt <= doubMatrix.length; cCnt++) { newMatrix[rCnt][cCnt] = doubMatrix[rCnt][cCnt] + tempDoub[rCnt][cCnt]; } } } else { newMatrix = new double[0][0]; DoubleMatrix(newMatrix) } return newMatrix; }// end addMatrix method Can someone point me to the right direction and explain why I'm getting an error?

    Read the article

  • User Input That Involves A ' ' Causes A Substring Out Of Range Error

    - by Greenhouse Gases
    Hi Stackoverflow people. You have already helped me quite a bit but near the end of writing this program I have somewhat of a bug. You see in order to read in city names with a space in from a text file I use a '/' that is then replaced by the program for a ' ' (and when the serializer runs the opposite happens for next time the program is run). The problem is when a user inputs a name too add, search for, or delete that contains a space, for instance 'New York' I get a Debug Assertion Error with a substring out of range expression. I have a feeling it's to do with my correctCase function, or setElementsNull that looks at the string until it experiences a null element in the array, however ' ' is not null so I'm not sure how to fix this and I'm going a bit insane. Any help would be much appreciated. Here is my code: // U08221.cpp : main project file. #include "stdafx.h" #include <_iostream> #include <_string> #include <_fstream> #include <_cmath> using namespace std; class locationNode { public: string nodeCityName; double nodeLati; double nodeLongi; locationNode* Next; locationNode(string nameOf, double lat, double lon) { this->nodeCityName = nameOf; this->nodeLati = lat; this->nodeLongi = lon; this->Next = NULL; } locationNode() // NULL constructor { } void swapProps(locationNode *node2) { locationNode place; place.nodeCityName = this->nodeCityName; place.nodeLati = this->nodeLati; place.nodeLongi = this->nodeLongi; this->nodeCityName = node2->nodeCityName; this->nodeLati = node2->nodeLati; this->nodeLongi = node2->nodeLongi; node2->nodeCityName = place.nodeCityName; node2->nodeLati = place.nodeLati; node2->nodeLongi = place.nodeLongi; } void modify(string name) { this->nodeCityName = name; } void modify(double latlon, int mod) { switch(mod) { case 2: this->nodeLati = latlon; break; case 3: this->nodeLongi = latlon; break; } } void correctCase() // Correct upper and lower case letters of input { int MAX_SIZE = 35; int firstLetVal = this->nodeCityName[0], letVal; int n = 1; // variable for name index from second letter onwards if((this->nodeCityName[0] >90) && (this->nodeCityName[0] < 123)) // First letter is lower case { firstLetVal = firstLetVal - 32; // Capitalise first letter this->nodeCityName[0] = firstLetVal; } while(this->nodeCityName[n] != NULL) { if((this->nodeCityName[n] >= 65) && (this->nodeCityName[n] <= 90)) { if(this->nodeCityName[n - 1] != 32) { letVal = this->nodeCityName[n] + 32; this->nodeCityName[n] = letVal; } } n++; } } }; Here is the main part of the program: // U08221.cpp : main project file. #include "stdafx.h" #include "Locations2.h" #include <_iostream> #include <_string> #include <_fstream> #include <_cmath> using namespace std; #define pi 3.14159265358979323846264338327950288 #define radius 6371 #define gig 1073741824 //size of a gigabyte in bytes int n = 0,x, locationCount = 0, MAX_SIZE = 35 , g = 0, i = 0, modKey = 0, xx; string cityNameInput, alter; char targetCity[35], skipKey = ' '; double lat1, lon1, lat2, lon2, dist, dummy, modVal, result; bool acceptedInput = false, match = false, nodeExists = false;// note: addLocation(), set to true to enable user input as opposed to txt file locationNode *temp, *temp2, *example, *seek, *bridge, *start_ptr = NULL; class Menu { int junction; public: /* Convert decimal degrees to radians */ public: void setElementsNull(char cityParam[]) { int y=0; while(cityParam[y] != NULL) { y++; } while(y < MAX_SIZE) { cityParam[y] = NULL; y++; } } void correctCase(string name) // Correct upper and lower case letters of input { int MAX_SIZE = 35; int firstLetVal = name[0], letVal; int n = 1; // variable for name index from second letter onwards if((name[0] >90) && (name[0] < 123)) // First letter is lower case { firstLetVal = firstLetVal - 32; // Capitalise first letter name[0] = firstLetVal; } while(name[n] != NULL) { if((name[n] >= 65) && (name[n] <= 90)) { letVal = name[n] + 32; name[n] = letVal; } n++; } for(n = 0; targetCity[n] != NULL; n++) { targetCity[n] = name[n]; } } bool nodeExistTest(char targetCity[]) // see if entry is present in the database { match = false; seek = start_ptr; int letters = 0, letters2 = 0, x = 0, y = 0; while(targetCity[y] != NULL) { letters2++; y++; } while(x <= locationCount) // locationCount is number of entries currently in list { y=0, letters = 0; while(seek->nodeCityName[y] != NULL) // count letters in the current name { letters++; y++; } if(letters == letters2) // same amount of letters in the name { y = 0; while(y <= letters) // compare each letter against one another { if(targetCity[y] == seek->nodeCityName[y]) { match = true; y++; } else { match = false; y = letters + 1; // no match, terminate comparison } } } if(match) { x = locationCount + 1; //found match so terminate loop } else{ if(seek->Next != NULL) { bridge = seek; seek = seek->Next; x++; } else { x = locationCount + 1; // end of list so terminate loop } } } return match; } double deg2rad(double deg) { return (deg * pi / 180); } /* Convert radians to decimal degrees */ double rad2deg(double rad) { return (rad * 180 / pi); } /* Do the calculation */ double distance(double lat1, double lon1, double lat2, double lon2, double dist) { dist = sin(deg2rad(lat1)) * sin(deg2rad(lat2)) + cos(deg2rad(lat1)) * cos(deg2rad(lat2)) * cos(deg2rad(lon1 - lon2)); dist = acos(dist); dist = rad2deg(dist); dist = (radius * pi * dist) / 180; return dist; } void serialise() { // Serialize to format that can be written to text file fstream outfile; outfile.open("locations.txt",ios::out); temp = start_ptr; do { for(xx = 0; temp->nodeCityName[xx] != NULL; xx++) { if(temp->nodeCityName[xx] == 32) { temp->nodeCityName[xx] = 47; } } outfile << endl << temp->nodeCityName<< " "; outfile<<temp->nodeLati<< " "; outfile<<temp->nodeLongi; temp = temp->Next; }while(temp != NULL); outfile.close(); } void sortList() // do this { int changes = 1; locationNode *node1, *node2; while(changes > 0) // while changes are still being made to the list execute { node1 = start_ptr; node2 = node1->Next; changes = 0; do { xx = 1; if(node1->nodeCityName[0] > node2->nodeCityName[0]) //compare first letter of name with next in list { node1->swapProps(node2); // should come after the next in the list changes++; } else if(node1->nodeCityName[0] == node2->nodeCityName[0]) // if same first letter { while(node1->nodeCityName[xx] == node2->nodeCityName[xx]) // check next letter of name { if((node1->nodeCityName[xx + 1] != NULL) && (node2->nodeCityName[xx + 1] != NULL)) // check next letter until not the same { xx++; } else break; } if(node1->nodeCityName[xx] > node2->nodeCityName[xx]) { node1->swapProps(node2); // should come after the next in the list changes++; } } node1 = node2; node2 = node2->Next; // move to next pair in list } while(node2 != NULL); } } void initialise() { cout << "Populating List..."; ifstream inputFile; inputFile.open ("locations.txt", ios::in); char inputName[35] = " "; double inputLati = 0, inputLongi = 0; //temp = new locationNode(inputName, inputLati, inputLongi); do { inputFile.get(inputName, 35, ' '); inputFile >> inputLati; inputFile >> inputLongi; if(inputName[0] == 10 || 13) //remove linefeed from input { for(int i = 0; inputName[i] != NULL; i++) { inputName[i] = inputName[i + 1]; } } for(xx = 0; inputName[xx] != NULL; xx++) { if(inputName[xx] == 47) // if it is a '/' { inputName[xx] = 32; // replace it for a space } } temp = new locationNode(inputName, inputLati, inputLongi); if(start_ptr == NULL){ // if list is currently empty, start_ptr will point to this node start_ptr = temp; } else { temp2 = start_ptr; // We know this is not NULL - list not empty! while (temp2->Next != NULL) { temp2 = temp2->Next; // Move to next link in chain until reach end of list } temp2->Next = temp; } ++locationCount; // increment counter for number of records in list } while(!inputFile.eof()); cout << "Successful!" << endl << "List contains: " << locationCount << " entries" << endl; inputFile.close(); cout << endl << "*******************************************************************" << endl << "DISTANCE CALCULATOR v2.0\tAuthors: Darius Hodaei, Joe Clifton" << endl; } void menuInput() { char menuChoice = ' '; while(menuChoice != 'Q') { // Menu if(skipKey != 'X') // This is set by case 'S' below if a searched term does not exist but wants to be added { cout << endl << "*******************************************************************" << endl; cout << "Please enter a choice for the menu..." << endl << endl; cout << "(P) To print out the list" << endl << "(O) To order the list alphabetically" << endl << "(A) To add a location" << endl << "(D) To delete a record" << endl << "(C) To calculate distance between two points" << endl << "(S) To search for a location in the list" << endl << "(M) To check memory usage" << endl << "(U) To update a record" << endl << "(Q) To quit" << endl; cout << endl << "*******************************************************************" << endl; cin >> menuChoice; if(menuChoice >= 97) { menuChoice = menuChoice - 32; // Turn the lower case letter into an upper case letter } } skipKey = ' '; //Reset skipKey so that it does not skip the menu switch(menuChoice) { case 'P': temp = start_ptr; // set temp to the start of the list do { if (temp == NULL) { cout << "You have reached the end of the database" << endl; } else { // Display details for what temp points to at that stage cout << "Location : " << temp->nodeCityName << endl; cout << "Latitude : " << temp->nodeLati << endl; cout << "Longitude : " << temp->nodeLongi << endl; cout << endl; // Move on to next locationNode if one exists temp = temp->Next; } } while (temp != NULL); break; case 'O': { sortList(); // pass by reference??? cout << "List reordered alphabetically" << endl; } break; case 'A': char cityName[35]; double lati, longi; cout << endl << "Enter the name of the location: "; cin >> cityName; for(xx = 0; cityName[xx] != NULL; xx++) { if(cityName[xx] == 47) // if it is a '/' { cityName[xx] = 32; // replace it for a space } } if(!nodeExistTest(cityName)) { cout << endl << "Please enter the latitude value for this location: "; cin >> lati; cout << endl << "Please enter the longitude value for this location: "; cin >> longi; cout << endl; temp = new locationNode(cityName, lati, longi); temp->correctCase(); //start_ptr allignment if(start_ptr == NULL){ // if list is currently empty, start_ptr will point to this node start_ptr = temp; } else { temp2 = start_ptr; // We know this is not NULL - list not empty! while (temp2->Next != NULL) { temp2 = temp2->Next; // Move to next link in chain until reach end of list } temp2->Next = temp; } ++locationCount; // increment counter for number of records in list cout << "Location sucessfully added to the database! There are " << locationCount << " location(s) stored" << endl; } else { cout << "Node is already present in the list and so cannot be added again" << endl; } break; case 'D': { junction = 0; locationNode *place; cout << "Enter the name of the city you wish to remove" << endl; cin >> targetCity; setElementsNull(targetCity); correctCase(targetCity); for(xx = 0; targetCity[xx] != NULL; xx++) { if(targetCity[xx] == 47) { targetCity[xx] = 32; } } if(nodeExistTest(targetCity)) //if this node does exist { if(seek == start_ptr) // if it is the first in the list { junction = 1; } if(seek->Next == NULL) // if it is last in the list { junction = 2; } switch(junction) // will alter list accordingly dependant on where the searched for link is { case 1: start_ptr = start_ptr->Next; delete seek; --locationCount; break; case 2: place = seek; seek = bridge; seek->Next = NULL; delete place; --locationCount; break; default: bridge->Next = seek->Next; delete seek; --locationCount; break; } cout << endl << "Link deleted. There are now " << locationCount << " locations." << endl; } else { cout << "That entry does not currently exist" << endl << endl << endl; } } break; case 'C': { char city1[35], city2[35]; cout << "Enter the first city name" << endl; cin >> city1; setElementsNull(city1); correctCase(targetCity); if(nodeExistTest(city1)) { lat1 = seek->nodeLati; lon1 = seek->nodeLongi; cout << "Lati = " << seek->nodeLati << endl << "Longi = " << seek->nodeLongi << endl << endl; } cout << "Enter the second city name" << endl; cin >> city2; setElementsNull(city2); correctCase(targetCity); if(nodeExistTest(city2)) { lat2 = seek->nodeLati; lon2 = seek->nodeLongi; cout << "Lati = " << seek->nodeLati << endl << "Longi = " << seek->nodeLongi << endl << endl; } result = distance (lat1, lon1, lat2, lon2, dist); cout << "The distance between these two locations is " << result << " kilometres." << endl; } break; case 'S': { char choice; cout << "Enter search term..." << endl; cin >> targetCity; setElementsNull(targetCity); correctCase(targetCity); if(nodeExistTest(targetCity)) { cout << "Latitude: " << seek->nodeLati << endl << "Longitude: " << seek->nodeLongi << endl; } else { cout << "Sorry, that city is not currently present in the list." << endl << "Would you like to add this city now Y/N?" << endl; cin >> choice; /*while(choice != ('Y' || 'N')) { cout << "Please enter a valid choice..." << endl; cin >> choice; }*/ switch(choice) { case 'Y': skipKey = 'X'; menuChoice = 'A'; break; case 'N': break; default : cout << "Invalid choice" << endl; break; } } break; } case 'M': { cout << "Locations currently stored: " << locationCount << endl << "Memory used for this: " << (sizeof(start_ptr) * locationCount) << " bytes" << endl << endl << "You can store " << ((gig - (sizeof(start_ptr) * locationCount)) / sizeof(start_ptr)) << " more locations" << endl ; break; } case 'U': { cout << "Enter the name of the Location you would like to update: "; cin >> targetCity; setElementsNull(targetCity); correctCase(targetCity); if(nodeExistTest(targetCity)) { cout << "Select (1) to alter City Name, (2) to alter Longitude, (3) to alter Latitude" << endl; cin >> modKey; switch(modKey) { case 1: cout << "Enter the new name: "; cin >> alter; cout << endl; seek->modify(alter); break; case 2: cout << "Enter the new latitude: "; cin >> modVal; cout << endl; seek->modify(modVal, modKey); break; case 3: cout << "Enter the new longitude: "; cin >> modVal; cout << endl; seek->modify(modVal, modKey); break; default: break; } } else cout << "Location not found" << endl; break; } } } } }; int main(array<System::String ^> ^args) { Menu mm; //mm.initialise(); mm.menuInput(); mm.serialise(); }

    Read the article

  • Why is insertion into my tree faster on sorted input than random input?

    - by Juliet
    Now I've always heard binary search trees are faster to build from randomly selected data than ordered data, simply because ordered data requires explicit rebalancing to keep the tree height at a minimum. Recently I implemented an immutable treap, a special kind of binary search tree which uses randomization to keep itself relatively balanced. In contrast to what I expected, I found I can consistently build a treap about 2x faster and generally better balanced from ordered data than unordered data -- and I have no idea why. Here's my treap implementation: http://pastebin.com/VAfSJRwZ And here's a test program: using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; namespace ConsoleApplication1 { class Program { static Random rnd = new Random(); const int ITERATION_COUNT = 20; static void Main(string[] args) { List<double> rndTimes = new List<double>(); List<double> orderedTimes = new List<double>(); rndTimes.Add(TimeIt(50, RandomInsert)); rndTimes.Add(TimeIt(100, RandomInsert)); rndTimes.Add(TimeIt(200, RandomInsert)); rndTimes.Add(TimeIt(400, RandomInsert)); rndTimes.Add(TimeIt(800, RandomInsert)); rndTimes.Add(TimeIt(1000, RandomInsert)); rndTimes.Add(TimeIt(2000, RandomInsert)); rndTimes.Add(TimeIt(4000, RandomInsert)); rndTimes.Add(TimeIt(8000, RandomInsert)); rndTimes.Add(TimeIt(16000, RandomInsert)); rndTimes.Add(TimeIt(32000, RandomInsert)); rndTimes.Add(TimeIt(64000, RandomInsert)); rndTimes.Add(TimeIt(128000, RandomInsert)); string rndTimesAsString = string.Join("\n", rndTimes.Select(x => x.ToString()).ToArray()); orderedTimes.Add(TimeIt(50, OrderedInsert)); orderedTimes.Add(TimeIt(100, OrderedInsert)); orderedTimes.Add(TimeIt(200, OrderedInsert)); orderedTimes.Add(TimeIt(400, OrderedInsert)); orderedTimes.Add(TimeIt(800, OrderedInsert)); orderedTimes.Add(TimeIt(1000, OrderedInsert)); orderedTimes.Add(TimeIt(2000, OrderedInsert)); orderedTimes.Add(TimeIt(4000, OrderedInsert)); orderedTimes.Add(TimeIt(8000, OrderedInsert)); orderedTimes.Add(TimeIt(16000, OrderedInsert)); orderedTimes.Add(TimeIt(32000, OrderedInsert)); orderedTimes.Add(TimeIt(64000, OrderedInsert)); orderedTimes.Add(TimeIt(128000, OrderedInsert)); string orderedTimesAsString = string.Join("\n", orderedTimes.Select(x => x.ToString()).ToArray()); Console.WriteLine("Done"); } static double TimeIt(int insertCount, Action<int> f) { Console.WriteLine("TimeIt({0}, {1})", insertCount, f.Method.Name); List<double> times = new List<double>(); for (int i = 0; i < ITERATION_COUNT; i++) { Stopwatch sw = Stopwatch.StartNew(); f(insertCount); sw.Stop(); times.Add(sw.Elapsed.TotalMilliseconds); } return times.Average(); } static void RandomInsert(int insertCount) { Treap<double> tree = new Treap<double>((x, y) => x.CompareTo(y)); for (int i = 0; i < insertCount; i++) { tree = tree.Insert(rnd.NextDouble()); } } static void OrderedInsert(int insertCount) { Treap<double> tree = new Treap<double>((x, y) => x.CompareTo(y)); for(int i = 0; i < insertCount; i++) { tree = tree.Insert(i + rnd.NextDouble()); } } } } And here's a chart comparing random and ordered insertion times in milliseconds: Insertions Random Ordered RandomTime / OrderedTime 50 1.031665 0.261585 3.94 100 0.544345 1.377155 0.4 200 1.268320 0.734570 1.73 400 2.765555 1.639150 1.69 800 6.089700 3.558350 1.71 1000 7.855150 4.704190 1.67 2000 17.852000 12.554065 1.42 4000 40.157340 22.474445 1.79 8000 88.375430 48.364265 1.83 16000 197.524000 109.082200 1.81 32000 459.277050 238.154405 1.93 64000 1055.508875 512.020310 2.06 128000 2481.694230 1107.980425 2.24 I don't see anything in the code which makes ordered input asymptotically faster than unordered input, so I'm at a loss to explain the difference. Why is it so much faster to build a treap from ordered input than random input?

    Read the article

  • ArrayList access

    - by Ricky McQuesten
    So once again I have a question about this program. I want to store transactions that are made in an arraylist and then have an option in the case menu where I can print out those that are stored. I have been researching online and have been unable to find a solution to this, so is this possible and how would I go about doing this? I also want to attach a timestamp to each transaction as well. Here is the code I have so far. So my question is how would I add a timestamp to each withdrawal or deposit, and how would I store each transaction in array list? import java.util.*; public class BankAccount extends Money { //inheritence static String name; public static int acctNum; public static double balance, amount; BankAccount(String name, int accNo, double bal) { this.name = name; this.acctNum = accNo; this.balance = bal; } void display() { System.out.println("Your Name:" + name); System.out.println("Your Account Number:" + acctNum); System.out.println("Your Current Account Balance:" + Money.getBalance()); } void displayBalance() { System.out.println("Balance:" + balance); } } import java.util.Scanner; /** * * @author Ricky */ public class Money { public static int accountNumber; public static double balance; static double amount; static String name; public void setDeposit(double amount) { balance = balance + amount; if (amount < 0) { System.out.println("Invalid"); } } public double getDeposit() { return 1; } public void setBalance(double b) { balance = b; } public static double getBalance() { return balance; } public void setWithdraw(double amount) { if (balance < amount) { System.out.println("Not enough funds."); } else if(amount < 0) { System.out.println("Invalid"); } else { balance = balance - amount; } } public double getWithdraw() { return 1; } } import java.util.*; public class Client { public static void main(String args[]) { int n = 0; int count; String trans; ArrayList<String> transaction= new ArrayList<String>(n); Scanner input = new Scanner(System.in); System.out.println("Welcome to First National Bank"); System.out.println("Please enter your name: "); String cusName = input.nextLine(); System.out.println("You will now be assigned an account number."); Random randomGenerator = new Random(); int accNo = randomGenerator.nextInt(100000); //random number System.out.println("Your account number is: " + accNo); System.out.println("Please enter your initial account balance: "); Double balance = input.nextDouble(); BankAccount b1 = new BankAccount(cusName, accNo, balance); b1.setBalance(balance); int menu; /*System.out.println("Menu"); System.out.println("1. Deposit Amount"); System.out.println("2. Withdraw Amount"); System.out.println("3. Display Information"); System.out.println("4. Exit");*/ boolean quit = false; do { System.out.println("*******Menu*******"); System.out.println("1. Deposit Amount"); // menu to take input from user System.out.println("2. Withdraw Amount"); System.out.println("3. Display Information"); System.out.println("4. Exit"); System.out.print("Please enter your choice: "); menu = input.nextInt(); switch (menu) { case 1: System.out.print("Enter depost amount:"); b1.setDeposit(input.nextDouble()); b1.getDeposit(); transaction.add(trans); break; case 2: System.out.println("Current Account Balance=" + b1.getBalance()); System.out.print("Enter withdrawal amount:"); b1.setWithdraw(input.nextDouble()); b1.getWithdraw(); transaction.add(trans); break; // switch statments to do a loop case 3: b1.display(); break; case 4: quit = true; break; } } while (!quit); } } public class Date { static Date time = new Date(); }

    Read the article

  • Pass a Delphi class to a C++ function/method that expects a class with __thiscall methods.

    - by Alan G.
    I have some MSVC++ compiled DLL's for which I have created COM-like (lite) interfaces (abstract Delphi classes). Some of those classes have methods that need pointers to objects. These C++ methods are declared with the __thiscall calling convention (which I cannot change), which is just like __stdcall, except a this pointer is passed on the ECX register. I create the class instance in Delphi, then pass it on to the C++ method. I can set breakpoints in Delphi and see it hitting the exposed __stdcall methods in my Delphi class, but soon I get a STATUS_STACK_BUFFER_OVERRUN and the app has to exit. Is it possible to emulate/deal with __thiscall on the Delphi side of things? If I pass an object instantiated by the C++ system then all is good, and that object's methods are called (as would be expected), but this is useless - I need to pass Delphi objects. Edit 2010-04-19 18:12 This is what happens in more detail: The first method called (setLabel) exits with no error (though its a stub method). The second method called (init), enters then dies when it attempts to read the vol parameter. C++ Side #define SHAPES_EXPORT __declspec(dllexport) // just to show the value class SHAPES_EXPORT CBox { public: virtual ~CBox() {} virtual void init(double volume) = 0; virtual void grow(double amount) = 0; virtual void shrink(double amount) = 0; virtual void setID(int ID = 0) = 0; virtual void setLabel(const char* text) = 0; }; Delphi Side IBox = class public procedure destroyBox; virtual; stdcall; abstract; procedure init(vol: Double); virtual; stdcall; abstract; procedure grow(amount: Double); virtual; stdcall; abstract; procedure shrink(amount: Double); virtual; stdcall; abstract; procedure setID(val: Integer); virtual; stdcall; abstract; procedure setLabel(text: PChar); virtual; stdcall; abstract; end; TMyBox = class(IBox) protected FVolume: Double; FID: Integer; FLabel: String; // public constructor Create; destructor Destroy; override; // BEGIN Virtual Method implementation procedure destroyBox; override; stdcall; // empty - Dont need/want C++ to manage my Delphi objects, just call their methods procedure init(vol: Double); override; stdcall; // FVolume := vol; procedure grow(amount: Double); override; stdcall; // Inc(FVolume, amount); procedure shrink(amount: Double); override; stdcall; // Dec(FVolume, amount); procedure setID(val: Integer); override; stdcall; // FID := val; procedure setLabel(text: PChar); override; stdcall; // Stub method; empty. // END Virtual Method implementation property Volume: Double read FVolume; property ID: Integer read FID; property Label: String read FLabel; end; I would have half expected using stdcall alone to work, but something is messing up, not sure what, perhaps something to do with the ECX register being used? Help would be greatly appreciated. Edit 2010-04-19 17:42 Could it be that the ECX register needs to be preserved on entry and restored once the function exits? Is the this pointer required by C++? I'm probably just reaching at the moment based on some intense Google searches. I found something related, but it seems to be dealing with the reverse of this issue.

    Read the article

  • Referencing ASP.net textbox data in JavaScripts

    - by GoldenEarring
    I'm interested in making an interactive 3D pie chart using JavaScript and ASP.net controls for a webpage. Essentially, I want to make an interactive version of the chart here: https://google-developers.appspot.com/chart/interactive/docs/gallery/piechart#3D I want to have 5 ASP.net textboxes where the user enters data and then submits it, and the chart adjusts according to what the user enters. I understand using ASP.net controls with JS is probably not the most effective way to go about it, but I would really appreciate if someone could share how doing this would be possible. I really don't know where to begin. Thanks for any help! <%@ Page Language="C#" %> <!DOCTYPE html> <script runat="server"> void btn1_Click(object sender, EventArgs e) { double s = 0.0; double b = 0; double g = 0.0f; double c = 0.0f; double h = 0.0f; s = double.Parse(txtWork.Text); b = double.Parse(txtEat.Text); g = double.Parse(txtCommute.Text); c = double.Parse(txtWatchTV.Text); h = double.Parse(txtSleep.Text); double total = s + b + g + c + h; if (total != 24) { lblError.Text = "Warning! A day has 24 hours"; } if (total == 24) { lblError.Text = string.Empty; } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", { packages: ["corechart"] }); google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], ['Work', 11], ['Eat', 2], ['Commute', 2], ['Watch TV', 2], ['Sleep', 7] ]); var options = { title: 'My Daily Activities', is3D: true, }; var chart = new google.visualization.PieChart(document.getElementById('piechart_3d')); chart.draw(data, options); } var data = new google.visualization.DataTable(); var txtWork = document.getElementById('<%=txtWork.ClientID%>') txtEat = document.getElementById('<%=txtEat.ClientID%>') txtCommute = document.getElementById('<%=txtCommute.ClientID%>') txtWatchTV = document.getElementById('<%=txtWatchTV.ClientID%>') txtSleep = document.getElementById('<%=txtSleep.ClientID%>'); var workvalue = parseInt(txtWork, 10) var eatvalue = parseInt(txtEat, 10) var commutevalue = parseInt(txtCommute, 10) var watchtvvalue = parseInt(txtWatchTV, 10) var sleepvalue = parseInt(txtSleep, 10) // Declare columns data.addColumn('string', 'Task'); data.addColumn('Number', 'Hours per day'); // Add data. data.addRows([ ['Work', workvalue], ['Eat', eatvalue], ['Commute', commutevalue], ['Watch TV', watchtvvalue], ['Sleep', sleepvalue], ]); </script> </head> <body> <form id="form1" runat="server"> <div id="piechart_3d" style="width: 900px; height: 500px;"> </div> <asp:Label ID="lblError" runat="server" Font-Size="X-Large" Font-Bold="true" /> <table> <tr> <td>Work:</td> <td><asp:TextBox ID="txtWork" Text="11" runat="server" /></td> </tr> <tr> <td>Eat:</td> <td><asp:TextBox ID="txtEat" text="2" runat="server" /></td> </tr> <tr> <td>Commute:</td> <td><asp:TextBox ID="txtCommute" Text="2" runat="server" /></td> </tr> <tr> <td>Watch TV:</td> <td><asp:TextBox ID="txtWatchTV" Text="2" runat="server" /></td> </tr> <tr> <td>Sleep:</td> <td><asp:TextBox ID="txtSleep" Text="7" runat="server" /></td> </tr> </table> <br /> <br /> <asp:Button ID="btn1" text="Draw 3D PieChart" runat="server" OnClick="btn1_Click" /> </form> </body> </html>

    Read the article

  • Best way to implement a data structure in PHP ?

    - by Double Gras
    Hi, I want to use some kind of data structure in PHP (5.2), mainly in order to not pollute the global namespace. I think about two approaches, using an array or a class. Could you tell me which approach is better ? Thanks $SQL_PARAMETERS = array ( 'server' => '127.0.0.1', 'login' => 'root'); class SqlParameters { const SERVER = '127.0.0.1'; const LOGIN = 'root'; } echo $SQL_PARAMETERS['server']; echo SqlParameters::SERVER;

    Read the article

  • SQLiteDataAdapter Fill exception

    - by Lirik
    I'm trying to use the OleDb CSV parser to load some data from a CSV file and insert it into a SQLite database, but I get an exception with the OleDbAdapter.Fill method and it's frustrating: An unhandled exception of type 'System.Data.ConstraintException' occurred in System.Data.dll Additional information: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. Here is the source code: public void InsertData(String csvFileName, String tableName) { String dir = Path.GetDirectoryName(csvFileName); String name = Path.GetFileName(csvFileName); using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + @";Extended Properties=""Text;HDR=No;FMT=Delimited""")) { conn.Open(); using (OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + name, conn)) { QuoteDataSet ds = new QuoteDataSet(); adapter.Fill(ds, tableName); // <-- Exception here InsertData(ds, tableName); // <-- Inserts the data into the my SQLite db } } } class Program { static void Main(string[] args) { SQLiteDatabase target = new SQLiteDatabase(); string csvFileName = "D:\\Innovations\\Finch\\dev\\DataFeed\\YahooTagsInfo.csv"; string tableName = "Tags"; target.InsertData(csvFileName, tableName); Console.ReadKey(); } } The "YahooTagsInfo.csv" file looks like this: tagId,tagName,description,colName,dataType,realTime 1,s,Symbol,symbol,VARCHAR,FALSE 2,c8,After Hours Change,afterhours,DOUBLE,TRUE 3,g3,Annualized Gain,annualizedGain,DOUBLE,FALSE 4,a,Ask,ask,DOUBLE,FALSE 5,a5,Ask Size,askSize,DOUBLE,FALSE 6,a2,Average Daily Volume,avgDailyVolume,DOUBLE,FALSE 7,b,Bid,bid,DOUBLE,FALSE 8,b6,Bid Size,bidSize,DOUBLE,FALSE 9,b4,Book Value,bookValue,DOUBLE,FALSE I've tried the following: Removing the first line in the CSV file so it doesn't confuse it for real data. Changing the TRUE/FALSE realTime flag to 1/0. I've tried 1 and 2 together (i.e. removed the first line and changed the flag). None of these things helped... One constraint is that the tagId is supposed to be unique. Here is what the table look like in design view: Can anybody help me figure out what is the problem here? Update: I changed the HDR property from HDR=No to HDR=Yes and now it doesn't give me an exception: OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + @";Extended Properties=""Text;HDR=Yes;FMT=Delimited"""); I assumed that if HDR=No and I removed the header (i.e. first line), then it should work... strangely it didn't work. In any case, now I'm no longer getting the exception. The new problem is here: public void InsertData(QuoteDataSet data, String tableName) { using (SQLiteConnection conn = new SQLiteConnection(_connectionString)) { conn.Open(); using (SQLiteDataAdapter sqliteAdapter = new SQLiteDataAdapter("SELECT * FROM " + tableName, conn)) { Console.WriteLine("Num rows updated is " + sqliteAdapter.Update(data, tableName)); } } } Now the Num rows updated is 0... any hints?

    Read the article

  • XSL Template outputting massive chunk of text, rather than HTML. But only on one section

    - by Throlkim
    I'm having a slightly odd situation with an XSL template. Most of it outputs fine, but a certain for-each loop is causing me problems. Here's the XML: <area> <feature type="Hall"> <Heading><![CDATA[Hall]]></Heading> <Para><![CDATA[Communal gardens, pathway leading to PVCu double glazed communal front door to]]></Para> </feature> <feature type="Entrance Hall"> <Heading><![CDATA[Communal Entrance Hall]]></Heading> <Para><![CDATA[Plain ceiling, centre light fitting, fire door through to inner hallway, wood and glazed panelled front door to]]></Para> </feature> <feature type="Inner Hall"> <Heading><![CDATA[Inner Hall]]></Heading> <Para><![CDATA[Plain ceiling with pendant light fitting and covings, security telephone, airing cupboard housing gas boiler serving domestic hot water and central heating, telephone point, storage cupboard housing gas and electric meters, wooden panelled doors off to all rooms.]]></Para> </feature> <feature type="Lounge (Reception)" width="3.05" length="4.57" units="metre"> <Heading><![CDATA[Lounge (Reception)]]></Heading> <Para><![CDATA[15' 6" x 10' 7" (4.72m x 3.23m) Window to the side and rear elevation, papered ceiling with pendant light fitting and covings, two double panelled radiators, power points, wall mounted security entry phone, TV aerial point.]]></Para> </feature> <feature type="Kitchen" width="3.05" length="3.66" units="metre"> <Heading><![CDATA[Kitchen]]></Heading> <Para><![CDATA[12' x 10' (3.66m x 3.05m) Double glazed window to the rear elevation, textured ceiling with strip lighting, range of base and wall units in Beech with brushed aluminium handles, co-ordinated working surfaces with inset stainless steel sink with mixer taps over, co-ordinated tiled splashbacks, gas and electric cooker points, large storage cupboard with shelving, power points.]]></Para> </feature> <feature type="Entrance Porch"> <Heading><![CDATA[Balcony]]></Heading> <Para><![CDATA[Views across the communal South facing garden, wrought iron balustrade.]]></Para> </feature> <feature type="Bedroom" width="3.35" length="3.96" units="metre"> <Heading><![CDATA[Bedroom One]]></Heading> <Para><![CDATA[13' 6" x 11' 5" (4.11m x 3.48m) Double glazed windows to the front and side elevations, papered ceiling with pendant light fittings and covings, single panelled radiator, power points, telephone point, security entry phone.]]></Para> </feature> <feature type="Bedroom" width="3.05" length="3.35" units="metre"> <Heading><![CDATA[Bedroom Two]]></Heading> <Para><![CDATA[11' 4" x 10' 1" (3.45m x 3.07m) Double glazed window to the front elevation, plain ceiling with centre light fitting and covings, power points.]]></Para> </feature> <feature type="bathroom"> <Heading><![CDATA[Bathroom]]></Heading> <Para><![CDATA[Obscure double glazed window to the rear elevation, textured ceiling with centre light fitting and extractor fan, suite in white comprising of low level WC, wall mounted wash hand basin and walk in shower housing 'Triton T80' electric shower, co-ordinated tiled splashbacks.]]></Para> </feature> </area> And here's the section of my template that processes it: <xsl:for-each select="area"> <li> <xsl:for-each select="feature"> <li> <h5> <xsl:value-of select="Heading"/> </h5> <xsl:value-of select="Para"/> </li> </xsl:for-each> </li> </xsl:for-each> And here's the output: Hall Communal gardens, pathway leading to PVCu double glazed communal front door to Communal Entrance Hall Plain ceiling, centre light fitting, fire door through to inner hallway, wood and glazed panelled front door to Inner Hall Plain ceiling with pendant light fitting and covings, security telephone, airing cupboard housing gas boiler serving domestic hot water and central heating, telephone point, storage cupboard housing gas and electric meters, wooden panelled doors off to all rooms. Lounge (Reception) 15' 6" x 10' 7" (4.72m x 3.23m) Window to the side and rear elevation, papered ceiling with pendant light fitting and covings, two double panelled radiators, power points, wall mounted security entry phone, TV aerial point. Kitchen 12' x 10' (3.66m x 3.05m) Double glazed window to the rear elevation, textured ceiling with strip lighting, range of base and wall units in Beech with brushed aluminium handles, co-ordinated working surfaces with inset stainless steel sink with mixer taps over, co-ordinated tiled splashbacks, gas and electric cooker points, large storage cupboard with shelving, power points. Balcony Views across the communal South facing garden, wrought iron balustrade. Bedroom One 13' 6" x 11' 5" (4.11m x 3.48m) Double glazed windows to the front and side elevations, papered ceiling with pendant light fittings and covings, single panelled radiator, power points, telephone point, security entry phone. Bedroom Two 11' 4" x 10' 1" (3.45m x 3.07m) Double glazed window to the front elevation, plain ceiling with centre light fitting and covings, power points. Bathroom Obscure double glazed window to the rear elevation, textured ceiling with centre light fitting and extractor fan, suite in white comprising of low level WC, wall mounted wash hand basin and walk in shower housing 'Triton T80' electric shower, co-ordinated tiled splashbacks. For reference, here's the entire XSLT: http://pastie.org/private/eq4gjvqoc1amg9ynyf6wzg The rest of it all outputs fine - what am I missing from the above section?

    Read the article

  • Trying to change variables in a singleton using a method

    - by Johnny Cox
    I am trying to use a singleton to store variables that will be used across multiple view controllers. I need to be able to get the variables and also set them. How do I call a method in a singleton to change the variables stored in the singleton. total+=1079; [var setTotal:total]; where var is a static Singleton *var = nil; I need to update the total and send to the setTotal method inside the singleton. But when I do this the setTotal method never gets accessed. The get methods work but the setTotal method does not. Please let me know what should. Below is some of my source code // // Singleton.m // Rolo // // Created by on 6/28/12. // Copyright (c) 2012 Johnny Cox. All rights reserved. // #import "Singleton.h" @implementation Singleton @synthesize total,tax,final; #pragma mark Singleton Methods + (Singleton *)sharedManager { static Singleton *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[Singleton alloc] init]; // Do any other initialisation stuff here }); return sharedInstance; } +(void) setTotal:(double) tot { Singleton *shared = [Singleton sharedManager]; shared.total = tot; NSLog(@"hello"); } +(double) getTotal { Singleton *shared = [Singleton sharedManager]; NSLog(@"%f",shared.total); return shared.total; } +(double) getTax { Singleton *shared = [Singleton sharedManager]; NSLog(@"%f",shared.tax); return shared.tax; } @end // // Singleton.h // Rolo // // Created by on 6/28/12. // Copyright (c) 2012 Johnny Cox. All rights reserved. // #import <Foundation/Foundation.h> @interface Singleton : NSObject @property (nonatomic, assign) double total; @property (nonatomic, assign) double tax; @property (nonatomic, assign) double final; + (id)sharedManager; +(double) getTotal; +(void) setTotal; +(double) getTax; @end

    Read the article

  • Averaging initial values for rolling series

    - by Dave Jarvis
    Question Given a maximum sliding window size of 40 (i.e., the set of numbers in the list cannot exceed 40), what is the calculation to ensure a smooth averaging transition as the set size grows from 1 to 40? Problem Description Creating a trend line for a set of data has skewed initial values. The complete set of values is unknown at runtime: they are provided one at a time. It seems like a reverse-weighted average is required so that the initial values are averaged differently. In the image below the leftmost data for the trend line are incorrectly averaged. Current Solution Created a new type of ArrayList subclass that calculates the appropriate values and ensures its size never goes beyond the bounds of the sliding window: /** * A list of Double values that has a maximum capacity enforced by a sliding * window. Can calculate the average of its values. */ public class AveragingList extends ArrayList<Double> { private float slidingWindowSize = 0.0f; /** * The initial capacity is used for the sliding window size. * @param slidingWindowSize */ public AveragingList( int slidingWindowSize ) { super( slidingWindowSize ); setSlidingWindowSize( ( float )slidingWindowSize ); } public boolean add( Double d ) { boolean result = super.add( d ); // Prevent the list from exceeding the maximum sliding window size. // if( size() > getSlidingWindowSize() ) { remove( 0 ); } return result; } /** * Calculate the average. * * @return The average of the values stored in this list. */ public double average() { double result = 0.0; int size = size(); for( Double d: this ) { result += d.doubleValue(); } return (double)result / (double)size; } /** * Changes the maximum number of numbers stored in this list. * * @param slidingWindowSize New maximum number of values to remember. */ public void setSlidingWindowSize( float slidingWindowSize ) { this.slidingWindowSize = slidingWindowSize; } /** * Returns the number used to determine the maximum values this list can * store before it removes the first entry upon adding another value. * @return The maximum number of numbers stored in this list. */ public float getSlidingWindowSize() { return slidingWindowSize; } } Resulting Image Example Input The data comes into the function one value at a time. For example, data points (Data) and calculated averages (Avg) typically look as follows: Data: 17.0 Avg : 17.0 Data: 17.0 Avg : 17.0 Data: 5.0 Avg : 13.0 Data: 5.0 Avg : 11.0  Related Sites The following pages describe moving averages, but typically when all (or sufficient) data is known: http://www.cs.princeton.edu/introcs/15inout/MovingAverage.java.html http://stackoverflow.com/questions/2161815/r-zoo-series-sliding-window-calculation http://taragana.blogspot.com/ http://www.dreamincode.net/forums/index.php?showtopic=92508 http://blogs.sun.com/nickstephen/entry/dtrace_and_moving_rolling_averages

    Read the article

  • Scala Array constructor?

    - by Lukasz Lew
    scala> val a = Array [Double] (10) a: Array[Double] = Array(10.0) scala> val a = new Array [Double] (10) a: Array[Double] = Array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) Why these two expressions have different semantics?

    Read the article

  • Java: CSV file read & write.

    - by battousai622
    Im reading in 2 csv file: store_inventory & new_acquisitions... I want to be able to compare the store_inventory csv file with new_acquisitions. 1) If the item names match just update the quantity in store_inventory. 2) If new_acquisitions has a new item that does not exist in store_inventory, then add it to the store_inventory. Heres what i have so far but its not very good. I added comments where i need to add taks 1) & 2). Any advice or code would be great, thanks. File new_acq = new File("/src/test/new_acquisitions.csv"); Scanner acq_scan = null; try { acq_scan = new Scanner(new_acq); } catch (FileNotFoundException ex) { Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex); } String itemName; int quantity; Double cost; Double price; File store_inv = new File("/src/test/store_inventory.csv"); Scanner invscan = null; try { invscan = new Scanner(store_inv); } catch (FileNotFoundException ex) { Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex); } String itemNameInv; int quantityInv; Double costInv; Double priceInv; while (acq_scan.hasNext()) { String line = acq_scan.nextLine(); if (line.charAt(0) == '#') { continue; } String[] split = line.split(","); itemName = split[0]; quantity = Integer.parseInt(split[1]); cost = Double.parseDouble(split[2]); price = Double.parseDouble(split[3]); while(invscan.hasNext()) { String line2 = invscan.nextLine(); if (line2.charAt(0) == '#') { continue; } String[] split2 = line2.split(","); itemNameInv = split2[0]; quantityInv = Integer.parseInt(split2[1]); costInv = Double.parseDouble(split2[2]); priceInv = Double.parseDouble(split2[3]); if(itemName == itemNameInv) { //update quantity } } //add new entry into csv file } Thanks again for any help. =]

    Read the article

  • Add elements to Arraylist and it replaces all previous elements in Java

    - by pie154
    I am adding elements to a ArrayList and it adds the first one correctly but then when I add any subsequent elements it wipes replaces the other elements with the value form the most recently added and adds a new element to the ArrayList. I ran test using arraylist and ints and even another created class and it worked perfectly but soemthing about the custon class i am using here causes problems. The code for the array list is public static void main(String args[]){ List<BasicEvent> list = new ArrayList<BasicEvent>(); list.add(new BasicEvent("Basic", "Door", 9, 4444, new Date(12,04,2010), new Time(12,04,21), 1, 0.98, 0)); list.add(new BasicEvent("Composite", "Door", 125, 4444, new Date(12,04,2010), new Time(12,04,20), 1, 0.98, 1)); list.add(new BasicEvent("Basic", "Door", 105, 88, new Date(12,04,2010), new Time(12,05,23), 1, 0.98, 0)); list.add(new BasicEvent("Basic", "Door", 125, 12, new Date(12,04,2010), new Time(12,05,28), 1, 0.98, 1)); list.add(new BasicEvent("Basic", "Door", 129, 25, new Date(12,04,2010), new Time(12,05,30), 1, 0.98, 0)); list.add(new BasicEvent("Basic", "Door", 125, 63, new Date(12,04,2010), new Time(12,04,20), 1, 0.98, 1)); list.add(new BasicEvent("Basic", "Detect", 127, 9, new Date(12,04,2010), new Time(12,05,29), 1, 0.98, -1)); for(int i=0;i<list.size();i++) {System.out.println("list a poition " + i + " is " + BasicEvent.basicToString(list.get(i)));} And the code for the custom class basicEvent is public class BasicEvent { public static String Level; public static String EType; public static double xPos; public static double yPos; public static Date date; public static Time time; public static double Rlb; public static double Sig; public static int Reserved; public BasicEvent(String L, String E, double X, double Y, Date D, Time T, double R, double S, int Res){ Level = L; EType = E; xPos = X; yPos = Y; date = D; time = T; Rlb = R; Sig = S; Reserved = Res; }; public static String basicToString(BasicEvent bse){ String out = bse.getLevel() + ";" + bse.getEtype() + ";" + bse.getxPos() + ";" + bse.getyPos() + ";" + bse.getDate().dateAsString() + ";" + bse.getTime().timeAsString() + ";" + bse.getRlb() + ";" + bse.getSig() + ";" + bse.getReserved(); return out; }

    Read the article

  • My dialog box below does not work, Please correct

    - by Mukul Shukla
    pbutton.setOnClickListener(new OnClickListener() { private AlertDialog show; public void onClick(View arg0) { if ((input1.getText().length() == 0) || (input1.getText().toString().equals(" ")) || (input2.getText().length() == 0) || (input2.getText().toString().equals(" "))|| (input1.getText().toString().equals(""))||(input2.getText().toString().equals(""))) { show = new AlertDialog.Builder(MainActivity.this).setTitle("Error").setMessage("Some inputs are empty").setPositiveButton("OK", null).show(); } double result = new Double(input1.getText().toString())+ new Double(input2.getText().toString()); output.setText(Double.toString(result)); } I've also tried passing the context which also doesn't work

    Read the article

  • Is it ok to dynamic cast "this" as a return value?

    - by Panayiotis Karabassis
    This is more of a design question. I have a template class, and I want to add extra methods to it depending on the template type. To practice the DRY principle, I have come up with this pattern (definitions intentionally omitted): template <class T> class BaseVector: public boost::array<T, 3> { protected: BaseVector<T>(const T x, const T y, const T z); public: bool operator == (const Vector<T> &other) const; Vector<T> operator + (const Vector<T> &other) const; Vector<T> operator - (const Vector<T> &other) const; Vector<T> &operator += (const Vector<T> &other) { (*this)[0] += other[0]; (*this)[1] += other[1]; (*this)[2] += other[2]; return *dynamic_cast<Vector<T> * const>(this); } } template <class T> class Vector : public BaseVector<T> { public: Vector<T>(const T x, const T y, const T z) : BaseVector<T>(x, y, z) { } }; template <> class Vector<double> : public BaseVector<double> { public: Vector<double>(const double x, const double y, const double z); Vector<double>(const Vector<int> &other); double norm() const; }; I intend BaseVector to be nothing more than an implementation detail. This works, but I am concerned about operator+=. My question is: is the dynamic cast of the this pointer a code smell? Is there a better way to achieve what I am trying to do (avoid code duplication, and unnecessary casts in the user code)? Or am I safe since, the BaseVector constructor is private?

    Read the article

  • Pointers to class fields

    - by newbie_cpp
    My task is as follows : Using pointers to class fields, create menu allowing selection of ice, that Person can buy in Ice shop. Buyer will be charged with waffel and ice costs. Selection of ice and charging buyers account must be shown in program. Here's my Person class : #include <iostream> using namespace std; class Iceshop { const double waffel_price = 1; public: } class Person { static int NUMBER; char* name; int age; const int number; double plus, minus; public: class Account { int number; double resources; public: Account(int number, double resources) : number(number), resources(resources) {} } Person(const char* n, int age) : name(strcpy(new char[strlen(n)+1],n)), number(++NUMBER), plus(0), minus(0), age(age) {} Person::~Person(){ cout << "Destroying resources" << endl; delete [] name; } friend void show(Person &p); int* take_age(){ return &age; } char* take_name(){ return name; } void init(char* n, int a) { name = n; age = a; } Person& remittance(double d) { plus += d; return *this; } Person& paycheck(double d) { minus += d; return *this; } Account* getAccount(); }; int Person:: Person::Account* Person::getAccount() { return new Account(number, plus - minus); } void Person::Account::remittance(double d){ resources = resources + d; } void Person::Account::paycheck(double d){ resources = resources - d; } void show(Person *p){ cout << "Name: " << p->take_name() << "," << "age: " << p->take_age() << endl; } int main(void) { Person *p = new Person; p->init("Mary", 25); show(p); p->remittance(100); system("PAUSE"); return 0; } How to start this task ? Where and in what form should I store menu options ?

    Read the article

  • Having trouble returning a value from a method call when sending an array and the program is error out when run in reference to the sort

    - by programmerNOOB
    I am getting the following output when this program is run: Please enter the Social Security Number for taxpayer 0: 111111111 Please enter the gross income for taxpayer 0: 20000 Please enter the Social Security Number for taxpayer 1: 555555555 Please enter the gross income for taxpayer 1: 50000 Please enter the Social Security Number for taxpayer 2: 333333333 Please enter the gross income for taxpayer 2: 5464166 Please enter the Social Security Number for taxpayer 3: 222222222 Please enter the gross income for taxpayer 3: 645641 Please enter the Social Security Number for taxpayer 4: 444444444 Please enter the gross income for taxpayer 4: 29000 Taxpayer # 1 SSN: 111111111, Income is $20,000.00, Tax is $0.00 Taxpayer # 2 SSN: 555555555, Income is $50,000.00, Tax is $0.00 Taxpayer # 3 SSN: 333333333, Income is $5,464,166.00, Tax is $0.00 Taxpayer # 4 SSN: 222222222, Income is $645,641.00, Tax is $0.00 Taxpayer # 5 SSN: 444444444, Income is $29,000.00, Tax is $0.00 Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --- System.ArgumentException: At least one object must implement IComparable. at System.Collections.Comparer.Compare(Object a, Object b) at System.Collections.Generic.ObjectComparer`1.Compare(T x, T y) at System.Collections.Generic.ArraySortHelper`1.SwapIfGreaterWithItems(T[] keys, IComparer`1 comparer, Int32 a, Int32 b) at System.Collections.Generic.ArraySortHelper`1.QuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer) at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) --- End of inner exception stack trace --- at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer) at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer) at System.Array.Sort[T](T[] array) at Assignment5.Taxpayer.Main(String[] args) in Program.cs:line 150 Notice the 0s at the end of the line that should be the tax amount??? Here is the code: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace taxes { class Rates { // Create a class named rates that has the following data members: private int incLimit; private double lowTaxRate; private double highTaxRate; // use read-only accessor public int IncomeLimit { get { return incLimit; } } public double LowTaxRate { get { return lowTaxRate; } } public double HighTaxRate { get { return highTaxRate; } } //A class constructor that assigns default values public Rates() { int limit = 30000; double lowRate = .15; double highRate = .28; incLimit = limit; lowTaxRate = lowRate; highTaxRate = highRate; } //A class constructor that takes three parameters to assign input values for limit, low rate and high rate. public Rates(int limit, double lowRate, double highRate) { } // A CalculateTax method that takes an income parameter and computes the tax as follows: public int CalculateTax(int income) { int limit = 0; double lowRate = 0; double highRate = 0; int taxOwed = 0; // If income is less than the limit then return the tax as income times low rate. if (income < limit) taxOwed = Convert.ToInt32(income * lowRate); // If income is greater than or equal to the limit then return the tax as income times high rate. if (income >= limit) taxOwed = Convert.ToInt32(income * highRate); return taxOwed; } } //end class Rates // Create a class named Taxpayer that has the following data members: public class Taxpayer { //Use get and set accessors. string SSN { get; set; } int grossIncome { get; set; } // Use read-only accessor. public int taxOwed { get { return taxOwed; } } // The Taxpayer class should be set up so that its objects are comparable to each other based on tax owed. class taxpayer : IComparable { public int taxOwed { get; set; } public int income { get; set; } int IComparable.CompareTo(Object o) { int returnVal; taxpayer temp = (taxpayer)o; if (this.taxOwed > temp.taxOwed) returnVal = 1; else if (this.taxOwed < temp.taxOwed) returnVal = -1; else returnVal = 0; return returnVal; } // End IComparable.CompareTo } //end taxpayer IComparable class // **The tax should be calculated whenever the income is set. // The Taxpayer class should have a getRates class method that has the following. public static void GetRates() { // Local method data members for income limit, low rate and high rate. int incLimit = 0; double lowRate; double highRate; string userInput; // Prompt the user to enter a selection for either default settings or user input of settings. Console.Write("Would you like the default values (D) or would you like to enter the values (E)?: "); /* If the user selects default the default values you will instantiate a rates object using the default constructor * and set the Taxpayer class data member for tax equal to the value returned from calling the rates object CalculateTax method.*/ userInput = Convert.ToString(Console.ReadLine()); if (userInput == "D" || userInput == "d") { Rates rates = new Rates(); rates.CalculateTax(incLimit); } // end if /* If the user selects to enter the rates data then prompt the user to enter values for income limit, low rate and high rate, * instantiate a rates object using the three-argument constructor passing those three entries as the constructor arguments and * set the Taxpayer class data member for tax equal to the valuereturned from calling the rates object CalculateTax method. */ if (userInput == "E" || userInput == "e") { Console.Write("Please enter the income limit: "); incLimit = Convert.ToInt32(Console.ReadLine()); Console.Write("Please enter the low rate: "); lowRate = Convert.ToDouble(Console.ReadLine()); Console.Write("Please enter the high rate: "); highRate = Convert.ToDouble(Console.ReadLine()); Rates rates = new Rates(incLimit, lowRate, highRate); rates.CalculateTax(incLimit); } } static void Main(string[] args) { Taxpayer[] taxArray = new Taxpayer[5]; Rates taxRates = new Rates(); // Implement a for-loop that will prompt the user to enter the Social Security Number and gross income. for (int x = 0; x < taxArray.Length; ++x) { taxArray[x] = new Taxpayer(); Console.Write("Please enter the Social Security Number for taxpayer {0}: ", x + 1); taxArray[x].SSN = Console.ReadLine(); Console.Write("Please enter the gross income for taxpayer {0}: ", x + 1); taxArray[x].grossIncome = Convert.ToInt32(Console.ReadLine()); } Taxpayer.GetRates(); // Implement a for-loop that will display each object as formatted taxpayer SSN, income and calculated tax. for (int i = 0; i < taxArray.Length; ++i) { Console.WriteLine("Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}", i + 1, taxArray[i].SSN, taxArray[i].grossIncome, taxRates.CalculateTax(taxArray[i].grossIncome)); } // end for // Implement a for-loop that will sort the five objects in order by the amount of tax owed Array.Sort(taxArray); Console.WriteLine("Sorted by tax owed"); for (int i = 0; i < taxArray.Length; ++i) { Console.WriteLine("Taxpayer # {0} SSN: {1}, Income is {2:c}, Tax is {3:c}", i + 1, taxArray[i].SSN, taxArray[i].grossIncome, taxRates.CalculateTax(taxArray[i].grossIncome)); } } //end main } // end Taxpayer class } //end Any clues as to why the dollar amount is coming up as 0 and why the sort is not working?

    Read the article

  • error with passing my object with serializable?

    - by Jony Scherman
    i was trying to send my object class GastronomyElement to another activity but i have got this error java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.example.despegarteproject.classes.GastronomyElement) i have seen another posts like this but i couldn not solve it. this is my class code public class GastronomyElement implements Serializable { String id, name, formattedAddress, formattedPhoneNumber, reference, photo; List<String> photos; Boolean openNow; Horarios horarios; List<Review> reviews; String priceLevel; double latitude, longitude; Double rating; public String getName () { return name; } public void setName (String name) { this.name = name; } public String getId () { return id; } public void setId (String id) { this.id = id; } public String getFormattedAddress () { return formattedAddress; } public void setFormattedAddress (String formattedAddress) { this.formattedAddress = formattedAddress; } public String getReference () { return reference; } public void setReference (String reference) { this.reference = reference; } public String getPhoto () { return photo; } public void setPhoto (String photo) { this.photo = photo; } public List<String> getPhotos () { return photos; } public void setPhotos (List<String> photos) { this.photos = photos; } public double getLatitude() { return latitude; } public void setLatitude (double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude (double longitude) { this.longitude = longitude; } public Double getRating () { return rating; } public void setRating (Double rating) { this.rating = rating; } public Boolean getOpenNow () { return openNow; } public void setOpenNow (Boolean openNow) { this.openNow = openNow; } public Horarios getHorarios () { return horarios; } public void setHorarios (Horarios horarios) { this.horarios = horarios; } public String getPriceLevel () { return priceLevel; } public void setPriceLevel (String priceLevel) { this.priceLevel = priceLevel; } public String getFormattedPhoneNumber () { return formattedPhoneNumber; } public void setFormattedPhoneNumber (String formattedPhoneNumber) { this.formattedPhoneNumber = formattedPhoneNumber; } public List<Review> getReviews () { return reviews; } public void setReviews (List<Review> reviews) { this.reviews = reviews; } } and this is how i am sending it Intent act = new Intent (context, ActivityLugarDetalles.class); act.putExtra("elementDetails", elementDetails); startActivity(act); i would appreciate your help! thank you!

    Read the article

< Previous Page | 41 42 43 44 45 46 47 48 49 50 51 52  | Next Page >