Wednesday, October 31, 2012

ExtJS4: date formatting reference

Here is a nice guide to handle date formatting with ExtJS4:

http://senchaexamples.com/2012/05/03/formatting-dates-using-ext-js-4/

HTML5 : input date referred types not supported on almost all browsers

Be careful, most of the date referred types like date,datetime,time,month,week are not currently supported by Chrome or FF or IE,

http://www.quirksmode.org/html5/inputs.html

Jquery: change label text

in html file:

...
<label id="resultadoconsulta">my Old Text</label>
...

in javascript:

$('#resultadoconsulta').text("my New Text");

Resource:
http://stackoverflow.com/questions/3584145/change-text-of-label-in-jquery

JQuery Validation Plugin: simple demo

Javascript: convert from string to integer

Use parseInt:

var myString = "34";
var myIntegerFromString = parseInt(myString); // 34 (integer)

console.log("myString ");
console.log(myString); // 34
console.log(typeof myString); //string

console.log("myIntegerFromString ");
console.log(myIntegerFromString); // 34
console.log(typeof myIntegerFromString); //integer

Resource:
http://www.javascripter.net/faq/convert2.htm
http://www.javascriptkit.com/javatutors/determinevar2.shtml


Python: delete element from dict

Use del:

dict2 = {"key1":"value1","key2":"value2","key3":"value3"}

print "############### print before del#################"
for k in dict2.keys():
    myValue = dict2[k]
    print "key: %s , value: %s" % (k,myValue)
    
del dict2["key2"]

print "############### print after del#################"
for k in dict2.keys():
    myValue = dict2[k]
    print "key: %s , value: %s" % (k,myValue)

Resource:
http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary

Python: validate if attribute is a instance method


Use type() or isinstance() functions:

# test.py

import types

class Person():
    def __init__(self,fistname,lastname):
        self.fistname = fistname
        self.lastname = lastname
        
    def run(self):
        print "run"
        
    def jump(self):
        print "jump"

myPerson = Person("jack","smith")
for name in dir(myPerson):
    print "name: %s" % (name)
    myAttrib = getattr(myPerson, name)
    print "myAttrib: %s" % (myAttrib)    
    print "(type(myAttrib)) == types.MethodType: %s" % ((type(myAttrib)) == types.MethodType)
    print "isinstance(myAttrib, types.MethodType: %s" % (isinstance(myAttrib, types.MethodType))
   
Result:


C:\Users\John\Desktop>python test.py
name: __doc__
myAttrib: None
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: __init__
myAttrib: <bound method Person.__init__ of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True
name: __module__
myAttrib: __main__
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: fistname
myAttrib: jack
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: jump
myAttrib: <bound method Person.jump of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True
name: lastname
myAttrib: smith
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: run
myAttrib: <bound method Person.run of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True

Resources:
http://stackoverflow.com/questions/624926/how-to-detect-whether-a-python-variable-is-a-function
http://docs.python.org/2/library/types.html
http://stackoverflow.com/questions/402504/how-to-determine-the-variable-type-in-python


Python: iterate dict

dict2 = {"key1":"value1","key2":"value2","key3":"value3"}

for k in dict2.keys():
    myValue = dict2[k]
    print "key: %s , value: %s" % (k,myValue)

Result:


C:\Users\John\Desktop>python test.py
key: key3 , value: value3
key: key2 , value: value2
key: key1 , value: value1


Resource:
http://stackoverflow.com/questions/6332691/python-dictionary-iteration


HTML5: show hint when input type text is empty

Use placeholder attribute:

<input type = "text" name="text" placeholder="Email Address">

Reference:
http://stackoverflow.com/questions/108207/how-do-i-make-an-html-text-box-show-a-hint-when-empty

Apache: Origin is not allowed by Access-Control-Allow-Origin.


Enable in the httpd.conf file:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

In the ./extra/httpd-proxy.conf file set:

ProxyRequests Off
ProxyPreserveHost On

<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

Also add  the url you want ie, for /document:

ProxyPass /document http://192.168.2.12:8080/document
ProxyPassReverse /document http://192.168.2.12:8080/document
<Location /document>
    Order allow,deny
    Allow from all
</Location>


Finally restart apache

Resource:
http://stackoverflow.com/questions/7807600/apache-mod-proxy-configuring-proxypass-proxypassreverse-for-cross-domain-ajax

JQuery Validation Plugin: validate onclick


$('#link').click(function() 
   { 
      // call .valid() method for each field
      if ($("input[name=name]").valid() && $("input[name=email]").valid()) 
      { 
         // do some stuff 
      } 
      else 
      { 
         // just show validation errors, dont post 
      } 
   });

Reference:
http://stackoverflow.com/questions/9129029/jquery-validation-onclick

Tuesday, October 30, 2012

ExtJS4: date format reference

There is a very useful link with the reference of the Extjs4 date formatting

http://senchaexamples.com/2012/05/03/formatting-dates-using-ext-js-4/

Google Maps V3: get latitude and longitude by location name


var geocoder = new google.maps.Geocoder();
var address = "bogota, colombia";
geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK)
  {
      // do something with the geocoded result
      var myLat = results[0].geometry.location.Ya;
      var myLng = results[0].geometry.location.Za;
      console.log("latitude: " +myLat );
      console.log("longitude: " +myLng );
  }
});

Reference:
http://stackoverflow.com/questions/3490622/get-latitude-and-longitude-based-on-location-name-google-maps-api

Friday, October 26, 2012

Apache: [warn] (OS 64)The specified network name is no longer available. : winnt_accept: Asynchronous AcceptEx failed.

If you get this error:

[warn] (OS 64)The specified network name is no longer available.  : winnt_accept: Asynchronous AcceptEx failed. 

Try adding the following line to your httpd.conf file:

Win32DisableAcceptEx

Resource:
http://www.apachelounge.com/viewtopic.php?p=10611
http://www.mydigitallife.info/winnt_accept-asynchronous-acceptex-failed-error-in-apache-log/

Monday, October 22, 2012

Javascript: count number of attributes of an Object

var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
var myObjectPropertiesCount = 0;
         
 for (var myObjectElement in myObject){
      myObjectPropertiesCount++;
 }

console.log(myObjectPropertiesCount);//3

Resource:
http://stackoverflow.com/questions/1345939/how-do-i-count-a-javascript-objects-attributes


Friday, October 19, 2012

PHP: Unable to load dynamic library 'php_oci8.dll' , the procedure entry point ocilobread2 could not be located

Situation:

The Apache service wasn't starting

in the Apache error.log file I was getting the following error:

"Warning: PHP Startup: Unable to load dynamic library 'C:/php/ext/php_oci8.dll' - The specified procedure could not be found. \r \n in Unknown on line 0"

the I tried to execute from windows console the php command and I got the following error in an emerging window:

"the procedure entry point ocilobread2 could not be located in the dynamic link library oci.dll"

And also, in the PHP console, I got the error that I mentioned in the beginning of this post : "... Unable to load dynamic library .... "

Solution:

- download and unzip instantclient_10_2

- set PATH variable with the instantclient_10_2 folder route ie (C:\instantclient_10_2) . Note: Is VERY important that the instantclient path must be added at beginning of PATH variable or VERIFY the PATH variable in order to avoid having other routes to a different instanclient.

- check up php command in console

- restart APACHE


Resource:

https://forums.oracle.com/forums/thread.jspa?messageID=2324855

http://ivoronline.com/Coding/Languages/PHP/Tutorials/PHP%20-%20Errors%20-%20The%20specified%20procedure%20could%20not%20be%20found.php



Wednesday, October 10, 2012

Windows 7: One way ping

I have two machines connected to the same wireless network:

  • Machine1: SO: Windows7 , IP 192.168.10.20
  • Machine2: SO: Windows7 , IP 192.168.10.11
#Ping from machine1 to machine 2
>ping 192.168.10.11
Pinging 192.168.10.11 with 32 bytes of data:
Reply from 192.168.10.11: bytes=32 time=362ms TTL=128
Reply from 192.168.10.11: bytes=32 time=74ms TTL=128
Reply from 192.168.10.11: bytes=32 time=99ms TTL=128

#ping from machine2 to machine1
>ping 192.168.10.20
Pinging 192.168.10.20 with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 192.168.10.20:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss)

I solved the problem enabling a firewall rule in the machine1 following these steps:

1. Click on Start Icon
2. Type "Windows Firewall"
3. Click on Windows Firewall with Advanced Security
4. Click on Inbound Rules 
5. Look for the following rule:
    • Name: "File and Printer Sharing (Echo Request - ICMPv4-In)"
    • Profile: "Private,Public"
6. Right Click on the rule
7. Click on "enable rule"

Resource:


Extjs4.1: center buttons in formPanel

use the config buttonAlign:

{
   ...
   ,...
   ,buttonAlign: "center" // here

   ,buttons: [
     { text: 'Button 1' }
   ]

}

Resource:
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.form.Panel-cfg-buttonAlign

Ubuntu11.04 : cp: cannot create symbolic link: Operation not permitted


The problem is because your destination device doesn't support the symbolic link creation, mainly because of it's format. In my case, the destination device format was Fat-32. Then there are 2 options:

1. Format your destination device with a format that support the symbolic link creation like NTFS format. And try again the cp command

2. Copy the entire file instead of the symbolic link, using -L option in the cp command:

cp -rL source_dir dest_dir

Resource:
http://diogomelo.net/node/46

Tuesday, October 9, 2012

ExtJS4.1: Modal Window

Use the modal config:


                      var myWindow = Ext.create("Ext.Window",{
                                width : 200
                                ,height: 200
                                ,title : 'Crear Usuario'                                
                                ,layout: 'absolute'
                                ,closable : true
                                ,modal:true // here
                            }).show();

Resources:
http://stackoverflow.com/questions/6053847/how-to-make-a-full-modal-window-in-ext-4

ExtJS4.1: Set background color to Panel

Use bodyStyle config:

 new Ext.Panel({
    width:200,
    height:200,
    bodyStyle:'background-color: #DCE8EA;' // here  
});

Resources:
http://www.sencha.com/forum/showthread.php?75830-Panel-background-color

ExtJS4.1 : Uncaught TypeError: Cannot call method 'getWidth' of undefined


I created a formpanel, which has a predefined width and height:

var myCrearUsuarioFormPanel = Ext.create('WebMonitorClass.view.CrearUsuarioFormPanel');

Know I needed to put my myCrearUsuarioFormPanel into a window. I needed to set the window width and height the same as the myCrearUsuarioFormPanel width and height:
                         
                            var myWindow = Ext.create("Ext.Window",{
                                width : myCrearUsuarioFormPanel.getWidth() //  here I tried that
                                ,height: myCrearUsuarioFormPanel.getHeight() // here I tried that
                                ,title : 'Crear Usuario'                                
                                ,layout: 'absolute'
                                ,closable : false                                
                                ,items:[myCrearUsuarioFormPanel]
                            }).show();

But I Got:

Uncaught TypeError: Cannot call method 'getWidth' of undefined 

in this line

width : myCrearUsuarioFormPanel.getWidth()

The solution is to use the offsetWidth and offsetHeight properties:


                          var myWindow = Ext.create("Ext.Window",{
                                width : myCrearUsuarioFormPanel.offsetWidth // Here is the solution
                                ,height: myCrearUsuarioFormPanel.offsetHeight // Here is the solution
                                ,title : 'Crear Usuario'                                
                                ,layout: 'absolute'
                                ,closable : false                                
                                ,items:[myCrearUsuarioFormPanel]
                            }).show();

Resource:
http://stackoverflow.com/questions/5249723/wrong-div-width-when-getting-it-with-javascript
http://stackoverflow.com/questions/10634282/in-extjs-when-dragdrop-offsetwidth-is-null-or-not-an-object-error-for-ie7

Monday, October 8, 2012

Microsoft Visio 2007: Create Sitemap


Open Microsoft Visio 2007 and go Go to "File" > "New" > "Software and Database" > "Conceptual Web Site (Metric)".

Here is a complete Guide Video:
http://www.youtube.com/watch?v=RZpRaU2UYOQ

Sunday, October 7, 2012

Javascript: substring


var str="Hello world!";
document.write(str.substring(3)+"<br />");
document.write(str.substring(3,7));

Reference:
http://www.w3schools.com/jsref/jsref_substring.asp

Javascripy: simple encode/decode Json LIbrary

Use the Extjs JSON library

// create new object
var myObject = new Object();
// set properties to the object
myObject["RB"] = "(aBc+ABC)";
myObject["RA"] = "(aBC+AbC)";
myObject["SA"] = "(abc+ABc)";
myObject["SB"] = "(abC+Abc)";
//from javascript object to json text:
var myJsonString = Ext.JSON.encode(myObject);


//from jsontext to javascript object
var myResponseString = '{"RB":"(aBc+ABC)","RA":"(aBC+AbC)","SA":"(abc+ABc)","SB":"(abC+Abc)"}';
var myResponseObject = Ext.JSON.decode(myResponseString);
alert(myResponseObject["RB"]) // "(aBc+ABC)"
alert(myResponseObject["RA"]) // "(aBC+AbC)"
alert(myResponseObject["SA"]) //  "(abc+ABc)"
alert(myResponseObject["SB"]) //  "(abC+Abc)"

Resources:
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.JSON
http://www.sencha.com/forum/showthread.php?3333-json-encode-decode

Java: Converting Jsontext to JavaObject

Look at this great sample:


import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }

    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

Reference:
http://stackoverflow.com/questions/1688099/converting-json-to-java/1688182#1688182

Javascript: Remove Duplicate Values from Array

Using JQuery:


var names = ["Mike","Matt","Nancy","Mike","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
alert(uniqueNames);// ["Mike","Matt","Nancy","Jenny","Carl"];

Resource:
http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array

Javascript: convert numbers to equal ASCII character

Use String.fromCharCode() method:

var myInt = 65;
var myString = String.fromCharCode(myInt); // A

Resource:
http://stackoverflow.com/questions/94037/convert-character-to-ascii-code-in-javascript

Javascript: zerofill function

function zeroFill( number, width )
{
  width -= number.toString().length;
  if ( width > 0 )
  {
    return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
  }
  return number + ""; // always return a string
}

Resource:

Saturday, October 6, 2012

Javascript: calculating logarithm of a number in any base

Given that the javascript log() method returns the natural logarithm of the given number. You have to use the logarithms property using the natural logarithms. For example to calculate the log of x with 10 base or 2 base:


 So,


function log(val, x) {
  return Math.log(val) / Math.log(X);
}

where x is the base, and val is the number you want to calculate the logarithm.

Resources:
http://www.w3schools.com/jsref/jsref_log.asp
http://stackoverflow.com/questions/3019278/any-way-to-specify-the-base-of-math-log-in-javascript

Javascript: getting selected item


Html:

<select id="estadosiniciales">
                    <option value ="sydney">Sydney</option>
                    <option value ="melbourne">Melbourne</option>
                    <option value ="cromwell" selected>Cromwell</option>
                    <option value ="queenstown">Queenstown</option>
</select>

Javascript:


var selectIni = document.getElementById("estadosiniciales");      
alert(selectIni.options[selectIni.selectedIndex].text);


Resources:
http://www.java2s.com/Tutorial/JavaScript/0200__Form/Findtheselectedoption.htm

Javascript: adding options to select dynamically

Your html:


<select id="estadosiniciales">
                    <option value ="sydney">Sydney</option>
                    <option value ="melbourne">Melbourne</option>
                    <option value ="cromwell" selected>Cromwell</option>
                    <option value ="queenstown">Queenstown</option>
</select>

Your Javascript:


var newOption = new Option("newStateName","newStateName");
var selectIni = $("#estadosiniciales"); // using Jquery
selectIni.append(newOption)


Resources:
http://www.devguru.com/technologies/ecmascript/quickref/option.html
http://stackoverflow.com/questions/4647863/trouble-dynamically-adding-options-to-select

Wednesday, October 3, 2012

Eclipse: Svn error : RA layer request failed

If you get this error:

RA layer request failed
svn: Commit failed (details follow):
svn: PROPFIND request failed on '/repo/path/!svn/vcc/default'
svn: PROPFIND of '/repo/path/!svn/vcc/default': Could not read status line: connection was closed by server. (http://example.com)

Switch from JavaHL(JNI) to SVNKit(Pure Java) in Eclipse:

  1. in eclipse go to Help –> Install New Software…
  2. Work with: –> choose the community.polarion.com update site
  3. expand Subversive SVN Connectors
  4. choose the SVNKit version corresponding with your version of subversion
  5. click Next, and then follow the instructions to complete installation
  6. Window –> Preferences –> expand "Team" –> select "SVN" –> select the "SVN Connector" tab –> change the SVN Connector to SVNKit –> OK


Resource:
http://languor.us/eclipse-subversion-ra-layer-request-failed-could-not-read-status-line-errors

PHP: REST APl Sample

Here is a simple and great example of a REST API using PHP

http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/

Windows 7 : Enable Telnet Client

When you try yo execute telnet command:


C:\Users\John>telnet localhost 80

You get:

'telnet' is not recognized as an internal or external command,
operable program or batch file.

Do this:


  1. Start
  2. Control Panel
  3. Programs And Features
  4. Turn Windows features on or off
  5. Check Telnet Client
  6. Click 'OK' button

After that you can start Telnet via Command Prompt.

Resource:
http://www.fettesps.com/windows-7-enable-telnet/