Some techniques from the heady world of Functional Programming implemented in idiomatic Perl using various techniques: closures, iterators, Devel::Declare, and some distilled evil. New version now with monads! (As presented at http://conferences.yapceurope.org/lpw2008/ )
From session at http://www.lambdalounge.org.uk/ on 18th April 2016. Here's the original blurb:
So, Haskell is "an advanced purely-functional programming language" which supports writing "declarative, statically typed code". It may be optimized for academic buzzwords you've never heard of but... is it any good for writing code in the way that you'd write Perl, Python, or Ruby?
What are strong types, and why are we so frightened of them anyway? Can you develop interactively in Haskell, the way you would in a dynamic language?
Does Haskell have "whipuptitude" (being able to get things done quickly) as well as "manipulexity" (being able to manipulate complex things)? And perhaps most importantly, can writing Haskell be *fun*?
Haskell is founded on decades of the finest mathematical and computer science research. Perl, quite demonstrably isn't... but why do so many Perl programmers also love Haskell?
Audrey Tang wrote the first prototype for Perl 6, Pugs, in Haskell, and coined the phrase "lambdacamel" for the substantial crossover between the languages.
What does a Perl programmer make of Haskell? What are the lessons that can be learned (in either direction). And do the languages have more in common than you might have thought?
There are a lot of operators in Perl 6, so many that it can be called an OOL: operator oriented language. Here I describe most of them from the angle of contexts, which Perl 6 has also much more than Perl 5.
Some techniques from the heady world of Functional Programming implemented in idiomatic Perl using various techniques: closures, iterators, Devel::Declare, and some distilled evil. New version now with monads! (As presented at http://conferences.yapceurope.org/lpw2008/ )
From session at http://www.lambdalounge.org.uk/ on 18th April 2016. Here's the original blurb:
So, Haskell is "an advanced purely-functional programming language" which supports writing "declarative, statically typed code". It may be optimized for academic buzzwords you've never heard of but... is it any good for writing code in the way that you'd write Perl, Python, or Ruby?
What are strong types, and why are we so frightened of them anyway? Can you develop interactively in Haskell, the way you would in a dynamic language?
Does Haskell have "whipuptitude" (being able to get things done quickly) as well as "manipulexity" (being able to manipulate complex things)? And perhaps most importantly, can writing Haskell be *fun*?
Haskell is founded on decades of the finest mathematical and computer science research. Perl, quite demonstrably isn't... but why do so many Perl programmers also love Haskell?
Audrey Tang wrote the first prototype for Perl 6, Pugs, in Haskell, and coined the phrase "lambdacamel" for the substantial crossover between the languages.
What does a Perl programmer make of Haskell? What are the lessons that can be learned (in either direction). And do the languages have more in common than you might have thought?
There are a lot of operators in Perl 6, so many that it can be called an OOL: operator oriented language. Here I describe most of them from the angle of contexts, which Perl 6 has also much more than Perl 5.
Haste (Same Language, Multiple Platforms) and Tagless Final Style (Same Synta...takeoutweight
I discuss Haste, which compiles Haskell code to Javascript to be run on the browser. I then cover Tagless Final Style, which is a technique for creating flexible and extensible DSLs.
Video: https://www.youtube.com/watch?v=SfrEThI_m7g
Source code: https://github.com/Alotor/2015-greach-groovy-dsls
Behind each good Groovy library or framework there is a good DSL (Domain Specific Language). And this is not by chance, one of the most exciting features of Groovy is its amazing syntax flexibility and metaprogramming capabilities that allow us do things in a highly expressive manner through DSLs.
In this talk I’ll explain the basics of doing DLS’s with Groovy. What you’ll need to start and what to investigate deeper. Also, we’ll check some of the most well known ones libraries like Spock, Gradle or Grails so you can use their techniques in your own Groovy projects.
Redis is not just a cache, Andrew Lavers, ConFoo Montreal 2020Andrew Lavers
A common misunderstanding about Redis is that it's just a cache, or that you should only store ephemeral data there. In this talk I hope to dispel that myth by sharing some non-cache Redis recipes. I'll talk about how Redis can be used to solve problems such as distributed locking, message queues, one time tokens, and rate limiting.
Rust
Why do you care about Rust? Who has the time to learn all these new languages? It seems like a new one is popping up every other week and this trend is growing at an exponential rate. Good news, a fair number of them are crafted really well and efficiently solve specific problems. Bad news, how do you keep up with all of this, let alone decide which languages to include in your companies technology portfolio.
Despite the challenges of all these new languages, a majority of developers are intrigued about the idea of becoming a polyglot, but don't know where to begin or don't have the time. In my polyglot travels, there is one language of late that is the sure-fire answer to the above questions, Rust.
In this talk I’ll explore the value behind becoming more polyglotic as a developer, how to pick languages to learn, and then dive deep in the the language of Rust. Which in my opinion, is hands down the best up and coming languages to learn.
About the Presenter
Anthony Broad-Crawford has been a developer since the year 2000 with a short side stint as a semi-professional poker player. Since his transition to software development Anthony has...
1. Built 8 patent receiving technologies
2. Founded two global companies
3. Been a CTO (3x), CPO (1x), and CEO (1x)
and is currently the CTO at Fooda where he manages product, user experience, and engineering. Fooda is predominantly web and mobile technology company focused on bringing great & healthy food from the best restaurant's to people while at the office.
Through his career, in production applications Anthony has used Ruby, Java, Jave (Android), Objective-C and Swift, .NET, Erlang, Scala, Node.JS, LISP, Smalltalk, and even assembly, with his recent favorite, Rust . No, not all at the same time in the same application.
Anthony now spends his time building great teams, that leverage great technology, to build great products, but still looks to codes every chance he can get :)
Haste (Same Language, Multiple Platforms) and Tagless Final Style (Same Synta...takeoutweight
I discuss Haste, which compiles Haskell code to Javascript to be run on the browser. I then cover Tagless Final Style, which is a technique for creating flexible and extensible DSLs.
Video: https://www.youtube.com/watch?v=SfrEThI_m7g
Source code: https://github.com/Alotor/2015-greach-groovy-dsls
Behind each good Groovy library or framework there is a good DSL (Domain Specific Language). And this is not by chance, one of the most exciting features of Groovy is its amazing syntax flexibility and metaprogramming capabilities that allow us do things in a highly expressive manner through DSLs.
In this talk I’ll explain the basics of doing DLS’s with Groovy. What you’ll need to start and what to investigate deeper. Also, we’ll check some of the most well known ones libraries like Spock, Gradle or Grails so you can use their techniques in your own Groovy projects.
Redis is not just a cache, Andrew Lavers, ConFoo Montreal 2020Andrew Lavers
A common misunderstanding about Redis is that it's just a cache, or that you should only store ephemeral data there. In this talk I hope to dispel that myth by sharing some non-cache Redis recipes. I'll talk about how Redis can be used to solve problems such as distributed locking, message queues, one time tokens, and rate limiting.
Rust
Why do you care about Rust? Who has the time to learn all these new languages? It seems like a new one is popping up every other week and this trend is growing at an exponential rate. Good news, a fair number of them are crafted really well and efficiently solve specific problems. Bad news, how do you keep up with all of this, let alone decide which languages to include in your companies technology portfolio.
Despite the challenges of all these new languages, a majority of developers are intrigued about the idea of becoming a polyglot, but don't know where to begin or don't have the time. In my polyglot travels, there is one language of late that is the sure-fire answer to the above questions, Rust.
In this talk I’ll explore the value behind becoming more polyglotic as a developer, how to pick languages to learn, and then dive deep in the the language of Rust. Which in my opinion, is hands down the best up and coming languages to learn.
About the Presenter
Anthony Broad-Crawford has been a developer since the year 2000 with a short side stint as a semi-professional poker player. Since his transition to software development Anthony has...
1. Built 8 patent receiving technologies
2. Founded two global companies
3. Been a CTO (3x), CPO (1x), and CEO (1x)
and is currently the CTO at Fooda where he manages product, user experience, and engineering. Fooda is predominantly web and mobile technology company focused on bringing great & healthy food from the best restaurant's to people while at the office.
Through his career, in production applications Anthony has used Ruby, Java, Jave (Android), Objective-C and Swift, .NET, Erlang, Scala, Node.JS, LISP, Smalltalk, and even assembly, with his recent favorite, Rust . No, not all at the same time in the same application.
Anthony now spends his time building great teams, that leverage great technology, to build great products, but still looks to codes every chance he can get :)
Помните легендарные Java Puzzlers? Да-да, те самые, с Джошом Блохом и Нилом Гафтером? Ну, по которым ещё книжку написали? Так вот, в Groovy всё ещё веселее.
В смысле — задачки ещё более странные, и ответы ещё более поразительные. Этот доклад для вас, Groovy-разработчики, мы покажем вам настоящие, большие и красивые подводные камни! И для вас, Java-разработчики, потому что таких вещей на Java-подобном синтакисе вы точно никогда не видели! И для вас, PHP-разработчики… хотя, нет, не для вас :)
Всем точно будет весело — ваши ведущие Женя и Барух будут зажигать, шутить, спорить, бросаться футболками в публику, и самое главное — заставят вас офигевать от Groovy.
The need for functional programming languages is more important than ever with the current hardware and software trends. Scala has become the number one choice for functional programming languages and is becoming the language of choice for many development teams. But with the introduction of functional programming in Java 8 is Scala still relevant and needed?
Introduction to Swift programming language.Icalia Labs
Take a look to Swift, if you've been developing for iOS in Objective-C many things may look familiar, maybe just "upgraded". If you're a first timer diving into iOS development we strongly recommend you to understand first the basics of Cocoa.
Offshoring software development in Switzerland: You can do itAlexandre Masselot
If offshoring is often driven by short term considerations and economical drivers, there are better reasons to externalize software development. And why not coming to Switzerland?. Over the past two years, we have reversed the offshoring flow, pursuing ambitious IT projects for US companies, from the Swiss mountains.
The Agile Tour conference in Lausanne is the occasion of the lessons learned during adventures and to reflect on how we can improve the development of inhouse digital products.
Dev Wednesday - Swiss Transport in Real Time: Tribulations in the Big Data StackAlexandre Masselot
A couple more slides than the original https://www.slideshare.net/alexmass/swiss-transport-in-real-time-tribulations-in-the-big-data-stack
And a great evening in Bern
Swiss Transport in Real Time: Tribulations in the Big Data StackAlexandre Masselot
A lot of data are available in realtime on Swiss public transportation. Vehicles positions, station board (with delays) etc.
We use these data to illustrate a common pattern and build a proof of concept project. The idea is to address the question: "Is it possible to build a simple scalable infrastructure, to dispatch, transform and visualize 'near real time' massive data and achieve a posteriori analysis?"
We will describe such an infrastructure, focusing on the different bricks:
* streaming events with Kafka and Logstash;
* flow transformation with Akka or Play Streaming;
* storage in Elasticsearch;
* real time visualization with ReactJS and d3.js;
* a posteriori analysis with Python and Jupyter;
* not to forget DevOps with Docker, GCE and AWS.
A conference given at softshake 2016 in Geneva - www.softshake.ch
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
GridMate - End to end testing is a critical piece to ensure quality and avoid...
groovy & grails - lecture 3
1. Groovy: Efficiency Oriented Programming
Lecture 3
Master Proteomics & Bioinformatics - University of Geneva
Alexandre Masselot - summer 2011
2. Contents
• Eclipse tips
• The Groovy truth
• Control structures
• Regular expressions, a few step forwards
• Introduction to classes
3. A couple of eclipse tips
• <ctrl>-F : search text in file, replace; regular expressions possible,
4. A couple of eclipse tips
• <ctrl>-F : search text in file, replace; regular expressions possible,
• <ctrl>-J + word : search text in file, without opening a popup,
5. A couple of eclipse tips
• <ctrl>-F : search text in file, replace; regular expressions possible,
• <ctrl>-J + word : search text in file, without opening a popup,
• <ctrl>-R + filena : jump to the given filename directly. If multiple files
correspond to the name entered, they are proposed,
6. A couple of eclipse tips
• <ctrl>-F : search text in file, replace; regular expressions possible,
• <ctrl>-J + word : search text in file, without opening a popup,
• <ctrl>-R + filena : jump to the given filename directly. If multiple files
correspond to the name entered, they are proposed,
• select text + <ctrl>-7 [ right button -> source -> toggle comment] :
passed the whole selection in or out comment mode (prepend // to lines)
7. A couple of linux (shell) tips
history to list the last console command
history
history | grep psql //the last command with “psql”
8. A couple of linux (shell) tips
history to list the last console command
history
history | grep psql //the last command with “psql”
<ctrl>-R to find last command
<ctrl>-r + ls //jump to last command with “ls”
//call <ctrl>-r multiple times
9. A couple of linux (shell) tips
history to list the last console command
history
history | grep psql //the last command with “psql”
<ctrl>-R to find last command
<ctrl>-r + ls //jump to last command with “ls”
//call <ctrl>-r multiple times
tab for completion of the current word in plenty of context
fin<tab> //all command start with “fin”
10. A couple of linux (shell) tips
history to list the last console command
history
history | grep psql //the last command with “psql”
<ctrl>-R to find last command
<ctrl>-r + ls //jump to last command with “ls”
//call <ctrl>-r multiple times
tab for completion of the current word in plenty of context
fin<tab> //all command start with “fin”
ls to list files
ls -lrt //long format, sorted reverse on time
ls -lh //size in human format (1.2M, 3.5G ...)
ls -lhrt | tail //10 most recent 10
11. Control structures : the Groovy truth
• In many situations, a boolean (true or false) must be deduced from the
context
12. Control structures : the Groovy truth
• In many situations, a boolean (true or false) must be deduced from the
context
• In perl, for example, false can be deduced from
• undef
• empty string ‘’
•0
16. conditional construct
Like in perl, the classic if/else construction
if(x<10){
...
}else if(x<20){
...
}else{
...
}
Or the switch
switch(x){
case 1 : println ‘one’; break
case 2..10 : println ‘between 2 and 10’; break
default : println ‘anything else’
}
17. Single line conditional statement
Like in other language, the (...)?(...):(...)
boolean cond=true
int x
if(cond){ x=10 }
else { x=42 }
18. Single line conditional statement
Like in other language, the (...)?(...):(...)
boolean cond=true
int x
if(cond){ x=10 }
else { x=42 }
Can be replaced by
int x=cond?10:42
19. Single line conditional statement
Like in other language, the (...)?(...):(...)
boolean cond=true
int x
if(cond){ x=10 }
else { x=42 }
Can be replaced by
int x=cond?10:42
In the same idea, a default value can be set
if(params.x){ xVal=params.x } else { xVal=42 }
20. Single line conditional statement
Like in other language, the (...)?(...):(...)
boolean cond=true
int x
if(cond){ x=10 }
else { x=42 }
Can be replaced by
int x=cond?10:42
In the same idea, a default value can be set
if(params.x){ xVal=params.x } else { xVal=42 }
Can be replaced with the ?: (the equivalent of perl’s ||)
xVal=params.x?:42
21. Single line conditional statement (cont’d)
Imagine we want to sort elements on last name, and if they are equals, on
the first name
def nameList=[[first:'Harry', last:'Potter'], [first:'Ron',
last:'Weasley'], [first:'Fred', last:'Weasley'], [first:'Georges', last:'Weasley'], , [first:'Hermione', last:'Granger'] ]
22. Single line conditional statement (cont’d)
Imagine we want to sort elements on last name, and if they are equals, on
the first name
def nameList=[[first:'Harry', last:'Potter'], [first:'Ron',
last:'Weasley'], [first:'Fred', last:'Weasley'], [first:'Georges', last:'Weasley'], , [first:'Hermione', last:'Granger'] ]
The first “long” way:
nameList.sort{o1, o2 ->
if(o1.last == o2.last){
return o1.first <=> o2.first // <=> the spaceship
}else{ // operator
return o1.last <=> o2.last // compares elements
}
}.each{println “$it.first $it.last”}
23. Single line conditional statement (cont’d)
Imagine we want to sort elements on last name, and if they are equals, on
the first name
def nameList=[[first:'Harry', last:'Potter'], [first:'Ron',
last:'Weasley'], [first:'Fred', last:'Weasley'], [first:'Georges', last:'Weasley'], , [first:'Hermione', last:'Granger'] ]
The first “long” way:
nameList.sort{o1, o2 ->
if(o1.last == o2.last){
return o1.first <=> o2.first // <=> the spaceship
}else{ // operator
return o1.last <=> o2.last // compares elements
}
}.each{println “$it.first $it.last”}
Or the more compact manner:
(o1.last <=> o2.last)?:(o1.first <=> o2.first)
24. While loop
while(cond) is evaluated until the condition is false
List l=[]
x=5
while(x--){
l << x
}
assert l == [4, 3, 2, 1, 0]
25. While loop
while(cond) is evaluated until the condition is false
List l=[]
x=5
while(x--){
l << x
}
assert l == [4, 3, 2, 1, 0]
A loop scope can be exited with a break
List l=[]
x=5
while(x--){
l << x
if(x==3) break // NB a single line statement, no {}
}
assert l == [4, 3]
26. Loop: breaking the flow (cont’d)
It can be useful to jump directly to the next iteration, without evaluation the
remaining part of the loop, with the continue statement
int x = 10
def list=[]
while(x--){
if (x%2) continue // return to the while evaluation
if (x<4) break // exit
list << x
}
assert list == [8, 6, 4]
27. for loop
Although closure makes it less critical, the for statement allows to walk
through a collection
String t=’’
for(String s in ‘a’..’d’){
t+=s
}
assert t == ‘abcd’
28. for loop
Although closure makes it less critical, the for statement allows to walk
through a collection
String t=’’
for(String s in ‘a’..’d’){
t+=s
}
assert t == ‘abcd’
It is equivalent to
(‘a’..’d’).each{t+=it}
29. for loop
Although closure makes it less critical, the for statement allows to walk
through a collection
String t=’’
for(String s in ‘a’..’d’){
t+=s
}
assert t == ‘abcd’
It is equivalent to
(‘a’..’d’).each{t+=it}
And
for(int i in 0..<5){println i} //NB the half inclusive ..<
30. for loop
Although closure makes it less critical, the for statement allows to walk
through a collection
String t=’’
for(String s in ‘a’..’d’){
t+=s
}
assert t == ‘abcd’
It is equivalent to
(‘a’..’d’).each{t+=it}
And
for(int i in 0..<5){println i} //NB the half inclusive ..<
is equivalent to
5.times{println it}
31. Regular Expression
• You want to know if a string match a structure? find the matches? replace
the matches? Regular expressions are the answer.
32. Regular Expression
• You want to know if a string match a structure? find the matches? replace
the matches? Regular expressions are the answer.
• Regular expression is a language by itself. Most of the features are cross
languages (perl, java, php...).
33. Regular Expression
• You want to know if a string match a structure? find the matches? replace
the matches? Regular expressions are the answer.
• Regular expression is a language by itself. Most of the features are cross
languages (perl, java, php...).
• TIMTOWTDI : regexp is a domain where syntax can become particularly
ugly, when inappropriate choice are made.
34. Regular Expression
• You want to know if a string match a structure? find the matches? replace
the matches? Regular expressions are the answer.
• Regular expression is a language by itself. Most of the features are cross
languages (perl, java, php...).
• TIMTOWTDI : regexp is a domain where syntax can become particularly
ugly, when inappropriate choice are made.
• A large toolkit is available, and we’ll try to present here the most commonly
used and groovy oriented syntax.
35. Regular Expression
• You want to know if a string match a structure? find the matches? replace
the matches? Regular expressions are the answer.
• Regular expression is a language by itself. Most of the features are cross
languages (perl, java, php...).
• TIMTOWTDI : regexp is a domain where syntax can become particularly
ugly, when inappropriate choice are made.
• A large toolkit is available, and we’ll try to present here the most commonly
used and groovy oriented syntax.
• “Mastering Regular Expressions” by Jeffrey E.L Friedl (O'Reilly).
36. Regular Expression
• You want to know if a string match a structure? find the matches? replace
the matches? Regular expressions are the answer.
• Regular expression is a language by itself. Most of the features are cross
languages (perl, java, php...).
• TIMTOWTDI : regexp is a domain where syntax can become particularly
ugly, when inappropriate choice are made.
• A large toolkit is available, and we’ll try to present here the most commonly
used and groovy oriented syntax.
• “Mastering Regular Expressions” by Jeffrey E.L Friedl (O'Reilly).
• http://www.regexp.info/
38. regexp: find or match
Two operators are commonly used
The find operator: is a substring matching the pattern?
assert “The Lord of the Rings” =~ /Lord/
39. regexp: find or match
Two operators are commonly used
The find operator: is a substring matching the pattern?
assert “The Lord of the Rings” =~ /Lord/
The match operator: is the whole string matching the pattern?
assert ! “The Lord of the Rings” ==~ /Lord/
assert “The Lord of the Rings” ==~ /.*Lord.*/
42. regexp: anchoring
When finding a pattern, we can anchor it
To the start of the line ^
assert ‘The Lord of the Rings’ =~ /^The Lord/
assert ! ‘The Lord of the Rings’ =~ /^Lord/
43. regexp: anchoring
When finding a pattern, we can anchor it
To the start of the line ^
assert ‘The Lord of the Rings’ =~ /^The Lord/
assert ! ‘The Lord of the Rings’ =~ /^Lord/
To the end of the line $
assert ‘The Lord of the Rings’ =~ /the Rings$/
assert ! ‘The Lord of the Rings’ =~ /Lord$/
44. regexp: anchoring
When finding a pattern, we can anchor it
To the start of the line ^
assert ‘The Lord of the Rings’ =~ /^The Lord/
assert ! ‘The Lord of the Rings’ =~ /^Lord/
To the end of the line $
assert ‘The Lord of the Rings’ =~ /the Rings$/
assert ! ‘The Lord of the Rings’ =~ /Lord$/
A word boundary b
assert ‘The Lord of the Rings’ =~ /bLor/
assert ‘The Lord of the Rings’ =~ /bThe Lor/
assert ‘The Lord of the Rings’ =~ /ordb/
45. regexp: character classes
assert ‘The Lord’ =~ /L.rd/ // . matches any character
assert ‘The Lord’ =~ /L..d/
assert ! ‘The Lord’ =~ /.The/
55. regexp: repetitions (cont’d)
{n} : n times
assert ‘abcd’ ==~ /w{4}/
{n,m} : between n and m times
assert ‘abcd’ ==~ /w{3,6}/
56. regexp: repetitions (cont’d)
{n} : n times
assert ‘abcd’ ==~ /w{4}/
{n,m} : between n and m times
assert ‘abcd’ ==~ /w{3,6}/
{n,} : ≥ n times
assert ‘abc’ ==~ /w{3,}/
57. regexp: repetitions (cont’d)
{n} : n times
assert ‘abcd’ ==~ /w{4}/
{n,m} : between n and m times
assert ‘abcd’ ==~ /w{3,6}/
{n,} : ≥ n times
assert ‘abc’ ==~ /w{3,}/
Greedy or not greedy ? Repetitions by default tries to consume the most
characters possible. Adding a question mark ‘?’ put the expanding operator
in restrictive mode
‘the Lord of the Rings’ =~ /.*s/
‘the Lord of the Rings’ =~ /.*?s/
59. regexp: matching this or that
We can match “multiple choices”
assert ‘this’ ==~ /this|that/
assert ‘this’ ==~ /th(is|at)/
60. regexp: matching this or that
We can match “multiple choices”
assert ‘this’ ==~ /this|that/
assert ‘this’ ==~ /th(is|at)/
Leftmost match: the order of the choice will infer the match
‘"So you're going to go through with it, then", Gandalf
the Wizard said slowly’ =~ /going|go/
‘"So you're going to go through with it, then", Gandalf
the Wizard said slowly’ =~ /go|going/
62. regexp: modifiers
It is possible to modify the behavior of the matching engine
Case sensitivity: by default, regular expression are case sensitive
assert ! ‘The Lord of the Rings’ =~ /ring/
assert ‘The Lord of the Rings’ =~ /(?i)ring/
63. regexp: modifiers
It is possible to modify the behavior of the matching engine
Case sensitivity: by default, regular expression are case sensitive
assert ! ‘The Lord of the Rings’ =~ /ring/
assert ‘The Lord of the Rings’ =~ /(?i)ring/
Multi or single line: by default, regular expression are not evaluated across
new line char (n are not covered by s or .)
64. regexp: modifiers
It is possible to modify the behavior of the matching engine
Case sensitivity: by default, regular expression are case sensitive
assert ! ‘The Lord of the Rings’ =~ /ring/
assert ‘The Lord of the Rings’ =~ /(?i)ring/
Multi or single line: by default, regular expression are not evaluated across
new line char (n are not covered by s or .)
In other word, with single line modifier, n is considered just like another
character
‘’’The Lord //NB ‘’’ for multi line string
of the Rings’’’ =~ /.+/
‘’’The Lord
of the Rings’’’ =~ /(?s).+/
66. regexp: looking around
Regular expression usually consume character
Let’s consider cleaving a protein sequence with trypsin
‘ACDEFKPGHRILKM’ =~/(w+?[KR])[^P]/ // the I is consumed
67. regexp: looking around
Regular expression usually consume character
Let’s consider cleaving a protein sequence with trypsin
‘ACDEFKPGHRILKM’ =~/(w+?[KR])[^P]/ // the I is consumed
If the next amino acid is consumed, it will not be caught in a situation where
we want to capture all the matches of the regular expression
68. regexp: looking around
Regular expression usually consume character
Let’s consider cleaving a protein sequence with trypsin
‘ACDEFKPGHRILKM’ =~/(w+?[KR])[^P]/ // the I is consumed
If the next amino acid is consumed, it will not be caught in a situation where
we want to capture all the matches of the regular expression
Hopefully, we can ‘lookahead’
‘ACDEFKPGHRILKM’ =~/(w+?[KR])(?=[^P])/
69. regexp: looking around
Regular expression usually consume character
Let’s consider cleaving a protein sequence with trypsin
‘ACDEFKPGHRILKM’ =~/(w+?[KR])[^P]/ // the I is consumed
If the next amino acid is consumed, it will not be caught in a situation where
we want to capture all the matches of the regular expression
Hopefully, we can ‘lookahead’
‘ACDEFKPGHRILKM’ =~/(w+?[KR])(?=[^P])/
Respectively, it is possible to check is a regexp matches before the captured
string (look behind)
(?<=...)
70. regexp at works : splitting a string
One of the most commons use of the regular expression is to split a string
into an array
71. regexp at works : splitting a string
One of the most commons use of the regular expression is to split a string
into an array
Splitting point can be defined by a regular expression
assert “a b c d”.split(/s+/)==[‘a’, ‘b’, ‘c’, ‘d’]
72. regexp at works : splitting a string
One of the most commons use of the regular expression is to split a string
into an array
Splitting point can be defined by a regular expression
assert “a b c d”.split(/s+/)==[‘a’, ‘b’, ‘c’, ‘d’]
An extra argument can be passed, to limit the number of elements in the
returned list
assert “a b c d”.split(/s+/, 3)==[‘a’, ‘b’, ‘c d’]
73. regexp at works : splitting a string
One of the most commons use of the regular expression is to split a string
into an array
Splitting point can be defined by a regular expression
assert “a b c d”.split(/s+/)==[‘a’, ‘b’, ‘c’, ‘d’]
An extra argument can be passed, to limit the number of elements in the
returned list
assert “a b c d”.split(/s+/, 3)==[‘a’, ‘b’, ‘c d’]
Do not forget to pipe to an collect closure
assert “0 1 2”.split(/s+/).collect{it as Integer}
74. regexp at works : splitting a string
One of the most commons use of the regular expression is to split a string
into an array
Splitting point can be defined by a regular expression
assert “a b c d”.split(/s+/)==[‘a’, ‘b’, ‘c’, ‘d’]
An extra argument can be passed, to limit the number of elements in the
returned list
assert “a b c d”.split(/s+/, 3)==[‘a’, ‘b’, ‘c d’]
Do not forget to pipe to an collect closure
assert “0 1 2”.split(/s+/).collect{it as Integer}
Or use splitEachLine
txt.splitEachLine(/regexp/){it.action}
75. regexp: loop across matches
All the occurrence of a match is returned into a list:
String title = "The Lord of the Rings"
assert (title=~/(?i)thes+w+/).collect{"<$it>"} ==
[‘<The Lord>’, ‘<the Rings>’]
76. regexp: loop across matches
All the occurrence of a match is returned into a list:
String title = "The Lord of the Rings"
assert (title=~/(?i)thes+w+/).collect{"<$it>"} ==
[‘<The Lord>’, ‘<the Rings>’]
It is also natural to loop across all such occurrences:
(title=~/(?i)thes+w+/).each{println "<$it>"}
77. regexp: loop across matches
All the occurrence of a match is returned into a list:
String title = "The Lord of the Rings"
assert (title=~/(?i)thes+w+/).collect{"<$it>"} ==
[‘<The Lord>’, ‘<the Rings>’]
It is also natural to loop across all such occurrences:
(title=~/(?i)thes+w+/).each{println "<$it>"}
Is equivalent to
title.eachMatch(/(?i)thes+w+/){println "<$it>"}
78. regexp: capturing
Like in perl, it is possible to define with parenthesis sub patterns to be
captured in the pattern
79. regexp: capturing
Like in perl, it is possible to define with parenthesis sub patterns to be
captured in the pattern
If such parenthesis are present, the java.util.regex.Matcher structure
returned is different
def matcher = title=~/(?i)thes+(w+)/
assert matcher.hasGroup()
assert matcher[0][0] == ‘The Lord’ //the whole match
assert matcher[0][1] == ‘Lord‘ //first captured block
80. regexp: capturing
Like in perl, it is possible to define with parenthesis sub patterns to be
captured in the pattern
If such parenthesis are present, the java.util.regex.Matcher structure
returned is different
def matcher = title=~/(?i)thes+(w+)/
assert matcher.hasGroup()
assert matcher[0][0] == ‘The Lord’ //the whole match
assert matcher[0][1] == ‘Lord‘ //first captured block
It is possible to loop around with a closure
(title=~/(?i)thes+(w+)/).each{all, name ->
println "all: <$all>, capt:<$name>"
}
Editor's Notes
\n
horizontal learning\n
read the function shortcuts and try to memorize your most commons\n
read the function shortcuts and try to memorize your most commons\n
read the function shortcuts and try to memorize your most commons\n
read the function shortcuts and try to memorize your most commons\n
\n
\n
\n
\n
ask for perl before bullet 2\n
ask for perl before bullet 2\n
\n
if you don&#x2019;t write the break, next line will be evaluated!!\n
if you don&#x2019;t write the break, next line will be evaluated!!\n
take care if params.x is 0 or &#x2018;&#x2019;\ndepends on the context\nparams.x?:42 + 23 != (params.x?:42) + 23\n
take care if params.x is 0 or &#x2018;&#x2019;\ndepends on the context\nparams.x?:42 + 23 != (params.x?:42) + 23\n
take care if params.x is 0 or &#x2018;&#x2019;\ndepends on the context\nparams.x?:42 + 23 != (params.x?:42) + 23\n
take care if params.x is 0 or &#x2018;&#x2019;\ndepends on the context\nparams.x?:42 + 23 != (params.x?:42) + 23\n
\n
\n
\n
\n
sometimes, while(true) , then break exit for the condition\n
sometimes, while(true) , then break exit for the condition\n
\n
rich scripting => TIMTOWTDI\nmore than one manner: choose your preferred, but be able to read other people code\n
rich scripting => TIMTOWTDI\nmore than one manner: choose your preferred, but be able to read other people code\n
rich scripting => TIMTOWTDI\nmore than one manner: choose your preferred, but be able to read other people code\n
rich scripting => TIMTOWTDI\nmore than one manner: choose your preferred, but be able to read other people code\n
most of what is seen here was already discussed in winter => go fast\n
most of what is seen here was already discussed in winter => go fast\n
most of what is seen here was already discussed in winter => go fast\n
most of what is seen here was already discussed in winter => go fast\n
most of what is seen here was already discussed in winter => go fast\n
most of what is seen here was already discussed in winter => go fast\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
always prefer \\s+ to &#x2018; &#x2018; when you suspect tab\ninverse of split is join\n\n
always prefer \\s+ to &#x2018; &#x2018; when you suspect tab\ninverse of split is join\n\n
always prefer \\s+ to &#x2018; &#x2018; when you suspect tab\ninverse of split is join\n\n
always prefer \\s+ to &#x2018; &#x2018; when you suspect tab\ninverse of split is join\n\n
always prefer \\s+ to &#x2018; &#x2018; when you suspect tab\ninverse of split is join\n\n