1. The code sample provided defines a simple Java class called HelloWorld with a main method that prints "Epic Fail".
2. The class contains a single public static void main method that takes an array of String arguments.
3. Within the main method it prints the text "Epic Fail" without any other processing or output.
Kotlin is something more than just tool that help you remove boilerplate from you code. It brings much more than just lamdas and handy syntax to your Java or Android project
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Kotlin is something more than just tool that help you remove boilerplate from you code. It brings much more than just lamdas and handy syntax to your Java or Android project
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
In functional programming, words from Category Theory are thrown around, but how useful are they really?
This session looks at applications of monoids specifically and how using their algebraic properties offers a solid foundation of reasoning in many types of business domains and reduces developer error as computational context complexity increases.
This will provide a tiny peak at Category Theory's practical uses in software development and modeling. Code examples will be in Haskell and Scala, but monoids could be constructed in almost any language by software craftsmen and women utilizing higher orders of reasoning to their code.
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinFabio Collini
It’s never easy to write async code but luckily there are many libraries to manage asynchronicity without adding too much complexity. In the last years RxJava and the other ReactiveX libraries have been very popular but lately there is a new way to manage async code in Kotlin: the coroutines. In this talk we’ll pros and cons of there two approaches and how to leverage them to simplify asynchronous code on Android.
Do they solve the same problem? Can we use them together? Which one can be used to write functional code? How can we use them effectively in Android development?
Spoiler alert: They are both great!
In this talk we’ll see how to solve common problems using RxJava or Coroutines, starting from basic concepts (for example the Retrofit support and how to cancel a task) to some more advanced (like threading, error management and how to combine multiple tasks).
All example of the talk are available on this repository:
https://github.com/fabioCollini/RxJavaVsCoroutines
Concurrent Programming in Java provides a brief overview of the following topics:
• Java language support for concurrency
• Concurrency utilities (java.util.concurrent package)
• Java collections for multithreading (java.util package)
• Parallel streams in Java 8.
Try out the examples. Source code here: https://github.com/CodeOpsTech/ConcurrentJava
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
Kotlin Bytecode Generation and Runtime Performanceintelliyole
In this talk, we'll dive into the details of how various language features supported by Kotlin are translated to Java bytecode. We'll use the JMH microbenchmarking tool to study the relative performance of various constructs and to understand how we can ensure top performance of the Kotlin code that we write.
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
In functional programming, words from Category Theory are thrown around, but how useful are they really?
This session looks at applications of monoids specifically and how using their algebraic properties offers a solid foundation of reasoning in many types of business domains and reduces developer error as computational context complexity increases.
This will provide a tiny peak at Category Theory's practical uses in software development and modeling. Code examples will be in Haskell and Scala, but monoids could be constructed in almost any language by software craftsmen and women utilizing higher orders of reasoning to their code.
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinFabio Collini
It’s never easy to write async code but luckily there are many libraries to manage asynchronicity without adding too much complexity. In the last years RxJava and the other ReactiveX libraries have been very popular but lately there is a new way to manage async code in Kotlin: the coroutines. In this talk we’ll pros and cons of there two approaches and how to leverage them to simplify asynchronous code on Android.
Do they solve the same problem? Can we use them together? Which one can be used to write functional code? How can we use them effectively in Android development?
Spoiler alert: They are both great!
In this talk we’ll see how to solve common problems using RxJava or Coroutines, starting from basic concepts (for example the Retrofit support and how to cancel a task) to some more advanced (like threading, error management and how to combine multiple tasks).
All example of the talk are available on this repository:
https://github.com/fabioCollini/RxJavaVsCoroutines
Concurrent Programming in Java provides a brief overview of the following topics:
• Java language support for concurrency
• Concurrency utilities (java.util.concurrent package)
• Java collections for multithreading (java.util package)
• Parallel streams in Java 8.
Try out the examples. Source code here: https://github.com/CodeOpsTech/ConcurrentJava
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
Not so long ago Microsoft announced a new language trageting on front-end developers. Everybody's reaction was like: Why?!! Is it just Microsoft darting back to Google?!
So, why a new language? JavaScript has its bad parts. Mostly you can avoid them or workaraund. You can emulate class-based OOP style, modules, scoping and even run-time typing. But that is doomed to be clumsy. That's not in the language design. Google has pointed out these flaws, provided a new language and failed. Will the story of TypeScript be any different?
Pybelsberg is a project allowing constraint-based programming in Python using the Z3 theorem prover [1].
It is available on Github [2] and is licensed under the BSD 3-Clause License.
By Robert Lehmann, Christoph Matthies, Conrad Calmez, Thomas Hille.
See also Babelsberg/R [4] and Babelsberg/JS [5].
[1] https://github.com/Z3Prover/z3
[2] https://github.com/babelsberg/pybelsberg
[3] http://opensource.org/licenses/BSD-3-Clause
[4] https://github.com/timfel/babelsberg-r
[5] https://github.com/timfel/babelsberg-js
Part presentation, part debate about the future of the language while touching base on the current state of the industry with respect to ES6/ES2015, and the possibilities of using it today in web applications and frameworks, the different options, and the things to keep in mind. Additionally, we will do a walk-through on the new features included in ES7/ES2016 draft, and those that are being discussed for ES8/ES2017.
Dr. Hsieh is teaching how to use the state-of-the-art libraries, Spark by Apache, to conduct data analysis on hadoop platform in ISSNIP 2015, Singapore. He started with teaching the basic operations like “map, reduce, flatten, and more,” followed by explaining the extension of Spark, including MLib, GraphX, and SparkSQL.
A bird's eye view on some programming languages, focusing on concepts like typing, execution model or style. Presented on T3chFest 2016 in Leganés, Madrid, Spain.
Il processo di certificazione della capacità operativa delle applicazioni web è basato su un metodo analitico che permette di predire il comportamento del sistema in produzione.
Il comportamento dell’applicazione viene misurato durante test eseguiti nell’ambiente di stress che usano carichi di lavoro progressivamente crescenti. Attraverso l’andamento dei principali parametri di performance si costruisce un modello lineare che descrive il comportamento del sistema in funzione del carico di lavoro. Tale modello è utilizzato per prevedere le performance del sistema in produzione.
Saranno presentati alcuni esempi concreti, ognuno con necessità e complessità diverse, in cui abbiamo applicato con successo il processo di certificazione. Per ognuno di essi mostreremo le specificità dell’analisi preliminare, gli strumenti software disponibili, gli obiettivi preposti e come questi siano stati raggiunti utilizzando il metodo esposto.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Hierarchical Digital Twin of a Naval Power SystemKerry Sado
A hierarchical digital twin of a Naval DC power system has been developed and experimentally verified. Similar to other state-of-the-art digital twins, this technology creates a digital replica of the physical system executed in real-time or faster, which can modify hardware controls. However, its advantage stems from distributing computational efforts by utilizing a hierarchical structure composed of lower-level digital twin blocks and a higher-level system digital twin. Each digital twin block is associated with a physical subsystem of the hardware and communicates with a singular system digital twin, which creates a system-level response. By extracting information from each level of the hierarchy, power system controls of the hardware were reconfigured autonomously. This hierarchical digital twin development offers several advantages over other digital twins, particularly in the field of naval power systems. The hierarchical structure allows for greater computational efficiency and scalability while the ability to autonomously reconfigure hardware controls offers increased flexibility and responsiveness. The hierarchical decomposition and models utilized were well aligned with the physical twin, as indicated by the maximum deviations between the developed digital twin hierarchy and the hardware.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
34. @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
public boolean enabled() default true;
}
public class T {
@Test(enabled = false)
void testB() {
throw new RuntimeException("This test always passed");
}
}
public class M {
public static void main(String[] args) throws Exception {
for (Method method : T.class.getDeclaredMethods()) {
if (method.isAnnotationPresent(Test.class)) {
Annotation annotation = method.getAnnotation(Test.class);
Test test = (Test) annotation;
if (test.enabled()) {
method.invoke(obj.newInstance());
}}}}}
@annotation/metadata/reflection
Logging
Timing
Aspects(AOP)
Mocking/Testing
35. inspect/dir/dict
class T:
def test():
raise Exception("ciao")
test.enabled = True
import inspect
for name, method in inspect.getmembers(T, inspect.ismethod):
if getattr(method, 'enabled', False):
method(T())
for val in T.__dict__.values():
if callable(val) and getattr(method, 'enabled', False):
val(T())
36. generators def firstn(n):
num = 0
while num < n:
yield num
num += 1
sum_of_first_n = sum(firstn(1000000))
sum_of_first_n = sum(range(1000000))
sum_of_first_n = sum(xrange(1000000))
def fib():
a,b = 0,1
while True:
yield a
b = a+b
yield b
a = a+b
asynchronous
low memory
infinite
37. streams
IntStream natural = IntStream.iterate(0, i -> i + 1);
natural.limit(10000).sum();
LongStream fibs = Stream.iterate(
new long[]{1, 1}, f -> new long[]{f[1], f[0] + f[1]})
.mapToLong(f -> f[0]);
38. context managers
@contextmanager
def opened(filename, mode="r"):
f = open(filename, mode)
try:
yield f
finally:
f.close()
with opened("/etc/passwd") as f:
for line in f:
print line.rstrip()
class released:
def __init__(self, lock):
self.lock = lock
def __enter__(self):
self.lock.release()
def __exit__(self, type, value, tb):
self.lock.acquire()
@contextmanager
def tag(name):
print "<%s>" % name
yield
print "</%s>" % name
>>> with tag("h1"):
... print "foo"
...
<h1>
foo
</h1>
39. try-with-resources
try(FileInputStream input = new FileInputStream("file.txt")) {
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
try (Connection conn = ds.getConnection();
Statement stmt = conn.createStatement()) {
stmt.execute(insertsql);
try (ResultSet rs = stmt.executeQuery(selectsql)) {
rs.next();
}
}
public interface AutoClosable {
public void close() throws Exception;
}
44. mixin class HasMethod1(object):
def method(self):
return 1
class HasMethod2(object):
def method(self):
return 2
class UsesMethod10(object):
def usesMethod(self):
return self.method() + 10
class UsesMethod20(object):
def usesMethod(self):
return self.method() + 20
class C1_10(HasMethod1, UsesMethod10): pass
class C1_20(HasMethod1, UsesMethod20): pass
class C2_10(HasMethod2, UsesMethod10): pass
class C2_20(HasMethod2, UsesMethod20): pass
assert C1_10().usesMethod() == 11
assert C1_20().usesMethod() == 21
assert C2_10().usesMethod() == 12
assert C2_20().usesMethod() == 22
__mro__
45. defaults interface methods
interface InterfaceA {
public void saySomething();
default public void sayHi() {
System.out.println("Hi");
}
}
interface InterfaceB {
default public void sayHi() {
System.out.println("Hi from InterfaceB");
}
}
public class MyClass implements InterfaceA, InterfaceB {
@Override
public void saySomething() {
System.out.println("Hello World");
}
@Override
public void sayHi() {
//System.out.println("implemetation of sayHi() in MyClass");
InterfaceA.super.sayHi();
}
}
46. unpacking
def my_function():
return 1, 2
a, b = my_function()
a = my_function()[0]
import datetime
t= (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6])
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[:7])
>>> def parrot(voltage, state='a stiff', action='voom'):
... print "-- This parrot wouldn't", action,
... print "if you put", voltage, "volts through it.",
... print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
47. public void show(String message){
}
public void show(String message, boolean show){
}
public void show(Integer message){
}
// does not compile!
public boolean show(String message){
return false;
}
overloading methods
48. *args, **kwargs >>> def print_everything(*args):
for count, thing in enumerate(args):
... print '{0}. {1}'.format(count, thing)
...
>>> print_everything('apple', 'banana', 'cabbage')
0. apple
1. banana
2. cabbage
>>> def table_things(**kwargs):
... for name, value in kwargs.items():
... print '{0} = {1}'.format(name, value)
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit
class Foo(object):
def __init__(self, value1, value2):
# do something with the values
print value1, value2
class MyFoo(Foo):
def __init__(self, *args, **kwargs):
# do something else, don't care about the args
print 'myfoo'
super(MyFoo, self).__init__(*args, **kwargs)
49. varargs…
public class HelloWorldVarargs {
public static void main(String args[]) {
test(215, "India", "Delhi");
test(147, "United States", "New York", "California");
}
public static void test(int some, String... args) {
System.out.print("n" + some);
for(String arg: args) {
System.out.print(", " + arg);
}
}
}
class Logger {
void error(Marker marker,
String message,
Object... params)
}
50. properties
class Celsius(object):
def __init__(self, temperature = 0):
self._temperature = temperature
def to_fahrenheit(self):
return (self.temperature * 1.8) + 32
@property
def temperature(self):
print("Getting value")
return self._temperature
@temperature.setter
def temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
celsius = Celsius(10)
celsius.temperature = 300
51. getter/setter
public class User {
private String name;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
}
set accessible=True
frameworks conventions
52. descriptors
class Foo(object):
name = TypedProperty("name",str)
num = TypedProperty("num",int,42)
>> acct = Foo()
>> acct.name = "obi"
>> acct.num = 1234
>> print acct.num
1234
>> print acct.name
obi
# trying to assign a string to number fails
>> acct.num = '1234'
TypeError: Must be a <type 'int'>
class TypedProperty(object):
def __init__(self, name, type, default=None):
self.name = "_" + name
self.type = type
self.default = default if default else type()
def __get__(self, instance, cls):
return getattr(instance, self.name, self.default)
def __set__(self,instance,value):
if not isinstance(value,self.type):
raise TypeError("Must be a %s" % self.type)
setattr(instance,self.name,value)
def __delete__(self,instance):
raise AttributeError("Can't delete attribute")
53. list comprehension
>>> S = [x**2 for x in range(10)]
>>> V = [2**i for i in range(13)]
>>> M = [x for x in S if x % 2 == 0]
>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> primes = [x for x in range(2, 50) if x not in noprimes]
>>> print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> words = 'The quick brown fox jumps over the lazy dog'.split()
>>> stuff = [[w.upper(), w.lower(), len(w)] for w in words]
['THE', 'the', 3]
['QUICK', 'quick', 5]
...
l = [['40', '20', '10', '30'], ['20', '20', '20'], ['100', '100'], ['100', '100', '100']]
[[float(y) for y in x] for x in l]
>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
54. list slicing
a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
There is also the step value, which can be used with any of the above:
a[start:end:step] # start through not past end, by step
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
55. factory: class inside a function
>>> def class_with_method(func):
... class klass: pass
... setattr(klass, func.__name__, func)
... return klass
...
>>> def say_foo(self): print 'foo'
...
>>> Foo = class_with_method(say_foo)
>>> foo = Foo()
>>> foo.say_foo()
>>> from new import classobj
>>> Foo2 = classobj('Foo2',(Foo,),{'bar':lambda self:'bar'})
>>> Foo2().bar()
'bar'
>>> Foo2().say_foo()
foo
# metaclass
>> X = type('X',(),{'foo':lambda self:'foo'})
>>> X, X().foo()
(<class '__main__.X'>, 'foo')
56. __metaclass__
>>> class Printable(type):
... def whoami(cls): print "I am a", cls.__name__
...
>>> Foo = Printable('Foo',(),{})
>>> Foo.whoami()
I am a Foo
>>> Printable.whoami()
Traceback (most recent call last):
TypeError: unbound method whoami() [...]
>>> class Bar:
... __metaclass__ = Printable
... def foomethod(self): print 'foo'
...
>>> Bar.whoami()
I am a Bar
>>> Bar().foomethod()
foo
# metaclass magic methods
# def __new__(cls, name, bases, dict):
# def __init__(self, name, bases, dict):
57. boolean b = false;
Double d1 = 0d;
Double d2 = null;
Double d = b ? d1.doubleValue() : d2;
long value = (Long) null;
long propertyValue = (Long) obj.getProperty(propertyModel.getName());
auto(un)boxing
NPE a gogo