Code Share - Page 4
Page 4 of 8 FirstFirst ... 23456 ... LastLast
Results 46 to 60 of 109

Thread: Code Share

  1. #46
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    8,546
    Here's the actual app.
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  2. #47
    Senior Member
    Join Date
    Jun 2003
    Location
    Charlottesville
    Posts
    208
    I think it's time for me to share some code again:

    Coin flip simulator:

    PHP Code:
    <?php
    $tf 
    = array('T','H');
    $dubTails=0;
    $oneEach=0;
    $dubHeads=0;
    for(
    $i=0$i<=99$i++){
        
    $curFlip1 $tf[rand(0,1)];
        
    $curFlip2 $tf[rand(0,1)];
        if(
    $curFlip1 == "T" && $curFlip2 == "T"){
            
    $dubTails $dubTails 1;
        } elseif(
    $curFlip1 == "H" && $curFlip2 == "T" || $curFlip1 == "T" && $curFlip2 == "H"){
            
    $oneEach$oneEach 1;
        } elseif(
    $curFlip1 == "H" && $curFlip2 == "H"){
            
    $dubHeads$dubHeads 1;
        }
    }
    echo 
    "Double Tails: ".$dubTails."<br /> \r\n Heads and Tails: ".$oneEach."<br /> \r\n Double Heads: ".$dubHeads;
    ?>

  3. #48
    Computers can do that? drawmack's Avatar
    Join Date
    Apr 2003
    Location
    Pocono Mtns PA
    Posts
    3,265
    Here is a little function that will find all the prime numbers less then a specified number. It is a useful function for encryption.
    PHP Code:
    function primes($n) {
        
    $calc = array(1,2);
        for(
    $i=3;$i<$n;$i+=2) {
            
    $exists FALSE;
            for(
    $j=1;$j<count($calc);$j++) {
                if(
    $i%$calc[$j] == 0)
                    
    $exists TRUE;
            } 
    //end for
            
    if(!$exists)
                
    $calc[] = $i;
        } 
    //end for
        
        
    return $calc;
    //end primes 
    Let’s take a look into the code and see what it is doing mmkay.

    $calc = array(1,2) – We already know that 1 and 2 are primes of everything larger and we assume the user isn’t trying to find the primes for either of those numbers so we include them in the return value without any checking.

    for($i=3;$i<$n;$i+=2) – here we use some more human logic to speed up the algorithm. This loop does not even look at even numbers because we already know they are not primes.

    if($i%$calc[$j] == 0) – this checks to see if the current number is a multiple of any number already in the $calc array. However being inside a loop that starts at 1 it will avoid checking against 1 because the answer to that is always true and by definition a prime must have two devisors 1 and itself.

    Oh and just for a mental exercise here is Euclid’s algorithm in one line.
    PHP Code:
    function gcd($a,$b) {
        return (
    == ($a%$b)) ? $b gcd($b,($a%$b));
    //end gcd 
    Note: there is no error checking on this function and it assumes the initial parameters to meet the criteria of $a<=$b

  4. #49
    Computers can do that? drawmack's Avatar
    Join Date
    Apr 2003
    Location
    Pocono Mtns PA
    Posts
    3,265
    Well if you're anything like me then doing the same thing over and over again bores you. So I got bored with revalidating my pages for the smallest html changes, cause we all know the time you think "That's too simple to mess up" is the time you'll mess it up. So I wrote this little function which dynamically displays the valid image at the bottom of the page. This way I only have to revalidate when the html comes up not valid.
    PHP Code:
    <?php
    function check_html_compliance($url) {
        
    $query_string '';
        foreach(
    $_GET as $key => $val)
            
    $query_string .= '&' $key '=' $val;
        if(
    $query_string != '') {
            
    $query_string substr($query_string,1);
            
    $referer $url '?' $query_string;
        } else
            
    $referer $url;
        
    $ch curl_init('http://validator.w3.org/check?uri=referer');
        
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        
    curl_setopt($ch,CURLOPT_REFERER,$referer);
        
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        
    curl_setopt($ch,CURLOPT_TIMEOUT,30);
        
    $output curl_exec($ch);
        
    curl_close($ch);
        
        if(
    eregi('This page is valid',$output)) {
            
    $start strpos($output,'&lt;p&gt;') + 9;
            
    $end strpos($output,'&lt;/p&gt;') - $start;
            
    $retval html_entity_decode(substr($output,$start,$end));
        } else {
            
    $retval 'Not Valid Code';
        }
        
        return 
    $retval;
    //end check_html_compliance
    ?>
    There is one small problem with this though. It sets off an infinite loop of validation. So you should call it with something like this
    PHP Code:
    <?php
    if(!eregi('^W3C_Validator',$_SERVER['HTTP_USER_AGENT'])) 
        echo 
    check_html_compliance($thisPage);
    ?>
    So that the function only runs when the page isn't being loaded by the validator.

    The if statement could be moved inside the function, but I didn't feel like it since all my pages are templated it's only one file per site that contains the call.

  5. #50
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    8,546

    Talking Be a "Guru Hacker", heh heh...

    I decided I wanted to be known as a "guru hacker', as described in the classic tale here (and indeed, all over the web)....

    So, here 'tis:
    PHP Code:
    <?php

    array_unshift
    ($argv"cat");
    $arguments=array();

    foreach (
    $argv as $ar) {
        if (
    $ar=="") {
            break;
        }
        elseif (
    $ar=="cat" || $ar==$_SERVER['PHP_SELF']) {
        } else {
            
    $arguments[]=$ar;
        }
    }

    $argstring=implode($arguments" ");

    if (
    $argstring=="") {
            echo 
    "Hello, World!\n";
    } else {
            
    system("cat $argstring");
    }
    ?>
    Now, just set up this shell alias ---
    Code:
    cat    "/usr/local/bin/php -q /path/to/the/above/script"
    --- and you too can be a "guru hacker".

    Best method: set this up on your friend's box and mail him saying, "I think you've been HaX0r3d!!"
    Last edited by dalecosp; 08-23-2004 at 01:48 PM.
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  6. #51
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Running Gear"
    Posts
    22,573

    Re: Be a "Guru Hacker", heh heh...

    Originally posted by dalecosp
    I decided I wanted to be known as a "guru hacker', as described in the classic tale here (and indeed, all over the web)....
    Why do I get the feeling that "Master Programmer" was bowdlerised from "Microsoft Programmer"?
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  7. #52
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    8,546

    Re: Re: Be a "Guru Hacker", heh heh...

    Originally posted by Weedpacket
    Why do I get the feeling that "Master Programmer" was bowdlerised from "Microsoft Programmer"?
    That was my impression, too; look at the symptoms; code bloat, overstructured, complex dependencies, etc. etc.

    That why I wanted to be a "Guru Hacker". Type your command, and it Does The Right Thing (TM). Seemed like the best of the best in the tradition
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  8. #53
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Running Gear"
    Posts
    22,573

    Had a need to syntax-check a buncha uploaded PHP files.

    Essentially:
    PHP Code:
    $code file_get_contents('file_to_test.php');
    $code str_replace("'""'\"'\"'",$code);
    $check = `echo '$code' | php -l`;
    echo 
    $check
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  9. #54
    Posts: 13
    Join Date
    Mar 2003
    Location
    Ewok Village (Wales) / Mos Ilford
    Posts
    1,593
    I knocked this up ages ago when I was still on dial up but still use it now.

    It caches pages from On The Box and localises all the links and pictures so I can have a look at the telly listings really quick. If you get pages for future days it'll still show you that page when it arrives.

    Useful if you live in Britain, and I'm sure it can be tacked onto somewhere else really easily.
    Not using [PHP] tags makes the baby jesus cry.
    The help of an enthusiastic idiot is worse than the sabotage of an expert.
    Don't be a PhPenis - RTFM - still stuck? Then go DAFT (Do A Fekkin Tutorial)

  10. #55
    WARNING: I am watching u! jayant's Avatar
    Join Date
    Aug 2002
    Location
    New Delhi, India
    Posts
    886
    Originally posted by drawmack
    for($j=1;$j<count($calc);$j++)
    Instead of using this as the statement for for loop using:

    $sqrt_of_n = sqrt($n);
    for($j=1;$j<count($calc)&&$calc[$j]<$sqrt_of_n;$j++)

    we only need to check with all primes less than the square root of the number to confirm whether the number is prime or not.
    Jayant Kumar Gandhi
    Computer Help | GZip/ Page Compression Test | My pic/ How I look?
    Marking the thread as 'resolved' is more important than saying "thanks. that solved it"
    Click "Mark Thread Resolved" in the thread tools and the top of the thread.
    Keep sensible thread titles.

  11. #56
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    8,546
    Hmm, I'd never even looked at drawmack's "primes" post. Probably 'cuz he'd put the "validator" one down so quickly after it, and I found the validator more interesting/pertinent at the time...

    Anyway, one of the coding contests we had $n months ago was on this subject, and there is plenty of discussion there. It was interesting --- for the limited subset of numbers we were using (3 second execution limit IIRC), it was actually quicker to do a rather simple loop of trial division than to use a more complex (read caching, for one) algorithm...IIRC, Weedpacket won that one (big surprise, that )
    Last edited by dalecosp; 11-08-2004 at 12:37 PM.
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  12. #57
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Running Gear"
    Posts
    22,573

    Overflow-resistant averages.

    Here's a nifty way of calculating the mean of an array of numbers that works
    even in cases where there are a LOT of large numbers (i.e., in situations where
    adding all the numbers together and then dividing can result in a loss of
    precision because the intermediate sum got too big).

    PHP Code:
    function mean($array)
    {
        
    $mean 0;
        for(
    $i=0,$c=count($array); $i<$c$i++)
            
    $mean += ($array[$i]-$mean)/($i+1);
        return 
    $mean;

    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  13. #58
    the stand in Telepath tekky's Avatar
    Join Date
    Jul 2003
    Location
    College Station, Texas
    Posts
    2,258
    Originally posted by benkillin
    I think it's time for me to share some code again:

    Coin flip simulator:
    just some optimizations ideas, nothing major

    PHP Code:
    <?php
    $tf 
    = array('T','H');
    $results = array(); //T = dubTails H=dubHeads and E=oneEach
    for($i=0$i<100$i++){// i seem to recall that <= is more intensive
        
    $curFlip1 $tf[rand(0,1)];
        
    $curFlip2 $tf[rand(0,1)];
        if(
    $curFlip1 == $curFlip2//why check twice?
            
    $results[$curFlip1]++; //take advantage of the increment operators and flip values to indice the results array
        
    else
                                    
    $results['E']++; //1 each
    }
    echo 
    'Double Tails: '.$results['T'].'<br /> \r\n Heads and Tails: '.$results['E'].'<br /> \r\n Double Heads: '.$results['H'];
    ?>
    just something I noticed could be improved a bit
    -Karl
    Problem solved? Mark your thread resolved!
    See how many times my link has been used to mark a thread resolved here
    (fixed to work with updated VBulletin... this works again!)

  14. #59
    the stand in Telepath tekky's Avatar
    Join Date
    Jul 2003
    Location
    College Station, Texas
    Posts
    2,258
    and to join in the contribution

    a function that would mimic the 'short story' function on blogs... but instead of always being degradative (is that a word?) and always removing words to meet or beat the limit imposed by $len, it will check the length of the next word and add it, if it will bring it closer to $len then dropping the previous word.
    this is based on len-current strlen < current strlen+nextwordlen-len = current result is closer

    ie.
    len=5
    'abc e f' would return 'abc e...'
    len=5
    'ab cdefghi' would return 'ab...' but (5-2=3,9-5=4)
    len=6 woule return 'ab cdefghi...' (6-2=4,9-6=3)

    The user that requested help with a function like this tested it on a fairly large DB he said and it wasnt slow at all, but I'm always open to suggestions that I've overlooked in speeding it up

    PHP Code:
    <?php
    function limit_char($str,$len)
    {
        
    //this will always return the first word at minimum
        
    $arr explode(' '$str);
        
    $cnt count($arr);
        
    $return '';
        if (
    $len strlen($str)) //if len is longer then str return full str
            
    return(trim($str));
        if (
    substr($str,$len,1) == ' ' || substr($str,$len+1,1) == ' '//simple check to see if len is at or just before a space
            
    return(trim(substr($str,0,$len+1)) . '...');
        
    //we dont do the opposite check for just after a space due to short words following the break
        
    for($i=0;$i<$cnt;$i++)
        {
            if (
    $i 0)
            {
                
    $wlen strlen($arr[$i]); //current word len
                
    $rlen strlen($return); //current return string length + 1 space
                
    if (($wlen+$rlen) > $len//next word puts us over the limit
                    
    if ($len $rlen $rlen+$wlen-$len//if current return closer to len then return+ next word..
                        
    return(trim($return) . '...');
                    else 
    //adding next word will be closer to len then the current return value
                        
    return($return $arr[$i] . '...');
                else
                    
    $return .= $arr[$i] . ' '//next word still under len, add it
                
    next;
            }
            else
            {
                
    $return .= $arr[$i] . ' ';
            }
            if (
    strlen($return) == $len || strlen($return) > $len//see if first word puts us at or above the limit
                
    return(trim($return) . '...');
        }
    }
    echo 
    'strlen=32<br />';
    for(
    $j=0;$j<32;$j++)
        echo 
    "len=$j " limit_char('abc def ghi jklmno pqr stu vwxyz',$j) . '<br />';
    ?>
    -Karl
    Problem solved? Mark your thread resolved!
    See how many times my link has been used to mark a thread resolved here
    (fixed to work with updated VBulletin... this works again!)

  15. #60
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Running Gear"
    Posts
    22,573

    Static initialisation without static initialisers.

    PHP doesn't have static initialisers for classes the way - for example - Java does. In fact, you can't even use a constant expression (not even 5+4) as a static initialiser. Literals and arrays of literals, that's pretty much your lot.

    But that's okay. PHP doesn't need them.
    PHP Code:
    class foo
    {
        private static 
    $one$two$three;

    public static function 
    static__construct()
    {
        static 
    $constructed false;
        if(
    $constructed) return;
        
    $constructed true;

        
    self::$one time();
        
    self::$two self::precompute_some_sort_of_table();
        
    self::$three self::$two[self::$one%42];
    }

    public function 
    __construct()
    {
        
    //....etc.
    }

    //......Yadayadayada.......

    // End of class. Unless you're on detention.
    foo::static__construct(); 
    (On a parenthetical note, I just realised today that "self" can be used within a class anywhere the class's name is used - it's not just for static method calls any more.
    PHP Code:
    static function splunge(self $beetroot)
    {
        
    $turnip = new self;
        
    $turnip->mash_with($beetroot);
        
    $vegie self::dig_something_up();
        if(
    $vegie instanceof self)
            echo 
    'Get all smug.';
        else
            throw new 
    wobbly("An Unexpected Error occurred.");
        return 
    $vegie->mash_with($turnip);

    This probably comes as no surprise to anyone, but frankly I blinked when I found it doing so eminently sensible. This can be evidence by my not doing it in my intervals class.)
    Last edited by Weedpacket; 04-21-2006 at 05:55 AM. Reason: self:$one, not $one
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •