Quantcast
Channel: Programming Forums
Viewing all 51036 articles
Browse latest View live

Yet another temp. converter c# (math problem?)

$
0
0
So ive tried as many variations of math as i can figure out/locate on google.
I am pretty sure my math is correct, but for some reason my variable seems to be holding old values?
If some one would be so kind enough to run this code they will see.
My first few conversions work great ie; 0c = -32f, 212f = 100c
How ever 100c = 68f is definatley wrong
Any help would be appreciated. :surrender:/> :surrender:/>
 
namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        private float _num1, _num2, _answer, answer;
        public Form1()
        {
            InitializeComponent();
        }

        private void btn1_Click(object sender, EventArgs e) //convert to F
        {
            _num1 = Convert.ToSingle(txtc.Text);
            _answer = (_num1-32) * (9 / 5); 
            lbx.Items.Add(_answer + " F ");

        }

        private void button1_Click(object sender, EventArgs e) //convert to C
        {
            _num2 = Convert.ToSingle(txtf.Text);
            answer = (_num2 - 32) * 5 / 9; ;
            lbx.Items.Add(answer + " C ");
        }
    }


general c++ questions

$
0
0
I'm having trouble answering a few questions, can someone explain the answers to these please?

1. For a class with several stl::string data members, why can C++ copy objects of the class without
an explicitly written copy constructor in the class?

--------------------------------------------------------------------
2. C++ allows constructor overloading. Why doesn't it allow
destructor overloading?

--------------------------------------------------------------------
3. When enabling a class to work with iostreams by adding overloaded
operator<< and operator>> functions, should they be friends
of the class or member functions, and why?

Date Class (Any Suggestion )

$
0
0

Quote

Hello
Its very simple program for your all. I little bit complete program. It increment the day, Number of days, Decrement the day or number of days. But I could not solve how to subtract date from other date.
Any advise to me to make better this in onward future...

/* It is vey nice program.
Because you will see date is increment of user persopective view
It check all the aspects of the date. mean, date increment
month increment and year increment..
if date 27 and after 5 days....it is solution give below...*/
#include <iostream>
using namespace std;
class Date
{
    private :
    int day , month , year ;
    //Array for 12 months
    static const int dayinMonth[];
    //For leapYear return
    int dayofMonth (Date) ;
    // Its check wether it is leap year or not
    bool leapYear(int ) ;
    // Public part
    public :
    void display ();
    // Default function arguments
    Date (int = 1 , int = 1 , int = 2000 ) ;
    void setDate (int , int , int ) ; //validation of date
    // Operator Declration for date PLUS
    Date operator + ( int ) ;
    Date operator ++ () ;
    //Its specific function for user Flexiblity
    friend Date operator + ( int , Date ) ;
    friend Date operator - (int ,Date ) ;
    //operator for date subtraction
    Date operator - (int) ;
    Date operator -- ();
    //its the function which validate the subtract function
    int fun ( int , int );
   // int operator -= ( Date  ) ;
};


/////////////////////////Class Member Function Declaration////////////////////


const int Date::dayinMonth[] = {0 ,31 , 28, 31,30,31,30,31,31,30,31,30,31};

/////////////////////// Date Set or Constructor ////////////////////

Date :: Date (int d , int m , int y )
{
    setDate (d , m , y ) ;
}

////////////////////////////////////Display Function/////////////////////

void Date :: display ()
{
    cout << "\n Date: " <<day << "-" << month <<"-" <<year << endl;
}

/////////////////////Its complex date setting... Paying attention to detail///////////

void Date :: setDate ( int d , int m , int y)
{
    year = y ;
    if (m < 1 && m > 12 )
    {
        month = 1 ;
    }
    else
    {
        month = m ;
    }
        if ( m == 2 && leapYear (y )) // Here function call, checks leap year
        {
            if ( d >= 1 && d <=29 )
            {
                day = d ;
            }
            else
            {
                day = 1 ;
            }
        }
        else

            if ( d >= 1 && d <= dayinMonth[month] ) // Call the arrayOFmonth
            {
                day = d ;
            }
            else
            {
                day = 1 ;
            }

}

/////////////////////////////   Leap Year Checking here ///////////////

bool Date :: leapYear (int y )
{
    if ( (y % 4 == 0) && (y % 4 == 0 && y % 100 != 0))
    {
        return true ;
    }
    else
    {
        return false ;
    }
}
/////////////////////DAY OF MONTH DEFINITION HERE//////////////////////
///////////////////// Its function specially For ++ operator//////////////////
int Date :: dayofMonth(Date d )
{
    //check for leap year
    if (d.month == 2 && leapYear(d.year ) )
    {
        return 29 ;
    }
    else
    {
        return dayinMonth[d.month] ;
    }
}

////////////////////////////Operator + () Definition here. /////////////////

Date Date :: operator + ( int d )
{
    for ( int i = 1 ; i <= d ; i ++ )
    {
        // YOu can use "Date d " .. d here instead of *this
        ++(*this ) ; // here this point to current object & call to Unary Operator ++
    }
    return (*this ) ;

}
///////////////////////It is unary operator mean just one increment in date //////////
//////////////////////Paying attention to detail/////////////////
Date Date :: operator ++ ()
{
    if ( day == dayofMonth(*this) && month == 12 )
    {
        day = 1 ;
        month = 1;
        ++year ;
    }
    else if ( day == dayofMonth(*this ) ) // This which point current object
    {
        day = 1 ;
        ++month ;
    }
    else
    {
        day++ ;
    }
}
////////////////////////// UNARY OPERATOR DEFINATION HERE//////////////////
Date Date :: operator -- ()
{

    if ( day == 1 && month == 1 )
    {
        day = 31;
        month = 12;
        --year;
    }
    else if (day == 1 && month == 3 )
    {
        day = fun ( month , year ) ;
        --month ;
    }
    else if (day == 1  )
    {
        day = fun ( month , year ) ;
        --month ;
    }
    else
    {
        --day ;
    }
}
/////////////////////It is a function for unary operator/////////
///////////////////// Paying attention to detail/////////////
int Date :: fun ( int x , int y )
{
    if ( x == 3 && leapYear ( y ) )
    {
        return 29 ;
    }
    else
    {
        return dayinMonth[--x] ;
    }
}
////////////////// HERE - OPERATOR DEFINATION HERE////////////////////
Date Date :: operator - ( int d )
{
    for ( int i = 1 ; i <= d ; i ++ )
    {
        -- (*this ) ;
    }
    return (*this ) ;
}
////******************************** MAIN CLASS *******************************////

int main ()
{
    Date obj1 (24,7,2103) ;
    Date obj2 ;
    obj1.display();
    char choice ;
    int number ;
    do
    {
    cout << " \n It is a current Date \n Please Enter a number for follwoing choices " ;
    cout << "\n 1. for Next Day:\n 2. For Increment the number of days: " ;
    cout << "\n 3. For prvious Day : \n 4. For decremnet the number of days: " ;
    cout << "\n Note. Any other choice to show wrong number \n \"Z\" for Exit\n " ;
    cin >> choice ;
    switch (choice )
    {
        case '1' :
        {
            ++obj1 ;
            obj1.display();
            break ;
        }
        case '2' :
        {
            cout << "\n Enter a number to increment the days : " ;
            cin >> number ;
            obj1 = number + obj1;
            obj1.display();
            break ;
        }
        case '3' :
        {
            --obj1;
            obj1.display();
            break;
        }
        case '4' :
        {
            cout << "\n Enter a number to decrement the days : " ;
            cin >> number ;
            obj1 = obj1 - number ;
            obj1.display();
            break ;
        }
        default :
        {
            cout << "\n Sorry! wrong number Try for next time :)/> Thank you!! \n" ;
            break ;
        }
    }
    }while ( choice != 'z' && choice != 'Z' ) ;

    return 0 ;
}
////////////// It is freind funciton for User flexbility ///////////////////////////

Date operator + (int num , Date obj )
{
    for (int i = 1 ; i <= num; i ++ )
    {
        ++(obj) ;
    }
    return obj ;
}
///////////////////// Friend Function for user Flexiblity //////////////
Date  operator - ( int num , Date obj )
{
    for ( int i = 1 ; i <= num ; i ++ )
    {
        --(obj ) ; // Called unary operator
    }
    return obj ;
}

What am I doing wrong here?

$
0
0
I am trying to follow a tutorial here (page 11), but am getting invalid output. A runtime error should occur when the private variable is trying to echo.

The output is:

getName(); echo "My pin: " . $aPerson->$pin; ?>

What I have for the class:

<?php
class person
{
	var $name;
	public $height;
	protected $social_insurance;
	private $pin;
	
	function __construct($theName)
	{
		$this->name = $theName;
	}
	
	function setName($newName)
	{
		$this->name = $newName;
	}
	
	function getName()
	{
		return $this->name;
	}
}
?>



Here is the markup
<!DOCTYPE HTML>
<html>
	<head>
		<title>OOP Test</title>
		<?php include("class.php"); ?>
	</head>
	<body>
	<?php
		$aPerson = new person("a name");
		echo $aPerson->getName();
		echo "My pin: " . $aPerson->$pin;
	?>
	</body>
</html>

Create Dynamic Label with Drag and Drop Function

$
0
0
Hello All,



I want to make a Label that I can drag and drop. At the same time when I drag the original label it will leave a copy of it self.



Example: When I drag Label1 it will leave another Label to its Original Position( Lets Name the New Label1 in Original Position as Label2),

Then I should also be able to drag Label2 and Leave another Label (Label3), I also want to drag Label1 and Label2 but it should not leave a copy.



Here is my code: I been able to do multiplication of Label and Dragging of Label but I cannot drag all Labels:


    Public Class Form1  
        Dim cursorX, cursorY As Integer  
        Dim dragging As Boolean  
        Dim labelno As Integer = 1  
      
        Private Sub Control_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Label1.MouseDown  
            dragging = True  
            cursorX = e.X  
            cursorY = e.Y  
      
      
            Dim label2 As New Label  
            labelno += 1  
            label2.Location = New Point(Label1.Location.X, Label1.Location.Y)  
            label2.Name = "Label" + labelno.ToString  
            label2.Text = label2.Location.ToString  
            Me.Controls.Add(label2)  
      
        End Sub  
      
        Private Sub Control_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Label1.MouseUp  
            dragging = False  
        End Sub  
      
        Private Sub control_MouseMOve(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Label1.MouseMove  
            If dragging Then  
                Dim ctrl As Control = CType(sender, Control)  
                ctrl.Left = (ctrl.Left + e.X) - cursorX  
                ctrl.Top = (ctrl.Top + e.Y) - cursorY  
                ctrl.BringToFront()  
            End If  
        End Sub  




If you have clarification please inform me.



Thanks

Dictionary with Sets

$
0
0
Hello,

I am implementing a spellchecker program that utilized vectors and lists but will now utilize sets. Here is what I have given:

correction.h

#ifndef CORRECTION_H
#define CORRECTION_H

#include "wordoccurrence.h"


class Correction
//
// A correction consists of a word occurrence that has been judged to
// be misspelled and a string representing the replacement spelling.
// (Note that the replacement is not necessarily a "word" as the
// correction might involve other characters, for example correcting "tothe"
// to "to the".)

{
public:

  Correction();
  //post: getMisspelling() == WordOccurrence()
  //      && getReplacement() == ""

  Correction (const WordOccurrence& wo,
	      const std::string& replacement);
  //post: getMisspelling() == wo
  //      && getReplacement() == replacement


  WordOccurrence getMisspelling() const             {return _misspelling;}
  void putMisspelling (const WordOccurrence& missp) {_misspelling = missp;}

  std::string getReplacement() const            {return _replacement;}
  void putReplacement (const std::string& repl) {_replacement = repl;}


  // Output (mainly for debugging purposes)
  void put (std::ostream&) const;


private:
  WordOccurrence _misspelling;
  std::string _replacement;
};


inline
std::ostream& operator<< (std::ostream& out,
			  const Correction& correction)
{
  correction.put (out);
  return out;
}



bool operator< (const Correction& left, const Correction& right);
bool operator== (const Correction& left, const Correction& right);



#endif



correction.cpp
#include "correction.h"

using namespace std;

Correction::Correction()
  //post: getMisspelling() == WordOccurrence()
  //      && getReplacement() == ""
{}

  
Correction::Correction (const WordOccurrence& wo,
			const string& replacement)
  //post: getMisspelling() == wo
  //      && getReplacement() == replacement
  : _misspelling(wo), _replacement(replacement)
{}



// Output (mainly for debugging purposes)
void Correction::put (std::ostream& out) const
{
  out << _misspelling << "=>" << _replacement;
}



bool operator< (const Correction& left, const Correction& right)
{
  return (left.getMisspelling() < right.getMisspelling())
    || ((left.getMisspelling() == right.getMisspelling())
	&& (left.getReplacement() < right.getReplacement()));
}



bool operator== (const Correction& left, const Correction& right)
{
  return (left.getMisspelling() == right.getMisspelling())
    && (left.getReplacement() == right.getReplacement());
}



replacement.h

#ifndef REPLACEMENT_H
#define REPLACEMENT_H

#include <iostream>
#include <string>

class Replacement 
{
public:
  Replacement () {}
  Replacement (const std::string& missp, const std::string& repl);

  void setMisspelledWord (const std::string& mw) {_misspelledWord = mw;}
  std::string getMisspelledWord() const          {return _misspelledWord;}
  
  void setReplacement (const std::string& r)     {_replacement = r;}
  std::string getReplacement() const             {return _replacement;}
  
  void put (std::ostream&) const;
  
private:
  std::string _misspelledWord;
  std::string _replacement;
};

inline
std::ostream& operator<< (std::ostream& out, const Replacement& r)
{
  r.put (out);
  return out;
}


bool operator== (const Replacement& left, const Replacement& right);
bool operator< (const Replacement& left, const Replacement& right);



#endif



replacement.cpp
#include "replacement.h"

using namespace std;

Replacement::Replacement (const std::string& missp, const std::string& repl)
  : _misspelledWord(missp), _replacement(repl)
{}

void Replacement::put (ostream& out) const
{
  out << _misspelledWord << "=>" << _replacement;
}

bool operator== (const Replacement& left, const Replacement& right)
{
  return (left.getMisspelledWord() == right.getMisspelledWord());
}

bool operator< (const Replacement& left, const Replacement& right)
{
  return (left.getMisspelledWord() < right.getMisspelledWord());
}



sequential.h
#ifndef SEQUENTIAL_H
#define SEQUENTIAL_H


template <class Etype>
int sequentialSearch (const Etype* a, unsigned n, const Etype& x)
//
//  Search the array a[] for x, given that a contains n elements.
//  Return the position where x is found, or -1 if not found.
//  Assumes a[] is sorted, i.e., for all i in 0..n-2, a[i] <= a[i+1]
//
{
  int i = 0;
  while ((i < n) && (a[i] < x))
    ++i;
  if ((i >= n) || (x < a[i]))
    return -1;
  else
    return i;
}


template <class Etype>
int sequentialInsert (Etype* a, unsigned n, const Etype& x)
//
//  Insert x into the array a[], given that a contains n elements.
//  Assumes a[] is sorted, i.e., for all i in 0..n-2, a[i] <= a[i+1]
//  x is inserted into a position that leaves a still sorted.
//  Return the position where x was inserted.
//
{
  int i;
  for (i = n; (i > 0) && (x < a[i]); --i)
    a[i] = a[i-1];
  a[i] = x;
  return i;
}


#endif



token.h
#ifndef TOKEN_H
#define TOKEN_H

#include <string>
#include <iostream>

class Token 
//
// A "token" is a meaningful unit extracted from a text file.
// For example, a C++ compile would consider the keyword "class" 
// and the identifier "Token" in the line above to each be a single 
// token. In most applications, tokens can be formed from different numbers 
// of characters, usually do not  include white space (blanks, new lines,
// etc.), but the exact definition of a "token" is highly
// application-dependent.
{
public:
  typedef long unsigned Location;
  
  Token();
  //post: getLexeme()=="" && getLocation()==0

  Token (const std::string& lexeme,
	 Location location);

  // A "lexeme" is the string of characters that has been identified
  // as constituting a token.
  std::string getLexeme() const          {return _lexeme;}
  void putLexeme (const std::string& lex) {_lexeme = lex;}

  // The location indicates where in the original file the first character of
  // a token's lexeme was found.
  Location getLocation() const;
  void putLocation (const Location&);

  // Read a token from a stream. A token is recognized as a consecutive
  // string of 1 or more characters beginning with some character from
  // startingCharacters, followed by zero or more characters from
  // middleCharacters, and ending with a character from endingCharacters (which
  // may be the same character as the beginning character).
  // Returns true if a token was found. Returns false if no token could
  // be found (i.e., an input error occurred or end-of-file was reached
  // before finding an acceptable token).
  //
  // Warning: this function may read and discard an arbitrary number of extra
  // startingCharacters and middleCharacters until finding a valid token (followed
  // by a non-middleCharacter).  
  virtual bool readToken(std::istream& input,
			 const std::string& startingCharacters,
			 const std::string& middleCharacters,
			 const std::string& endingCharacters);

  // Output (mainly for debugging purposes)
  void put (std::ostream&) const;
  
private:
  std::string _lexeme;
  Location _location;
};


bool operator< (const Token& left, const Token& right);
bool operator== (const Token& left, const Token& right);

inline
std::ostream& operator<< (std::ostream& out, const Token& t)
{
  t.put(out);
  return out;
}

inline
Token::Location Token::getLocation() const
{
  return _location;
}

inline
void Token::putLocation (const Token::Location& loc)
{
  _location = loc;
}





#endif


token.cpp
#include "token.h"

//
// A "token" is a meaningful unit extracted from a text file.
// For example, a C++ compile would consider the keyword "class" 
// and the identifier "Token" in the line above to each be a single 
// token. In most applications, tokens can be formed from different numbers 
// of characters, usually do not  include white space (blanks, new lines,
// etc.), but the exact definition of a "token" is highly
// application-dependent.



using namespace std;

Token::Token(): _location(0)
  //post: getLexeme()=="" && getLocation()==0
{}

    

Token::Token (const std::string& lexeme,
	      Location location)
  : _lexeme(lexeme), _location(location)
{}


  // Read a token from a stream. A token is recognized as a consecutive
  // string of 1 or more characters beginning with some character from
  // startingCharacters, followed by zero or more characters from
  // middleCharacters, and ending with a character from endingCharacters.
  // Returns true if a token was found. Returns false if no token could
  // be found (i.e., an input error occurred or end-of-file was reached
  // before finding an acceptable token).
bool Token::readToken(std::istream& input,
		      const std::string& startingCharacters,
		      const std::string& middleCharacters,
		      const std::string& endingCharacters)
{
  string lexeme;
  Location location;
  char c;
  bool done = false;

  while (!done)
    {
	  // Hunt for a starting character
      c = input.get();
	  // cerr << c << " is at " << startingCharacters.find(c) << endl;
	  while ((input) && (startingCharacters.find(c) == string::npos))
	  {
		c = input.get();
	  }
      if (!input) return false;  // Could not find starting character

	  lexeme = c;
	  location = (Location)input.tellg() - (Location)1;

	  // Now read forward until we come to something that is not a middle character
      c = input.get();
	  while ((input) && (middleCharacters.find(c) != string::npos))
	  {
		lexeme += c;
		c = input.get();
	  }

	  if ((input) && (endingCharacters.find(c) == string::npos))
	  {
		  // If the last character we read was not an endingCharacter, put
		  // it back into the input stream.
		  input.unget();
	  } else if (input) {
		  lexeme += c;
	  }

	  // Did we find an ending character anywhere in the characters we read?
	  int endingPos = lexeme.find_last_of(endingCharacters);
	  if (endingPos == string::npos) {
		  // No: keep trying (if there's more input available)
		  done = !input;
	  }
	  else 
	  {
		  // Yes: return the lexeme we have found
		  _location = location;
		  _lexeme = lexeme.substr(0, endingPos+1);
		  return true;
	  }
  }
  return false;
}


// Output (mainly for debugging purposes)
void Token::put (std::ostream& out) const
{
  out << _lexeme << '@' << _location;
}


bool operator< (const Token& left, const Token& right)
{
  if (left.getLocation() < right.getLocation())
    return true;
  else if (left.getLocation() == right.getLocation())
    return (left.getLexeme() < right.getLexeme());
  else
    return false;
}

bool operator== (const Token& left, const Token& right)
{
  return ((left.getLocation() == right.getLocation())
	  && (left.getLexeme() == right.getLexeme()));
}





wordoccurrence.h

#ifndef WORDOCCURRENCE_H
#define WORDOCCURRENCE_H

#include "token.h"


class WordOccurrence 
//
// A "word" is a string that beings with an alphnumberic character,
// continues with 0 or more of the same characters, hyphens, or apostrophes,
// and ends with an alphanumeric character. For example,
//    the 2nd wasn't how-do-you-do
// are all words, but
//    ./? Yes? 123 multi-
// are not.
//
// A word occurrence describes a word within a document, combining a 
// "lexeme" (the string of characters) that comprise a word with the
// location within the document where the word was found.

{
public:
  typedef Token::Location Location;
  
  WordOccurrence();
  //post: getLexeme()=="" && getLocation()==0

  WordOccurrence (const std::string& lexeme,
		  Location location);

  // A "lexeme" is the string of characters that has been identified
  // as constituting a token.
  std::string getLexeme() const           {return tok.getLexeme();}
  void putLexeme (const std::string& lex) {tok.putLexeme (lex);}

  // The location indicates where in the original file the first character of
  // a token's lexeme was found.
  Location getLocation() const {return tok.getLocation();}
  void putLocation (const Location& loc)  {tok.putLocation(loc);}



  // Read a word from a stream.
  bool read(std::istream& input);
  

  // Output (mainly for debugging purposes)
  void put (std::ostream& out) const  {tok.put(out);}

private:
  Token tok;

  static const std::string startingChars;
  static const std::string middleChars;
  static const std::string endingChars;

  friend bool operator< (const WordOccurrence& left, 
			 const WordOccurrence& right);
  friend bool operator== (const WordOccurrence& left, 
			  const WordOccurrence& right);

};

inline
bool operator< (const WordOccurrence& left, const WordOccurrence& right)
{
  return left.tok < right.tok;
}

inline
bool operator== (const WordOccurrence& left, const WordOccurrence& right)
{
  return left.tok == right.tok;
}

inline
std::ostream& operator<< (std::ostream& out, const WordOccurrence& t)
{
  t.put(out);
  return out;
}


#endif



wordoccurrence.cpp
#include "wordoccurrence.h"

using namespace std;


const string WordOccurrence::endingChars
  = string("abcdefghijklmnopqrstuvwxyz")
    + "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

const string WordOccurrence::startingChars
  = endingChars + "0123456789";

const string WordOccurrence::middleChars
  = startingChars + "-'";


WordOccurrence::WordOccurrence()
//post: getLexeme()=="" && getLocation()==0
{}

WordOccurrence::WordOccurrence (const std::string& lexeme,
				Location location)
  : tok(lexeme, location)
{}




// Read a word from a stream.
bool WordOccurrence::read(std::istream& input)
{
  return tok.readToken(input, startingChars, middleChars, endingChars);
}



and finally the file that will hold all of my code edits:

spellcheck.cpp

// Spellcheck program

/*#include <algorithm>
#include <fstream>
#include <list>
#include <vector>
#include "wordoccurrence.h"
#include "correction.h"
#include "replacement.h"
#include "vectorUtils.h"*/

#include <algorithm>
#include <fstream>
#include "wordoccurrence.h"
#include "correction.h"
#include "replacement.h"
#include <set>

using namespace std;


/*
typedef list<string> WordSet;
typedef list<Replacement> ReplacementSet;
typedef vector<WordOccurrence> WordOccurrenceOrderedSequence;
typedef vector<Correction> CorrectionOrderedSequence;
*/


typedef set<string> WordSet;
typedef set<Replacement> ReplacementSet;
typedef set<WordOccurrence> WordOccurrenceOrderedSequence;
typedef set<Correction> CorrectionOrderedSequence;






std::string promptForAction (const WordOccurrence& misspelled);


std::string get_replacement_spelling(const std::string& word,
				    const WordSet& dictionary);

std::string getSaveFileName();





using namespace std;

#ifdef GRADING
string saveFileName;
#endif


void readDictionary (const string& dictionaryFileName,
		     WordSet& dictionary);


void collectMisspelledWords (const string& targetFileName,
			     const WordSet& dictionary,
			     WordOccurrenceOrderedSequence& misspellings);

void promptUserForCorrections
  (const string& targetFileName,
   const WordSet& dictionary,
   const WordOccurrenceOrderedSequence& misspellings,
   CorrectionOrderedSequence& corrections);


void produceCorrectedDocument(const string& targetFileName,
			      /*const*/CorrectionOrderedSequence& corrections,
			      const string& correctedFileName);





int main (int argc, char** argv)
{
#ifndef GRADING
  if (argc != 3) {
    cerr << "Usage: " << argv[0]
	 << " dictionaryFileName documentFileName"
	 << endl;
    return 1;
  }
#else
  if (argc != 4) {
    cerr << "Usage: " << argv[0]
	 << " dictionaryFileName documentFileName saveFileName"
	 << endl;
    return 1;
  }
  saveFileName = argv[3];
#endif

  string dictionaryFileName = argv[1];
  string targetFileName = argv[2];



  // main spellcheck routine
  WordSet dictionary;
  readDictionary (dictionaryFileName, dictionary);

  WordOccurrenceOrderedSequence misspellings;
  collectMisspelledWords (targetFileName, dictionary, misspellings);


  CorrectionOrderedSequence corrections;
  promptUserForCorrections(targetFileName, dictionary,
			   misspellings, corrections);

#ifndef GRADING
  if (!corrections.empty())
#endif
    {
      string correctedFileName = getSaveFileName();
      produceCorrectedDocument(targetFileName, corrections,
			       correctedFileName);
    }

  return 0;
}



void readDictionary (const string& dictionaryFileName,
		     WordSet& dictionary)
{
  dictionary.clear();
  WordSet temp;
  ifstream dictin (dictionaryFileName.c_str());
  string word;
  while (dictin >> word)
    {
      temp.insert (word);
    }
  //temp.sort();
  /*string count = 0;
  for (int i=0; i< temp.size(); ++i)
  {
      count = temp.insert(count, word);
      ++count;
  }*/
  unique_copy (temp.begin(), temp.end(), back_inserter(dictionary));
}


bool contains (const WordSet& words, const string& s)
{
  return find(words.begin(), words.end(), s) != words.end();
}


void collectMisspelledWords (const string& targetFileName,
			     const WordSet& dictionary,
			     WordOccurrenceOrderedSequence& misspellings)
{
  ifstream targetFile (targetFileName.c_str());
  cout << "Checking " << targetFileName << endl;

  WordOccurrence w;
  while (w.read(targetFile))
    {
      if (!contains(dictionary, w.getLexeme()))
       {
         //  int count = 0;
           //misspellings.size() = count;
           //count++;
	 //addInOrder (misspellings, w);
       }
  }
  cout << misspellings.size() << " possible misspellings found." << endl;
}



void display_in_context (const WordOccurrence& occur, istream& inFile)
{
  static const WordOccurrence::Location ContextSize = 20;

  WordOccurrence::Location start = (occur.getLocation() >= ContextSize) ?
    occur.getLocation() - ContextSize : (WordOccurrence::Location)0;
  WordOccurrence::Location stop = occur.getLocation() + ContextSize
    + (WordOccurrence::Location)occur.getLexeme().length();


  string beforeMisspelling;
  string afterMisspelling;
  inFile.seekg(start);
  for (; start < occur.getLocation(); start+=1)
    beforeMisspelling += (char)inFile.get();

  start = occur.getLocation() + (WordOccurrence::Location)occur.getLexeme().length();
  inFile.seekg(start);
  for (; start < stop; start+=1)
    afterMisspelling += (char)inFile.get();

  // If there is a line break (\c or \n) more than 2 chars from
  // this misspelling, terminate the context there.

  int loc = beforeMisspelling.substr(0, beforeMisspelling.length()-2)
    .find_last_of("\r\n");
  if (loc != string::npos) {
    beforeMisspelling = beforeMisspelling.substr(loc+1);
  }
  loc = afterMisspelling.find_first_of("\r\n", 2);
  if (loc != string::npos) {
    afterMisspelling = afterMisspelling.substr(0, loc-1);
  }

  cout << beforeMisspelling << "\n   "
       << occur.getLexeme() << "\n"
       << afterMisspelling << endl;
}






void promptUserForCorrections
  (const string& targetFileName,
   const WordSet& dictionary,
   const WordOccurrenceOrderedSequence& misspellings,
   CorrectionOrderedSequence& corrections)
{
  // assume misspellings are in order of occurrence within the
  // target file (if not, sort them)
  ifstream targetFile (targetFileName.c_str());

  WordSet globalIgnoredSet;
  ReplacementSet globalReplacementSet;

  for (WordOccurrenceOrderedSequence::const_iterator m =  misspellings.begin();
       m != misspellings.end(); ++m)
    {
      WordOccurrence misspelling = *m;
      string mword = misspelling.getLexeme();
      WordOccurrence::Location mloc = misspelling.getLocation();

      ReplacementSet::iterator repl =
	find(globalReplacementSet.begin(), globalReplacementSet.end(),
	     Replacement(mword,""));
      if (repl != globalReplacementSet.end())
	{
	 // addInOrder(corrections,Correction(misspelling,
					  //  (*repl).getReplacement()));
	}
      else
	{
	  display_in_context(misspelling, targetFile);
	  string response = promptForAction(misspelling);
	  if (response == "ignore")
	    {
	      // do nothing
	    }
	  else if (response == "ignore every time")
	    {
	      globalIgnoredSet.insert(mword);
	    }
	  else if (response == "replace")
	    {
	      string r = get_replacement_spelling(mword, dictionary);
//	      addInOrder (corrections, Correction(misspelling, r));
	    }
	  else if (response == "replace every time")
	    {
	      string r = get_replacement_spelling(mword, dictionary);
	      addInOrder (corrections, Correction(misspelling, r));
	      globalReplacementSet.push_back (Replacement(mword, r));
	    }
	  else if (response == "quit")
	    {
	      break;
	    }
	}
    }
}





void produceCorrectedDocument(const string& targetFileName,
			      /*const*/CorrectionOrderedSequence& corrections,
			      const string& correctedFileName)
{
  cout << "Corrected document saving to " << correctedFileName << endl;

  // assume corrections are in order of occurrence within the
  // target file (if not, sort them)
  ifstream targetFile (targetFileName.c_str());
  ofstream correctedFile (correctedFileName.c_str());

  for (CorrectionOrderedSequence::iterator c = corrections.begin();
       c != corrections.end(); ++c)
    {
      // copy into the correctedFile all characters from
      //   current location of the targetFile up to
      //   the location of c;
      for (long offset = (*c).getMisspelling().getLocation()
	                 - targetFile.tellg();
	   offset > 0; --offset) {
	correctedFile.put ((char)targetFile.get());
      }

      // read and discard the misspelled word from the targetFile;
      WordOccurrence misspelled;
      misspelled.read(targetFile);

      // write the corrected spelling from c into the correctedFile;
      correctedFile << (*c).getReplacement();
    }

  // copy any remaining characters from the targetFile into the
  //   correctedFile;
  char ch = targetFile.get();
  while ((targetFile) && (ch >= 0))
    {
      correctedFile.put(ch);
      ch = targetFile.get();
    }
  cout << "Corrected document saved in " << correctedFileName << endl;
}



/***************************
     Interactive routines for the spellcheck program

  When compiled with GRADING flag set, these are replaced by
  noninteractive code for auto-testing purposes.
****************************/

string promptForAction (const WordOccurrence& misspelled)
{
#ifndef GRADING
  cout << "\n" << misspelled.getLexeme() << ":\n"
       << " (r)eplace this word, just this once\n"
       << " (R)eplace this word every time\n"
       << " (i)gnore this word, just this once\n"
       << " (I)gnore this word every time\n"
       << " (Q)uit\n"
       << ">" << flush;

  char response;
  bool OK = false;
  while (1)
    {
      cin >> response;
      switch (response) {
	case 'r': return "replace";
	case 'R': return "replace every time";
	case 'i': return "ignore";
	case 'I': return "ignore every time";
	case 'Q': return "quit";
      }
      if (response > ' ')
	cout << "Please respond with one of: rRiIQ\n>" << flush;
    }
#else
  return "replace every time";
#endif
}


string get_replacement_spelling(const string& word,
				const WordSet& dictionary)
{
#ifndef GRADING
  cout << "\n" << word << ":" << endl;

  // Get a list of potential replacement strings
  // (not yet implemented)
  string* replacements = 0;
  int nReplacements = 0;

  if (nReplacements > 0)
    {
      // display the various possible replacements, let user pick from
      // among them (not yet implemented)
    }
  else
    {
      // Prompt user directly for corrected spelling
      string corrected;
      while (corrected == "")
	{
	  cout << "\nEnter correct spelling: " << flush;
	  cin >> corrected;
	}
      return corrected;
    }
#else
  return "[" + word + "]";
#endif
}







string getSaveFileName()
{
#ifndef GRADING
  string fileName;
  cout << "Enter name of file to contain the corrected document, or blank\n"
       << "to discard all corrections:\n"
       << "> " << flush;
  while (fileName == "")
    {
      getline(cin, fileName);
    }
  return fileName;
#else
  return saveFileName;
#endif
}



The boundaries are that i cannot make any changes to code that lies between an #ifndef GRADING...#endif


I was given the last file as a vector and list implementation. I've attempted to tweak it to fit the std::set but I'm getting a compile error for:

globalReplacementSet.push_back (Replacement(mword, r));


I know push_back isn't in the set library so what is the set equivalent for push_back?

telnet > xml > vb

$
0
0
Hey. Im writing a program to allow me to set up a 3d studio max render farm quickly.
I use telnet to communicate with backburner (the render manager) and i need to be able to send commands to telnet as well as reciever them.
However there is one command 'get joblist' that returns me an xml formatted list of jobs.
What i want to know is whether its possible to retrieve each job name from the text in telnet and put it into a datagrid.
But a problem arises when the job datagrid refreshes because i dont want vb to search the entire telnet window because there could be multiple 'get joblist' commands in the previous command list.

Could someone help me out with this kind of thing?
Ive done some xml > vb before but never from a command window.

Thank you

Jack :)

My.Computer.FileSystem.GetFiles Could not find a part of the path

$
0
0
I have a program to backup folders that works file the first time, but fails if I try to backup another folder (or set of folders) without restarting the program. I got sick of Windows copying all files with matching names and wanted a file copy program that only overwrites a file if the source file is newer than the destination file. It allows me to select several source folders and a single destination folder.

The program is too big to list all the code here but I will include a summary and all of the My.Computer.FileSystem uses and the relevant code that has the problem.

First, the program builds displays two checkbox treeviews, one for the source folders and one for the target folder. It uses the My.Computer.FileSystem.Drives(x) to get the drive info and My.Computer.FileSystem.GetDirectories and My.Computer.FileSystem.GetDirectoryInfo to get the folder info and load the treeviews.

Then, after the user selects the folders and clicks the start button it uses the GetDirectories and GetDirectoryInfo to build a table of all the source folders selected and their subfolders.

Then, it uses My.Computer.FileSystem.DirectoryExists and My.Computer.FileSystem.CreateDirectory to create any target folders that do not exit.

Then it runs this routine twice, once to get statistics (AnalyzeCopy = Analyze) and then to do the actual backup (AnalyzeCopy = Copy). I have removed the irrelevant code and all the comments (sorry):

Private Sub ProcessSourceFolderTable(ByVal AnalyzeCopy As String)
    Dim sourceFileInfo As System.IO.FileInfo
    Dim targetFileInfo As System.IO.FileInfo
    Dim sourcePath As String
    Dim targetPath As String
    Dim sourceDate As String
    Dim targetDate As String
    For Me.sourcePathIndex = 1 To sourcePathTotal
        sourcePath = sourceBasePath(sourcePathIndex) + sourceCommonPath(sourcePathIndex) + "\"
        targetPath = targetSelectedPath + sourceCommonPath(sourcePathIndex) + "\"
        Try
            For Each sourceFile As String In My.Computer.FileSystem.GetFiles(sourcePath)
                sourceFileInfo = My.Computer.FileSystem.GetFileInfo(sourceFile)
                sourceDate = sourceFileInfo.LastWriteTime
                Dim fileSize As Integer = sourceFileInfo.Length
                If sourceFileInfo.Attributes.ToString.Contains(IO.FileAttributes.Hidden.ToString) Then
                Else
                    If System.IO.File.Exists(targetPath + sourceFileInfo.Name) = False Then
                        CopyFile(sourcePath, targetPath, sourceFileInfo.Name, fileSize, AnalyzeCopy)
                    Else
                        targetFileInfo = My.Computer.FileSystem.GetFileInfo(targetPath + sourceFileInfo.Name)
                        targetDate = targetFileInfo.LastWriteTime
                        If sourceDate > targetDate Then
                            CopyFile(sourcePath, targetPath, sourceFileInfo.Name, fileSize, AnalyzeCopy)
                        Else
                            If sourceDate < targetDate And AnalyzeCopy = "Copy" Then
                               ‘ Message and choice
                               CopyFile(targetPath, sourcePath, sourceFileInfo.Name, fileSize, AnalyzeCopy)
                            End If
                        End If
                    End If
                End If
            Next
        Catch ex As Exception
            MsgBox("Error PSFT: " + ex.Message)
        End Try
    Next sourcePathIndex
End Sub

Private Sub CopyFile(ByVal sourcePath As String, ByVal targetPath As String, ByVal sourceFile As String, ByVal fileSize As Integer, ByVal AnalyzeCopy As String)
    Try
        If AnalyzeCopy = "Analyze" Then
            FilesTotal += 1
            BytesTotal += fileSize / 1000
        Else
            FilesUsed += 1
            BytesUsed += fileSize / 1000
            My.Computer.FileSystem.CopyFile(sourcePath + sourceFile, targetPath + sourceFile, True)                
        End If
    Catch ex As Exception
        MsgBox("Error CF: " + ex.Message)
    End Try
End Sub


This all works fine. Until I try to do a second backup without closing the program.
I select new folders and click the start command and ProcessSourceFolderTable blows up on the:

For Each sourceFile As String In My.Computer.FileSystem.GetFiles(sourcePath) 


with a “Could not find a part of the path”.

It seems that “sourcePath” now contains the FileSystem.CurrentDirectory plus the real sourcePath. Example: Say the current directory is “C:\Test\CurrentDirectory” and the sourcePath is “C:\Test\SourcePath”.

My error reads: “Could not find a part of the path: C:\Test\CurrentDirectory\Test\SourcePath”

I have done considerable debugging and know it is blowing on that line. At the time of the abend, variable sourcePath is correct. I have also spent considerable time searching this and other forums and tutorials.

I’m stumped! Any ideas? Thanks in advance.

Pdo backwards compatinility?

$
0
0
I suspect its not, but I'll ask anyways.
I'm trying to upgrade mysite, whats there anyways, to PHP 5.5. (PDO). Hostgator only has PHP 5.2 when I did the phpinfo().
I'm very disappointed.
Is this backwards compatible or should I forget PDO?
Thanks

C++ assignment help - enum & structs

$
0
0
Hello all,

this would be my first post on DIC, so hopefully this post will all be somewhat clear for any more experienced coders

I'm taking a C++ class over the summer for my major requirement, and so far, its been pretty interesting.

We have just touched on enum and structures and have some work to be done for this week. We have been given a start up project by our professor and we are to modify the code using the instructions provided within it as comments. I have been somewhat able to follow the code, but when I compile the program, it gives me something very different than what I would like it to show. Basically, the code spits out recommendations of cars to use depending on the amount of people you'd need to fit in it. Heres the code:

/*  Assignment 7
    VehicleRecommendation.cpp

    Student Name: <type your name here>

*/

#include<iostream>
#include<iomanip>
#include<string>
#include<cctype>
using namespace std;

// Named constants for vehicle category

const string CARPOOL = "Carpool",
             FAMILY = "Family",
             SPORT = "Sport";

// * TODO * (Objective 1):	Replace named constants for capacity groupings with
//						    the required CapacityGroup enumeration

enum CapacityGroup {CG_ERR, CG_1_2, CG_3_4, CG_5_6, CG_7_8, CG_9_12};

// Named constants for seating capacity groupings




// ** TODO ** (Objective 2):	Define the required Vehicle structure
//								with these two fields

//          category:       type string
//          occupants:      type int

struct Vehicle
{
	string category;
	int occupants;
};



//------------------------------------------------------------------------------

// function prototype declarations

void DisplayResults(string category, int occupants);

// *** TODO *** (Objective 3, step a):	Replace both parameters below with just
//										one Vehicle structure parameter
string GetRecommendation(Vehicle motorVehicle);


// (Recommended Improvement 1, step a): Change the return type to CapacityGroup
CapacityGroup GetCapacityGroup(int occupants);


// (Recommended Improvement 2, step a): Change parameter type to CapacityGroup
string GetCarpoolRecommendation(CapacityGroup group);
string GetFamilyRecommendation(CapacityGroup group);
string GetSportRecommendation(CapacityGroup group);




//------------------------------------------------------------------------------

int main()
{
    /*
        DO NOT MODIFY the main() function block!
    */

    cout << endl
         << "------------------------------------------------------" << endl
         << "This program recommends a vehicle based on its purpose" << endl
         << "and the seating capacity for expected occupants." << endl
         << "------------------------------------------------------" << endl
         << endl;

    // Test Carpool category.

    cout << CARPOOL << ":" << endl;

    for(int occupants = 13; occupants >= 0; occupants--)
        DisplayResults(CARPOOL, occupants);

    cout << endl;

      // Test Family category.

    cout << FAMILY << ":" << endl;

    for(int occupants = 13; occupants >= 0; occupants--)
        DisplayResults(FAMILY, occupants);

    cout << endl;

      // Test Sport category.

    cout << SPORT << ":" << endl;

    for(int occupants = 13; occupants >= 0; occupants--)
        DisplayResults(SPORT, occupants);

    cout << endl;

      // Test unknown and not specified category

    cout << "Other:" << endl;

    DisplayResults("Vacation", 5);          // category unknown
    DisplayResults("", -1);                 // category not specified

    cout << endl << "- End Program - " << endl;
}

//------------------------------------------------------------------------------

// Function definitions

  /*  Function: DisplayResults(string category, int occupants)

      Prints occupants, and then gets and prints a recommendation.

      Parameters:

      category - incoming:  A string for identifying purpose of vehicle
      occupants - incoming: An integer indicating how many occupants are expected

      Return value: None.
  */

void DisplayResults(string category, int occupants)
{
    // *** TODO *** (Objective 3, step c): Declare Vehicle structure variable
	
	Vehicle motorVehicle;
	
	
    // *** TODO *** (Objective 3, step c):	Initialize Vehicle variable fields
    //										with two function parameter values
    //										passed into this function
	
	motorVehicle.category ;
	motorVehicle.occupants = 0;


	

    // *** TODO *** (Objective 3, step c): 	Replace both function call arguments
    //										with one Vehicle structure variable

    string recommendation = GetRecommendation(motorVehicle);
	
    cout << setw(12) << motorVehicle.occupants << " occupants - "
         << recommendation << endl;
}

//------------------------------------------------------------------------------

/*
  Gets a capacity grouping designation based on number of occupants.

  POST CONDITION: return value is in range 1-12
  with invalid values designated CG_ERR
*/

// (Recommended Improvement 1, step a): Change return type to CapacityGroup
CapacityGroup GetCapacityGroup(int occupants)
{
    // (Recommended Improvement 1, step B)/>/>/>/>: Change variable type to match function
    //										return type

    CapacityGroup group;


    if( occupants < 1 || occupants > 12 )   // invalid
        group = CG_ERR;
    else if( occupants >= 9 )               // 9-12
        group = CG_9_12;
    else if( occupants >= 7 )               // 7-8
        group = CG_7_8;
    else if( occupants >= 5 )               // 5-6
        group = CG_5_6;
    else if( occupants >= 3 )               // 3-4
        group = CG_3_4;
    else                                    // 1-2
        group = CG_1_2;

    return group;
}

//------------------------------------------------------------------------------

/*
  Gets a vehicle recommendation based on the category and number of
  occupants.

  POST CONDITION: return value is a vehicle recommendation or other message.
*/

// *** TODO *** (Objective 3, step a):  Replace string and int function parameters
//										with just one Vehicle parameter

string GetRecommendation(Vehicle motorVehicle)
{
    // *** TODO *** (Objective 3, step B)/>/>/>/>:  Use Vehicle fields where necessary in
    //										place of the string and int parameters
    //										that were replaced in step a.
    // NOTE: This step will require
    // 4 modifications throughout this function


    // (Recommended Improvement 2, step B)/>/>/>/>: Change variable type to match function
    //										return type
    // NOTE: This step also is related to Improvement 1
    // Get the capacity group for the occupants parameter.
    CapacityGroup group = GetCapacityGroup(motorVehicle.occupants);




    string recommendation;

    // Compare the category parameter to string constants.

    if( motorVehicle.category == CARPOOL )
    {
      recommendation = GetCarpoolRecommendation(group);
    }
    else if( motorVehicle.category == FAMILY )
    {
      recommendation = GetFamilyRecommendation(group);
    }
    else if( motorVehicle.category == SPORT )
    {
      recommendation = GetSportRecommendation(group);
    }
    else
    {
      recommendation = "Purpose unknown or not specified.";
    }

    return recommendation;
}

//------------------------------------------------------------------------------

/*
  Gets a vehicle recommendation for CARPOOL category based on the capacity grouping

  POST CONDITION: return value is a vehicle recommended for this grouping, or other
  message if one cannot be determined.
*/
// (Recommended Improvement 2, step a): Change parameter type to CapacityGroup
string GetCarpoolRecommendation(CapacityGroup group)
{
    string recommendation;

    switch( group )
    {
      case CG_9_12:  recommendation = "Dodge Sprinter Wagon";
                     break;
      case CG_7_8:   recommendation = "Ford E-150 XL";
                     break;
      case CG_5_6:   recommendation = "Chrysler Town and Country";
                     break;

      case CG_3_4:
      case CG_1_2:   recommendation = "Consider a smaller vehicle.";
                     break;

      default: recommendation = "No recommendation for this capacity.";
    }

    return recommendation;
}

//------------------------------------------------------------------------------

/*
  Gets a vehicle recommendation for FAMILY category based on the capacity grouping.

  POST CONDITION: return value is a vehicle recommended for this grouping, or other
  message if one cannot be determined.
*/
// (Recommended Improvement 2, step a): Change parameter type to CapacityGroup
string GetFamilyRecommendation(CapacityGroup group)
{
    string recommendation;

    switch( group )
    {
      case CG_9_12:  recommendation = "Consider a larger vehicle.";
                     break;

      case CG_7_8:   recommendation = "Honda Odyssey";
                     break;
      case CG_5_6:   recommendation = "Buick Lucerne";
                     break;
      case CG_3_4:   recommendation = "Chevy Malibu";
                     break;

      case CG_1_2:   recommendation = "Consider a smaller vehicle.";
                     break;

      default: recommendation = "No recommendation for this capacity.";
    }

    return recommendation;
}

//------------------------------------------------------------------------------

/*
  Gets a vehicle recommendation for SPORT category based on the capacity grouping.

  POST CONDITION: return value is a vehicle recommended for this grouping, or other
  message if one cannot be determined.
*/
// (Recommended Improvement 2, step a): Change parameter type to CapacityGroup
string GetSportRecommendation(CapacityGroup group)
{
    string recommendation;

    switch( group )
    {
      case CG_9_12:
      case CG_7_8:
      case CG_5_6:   recommendation = "Consider a larger vehicle.";
                     break;

      case CG_3_4:   recommendation = "Ford Mustang";
                     break;
      case CG_1_2:   recommendation = "Dodge Viper";
                     break;

      default: recommendation = "No recommendation for this capacity.";
    }

    return recommendation;
}

//------------------------------------------------------------------------------

 /* Program Output

------------------------------------------------------
This program recommends a vehicle based on its purpose
and the seating capacity for expected occupants.
------------------------------------------------------

Carpool:
          13 occupants - No recommendation for this capacity.
          12 occupants - Dodge Sprinter Wagon
          11 occupants - Dodge Sprinter Wagon
          10 occupants - Dodge Sprinter Wagon
           9 occupants - Dodge Sprinter Wagon
           8 occupants - Ford E-150 XL
           7 occupants - Ford E-150 XL
           6 occupants - Chrysler Town and Country
           5 occupants - Chrysler Town and Country
           4 occupants - Consider a smaller vehicle.
           3 occupants - Consider a smaller vehicle.
           2 occupants - Consider a smaller vehicle.
           1 occupants - Consider a smaller vehicle.
           0 occupants - No recommendation for this capacity.

Family:
          13 occupants - No recommendation for this capacity.
          12 occupants - Consider a larger vehicle.
          11 occupants - Consider a larger vehicle.
          10 occupants - Consider a larger vehicle.
           9 occupants - Consider a larger vehicle.
           8 occupants - Honda Odyssey
           7 occupants - Honda Odyssey
           6 occupants - Buick Lucerne
           5 occupants - Buick Lucerne
           4 occupants - Chevy Malibu
           3 occupants - Chevy Malibu
           2 occupants - Consider a smaller vehicle.
           1 occupants - Consider a smaller vehicle.
           0 occupants - No recommendation for this capacity.

Sport:
          13 occupants - No recommendation for this capacity.
          12 occupants - Consider a larger vehicle.
          11 occupants - Consider a larger vehicle.
          10 occupants - Consider a larger vehicle.
           9 occupants - Consider a larger vehicle.
           8 occupants - Consider a larger vehicle.
           7 occupants - Consider a larger vehicle.
           6 occupants - Consider a larger vehicle.
           5 occupants - Consider a larger vehicle.
           4 occupants - Ford Mustang
           3 occupants - Ford Mustang
           2 occupants - Dodge Viper
           1 occupants - Dodge Viper
           0 occupants - No recommendation for this capacity.

Other:
           5 occupants - Purpose unknown or not specified.
          -1 occupants - Purpose unknown or not specified.

- End Program -
Press any key to continue . . .
 */



I have gone through most of the requirements, but I am getting a little lost within the void function DisplayResults.
In the function, I must initialize the structure variable (I'm guessing that would be "Vehicle motorVehicle"?") as well as initialize the fields with two parameters (which would be both the occupants and category in the struct). Because of my lack of confidence in the code I put in the DisplayResults function, I'm assuming that's where everything goes to crap. I have looked through the book as well as looked through example codes that we have been provided in class, but I can't seem to find the proper way to initialize these two parts in the void function. If anyone has any insight, I'd greatly appreaciate your input.

Thanks!

no data is passed

$
0
0
why there are no data are passed when I choosed DHL as a shipping method.
this is my shipping code:
<?php

		$options = "";
		
		
		
		
		//$_SESSION['shipment'] = isset($_REQUEST['shipment']);

$result = mysql_query("SELECT id, country, first_kg, additional_kg FROM country");
 while($row = mysql_fetch_array($result)) {
  
   $options.="<option value='$row[0]'>$row[1]</option>";

	}
   
 
  mysql_free_result($result);
 
			
	if(isset($_REQUEST['shipping']) && isset($_REQUEST['shipment']))  {		
		$id = $_REQUEST['shipping'];
		$shipment = $_REQUEST['shipment'];	
		$qty = cartItems();
	
			if($shipment == "postal"){
				
				
				//postal shipping
				$result = mysql_query("SELECT id, country, first_kg, additional_kg FROM country WHERE id='$id'");
				while($row = mysql_fetch_array($result)) {
   
				
				$_SESSION['country'] = $row[1];
				
				
					
					
						
							if($qty > 1){
					
								$qty = $qty - 1;
								$add = $qty * $row[3];
								$_SESSION['ship'] = $row[2] + $add;
								$_SESSION['paypalShipping'] = ($_SESSION['ship'] / cartItems()) / 39;
						
						
								}else
									{$_SESSION['ship'] = $row[2];
									$_SESSION['paypalShipping'] = ($_SESSION['ship'] / cartItems()) / 39;}
					
					
				
				}
				
				
				
				
				}else if($shipment == 'dhl'){
				
				
				
				
							//dhl shipping
				
				
							$result = mysql_query("SELECT zone, country FROM country WHERE id='$id'");
							$row = mysql_fetch_array($result);
							$z = $row['zone'];
							$_SESSION['country'] = $row['country'];
				
							$zone = mysql_query("SELECT first_kg, additional_kg FROM zone WHERE id='$z'");
							while($row = mysql_fetch_array($zone)){
							
   
						
							if($qty > 1){
					
								$qty = $qty - 1;
								$add = $qty * $row['additional_kg'];
								$_SESSION['ship'] = $row['first_kg'] + $add;
								$_SESSION['paypalShipping'] = ($_SESSION['ship'] / cartItems()) / 39;
						
						
								}else
									{$_SESSION['ship'] = $row['first_kg'];
									$_SESSION['paypalShipping'] = ($_SESSION['ship'] / cartItems()) / 39;}
				
				
							}
				
				
				}
				
				
				
			


		}

			
				
				
?>

	<select name='shipping'>
			<option value='<?php if(isset($_SESSION['ship'])){echo stripslashes($_SESSION['ship']);}else{echo "";}?>'>Select a country...</option>
			<?php echo $options; ?>
			
	</select> *

pdo connecting to database

$
0
0
Or not connecting rather:)

I have an include file that is connect.php. I have the following code.

define ('DOCUMENT_ROOT' , dirname(_FILE_));

try	{
$conn = new PDO('mysql:host=localhost:dbname='rcomments', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}




When I do use include (or include_once), it gives me a fatal error.

Warning: include(/includes/rconnect.php) [function.include]: failed to open stream: No such file or directory in /home1/username/public_html/page.php on line 32

Warning: include() [function.include]: Failed opening '/includes/rconnect.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home1/username/public_html/page.php on line 32


Line 32 is inside of the page and it reads only

<?php
include '/includes/connect.php';
?>




From what I have read, the document root is not defined, which explains why I put the document_root inside the include. But no go.

Thanks

how to change the default size of the form?

$
0
0
hi there.
I have a form that FormborderStyle is none put it, after I create forms like resizing the original form, but its default size does not change when scaled
how to change the default size of the form?
for example, the default size of the media player in window 7
Thank you !

java calculator using swing

$
0
0
import java.io.*;
import java.util.*;

public class exercise1
{

public static void main(String args[])
{
System.out.println("Selection from the choices below:\n");
System.out.println(" 1. Addition");
System.out.println(" 2. Subtraction");
System.out.println(" 3. Multiplication");
System.out.println(" 4. Division");
System.out.println(" 5. Modulo\n");

System.out.print(" Your choice? ");


Scanner kbReader = new Scanner(System.in);
int choice = kbReader.nextInt();


if((choice<=5) && (choice>0))
{

System.out.print("\nEnter first number: ");
int x = kbReader.nextInt();


System.out.print("Enter second number: ");
int y = kbReader.nextInt();




System.out.println("");

switch (choice)
{
case 1: //addition 1 decimal
System.out.println(x + " plus " + y + " = " + (x + y) );
break;

case 2: //subtraction no decimal
System.out.println(x + " minus " + y + " = " + (x - y) );
break;

case 3: //multiplication 3 decimal
System.out.println(x + " times " + y + " = " + (x * y) );
break;

case 4: //division 4 decimal
System.out.println(x + " divided by " + y + " = " + (x / y) );
break;

case 5: //modulo
System.out.println(x + " modulo " + y + " = " + (x % y) );
//break;
}

}
else
{
System.out.println("Please enter a 1, 2, 3, 4 or 5.");
}
}
}

using provider class and user class

$
0
0
i'm trying to write a program to ask user input for number of students,input their grades,calculate the grades average,find the max n min grade.i'm trying to write the program using 2 separate .java.

this is the code for the provider class

package gradesstatistics;
import java.util.Scanner;

public class GradesStatistics{
    private int numOfStudents;
    private int sum=0;
    private double average=0;
    Scanner in=new Scanner(System.in);
    int[]grades=new int[numOfStudents];
    
    //prompt user for the number of students and allocate the "grades" array
    //prompt user for grade n check for valid grade,and store in "grades"
    public void readGrades(){
        System.out.println("Enter the number of students: ");
        numOfStudents=in.nextInt();
                  
        for(int student=0;student<numOfStudents;student++){
            System.out.println("Enter the grade for student "+(student+1)+": ");
            grades[student]=in.nextInt();
            while(grades[student]<0 || grades[student]>100){
                System.out.println("Invalid grade.try again");
                grades[student]=in.nextInt();
            }
            sum+=grades[student];
            }
        }
    
    //return the average value of int[] grades
    public double average(){
        average=sum/numOfStudents;
        return average;
    }
    
    //find max grade
    public int max(){
        int highGrade=0;//assume highest grade is 0
        //loop through grades array
        for(int student=0;student<numOfStudents;student++){
            //if current grade higher than highGrade,assign it to highGrade
            if(grades[student]>highGrade)
                highGrade=grades[student];
        }
        return highGrade;
    }
    
    //find min grade
    public int min(){
          int lowGrade=100;//assume highest grade is 0
        //loop through grades array
        for(int student=0;student<numOfStudents;student++){
            //if current grade higher than highGrade,assign it to highGrade
            if(grades[student]>lowGrade)
                lowGrade=grades[student];
        }
        return lowGrade;
    }
}


this is the program for user class

package gradesstatistics;

public class GradesStatisticsMain{
public static void main(String[]args){
    GradesStatistics n=new GradesStatistics();
    n.readGrades();
    System.out.println("The average grade is "+n.average());
    System.out.println("The minumum grade is "+n.min());
    System.out.println("The maximum grade is "+n.max());
}
}


this is the error i got:

run:
Enter the number of students:
3
Enter the grade for student 1:
89
Enter the grade for student 2:
87
Enter the grade for student 3:
86
The average grade is 87.0
Exception in thread "main" java.lang.NullPointerException
at gradesstatistics.GradesStatistics.min(GradesStatistics.java:56)
at gradesstatistics.GradesStatisticsMain.main(GradesStatisticsMain.java:8)
Java Result: 1
BUILD SUCCESSFUL (total time: 11 seconds)

i suspect the error is because there is something wrong with the int[]grades=new int[numOfStudents];
perhaps wrong location of declaring it?

Question How do I properly multiply with "For Loops" and 2 var

$
0
0
Well
I am currently learning "C" and I'm trying to multiply 2 variables just to get the exercise to learn the language.
The code is:

#include <stdio.h>

int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int factorial = 1;
int i;

/* Code to calculate the factorial using "For Loops" */

printf("10! is %d.\n", factorial);
}


I have tried a few different things, example adding this to the code

#include <stdio.h>

int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int factorial = 1;
int i;

for (i = 0; i < 10; i++) {
        factorial *= array[i];
}

printf("10! is %d.\n", factorial);
}


And just switching the "factorial" and "array" so it got like this:

#include <stdio.h>

int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int factorial = 1;
int i;

for (i = 0; i < 10; i++) {
        array *= factorial[i];
}

printf("10! is %d.\n", factorial);
}


Any suggestions for what I'm doing wrong?
The code simply doesn't run with an answer

Problem with DevComponents.DotNetBar2.dll

$
0
0
I have a problem regarding DevComponents.DotNetBar2.dll.

I already add reference it and modify my forms but when I started to start my form. It appears it in normal.
I mean the designs doesn't appear at all in start up.

Anyone can help me.
Thank you.

java calculator using Scanner

$
0
0
import java.io.*;
import java.util.*;

public class exercise1 {

	public static void main(String args[]) {
		System.out.println("Selection from the choices below:\n");
		System.out.println(" 1. Addition");
		System.out.println(" 2. Subtraction");
		System.out.println(" 3. Multiplication");
		System.out.println(" 4. Division");
		System.out.println(" 5. Modulo\n");

		System.out.print(" Your choice? ");

		Scanner kbReader = new Scanner(System.in);
		int choice = kbReader.nextInt();

		if ((choice <= 5) && (choice > 0)) {

			System.out.print("\nEnter first number: ");
			int x = kbReader.nextInt();

			System.out.print("Enter second number: ");
			int y = kbReader.nextInt();

			System.out.println("");

			switch (choice) {
			case 1: // addition 1 decimal
				System.out.println(x + " plus " + y + " = " + (x + y));
				break;

			case 2: // subtraction no decimal
				System.out.println(x + " minus " + y + " = " + (x - y));
				break;

			case 3: // multiplication 3 decimal
				System.out.println(x + " times " + y + " = " + (x * y));
				break;

			case 4: // division 4 decimal
				System.out.println(x + " divided by " + y + " = " + (x / y));
				break;

			case 5: // modulo
				System.out.println(x + " modulo " + y + " = " + (x % y));
				// break;
			}

		} else {
			System.out.println("Please enter a 1, 2, 3, 4 or 5.");
		}
	}
}

The 'MicroSoft.ACE.OLEDB.12.0' provider is not registered on t

$
0
0
I developed an asp.net website using Windows 7 (32 bit),Visual Studio 2010 and MS Access Database(32 bit). After uploading this website on my personal server, I get an error- "The 'MicroSoft.ACE.OLEDB.12.0' provider is not registered on the local machine." What am i supposed to do??? :helpsmilie:

Automate OAuth2 authentication

$
0
0
I'm working with measuring vital signs devices. The manufacturer is iHealth. These connect with a smartphone where is installed an app that when you are logged in with your account it sends the measurements to their server. I have to connect to this server and extract the datas from many accounts but at the moment I will be satisfy to extract only mine. To do this iHealth provides a Sandbox like example that you can download at this url:  SandboxAPISample.zip (81.81K)
: 7 .

In this example all the needed variables (client_id, client_secret, redirect_url etc) are set up in the ConnectToiHealthlabs.cs class.

When you start the project the page GetStarted.aspx is loaded and only a button appears. By clicking the button the follow method is called from ConnectToiHealthlabs.cs class:

public void GetCode()
    {
        string url = url_authorization
            + "?client_id=" + client_id
            + "&response_type=" + response_type_code
            + "&redirect_uri=" + redirect_uri
            + "&APIName=" + APIName_BP + " " + APIName_Weight;

        HttpContext.Current.Response.Redirect(url);
    }


The url where it redirects is
http://sandboxapi.ihealthlabs.com/api/OAuthv2/userauthorization.ashx?client_id=e4dce2f7027044e0a6ce82ef44d27e23&response_type=code&redirect_uri=http://localhost:9201/TestPage.aspx&APIName=OpenApiBP OpenApiWeight


So you will arrive to the page
http://sandboxapi.ihealthlabs.com/api/OAuthv2/oauthlogin.aspx?redirect_uri=%2fapi%2fOAuthv2%2fuserauthorization.ashx%3fclient_id%3de4dce2f7027044e0a6ce82ef44d27e23%26response_type%3dcode%26redirect_uri%3dhttp%3a%2f%2flocalhost%3a9201%2fTestPage.aspx%26APIName%3dOpenApiBP%2520OpenApiWeight


Now you can authenticate with the sandbox credentials:

username: sandboxuser@ihealthlabs.com

Password: 111111

If the credentials are right you will be redirected to TestPage.aspx where this method is called:

public bool GetAccessToken(string code, string client_para, HttpContext httpContext)
    {
        string url = url_authorization
        + "?client_id=" + client_id
        + "&client_secret=" + client_secret
        + "&client_para=" + client_para
        + "&code=" + code
        + "&grant_type=" + grant_type_authorization_code
        + "&redirect_uri=" + redirect_uri;

        string ResultString = this.HttpGet(url);

        if (ResultString.StartsWith("{\"Error\":"))
        {
            this.Error = JsonDeserializ<ApiErrorEntity>(ResultString);
            return false; 
        }
        else
        {
            AccessTokenEntity accessToken = this.JsonDeserializ<AccessTokenEntity>(ResultString);
            httpContext.Session["token"] = accessToken;
            return true;
        }
    }


The result url is
http://sandboxapi.ihealthlabs.com/api/OAuthv2/userauthorization.ashx?client_id=e4dce2f7027044e0a6ce82ef44d27e23&client_secret=bb6a0326db55468f8f474ad5fd79aa0a&client_para=123&code=a1yBBCZu80DXlhnSmyYEKIY6cQ73cVj7O9i1hv7rH68EQIgIlY0*pODnNbD2gyEMu6UnHvksB5Ndf42-I8i4xPHb4jTqzpue0S9PVLTCjw2bUMOZCyiBoCBjcllUzHzo&grant_type=authorization_code&redirect_uri=http://localhost:9201/TestPage.aspx


So if everything is correct you can see a button to download BP data (url:
http://sandboxapi.ihealthlabs.com/api/OpenApi/downloadbpdata.ashx?access_token=a1yBBCZu80DXlhnSmyYEKIY6cQ73cVj7O9i1hv7rH6-zMHK6iEu9OCg4MCErg-lOvm0WKcGwfZfVWanKB3-s2BLUZniYfwn99tsdWTRhlvBU8ZFTcIk-9qPeMtN*zVTNosPp4RsCiHF2D-o-DvpdwjS9qQhcwMEKgunaLSK1Qu8&client_id=e4dce2f7027044e0a6ce82ef44d27e23&client_secret=bb6a0326db55468f8f474ad5fd79aa0a&redirect_uri=http://localhost:9201/TestPage.aspx&sc=082a65ac25db4262b795f635c974de47&sv=bd82a25dcf18446b90f3219ef7d0b441
),

download weight data (url:
http://sandboxapi.ihealthlabs.com/api/OpenApi/downloadweightdata.ashx?access_token=a1yBBCZu80DXlhnSmyYEKIY6cQ73cVj7O9i1hv7rH6-zMHK6iEu9OCg4MCErg-lOvm0WKcGwfZfVWanKB3-s2BKc5tIrfqZpz5gC*IAhOnIr1J1PhT0M0*IPDtIZ6SLuTZtNC5Hn0C4u0yDBo9zunmoDwkoz2wKmAqE4aXUJFE4&client_id=e4dce2f7027044e0a6ce82ef44d27e23&client_secret=bb6a0326db55468f8f474ad5fd79aa0a&redirect_uri=http://localhost:9201/TestPage.aspx&sc=082a65ac25db4262b795f635c974de47&sv=add22354420244ba9e0f3a5a6b402096
)

and refresh token (url:
http://sandboxapi.ihealthlabs.com/api/OAuthv2/userauthorization.ashx?client_id=e4dce2f7027044e0a6ce82ef44d27e23&client_secret=bb6a0326db55468f8f474ad5fd79aa0a&client_para=&refresh_token=a1yBBCZu80DXlhnSmyYEKIY6cQ73cVj7O9i1hv7rH6-zMHK6iEu9OCg4MCErg-lOvm0WKcGwfZfVWanKB3-s2Pl0dL9j3ijv6zPwlqNtRkO2lRuNbVszrIeKHqx2ZToJCLvFHNHmMJWni*QMiIgWRl-B3VIHGdpGFPpD5iD0p9Y&response_type=refresh_token&redirect_uri=http://localhost:9201/TestPage.aspx
).

In this example it databinds a repeater with the list that returns DownloadBPData and DownloadWeightData methods to show the values in the page.

My goal is to arrive these two lists without open popups and without manual authentications scheduling the update speed.

All in a log like page:

24/07/2013 12:00 - Found new data for user ABC

24/07/2013 11:30 - Found new data for user XYZ

24/07/2013 11:00 - etc...

But I really don't know where to start.

The only documentation that I have is the following file:  Open API Protocol.zip (459.46K)
: 7

The url in the sandbox project are differents from the server where I have to connect I found a lot of OAuth2 libraries but all the examples are for Facebook, Twitter etc.

Thank you.
Viewing all 51036 articles
Browse latest View live




Latest Images