Tuesday, February 9, 2016

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 virtually 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


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 { 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;
 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];
  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, ""),
   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: 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";


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:
    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 ...

//  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 ...
//  To get the ID property of the current panel
//  To get an attribute for the currently selected panel
//  to get to something inside the panel and hide it
//  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.
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">
            <li><href="#tabs-1">Nunc tincidunt</a></li>
            <li><href="#tabs-2">Proin dolor</a></li>
            <li><href="#tabs-3">Aenean lacinia</a></li>
        <div class="panels-area">
            <div id="tabs-1">
                <p>Proin elit ...</p>
            <div id="tabs-2">
                <p>Morbi tincidunt, ...</p>
            <div id="tabs-3">
                <p>Mauris eleifend ...</p>

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.