Friday, January 19, 2018

Java File Transfer Using UDP Connection

What is UDP ?

User Datagram Protocol (UDP) is part of the Internet Protocol suite used by programs running on different computers on a network. UDP is used to send short messages called datagrams but overall, it is an unreliable, connectionless protocol. Basically a client will throw something to the server. And then, the server may or may not take the file, do something to that file and then may or may not send the file to some client. Unlike TCP connection, UDP doesn't need to establish connection between server and client before handling any kind of transfer.

What we will do :
  1. Create two new project: one for Server, another for Client
  2. Server will show client specific file items in a specific directory
  3. Client will then request the server to download a file from that directory by inserting the file name
  4. Server will then find the file in the directory, make a copy of it in another desirable directory
  5. Close socket
Client Part:


First, we create a public class named UDPClient under UDPClient project. The port number is where (Server) we will send our data. Scanner will be used to take user input for the filename.
A DatagramSocket is the sending or receiving point for a packet delivery service. Each packet sent or received on a DatagramSocket is individually addressed and routed. Multiple packets sent from one machine to another may be routed differently, and may arrive in any order. We created a DatagramSocket named ds.

DatagramPacket is used to implement a connectionless packet delivery service. We created two DatagramPacket named outdata (for sending packet to server), indata(for receiving packet from server).

byte array is required to get the data from the packet as bytes. So we also created them.
Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name. We will get localhost for this purpose.


Now we know that server doesn't know anything about client unlike TCPconnection where firstly connection in established between server and client. So to get our server know about the client, we will send something to server from our client program. I sent address and port number ( it's not necessary, but i did it anyways :P ).
outdata is the DatagramPacket and it takes 4 parameters as input. Serially they are:

#Byte array where the data is stored
#Length of the byte array
#Address of the client
#Port number of the client


Now server knows client's port and address. So from the server (we will discuss it later), some specific file names from specific directory is sent to the client as packet and client will now receive that packet in indata, the DatagramPacket we declared earlier. For receiving a packet only byte array name and length is required, in which we will store our packet. Then converting into string, we simply print out the file names in the screen for the client to choose which file should be downloaded.


String fname will contain the user input file name and we will send it to the server via packet like we did at the first time.




Now after the server get the file name for download, server will send that as a packet and client will receive the file and write it in client's desired path.
public class BufferedWriter extends Writer. Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. We used BufferedWriter to write out the file.
In java, FileOutputStream is a bytes stream class that's used to handle raw binary data. To write the data to file, you have to convert the data into bytes and save it to file.
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset . ... Each invocation of a write() method causes the encoding converter to be invoked on the given character(s).
Finally we will close the socket.
See the sample code below for UDPClient. Next we will  talk about the server part.

Server Part:




Same as client code before, we declared DatagramSocket, Server needs the address and the port number of the client that is trying to connect with it. So we will get the address and port from the client's file using getAddress() and getPort() method.



Now we have just received the packet here and printed the result. With this server got the address and port number of the client ( So, later server can send packet to the address of the client willingly ).




Now, server will send the file names from the directory. String dirname contains the path of the directory. Then we created a File named f1 to get the files from dirname and then created an array direct[] to contain the list of all the files from f1. Then with some coding we got our file names and send it to the client as packet.



Now, server will get the file name for downloading from the client. String fname holds the file name to be downloaded. Then we check whether the file exists in the direct[] or not. If we find matching, then we preserve the index of the file. Then, File copy = new File(direct[idx].getAbsolutePath()); it will contain the path of the desired file. Then with the help of BufferedReader, we will write the file in String s, and then convert it to bytes for packeting, then we will send it to the client. Finally client will then rewrite the file in it's desired directory which we have already seen above.
Here is the code for UDPServer. Thank you for reading patiently.

Now, let's see how to transfer any size of file here.

Simple Project (Data Structure)

আমরা এখন একটি student management টাইপ সিস্টেম নিয়ে কথা বলবো। প্রোজেক্ট টি খুব ই সিম্পল। যাদের নূন্যতম ডাটা স্ট্রাকচার নিয়ে জ্ঞান আছে, তারা আশা করি খুব সহজে বুঝতে পারবে কোড এ কি করা হয়েছে। যেসব ফাংশন ব্যবহার করা হয়েছে তার কিছু নিচে বলা হলঃ
কোড ঃ 


struct info ডাটা টাইপ এ আমার যেসব ইনফরমেশন দরকার তা ভ্যারিয়েবল আকারে লিখে রাখলাম, এটা আসলে কোডার এর উপর নির্ভর করে যে কিকি টাইপ ডাটা নিয়ে প্রোগ্রাম টা কাজ করবে। এটা একটা স্ট্রাকচার টাইপ ডাটা টাইপ।
struct node টাইপ এর একটা ডাটা টাইপ এ নাম এবং সিজিপিএ ( CGPA ) রেখে কাজ করবো যাতে পরবর্তীতে আমরা CGPA এর উপর ভিত্তি করে নাম গুলো সর্টেড আকারে আউটপুট দেখাতে পারি।
cmp( node p, node q ) একটা compare টাইপ ফাংশন যার কাজ হচ্ছে স্ট্রাকচার এর ভিতরের ডাটাগুলো compare করে ঐ অনুযায়ী আউটপুট দেখানো।
void option() আমি আমার প্রোগ্রামটি রান করার সময় user দের কি show করবো তার একটা সিম্পল ডেমো।
void show_data(item *root) নতুন নতুন ডাটা ইনসার্ট এর সময় আমি লিংক লিস্ট আকারে ইনসার্ট করেছি, তাই একেকটা নোড ( স্ট্রাকচার ) এর যাযা ভ্যারিয়েবল এ যাযা ডাটা ছিল তা একবারে দেখানোর জন্য এই ফাংশন।
void show_all() যতগুলি ডাটা ইনসার্ট করা হয়েছে তা সিরিয়ালি সব দেখানো।
void inserting() ডাটা ইনসার্ট করা।
void deleting() ডাটা ডিলিট করা।
void updating() ডাটা আপডেট করা।
void searching() নামের উপর ভিত্তি করে ডাটা সার্চ করা। ( লিংক লিস্ট এর ব্যাসিক সার্চিং )।
void show_cgpa() এখানে নাম এবং CGPA লিংক লিস্ট থেকে struct node টাইপ একটি অ্যাারে calc [ ] এর মধ্যে রেখে STL এর sort ( ) ফাংশন ব্যবহার করে আউটপুট অ্যাারেটা কনসোল এ দেখানো হয়েছে।

Matrix Exponentiation

Where there is recurrence , there is Matrix Expo.

We use matrix expo to calculate very large number, terms of the recurrence where even DP can't help us to pre-calculate the result.

You are all requested to read this blog  Matrix Expo  for understanding the matrix exponentiation.
Here is a sample code for generating Fibonacci numbers.



Note: For different types of recurrence , the base matrix will change accordingly. We have to generate this base matrix carefully , else every other things are pretty much same.

Sample Input/Output (I/O) for Programming contest (for beginners)

Programming contest বা Online OJ তে প্রব্লেম সাবমিট করার জন্য কিছু নিয়ম আছে। তার কিছু এখানে তুলে ধরা হলঃ

১। Main function int main() দিয়ে শুরু করা ভালো, void main() ব্যবহার করার চেয়ে। কোনো কোনো কম্পাইলার error দেয় void main() ব্যবহার করলে। কাজেই যেহেতু আমরা জানি না আমাদের কোড কোন কম্পাইলার এ চালানো হবে, কাজেই void main() ব্যবহার না করাই ভালো। প্রতি প্রোগ্রাম শেষে return 0; লিখা ভালো অভ্যাস।

২। প্রগ্রামিং কন্টেস্ট এ শুধু #include<conio.h> ব্যবহার করা যাবেনা। কাজেই clrscr(), getch() এসব ব্যবহার করা যাবে না।
C তে কোড করলে C99 এ যেসব header file সাপোর্ট করে সেসব ব্যবহার করা যাবে, কিন্তু যেহেতু #include স্ট্যান্ডার্ড header file না, তাই এটা লিখা যাবে না। String reverse এর ক্ষেত্রে কেউ যদি strrev ব্যবহার করে তাহলেও CE ( Compilation Error ) হবে,কারন এটাও C99 স্ট্যান্ডার্ড header file এর ফাংশন না। এরকম আরও অনেক কিছু আছে, এসব প্রোগ্রাম করতে করতে শিখা হবে। আর একটা কথা হচ্ছে কোন key word এর নাম ভুলেও variable নাম হিসাবে ব্যবহার করা যাবেনা, এতে প্রোগ্রাম run ই করবে না।

৩। কন্টেস্টের প্রশ্নে ইনপুট নেয়ার ক্ষেত্রে যদি কতবার ইনপুট নিতে হবে তা না বলা থাকে তাহলে scanf ("%d", &a) এর বদলে while(scanf("%d",&a)!=EOF ) ব্যবহার করতে হবে।
exp: problem: find a+b.
solve:
#include
int main () {
int a, b, sum;
while (scanf ("%d %d", &a, &b) != EOF) {
sum = a + b;
printf ("%d", sum);
printf ("\n");
}
return 0;
}

৪। new line এর ব্যাপারে সতর্ক থাকতে হবে।ঠিকমত লাইন প্রিন্ট করতে নয়া পারলে PE ( Presentation Error ) দিবে এবং প্রব্লেম এর আউটপুট এ ঠিক যেভাবে প্রিন্ট করতে বলা হবে একদম সেভাবেই প্রিন্ট করতে হবে, একটা দাড়ি, কমা ও কমবেশি দেয়া যাবেনা।

৫। প্রগ্রামিং কন্টেস্ট এর প্রশ্নে sample ইনপুট আউটপুট দেয়া থাকে। কিন্তু ওটা দেখেও অনেক সময় কিভাবে আউটপুট দিতে হবে বোঝা যায়না। যেমনঃ

Problem Description: I have a very simple problem for you.
Given two integers A and B, your job is to calculate the Sum of A + B.

Input: The first line of the input contains an integer T(1<=100). Then T lines follow each having two integers A & B.

Output: For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case.
The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces in the equation.
Output a blank line between two test cases.

Sample Input:
2
1 2
3 10

Sample Output:
Case 1:
1 + 2 = 3
Case 2:
3 + 10 = 13

( এখানে Case 1: দেয়ার পরে কোন space না দিয়ে একটা new line ( '\n' ) দিতে হবে। পরবর্তী লাইন এ 1 + 2 = 3 দিতে হবে অবশ্যই অর্থ্যাত ঠিকমত space দিতে হবে যেভাবে আউটপুট এ চাওয়া হয়েছে। প্রত্যেকটা আউটপুট এর পরে একটা করে new line দেয়া লাগবে। যদি বলা থাকে পরপর test case এর মাঝে blank line or new line দিতে হবে, তাহলে আরও একটা new line প্রিন্ট করতে হবে। আর সবার শেষ test case এর জন্য কোন blank line or extra new line প্রিন্ট করা যাবেনা )
কোড ঃ

#include
int main () {
int tc, t;
scanf ("%d", &t);
for (tc = 1; tc <= t; tc++){
int a, b;
scanf ("%d %d", &a, &b);
printf ("Case %d:\n%d + %d= %d\n", tc, a, b, (a + b));
if (tc < t) printf ("\n");   // Output a blank line between two test cases
}
return 0;
}


কিছু verdict সম্পর্কে লিখা হল। এগুলা UVA থেকে কপি পেস্ট করা :)


Accepted (AC) (and the CPU time & memory used): OK! Your program is correct!. Note that during true contest perhaps only 1 CPU minute will be allowed If your program spends a reasonable time, it may be ok, but this depends on the judge power in comparison with the true contest computers.

Presentation Error (PE): Your program outputs are correct but are not presented in the correct way. Check for spaces, justify, line feeds...

Accepted (P.E.): Same as above, but the Presentation Error is intended only for contests. The 24-hours judge takes it only as a warning. Don't worry a lot, since many of our problems have the output specification not very fine.

Wrong Answer (WA): Correct solution not reached for the inputs. The inputs and outputs that we use to test the programs are not public (it is recommendable to get accustomed to a true contest dynamic.

Crash - Run time Error (RTE): Your program failed during the execution (segmentation fault, floating point exception...). The exact cause is reported to the user.

Time Limit Exceeded (TLE): Your program tried to run during too much time; this error don't allows you to know if your program would reach the correct solution to the problem.

Memory Limit Exceeded (MLE): Your program tried to use more memory than the judge default settings. If you are sure that such problem needs more memory, please contact us.

Output Limit Exceeded (OLE): Your program tried to write too much information. This usually occurs if it goes into a infinite loop.

Restricted Function (RF): Your source program tried to use a not allowed function (such as fork(), fopen(), ...)

Compile Error (CE): The compiler (gcc/g++/gpc) could not compile your ANSI program. Of course, warning messages are not error messages. The compiler output messages are reported you by E-Mail.

Submission Error (SE): You don't specified correctly the @JUDGE_ID fields (a incorrect User ID, number of problem...).

Can't Be Judged (CJ): The judge hasn't test input and outputs for the selected problem. While choosing a problem be careful to ensure that the judge will be able to judge it!.

Access Denied (AD): Your Internet address is not allowed to submit problems. Maybe you have setup to accept programs only from your E-Mail address: edit and update your personal information in the Web. Otherwise, contact us.

Non Authenticated (NA): Your E-Mail is not authenticated or the submit tool did not sent authentication information. If you aren't a hacker, please contact us.

Out Of Contest Time (OC): this message can only appear during a contest, if a program is submitted out of contest time.

Delayed (DL): if the judge host is too busy, the execution of programs which spent too much resources (inside the allowed limits) is delayed by some seconds or minutes. Don't re-submit again your program (the judge would spent even more time before replying).

শেষ কথা ঃ
 কন্টেস্ট এ participate করলে অনেক কিছু শিখা হয়ে যাবে আপনাআপনি। প্রথম প্রথম অনেক ভুল হবে, কিন্তু আস্তে আস্তে সবকিছু ঠিক হয়ে যাবে। আমার একটা experience শেয়ার করি ঃ
আমি যখন ভার্সিটির ১.১ এ ছিলাম তখন আই ইউ টি ( IUT ) তে national ict fest এ আমার ২ বন্ধু নিয়ে কন্টেস্ট করতে যাই, পারতাম না কিছুই, খালি ভার্সিটি স্লট পাইছে, তাই গিয়েছিলাম -_- । যাহোক, ওইখানে গিয়ে ৫ ঘন্টা আমরা খালি সেলফি তুলছি, বাঁকা করে কী-বোর্ড এর পিক ও তুলছি,  ওইটা আবার অনেকদিন ফেইসবুক এর কভার পিক ও দিয়ে রাখছিলাম, যাহক, কন্টেস্ট এর টাইম এ একটা প্রব্লেম, যেইটা give away টাইপ প্রব্লেম ছিল ( give away : একদম বিগিনারদের পারার জন্য সবচেয়ে easy যেই প্রব্লেম দেয় ওইটা )। তো, ওইটা আমরা সুন্দর সল্ভ করলাম, সাবমিট দিলাম ,verdict আসলো RTE -_- । এরপরে আমরা আরও অনেকভাবে কোড করলাম, সবকিছু ওকে, কিন্তু সাবমিট দিলেই RTE। আসলে ভুল টা ছিল যে array এর সাইজ ১০^৭ পর্যন্ত হতে পারবে, আমরা main () ফাংশন এর ভিতরে ১০^৭ সাইজ এর অ্যাারে ডিক্লার করেছিলাম, কিন্তু এটা যদি গ্লোবালি ডিক্লার করতাম, তাইলেই AC পাইতো :( । তখন ও ক্লাস এ লোকাল গ্লোবাল ভ্যারিয়েবল ডিক্লার পড়ায় নাই,তাই ব্যাপারটা আসলে জানতাম না। পরে কন্টেস্ট শেষে শাকিল ভাইয়ার কাছে শুনার পরে নিজেকে বড় মাপের ছাগল মনে হইতেছিল। সবচেয়ে মজার ব্যাপার হল, আমরা প্রব্লেমটা সাবমিট দিছিলাম মোট ৩৯ বার এবং প্রত্যেকবার verdict ছিল RTE। আর সন্ধ্যায় পুরষ্কার দেবার সময় ( may be কায়কোবাদ স্যার ছিলেন, ঠিক মনে নাই ) আমাদের কথা উনি বলছিলেন যে "একটা টীম A নম্বর প্রব্লেমটা ৩৯ বার সাবমিট দিছে, তারা একদম শেষ পর্যন্ত সাবমিট দিয়ে গেছে, কন্টেস্ট এর মাঝে তাই হাল ছাড়তে নেই।" ( আমি তো লজ্জায় শক্ত হয়ে বসে ছিলাম না জানি টীম এর নাম বলেন , যাহোক উনি ভালো মানুষ, নাম বলেন নাই, আরো অনেক inspirational কথাবার্তা বলেছেন, ওইগুলা এখন আর মনে নাই :( )
কাজেই, আজকে ভুল করা মানে এই না যে আগামীতেও ভুল করবা, আমি ফাঁকিবাজ মানুষ, তাই ঠিকমত কন্টেস্ট continue করিনাই, কিন্তু তোমরা যারা নতুন, তারা আশা করি আমার মত ভুল করবা না :) ।

Best of luck and happy programming <3.

Cool Magic Square Trick

Today I will talk about a very exciting and cool trick regarding magic square. Once you learn this trick, everybody will definitely acknowledge you as a great math magician ;)
Let's get started then,

First choose a participant. Ask him/her to select a 2 digit number between 22 and 99. Suppose he choses the number 50. Now I will construct a 4x4 magic square with different unique numbers and make him/her believe that I'm the greatest math magician :D
I will now take a pen and paper, draw a 4x4 grid and fill up the grid with some random numbers like this:

Well see, every number is random and unique. If you calculate the sum of every column or every row, even the diagonals, you will see the sum is 50 ! And that is your chosen number. If you take the sum of the numbers of the 4 corners, it will be 50 ( 30+7+4+9 = 50 ).
if you take any 4 square inside the grid, the summation of numbers there will be 50. Don't believe? Check yourself :P

Ok, but the trick doesn't end here actually. If you take any 9 square (3x3) and take the summation of 4 corners for that square, the sum will also be 50 !

Check the red colored tiles and see the magic yourself. Cool , right? And I can do this all
day with different numbers ;)
And even this is also possible:

The red and blue tiles sum is also 50! Well there are 28 different combinations where we can get the desired value.
Okay, let's reveal the trick behind the scene. First think of your magic square like this in your mind:

These four blocks are our magic blocks that will determine the outcome. Remember this by heart and randomly place numbers to other 12 blocks to confuse your partner. But you aren't doing it randomly, are you? ;) The greater the magician, the innocent he looks, so you have to be really smart and innocent to pull this off :P
Well, just fill the 12 blocks like this each and everytime:

You can remember this through some practice of course. Well it is essential for every magician to practice, so it's alright for you to do so. Look we didn't fill up the A, B, C, D blocks. We only placed the numbers from 1 to 12 here. And remember, everytime these 12 numbers have to be placed like this exactly. Now we will fill up the 4 magic blocks with four different magic numbers. How we will generate these magic numbers? Here is the answer:

A : Subtract 20 from the given number. The number given was 50. So I get 50 - 20 = 30 for the block A.
B : 
Subtract 1 from A, so we get 30 - 1 = 29.
C : Add 2 with A, so we get 30 + 2 = 32 for C.
D : Add 1 with A, so we get 30 + 1 = 31 for D.

Thank you for reading this. Hope you enjoyed all.