Terminal / OSX

## Watch a log file for changes
$ tail -f /path/to/log/file.log

## Copy ssh key to clipboard
$ pbcopy < ~/.ssh/id_rsa.pub

## Find all files of a certain type in directory and subdirectory(ies)
$ find /path/to/directory -type f -iname "*.ext"

## Check disk space usage
$ du -shc *
$ du -shc * | sort -h #Sort smallest to largest

## Download a file via SSH
$ scp user@example.com:/path/to/file ~/local/destination/path

## Count lines of code (recursively in selected dir)
$ find . \( -iname '*.css' -o -iname '*.php' -o -iname '*.ctp' -o -iname '*.js' -o -iname '*.less' \) | xargs wc -l | sort -n

## Make a symlink somewhere
$ ln -s /Path/To/Directory /Path/To/Symlink

## Copy a directory
$ cp -r dir dircopy

## Moving or Renaming a directory
$ mv source destination

## Removing a directory
rm -r dir

## Make tar archive
$ tar -cvzf tarfile.tar.gz /path/to/files

## Make tar archive and ignore certain files
## Important: any `--exclude` statements MUST be BEFORE the "/path/to/files" bit
$ tar -cvzf --exclude="exact_match" --exclude="pattern*" --exclude="*.another_pattern" tarfile.tar.gz /path/to/files

## Untar
$ tar -zxvf yourfile.tar.gz

## Unxar
$ xar -xvf filename-to-unxar.xar

## Change screencapture location
$ defaults write com.apple.screencapture location /path/to/screencaptures

## Change mysql password for user
$ mysql -uusername -ppassword
$ use mysql;
$ select Host, User, Password from user; ## If you don't know the user and/or host
$ SET PASSWORD FOR `user`@`host` = PASSWORD('newpassword');

## Find and replace a string in *all* files in a directory and subdirectory(ies)
$ perl -e "s/FIND/REPLACE/g;" -pi $(find /path/to/directory -type f)

## Find and replace a string in all of a certain type of file (ie, .php) in a directory and subdirectory(ies)
$ perl -e "s/FIND/REPLACE/g;" -pi $(find /path/to/directory -type f -iname "*.php")

## Update file permissions for all files with a type of XXX to XXX
#
#  In below example, any file (recursively) with 0600 are changed to 0644
#  For more details, see related article
#
$ find /path/to/root/dir -type f -perm 600 -print -exec chmod 644 {} \;

GIT commands

Settings

# Ignore file mode changes per repository
$ git config core.fileMode false

# Ignore file mode changes globally
$ git config --global core.fileMode false

Snippets

# Clone repository
$ git clone [address-to-git-repository]

# Update repository
$ git pull origin master

# Commit changes
$ git commit -am 'commit message'

# Push changes to live branch
$ git push origin master

# Git Upstream
$ git fetch upstream
$ git merge upstream/master

# View a list of files that were changed in the last commit
$ git show --pretty="format:" --name-only

# Remove cached DS_Store files
$ find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch

# Completely remove git ignored files from repo
$ git rm -r --cached .
$ git add .
$ git commit -am 'Remove cached ignored files'

# Delete remote tag
$ git tag -d 12345
$ git push origin :refs/tags/12345

Most common git questions and solutions

Borrowed from “Most common git screwups/questions and solutions

## I wrote the wrong thing in a commit message
$ git commit --amend

## How can I undo the last commit?
git reset --hard HEAD~1

## To undo but keep working changes
git reset --soft HEAD~1

## Delete a git branch remotely
git push origin --delete branchname

## Remove all local untracked files (and directories) from local clone
## WARNING: You cannot undo this, so you should make a backup before doing this
git clean -f -d

## Clone all remote branches
git branch -a                                   # Check if branch is there
git checkout origin/branchname                  # Take a look at branch
git checkout -b branchname origin/branchname    # Create a local tracking branch

## Rename local branch
git branch -m oldname newname

## Revert to a previous git commit
git reset --hard commitid

## or, use soft to keep working items
git reset --soft commitid

## Remove a git submodule
git submodule deinit submodulename
git rm submodulename
git rm --cached submodulename
rm -rf .git/modules/submodulename

## Overwrite local files when doing a git pull
git fetch --all
git reset --hard origin/master

## Git export, exporting the source code as with “svn export”
git archive --format zip --output /full/path/to/zipfile.zip master

## Discard all my unchecked in changes
git checkout -- .

## Create a new remote branch from the current local one
git config --global push.default current
git push -u

## Restore a deleted file
## 1) Find the commit when file last existed
git rev-list -n 1 HEAD -- filename

## 2) Then checkout that file
git checkout deletingcommitid^ -- filename

## Revert a single file to a specific previous commit
git checkout commitid filename

## Make git ignore permissions/filemode changes
git config core.fileMode false

## Take a quick look at an old revision of a single file
git show commitid:filename

Create New Repository (local/server)

## On local machine
$ cd /path/to/new_project
$ git init
$ git add *
$ git commit -m "Initial commit"

## On git server (gitdev.geekrescue.com /home/git)
$ cd /home/git
$ sudo mkdir new_project.git
$ cd new_project.git
$ sudo git --bare init
$ sudo git config receive.denyNonFastforwards true
$ sudo chown -R git:git /home/git/

## Back to local machine (inside /path/to/new_project)
$ git remote add origin git@gitdev.geekrescue.com:new_project.git
$ git push -u origin master

Reset to Previous Commit

# reset the index to the desired tree (example, <56e05fced>)
$ git reset 56e05fced

# move the branch pointer back to the previous HEAD
$ git reset --soft HEAD@{1}

$ git commit -m "Revert to 56e05fced"

# Update working copy to reflect the new commit
$ git reset --hard

Remote Server permissions

# In order for remote server authorized_keys to work (for git user)
$ chmod 700 /home/git
$ chmod 700 /home/git/.ssh
$ chmod 600 /home/git/.ssh/authorized_keys

PHP

Gists / Snippets

## PHP + Javascript `tail`
https://gist.github.com/cornellsteven/a0ddca8d1b3dec373182

Show PHP Errors

error_reporting(E_ALL);
ini_set('display_errors','1');

Force SSL (via PHP)

if ($_SERVER['SERVER_PORT'] != 443) {
    $url = 'https://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    header("Location: $url");
}

Force SSL (via .htaccess)

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

# If used with a typical brookside site (Cake, etc), put
# the snippet ABOVE all other rules. For example:

<IfModule mod_rewrite.c>
   RewriteEngine on

   # Force SSL
   RewriteCond %{SERVER_PORT} 80
   RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
   # End force SSL

   RewriteCond %{SERVER_PORT}   !82
   RewriteCond  %{REQUEST_URI}  !phpMyAdmin
   RewriteCond  %{REQUEST_URI}  !phpmyadmin
   RewriteCond  %{REQUEST_URI}  !stats
   RewriteCond  %{REQUEST_URI}  !appies
   RewriteRule    ^$ app/webroot/    [L]

   RewriteCond %{SERVER_PORT}   !82
   RewriteCond  %{REQUEST_URI}  !phpMyAdmin
   RewriteCond  %{REQUEST_URI}  !phpmyadmin
   RewriteCond  %{REQUEST_URI}  !stats
   RewriteCond  %{REQUEST_URI}  !appies
   RewriteRule    (.*) app/webroot/$1 [L]
</IfModule>

pr [better print_r]

function pr() {
    echo '<pre>';
    for ($i = 0 ; $i < func_num_args(); $i++) {
        print_r(func_get_arg($i)); echo "\n";
    }
    echo '<pre/>'; exit();
}

CURL Example (sending post fields)

$url = 'http://www.example.com/get-post.php';
$fields = array(
    'first_name' => 'Cornell',
    'last_name' => 'Campbell',
);

$fstring = '';
foreach ($fields as $key => $value) {
    $fstring .= $key . '=' . urlencode($value) . '&';
}
$fstring = substr($fstring, 0, -1);

// Initialize and set post fields
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fstring);

// Execute Curl
$result = curl_exec($ch);

// Close connection
curl_close($ch);

Truly Unique String (40 characters)

sha1(uniqid(mt_rand(), true)) //I.e., 7c7b65605950a06c7ce4542d819b75f9c6c4de9a

Return JSON String to AJAX

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit();

Increase memory limit

set_time_limit(0);
ini_set('memory_limit', '900M');

(mt)

## Database Host
## internal-db.s66044.gridserver.com
$_SERVER['DATABASE_HOST']

HTML & Plain Text example

$to = 'name@example.com';
$subject = 'This is the Subject';
$mime_boundary = md5(time());
$domain = 'domain.com';
$date_r = date('r');
$message_id = sha1(time()) . '@' . $domain;

$headers = <<<HEADERS
From: Company <no-reply@$domain>
X-Mailer: CakePHP Email
Date: $date_r
Message-ID: <$message_id>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="$mime_boundary"
Content-Transfer-Encoding: 8bit
HEADERS;

$body = <<<MESSAGE
--$mime_boundary
Content-Type: multipart/alternative; boundary="alt-$mime_boundary"

--alt-$mime_boundary
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This is a Headline
==================
This is my plain text message.


--alt-$mime_boundary
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 8bit

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
    <head>
        <title>$subject</title>
    </head>
    <body>
        <h1>This is a Headline</h1>
        <p>This is my <strong>html</strong> message.</p>
    </body>
</html>

--alt-$mime_boundary--


--$mime_boundary--

MESSAGE;

mail($to, $subject, $body, $headers);

Javascript

Snippets

// Quick way to check/uncheck all checkboxes
$('input[type=checkbox]').attr('checked', (!$('input[type=checkbox]')[0].checked));

javascript print_r

function print_r(l){var g="";g=" ";var m=4,o=this.window.document;function n(a){a=/\W*function\s+([\w\$]+)\s*\(/.exec(a);if(!a)return"(Anonymous)";return a[1]}function h(a,b){for(var c="",d=0;d0&&b++;var j=h(c*b,d),k=h(c*(b+1),d),e="";if(typeof a==="object"&&a!==null&&a.constructor&&n(a.constructor)!=="PHPJS_Resource"){e+="Array\n"+j+"(\n";for(var f in a)e+=Object.prototype.toString.call(a[f])==="[object Array]"?k+"["+f+"] => "+i(a[f],b+1,c,d):k+"["+f+"] => "+
a[f]+"\n";e+=j+")\n"}else e=a===null||a===undefined?"":a.toString();return e}g=i(l,0,m,g);alert(g)};

in_array()

function in_array(needle, haystack) {
    if (typeof(input) == 'object' && (input instanceof Array)) {
        for (var i=0, j=haystack.length; i < j; i++) {
            if (needle == haystack[i]) return true;
        }
    }
    return false;
}

CakePHP

Snippets

## Reset Auth User data (after editing user or related model)
$this->Session->write('Auth', $this->User->read(null, $this->Auth->user('id')));

## View SQL Log from Controller or Model
$log = $this->getDataSource()->getLog(false, false); debug($log);

## If `Console/cake` throws a "Permission Denied" error
chmod +x Console/cake

## Location to change the default IMAGES_URL
## /lib/Cake/bootstrap.php Line 114

Utilities / Hash

  • Hash::get($data, $path, $default = NULL);

    get() is a simplified version of extract(), it only supports direct path expressions. Paths with {n}, {s} or matchers are not supported. Use get() when you want exactly one value out of an array. The optional third argument will be returned if the requested path is not found in the array. [Docs]

  • Hash::extract($data, $path);

    Hash::extract() supports all expression, and matcher components of Hash path syntax. You can use extract to retrieve data from arrays, along arbitrary paths quickly without having to loop through the data structures. Instead you use path expressions to qualify which elements you want returned. [Docs]

  • Hash::insert($data, $path, $values = NULL);

    Inserts $data into an array as defined by $path [Docs]

  • Hash::remove($data, $path);

    Removes all elements from an array that match $path. [Docs]

  • Hash::combine($data, $keyPath, $valuePath = NULL, $groupPath = NULL);

    Creates an associative array using a $keyPath as the path to build its keys, and optionally $valuePath as path to get the values. If $valuePath is not specified, or doesn’t match anything, values will be initialized to null. You can optionally group the values by what is obtained when following the path specified in $groupPath. [Docs]

  • Hash::format($data, $paths, $format);

    Returns a series of values extracted from an array, formatted with a format string. [Docs]

  • Hash::contains($data, $needle);

    RDetermines if one Hash or array contains the exact keys and values of another. [Docs]

  • Hash::check($data, $path = NULL);

    Checks if a particular path is set in an array. [Docs]

  • Hash::filter($data, $callback = array('Hash', 'filter'));

    Filters empty elements out of array, excluding ‘0’. You can also supply a custom $callback to filter the array elements. Your callback should return false to remove elements from the resulting array. [Docs]

  • Hash::flatten($data, $separator = '.');

    Collapses a multi-dimensional array into a single dimension. [Docs]

  • Hash::expand($data, $separator = '.');

    Expands an array that was previously flattened with Hash::flatten(). [Docs]

  • Hash::merge($data, $merge[, array $n]);

    This function can be thought of as a hybrid between PHP’s array_merge and array_merge_recursive. The difference to the two is that if an array key contains another array then the function behaves recursive (unlike array_merge) but does not do if for keys containing strings (unlike array_merge_recursive). [Docs]

  • Hash::numeric($data);

    Checks to see if all the values in the array are numeric. [Docs]

  • Hash::dimensions($data);

    Counts the dimensions of an array. This method will only consider the dimension of the first element in the array. [Docs]

  • Hash::maxDimensions($data);

    Similar to dimensions(), however this method returns, the deepest number of dimensions of any element in the array. [Docs]

  • Hash::map($data, $path, $function);

    Creates a new array, by extracting $path, and mapping $function across the results. You can use both expression and matching elements with this method. [Docs]

  • Hash::reduce($data, $path, $function);

    Creates a single value, by extracting $path, and reducing the extracted results with $function. You can use both expression and matching elements with this method. [Docs]

  • Hash::apply($data, $path, $function);

    Apply a callback to a set of extracted values using $function. The function will get the extracted values as the first argument. [Docs]

  • Hash::sort($data, $path, $dir, $type = 'regular');

    Sorts an array by any value, determined by a Hash path syntax Only expression elements are supported by this method. [Docs]


    $dir can be either asc or desc. $type can be one of the following values:

    • regular for regular sorting
    • numeric for sorting values as their numeric equivalents
    • string for sorting values as their string value
    • natural for sorting values in a human friendly way. Will sort foo10 below foo2 as an example. Natural sorting requires PHP 5.4 or greater
  • Hash::diff($data, $compare);

    Computes the difference between two arrays. [Docs]

  • Hash::mergeDiff($data, $compare);

    This function merges two arrays and pushes the differences in data to the bottom of the resultant array. [Docs]

  • Hash::normalize($data, $assoc = TRUE);

    Normalizes an array. If $assoc is true, the resulting array will be normalized to be an associative array. Numeric keys with values, will be converted to string keys with null values. Normalizing an array, makes using the results with Hash::merge() easier. [Docs]

  • Hash::nest($data, $options = array());

    Takes a flat array set, and creates a nested, or threaded data structure. Used by methods like Model::find('threaded'). [Docs]


    Options:

    • children The key name to use in the result set for children. Defaults to ‘children’.
    • idPath The path to a key that identifies each entry. Should be compatible with Hash::extract(). Defaults to {n}.$alias.id
    • parentPath The path to a key that identifies the parent of each entry. Should be compatible with Hash::extract(). Defaults to {n}.$alias.parent_id
    • root The id of the desired top-most result.

Cake Bake

## Bake All
cake -app /path/to/cake/app/ bake all

## Bake Models
cake -app /path/to/cake/app/ bake model all

## Bake Controllers
cake -app /path/to/cake/app/ bake controller all

## Bake Views
cake -app /path/to/cake/app/ bake view all

MISCELLANEOUS

Facebook / Google Plus dimensions

Facebook Cover Photo:    851 x 315 (x2: 1702 x 630) ## Template /Dropbox/_files/facebook-cover-photo-tmp.psd
Google+ Cover Photo:    900 x 180 (x2: 1800 x 360) ## Template /Dropbox/_files/google-plus-cover-photo-tmp.psd

dompdf

/* Force page break */
div { page-break-before: always; }

/* To avoid breaking inside an element */
div { page-break-inside: avoid; }

Mysql

-- Run the following queries on local DB to enable local development of live site
-- Replace [REMOTE URL] with the full url of the live site (http://example.com)
-- Replace [LOCAL URL] with the full url of the site on your local machine (http://localhost:8888/example.com)
UPDATE wp_options SET option_value = replace(option_value, '[REMOTE URL]', '[LOCAL URL]') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET post_content = replace(post_content, '[REMOTE URL]', '[LOCAL URL]');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'[REMOTE URL]','[LOCAL URL]');


MySQL Field Types

Type Use for Size
TINYINT A very small integer The signed range is –128 to 127. The unsigned range is 0 to 255.
SMALLINT A small integer The signed range is -32,768 to 32,767. The unsigned range is 0 to 65,535
MEDIUMINT A medium-size integer The signed range is -8,388,608 to 8,388,607. The unsigned range is 0 to 16,777,215
INT or INTEGER A normal-size integer The signed range is -2,147,483,648 to 2,147,483,647. The unsigned range is 0 to 4,294,967,295
BIGINT A large integer The signed range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,808. The unsigned range is 0 to 18,446,744,073,709,551,616
FLOAT A small (single-precision) floating-point number. Cannot be unsigned Ranges are –3.402823466E+38 to –1.175494351E-38, 0 and 1.175494351E-38 to 3.402823466E+38. If the number of Decimals is not set or <= 24 it is a single-precision floating point number
DOUBLE, DOUBLE PRECISION, REAL A normal-size (double-precision) floating-point number. Cannot be unsigned Ranges are -1.7976931348623157E+308 to -2.2250738585072014E-308, 0 and 2.2250738585072014E-308 to 1.7976931348623157E+308. If the number of Decimals is not set or 25 <= Decimals <= 53 stands for a double-precision floating point number
DECIMAL, NUMERIC An unpacked floating-point number. Cannot be unsigned Behaves like a CHAR column: “unpacked” means the number is stored as a string, using one character for each digit of the value. The decimal point, and, for negative numbers, the ‘-‘ sign is not counted in Length. If Decimals is 0, values will have no decimal point or fractional part. The maximum range of DECIMAL values is the same as for DOUBLE, but the actual range for a given DECIMAL column may be constrained by the choice of Length and Decimals. If Decimals is left out it’s set to 0. If Length is left out it’s set to 10. Note that in MySQL 3.22 the Length includes the sign and the decimal point
DATE A date The supported range is ‘1000-01-01’ to ‘9999-12-31’. MySQL displays DATE values in ‘YYYY-MM-DD’ format
DATETIME A date and time combination The supported range is ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’. MySQL displays DATETIME values in ‘YYYY-MM-DD HH:MM:SS’ format
TIMESTAMP A timestamp The range is ‘1970-01-01 00:00:00’ to sometime in the year 2037. MySQL displays TIMESTAMP values in YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD or YYMMDD format, depending on whether M is 14 (or missing), 12, 8 or 6, but allows you to assign values to TIMESTAMP columns using either strings or numbers. A TIMESTAMP column is useful for recording the date and time of an INSERT or UPDATE operation because it is automatically set to the date and time of the most recent operation if you don’t give it a value yourself
TIME A time The range is ‘-838:59:59’ to ‘838:59:59’. MySQL displays TIME values in ‘HH:MM:SS’ format, but allows you to assign values to TIME columns using either strings or numbers
YEAR A year in 2- or 4- digit formats (default is 4-digit) The allowable values are 1901 to 2155, and 0000 in the 4 year format and 1970-2069 if you use the 2 digit format (70-69). MySQL displays YEAR values in YYYY format, but allows you to assign values to YEAR columns using either strings or numbers. (The YEAR type is new in MySQL 3.22.)
CHAR A fixed-length string that is always right-padded with spaces to the specified length when stored The range of Length is 1 to 255 characters. Trailing spaces are removed when the value is retrieved. CHAR values are sorted and compared in case-insensitive fashion according to the default character set unless the BINARY keyword is given
VARCHAR A variable-length string. Note: Trailing spaces are removed when the value is stored (this differs from the ANSI SQL specification) The range of Length is 1 to 255 characters. VARCHAR values are sorted and compared in case-insensitive fashion unless the BINARY keyword is given
TINYBLOB, TINYTEXT A BLOB or TEXT column with a maximum length of 255 (2^8 - 1) characters
BLOB, TEXT A BLOB or TEXT column with a maximum length of 65,535 (2^16 - 1) characters
MEDIUMBLOB, MEDIUMTEXT A BLOB or TEXT column with a maximum length of 16,777,215 (2^24 - 1) characters
LONGBLOB, LONGTEXT A BLOB or TEXT column with a maximum length of 4,294,967,295 (2^32 - 1) characters
ENUM An enumeration A string object that can have only one value, chosen from the list of values ‘value1’, ‘value2’, ..., or NULL. An ENUM can have a maximum of 65535 distinct values.
SET A set A string object that can have zero or more values, each of which must be chosen from the list of values ‘value1’, ‘value2’, ... A SET can have a maximum of 64 members

Useful Links

## CODE GUIDE
http://gitdev.geekrescue.com/dev/code-guide/

## CSS
http://www.456bereastreet.com/archive/200601/css_3_selectors_explained/
http://css-tricks.com/a-couple-of-use-cases-for-calc/

## JS
http://api.jquery.com

## PHP
http://book.cakephp.org/2.0/en/index.html

## GIT
http://git-scm.com/book
http://pcottle.github.io/learnGitBranching/
http://chris.beams.io/posts/git-commit/

## DEVELOPMENT
http://docs.emmet.io/cheat-sheet/
https://github.com/pingjiang/emmet-objc/releases/download/v10.10.1/Emmet.tmplugin.zip
https://code.google.com/p/zen-coding/
http://realfavicongenerator.net
https://github.com/cornellsteven/bootstrap
http://scottboms.com/downloads/desktops/textmate_shortcuts_1920.png
http://code.cornellcampbell.com

## OTHER
https://developer.nvidia.com/jetson-tk1
http://sidebar.io
http://cabbibo.com/
https://gist.github.com/p1nox/6102015
http://asepsis.binaryage.com
https://github.com/gf3/dotfiles
http://www.mayerdan.com/programming/2013/12/01/configuring-osx-mavericks-dev-machine/