Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts

Friday, October 2, 2015

Python | Simple PyQt5 GUI example with QSS Styling

Hello All,

I started reading about PyQt I decide to try the framework. Till now I had only worked with Java Swing. But after trying I seriously think that I might forget using Java Swing. I loved using PyQt5 since it is very easy and quite powerful, fast, and flexible. It does have more GUI features than Java (I don't know but with my experience in Java, I find Qt to be more mature.)

Since I have moved to Python 3.4 and hence decided to use the latest version and that is PyQt5 instead of PyQt4.

Today I will give you a little snippet that I wrote just as a part of learning the framework. I can't tell much about the efficiency of my code since I have very less experience with Python and Qt. So, if someone more experienced will comment or criticize my code then I am always open and would be very happy as well.

To develop this little GUI I used GridLayout and so the GUI and its widgets are adjustable with the base window. I used QSS to design the gui with colors.

QSS : Its a variant of CSS with most of the properties intersecting with CSS styles and specially designed to work and design the Qt guis and widgets. But instead of HTML tags we use the Widgets class name for styling them, like :- QWidget, QLineEdit, QLabel, QPushButton etc. etc.

QSS is a feature which I loved the most since everything else was pretty much the same with Java Swings.

Screenshot

[Image: H7uLJPu.png] 

QSS File Code

QWidget {
   background-color: #222222;
}

QLineEdit {
   background-color: aliceblue;
   color: #618b38;
   font-style: italic;
   font-weight: bold;
}

QLabel {
   background-color: #222222;
   color: #618b38;
}

QPushButton {
   background-color: #8b0000;
   color: #ffffff;
   border-radius: 5px;
   border-style: none;
   height: 25px;
}


Code for GUI

from PyQt5 import QtCore, QtWidgets

__author__ = "Psycho_Coder"


# noinspection PyUnresolvedReferences
class MainUiWindow(object):

   def __init__(self):

       #Main Window
       self.centralwidget = QtWidgets.QWidget(MainWindow)

       """
       Using Grid Layouts for Widgets Alignment
       """
       #Grid Layout for Main Grid Layout
       self.maingrid_layout = QtWidgets.QGridLayout(self.centralwidget)

       #Grid Layout for Result Section Layout
       self.resultgird = QtWidgets.QGridLayout()

       #Grid Layout for Information section
       self.infogrid = QtWidgets.QGridLayout()

       #Grid Layout for holding all the widgets in place
       self.outergrid = QtWidgets.QGridLayout()

       #Button to clear all test input
       self.clearall = QtWidgets.QPushButton(self.centralwidget)

       #Button to show the final result by append
       self.showres = QtWidgets.QPushButton(self.centralwidget)

       #Horizontal layout to hold the result section horizontally
       self.horizontal_layout = QtWidgets.QHBoxLayout()

       """
       Show results widgets
       """
       self.fullname = QtWidgets.QLabel(self.centralwidget)
       self.result = QtWidgets.QLabel(self.centralwidget)

       """
       Get Names info section
       """
       self.firstname = QtWidgets.QLabel(self.centralwidget)
       self.lastname = QtWidgets.QLabel(self.centralwidget)

       #TextBox to get user input
       self.fname = QtWidgets.QLineEdit(self.centralwidget)
       self.lname = QtWidgets.QLineEdit(self.centralwidget)

   def init_gui(self, MainWindow):

       MainWindow.setObjectName("MainWindow")

       MainWindow.setStyleSheet(open("style.qss", "r").read())
       MainWindow.setAutoFillBackground(True)
       MainWindow.resize(328, 166)

       self.centralwidget.setObjectName("centralwidget")

       self.maingrid_layout.setObjectName("maingrid_layout")
       self.outergrid.setObjectName("outergrid")
       self.infogrid.setObjectName("infogrid")

       self.firstname.setObjectName("firstname")
       self.infogrid.addWidget(self.firstname, 0, 0, 1, 1)

       self.fname.setObjectName("fname")
       self.infogrid.addWidget(self.fname, 0, 1, 1, 1)

       self.lastname.setObjectName("lastname")
       self.infogrid.addWidget(self.lastname, 1, 0, 1, 1)

       self.lname.setObjectName("lname")
       self.infogrid.addWidget(self.lname, 1, 1, 1, 1)

       self.outergrid.addLayout(self.infogrid, 0, 0, 1, 1)

       self.fullname.setObjectName("fullname")

       self.result.setMaximumSize(QtCore.QSize(140, 16777215))
       self.result.setObjectName("result")

       self.resultgird.setObjectName("resultgird")
       self.resultgird.addWidget(self.fullname, 0, 0, 1, 1)
       self.resultgird.addWidget(self.result, 0, 1, 1, 1)

       self.outergrid.addLayout(self.resultgird, 1, 0, 1, 1)

       self.showres.setObjectName("showres")
       self.clearall.setObjectName("clearall")

       self.horizontal_layout.setObjectName("horizontal_layout")
       self.horizontal_layout.addWidget(self.showres)
       self.horizontal_layout.addWidget(self.clearall)

       self.outergrid.addLayout(self.horizontal_layout, 2, 0, 1, 1)
       self.maingrid_layout.addLayout(self.outergrid, 0, 0, 1, 1)

       MainWindow.setCentralWidget(self.centralwidget)

       self.retranslate_gui(MainWindow)

       #Add signals of clear to LineEdit widgets to clear the texts
       self.clearall.clicked.connect(self.result.clear)
       self.clearall.clicked.connect(self.lname.clear)
       self.clearall.clicked.connect(self.fname.clear)
       self.showres.clicked.connect(self.__name)

       QtCore.QMetaObject.connectSlotsByName(MainWindow)

   def __name(self):
       name = self.fname.text() + " " + self.lname.text()
       self.result.setText("" + name + "")

   def retranslate_gui(self, MainWindow):
       _translate = QtCore.QCoreApplication.translate
       
       MainWindow.setWindowTitle(_translate("MainWindow", "Name Concatenation"))
       self.lastname.setText(_translate("MainWindow", "Last Name :"))
       self.firstname.setText(_translate("MainWindow", "First Name :"))
       self.fullname.setText(_translate("MainWindow", "Concatenated Name :-"))
       self.result.setText(_translate("MainWindow", ""))
       self.showres.setText(_translate("MainWindow", "Show Name!"))
       self.clearall.setText(_translate("MainWindow", "Clear All"))

if __name__ == "__main__":
   import sys
   app = QtWidgets.QApplication(sys.argv)
   MainWindow = QtWidgets.QMainWindow()
   ui = MainUiWindow()
   ui.init_gui(MainWindow)

   MainWindow.show()
   sys.exit(app.exec_())


I hope you like this short snippet (not short I guess :troll:) and probably you learnt a bit by observation how to design GUIs and use layouts properly and how the hierarchy should be followed. Share this post. Thank you.
Continue Reading →

Sunday, September 6, 2015

Peter de Jong Attractor in Python

It's pretty simple and I have specially given the code in python which demonstrates the concept. For details on Attractors please refer wikipedia. I have used the Python pygame module for graphics.

Here's the end result:-

[Image: GOVr9W9.png]

Here's the code:


I have used two custom fonts as you can see in the code above. You can get them from here and here. You can use either system font or download two new fonts and put them in the same execution directory. Make sure you edit the code with proper font names. 

self.xn, self.yn = ( sin( self.constants["a"] * self.yn ) - cos ( self.constants["b"] \
                                   * self.xn ) ), ( sin( self.constants["c"] * self.xn ) - cos( self.constants["d"] * self.yn ) )
                   #  xn, yn = ( d * sin( a * xn ) - sin ( b * yn ) ), ( c * cos( a * xn ) + cos( b * yn ) )
                   self.coords.append( ( self.xn, self.yn ) )
                   pygame.draw.circle( self.screen, self.grayshade , ( self.width // 2 + \
                                           int( 120 * self.xn ), self.height // 2 + int( 120 * self.yn ) ), 1, 1 )
Changing the constants a,b, c and varying the number of iteration you can create many more custom shapes. So be creative and start hacking!
Continue Reading →

Monday, July 20, 2015

Bouncing Box animation in Python using PyGame

Bouncy is a class which demonstrates Bouncing rectangle animation which options like resolution, bouncy rectangle size, speed. Whenever it collides with the borders or wall it plays a sound. The code doesn't have any Magic Numbers, everything has been named pretty well so that it is readable to most and many error handling cases has been handled (These being the reason that the code is long else it can be reduced).


How to use ?

Just initialize the class with the parameters. if you don't give any params a default value is taken.


Parameters :-

1. resolution : Takes a tuple of values for Screen Size like (800, 600). Default Value : (640, 480)
2. rectobj_size : Takes a tuple of values for rectangle object size like (40, 30). Default Value : (50, 50)
3. speed : Animation Speed. Min value 1

Example :-

Bouncy( ( 600, 400 ), ( 40, 40 ), 5 ) or Bouncy( resolution = ( 600, 400 ), rectobj_size = ( 40, 40 ), speed = 5 )

Code:



Continue Reading →

Sunday, July 19, 2015

Create basic shapes using PyGame

We create a basic window in Python and draw the basic geometrical shapes like Rectangle, Circle, Line, ellipse or polygon etc. You should have pygame installed else the code will not execute and throw an ImportError.






Continue Reading →

Thursday, July 16, 2015

Memory Puzzle game in Java

Memory puzzle is a simple puzzle game of flipping and discovering pairs of similar cards. The player flips inverted cards one by one. If two cards flipped are same, they stay in that state, else they are flipped back to their original inverted state. The game ends when all the cards are flipped in pairs successfully.

Screenshot

[Image: memorypuzzle.png]

Source Code

Cards.java

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;


public class Cards {

private static BufferedImage card[] = new BufferedImage[9];
private static BufferedImage cardBack;

private static String cardFileName[] = {"1.jpg", "2.jpg", "3.jpg", "4.jpg",
"5.jpg", "6.jpg", "7.jpg", "8.jpg", "9.jpg"};
private static String cardBackName = "back.jpg";

static {
for(int i = 0; i < cardFileName.length; i++) {
try {
card[i] = ImageIO.read(Cards.class.getResourceAsStream(cardFileName[i]));
}
catch(Exception e) {
e.printStackTrace();
}
}

try {
cardBack = ImageIO.read(Cards.class.getResourceAsStream(cardBackName));
}
catch(Exception e) {
e.printStackTrace();
}
}

public static BufferedImage get(int v) {
return card[v];
}
public static BufferedImage getBack() {
return cardBack;
}
}

CardSlot.java

import java.awt.image.BufferedImage;


public class CardSlot {
private BufferedImage image;
private boolean visible, pairedUp;
private int value;

public CardSlot(int card) {
value = card;
image = Cards.get(card);
visible = false;
pairedUp = false;
}

public boolean isVisible() {
return visible;
}
public boolean flipCard() {
if(!pairedUp) {
visible = !visible;
return true;
}
return false;
}

public boolean isPairedUp() {
return pairedUp;
}
public void pairUp() {
pairedUp = true;
}

public BufferedImage getImage() {
if(isVisible())
return image;
else
return Cards.getBack();
}

public int getValue() {
return value;
}
}

Game.java

import java.awt.event.KeyEvent;
import java.util.Random;


public class Game {
private int width;
private int difficulty;
private int[][] board;
private int zX, zY;
private int forbidden;

public Game(int width, int difficulty) {
this.width = width;
this.difficulty = difficulty;

board = new int[width][width];

int ctr = 1;
for(int i = 0; i < width; i++) {
for(int j = 0; j < width; j++) {
board[j][i] = ctr++;
}
}
board[width - 1][width - 1] = 0;
zX = width - 1;
zY = width - 1;
forbidden = 2;

shuffle();
}

private void shuffle() {
Random random = new Random();
int i = 0;
while(i < difficulty) {
int v = random.nextInt(4);

switch(v) {
case 1:
if(up() && forbidden != 1) {
i++;
forbidden = 2;
}
break;
case 2:
if(down() && forbidden != 2) {
i++;
forbidden = 1;
}
break;
case 3:
if(left() && forbidden != 3) {
i++;
forbidden = 4;
}
break;
case 4:
if(right() && forbidden != 4) {
i++;
forbidden = 3;
}
break;
}
}
}

private boolean up() {
if(zY > 0) {
board[zX][zY] = board[zX][zY - 1];
board[zX][zY - 1] = 0;
zY--;
return true;
}
return false;
}
private boolean down() {
if(zY < width - 1) {
board[zX][zY] = board[zX][zY + 1];
board[zX][zY + 1] = 0;
zY++;
return true;
}
return false;
}
private boolean left() {
if(zX > 0) {
board[zX][zY] = board[zX - 1][zY];
board[zX - 1][zY] = 0;
zX--;
return true;
}
return false;
}
private boolean right() {
if(zX < width - 1) {
board[zX][zY] = board[zX + 1][zY];
board[zX + 1][zY] = 0;
zX++;
return true;
}
return false;
}

public boolean isCorrect() {
int ctr = 1;
for(int i = 0; i < width; i++) {
for(int j = 0; j < width; j++) {
if(board[j][i] == ctr++ || (i == width - 1 && j == width - 1))
continue;
else
return false;
}
}
return true;
}

public int getValueAt(int x, int y) {
if(x >= 0  && x <= width - 1 && y >= 0 && y <= width-1) {
return board[x][y];
}
return 0;
}

public void keyPressed(int key) {
switch(key) {
case KeyEvent.VK_UP:
up();
break;
case KeyEvent.VK_DOWN:
down();
break;
case KeyEvent.VK_LEFT:
left();
break;
case KeyEvent.VK_RIGHT:
right();
break;
}
}
}

SlidingPuzzlePanel.java

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class SlidingPuzzlePanel extends JPanel {

private static final long serialVersionUID = 4501938941435763747L;

private static final int SIDE = 4;
private static final int FONT_SIZE = 40;
private static int LEVEL = 10;

private Game game;
private Font font;
private Color background, foreground, borderColor;

private int slotWidth, slotHeight, slotXOffset, slotYOffset;

private int inX, inY, xOffset, yOffset;
private boolean dragged;

public SlidingPuzzlePanel() {
game = new Game(SIDE, LEVEL);
font = new Font(Font.SERIF, Font.BOLD, FONT_SIZE);

slotWidth = SlidingPuzzle.WIDTH / SIDE;
slotHeight = SlidingPuzzle.HEIGHT / SIDE;
slotXOffset = slotWidth / 2 - FONT_SIZE / 4;
slotYOffset = slotHeight / 2 + FONT_SIZE / 3;

background = new Color(123, 155, 232);
foreground = new Color(123, 255, 132);
borderColor = new Color(223, 255, 132);
dragged = false;

setFocusable(true);
requestFocus();

addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if(dragged) {
inX = e.getXOnScreen() - xOffset;
inY = e.getYOnScreen() - yOffset;
SlidingPuzzle.frame.setLocation(inX, inY);
}
else {
dragged = true;
xOffset = e.getX();
yOffset = e.getY();
}
}

@Override
public void mouseMoved(MouseEvent e) {
dragged = false;
}
});

addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch(key) {
case KeyEvent.VK_ESCAPE:
SlidingPuzzle.frame.dispose();
break;
default:
game.keyPressed(key);
repaint();
if(game.isCorrect()) {
JOptionPane.showMessageDialog(SlidingPuzzle.frame, "You Win!");
LEVEL += 10;
game = new Game(SIDE, LEVEL);
repaint();
}
}
}
});
}

@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setFont(font);
g2d.setColor(background);
g2d.fillRect(0, 0, getWidth(), getHeight());
drawBorders(g2d);

g2d.setColor(foreground);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(game.getValueAt(j, i) != 0)
g2d.drawString(""+game.getValueAt(j, i), slotXOffset + j * slotWidth,
slotYOffset + i * slotHeight);
}
}
}
private void drawBorders(Graphics2D g2d) {
g2d.setColor(borderColor);
for(int i = 0; i < 3; i++)
g2d.drawRect(i, i, SlidingPuzzle.WIDTH - 1 - 2 * i, SlidingPuzzle.HEIGHT - 1 - 2 * i);

for(int  i = 1; i < 4; i++) {
int level = i * slotHeight;
g2d.drawLine(0, level, SlidingPuzzle.WIDTH, level);
g2d.drawLine(0, level + 1, SlidingPuzzle.WIDTH, level + 1);
g2d.drawLine(0, level + 2, SlidingPuzzle.WIDTH, level + 2);

g2d.drawLine(level, 0, level, SlidingPuzzle.HEIGHT);
g2d.drawLine(level + 1, 0, level + 1, SlidingPuzzle.HEIGHT);
g2d.drawLine(level + 2, 0, level + 2, SlidingPuzzle.HEIGHT);
}
}
}

SlidingPuzzle.java

import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class SlidingPuzzle {
public static final int WIDTH = 512;
public static final int HEIGHT = 512;

public static JFrame frame;

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
frame = new JFrame("Sliding Puzzle");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setUndecorated(true);
frame.setSize(WIDTH, HEIGHT);

SlidingPuzzlePanel spp = new SlidingPuzzlePanel();
frame.add(spp);

frame.setVisible(true);
}
});
}
}


Download Runnable Jar:- Memory Puzzle 
Credits for Game:- Solixious

Continue Reading →

Wednesday, July 15, 2015

Sliding Puzzle Game in Java

Sliding Puzzle is a puzzle game in which numbers are arranged in an unordered fashion in a 4x4 grid along with one slot missing. You have to use the four arrow keys to slide the adjacent grid value into the blank grid and ultimately getting the grid in order.

Screenshot

[Image: slidingpuzzle.png]

Source Code 


Game.Java
 
SlidingPuzzlePanel.java
 
SlidingPuzzle.java
Credits for Game :- Solixious


Continue Reading →

Space Warrior Game in Java

The game simply consists of a ship that travels through space encountering asteroids and villains in the way. The game ends when the final boss is destroyed. FYI, I myself could not complete this game, except in the testing stage where I manipulated code to call boss very early.

Screenshots:

[Image: sw1.png]

[Image: sw2.png] 

[Image: sw3.png] 

Runnable JAR : space_warrior.jar
Java 8 or higher is recommended for execution of the runnable JAR file.

Github Link : Space Warrior

Credits for the sprite images go to Ari Feldman.

Credits for this Game :- Solixious

 
Continue Reading →

Thursday, July 2, 2015

3D Heart Surface in MATLAB


Matlab is pretty neat, I downloaded a trial version of Matlab to try it out. I came across on Mathworld something called Heart Equation and this 3D Heart Surface which looked pretty neat and cool and hence I tried it out in MATLAB.

Here's the code :-

Continue Reading →

Wednesday, July 1, 2015

Create Vector images using Bit Arrays in Java

Hello Everyone,


Today I will show you how to create a simple image by using code in Java in Applet. I have used Netbeans IDE 7.3 beta 2 and Java 7. You must have a bit knowledge about java and Applets for you to understand this code properly.

We will create a simple smiley and a hut. To create a simple hut or smiley we have to create a pixel array of the image which we will use to create a image. We will make a pixel Array of 16 X 16 bit as shown in the image below..

 

[Image: create_image_zps27f07944.png]
[Image: tongue_zps23d8d0a2.png]



If you use an IDE like Netbeans or eclipse then you can see the image as an IDE traces out similar variable and highlights them and so it will be easier for you to create them.

we create two object of image class in which the image will be stored or created.

Image smiley;
Image house;


Next we instantiate the colors we want to use for displaying the image

protected static final int w = Color.white.getRGB();
protected static final int y = Color.yellow.getRGB();
protected static final int b = Color.black.getRGB();
protected static final int r = Color.red.getRGB();
protected static final int g = Color.green.getRGB();


Here are the pixel arrays for hut and smiley1 = :) and Smiley2 = :P

protected static final int imageData[] = {
        w, w, w, y, y, y, y, y, y, y, y, y, y, w, w, w,
        w, w, y, y, y, y, y, y, y, y, y, y, y, y, w, w,
        w, y, y, y, y, y, y, y, y, y, y, y, y, y, y, w,
        w, y, y, y, b, b, y, y, y, y, b, b, y, y, y, w,
        y, y, y, y, b, b, y, y, y, y, b, b, y, y, y, y,
        y, y, y, y, y, y, y, y, y, y, y, y, y, y, y, y,
        y, y, y, y, y, y, y, y, y, y, y, y, y, y, y, y,
        y, y, y, y, y, y, y, y, y, y, y, y, y, y, y, y,
        y, y, y, y, y, y, y, y, y, y, y, y, y, y, y, y,
        y, y, y, b, y, y, y, y, y, y, y, y, b, y, y, y,
        y, y, y, y, b, y, y, y, y, y, y, b, y, y, y, y,
        y, y, y, y, y, b, b, y, y, b, b, y, y, y, y, y,
        w, y, y, y, y, y, y, b, b, y, y, y, y, y, y, w,
        w, y, y, y, y, y, y, y, y, y, y, y, y, y, y, w,
        w, w, y, y, y, y, y, y, y, y, y, y, y, y, w, w,
        w, w, w, y, y, y, y, y, y, y, y, y, y, w, w, w
    };

protected static final int imageData2[] = {
        w, w, w, b, b, b, b, b, b, b, b, b, b, w, w, w,
        w, w, b, g, g, g, g, g, g, g, g, g, g, b, w, w,
        w, b, g, g, g, g, g, g, g, g, g, g, g, g, b, w,
        b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b,
        b, y, y, y, y, y, y, y, y, y, y, y, y, y, y, b,
        b, y, y, y, y, y, y, y, y, y, y, y, y, y, y, b,
        b, y, y, b, b, y, y, r, r, y, y, b, b, y, y, b,
        b, y, y, b, b, y, y, r, r, y, y, b, b, y, y, b,
        b, y, y, y, y, y, y, r, r, y, y, y, y, y, y, b,
        b, y, y, y, y, y, y, r, r, y, y, y, y, y, y, b,
        b, y, y, y, y, y, y, r, r, y, y, y, y, y, y, b,
        b, b, b, b, b, b,  b, b, b, b, b, b, b,  b, b, b,
        w, w, w, w, w, w, w, w, w, w, w, w, w, w, w, w,
        w, w, w, w, w, w, w, w, w, w, w, w, w, w, w, w,
        w, w, w, w, w, w, w, w, w, w, w, w, w, w, w, w,
        w, w, w, w, w, w, w, w, w, w, w, w, w, w, w, w
};

protected static final int imageData3[] = {
        w, w, w, y, y, y, y, y, y, y, y, y, y, w, w, w,
        w, w, y, y, y, y, y, y, y, y, y, y, y, y, w, w,
        w, y, y, y, y, y, y, y, y, y, y, y, y, y, y, w,
        w, y, y, y, b, b, y, y, y, y, b, b, y, y, y, w,
        y, y, y, y, b, b, y, y, y, y, b, b, y, y, y, y,
        y, y, y, y, y, y, y, y, y, y, y, y, y, y, y, y,
        y, y, y, y, y, y, y, y, y, y, y, y, y, y, y, y,
        y, y, y, y, y, y, y, y, y, y, y, y, y, y, y, y,
        y, y, y, y, y, y, y, y, y, y, y, y, y, y, y, y,
        y, y, y, b, y, y, y, y, y, y, y, y, b, y, y, y,
        y, y, y, y, b, y, y, y, y, y, y, b, r, y, y, y,
        y, y, y, y, y, b, b, y, y, b, b, r, r, y, y, y,
        w, y, y, y, y, y, y, b, b, r, r, r, r, y, y, w,
        w, y, y, y, y, y, y, y, y, r, r, r, r, y, y, w,
        w, w, y, y, y, y, y, y, y, r, r, r, r, y, w, w,
        w, w, w, y, y, y, y, y, y, y, r, r, y, w, w, w
};


Here's the complete code :-


Here is the resulting output image :-

[Image: newsmiley_zpsfdbadd83.png]

How this will help you ?

This will help you in many ways. Suppose that you are writing some kind of game and with this you can make your own gaming vectors like arrows, pointers, small cars or human figures. Even of you wan then you can colorize these, it depends upon the programmer on how will he/she is able to apply a concept.


Have fun coding.

Thank you,
Sincerely,
Psycho_Coder

Continue Reading →

JCA (Java Cryptography Architecture) | Listing all Security Providers

Duke, the Java Mascot, in the waving pose. Duk...
Duke, the Java Mascot(Photo credit: Wikipedia)
The term "Cryptographic Service Provider" (used interchangeably with "provider" in this document) refers to a package or set of packages that supply a concrete implementation of a subset of the JDK Security API cryptography features. The Provider class is the interface to such a package or set of packages. It has methods for accessing the provider name, version number, and other information.

The above paragraph has been taken from Here

If you want to get the list of the all the JCA Security Providers then you can use the following code, and it also prints the information's and  its version : -

Code :-


Continue Reading →

Tuesday, June 30, 2015

Monday, June 29, 2015

Code for Damerau Lavenshtein Distance in Java

Earlier I had posted a tutorial on Fuzzy String Matching with Python Code. Here in this post I am sharing the Damerau Lavenshtein Algorithm Code in Java.

package com.codehackersblog.editdistance;

/**
*
* @author psychocoder
* @version 1.0
*/
public class DamerauLavenshtein {

    private String s1;
    private String s2;
    private int len_s1;
    private int len_s2;

    public DamerauLavenshtein() {
        s1 = null;
        s2 = null;
    }

    public DamerauLavenshtein(String s1, String s2) {
        this.s1 = s1.toLowerCase();
        this.s2 = s2.toLowerCase();
    }

    private void putValue(String m, String n) {
        s1 = m.toLowerCase();
        s2 = n.toLowerCase();
    }

    private int getMinimum(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }

    private int getDamerauLavenshtein() {

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        if (len_s1 == 0) {
            return len_s2;
        }

        if (len_s2 == 0) {
            return len_s1;
        }

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    cost = 0;
                } else {
                    cost = 1;
                }

                d[i][j] = getMinimum(
                        d[i - 1][j] + 1, /*Deletion*/
                        d[i][j - 1] + 1, /*Insertion*/
                        d[i - 1][j - 1] + cost /*Substitution*/
                );

                if (i > 1 && j > 1 && s1.charAt(i - 1) == s2.charAt(j - 1)
                        && s2.charAt(j - 1) == s1.charAt(i - 1)) {
                    d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);  /*transposition*/

                }
            }
        }

        return d[len_s1][len_s2];
    }

    private int getDamerauLavenshtein(String s1, String s2) {

        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    cost = 0;
                } else {
                    cost = 1;
                }

                d[i][j] = getMinimum(
                        d[i - 1][j] + 1, /*Deletion*/
                        d[i][j - 1] + 1, /*Insertion*/
                        d[i - 1][j - 1] + cost /*Substitution*/
                );

                if (i > 1 && j > 1 && s1.charAt(i - 1) == s2.charAt(j - 1)
                        && s2.charAt(j - 1) == s1.charAt(i - 1)) {
                    d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);  /*transposition*/

                }
            }
        }

        return d[len_s1][len_s2];

    }

    public static void main(String... args) {
        DamerauLavenshtein ob = new DamerauLavenshtein("Ludo", "lludo");
        System.out.println(ob.getDamerauLavenshtein());
        System.out.println(ob.getDamerauLavenshtein("Hello", "olhel"));
    }

}

Continue Reading →

Code for Wagner Fisher Algorithm in Java

Earlier I had posted a tutorial on Fuzzy String Matching with Python Code. Here in this post I am sharing the Wagner Fisher Algorithm Code in Java.

package com.codehackersblog.editdistance;

/**
*
* @author psychocoder
* @version 1.0
*/
public class WagnerFisher {

    private String s1;
    private String s2;
    private int len_s1;
    private int len_s2;

    public WagnerFisher() {
        s1 = null;
        s2 = null;
    }

    public WagnerFisher(String s1, String s2) {
        this.s1 = s1.toLowerCase();
        this.s2 = s2.toLowerCase();
    }

    private void putValue(String m, String n) {
        s1 = m.toLowerCase();
        s2 = n.toLowerCase();
    }

    private int getMinimum(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }

    private int getWagnerFisher() {

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    d[i][j] = d[i - 1][j - 1];
                } else {

                    d[i][j] = getMinimum(
                            d[i - 1][j] + 1, /*Deletion*/
                            d[i][j - 1] + 1, /*Insertion*/
                            d[i - 1][j - 1] + 1 /*Substitution*/
                    );
                }
            }
        }

        return d[len_s1][len_s2];
    }

    private int getWagnerFisher(String s1, String s2) {

        s1 = s1.toLowerCase();
        s2 = s2.toLowerCase();

        len_s1 = s1.length();
        len_s2 = s2.length();

        int[][] d = new int[len_s1 + 1][len_s2 + 1];
        int i, j, cost;

        for (i = 0; i <= len_s1; i++) {
            d[i][0] = i;
        }

        for (j = 0; j <= len_s2; j++) {
            d[0][j] = j;
        }

        for (i = 1; i <= len_s1; i++) {
            for (j = 1; j <= len_s2; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    d[i][j] = d[i - 1][j - 1];
                } else {

                    d[i][j] = getMinimum(
                            d[i - 1][j] + 1, /*Deletion*/
                            d[i][j - 1] + 1, /*Insertion*/
                            d[i - 1][j - 1] + 1 /*Substitution*/
                    );
                }
            }
        }

        return d[len_s1][len_s2];

    }

    public static void main(String... args) {
        WagnerFisher ob = new WagnerFisher("loookes", "looks");
        System.out.println(ob.getWagnerFisher());
        ob.putValue("Hiya", "Hey");
        System.out.println(ob.getWagnerFisher());
        System.out.println(ob.getWagnerFisher("Hello", "Heoll"));
    }

}

Continue Reading →

Sunday, June 28, 2015

C Code for Longest Common Subsequence Using Dynamic Programming

Here's the C Code for LCS using Dynamic programming :-


Output:-
Output:-

Matrix Generated

0 |0 |0 |0 |0 |
0 |0 |0 |0 |0 |
0 |1 |1 |1 |1 |
0 |1 |2 |2 |2 |
0 |1 |2 |3 |3 |
0 |1 |2 |3 |4 |

Length of Longest Common Subsequence = 4

Continue Reading →

Friday, June 26, 2015

Bouncing Ball Animation using Processing.js



Today I made the old school Bouncing Ball Animation using Processing.js

Here's the code with output :-




Continue Reading →

Wednesday, June 24, 2015

PDF File Generation example in Java using iText Library

made an example where reports can be generated in PDF file format using iText library for Java. I made a swing app and we enter the data and then click the create pdf button to generate the pdf. Its not a tutorial but more like an example with a demo. Use the code, and I hope its readable enough.

[Image: 2Ssa87i.png]


Continue Reading →

Tuesday, June 23, 2015

L-Systems | Sierpinski Triangle in VB.NET


The Sierpinski triangle (also with the original orthography SierpiƄski), also called the Sierpinski gasket or the Sierpinski Sieve, is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller equilateral triangles.

Public Class Form1
   'We have used the following rules
   ' -1 = turn right by angle
   ' +1 = turn left by angle
   ' 2 = 'a'
   ' 3 = 'b'
   'Therefore te rules are represented like this
   ' 2 --> 3 -1 2 1 3
   ' 3 --> 2 +1 3 +1 2
   'Start Symbol : a
   ' 
   Dim angle As Double
   Dim size_of_triangle As Integer
   Dim no_of_iter As Integer
   Dim t As Integer
   Dim lst As List(Of Integer) = New List(Of Integer)

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       numIter.Value = 7
       numSize.Value = 4
       numAngle.Value = 60
   End Sub

   Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
       Dim drawingPt As Point = New Point(250, Me.ClientSize.Height - 5)
       Dim D As Double = 0
       Dim P1 As Point
       For Each i As Integer In lst
           Select Case i
               Case -1
                   D -= angle
               Case 1
                   D += angle
               Case 2, 3
                   P1 = getNewPoint(drawingPt, D)
                   e.Graphics.DrawLine(Pens.Tomato, drawingPt, P1)
                   drawingPt = P1
           End Select
       Next

   End Sub

   Private Function getNewPoint(ByVal p0 As Point, ByVal d As Double) As Point
       Dim p1 As Point
       p1.X = p0.X + Math.Cos(d) * size_of_triangle
       p1.Y = p0.Y + Math.Sin(d) * size_of_triangle
       Return p1
   End Function

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       Label4.Visible = True
       Me.TransparencyKey = Color.Beige
       angle = (numAngle.Value) * Math.PI / 180
       size_of_triangle = numSize.Value
       no_of_iter = numIter.Value
       t = 1
       If (no_of_iter Mod 2) = 1 Then t = -1
       lst = New List(Of Integer)
       lst.Add(2)
       For i As Integer = 0 To no_of_iter
           lst = Expand(lst)
       Next i
       Me.Invalidate()
   End Sub

   Private Function Expand(ByVal lst As List(Of Integer)) As List(Of Integer)
       Dim lst1 As List(Of Integer) = New List(Of Integer)
       For Each i As Integer In lst
           Select Case i
               Case -1, 1
                   lst1.Add(i)
               Case 2
                   ' 2 --> 3 -1 2 -1 3
                   lst1.Add(3)
                   lst1.Add(-1 * t)
                   lst1.Add(2)
                   lst1.Add(-1 * t)
                   lst1.Add(3)
               Case 3
                   ' 3 --> 2 +1 3 +1 2
                   lst1.Add(2)
                   lst1.Add(1 * t)
                   lst1.Add(3)
                   lst1.Add(1 * t)
                   lst1.Add(2)
           End Select
       Next
       Return lst1
   End Function

   Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
       Application.Exit()
   End Sub

   Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
       Label4.Visible = False
       Me.TransparencyKey = Color.Black
   End Sub
End Class



Related articles
Continue Reading →

Follow Me!

Followers

Visitor Map