Summary for book "Die OSGI Service Platform-Eine Einführung mit Eclipse Equinox" link
The book is a good introduction to OSGi. It has 24 chapters, from OSGi introduction to OSGi and Equinox Standard Services. The book is divided in three part: part one: OSGi Framework, part two: OSGi Standard Services, part three: Equinox Services(Extensions)
Following chapters are discused in first part:
Bundles, Bundles lifcycles, Packages dependencies, OSGi Services, dynamic Services, Fragment Bundles, Security, Management of OSGi Service Platform, Packaging and Deployment
this blog summary the summary of the book:
* how to install Eclipse PDE (download eclipse-equinox-SDK-3.xxxx.zip)
* describe how OSGi work: bundles, layers, lifecycles, deployment, services, avaiable implementations(felix, equinox), example to start a http game services.
* Bundle Manifest have descriptive information about bundles, the manifest will be readed and interpreted by OSGi platform.
* Bundle-Classpath have locale paths
* Bundle-Activator is the start and stop point of a bundle with org.osgi.framework.BundleActivator
* BundleContext (parameter on start()/stop()), allow access to OSGi framework. Through context you can install new bundles, register listener, register and ask for services.
* Equinox console is a simpler Management Agent. You can ask for state of bundles and OSGi environment. A bundle has different states (installed, uninstalled, running, stoped)
* Activator Policies can change the behavior of bundles starts. (time, sequence, ressources). Lazy Activator set the bundle only start if other required him.
* It exists change of states with code too. (not only manifest-file)
* Bundle listener can notify you about state changes. Listener are registered with BundleContext.
* Bundle Cache save the states for persistence beyound the start()/stop() borders.
* For using other bundles you must explizit import/export you bundles in manifest-file.
* That is done with Export-Package and Import-Package labels.
* Required-Bundle specific the whole bundle. Import-Package only classes/packages. '*' import all class in a package.
* With Versioning you can specify which version of a same bundle the other bundle should use.
* With DynamicImport-Package you can import packages which doesn't exists yet.
* OSGi services are simple java objects (POJO Plain Old Java Objects). The services are registered to Service Registry with theirs class names. The services could quered by other bundles.
* The access to Services happen with ServiceReference and BundleContext
* On registry you can send some properties (which is a simple hash map)
* To get a reference: BundleContext.getServiceReferences() and the class name of service. Then you can use filter.
* With start leveln you can affect the start sequence of bundles.
* Sercice Tracker help you to work with one interface, independent from runtime/lifecycle. Tracker help dynamic react to services in/outgoing.
* ServiceTrackerCustomizer help you to react to different changes with call-back methods.
* Central OSGi Service Registry is the Whiteboard-Pattern and allow simple way the traditional listener-patern to replace.
* Fragments bundles expand the classpath of others bundles ( to avoid overloading of code/info for one bundle). It is a simple way to divide logic part from presentation(templates, languages).
* Fragmenst have no lifecycles (no Activators). manifest: Fragment-Host
* The Import/Export/Requirement information from Fragment Bundle will transfer to Host Bundle (which use the Fragment Bundle)
* Extension Bundles you can change the boot-classpath and expand it with additional features.
* Security in OSGi: local access can be setted to avoid execution in OSGI-INF/permissions.perm
* You can run only signed bundles or with certificates
* Conditional Permission Admin Service asign global authorization (Conditions)
* Management Agent implement an access to OSGi framework. For administrate framework from outside.
* It can be done by shell. or with programmatic.
* You can code your own commands with implement a CommandProvider with org.eclipse.osgi.framework.console.CommandProvider and register it to OSGi Service Registry.
* Plug-in Export Wizard is a simple facility to build bundles for extern world (and not only work with eclipse)
* For automatic build: ant4eclipse, Maven
* To start Eclipse Equinox: use org.eclipse.osgi_version.jar. Or start org.eclipse.core.runtime.adapptor.EclipseStarter from an Java application.
* With System properties or config.ini you can manipulate Equinox
all about go, ruby, python, perl, java, scala, osgi, RCP computing, network, hacking, security, encryption. and other interesting stuff
Mittwoch, 14. Oktober 2009
Dienstag, 13. Oktober 2009
Sonntag, 11. Oktober 2009
Python stuff
functions numbers
int(), long8), float(), round(), hex(), oct(), pow(), cmp()
s1+s2 merge
s1*n s1+s1+s1+s1+...
functions strings:
org(), chr(), str(), repr(), unicode(), len()
s.count(), s.encode(), s.endswith(), s.find(), s.isalnum(), s.iksalpha(), s.isdigi(), s.islower(), s.isspace(), s.join(), s.lstrip(), s.replace(), s.rfind(), s.rstrip(), s.split(), s.startswith(), s.strip(), s.swapcase()
List:
array=[1,2,3,4]
len(array)
array[1]="blub"
array[2]=["bla", [1,2,3], 'ups']
append(), extend(), count(), index(), insert(), remove(), pop(), reverse(), sort()
range()
range(4)
[0,1,2,3]
range(5,10,2]
[5,7,9]
Tuples
same as list but imutable
t1=(1,2,3)
indicies and slices
s[4:]
s[4:7]
s[:-7]
s[-4:]
s[:]
max(), min(), len()
a,b,c = [ 1, 2, 3 ]
del delete a varaible
a= 1
del a
assoziative lists, hash
h = { k:v, k2:v2, k3:v3 }
t={"peter":23450, "anna":39454, "blub":439549}
t["blub"]
items(), keys(), values(), has_key(), update()
t.has_key("anna")
len(), del()
None, type(), in-operator
if 2 in lists:
...
if not "a" in string:
...
Functions:
def p(n):
"bla bla, describe function for help"
for a in range(2,n):
...
p(3)
def fct(a, b="bla"):
...
fct(3, "lala")
fct(3)
several arguments with *
def h(g, *args):
for m in args:
...
h("bl", "blub", "abc", "dbc")
def h(**args):
if len(args==0): return
for n in args.keys():
print args[n]+" : "+ n
h(v1="blub", v2="aga")
def complexparameters(firma, delim="-", *address, **inventars):
def doNothing():
pass
functionale coding
add = lambda x,y: x+y
add(2,3)
map(ord, "string")
[115,116,114,...]
[ord(a) for a in "string"]
map(lambda x:x+1,(1,2,3))
map for tuple (1,2,3) x+1
def p(n):
for a in range(2,n):
if n%a == 0:
return 0
else:
return 1
filter(p, range(100))
reduce(function, collection)
a=5
exec("var" +str(a)+"="+str(a))
=> var5=5
docstrings:
def bla():
""" blal bla"""
...
bla.__doc__
Modules
int(), long8), float(), round(), hex(), oct(), pow(), cmp()
s1+s2 merge
s1*n s1+s1+s1+s1+...
functions strings:
org(), chr(), str(), repr(), unicode(), len()
s.count(), s.encode(), s.endswith(), s.find(), s.isalnum(), s.iksalpha(), s.isdigi(), s.islower(), s.isspace(), s.join(), s.lstrip(), s.replace(), s.rfind(), s.rstrip(), s.split(), s.startswith(), s.strip(), s.swapcase()
List:
array=[1,2,3,4]
len(array)
array[1]="blub"
array[2]=["bla", [1,2,3], 'ups']
append(), extend(), count(), index(), insert(), remove(), pop(), reverse(), sort()
range()
range(4)
[0,1,2,3]
range(5,10,2]
[5,7,9]
Tuples
same as list but imutable
t1=(1,2,3)
indicies and slices
s[4:]
s[4:7]
s[:-7]
s[-4:]
s[:]
max(), min(), len()
a,b,c = [ 1, 2, 3 ]
del delete a varaible
a= 1
del a
assoziative lists, hash
h = { k:v, k2:v2, k3:v3 }
t={"peter":23450, "anna":39454, "blub":439549}
t["blub"]
items(), keys(), values(), has_key(), update()
t.has_key("anna")
len(), del()
None, type(), in-operator
if 2 in lists:
...
if not "a" in string:
...
Functions:
def p(n):
"bla bla, describe function for help"
for a in range(2,n):
...
p(3)
def fct(a, b="bla"):
...
fct(3, "lala")
fct(3)
several arguments with *
def h(g, *args):
for m in args:
...
h("bl", "blub", "abc", "dbc")
def h(**args):
if len(args==0): return
for n in args.keys():
print args[n]+" : "+ n
h(v1="blub", v2="aga")
def complexparameters(firma, delim="-", *address, **inventars):
def doNothing():
pass
functionale coding
add = lambda x,y: x+y
add(2,3)
map(ord, "string")
[115,116,114,...]
[ord(a) for a in "string"]
map(lambda x:x+1,(1,2,3))
map for tuple (1,2,3) x+1
def p(n):
for a in range(2,n):
if n%a == 0:
return 0
else:
return 1
filter(p, range(100))
reduce(function, collection)
a=5
exec("var" +str(a)+"="+str(a))
=> var5=5
docstrings:
def bla():
""" blal bla"""
...
bla.__doc__
Modules
JAVA stuff
read from input:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
int age = new Integer( br.readLine() ).intValue();
RUBY codes: code blocks and iterations
from "Ruby Cookbook" O'Reilly
for detailed information, look this book
Clousure:
Every Ruby block is also a closure.
the var celing is context depended.
Lambda and Proc
Yielding
for detailed information, look this book
[1,2,3].each { |i| puts i }
[1,2,3].each do |i|
if i%2 == 0
puts "="
else
puts "!"
end
end
1.upto 3 do |x| # same 1.upto(3)
1.upto(3) { |x| ... } # ok
1.upto 3 { |x| ... } # error
log = lambda { |str| puts "[LOG] #{str}" }
log.call("A test log message.")
{1=>2, 2=>4}.each { |k,v| puts "Key #{k}, value #{v}" }
def times_n(n)
lambda { |x| x * n }
end
times_ten = times_n(10)
times_ten.call(5) # => 50
circumference = times_n(2*Math::PI)
[1, 2, 3].collect(&circumference)
# => [6.28318530717959, 12.5663706143592, 18.8495559215388]
Clousure:
Every Ruby block is also a closure.
ceiling = 50
[1, 10, 49, 50.1, 200].select { |x| x < ceiling }
# => [1, 10, 49]
the var celing is context depended.
Lambda and Proc
block = { |x| puts x } # error
block = lambda { |x| puts x } # ok
block.call "bla bla!"
def my_lambda(&aBlock) # a block in function parameters
aBlock
end
b = my_lambda { puts "Hello World My Way!" }
b.call
b.class # => Proc
aBlock = Proc.new { |x| puts x }
aBlock = proc { |x| puts x }
aBlock = lambda { |x| puts x }
add_lambda = lambda { |x,y| x + y }
add_lambda.call(4,5,6) # ArgumentError: wrong number of arguments (3 for 2)
add_procnew = Proc.new { |x,y| x + y }
add_procnew.call(4,5,6) # => 9
Yielding
def myfunc
puts "1"
yield
puts "2"
yield
end
myfunc("3")
# 1
# 3
# 2
# 3
def repeat(n)
if block_given?
n.times { yield }
else
raise ArgumentError.new("I can't repeat a block you don't give me!")
end
end
repeat(4) { puts "Hello." }
# Hello.
# Hello.
# Hello.
# Hello.
repeat(4)
# ArgumentError: I can't repeat a block you don't give me!
Freitag, 9. Oktober 2009
read file in Scala
read file in scala:
list a directory
ask is file not a directory
simple print out of a file
read a file in an iterator
read a file in a string
or you can use Java API
for (file <- new File("/var/log/").listFiles) {
list a directory
if (!file.isDirectory) {
ask is file not a directory
simple print out of a file
import scala.io.Source
for {
(line) <- Source.fromFile("bla.txt").getLines
} print(line)
read a file in an iterator
scala> val lines = scala.io.Source.fromFile("/var/log/syslog")
lines: scala.io.Source = non-empty iterator
scala> lines
res5: scala.io.Source = non-empty iterator
read a file in a string
val lines = scala.io.Source.fromFile("/var/log/syslog").mkString
// for utf-8 encoding
val lines = scala.io.Source.fromFile("file.txt", "utf-8").getLines.mkString
or you can use Java API
val os = new BufferedOutputStream(new FileOutputStream("gen/" + file.getName))
Donnerstag, 8. Oktober 2009
Challenge: pattern syslog
Challenge:
filtern some patern in file /var/log/syslog
and print it out
Shell:
Java:
Scala:
Perl:
Ruby:
Python:
PHP:
C:
filtern some patern in file /var/log/syslog
and print it out
Shell:
fgrep usb /var/log/syslog
Java:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaFilters {
public static void main(String[] args) {
String path="/var/log/syslog";
try {
BufferedReader input = new BufferedReader(new FileReader(path));
String line;
try {
Pattern p = Pattern.compile("dhclient");
while (( line = input.readLine()) != null){
Matcher m = p.matcher(line);
if(m.find())
System.out.println("found:: "+line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Scala:
import scala.io.Source
import java.util.regex._
var p = Pattern.compile("usb")
for ( line <- Source.fromFile("/var/log/syslog").getLines ){
var m = p.matcher(line);
if( m.find )
print("found::" + line)
}
Perl:
#!/usr/bin/perl
open(IN, "/var/log/syslog") or die "canot open file: $!";
@lines = <IN>;
close IN;
foreach $line(@lines) {
if( $line =~ /dhclient/) {
print "found:: $line";
}
}
Ruby:
#!/usr/bin/ruby
file = File.new("/var/log/syslog", "r") or die "canot open file"
while (line = file.gets)
if ( line =~ /usb/ )
print "found:: "+line
end
end
Python:
#!/usr/bin/python
try:
f = open('/var/log/syslog', 'r')
for line in f.readlines():
if( "usb" in line ):
print("found:: %s"%line)
except:
print "error in file"
PHP:
<?php
$file = "/var/log/syslog";
if (file_exists($file)) {
$lines = file($file);
foreach ($lines as $line_num => $line)
if( preg_match("/usb/", $line) )
echo "$line";
}
?>
C:
#include
#include
#include
#include
#include
FILE *file = NULL;
int main(int argc, char **argv)
{
char line[1024];
int err;
char err_str[200];
char results[500];
regex_t preg;
regmatch_t pmatch[100];
if( (regcomp(&preg, argv[1], 0)) != 0) {
printf("regcomp error\n");
return -1;
}
if((file = fopen("/var/log/syslog", "r")) != NULL) {
while (!feof(file)){
fgets(line, 1024, file);
if( regexec(&preg, line, preg.re_nsub, pmatch, 0) == 0) {
printf("found:: %s", line);
}
}
}
regfree(&preg);
return 0;
}
Dienstag, 6. Oktober 2009
learning Scala 3
this tutorial based on:
http://www.artima.com/scalazine/articles/steps.html
def max(x: Int, y: Int) -> define a function, with 2 parameters (integer)
: Int -> return is integer.
if (x < y) y else x -> function body
greet save a Unit -> a function
create an array with 3 strings
important indexes are in brakes () not square brackets[]
http://www.artima.com/scalazine/articles/steps.html
def max(x: Int, y: Int): Int = if (x < y) y else x
def max(x: Int, y: Int) -> define a function, with 2 parameters (integer)
: Int -> return is integer.
if (x < y) y else x -> function body
scala> def greet() = println("Hello, world!")
greet: ()Unit
scala> greet()
Hello, world!
scala> greet
Hello, world!
greet save a Unit -> a function
args.foreach(arg => println(arg))
args.foreach((arg: String) => println(arg))
args.foreach(println)
for (arg <- args)
println(arg)
scala> for (i <- 0 to 5)
| println(i)
0
1
2
3
4
5
val greetStrings: Array[String] = new Array[String](3)
create an array with 3 strings
greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!\n"
important indexes are in brakes () not square brackets[]
for (i <- 0 to 2)
print(greetStrings(i))
learning Scala 2
this tutorial based on:
http://www.thomasknierim.com/104/scala/scala-tutorial-1/
http://www.thomasknierim.com/104/scala/scala-tutorial-2/
http://www.thomasknierim.com/104/scala/scala-tutorial-3/
for(val arg: String <- args) -> an array into each arg as String
similar: args.foreach(arg => println("Hello" + arg + "!"))
"=>" that can be read “with a given argument this do that”
args.foreach(println)
(x: Int) => x - 1 -> anonymous function declaration
var decrease = (x: Int) => x – something
something is not defined yet. decrease is depend on context -> clousure
In terms of computer science, a closure is a function that is evaluated and whose result depend on an outer context.
something = 10
decrease(100)
some examples for higher-order functions
List("alpha", "beta", "crash") -> create a list
map() -> map each list element to some condition/function
p => p.substring(0,1) p is the element p.substring(0,1) is the function
_ -> ist the element (similar to perl $_ )
(_*2) is equivalent to (i => i * 2)
let look:
new java.io.File(".") use the java api and create a file object File.
listFiles is the same as listFiles() in java. in scala you don't need brakes.
for (file <- filesHere; if matcher(file.getName))
yield file
iterate all filesHere (files in path "."). if name match to query, yield the file. the file get in an array.
define different functions
filesMatching(matcher: String => Boolean)
define the function with a matcher(String) which return Boolean
http://www.thomasknierim.com/104/scala/scala-tutorial-1/
http://www.thomasknierim.com/104/scala/scala-tutorial-2/
http://www.thomasknierim.com/104/scala/scala-tutorial-3/
object Hello {
def main(args: Array[String]) {
for(val arg: String <- args)
System.out.println("Hello, " + arg + "!");
}
}
for(val arg: String <- args) -> an array into each arg as String
similar: args.foreach(arg => println("Hello" + arg + "!"))
"=>" that can be read “with a given argument this do that”
args.foreach(println)
var decrease = (x: Int) => x - 1
decrease(11)
(x: Int) => x - 1 -> anonymous function declaration
var decrease = (x: Int) => x – something
something is not defined yet. decrease is depend on context -> clousure
In terms of computer science, a closure is a function that is evaluated and whose result depend on an outer context.
something = 10
decrease(100)
some examples for higher-order functions
scala> List("alpha", "beta", "crash").map(
p => p.substring(0,1))
res0: List[java.lang.String] = List(a, b, c)
scala> List(1, 2, 3) map (_ * 2)
res1: List[Int] = List(2, 4, 6)
scala> List("Tango", "Mango", "Bobo", "Gogo")
map (_.endsWith("go"))
res2: List[Boolean] = List(true, true, false, true)
List("alpha", "beta", "crash") -> create a list
map() -> map each list element to some condition/function
p => p.substring(0,1) p is the element p.substring(0,1) is the function
_ -> ist the element (similar to perl $_ )
(_*2) is equivalent to (i => i * 2)
object FileMatcher {
private val filesHere=(new java.io.File(".")).listFiles
private def filesMatching(matcher: String => Boolean)=
for (file <- filesHere; if matcher(file.getName))
yield file
def filesEnding(query: String)=
filesMatching(_.endsWith(query))
def filesContaining(query: String)=
filesMatching(_.contains(query))
def filesRegex(query: String)=
filesMatching(_.matches(query))
}
object Main {
def main(args: Array[String]) {
val query = args(0);
var matchingFiles = FileMatcher.filesEnding(query)
matchingFiles = FileMatcher.filesContaining(query)
matchingFiles = FileMatcher.filesRegex(query)
}
}
let look:
scala> (new java.io.File(".")).listFiles
res2: Array[java.io.File] = Array(./FrenchDate$.class, ./FrenchDate.class, ./Complex.scala, ./s1.class, ./s1$.class, ./FrenchDate.scala, ./Timer$$anonfun$main$1.class, ./s1.scala, ./Timer$.class, ./Hello.class, ./ComplexNumbers.class, ./Hello.scala, ./Hello$$anonfun$main$1.class, ./blog_scala2.txt, ./Timer.class, ./Hello$.class, ./Complex.class, ./blog_scala1.txt, ./ComplexNumbers.sca...
new java.io.File(".") use the java api and create a file object File.
listFiles is the same as listFiles() in java. in scala you don't need brakes.
for (file <- filesHere; if matcher(file.getName))
yield file
iterate all filesHere (files in path "."). if name match to query, yield the file. the file get in an array.
scala> var matchingFiles = FileMatcher.filesEnding(query)
matchingFiles: Array[java.io.File] = Array(./Complex.scala, ./FrenchDate.scala, ./s1.scala, ./Hello.scala, ./Main.scala, ./ComplexNumbers.scala, ./Timer.scala)
def filesEnding(query: String)=
filesMatching(_.endsWith(query))
define different functions
filesMatching(matcher: String => Boolean)
define the function with a matcher(String) which return Boolean
learning Scala
This tutorial based on:
http://www.scala-lang.org/docu/files/ScalaTutorial.pdf
http://www.thomasknierim.com/77/scala/scala-tutorial-2/
write a file s1.scala
object -> declare a static singleton object
args: Array[String] -> a variable args as Array of Strings
compile and execute
you get created standard java class files, but you must use java interpreter with setted parameters.
As you can see, the scala executable is a simple shell script, which start the java virtual machine with specific parameters and the scala library.
Create Date.scala
In scala is everything an object. There is no primitive datatypes (that is similar to ruby).
Because scala based on functional programming functions are objects too.
with functions as object you can very simple code a callback.
rather the function timeFlies() you can use anonymous functions ala:
oncePerSecond(() => println("time flies like an arrow..."))
"() => code" declare an anonymous function
Clases:
define class Complex with two arguments,
def re() and im() are getters. return type of these two methods is not given explicitly
if you have no arguments in function, write: def re = real
class Complex(real: Double, imaginary: Double) -> primary constructor, which is part of the class declaration
override -> for overriding functions
(if (im < 0) "" else "+") have you see it ;)
require(denominator != 0) -> look that variable is not null, throw exception
def this(n: Int) = this(n, 1) -> create from Rational(2) -> Rational(2,1)
you can see +-*/ are objects functions, which can be simple overrided
http://www.scala-lang.org/docu/files/ScalaTutorial.pdf
http://www.thomasknierim.com/77/scala/scala-tutorial-2/
write a file s1.scala
object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}
object -> declare a static singleton object
args: Array[String] -> a variable args as Array of Strings
compile and execute
$ scalac s1.scala
$ ls
s1.class s1$.class s1.scala
you get created standard java class files, but you must use java interpreter with setted parameters.
$ java s1
Exception in thread "main" java.lang.NoClassDefFoundError: scala/ScalaObject
at java.lang.ClassLoader.defineClass1(Native Method)
....
$ file /usr/bin/scala
$ /usr/bin/scala: POSIX shell script text executable
$ cat /usr/bin/scala
#!/bin/sh
JAVA_DIR=/usr/share/java
LIB_CLASSPATH=$JAVA_DIR/scala-library.jar:$JAVA_DIR/scala-compiler.jar:$JAVA_DIR/jline.jar
exec ${JAVACMD:=java} ${JAVA_OPTS:=-Xmx256M -Xms16M} \
-Xbootclasspath/a:$LIB_CLASSPATH \
-classpath .:$CLASSPATH:$LIB_CLASSPATH \
scala.tools.nsc.MainGenericRunner \
"$@"
$ scala s1
hallo
As you can see, the scala executable is a simple shell script, which start the java virtual machine with specific parameters and the scala library.
Create Date.scala
import java.util.{Date, Locale}
import java.text.DateFormat
import java.text.DateFormat._
object FrenchDate {
def main(args: Array[String]) {
val now = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
println(df format now)
}
}
import java.util.{Date, Locale} | import Date and Locale from java.util |
import java.text.DateFormat._ | DateFormat._ is similar to DateFormat.* in java |
val | declare an inmutable variable |
val now = new Date | simmilar to "Date now = new Date();" in java |
println(df format now) | "df format now" is similar to "df.format(now)" |
In scala is everything an object. There is no primitive datatypes (that is similar to ruby).
Because scala based on functional programming functions are objects too.
object Timer {
def oncePerSecond(callback: () => Unit) {
while (true) { callback(); Thread sleep 1000 }
}
def timeFlies() {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies)
}
}
with functions as object you can very simple code a callback.
timeFlies() | our callback function. |
callback: () => Unit | parameter for a function. ()=>Unit is the type of all functions which take no arguments and return nothing. |
Thread sleep 1000 | is similar to Thread.sleep(1000) |
rather the function timeFlies() you can use anonymous functions ala:
oncePerSecond(() => println("time flies like an arrow..."))
"() => code" declare an anonymous function
Clases:
class Complex(real: Double, imaginary: Double) {
def re() = real
def im() = imaginary
}
define class Complex with two arguments,
def re() and im() are getters. return type of these two methods is not given explicitly
object ComplexNumbers {
def main(args: Array[String]) {
val c = new Complex(1.2, 3.4)
println("imaginary part: " + c.im())
}
}
if you have no arguments in function, write: def re = real
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
override def toString() =
"" + re + (if (im < 0) "" else "+") + im + "i"
}
class Complex(real: Double, imaginary: Double) -> primary constructor, which is part of the class declaration
override -> for overriding functions
(if (im < 0) "" else "+") have you see it ;)
class Rational(numerator: Int, denominator: Int) {
require(denominator != 0)
private val gcd = greatestCommonDivisor(numerator.abs,
denominator.abs)
val n = numerator / gcd
val d = denominator / gcd
def this(n: Int) = this(n, 1)
private def greatestCommonDivisor(a: Int, b: Int): Int =
if (b == 0) a else greatestCommonDivisor(b, a % b)
def + (that: Rational): Rational =
new Rational(n * that.d + d * that.n, d * that.d)
def - (that: Rational): Rational =
new Rational(n * that.d - d * that.n, d * that.d)
def * (that: Rational): Rational =
new Rational(n * that.n, d * that.d)
def / (that: Rational): Rational =
new Rational(n * that.d, d * that.n)
override def toString = n + "/" + d
}
require(denominator != 0) -> look that variable is not null, throw exception
def this(n: Int) = this(n, 1) -> create from Rational(2) -> Rational(2,1)
you can see +-*/ are objects functions, which can be simple overrided
Sonntag, 4. Oktober 2009
some commands
lpr -Plp Datei # datei ausdrucken
fuser -k /dev/lp0 # alle dienste die den /dev/lp0 benutzen toeten
#/dev/usb/lp0
scsi-scanner /dev/sg0
set -o nochlobber
git-rev-tree --bisect ^good1 ^good2 bad > git/refs/headers/tryN
git checkout tryN
^goodx > v2.6.12 bad > master
movw%bx, (%rsi) <-> recvfrom()
/usr/sbin/snort -b -m 027 -D -N -c /etc/snort/snort.conf -d -u snort -g snort -i eth1
iptables -A INPUT -ptcp -s PVT_IP_HERE -d 0/0
wget -p nur inhalt,
wget -r -np nur unterverzeichniss, nicht von root an
fuser -k /dev/lp0 # alle dienste die den /dev/lp0 benutzen toeten
#/dev/usb/lp0
scsi-scanner /dev/sg0
set -o nochlobber
git-rev-tree --bisect ^good1 ^good2 bad > git/refs/headers/tryN
git checkout tryN
^goodx > v2.6.12 bad > master
movw%bx, (%rsi) <-> recvfrom()
/usr/sbin/snort -b -m 027 -D -N -c /etc/snort/snort.conf -d -u snort -g snort -i eth1
iptables -A INPUT -ptcp -s PVT_IP_HERE -d 0/0
wget -p nur inhalt,
wget -r -np nur unterverzeichniss, nicht von root an
make kpkg, create a linux kernel image
export CONCURRENCY_LEVEL=6
time make-kpkg --initrd --append-to-version 1 --revision 1 kernel_image modules
time make-kpkg --initrd --append-to-version 1 --revision 1 kernel_image modules
Samstag, 3. Oktober 2009
trying Scala ... 3
List:
def define a function/method
od() name
inLst:List[Int] => inLst parameter name with a List type of Integers
:List[Int] return a List of Integers
Nil similar to none, None, null, void
inLst.head first element
inLst.tail all other elements after first element
scala> var lst = List(1, 7, 2, 8, 5, 6, 3, 9, 14, 12, 4, 10)
res29: List[Int] = List(1, 7, 2, 8, 5, 6, 3, 9, 14, 12, 4, 10)
scala> def odd(inLst:List[Int]):List[Int]={
| if(inLst==Nil) Nil
| else if(inLst.head%2==1) inLst.head::odd(inLst.tail)
| else odd(inLst.tail)
| }
odd: (List[Int])List[Int]
def define a function/method
od() name
inLst:List[Int] => inLst parameter name with a List type of Integers
:List[Int] return a List of Integers
Nil similar to none, None, null, void
inLst.head first element
inLst.tail all other elements after first element
scala> odd(lst)
res32: List[Int] = List(1, 7, 5, 3, 9)
trying Scala ... 2
scala> val try1=if (1==2) 8 else 9
try1: Int = 9
scala> var total=18
total: Int = 18
scala> while(total < 17) total+=3
scala> total
res15: Int = 18
scala> for(i <- 1 to 4) println("hi five")
hi five
hi five
hi five
hi five
scala> for(i <- 1 until 5 ; j <- 1 to 3) println(i,j)
(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
(3,3)
(4,1)
(4,2)
(4,3)
scala> for(c<-"hello")println(c)
h
e
l
l
o
hex, octal, bin is the same as in java
scala> val abyte: Byte = 27
abyte: Byte = 27
scala> var chr='A'
chr: Char = A
scala> chr=5
chr: Char =
scala> chr=66
chr: Char = B
define functions:
scala> def max(x: Int, y: Int): Int = {
| if (x > y) x
| else y
| }
max: (Int,Int)Int
scala> max(6,7)
res22: Int = 7
scala> max(3.6, 4)
:6: error: type mismatch;
found : Double(3.6)
required: Int
max(3.6, 4)
define a class
scala> class Point {
| var x=0
| var y=0
| }
defined class Point
scala> val p=new Point
p: Point = Point@18b62e0
scala> p.x=3
scala> p.y=4
scala> class Point( ix:Int,iy:Int){
| var x=ix
| var y=iy
| def vectorAdd(newpt:Point):Point={
| new Point(x+newpt.x,y+newpt.y)
| }
| }
defined class Point
scala> val p1=new Point(3,4)
p1: Point = Point@75455c
scala> val p2=new Point(7,2)
p2: Point = Point@1ba3523
scala> val p3=p1.vectorAdd(p2)
p3: Point = Point@1095c6c
scala> println(p3.x,p3.y)
(10,6)
scala> class Point( ix:Int,iy:Int){
| var x=ix
| var y=iy
| def +(newpt:Point):Point={
| new Point(x+newpt.x,y+newpt.y)
| }
| def -(newpt:Point):Point={
| new Point(x-newpt.x,y-newpt.y)
| }
| override def toString="Point("+x+","+y+")"
| }
defined class Point
scala> val p1=new Point(3,4)
p1: Point = Point(3,4)
scala> val p2=new Point(7,2)
p2: Point = Point(7,2)
scala> val p3=new Point(-2,2)
p3: Point = Point(-2,2)
scala> val p4=p1+p2-p3
p4: Point = Point(12,4)
scala> println(p4.x,p4.y)
(12,4)
there is no switch -> use match
scala> def decode(n:Int){
| n match {
| case 1 => println("One")
| case 2 => println("Two")
| case 5 => println("Five")
| case _ => println("Error")
| }
| }
decode: (Int)Unit
trying Scala ...
install scala, and type scala in console ;)
var and val define variables, val is immutable
For printing is here
operators and control sturctures (if, else, ...) are the same as in java.
scala> 4/3.0
res5: Double = 1.3333333333333333
scala> 4/0
java.lang.ArithmeticException: / by zero
at .(:5)
at .()
at RequestResult$.(:3)
at RequestResult$.()
at RequestResult$result()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAcce...
scala> var a=3
a: Int = 3
scala> a
res7: Int = 3
scala> a=5
a: Int = 5
scala> val b=3
b: Int = 3
scala> b
res10: Int = 3
scala> b=5
<console>:5: error: reassignment to val
b=5
var and val define variables, val is immutable
For printing is here
Ascala> println(b)
3
operators and control sturctures (if, else, ...) are the same as in java.
scala> val isBook = 6>=3
isBook: Boolean = true
scala> val price=16
price: Int = 16
scala> val vol=10
vol: Int = 10
scala> val sale=if (isBook)price*vol else price/vol
sale: Int = 160
scala> sale
res13: Int = 160
trying Scala
Tutorials: http://www.simplyscala.com/
Book: http://programming-scala.labs.oreilly.com/
further info from http://www.scala-lang.org/
http://www.scala-lang.org/node/1305
Book: http://programming-scala.labs.oreilly.com/
further info from http://www.scala-lang.org/
http://www.scala-lang.org/node/1305
RCPLinAdmin
RCPLinAdmin is in planing,
should be an universal admin management tool for linux local/ssh writed in RCP/Eclipse.
http://sites.google.com/site/rcplinadmin
should be an universal admin management tool for linux local/ssh writed in RCP/Eclipse.
http://sites.google.com/site/rcplinadmin
Abonnieren
Posts (Atom)