Saturday, December 4, 2010
ACM Apply on Google App Engine
Tuesday, November 23, 2010
Filling a bounded region, Turbo C
Implementation:
Starting from the given point apply dfs to the points at n,s,e and w. As the base conditions check whether the color at the given pixel is equal to the boundary. If it is, return. Also even if it is equal to the fill color, return. Sadly I had to program in Turbo C, yes our college still uses that compiler. Here 4 is the fill color.
Function:
// x and y coordinates of point inside
// getmaxcolor() is the color of boundary
// fill the pixel with color 4
dfs(int x, int y) {
if (getpixel(x,y)==getmaxcolor() || getpixel(x,y)==4)
return;
putpixel(x,y,4);
dfs(x-1,y);
dfs(x+1,y);
dfs(x,y-1);
dfs(x,y+1);
}
Floodfill implementation using dfs (stack)
Image Source: Wikipedia
The output is pretty interesting when you use a delay function with it.
Monday, November 22, 2010
929 - Number Maze Uva Online Judge
929 - Number Maze | Time limit | Java | 3.000 | 0.144 | 8 hours ago |
Friday, November 19, 2010
Programming in 61 minutes
Tuesday, November 16, 2010
PriorityQueue Implementation
It basically keeps the elemts sorted accordingly. The head of the queue is the least element to the specified ordering. Implementation note: this implementation provides O(log(n)) time for the insertion methods (offer, poll, remove() and add) methods; linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size).
Sunday, October 31, 2010
Setting up Eclipse for C++ in Windows
Add a new site
http://download.eclipse.org/tools/cdt/releases/helios
Then follow the normal instructions.
I don't know why even I am adding this as a blog post.
Sunday, October 24, 2010
Java Program to print all links in the specified URL
import java.util.StringTokenizer;
import java.io.*;
public class ReadURL
{
public static void main(String[] args) throws Exception
{
URL yahoo = new URL("http://aintmeekcoder.blogspot.com");
BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream()));
String inputLine;
int loc;
while ((inputLine = in.readLine()) != null)
{
if ((loc=inputLine.indexOf("
{
for (int i=loc+9; inputLine.charAt(i)!='>'; i++)
{
System.out.print(inputLine.charAt(i));
}
System.out.println();
}
}
in.close();
}
}
Tuesday, October 19, 2010
352 Seasonal War Uva Online Judge
My Approach:
- Traverse all elements starting from 0,0
- Check whether the element is one
- If it is the applydfs
- applydfs
- if it is one, mark it as 0
- apply the same to all its unvisited neighbours
- if zero, return
- count the no. of times dfs is applied
- this will count the number of connected components
- And thus we have our answer
784 Maze Exploration Uva Online Judge
1. Consider any line starting with '_' as seperator between the inputs.
2. Print the seperator also along with the grid.
3. The walls of the grid can be represented using any alphabet (any character as a matter of fact)
Friday, October 8, 2010
Codechef Programming Google Calendar
Codechef Programming Calendar
Sunday, September 26, 2010
Programming Abstraction Notes: Lecture 4
ifstream for Input Stream for a File. Also remember that ifstream in
in.open("oldfile.txt");
This takes as Parameter old string that means quotations. Which means that
string s = "oldfile.txt";
in.open(s) will give us an error
To fix this problem use s.c_str() function instead of s as the parameter, This
converts it into the old string
Some Discussions about Object Oriented Programming. The Next Big Thing.
Scanner Class was discussed. In Visual C++ while creating a new object there is
no need for the new operator.
What are Container Classes?
CS106B Vector class has a built in Better Array
Bounds Checking
Add, Insert, remove
Memory Managemet, knows its size
Vector Class as a template. Vector decribes what it is storing using a place holder. Example:
template
class Vector {
public:
addObject ( ElemType value);
}
Sunday, August 22, 2010
How to check if an integer is a power of 2 ?
Source: http://www.codechef.com/wiki/tutorial-bitwise-operations
Explanation:
The Integer which is the power of two will always have the leftmost bit 1 and the remaining bits as 0. Let this number be x.
And the number (x-1) will never have the leftmost bit as 1. So x & (x-1) will always give 0 if the number is power of 2.
So to check whether the number is power of two, check x & (x-1) , if the answer is 0 then the number is infact power of 2.
Monday, August 9, 2010
JSP Servlets, Tomcat v6 and MySql
Installing the Server, Tomcat
- Install Java. Make sure you have Java 5 or 6 installed.
- Unzip Tomcat. Unzip tomcat-6.0.28-preconfigured.zip.
- Download Eclipse. Install the Java EE version of Eclipse. If you have JDK 1.6.0_21 or later, you must fix the Eclipse permgen space error.
- Tell Eclipse about Tomcat. Start Eclipse and go to the Workbench. Click on Servers tab at bottom. R-click, New, Server, Apache, Tomcat v6.0, navigate to Tomcat installation folder (e.g.,C:\apache-tomcat-6.0.28), OK.
- Test the server. Test Tomcat within Eclipse. Details here.
- Adjust Eclipse preferences. Suppress unnecessary warnings about serialized classes. Window, Preferences, Java, Compiler, Errors/Warnings, change "Serializable class without ..." to "Ignore". Many other personal preferences re font size, indentation style, etc.
Installing MySql Community Server (Database)
- Use the following link http://dev.mysql.com/downloads/mysql/ to download MySql Community Server
- MySQL will be installed as a service which will start up with Windows. It is recommended you accept most of the defaults although I did check in the "Include Bin Directory in Windows Path" checkbox (which allows Windows to find executables from the command line if you choose to run it that way occasionally) and you should add a password when given the opportunity. You should configure your firewall to accept the port(usually port 3306).
- Download the Java MySql Connector dev.mysql.com/downloads/connector/j/5.1.html
- Download and unzip the file linked above. Copy the mysql-connector-java-5.1.6-bin.jar to the WEB-INF/lib
- Download the proper Graphic User Interface for your MySql: dev.mysql.com/downloads/gui-tools/5.0.html
Java Code to Create your Database, Make sure you replace username and password with the proper values:
import java.io.*;
import java.sql.*;
public class CreateDatabase{
public static void main(String[] args) {
System.out.println("Database creation example!");
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/","root","HashMap");
try{
Statement st = con.createStatement();
BufferedReader bf = new BufferedReader
(new InputStreamReader(System.in));
System.out.println("Enter Database name:");
String database = bf.readLine();
st.executeUpdate("CREATE DATABASE "+database);
System.out.println("1 row(s) affected");
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Java Code to connect to the database you just created.
import java.sql.*;
public class MysqlConnect{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "Replace with YOUR SCHEMA NAME";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Saturday, August 7, 2010
Installing Microsoft Visual Studio 2005 on Windows 7
Install Microsoft Visual Studio 2005 and then install the following updates:
Service Pack 1
Service Pack 1 Update
Friday, July 30, 2010
String.matches()
public boolean matches(String regex)
- Tells whether or not this string matches the given regular expression.
Wednesday, July 14, 2010
Using String.split() instead of String Tokenizer
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
Tuesday, July 6, 2010
Design and Analysis of Algorithms
Resources:
Princeton : http://www.cs.princeton.edu/~wayne/cs423/lectures.html
Friday, June 25, 2010
<c:out = “” /> tag problem
While using the JSTL a very common problem faced is that
<c:out value="${now}"/> tags are not interpreted as they are supposed to be.
After going through the forums, I changed my xml version from 2.5 to 2.4 and all the tags started working correctly.
Earlier XML:
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
After Making the Changes:
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd" version="2.4">
References: http://forum.springsource.org/archive/index.php/t-21093.html
Thursday, June 24, 2010
Local Datastore Dashboard for Google App Engine
Using the JSP Standard Tag Library (JSTL) in Spring Framework
We need jar files namely jstl.jar and standard.jar that are there in the Spring Framework, these files are to be copied to ‘/war/WEB-INF/lib' directory.
Also we have to copy this file from the Spring distribution ('spring-framework-2.5/dist/resources/spring-form.tld') to the 'springapp/war/WEB-INF/tld' directory that we also need to create. Next we must also add a <taglib/> entry to the 'web.xml' file.
<jsp-config>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/tld/spring-form.tld</taglib-location>
</taglib>
</jsp-config>
Tuesday, June 22, 2010
Using Spring Framework and Google App Engine for a Web Application.
Step by Step Procedure for the Hello World Application:
- Install the Google Plugin
- Create a new Web application and untick GWT (Google Web Toolkit)
- Download the latest Spring Release
- Add the Jars to the folder WEB-INF/lib
The following JAR files should be present in the folder:
Make the Following Changes to the web.xml file
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet><servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/a/*</url-pattern>
</servlet-mapping>
</web-app>
Create a file dispatcher-servler.xml in the WEB-INF Directory
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="ipathshala.controllers" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp" >
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
</beans>
HelloController.java
package ipathshala.controllers;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
@Controller
@RequestMapping("/hello")
public class HelloController {
private UserService userService = UserServiceFactory.getUserService();
@RequestMapping(method = RequestMethod.GET)
public String hello(HttpServletRequest request, ModelMap model)
{
String url = request.getRequestURI();
String message;
if(request.getUserPrincipal() != null)
{
message = new StringBuilder()
.append("Hello, ")
.append(request.getUserPrincipal().getName())
.append("! You can <a href=\"")
.append(userService.createLogoutURL(url))
.append("\">Sign Out</a>.").toString();
}else{
message = new StringBuilder()
.append("Please ")
.append("<a href=\"")
.append(userService.createLoginURL(url))
.append("\">Sign In</a>.").toString();
}
model.addAttribute("message", message);
return "hello/hello";
}
}
This line above @RequestMapping("/hello") maps all the requests /a/hello to this controller after being examined by the DispatcherServlet.
Create a Folder views under WEB-INF and two Sub folders hello and common.
hello/hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ include file="/WEB-INF/views/common/includes.jsp" %>
<p>${message}</p>
<%@ page session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
You should now be able to click “Debug” and run the application by visiting “localhost:8888/a/hello”.
References:
- Adent Lord’s Spring 3.0 GAE article: http://www.ardentlord.com/apps/blog/show/829881-spring-3-0-on-google-app-engine
- GAE Documentation: http://code.google.com/appengine/docs/java/gettingstarted/
- Spring 3.0 Documentation: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/
- Spring MVC 2.5 Tutorial: http://static.springsource.org/docs/Spring-MVC-step-by-step/
Friday, June 11, 2010
Session Management using Google User on Google App Engine
HttpSession s = request.getSession();
if (s.getAttribute("logged")==null){
s.setAttribute("from",request.getRequestURI());
response.sendRedirect("/login");
}
else {
s.setAttribute("from",request.getRequestURI());
%>Logout<%
//UserService userSer = (UserService)s.getAttribute("userSer");
}
Login.java
public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
UserService userSer=UserServiceFactory.getUserService();
User u=userSer.getCurrentUser();
HttpSession s=request.getSession();
String from=(String)s.getAttribute("from");
s.setAttribute("logged","yes");
s.setAttribute("userSer", userSer);
response.sendRedirect(userSer.createLoginURL(from));
}
}
Logout.java
public class Logout extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
HttpSession s = request.getSession();
String from=(String)s.getAttribute("from");
UserService us=(UserService)s.getAttribute("userSer");
s.invalidate();
response.sendRedirect(us.createLogoutURL("/index.html"));
}
}
Java Best Practices
http://java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp/
Monday, June 7, 2010
Edit Form Example using php
$query = mysql_query("SELECT * FROM table") or die(mysql_error());Read eco as echo
while ($row = mysql_fetch_assoc($query))
{
eco '';
}
Friday, June 4, 2010
Google App Engine and Apache Struts
http://code.google.com/p/struts2-gae/
http://royjin.wordpress.com/2010/05/25/create-google-app-engine-struts-java-application/
Tuesday, June 1, 2010
A better and Efficient Date input Calendar
http://www.dynamicdrive.com/dynamicindex7/jasoncalendar.htm
Monday, May 31, 2010
Deleting All entries in the Google Datastore locally
WEB-INF/appengine-generated/
directory. (It is not uploaded with your application.)http://code.google.com/intl/fr/appengine/docs/java/tools/devserver.html#Using_the_Datastore
To delete all entries, stop the server, delete this file and then Start the server again.
Friday, May 28, 2010
Searching the Student Objects stored in the Datastore by their Name
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
@SuppressWarnings("serial")
public class NameSearch extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String token = req.getParameter("search");
PersistenceManager pm=PMF.get().getPersistenceManager();
String query= "select from " + Student.class.getName();
List
ArrayList results = new ArrayList();
for (Student a:students)
{
// Checking whether token appears in the name whether lower or upper
if (a!=null && token!=null)
if(a.getName().toLowerCase().indexOf(token.toLowerCase()) != -1)
{
// Adding the reference to the object into the ArrayList
System.out.println(a.getName());
results.add(a);
}
}
req.setAttribute("result", results);
//Sending the results data via RequestDispatcher to your JSP Page.
RequestDispatcher r=req.getRequestDispatcher("SearchAS.jsp");
try
{
r.forward(req, resp);
} catch (ServletException e)
{
e.printStackTrace();
}
}
}
Thursday, May 27, 2010
Converting String to a date object
01.
package
org.kodejava.example.java.util;
02.
03.
import
java.text.DateFormat;
04.
import
java.text.SimpleDateFormat;
05.
import
java.text.ParseException;
06.
import
java.util.Date;
07.
08.
public
class
StringToDate
09.
{
10.
public
static
void
main(String[] args)
11.
{
12.
DateFormat df =
new
SimpleDateFormat(
"dd/MM/yyyy"
);
13.
14.
try
15.
{
16.
Date today = df.parse(
"20/12/2005"
);
17.
System.out.println(
"Today = "
+ df.format(today));
18.
}
catch
(ParseException e)
19.
{
20.
e.printStackTrace();
21.
}
22.
}
23.
}