Tuesday, December 18, 2012

Wednesday, December 12, 2012

Cross Browser Opacity Classes

These come in handy pretty often:

.no_opacity {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; /* IE 8 */
    filter: alpha(opacity=0); /* IE 5-7 */
    -moz-opacity: 0.0;  /* Netscape */
    -khtml-opacity: 0.0; /* Safari 1.x */
    opacity: 0.0; /* Good browsers */
}
.half_opacity {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; /* IE 8 */
    filter: alpha(opacity=50); /* IE 5-7 */
    -moz-opacity: 0.5;  /* Netscape */
    -khtml-opacity: 0.5; /* Safari 1.x */
    opacity: 0.5; /* Good browsers */
}
.full_opacity {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; /* IE 8 */
    filter: alpha(opacity=100); /* IE 5-7 */
    -moz-opacity: 1.0;  /* Netscape */
    -khtml-opacity: 1.0; /* Safari 1.x */
    opacity: 1.0; /* Good browsers */
}

Thursday, December 6, 2012

Installing Drupal Commons

Install xampp, or anything with Apache and MySQL

Create a database with any name for your Drupal Commons installation.

Get your download here:
https://network.acquia.com/downloads/drupal-commons

Extract these files, and move the resulting Drupal file directory structure into the web root, or any sub folder.

Configure a settings.php file from the example ( default.settings.php ) file provided.

Edit this line with your database information:
$db_url = 'mysql://username:password@localhost/databasename';

The simplest example ( only fun for a development site ) is:

$db_url = 'mysql://root@localhost/database_name';
Save settings.php

*** You will probably need to edit php.ini here to allow a maximum_execution longer than 30 seconds, this is a common fail. Try 300. Remember to restart Apache for the php.ini settings to take effect.

Use a web browser to execute the install.php file in the folder containing the installation.


Wednesday, November 28, 2012

Detecting character encoding in PHP

Dealing with character encoding is never fun. It's easy to know that something has gone wrong when text is displaying as hieroglyphics, but it can be difficult to figure out why.

I found myself in this position trying to fix some Japanese text the other day and wanted to write a short example of  mb_detect_encoding(); before I forget it.

<?php
// a list of possible encodings
$encodings = array('UTF-8','windows-1251','ISO-8859-1','ASCII','JIS','EUC-JP');

$string = "Example text";  // the text you wish to test
$in_encoding = mb_detect_encoding($string, $encodings, true);
echo "Encoding type: ".$in_encoding;
?>

 If you find that your encoding is something other than what you desire, you should check out iconv();

Thursday, November 8, 2012

Speed up your local Drupal development environment

A friend came across an interesting suggestion for speeding up the database interactions on my local development environment on this page: 

http://drupal.org/node/469086

Basically it's just some changes to mysql's my.ini configuration file:

innodb_buffer_pool_size = 1G
innodb_flush_log_at_trx_commit = 2
innodb_thread_concurrency=8
transaction-isolation=READ-COMMITTED


Then restart mysql.

The improvement will probably vary.

Wednesday, October 24, 2012

Packaging Drupal Rules into a Module

The Rules module comes with a nice Import/Export feature which makes it easy to move complicated sets of rules from one environment to another without a bunch of unnecessary re-configuration.  The simplest way is to simply copy the code out of the 'export' page ( an array ), and paste it into the 'Import' page on the target installation.

An even cooler way to move rules and be sure they're available to custom modules that depend on them is to include hook_rules_defaults() in your module code.

An example would look like this:

function hook_rules_defaults() {
   $rules = // paste the exported rules array here and add a ';' at the end of the array

   return $rules;
}

When the module is installed, so are the rules outlined in the array.

Friday, October 19, 2012

Drupal - Theming Views

http://pedroposada.com/blog/embed-views-2-nodes.html

methods available to a $view object:
http://drupalcontrib.org/api/drupal/contributions%21views%21includes%21view.inc/class/view/6

Registering template files in hook_theme():
        'views_view_table__map_requests__panel_pane_2' => array(
          'template' => 'views-view-table--map-requests--panel-pane-2',
          'path'  => drupal_get_path("module","maprequest") . '/themes',
        ),

Pass variables through to the template using:

function maprequest_theme_registry_alter (&$theme_registry) {
    {
    $tpl = $theme_registry['views_view_table'];
    $theme_registry['views_view_table__map_requests__panel_pane_2']['arguments'] = $tpl['arguments'];
    $theme_registry['views_view_table__map_requests__panel_pane_2']['preprocess functions'] = $tpl['preprocess functions'];
    } 
}

Friday, October 5, 2012

Nexus 7 - Setting up USB debugging

I recently bought a ASUS Nexus 7 tablet and I'm very pleased with it. I'm particularly happy that it came with Android 4.1 (Jellybean) because I'm interested in using it as a development device for web and apps.

I was excited to learn that by plugging my tablet into my computer I can get full access to Chrome developer tools. The setup was just a little more involved than I had planned.  It's hard to say if everyone will encounter these same hurdles, but the following sequence of events got mine working!

Setup Nexus 7 for Chrome USB debugging:

On Nexus 7:
- In Chrome settings, enable USB debugging
- In Device Settings -> Developer Options -> enable USB debugging
- Device Settings -> Storage -> Settings -> USB computer connection -> enable MTP

On PC:
- Plug in device
- Install Java JDK from oracle
- (optional) Download and install Eclipse Classic 4.2.1 or newer
- Install Android SDK
- Launch Android SDK Manager ( start as administrator! )
- Install Adroid 4.1, all tools, and the google usb driver

Download drivers from ASUS site:
- http://support.asus.com/Download.aspx?SLanguage=en&m=Nexus+7&p=20&s=16
- select the 'Global' download option ( middle of three )

In Windows device manager locate the Nexus 7 - generally under 'Other devices'
- 'Update Driver Software' -> browse to local copy of downloaded drivers & install
- Device should now be listed as an android phone

Check Device Connectivity:
- Open command prompt and change directory to C:\Program Files (x86)\Android\android-sdk\platform-tools  ( or the location of adb.exe )
- Execute command: 'adb devices' - the device should be listed. if not you have failed somewhere

Set up Chrome debugging:
- Execute:  'adb forward tcp:9222 localabstract:chrome_devtools_remote'
- Go to Chrome, navigate to localhost:9222 -> tabs on nexus chrome should be visible for debugging

And hopefully that will get you there...

Update:  If you're still having trouble, check that the 'USB Computer Connection' type is set to PTP.  This setting can be located in Settings -> Storage -> (menu) USB Computer Connection.

Thursday, September 13, 2012

Wednesday, September 12, 2012

jQuery.syntax()

I've been researching automated syntax hi-lighters and jQuery.syntax() is starting to look like a good option. Heck, it would even make this blog look better! Check it out:
http://www.oriontransfer.co.nz/projects/jquery-syntax/index.en

Tuesday, September 11, 2012

Send javascript variables from drupal module to js


    drupal_add_js(array('mymodule' => array(
        'username' => 'Anthony',
        'uid' => 123,
        'likes' => array('ice cream', 'peanuts', 'coffee'),
    )), 'setting');

Friday, August 31, 2012

jQuery has ruined my Javascript - here are some fallbacks

It's true. Using jQuery is likely to make you forget how to do fundamental things in javascript. Some people get all riled up about this because jQuery is just a library, meaning its only javascript anyway.  The way jQuery allows selectors to be written is reason enough to utilize it. Compare these examples:

A) $("#first_paragraph").text("Booya");
B) document.getElementbyId("first_paragraph").innerHTML = "Booya";

jQuery accomplishes the same thing in half as many characters.

There are times when a customer wants something written in pure javascript. I suppose they're trying to avoid licensing and compatibility issues that might come with using libraries.

Anyway, long story short, here are the javascript equivalents of some of my favorite jQuery functions:

// works like the $(".classname") selector
function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

// same as $.inArray()
function contains (needle,haystack) {
   for (var i=0; i < haystack.length; i++) {
      if (needle == haystack[i]) {
         return true;
      }
   }
   return false;
}

// counts the frequency of identical indices in an array
// I'm not sure if there is a jQuery equivalent of this but I love the function in PHP!
function arrayFreq(myArray) {
   var myBlocks = new Object ;

   for (var i=0; i<myArray.length; i++) {
      var aBlock = myArray[i] ;
      if (myBlocks.hasOwnProperty(aBlock)) {
         myBlocks[aBlock]++ ;
      } else {
         myBlocks[aBlock] = 1 ;
      }
   }
   return(myBlocks);
}

Thursday, August 23, 2012

CSS rounding X-Browser


I've probably visited this guy's site 40 times to get this syntax:
http://css-tricks.com/snippets/css/rounded-corners/  - and a great resources for all other things CSS.

"
Standard Rounding:
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px; /* future proofing */
-khtml-border-radius: 10px; /* for old Konqueror browsers */

Individual Corners:
-moz-border-radius-topleft: 10px;
-moz-border-radius-topright: 20px;
-moz-border-radius-bottomright: 30px;
-moz-border-radius-bottomleft: 0;

-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 20px;
-webkit-border-bottom-right-radius: 30px;
-webkit-border-bottom-left-radius: 0;
"

Tuesday, August 21, 2012

Javascript fallback for jQuery $.inArray

Sometimes, for whatever reason, someone doesn't want you to use jQuery.  It helps to know this from the beginning, so ask first.

Here is the javascript fallback for one of my favorite jQuery methods, $.inArray();

function contains (needle,haystack) {
   for (var i=0; i < haystack.length; i++) {
      if (needle == haystack[i]) {
         return true;
      }
   }
   return false;
}

Sending your two values, needle and haystack, to this function will return true on success ( the value is in the array ) or false if it is not.

Example

var favBeers = ["Laguinitas IPA", "Bear Republic Racer 5 IPA", "Deschutes Mirror Pond Pale Ale"];
var aBeer = "Corona";

if  (contains(aBeer, favBeers)) {
   //   nothing happens here because Corona sucks.
}

Tuesday, July 31, 2012

Referencing an array within an object with a $variable property name (PHP)

Whew. This took some research and about thirty minutes of banging my face against the keyboard...

In a Drupal module I'm developing I'm allowing the user to upload a .csv file, then I'm parsing the contents of each row into a property of an object. A brief example of the code looks like:

    $handle = fopen($file, "r");
   
    $csv_content = new stdClass();
    while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {           
            $csv_content->$data[0] = array(
                'first_name' => $data[0],
                'hobbies' => array() // *** the new array
            );
     }

     fclose($handle);

I created an empty array for each row's 'hobbies' property, in hopes that I would later be able to stuff values into this array. I quickly found this to be a lot more difficult that I expected.  I eventually realized it was a matter of the syntax I was using, specifically a problem with using a variable as the name of an object property.

It turns out that :  $csv_content->$data[0]['hobbies'] was not giving me access to the new array created under the 'hobbies' property of $csv_content->$data[0]  ( I think because PHP is interpreting $data[0]['hobbies'] to be the property name, rather than ['hobbies'] being an array within the $data[0] property )

THE SOLUTION:
To force PHP to recognize $data[0] as the property name, WRAP IT IN CURLY BRACES!

$csv_content->{$data[0]}['hobbies']  does the trick!

I hope someone finds this helpful. I had never run across this problem before.

Tuesday, July 10, 2012

ajaxload.info

This site is a fast and free way to create ajax loading icons like this:

ajaxload.info

Custom colors, color or transparent backgrounds, many styles, free. Check it out

Thursday, May 24, 2012

CSS transition class

This fun little class will add a 0.3 second transition between an element's normal and :hover states. Breaking it out into it's own class saves a lot of repetition in CSS and makes it easy to slap onto almost any html 'class' attribute.

.transition {
    -webkit-transition-duration: 0.3s;
    -moz-transition-duration: 0.3s;
    transition-duration: 0.3s;
}

If you define an element like this:

#box {
     background-color: #999999;
}
#box:hover {
     background-color: #000000;
}

And in the HTML:

<div id="box">I'm a box!</div>

It will simply flicker gray to black when hovered.

If you add the 'transition' class:

<div id="box" class="transition">I'm a box!</div>

Now it will animate a gray->black animation for 0.3 seconds!

Thursday, April 26, 2012

colorscheme.ru

This is the best color scheme engine I've found:
http://colorscheme.ru/
It is in Russian, but that just makes it more fun. Or you can use google translate and get a hilarious translation of the various controls.


Friday, April 20, 2012

The 'mobile' meta tag

This tag isn't a magic bullet, but don't forget to include it whenever you're starting a mobile site design.

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=false;" />

// user-scalable=true?  It's up to you.

Tons of information available here:  https://developer.mozilla.org/en/Mobile/Viewport_meta_tag

UPDATE 12/14/12:  I've been having luck with this one too:
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, target-densitydpi=device-dpi" />

Wednesday, February 29, 2012

Android Splash Screen - all resolutions and dpis

I was designing a splash screen for an app at work and found this info harder to find than it should be.  Putting it on my blog will surely not help, but if you're reading this maybe copy it down somewhere or spread the word.

Android Splash Screen Resolutions:

long-land-hdpi - 800x480 - 240dpi
long-port-hdpi - 480x800 - 240dpi

long-land-ldpi - 400X240 - 120dpi
long-port-ldpi - 240x400 - 120dpi

notlong-land-hdpi - 800x480 - 240dpi
notlong-land-ldpi - 320x240 - 120dpi
notlong-land-mdpi - 480x320 - 160dpi

notlong-port-hdpi - 480x800 - 240dpi
notlong-port-ldpi - 240x320 - 120dpi
notlong-port-mdpi - 320x480 - 160dpi

Having these specs won't change that its a huge pain to create 10 versions of the same splash screen, but .... well now you have the specs.

Tuesday, February 14, 2012

Ternary Syntax in PHP


Conditional statements are the building blocks of any complex application, on the web or otherwise.
One of my only objections to the classic 'if' statement is that it can take up several lines even for a simple bit of logic. Of course, there is a solution to this and in this case it's called ternary syntax or a ternary operator.

Ternary means 'composed of three' or 'involving three variables', and so does our classic if statement. The first element is the condition to be evaluated between the parenthesis, the second and third being the 'if' and 'else' statements.

Consider this typical use of an if / else statement:
$val = 5;
if ($val < 10) {                 // first component
    $test = "less than ten!";    // second component
} else {
    $test = "more than ten!";    // third component
}
print $test;

// Output: "less than ten!"

And now the same thing, this time using ternary syntax:
$val = 5;
$test = ($val < 10) ? "less than ten!" : "more than ten!";
print $test;

// Output: "less than ten!"

Here in pseudo-code:
(comparison) ? "if true outcome" : "else outcome";

The above line will return one of the two defined values on the right side, depending on the outcome of the conditional comparison between the parenthesis. A variable is most commonly used to capture the return value, but you can also execute code.
$val = 5;
($val < 10) ? print "less than ten!" : print "more than ten!";

Example Use Cases:

I often use this syntax when checking on an unreliable variable to provide an alternative if the variable isn't set:
$user = ($data->username != "") ? $data->username : "Guest";
print "Welcome, ".$user;
The output will now depend on if a valid ( != "" ) username exists in $data. If the username is blank, the user will instead be referred to as 'Guest'. This outcome is favorable to an error message which is not only ugly but may also reveal the inner workings of your code, which could be a security risk.

Another handy use case is converting and applying unit labels to values. In the example below we take a $value in inches and output it in a more user-friendly format. Values less than one foot are simply concatenated with ' inches', while values over 12 inches are converted to, "x feet, x inches."
$inches = 45;
$converted = ($inches <= 12) ? $inches." inches" : intval($inches/12)." feet, ".($inches % 12)." inches";
print $converted;

// Output: 3 feet, 9 inches
This is a good time to point out that putting this much logic into this syntax gets difficult to look at. When writing complex logic or working on code with others, you may want to avoid going ternary.  A good exercise is writing your if/else blocks with traditional syntax and seeing if you can convert them to ternary syntax.

You can even nest ternary conditionals inside of others, but that's starting to get into syntax so ugly I don't want to talk about it here. Enjoy the new syntax and stay tuned for an upcoming, related post on 'Control Structure Syntax'.

Monday, February 13, 2012

CSS code box

This is the CSS I'm going to use to style my code snippets:
.code {
 background:#f5f8fa;
 background-repeat:no-repeat;
 border: solid #5C7B90;
 border-width: 1px 1px 1px 20px;
 color: #000000;
 font: 13px 'Courier New', Courier, monospace;
 line-height: 16px;
 margin: 10px 0 10px 10px;
 max-height: 300px;
 min-height: 16px;
 overflow: auto;
 padding: 28px 10px 10px;
 width: 90%; 



.code:hover {
 background: #FAFAFA;
 background-repeat:no-repeat;
}
Feel free to copy the above classes to use on your own site / blog. Simply put all your markup within a 'div' tag with class='code', and presto.

Wednesday, February 1, 2012

Welcome to my code blog

Welcome to the code blog.  I intend to write about topics spanning these subjects: CSS, PHP, Javascript & JQuery.

Between my job and hobbies I've been doing a lot of web development recently. The internet has been such a powerful resource that I felt it was time to start my own blog and share some of my realizations along the path.

With this blog I intend to:
- show off things I have done
- teach you how to do things with the knowledge I've acquired

These posts are intended to quickly get you on your way with the sinppet of code in hand, and the fundamentals of how to use it. Please comment.