IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » class The latest public class snipts.

showing 1-20 of 24 snipts for class
  • get the index of the first occurrence of an object by class (using a block)
    /*
     * Some references:
     *     http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html
     *     http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/indexOfObjectPassingTest:
     *
     */
    
    /* Predeclare a block */
    BOOL (^IsSameClass)(id, NSUInteger, BOOL *) = ^(id element, NSUInteger idx, BOOL * stop) {
        *stop = [element isKindOfClass:UITabBar.class];
        return *stop;
    };
    	
    NSUInteger index = [myNSArray indexOfObjectPassingTest:IsSameClass];
    
    
    /* Using a block literal */
    NSUInteger index = [myNSArray indexOfObjectPassingTest:^(id element, NSUInteger idx, BOOL * stop){ 
        *stop = [element isKindOfClass:UITabBar.class];
        return *stop;
    }];
    

    copy | embed

    0 comments - tagged in  posted by jonatasmiguel on Sep 03, 2010 at 7:45 a.m. EDT
  • get the first occurrence of an object of a specific class
    /*
     * Some references:
     *     http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocFastEnumeration.html
     *     http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1
     *     http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isKindOfClass:
     *
     */
    
    /* NSArray+Additions.h */
    @interface NSArray (Additions) 
    
    - (id)objectOfClass:(Class)aClass;
    
    @end
    
    
    
    /* NSArray+Additions.m */
    #import "NSArray+Additions.h"
    
    
    @implementation NSArray (Additions)
    
    - (id)objectOfClass:(Class)aClass {
        for (id element in self) {
            if ([element isKindOfClass:aClass]) {
                return (element);
            }
        }
    
        return (nil);
    }
    
    @end
    

    copy | embed

    0 comments - tagged in  posted by jonatasmiguel on Sep 01, 2010 at 1:24 p.m. EDT
  • get the index of the first occurrence of an object by class
    /*
     * Some references:
     *     http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocFastEnumeration.html
     *     http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1
     *     http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isKindOfClass:
     *     http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/indexOfObject:
     *
     */
    
    /* NSArray+Additions.h */
    @interface NSArray (Additions) 
    
    - (NSInteger)indexOfObjectByClass:(Class)aClass;
    
    @end
    
    
    
    /* NSArray+Additions.m */
    #import "NSArray+Additions.h"
    
    
    @implementation NSArray (Additions)
    
    - (NSInteger)indexOfObjectByClass:(Class)aClass {
        for (id element in self) {
            if ([element isKindOfClass:aClass]) {
                return ([self indexOfObject:element]);
            }
        }
    
        return (-1);
    }
    
    @end
    

    copy | embed

    0 comments - tagged in  posted by jonatasmiguel on Sep 01, 2010 at 11:44 a.m. EDT
  • bank.cpp
    #include <string>
    
    using namespace std;
    
    #include "bankAccount.h"
    
    string bank::getName()
    {
        return name;
    }
    
    double bank::getBalance()
    {
        return balance;
    )
    
    void bank::setBalance(double balancePassed)
    {
        balance=balancePassed;
    }
    
    double bank::getOverdraft()
    {
        return overdraft;
    }
    
    void bank::setOverdraft(double overdraftPassed)
    {
        overdraft=overdraftPassed;
    }
    
    int bank::getState();
    {
        return state;
    }
    
    void bank::setState(int statePassed)
    {
        state=statePassed;
    }
    
    int bank::Withdraw(string namePassed, double )
    {
    
        return
    

    copy | embed

    0 comments - tagged in  posted by wafflesncheese on May 08, 2010 at 11:38 a.m. EDT
  • bank.h
    #ifndef BANKHEADER_H_INCLUDED
    #define BANKHEADER_H_INCLUDED
    
    class bank
    {
    public:
        string getName();
        double getBalance();
        void setBalance(double);
        double getOverdraft();
        void setOverdraft(double);
        int getState();
        void setState(int);
        int Withdraw(string, double);
        int TransferTo(string, double)
    private:
        string name;
        double balance
        double overdraft;
        int state;
    
    #endif // BANKHEADER_H_INCLUDED
    

    copy | embed

    0 comments - tagged in  posted by wafflesncheese on May 08, 2010 at 11:37 a.m. EDT
  • cat home
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class cat //start a class called cat
    {
    public: //public variables
        string catName;
        string catColor;
        int catTag;
        void set(int temp, string temp2); //function that is used to assign data into private
        void print(); //function that is used to print out data
    private: //private variables
        int catTel;
        string catAdd;
    };
    
    void cat::set(int temp, string temp2) //function used to assign data into private
    {
        catTel=temp; //stores first variable into catTel
        catAdd=temp2; //stores second variable into catAdd
    }
    
    void cat::print() //function used to print out data
    {
        cout<<"Cat's name: "<<catName<<endl;
        cout<<"Cat's color: "<<catColor<<endl;
        cout<<"Cat's tag: "<<catTag<<endl;
        cout<<"Cat's owner number: "<<catTel<<endl;
        cout<<"Cat's address: "<<catAdd<<endl<<endl;
    }
    int main()
    {
        cat c1; // create object c1 in class cat
        cat c2; //create object c2 in class cat
    
        cout<<"Welcome to MX's cat home, lol"<<endl<<"============================="<<endl;
        c1.catName="Cat1";      //input data
        c1.catColor="Blue";     //^
        c1.catTag=123;          //^
        c2.catName="Cat2";      //^
        c2.catColor="Purple";   //^
        c2.catTag=124;          //^
    
        c1.set(5678, "Land1"); //pass private data through function set so that they can be stored in private
        c2.set(9123, "Land2"); //^
    
        c1.print(); //print out data
        c2.print(); //^
        return 0;
    }
    

    copy | embed

    0 comments - tagged in  posted by wafflesncheese on May 05, 2010 at 11:35 a.m. EDT
  • AS3 Class File
    package
    {
    	import flash.display.MovieClip;
    
    	public class MyClass extends MovieClip
    	{
    		public function MyClass()
    		{
    		}
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by corbanb on Apr 30, 2010 at 8:59 a.m. EDT
  • Lazy Registry Class
    <?php
    /**
     * LRegistry Class
     *
     * Managing globals with the registry pattern.
     * This class provides lazy loading functionallity. This means it is possible to
     * add a callback or class (with arguments) which will be called or instanciated
     * when it is being used for the first time.
     *
     * @version  1.0
     * @author   Victor Villaverde Laan
     * @link     http://www.freelancephp.net/php-lazy-registry-class/
     * @license  MIT license
     */
    class LRegistry {
    
    	/**
    	 * Singleton pattern
    	 * @var Registry object
    	 */
    	private static $_instance = NULL;
    
    	/**
    	 * Containing all entries
    	 * @var array
    	 */
    	private $_entries = array();
    
    	/**
    	 * Default overwrite entries when being set more than once
    	 * @var boolean
    	 */
    	private $_default_overwrite = TRUE;
    
    	/**
    	 * Private contructer for singleton protection
    	 */
    	private final function __construct() {
    	}
    
    	/**
    	 * Private clone method for singleton protection
    	 */
    	private final function __clone() {
    	}
    
    	/**
    	 * Get instance of this class
    	 * @return Registry object
    	 */
    	public static function get_instance() {
    		if ( self::$_instance === NULL )
    			self::$_instance = new LRegistry;
    
    		return self::$_instance;
    	}
    
    	/**
    	 * Get value of given key
    	 * @param string  $key
    	 * @param boolean $reload  reload if class or callback was already loaded
    	 * @return mixed
    	 */
    	public static function get( $key, $reload = FALSE ) {
    		$instance = self::get_instance();
    
    		// check if entry exists
    		if ( ! key_exists( $key, $instance->_entries ) )
    			$instance->_exception( 'Key "' . $key . '" could not be found.' );
    
    		// get current entry
    		$entry = $instance->_entries[$key];
    
    		// check if entry should be loaded or reloaded
    		if ( ! $entry['loaded'] OR $reload ) {
    			if ( $entry['type'] == 'class' ) {
    				// get reflection class
    				$ref_class = new ReflectionClass( $entry['class'] );
    				// create instance
    				$entry['value'] = $ref_class->newInstanceArgs( $entry['args'] );
    			} else if ( $entry['type'] == 'callback' ) {
    				// run callback and set return value
    				$entry['value'] = call_user_func_array( $entry['callback'], $entry['args'] );
    			} else {
    				$instance->_exception( 'Type "' . $type . '" is not supported.' );
    			}
    
    			// set (new) value and change "loaded" setting
    			$instance->_entries[$key]['value'] = $entry['value'];
    			$instance->_entries[$key]['loaded'] = TRUE;
    		}
    
    		return $entry['value'];
    	}
    
    	/**
    	 * Set value of given key
    	 * @param string  $key
    	 * @param mixed   $value
    	 * @param boolean $overwrite  optional, when set will ignore the default overwrite setting
    	 * @return boolean  value was set succesfully
    	 */
    	public static function set( $key, $value, $overwrite = NULL ) {
    		// set normal value settings
    		$settings = array( 'type' => 'value',
    							'loaded' => TRUE,
    							'value' => $value );
    
    		return self::get_instance()->_set( $key, $settings, $overwrite );
    	}
    
    	/**
    	 * Set lazy entry of a class. Instance will only be created when entry
    	 * is requested using the get method.
    	 * @param string  $key
    	 * @param string  $class
    	 * @param array   $args
    	 * @param boolean $overwrite  optional, when set will ignore the default overwrite setting
    	 * @return boolean  value was set succesfully
    	 */
    	public static function set_lazy_class( $key, $class, $args = array(), $overwrite = NULL ) {
    		// set lazy class settings
    		$settings = array( 'type' => 'class',
    							'class' => $class,
    							'args' => $args,
    							'loaded' => FALSE,
    							'value' => NULL );
    
    		return self::get_instance()->_set( $key, $settings, $overwrite );
    	}
    
    	/**
    	 * Set lazy entry of a callback function.Function will only be called when entry
    	 * is requested using the get method.
    	 * @param string  $key
    	 * @param array   $callback
    	 * @param array   $args
    	 * @param boolean $overwrite  optional, when set will ignore the default overwrite setting
    	 * @return boolean  value was set succesfully
    	 */
    	public static function set_lazy_callback( $key, $callback, $args = array(), $overwrite = NULL ) {
    		// set lazy callback settings
    		$settings = array( 'type' => 'callback',
    							'callback' => $callback,
    							'args' => $args,
    							'loaded' => FALSE,
    							'value' => NULL );
    
    		return self::get_instance()->_set( $key, $settings, $overwrite );
    	}
    
    	/**
    	 * Check if given entry exists
    	 * @param string $key
    	 * @return boolean
    	 */
    	public static function has( $key ) {
    		return key_exists( $key, self::get_instance()->_entries );
    	}
    
    	/**
    	 * Check if given (lazy) entry is already loaded
    	 * @param string $key
    	 * @return boolean
    	 */
    	public static function is_loaded( $key ) {
    		return ( self::has( $key ) AND self::get_instance()->_entries[$key]['loaded'] === TRUE );
    	}
    
    	/**
    	 * Remove the given entry
    	 * @param string $key
    	 */
    	public static function remove( $key ) {
    		if ( ! self::has( $key ) )
    			self::get_instance()->_exception( 'Key "' . $key . '"does not exist.' );
    
    		unset( self::get_instance()->_entries[$key] );
    	}
    
    	/**
    	 * Set default overwriting entries when being set more than once.
    	 * @param boolean|NULL $overwrite  optional, if empty can be used as a getter
    	 * @return boolean
    	 */
    	public static function default_overwrite( $overwrite = NULL ) {
    		if ( $overwrite !== NULL )
    			self::get_instance()->_default_overwrite = (bool) $overwrite;
    
    		return self::get_instance()->_default_overwrite;
    	}
    
    	/**
    	 * Set value of given key (private use)
    	 * @param string  $key
    	 * @param mixed   $settings
    	 * @param boolean $overwrite  optional, when set will ignore the default overwrite setting
    	 * @return boolean  value was set succesfully
    	 */
    	protected function _set( $key, $settings, $overwrite = NULL ) {
    		$instance = self::get_instance();
    
    		// check if overwriting is allowed
    		$overwrite = ( $overwrite === NULL )
    					? $this->_default_overwrite
    					: $overwrite;
    
    		// check if entry exists and overwriting is allowed
    		if ( key_exists( $key, $this->_entries ) AND ! $overwrite )
    			return FALSE;
    
    		$this->_entries[$key] = $settings;
    
    		return TRUE;
    	}
    
    	/**
    	 * Throw an exception
    	 * @param string $message
    	 */
    	protected function _exception( $message ) {
    		throw new Exception( 'LRegistry: ' . $message );
    	}
    
    }
    
    /*?> // ommit closing tag, to prevent unwanted whitespace at the end of the parts generated by the included files */
    

    copy | embed

    0 comments - tagged in  posted by freelancephp on Mar 30, 2010 at 7:31 a.m. EDT
  • Return a class is a certain page template is used
    <?php
    function page_template_class() {
    	$page_template_class = '';
    	
    	if (is_page_template('kinderen.php')) {
    		$page_template_class = 'kinderen';
    	}
    	
    	if (!empty($page_template_class)) {
    		echo ' class="'.$page_template_class.'"';
    	}
    	else {
    		return false;
    	}
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by depi on Feb 20, 2010 at 1:33 p.m. EST
  • PHP class template
    <?php
    
    /**
     * @author 1:Carlos Pires}
     * @copyright Copyright (c) 2010, 2:2km interativa!}
     */
    
    class ${3:nome da classe} {
    	$end
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by cadu on Jan 28, 2010 at 12:36 p.m. EST
  • showing different python classes types
    class A(object):
        def foo(self,x):
            print "executing foo(%s, %s)" % (self, x)
    
        @classmethod
        def class_foo(cls, x):
            print "executing class_foo(%s, %s)" % (cls, x)
    
        #@staticmethod
        def static_foo(x):
            print "executing static_foo(%s)" % x
    
    A.class_foo(1)
    A.static_foo(1)
    A.class_foo(2)
    A.static_foo(2)
    
    a=A()
    a.foo(1)
    a.class_foo(1)
    a.static_foo(1)
    

    copy | embed

    0 comments - tagged in  posted by jpartogi on Nov 10, 2009 at 9:03 p.m. EST
  • string class
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        string str1="Singapore Polytechnic is the oldest polytechnic.";
        cout<<str1<<endl;
        cout<<str1.find("o",20)<<endl<<endl;    //use of find
    
        str1.replace(29,6,"coolest");         //use of replace
    
        //str1.erase(29,6);                       //use of erase
    
        //str1.insert(29,"coolest");
    
        cout<<str1<<endl;
        return 0;
    }
    

    copy | embed

    0 comments - tagged in  posted by ASaravanan on Nov 09, 2009 at 7:54 p.m. EST
  • bankaccount
    //This is Account.h
    
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    class Account
    {
    public:
        Account();
        Account(char* Name);
        ~Account();
        string getName();
        void setName(string Name);
        double getBalance();
        void setBalance(double Balance);
        double getOverdraft();
        void setOverdraft(double Overdraft);
    
        int withdraw(double amount);
        int transferTo(Account* acc,double amount);
        void deposit(double amount);
        double calcInterest(double rate, int year);
        void state(void);
    
    private:
        string name;
        double balance;
        double overdraft;
    };
    
    //This is Account.cpp
    
    #include "Account.h"
    
    using namespace std;
    
    Account :: Account()
    {
        balance = 0;
        overdraft = 0;
        name = "";
    }
    
    Account :: Account(char* Name)
    {
        balance = 0;
        overdraft = 0;
        name = Name;
    }
    
    Account :: ~Account()
    {
    }
    
    string Account :: getName()
    {
        return name;
    }
    
    void Account :: setName(string Name)
    {
        name = Name;
    }
    
    double Account :: getBalance()
    {
        return balance;
    }
    
    void Account :: setBalance(double Balance)
    {
        balance = Balance;
    }
    
    double Account :: getOverdraft()
    {
        return overdraft;
    }
    
    void Account :: setOverdraft(double Overdraft)
    {
        overdraft = Overdraft;
    }
    
    int Account :: withdraw(double amount)
    {
        if (amount < (balance + overdraft))
        {
            balance -= amount;
            return 1;
        }
        return 0;
    }
    
    int Account :: transferTo(Account* acc, double amount)
    {
        if (withdraw(amount))
        {
            acc->deposit(amount);
            return 1;
        }
        return 0;
    }
    
    void Account ::deposit(double amount)
    {
        balance += amount;
    }
    
    double Account :: calcInterest(double rate, int year)
    {
        double interest = 0.0;
        if (balance > 0.0)
        {
            interest = balance * rate * year;
    
        }
        return interest;
    }
    
    void Account :: state()
    {
        cout<<endl;
        cout<<"Name : "<<getName()<<endl;
        cout<<"Balance : "<<getBalance()<<endl;
        cout<<"Overdraft : "<<getOverdraft()<<endl;
    }
    
    //This is main.cpp
    
    #include <iostream>
    #include <string>
    #include "Account.h"
    
    using namespace std;
    
    int main()
    {
        Account* acc1 = new Account("TestName1");
        Account* acc2 = new Account("TestName2");
    
        double rate = 0.05;
        int yr = 1;
        double interest;
    
        int choice;
        char Name[128];
        double amt;
    
        do
        {
            cout<<"1  : Set Name for account 1"<<endl;
            cout<<"2  : Set Name for account 2"<<endl;
            cout<<"3  : Set Overdraft limit for account 1"<<endl;
            cout<<"4  : Set Overdraft limit for account 2"<<endl;
            cout<<"5  : Deposit money into account 1"<<endl;
            cout<<"6  : Deposit money into account 2"<<endl;
            cout<<"7  : Withdraw money from account 1"<<endl;
            cout<<"8  : Withdraw money from account 2"<<endl;
            cout<<"9  : Transfer money from account 1 to account 2"<<endl;
            cout<<"10 : Transfer money from account 2 to account 1"<<endl;
            cout<<"11 : Print out interest of account 1"<<endl;
            cout<<"12 : Print out interest of account 2"<<endl;
            cout<<"13 : Print cout the statement for account 1"<<endl;
            cout<<"14 : Print cout the statement for account 2"<<endl;
            cout<<"0  : Quit"<<endl;
    
            cout<<endl<<"Enter choice : ";
            cin>>choice;
            cout<<endl;
    
            switch(choice)
            {
                case 1:
                    cout<<"Enter name for account 1"<<endl;
                    cin>>Name;
                    acc1->setName(Name);
                    break;
    
                case 2:
                    cout<<"Enter name for account 2"<<endl;
                    cin>>Name;
                    acc2->setName(Name);
                    break;
    
                case 3:
                    cout<<"Set Overdraft for account 1"<<endl;
                    cin>>amt;
                    acc1->setOverdraft(amt);
                    break;
    
                case 4:
                    cout<<"Set Overdraft for account 2"<<endl;
                    cin>>amt;
                    acc2->setOverdraft(amt);
                    break;
    
                case 5:
                    cout<<"Enter the amount to deposit for account 1"<<endl;
                    cin>>amt;
                    acc1->deposit(amt);
                    break;
    
                case 6:
                    cout<<"Enter the amount to deposit for account 2"<<endl;
                    cin>>amt;
                    acc2->deposit(amt);
                    break;
    
                case 7:
                    cout<<"Enter the amount to withdraw for account 1"<<endl;
                    cin>>amt;
                    if (acc1->withdraw(amt))
                    {
                        cout<<"Withdraw succesfully for account 1"<<endl;
                    }
                    else
                    {
                        cout<<"Not enough cash for withdrawal"<<endl;
                    }
                    break;
    
                case 8:
                    cout<<"Enter the amount to withdraw for account 2"<<endl;
                    cin>>amt;
                    if (acc2->withdraw(amt))
                    {
                        cout<<"Withdraw succesfully for account 2"<<endl;
                    }
                    else
                    {
                        cout<<"Not enough cash for withdrawal"<<endl;
                    }
                    break;
    
                case 9:
                    cout<<"Enter the amount to tranfer from account 1 to account 2"<<endl;
                    cin>>amt;
                    if (acc1->transferTo(acc2, amt))
                    {
                        cout<<"Transfer succesfully to account 2"<<endl;
                    }
                    else
                    {
                        cout<<"Not enough cash for transfering"<<endl;
                    }
                    break;
    
                case 10:
                    cout<<"Enter the amount to tranfer from account 2 to account 1"<<endl;
                    cin>>amt;
                    if (acc2->transferTo(acc1, amt))
                    {
                        cout<<"Transfer succesfully to account 1"<<endl;
                    }
                    else
                    {
                        cout<<"Not enough cash for transfering"<<endl;
                    }
                    break;
    
                case 11:
                    cout << "The interest of account 1: ";
                    interest = acc1->calcInterest(rate, yr);
                    cout << interest<<endl;
                    break;
    
                case 12:
                    cout << "The interest of account 2: ";
                    interest = acc2->calcInterest(rate, yr);
                    cout << interest<<endl;
                    break;
    
                case 13:
                    acc1->state();
                    break;
    
                case 14:
                    acc2->state();
                    break;
    
                default:
                    if(choice!=0)
                    cout << "You enter wrong choice. Please re-enter choice again."<<endl;
                    break;
    
            }
            cout<<endl<<endl;
        }
        while (choice != 0);
    
        return 0;
    }
    

    copy | embed

    0 comments - tagged in  posted by HuiHui on Nov 08, 2009 at 4:19 a.m. EST
  • class-object
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Doggy
    {
        char doggyName[80];
        char doggyType[80];
        char doggyOwner[40];
        int dogTag;
    
    public:
        int gettel(int telnum, int Telnum);
        void settel(int telnum, int Telnum);
        char getAddress(char Address, char address);
        void setAddress(char Address, char address);
    
        void store(char * name, char * type, char * owner, int num);
        void show();
        void showadd_tel();
        void store1(int tel, char *add);
    
    private:
        int telnum;
        char address[100];
    
    };//semi col to mark End Of class dec
    
    int Doggy :: gettel(int telnum, int Telnum)
    {
        return telnum;
    }
    
    void Doggy :: settel(int telnum, int Telnum)
    {
        Telnum = telnum;
    }
    
    char Doggy :: getAddress(char Address, char address)
    {
        return address;
    }
    
    void Doggy :: setAddress(char Address, char address)
    {
        Address = address;
    }
    
    //:: is the binary scope, eg the fuction belong to which class
    void Doggy::store(char * name, char * type, char * owner, int num)
    {
        strcpy(doggyName, name);
        strcpy(doggyType, type);
        strcpy(doggyOwner, owner);
        dogTag = num;
    }
    
    void Doggy::show()
    {
        cout << "dog's Name: " << doggyName << endl;
        cout << "dog's Type: " << doggyType << endl;
        cout << "dog's Owner: " << doggyOwner << endl;
        cout << "dog tag number: " << dogTag << endl;
    }
    
    void Doggy :: showadd_tel()
    {
        cout << "telephone no.: " << telnum << endl;
        cout << "address: " << address << endl;
    }
    
    void Doggy :: store1(int tel, char *add)
    {
        telnum = tel;
        strcpy(address, add);
    }
    int main()
    {
    //create 3 new dog object
        Doggy d1;
        Doggy d2;
        Doggy d3;
    
        Doggy at1;
        Doggy at2;
        Doggy at3;
    
        cout << "Welcome to my Dog Kennel" << endl;
        d1.store("dipsy", "Maltest","Alice", 1001);
        d2.store("lala", "Dobberman","Bob", 1002);
        d3.store("tinki", "Collie","Malory", 1003);
    
        at1.store1(123, "woodlands");
        at2.store1(234, "bugis");
        at3.store1(345, "amk");
    
        d1.show();
        at1.showadd_tel();
        cout << endl;
    
        d2.show();
        at2.showadd_tel();
        cout << endl;
    
        d3.show();
        at3.showadd_tel();
        cout << endl;
        return 0;
    }
    

    copy | embed

    0 comments - tagged in  posted by HuiHui on Nov 02, 2009 at 7:06 a.m. EST
  • class initialiser
    + (void) initialize
    {
      if (self == [ClassName class])
      {
        /**
         * initialize class properties
         */
      }
    }
    

    copy | embed

    0 comments - tagged in  posted by nicolascormier on Oct 03, 2009 at 7:35 p.m. EDT
  • Database Helper Class with Cache
    <?php
    class Database {
    	
    	public $db = array(
    		'host'=>DB_HOST,
    		'user'=>DB_USER,
    		'pswd'=>DB_PSWD,
    		'db'=>DB_DB,
    		'status'=>true
    	);
    	public $caching = array(
    		'on'=>false,
    		'time'=>'',
    		'cache_path'=>'/db_query_cache/'
    	);
    	public $tbl;
    	private $queryCount = 0;
    
    	function __construct($wtbl='') {
    		if(@mysql_connect($this->db['host'],$this->db['user'],$this->db['pswd'])) {
    			mysql_select_db($this->db['db']);
    			$this->tbl = $wtbl;
    		} else {
    			$this->db['status'] = false;
    		}
    	}
    	
    	function tbl($tbl) {
    		$this->tbl = $tbl;
    		return $this;
    	}
    	
    	function cache($cache_time=3600) {
    		// Tell the code to cache the query
    		// It will be set to false after the query execution
    		$this->caching['on'] = true;
    		$this->caching['time'] = $cache_time;
    		return $this;
    	}
    	
    	function cacheActions($query) {
    		$this->caching['on'] = false;
    		$cache_file = realpath('.').$this->caching['cache_path'].md5($query).'.txt';
    		
    		if(file_exists($cache_file)) {
    			// If the cache exists, lets see if we must delete it
    			if((time()-filemtime($cache_file))>=$this->caching['time']) {
    				unlink($cache_file);
    				// Creating a new one with the results
    				$results = $this->cache_query($query);
    				file_put_contents($cache_file,serialize($results));
    				// Returning the results
    				return $results;
    			} else {
    				// If we're not deleting it, we're using it
    				return unserialize(file_get_contents($cache_file));
    			}
    		} else {
    			// Creating a new one with the results
    			$results = $this->cache_query($query);
    			file_put_contents($cache_file,serialize($results));
    			// Return the results
    			return $results;
    		}
    	}
    	
    	function cache_query($query) {
    		$result = mysql_query($query);
    		$results = array();
    		while($row = mysql_fetch_assoc($result)) { $results[] = $row; }
    		return $results;
    	}
    	
    	function find($arg='',$params=array()) {
    		++$this->queryCount;
    		// If we don't have a table, return false;
    		if($this->tbl=='') return false;
    		// If we didn't specify the fields, get all.
    		$fields = (isset($params['fields'])) ? $params['fields'] : '*';
    		if(is_integer($arg)||ereg('^[0-9]+$',$arg)) {
    			// If is integer or a numeric string, look for a result by its ID
    			return mysql_fetch_assoc(mysql_query('select '.$fields.' from '.$this->tbl." where id='$arg'"));
    		} else {
    			// If isn't a integer, select all row with $params parameters or not.
    			$query_params = '';
    			if(is_array($params)) {
    				// The query's params var
    				// Handle each one of $params options
    				$query_params .= (isset($params['where'])&&strlen($params['where'])>1) ? ' where '.$params['where'] : '';
    				$query_params .= (isset($params['group'])) ? ' group by'.$params['group'] : '';
    				$query_params .= (isset($params['order'])) ? ' order by '.$params['order'] : '';
    				$query_params .= (isset($params['limit'])) ? ' limit '.((isset($params['offset'])) ? $params['offset'].',' : '').$params['limit'] : '';
    			}
    			$query = 'select '.$fields.' from '.$this->tbl.$query_params;
    			if($this->caching['on']) {
    				return $this->cacheActions($query);
    			} else {
    				$result = mysql_query($query);
    				$results = array();
    				while($row = mysql_fetch_assoc($result)) { $results[] = $row; }
    				return $results;
    			}
    		}
    	}
    	
    	function query($query) {
    		$result = mysql_query($query);
    		$results = array();
    		while($row = mysql_fetch_assoc($result)) { $results[] = $row; }
    		return $results;
    	}
    	
    	function add($args) {
    		$args = func_get_args();
    		$values = array();
    		foreach($args as $value) {
    			$values[] = "'".$this->escp($value)."'";
    		}
    		return mysql_query('insert into '.$this->tbl.' values('.join(',',$values).')');
    	}
    	
    	function update($fields='',$condition) {
    		if(!is_array($fields)||$this->tbl=='') return false;
    		$values = array();
    		foreach($fields as $field=>$value) {
    			$values[] = $field."='".mysql_real_escape_string($value)."'";
    		}
    		$values = join(',',$values);
    		return mysql_query('update '.$this->tbl.' set '.$values.' where '.$condition);
    	}
    	
    	function del($conditions='') {
    		if($this->tbl=='') return false;
    		$conditions = ($conditions!='') ? ' where '.$conditions : '';
    		return mysql_query('delete from '.$this->tbl.$conditions);
    	}
    	
    	function escp($what) {
    		return mysql_real_escape_string($what);
    	}
    	
    	function get_increment($table='') {
    		$table = ($this->tbl=='') ? $table : $this->tbl;
    		if($table=='') return false;
    		$query = mysql_fetch_assoc(mysql_query('show table status from '.$this->db['db']." where name='$table'"));
    		return $query['Auto_increment'];
    	}
    	
    	function ar($is_update=false) {
    		if(!$is_update) {
    			return mysql_affected_rows();
    		} else {
    			$ar = (preg_match('/Rows matched: ([0-9]+)/',mysql_info(),$matches)) ? $matches[1] : 0;
    			return $ar;
    		}
    	}
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by shinobiesdf on Aug 16, 2009 at 2:44 a.m. EDT
  • JavaScript adds classes to BODY based on URL
    function setBodyClass() {
    	var url = new String(window.location.pathname),
    		dirs = url.split('/'),
    		classes = ' home';
    
    	if (dirs) {
    		classes = '';
    		for (i = 0; i < dirs.length; i++) {
    			var dir = dirs[i].split('.'); // removes file extentions
    			
    			if (dir[0]) {
    				classes += ' ';
    				classes += dir[0].toLowerCase();
    			}
    		}
    	}
    	// check if body has an existing class
    	if (!document.body.className) {
    		document.body.className = classes;
    	} else {
    		var newClassName = document.body.className;
    		newClassName += classes;
    		document.body.className = newClassName;
    	}
    }
    

    copy | embed

    0 comments - tagged in  posted by mountainash on May 21, 2009 at 10:05 a.m. EDT
  • Session Helper class
    <?php
    
    // Example of usage below the code
    
    class Session {
    
    	// To permit the same session var being accessed
    	// more than once at same time on different places.
    	var $prefix;
    
    	function Session() {
    		session_start();
    		$this->prefix = $_SERVER['HTTP_HOST'];
    		
    		if($this->get('flash')) {
    			foreach($_SESSION[$this->prefix]['flash'] as $name=>$vals) {
    				++$_SESSION[$this->prefix]['flash'][$name]['counter'];
    				if($_SESSION[$this->prefix]['flash'][$name]['counter']>1) {
    					unset($_SESSION[$this->prefix]['flash'][$name]);
    				}
    			}
    		}
    	}
    	
    	function get($session_var) {
    		return ((isset($_SESSION[$this->prefix][$session_var])) ? $_SESSION[$this->prefix][$session_var] : false);
    	}
    	
    	function get_cookie($cookie_name) {
    		return ((isset($_COOKIE[$cookie_name])) ? $_COOKIE[$cookie_name] : false);
    	}
    	
    	function set($session_var,$value) {
    		$_SESSION[$this->prefix][$session_var] = $value;
    	}
    	
    	function set_cookie($cookie_name,$value) {
    		setcookie($cookie_name,$value,time()+3600*24,'/');
    	}
    	
    	function del() {
    		$session_vars = func_get_args();
    		foreach($session_vars as $session_var) {
    			if($this->get($session_var)||is_array($this->get($session_var))) {
    				unset($_SESSION[$this->prefix][$session_var]);
    			}
    		}
    	}
    	
    	function del_cookie() {
    		$cookies = func_get_args();
    		foreach($cookies as $cookie) {
    			if($this->get_cookie($cookie)) {
    				setcookie($cookie,'del',time()-3600,'/');
    			}
    		}
    	}
    	
    	function flash($flash_var,$value) {
    		$_SESSION[$this->prefix]['flash'][$flash_var] = array('val'=>$value,'counter'=>0);
    	}
    	
    	function get_flash($flash_var) {
    		return ((isset($_SESSION[$this->prefix]['flash'][$flash_var]['val'])) ? $_SESSION[$this->prefix]['flash'][$flash_var]['val'] : false);
    	}
    
    }
    
    // USAGE EXAMPLES
    // First, obviously, we must instanciate the class
    // I like to name my var $Session, but it could be shorter like $S.
    $Session = new Session();
    
    // Performing basic $_SESSION operations:
    // Setting a $_SESSION var
    $Session->set('varname','value');
    // It's the same as $_SESSION['varname'] = 'value'
    
    // Retrieving a $_SESSION var's value
    $Session->get('varname');
    
    // Deleting a $_SESSION var
    // Accept multiple arguments
    $Session->del('varname','varname2','varname3');
    
    // Now, about the function FLASH
    // It sets a $_SESSION var that will last only the next HTTP request
    // It's useful to define error messages for forms
    // Example: we have a page form.php and process.php where this last
    // will manipulate data sended by form.php
    
    // PROCESS.PHP
    if($_POST['name']=="") {
      $Session->flash('error','Sorry, you must enter a name');
      header('location: form.php');
    }
    
    // FORM.PHP
    if($Session->get_flash('error')) {
      echo $Session->get_flash('error');
      // This would display "Sorry, you must enter a name"
    }
    
    // About the COOKIES funcions:
    // They works like the session functions, changing only its names: set_cookie() and del_cookie()(this one accept multiple args as well)
    ?>
    

    copy | embed

    2 comments - tagged in  posted by shinobiesdf on Mar 28, 2009 at 11:08 p.m. EDT
  • Database Helper class
    <?php
    // Examples of how to use below, after the class code.
    
    class Database {
    
    	var $QueryCount = 0;
    	
    	function Database() {
    		mysql_connect(DB_HOST,DB_USER,DB_PSWD);
    		mysql_select_db(DB_DB);
    	}
    	
    	function query($query) {
    		++$this->QueryCount;
    		return mysql_query($query);
    	}
    	
    	function select($table,$data='',$addOn='') {
    		++$this->QueryCount;
    		$data = ($data=='') ? '*' : $data;
    		return mysql_query("select $data from $table $addOn");
    	}
    	
    	function insert($table,$where,$data,$debug=false) {
    		$data = (!preg_match('/^\'[^\']*\'/',$data)) ? "'".$data."'": $data;
    		if($debug==false) {
    			return mysql_query("insert into ".$table.$where." values($data)");
    		} else {
    			echo "insert into ".$table.$where." values($data)";
    		}
    	}
    	
    	function update($table,$what,$where) {
    		return mysql_query("update $table set $what where $where");
    	}
    	
    	function delete($table,$id='') {
    		$id = ($id=='') ? '' : "where $id";
    		return mysql_query("delete from $table $id");
    	}
    	
    	function fobject($result) {
    		return mysql_fetch_object($result);
    	}
    	
    	function assoc($result) {
    		return mysql_fetch_assoc($result);
    	}
    	
    	function farray($result) {
    		return mysql_fetch_array($result,MYSQL_NUM);
    	}
    	
    	function nr($result) {
    		return mysql_num_rows($result);
    	}
    	
    	function ar($is_update=false) {
    		if($is_update==false) {
    			return mysql_affected_rows();
    		} else {
    			preg_match('/Rows matched: ([0-9]+)/',mysql_info(),$matched);
    			$ar = (int) $matched[1];
    			return $ar;
    		}
    	}
    	
    	function totalQueries() { return $this->QueryCount; }
    	
    	function get_increment($table) {
    		$query = mysql_fetch_assoc(mysql_query('show table status from '.DB_DB." where name='$table'"));
    		return $query['Auto_increment'];
    	}
    	
    	function close() { mysql_close(); }
    	
    }
    
    // Example of usage //
    
    // Connecting
    // On this example, I'm using constants just because I was using this class within an app.
    define('DB_HOST','localhost');
    define('DB_USER','root');
    define('DB_PSWD','pswd');
    define('DB_DB','posts');
    
    $Db = new Database();
    
    // Inserting a post in table 'posts' with 3 fields/columns: author,title,text
    // Note that third parameter is optional if the second is already in correct column order
    $Db->insert('posts',"'Shino','First post','First post text'","'author','title','text'");
    
    // If we had a field 'id' as a primary key and first field/column we would want to get the auto_increment before iserting
    $new_post_id = $Db->getIncrement('posts');
    $Db->insert('posts',"'".$new_post_id."','Shino','Second post','Second post text'");
    
    // Retrieving posts list
    $posts = $Db->select('posts','title,text,author',"where author='Shino'");
    // We could do the following too:
    // $Db->select('posts','',"where author='Shino'");
    // Ommiting the second parameter is the same as '*'
    
    while($post = $Db->assoc($posts)) {
      echo '<h1>'.$post['title'].'</h1>';
      echo '<h3>'.$post['author'].'</h3>';
      echo '<p>'.$post['text'].'</p>';
    }
    echo '<strong>Articles found: '.$Db->nr($posts).'</strong>';
    
    // Updating post
    $Db->update('posts',"author='Dee'","id='10'");
    // Number of posts updated
    // We set the parameter to true indicating that it is a update query's result.
    // We do this because if you accidentaly don't alter anything, for MySQL, it won't look like a update, and the affected_rows will be 0.
    echo $Db->ar(true).' posts updated';
    
    // Deleting posts with author 'Shino'
    $Db->delete('posts',"author='Shino'");
    // Number of posts deleted
    echo $Db->ar().' posts deleted';
    
    // Number of queries executed by query() or select() on this page
    echo $Db->totalQueries();
    
    ?>
    

    copy | embed

    6 comments - tagged in  posted by shinobiesdf on Mar 27, 2009 at 5:48 a.m. EDT
  • Overloading constructor #2
    #include <iostream>
    using namespace std;
    
    class Obj
    {
    private:
    	int a;
    	double b;
    public:
    	Obj(int a, double b);
    	Obj(int a);
    	Obj();
    	~Obj();
    };
    
    Obj::Obj()
    {
    	this->a = 1;
    	this->b = 1.0;
    	cerr << "Obj(): " << this->a << " " << this->b << endl;
    }
    
    Obj::Obj(int a)
    {
    	this->a = a;
    	this->b = 1.0;
    	cerr << "Obj(a): " << this->a << " " << this->b << endl;
    }
    
    Obj::Obj(int a, double b)
    {
    	this->a = a;
    	this->b = b;
    	cerr << "Obj(a,b): " << this->a << " " << this->b << endl;
    }
    
    Obj::~Obj()
    {
    	cerr << "Destructor loaded" << endl;
    }
    
    int main(int argc, char **argv)
    {
    	cerr << "obiekt_a --- ";
    	Obj obiekt_a;
    	
    	cerr << "obiekt_b --- ";
    	Obj obiekt_b(2);
    	
    	cerr << "obiekt_c --- ";
    	Obj obiekt_c(2,3.0);
    	
    	return 0;
    }
    

    copy | embed

    0 comments - tagged in  posted by tiraeth on Mar 08, 2009 at 6:03 a.m. EDT
Sign up to create your own snipts, or login.