Search Results

Search found 1626 results on 66 pages for 'age'.

Page 5/66 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • operator+ overload returning object causing memory leaks, C++

    - by lampshade
    The problem i think is with returing an object when i overload the + operator. I tried returning a reference to the object, but doing so does not fix the memory leak. I can comment out the two statements: dObj = dObj + dObj2; and cObj = cObj + cObj2; to free the program of memory leaks. Somehow, the problem is with returning an object after overloading the + operator. #include <iostream> #include <vld.h> using namespace std; class Animal { public : Animal() {}; virtual void eat() = 0 {}; virtual void walk() = 0 {}; }; class Dog : public Animal { public : Dog(const char * name, const char * gender, int age); Dog() : name(NULL), gender(NULL), age(0) {}; virtual ~Dog(); Dog operator+(const Dog &dObj); private : char * name; char * gender; int age; }; class MyClass { public : MyClass() : action(NULL) {}; void setInstance(Animal &newInstance); void doSomething(); private : Animal * action; }; Dog::Dog(const char * name, const char * gender, int age) : // allocating here, for data passed in ctor name(new char[strlen(name)+1]), gender(new char[strlen(gender)+1]), age(age) { if (name) { size_t length = strlen(name) +1; strcpy_s(this->name, length, name); } else name = NULL; if (gender) { size_t length = strlen(gender) +1; strcpy_s(this->gender, length, gender); } else gender = NULL; if (age) { this->age = age; } } Dog::~Dog() { delete name; delete gender; age = 0; } Dog Dog::operator+(const Dog &dObj) { Dog d; d.age = age + dObj.age; return d; } void MyClass::setInstance(Animal &newInstance) { action = &newInstance; } void MyClass::doSomething() { action->walk(); action->eat(); } int main() { MyClass mObj; Dog dObj("Scruffy", "Male", 4); // passing data into ctor Dog dObj2("Scooby", "Male", 6); mObj.setInstance(dObj); // set the instance specific to the object. mObj.doSomething(); // something happens based on which object is passed in dObj = dObj + dObj2; // invoke the operator+ return 0; }

    Read the article

  • Validation and Error Generation when using the Data Mapper Pattern

    - by AndyPerlitch
    I am working on saving state of an object to a database using the data mapper pattern, but I am looking for suggestions/guidance on the validation and error message generation step (step 4 below). Here are the general steps as I see them for doing this: (1) The data mapper is used to get current info (assoc array) about the object in db: +=====================================================+ | person_id | name | favorite_color | age | +=====================================================+ | 1 | Andy | Green | 24 | +-----------------------------------------------------+ mapper returns associative array, eg. Person_Mapper::getPersonById($id) : $person_row = array( 'person_id' => 1, 'name' => 'Andy', 'favorite_color' => 'Green', 'age' => '24', ); (2) the Person object constructor takes this array as an argument, populating its fields. class Person { protected $person_id; protected $name; protected $favorite_color; protected $age; function __construct(array $person_row) { $this->person_id = $person_row['person_id']; $this->name = $person_row['name']; $this->favorite_color = $person_row['favorite_color']; $this->age = $person_row['age']; } // getters and setters... public function toArray() { return array( 'person_id' => $this->person_id, 'name' => $this->name, 'favorite_color' => $this->favorite_color, 'age' => $this->age, ); } } (3a) (GET request) Inputs of an HTML form that is used to change info about the person is populated using Person::getters <form> <input type="text" name="name" value="<?=$person->getName()?>" /> <input type="text" name="favorite_color" value="<?=$person->getFavColor()?>" /> <input type="text" name="age" value="<?=$person->getAge()?>" /> </form> (3b) (POST request) Person object is altered with the POST data using Person::setters $person->setName($_POST['name']); $person->setFavColor($_POST['favorite_color']); $person->setAge($_POST['age']); *(4) Validation and error message generation on a per-field basis - Should this take place in the person object or the person mapper object? - Should data be validated BEFORE being placed into fields of the person object? (5) Data mapper saves the person object (updates row in the database): $person_mapper->savePerson($person); // the savePerson method uses $person->toArray() // to get data in a more digestible format for the // db gateway used by person_mapper Any guidance, suggestions, criticism, or name-calling would be greatly appreciated.

    Read the article

  • Is it safe to assert a functions return type?

    - by wb
    This question is related to this question. I have several models stored in a collection. I loop through the collection and validate each field. Based on the input, a field can either be successful, have an error or a warning. Is it safe to unit test each decorator and assert that the type of object returned is what you would expect based on the given input? I could perhaps see this being an issue for a language with function return types since my validation function can return one of 3 types. This is the code I'm fiddling with: <!-- #include file = "../lib/Collection.asp" --> <style type="text/css"> td { padding: 4px; } td.error { background: #F00F00; } td.warning { background: #FC0; } </style> <% Class UserModel Private m_Name Private m_Age Private m_Height Public Property Let Name(value) m_Name = value End Property Public Property Get Name() Name = m_Name End Property Public Property Let Age(value) m_Age = value End Property Public Property Get Age() Age = m_Age End Property Public Property Let Height(value) m_Height = value End Property Public Property Get Height() Height = m_Height End Property End Class Class NameValidation Private m_Name Public Function Init(name) m_Name = name End Function Public Function Validate() Dim validationObject If Len(m_Name) < 5 Then Set validationObject = New ValidationError Else Set validationObject = New ValidationSuccess End If validationObject.CellValue = m_Name Set Validate = validationObject End Function End Class Class AgeValidation Private m_Age Public Function Init(age) m_Age = age End Function Public Function Validate() Dim validationObject If m_Age < 18 Then Set validationObject = New ValidationError ElseIf m_Age = 18 Then Set validationObject = New ValidationWarning Else Set validationObject = New ValidationSuccess End If validationObject.CellValue = m_Age Set Validate = validationObject End Function End Class Class HeightValidation Private m_Height Public Function Init(height) m_Height = height End Function Public Function Validate() Dim validationObject If m_Height > 400 Then Set validationObject = New ValidationError ElseIf m_Height = 324 Then Set validationObject = New ValidationWarning Else Set validationObject = New ValidationSuccess End If validationObject.CellValue = m_Height Set Validate = validationObject End Function End Class Class ValidationError Private m_CSSClass Private m_CellValue Public Property Get CSSClass() CSSClass = "error" End Property Public Property Let CellValue(value) m_CellValue = value End Property Public Property Get CellValue() CellValue = m_CellValue End Property End Class Class ValidationWarning Private m_CSSClass Private m_CellValue Public Property Get CSSClass() CSSClass = "warning" End Property Public Property Let CellValue(value) m_CellValue = value End Property Public Property Get CellValue() CellValue = m_CellValue End Property End Class Class ValidationSuccess Private m_CSSClass Private m_CellValue Public Property Get CSSClass() CSSClass = "" End Property Public Property Let CellValue(value) m_CellValue = value End Property Public Property Get CellValue() CellValue = m_CellValue End Property End Class Class ModelValidator Public Function ValidateModel(model) Dim modelValidation : Set modelValidation = New CollectionClass ' Validate name Dim name : Set name = New NameValidation name.Init model.Name modelValidation.Add name ' Validate age Dim age : Set age = New AgeValidation age.Init model.Age modelValidation.Add age ' Validate height Dim height : Set height = New HeightValidation height.Init model.Height modelValidation.Add height Dim validatedProperties : Set validatedProperties = New CollectionClass Dim modelVal For Each modelVal In modelValidation.Items() validatedProperties.Add modelVal.Validate() Next Set ValidateModel = validatedProperties End Function End Class Dim modelCollection : Set modelCollection = New CollectionClass Dim user1 : Set user1 = New UserModel user1.Name = "Mike" user1.Age = 12 user1.Height = 32 modelCollection.Add user1 Dim user2 : Set user2 = New UserModel user2.Name = "Phil" user2.Age = 18 user2.Height = 432 modelCollection.Add user2 Dim user3 : Set user3 = New UserModel user3.Name = "Michele" user3.Age = 32 user3.Height = 324 modelCollection.Add user3 ' Validate all models in the collection Dim modelValue Dim validatedModels : Set validatedModels = New CollectionClass For Each modelValue In modelCollection.Items() Dim objModelValidator : Set objModelValidator = New ModelValidator validatedModels.Add objModelValidator.ValidateModel(modelValue) Next %> <table> <tr> <td>Name</td> <td>Age</td> <td>Height</td> </tr> <% Dim r, c For Each r In validatedModels.Items() %><tr><% For Each c In r.Items() %><td class="<%= c.CSSClass %>"><%= c.CellValue %></td><% Next %></tr><% Next %> </table> Thank you.

    Read the article

  • Ask HTG: How Can I Check the Age of My Windows Installation?

    - by Jason Fitzpatrick
    Curious about when you installed Windows and how long you’ve been chugging along without a system refresh? Read on as we show you a simple way to see how long-in-the-tooth your Windows installation is. Dear How-To Geek, It feels like it has been forever since I installed Windows 7 and I’m starting to wonder if some of the performance issues I’m experiencing have something to do with how long ago it was installed. It isn’t crashing or anything horrible, mind you, it just feels slower than it used to and I’m wondering if I should reinstall it to wipe the slate clean. Is there a simple way to determine the original installation date of Windows on its host machine? Sincerely, Worried in Windows Although you only intended to ask one question, you actually asked two. Your direct question is an easy one to answer (how to check the Windows installation date). The indirect question is, however, a little trickier (if you need to reinstall Windows to get a performance boost). Let’s start off with the easy one: how to check your installation date. Windows includes a handy little application just for the purposes of pulling up system information like the installation date, among other things. Open the Start Menu and type cmd in the run box (or, alternatively, press WinKey+R to pull up the run dialog and enter the same command). At the command prompt, type systeminfo.exe Give the application a moment to run; it takes around 15-20 seconds to gather all the data. You’ll most likely need to scroll back up in the console window to find the section at the top that lists operating system stats. What you care about is Original Install Date: We’ve been running the machine we tested the command on since August 23 2009. For the curious, that’s one month and a day after the initial public release of Windows 7 (after we were done playing with early test releases and spent a month mucking around in the guts of Windows 7 to report on features and flaws, we ran a new clean installation and kept on trucking). Now, you might be asking yourself: Why haven’t they reinstalled Windows in all that time? Haven’t things slowed down? Haven’t they upgraded hardware? The truth of the matter is, in most cases there’s no need to completely wipe your computer and start from scratch to resolve issues with Windows and, if you don’t bog your system down with unnecessary and poorly written software, things keep humming along. In fact, we even migrated this machine from a traditional mechanical hard drive to a newer solid-state drive back in 2011. Even though we’ve tested piles of software since then, the machine is still rather clean because 99% of that testing happened in a virtual machine. That’s not just a trick for technology bloggers, either, virtualizing is a handy trick for anyone who wants to run a rock solid base OS and avoid the bog-down-and-then-refresh cycle that can plague a heavily used machine. So while it might be the case that you’ve been running Windows 7 for years and heavy software installation and use has bogged your system down to the point a refresh is in order, we’d strongly suggest reading over the following How-To Geek guides to see if you can’t wrangle the machine into shape without a total wipe (and, if you can’t, at least you’ll be in a better position to keep the refreshed machine light and zippy): HTG Explains: Do You Really Need to Regularly Reinstall Windows? PC Cleaning Apps are a Scam: Here’s Why (and How to Speed Up Your PC) The Best Tips for Speeding Up Your Windows PC Beginner Geek: How to Reinstall Windows on Your Computer Everything You Need to Know About Refreshing and Resetting Your Windows 8 PC Armed with a little knowledge, you too can keep a computer humming along until the next iteration of Windows comes along (and beyond) without the hassle of reinstalling Windows and all your apps.         

    Read the article

  • What is the relevance of resumes in the age of GitHub, Stack Exchange, Coursera, Udacity, blogs, etc.?

    - by davidk01
    My resume is no longer relevant. It can no longer contain an adequate description of my technical abilities. One can get a much better sense of what I am capable of by looking at my GitHub repositories, my Stack Exchange profiles, and the various courses that I am taking at Udacity and Coursera. The problem is that I have no idea how to tell employers that those are the places to look if they want an accurate description of what I can do. Every time a recruiter contacts me I gently nudge them towards all the resources I just mentioned and I also provide a link to a publicly visible Google doc that contains my resume along with links to all those resources. Yet, they keep coming back asking for a more descriptive resume. How can I make it even more blatantly obvious that if somebody wants to hire me then they can save themselves a whole bunch of trouble by just clicking on a few links and browsing around?

    Read the article

  • Is it too late to start your career as a programmer at the age of 30 ?

    - by Matt
    Assuming one graduated college at 30 years old and has 5 years of experience (no real job experience, just contributing to open source and doing personal projects) with various tools and programming languages, how would he or she be looked upon by hiring managers ? Will it be harder to find a job considering that (I got this information looking at various websites, user profiles on SO and here, etc.) the average person gets hired in this field at around 20 years old. I know that it's never too late to do what you're passionate about and the like but sometimes it is too late to start a career. Is this the case? Managers are always looking for fresh people and I often read job descriptions specifically asking for young people. I don't need answers of encouragement, I know the community here is great and I wouldn't get offended by even the most cold answers. Please don't close this as being too localized, I'm not referring to any specific country or region, talk about the region you're in. I would also appreciate if you justified your answer.

    Read the article

  • How to write two-dimensional array to xml in Scala 2.8.0

    - by Shadowlands
    The following code (copied from a question from about a year ago) works fine under Scala 2.7.7, but does not behave correctly under Scala 2.8.0 (Beta 1, RC8). import scala.xml class Person(name : String, age : Int) { def toXml(): xml.Elem = <person><name>{ name }</name><age>{ age }</age></person> } def peopleToXml(people: Array[Person]): xml.Elem = { <people>{ for {person <- people} yield person.toXml }</people> } val data = Array(new Person("joe",40), new Person("mary", 35)) println(peopleToXml(data)) The output (according to 2.7.7) should be: <people><person><name>joe</name><age>40</age></person><person><name>mary</name><age>35</age></person></people> but instead comes out as: <people>\[Lscala.xml.Elem;@17821782</people> How do I get this to behave as it did in 2.7.x?

    Read the article

  • Updating an integer defined column in a MySQL DB with PHP

    - by Zloy Smiertniy
    I have a table defined like this: create table users ( id int(10), age int(3), name varchar (50) ) I want to use a query to update just age, which is an integer, that comes from an html form. When it arrives to the method that updates it, it comes as a string, so I change it to integer with PHP and try to update the table, but it doesn't work $age = intval($age); $q2 = "UPDATE users SET age='$age' where username like '$username';"; mysql_query($q2,$con);

    Read the article

  • Refactoring if/else logic

    - by David
    I have a java class with a thousand line method of if/else logic like this: if (userType == "admin") { if (age > 12) { if (location == "USA") { // do stuff } else if (location == "Mexico") { // do something slightly different than the US case } } else if (age < 12 && age > 4) { if (location == "USA") { // do something slightly different than the age > 12 US case } else if (location == "Mexico") { // do something slightly different } } } else if (userType == "student") { if (age > 12) { if (location == "USA") { // do stuff } else if (location == "Mexico") { // do something slightly different than the US case } } else if (age < 12 && age > 4) { if (location == "USA") { // do something slightly different than the age > 12 US case } else if (location == "Mexico") { // do something slightly different } } How should I refactor this into something more managable?

    Read the article

  • programming help

    - by user208639
    class Person holds personal data Its constructor receives 3 parameters, two Strings representing first and last names and an int representing age public Person(String firstName, String lastName, int age) { its method getName has no parameters and returns a String with format "Lastname, Firstname" its method getAge takes no parameters and returns an int representing the current age its method birthday increases age value by 1 and returns the new age value Create the class Person and paste the whole class into the textbox below public class Person { public Person(String first, String last, int age) { getName = "Lastname, Firstname"; System.out.print(last + first); getAge = age + 1; return getAge; System.out.print(getAge); birthday = age + 1; newAge = birthday; return newAge; } } im getting errors such as "cannot find symbol - variable getName" but when i declare a variable it still not working, i also wanted to ask if i am heading in the right direction or is it all totally wrong? im using a program called BlueJ to work on.

    Read the article

  • A Reusable Builder Class for Ruby Testing

    - by Liam McLennan
    My last post was about a class for building test data objects in C#. This post describes the same tool, but implemented in Ruby. The C# version was written first but I originally came up with the solution in my head using Ruby, and then I translated it to C#. The Ruby version was easier to write and is easier to use thanks to Ruby’s dynamic nature making generics unnecessary.  Here are my example domain classes: class Person attr_accessor :name, :age def initialize(name, age) @name = name @age = age end end class Property attr_accessor :street, :manager def initialize(street, manager) @street = street @manager = manager end end and the test class showing what the builder does: class Test_Builder < Test::Unit::TestCase def setup @build = Builder.new @build.configure({ Property => lambda { Property.new '127 Creek St', @build.a(Person) }, Person => lambda { Person.new 'Liam', 26 } }) end def test_create assert_not_nil @build end def test_can_get_a_person @person = @build.a(Person) assert_not_nil @person assert_equal 'Liam', @person.name assert_equal 26, @person.age end def test_can_get_a_modified_person @person = @build.a Person do |person| person.age = 999 end assert_not_nil @person assert_equal 'Liam', @person.name assert_equal 999, @person.age end def test_can_get_a_different_type_that_depends_on_a_type_that_has_not_been_configured_yet @my_place = @build.a(Property) assert_not_nil @my_place assert_equal '127 Creek St', @my_place.street assert_equal @build.a(Person).name, @my_place.manager.name end end Finally, the implementation of Builder: class Builder # defaults is a hash of Class => creation lambda def configure defaults @defaults = defaults end def a(klass) temp = @defaults[klass].call() yield temp if block_given? temp end end

    Read the article

  • Using Query Classes With NHibernate

    - by Liam McLennan
    Even when using an ORM, such as NHibernate, the developer still has to decide how to perform queries. The simplest strategy is to get access to an ISession and directly perform a query whenever you need data. The problem is that doing so spreads query logic throughout the entire application – a clear violation of the Single Responsibility Principle. A more advanced strategy is to use Eric Evan’s Repository pattern, thus isolating all query logic within the repository classes. I prefer to use Query Classes. Every query needed by the application is represented by a query class, aka a specification. To perform a query I: Instantiate a new instance of the required query class, providing any data that it needs Pass the instantiated query class to an extension method on NHibernate’s ISession type. To query my database for all people over the age of sixteen looks like this: [Test] public void QueryBySpecification() { var canDriveSpecification = new PeopleOverAgeSpecification(16); var allPeopleOfDrivingAge = session.QueryBySpecification(canDriveSpecification); } To be able to query for people over a certain age I had to create a suitable query class: public class PeopleOverAgeSpecification : Specification<Person> { private readonly int age; public PeopleOverAgeSpecification(int age) { this.age = age; } public override IQueryable<Person> Reduce(IQueryable<Person> collection) { return collection.Where(person => person.Age > age); } public override IQueryable<Person> Sort(IQueryable<Person> collection) { return collection.OrderBy(person => person.Name); } } Finally, the extension method to add QueryBySpecification to ISession: public static class SessionExtensions { public static IEnumerable<T> QueryBySpecification<T>(this ISession session, Specification<T> specification) { return specification.Fetch( specification.Sort( specification.Reduce(session.Query<T>()) ) ); } } The inspiration for this style of data access came from Ayende’s post Do You Need a Framework?. I am sick of working through multiple layers of abstraction that don’t do anything. Have you ever seen code that required a service layer to call a method on a repository, that delegated to a common repository base class that wrapped and ORMs unit of work? I can achieve the same thing with NHibernate’s ISession and a single extension method. If you’re interested you can get the full Query Classes example source from Github.

    Read the article

  • Problem while inserting data from GUI layer to database

    - by Rahul
    Hi all, I am facing problem while i am inserting new record from GUI part to database table. I have created database table Patient with id, name, age etc....id is identity primary key. My problem is while i am inserting duplicate name in table the control should go to else part, and display the message like...This name is already exits, pls try with another name... but in my coding not getting..... Here is all the code...pls somebody point me out whats wrong or how do this??? GUILayer: protected void BtnSubmit_Click(object sender, EventArgs e) { if (!Page.IsValid) return; int intResult = 0; string name = TxtName.Text.Trim(); int age = Convert.ToInt32(TxtAge.Text); string gender; if (RadioButtonMale.Checked) { gender = RadioButtonMale.Text; } else { gender = RadioButtonFemale.Text; } string city = DropDownListCity.SelectedItem.Value; string typeofdisease = ""; foreach (ListItem li in CheckBoxListDisease.Items) { if (li.Selected) { typeofdisease += li.Value; } } typeofdisease = typeofdisease.TrimEnd(); PatientBAL PB = new PatientBAL(); PatientProperty obj = new PatientProperty(); obj.Name = name; obj.Age = age; obj.Gender = gender; obj.City = city; obj.TypeOFDisease = typeofdisease; try { intResult = PB.ADDPatient(obj); if (intResult > 0) { lblMessage.Text = "New record inserted successfully."; TxtName.Text = string.Empty; TxtAge.Text = string.Empty; RadioButtonMale.Enabled = false; RadioButtonFemale.Enabled = false; DropDownListCity.SelectedIndex = 0; CheckBoxListDisease.SelectedIndex = 0; } else { lblMessage.Text = "Name [<b>" + TxtName.Text + "</b>] alredy exists, try another name"; } } catch (Exception ex) { lblMessage.Text = ex.Message.ToString(); } finally { obj = null; PB = null; } } BAL layer: public class PatientBAL { public int ADDPatient(PatientProperty obj) { PatientDAL pdl = new PatientDAL(); try { return pdl.InsertData(obj); } catch { throw; } finally { pdl=null; } } } DAL layer: public class PatientDAL { public string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString; public int InsertData(PatientProperty obj) { SqlConnection con = new SqlConnection(ConString); con.Open(); SqlCommand com = new SqlCommand("LoadData",con); com.CommandType = CommandType.StoredProcedure; try { com.Parameters.AddWithValue("@Name", obj.Name); com.Parameters.AddWithValue("@Age",obj.Age); com.Parameters.AddWithValue("@Gender",obj.Gender); com.Parameters.AddWithValue("@City", obj.City); com.Parameters.AddWithValue("@TypeOfDisease", obj.TypeOFDisease); return com.ExecuteNonQuery(); } catch { throw; } finally { com.Dispose(); con.Close(); } } } Property Class: public class PatientProperty { private string name; private int age; private string gender; private string city; private string typedisease; public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { age = value; } } public string Gender { get { return gender; } set { gender = value; } } public string City { get { return city; } set { city = value; } } public string TypeOFDisease { get { return typedisease; } set { typedisease = value; } } } This is my stored Procedure: CREATE PROCEDURE LoadData ( @Name varchar(50), @Age int, @Gender char(10), @City char(10), @TypeofDisease varchar(50) ) as insert into Patient(Name, Age, Gender, City, TypeOfDisease)values(@Name,@Age, @Gender, @City, @TypeofDisease) GO

    Read the article

  • Constructors taking references in C++

    - by sasquatch
    I'm trying to create constructor taking reference to an object. After creating object using reference I need to prints field values of both objects. Then I must delete first object, and once again show values of fields of both objects. My class Person looks like this : class Person { char* name; int age; public: Person(){ int size=0; cout << "Give length of char*" << endl; cin >> size; name = new char[size]; age = 0; } ~Person(){ cout << "Destroying resources" << endl; delete[] name; delete age; } void init(char* n, int a) { name = n; age = a; } }; Here's my implementation (with the use of function show() ). My professor said that if this task is written correctly it will return an error. #include <iostream> using namespace std; class Person { char* name; int age; public: Person(){ int size=0; cout << "Give length of char*" << endl; cin >> size; name = new char[size]; age = 0; } Person(const Person& p){ name = p.name; age = p.age; } ~Person(){ cout << "Destroying resources" << endl; delete[] name; delete age; } void init(char* n, int a) { name = n; age = a; } void show(char* n, int a){ cout << "Name: " << name << "," << "age: " << age << "," << endl; } }; int main(void) { Person *p = new Person; p->init("Mary", 25); p->show(); Person &p = pRef; pRef->name = "Tom"; pRef->age = 18; Person *p2 = new Person(pRef); p->show(); p2->show(); system("PAUSE"); return 0; }

    Read the article

  • how I can overcome this error C2679: binary '>>' : no operator found which takes a right-hand oper

    - by hussein abdullah
    #include <iostream> using std::cout; using std::cin; using std::endl; #include <cstring> void initialize(char[],int*); void input(const char[] ,int&); void print ( const char*,const int); void growOlder (const char [], int* ); bool comparePeople(const char* ,const int*,const char*,const int*); int main(){ char name1[25]; char name2[25]; int age1; int age2; initialize (name1,&age1); initialize (name2,&age2); print(name1,age1); print(name2,age2); input(name1,age1); input(name2,age2); print(name1,age1); print(name2,age2); growOlder(name2,&age2); if(comparePeople(name1,&age1,name2,&age2)) cout<<"Both People have the same name and age "<<endl; return 0; } void input(const char name[],int &age) { cout<<"Enter a name :"; cin>>name ; cout<<"Enter an age:"; cin>>age; cout<<endl; } void initialize ( char name[],int *age) { name[0]='\0'; *age=0; } void print ( const char name[],const int age ) { cout<<"The Value stored in variable name is :" <<name<<endl <<"The Value stored in variable age is :" <<age<<endl<<endl; } void growOlder(const char name[],int *age) { cout<< name <<" has grown one year older\n\n"; *age++; } bool comparePeople (const char *name1,const int *age1, const char *name2,const int *age2) { return(*age1==*age2 && !strcmp(name1,name2)); }

    Read the article

  • How to build a GridView like DataBound Templated Custom ASP.NET Server Control

    - by Deyan
    I am trying to develop a very simple templated custom server control that resembles GridView. Basically, I want the control to be added in the .aspx page like this: <cc:SimpleGrid ID="SimpleGrid1" runat="server"> <TemplatedColumn>ID: <%# Eval("ID") %></ TemplatedColumn> <TemplatedColumn>Name: <%# Eval("Name") %></ TemplatedColumn> <TemplatedColumn>Age: <%# Eval("Age") %></ TemplatedColumn> </cc:SimpleGrid> and when providing the following datasource: DataTable table = new DataTable(); table.Columns.Add("ID", typeof(int)); table.Columns.Add("Name", typeof(string)); table.Columns.Add("Age", typeof(int)); table.Rows.Add(1, "Bob", 35); table.Rows.Add(2, "Sam", 44); table.Rows.Add(3, "Ann", 26); SimpleGrid1.DataSource = table; SimpleGrid1.DataBind(); the result should be a HTML table like this one. ------------------------------- | ID: 1 | Name: Bob | Age: 35 | ------------------------------- | ID: 2 | Name: Sam | Age: 44 | ------------------------------- | ID: 3 | Name: Ann | Age: 26 | ------------------------------- The main problem is that I cannot define the TemplatedColumn. When I tried to do it like this ... private ITemplate _TemplatedColumn; [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateContainer(typeof(TemplatedColumnItem))] [TemplateInstance(TemplateInstance.Multiple)] public ITemplate TemplatedColumn { get { return _TemplatedColumn; } set { _TemplatedColumn = value; } } .. and subsequently instantiate the template in the CreateChildControls I got the following result which is not what I want: ----------- | Age: 35 | ----------- | Age: 44 | ----------- | Age: 26 | ----------- I know that what I want to achieve is pointless and that I can use DataGrid to achieve it, but I am giving this very simple example because if I know how to do this I would be able to develop the control that I need. Thank you.

    Read the article

  • SQL queries to determine all values that would satisfy an arbitrary query

    - by jasterm007
    I'm trying to figure out how to efficiently run a set of queries that will provide a new table of all values that would return results for an arbitrary query. Say my table has a schema like: id name age city What is an efficient way to list all values that would return results for an arbitrary query, say "NOT city=X AND age BETWEEN Y and Z"? My naive approach for this would be to use a script and recurse through all possible combinations of {city, age, age} and see which SELECTs return more than 0 results, but that seems incredibly inefficient. I've also tried building large joins on {city, age, age} as well and basically using that table as an argument list to the query, but that quickly becomes an impossibility for queries on many columns. For simple conjunctive equality queries, i.e. "name=X and age=Y", this is much simpler, as I can do something like SELECT name, age, count(*) AS count FROM main GROUP BY name, age HAVING count > 0 But I'm having difficulty coming up with a general approach for anything more complicated than that. Any pointers in the right direction would be most helpful, thanks.

    Read the article

  • How t have the RDLC pie chart show ranges instead of individual values

    - by Emad
    I have some data coming from a custom dataset that look like the following example Person Age P1 20 P2 21 P3 30 P4 31 P5 40 And I want to develop a pie showing the age distribution against the age. The point is that I want this Age to be shown in ranges. (20-29, 30-39, etc for example So we have: Slice with total number =2 (P1 + P2) as age is 20-29 (one at 20 and another at 21) Slice with total number =3 (P3 + P4) as age is 30-39 (one at 30 and another at 31) Slice with total number =1 (P5) as age is 40 (one at 40). How can i customize the pie chart to aggregate values by ranges that I can define?

    Read the article

  • How to make a Django model fields calculated at runtime?

    - by Anatoly Rr
    I have a model: class Person (models.Model): name = models.CharField () birthday = models.DateField () age = models.IntegerField () I want to make age field to behave like a property: def get_age (self): return (datetime.datetime.now() - self.birthday).days // 365 age = property (get_age) but at the same time I need age to be a true field, so I can find it in Person._meta.fields, and assign attributes to it: age.help_text = "Age of the person", etc. Obviously I cannot just override Person.save() method to calculate and store age in the database, because it inevitably will become wrong later (in fact, it shouldn't be stored in the database at all). Actually, I don't need to have setters now, but a nice solution must have setting feature. Is it possible in Django, or probably there is a more pythonic and djangoic approach to my problem?

    Read the article

  • issue in list of dict

    - by gaggina
    class MyOwnClass: # list who contains the queries queries = [] # a template dict template_query = {} template_query['name'] = 'mat' template_query['age'] = '12' obj = MyOwnClass() query = obj.template_query query['name'] = 'sam' query['age'] = '23' obj.queries.append(query) query2 = obj.template_query query2['name'] = 'dj' query2['age'] = '19' obj.queries.append(query2) print obj.queries It gives me [{'age': '19', 'name': 'dj'}, {'age': '19', 'name': 'dj'}] while I expect to have [{'age': '23' , 'name': 'sam'}, {'age': '19', 'name': 'dj'}] I thought to use a template for this list because I'm gonna to use it very often and there are some default variable who does not need to be changed. Why does doing it the template_query itself changes? I'm new to python and I'm getting pretty confused.

    Read the article

  • How do I write a writer method for a class variable in Ruby?

    - by tepidsam
    I'm studying Ruby and my brain just froze. In the following code, how would I write the class writer method for 'self.total_people'? I'm trying to 'count' the number of instances of the class 'Person'. class Person attr_accessor :name, :age @@nationalities = ['French', 'American', 'Colombian', 'Japanese', 'Russian', 'Peruvian'] @@current_people = [] @@total_people = 0 def self.nationalities #reader @@nationalities end def self.nationalities=(array=[]) #writer @@nationalities = array end def self.current_people #reader @@current_people end def self.total_people #reader @@total_people end def self.total_people #writer #-----????? end def self.create_with_attributes(name, age) person = self.new(name) person.age = age person.name = name return person end def initialize(name="Bob", age=0) @name = name @age = age puts "A new person has been instantiated." @@total_people =+ 1 @@current_people << self end

    Read the article

  • creating objects in list

    - by prince23
    List myList = new List { new Users{ Name="Kumar", Gender="M", Age=75, Parent="All"}, new Users{ Name="Suresh",Gender="M", Age=50, Parent="Kumar"}, new Users{ Name="Bennette", Gender="F",Age=45, Parent="Kumar"}, new Users{ Name="kian", Gender="M",Age=20, Parent="Suresh"}, new Users{ Name="Nathani", Gender="M",Age=15, Parent="Suresh"}, new Users{ Name="Peter", Gender="M",Age=90, Parent="All"}, new Users{ Name="Mica", Age=56, Gender="M",Parent="Peter"}, new Users{ Name="Linderman", Gender="M",Age=51, Parent="Peter"}, new Users{ Name="john", Age=25, Gender="M",Parent="Mica"}, new Users{ Name="tom", Gender="M",Age=21, Parent="Mica"}, new Users{ Name="Ando", Age=64, Gender="M",Parent="All"}, new Users{ Name="Maya", Age=24, Gender="M",Parent="Ando"}, new Users{ Name="Niki Sanders", Gender="F",Age=2, Parent="Maya"}, new Users{ Name="Angela Patrelli", Gender="F",Age=3, Parent="Maya"}, }; now i need to format the data like here i need to check the parent based on the parent i will be creating objects under the parent objects now { Name="Kumar", Gender="M", Age=75, Parent="All" } this is the top level as a property Parent ="all" now under parent object kumar here we again create a new object to store these information under object(kumar who is the parent) new Users{ Name="Suresh",Gender="M", Age=50, Parent="Kumar"}, new Users{ Name="Bennette", Gender="F",Age=45, Parent="Kumar"}, what i need to do here is i need to check the parent based on the parent create further objects under it ex: i need to achive like this. looking for the syntax how i can do it. public class SampleProjectData { public static ObservableCollection<Product> GetSampleData() { DateTime dtS = DateTime.Now; ObservableCollection<Product> teams = new ObservableCollection<Product>(); teams.Add(new Product() { PDName = "Product1", OverallStartTime = dtS, OverallEndTime = dtS + TimeSpan.FromDays(3), }); Project emp = new Project() { PName = "Project1", OverallStartTime = dtS + TimeSpan.FromDays(1), OverallEndTime = dtS + TimeSpan.FromDays(6) }; emp.Tasks.Add(new Task() { StartTime = dtS, EndTime = dtS + TimeSpan.FromDays(2), TaskName = "John's Task 3" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(3), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "John's Task 2" }); teams[0].Projects.Add(emp); emp = new Project() { PName = "Project2", OverallStartTime = dtS + TimeSpan.FromDays(1.5), OverallEndTime = dtS + TimeSpan.FromDays(5.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Victor's Task" }); teams[0].Projects.Add(emp); emp = new Project() { PName = "Project3", OverallStartTime = dtS + TimeSpan.FromDays(2), OverallEndTime = dtS + TimeSpan.FromDays(5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Jason's Task 1" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(7), EndTime = dtS + TimeSpan.FromDays(9), TaskName = "Jason's Task 2" }); teams[0].Projects.Add(emp); teams.Add(new Product() { PDName = "Product2", OverallStartTime = dtS, OverallEndTime = dtS + TimeSpan.FromDays(3) }); emp = new Project() { PName = "Project4", OverallStartTime = dtS + TimeSpan.FromDays(0.5), OverallEndTime = dtS + TimeSpan.FromDays(3.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1.5), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Vicky's Task" }); teams[1].Projects.Add(emp); emp = new Project() { PName = "Project5", OverallStartTime = dtS + TimeSpan.FromDays(2), OverallEndTime = dtS + TimeSpan.FromDays(6) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(2.2), EndTime = dtS + TimeSpan.FromDays(3.8), TaskName = "Oleg's Task 1" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(5), EndTime = dtS + TimeSpan.FromDays(6), TaskName = "Oleg's Task 2" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(8), EndTime = dtS + TimeSpan.FromDays(9.6), TaskName = "Oleg's Task 3" }); teams[1].Projects.Add(emp); emp = new Project() { PName = "Project6", OverallStartTime = dtS + TimeSpan.FromDays(2.5), OverallEndTime = dtS + TimeSpan.FromDays(4.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(0.8), EndTime = dtS + TimeSpan.FromDays(2), TaskName = "Kim's Task" }); teams[1].Projects.Add(emp); teams.Add(new Product() { PDName = "Product3", OverallStartTime = dtS, OverallEndTime = dtS + TimeSpan.FromDays(3) }); emp = new Project() { PName = "Project7", OverallStartTime = dtS + TimeSpan.FromDays(5), OverallEndTime = dtS + TimeSpan.FromDays(7.5) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1.5), EndTime = dtS + TimeSpan.FromDays(4), TaskName = "Balaji's Task 1" }); emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(5), EndTime = dtS + TimeSpan.FromDays(8), TaskName = "Balaji's Task 2" }); teams[2].Projects.Add(emp); emp = new Project() { PName = "Project8", OverallStartTime = dtS + TimeSpan.FromDays(3), OverallEndTime = dtS + TimeSpan.FromDays(6.3) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(1.75), EndTime = dtS + TimeSpan.FromDays(2.25), TaskName = "Li's Task" }); teams[2].Projects.Add(emp); emp = new Project() { PName = "Project9", OverallStartTime = dtS + TimeSpan.FromDays(2), OverallEndTime = dtS + TimeSpan.FromDays(6) }; emp.Tasks.Add(new Task() { StartTime = dtS + TimeSpan.FromDays(2), EndTime = dtS + TimeSpan.FromDays(3), TaskName = "Stacy's Task" }); teams[2].Projects.Add(emp); return teams; } } above is an sample data where i am grouping them with static data in the same way i need **to for teh data which is cmg from DB and i need to store them list** all these three data are comig from different services. and i am storing them in a list now i have three tables data Product , Project, Task. all the data are coming from webservies. i have created three list where i am storing the data in list. List<Project>objpro= new List<Project>(); List<Product>objproduct= new List<Product>(); LIst<Task>objTask= new List<Task>(); **now what i need to do is i need to do the mapping between these tables. if you see above. i have object of Product under Product i have added object of Project and then under project object i have added task object.** now from the above data which is stored in the list i need to do the same mapping between class. and group the data. public class Product : INotifyPropertyChanged { public Product() { this.Projects = new ObservableCollection<Project>(); } public string PDName { get; set; } public ObservableCollection<Project> Projects { get; set; } private DateTime _st; public DateTime OverallStartTime { get { return _st; } set { if (this._st != value) { TimeSpan dur = this._et - this._st; this._st = value; this.OnPropertyChanged("OverallStartTime"); this.OverallEndTime = value + dur; } } } private DateTime _et; public DateTime OverallEndTime { get { return _et; } set { if (this._et != value) { this._et = value; this.OnPropertyChanged("OverallEndTime"); } } } #region INotifyPropertyChanged Members protected void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } public class Project : INotifyPropertyChanged { public Project() { this.Tasks = new ObservableCollection<Task>(); } public string PName { get; set; } public ObservableCollection<Task> Tasks { get; set; } DateTime _st; public DateTime OverallStartTime { get { return _st; } set { if (this._st != value) { TimeSpan dur = this._et - this._st; this._st = value; this.OnPropertyChanged("OverallStartTime"); this.OverallEndTime = value + dur; } } } DateTime _et; public DateTime OverallEndTime { get { return _et; } set { if (this._et != value) { this._et = value; this.OnPropertyChanged("OverallEndTime"); } } } #region INotifyPropertyChanged Members protected void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } public class Task : INotifyPropertyChanged { public string TaskName { get; set; } DateTime _st; public DateTime StartTime { get { return _st; } set { if (this._st != value) { TimeSpan dur = this._et - this._st; this._st = value; this.OnPropertyChanged("StartTime"); this.EndTime = value + dur; } } } private DateTime _et; public DateTime EndTime { get { return _et; } set { if (this._et != value) { this._et = value; this.OnPropertyChanged("EndTime"); } } } #region INotifyPropertyChanged Members protected void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } hope my question is clear

    Read the article

  • How do I return clean JSON from a WCF Service?

    - by user208662
    I am trying to return some JSON from a WCF service. This service simply returns some content from my database. I can get the data. However, I am concerned about the format of my JSON. Currently, the JSON that gets returned is formatted like this: {"d":"[{\"Age\":35,\"FirstName\":\"Peyton\",\"LastName\":\"Manning\"},{\"Age\":31,\"FirstName\":\"Drew\",\"LastName\":\"Brees\"},{\"Age\":29,\"FirstName\":\"Tony\",\"LastName\":\"Romo\"}]"} In reality, I would like my JSON to be formatted as cleanly as possible. I believe (I may be incorrect), that the same collection of results, represented in clean JSON, should look like so: [{"Age":35,"FirstName":"Peyton","LastName":"Manning"},{"Age":31,"FirstName":"Drew","LastName":"Brees"},{"Age":29,"FirstName":"Tony","LastName":"Romo"}] I have no idea where the “d” is coming from. I also have no clue why the escape characters are being inserted. My entity looks like the following: [DataContract] public class Person { [DataMember] public string FirstName { get; set; } [DataMember] public string LastName { get; set; } [DataMember] public int Age { get; set; } public Person(string firstName, string lastName, int age) { this.FirstName = firstName; this.LastName = lastName; this.Age = age; } } The service that is responsible for returning the content is defined as: [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class TestService { [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] public string GetResults() { List<Person> results = new List<Person>(); results.Add(new Person("Peyton", "Manning", 35)); results.Add(new Person("Drew", "Brees", 31)); results.Add(new Person("Tony", "Romo", 29)); // Serialize the results as JSON DataContractJsonSerializer serializer = new DataContractJsonSerializer(results.GetType()); MemoryStream memoryStream = new MemoryStream(); serializer.WriteObject(memoryStream, results); // Return the results serialized as JSON string json = Encoding.Default.GetString(memoryStream.ToArray()); return json; } } How do I return “clean” JSON from a WCF service? Thank you!

    Read the article

  • Java Scanner class reading strings

    - by Max
    I've created a scanner class to read through the text file and get the value what I'm after. Let's assume that I have a text file contains 1 : Fnjiei : ID 7868860 : Age 18 2 : Oipuiieerb : ID 334134 : Age 39 3 : Enekaree : ID 6106274 : Age 31 I'm trying to get a name and id number and age, but everytime I try to run my code it gives me an exception. Here's my code. Any suggestion from java gurus?:) public void readFile(String fileName)throws IOException{ Scanner input = null; input = new Scanner(new BufferedReader(new FileReader(fileName))); try { while (input.hasNextLine()){ int howMany = 3; System.out.println(howMany); String userInput = input.nextLine(); String name = ""; String idS = ""; String ageS = ""; int id; int age; int count=0; for (int j = 0; j <= howMany; j++){ for (int i=0; i < userInput.length(); i++){ if(count < 2){ // for name if(Character.isLetter(userInput.charAt(i))){ name+=userInput.charAt(i); // store the name }else if(userInput.charAt(i)==':'){ count++; i++; } }else if(count == 2){ // for id if(Character.isDigit(userInput.charAt(i))){ idS+=userInput.charAt(i); // store the id } else if(userInput.charAt(i)==':'){ count++; i++; } }else if(count == 3){ // for age if(Character.isDigit(userInput.charAt(i))){ ageS+=userInput.charAt(i); // store the age } } id = Integer.parseInt(idS); // convert id to integer age = Integer.parseInt(ageS); // convert age to integer Fighters newFighters = new Fighters(id, name, age); fighterList.add(newFighters); } userInput = input.nextLine(); } } }finally{ if (input != null){ input.close(); } } } My appology if my mere code begs to be changed.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >