Archive of ‘programming magic’ category

Iterations in Less

Part of the beauty of Less and other CSS ‘compilers’ is to enable the author to automate tedious functions that normally must be coded by hand.

Cut Copy Paste

Cut Copy Paste (Photo credit: arthit)

Suppose you needed several classes that specified padding/margins:

.mRight50{margin-right:50px}
.mLeft50{margin-left:50px}
.pRight50{padding-right:50px}
.pLeft50{padding-left:50px}
.mRight25{margin-right:25px}
.mLeft25{margin-left:25px}
.pRight25{padding-right:25px}
.pLeft25{padding-left:25px}

No big deal, right? It wouldn’t take that long to type in; just cut and paste a bit.

Well, what if you needed them from 0-100 by 5s? (Never mind WHY you’d want to do this; this is a simple example.)

.mRight100{margin-right:100px}
.mLeft100{margin-left:100px}
.pRight100{padding-right:100px}
.pLeft100{padding-left:100px}
.mRight95{margin-right:95px}
.mLeft95{margin-left:95px}
.pRight95{padding-right:95px}
.pLeft95{padding-left:95px}
.mRight90{margin-right:90px}
.mLeft90{margin-left:90px}
.pRight90{padding-right:90px}
.pLeft90{padding-left:90px}
.mRight85{margin-right:85px}
.mLeft85{margin-left:85px}
.pRight85{padding-right:85px}
.pLeft85{padding-left:85px}
.mRight80{margin-right:80px}
.mLeft80{margin-left:80px}
.pRight80{padding-right:80px}
.pLeft80{padding-left:80px}
.mRight75{margin-right:75px}
.mLeft75{margin-left:75px}
.pRight75{padding-right:75px}
.pLeft75{padding-left:75px}
.mRight70{margin-right:70px}
.mLeft70{margin-left:70px}
.pRight70{padding-right:70px}
.pLeft70{padding-left:70px}
.mRight65{margin-right:65px}
.mLeft65{margin-left:65px}
.pRight65{padding-right:65px}
.pLeft65{padding-left:65px}
.mRight60{margin-right:60px}
.mLeft60{margin-left:60px}
.pRight60{padding-right:60px}
.pLeft60{padding-left:60px}
.mRight55{margin-right:55px}
.mLeft55{margin-left:55px}
.pRight55{padding-right:55px}
.pLeft55{padding-left:55px}
...

Ugh.

There’s a better way:


@steps: 100;

// Main Loop
.sidesX( @index ) when ( @index > 0 ) {
 (~".mRight@{index}") { .mRightX(@index); }
 (~".mLeft@{index}") { .mLeftX(@index); }
 (~".pRight@{index}") { .pRightX(@index); }
 (~".pLeft@{index}") { .pLeftX(@index); }

 .sidesX(@index - 5);
}

// End iteration at index zero
.sidesX( 0 ) {}<

// Individual class rendering
.mRightX( @offsetsize ) {
  margin-right: (~"@{offsetsize}px");
}
.mLeftX( @offsetsize ) {
 margin-left: (~"@{offsetsize}px");
}
.pRightX( @offsetsize ) {
 padding-right: (~"@{offsetsize}px");
}
.pLeftX( @offsetsize ) {
 padding-left: (~"@{offsetsize}px");
}

// Generate the CSS
.sidesX( @steps );
Enhanced by Zemanta

Regular Expressions Roundup

Writing some Regular Expressions?

Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
—Jamie Zawinski

Well, not really. There are some cases where using a Regular Expression—RegEx— instead of a heap of convoluted if statements just makes sense from both a lazy and practical standpoint.

When you’re knee-deep in writing your RegEx, you’ll need to test. My favorite RegEx ‘workbench’ is Oliver Steele’s “reWork.”

screenshot of reWork

To get a jumpstart on writing complex RegEx,  check out the Regular Expression Library, which contains a plethora of user-submitted RegEx recipes. Some of them are quite good (check each recipe’s rating).

screenshot of example page

Enhanced by Zemanta

Find Something You Like and Dissect It

Image representing Wikipedia as depicted in Cr...

Image via CrunchBase

I’m always on the lookout for a new technique or Better Mousetrap. I admit I don’t know all that much, so I’m happy to learn.

I was playing around with Wikify @ appointment.net (a nifty tool that goes through a block of text and ‘wikifies’ it–that is, links all the words it can find to relavant Wikipedia articles) when I noticed the behavior seemed rather…odd. I could see it go through the word list as it created links, and every time it linked up a word, every duplicate word was linked.

Let’s take some example text (from the now-defunct Dilbert Mission Statement Generator) and run it through the site:

“We have committed to synergistically fashion high-quality products so that we may collaboratively provide access to inexpensive leadership skills in order to solve business problems

Our mission is to continually leverage existing seven-habits-conforming catalysts for change as well as to competently leverage other’s error-free materials.

We globally leverage other’s professional meta-services as well as to conveniently integrate competitive solutions in order to solve business problems.

“It is our job to continually foster world-class infrastructures as well as to quickly create principle-centered sources to meet our customers needs

“Our challenge is to assertively network economically sound methods of empowerment so that we may continually negotiate performance based infrastructures

For example, the additional instances of “leverage,” “problems,” and “business” were quickly linked, once the first one was completed. Poking around their code, I noticed all the action takes place in wikify.js. There are a few gems in there. For example, the function call to reduce an array to only unique values:

function array_unique( array ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      input by: duncan
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nate
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Michael Grier
  // %          note 1: the second argument, sort_flags is not implemented
    // *     example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
    // *     returns 1: ['Kevin','van','Zonneveld']
    // *     example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'});
    // *     returns 2: {'a': 'green', 0: 'red', 1: 'blue'}

    var key = '', tmp_arr1 = {}, tmp_arr2 = [];
    var val = '';
    tmp_arr1 = array;

    var __array_search = function (needle, haystack) {
        var fkey = '';
        for (fkey in haystack) {
            if ((haystack[fkey] + '') === (needle + '')) {
                return fkey;
            }
        }
        return false;
    };

    for (key in tmp_arr1) {
        val = tmp_arr1[key];
        if (false === __array_search(val, tmp_arr2)) {
            tmp_arr2[key] = val;
        }
        delete tmp_arr1[key];
    }
    return tmp_arr2;
}

Aha! See how that works?

Enhanced by Zemanta

Wicked Cool FizzBuzz in Perl

Stack_Overflow_website_logo

The FizzBuzz problem is a simple coding demonstration to write an application in any language that counts from 1 to 100:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

I found the following on Stackprinter (deleted Stackoverflow questions) by  “ysth”; probably the best example of wicked-cool code obsfucation, ever.

(                       (
''))=~('('.'?'.'{'.("`"|
'%').('['^'-').('`'|'!').
('`'|',').'"'.('['^'+').(
         ((            (
         (             ((
         (             ((
         '['         ))))
          )))))^(')')).(
           '`'|")").(
         (              (
         '`'))|'.').('['^
         '/').'+'.('(').(
         '`'^'&').(('`')|
                     ((
                      ((
                    ')'))
                   ))).+(
                   "["^

         (              (
         '!'))).('['^'!')    .')'
         .'['.''.('$').    '_'.
         '%'.('^'^(('`')|     ((
         (              (
         '-')))))).(']').
         '.'.'('.('`'^'"'
         ).('['^'.').('['
                       ^
                       ((
                       ((
         '!'))))).(('[')^
         '!').')'.('[').
         ''.'$'.'_'
                        .
            '%'.('^'^('`'|'+'
         )).']'.'|'.'|'.''.
         '$'.'_'.','.''.'$'
         .+             (
         ((
           (
                  (
                  (
                  (
                  (
            '/')))))))).(
                  (
                  (
                  (
                   '`')))|
              '&').('`'|"/").(
           '['^')').('{'^'[').('^'
         ^('`'|'/'         )).".".
         ((                      '.'

         )                         )
         .                         (
         '^'^('`'|'/')).('^'^(('`')|
         '.')).('^'^('`'|'.')).('!'^
         (              (          (
         (              (          (
                        (          (
                        (          (
                       '+'         )
                      )))))        )
                                   )
                                  ))
                               ).'"'

         .              (
         '}').')');$:='.'    ^'~'
         ;$~='@'|"(";$^=    ')'^
         '[';$/='`'|".";     $,
                     ='('
         ^+           '}'
         ;($)         =(
         ('`'))|        (
         (  "!"));     (
         (    $:))=')'  ^
         (       '}');$~=
         (          '*')|
         ((            ((
         '`')
                     )));
         $^           =((
         '+'))         ^+
         '_';$/=        (
         (  "&"))|     (
         (    '@'));$,  =
         (       '[')&'~'
         ;          ($)=
         ((            ((
         ',')

         )))^                   '|';
         $:=('.')^         "~";$~=
           '@'|'(';$^=')'^"[";$/=
               '`'|'.';$,='('

                   ^'}';$
              ='`'|'!';$:=")"^
           '}';$~='*'|'`';$^="+"^
         ('_');$/=         '&'|'@';
         $,                      =((

           (             "[")))&
          ((           ('~')));$=
         ((           ','))^    '|'
         ;           ($:)=        ((
        '.'))^'~';$~='@'|'(';$^=")"^
         (          '[');          (
         (          $/))=          (
        '`')|'.';$,='('^'}';$=('`')|
         ((        '!')            )
         ;$:=    (')')^           (
           ('}'));$~=            (

         (
         (
         (
         (
         (
         (
         (
         (

         (                     ((
         '*')                ))  ))
            )))             )      )
               ))|          (      (
                   '`'       ));$^=
           '+'       ^((
         ((   ((        '_'
         )                  )))
         )     )              ;$/
          ='&'|                  '@'

          ;$,                    =
         '['                     &+
         ((                       ((
         (                         (
         (                         (
         (             ((          (
         '~'         ))))))      )))
         )));(    ($))  =','^"|";
          $:='.'^"~";    $~="@"|
            "(";$^=

         ')'^                   '[';
         $/=('`')|         ".";$,=
           '('^'}';$='`'|"!";$:=
               ')'^'}';$~='*'

          |+
         '`';
         ($^)

                   =('+')^
              '_';$/='&'|'@';$,
           ='['&'~';$=','^'|';$:=
         '.'^"~";         $~="@"|
         ((                      '('

         )                         )
         ;                         (
         $^)=')'^'[';$/='`'|".";$,=
         '('^'}';$='`'|'!';$:=")"^
         (              (          (
         (              (          (
         (              (          (
         (              (          (
         (             '}'        ))
         ))           ))))       )))
         ));(       $~)= '*'|'`';$^
          ='+'^"_";$/=   '&'|'@';
            $,='['&'~'      ;$=
              ","^
                        (
           '|');$:=('.')^
         '~';$~='@'|"(";
         $^=')'^('[');$/=
         ((
         ((
          (
         '`')))))|'.';$,=
         '('^'}';$="`"|
         '!';$:=')'^"}";
                     ($~)
         =(           '*'
         )|'`'         ;(
         $^)='+'        ^
         (  '_');$/     =
         (    '&')|'@'  ;
         (       $,)='['&
         (          '~');
         $            =(
         ',')
                     ^'|'
         ;(           $:)
         ='.'^         ((
         "~"));        (
         (  ($~)))=     (
         (    ('@')))|  (
         (       '('));$^
         =          ")"^
         ((            ((
         '[')

         )));                   ($/)
         ='`'|'.';         $,="("^
           '}';$='`'|'!';$:=")"^
               '}';$~='*'|'`'

                   ;$^='+'
              ^'_';$/='&'|"@";
           $,='['&'~';$=','^"|";
         $:=('.')^         "~";$~=
         ((                      '@'

           )             )|'(';$^
          =(           ')')^'[';$/
         =(           "`")|    '.'
         ;           ($,)=        ((
        '('))^'}';$='`'|'!';$:=")"^
         (          '}');          (
         (          $~))=          (
        '*')|'`';$^='+'^'_';$/=('&')|
         ((        '@')            )
         ;$,=    ('[')&           (
           ('~'));$=            (

         (
         (
         (
         (
         (
         (
         (
         (

         (                     ((
         ',')                ))  ))
            )))             )      )
               ))^          (      (
                   '|'       ));$:=
           '.'       ^((
         ((   ((        '~'
         )                  )))
         )     )              ;$~
          ='@'|                  '('

          ;(           ($^))=
         ((             (  (')'))))^
         (              ((      '[')
         )              );      ($/)
         =              ((      '`')
         )|            '.'      ;$,=
         "("^      '}';$      ='`'
          |'!';$:=')'^'}'       ;$~=
            '*'|'`';$^=         '+'^

         '_';                   ($/)
         ='&'|'@';         $,="["&
           '~';$=','^'|';$:="."^
               '~';$~='@'|'('

          ;(               ($^))=
         ')'^   '[';$/='`'|('.');$,=
         '('^      '}';$='`'|"!";

          $:               =")"^
         '}';   $~='*'|'`';$^=('+')^
         '_';      $/='&'|('@');$,=

           (             '[')&'~'
          ;(           $)=','^'|'
         ;(           ($:))=    '.'
         ^           "~";        $~
        ='@'|'(';$^=')'^'[';$/=('`')|
         (          '.');          (
         (          $,))=          (
        '(')^'}';$='`'|'!';$:=(')')^
         ((        '}')            )
         ;$~=    ('*')|           (
           ('`'));$^=            (

         (
         (
         (
         (
         (
         (
         (
         (

          ((
         '+')
       ))))))

           )             )))^'_';
          $/           ='&'|'@';$,
         =(           "[")&    '~'
         ;           ($)=        ((
        ','))^'|';$:='.'^'~';$~="@"|
         (          '(');          (
         (          $^))=          (
        ')')^'[';$/='`'|'.';$,=('(')^
         ((        '}')            )
         ;$=    ('`')|           (
           ('!'));$:=            (

         (
         ')')
            )^+
               '}'
                   ;$~
                     =((
                        '*'
                            ))|
                              '`'
                                 ;$^
                        =
         '+'^'_';$/='&'|"@";$,=
         '['&'~';$=','^'|';$:='.'^
         '~';$~='@'|'(';$^=')'^"[";
                        (      $/  )
                        =     ('`')|
                              ".";
              ($,)=
           '('^'}';$=
          '`'|'!';$:=')'
         ^+           ((
         (              (
         (              (
         (             ((
         '}')       ))))
           ))));$~='*'|
             "`";$^=
         (              (
         '+'))^'_';$/='&'
         |'@';$,='['&'~';
         $=','^('|');$:=
                     ((
                      ((
                    '.'))
                   ))^'~'
                   ;($~)

         =
         (                    (
         '@'))|'(';$^=')'^'[';$/=
         '`'|'.';$,='('^'}';$='`'
         |
         (
          ((
         '!')
         ));(

          $:
         )=((
         ')')

         )
         ^                    (
         '}');$~='*'|'`';$^="+"^
         '_';$/='&'|'@';$,='['&'~'
         ;
         (
                  $)=","^
             '|';$:='.'^'~';$~=
           '@'|'(';$^=')'^'[';$/=
          "`"|               ".";
         $,                       =(
         (                         (
         (                         (
         ((                      '('
          )))))               ))^((
           '}'));$='`'|('!');$:=
              ')'^'}';$~="*"|

                  ('`');$^=
             '+'^'_';$/='&'|'@'
           ;$,='['&'~';$=','^'|'
          ;($:)               ='.'^
         ((                       ((
         (                         (
         (                         (
         ((                      '~'
          )))))               )))))
           ;$~='@'|'(';$^=')'^'['
              ;$/='`'|".";#;#

Save the above Asciiart into a file called, for example, fizz.pl.

Then run it: perl fizz.pl

Enhanced by Zemanta