Friday, July 22, 2011

Why Process?

I'm beginning to understand why software companies have process. It isn't because you have bad programmers on your team. Usually you have a few great ones, a lot of good ones, some average ones, and the occassional bad one. But any one of them can mess up the system on any given day, and it isn't necessarily the bad programmers who are the worst offenders -- sometimes it's the great ones.

Friday, April 22, 2011

Netbeans API

Netbeans API
- tutorial - learning trail
- tried first example, didn't run until added more libraries
- do not see the System.out.println result

Tuesday, April 19, 2011

SVN Import

http://svnbook.red-bean.com/en/1.4/svn.tour.importing.html


svnadmin create /usr/local/svn/newrepos
$ svn import mytree file:///usr/local/svn/newrepos/some/project \
-m "Initial import"
Adding mytree/foo.c
Adding mytree/bar.c
Adding mytree/subdir
Adding mytree/subdir/quux.h

Committed revision 1.

---------------

So much better than the headache of figuring out CVS Root syntax

Monday, April 18, 2011

Hibernate Notes

Hibernate Notes
1. Develop a system that displays, allows add, delete, and modifications
New Project
2. Web Application,
3. select Hibernate and Java Faces frameworks,
4. choose correct database
hibernate configuration
1. open hibernate.cfg.xml
2. add,
a. driver_class,
b. url, jdbc:mysql://localhost:3306/databaseName
c. username,
d. password if not there
3. Optional Properties
a. Configuration properties
i. Show_sql – true
4. Miscellaneous properties
a. Current_session_context_class – thread
Package
Create filviewer package in Soruce Packages
HibernateUtil
i. Use File->Hibernate->New HIbernateUtil (or somewhere in there)
ii. Put in Source Packages in package filmviewer
Reverse Engineering
i. Go to default package
ii. Open up New file->Hibernate->Hibernate reverse engineering wizard
iii. Use src/java
iv. Add tables from database
Mapping POJO’s
i. Use File->Hibernate->Hibernate Mapping Files and POJO’s from Database
ii. Use
a. JDK5.1 language,
b. hibernate.cfg.xml ,
c. hibernate.reveng.xml,
d. domain Code,
e. Hibernate XML Mappings
Session Bean
i. Use File->JavaServer Faces->JSF Managed Bean
ii. Use either Request Scoped or Session Scoped as appropriate.
iii. Edit:
a. Import Org.hibernate.Session, Query, Transaction, java.util.*
b. Cache HibernateUtil.getSessionFactory().getCurrentSession() in an instance variable
c. Helper Methods
private Session getSession() {
return HibernateUtil.getSessionFactory().getCurrentSession();
}

private Transaction beginTransaction() {
return HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
}

private Transaction getTransaction() {
return HibernateUtil.getSessionFactory().getCurrentSession().getTransaction();
}
View
public List view() {
try {
beginTransaction();
Query query getSession().createQuery("from Film");
List< POJO > result = (List< POJO >) query.list();
getTransaction().commit();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Add
public void add(String title, String description) {
try {
beginTransaction();
POJO film = new POJO ();
film.setTitle(title);
film.setDescription(description);
getSession().save(film);
getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
}
Delete
public void delete(int id) {
try {
beginTransaction();
Film film = (Film)getSession().get(Film.class, id);
getSession().delete(film);
getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
}
Update

public void update(int id, String title, String description) {
try {
beginTransaction();
Film film = (Film)m_session.get(Film.class, id);
film.setTitle(title);
film.setDescription(description);
getSession().update(film);
getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
}


Running Methods/Accessing View
a. Edit Web Pages/index.xhtml
b. Add xmlns:f=http://java.sun.com/jsf/core
c.














Debugging
1. Helpful to run server from console using glassfish\bin\startserv so you can see stacktraces in terminal window.
Database
Example of how to create a table with autoincremented primary key
CREATE TABLE film (
filmId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) ,
description VARCHAR(1000)
);

What to plan before starting development on a project?

[someone asked this on Programmers.stackexchange.com - my response]

Most important thing to do: review the specs, interact with customer to get more refined specs.

The requirements are undoubtedly incomplete, vague, or incorrect. The biggest waste of time is doing the wrong thing. Customers are not professional software engineeers, and cannot be expected to be good at developing a good set of requirements.

So, you should review the specs, interview the customer and find out if this is what he/she really needs and wants, and can afford, etc.

Develop test/use cases and review with customer. If a requirement isn't testable, throw it out.

Develop the design and make sure if all the pieces function correctly that it would in theory do what you need.

Develop an architecture prototype that tests all of the technology to be used in every layer but ignore functionality. You are testing the architecture, not the functional specification. Having the wrong architecture will mean you have to rewrite everything, so getting the right architecture is important. Make sure it can meet your requiremenets for speed, efficiency, security, etc.

Tuesday, April 12, 2011

How to delete a windows service

1. Run Regedit or Regedt32

2. Find the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"

3. Look for the service there and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).

Saturday, April 9, 2011

Glassfish no free port available port value out of range

You may get this error when trying to start the Glassfish server. I believe this occurs because it's trying to use a port already in use.

My glassfish was set up with default ports 8080, and I had a Default Web Site and Team Foundation server running using port 8080. When I shut these off, this error disppeared.

When I have time I'll just change the ports.

Thursday, April 7, 2011

Kamikaze Java

Sun's Java initiative reminds me of the Kamikaze in WWII. A gutsy move against an overwhelmingly powerful enemy, but they had to know its close to the end when they're that desperate.

Monday, April 4, 2011

Zune - No installation Media

This fix worked for me

http://support.microsoft.com/kb/910336

Tuesday, March 29, 2011

find Missing int - amazon question

static private void findMissing(int[] intArray, int n)
{
bool[] bitArray = new bool[n];

if (intArray == null)
throw new Exception("findMissing - intArray is null");

for (int i = 0; i < n; i++)
bitArray[i] = false;

foreach (int x in intArray)
{
if (x < 0 || x >= n)
throw new Exception("findMissing - x is out of range - x=" + x);
bitArray[x] = true;
}
for (int i = 0; i < n; i++)
{
//Console.WriteLine("i=" + i + " bit=" + bitArray[i].ToString());
if (!bitArray[i])
Console.WriteLine("Missing element at i=" + i);
}
}

static private void testFindMissing()
{
int[] intArray = new int[]{ 1, 2, 4, 7, 3, 5, 6, 0, 9, 10 };
findMissing(intArray, 11);
Console.ReadLine();
}

amazon question find min diff in a list of int

static private void minDiff(int[] intArray)
{
if (intArray == null)
throw new Exception("minDiff - intArray is null");

var query = intArray.OrderBy(x1 => x1);
List intList = query.ToList();
if (intList.Count <= 1)
throw new Exception("minDiff - must have at least 2 elements in list");

int minDiff = int.MaxValue;
int x = -1;
int y = -1;
for (int i = 1; i < intList.Count - 1; i++)
{
if (intList[i] - intList[i - 1] < minDiff)
{
x = intList[i];
y = intList[i - 1];
minDiff = x - y;
}
}
Console.WriteLine("x=" + x + " y=" + y + " minDiff=" + minDiff);
Console.ReadLine();
}

static private void testMinDiff()
{
int[] intArray = new int[] { 3, 9, 6, 17, 33, 1, 16 };
minDiff(intArray);
}

Wednesday, March 23, 2011

Nesting Functions vs Intermediate Variables

Unless you really love looking at the call stack, create intermediate variables and un-nest your function. The compiler will compile away these variables anyways, so no loss in efficiency. They will be handy for debugging and make the code clearer.

Tuesday, March 22, 2011

Delete a Project from Team Foundation Server

Answer: go to the Visual Studio 2010 command prompt and use “TfsDeleteProject.exe“.

Example:


TfsDeleteProject /collection:http://larry-pc:8080/tfs “Fret Project“

You can get the url, if you've forgotten it, by going to
Team -> Connect to Team Foundation Servers -> Servers ..

Forcing DataGridView to Refresh when changed

This works - save DataSource, save scroll position, restore datasource, restore scroll position, e.g.

private void forceRefresh()
{
int x = dgvMusicalScaleList.FirstDisplayedScrollingRowIndex;
dgvMusicalScaleList.DataSource = null;
dgvMusicalScaleList.DataSource = musicalScaleList;
dgvMusicalScaleList.FirstDisplayedScrollingRowIndex = x;
}

Monday, March 21, 2011

You forgot to make it public, dummy!

Microsoft has a convoluted way of saying this;

Error 1 Inconsistent accessibility: property type 'System.Collections.Generic.List' is less accessible than property 'Frets.MusicalScale.notes' J:\Users\Larry\Documents\Visual Studio 2008\Projects\Frets\Frets\Classes\MusicalScale.cs 44 41 Frets

Saturday, March 19, 2011

2-valued boolean variable

What do you name a variable that is a boolean but can have 2 meaningful values out of N?

Example: x can have values "red" or "blue".

Calling it bRed, or isRed, is meaningful if he value is true , but doesn't convey any info about the "false" case.

YOu could implement it as an int, or if you are picky, as an enum. But this means more lines of code to declare the enum, etc.

I thought of "redOrBlue", but logically speaking, the value is always true :)

What do you think of "redNotBlue"? Any better ideas?

DataGridView not Updating when DataSource modified

I had this problem. I managed to solve it as follows:

int x = dgvMetronomeSpeeds.FirstDisplayedScrollingRowIndex;
dgvMetronomeSpeeds.DataSource = null;
m_metronomeSpeeds.Add(new Integer(0));
dgvMetronomeSpeeds.DataSource = m_metronomeSpeeds;
dgvMetronomeSpeeds.FirstDisplayedScrollingRowIndex = x;


If you don't save and restore the FirstDisplayedScrollingRowIndex, then the user loses his/her scroll position.

other keywords - c#, msdn, .NET, scrolling

Friday, March 18, 2011

Never take notice of an error that you don't know how to handle

This is in general a good principle, but in specific cases it is a good idea to intercept it. The special case is when the error occurs at a very low level (i.e. a null pointer exception) and thus there is not enough context information to make sense of the error.

When debugging, it isn't an issue because you have access to the call stack and can figure out the context from there. If, however, the error is generated for a user, and the user provides the information to support, then there won't be enough information to figure out the error, at least not easily.

In this case (or if you are a developer and are anticipating this case happening in the future, where the user might be QA) it is often helpful to catch the error, add some context information, and rethrow the exception. Or, you could check for the error that might cause the exception, and throw an exceptioin yourself instead of calling the routine that might generate the exception.

For example, usinng a variable

Class1 c = complicatedCreationMethod();

....

c.method1();

Now, method1 will fail if c is null. If there is any possibility that complicatedCreationMethod() might return null, you may want to check for this and throw an exception rather than simply letting the null pointer exception percolate to the top of the error handlers.

Wednesday, March 16, 2011

Tracking down bugs

This is basic, but anyways this is how I do it.

Put a breakpoint before the error occurs (your best guess). Step OVER code (not going into any code) until you run into the exception. Then, set the breakpoint at that procedure call, remove the previous breakpoint, step into that part, and repeat above until you find the bug.

Eventually you end up with a single line of code where the error occurs, that has no function calls. Simplify the call by removing any nested procedure calls and serializing them. E.g. instead of f1(f2(f3)) do x = f3; y = f2(x); z = f1(y). This makes it easier to step and watch the variables.

Monday, March 14, 2011

Data Design or Procedure First?

It's often a difficult decision whether to design the data representation or the algorithm first.

In a big team, designing the data representation first means that all team members can work on their individual functional components that operate on the same data representation.

However, the data representation may not be the right one for the algorithms, or not as simple or optimal as it could be. To determine the best data representation, you need to design the algorithm first.

When programming individually, I find it is best to figure out the simplest data representation (even if hard-coded, no IO) required to develop the algorithm, get that working, then modify the data representation to fit additional requirements (i.e. persistence, modifiability, etc). There's no point designing a lot of functionality (i.e. communication, database, etc.) if you don't have a good representation.

In a team, you can do this by prototyping critical algorithms first, then designing the data representation, then passing out functional component work.

Xml Serialization and Deserialization of Complex Objects/Lists

http://msdn.microsoft.com/en-us/library/ms950721.aspx

what isn't really made clear here is that you have to pass into the XMLSerializer constructor all the types that will come in the nested types of the objects. you can do this e.g.

public class Class1
{
public static Type[] extraTypes = new Type[] { typeof(Class2), typeof(Class3) }

private list1 List = new List();
public List
{
get ..
set ..
}
... same for Class3 ..
}

Then you need to create the xml serializer as XmlSerializer(typeof(Class1), Class1.extraTypes)

Friday, March 11, 2011

Changing SoundPlayer volume

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/42b46e40-4d4a-48f8-8681-9b0167cfe781

Wednesday, February 23, 2011

CheckedListBox Mutual Exclusive Selection

I thought that this would be a simple property setting in the CheckedListBox, but no I guess not. I assume that the individual only wants to select one item, and that item should be both selected and checked.

Here's how I did it:

private void checkOnlySelection(CheckedListBox cbox)
{
Object selectedItem = cbox.SelectedItem;
if (selectedItem == null)
return;
for (int i = 0; i < cbox.Items.Count; i++)
{
Object o = cbox.Items[i];
bool match = o == selectedItem;
cbox.SetItemChecked(i, match);
}
}

Just call this method in the SelectedIndexChange event handler and it will do the trick.

Thursday, February 17, 2011

Career Aptitude Tests - Nature vs. Nurture

If they ever develop a really good test for career aptitudes, what correlations they would find? Gardeners <-> biologists, mechanics <-> computer programmers, waiters/tresses <-> actors/actresses? But every waiter is an aspiring actor so it would be hard to separate nurture vs. nature. Are they called waiters/resses because they're all waiting to become actors/tresses?

Orange Peel Plant Food

Cut up orange peels added to the soil really give house plants a growth spurt. Grapefruit and lemonade also work, but not vinegar, so it's something in the citrus (vitamin C?) and not the acidity.

Blues and Folk and Rap

Blues, folk, and rap are pretty similiar. Structured chord progressions, and in the foreground, the guitar solo is speaking for blues, the singer's voice is speaking for folk, and the rapper's words is speaking for rap.

Sunday, February 13, 2011

Media Sync Problem on Blackberry

I tried to use the "Media Sync" on the Blackberry Desktop software and got an error

Media Services are Not Available.

You need to turn on mass storage mode from the connected Blackberry device to use this feature. This may require you to reconnect your device.


Here's a link on the blackberry site for a fix.

In theory, yes. But when the device reset, and I clicked on "Media Sync", I once again got the "Media Services are Not Available" message. Maybe next time I'll get a Nokia or Samsung (IPhones are cool but way outside my budget until I get off my contract).

The article then says to go to Microsoft Support and look up KB 297694. This has a hotfix -- for Windows XP only. I've got Windows 7. And the "Contact Us" link doesn't actually have any specific category for technical issues - only one for non-technical issues, instructions to contact your manufacturer, or specific categories (like IPhone) that aren't related.

Now I'm not only getting the runaround within a company, they are coordinating their runaround strategies to send me to another companie's runaround department.

Someone suggested just going back to version 5.0. Having worked in this industry, I can guess what happened: the guy who wrote the software and understood it moved on to another job, within or outside the company, and the new programmers are being managed according to the latest approach (structured programming? agile? foobarius?) and no one really knows how the software works.

Wednesday, January 5, 2011

bizspark

I finally got my site www.sym3d.ca done, and applied to the BizSpark program offered by Microsoft at www.Bizspark.com It's a handy program that gives you cheap access to Microsoft software, and contact with venture capital and business partners.

To apply, you need a business site, and a non-free email account. Most hosting services give you some email addresses associated with the site for free, and google apps gives you a free version restricted to 50 users. I used the hosting service discountasp.net which offered a year of hosting for $90.