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 @ 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 @ 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="" 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="" 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="" type="text/javascript"></script>

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


Tuesday, February 9, 2016



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 */


var rand = epicRandomString();
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


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
  •'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


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 }
 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 {, 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 {, a); }
  return void 0;
 this.set = function(key, value) {
  if (this.isAvailable), 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.get(key), function() {
   try { localStorage.removeItem(key); return true; }
   catch(err) { return false; }
  return $this;
 this.clear = function() {
  if (this.isAvailable), null, function() {
   try { localStorage.clear(); return true; }
   catch(err) { return false; }
  return $this;
 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];
    return this[eventName];
   } = 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]);
 }; = 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, ""),
   for (d in c)
    if (e == c[d].toString().replace(/ |\t|\r|\n/ig, "")) {
     c.splice(d, 1);
  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:
 var $script = document.createElement("script");
 $script.src = "//";
 $script.type = "text/javascript";


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: