2016年8月31日 星期三

[Scala IA] The Basics : Ch3. OOP in Scala - Modifiers

Modifiers (p86) 
You’ve already seen a few modifiers in action, but let’s look deeper into them. Along with standard modifiers like private and protected, Scala has more modifiers and new abilities. 

The private modifier can be used with any definition, which means it’s only accessible in an enclosed class, its companion object, or a companion class. In Scala, you can qualify a modifier with a class or a package name. In the following example, the private modifier is qualified by class and package name: 
  1. package outerpkg.innerpkg  
  2.   
  3. class Outer {  
  4.     class Inner {  
  5.         private[Outer] def f() = "This is f"  
  6.         private[innerpkg] def g() = "This is g"  
  7.         private[outerpkg] def h() = "This is h"  
  8.     }  
  9. }  
Here, access to the f method can appear anywhere within the Outer class, but not outside it. The method g is accessible anywhere within outerpkg.innerpkg. It’s like the package private in Java. You could use it to make your methods available for unit tests in the same package. Because the h method is qualified with outerpkg, it can appear anywhere within outerpkg and its subpackages. Scala also lets you qualify the private modifier with thisprivate[this]. In this case, it means object private. And object private is only accessible to the object in which it’s defined. When members are marked with private without a qualifier, they’re called class-private

The protected modifier is applicable to class member definitions. It’s accessible to the defining class and its subclasses. It’s also accessible to a companion object of the defining class and companion objects of all the subclasses. Like the private modifier, you can also qualify the protected modifier with class, package, and this. By default, when you don’t specify any modifier, everything is public. Scala doesn’t provide any modifier to mark members as public

Like Java, Scala also provides an override modifier, but the main difference is that in Scala the override modifier is mandatory when you override a concrete member definition from the parent class. The overridemodifier can be combined with an abstract modifier, and the combination is allowed only for members of traits. This modifier means that the member in question must be mixed with a class that provides the concrete implementation. An example will demonstrate this fact. The following creates a DogMood trait (dogs are moody, you know) with an abstract greet method and an AngryMood trait that overrides it: 
  1. trait DogMood{  
  2.     def greet  
  3. }  
  4.   
  5. trait AngryMood extends DogMood {  
  6.     override def greet = {  
  7.         println("bark")  
  8.         super.greet  
  9.     }  
  10. }  
The problem with this code is the super.greet line. You can’t invoke the super greet method because it’s abstract. But super calls are important if you want your trait to be stackable so that it can get mixed in with other traits. In cases like this, you can mark the method with abstract override, which means it should be mixed in with some class that has the concrete definition of the greet method. To make this code compile, you have to add abstract along withoverride, as in the following: 
  1. trait AngryMood extends DogMood {  
  2.     abstract override def greet = {  
  3.         println("bark")  
  4.         super.greet  
  5.     }  
  6. }  
So you can use above design as below: 
  1. trait DogMood{  
  2.     def greet  
  3. }  
  4.   
  5.   
  6. trait AngryMood extends DogMood {  
  7.     abstract override def greet = {  
  8.         printf("Bark ~~ ")  
  9.         super.greet  
  10.     }  
  11. }  
  12.   
  13. class ADog extends DogMood{  
  14.     override def greet = { println("Wow---") }  
  15. }  
  16.   
  17. class BDog extends ADog with AngryMood  
  18.   
  19.   
  20. val bdog = new BDog()  
  21. bdog.greet   // Bark ~~ Wow---  
Scala has introduced a new modifier called sealed, which applies only to class definitions. It’s a little different from the final modifier; classes marked final in Scala can’t be overridden by subclasses. But classes marked sealed can be overridden as long as the subclasses belong to the same source file. You used sealed in a previous section when you created QueryOption case classes: 
  1. sealed trait QueryOption  
This is a common pattern when you want to create a defined set of subclasses but don’t want others to subclass it. 

Supplement 
Scala's Stackable Trait Pattern

[ Python 常見問題 ] Python exception handling - line number

Source From Here
Question
I'm using python to evaluate some measured data. Because of many possible results it is difficult to handle or possible combinations. Sometimes an error happens during the evaluation. It is usually an index error because I get out of range from measured data. It is very difficult to find out on which place in code the problem happened. It would help a lot if I knew on which line the error was raised. If I use following code:
  1. try:  
  2.     result = evaluateData(data)  
  3. except Exception, err:  
  4.     print ("Error: %s.\n" % str(err))  
Unfortunately this only tells me that there is and index error. I would like to know more details about the exception (line in code, variable etc.) to find out what happened. Is it possible?

How-To
Solution, printing filename, linenumber, line itself and exception descrition:
  1. import linecache  
  2. import sys  
  3.   
  4. def PrintException():  
  5.     # This function returns a tuple of three values that give information about the exception that is currently being handled.   
  6.     # More: https://docs.python.org/2/library/sys.html#sys.exc_info  
  7.     exc_type, exc_obj, tb = sys.exc_info()  
  8.     f = tb.tb_frame  
  9.     # This function returns the current line number set in the traceback object.  
  10.     lineno = tb.tb_lineno  
  11.     filename = f.f_code.co_filename  
  12.     linecache.checkcache(filename)  
  13.     line = linecache.getline(filename, lineno, f.f_globals)  
  14.     print 'EXCEPTION IN ({0}, LINE {1} "{2}"): {3}'.format(filename, lineno, line.strip(), exc_obj)  
  15.   
  16.   
  17. try:  
  18.     print 1/0  
  19. except:  
  20.     PrintException()  
Execution Result:
EXCEPTION IN (a.py, LINE 15 "print 1/0"): integer division or modulo by zero

Supplement
Python package - linecache — Random access to text lines
The linecache module allows one to get any line from any file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file. This is used by the traceback module to retrieve source lines for inclusion in the formatted traceback.

Python package - traceback — Print or retrieve a stack traceback
This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter.


2016年8月28日 星期日

[Scala IA] The Basics : Ch3. OOP in Scala - Named and default arguments and copy constructors

Named and default arguments and copy constructors (p83) 
Scala lets you specify method arguments using a named style. When you have methods or class constructors taking similar types of arguments, it becomes difficult to detect errors if you swap them by mistake. Let’s take the example of Person again. Instead of passing in an order of first name, last name, if we swap the order, Scala won’t complain: 
scala> case class Person(firstName:String, lastName:String)
defined class Person

scala> val p = Person("lastName", "firstName")
p: Person = Person(lastName,firstName)

Unfortunately, both parameters are of the same type, and the compiler can’t detect the mistake at compile time. But now, using named style arguments, you can avoid the problem: 
scala> val p = Person(lastName = "lastName", firstName = "firstName")
p: Person = Person(firstName,lastName)

The named arguments use the same syntax as a variable assignment, and when you use named arguments, the order doesn’t matter. You can mix the named arguments with positional arguments, but that’s usually a bad idea. When going for named arguments, always try to use a named style for all the arguments. The following example uses a named style for the first argument but not for the second. As mentioned earlier, it’s good practice to avoid this: 
scala> val p = Person(firstName = "firstName", "lastName")
p: Person = Person(firstName,lastName)

When using a named style, if the parameter name doesn’t match, the Scala compiler will complain about the value not being found. But when you override a method from a superclass, the parameters’ names don’t have to match the names in the superclass method. In this case, the static type of the method determines which names have to be used. Consider this example, where you have the Person trait and SalesPerson overriding the grade method and changing the parameter name in the process from years to yrs
scala> trait Person { def grade(years:Int): String }
defined trait Person
warning: previously defined object Person is not a companion to trait Person.
Companions must be defined together; you may wish to use :paste mode for this.


scala> class SalesPerson extends Person { def grade(yrs:Int) = "Senior" }
defined class SalesPerson

scala> val s = new SalesPerson
s: SalesPerson = SalesPerson@51776d39

scala> s.grade(yrs = 1)
res1: String = Senior

scala> s.grade(years = 1)
:15: error: not found: value years

Here years won’t work because the type of the s instance is SalesPerson. If you force the type variable to Person, then you can use years as a named argument. I know this is a little tricky to remember, so watch out for errors like this: 
scala> val s:Person = new SalesPerson
s: Person = SalesPerson@6514451b

scala> s.grade(years = 1)
res3: String = Senior

scala> s.grade(yrs = 1) // Currently variable s is as pointer of Person
:15: error: not found: value yrs

The value of the named argument could be an expression like a method or block of code, and every time the method is called, the expression is evaluated: 
scala> s.grade(years = {val x = 10; x + 1})
res4: String = Senior

The complementing feature to named arguments is default arguments. You’ve already seen one example of a default argument in the query example, where the last argument of the case class defaulted to NoOption
  1. case class Query(q: DBObject, option: QueryOption = NoOption) {  
  2.     def sort(sorting: DBObject) = Query(q, Sort(sorting, option))  
  3.     def skip(skip: Int) = Query(q, Skip(skip, option))  
  4.     def limit(limit: Int) = Query(q, Limit(limit, option))  
  5. }  
The default argument has the form argType = expression, and the expression part is evaluated every time the method uses the default parameter. If you create a Query instance using Skip, the default won’t be used: 
  1. val skipOption = Skip (10, NoOption)  
  2. val newQuery = Query(new BasicDBObject(), skipOption)  
One of the interesting uses of default arguments in Scala is in the copy method of case classes. Starting from Scala 2.8 on, along with the usual goodies, every case class has an additional method called copy to create a modified instance of the class. This method isn’t generated if any member exists with the same name in the class or in one of its parent classes. The following example uses the copy method to create another instance of the skipquery option, but with a Limit option instead of NoOption
scala> val skipOption = Skip(10, NoOption)
skipOption: Skip = Skip(10,NoOption())

scala> val skipWithLimit = skipOption.copy(anotherOption = Limit(10, NoOption))
skipWithLimit: Skip = Skip(10,Limit(10,NoOption))

The copy method is using a named argument to specify the parameter that you’d like to change. The copy method generated by the Scala compiler for the Skip case class looks like the following: 
  1. case class Skip(number: Int, anotherOption: QueryOption) extends QueryOption {  
  2.     def copy(number: Int = number, anotherOption: QueryOption = anotherOption) = {  
  3.         Skip(number, anotherOption)  
  4.     }  
  5. }  
As you can see, in the generated method all the parameters are defaulted to the value provided to the constructor of the class, and you can pick and choose the parameter value you want to change during the copy. If no parameters are specified, copy will create another instance with the same values: 
scala> Skip(10, NoOption) == Skip(10, NoOption).copy()
res22: Boolean = true

In Scala, invoking the == method is the same as calling the equals method. The == method is defined in the scala.Any class, which is the parent class for all classes in Scala.

[ Py DS ] Ch3 - Data Manipulation with Pandas (Part5)

Source From  Here   Pivot Tables   We have seen how the  GroupBy  abstraction lets us explore relationships within a dataset. A pivot ta...