Yawn, teach me how to write my first Java program, asshat!

How does one write their first java program?

We are going to make our computer say,

Hello Human, I am your servent..

I’ll do as you please!

I bow down to you master. 

But (I like big butts and I cannot lie, sorry I can’t stop singing that song).. but before that, we need to do some shit called “setup” for writing our first java program.

Your first Java program is going to look lengthy and wordy compared to other programming languages such as Python. So, I say fuck setting up your computer for now. Heck, Java’s “hello world” scares off people even if it is dumb easy just due to sheer length. Now, if I made you download a bazillion files and made you follow 10 different step to set up things, you are going to run the fuck away. 

My intention is to show you, Java is a fucking easy language. It’s not C++ which you’re only qualified to write if you’re a nerd with no sex life (ba dum diss). So, I suggest you go over here. 

An online coding environment will save us from so many steps that will come between you and your code. Fuck that for now. 

You talk a lot, show me the code 

Okay. Just in a bit..

See.. a java program has a structure to it that looks like,

Screen Shot 2018 08 06 at 11.41.14 PM - Yawn, teach me how to write my first Java program, asshat!

So, a java program is a bunch of thingies called classes that have code inside. That’s all to it for now. 

How does one define a class?

All you need to do is use a class keyword. 

class myClass{

//code

}

Okay, how does one write the program you mentioned above?

public class IAmTheBoss {
public static void main(String args[]) {
System.out.println("Hello Human, I am your servent..");
System.out.println("I'll do as you please!");
System.out.println("I bow down to you master.");
}
}

In JDoodle it’ll look like this if you hit the execute button. 

Screen Shot 2018 08 06 at 11.49.40 PM - Yawn, teach me how to write my first Java program, asshat!

Explain the code, please

I knew you’d ask. Let’s break down the code. 

Iteration 1

public class IamTheBoss{

}

This is our class definition. The public here is something called access modifier. Ignore what that means for now. Just think of it like our class can be accessed from anywhere within the same folder if it’s set to public.

Iteration 2

public class IAmTheBoss {
public static void main(String args[]) {

} // main ends here
} //class ends here

Java programs require something called the “main method” to run. The class that has this main method is called the main class. You need one main class in your java program.

Now methods are synonymous with functions. But if you don’t know what “function” means don’t sweat it. We’ll have a whole article on that. 

public static void main(String args[])  is a way to define the main method in java. Now, each of the words there such as static, void, String etc. have certain meanings which we’ll explore in some other article. For now, just understand that it’s needed to define the main method thingy. You don’t need to rote memorize it either. If you type main and press tab on Jdoodle, it’ll generate the code for you. 

Iteration 3

public class IAmTheBoss {
public static void main(String args[]) {
System.out.println("Hello Human, I am your servent..");
System.out.println("I'll do as you please!");
System.out.println("I bow down to you master.");
}
}

System.out.println displays the output on the screen. If you type println and press tab on Jdoodle then it’ll generate the whole thing for you. println means the thing you want to display is going to be printed on a new line. So, you could do System.out.print but everything would be on the same line. 

There’s a reason behind x.y.z kinda shit in Java. It means z exists inside y which exists inside x. So, System.out.print thingy means that the “print” function resides inside “out” which further resides inside the “system”. 

So, what else can I do?

I suggest you play around with Jdoodle. And see what works and what does not. And subscribe/bookmark to this blog to read more articles on Java.

What the hell is Java programming language?

What is Java? Isn’t it coffee or something?

The Java(TM) is programming language which is a bit different from coffee java as you might have guessed. 

If you search for “Java” in Wikipedia.org, it’ll answer the following

Java is an island of Indonesia. At about 138,800 square kilometers, the island is comparable in size to England.

And if you click see Java (programming language), it’ll return

Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented. It is intended to let application developers “write once, run anywhere” (WORA) meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.

The first definition seems like it was written in English. It’s easy to understand. The second one seems like it was written by someone whose third or fourth language is English. It seems like it was written by someone who’s been a professional Java programmer for a while and has lost the sense of how new students find it hard to decipher the technical jargon.

But it’s still more readable than what’s in the official docs at least.  You probably skimmed through it  and are like “Okay.. so it’s a programming language and you can write it once and run it anywhere whatever that means.” And some words such as “concurrent” flew right over your head. 

If you have never programmed before. Or you just had some introductory QBasic and C shit. A lot of words in there don’t fucking make sense. 

What in the hell is a general-purpose programming language? Is it another way of saying that it’s a mainstream programming language and not for hipsters? 

What the hell is object oriented? Does it mean that Java is sexist and treats women as objects?

What is the actual hell is recompilation now? And this recompilation thing, is it that bad? Why is it bad? Maybe it’s good. Who the fuck knows?

 

Let’s define Java the way we’d like to

All those jargony words. They mean something in their own context. Those are some fancy features of the language which we don’t need to understand right now so fuck it. 

I’d say .. 

Java helps humans write instructions for machines such your laptop, mobile phone etc. so that we can make the machine do whatever the hell we want to. Like every other programming language in the observable universe.  

Sure, it has its own way of doing things with those fancy sounding words. And this “my way or the highway” attitude of Java can be a gift or a curse depending on the situation. It can be a gift because you don’t have to think much about things yourself. The language will dictate how you write and organize your code. It can be a curse when you feel like thinking outside of Java’s opinionated box. 

 

Enough Talk. How do I make this Java thingy make my computer do something for me? 

Well, we’ll look into that in the next post. Be patient. We’ll use and abuse this so-called programming language together to make our computers do shit for us. Until then chug some coffee and call Oracle service center and ask them if chugging a mug of coffee is the proper way to download Java. 

 

 

 

ranji can't

How to write a south Indian movie

Note: For the sake of simplicity, indie south Indian movies and the ones that don’t make it to Hindi dub or a Bollywood remake are excluded because they don’t fit this narrative. Heck, even some Bollywood movies have a really good plot and execution. But when a typical non-south Indian person says that they like south Indian movies, they usually are talking about the worst of those to exist in the history of mankind.  Those are movies we are talking about because “the amount of bad movie > amount of good movies” always. 

1. Superpowers 

captain america - How to write a south Indian movie

To write a south Indian movie, it is very important that you give your lead actor some sort of superpower. It’s usually something similar to that of Captain America or black panther but without a shield or costume because we are pretending that someone who can beat about 100 people up with only a few scratches on their body and someone who can twist a fucking iron rod is a normal human being. It may be executed like that because south Indian moms need to advertise milk to their children. “Drinka this milka, man. stronga bones.” P.S I picked up that “man” from my Banglore days. Why tf do you folks use the word “man” so much? Smh. 

 

2. Gravity is a conspiracy invented by Newton 

 gravity - How to write a south Indian movie

As an aspiring south Indian movie writer or director, you need to be aware of the fact that gravity is indeed a conspiracy. It does not exist and it should not exist in real life. Laws of physics don’t make sense and they should be discarded. Old American cartoon got that one right.  

 

3. Fair sleazy female lead 

 

 

 

fair - How to write a south Indian movie

If you can manage it, write an actress that does not look south Indian at all. If she indeed happens to be south Indian, make sure she has a fair skin. Kamal Hasan’s daughter works. You can go darker but not more than light brown. Black is a no-no. It’s not racism. They embrace any caste, culture, creed, ethnicity, religion as long as the actress is fair.

P.S: Make sure that actresses don’t actually have to act. They only serve as a love interest of the male lead. They can indeed be great actresses on their own merit but fuck that. You hire them to look pretty. And that’s what you want from them. It’s better if they’re the ones chasing the male lead. The male lead’s got important things to do, like save the world. He doesn’t have time for chicks or whatsoever. 

 

4. anti-heroes because heroes are super boring 

antihero - How to write a south Indian movie

Urban dictionary defines it as “Someone who is supposed to be the hero but has a lack of hero qualities, which would mean he or she isn’t pretty, brave or strong or whatsoever a hero should be. 
The Antihero is someone with some of the qualities of a villain, up to and including brutality, cynicism, and ruthlessness, but with the soul or motivations of a more conventional hero.”  
 
In simple words “Someone who is too good to be a villain and too bad to be a normal hero.”

Typical heroes are boring. Make them shit who people actually root for because most people themselves are shit. So, people get validated for their typical assholery. 

 

5. Good triumphs evil

good triumphs evil - How to write a south Indian movie

Learn from Disney. Take our heroes from minor obstructions to their destination. Nothing they can’t solve with their superpowers but there should be a conflict. Conflict is a working formula for every story out there. Just create some minor nuisances for our superhero and help him overcome it and remember good always wins. We don’t have time for bold plots and tragedies. Fuck that. All that matters is that the fools get entertained.

 

6. Plagiarism

Screen Shot 2018 04 20 at 8.57.58 PM - How to write a south Indian movie

Bollywood doesn’t know how to copy. They just present a dumbed down version of a Hollywood movie or they just make an official remake nowadays and still get shit for copying. Even from the south Indian industry. The Tamil movie Gajhini was “inspired” by Christopher Nolan’s Memento. Mahesh Babu’s “Nenokkadine” is basically a south Indian-fied version of Liam Neeson’s “Unknown”. S. J. Surya’s character in “Spyder” is basically south Indian take on the Batman’s Joker. So you get the gist. You take some Hollywood characters or the plot and you south Indian-ify it with  the above-mentioned steps. 

 

7. Character actors 

Screen Shot 2018 04 20 at 9.00.41 PM - How to write a south Indian movie

character actor or character actress is a supporting actor who plays unusual, interesting, or eccentric characters. The term often is contrasted with that of the leading actor.

Character actors are absolutely crucial so that the dumb audience feel like at least the laughter was worth the ticket. You can fuck the plot. Always write a role for Brahamanandam. In case he’s booked, any other character actor can fill in.  

Note: I do know and understand that there are multiple movie industries in south India. Tamil, Telegu, Kannada etc. But you all fucking look the same to me. And I hate you all because I once happened to go Banglore for my further studies. Shit was so traditional that even Kathmandu feels like abroad studies to me. So, fuck ya’ll. 

 

 

 

 

 

Java AWT viva questions with answers

  1. What is AWT?
    Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application in java. It contains numerous classes and methods that allow you to create windows and simple controls. It was Java’s first GUI framework, and it has been part of Java since version 1.0.

  2. Where are AWT classes contained? / Which package contains AWT classes? 
    The AWT classes are contained in the java.awt package. It is one of Java’s largest packages.

  3. What is a component?
    By definition, the subclass of a java.awt.Component class is known as a component. A component can be a Button or TextField etc. Component class lies at the top of AWT hierarchy. Component class is an abstract class that encapsulates all of the attributes of a visual component.

  4. What is an abstract class ?
    A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).

  5. Are menus subclass of a component?
    No. Except for menus, all user interface elements that are displayed on the screen and that interact with the user are subclasses of Component.

  6. What is a component?
    By definition, the subclass of a java.awt.Container class is known as a container. A container can be a Frame or Applet or Dialog box etc. A container holds the components. If a button is to be displayed to the user, it must be added to a container.

  7. What is a container class? 
    The Container class is a subclass of Component.

  8. What is the super class of all containers?
     java.awt.Container.

  9. What is a window?
    The window is the container that has no borders and menu bars. You must use frame, dialog or another window for creating a window. Generally, you won’t create Window objects directly. Instead, you will use a subclass of Window called Frame.

  10. What is a panel? 
    The Panel class is a concrete subclass of Container. Like window panel also does not contain a title bar, menu bar, or border. 

    To have a greater flexibility on the arrangement of components, panels are extensively used with layout managers. Components are added to panel and panel, in turn, can be added to a container. That is, a panel can work like a container and a component. As container, components can be added to it and as a component, panel can be added to a frame or applet.

  11. What are subclasses of the component?
    Subclasses of Container include Frame, Panel, and Applet which is a subclass of Panel.

  12.  Among the standard classes in Java are Container and Component. In order to create a GUI, the programmer uses subclasses of these two classes. What are some examples of subclasses of Container and Component? What is the essential difference between Containers and Components?

    Java’s Component class represents visual elements of a Graphical User Interface. Its subclasses include Button, Checkbox, TextField, Choice, and Canvas. The Container class is another subclass of Component. A Container is a component that can contain other components (including other containers). This is the essential difference between containers and other types of component. Subclasses of Container include Frame, Panel, and Applet.

  13. How to add other components to a panel?
    Other components can be added to a Panel object by its  

    • add( ) method (inherited from Container).

  14. How to position components in a Panel? 
    setLocation( ), setBounds() methods defined by Components class can be used to position components. 

  15. How to resize components?
    setLocation( ) and setPreferredSize( ) methods. 

  16. What is a Frame? 
    Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. The Frame is the container that contains title bar and can have menu bars. It can have other components like button, textfield etc.

  17. Mention any 4 methods of component class? 
    public void add(Component c) -> inserts a component on this component.
    public void setSize(int width,int height) -> sets the size (width and height) of the component.
    public void setLayout(LayoutManager m) -> defines the layout manager for the component.
    public void setVisible(boolean status) -> changes the visibility of the component, by default false.

  18.  What are the two ways to create a frame in awt? 
    By extending Frame class (inheritance)
    By creating the object of Frame class (association) 

  19. What are the constructors of Frame? 
    Frame( ) throws HeadlessException  -> creates a standard window that does not contain a title.
    Frame(String title) throws HeadlessException -> creates a window with the title specified by title.

  20. Constructors of setSize() ?
    • void setSize(int newWidth, int newHeight)
    • void setSize(Dimension newSize)

      The new size of the window is specified by newWidth and newHeight, or by the width and height fields of the Dimension object passed in newSize. The dimensions are specified in terms of pixels.

  21. How to obtain a current size of a window? 
    The getSize( ) method is used to obtain the current size of a window.

Explain different types of Operating Systems

What is an Operating System? Explain different types of Operating Systems. [PU Fall 2017, Spring 2014]

An operating system (OS) is a system software that manages computer hardware and software resources and provides common services for computer programs.

System software is computer software designed to provide a platform to other software. Examples of system software include operating systems, computational science software, game engines, industrial automation, and software as a service applications.

In contrast to system software, software that allows users to do things like create text documents, play games, listen to music, or surf the web is called application software.

Types of OS: 

Sequential, Batch, Multiprogramming (multitasking), Multiprocessing (multiprocessor), Time Sharing, Real Time, Distributed, Embedded, Kernel (syllabus)

  1. Sequential OS: Sequential access compared to random access. In computer science, sequential access means that a group of elements (such as data in a memory array or a disk file or on magnetic tape data storage) is accessed in a predetermined, ordered sequence. Sequential access is sometimes the only way of accessing the data, for example if it is on a tape. It may also be the access method of choice, for example if all that is wanted is to process a sequence of data elements in order.
  2. Batch OS:  The users of a batch operating system do not interact with the computer directly. Each user prepares his job on an off-line device like punch cards and submits it to the computer operator. To speed up processing, jobs with similar needs are batched together and run as a group. The programmers leave their programs with the operator and the operator then sorts the programs with similar requirements into batches.

    The problems with Batch Systems are as follows −

    1. Lack of interaction between the user and the job.
    2. CPU is often idle, because the speed of the mechanical I/O devices is slower than the CPU.
    3. Difficult to provide the desired priority.
  3. Multiprogramming OS: 

    To overcome the problem of underutilization of CPU and main memory, the multiprogramming was introduced. The multiprogramming is interleaved execution of multiple jobs by the same computer. In a multiprogramming system, when one program is waiting for I/O transfer; there is another program ready to utilize the CPU. So it is possible for several jobs to share the time of the CPU. But it is important to note that multiprogramming is not defined to be the execution of jobs at the same instance of time. Rather it does mean that there are a number of jobs available to the CPU (placed in main memory) and a portion of one is executed then a segment of another and so on.
    A program in execution is called a “Process”, “Job” or a “Task”. The concurrent execution of programs improves the utilization of system resources and enhances the system throughput as compared to batch and serial processing. In this system, when a process requests some I/O to allocate; meanwhile the CPU time is assigned to another ready process. So, here when a process is switched to an I/O operation, the CPU is not set idle. Read More

  4.  Multiprocessor Operating System: 

    It refers to the use of two or more central processing units (CPU) within a single computer system. These multiple CPUs are in a close communication sharing the computer bus, memory and other peripheral devices. These systems are referred as tightly coupled systems. These types of systems are used when very high speed is required to process a large volume of data. These systems are generally used in environment like satellite control, weather forecasting etc. 
    Multiprocessing system is based on the symmetric multiprocessing model, in which each processor runs an identical copy of operating system and these copies communicate with each other. In this system processor is assigned a specific task. A master processor controls the system. This scheme defines a master-slave relationship. These systems can save money in compare to single processor systems because the processors can share peripherals, power supplies and other devices. The main advantage of multiprocessor system is to get more work done in a shorter period of time. Moreover, multiprocessor systems prove more reliable in the situations of failure of one processor. In this situation, the system with multiprocessor will not halt the system; it will only slow it down. 
    Read More

  5. Time Sharing Operating System: 

    Time-sharing is a technique which enables many people, located at various terminals, to use a particular computer system at the same time. Time-sharing or multitasking is a logical extension of multiprogramming. Processor’s time which is shared among multiple users simultaneously is termed as time-sharing.

    The main difference between Multiprogrammed Batch Systems and Time-Sharing Systems is that in case of Multiprogrammed batch systems, the objective is to maximize processor use, whereas in Time-Sharing Systems, the objective is to minimize response time.

    Multiple jobs are executed by the CPU by switching between them, but the switches occur so frequently. Thus, the user can receive an immediate response. For example, in a transaction processing, the processor executes each user program in a short burst or quantum of computation. That is, if nusers are present, then each user can get a time quantum. When the user submits the command, the response time is in few seconds at most.

    The operating system uses CPU scheduling and multiprogramming to provide each user with a small portion of a time. Computer systems that were designed primarily as batch systems have been modified to time-sharing systems.

    Advantages of Timesharing operating systems are as follows −

    • Provides the advantage of quick response.
    • Avoids duplication of software.
    • Reduces CPU idle time.

    Disadvantages of Time-sharing operating systems are as follows −

    • Problem of reliability.
    • Question of security and integrity of user programs and data.
    • Problem of data communication.
  6. Real Time Operating System: 

    A real-time system is defined as a data processing system in which the time interval required to process and respond to inputs is so small that it controls the environment. The time taken by the system to respond to an input and display of required updated information is termed as the response time. So in this method, the response time is very less as compared to online processing.

    Real-time systems are used when there are rigid time requirements on the operation of a processor or the flow of data and real-time systems can be used as a control device in a dedicated application. A real-time operating system must have well-defined, fixed time constraints, otherwise the system will fail. For example, Scientific experiments, medical imaging systems, industrial control systems, weapon systems, robots, air traffic control systems, etc. Read More

  7. Distributed OS: 

    Distributed systems use multiple central processors to serve multiple real-time applications and multiple users. Data processing jobs are distributed among the processors accordingly.

    The processors communicate with one another through various communication lines (such as high-speed buses or telephone lines). These are referred as loosely coupled systems or distributed systems. Processors in a distributed system may vary in size and function. These processors are referred as sites, nodes, computers, and so on.

    The advantages of distributed systems are as follows −

    • With resource sharing facility, a user at one site may be able to use the resources available at another.
    • Speedup the exchange of data with one another via electronic mail.
    • If one site fails in a distributed system, the remaining sites can potentially continue operating.
    • Better service to the customers.
    • Reduction of the load on the host computer.
    • Reduction of delays in data processing.
  8. Embedded OS: An embedded operating system is an operating system for embedded computer systems. This type of operating system is typically designed to be resource-efficient and reliable. Resource efficiency comes at the cost of losing some functionality or granularity that larger computer operating systems provide, including functions which may not be used by the specialized applications they run. Depending on the method used for multitasking, this type of OS is frequently considered to be a real-time operating system. Read More
  9. Kernel:  A kernel is the core component of an operating system. Using interprocess communication and system calls, it acts as a bridge between applications and the data processing performed at the hardware level.

    When an operating system is loaded into memory, the kernel loads first and remains in memory until the operating system is shut down again. The kernel is responsible for low-level tasks such as disk management, task management, and memory management. Read More

Poonam Pandey hot wallpaper3 - Top 7 reasons why Pandeys are evil little monsters

Top 7 reasons why Pandeys are evil little monsters

We all have that one Pandey friend. We are unsuspecting of them. We are naive and we don’t understand they get manufactured by factories funded by the devil himself or herself .. in case devil is a female. And to all the feminists, apologies in advance, my male privilege made me write him before her. I’m ashamed. I deserve harsh social justice punishment. BDSM style. 

K… enough chit chat. Here’s your list..

1. Chulbul Pandey

Chulbul Pandey Salman Khan police inspector Dabangg - Top 7 reasons why Pandeys are evil little monsters

Well, this guy almost got his own brother and father killed despite his “I’m homosexual so I need to act extra manly” body language. He probably killed his wife’s father too to be able to marry her. Think about it. He wouldn’t let her marry someone because there would be no one to feed him and her father conveniently dies like some kind of divine intervention. And our Pandey conveniently marries her like nothing happened?

He is corrupt. It is obvious. He talks funny but don’t you fall his absolutely charming personality. “Hum tumpe itne ched kardenge” is not a comedic dialogue. It’s him trying to establish dominance and giving us a glimpse of how evil he is. I say he is eviler than Kyser Soze on Kevin Spacey movie “The Usual Suspects”.

2. They don’t have a first name

What’s their first name anyway? No one knows. It’s a fucking 8th wonder of this swine infested world. They can hide something as basic as their own names. Think about it? What else they must be hiding from you. What deep-seated evil plans they must be hatching? They’re preying on your vulnerability. Be warned. 

3. They’re cunning

Well, this one must be obvious. On the surface these Pandeys look cute and fuzzy but if you look deeper you realize how cunning they are. And all of them. It’s like they were manufactured from some “Pandey manufactuing” factory. 

4. Poonam Pandey

Indian Express’ “I created controversies to get noticed in Bollywood”. News18’s “I used to controversies to gain limelight.” There are tons of articles and her own interviews that shows that the level of her shallowness. You might make fun of her semi-nude social media posts but it’s keeping her in limelight. Think about it? That’s pretty darn evil to me. Not as evil as one of my Pandey frenemy making his sole mission to date every Parajuli woman ever to exist but still. 

5. They are Brahmins?

Brahimins are sexist, racist, bigoted. Case closed. 

6. They’re like cats

They come to you when they need you. They purr and make you want to feed you and voila they disappear from the face of the earth. 

7. They feed on your soul

The Exorcist is every Pandey’s favorite movie. But.. the thing is they’re hinting you that they’re feeding on your soul. And they’re letting you know that they can get away with it like Mark Zukerberg can get away from being one of the lizard people. It might also be a test to see how dumb some non Pandeys can get. But those who non Pandeys who are smart enough are also not safe from thier wrath. 

What the fuck is a process?

Well, what the fuck is a program and how the fuck is it related to a process?

Before we go into what the fuck a process is, let’s try to understand what the fuck a program is first. 

A set of instructions. 

Well now, that wasn’t very clear, was it? Let’s try to kinda redefine it.. I say “A program is a set of instructions that a computer can follow to achieve a goal.” But it’s still a little jargony, isn’t it? Think of it as a recipe, a handbook, or a manual.. a set of instructions… now it clicks, doesn’t it? It’s basically a programmer’s written note to the computer that says.. do this.. do this.. and do that after that… and finally do that and that’s how you get the citizenship of Saudi Arabia.

But here’s the catch. A program is merely a set of instructions. You do have to run it, to reach the goal. And that’s where process comes in but more on that later. Think of a program as like a book named “How to get inside a girl’s pants in 10 steps” and process as the action you take based on the book to get inside her pants. 

A process is a program in execution.

For example, when you write a program in Java and compile it, the JVM creates a bytecode thingy. The original code and the bytecode thingy, both are programs. When you actually run the binary code, it becomes a process.

A process is an ‘active’ entity as opposed to a program which is considered to be a ‘passive’ entity. A single program can create many processes when it’s run multiple times, for example when we open a .exe or binary file multiple times, many instances begin (many processes are created).

Process models (Uniprogramming, Multiprogramming, Multiprocessing)

Uniprogramming => Only one process at a time.

Screen Shot 2018 03 31 at 7.46.32 AM - What the fuck is a process?

Multiprogramming => Multiple processes at a time i.e A computer running more than one program at a time (like running MS Word and Google Chrome simultaneously to be able to copy Wikipedia for the group project report).

Screen Shot 2018 03 31 at 7.51.11 AM - What the fuck is a process?

Multiprocessing => System with multiple processors i.e A computer using more than one CPU at a time.

Screen Shot 2018 03 31 at 7.53.19 AM - What the fuck is a process?

 Multitasking – Tasks sharing a common resource (like a single CPU).

As the name itself suggests, multitasking refers to the execution of multiple tasks (say processes, programs, threads etc.) at a time. But.. But.. hold on a minute…

Isn’t it same as multiprogramming? How does it differ from multiprogramming?

Multitasking is a logical extension of multiprogramming. The major way in which multitasking differs from multiprogramming is that multiprogramming works on the concept of context switching whereas multitasking is solely based on time-sharing systems. So, basically, a multitasking system basically divides CPU’s time to be able to do what it does.

K.. I’m bored now. In the next article… we’ll probably look at the states of process and process control block which means how the process looks inside a memory. But for now… hosta la vista,  amigos. 

 

What the fuck is Peterson’s algorithm? 

What the fuck is Peterson’s algorithm? 

As we all know when two or more processes need to share a single resource, conflict occurs. Remember fighting with your mom for that TV remote back in the days when you watched TV. You still do? ..hah.. what a loser. So, moving on, to solve this conflict we kinda need to use a thing called mutual exclusion which basically means TV serials are your mom’s time and you are not allowed near that TV when she’s watching.

Peterson’s algorithm is a mutual exclusion algorithm that allows two or more processes to share a single-use resource without conflict. 

The algorithm is named after Gary L. Peterson who literally made the algorithm. His original work only focused on two processes (i.e you and your mom because I needed an opportunity to say your mom). But, it can be generalized for more than two processes. So, the algorithm kinda works for two or more than two processes. So, that means you dad and your mom’s boyfriend can join in too if they wish to. 

Note: Dekker also tried to solve the issue between you and your mom but Peterson’s solution is simpler because he knows that you’re a dumbfuck. 

So, how does this algorithm thingy work? 

Here’s a little rote memorization trick for you because you’re too dumb to understand anything. The algorithm used two variables flag and turn. A flag[0]=true indicates that Po wants to enter the critical section. Entrance to critical section is given to P0 if P1 does not want to enter its critical section or P1 has given priority to Po by setting turn to 0

P0:      flag[0] = true;
P0_gate: turn = 1;
         while (flag[1] == true && turn == 1)
         {
             // busy wait
         }
         // critical section
         ...
         // end of critical section
         flag[0] = false;
P1:      flag[1] = true;
P1_gate: turn = 0;
         while (flag[0] == true && turn == 0)
         {
             // busy wait
         }
         // critical section
         ...
         // end of critical section
         flag[1] = false;

P1 and P0 can never be in the critical section at the same time. If P0 is in its critical section, then flag[0] is true. In addition, either flag[1] is false ( meaning P1 has left its critical section), or turn is 0 (meaning P1 is just now trying to enter the critical section but is waiting, or P1 is at label P1_gate (trying to enter its critical section, after setting flag[1] to true  but before setting turn to 0 and busy waiting). So if both processes are in their critical sections then we conclude that the state must satisfy flag[0] and flag[1]  and turn = 0 and turn = 1. No state can satisfy both turn = 0 and turn = 1, so there can be no state where both processes are in their critical sections. 

 

 

Java Servlet Example 3

3. Develop a servlet that displays the number of visits on the servlet. Also display the client’s hostname and IP address, as shown in Figure. Use an instance variable to store count. When the servlet is created for the first time, the count is 0. count is incremented every time the servlet’s doGet method is invoked. When the Web server stops, the count is lost.

getRemoteHost()

getRemoteAddr()

Screen Shot 2018 03 09 at 3.56.54 PM - Java Servlet Example 3

  • VisitorServlet.java (put it in the “src” folder)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/VisitorServlet") public class GreetingServlet extends HttpServlet {
static int count = 0;     
protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
response.setContentType("text/html");         
PrintWriter out = response.getWriter();         
// client's IP address         
String remoteAddr = request.getRemoteAddr();         
// client's hostname         
String remoteHost = request.getRemoteHost();         
if (count == 0){             
out.print("<h3>");             
out.print("Welcome to the fist Time </h3>");             
count++;         
} else {            
 out.print("<h3>You have visited " + count + " times");         
    count++;             
out.print("</h3>");      
   }         
out.println("Host name: ");         
out.print(remoteAddr);       
  out.println("<br>");         
out.println("IP address:");         
out.print(remoteHost);        
 out.close();    
 } }
  • index.jsp(put it in the “web” folder) 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
 <html>
   <head>
     <title></title>
   </head>
   <body> </body>
 </html>
  • web.xml(put it in the “WEB-INF” folder which resides inside the “web”.) 

      Note: This step is not mandatory. You may choose not to do it. And the program will still run. 

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, 
Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> 
<web-app> 
    <display-name>myweb</display-name> 
    <!-- Servlet Definitions  --> 
   <servlet> 
      <servlet-name>VisitorServlet</servlet-name> 
      <servlet-class>VisitorServlet</servlet-class>  
  </servlet> 
<!--   Servlet Mappings   --> 
   <servlet-mapping> 
      <servlet-name>VisitorServlet</servlet-name> 
       <url-pattern>/VisitorServlet</url-pattern>  
  </servlet-mapping> 
</web-app>  

Note: To run this program, type inlocalhost:8080/VisitorServlet the browser URL. Click here if you don’t know how to set up a servlet project in NetBeans.

 

 

Java Servlet Example 2

HTML Form

Screen Shot 2018 03 09 at 4.00.55 PM - Java Servlet Example 2 Screen Shot 2018 03 09 at 4.01.09 PM - Java Servlet Example 2

  • index.jsp (put it in the “web” folder) 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Calculator</title>
</head>
<body bgcolor="aqua">

<form method="post" action="GreetingServlet">


  <h3 style="text_align:center;">Choose an operation:
    <input type="radio" name="r1" value="add" />addition
    <input type="radio" name="r2" value="sub" />subtraction
    <input type="radio" name="r3" value="mul" />multiplication
    <input type="radio" name="r4" value="div" />division
  </h3>

  </label>
  <label>Choose 1<sup>st</sup> number:</label>
  <input type="text" name="n1" />
  <br>
  <label>Choose 2<sup>nd</sup> number:</label>
  <input type="text" name="n2" />
  <br>
  <label>
      <input type="submit" value="Submit" style="background-color: hotpink">
  </label>

</form>
</body>
</html>

  • FormServlet.java (put it in the “src” folder) 

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/FormServlet")
public class GreetingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

   public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try
        {
            response.setContentType("text/html");
            PrintWriter out= response.getWriter();
            out.println("<body style='background-color:black;color:yellow;'>");
            out.println("<h3 style='color:red;'>Output of your inputs </h3>");
            int a1= Integer.parseInt(request.getParameter("n1"));
            int a2= Integer.parseInt(request.getParameter("n2"));
            if(request.getParameter("r1")!=null)
            {
                out.println("<p>Addition</p>"+(a1+a2));
            }
            if(request.getParameter("r2")!=null)
            {
                out.println("<p>Subtraction</p>"+(a1-a2));
            }
            if(request.getParameter("r3")!=null)
            {
                out.println("<p>Multiplication</p>"+(a1*a2));
            }if(request.getParameter("r1")!=null)
        {
            out.println("<p>Division</p>"+(a1/a2));
        }
        }
        catch(Exception e)
        {
            System.out.println("error" + e.getMessage());

        }
    }
}

Note: To run this program type: localhost:8080 in the browser URL. 

Click here if you don’t don’t how to set up a NetBeans servlet project.