Pages

Monday 28 April 2014

How to keep up with technologies


Every month a new web framework is launched. New Libraries go on GitHub every day.
New techniques turn up very often, specially in the Font-end development where all the excitement is right now.

It can be extremely hard to keep up-to-dated and try to read every single link in the web.


Here are some two things I do optimize my time and filter out what I consider important:


  • I follow some of my favourites people in the industry on Twitter.
  • Subscribe to the Web Development Reading List - WDRL.


WDRL is a hand-crafted and carefully selected weekly newsletter containing links to the latest technologies and techniques.


Here is the web page where you can subscribe:
http://wdrl.info/


Thanks to Anselm Hannemann for creating and maintained this valuable resource.

cheers
Leonardo Correa

Thursday 12 September 2013

windows devices detect touch events present




Hello guys


As usual, Microsoft gives different names for the same thing just to make harder for us developers.

First we tried to detect if windows devices have touch by using "window.navigator.msPointerEnabled".

Then I noticed that Internet Explorer 10 on desktop report something other than "undefined".

The correct way to detect is by using "window.navigator.msMaxTouchPoints". It returns "undefined" for desktops or the number of touches supported by the device.

Tested on a few Nokia Lumia devices and Surface.

My final function is something like this:


    hasTouch: function() {
       return Modernizr.touch || !!window.navigator.msMaxTouchPoints;
    },



I hope future Modernizr version does this job for us soon.

more details about MS touch: http://msdn.microsoft.com/en-us/library/ie/hh920754(v=vs.85).aspx


cheers
Leonardo Correa



Monday 22 July 2013

hide url bar on safari iphone android and any device


Do you have a requirement to hide url bar on mobiles?


If so read on. This is may be for you!

This is NOT for you if:

  • If your page is bigger than the height of the phone you DON'T have this issue. This will use the normal browser scroll. Your solution is simply: window.scrollTo(0, 0);


This is for you if:

  • If for some reason, your requirement is to have a page height on the size of the phone height. Eg.: page with a Map. Google Maps mobile is an example. Obviously the other example is the company that I work for... coincidentally a map engine company too.
  • Maybe you have some static header and footer with scrollable content in the middle. I always try to push back those kind of UX designs. Currently mobiles on the market struggle to do a "overflow-y: auto" on a div that has fixed height. Eg.: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_overflow . It may work on iPhones, some androids but when you build an real world app you'll have a hard time with buggy scroll devices. 


The main advantage of hiding URL or address bar is to get extra space for content. UX's love that so do users.


Assuming that you have a web page with some CSS:

    #map{
        height: 100%;
        width: 100%;
    }

And your page looks like this one:




Note the huge chunk of screen wasted because if the address bar. It is even worse with debug bar as well.

This is what we want to achieve:



So much better now. Look at the big map taking over the whole available visible area of the phone.


So back to the problem...

Height 100% on div map won't do the trick. You also don't want to hardcode the height in pixels either.

If you disable debug console, this code "window.innerHeight" returns 356 at this point.
This is not the height that we want.

$(window).height() returns the same 356. This function is not ideal for what we want. Avoid it.


As I said before, there is no scrollable content. We need it. So we will force the page to get bigger in order to get real height using window.innerHeight.

those are the steps:

  • make dummy yellow div bigger than all the bars together: $("#dummyHeight").height( $(window).height() + 400 );
  • scroll to the top: window.scrollTo(0, 1);
  • wait 300 millisecs and now get the real height: window.innerHeight; 
  • At this point you can set up the height of the map with all the available height: $("#map").height(realHeight); 

If you have scrollable content in your page (content is bigger than phone height), the jQuery function "$(window).height()" still returns 356 - wrong. The correct value 416 is return  by the old school property "window.innerHeigh".


The trick here is use "window.innerHeight". I have seen lots of people using $(window).height() or window.height. Anything other that "window.innerHeight" will return the wrong value.

You may not need this yellow bar on your real app. I only use it because we don't like the map jumping around too much with resizing.

I am not gonna explain every single line here. I will post the source code and you look at it.

Running this example:


All you need to do is copy, paste in a dummy html file, search in a web application, load in a phone and see it working. Link to the code is at the end.

Be aware that this yellow bar in for demonstration only. In real app you would make it invisible.  

On this example, drag the yellow bar up/down in order to confirm that the map has got the desired height. You can also click on the yellow bar in order to scroll to top again.

Please excuse me the CSS and JS in the html. This is a demo only. The important part is the JS function to do the job. I have got a more elaborated version of this code caches the calculation after the first time per orientation.


Verions 1: Source Code for this working example is here
This version one is very simple. I will make it fancy on version 2 of this code:
- simple and effective calculation to hide url bar
- recalculation hooked up on window.resize for now.

Version 2: The second verison will provide (yet to come): 
- calculation caching. It will do it only once per orientation, save it and reuse it when necessary.
- hook up on orientationchange event.

Tested on:

  • iPhone 5, IOS 6.1.2
  • iPhone 4S, IOS 6.1.2
  • iPhone 4S, IOS 5.1
  • iPhone 3GS, IOS 6.x
  • Samsung Galaxy S4, Android 4.1.2
  • Samsung Galaxy S3, Android 4.1.2
  • Samsung Galaxy S2, Android 4.1.2
  • Samsung Note 2, Android 4.1.2
  • HTC One, Android 4.1.2
  • Sony Xperia 4G (pretty sure tested on it)


Some phones don't seem to be possible to hide URL bar:

  • Nokia Lumia 920, Windows 8


Please leave your feedback. We have been though a lot of issues with mobile resizing. Feedback is always welcome.


cheers
Leonardo Correa

Thursday 26 January 2012

Hello guys, I have moved Java2word to its own blog. http://java2word.blogspot.com/p/documentation.html
Issues and SVN code repository will remain over there. Thank all of you for your contribution over the last 18 months.
Leonardo Correa

Monday 31 October 2011

ellesquire on the prowl lyrics aussie hiphop

Ollesquire is a Sydney hip hop rapper and released his first record called "Ready" in August 2011.
Ollesquire is coming to Melbourne:
Fri, Nov 25 - 8:30 pm
Northcote Social Club - Melbourne (W/ Thundamentals Foreverlution Tour)

further info on his Facebook page: http://www.facebook.com/ellesquire?sk=app_178091127385

He is best known for the track "on the prowl" where he uses humor and sincerity to describe a typical situation when we go out for hunting! Really funny!


I tried to find "on the prowl" lyrics in the internet but is is not available. What do we do in this situation? We write it!
If you see this lyrics anywhere else, they copied from here.

As English is not my first language, it was a good exercise to sit down, write the lyrics and understand better the Aussie accent and slang.  Obviously I didn't get it all done. I did 70% and asked Genny to help with the rest. There is still a few words we couldn't get it but.

You can listen to "on the prowl" on his Facebook page or youtube" http://www.youtube.com/watch?v=ipU7_e6uF3A

So, do you like stuff??? very Aussie - here we go:



Ellesquire - on the prowl

Oh yeah
I'm on fire when I go to the night clubs
My pick up line is
so do you like stuff?
if they are keen they're probably a mindfuck

or they're fine  but they've turned dark known' my luck

I've gone right up to 'em and like Hi but
I never have a follow up line
So I just hi em up

Can I buy you a drunk
I mean buy a drink
I mean shit n' a fuck

I'm trying to think of somethin' witty to say
and she's like "whatever"
I'm sorry baby you could've been mine forever

I came on too strong
played on too long and found myself dancing to Akon's new song

Drunk as all fuck
Still trying to get my groove on
Bouncer comes up
"Sir can you please move on, you're too drunk it's time to call it quits"
I says:
"too drunk this is only my fourth of fifth, plus you're interrupting me, I'm trying' to talk to chicks"
he says "it's not a girl, you're talking to the wall you dick"
ahh shit...
"No wonder she was such a good listener, about to start kissing' her and get all of her digits, but you interrupted!"
he didn't find it funny
he kicked me out the club and then he punched me in the tummy

He's calling me a smartass and a drunk bum
said "I'd rather be a smartass than a dum cunt" (ehee no you didn't?)
No I didn't
but I think it's probably what I would've said if I was bigger

Full of liquor I move on to the next pub
I'm not gonna go home,
I've gotten all dressed up

Listen to me

(chorus)
Single and I'm on the prowl
I wish that I could mingle, I just don't know how
I get pissed too quick
Then I get thrown out
before I even get a chance to write your number down
(repeat)

Hey..um.. so I'm a rapper you know
oh you're a rapper, what?
you know like I rap and stuff
My mate is in the hilltop hoods
No, I don't know the hilltop hoods
They're awesome...yeah, you should see them
I'm good but, I'm heaps good, do you want me to do a rap for you?
no, I m actually gonna go over here now

So I find myself
in the middle of the largest of lines
just to get into a bar for a lager or five

I'd already been going hard drunk a carton at mine
before I even left my apartment and started my night

I see a hottie walk pass so I ask her for a light
She says "no I don't smoke"
n I say 'nah, neither do I'

We got to have a laugh at my retarded reply
but then she kept walking like she just passing me by

I had to think fast so I ask for the time
she says 'the thing on your wrist will give a rather good guide'

back to old smart ass like she's larger than life
ah forget her
I'm already at the start of the line
So I get into the venue where the party is right
everybody is looking like they're haven' a marvellous night
so many ladies in the place that it was hard to see guys
So it can't be hard for me to get a part of the pie
Pardon me I think I'll get a glass of your wine
the barman behind next to the chick in the karky design
The bartender just laughs and says "aren't you surprised that apart from you and I in the club there aren't any guys"
Well I did feel a little bit marginalised
But hell, all the more girls for me to party with me right?'

he's like "next time you (?find or win?) yourself some ass for the night n stay away from here dude this is a bar just for dykes"

(chorus)
Single and I'm on the prowl
I wish that I could mingle, I just don't know how
I get pissed too quick
Then I get thrown out
before I even get a chance to write you number down
(repeat)




This is Aussie talent! I will definitely check it out in Melbourne on 25th Nov.


cheers
Leonardo

Tuesday 25 October 2011

Web Mobile iPhone and Androids Inconsistencies

As I wrote in my profile, I am currently working as a Web Mobile Developer, focussed on high-end devices and will start to share my experiences and hacks to get the work done.

It has been a great experience working with HTML5, CSS3 and Javascript. Most people thinks this is all about rounded corner divs but we can build powerful web mobiles applications with HTML5 and CSS3.

Therefore nothing comes without some reasonable hassle. If you were one that complains about inconsistence on standard web site like Internet Explorer versus firefox, you need relax. You should be really happy where you are.

Web Mobiles is ten times more inconsistent than web for desktop. IPhones run safari mobile, which is not the same as safari desktop.  Androids behave slightly differently over device manufacturers (Eg.: annoying -webkit-tap-highlight-color css3 property) and totally different from iPhones.  


Please don't get me wrong: I love mobiles! that's why I didn't kill myself when I found out that safari mobile does not implement fixed position, neither div overlay scroll.

Can you do anything on web for desktop without fixed position and overflow scroll? In mobiles we have to do it. Find a good work-around is part of your role.

Worse yet, here comes safari mobile - the new Internet Explorer headache in mobiles.


But there are things that both iPhone and Androids sucks:

input type="search"

This code is supposed to give you that "clear on demand", the same on iphone apps but without any extra code. This is specified on HTML5 but they don't implement it.


Safari mobile does not implement overflow scroll for divs. Luckily there is the fantastic iScroll (http://cubiq.org/iscroll-4) that "fixes" this problem.


There are consistent things as well like geoLocation:
    navigator.geolocation.getCurrentPosition(foundLocationFunc, noLocationFunc); 
works for both devides and in a second you'll .


Next time I will share how to implement like a centralized spinner with a full screen semi-transparent overlay locking the page background. There are some tricks when the page is bigger than the screen and you have scroll.

Later on, I will share how to use full screen for iphone, take the most of this huge screen height.


cheers
Leonardo

Friday 30 September 2011

soccer world cup 2014 brazil

Soccer world cup in Brazil is in less than 1000 days. Nice! This is the task list for this event to happen (from blog blogfazendoasocial):
  • 12 stadiums 
  • 3 years
  • 1 national team
I would add:
  • Decent airports 
  • Get rid of corrupt politicians and policemen all over the country
  • Sack Mano Menezes (current coach)

Brazil is the only place in the world that politicians take the money and never go to jail regardless of evidences like videos, phone call records and documents. Worse yet, those corrupt politicians never give the robbed money back - it disappears like magic.

Fact: In Brazil, everything that involves politicians has corruption.

Soccer stadiums construction are running late, airports have reached maximum capacity and the government is government (don't need to say anything else: made up of laziness and corruption).

If you haven't bough your tickets to Brazil 2014, don't do it because who knows if this world cup will ever happen.


Leonardo Correa

Tuesday 22 March 2011

Java2word Templates

Now you can use Templates with Java2word!

Take a look at the wiki page: https://code.google.com/p/java2word/wiki/TemplatesWithJava2word

It is not the most advanced solution but gets the job done!



https://code.google.com/p/java2word/



Leonardo Correa
coding for fun...

Sunday 20 February 2011

Java2word in numbers statistics

Java2word started in August 2010. Since then, I have spent many hours of my own time to implement this code. There has been a lot of collaboration from people all over the world. 


Last 30 days: 
  • Visits: 850  
  • Pageviews: 3,189 

At all times(7 months):
  • Visits: 3,429
  • Pageviews: 15,146

Now we have style, fluent interface, over 92% test coverage.
Unfortunately I can't fit cucumber here...


TODO:
  • Knock off some cyclomatic complexity
  • Get to 100% test coverage
  • Make font-size work
  • Implement bullet points


I decide to write in one unit test that uses all elements of the API. This works like a documentation/demonstration  of what can be done with java2word.


Take a look at the project page and search (ctrol + f) for "testJava2wordAllInOne"

https://code.google.com/p/java2word/



thanks everyone for helping!

Leonardo Correa
 

Saturday 19 February 2011

Java2word covariant return type

When I was studying for SCJP exam, in 2007, I had to learn a lot of things that didn't make sense and I thought that I would never use. 

Today, in my Java2word library, I utilized Covariant Return Type.

This basically is when you override some method, you can return any subtype of the original return type. Eg.:

The class ParagraphPieceStyle extends AbstractStyle and overrides the method create().

public abstract class AbstractStyle implements ISuperStylin {

    private IElement element;
   
    public void setElement(IElement element) {
        this.element = element;
    }
   
    public IElement create() {
        return this.element;
    }
   
}

public class ParagraphPieceStyle extends AbrstractStyle{

    @Override
    public ParagraphPiece create() {
        return (ParagraphPiece) super.create();
    }

}


The original return type is "IElement" but returns "ParagraphPieceStyle".The advantage of this is the flexibility to return any subtype of the original type.

this is the code without Covariant:

ParagraphPiece myParPiece01 = (ParagraphPiece) ParagraphPiece.with("...");


This is with covariant:

ParagraphPiece myParPiece01 = ParagraphPiece.with("..."); 

Now I don't need to do a type cast (downcast) of the type.




https://code.google.com/p/java2word/


cheers

Leonardo Correa

Saturday 12 February 2011

My Dexter Addiction

what is our concept of wrong and right? how about punishment; how should we punish someone that does something wrong? Have you ever thought that you would like someone that kills people?


Friend of mine called Dylon talked about a TV serie that the main character is a serial killer. I couldn't believe it! But he said: He kills only bad people!
Yeah... sounds cool...

I downloaded some episodes, watched them and quickly became addicted to it. It surprised me the  number of people supporting the ideas behind Dexter.
On the other hand, there are lots of people against Dexter's concepts - I respect their opinion.


I must define "bad people" at this point:

Murderers, Brazilian Politicians (all fucking corrupt politicians and policemen), presidents and ex-presidents of some countries, ..., ..., ..., this list could never finish...


The pleasure to see real punishment, punish whom ever f$%#ng deserve is priceless. We are sick of bad people* not being punished properly.

 Dexter judges and executes the sentence at the same time. He efficiently does what the system can't do it.

Surely no one wouldn't mind if Dexter applies his skills on Brazilian politicians - I think they deserve... fucking deserve. Conventional justice doesn't work for then.

If you grew up in a first world-country (or decent place), you have NO idea what I am talking about here. You may have never seen corruption in the same way.

I have seen so much corruption in the government. I used to be an accountant and worked in the treasure department for 3 years.


 Everybody has their own secrets. I love when Dexter is holding his baby and says: "I ll tell you a secret - daddy kills people, but only bad guys..."

In my point of view people love Dexter because the world is missing a very simple thing: give bad people what they deserve. At the end of the day what we want is justice, nothing more...


Tuesday 7 December 2010

Mobile Web Sites BDD Cucumber Capybara Gizmo

Have you ever thought about running Cucumber tests for Mobile Web Sites?

Background about my current role:

I have been working as a Mobile Developer. I build web page to run in mobile devices. They could be iPhone, iPad, T-Touch, T-Hub, Galaxy, Nokia, Motorola or any mobile device that can access internet via somehow.


First of all:
  • what is a Mobile Web Site?
It is a site that runs on smart phones, tablets or handsets.

  • what is NOT a Mobile Web Site (in this blog)?
I am not talking about iPhones or Android Apps. If you have one Nokia Mobile you can't install any apple app. 


More about Mobile Web Site here:  http://en.wikipedia.org/wiki/Mobile_Web 




The Funny Challenging

If we have a traditional Web Site we now already how to test it.
We could use Cucumber + Capybara + Gizmo + Selenium Web Driver and run this on the Continouns Integration Server (CI).

We could have in our CI, at least those three different virtual machines: One with in Firefox + Linux, other with Firefox + Windows and last with Windows + Internet Explorer. 

You could consider IE6, IE7, Vista, Windows Seven... anyway this is just an illustration.

How about Mobiles????????????????????????????
Can we run automatic Cucumber tests natively on a Mobile device???????

Additional information: In my work, there are one list of twenty mobile devices that we support. Those devices can be classified as the screen size such as tiny, small, medium, large, extra-large and maybe huge.

The application gives a different CSS configuration per device, but the content by itself is basically the same in most cases. Mobiles from a specific carrier (Eg.: Telstra) could have additional content available.  

Not enough, other devices don't accept cookies. Example of those are some dodge Nokias that surprisingly come up at the tip of the list, according to the corporate stats. This non-cookie devices we have to use URL rewriting .

Every time we have a release, QA guys have to test the application in many different devices. Regarding to mobile, we need to see the font size, if images are visible, text in the write place, etc. In other words, for 20 different devices, possibly 20 different pages.

I am not even talking about HTML5 neither Web Semantic - not also about table-less approach. All those issues would deserve another post and we surely take care of them in my workplace.

Despite of those issues, I think we still can test a lot of things automatically via Cucumber. Using a normal PC web browser, we can definitely test at least 70% of the application.

Certainly we could perform a complete functional test using Cucumber, and finally, by the time  that QA guys take the manual  tests using handset, there will be no more basic functional errors.


How can we emulate a mobile device using Firefox?

I figured it out a way to do this changing Firefox HTTP request headers. This way, the application will respond the request the same way it does for a real device.

I will assume that you have your Cucumber + Capybara environment up and running.

If not, follow these steps:
  • Read this page https://github.com/icaruswings/gizmo
  • git clone https://github.com/icaruswings/gizmo.git
  • Now you have got a Cubumber + Capybara + Gizmo environment half way done.
Now you need to install all gems. I use bundle but if you want something quickly up and running, install the following gems:

  • sudo gem install cucumber
  • sudo gem install rspec
  • sudo gem install gizmo
  • sudo gem install capybara
  • sudo gem install tilt

Now you can run:
  • cucumber features/github_example.feature
This should start Firefox and successfully run the feature.


If you are on Linux Ubuntu 10.10 and see some problem like: spec/specification, run:
  • sudo apt-get install librspec-ruby1.8



Finally The Cool Point of this Post

* Assuming that Cucumber + Capybara is up and running. 

Your env.rb has got a line like this:


Capybara.default_driver = :selenium


I will write my env.rb and how I override Firefox headers using a Firefox Profile. I removed this line and added:

Capybara.default_driver = :selenium_iphone
Capybara.register_driver :selenium_iphone do |app| 
  require 'selenium-webdriver'
  profile = Selenium::WebDriver::Firefox::Profile.new

  profile['general.user


.override'] = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7"
  profile['general.description.override'] = "Mozilla" # appCodeName
  profile['general.appname.override'] = "Netscape"
  profile['general.appversion.override'] = "5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7"
  profile['general.platform.override'] = "iPhone"
  profile['general.useragent.vendor'] = "Apple Computer, Inc."
  profile['general.useragent.vendorSub'] = ""

  Capybara::Driver::Selenium.new(app, :profile => profile)

end



This is my spike feature:

Feature:
    As a Mobile Developer
    In want to have a DRY, elegant and maintainable tests for all diferent devices
    So that I can to simulate mobile (hi-end and low-end) and desktop browsers 

    @iphone
    Scenario: It opens the test page and shows which browser is being simulated
        Given a user is on the user-agent-switcher homepage



This is the implementation of the one and only one step:

Given /^a user is on the user\-agent\-switcher homepage$/ do        
  visit "http://chrispederick.com/work/user-agent-switcher/features/test/" 
  sleep 15 # so that I can see the new values
end


At this point I would recommend you to take a look at the Firefox Plugin and web page User Agent Switcher: http://chrispederick.com/work/user-agent-switcher/features/test/



In addition, you can enable and disable cookies. Why? If some developer forget to use URL rewriting (JSTL: ), you can catch this in your tests. Disable cookies with this code:

  if ENV["disable_cookies"]  #or variable or whatever...
    puts "_________________ Cookies have been Disabled...."
    profile['network.cookie.cookieBehavior'] = 2 #0 enables, 2 disable all
  end


This is all spike code and you should get those snippets and fit in your test implementation.


I am happy to hear your experience! Feel free to write back with your thoughts and suggestions.

If you are a Mobile Dev and would like to say how you do integration tests or how you do Agile or whatever, leave a comment.


* Curiosities:
  • Capybara creator jnicklas said that wasn't possible to change request headers via Capybara. I found a workaround and did via Selenium Profile. Then I asked him again and He told de me how to do it (Imagine if I had given up with the first answer...). He said that didn't know that was possible to do this workaround...  Thanks jnicklas!!!
  • I almost forgot to sleep one night because the problem was quite interesting...
  • I don't know how to format code in this blog, or how to add code block... shame on me...


cheers

Leonardo Correa

Tuesday 30 November 2010

best vi vim macvim command reference

I have recently started using MacVim for my Ruby stuff I write for fun. It is amazing things you can do using this text editor combined with all those plugins.

I installed Janus version (https://github.com/carlhuda/janus) of MacVim and turned it to a proper IDE for ruby code.

I found this website that has absolutely everything about vi - best VI reference:
http://www.rayninfo.co.uk/vimtips.html

I use Janus on Linux as well and works perfectly as well.


cheers

Leonardo

Wednesday 24 November 2010

Optus inefficiency sucks


Optus Systems Nightmare
...


I have got an Optus mobile post-paid plan in Australia and I am very unhappy with the service provided by this company.

They are so bad, so inefficient that deserves one post so we can make all that shit public. Maybe they will care about it...

I set up an online account to check my plan, usage and payments. For some strange reason, the system "locked" my account and when I try to login I get the message:

"To protect the security of Optus customers, a limit is placed on the number of login attempts per session. Please verify your User Name and Password and try again later."

Then I call 1300 300 937, speak with some unprepared call centre people and after 35 minutes, the teller says:

- Yes, sir, your account has been "locked"
- We can't unlock because there is a problem in the system, so you'll have to create another on-line account.


This means I will lose all configurations because of their lack of capability to build systems and solve problems.

Other funny thing happens when I try to login via iPhone app. It says that my account has been temporarily locked. If they can't unlock, Why the fuck they say "temporarily"???


I went to the Optus website, clicked in "register" and set up a second on-line account, according to the bad advice from call centre people.

When I try to link "link billing account" and enter my Optus customer number, I got the following error message:

"This service has previously been added to another web profile. Please login to My Account using your other web profile. "

Now I am in a situation that I can't fix my first account and can't set up a second one.

For us that work in IT, it is just unbelievable hear such a huge bullshit. They said that the IT guys are working on it - bullshit again!

it is amazing how they can lock your account but they can not unlock it.

All these dodge situations occur specially when you use Internet services (on-line account or iPhone app). If you are an IT or tech person and want to take the most of technology AVOID Optus.


Other Problem to prove how bad and inefficient Optus is:

When I migrated from pre-paid to post-paid, my name and surname were wrong in the system. They said that they had to fix my name before start the post-paid contract.

The teller made a call and ask to change my name. But she changed my first name only. she called again and ask to change my surname. She got an answer back saying that is is not possible to change the name more then once a day because the system doesn't allow that. Change your name on Facebook and see the change straight away.

If you had any bad experience with Optus feel free to share. I will send this link to Optus and all my friends. I am stuck in a year contract...




I figured it out that I am not the only one pissed off with Optus:
http://bella2007.blogspot.com/2007/10/optus-sucksdont-ever-go-there.htm
http://www.facebook.com/group.php?gid=23162216637
http://www.facebook.com/group.php?gid=23162216637


cheers

Leonardo

Monday 22 November 2010

Java Sun JDK 1.5 or 1.6 no Ubuntu 10.10 or 11.04 (updated: 01 Jun 2011)

As we know, Java 1.5 has not been maintained anymore and Java 6, has been hanging around for a while and Java 7 is coming soon. But it doesn't mean everybody has to move on to Java 1.6. The problem in Ubuntu is they force you to use OpenJDK. Worse yet, they don't let you downgrade to 1.5.

There are lots of legacy systems running on Java 5 and we can't forget that. It is also about freedom of choice. If you want to install Sun JDK 5 or 6 Ubuntu should not make your life difficult.

Ubuntu 10 and 11 don't allow us to natively (or easily) install Sun JDK's via apt-get.

It is so frustrate when we try to install it on Ubuntu 10.10 and have no luck:

sudo apt-get install sun-java5-jdk (or sudo apt-get install sun-java6-jdk)

After installed, the JDK will go to this directory: /usr/lib/jvm/java-6-sun

You can see all JDK's installed running the following command:

sudo update-java-alternatives -l


After a while, finally got the solution for this:

sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ jaunty multiverse"

sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ jaunty-updates multiverse"

sudo apt-get update

sudo apt-get install sun-java5-jdk



Check it out just to confirm:

sudo update-java-alternatives -l


The commands above worked for me in Ubuntu 10 and 11, installing Sun JDK 1.5 and 1.6.
If it doesn't work, try to add the following repositories and repeat the process: (anonymous suggestion - thanks a lot):

sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ hardy multiverse"
sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ hardy-updates multiverse"


Cheers

Leonardo

Saturday 23 October 2010

HP Officejet 6500 refill cartridge LX920 - hacky way

My girlfriend bought a printer HP Officejet 6500 short ago and we were pretty happy until the cartridge's ink finished.

I was really disappointed with the price of the new cartridge: AU $50.00. I decided to buy just the ink in order to refill the cartridge.

When I arrived at home and tried to refill the cartridge, I realized that there was no place to inject the ink.

I spent a few minutes looking to the fu%$^#g cartridge and conclude that there was no way to access the ink tank without making a hole at the top of the cartridge.

I will explain what I hacked this cartridge and put the ink inside.

This next two pictures show all you need:











































You will need a clip, 20ml ink and obviously the empty cartridge.


Step-by-step:

1 - Buy the ink (see image bellow). I didn't find HP ink then I bought Cannon ink: AU $5.00.

2 - Get a clip, put on the fire for a few seconds

3 - Using the hot clip, make a hole in the cartridge on the place appointed in the last picture bellow. You might have to repeat the process if the ink needle doesn't fit in the hole.

4 - Inject 20 ml of ink slowly

5 - Seal the hole with a tape

6 - Put it back in the printer

7 - It will not work straight away. You will have to use the functionality in the printer to clean up the print head. Press the button "Setup", choose "Tools", then select "Clean Printhead".
This could take up to 5 minutes.

8 - Sometimes the printer may complain about the cartridge. In this case just press ok and ignore those messages about the cartridge.


That is it!

If you are really wondering what this cartridge looks like inside, take a look at the following pictures:

Inside the cartridge. Tank on the left and the the sponge on the right side:





















See where you have to make the hole on the left side. On the right, there are three sponges and a little hole between the tank and the sponge compartment:



















I have done this twice and everything has been going fine.

Obviously this cartridge in the pictures is rubbish and can NOT be utilized anymore.

Stay clear from HP!


Leonardo Correa

Thursday 22 July 2010

Java2Word Microsoft Word Document Generator from Java code without any "special" components or libraries

I had a problem in my work a few weeks ago which was how to generate one Microsoft Word Document from Java code. Reports were composite by 40 pages around and over 30 database queries to bring data. It also had cover page, table of contents, header, footer and many tables.

We tried a lot of things but they were all crap solution. We had to delivery those "word" reports so the solution was pretty bad: Generate Jasper RTF and open as an Word Document.

When you open this rtf, the result is just horrible. You can't properly edit those dodge tables generated by jasper. Other problem is when you save this document as .doc, file size increased from 5 MB to 40 MB.

So... there were I again... playing around with the problem...

I decide to create an API in Java to generate Word documents from Java code. The Document generated HAS to be compatible with Microsoft Word and can't have any manipulation - so has to be ready for the end user!

I wrote two implementations: one for Word 97 - 2003 and another for Word 2004 +.

To be honest I spent more time in W2004 because this is the current standard.

I have created the java project and hosted in Google code:

http://code.google.com/p/java2word/

The philosophy is have something in Java and really easy like:

   IDocument myDoc = new Document2004();
myDoc.getBody().addEle(new Heading1("Heading01"));
myDoc.getBody().addEle(new Paragraph("This is a paragraph..."));



You are Java dev and deal with this API. You Don't need to worry about the implementation!

*Project has 97% of code test coverage.

** When I say no "special" components I mean not using any MS library.
In order to use the Java2Word you will need in your classpath xstream (if you use images) and log4j (for other than JBoss server).
Please refer to dependencies section in the project page.


Sunday 30 May 2010

SQL Server performs very well on data warehouse

I personally don't like .net, ms office, windows and all this shit. Maybe because I love open source, Linux, Java, Mac.

In a data warehouse project, we utilized MySql as first option but the database was considerably slow with 90 Gigabytes database (We are using "star schema" for the data warehouse).

In order to solve this problem, the database was switched to SQL Server . After the initial historical loading, the SQL Server database has got 460 Gigabytes of data and I am very impressed with the response time.

Considering the amount of data processed, I have to admit that SQL Server is a great database for huge data warehouse projects.

It is difficult to sit on your hands when the SQL Server performs comfortably well in a 460 GB database.

Monday 5 April 2010

Agile na veia: BDD e TDD.

Estou trabalhando em um projeto na Austrália onde o pessoal adota agile completo com SCRUM, XP, BDD (Business Driven Development) e TDD (Test Driven Development)

Vou escrever esse em portugues porque eu não sei se o pessoal esta usando as mesmas coisas no Brazil. E tambem quero praticar meu portugues já que não falo e nem escrevo em pt_br há bastante tempo.

Ferramentas utilizadas são:

Cucumber: Testes de integração automatizados escritos por QA (quality assurance). Testes são implementados em Ruby e JRuby.

Selenium + Webrat: End-to-end testes totalmente automatizados - acabou aquela época de o tester ficar igual a um macaquinho clicando em todos os links etc...

Agile: stand up meeting todo dia pela manha, Retro meetings no final de cada iteração para discutir o que ocorreu de bom e ruim. É tipo uma lavação de roupa suja por meia hora. Pair programming o tempo todo - eu disse o tempo todo. Nenhum codigo pode ser escrito sem "pair

JBoss ESB: Transformação dos dados e alimentaçao do FAST. A transformaçao é feita usando Smooks e gerando um XML através do Freemaker e entao fornecendo essa XML para armazenamento pelo FAST.

Liquibase: Melhora o controle de mudanças no banco de dados.

MySql: Base de dados de uns 90GB.

FAST ESP: Melhorar performance nas pesquisas e na indexação de documentos. Neste caso FAST e usado como um banco de dados com performance elevada. NÃO ache que documento é um .doc ou .xls. Na minha opinião FAST é um "Elefante branco".

Git: Controle de versoes - tipo SVN.

Hudson: Nosso CI (Continuous integration)

O que eu mais gostei:

Com o pair programming eu aprendi Ruby em um tempo muito reduzido. Tambem aprendi a escrever código curto e fácil de ser testado.

Achei o BDD legal. Outra regra no projeto é: Não se escreve código sem Cucumber test que o justifique. Cucumber testes são escritos no ponto de vista do usuário final e segem todos os critérios de aceitação para aquela implementação. Isso quer dizer que quando você desenvolvedor escreve seu codigo, voce já sabe exatamente o que tem que implementar.

Comunicação constante no stand-up sobre o que voce fez, vai fazer e problemas.
Qualquer pedaço de papel ou rabisco vira documentação.

Também acabou aquela palhaçada de o gerente do projeto ficar enchendo a porra do saco a cada 10 minutos perguntando sobre o andamento da tarefa - é só olhar o card board que está tudo lá (what the fuck???).

Refactoring o tempo todo. Voce se sente seguro em efetuar um refactoring porque o código esta todo coberto por testes unitários.

Trabalhei eu vários projetos onde existiam códigos cheios de gambiarra, ninguém sabia como funcionava e niguém podia alterar nada senao parava de funcionar - eu tinha até medo de tocar naquele código.

Com agile, o codigo fica mais maduro com o passar do tempo porque ele vai ser testado e refatorado centena de vezes.


Abraço a todos!

Leonardo

Monday 21 December 2009

Java Developer convertido ao Mac Os

Essa eu vou escrever em português porque este post e direcionado ao pessoal no Brasil. No Brasil, a utilizacão do sistema operacional Mac OS e quase nula.

No mundo, Mac Os possui somente 7.46% do mercado. O líder ainda e o Windows XP com 57.57% e o Windows Vista aparece em segundo com 21.73% do mercado. Ja o nosso grandioso Linux, possui aproximadamente 2%.

Aqui na Austrália, praticamente todas as empresas de desenvolvimento usam Mac OS. Mas este privilegio não esta restrito somente a empresas de desenvolvimento mas também empresas em outras áreas. Usuários domésticos também apreciam este sistema operacional.

Perfil do usuário Mac: Quem gosta de coisa de qualidade e não liga para o valor que vai gastar para ter essa qualidade desejada - dinheiro nao e o problema.
A Apple abriu a primeira loja no Brasil no inicio de 2008 no bairro do Morumbi, em São Paulo

No meu primeiro dia de trabalho, eu perguntei meu chefe se eu tinha mesmo que usar Mac. Ele disse para eu usar por um més e se eu não gostasse ele me forneceria o sistema operacional que eu quisesse. As duas primeiras semanas foi só para me acostumar com as novas teclas.
Eu era uma pessoa infeliz e decepcionada usando rWindows, sofrendo com a falta de estabilidade e segurança deste sistema. No Linux, sofria com a falta de usabilidade nas primeiras versões do Linux para desktop.

Emfim fui apresentado ao Mac Os Snow Leopard! Simplesmente e o sistema que reúne a usabilidade do rWindows e a segurança e estabilidade do Linux!

Mac e sem duvida um caminho irreversível - Eu nunca mais trabalho em empresa que usa rWindows na minha vida. Ubuntu 9 e uma alternativa barata ao Mac e estaria feliz com ele. Já faco uso do Ubuntu há dois anos.

*** Uso Mac OS para desenvolvimento e não falta nenhuma ferramenta para Mac. Caso não exista versão para Mac, pode instalar o macPorts e através dele, instalar qualquer aplicativo Linux no Mac.

Fonte:
http://www.w3counter.com/globalstats.php

Friday 14 August 2009

java.lang.OutOfMemoryError: PermGen space, JBoss running JBoss Seam

Who has never faced to "java.lang.OutOfMemoryError: PermGen space" using JBoss Application Server and JBoss Seam Framework?

I have faced to this problem more frequently in production environment because the application has expanded considerably. I remember I had the same problem in Brazil when we were doing our final project of Post Graduate APGS at PUC University. When I got this job, the fist thing I did was change JVM settings to fix this problem in my workstation.

You are going to see in many sites and blogs people saying that increasing the PermSize will solve the problem. This way you just postpone this exception.

By default, the Collect Garbage cleans the Heap but does NOT clean the Permanent Generation.

The default value for PermSize is 64 MB which is not enough neither for development nor production environment. You definitely should not use the default configuration for professional applications involving JBoss Application Server and JBoss Seam Freamework.

The only way to really resolve this issue is enabling CG to clean the Permanent Generation space as well.

I haven't had this problem since I started using those configuration:

-Xms512m -Xmx1024m -XX:PermSize=128m -XX:MaxPermSize=512m -XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000


I run JBoss in my computer inside Eclipse but if you run outside or for production environment you have to put those parameters on the file JBOSS_HOME/bin/run.conf .

#
# Specify options to pass to the Java VM.
#
if [ "x$JAVA_OPTS" = "x" ]; then
#JAVA_OPTS="-Xms1024m -Xmx1024m -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000"
JAVA_OPTS="-Xms1024m -Xmx1024m -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -XX:PermSize=192m -XX:MaxPermSize=192m -XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled"
fi

I am sure you will never see PermGen space again!

cheers
Leonardo Pinho Correa
Java Analyst/Developer, soccer player and beer drinker

Sunday 26 July 2009

MySQL command Explain saved my life!

Today I have to thank Paulinho about everything I learned in my Post Graduate APGS (Analisys, Project and Management of Information System - Latu Sensu ). Paulinho is a database specialist and teaches DB subject at PUC-RJ (Pontífica Universidade Católica) in Rio de Janeiro.

I remember I didn 't give it a shit about that subject, used to joke about that and I didn 't believe in that f#&*$ng "explain" command at that time.

I have been involved in a project which uses MySql, JBoss Seam, JBoss Server, JAX-WS and RedHat Linux... Pretty cool stuff!!!

I had to run one query quite big with a couple of joins. I left running for 1 hour and didn 't finish.

This time I remembered Database classes with the teacher Paulinho and decided to "explain" that query.
You don't need to be a DBA to do it, just need to put the word "explain" in front of your query and run it!!! like this:

explain select * from employee inner join department on ...

The most important thing in your result is the column "Type" which tells you how bad is you query.

For the worse to the best ones, here are possibles values of "Type" (in Mysql):

All, index, range, Eq_ref, const, system

If you see "All" in any line of the "type" column means you have your ass in the line (tá fudido).

If you carefully analyze the result you can much improve your query. In my case I just created a few indexes and removed some calculated fields from the clause where.

The original query was running in one hour - The new query ran in less than one minute making inner join in tables with over 1 million lines each!!!

Now we are going to take a look at Ingres database... Let have a go and see it... write about that later...

Leonardo Correa
Java Analyst/Developer, soccer player and beer drinker

Monday 5 January 2009

Primeira Impressão – Adelaide, Perth e Melbourne.

Primeira Impressão – Adelaide, Perth e Melbourne.

Welcome to the First World Country!!!

Já tinha lido muito sobre a Austrália e após alguns dias percebi que aqui tem tudo que se espera do terceiro país mais desenvolvido do mundo (3ª colocado no IDH – Índice de Desenvolvimento Humano da ONU). Não é a toa que grande parte das pessoas que vem acabam permanecendo por tempo indeterminado. Índice de violência e de corrupção são baixos(quase nulo) e não existe o “Forô privilegiado” para políticos como no Brasil e os políticos são julgados como qualquer cidadão. Para resumir, Austrália é o “Brazil” que deu certo! O sistema aqui realmente funciona e vale a pena pagar seus impostos!!!

Vida na Austrália...

Logo de cara já vi a “Mão inglesa” - carros com volante no direito e os carros no lado esquerdo. O asfalto aqui é perfeito e as ruas são limpas. Praticamente todos os carros são com câmbio automático, inclusive os carros com 20 ou 30 anos de uso. Há uma grande diversidade de marcas mas as mais predominantes são: Toyota, Subaru, Honda, Suzuki, Ford, Audi e alguns VW...

Praticamente todas as pessoas são “classe média” pois o salário mínimo aqui é em torno de 2000 dólares(Quase 3000 reais). Esse é o salário que um australiano ganha para trabalhar como recepcionista, auxiliar de limpeza, vendedor etc... É um salário bem razoável e suficiente para a pessoa viver de maneira satisfatória, ter carro novo e talvez fazer uma viagem internacional por ano.

Aqui na Austrália, como em todos os países desenvolvidos, é normal fazer viagens internacionais. Quase todos conhecem no mínimo a Europa e ásia e alguns América do sul. As pessoas não acreditam que essa é minha primeira viagem internacional com 26 anos. Então eu tenho que explicar como é a vida em um país subdesenvolvido... Índice de violência é muito baixo. Já os acidentes de trânsito apresentam um número considerável e geralmente são decorrente de consumo de bebidas e drogas.

Crianças...

As crianças são bem educadas e sempre respeitam as pessoas. Não é necessário falar mais de uma vez para elas obedeçam. Para ter uma idéia, quando elas entram no carro, a primeira coisa que elas fazem e colocolar o cinto de segurança. Elas sempre separam o lixo reciclável do lixo normal e nunca jogam lixo no chão. Se não houver lixeira perto, elas quadram o lixo até que encontrem uma. As crianças aqui estudam em horário integral e praticam no mínimo três esportes de forma compulsória. Aqui não se estuda gramática de maneira absurda como no Brasil. Estuda-se somente o básico.

Animais...

Já tive meu primeiro contato com uma aranha “red-back”(Costas vermelha) de 4 centímetros e extremamente perigosa. Essa aranha pode matar uma pessoa caso ela não receba cuidados médicos dentro de 24 h. Essa aranha estava debaixo da mesa de madeira utilizada no almoço de natal. Ainda não vi nenhum canguru...

Praias...

As praias são limpas e a água é verde e outras são azul turquesa. É possível ver o fundo do mar como se fosse uma piscina – parece a praia de “Lost”. As garotas usam biquines gigantescos e os homens usam bermudas e camisas. Na austrália, há um alto índice de câncer de pele decorrente do sol. O sol é muito forte e parece não haver a proteção na camada de ozônio. Em Perth ou Adelaide eu não consigo ficar no sol por muito tempo. No segundo dia eu já tive que usar protetor solar, camisa e chapel.

Lindas praias porém cheias de tubarões aguardando ansiosamente para fazer um lanche. Saiu uma reportagem sobre um tubarão branco que foi filmado passeando pela praia de Perth a cerca de 300 metros da areia – eu estava nesta praia este dia!!!

Vinhos, comida...

A Austrália tem uma grande tradição em vinhos. É hábito beber vinho aqui. Em alguns dias acho que já bebi mais vinho do que minha vida inteira. Não se come feijão aqui e o almoço geralmente é sanduíche e a grande refeição é à noite. Pizza aqui é realmente saborosa e não é necessário catchup. Finalmente conheci o verdadeiro catchup, que aqui é chamado de molho de tomate. Não é essa porcaria que tem no BR.

Em Melbourne, existem restaurantes tailandeses, vietnamitas, indianos, japoneses, chineses, brasileiros, italianos e de quase todos os países... Melbourne hoje é uma das cidades mais internacionais do mundo. Você vê facilmente nas ruas pessoas de vários países e cada um vestido de uma forma diferente! Neste ponto parece uma Lapa gigante onde cada um faz a sua moda! O pessoal gostou da minha calça xadrez.

Esportes...

Aqui o pessoal gosta de Tênis, Cricket, Rugby e Aussie Rules. O pessoal está começando a se acostumar com o futebol.

Brasil no ponto de vista dos australianos...

O pessoal aqui não conhece somente Pelé e Carnaval... O pessoal lê bastante Paulo Coelho! Eles conhecem o Cássio que joga no Adelaide FC e Romário que também teve uma passagem rápida por este clube. Eles gostam muito do filme Cidade de Deus e do seriado Cidade dos Homens. Eu vou apresenta-los o Tropa de Elite em breve!!!

Todos conhecem a capoeira, carnaval, mulheres, Kaká, Ronaldo, Ronaldinho, Copacabana, bossa nova e samba.

O caso dos travestis do Ronaldo saiu nos jornais aqui também!

Leis, Bebidas...

Aqui ainda não se conhece nenhum caso de suborno para policiais e eles são todos confiáveis. As leis são extremamente rigorosas aqui. É permitido beber e dirigir dentro de um limite. Para estar apto a dirigir, é aconselhável na primeira hora duas bebidas e depois, uma bebida a cada hora. Os pubs geralmente disponibilizam garrafas de água para facilitar a vida de quem está bebendo.

As cervejas são extremamente saborosas. Existem as cervejas leves(light) e as secas ou fortes(“Pale Ale”, “Dry” ou “Extra dry”). As leves são iguais a skol, antártica e as fortes parecem as cerveja belga ou alemã. Eu bebo bastante cervejas do tipo “pale ale”. Depois de dois copos de 500ml já to ficando meio torto porque ainda to me acostumando com esse tipo de cerveja.

Os australianos(e australianas) bebem muito!!! Mas muito mesmo!!!

Eu estava bebendo em um pub, então comecei a conversar com uns caras. Tinha um que já estava bem doidão. Então a garçonete disse para ele:

“Essa é a sua última cerveja! Bebe essa garrafa de água!”

Eu disse para o cara que a garçonete estava afim dele mas depois eu descobri que aqui existe um negócio chamado “Responsibility Alchoholic Services”. A garçonete não pode servir bebidas para quem já está ficando bêbado e ela pode ser responsabilizada pelos atos cometidos por essa pessoa bêbada!

Eu quase morri de rir quando a soube disso! Eu já estava quase no meu limite também.

Nights e Mulheres...

Na Austrália em geral existem mais homens do que mulheres. Nas boates que fui, constatei que aproximadamente 55 a 60% eram homens e 40 a 45% eram mulheres. O fato positivo é que as mulheres são bem bonitas e o problema é que os caras também são “boa pinta”...

Então para quem quer se dar bem aqui, vai ter que ralar muito... É aquela velha história né... Eu sempre cobrei muito das pessoas o “diferencial”....

Percebi que aqui também não seria muito difícil desde de que você faça a diferença!!! Ou seja, depende da disposição ou capacidade de cada um!

Várias vezes que fui ao bar pegar cervejas e drinks, alguma garota disse: “Hi!” ou “Cheers”... Percebi que as coisas devem ficar mais fáceis no decorrer da noite ou quando a bebida começa a fazer efeito...

Drogas...

O consumo de drogas é alto porém nenhuma droga é permitida por lei. A maconha é droga quase padrão aqui. Eles consomem a maconha do tipo “Hidropônica”. A droga da elite aqui é a cocaína. A grama da cocaína custa cerca de 300 dólares! Coisa absurda! A droga mais consumida aqui é o ecstase. A droga suja aqui é a heroína.


Essa foi minha primeira impressão sobre a Austrália após 15 dias de observação e muita conversa com as pessoas. Austrália também tem alguns problemas mas nada que se compara aos problemas dos países de terceiro mundo.

Leonardo Pinho Correa
Java Analyst/Developer, soccer player and beer drinker