Detect CMYK in Browser

NewImage

 CMKY is supported in CSS3, but many browsers don’t provide support for it – and hence a problem if you have images rendered in it. CMKY as we well know, is used by designers and printing houses for it’s ease of use. As of CSS3 there is new color support; (with accompanying api calls) as below:

  1. HSL – hsl(hue, saturation, lightness)
  2. CMYK – cmyk(cyan, magenta, yellow, black)
  3. HSLA – hsla(hue, saturation, lightness, alpha)
  4. RGBA – rgba(red, green, blue, alpha)

A question in this direct context was asked on StackOverflow on how to detect CMYK support in the browser. 

Now there is three ways to resolve this:

  1. Server-Side Code (Asp.Net – Bitmap Api or Php – getImageSize – by looking at the image properties and maybe converting it to RGB to avoid this whole mess
  2. Browser Detection (jQuery/HTML Directive)  – mark those browsers that don’t support it, predominantly IE.
    1. if($.browser.msie && parseInt($.browser.version,10)<=8){}
      <!--[if IE 8]> <![endif]-->
  3. Javascript – validation by using the API and throwing an exception to validate it’s existence

I am going to be looking at the last method, number 3, as the prior two are real hacks and lead Alice down a Rabbit Hole she really shouldn’t traverse;

<html>

<head>

<script>

var IS_CMYK_SUPPORTED = (function(){

var value =‘cmyk(1%,1%,1%,0.5%)’,

el = document.createElement(‘p’),

result = false;

try {

el.style.color = value;

result = /^cmyk/.test(el.style.color);

} catch(e) { }

el = null;

return result;

})();

</script>

</head>

<bodyonLoad=‘alert(“IS CMYK Supported:” + IS_CMYK_SUPPORTED)’>

</body>

</html>


Simplistically, all that is happening here is a creation of an element to which we then try and set a color using the CMYK api. If the support is there we will return a valid result, if not the result will be false (via the exception thrown).
 
Hope this helps.
 
Reference the following URL for added information
Don't be shellfish...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

Why should I use SASS?

 Problem:

Being a web developer one often hits that momentous stumbling block, of though being able to knit code together amazingly, that the “code’s face”, the actual UI is not quite what as “beautiful” as it’s internal structure. Perhaps a reason for this is not a lack of creativity, but rather a syntax that is “sour, leaving a bitter taste” in ones mouth – and that of CSS. Sometimes it’s not that the developer lacks “design skills”, but that he or she fails to come to terms with a language that’s “crude and difficult to read”. 

It’s kind of like an “artist” who has a palette with “two colors”, and the result of every painting is a boring stale end-result that is repeated over and over. However, if the “artist” is then informed, that he/she has an array of colors, as they find or choose to be necessary; then what can be created is truly marvelous!

My point – CSS for new developers can take a while to understand, grasp or even stomach, and in steps SASS (Syntactically Awesome Style Sheets). This then, is that introduction to something sweet that can help make your “web development” experience more pleasurable and less painful (easy to maintain, and less repeatable).

 

SASS

What Is SASS?

SASS friend, is simply a framework or rather a set of tools for allowing developers to leverage CSS in a manner that is more logical, and as “Rails developers like to say”, more DRY (Don’t Repeat Yourself).

Why use SASS?

Why use SASS? Now a Google will return lots of results and I mean there are so many frameworks out there, unless referred to by a colleague etc; you almost pass it by, thinking it’s just another “web” technology among the myriad. So to address that I would like to just cover 3 of Top “PRO’s” of SASS, that can bring immediate improvement to your “development time and experience” and perhaps persuade you to use it.

Variables

In developing any web site, I like to stick to 3 colors at a maximum to predominantly decide the look and feel or the UI. Often times, I find myself hunting down shades of one primary color, like blue, light-blue etc (or rather their HEX Values).

The beauty of SASS, is that we have Variables, yes, actual “Variables”, so you can do something like:

 $gray-Dark: #474546;

So now, when I need to reference that, let’s say for a 


header {
 background-color: $gray-Dark;
}

footer {
 margin-top: 30px;
 padding-top: 5px;
 border-top: 1px solid $gray-Dark;
 background-color: $gray-Light;
}

The power behind this of course, is now you have one reference point for changing a color as opposed to rippling through multiple CSS or a large CSS to change the color for all accompanying tags. Also a great plus, for quick “mockups”.

But let’s say, however, I wanted to make my footer slightly lighter as a variant of Gray. I could define a new variable, as such:


$gray-Light: lighten($gray-Dark, 20%);

footer {
 margin-top: 30px;
 padding-top: 5px;
 border-top: 1px solid $gray-Dark;
 background-color: $gray-Light;
}

There are a myriad of other functions, and you should check that out (like “darken”, “lightness” etc).

Nesting:

Now traditionally with CSS you would do the follow to NEST;


#header {
 background-color: $gray-Dark;
}

#header h1 {
 float: left;
}

With SASS, ‘nesting’ is much sweeter; we can NEST directly inside the target (class).


#header {
 background-color: $gray-Dark;

h1 {
 float: left;
 }

}

Functions:

Would you believe it, yes, your own functions. Now I cannot express enough the power behind this, but let’s use an example to give you some idea.


#header {
 background-color: $gray-Dark;
 border-radius: 10px;
 -moz-border-radius: 10px;
 -webkit-border-radius: 10px;

h1 {
 float: left;
 }
}

#nav-left {
 padding: 5px 12px;
 margin: 10px 0;
 border-radius: 10px;
 -moz-border-radius: 10px;
 -webkit-border-radius: 10px;
}

#footer {
 border: solid 1px $gray-Dark
 border-radius: 10px;
 -moz-border-radius: 10px;
 -webkit-border-radius: 10px;
}

Now as you can see the border-radius is repeated 3 times. A change to one would require me to meticulously make changes to all three. But that’s a bit cumbersome not to mention extra code, extending the size of my file, and decreasing readability. With SASS, I can instead rip out this ‘CSS’ and create a seperate function for this which I can address in all 3 places.

At the head of my file, where my variables are declared; we add in our Function, or as SASS calls it, MIXIN.


@mixin &lt;name&gt; {

// CODE TO REPEAT
}

@mixin rounded-corners {
 border-radius: 10px;
 -moz-border-radius: 10px;
 -webkit-border-radius: 10px;
}

And it’s implementation like this:


#header {
 background-color: $gray-Dark;
 @include rounded-corners

h1 {
 float: left;
 }
}

#nav-left {
 padding: 5px 12px;
 margin: 10px 0;
 @include rounded-corners
}

#footer {
 border: solid 1px $gray-Dark
 @include rounded-corners
}

But let’s say, the rounded corners are different for #nav-left – instead of 10px for the border-radius it should be 8px. How can SASS help us?

Well a “function” (mixin) is not a true function unless we can also provide “parameters” or “arguments”. So let’s modify our MIXIN a little to support custom radii.

That is:


@mixin rounded-corners($radius) {
 border-radius: $radius;
 -moz-border-radius: $radius;
 -webkit-border-radius: $radius;
}

But before we implement, how about a default, in places were the MIXIN is used, but no radius is specified;


@mixin rounded-corners($radius: 8px) {
 border-radius: $radius;
 -moz-border-radius: $radius;
 -webkit-border-radius: $radius;
}

Beautiful isn’t it, but let’s look at our implementation, which if you being any sort of developer should already have in your mind:


#header {
 background-color: $gray-Dark;
 @include rounded-corners(10px);

h1 {
 float: left;
 }
}

#nav-left {
 padding: 5px 12px;
 margin: 10px 0;
 @include rounded-corners(8px);
}

#footer {
 border: solid 1px $gray-Dark
 @include rounded-corners(10px);
}

But the programmability doesn’t end there, and again, so not to overload you with information, but to give you an understanding of it’s power; SASS also supports Conditional States (if, else if, else); as well as “For” loops and “For Each”.

Conclusion:

This is just the tip of the iceberg of SASS, and if you would like to learn more, you can visit the following links:

  1. SASS Website
  2. SASS Functions
  3. Beginner Tutorial on SASS
  4. Advanced Tutorial on SASS
Don't be shellfish...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

HTML Scraper with Ruby

Introduction:

 

Great Gem

Being a .NET Developer by trade, I’ve become increasingly interested in Ruby. Being a C# developer for years, one finds one self often drifting to the “dark side” of open-source to play, learn and experience.

And on one such night, I decide how about test driving Ruby – and this little project. In South Africa we have an online business Directory, and I thought writing a HTML Scraper would be a great first project in this language that speaks of “Convention over Configuration”, and “DRY”.

So where to begin?

Requirements:

Well, firstly, what are our requirements:

(a) A quick review of the business directory, revealed a list of Supermarkets available across Africa, and that will be the data we will mine for 

(b) Obviously the output should be in a “form” that we can use, CSV/PlainText.

( c) Perhaps a Library (Gem) that we can use to Scrape the HTML (that is manipulate the HTML/DOM), and that is NokoGiri.

(d) Understanding the layout of the pages and understanding the data structure (Name, Postal Address, Telephone etc). As with all websites of any value – CSS is inherent, and standards for presenting large amounts of data in the same structure (so we should be one up already)

Reviewing the Structure:

  1. Determine what the URL is going to look like and obviously because the information for the super-markets/stores are large they are paginated, so let’s see if we can find a way to reference them directly (that is get their pagination address).  As you can see below that seems to be the constant URL, and reviewing the “pagination” links, a number is added to the end in iterations of 10. That is; /S0914E/10 or /S0914E/20Url
  2. Secondly, breaking down the structure of a store/supermarket – we can almost guarantee they will be broken down by a <div>. I’m using Chrome and “Inspect Element” to narrow down the data and it’s structure. Each store is found in a class called “list-directory_entry_4”, the title for the store in a div class called “list-entryTitlebar” in the TEXT of the <a href>. The class “list-details” gives extra details about the store (location). Also there follows a URL that links to extra information which we will scrape as well found in class, “list-entryInfoBar”Structure of Store's Data

Code Time:

  • Some points worth noting, I use am STDOUT in Ruby to create our CSV. I call “sync” at the end to dump after I complete a page, else it will build in Memory (not good when dealing with tons of pages)
  • Secondly, NokoGiri supports XPath which is wonderful for accessing the HTML. Note I am using XPATH with starts with to match for some inconsistencies in store “divs”. Very handy! page.xpath("//div[starts-with(@class,'list-directory_entry_')]")
  •  In this section of code, I am creating the URL’s I intend to work with; that is the paginated pages with the content. So that I can apply the generic HTML scraping algorithm to it. 
  • URLs
 
  • Then iterate each URL, using NokoGiri, and use the XPath explained above to find the “div” for a store to scrape.XPath


  • Thereafter I grab the specific data I need using “css selectors” found in NokoGiri; Selector
 
 
 
             Lastly, I make use of .gsub(/s+/, “”) to remove any spaces that are not necessary. That’s it really, nice and simple.
  • Gsub



Code:

 

require ‘rubygems’
require ‘nokogiri’

require ‘open-uri’
#Create File for Output
$stdout = File.new(‘console.out’, ‘w’)
arrPages = Array.new
pageLoc = 10
#First Page (396 paginated pages)

arrPages.push “http://x.x.com/type/supermarkets/any/supermarkets/S0914E/”

 

for i in 1..396

arrPages.push “http://x.x.com/type/supermarkets/any/supermarkets/S0914E/” + pageLoc.to_s()

pageLoc = pageLoc + 10;

end
arrPages.each do |pageToScrape|
page = Nokogiri::HTML(open(pageToScrape))

page.xpath(“//div[starts-with(@class,’list-directory_entry_’)]”).each do |store|


result = String.new

iUrl = String.new

array = Array.new

 

# Get Details [Name] + [Location]

array.push store.css(“h2 a”).text + “|”

array.push store.css(“.list-details”).text + “|”
# Get About
# Get’s the More Info Page, filters that

iUrl = store.css(“.list-entryInfoBar a”)[0][‘href’]
infoPage = Nokogiri::HTML(open(iUrl))

array.push infoPage.css(“.phone”).text + “|”

array.push infoPage.css(“.fax”).text + “|”

array.push infoPage.css(“.email”).text + “|”

array.push infoPage.css(“.web”).text + “|”

array.push infoPage.css(“.address_1”).text + “|”

array.push infoPage.css(“.address_2”).text + “|”

 

puts array.join{” “}.gsub(/s+/, “”)

$stdout.sync = true
end

sleep 20

end


Helpful Links

  1. NokoGiri Tutorial
  2. Ruby in 20 minutes
  3. Other Ruby Help
  4. Bastards Book of Ruby

 

 

Don't be shellfish...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

Sencha Custom Build (ExtJs 4.0/4.1)

I cannot tell you, or express the deep frustration and anger I feel when a company who is so public, and who create such good software produces a tool to fulfill a desired task, but the documentation is near non-existent, the support lacking, and the tool itself, a piece of “junk” from the pits of hell. <rant over Sencha>

Moving along, if you want to build custom ExtJs, cause obviously the default one is too big to be used on production websites; here is the process to go about:

  1. Read This with a focus on the new MVC model as well as Sencha SDK –http://www.sencha.com/learn/getting-started-with-ext-js-4/
  2. Download the SDK (version 2 and not 1.2.3)
  3. Huge thanks to Sottilde – http://www.sencha.com/forum/showthread.php?203663-Sencha-SDK-Tools-2.0-and-ExtJS4-The-Missing-Docs (this is a must) – make sure you download the new PhantomJS file
  4. On the latter part of that forum, I posted my index-build.html, my configuration file (Layout.js) and some tips as well (especially if you using ASP.NET)

Hope that helps ya!

Don't be shellfish...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

ExtJs Double Load

I recently starting working with ExtJS, moving away from jQuery UI Layout for a bug in their “splitter”. This was not fixed by them, despite my bug report. They did make an effort which  I appreciate. But I’m getting side-tracked. The problem I was experiencing in migrating to ExtJS was that I had an iframe that was loading in my “center” but it was loading twice.

No matter what I did, it just reloaded twice. Whether I added it with $(document).ready(). The solution was to add it to my “ExtJs” layout configuration, and success:

Don't be shellfish...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

Struggling to Remember Passwords?

Much has been said about Passwords and their importance. The problem of course is that “security” itself is a hindrance to the memory as well as to man’s ability to fulfill a desired function. I often get stuck visiting different website, where I registered 1 year ago, or when I last accessed 2 years ago.

I like any ordinary programmer, would prefer using in Memory Cache (my brain), as opposed to using some tool to manage it with the possibility that it might be intercepted via keystroke or the password cracked to provide every one of your details.

Instead what I have done is a simple concept; I have a Password Structure that is dependent on the Website I visit. An example;

Structure: <Last 4 Letters of Surname><Website Name><First 4 Numbers of Cell Phone>

So if I visited Gmail;

My password would be:

aliaGmail6777

Now instead of having to run some stupid password generation tool, or even bother with opening KeyPass; I have a generic structure to which I can approach any site and know my password.

Holding the Key to the Door, Makes it Much Easier to Turn the Knob.

Cheers

Dane

Don't be shellfish...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

Preventing ‘Stop running this script’ in Browsers

 Introduction

On all major versions of IE you may run into this error – “This page contains a script which is taking an unusually long time to finish. To end this script now, click Cancel”. This is beyond irritating especially when the code is live and is affecting customers. Microsoft has a fix for it, but obviously we cannot ask a customer to do this.

Background

What we are going to try and do is create a “for loop” that builds an array. But consisting of 100000 items.

Using the code

I’ve include a sample project – it’s always so much easier when you can play with the code yourself. Have fun!

Before we get into the code, Kudos completely to Guido Tapia for his code and implementation.

I’ve modified the code and made it slightly mode applicable to me, and also to external readers who do not have the context of the code. There was also some bugs which I ironed out. But again, Kudos to him.

 Collapse | Copy Code
 // Make an Object
RepeatOperation = function (anonymousOperation, whenToYield) {
    var count = 0;
    return function () {
        if (++count >= whenToYield) {
            count = 0;
            setTimeout(function () { anonymousOperation(); }, 100);
        }
        else {
            anonymousOperation();
        }
    }
};

Above we create a simple Object called “RepeatOperation”. In it we have to arguments. One will be our (or your) anonymous operation (work that needs to get done). The second argument, will be the when to yield, or when to fire the Time Out.

In side the function, is a basic count to determine where we are in the “process”. Every time our anonymous operation is called it will come back in here and increment count. When it reaches the yield count, it will then set the Time Out letting the Browser know that this is no an infinite loop.

 Collapse | Copy Code
// Implementation
var i = 0;
var myArray = new Array(noInArray);
var yieldAfter = 100;
var noInArray = 100000;
var ro = new RepeatOperation(function () {  // Anonymous function which is our work that we need 2 
    myArray[i] = i * 1;
    if (++i < noInArray) {
        ro();
    }
    else {
        // Finished with Operation
        $("#txtBox").val("Completed Operation and no Browser Warning!");
    }
}, yieldAfter);

// Let's begin
ro();

Now we get to the meat – remembering that state is maintained across the calls due to that little thing called “closure”. For a better understanding of this implementation, look at this, it’s a wonderful read.

Moving along, we create an instance of RepeatOperation, passing in our “operation” as well as when to yield (after x number of iterations). We then begin by calling RepeatOperation through ro(); Remembering in light of closures, this will now call the “return” function found in RepeatOperation, and where it will validate where we are, and set the Time Out if necessary.

The code will continuously call itself back, and while doing so, build the array that we need or get the work done that we need. When done, it will finish and add the text to our “txtBox”.

Don't be shellfish...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

SignalR – Building Blocks

If you are not aware, to ensure communications of messages, SignalR uses three techniques (found across browsers) [ in this order ];

  1. WebSockets (support in HTML5): This is an HTML 5 specification for a single socket connection (full-duplex) [ Javascript Interface] over which messages can be sent between client and server.
  2. ServerSideEvents (support in other browsers): Also called Event Source. It’s a push technology for sending notifications from the server to a client in the form of DOM Events.
  3. ForeverFrames (support in IE): This makes use of Chunking as found in the HTTP specification, but simiplistically is a Hidden iFrame in a Page that maintains a long-lived connection. Chunking is the process of breaking down large data and sending it incrementally and that same concept exists here with the Hidden iFrame.
  4. Long Polling: Like Polling except the server does not return to client until it is complete (getting the data)
So it will make use of each of these 4 technologies as it sees fit, where it is supported or not.

Hope this helps.

Dane

Don't be shellfish...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone