30 Mart 2012 Cuma

Documentation - UML Diagram

Projenizin design ve documentation aşamalarında genellikle kullanılan UML diagrams, sequence diagrams,
state diagram, activity diagram ... oluşturmak için gliffy çok kullanışlı online olarak üyeliğe gerek olmadan kolay bir şekilde kulanabilirsiniz.


Eğer büyük bir proje yapıyorsanız veya source code dan hemen UML oluşturturmak istiyorsanız
Visual Paradigm kullanabilirsiniz.

24 Mart 2012 Cumartesi

Icon overlay on taskbar button

Sample code

overlay icon un yanı sıra jump list, progress bar, gibi değişikler yapabilirisiniz taskbar button a.






package com.strixcode.j7goodies.samples;

import com.strixcode.j7goodies.AppUserModelId;
import com.strixcode.j7goodies.TaskbarButton;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;

/**
* Demonstrates how to use the TaskbarButton class to display an overlay icon.
*/
public class OverlayIconSample extends JFrame implements ActionListener {
TaskbarButton taskbarButton;

public OverlayIconSample() {
super("J7Goodies Demo");

getContentPane().add("Center", new JLabel("Click a button to display an overlay icon"));
Box box = Box.createVerticalBox();


final String[] icons = {"n/a", "images/available.png", "images/away.png",
"images/busy.png", "images/offline.png"
};
final String[] captions = {"No icon", "Available", "Away", "Busy",
"Offline"
};

for (int i = 0; i < icons.length; ++i) {
JButton cb = new JButton(captions[i], loadIcon(icons[i]));
cb.addActionListener(this);
box.add(cb);
}
getContentPane().add("South", box);
}

protected final ImageIcon loadIcon(String path) {
java.net.URL imgURL = this.getClass().getResource(path);
if (imgURL != null)
return new ImageIcon(imgURL);
else
return null;
}

@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
ImageIcon icon = (ImageIcon) button.getIcon();
if (icon != null)
taskbarButton.setOverlayIcon(icon);
else
taskbarButton.clearOverlayIcon();
}

private void setTaskbarButton(TaskbarButton taskbarButton) {
this.taskbarButton = taskbarButton;
}

public static void main(String[] args) throws Exception {
// AppUserModelID must be set before any GUI is shown
AppUserModelId.setCurrentProcessId("StrixCode.J7Goodies.Trial");

// Access GUI objects on the GUI thread
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {}

final OverlayIconSample frame = new OverlayIconSample();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);

// *After* the frame become visible, create a TaskbarButton
// instance for it.
frame.setTaskbarButton(new TaskbarButton(frame));
}
});
}
}

19 Mart 2012 Pazartesi

Matlab - histeq implementation

Matlab da histogram equalization için kullanılan histeq fonksiyonunun implementasyonu:

***F bir gray scale input image****

function image_histeq(F)

I = imread(F);

%histeq
J = histeq(I);

%Output image of our algorithm and its histogram

width = size(I,1);
height = size(I,2);
MN = width * height;

Hist = uint8(zeros(width , height));

frequency = zeros(256 , 1);

probability = zeros(256,1);


for i = 1 : width
for j = 1 : height
value = I(i , j);
frequency(value + 1) = frequency(value + 1) + 1;
probability(value + 1) = frequency(value + 1) / MN;
end
end

sum = 0;
bits = 255;

probCount = zeros(256 , 1);

cum = zeros(256 , 1);


output = zeros(256 , 1);

for i = 1 : size(probability)
sum = sum + frequency(i);
cum(i) = sum;
probCount(i) = cum(i) / MN;
output(i) = round(probCount(i) * bits);
end


for i = 1 : width
for j = 1 : height

Hist(i,j) = output(I(i , j) + 1);

end
end

%display all

subplot(3,2,1);
imshow(I);
title('Input Image');
subplot(3,2,2);
imhist(I);
title('Input image histogram');
subplot(3,2,3);
imshow(J);
title('Output image of histeq function');
subplot(3,2,4);
imhist(J);
title('histeq function histogram');
subplot(3,2,5);
imshow(Hist);
title('Output image of our algorithm');
subplot(3,2,6);
imhist(Hist);
title('our algorithm histogram');


return

Download Code

Matlab - filter Implementation

filter2 fonkiyonuyla yapılan bluring işleminin implementasyonu:

***filter2 ve algoritmanın output imageları aynı pencerede subplot kullanarak gösteriliyor***
**** 3 X 3 bir filter kullanılıyor****
***filter size arttıkça bluring artar***
*** F input image: bir gray scale image***


% Main function
function image_filter(F)

%filter2
I = imread(F);
filt = ones(3 , 3) / 9;
res = filter2(filt, I, 'same');
J = uint8(res);

%our filtering algorithm

height = size(I, 1);
width = size(I, 2);

a = zeros(height + 2, width + 2, 'uint8');


for i = 2 : height + 1
for j = 2 : width + 1
a (i, j) = I(i - 1, j - 1);
end
end
b = zeros(height, width, 'uint8');

for i = 1 : height
for j=1 : width
avg = mean2(a(i : i + 2, j : j + 2));
b(i , j) = avg;
end
end

%display all

subplot(2,2,1);
imshow(I);
title('Input Image');
subplot(2,2,2);
imshow(J);
title('Output image of filter2 function');
subplot(2,2,3);
imshow(b);
title('Output image of our function');

return

Download Code

15 Mart 2012 Perşembe

Windows Loopback Sniffer

Projenizi localde çalıştırıp denemek için 127.0.0.1 yani localhost kullanılır.
Socket programlama da debugging biraz sıkıntı olduğu için paketleri izlemek için en iyisi wireshark kullanmak.

Wireshark

Ubuntu da loopback çalışıyor ama windows da çalışmıyor maalesef :(

En basit çözümü bir tane snifferla, örneğin RawCap, 127.0.0.1 i dinlemek ve oluşan dosyayı, örneğin "a.pcap",
wireshark la açıp paketleri inceliyebilirsinz.

RawCap

>>cmd

> RawCap.exe 127.0.0.1 localhost a.pcap

13 Mart 2012 Salı

Java - TCP - Streams

TCP de data stream olarak gönderildiği için data nızın fixed size olması gerekiyor.
mesela 5 byte okuyacağını karşı taraf bilmeli.
Eğer göndereceğiniz paketin size ı değişiyorsa, ilk önce okuyacağı size miktarını göndermeniz lazım ve daha sonra
data yı göndermelisiniz.
Veya bir size belirleyip o size kadar göndermelisiniz.
/***
**** 11 byte okuyorum. Eger -1 olana kadar okursam stream in kapanana kadar anlamına gelir.
/
public static byte[] getRequest(InputStream is) {

byte[] aByte = new byte[11];
int bytesRead = 0;

if (is != null) {

try {

bytesRead = is.read(aByte, 0, aByte.length);

}
catch (Exception ex) {
// Do exception handling
System.out.println("hatta " + ex.getMessage());
}
}
return aByte;
}

12 Mart 2012 Pazartesi

Close java socket

Closing the InputStream of the Socket will lead to the closing of the Socket.
The same goes for closing the OutputStream of the Socket.
Closing the returned InputStream will close the associated socket.

link

10 Mart 2012 Cumartesi

Java - Concurrent Server Using Threads

Server
Thread

import java.net.*;
import java.io.*;

public class KKMultiServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;

try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(-1);
}

while (listening)
new KKMultiServerThread(serverSocket.accept()).start();

serverSocket.close();
}
}



import java.net.*;
import java.io.*;

public class KKMultiServerThread extends Thread {
private Socket socket = null;

public KKMultiServerThread(Socket socket) {
super("KKMultiServerThread");
this.socket = socket;
}

public void run() {

try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));

String inputLine, outputLine;
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);

while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye"))
break;
}
out.close();
in.close();
socket.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}

9 Mart 2012 Cuma

How to Write a Network Protocol

Socket programlama ile bir application gerçektireceksek eğer, ilk önce yapmamız gereken bir protocol oluşturmak.

Geliştireceğimiz application ne gibi işlemler yapacak önce bunu belirlemeliyiz.

Ör:
OPCode(short)     FileName(String)

   1                         "a.txt"

Herbir operasyona bir operasyon kodu yani opcode vermek en mantıklısı.

Bu örnekte client istediği dosyanın adını server a gönderiyor.

Opcode genellikle short tur, 16 bit yeterli.

** 2 numaralı operasyonda da veri gönderiyoruz

OPCode(short)         Data

   2                     ...

**3 numaralı operasyondada reply message ını gönderiyoruz. İstediğimiz sayıyı OK, istediğimiz sayıyı Error yapabiliriz.
Çünkü bunu biz belirliyoruz ve client da server da bunun böyle olduğunu biliyor.

OPCode(short)     Reply #(short)

   3                          26 for OK
                    60 for Error


***Protokolümüzü bu şekilde kağıt üzerine döktükten sonra programlamaya geçmek en iyisidir.
Artık operasyonlar ve işlemler artık belli. Sadece onları implement etmek kalıyor.

7 Mart 2012 Çarşamba

Eclipse - How to build Jar File

link

Creating a New JAR File
To create a new JAR file in the workbench:

1. In the Package Explorer, you can optionally pre-select one or more Java elements to export. (These will be automatically selected in the JAR Package Specification wizard page, described in Step 4.)
2. Either from the context menu or from the menu bar's File menu, select Export.
3. Expand the Java node and select JAR file. Click Next.
4. In the JAR File Specification page, select the resources that you want to export in the Select the resources to export field.
5. Select the appropriate checkbox to specify whether you want to Export generated class files and resources or Export Java source files and resources. Note: Selected resources are exported in both cases.
6. In the Select the export destination field, either type or click Browse to select a location for the JAR file.
7. Select or clear the Compress the contents of the JAR file checkbox.
8. Select or clear the Overwrite existing files without warning checkbox. If you clear this checkbox, then you will be prompted to confirm the replacement of each file that will be overwritten.
9. Note: The overwrite option is applied when writing the JAR file, the JAR description, and the manifest file.
10. You have two options:
Click Finish to create the JAR file immediately.
Click Next to use the JAR Packaging Options page to set advanced options, create a JAR description, or change the default manifest.

Creating a new manifest
1. Follow the procedure for creating a JAR file, but click Next in the last step to go to the JAR Packaging Options page.
2. Set any advanced options that you want to set, and then click Next again to go to the JAR Manifest Specification page.
3. If it is not already selected, click the Generate the manifest file button.
4. You can now choose to save the manifest in the workbench. This will save the manifest for later use. Click Save the manifest in the workspace, then click Browse next to the Manifest file field to specify a path and file name for the manifest.
5. If you decided to save the manifest file in the previous step and you chose to save the JAR description on the previous wizard page, then you can choose to reuse it in the JAR description (by selecting the Reuse and save the manifest in the workspace checkbox). This means that the saved file will be used when the JAR file is recreated from the JAR description.This option is useful if you want to modify or replace the manifest file before recreating the JAR file from the description.
6. You can choose to seal the JAR and optionally exclude some packages from being sealed or specify a list with sealed packages. By default, nothing is sealed.
7. Click the Browse button next to the Main class field to specify the entry point for your applications.
8. Note: If your class is not in the list, then you forgot to select it at the beginning.
Click Finish. This will create the JAR, and optionally a JAR description and a manifest file.

3 Mart 2012 Cumartesi

MatLab - Flip & Rotate & Resize image

% Main function
function main()
global height;
global width;
global x;

x = imread('sample_img.jpg');

% display the original image
figure
image(x);
title('original');

height = size(x, 1);
width = size(x, 2);

flipVertical();
flipHorizantal();
rotateLeft();
rotateRight();
resizeImage();

return

% flips input image vertically
function flipVertical()
global height;
global width;
global x;
y = zeros(height, width, 3, 'uint8');

for i=1:height
for j=1:width
for k=1:3
y(height - i + 1, j, k) = x(i, j, k);
end
end
end
imwrite(y, 'flipVertical.jpg', 'jpg');
figure
image(y);
title('vertical flip');
return

% flips input image horizontally
function flipHorizantal()
global height;
global width;
global x;
y = zeros(height, width, 3, 'uint8');

for i=1:height
for j=1:width
for k=1:3
y(i, width - j + 1, k) = x(i, j, k);
end
end
end
imwrite(y, 'flipHorizontal.jpg', 'jpg');
figure
image(y);
title('horizontal flip');
return

% rotates input image to left
function rotateLeft()
global height;
global width;
global x;
y = zeros(width, height, 3, 'uint8');

for i=1:width
for j=1:height
for k=1:3
y(i, j, k) = x(j, width-i+1, k);

end
end
end
imwrite(y, 'rotateLeft.jpg', 'jpg');
figure
image(y);
title('rotate left');
return

% rotates input image to right
function rotateRight()
global height;
global width;
global x;
y = zeros(width, height, 3, 'uint8');

for i=1:width
for j=1:height
for k=1:3
y(i, j, k) = x(height - j + 1, i, k);
end
end
end
imwrite(y, 'rotateRight.jpg', 'jpg');
figure
image(y);
title('rotate right');
return

% resizes input image to half by keeping aspect ratio
function resizeImage()
global x;
y = zeros(201, 250, 3, 'uint8');
for i=1:201
for j=1:249
for k=1:3
y(i, j, k) = x(i * 2, j * 2, k);
end
end
end

imwrite(y, 'resizeImage.jpg', 'jpg');
figure
image(y);
title('resized');

return

Download Code