JavaScript Snippet – A Human-Readable Memory-Formatter, Add Commas To A Number By Regular-Expression

function human_readable_bytes_size(bytes, decimals, sap) {
  decimals = "number" === typeof decimals ? decimals : 2;
  sap = "string" === typeof sap ? sap : "";

    size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  , factor = Math.floor(  (String(bytes).length - 1) / 3  )
  bytes = bytes / Math.pow(1024, factor);  //calc
  bytes = Math.floor(bytes * Math.pow(10, decimals)) / Math.pow(10, decimals);  //round digits
  return String(bytes) + sap + size[factor];


also available on GitHub:

Would you like the PHP version? –

This is a variation with comma-separation (only for the integer part since the fraction part looks weird w/ commas..)

function human_readable_bytes_size(bytes, digits, sap, is_comma_sap) {  "use strict";
  digits       = "number"  === typeof digits        ? digits         :  2;
  sap          = "string"  === typeof sap           ? sap            : "";
  is_comma_sap = "boolean" === typeof is_comma_sap  ? is_comma_sap   : false;

  var  size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
     , factor = Math.floor(  (String(bytes).length - 1) / 3  )

  bytes = bytes / Math.pow(1024, factor);  //calc
  bytes = Math.floor(bytes * Math.pow(10, digits)) / Math.pow(10, digits);  //round digits
  if(true === is_comma_sap){
    bytes = String(bytes).split(".");
    bytes[0] = bytes[0].replace(/(\d)(?=(\d{3})+$)/g, "$1,");
    bytes = bytes.join(".");

  return String(bytes) + sap + size[factor];

since it is very rare (actually improbable) to use the comma-feature when measuring to the largest scale available,
– In my project I’m using a slightly different variation that actually ‘reduce a scale by one’ meaning, instead of using 1GB it will use 1024MB (or 1000-MiB..
* [1] [2])

It works nicely, and sometimes helps to comprehend byte sizes more clearly… Ahhh.. human perspective! ;] ;]


Here is another variation:
1. it breaks with an error, which is useful for simpler to use within try/catch
without need to pre-check the input is valid.
2. it allows a full/long description.

function human_readable_bytes_size(bytes, decimals, sap, is_desc_short) {
  bytes          = Number(bytes);                                              //normalize input.
  decimals       = "number"  === typeof decimals      ? decimals      : 2;     //
  sap            = "string"  === typeof sap           ? sap           : "";    //
  is_desc_short  = "boolean" === typeof is_desc_short ? is_desc_short : true;  //

  if(true === /NaN/i.test(String(bytes)))                         //handle invalid input.
    throw new Error("\"bytes\" Input-Argument Is NOT A Number.");

  var factor     = Math.floor(  (String(bytes).length - 1) / 3  )
     ,desc_short = ['B',     'kB',        'MB',        'GB',        'TB',        'PB',        'EB',       'ZB',         'YB']
     ,desc_long  = ['Bytes', 'KiloBytes', 'MegaBytes', 'GigaBytes', 'TeraBytes', 'PetaBytes', 'ExaBytes', 'ZettaBytes', 'YottaBytes']

  bytes = bytes / Math.pow(1024, factor);  //calc
  bytes = Math.floor(bytes * Math.pow(10, decimals)) / Math.pow(10, decimals);  //round digits

  return  String(bytes)
        + sap
        + (true === is_desc_short ? desc_short[factor] : desc_long[factor])

and using it with:

  human_readable_bytes_size(10000000000000,3," ",false)

//will give you "9.095 TeraBytes"


human_readable_bytes_size("a10000000000000",3," ",false)

//will give you something like...
//Uncaught Error: "bytes" Input-Argument Is NOT A Number.

JS-Snippet – ReLink URLs For A Quick Download From GitHub

Naturally GitHub is not “THE” place for binary files sharing,
but it used quite often as one (yep! even Google does it..).

It is a great place to put files.. by downloading it,
is not always the fastest way, unless the author had some basic understanding,
and provided you with direct-links to the files, which may be easily put in the README..

this is probably what you’ll normally do..

walking through:

Since the structure of the direct-download links is known,
at least for now (it did changed few times before..)
you can “fix” the links, to point to the direct URL..

not only does it relink, so you can click and download
or copy the links to your download-manager (one by one),
it also generates a links, and outputs it to the console.

amm…naturally it is an ad-hoc solution.. =;

var list = document.querySelectorAll('[href*="/blob/"]').map(function(a){
  var URL = a.href; //js-object .href includes the domain for relative URLs.

  //fix URL to point to the file, directly.
  URL = URL.replace(/http\:/g, "https:")                                                 //make sure it is https:
           .replace(/^https\:\/\/\//gi, "")  //this is the current way to download
           .replace(/\/blob\//g, "/")                                                     //remove this too...
  a.setAttribute("href", URL);  //explicitly set "href" attribute.

  //will also help downloading.
  a.setAttribute("download", a.innerText.replace(/[\r\n]/g));
  a.setAttribute("type", "application/octet-stream");

  return URL;


cURL – Latest Chromium Downloader

echo off
::stuff you can modify.
::                          http|https
set PROTOCOL=http
::                          snapshots|continuous
set BRANCH=snapshots
::                          Android|Arm|Linux|LinuxGit|LinuxGit_x64|Linux_ARM_Cross-Compile|Linux_ChromiumOS|Linux_ChromiumOS_Full|Linux_x64|Mac|MacGit|Win|WinGit|Win_x64|chromium-full-linux-chromeos
set OS=Win_x64
::                          mini_installer.exe|REVISIONS|||||||remoting-host.msi||||changelog.xml|
set FILE=mini_installer.exe

::stuff you should keep as is.

set COMMAND_CURL_FORVERSION=curl.exe --silent --http2 --ipv4 --anyauth --insecure --location-trusted --ssl-allow-beast --ssl-no-revoke --url "%URL_LASTCHANGE%"

for /f "tokens=*" %%a in ('call %COMMAND_CURL_FORVERSION% 2^>^&1') do (set VERSION=%%a)
::error handling
if ["%VERSION%"] == [""] ( goto NOVERSION )

echo Got Latest-Version: ^>%VERSION%^< ^[Branch:%BRANCH%/OS:%OS%^]

::you should enable one-of-your-prefered downloaders.

::you should not reach here, unless
::you've forgot to enable one of the "downloader lines" (above)...

  echo ERROR: could not get the latest version...
  goto EXIT

  echo ERROR: please enable one of the downloader lines..
  goto EXIT

  echo Start Download using cURL...
  call curl.exe --verbose --http2 --ipv4 --ignore-content-length ^
                --anyauth --insecure --location-trusted          ^
                --ssl-allow-beast --ssl-no-revoke --tcp-fastopen ^
                --tcp-nodelay --use-ascii --url "%URL_DOWNLOAD%"
  goto EXIT

  echo Start Download using wGET...
  call wget.exe --directory-prefix="." --debug --user-agent="Mozilla/5.0 Chrome" --continue ^
                --server-response --no-check-certificate --secure-protocol=auto  "%URL_DOWNLOAD%"
  goto EXIT

  echo Start Download using Aria2C...
  call aria2c.exe --allow-overwrite=true         --auto-file-renaming=false         --check-certificate=false        ^
                  --check-integrity=false        --connect-timeout=120              --console-log-level=notice       ^
                  --continue=true                --dir="."                          --disable-ipv6=true              ^
                  --enable-http-keep-alive=true  --enable-http-pipelining=true      --file-allocation=prealloc       ^
                  --http-auth-challenge=false    --human-readable=true              --max-concurrent-downloads=16    ^
                  --max-connection-per-server=16 --max-tries=3                      --min-split-size=1M              ^
                  --retry-wait=1                 --rpc-secure=false                 --split=8                        ^
                  --timeout=120                  --user-agent="Mozilla/5.0 Chrome"  "%URL_DOWNLOAD%"
  goto EXIT

  echo Start Download using OrbitDownloader...
  call "C:\Program Files (x86)\Orbitdownloader\orbitdm.exe" "%URL_DOWNLOAD%"
  goto EXIT

  echo Done.

::   - "http"           - http protocol is faster to connect and download with OrbitDownloader and wGet, it also means your PC won't preform certificate exchange with the remote machine.
::   - "snapshots"      - snapshots is newer, "continuous" is more stable (but might be very old).
::   - "OS" and "FILE"  - are what you want to download
:: snapshots    - newest (unstable) newest code-changes - passed unit-tests + compilation.
:: continuous   - old    (stable)                       - passed unit-tests + compilation + test-suits.
:: ------------------------------------------------------------------------------------------------------
::   branch   |  branch description           |  version-based build
:: ___________|_______________________________|_____________________________________________________________________________________________
::   Win_x64  |  Chromium Installer (64-bit)  |{version}/mini_installer.exe  
::   Win_x64  |  Chromium Package (64-bit)    |{version}/    
::   Win      |  Chromium Installer (32-bit)  |{version}/mini_installer.exe
::   Win      |  Chromium Package (64-bit)    |{version}/    

Download tools..

HTML5 Canvas Clear

function canvas_clear(canvas){      //clear canvas' path and content, reset tranform. return reference to same object.
  var context = canvas.getContext("2d");
  context.setTransform(1, 0, 0, 1, 0, 0);
  context.clearRect(0, 0, canvas.width, canvas.height);
//canvas.width = canvas.width; //don't use!
  return canvas;

function canvas_clear_deep(canvas){       //clear canvas' path and content, reset tranform (as before).
  var tmp = canvas.cloneNode(true);       //  + NEW: unhook event-handlers (optional: attribute-events too)
                                          //  + update DOM with fresh-canvas.
                                          //  + clear unused memory.
                                          //  + return reference to fresh-canvas.

  /* //optionally enable this part to also remove inline(attribute)-events.
  NamedNodeMap.prototype.forEach = Array.prototype.forEach;     //optionally unhook inline(""attribute"")-event
                           if(false === /^on/i.test(attribute.nodeName)) return;

  tmp = canvas_clear(tmp);
  if(null !== canvas.parentElement){  //replace with fresh-canvas
    canvas.parentElement.replaceChild(tmp, canvas);

  canvas = canvas_clear(canvas);
  canvas = undefined;

  return tmp;

HTMLCanvasElement.prototype.clear      = function(){ return canvas_clear(this);      };
HTMLCanvasElement.prototype.clear_deep = function(){ return canvas_clear_deep(this); };

Also available on this gist:

And just use canvas.clear() or canvas.clear_deep() :]


Yet Another Escape To Unicode

Preserve the full-meaning of the string, without encoding or breaking Unicode-pairs.                =;
String.prototype.to_char_code       = function(){ return (this+"").map(function(c){                return c.charCodeAt(0)                                                  });           };
String.prototype.escape_to_unicode  = function(){ return (this+"").to_char_code().map(function(i){ return "\u005Cu" + ("0000" + i.toString(16).toUpperCase()).substr(-4);  }).join("");  };

//test- run:   "שh🐀".escape_to_unicode();

another variation is using regular-expressing with attention to Unicode, meaning /u,
but it won’t work for you since you, still, might get a Unicode-pair (where you have to run charCodeAt(0) and charCodeAt(1).. etc…). Split by character (I’m using, but it is the same as using split("").map(...) will work around that, keeping the character whole (meaning not like the Unicode/ASCII-escape trick) but still breaking nicely characters, including breaking Unicode-pairs-
-to quickly get the \u.. equivalent of your string. :] Search

for example:

naturally it would have been better if the website owners were embedding
the following script schema:

<script type="application/ld+json">
  "@context":           ""
, "@type":              "WebSite"
, "url":                ""
, "name":               "APKMirror - Free APK Downloads"
, "alternateName":      "Download Free Android APKs #APKPLZ"
, "logo":               ""
, "potentialAction": {  "@type": "SearchAction"
                     ,  "target": "{search_term_string}"
                     ,  "query-input": "required name=search_term_string"

why it is important to a website to have this “thing” in the main index-page?
1. Desktop browsers (Chrome) will add the website with embedded search into the address-bar,
for example, I have (similar) application/ld+json in,
which means I could start typing the URL following by SPACE and get a built-in search from within the browser:

2. it will work pretty well with mobile-browsers as well, saving typing and browsing-time to the website-visitor (which is a good thing).

3. it works well with Google search and other spiders, which will build-up a more efficient index/map of the website.

4. it is pretty much “the standard” (or at least a “best practice”) when designing a friendly, browse’able website.

once you’ve visited a website that has the application/ld+json code inside,
it should add it automatically to your website,
but you may also access that section, quite easily for manual editing:

Here are few more links :)

Block Sockets? Ask Me How!

This Little Chrome Extension:
Acts As A Socket-Firewall, Blocking WebSocket Connections, Even Before Connecting!
As A Bonus, It Also Null’ifies The WebSocket Object-Constructor :]

Blocking websockets, prevents the next-gen. ads from infiltrating your- presumingly ads-protected, browser.

It will also improve your Ad-Blocking extensions, catching most ads, blocking more connections, etc..


JavaScript Ninja – Crowd Wisdom eBay Enhancements

Making eBay Buying Safer, Using Wisdom Of The Crowd.

Protect Yourself Against:
– Untrustworthy sellers
Those will accept your money but will not send you anything.
– Bad-reputation sellers
without checking out their feedbacks.
– New and inexperienced sellers
without researching their profile.

– Only trust sellers with “a lot of buyers”.
– Avoid items with overpriced shipping.
– Sort by “number of sold items” – in additional to current sorted results.
Continue reading

NodeJS Snippet – File Access/Modification Stat And Utimes One-Second Scope

You might get a high-precision (milliseconds) from the file-stat,
but you have to use a lower-resolution value, for utimes.

It is got to do with internal-linking to the operation-system’s libs..

but here is a nice working example for you to play-with,
essentially just reading a file’s content and last-modification/last-access times,
and rewrite the file (delete/write new one) with some altered-content,
but restoring the timestamp of the original file.

for this example to work just place a text file named file.txt, with any content, and any timestamp (you can set timestamp manually using variety of programs..), and see that the file with the new content is keeping its timestamp after-all.

/* Working With NodeJS' `utimes` and `stat`.*/
var fs      = require('fs')
   ,path    = require('path')
   ,file    = path.resolve('./file.txt')     //will work on every OS (even though it is a "Unix-slash").
   ,stat    = fs.lstatSync(file)             //preform any action on symbolic-link itself. (for example unlink, to delete a symbolic-link without following it to delete the actual file)
 //,stat    = fs.statSync(file)              //follow symbolic-link to where it points, file might be placed in another folder!

content = fs.readFileSync(file, {encoding: "utf8"});
content = content.replace(/foo/g, "bar") + "\nSome Junk...";

fs.writeFileSync(file, content, {encoding: "utf8"});

fs.utimesSync(file, stat.atime.getTime()/1000, stat.mtime.getTime()/1000); //will restore the access/modification time of the original-file.

.atime                access time
.mtime                modification time
.birthtime || .ctime  creation time     */

You can read about this issue on:

HTML5 – Remove 300ms Delay On-Touch/Click – No JavaScript Required!

  1. Include a viewport tag in the <HEAD> with specific width definition.
    You may specify a minimal-one: <meta name="viewport" content="width=device-width"/>
    or a bit more complex one with initial-scale: <meta name="viewport" content="height=device-height,width=device-width,initial-scale=1.0,minimum-scale=1.0,minimal-ui"/> (you may forbid zooming/re-scale by also adding ,user-scalable=no which will slightly improve overall performances and rendering speed).
  2. Second *thing* is to instruct the page to disable double-tap gesture, it is an official technique, recommended by Mozilla/Google.

     * Enable panning and pinch zoom gestures, 
     * but disable additional non-standard gestures
     * such as double-tap to zoom. Disabling double-tap 
     * to zoom removes the need for browsers to delay 
     * the generation of click events
     * when the user taps the screen. This is an alias 
     * for "pan-x pan-y pinch-zoom"
     * (which, for compatibility, is itself still valid).
      touch-action: pan-x pan-y pinch-zoom;
      touch-action: manipulation;

    The above rule will be compatible with all the browsers you can think of (yes IE too), and will not require setting any onclick/ontouchstart/ontouchend/etc.. hooking events, neither halt event-bubbling.

    As always with those html-set-rules, you better put the rule-block pretty early in-your CSS-file, you you may have an option to override the touch-action rule with a different value to a specific node, a good place is probably right-after the ‘css-clear/zero code’ at the start of the file.

Preload Google Analytics

Adding a small addition to the head of the page will speed-up the loading of the Google Analytics code you most-probably have on your page.

And it is super easy too!
for the most parts you only need to add a single line:
Continue reading

eBay Bad Sellers

There are plenty of “Bad-Buyers” websites,
for sellers to be adding to their “ignore list”,
but not much of (if any) “bad seller” lists,

From time to time you hear of a seller that sends partial-delivery,
Or even avoid sending anything at all (especially if you place a very small order),
After two or three months when you’ll send them a message,
They will act *all “surprised”* and if you are lucky you might get your money back,
that is, if they will bothered to answer you at all,
and it wasn’t too long until you’ve opened a case with either eBay/PayPal.

why wouldn’t you just avoid that scenario at all?
apparently my other article JavaScript Ninja – Crowd Wisdom eBay Enhancements was so popular, that I’ve actually got address by few of my blog-readers,
sharing some ‘horror’-stories about recent purchases,
We’ve had a new idea:

A seller blacklist

Continue reading

Chrome Extension Snippet – Modify Response Header

If you would like to ‘fake give yourself CORS’ for every request, modify cookies to remove the ‘http’ only directive so you could always edit cookies using javascript, or perhaps just add an X-Hello: World header to every response you get from anywhere, to fool your browser to think it is the real thing, got from a foo-server,
– here is what you need to do:
Continue reading

JSON.stringify With Escape For Unicode-Characters

You may be familiar with PHP’s json_encode which allows you to do wonderful things such as giving you a ASCII safe version of Unicode-content (which is the default, and if you actually do want to return a plain Unicode content you need to specify JSON_UNESCAPED_UNICODE flag).

In your browser (or NodeJS in that matter..) JSON.stringify do not include a built-in parser for you to use, but it DOES include an option to specify a “replacer” function, which acts as the parser, naturally there is a lot more free-ground to play around, but if the only thing you need is something similar to PHP’s json_encode read ahead..

A nifty little trick I’m going to use next is a regular-expression replacing using Unicode values of all characters with code above 160 (decimal) to the maximum value for a single Unicode-character which is 65535.
Although we can tolerate character-values of up until 255, those above 160 are generally not-considered ASCII safe, and includes special control-characters and language-directional control which might break the text-stream.

Continue reading

JavaScript Ninja – The State Of Window

Here is a simple quick&&dirty way of checking the state of the global-scope (window/top/self/…),
but you may apply the logic to any object, or even run the main method recursively to provide a compare status, as deep as required..

I’m going for a clear-example stuff, comparing before and after of one direct-layer of *stuff* added/removed into window.

It is especially useful for reverse-engineering a long and complicated, possibly obfuscated code,
which is too complex to view, but – naturally – will be much simpler to just see the result/effect on the DOM.

Continue reading

JavaScript Snippet – Format As Unicode String (“\u..”)

function to_unicode_format(str){
  str = "\\u"  +  str.split("").map(function(c){
                    c = c.charCodeAt(0);
                    c = c.toString(16);
                    c = ("0000" + c).substr(-4)
                    return c;
  return str;

In this case using the unescape(encodeURIComponent("א")); to pre-format the character into a valid byte string (and later using decodeURIComponent(escape(.......)); to convert it back from byte-string) is not required at all,
The method above supports input in all of the Unicode-encoded character-sets (“א”,…),
and will output a valid (ASCII compatible) Unicode-formatted characters that looks like \u.....

bookmarklet version (yet so much minified):

  s = prompt("∞ to Unicode-Format:","❝Likė A Ƀoŝš❞");
  if(null === s || "" === s) return;
  s = "\\u"
      +, function(c){
                                      return ("0000" + c.charCodeAt(0).toString(16)).substr(-4);

bookmarklet minified:

javascript:(function(s){if(null===s||""===s)return;s="\\u"+s.split("").map(function(c){return ("0000" + c.charCodeAt(0).toString(16)).substr(-4);}).join("\\u");prompt("output:",s);}(prompt("∞ to Unicode-Format:","❝Likė A Ƀoŝš❞"))); For Your WebSite

This will provide built-in search integration within Chrome and other modern browsers,
and help your website to be crawled by Google’s crazy-inconsistent web-crawler(s).

By Example: