Getting Set Up with Your Projects on Github

So you want to use git to manage your projects?

Make sure you’ve installed git: https://help.github.com/articles/set-up-git

To make a new repo: https://help.github.com/articles/create-a-repo

Once you’ve created the repo on github follow the “next steps” it gives you. There are just a bunch of one liners you can enter into your terminal.

If the repo already exists?

cd {to the directory where you wan to store the repo}
git clone git@github.com:{your_user_name}/{example_repo_name}.git

Watch git do some magic, then:

cd {repo name}

And your off and running.

How it works?

The process goes something like this.

  1. Make sure you do “git pull” before you start working on your project for the day. This will ensure you merge any changes that other may have made to your repo over night.
    git pull origin master
  2. Work work work…
  3. When you think your ready to upload some changes, add your changes
    git add .
  4. Then you need to commit your changes to the repo
    git commit -am "added some stuff"
  5. After everything is done, push your changes to github
    git push origin master

You should be all set.

Branching

There’s an excellent article here about branching and merging. The basic idea is to have a “master” branch, that is designated as “read for production deployment”. Meaning anything that goes on master can be copied directly to the server and expected to run. If we’re working on a bugfix, we make a “bugfix” branch. This essentially copies the master and allows you to make changes, when your ready to push changes, you push them to the bugfix branch. This way we can share our bug fixes with the team. Once we’ve concluded that the bugfixes are working, a team member in charge of the repo will merge the “bugfix” with “master” and handle any conflicts.

Let’s say I Katy walks into my office and says, “your shit ait’t workin’ and it’s all messed up!” I quickly do a “git pull” of my master branch to make sure I’m up to date. Then I do the following:

Create a new branch to start this “hotfix”. I name it “hotfix1”:

git branch hotfix1

Then I want to switch to that branch:

git checkout hotfix1

Now I can start making changes. Let’s say I figure out the issue and am confident the branch contains the fix.

git add .
git commit -am "fixed this shit"
git push origin hotfix1

I’ve pushed the hotfix to the repo, my other team members can pull that branch from the repo, run it locally and verify that it’s working. Once we’ve confirmed, our team member in charge of the repo can merge the “hotfix1” branch to master. Then we can all pull down the master branch and the fix is permanent.

Now let’s say I’ve pushed the branch and my team members are in the process of verifying that it works. In the mean time I just want to update the server with the latest master just to make sure the problem isn’t someplace else. I change back to the master branch:

git checkout master

And git automatically changes the files on my system to reflect what I had for “master” instead of “hotfix1”. So I can take master, upload it to the server and be confident that it will run. Once my team members have confirmed my hotfix, I can pull down the latest master and delete my local copy of “hotfix1”

git checkout master
git pull origin master
git branch -d hotfix1

 

 

 

Cinder Problems Compiling/Building Kinect Library

For those of you with  this problem “‘Obj’ is a protected member of ‘cinder::Kinect'”. You’ve got a couple build settings that need to be updated

Here’s scenerio. You’ve installed Cinder, installed Cinder Kinect library (https://github.com/cinder/Cinder-Kinect) in blocks and rebuilt.

Now you’re getting build errors when you try to run the sample projects.

Here’s what I did:

  1. Changed the default SDK to 10.7 (if you havent already)
  2. change the build compiler to LLVM GCC 4.2
  3. Change the Inline Methods Hidden Option to ‘No’
  4. Change the Symbols Hidden By Default to ‘No’

“Clean & Build” and you should be good to go!

Also, once you’ve compiled the sample you’ll want to build your own. Your going to end up having linker erros. Follow this: https://forum.libcinder.org/topic/how-to-use-cinderblocks-in-xcode

and you should be all set. Bascially, you need to tell xcode where to find some of these libraries when using blocks.

Get redis to work on heroku

if you’ve tried to install toolbelt and then run redis but following these instructions:

https://devcenter.heroku.com/articles/nodejs

Then you know that you can just run redis. It errors out wit a message: Redis connection to 127.0.0.1:6379 failed – connect ECONNREFUSED

something like that…

follow this instead: https://devcenter.heroku.com/articles/redistogo#using-with-node

so install x-code command line tools from x-code preferences.

then download redis: http://redis.io/download

then follow these instructions: http://jasdeep.ca/2012/05/installing-redis-on-mac-os/

to get redis installed on your mac. Then run the redis server again.

Now you can test redis on heroku locally…

Note: if you’re also using something like socket.io, you must make sure to use redis to configure socket.io, otherwise it wont scale across processes

https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO

Also, worker processes are different than web processes. web will idle out after an hour if only one dyno is running. worker dynos never idle: https://devcenter.heroku.com/articles/dynos

How the fuck does vertical align work?

I normally don’t curse online since it gets saved to the ether of the universe and will forever haunt me if I try to go into politics…but this question probably gets asked on google a thousand times a day and I want some search engine traffic. So there.

Anyway, read this: http://css-tricks.com/vertically-center-multi-lined-text/

And remember to give the table a height if it’s still not working. It makes sense, if your table has a height, the the browser can calculate how far down to alight the text, if it doesn’t have a height set, then it can’t tell how far down the text needs to go in order to vertically center it.

Boom.

Javascript Objects: Survival 101

So there are a lot of ways to create an object in Javascript.

If you have some helper functions that should be called statically from time to time all over your script you might do something like this:

var myObjectLiteral = {

   variable1: "my variable",

   function1: function() {
      return this.variable1;
   }

};

Think of object literals as a toolbox for your page, not really a full blown class. Not to shabby but a but heavy on the performance side, and it doesn’t really provide you any of the benefits of polymorphism, I.E. let’s say I created a class called shape. This class can have a circle or square in it. The shapes can be different colors. All the shapes need to know if they are a circle or a square and what color they might be…

Something like this might be what you need:

var shape = function(shape, color) {

    // private vars
    var color = color,
        shape = '';

    // construct
    var init = function() {
        if(shape == 'square'){
            makeSquare();
        } else {
            makeCircle();
        }
    };

    // private
    var makeSquare = function() {
        shape = 'square';
    };

    var makeCircle = function() {
        shape = 'circle';
    };

    // public
    this.getShape = function() {
        return shape;
    };

};

You might call this by saying:

var blueCircle = new shape('circle', 'blue');

var redSquare = new shape('red', 'square');

// would return "circle"
console.log(blueCircle.getShape());

That’s great, it’s still not totally optimized yet (that was using the “module” pattern). You might write the same object using the contructor or “prototype” pattern:

var shape = function(shape, color) {    this.shape = shape;    this.color = color;};
shape.prototype.getShape = function() {    return this.shape;};

var shape = function(shape, color) {
    this.shape = shape;
    this.color = color;
};

shape.prototype.getShape = function() {
    return this.shape;
};

Finally, if you’re looking for something optimized, a good workhorse is what’s known as function caching…

Basically, its a modular design pattern but your functions are cached and ready to be garbage collected if the scope is right:

// function caching
var getShapeFunc = function() {
    return this.shape;
};

var initFunc = function(color, shape) {
    this.color = color,
    this.shape = shape;
};

var shape = function () {
    return {
        init: initFunc,
        getShape: getShapeFunc
    };
};

Ok that’s it for me, I’m going to bed. Pretty cool shit though right? There’s also a great resource that explains some of this further:

http://addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjavascript

And an awesome Javascript performance article here:

http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/

 

Failed to Load an Image? Load a Default

I know I know, before I even get started most of you are thinking this is pretty beginner stuff.

But it’s good to refresh every once in a while. Here’s how I do it:

<img src="profile-photo.jpg" alt="profile" onerror="this.src='default.jpg'" />

The important part is the “onerror=” that basically says if we get an error instead of the photo, change the image src to “default.jpg”.

There you have it! Quick and easy.

CakePHP Hints 1.0: A Refresher

Hey all, as usual I don’t have a whole lot of time to explain myself or go into detail.

I’ve been getting back into cakephp and I’ve forgotten so much shit that I’m finding it useful to log all of this stuff. As a result, here’s what to remember if you’re just getting started with cakephp (again…).

Hint #1:

In your controller you find a variable called “$uses”. Normally, if you use a default setup you don’t need this. Cake will automatically associate your controller with the correctly named model. For instance if you have a controller named “UsersController” in the file “UsersController.php” and then have a model named “UserModel” in a file named “UserModel.php” in the models folder. Well cake is smart enough to figure that out. But let’s say I have “LoginController”…well I don’t want to rename it to “LoginsController” just to keep with tradition. So I can say in my controller:

var $uses = array(Login');

Then I can call $this->Login->find();  or whatever… Cake will associate my controller with the LoginModel class. I can also use cake’s “loadModel” function in my controller like this:

$this->loadModel('Login');
$this->set('data', $this->Login->find(null, '1'));

Hint #2:

Let’s say I make something called a “BouncerModel” which is supposed to act like a bouncer at a nightclub. He only allows people in who are on the list. Let’s also say I’m a giant retard (true) and I put all the users on the list in a different database. Well, in order for me to check some information about the users, my “Bouncer” needs access to call the other database…

There’s a special variable you can use for this:

public $useDbConfig = 'another_database_name';

This allows that model to use another database connection defined in your “database.php” file.

Hint #3:

You can respond to ajax calls with json easily in cakePHP, no need to set autorender to false for this one. Simply set the response type to json. Make an array of data, encode it in json with PHP and set the response body to the encoded array. Then send the response:

$this->response->type('json')

$r = array('data' => 'stuff', 'more_data' => 'more stuff');

$this->response->body(json_encode($r));

$this->response->send();

Easy enough!

Hint #4:

If you download the zip from github for cakePHP, and it gives the error “URL rewriting is not configured properly” then it’s most likely the .htaccess folder in your project root. Look here for more information. Basically, you need three .htaccess files. One in webroot. One in your “app” folder and finally another .htaccess file in your project root directory. The .htaccess in your project root should have this:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
</IfModule>

Make sure you have all these files. Just to reiterate. The /htdocs/project/app/webroot/.htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

The /htdocs/project/app/.htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>

And finally, the /htdocs/project/.htaccess:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
</IfModule>

That’s it!

Hint #5:

If you cake application sends keep alive headers or seems to be hanging…you can stop it manually:

$this->response->send();
$this->_stop();

This will force ajax headers to stop with the keep-alive stuff…

Hint #6:

You forgot to add the “tmp” directory to .gitignore. You uploaded some tracked files, pulled with your other workstation and then realized your mistake. You removed your ignored files with:

git rm -r /absolute/path/to/directory

Now everything is peachy except for about a million errors on your normally 100% functioning cake app. Mostly permission based stuff saying file engine couldnt write to the file “access denied.” Well no worries. If you look at your default cake install under the tmp/cache directory you’ll see there are three folders “persistent”, “models” and “views”. Simply remove the cache folder completely, create a new “cache” folder with “persistent”, “models” and “views” as subfolders. Boom.

Hint #7:

Why gather specific form fields to submit with your ajax call, when you can simply serialize all the form data (as long as it was created with CakePHP’s htmlFormHelper). I’ll give an example. Let’s say I create the following form with cakePHP:

echo $this->Form->create('Hoody', array(
        'url' => array('controller' => 'hoodies', 'action' =>  'submit'),
        'type' => 'post',
        'label' => ''
    ));

    echo $this->Form->input('size', array(
        'id' => 'size',
        'type' => 'text',
        'label' => 'Hoodie Size',
        'value' => $hoody_size
    ));

    echo $this->Form->input('letter', array(
        'id' => 'letter',
        'type' => 'text',
        'label' => 'Hoodie Letter',
        'value' => $hoody_letter
    ));

    echo $this->Form->end('Submit');

Now I don’t need javascript to do a ton of heavy lifting here. I can simply stop the default behavior when someone hits the submit button:

$('#form').on('click', function(evt) {
   evt.preventDefault();
});

You knew that… Then I can submit the form to the correct url using jquery’s “post” function. Just make sure you serialize your data!

// gather form data
       var _form = $('#form');

        var data = _form.serialize();

        // submit to proper url
        $.post(_form[0].action, data, function(data) {
            console.dir(data);
            // wait for a response and take action
        }, 'json');

Not always that obvious but very useful.

More to come…

Running PHP from XAMPP manually through Terminal

I have been spending some time with CakePHP today and in order to execute php through the terminal to get it to connect to XAMPP’s correct mysql port, I need to run terminal. The problem is if you execute plain old php in terminal like “php –info” or “which php” you’ll get a response from the default installation of PHP on your mac. You need to run PHP as if it’s being run on the XAMPP environment.

In order to do this, make sure you execute php from the bin directory of XAMPP.

/Applications/xampp/xamppfiles/bin/php --info

This way, your terminal application is executing PHP with the correct settings to do all the things it needs to do to connect to its version of mysql and write the correct files in your XAMPP environment (when you’re “baking” with cakePHP).

cURL won’t work locally

We setup up two brand spankin’ new installations of XAMPP on two computers here at work and tried to run a PHP script that uses cURL to get some facebook data….

Low and behold it didn’t work, but when I loaded it on my old machine and the server everything was fine! My first thought was to check and make sure the curl module was loaded so I created a php page and quickly loaded in:

<?php
phpinfo();
?>

Then visited that file in a browser. It said cURL was enabled! WTF. So I did a bit of googling and found that even though its enabled, xampp may not have loaded the right .dll or .so automatically. Now worries, go into your php.ini file here (mac):

/Applications/XAMPP/xamppfiles/etc/php.ini

Search for “;extension=php_curl.so” (.dll if your on windows) and uncomment it be removing the “;” semicolon.

Whabam, done!