Sunday, 28 May 2023

Operating System Interview Questions


Operating System Interview Questions


What is Operating System?

The operating system is a software program that facilitates computer hardware to communicate and operate with the software applications and it acts as an interface between the user and the computer hardware. It is the most important part of a computer system without it computer is just like a box.

What is Deadlock?

Deadlock is a situation when two or more processes wait for each other to finish and none of them ever finish. Consider an example when two trains are coming toward each other on same track and there is only one track, none of the trains can move once they are in front of each other. Similar situation occurs in operating systems when there are two or more processes hold some resources and wait for resources held by other(s).

What is Time-sharing system?


In a Time-sharing system, the CPU executes multiple jobs by switching among them, also known as multitasking. This process happens so fast that users can interact with each program while it is running.

Define Thoroughput.

Throughput – number of processes that complete their execution per time unit. Turnaround time – amount of time to execute a particular process. Waiting time – amount of time a process has been waiting in the ready queue. Response time – amount of time it takes from when a request was submitted until the first response is produced, not output (for time-sharing environment).

What are the functions of operating system?

The operating system controls and coordinates the use of hardware among the different processes and applications. It provides the various functionalities to the users. The following are the main job of operating system.

– Resource utilization
– Resource allocation
– Process management
– Memory management
– File management
– I/O management
– Device management


What Are Real-time Systems?

Real-time systems are used when rigid time requirements have been placed on the operation of a processor. It has well defined and fixed time constraints.

Explain the concept of Reentrancy?

It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Each execution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack.
Note: A reentrant procedure can be interrupted and called by an interrupting program, and still execute correctly on returning to the procedure.


What is multi-programming, and what are the advantages?

A multiprogramming operating system is one that allows a process where multiple programs execute over one CPU. If your interviewer asks OS questions on multiprogramming, you can highlight key differences between a multiprogramming OS and other systems.

One way to display that you understand the benefits of multi-programming is to use a real-life example. By offering an instance when you used multi-programming to receive such benefits, you are displaying hands-on knowledge of a system that might be important to the interviewer.


What is virtual memory?

Virtual memory is a memory management method that helps to execute the process using the primary and secondary memory. Though the program gets executed using the main memory, the resources and pages load from the secondary memory.


What is Thrashing?

Thrashing is a situation when the performance of a computer degrades or collapses. Thrashing occurs when a system spends more time processing page faults than executing transactions. While processing page faults is necessary to in order to appreciate the benefits of virtual memory, thrashing has a negative affect on the system. As the page fault rate increases, more transactions need processing from the paging device. The queue at the paging device increases, resulting in increased service time for a page fault.


What is the difference between micro kernel and macro kernel?

Micro kernel: micro kernel is the kernel which runs minimal performance affecting services for operating system. In micro kernel operating system all other operations are performed by processor.

Macro Kernel: Macro Kernel is a combination of micro and monolithic kernel.


Enumerate the different RAID levels.



RAID 0 – Non-redundant striping
RAID 1 – Mirrored Disks
RAID 2 – Memory-style error-correcting codes
RAID 3 – Bit-interleaved Parity
RAID 4 – Block-interleaved Parity
RAID 5 – Block-interleaved distributed Parity
RAID 6 – P+Q Redundancy


Is it possible to have a deadlock involving only one process? Explain your answer.

Deadlock with one process is not possible. Here is the explanation. A deadlock situation can arise if the following four conditions hold simultaneously in a system.Mutual Exclusion.
Hold and Wait.
No Preemption.
Circular-wait.It is not possible to have circular wait with only one process, thus failing a necessary condition for Circular wait. There is no second process to form a circle with the first one. So it is not possible to have a deadlock involving only one process.


How Are Server Systems Classified?

Server systems can be classified as either computer-server systems or file server systems. In the first case, an interface is made available for clients to send requests to perform an action. In the second case, provisions are available for clients to create, access and update files.


List the Coffman’s conditions that lead to a deadlock.

Mutual Exclusion: Only one process may use a critical resource at a time.
Hold & Wait: A process may be allocated some resources while waiting for others.
No Pre-emption: No resource can be forcible removed from a process holding it.
Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain.


Describe how to boot an operating system.

The word “boot” is short for “bootstrap,” which is the name of the program that prompts the operating system at startup. Booting occurs when you start a computer from the kernel. This usually happens when you start it for the first time. It may also occur when the computer malfunctions and you have to put it in safe mode or reboot it as though it were a new CPU.

Booting an operating system is an essential function that applies to many varied work environments. If you have a workplace with computers, it’s highly likely you will have to boot new and existing computers as an IT professional. The answer to this question offers the interviewer a read on your fundamental skills with regards to operating systems.


What is demanding Paging?

Demanding pages is a concept used by the virtual machine. Only a part of the process needs to be present in the main memory to execute some process, which means that only a few pages will only be present in the main memory at any time, and rest will be kept in the secondary memory.


What is Banker’s algorithm?

Banker’s algorithm is used to avoid deadlock. It is the one of deadlock-avoidance method. It is named as Banker’s algorithm on the banking system where bank never allocates available cash in such a manner that it can no longer satisfy the requirements of all of its customers.


Give an example of a Process State.

New State – means a process is being created
Running – means instructions are being executed
Waiting – means a process is waiting for certain conditions or events to occur
Ready – means a process is waiting for an instruction from the main processor
Terminate – means a process is stopped abruptly


What is a pipe?

A traditional pipe is unnamed and can be used only for the communication of related process. If unrelated processes are required to communicate – named pipes are required.
It is a pipe whose access point is a file available on the file system. When this file is opened for reading, a process is granted access to the reading end of the pipe. Similarly, when the file is opened for writing, the process is granted access to writing end of the pipe.
A named pipe is also referred to as FIFO or named FIFO.


Explain the main purpose of an operating system?

There are two main purposes of Operating systems :One is that it is designed to make sure a computer system performs well by managing its computational activities.
Another is that it provides an environment for the development and execution of programs.


What are the advantages of a multiprocessor system?

With an increased number of processors, there is a considerable increase in throughput. It can also save more money because they can share resources. Finally, overall reliability is increased as well.

What is kernel?

A kernel is the core of every operating system. It connects applications to the actual processing of data. It also manages all communications between software and hardware components to ensure usability and reliability.

What are real-time systems?

Real-time systems are used when rigid time requirements have been placed on the operation of a processor. It has well defined and fixed time constraints.

What do you mean by a process?

An executing program is known as a process. There are two types of processes:Operating System Processes
User Processes

What is time- sharing system?

In a Time-sharing system, the CPU executes multiple jobs by switching among them, also known as multitasking. This process happens so fast that users can interact with each program while it is running.

What are the different states of a process?

New Process
Running Process
Waiting Process
Ready Process
Terminated Process


What is the difference between process and program?


ProgramProcess
Program is a set of instructions written to complete a task. Process is a program in execution.
Program is a passive/static entity. Process is an active/dynamic entity.
Program resides in secondary memory. A process in execution resides in Primary Memory.
Program has a longer life span. A process has a limited life span.
A program only requires memory space to store itself. Process needs execution time in CPU, I/O requirements, shared resources, files, memory addresses and more.
It has no significant overhead. Has a significant overhead.

What is the basic difference between pre-emptive and non-preemptive scheduling?

Pre-Emptive SchedulingNon Pre-Emptive Scheduling
CPU allocation is for a limited time. CPU allocation until the process is complete.
Execution of the process is interrupted in the middle. Execution of the process remains uninterrupted until it is completed.
The concept bears an overhead of switching between the tasks. No such overhead of switching between the tasks.
If the CPU receives continuous high priority tasks, a process may remain in the waiting state indefinitely. If the CPU is processing a program with the largest burst time, even a program with the smallest burst time may have to starve.
It allows flexibility to the processes which are in the waiting state allowing the high priority tasks to be executed first. This approach is also known as the rigid scheduling as it offers no flexibility to the processes irrespective of their urgency for execution.
Pre emptive scheduling needs to maintain the integrity of the shared data and to ensure no data loss occurs when processes are swapped from the waiting state to the ready state. The Non- pre-emptive Scheduling does not require to maintain data integrity as no processes are swapped from the waiting state to the ready state.

What are the deadlock avoidance algorithms?


A dead lock avoidance algorithm dynamically examines the resource-allocation state to ensure that a circular wait condition can never exist. The resource allocation state is defined by the number of available and allocated resources, and the maximum demand of the process. There are two algorithms:Resource allocation graph algorithm
Banker’s algorithmSafety algorithm
Resource request algorithm


What is CPU Scheduler?

Selects from among the processes in memory that are ready to execute, and allocates the CPU to one of them. CPU scheduling decisions may take place when a process:Switches from running to waiting state.
Switches from running to ready state.
Switches from waiting to ready.
Terminates.

What is Dispatcher?


Dispatcher module gives control of the CPU to the process selected by the short-term scheduler; this involves:Switching context
Switching to user mode
Jumping to the proper location in the user program to restart that program
Dispatch latency – time it takes for the dispatcher to stop one process and start another running.

Which are the necessary conditions to achieve a deadlock?

There are 4 necessary conditions to achieve a deadlock:Mutual Exclusion: At least one resource must be held in a non-sharable mode. If any other process requests this resource, then that process must wait for the resource to be released.
Hold and Wait: A process must be simultaneously holding at least one resource and waiting for at least one resource that is currently being held by some other process.
No preemption: Once a process is holding a resource ( i.e. once its request has been granted ), then that resource cannot be taken away from that process until the process voluntarily releases it.
Circular Wait: A set of processes { P0, P1, P2, . . ., PN } must exist such that every P[ i ] is waiting for P[ ( i + 1 ) % ( N + 1 ) ].

How many types of fragmentation occur in Operating System?

There are two types of fragmentation:Internal fragmentation: It is occurred when we deal with the systems that have fixed size allocation units.
External fragmentation: It is occurred when we deal with systems that have variable-size allocation units.

What is Memory-Management Unit (MMU)?


Hardware device that maps virtual to physical address. In MMU scheme, the value in the relocation register is added to every address generated by a user process at the time it is sent to memory. The user program deals with logical addresses; it never sees the real physical addresses

Advanced OS Interview Questions


Explain the different sections of a process.


Every process has a process memory, which is generally divided into 4, this is done to make the most efficient functioning as possible –Stack – This houses all the temporary data and local variables like function parameters and addresses.
Heap – When the process is in its run time, for dynamic memory allocation, for operations such as new(), delete(), malloc(), etc heap is used for fastest access at the run time.
Text – Contains value of Program Counter and the contents of the processor’s registers which just the most low level instructions of the compiled program
Data – Has static and global variables.


What are the different types of scheduling algorithms?

This is the advanced OS Interview Questions which is asked in an interview. The different types of scheduling algorithms are as follows:First come First serve(FCFS): First came process is served first.
Round Robin(RR): Each process is given a quantum amount of time.
Shortest job first(SJF): Process with lowest execution time is given first preference.
Priority scheduling (PS): Priority value called (nice value) is used for selecting process. Its value is from 0 to 99. 0 being maxed and 99 being least.

What are the difference between user level thread and kernel level thread?

User-Level ThreadsMulti-Threaded Model
User Threads are implemented by users. Kernel Threads are implemented by OS.
OS does not recognize user level threads. Kernel threads are recognized by OS.
Implemetation is easy. Implementation is complicated.
Context switch time is less. Context switch time is more.
Context switch-no hardware support. Hardware support is needed.
If one user level thread perform blocking operation then entire process will be blocked. If one kernel thread perform blocking operation then another thread can continue execution.

What is synchronization? What are the different synchronization mechanisms?

When several threads (or processes) share data, running in parallel on different cores, then changes made by one process may override changes made by another process running parallel. Resulting in inconsistent data. So, this requires processes to be synchronized, handling system resources and processes to avoid such situation is known as Process Synchronization.

Different synchronization mechanisms are: Mutex
Semaphores
Monitors
Condition variables
Critical regions
Read/ Write locks

What is the use of paging in operating system?

Paging is a memory-management scheme that permits the physical address space of a process to be non contiguous or in other words eliminates the need for contiguous allocation of physical memory.That is we can have logically use memory spaces that physically lie at different locations in the memory.
This allows viewing memory spaces that physically lie at different locations in the hardware to be logically viewed as contiguous.

What is the Zombie process?

A zombie process is a process that has completed and in the terminated state but has its entry in the process table. It shows that the resources are held by the process and are not free.

When does the Belady’s anomaly occur?

In the Virtual memory system, all the processes are divided into fixed-sized pages. These pages are loaded into the physical memory using the method of demand paging. Under demand paging, during the execution of a particular process, whenever a page is required, a page fault occurs, and then the required page gets loaded into the memory replacing some other page. The page replacement algorithm specifies the choice of the page which is to be replaced. Now, Belady’s Anomaly is said to occur when the number of page faults increases significantly.


What is the basic difference between Segmentation and Paging?


PagingSegmentation
A page is a physical unit of information. A segment is a logical unit of information.
Frames on main memory are required. No frames are required.
No frames are required. The page is of the variable block size
It leads to internal fragmentation It leads to external fragmentation
The page size is decided by hardware in paging Segment size is decided by the user in segmentation
It does not allow logical partitioning and protection of application components It allows logical partitioning and protection of application components
Paging involves a page table that contains the base address of each page Segmentation involves the segment table that contains the segment number and offset

What are the different types of Kernel?


Kernels are basically of two types:Monolithic Kernels –In this architecture of kernel, all the system services were packaged into a single system module which lead to poor maintainability and huge size of kernel.
Microkernels – They follow the modular approach of architecture. Maintainability became easier with this model as only the concerned module is to be altered and loaded for every function. This model also keeps a tab on the ever growing code size of the kernel.


What is Starvation?


If the CPU gets the processes of the higher burst time at the front end of the ready queue then the processes of lower burst time may get blocked which means they may never get the CPU if the job in the execution has a very high burst time. This is called convoy effect or starvation.In starvation resources are continuously utilized by high priority processes. Problem of starvation can be resolved using Aging.
In Aging priority of long waiting processes is gradually increased.

What is a safe state and what is its use of deadlock avoidance?

A state is safe if the system can allocate all resources requested by all processes ( up to their stated maximums ) without entering a deadlock state. System is in safe state if there exists a safe sequence of all processes. Deadlock Avoidance: Ensure that a system will never enter an unsafe state.

What are turn around time and response time?

The basic difference b/w the turn around time and response time is:-Turn around time is the interval between the submission of a job and its completion.
Response time is the interval b/w the submission of the request, and the first response to that request.

What are the reasons for process suspension?

Swapping
Interactive User Request
Timing
Parent Process Reques

What are various scheduling queues?

Given below are the scheduling queues:-Job Queue:- When a process enters the system it is placed in the job queue.
Ready Queue:- The processes that are residing in the main memory and are ready and waiting to execute are kept on a list called the ready queue.
Device Queue:- A list of processes waiting for a particular I/O device is called device queue.


Tuesday, 3 January 2023

Ruby On Rails Objective type Questions and Answers for experienced



1. What is bundler?a) rails generate scaffold User name:string email:string
b) self-contained bundles of gems. Useful for versioning.
c) Edit Gemfile, then run ‘bundle install’ or just ‘bundle’.
d) Ruby Version Manager. Install and manage multiple versions of Ruby.
Ans: C

2. What is gemset?
a) self-contained bundles of gems. Useful for versioning.
b) self-contained packages of Ruby code
c) Ruby Version Manager. Install and manage multiple versions of Ruby.
d) rails generate scaffold User name:string email:string
Ans: A




3. What is gem?
a) rails generate scaffold User name:string email:string
b) self-contained packages of Ruby code
c) self-contained bundles of gems. Useful for versioning.
d) Ruby Version Manager. Install and manage multiple versions of Ruby.
Ans: B

4. what is scaffold command?
a) rails generate scaffold User name:string email:string
b) Ruby Version Manager. Install and manage multiple versions of Ruby.
c) self-contained packages of Ruby code
d) self-contained bundles of gems. Useful for versioning.
Ans: A

5. What is rake?
a) self-contained bundles of gems. Useful for versioning.
b) bundle exec rake db:migrate. Using bundle exec ensures that the rake version in our Gemfile is used.
c) rails generate scaffold User name:string email:string
d) Ruby Version Manager. Install and manage multiple versions of Ruby.
Ans: B

6. What is rvm?
a) rails generate scaffold User name:string email:string
b) Ruby Version Manager. Install and manage multiple versions of Ruby.
c) self-contained bundles of gems. Useful for versioning.
d) self-contained packages of Ruby code
Ans: B

7.how do you create a migration that adds a “phone” field to the “tickets” table?
a) unit, functional, and integration tests
b) RAILS_ENV (RAILS_ENV=production)
c) integration test
d) rails generate migration AddPhoneToTickets phone:string
Ans: D

8.Rails’ application framework is called ———-?
a) ActionPack
b) ActiveRecord
c) a web page
d) an object
Ans: A

9.how do you run a migration?
a) CamelCase
b) ruby make
c) an object
d) rake db:migrate
Ans: D

10.what does “show” refer to as the :action value?
a) the method within the controller to call
b) HTTP methods (post, get, put, delete)
c) the data being presented by the web page
d) their names begin with an underscore
Ans: A

11.how do you update?
a) update_attributes (as in @ad.update_attributes(params[:ad]))
b) unit, functional, and integration tests
c) format (that period is a concatenation period)
d) it is not associated with a model
Ans: A

12.what comes after <% form_for()... ?
a) redirect_to " ... "
b) the request parameters table
c) <%= f.text_field :name %>
d) do |f| (where “f” can be anything)
Ans: D

13.what kind of tests are there?
a) unit, functional, and integration tests
b) it is not associated with a model
c) id, created_at, updated_at
d) it runs its validators
Ans: A

14.how do you specify a format like html or xml in routes.rb?
a) .:format (that period is a concatenation period)
b) HTTP methods (post, get, put, delete)
c) their names begin with an underscore
d) unit, functional, and integration tests
Ans: A

15.when you put something into an array, does the array keep a separate copy?
a) no. arrays just keep references to objects stored in memory.
b) the data being presented by the web page
c) it is not associated with a model
d) the request parameters table
Ans: A

16.what is scriptlet versus expression
a) it runs its validators
b) it is not associated with a model
c) Representational State Transfer
d) expression is ruby code that prints out a value in html
Ans: D

17.what does the “h” in <%=h ... %> mean?
a) .:format (that period is a concatenation period)
b) h is a helper method that escapes special characters to sanitize malicious input
c) a script that alters the structure of the underlying database
d) the method within the controller to call
Ans: B

18.what’s the difference between model names and controller names?
a) the method within the controller to call
b) the data being presented by the web page
c) model names are singular, controller (and table) names are plural
d) in the controller: respond_to do |format| … end
Ans: C

19.what is “migration”?
a) It is a format (that period is a concatenation period)
b) a script that alters the structure of the underlying database
c) their names begin with an underscore
d) the data being presented by the web page
Ans: B

20.what steps get you from fild.erb to file.html?
a) data from model objects AND the page template
b) .erb -> Embedded Ruby -> ruby code (file.rb) -> fild.html
c) the method within the controller to call
d) the data being presented by the web page
Ans: B

21.what is the filter code that calls on the “check_logged_in” method for only the “edit” and “update” methods?
a) the data being presented by the web page
b) HTTP methods (post, get, put, delete)
c) data from model objects AND the page template
d) before_filter :check_logged_in, :only => [:edit, :update]
Ans: D

22.representation of a resource is called ————-.
a) CamelCase
b) ruby make
c) a web page
d) ActionPack
Ans: C

23.converts database records to objects is called ————-.
a) for ad in @ads
b) integration test
c) Representational State Transfer
d) an object-relational mapping library
Ans: D

24.what checks if an input is numeric?
a) integration test
b) a responder object
c) validate
d) validates_numericality_of
Ans: D

25.what is Rails’ object-relational mapping library?
a) CamelCase
b) ActiveRecord
c) an object
d) underscores
Ans: B

26.where do you add the filter code?
a) rails generate migration AddPhoneToTickets phone:string
b) the data being presented by the web page
c) data from model objects AND the page template
d) right after the line introducing the class in the controller
Ans: D

27.why is it good to redirect after inserting info into the database?
a) unit, functional, and integration tests
b) a script that alters the structure of the underlying database
c) so that users can’t accidentally resubmit information by refreshing the page
d) the data being presented by the web page
Ans: C

28.which two steps to include test.xml data to the partial “map” (via the variable “data”)…?
a) from general to specific (‘/ads/’ and then ‘/ads/:id’)
b) include test.xml to root of “public” folder and , render (:partial=>’map’, :locals=>{:data=>’/test.xml’})
c) just replace the word “scaffold” with the word “model”
d) login method (that checks a username and password) and , a filter (that calls the login method when needed)
Ans: B

29.what environments does Rails have by default?
a) development, test, production
b) render :partial
c) RAILS_ENV (RAILS_ENV=production)
d) integration test
Ans:A

30.how do you generate regular model code (not scaffolding)?
a) just replace the word “scaffold” with the word “model”
b) it is not associated with a model
c) username == “admin” && password == “some_password”
d) do |f| (where “f” can be anything)
Ans: A

31.how should you order routes?
a) just replace the word “scaffold” with the word “model”
b) from general to specific (‘/ads/’ and then ‘/ads/:id’)
c) rails generate migration AddPhoneToTickets phone:string
d) do |f| (where “f” can be anything)
Ans: B

32.what should you write in routes.rb to give meaning to http://mebay.com/ads/3?
a) from general to specific (‘/ads/’ and then ‘/ads/:id’)
b) map.connect ‘/ads/:id’, :controller=>’ads’, :action=>’show’
c) include test.xml to root of “public” folder and ,render (:partial=>’map’, :locals=>{:data=>’/test.xml’})
d) form_for(@object, :url=>{:action=>’create’})
Ans: B

33.to add login security, which two pieces of code do you need?
a) 1.all important data is a resource2. every resource has a proper name (URL)
b) .:format (that period is a concatenation period)
c) the method within the controller to call
d) 1. login method (that checks a username and password) and 2. a filter (that calls the login method when needed)
Ans: D

34.how do partials look compared to regular erb files?
a) underscores
b) it runs its validators
c) it is not associated with a model
d) their names begin with an underscore
Ans: D

35.how does “rake” differ from “ruby”?
a) right after the line introducing the class in the controller
b) a script that alters the structure of the underlying database
c) it can do more complex things like modifying the database structure and running tests
d) expression is ruby code that prints out a value in html
Ans: C

36.why should partials generally use local variables?
a) because they make the partial less dependent on other code
b) the data being presented by the web page
c) their names begin with an underscore
d) the request parameters table
Ans: A

37.do models have singular or plural names?
a) controller
b) CamelCase
c) flight_id
d) singular
Ans: D

38.how does rake tell which migrations have been run and which have not?
a) rails generate migration AddPhoneToTickets phone:string
b) rails records the latest timestamp of all the migrations it runs (and runs only the latest ones)
c) because they make the partial less dependent on other code
d) it can do more complex things like modifying the database structure and running tests
Ans: B

39.how does Rails choose to correct format to generate?
a) in the controller: respond_to do |format| … end
b) it is not associated with a model
c) redirect_to ” … ”
d) the data being presented by the web page
Ans: A

40.how do you express error messages in a form (do |f|)?
a) ruby make
b) f.error_messages
c) for ad in @ads
d) underscores
Ans: B

41.what are the three “magic columns”
a) id, created_at, updated_at
b) render :partial:id
c) integration test
d) rake db:migrate:id:delete
Ans: A

42.what tag starts a form?
a) integration test
b) <%= f.text_field :name %>
c) <% form_for() %>
d) <%= yield %>
Ans: C

43.what is params[…]?
a) have the same URL of a table
b) the word “private”
c) a responder object
d) the request parameters table
Ans: D

44.what comes after “def check_logged_in” line for site “ads”?
a) in the controller: respond_to do |format| … end
b) errors.add_to_base(“there was an error”)
c) .:format (that period is a concatenation period)
d) authenticate_or_request_with_http_basic(“Ads”) do |username, password|
Ans: D

45.what is naming convention for classes?
a) ActionPack
b) CamelCase
c) ruby make
d) a web page
Ans: B

46.to create scafolding for “thing” data, run…
a) because they make the partial less dependent on other code
b) expression is ruby code that prints out a value in html
c) just replace the word “scaffold” with the word “model”
d) rails generate scaffold thing : : Ans: D

47.what variable changes the environment?
a) RAILS_ENV (RAILS_ENV=production)
b) development, test, production
c) render :partial
d) validates_numericality_of
Ans: A

48.what is naming convention for file names ?
a) ActiveRecord
b) underscores
c) an object
d) validate
Ans: B

49.why do you only need to call “render” in the controller sometimes and not always?
a) .:format (that period is a concatenation period)
b) redirect_to ” … ”
c) errors.add_to_base(“there was an error”)
d) if you’re happy with the default template, you can omit “render”
Ans: D

50.a RESTful application uses … to define an interaction with the data.
a) a responder object
b) it is not associated with a model
c) HTTP methods (post, get, put, delete)
d) the request parameters table
Ans: C

51.what generates web pages from page templates?
a) underscores
b) Embedded Ruby (ERb)
c) a web page
d) render :partial
Ans: B

52.where do you edit routs?
a) :controller
b) underscores
c) ActiveRecord
d) config/routes.rb
Ans: D

53.if looping through “f” object, how do you make a text field “name”?
a) <%= yield %>
b) … have the same URL
c) <% form_for() %>
d) <%= f.text_field :name %>
Ans: D

54.what does a model object do before it saves or updates data?
a) underscores
b) it runs its validators
c) validate
d) rake db:migrate
Ans: B

55.what does “rake” mean?
a) #{1+1}
b) singular
c) ruby make
d) flight_id
Ans: C

56.how do you start a loop that reads through the array object “@ads”?
a) a web page
b) ruby make
c) for ad in @ads
d) ActionPack
Ans: C

57.what scripts does the model-generator command create?
a) their names begin with an underscore
b) the model class (app/models/something.rb) and the data migration (db/migrate/…_create_something.rb)
c) model names are singular, controller (and table) names are plural
d) rails generate migration AddPhoneToTickets phone:string
Ans: B

58.what does Embedded Ruby (ERb) process as inputs?
a) data from model objects AND the page template
b) HTTP methods (post, get, put, delete)
c) it is not associated with a model
d) their names begin with an underscore
Ans: A

59.what kind of test do you create yourself?
a) an object
b) ActionPack
c) rake db:migrate
d) integration test
Ans: D

60.what is “format” in “repond_to do |format|”?
a) underscores
b) an object
c) a responder object
d) integration test
Ans: C

61.what does REST stand for?
a) runs State test
b) the request State Transfer
c) Representational State Transfer
d) runs State Transfer
Ans: C

62.what parameters are in <% form_for() %>?
a) data from model objects AND the page template
b) form_for(@object, :url=>{:action=>’create’})
c) .:format (that period is a concatenation period)
d) do |f| (where “f” can be anything)
Ans: B

63.how do you add an error (called “there was an error”) in the validate method?
a) redirect_to ” … ”
b) errors.add_to_base(“there was an error”)
c) the word “private”
d) their names begin with an underscore
Ans: B

64.how do you call a partial?
a) a web page
b) underscores
c) singular
d) render :partial
Ans: D

65.how do you run the latest migrations?
a) ruby make
b) a web page
c) rake db:migrate
d) CamelCase
Ans: C

66.what’s special about a search form?
a) for ad in @ads
b) it is not associated with a model
c) Representational State Transfer
d) it runs its validators
Ans: B

67.what expression do all layouts have?
a) <%= yield %>
b) <% form_for() %>
c) integration test
d) <%= f.text_field :name %>
Ans: A

68.if the table Seats is associated with the table Flights, how should you name the table column in Seats to indicate its flight?
a) an object
b) flight_id
c) ruby make
d) #{1+1}
Ans: B

69.how would you insert “1 + 1” into a string?
a) CamelCase
b) #{1+1}
c) singular
d) validate
Ans: B

70.what is the second uri indicate?
a) an object
b) ActionPack
c) CamelCase
d) :controller
Ans: D

71.what precedes the “check_logged_in” method in a class?
a) the request parameters table
b) the word “private”
c) <% form_for() %>
d) redirect_to ” … ”
Ans: B

72.what method name indicates to rails that it should validate before saving/updating?
a) validate
b) ActionPack
c) flight_id
d) ruby make
Ans: A

73.how do you ask for all records of the Ads table?
a) singular
b) @ads = Ad.find(:all)
c) validate
d) rake db:migrate
Ans: B

74.when data is retrieved from the database, what does Rails turn it into?
a) a responder object
b) validate
c) flight_id
d) an object
Ans: D

75.what are the main principles of REST?
a) 1. all important data is a resource, 2. every resource has a proper name (URL), 3. you can perform a standard set of operations on resources (usually CRUD), 4. client and server talk statelessly
b) model names are singular, controller (and table) names are plural
c) a script that alters the structure of the underlying database
d) no. arrays just keep references to objects stored in memory.
Ans: A

76.When is it best to use an array rather than a hash?
a) An array uses indices and a hash uses “keys”
b) puts (pronounced “put-ess”)
c) Red refers to writing a failing test
d) When the order matters, use an array.
Ans: D

77.Describe the TDD cycle.
a) An array uses indices and a hash uses “keys”
b) It’s a test that simulates a browser accessing our application.
c) Red, Green, Refactor,Red refers to writing a failing test,Green refers to writing a passing test Once we have a passing test we are free to refactor the code.
d) This maps requests for the URL /pages/home to the home action in the Pages controller.
Ans: C

78.How does a local variable differ from an instance variable when empty?
a) This is not a standard rails directory, but a directory installed by RSpec in which all test files are kept.
b) The @ indicates that this is an “instance variable”. An instance variable defined in the action (or function) of a controller is automatically available in the view of that same name.
c) It’s a test that simulates a browser accessing our application.
d) Ruby complains if we try to evaluate an undefined local variable, but issues no such complaint for an instance variable; instead, instance variables are nil if not defined
Ans: D

79.What is a .erb file?
a) The “erb” stands for “Embedded RuBy”. .erb files look like about.html.erb and live in the “views” directory.They are just html files with embedded ruby in them.
b) The @ indicates that this is an “instance variable”. An instance variable defined in the action (or function) of a controller is automatically available in the view of that same name.
c) puts (pronounced “put-ess”)
d) It’s a test that simulates a browser accessing our application.
Ans: A

80.What’s the best way to describe an object in Ruby?
a) An array uses indices and a hash uses “keys”
b) It’s easier to describe what objects do, which is respond to messages. An object like a string, for example, can respond to the message length, which returns the number of characters in the string
c) This maps requests for the URL /pages/home to the home action in the Pages controller.
d) It’s a test that simulates a browser accessing our application.
Ans: B

81.What is a Class?
a) An array uses indices and a hash uses “keys”
b) Classes are simply a convenient way to organize functions (also called methods). In pages_controller.rb, PagesController is a Class which holds a “home” action.
c) A controller is a container for a group of (possibly dynamic) web pages.
d) This maps requests for the URL /pages/home to the home action in the Pages controller.
Ans: B

82.What kind of object is “@title” and what is special about it in Rails?
a) It’s a test that simulates a browser accessing our application.
b) The “erb” stands for “Embedded RuBy”. .erb files look like about.html.erb and live in the “views” directory.They are just html files with embedded ruby in them.
c) Ruby complains if we try to evaluate an undefined local variable, but issues no such complaint for an instance variable; instead, instance variables are nil if not defined
d) The @ indicates that this is an “instance variable”. An instance variable defined in the action (or function) of a controller is automatically available in the view of that same name.
Ans: D

83.What does the routes.rb file do with “get pages/home”?
a) When a request is made for, say, /pages/home, the Pages controller executes the code in the “home” action and then automatically renders the view corresponding to the action — in this case, home.html.erb.
b) This maps requests for the URL /pages/home to the home action in the Pages controller.
c) When the order matters, use an array.
d) It’s a test that simulates a browser accessing our application.
Ans: B

84.Describe a “symbol” in Rails?
a) Ruby complains if we try to evaluate an undefined local variable, but issues no such complaint for an instance variable; instead, instance variables are nil if not defined
b) Symbols look kind of like strings, but prefixed with a colon instead of surrounded by quotes. For example, :name is a symbol. You can think of symbols as basically strings without all the extra baggage
c) An array uses indices and a hash uses “keys”
d) This is not a standard rails directory, but a directory installed by RSpec in which all test files are kept.
Ans: B

85.What is the status code for “success” when throwing a GET?
a) 300
b) 200
c) 400
d) 150
Ans: B

86.What is the command to print to the screen?
a) When the order matters, use an array.
b) An array uses indices and a hash uses “keys”
c) It’s a test that simulates a browser accessing our application.
d) puts (pronounced “put-ess”)
Ans: D

87.What is the main benefit that a Class gets by inheritance from ApplicationController?
a) An array uses indices and a hash uses “keys”
b) When a request is made for, say, /pages/home, the Pages controller executes the code in the “home” action and then automatically renders the view corresponding to the action — in this case, home.html.erb.
c) This maps requests for the URL /pages/home to the home action in the Pages controller.
d) When the order matters, use an array.
Ans: B

88.Name two ways to indicate a “block” in Rails
a) This maps requests for the URL /pages/home to the home action in the Pages controller.
b) The request hits the rails router which dispatches to the proper controller action. In this case, it goes to the index action in the Users controller.
c) Curly braces or do..end. It’s best to use curly braces for short one-line blocks and the do..end for mult-iline blocks.
d) When the order matters, use an array.
Ans: C

89.What is an integration test?
a) It’s a test that simulates a browser accessing our application.
b) When the order matters, use an array.
c) puts (pronounced “put-ess”)
d) An array uses indices and a hash uses “keys”
Ans: A

90.What is the most special aspect of nil?
a) This maps requests for the URL /pages/home to the home action in the Pages controller.
b) A controller is a container for a group of (possibly dynamic) web pages.
c) When the order matters, use an array.
d) Other than the object “false” itself, nil is the only object that defaults to false.
Ans: D

91.What is the /spec directory in rails?
a) Ruby complains if we try to evaluate an undefined local variable, but issues no such complaint for an instance variable; instead, instance variables are nil if not defined
b) Symbols look kind of like strings, but prefixed with a colon instead of surrounded by quotes. For example, :name is a symbol. You can think of symbols as basically strings without all the extra baggage
c) This is not a standard rails directory, but a directory installed by RSpec in which all test files are kept.
d) This maps requests for the URL /pages/home to the home action in the Pages controller.
Ans: C

92.What’s the difference between a hash and an array?
a) An array uses indices and a hash uses “keys”
b) When the order matters, use an array.
c) It’s a test that simulates a browser accessing our application.
d) puts (pronounced “put-ess”)
Ans: A

93.What is a controller?
a) A controller is a container for a group of (possibly dynamic) web pages.
b) An array uses indices and a hash uses “keys”
c) It’s a test that simulates a browser accessing our application.
d) When the order matters, use an array.
Ans: A

94.how do you define a “status” parameter (within a “tweet” parameter)?
a) code = tweet,url = /tweets/1
b) @tweet = Tweet.create(:status => params[:status])
c) params = {:tweet => {:status => “I’m dead” }}
d) @tweet = Tweet.create(:status => params[:tweet][:status])
Ans: D

95.how do you check the logged in user’s id?
a) :status
b) session[:user_id]
c) t.errors
d) the attribute
Ans: B

96.let’s say you have a method…
def get_tweet
@tweet = Tweet.find(params[:id])
end
how do you tie an action to that that only kicks in for the edit, update, and destroy methods?
a) index, show, new, edit, create, update, destroy
b) code = tweet, :method => :delete
url = /tweets/1
c) before_filter :get_tweet, :only => [:edit, :update, :destroy]
d) @tweet = Tweet.create(:status => params[:tweet][:status])
Ans: C

97.How to includes all javascript?
a) <%= stylesheet_link_tag :all %>
b) <%= javascript_include_tag :defaults %>
c) <%= csrf_meta_tag %>
d) <%= link_to ... %>
Ans: B

98.what do you use to send messages to the user?
a) t.errors
b) :status
c) a flash
d) @tweet
Ans: C

99.how includes all stylesheet files?
a) <%= javascript_include_tag :defaults %>
b) <%= csrf_meta_tag %>
c) <%= link_to ... %>
d) <%= stylesheet_link_tag :all %>
Ans: D

100.how do you make sure your forms don’t get hacked?
a) <%= stylesheet_link_tag :all %>
b) <%= csrf_meta_tag %>
c) <%= link_to ... %>
d) tweets_path
Ans: B

Friday, 12 May 2017

Remove last two characters from given string using slice


#Remove last #two #characters from given string using #slice in #javascript. There are some more methods to remove last two characters.

var fruits = ["Orange", "Strawberry", "Banana", "Orange", "Mango"];
var myBest = fruits.slice(-3, -1);



Monday, 19 December 2016

Node.js - RESTful API


Node.js - RESTful API

What is REST architecture?

REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000.

A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource like text, JSON, XML but JSON is the most popular one.

HTTP methods

Following four HTTP methods are commonly used in REST based architecture.
  • GET - This is used to provide a read only access to a resource.
  • PUT - This is used to create a new resource.
  • DELETE - This is used to remove a resource.
  • POST - This is used to update a existing resource or create a new resource.

RESTful Web Services

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., communication between Java and Python, or Windows and Linux applications) is due to the use of open standards.

Web services based on REST Architecture are known as RESTful web services. These webservices uses HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, which provides resource representation such as JSON and set of HTTP Methods.

Creating RESTful for A Library

Consider we have a JSON based database of users having the following users in a file users.json:

{
   "user1" : {
      "name" : "mahesh",
      "password" : "password1",
      "profession" : "teacher",
      "id": 1
   },
   "user2" : {
      "name" : "suresh",
      "password" : "password2",
      "profession" : "librarian",
      "id": 2
   },
   "user3" : {
      "name" : "ramesh",
      "password" : "password3",
      "profession" : "clerk",
      "id": 3
   }
}

Based on this information we are going to provide following RESTful APIs.

S. N.URIHTTP MethodPOST bodyResult
1listUsersGETemptyShow list of all the users.
2addUserPOSTJSON StringAdd details of new user.
3deleteUserDELETEJSON StringDelete an existing user.
4:idGETemptyShow details of a user.

I'm keeping most of the part of all the examples in the form of hard coding assuming you already know how to pass values from front end using Ajax or simple form data and how to process them using express Request object.

List Users

Let's implement our first RESTful API listUsers using the following code in a server.js file:

server.js

var express = require('express');
var app = express();
var fs = require("fs");
 
app.get('/listUsers', function (req, res) {
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       console.log( data );
       res.end( data );
   });
})
 
var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at http://%s:%s", host, port)
})


 Now try to access defined API using URL: http://127.0.0.1:8081/listUsers and HTTP Method : GET on local machine using any REST client. This should produce following result:

You can change given IP address when you will put the solution in production environment.

{
   "user1" : {
      "name" : "mahesh",
      "password" : "password1",
      "profession" : "teacher",
      "id": 1
   },
   "user2" : {
      "name" : "suresh",
      "password" : "password2",
      "profession" : "librarian",
      "id": 2
   },
   "user3" : {
      "name" : "ramesh",
      "password" : "password3",
      "profession" : "clerk",
      "id": 3
   }
}


Add User
Following API will show you how to add new user in the list. Following is the detail of the new user:


user = {
   "user4" : {
      "name" : "mohit",
      "password" : "password4",
      "profession" : "teacher",
      "id": 4
   }
}


You can accept the same input in the form of JSON using Ajax call but for teaching point of view, we are making it hard coded here. Following is the addUser API to a new user in the database:

server.js
var express = require('express');
var app = express();
var fs = require("fs");
 
var user = {
   "user4" : {
      "name" : "mohit",
      "password" : "password4",
      "profession" : "teacher",
      "id": 4
   }
}
 
app.post('/addUser', function (req, res) {
   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       data = JSON.parse( data );
       data["user4"] = user["user4"];
       console.log( data );
       res.end( JSON.stringify(data));
   });
})
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at http://%s:%s", host, port)
 
})

Now try to access defined API using URL: http://127.0.0.1:8081/addUser and HTTP Method : POST on local machine using any REST client. This should produce following result:

{
"user1":{"name":"mahesh","password":"password1","profession":"teacher","id":1},
"user2":{"name":"suresh","password":"password2","profession":"librarian","id":2},
"user3":{"name":"ramesh","password":"password3","profession":"clerk","id":3},
"user4":{"name":"mohit","password":"password4","profession":"teacher","id":4}
}

Show Detail

Now we will implement an API which will be called using user ID and it will display the detail of the corresponding user.

server.js

var express = require('express');
var app = express();
var fs = require("fs");
 
app.get('/:id', function (req, res) {
   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       users = JSON.parse( data );
       var user = users["user" + req.params.id] 
       console.log( user );
       res.end( JSON.stringify(user));
   });
})
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at http://%s:%s", host, port)
 
})

Now try to access defined API using URL: http://127.0.0.1:8081/2 and HTTP Method : GET on local machine using any REST client. This should produce following result:

{"name":"suresh","password":"password2","profession":"librarian","id":2}

Delete User

This API is very similar to addUser API where we receive input data through req.body and then based on user ID we delete that user from the database. To keep our program simple we assume we are going to delete user with ID 2. 

server.js

var express = require('express');
var app = express();
var fs = require("fs");
 
var id = 2;
 
app.delete('/deleteUser', function (req, res) {
 
   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       data = JSON.parse( data );
       delete data["user" + 2];
       
       console.log( data );
       res.end( JSON.stringify(data));
   });
})
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at http://%s:%s", host, port)
 
})

 Now try to access defined API using URL: http://127.0.0.1:8081/deleteUser and HTTP Method : DELETE on local machine using any REST client. This should produce following result:

{"user1":{"name":"mahesh","password":"password1","profession":"teacher","id":1},
"user3":{"name":"ramesh","password":"password3","profession":"clerk","id":3}}