Thursday, 28 December 2017

Java8 interfaces

Java8::Interfaces

interfaces: Interfaces are used in Java to provide a template to developers .In an interface all the fields (variables) are by default public, static and final. Up to Java 1.7 version, all the methods declared in interfaces are public and abstract by default. Since Java 1.8, an interface can have default methods and static methods as well.
An interface can have default methods and static methods. Any other methods are implicitly public and abstract. All the fields declared in an interface are implicitly public, static and final constants.

interface exampple:


Output: from implementaion class::Register
from default impl from Register
in above code if you comment out defaultimpl in register class,call object of esgiter.defaultimpl((from eight interface method as described above).

Output: from implementaion class::Register
from default impl from eigthinterfac
how can you call static methods used in class implements interface(eight interface): you can  call static methods in class or interace using  classname:methodname

output : from implementaion class::Register
from default impl from eigthinterface
from display()  heloo

How can you call if two interfaces have same methods?

call the default method of the specified interface using super keyword.following is example having two interfaces(eigthinterface,secondinterface) and class register.
call same method using class or interfcename.super.methodname.



OutPut: from implementaion class::Register
from default impl from eigthinterface
from default impl from SecondInterface
from display()  heloo

FunctionalInterface::

An interface with one abstract method declaration is known as a functional interface. Functional Interface is also know as SAM Interface because it contains only one abstract method.
SAM Interface stands for Single Abstract Method Interface.
The compiler verifies all interfaces annotated with a
@FunctionalInterface that the interfaces really contain one and only one abstract method.

A compile-time error is generated if the interfaces annotated with this annotation are not functional interfaces. It is also a compile-time error to use this annotation on classes, annotation types, and enums. The FunctionalInterface annotation type is a marker interface.

A functional interface is simply an interface that has exactly one abstract method. The following types of methods in an interface do not count for defining a functional interface:
• Default methods
• Static methods
• Public methods inherited from the Object class
Note that an interface may have more than one abstract method, and can still be a functional interface if all but one of them is a redeclaration of the methods in the Object class.

to define fucntion interface using @Fucntioninterface on interface,below are following rues:
 i)Define an interface with one and only one abstract method.
ii)We cannot define more than one abstract method.
iii)Use @FunctionalInterface annotation in interface definition.
iv)We can define any number of other methods like Default methods, Static methods.
v) If we override java.lang.Object class’s method as an abstract method, which does not count as an abstract method.

Note:Even if you are not  defining functional interface annotation on interface but should define only one abstract method by default it cosidered as functional interface.

if we apply functional interface in classe it will show following error


Wednesday, 20 December 2017

Pyhton :Operators


Python Operators:
Operators are the symbols which perform the operation on the some values. These values are known as operands. Python have following operators –

Arithmetic Operators
Relational Operators
Assignment Operators
Logical Operators
Membership Operators
Identity Operators
Bitwise Operators
Arithmetic Operators:

OperatorNameExampleResult
+Additionx+ySum of x and y.
-Subtractionx-yDifference of x and y.
*Multiplicationx*yProduct of x and y.
/Divisionx/yQuotient of x and y.
%Modulusx%yRemainder of x divided by y.
**Exponentx**yx**y will give x to the power y
//Floor Divisionx/ yThe division of operands where the result is the quotient in which the digits after the decimal point are removed.
Relational Operators :  It is also known as comparison operator because it compares the values. After comparison it returns the Boolean value i.e. either true or false.

OperatorNameExampleResult
==Equalx==yTrue if x is exactly equal to y.
!=Not equalx!=yTrue if x is exactly not equal to y.
>Greater thanx>yTrue if x (left-hand argument) is greater than y (right-hand argument).
<Less thanx<yTrue if x (left-hand argument) is less than y (right-hand argument).
>=Greater than or equal tox>=yTrue if x (left-hand argument) is greater than or equal to y (left-hand argument).
<=Less than or equal tox<=yTrue if x (left-hand argument) is less than or equal to y (right-hand argument).
Assignment Operators:

OperatorShorthandExpressionDescription
+=x+=yx = x + yAdds 2 numbers and assigns the result to left operand.
-=x-= yx = x -ySubtracts 2 numbers and assigns the result to left operand.
*=x*= yx = x*yMultiplies 2 numbers and assigns the result to left operand.
/=x/= yx = x/yDivides 2 numbers and assigns the result to left operand.
%=x%= yx = x%yComputes the modulus of 2 numbers and assigns the result to left operand.
**=x**=yx = x**yPerforms exponential (power) calculation on operators and assign value to the equivalent to left operand.
//=x//=yx = x//yPerforms floor division on operators and assign value to the left operand
Logical Operators:
OperatorExampleResult
and(x and y)is True if both x and y are true.
or(x or y)is True if either x or y is true.
not(x not y)If a condition is true then Logical not operator will make false.
Membership Operators:

OperatorDescriptionExample
inIt returns true if it finds a variable in the sequence otherwise returns falseList = [1,2,3,4,5,6,7,8];i=1;If(i in List):print (‘i is available in list’)Else print (‘i is not available in list’)Output – i is available in list
not inIt returns true if it does not find a variable in the sequence otherwise returns falseList = [1,2,3,4,5,6,7,8];j=10;If(j not in List):print (‘j is not available in list’)Else print (‘j is available in list’)Output – j is not available in list
Identity Operators:
These operators are used to compare the memory address of two objects.
OperatorDescriptionExample
isIt returns true if both operand ‘s identity is same otherwise falseI = 20J = 20If(I is J):print ‘I and J have same identity’Elserint ‘I and J have not same identity’Output – I and J have same identity
is notIt returns true if both operand ‘s identity is not same otherwise falseI = 20J = 230If(I is not J):print (‘I and J have not same identity’)Else print (‘I and J have same identity’)Output – I and J have not same identity
Bitwise Operators:

OperatorShorthandExpressionDescription
&Andx & yBits that are set in both x and y are set.
|Orx | yBits that are set in either x or y are set.
^Xorx ^ yBits that are set in x or y but not both are set.
~Not~xBits that are set in x are not set, and vice versa.
<<Shift leftx <<yShift the bits of x, y steps to the left
>>Shift rightx >>yShift the bits of x, y steps to the right.
Operator Precedence:
Highest precedence at top, lowest at bottom.
OperatorDescription
( )Parentheses
x[index],x[index1:index2],f(arg...),x.attributeSubscription, slicing, call, attribute reference
**Exponentiation
+x, -x, ~xPositive, negative, bitwise NOT
*, /, %Multiplication, division, remainder
+, -Addition and subtraction
<<, >>Shifts
&Bitwise AND
^Bitwise XOR
|Bitwise OR
in, not in, is, is not, <, <=, >, >=, !=, ==Comparisons, including membership tests and identity tests
not xBoolean NOT
andBoolean AND
orBoolean OR
if - elseConditional expression
lambdaLambda expression
Operators which all have same precedence and chain evaluates from left to right except for comparisons and exponentiation. Comparisons can be chained arbitrarily.





Tuesday, 19 December 2017

Python Exception Handling


Exception handling in pyhton:An exception is an error that happens during execution of a program. When thaterror occurs, Python generate an exception that can be handled, which avoids your
program to crash.
why we use excepitons:Exceptions are convenient in many ways for handling errors and special conditionsin a program. When you think that you have a code which can produce an error then you can use exception handling.
Raising an Exception :You can raise an exception in your own program by using the raise exception statement.Raising an exception breaks current code execution and returns the exception back until it is handled.
In Python programming, exceptions are raised when corresponding errors occur at run time, but we can forcefully raise it using the keyword raise.

Catching Exceptions in Python:

Exception are handled by using try and except keyword.A critical operation which can raise exception is placed inside the try clause and the code that handles exception is written in except clause.A try clause can have any number of except clause to handle them differently but only one will be executed in case an exception occurs.

Ex: try:
   # do something
   pass

except ValueError:
   # handle ValueError exception
   pass

except (TypeError, ZeroDivisionError):
   # handle multiple exceptions
   # TypeError and ZeroDivisionError
   pass

except:
   # handle all other exceptions
   pass






How To Raise An Exception And Provide Arguments?

We can forcefully raise an exception using the raise keyword. We can also optionally pass values to the exception and specify why this exception should occur. Here is the syntax for calling the “raise” method.
syntax:raise [Exception [, args [, traceback]]]
i)The exception is the name of the exception.
ii)The “args” is optional and represents the value of the exception argument.
iii)The final argument, traceback, is also optional and if present, is the traceback object used for the exception.
To trigger exceptions you need to code raise statements. Their general form is simple: the keyword raise followed by the name of the exception to be raised. You can also pass an extra data item (an object) along with the exception by listing it after the exception name. 












Saturday, 16 December 2017

GraspTechnology: Python basics

GraspTechnology: Python basics: Python Identifiers Identifier is the name given to entities like class, functions, variables etc. in Python. It helps differentiating o...

Friday, 1 December 2017

Python Functions

Functions : In Python, function is a group of related statements that perform a specific task.Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable

Functions in Python are used to utilize the code in more than one place in a program, sometimes also called method or procedures. Python provides you many inbuilt functions like print(), but it also gives freedom to create your own functions.


How to define and call a function in Python:

function in Python is defined by the "def " statement followed by the function name and parentheses ( () )


def function_name(parameters):

"""docstring"""

statement(s)

Above shown is a function definition which consists of following components.
  1. Keyword def marks the start of function header.
  2. A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.
Ex:def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")

Function Call

Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.
Ex : greet('pyhton programming')

Significance of Indentation (Space) in Python

Before we get familiarize with Python functions, it is important that we understand the indentation rule to declare Python functions and these rules are applicable to other elements of Python as well like declaring conditions, loops or variable.
Python follows a particular style of indentation to define the code, since Python functions don't have any explicit begin or end like curly braces to indicate the start and stop for the function, they have to rely on this indentation. Here we take a simple example with "print" command. When we write "print" function right below the def func 1 (): It will show an "indentation error: expected an indented block".
Python Functions Tutorial - Define, Call, Indentation & Arguments
Now, when you add the indent (space) in front of "print" function, it should print as expected.
Python Functions Tutorial - Define, Call, Indentation & Arguments
At least, one indent is enough to make your code work successfully. But as a best practice it is advisable to leave about 3-4 indent to call your function.

The return statement

The return statement is used to exit a function and go back to the place from where it was called.
syntax: return expression
This statement can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.
Ex:print(greet("May"))
Hello, May. Good morning!
output:None

Arguments in Functions

The argument is a value that is passed to the function when it's called.In other words on the calling side, it is an argument and on the function side it is a parameter.
Step 1) Arguments are declared in the function definition. While calling the function, you can pass the values for that args as shown below
Python Functions Tutorial - Define, Call, Indentation & Arguments
Step 2) To declare a default value of an argument, assign it a value at function definition.
Python Functions Tutorial - Define, Call, Indentation & Arguments
Example: x has no default values. Default values of y=0. When we supply only one argument while calling multiply function, Python assigns the supplied value to x while keeping the value of y=0. Hence the multiply of x*y=0
Python Functions Tutorial - Define, Call, Indentation & Arguments
Step 3) This time we will change the value to y=2 instead of the default value y=0, and it will return the output as (4x2)=8.
Python Functions Tutorial - Define, Call, Indentation & Arguments
Step 4) You can also change the order in which the arguments can be passed in Python. Here we have reversed the order of the value x and y to x=4 and y=2.
Python Functions Tutorial - Define, Call, Indentation & Arguments
Step 5) Multiple Arguments can also be passed as an array. Here in the example we call the multiple args (1,2,3,4,5) by calling the (*args) function.
Example: We declared multiple args as number (1,2,3,4,5) when we call the (*args) function; it prints out the output as (1,2,3,4,5)
Python Functions Tutorial - Define, Call, Indentation & Arguments

Scope and Lifetime of variables

Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope.Lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls.
Ex:def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)

Variable Function Arguments::

Python Default Arguments
Function arguments can have default values in Python.

We can provide a default value to an argument by using the assignment operator (=).
def greet(name, msg = "Good morning!"):
   """
   This function greets to
   the person with the
   provided message.

   If message is not provided,
   it defaults to "Good
   morning!"
   """

   print("Hello",name + ', ' + msg)

greet("Kate")
greet("Bruce","How do you do?")

Note:: Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.

Python keyword arguments:

Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed. Following calls to the above function are all valid and produce the same result.

Python recursion:

Recursion is the process of defining something in terms of itself.A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
Ex: def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)
print factorial(3)

Limitations of recursions::


Everytime a function calls itself and stores some memory. Thus, a recursive function could hold much more memory than a traditional function. Python stops the function calls after a depth of 1000 calls. If you run this example:
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)


print factorial(3000)

you will get error: RuntimeError: maximum recursion depth exceeded.


In other programming languages, your program could simply crash. You can resolve this by modifying the number of recursion calls such as:

import sys

sys.setrecursionlimit(5000)

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)


print factorial(3000)

Anonymous/Lambda functions:
In Python, anonymous function is a function that is defined without a name.While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword.
anonymous functions are also called lambda functions.

Lambda Functions ::A lambda function has the following syntax.

Syntax of Lambda Function ::
lambda arguments: expression

Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.

The lambda's general form is :

lambda arg1, arg2, ...argN : expression using arguments

Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs. However, there are a few differences that make lambda useful in specialized roles:

lambda is an expression, not a statement.
Because of this, a lambda can appear in places a def is not allowed. For example, places like inside a list literal, or a function call's arguments. As an expression, lambda returns a value that can optionally be assigned a name. In contrast, the def statement always assigns the new function to the name in the header, instead of returning is as a result.
lambda's body is a single expression, not a block of statements.

The lambda's body is similar to what we'd put in a def body's return statement. We simply type the result as an expression instead of explicitly returning it. Because it is limited to an expression, a lambda is less general that a def. We can only squeeze design, to limit program nesting. lambda is designed for coding simple functions, and def handles larger tasks.

double = lambda x: x * 2

# Output: 10

print(double(5))

2) my_list = [1, 5, 4, 6, 8, 11, 3, 12]


new_list = list(filter(lambda x: (x%2 == 0) , my_list))


# Output: [4, 6, 8, 12]


print(new_list)

3) f = lambda x, y, z: x + y + z
 f(2, 30, 400)
output:432

4) mz = (lambda a = 'Wolfgangus', b = ' Theophilus', c = ' Mozart' : a + b + c)
 mz('Wolfgang', ' Amadeus')
'Wolfgang Amadeus Mozart'


5)L = [lambda x: x ** 2,
         lambda x: x ** 3,
         lambda x: x ** 4]
for f in L:
print(f(3))

output:9
27
81

*args: In Python, the single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions. It is worth noting that the asterisk (*) is the important element here, as the word args is the established conventional idiom, though it is not enforced by the language.

We may want to use *args when we're not sure how many arguments might be passed to our function, i.e. it allows us to pass an arbitrary number of arguments to our function.


**kwargs  ::The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks (**) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.

The ** is similar but it only works for keyword arguments. In other words, it collects them into a new dictionary. Actually, ** allows us to convert from keywords to dictionaries.


ike *args**kwargs can take however many arguments you would like to supply to it. However, **kwargs differs from *args in that you will need to assign keywords.

Ordering Arguments:
When ordering arguments within a function or function call, arguments need to occur in a particular order:

1)Formal positional arguments
2)*args
3)Keyword arguments
4) **kwargs
when working with explicit positional parameters along with *args and **kwargs, your function would look like this:
def example(arg_1, arg_2, *args, **kwargs):
And, when working with positional parameters along with named keyword parameters in addition to *args and **kwargs, your function would look like this:

def example2(arg_1, arg_2, *args, kw_1="shark", kw_2="blobfish", **kwargs):