Pages

Thursday, December 29, 2016

'node' is not recognized as an internal or external command, operable program or batch file - even after installing node in Windows

Though I had admin priviledges, the corporate firewall and the group policies kept haunting me and were a great hurdle preventing me from setting up a proper node workspace

 

My frustrations kept sky rocketing when I kept receiving the error messages as present in the following screen shot

 

 

Not being used to work with the windows command line, it was a head ache and after lot of waiting, thinking and research, I figured out to stick with what I know best and use the same to my advantage.

 

I never got lucky with setting the correct path for the variables etc, but I ended up writing a batch file that will let me work with some what similar environment.

 

For example I created a command file which I named “installNodeKeys.cmd” in memory of the  famous old days of using “Doskey.exe” in command prompt and added the following code to it

 

@echo off

rem use %node% instead of node

prompt $$

set node=d:\dev\tools\nodeCircle\nodejs\node.exe

cls

 

 

Later I got the file to grow pointing to more executable files. But be warned, you may want to traverse through all the installed packages and replace node with %node% and other commands with their corresponding %command%.

 

@echo off

rem use %node%, %npm% , %tsc% ect instead of node, npm, tsc etc in the command terminal

prompt $$

set node=d:\dev\tools\nodeCircle\nodejs\node.exe

set npm=d:\dev\tools\nodeCircle\nodejs\npm

set tsc=D:\dev\workspace\typescriptWorkspace\node_modules\.bin\tsc.cmd

set subl="D:\softwares\editors\Sublime Text Build 3126\subl"

set babel="D:\dev\workspace\babelWorkspace\node_modules\.bin\babel.cmd"

cls

 

This may not be the best solution. At least this helped me create a working environment that let me learn Angular 2 and React JS.

typings ERR! caused by certificate not trusted

 

I happened to fix this issue by creating a file named “.typingsrc” with the following contents in my project’s root directory

 

{

                "rejectUnauthorized": false,

                "registryURL": "http://api.typings.org/"

}

 

Good luck

This e-mail and any files transmitted with it are for the sole use of the intended recipient(s) and may contain confidential and privileged information. If you are not the intended recipient(s), please reply to the sender and destroy all copies of the original message. Any unauthorized review, use, disclosure, dissemination, forwarding, printing or copying of this email, and/or any action taken in reliance on the contents of this e-mail is strictly prohibited and may be unlawful. Where permitted by applicable law, this e-mail and other e-mail communications sent to and from Cognizant e-mail addresses may be monitored.

Tuesday, August 23, 2016

Detecting IE11 and other browsers with plain Javascript

I found that IE11 does not support document.all any more. I had tradinally used it for quickly detecting if an existing browser is IE or not.

Well I did find a work around for that, will come to that later. As of now, I find the following code to be generic to be used across browsers for browser detection

// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';
    // At least Safari 3+: "[object HTMLElementConstructor]"
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !!document.documentMode;
    // Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
    // Chrome 1+
var isChrome = !!window.chrome && !!window.chrome.webstore;
    // Blink engine detection


And comming back to the work around, if you are bothered about your existing code being broke due this in IE use the following

if(!document.all) {
  document.all = document.getElementById;
}

Hope that helps
  

Tuesday, July 19, 2016

Creating text file with lotusscript

Following is a block of lotusscript code that helps one understand how a text file can be created and updated using Freefile and NotesStream concepts

As a catch, the code employs a validation mechanism that check if a given file exists or not and create it only if its not found.

Hope this helps

Function updateLog(logText As String)
      Dim session As New NotesSession
      Dim stream As NotesStream
     
      On Error GoTo errHandler
  Set session = New NotesSession
 
  REM Create stream and display properties
  Set stream = session.CreateStream
 
  'check if log file exists
  If Not stream.Open("C:\\ak\\log.txt") Then
      'if log file doesnot exist then create one and add a time stamp to it
      Dim fileNum As Integer
      fileNum% = FreeFile()
      Open "/ww414/notes/ebcdicfile.txt" For Output As fileNum%
     
      Print #fileNum%, "Created: " ; CStr(Now)
     
      Close fileNum%
      'this should have created the log file. see if it existis now
      If Not stream.Open("C:\\ak\\log.txt") Then
            'if log file has not been created yet then let the user know of the error that blocks the operation
            print "Log file Is inaccessible"
            Exit Function
      End if
  End If

  'update log
  Call stream.WriteText(Chr(13) & Chr(10) & CStr(Now) & "  ::  >  " & logText)
  'close stream/file open in memory
  Call stream.Close()
Exit Function
errHandler:
'display unhandled errors
print Error & " on line " & CStr(Erl)
Exit function

End function

'now try producing some logs with the following statements
updateLog "This is a sample log"
updateLog "This is an other sample log"
updateLog "This is yet an other sample log"
updateLog "I am done logging"
updateLog "forget it bye bye"

'you can view the results on the text file or through browser as follows



Thursday, June 23, 2016

Screen flickers when hovering on li elements - a possible relief

I had a list of nested un-ordered list which were working fine until I made a few changes.

I am speaking about nested ul and li tags.

I spent an hour trying to figure out what was causing the issue and had been inspecting through the style associated with the page and nothing seemed to help.

The culprit was the chrome's developer tool itself. I turned off the developer tool and the list worked like charm and the screen flickering went away.

That is a bummer. Though it is not a code level solution, I am relieved cos now I know that the testers  wont be bothering me in respect to this pest :)

Wednesday, May 25, 2016

Some basic experiments with dojo/_base/lang

Dojo/_base/lang
The important pointers to remember about this package are, this provides following functionalities
Clone – helps clone a node to an other. A literal copy
Delegate – helps create a bounded subclassed object. Changes are reflected to child when parent object is changed, provided, its done in the oops way *(note1:refer note below)
exists getObject setObject
extend mixin partial – extend works with prototype, mixin with properties and partial helps overload functions with ease
hitch – force scope for an object
replace – A huge feature. Lot of varities and customizations are possible. Refer the following html code to understand what it does


*note1
var lang=require("dojo/_base/lang")
var obj = { a:"b", c:"d" };
var thing = lang.delegate(obj);
obj.e='f';
thing; //:is a {a: "b", c: "d", e: "f"}
obj = { a:"b", c:"d" , g:"h"};
thing; //:is still a {a: "b", c: "d", e: "f"} – note g:”h” did not get updated as it was not done in the oops way.

Use the following html file and watch the logs that gets printed. Then run through the code that produced them. This will you understand what does what
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dojo Lang</title>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js"
data-dojo-config="async: true"></script>

<script>
//lang.extend & lang.mixin
require([ "dojo/_base/lang", "dojo/json" ], function(lang, json) {
// define a class
var myClass = function() {
this.defaultProp = "default value";
};
myClass.prototype = {};
console.log("the class (unmodified):", json
.stringify(myClass.prototype));

// extend the class
lang.extend(myClass, {
"extendedProp" : "extendedValue"
});
console.log("the class (modified with lang.extend):", json
.stringify(myClass.prototype));

var t = new myClass();
// add new properties to the instance of our class
lang.mixin(t, {
"mixin property" : "myValue"
});
console.log("\nmixin does not bother protoype")
console.log("the instance (modified with lang.mixin):", json
.stringify(t));
});

//lang.getObject()
console.log("\n****lang.getObject()****")
require([ "dojo/_base/lang" ], function(lang) {
// define an object (intentionally global to demonstrate)
foo = {
bar : "lang.getObject() value"
};

console.log("foo.bar=" + lang.getObject("foo.bar"));// returns "some value"

// get the "foo.baz" property, create it if it doesn't exist
console.log(lang.getObject("foo.baz", true)); // returns foo.baz - an empty object {}

// get the "bar" property of the foo object
console.log(lang.getObject("bar", false, foo)); // returns "some value"
});

//lang.partial
//helps create over loaded function
console.log('\n****Overload functions using lang.partial****')
require([ "dojo/_base/lang", "dojo/request" ], function(lang, request) {
var dataLoaded = function(funcName, someFirstParam, data, ioargs) {
if (!funcName || funcName == '')
funcName = 'dataLoaded';
console.log(funcName + "::someFirstParam=" + someFirstParam);
console.log(funcName + "::data=" + data);
console.log(funcName + "::ioargs=" + ioargs);
};

console.log('\ndataLoaded() gives following logs');
dataLoaded();
var partialDataLoaded = lang.partial(dataLoaded, "partialDataLoaded",
"firstValue");
console.log('\npartialDataLoaded() gives following logs');
partialDataLoaded();
console.log('\npartialDataLoaded("myData") gives following logs');
partialDataLoaded("myData");
});

console.log('\n****lang.Replace()****');
require(
[ "dojo/_base/lang", "dojo/dom", "dojo/_base/array",
"dojo/domReady!" ],
function(lang, dom, array) {

replacedString = lang.replace(
"Hello, {name.first} {name.last} AKA {nick}!", {
name : {
first : "Karthikeyan",
middle : "X",
last : "Alagirisamy"
},
nick : "AK"
});
console.log('replacedString=' + replacedString);
replacedString = lang.replace("Hello, {0} {2} AKA {3}!", [
"Karthikeyan", "X", "Alagirisamy", "Manda" ]);
console.log('replacedString=' + replacedString);

console.log('\n*** replace with a function');

// helper function for complex replace
function sum(a) {
var t = 0;
array.forEach(a, function(x) {
t += x;
});
return t;
}

var complexReplace = lang
.replace(
"{count} items averaging {avg} per item ranging from {min} to {max} with a total sum of {sum}.",
lang.hitch(
{
payments : [ 11, 16, 12, 24, 99,
46, 8, 82 ]
}, function(_, key) {
switch (key) {
case "count":
return this.payments.length;
case "min":
return Math.min.apply(Math,
this.payments);
case "max":
return Math.max.apply(Math,
this.payments);
case "sum":
return sum(this.payments);
case "avg":
return sum(this.payments)
/ this.payments.length;
}
}));

console.log("complexReplace = " + complexReplace);

console.log("\n***Replace using custom patterns");
var customReplace = lang
.replace("Hello, %[0] %[2] AKA %[3]!", [ "Robert", "X",
"Cringely", "Bob" ], /\%\[([^\]]+)\]/g);
console.log("customReplace=" + customReplace);

console.log("\n***Escaping Substitutions");
function safeReplace(tmpl, dict) {
// convert dict to a function, if needed
var fn = lang.isFunction(dict) ? dict : function(_, name) {
return lang.getObject(name, false, dict);
};

// perform the substitution
return lang.replace(tmpl, function(_, name) {
if (name.charAt(0) == '!') {
// no escaping
return fn(_, name.slice(1));
}
// escape
return fn(_, name).replace(/&/g, "&")
.replace(/</g, "<").replace(/>/g, ">").replace(
/"/g, '"');
});
}

// we don't want to break the Code Glass widget here
var bad = "{script}alert('Let\' break stuff!');{/script}";

// let's reconstitute the original bad string
bad = bad.replace(/\{/g, "<").replace(/\}/g, ">");

// now the replacement
var escapedSubstitution = safeReplace("<div>{0}</div", [ bad ]);
console.log('escapedSubstitution=' + escapedSubstitution);

console.log('\n****Formatting Substitutions');
function format(tmpl, dict, formatters) {
// convert dict to a function, if needed
var fn = lang.isFunction(dict) ? dict : function(_, name) {
return lang.getObject(name, false, dict);
};

// perform the substitution
return lang.replace(tmpl,
function(_, name) {
var parts = name.split(":"), value = fn(_,
parts[0]);
if (parts.length > 1) {
value = formatters[parts[1]](value, parts
.slice(2));
}
return value;
});
}

// simple numeric formatters
var customFormatters = {
f : function(value, opts) {
// return formatted as a fixed number
var precision = opts && opts.length && opts[0];
return Number(value).toFixed(precision);
},
e : function(value, opts) {
// return formatted as an exponential number
var precision = opts && opts.length && opts[0];
return Number(value).toExponential(precision);
}
};

// that is how we use it:
var output1 = format(
"pi = {pi}<br>pi:f = {pi:f}<br>pi:f:5 = {pi:f:5}", {
pi : Math.PI,
big : 1234567890
}, customFormatters);

var formatingSubEx1 = format(
"pi = {pi}<br>pi:f = {pi:f}<br>pi:f:5 = {pi:f:5}", {
pi : Math.PI,
big : 1234567890
}, customFormatters);

var formatingSubEx2 = format(
"big = {big}<br>big:e = {big:e}<br>big:e:5 = {big:e:5}",
{
pi : Math.PI,
big : 1234567890
}, customFormatters);

console.log("formatingSubEx1=" + formatingSubEx1);
console.log("formatingSubEx2=" + formatingSubEx2);

console.log('\n******lang.setObject************');
var obj={};
lang.setObject("parent.child.prop", "some value", obj);
console.log("obj.parent.child.prop=" + obj.parent.child.prop);

console.log('\n**********lang.trim**********');
function show(str) {
console.log("|" + lang.trim(str) + "|");
}
show("   one");
show("two ");
show("   three ");
show("\tfour\r\n");
show("\f\n\r\t\vF I V E\f\n\r\t\v");

/*
isString() Checks if the parameter is a String
isArray() Checks if the parameter is an Array
isFunction() Checks if the parameter is a Function
isObject() Checks if the parameter is a Object
isArrayLike() Checks if the parameter is like an Array
isAlien() Checks if the parameter is a built-in function
*/
});
</script>

</head>
<body>http://pc301227.xts.com:8090/DojoCracker/index.html
</body>
</html>



Console shall produce the following output
the class (unmodified): {}
dojo_base_lang.html:25 the class (modified with lang.extend): {"extendedProp":"extendedValue"}
dojo_base_lang.html:33
mixin does not bother protoype
dojo_base_lang.html:34 the instance (modified with lang.mixin): {"defaultProp":"default value","mixin property":"myValue"}
dojo_base_lang.html:39
****lang.getObject()****
dojo_base_lang.html:46 foo.bar=lang.getObject() value
dojo_base_lang.html:49 Object {}
dojo_base_lang.html:52 lang.getObject() value
dojo_base_lang.html:57
****Overload functions using lang.partial****
dojo_base_lang.html:67
dataLoaded() gives following logs
dojo_base_lang.html:62 dataLoaded::someFirstParam=undefined
dojo_base_lang.html:63 dataLoaded::data=undefined
dojo_base_lang.html:64 dataLoaded::ioargs=undefined
dojo_base_lang.html:71
partialDataLoaded() gives following logs
dojo_base_lang.html:62 partialDataLoaded::someFirstParam=firstValue
dojo_base_lang.html:63 partialDataLoaded::data=undefined
dojo_base_lang.html:64 partialDataLoaded::ioargs=undefined
dojo_base_lang.html:73
partialDataLoaded("myData") gives following logs
dojo_base_lang.html:62 partialDataLoaded::someFirstParam=firstValue
dojo_base_lang.html:63 partialDataLoaded::data=myData
dojo_base_lang.html:64 partialDataLoaded::ioargs=undefined
dojo_base_lang.html:77
****lang.Replace()****
dojo_base_lang.html:92 replacedString=Hello, Karthikeyan Alagirisamy AKA AK!
dojo_base_lang.html:95 replacedString=Hello, Karthikeyan Alagirisamy AKA Manda!
dojo_base_lang.html:97
*** replace with a function
dojo_base_lang.html:133 complexReplace = 8 items averaging 37.25 per item ranging from 8 to 99 with a total sum of 298.
dojo_base_lang.html:135
***Replace using custom patterns
dojo_base_lang.html:139 customReplace=Hello, Robert Cringely AKA Bob!
dojo_base_lang.html:141
***Escaping Substitutions
dojo_base_lang.html:169 escapedSubstitution=<div><script>alert('Let' break stuff!');</script></div
dojo_base_lang.html:171
****Formatting Substitutions
dojo_base_lang.html:225 formatingSubEx1=pi = 3.141592653589793<br>pi:f = 3<br>pi:f:5 = 3.14159
dojo_base_lang.html:226 formatingSubEx2=big = 1234567890<br>big:e = 1e+9<br>big:e:5 = 1.23457e+9
dojo_base_lang.html:228
******lang.setObject************
dojo_base_lang.html:231 obj.parent.child.prop=some value
dojo_base_lang.html:233
**********lang.trim**********
dojo_base_lang.html:235 |one|
dojo_base_lang.html:235 |two|
dojo_base_lang.html:235 |three|
dojo_base_lang.html:235 |four|
dojo_base_lang.html:235 |F I V E|

Tuesday, August 25, 2015

This compilation unit is not on the build path of a Java project

Problem: Eclipse Showing error message - "This compilation unit is not on the build path of a Java project"
If you import a project as a General Project, it wont have the java nature and that will be a problem. In my case this was true . And rectifying the same will be as follows,
 Add the below lines in the .project file of your workspace and refresh.
      org.eclipse.jdt.core.javanature

Thursday, May 14, 2015

Deploying dojo in Apache Tomcat

-->
Well this is something that I did not want to reinvent and so I searched for the same in the internet aggressively for hours. Guess I am a little dumb. Though I found pages relating to the same, I did not find what I was looking for and instead I found this advice in multiple pages. Guess I am a little smart to understand this advice and hence I ended up working on it and found something that I can remember for a long time J. Really feels a little happy insideJ
My aim is to deploy dojo somewhere in the root directory of the tomcat server, so it becomes automatically available for all the applications that are deployed in the server. I had previously done such things using IIS servers and lotus domino servers. Lotus domino servers have classy ways and it actually comes with dojo inbuilt. Well trying not to deviate from the topic, actually I did not find a solution and ended up finding a work around.
I understand that the Dojo files needs to be deployed in the eclipseWorspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps directory to be available to the apps in the workspace. I know I can write software to do that and I know it could be the most dumbest thing I would have done in a long time. lol.
 
So I tried creating a separate web project which serves as a content management system for dojo and tried including the same in my other apps. The problem is though they worked, the huge size of dojo and its allied packages like dgrid 40+ MB really messed with my patience when the server had to republish them every time.
 
Necessity is the mother of all inventions, someone said. I know I did not invent this, but atleast reinvented it lol, created a separate workspace, with a separate server serving dojo packages and used them in my other workspaces holding my apps which required dojo.
 
Hurray, that’s my answer. lol. Stop, stop!!! don’t scold me.
 
Create a new workspace and create a new dynamic web application. Now import the dojo folder into the webContent folder of that app as illustrated by the following screen shot
Add your dojo application to the server, by right clicking on the server and click on “add or remove” and run it as illustrated by the following screen shot.
 
 
Now go and include this dojo package in your application as illustrated in the following screen shot
Hope you don’t scold me now. At least it’s what I use :@

Tuesday, May 12, 2015

A simple dojo JSONP example

Well I almost got sick of find out the missing link. The missing link I am talking about is something like “What the hell am I missing for a dojo JSONP request to work?” as I was trying those examples provided in dojotoolkit.org. 
Thanks to the post by Jason Schock  titled “So how does JSONP really work?”. With little tinkering I understood how native plain JSONP requests work.
All that was provided in the dojotookit websites says to use jsonp:’callback’ in the script request and that kept failing miserably even though I was able to see responses in the chrome’s developer tool->network tab->response tab of urls that have been hit from the page.
So the trick is to define a variable whose scope is available for both your dojo’s request – script’s jsonp request and callback function definition.
Following is my html file that creates this Jsonp request to a data.jsonp.js file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dojo Topic</title>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.6/dojo/dojo.js"
       data-dojo-config="async: true"></script>

<style>
.output {
       border: 2px solid green;
       margin: 10px;
       padding: 10px;
       color: #eeeeee;
       background-color: #000000;
       width: 500px;
       min-height: 200px;
}
</style>
<script>
       var jsonpRespData = null;
       require([ "dojo/request/script", "dojo/dom", "dojo/dom-construct",
                     "dojo/json", "dojo/on", "dojo/domReady!" ], function(script, dom,
                     domConst, JSON, on) {
             
              on(dom.byId("startButton"), "click", function() {
                     domConst.place("<p>Requesting...</p>", "output");
                     script.get("/DojoCracker/data/data.jsonp.js", {
                           //jsonp : "dojo_request_script_callbacks.dojo_request_script0",
                           query: {
                                  "callback" : "mycallback"
                   }
                     }).then(
                                  function(data) {
                                         domConst.place("<p>response data: <code>"
                                                       + JSON.stringify(jsonpRespData) + "</code></p>",
                                                       "output");
                                  },function(error) {
                                         domConst.place("<p>Error: <p>"
                                                       + error.response.text + "</p></p>",
                                                       "output");
                                  });
              });          
       });
      
       function mycallback(data){
              jsonpRespData = data
       }
</script>

</head>
<body>
       <h1>Output:</h1>
       <div id="output" class='output'></div>
       <button type="button" id="startButton">Start</button>
</body></html>
The closure in the my data.jsonp.js file as  follows
//dojo_request_script_callbacks.dojo_request_script0({ - will come to this later
mycallback({
              "identifier" : "abbr",
              "label" : "name",
              "items" : [ {
                     "abbr" : "ec",
                     "name" : "Ecuador",
                     "capital" : "Quito"
              }, {
                     "abbr" : "eg",
                     "name" : "Egypt",
                     "capital" : "Cairo"
              }, {
                     "abbr" : "sv",
                     "name" : "El Salvador",
                     "capital" : "San Salvador"
              }, {
                     "abbr" : "gq",
                     "name" : "Equatorial Guinea",
                     "capital" : "Malabo"
              }, {
                     "abbr" : "er",
                     "name" : "Eritrea",
                     "capital" : "Asmara"
              }, {
                     "abbr" : "ee",
                     "name" : "Estonia",
                     "capital" : "Tallinn"
              }, {
                     "abbr" : "et",
                     "name" : "Ethiopia",
                     "capital" : "Addis Ababa"
              } ]
       });


So here is the explanation.  When you look into the html code you will be able to find the following
<![if !supportLists]>1.       <![endif]>First a variable is simply declared and initialized to null – “var jsonpRespData = null;”
<![if !supportLists]>2.       <![endif]>Then comes the dojo code with jsonp callback definition -
query: {"callback":"mycallback"}
<![if !supportLists]>3.       <![endif]>Then there is this function definition mycallback(data)
<![if !supportLists]>4.       <![endif]>Then back in the jsonp success callback I use - JSON.stringify(jsonpRespData)

And that’s what I see on the screen

So why bother this much when its not documented in the dojotoolkit website. Well when I use the param jsonp:’callback’ as such as described in the dojotoolkit website, I see the following on the screen
And this error on regarding the closure defined in the data.jsonp.js  file and I don’t get a hold on the response even though I see it in the response and preview tab
Well something tells me that I still miss a link o.0

This e-mail and any files transmitted with it are for the sole use of the intended recipient(s) and may contain confidential and privileged information. If you are not the intended recipient(s), please reply to the sender and destroy all copies of the original message. Any unauthorized review, use, disclosure, dissemination, forwarding, printing or copying of this email, and/or any action taken in reliance on the contents of this e-mail is strictly prohibited and may be unlawful. Where permitted by applicable law, this e-mail and other e-mail communications sent to and from Cognizant e-mail addresses may be monitored.