Thursday, April 14, 2016

JavaScript: Get Random Number Between A Given Range of 2 Numbers

Ever had that moment where you needed a random number between two given numbers, but find it hard to get exactly what you're looking for a regular and repeated basis? Quite often, if you go searching, you may see something like:

function getRandomIntInclusive(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

The previous is the most common method and can be found at @ developer.mozilla.org. The problem with this method is it's lack of involvement. For instance, what if you need a random decimal value between 1 and 2? What if you need to never include the minimum and maximum in the range? What if you need to ensure they are always a possibility?

There are countless reasons as to why this one method just won't do, which is why there are more than one methods @ developer.mozilla.org. But what you just want one simple method you can use regularly for most every possible instance you can think of?

Well, you're in the right place!

I've created a method and provided several ways of adding it to your site that makes everything about generating random numbers so much easier! - [Find @ github]

First, what it does:

If you simply need to get a random number within a given range, including the possible minimum and maximum, then simply call the method and pass the smallest number as the first parameter and the largest number as the second parameter, such as:

getRandInt(1, 2) = 1.2783833924813244

However, if you need to ensure it's ALWAYS a whole number, then simply add a third parameter of true!

getRandInt(1, 2, true) = 1

Or perhaps you need a set number of decimal places [Currently only supports up to 20]

getRandInt(1, 2, 19) = 1.1342048875680916797

Or maybe you need to ensure it's ONLY between the range and NEVER includes the min and max given, then simply reverse the parameters!

getRandInt(2, 1) = 1.3221148112756618

It's all pretty simple!


Now, for implementation ... can you say "EZ"?

Just how easy you ask? Well, I've taken the guess work out of most everything!

For a simple Global Method you can call anywhere, such as getRandInt(1, 2); simply add the following to your <head>

<script src="https://rawgit.com/JDMcKinstry/JavaScript-getRandInt/master/window.getRandInt.min.js" type="text/javascript"></script>

Or If you'd like to add it to the Math Object for a more familiar use, then include the following in your <head>

<script src="https://rawgit.com/JDMcKinstry/JavaScript-getRandInt/master/Math.getRandInt.min.js" type="text/javascript"></script>

OR[¡BONUS TIME!] If you want to use it as a jQuery method, then include the following in your <head> BUT make sure it comes after your jQuery inclusion!

<script src="https://rawgit.com/JDMcKinstry/JavaScript-getRandInt/master/jQuery.getRandInt.js" type="text/javascript"></script>

If you'd like to play around with it a bit and test it out, then check out this jsFiddle!

NOW GO FORTH, AND GET RANDOM!

Tuesday, February 9, 2016

EPIC RANDOM STRING GENERATOR 9001!!! IT'S OVER 9000!!!

BEHOLD! THE ULTIMATE RANDOM STRING MAKER 9001!

Do you want random strings to the extreme?! Do you crave the random goodness in favor of something better than what you see elsewhere?! Are you tired of all these weak answers out there saying they solve this problem or that without having a problem of their own?! ARE YOU MISSING A COMBO OF NUMBERS, AND UPPER AND LOWER CASE LETTERS?! Then I've got the juice for you!
¡UPDATE! Now improved performance of random string request having a length greater than 23! Was a slight issue before where long strings might not always be number requested, if request was greater than 23. However, NO LONGER A PROBLEM! ¡ENJOY!
/* COPY && PASTE */
function epicRandomString(b){for(var a=(Math.random()*eval("1e"+~~(50*Math.random()+50))).toString(36).split(""),c=3;c<a.length;c++)c==~~(Math.random()*c)+1&&a[c].match(/[a-z]/)&&(a[c]=a[c].toUpperCase());a=a.join("");a=a.substr(~~(Math.random()*~~(a.length/3)),~~(Math.random()*(a.length-~~(a.length/3*2)+1))+~~(a.length/3*2));if(24>b)return b?a.substr(a,b):a;a=a.substr(a,b);if(a.length==b)return a;for(;a.length<b;)a+=epicRandomString();return a.substr(0,b)};
/* COPY && PASTE */

EASY TO USE!!!

var rand = epicRandomString();
/*  OR IF YOU NEED A SET LENGTH!    */
var rand = epicRandomString(10);
Tested 1 MILLION TIMES! and found 0! duplicates with no set length, and only 14! duplicates with a set length of 10!

JavaScript to get Aspect Ratio

The following is just a simple calclator for gaining Aspect Ratio.

This will allow you to find 4th value if needed, or simply tell you what the aspect ratio between two sets of measurements is, provided they match. An AR of 4/3 isn't going to match 9/7, thus you'd get a false return. In this way, you can check that an Aspect Ratio was adjusted correctly.

Easy Uses!

  • aspectRatioHD({ "height": 600, "width": 800 }, { "height": 1200 }); // would return 1600, which would be your new "width"
  • aspectRatioHD({ "height": 600, "width": 800 }, { "width": 1600 }); // would return 1200, which would be your new "height"
  • aspectRatioHD({ "height": 600 }, { "height": 1200, "width": 1600 }); // would return 800, which would be your new "width"
  • aspectRatioHD({ "width": 800 }, { "height": 1200, "width": 1600 }); // would return 600, which would be your new "height"
  • aspectRatioHD({ "height": 600, "width": 800 }, { "height": 1200, "width": 1600 }); // would return [4,3], The spect Ratio in Array Format being [W,H]
  • aspectRatioHD({ "height": 600, "width": 800 }, { "height": 1200, "width": 1600 }); // would return [4,3], The spect Ratio in Array Format being [W,H]
  • aspectRatioHD({ "height": 3, "width": 4 }, { "height": 7, "width": 9 }); // would return false, since these 2 aspect ratios do not match

Code

function aspectRatioHD(){if(2==arguments.length){var d=function(a){a=parseFloat((""+a).replace(/[^0-9.]/g,""));return a==a?a:void 0},a=function(a){var b={},c;for(c in a)if(a.hasOwnProperty(c))switch(c.toLowerCase()){case "height":b.h=d(a[c]);break;case "width":b.w=d(a[c])}if("number"!=typeof b.h||b.h!=b.h)b.h=void 0;if("number"!=typeof b.w||b.w!=b.w)b.w=void 0;return b},b=a(arguments[0]),a=a(arguments[1]);if(b.w&&b.h&&a.w&&a.h)return Math.round(a.w/a.h*100)/100==Math.round(b.w/b.h*100)/100?(b=function e(a,
b){return b?e(b,a%b):a},b=b(a.w,a.h),[a.w/b,a.h/b]):a.w/a.h==b.w/b.h;if(b.w&&b.h&&!a.w&&a.h)return Math.round(b.w/b.h*a.h);if(b.w&&b.h&&a.w&&!a.h)return Math.round(a.w/(b.w/b.h));if(!b.w&&b.h&&a.w&&a.h)return Math.round(a.w/a.h*b.h);if(b.w&&!b.h&&a.w&&a.h)return Math.round(b.w/(a.w/a.h))}else throw Error("Invalid Amount of Arguments. Must have 2 arguments such as: [{height:1,width:2},{height:3}]");};

Go play with it here!

Or see the Result below

HTML5 JavaScript localStorage Helper!!! Beyond a how to; "localStorageHelper" a clear and simple way to use Local Storage!

Just a quick and simple class for working with `localStorage`! Extremely easy to use!

Easy Uses!

Simply assign:

var lsh = new localStorageHelper()

And go!
  • lsh.isAvailable; // after class called, becomes boolean property
  • lsh.get(); // retrieve an Object of ALL available localStorage items
  • lsh.get('keyName'); // retrieve value for storage item having passed key name
  • lsh.set('keyName', 'assorted value'); // value can be ALMOST anything!
  • lsh.remove('keyName'); // seeks to remove storage item having key name
  • lsh.clear(); // remove ALL storage items
  • lsh.on('eventName', callback); // set a callback method to preform when event is fired
  • lsh.off('eventName', callback); // attempts to remove callback from list of handlers on given event

Oh, and did I mention events?!

  • lsh.on('get', function(e) { /* e={ eventType: "get", key: "keyName", url: "currentAddress", value: "the value" } */ }); // do work whenever get is called AND something is actually retrieved
  • lsh.on('set', function(e) { /* e={ eventType: "set", key: "keyName", success: bool, url: "currentAddress", value: "the value" } */ }); // do work when new value is set
  • lsh.on('remove', function(e) { /* e={ eventType: "remove", key: "keyName", success: bool, url: "currentAddress", value: "the value" } */ }); // do work when value is removed
  • lsh.on('clear', function(e) { /* e={ eventType: "clear", success: bool, url: "currentAddress" } */ }); // do work when all values are cleared

Code

function localStorageHelper() {
 // variable for this class
 var $this = this;
 
 // set whether if localstorage is isAvailable
 this.isAvailable = function() {
  try { return 'localStorage' in window && window['localStorage'] !== null; }
  catch (e) { return !1 }
 }();
 
 // HELPERS
 this.keyExists = function(key) { return this.isAvailable && key !== void 0 && localStorage.key(key); }
 this.keyAtIndex = function(i) { return this.isAvailable ? localStorage.key(i) : void 0; }
 // returns an array of keys
 this.getKeys = function() {
  if (!this.isAvailable) return void 0; 
  var k = []; 
  for (var i=0;i<localStorage.length;i++) k.push(localStorage.key(i)); 
  return k;
 }
 // returns array of values
 this.getValues = function() {
  if (!this.isAvailable) return void 0; 
  var v = []; 
  for (var i=0;i<localStorage.length;i++) v.push(this.get(localStorage.key(i))); 
  return v;
 }
 
 // get/set/remove/clear local storage item(s) and fire get event
 this.get = function(key) {
  if (this.isAvailable) {
   if (typeof key === "number") key = this.keyAtIndex(key);
   if (this.keyExists(key)) {
    var val;
    try { return val = JSON.parse(localStorage.getItem(key)); }
    catch(err) { return val = localStorage.getItem(key); }
    finally { this.onGet.fire(key, val); }
   }
   else if (key === void 0) { // if no key provided, then assume "get all" and return Object of all items in localStorage
    var a = {};
    try {
     for (var i=0;i<localStorage.length;i++) if (this.keyAtIndex(i)) a[this.keyAtIndex(i)] = this.get(this.keyAtIndex(i));
     return a;
    }
    finally { this.onGet.fire(key, a); }
   }
  }
  return void 0;
 }
 this.set = function(key, value) {
  if (this.isAvailable) this.onSet.fire(key, value, function() {
   try {
    try { localStorage.setItem(key, JSON.stringify(value)); }
    catch(err) { localStorage.setItem(key, value); }
    return true;
   }
   catch(err) {}
   return false;
  }());
  return $this;
 }
 this.remove = function(key) {
  if (this.isAvailable && this.keyExists(key)) this.onRemove.fire(key, this.get(key), function() {
   try { localStorage.removeItem(key); return true; }
   catch(err) { return false; }
  }());
  return $this;
 }
 this.clear = function() {
  if (this.isAvailable) this.onClear.fire(null, null, function() {
   try { localStorage.clear(); return true; }
   catch(err) { return false; }
  }());
  return $this;
 }
 
 // EVENTS
 function setEvent(eType) {
  var eventName = "on" + (eType.charAt(0).toUpperCase() + eType.slice(1)),
   ret = function(handler) {
    if (typeof handler == "function") {
     var $handlers = this[eventName].handlers,
      strHandler = handler.toString().replace(/ |\t|\r|\n/ig, '');
     for (var x in $handlers) if (strHandler == $handlers[x].toString().replace(/ |\t|\r|\n/ig, '')) return this[eventName];
     $handlers.push(handler);
    }
    return this[eventName];
   }
  ret.fire = function(k, v, s) {
   var $handlers = this.handlers,
    args = { eventType: eType };
   if (k !== undefined && k !== null) args.key = k
   if (v !== undefined && v !== null) args.value = v
   if (s !== undefined && s !== null) args.success = s
   args.url = window.location.toString();
   for (var x in $handlers) $handlers[x].apply($this, [args])
  }
  ret.handlers = [];
  return ret;
 }
 this.on = function(a, b) {
  a = "on" + (a.charAt(0).toUpperCase() + a.slice(1));
  this.hasOwnProperty(a) && this[a].apply($this, [b]);
 };
 this.off = function(a, b) {
  a = "on" + (a.charAt(0).toUpperCase() + a.slice(1));
  if (this.hasOwnProperty(a) && "function" == typeof b) {
   var c = this[a].handlers,
    e = b.toString().replace(/ |\t|\r|\n/ig, ""),
    d;
   for (d in c)
    if (e == c[d].toString().replace(/ |\t|\r|\n/ig, "")) {
     c.splice(d, 1);
     break;
    }
  }
  return $this;
 };
 
 this.onGet = setEvent.apply(this, ['get']);
 this.onSet = setEvent.apply(this, ['set']);
 this.onRemove = setEvent.apply(this, ['remove']);
 this.onClear = setEvent.apply(this, ['clear']);
 
 // Final summary, check if LS is even available, if not, throw error and process callback method if provided
 if (!this.isAvailable) {
  var msg = "[localStorage] is unavailble!";
  if (arguments.length && typeof arguments[0] == "function") arguments[0].apply($this, [{ isAvailable: this.isAvailable, Error: msg }]);
  throw new Error(msg);
 }
 
 return this;
}

Go play with it here!

Wednesday, June 18, 2014

Random String in PHP

I know it's been quite a while and I need to do some SERIOUS reformatting ... For now, here's a quick and easy method to getting a random string in PHP:

 substr(str_shuffle(MD5(microtime())), 0, 10);

That's it! Use it in a function like:

 function str_rand($length=10) { return substr(str_shuffle(MD5(microtime())), 0, $length); }
 echo str_rand();

Max user processing time will be *about .030s on average. Enjoy!


Update! Someone came to me wanting a mix of upper case letters too. Well here you go!

 implode('', array_map(function($i) { return rand(1, 10)%2 == 0 ? strtoupper($i) : $i; }, str_split(substr(str_shuffle(MD5(microtime())), 0, 10))));

That's it! Use it in a function like:

 function str_rand($length=10) { return implode('', array_map(function($i) { return rand(1, 10)%2 == 0 ? strtoupper($i) : $i; }, str_split(substr(str_shuffle(MD5(microtime())), 0, $length)))); }
 echo str_rand();

Wednesday, May 22, 2013

Add jQuery to almost any site from the console!

I know i seriously need to update my blog. But for now, a new fun entry!

Have you ever been to a site and wanted to manipulate some stuff on the site with ease? Without long lines of vanilla JS? The following code snippet will help you do exactly that! Simply open the console, paste the code, hit enter/submit and you're good to go! Have fun editing that site to look however you want! Enjoy!

if(typeof jQuery === 'undefined') {
 // jQuery site src: https://code.jquery.com/jquery-1.9.1.min.js
 var $script = document.createElement("script");
 $script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js";
 $script.type = "text/javascript";
 document.getElementsByTagName('head')[0].appendChild($script);
}

OR

Just go add "cjs" to your Chrome browser and do about the same thing!

Monday, November 12, 2012

How To: Reset Digital Signature on Infopath in a Sharepoint (2010) Workflow

I'm not sure how 2010 specific this is, although, right off the top, 2010 versions are all I have worked with thus far. As you can see at my StackOverflow question (found here), I had an issue arise not to long ago where I really needed to know how to do as the title says. After hours of Googling, forum searching, and even mIRC chatting I found no solution that actually worked. I found many solutions claiming to work, and perhaps they did for older versions, however none worked for our setup. I should mention we use all 2010 software and our SQL is on a virtual. Not sure how much difference any of that could make, but on to the point. I finally found the answer myself, through much trial and tribulation. Perhaps, on another day I will break this down more and detail what is going on, but for now, I'm keeping the explanation of code short. In short, I found, that to work with all users (including non-admins) I had to first raise security level and then read the XML file, find the correct url for creating the namespace object, and finally edit the XML and save it back to the document. Keep in mind, this InfoPath form is on a Library list in Sharepoint and all of this work (as per requirment) is done via CSharp in a WorkFlow. And now, the code:

Sunday, August 26, 2012

jQuery/jQueryUI Help: Tabs | Get Currently Selected Tab

Update! Please note: In newer versions of jQueryUI (1.9+), `ui-tabs-selected` has been replaced with `ui-tabs-active`.
So I've noticed a major need for further explanation on how to work with jQueryUI Tabs. It is probably one of the most popular features I've seen used and "mis-used" due simply to lack of understanding of some very simple code.
The question is often proposed, "How do I get the currently selected tab?" or "tab index?". The documentation actually answers the later, but people still seemed to be confused. I've noticed many coders also have trouble understanding what to do with the Tab Index once they have it.
Well let's get started shall we!?
First of all, the documentation on the sight states:
[jQueryUI Reference]
...retrieve the index of the currently selected tab
var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected'); // => 0

That seems all well and dandy, but what if you need to do more? What if you need the "panel" that is open in order to manipulate data within? What if you need the current tab itself in order to make some text change or promote a specific "pop-up"?
Their next suggestion is found a little hidden in the documentation via the "tabs events". Within events like "tabsshow" you can retrieve required info via the bonded return parameter "ui".
For examnple:
$("#tabsElementID").tabs({
    show: function(e, ui) {
        // Objects available in the function context:
        ui.tab     // anchor element of the selected (clicked) tab
        ui.panel   // element, that contains the selected/clicked tab contents
        ui.index   // zero-based index of the selected (clicked) tab
    }
});
But what if you need to access these items outside the tabs events?!?

Whatever your scenario may be, I have the answer!Keep Reading



I'll try to break things down and keep this as easy to follow as possible, so please read all the way through.
First of all, getting the currently selected tab and the currently selected panel is easy. However, let's break this up.
By "tab", I am referring to the ACTUAL TAB the user clicks on to change the screen.
By "panel", I am referring to the PANEL where your ACTUAL CONTENT exist. In other words, the change the user sees with his/her eyes.
Now, let's get those current items and see how easy we can make this:
//  To retrieve the current TAB and assign it to a variable ...
var curTab = $('.ui-tabs-selected'); // in NEWER jQueryUI, this is now ui-tabs-active
//  To retrieve the current PANEL and assign it to a variable ...
var curTabPanel = $('.ui-tabs-panel:not(.ui-tabs-hide)');
Now of course, if you have multiple tabs sections, you may need to inquire the encapsulating div element ID for the specific tabs group you want the current tab from. Such as:
//  if you have 2 tabs areas created as follows ...
$('#example-1').tabs();
$('#example-2').tabs();

//  and you want the current tab or panel for the tabs of example-2
//  then you would simpley include the element ID to the code I previously mentioned ...
var curTab = $('#example-2 .ui-tabs-selected');//  To retrieve the current TAB and assign it to a variable ...
var curTabPanel = $('#example-2 .ui-tabs-panel:not(.ui-tabs-hide)');//  To retrieve the current PANEL and assign it to a variable ...

YAY! I have what I need! Now what can I get from it?


In short, "Anyting yu want..."
That's right! You now have the power to go forth and do good work! I'll of course give you some examples. Remember earlier, how I showed you on the jQueryUI site, they mentioned how to get the index. See below on how to do that with this new piece of code ... and much ... MUCH MORE!
//  First, lets grab the panel for example-1
var curTabEx01 = $('#example-1 .ui-tabs-panel:not(.ui-tabs-hide)');

//  Now, to get the index just simply ...
curTabEx01.index();
//  To get the ID property of the current panel
curTabEx01.prop("id");
//  To get an attribute for the currently selected panel
curTabEx01.attr("class");
//  to get to something inside the panel and hide it
curTabEx01.find(".some-class-to-hide").hide();
//  and so forth and so on, I really hope you get the point by now
One Last thing to elaborate on. If you create your tabs exactly as seen in the jQueryUI examples, then your panel index will be on a 1-index value. This is not too much of a problem unless you expect 0-index value as with most things in coding. Just subtract one like: curTabEx01.index() - 1;
This is because the "ul" containing your "tabs" is technically index number 0.
HOWEVER!
If you want to have the panels be on a zero index value, and you don't want to subtract one every time you get the index, then you can place you panels inside their own encapsulating div element and it will not hurt anything. Like so:
<div class="demo">
    <div id="tabs">
        <ul>
            <li><a href="#tabs-1">Nunc tincidunt</a></li>
            <li><a href="#tabs-2">Proin dolor</a></li>
            <li><a href="#tabs-3">Aenean lacinia</a></li>
        </ul>
        <div class="panels-area">
            <div id="tabs-1">
                <p>Proin elit ...</p>
            </div>
            <div id="tabs-2">
                <p>Morbi tincidunt, ...</p>
            </div>
            <div id="tabs-3">
                <p>Mauris eleifend ...</p>
            </div>
        </div>
    </div>
</div>

Now you have the power, and hopefully the know-how to use it. G'luck coders and enjoy!

jsFiddle with example of this code in action

Friday, April 27, 2012

JavaScript Object.Join? With this jQuery Plug you can!

I had a need not to long ago to join an object much in the way you use Array.join().  Naturally, I thought it might be easier to convert the object's to array's, but then I thought, "Why not make a jQuery plug for this?  After all, how hard can it be?"  As it turned out, it was a little bit harder than I thought.  Although, I did finally figure it out and have been successfully using this plug for most of this year.  Now, admittedly, it hasn't been tested on every type of object, so if you use this and find an error, PLEASE COMMENT ME ABOUT IT!  After all, I can't "improve" it if I don't know where it is broken.  Also, if you do report a "bug", please be sure to give me some example of how you reached the bug so I can replicate the issue myself.  In this post, I'm simply going to add the jsFiddle (see below) as it has everything you need; the code, example usage, and example output.  Simply copy out the code between the comments in the JS area of the fiddle and paste it anywhere into your page you like, or paste it into a js file to be included in your header.  Perhaps one day soon, I'll make more official files and a better blog site, but for now, most you know what to do.


Wednesday, April 25, 2012

Simple JS Snippet for Adding a .position Function to the window Object

Not a whole lot to explain here.  I'll include a jsFiddle below that will even show you how to put this func on a timer to update value at a certain area (in my case, a pair of table columns) regularly so you can use this func to tell if the window is being moved!

This function is pretty straight forward and simple.  It first checks to see if anything else in the place of `window.position` and if not, it adds the simple function.  The function itself does nothing more than check browser version, then return an object containing an "x" and a "y" reflecting the current browser window's x and y position on your screen.

I forgot to mention, when I first posted this, using this function this way (preferably at the TOP of your JavaScript) not only enables `window.position`, but it actually assigns the function as a "global".  What this means is that you can recall it in most browsers by simply typing `position()`.  Now, just so you know, this is generally advised against for various reason's.  If you don't feel comfortable assigning this as a global function, you can always use a name-spacing ftw.  For more on name-spacing, check out this nice blog here.

The function:


The Example:

Tuesday, April 17, 2012

My Ongoing List of Fiddles (80+ & Counting)

Not sure why i'm doing this, other than to make it easier for ME to find my fiddles quickly, since the dashboard only show a few at a time.  But who knows, someone may find this page useful in finding my fiddles as well!  As you may notice, there is A LOT of "SO Help"(s), these mean they answered a question on Stackoverflow.com
FYI, it takes a minute to load ...

See more @ Spyk3's jsFiddle Dashboard!

Thursday, March 29, 2012

PHP: Get Age Comparison Results of 3 Functions

Perhaps I'll blog in detail more about these functions later, but for now, I'm going to present to you 3 of the more popular age formulas and the results I've found.
ALERT: function getAge_2 seems to be the most popular one I've found on the net and is the one that tends to be wrong!
First, the functions
function getAge_1($date) { // Y-m-d format
 $now = explode("-", date('Y-m-d'));
 $dob = explode("-", $date);
 $dif = $now[0] - $dob[0];
 if ($dob[1] > $now[1]) { // birthday month has not hit this year
  $dif -= 1;
 }
 elseif ($dob[1] == $now[1]) { // birthday month is this month, check day
  if ($dob[2] > $now[2]) {
   $dif -= 1;
  }
  elseif ($dob[2] == $now[2]) { // Happy Birthday!
   //$dif = $dif." Happy Birthday!";
  };
 };
 return $dif;
}

function getAge_2($date) { // Y-m-d format
 return floor((time() - strtotime($date))/(60*60*24*365.2425));
}

function getAge_3($date) { // Y-m-d format
 return intval(substr(date('Ymd') - date('Ymd', strtotime($date)), 0, -4));
}

The following results span 100 years from 1/1/1902 to today, 3/29/2012. As you will see in the following two tables, the key difference was found in getting the age of someone with a birthday tomorrow, expect on some years before 1932 where the difference was also found for the day AFTER tomorrow.

The Difference Table

Year

getAge_1

getAge_2

getAge_3

*1902-03-30*109110109
*1903-03-30*108109108
*1903-03-31*108109108
*1904-03-30*107108107
*1905-03-30*106107106
*1906-03-30*105106105
*1907-03-30*104105104
*1907-03-31*104105104
*1908-03-30*103104103
*1909-03-30*102103102
*1910-03-30*101102101
*1911-03-30*100101100
*1911-03-31*100101100
*1912-03-30*9910099
*1913-03-30*989998
*1914-03-30*979897
*1915-03-30*969796
*1915-03-31*969796
*1916-03-30*959695
*1917-03-30*949594
*1918-03-30*939493
*1919-03-30*929392
*1919-03-31*929392
*1920-03-30*919291
*1921-03-30*909190
*1922-03-30*899089
*1923-03-30*888988
*1923-03-31*888988
*1924-03-30*878887
*1925-03-30*868786
*1926-03-30*858685
*1927-03-30*848584
*1927-03-31*848584
*1928-03-30*838483
*1929-03-30*828382
*1930-03-30*818281
*1931-03-30*808180
*1931-03-31*808180
*1932-03-30*798079
*1933-03-30*787978
*1934-03-30*777877
*1935-03-30*767776
*1935-03-31*767776
*1936-03-30*757675
*1937-03-30*747574
*1938-03-30*737473
*1939-03-30*727372
*1940-03-30*717271
*1941-03-30*707170
*1942-03-30*697069
*1943-03-30*686968
*1944-03-30*676867
*1945-03-30*666766
*1946-03-30*656665
*1947-03-30*646564
*1948-03-30*636463
*1949-03-30*626362
*1950-03-30*616261
*1951-03-30*606160
*1952-03-30*596059
*1953-03-30*585958
*1954-03-30*575857
*1955-03-30*565756
*1956-03-30*555655
*1957-03-30*545554
*1958-03-30*535453
*1959-03-30*525352
*1960-03-30*515251
*1961-03-30*505150
*1962-03-30*495049
*1963-03-30*484948
*1964-03-30*474847
*1965-03-30*464746
*1966-03-30*454645
*1967-03-30*444544
*1968-03-30*434443
*1969-03-30*424342
*1970-03-30*414241
*1971-03-30*404140
*1973-03-30*383938
*1974-03-30*373837
*1975-03-30*363736
*1977-03-30*343534
*1978-03-30*333433
*1979-03-30*323332
*1981-03-30*303130
*1982-03-30*293029
*1983-03-30*282928
*1985-03-30*262726
*1986-03-30*252625
*1987-03-30*242524
*1989-03-30*222322
*1990-03-30*212221
*1991-03-30*202120
*1993-03-30*181918
*1994-03-30*171817
*1995-03-30*161716
*1997-03-30*141514
*1998-03-30*131413
*1999-03-30*121312
*2001-03-30*101110
*2002-03-30*9109
*2003-03-30*898
*2005-03-30*676
*2006-03-30*565
*2007-03-30*454
*2010-03-30*121
*2011-03-30*010

The Full table was way to big, so i'll find another way to show it later, gota get back to the grind, this was just to help others know! Laters!

Monday, March 19, 2012

Helpful Hints: Javascript/jQuery Knowing When the User Stopped Typing

This is just going to be a quick post with something on my mind to help new coders out there. Really I just need a short break from thinking.
Ever seen those handy dandy sites that preform some action AFTER you finish typing, rather than slowing down your device by trying to repeat the action for every character? Wanna know how to do it? GOOD! Then you're in the right place. This "type waiting" is actually very easy! It's all about timing ... or timers rather.
The one flaw to the following system is being unable to know the average type speed of a user. This is often countered by simply using a 2 second timer (although many sites use only a 1 second timer and preform fine). Two seconds is optimal because it is both: an easy amount of time that most people don't mind waiting to see a reaction, and is usually plenty of time to decide if even a "hunt 'n peck" user has stopped typing. However, you will only know what works best for your sight through experimentation. Now, who wants code?
On with the code! First I will example this action in javascript (hang on jQuery users, you're next) as it is really quite simple and will help you get a better idea of what is going on. The first thing you need to do is create a variable outside of your functions (preferably global, but its up to you, how, when, and where you want to use it). It doesn't have to be anything fancy, but be careful of name-spacing as per usual.
Ok, now that the hard part is over let's create our initial function.
Finally the really easy part, your WORK! Simply write the function you want called after the typeing timer stops!
With all the functions made, the rest is too easy. Simply find the element you want to attach it too. And viola! You're all done!
Now, for those of you using jQuery:
Create your variable. Then the code (even easier, cause its jQuery :D)

Enjoy!

Monday, March 5, 2012

jQuery: myURL Extension (How to get that pesky site URL on demand/dynamically)

UPDATE: Now includes Parameter support for making site links like http://www.mysite.com?para1=test&para2=test+2

As Seen in jsFiddle Example here:


I would also like to further reiterate that I do appreciate your input, good, bad, or indifferent!
     Let me first say, this is not my usual style blog in that I'm not going to explain this extension much today (perhaps another blog). This is simply to show off a fancy extension/plug-in I've made for jQuery that helps to retrieve your site URL (with parameters!) on demand.

     I find this feature most often useful when doing a lot of Ajax to PHP work where i'm needing to grab specific controllers or controller functions at specific moments. Usually in simple things like loading grids or collecting data for a live change of some sort.

     Anyway, on with the show! I'm going to start this by showing you how easy this function is to use. Then I'll give you all of it's possible uses. Finally, if you're just here for the extension, you'll find it at the bottom of this post.
     The Ease of Use!      OMG! That was so ... easy? Could it really be? And keep in mind, while there are many alternatives out there for doing this, most require you to check the browser version as different browsers have different methods for fetching the key info needed to build your URL string. I already did the work for you!

     Now let's look at many of the possible ways to use this so you can maximize your coding experience without a lot of horrendous thinking (ow my head!).

     Well you saw how to get the basic URL of your sight, but what if you need that ever famous `index.php` page? Try this:
     Now let's try something a little harder. Perhaps you need a image from your image folder that cannot be reached via the index.php but rather by your base URL plus images directory. In other words, your images folder would be like `http://spyk3lc.blogspot.com/images/`. LoL, all too easy for the myURL func!
     Wheh! We're almost to the end (finally, this is taking forever :P). You're final quest is to put it all together and grab a directory with content via the index.php add-in!
     Well, you're almost ready for the actual code, though I should throw just two more piece of info at ya. First, if you really don't like breaking it all down in multiple string parameters, then just use one! See:
     WAIT! What about this parameter update I came here for?      Perhaps you need your site link with data sent to a REST control or a youtube style player is on your site using your own videos, or whatever your purpose! Now simply include a JSON style object as the LAST parameter in your call to myURL and watch the magic happen!
     And finally, for you control freaks out there. I did ensure to include a config that can be run just after you add the plugin. These config options will allow you to set a main directory and sub-directory for both local and on-line use. Keep in mind though, these directories are added before index.php because this is ideal if you are working from a local host with multiple domain directories or even an online sand-box of the same setup. You can also change this at anytime, but every call you make to myURL after you change the config will be reflected.
FINALLY, the Plug-In!

Monday, February 27, 2012

How to Create a Simple jQuery Function

     I really feel the title of this should be "How to Turn Any Simple Function into a Reusable jQuery Function", but aside from that title being really long, if you're a bit of a jQuery noob, then you probably typed something similar to the the actual title in Google and thus ended up here.

     If you've used jQuery, or are just starting out, then you should realize jQuery functions as simplified namespace calls of otherwise tedious function calls.  For example, $.ajax() is a jQuery function that provides almost all of the complexities of an ajax call into one name space where parameters are passed through in simple json style such as $.ajax({ url: 'http://spyk3lc.blogspot.com' });.  You too can have this power!

     To demonstrate this easy procedure, I'm going to take something simple, used quite frequently ... everywhere and make it into a simple, reusable set of functions. So what is this all powerful command?  Simply tuning your cursor from default to waiting and back again.

     First, I'll look at the most simple approach.  Perhaps you simply want to set your cursor t wait while something is happening and then to default when that event is done.  So at the start of your action you may have something like:
While at the end of your action your change becomes:
     While this is a simple process, when surrounded by jQuery calls, it can look completely out of place and may not fit in the manner you wish.  So we want to change these calls to fit in jQuery style functions we can use again and again.

     A prior warning, this next couple steps negates paying attention to jQuery name-spacing and is not "best practice", however, before I end this article, I will explain a better way to "crop" this down to size and review why name-spacing is important, I promise.  For now, let's stick with the simple process of making those jQuery functions!

     The first thing to know is that this doesn't have to be wrapped in your typical "document.ready" bubble, as jQuery already provides a "plug-in" style way of adding your functions, after you've called for jQuery.  The mark up is simple:
     With that said, you are now ready to make your first custom jQuery function.  Inside your new extension set up, simply start your function with an if statement that determines if the namespace you're using is available in the jQuery library.  This if function is as simple as:
     Keep in mind, this check is no magic.  It is as simple as javascript trying to use the function $.cursorDefault and then getting a kick back tell it that namespace is undefined.  Yay! Then we can use it!  For future reference, get familiar with the console, and if ever question a namespace you are about to use, then simply try to console log it first to see if it exist.  For example, before writing this function we're about to write, if you want to double check if that namespace exist, then do the following:
  1. Use a browser like Google chrome and go to your page or even the jQuery homepage
  2. Open the debugging console (ctrl+shift+j in Chrome)
  3. Click to type in the console
  4. Type $.YourDesiredFunctionName
  5. If it says something like undefined after you press enter, then you are in the clear to use this as a function name, just be careful it doesn't interfer with any other desired
     Finally, we can make our first function.
     Walla! It was just that easy!  And reuse is even easier.  Simply type `$.cursorDefault();` and at that moment it is called, your cursor will magically become normal again.  Now where is that wait function?
     Oh there it is, but there is a problem here.  The namespace issue!  It's never a good idea to make multiple function names where one will do.  This is where you must be work smarter, not harder.  Think about what our two functions are doing and what they are similar too.
     Well, one function sets it to default or 0 as seen in the binary world, whereas the other provides it an action state.  This is very similar to a boolean!
     But how do we simulate this out of two functions?  Parameters!
    So now all we need is a new function name not being used by jQuery and one that probably want be used by other plugins.  In our case we'll use "cursorWait", as we already have it tested and working, but this time we're going to make a parameter change to it.
     So let's see how to rewrite this into one function name:
     Now, you have written your first jQuery function, and it's reuse is simple.
     Before we go,let me point out that our final function solution can actually be written in several ways.  I chose the switch statement simply to drive home the point that this will work weather it has a parameter or not.  However, since the only param we need is `false`, you could just as easily use a full if statement or even a online if statement such as:
     That's all for now!  Keep an eye out for more easy jQuery tips and even other language and library tips in the near future!  Good luck!