SlideShare a Scribd company logo
1 of 61
Download to read offline
DATE: May 13, 2013Florence, Italy
Clone Detection
in Python
Valerio Maggio (valerio.maggio@unina.it)
Introduction
Duplicated Code
Number one in the stink
parade is duplicated code.
If you see the same code
structure in more than one
place, you can be sure that
your program will be better if
you find a way to unify them.
2
Introduction
The Python Way
3
Introduction
The Python Way
3
Introduction
NLTK (tree.py)
4
Introduction
NLTK (tree.py)
4
Introduction
NLTK (tree.py)
4
Introduction
NLTK (tree.py)
4
Introduction
NLTK (tree.py)
4
Introduction
NLTK (tree.py)
4
Introduction
Duplicated Code
‣ Exists: 5% to 30% of code is similar
• In extreme cases, even up to 50%
- This is the case of Payroll, a COBOL system
5
Introduction
Duplicated Code
‣ Exists: 5% to 30% of code is similar
• In extreme cases, even up to 50%
- This is the case of Payroll, a COBOL system
‣ Is often created during development
5
Introduction
Duplicated Code
‣ Exists: 5% to 30% of code is similar
• In extreme cases, even up to 50%
- This is the case of Payroll, a COBOL system
‣ Is often created during development
• due to time pressure for an upcoming deadline
5
Introduction
Duplicated Code
‣ Exists: 5% to 30% of code is similar
• In extreme cases, even up to 50%
- This is the case of Payroll, a COBOL system
‣ Is often created during development
• due to time pressure for an upcoming deadline
• to overcome limitations of the programming language
5
Introduction
Duplicated Code
‣ Exists: 5% to 30% of code is similar
• In extreme cases, even up to 50%
- This is the case of Payroll, a COBOL system
‣ Is often created during development
• due to time pressure for an upcoming deadline
• to overcome limitations of the programming language
‣ Three Public Enemies:
5
Introduction
Duplicated Code
‣ Exists: 5% to 30% of code is similar
• In extreme cases, even up to 50%
- This is the case of Payroll, a COBOL system
‣ Is often created during development
• due to time pressure for an upcoming deadline
• to overcome limitations of the programming language
‣ Three Public Enemies:
• Copy, Paste and Modify
5
DATE: May 13, 2013Part I: Clone Detection
Clone Detection
in Python
DATE: May 13, 2013Part I: Clone Detection
Clone Detection
in Python
Part I: Clone Detection
Code Clones
‣ There can be different definitions of similarity,
based on:
• Program Text (text, syntax)
• Semantics
7
(Def.) “Software Clones are segments of code that are similar
according to some definition of similarity” (I.D. Baxter, 1998)
Part I: Clone Detection
Code Clones
‣ There can be different definitions of similarity,
based on:
• Program Text (text, syntax)
• Semantics
‣ Four Different Types of Clones
7
(Def.) “Software Clones are segments of code that are similar
according to some definition of similarity” (I.D. Baxter, 1998)
Part I: Clone Detection
The original one
8
# Original Fragment
def do_something_cool_in_Python(filepath, marker='---end---'):
	 lines = list()
	 with open(filepath) as report:
	 	 for l in report:
	 	 	 if l.endswith(marker):
	 	 	 	 lines.append(l) # Stores only lines that ends with "marker"
	 return lines #Return the list of different lines
Part I: Clone Detection
Type 1: Exact Copy
‣ Identical code segments except for differences in layout, whitespace,
and comments
9
Part I: Clone Detection
Type 1: Exact Copy
‣ Identical code segments except for differences in layout, whitespace,
and comments
9
# Original Fragment
def do_something_cool_in_Python(filepath, marker='---end---'):
	 lines = list()
	 with open(filepath) as report:
	 	 for l in report:
	 	 	 if l.endswith(marker):
	 	 	 	 lines.append(l) # Stores only lines that ends with "marker"
	 return lines #Return the list of different lines
def do_something_cool_in_Python (filepath, marker='---end---'):
	 lines = list() # This list is initially empty
	 with open(filepath) as report:
	 	 for l in report: # It goes through the lines of the file
	 	 	 if l.endswith(marker):
	 	 	 	 lines.append(l)
	 return lines
Part I: Clone Detection
Type 2: Parameter Substituted Clones
‣ Structurally identical segments except for differences in identifiers,
literals, layout, whitespace, and comments
10
Part I: Clone Detection
Type 2: Parameter Substituted Clones
‣ Structurally identical segments except for differences in identifiers,
literals, layout, whitespace, and comments
10
# Type 2 Clone
def do_something_cool_in_Python(path, end='---end---'):
	 targets = list()
	 with open(path) as data_file:
	 	 for t in data_file:
	 	 	 if l.endswith(end):
	 	 	 	 targets.append(t) # Stores only lines that ends with "marker"
	 #Return the list of different lines
	 return targets
# Original Fragment
def do_something_cool_in_Python(filepath, marker='---end---'):
	 lines = list()
	 with open(filepath) as report:
	 	 for l in report:
	 	 	 if l.endswith(marker):
	 	 	 	 lines.append(l) # Stores only lines that ends with "marker"
	 return lines #Return the list of different lines
Part I: Clone Detection
Type 3: Structure Substituted Clones
‣ Similar segments with further modifications such as changed, added (or deleted)
statements, in additions to variations in identifiers, literals, layout and comments
11
Part I: Clone Detection
Type 3: Structure Substituted Clones
‣ Similar segments with further modifications such as changed, added (or deleted)
statements, in additions to variations in identifiers, literals, layout and comments
11
import os
def do_something_with(path, marker='---end---'):
	 # Check if the input path corresponds to a file
	 if not os.path.isfile(path):
	 	 return None
	
	 bad_ones = list()
	 good_ones = list()
	 with open(path) as report:
	 	 for line in report:
	 	 	 line = line.strip()
	 	 	 if line.endswith(marker):
	 	 	 	 good_ones.append(line)
	 	 	 else:
	 	 	 	 bad_ones.append(line)
	 #Return the lists of different lines
	 return good_ones, bad_ones
Part I: Clone Detection
Type 3: Structure Substituted Clones
‣ Similar segments with further modifications such as changed, added (or deleted)
statements, in additions to variations in identifiers, literals, layout and comments
11
import os
def do_something_with(path, marker='---end---'):
	 # Check if the input path corresponds to a file
	 if not os.path.isfile(path):
	 	 return None
	
	 bad_ones = list()
	 good_ones = list()
	 with open(path) as report:
	 	 for line in report:
	 	 	 line = line.strip()
	 	 	 if line.endswith(marker):
	 	 	 	 good_ones.append(line)
	 	 	 else:
	 	 	 	 bad_ones.append(line)
	 #Return the lists of different lines
	 return good_ones, bad_ones
Part I: Clone Detection
Type 3: Structure Substituted Clones
‣ Similar segments with further modifications such as changed, added (or deleted)
statements, in additions to variations in identifiers, literals, layout and comments
11
import os
def do_something_with(path, marker='---end---'):
	 # Check if the input path corresponds to a file
	 if not os.path.isfile(path):
	 	 return None
	
	 bad_ones = list()
	 good_ones = list()
	 with open(path) as report:
	 	 for line in report:
	 	 	 line = line.strip()
	 	 	 if line.endswith(marker):
	 	 	 	 good_ones.append(line)
	 	 	 else:
	 	 	 	 bad_ones.append(line)
	 #Return the lists of different lines
	 return good_ones, bad_ones
Part I: Clone Detection
Type 3: Structure Substituted Clones
‣ Similar segments with further modifications such as changed, added (or deleted)
statements, in additions to variations in identifiers, literals, layout and comments
11
import os
def do_something_with(path, marker='---end---'):
	 # Check if the input path corresponds to a file
	 if not os.path.isfile(path):
	 	 return None
	
	 bad_ones = list()
	 good_ones = list()
	 with open(path) as report:
	 	 for line in report:
	 	 	 line = line.strip()
	 	 	 if line.endswith(marker):
	 	 	 	 good_ones.append(line)
	 	 	 else:
	 	 	 	 bad_ones.append(line)
	 #Return the lists of different lines
	 return good_ones, bad_ones
Part I: Clone Detection
Type 4: “Semantic” Clones
‣ Semantically equivalent segments that perform the same
computation but are implemented by different syntactic variants
12
Part I: Clone Detection
Type 4: “Semantic” Clones
‣ Semantically equivalent segments that perform the same
computation but are implemented by different syntactic variants
12
# Original Fragment
def do_something_cool_in_Python(filepath, marker='---end---'):
	 lines = list()
	 with open(filepath) as report:
	 	 for l in report:
	 	 	 if l.endswith(marker):
	 	 	 	 lines.append(l) # Stores only lines that ends with "marker"
	 return lines #Return the list of different lines
def do_always_the_same_stuff(filepath, marker='---end---'):
	 report = open(filepath)
	 file_lines = report.readlines()
	 report.close()
	 #Filters only the lines ending with marker
	 return filter(lambda l: len(l) and l.endswith(marker), file_lines)
Part I: Clone Detection
What are the consequences?
‣ Do clones increase the maintenance effort?
‣ Hypothesis:
• Cloned code increases code size
• A fix to a clone must be applied to all similar fragments
• Bugs are duplicated together with their clones
‣ However: it is not always possible to remove clones
• Removal of Clones is harder if variations exist.
13
Part I: Clone Detection 14
Duplix
Scorpio
PMD
CCFinder
Dup
CPD
Duplix
Shinobi
Clone Detective
Gemini
iClones
KClone
ConQAT
Deckard
Clone Digger
JCCD
CloneDr SimScan
CLICS
NiCAD
Simian
Duploc
Dude
SDD
Clone Detection Tools
Part I: Clone Detection 14
Duplix
Scorpio
PMD
CCFinder
Dup
CPD
Duplix
Shinobi
Clone Detective
Gemini
iClones
KClone
ConQAT
Deckard
Clone Digger
JCCD
CloneDr SimScan
CLICS
NiCAD
Simian
Duploc
Dude
SDD
‣ Text Based Tools:
• Lines are compared to other
lines
Clone Detection Tools
Part I: Clone Detection 14
Duplix
Scorpio
PMD
CCFinder
Dup
CPD
Duplix
Shinobi
Clone Detective
Gemini
iClones
KClone
ConQAT
Deckard
Clone Digger
JCCD
CloneDr SimScan
CLICS
NiCAD
Simian
Duploc
Dude
SDD
‣ Token Based Tools:
• Token sequences are compared to
sequences
Clone Detection Tools
Part I: Clone Detection 14
Duplix
Scorpio
PMD
CCFinder
Dup
CPD
Duplix
Shinobi
Clone Detective
Gemini
iClones
KClone
ConQAT
Deckard
Clone Digger
JCCD
CloneDr SimScan
CLICS
NiCAD
Simian
Duploc
Dude
SDD
‣ Syntax Based Tools:
• Syntax subtrees are
compared to each other
Clone Detection Tools
Part I: Clone Detection 14
Duplix
Scorpio
PMD
CCFinder
Dup
CPD
Duplix
Shinobi
Clone Detective
Gemini
iClones
KClone
ConQAT
Deckard
Clone Digger
JCCD
CloneDr SimScan
CLICS
NiCAD
Simian
Duploc
Dude
SDD
‣ Graph Based Tools:
• (sub) graphs are compared to each
other
Clone Detection Tools
Part I: Clone Detection
Clone Detection Techniques
15
‣ String/Token based Techiniques:
• Pros: Run very fast
• Cons: Too many false clones
‣ Syntax based (AST) Techniques:
• Pros: Well suited to detect structural similarities
• Cons: Not Properly suited to detect Type 3 Clones
‣ Graph based Techniques:
• Pros: The only one able to deal with Type 4 Clones
• Cons: Performance Issues
Part I: Clone Detection
The idea: Use Machine Learning, Luke
‣ Use Machine Learning Techniques to compute similarity of fragments by
exploiting specific features of the code.
‣ Combine different sources of Information
• Structural Information: ASTs, PDGs
• Lexical Information: Program Text
16
Part I: Clone Detection
Kernel Methods for Structured Data
‣ Well-grounded on solid and awful
Math
‣ Based on the idea that objects
can be described in terms of
their constituent Parts
‣ Can be easily tailored to specific
domains
• Tree Kernels
• Graph Kernels
• ....
17
Part I: Clone Detection
Defining a Kernel for Structured Data
18
Part I: Clone Detection
Defining a Kernel for Structured Data
The definition of a new Kernel for a Structured Object requires
the definition of:
18
Part I: Clone Detection
Defining a Kernel for Structured Data
The definition of a new Kernel for a Structured Object requires
the definition of:
‣ Set of features to annotate each part of the object
18
Part I: Clone Detection
Defining a Kernel for Structured Data
The definition of a new Kernel for a Structured Object requires
the definition of:
‣ Set of features to annotate each part of the object
‣ A Kernel function to measure the similarity on the smallest part
of the object
18
Part I: Clone Detection
Defining a Kernel for Structured Data
The definition of a new Kernel for a Structured Object requires
the definition of:
‣ Set of features to annotate each part of the object
‣ A Kernel function to measure the similarity on the smallest part
of the object
• e.g., Nodes for AST and Graphs
18
Part I: Clone Detection
Defining a Kernel for Structured Data
The definition of a new Kernel for a Structured Object requires
the definition of:
‣ Set of features to annotate each part of the object
‣ A Kernel function to measure the similarity on the smallest part
of the object
• e.g., Nodes for AST and Graphs
‣ A Kernel function to apply the computation on the different
(sub)parts of the structured object
18
Part I: Clone Detection
Kernel Methods for Clones:
Tree Kernels Example on AST
‣ Features: We annotate each node by a set of 4
features
• Instruction Class
- i.e., LOOP, CONDITIONAL_STATEMENT, CALL
• Instruction
- i.e., FOR, IF, WHILE, RETURN
• Context
- i.e. Instruction Class of the closer statement node
• Lexemes
- Lexical information gathered (recursively) from leaves
- i.e., Lexical Information
19
FOR
Part I: Clone Detection
Kernel Methods for Clones:
Tree Kernels Example on AST
‣ Kernel Function:
• Aims at identify the maximum
isomorphic Tree/Subtree
20
K(T1, T2) =
X
n2T1
X
n02T2
(n, n0
) · Ksubt(n, n0
)
block
print
p0.0s
=
1.0
=
p
s
f
block
print
y1.0x
=
x
=
y
x
f
Ksubt(n, n0
) = sim(n, n0
) + (1 )
X
(n1,n2)2Ch(n,n0)
k(n1, n2)
DATE: May 13, 2013Part II: Clones and Python
Clone Detection
in Python
DATE: May 13, 2013Part II: Clones and Python
Clone Detection
in Python
Part II: In Python
The Overall Process Sketch
22
1. Pre Processing
Part II: In Python
The Overall Process Sketch
22
block
print
p0.0s
=
1.0
=
p
s
f
block
print
y1.0x
=
x
=
y
x
f
1. Pre Processing 2. Extraction
Part II: In Python
The Overall Process Sketch
22
block
print
p0.0s
=
1.0
=
p
s
f
block
print
y1.0x
=
x
=
y
x
f
block
print
p0.0s
=
1.0
=
p
s
f
block
print
y1.0x
=
x
=
y
x
f
1. Pre Processing 2. Extraction
3. Detection
Part II: In Python
The Overall Process Sketch
22
block
print
p0.0s
=
1.0
=
p
s
f
block
print
y1.0x
=
x
=
y
x
f
block
print
p0.0s
=
1.0
=
p
s
f
block
print
y1.0x
=
x
=
y
x
f
1. Pre Processing 2. Extraction
3. Detection 4. Aggregation
Part II: In Python
Detection Process
23
Part II: In Python
Empirical Evaluation
‣ Comparison with another (pure) AST-based: Clone Digger
• It has been the first Clone detector for and in Python :-)
• Presented at EuroPython 2006
‣ Comparison on a system with randomly seeded clones
24
‣ Results refer only to
Type 3 Clones
‣ On Type 1 and Type 2
we got the same
results
Part II: In Python
Precision/Recall Plot
25
0
0.25
0.50
0.75
1.00
0.6 0.62 0.64 0.66 0.68 0.7 0.72 0.74 0.76 0.78 0.8 0.82 0.84 0.86 0.88 0.9 0.92 0.94 0.96 0.98
Precision, Recall and F-Measure
Precision Recall F1
Precision: How accurate are the obtained results?
(Altern.) How many errors do they contain?
Recall: How complete are the obtained results?
(Altern.) How many clones have been retrieved w.r.t. Total Clones?
Part II: In Python
Is Python less clone prone?
26
Roy et. al., IWSC, 2010
Part II: In Python
Clones in CPython 2.5.1
27
DATE: May 13, 2013Florence, Italy
Thank you!

More Related Content

What's hot

Sun RPC (Remote Procedure Call)
Sun RPC (Remote Procedure Call)Sun RPC (Remote Procedure Call)
Sun RPC (Remote Procedure Call)Peter R. Egli
 
Boyer moore algorithm
Boyer moore algorithmBoyer moore algorithm
Boyer moore algorithmAYESHA JAVED
 
Examen principal - Fondement Multimedia - correction
Examen principal - Fondement Multimedia - correctionExamen principal - Fondement Multimedia - correction
Examen principal - Fondement Multimedia - correctionInes Ouaz
 
Chapitre 4-Apprentissage non supervisé (1) (1).pdf
Chapitre 4-Apprentissage non supervisé (1) (1).pdfChapitre 4-Apprentissage non supervisé (1) (1).pdf
Chapitre 4-Apprentissage non supervisé (1) (1).pdfZizoAziz
 
BigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-ReduceBigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-ReduceLilia Sfaxi
 
Mining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and CorrelationsMining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and CorrelationsJustin Cletus
 
Génie Logiciel.pptx
Génie Logiciel.pptxGénie Logiciel.pptx
Génie Logiciel.pptxLatifaBen6
 
Lecture 16 17 code-generation
Lecture 16 17 code-generationLecture 16 17 code-generation
Lecture 16 17 code-generationIffat Anjum
 
Les algorithmes de génération des règles d association
Les algorithmes de génération des règles d associationLes algorithmes de génération des règles d association
Les algorithmes de génération des règles d associationHajer Trabelsi
 
Datagram vs. virtual circuit
Datagram vs. virtual circuitDatagram vs. virtual circuit
Datagram vs. virtual circuitVikash Gangwar
 
Chap 03 poo en java partie1
Chap 03 poo en java partie1Chap 03 poo en java partie1
Chap 03 poo en java partie1Yassine Badri
 
Introduction au Deep Learning
Introduction au Deep Learning Introduction au Deep Learning
Introduction au Deep Learning Niji
 
Méthodologie de tests et qualité
Méthodologie de tests et qualitéMéthodologie de tests et qualité
Méthodologie de tests et qualitéSpikeeLabs
 

What's hot (20)

L’etat de l’art
L’etat de l’artL’etat de l’art
L’etat de l’art
 
Sun RPC (Remote Procedure Call)
Sun RPC (Remote Procedure Call)Sun RPC (Remote Procedure Call)
Sun RPC (Remote Procedure Call)
 
Metrique
MetriqueMetrique
Metrique
 
Boyer moore algorithm
Boyer moore algorithmBoyer moore algorithm
Boyer moore algorithm
 
Examen principal - Fondement Multimedia - correction
Examen principal - Fondement Multimedia - correctionExamen principal - Fondement Multimedia - correction
Examen principal - Fondement Multimedia - correction
 
Chapitre 4-Apprentissage non supervisé (1) (1).pdf
Chapitre 4-Apprentissage non supervisé (1) (1).pdfChapitre 4-Apprentissage non supervisé (1) (1).pdf
Chapitre 4-Apprentissage non supervisé (1) (1).pdf
 
BigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-ReduceBigData_TP1: Initiation à Hadoop et Map-Reduce
BigData_TP1: Initiation à Hadoop et Map-Reduce
 
Mining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and CorrelationsMining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and Correlations
 
Génie Logiciel.pptx
Génie Logiciel.pptxGénie Logiciel.pptx
Génie Logiciel.pptx
 
Introduction à Python
Introduction à PythonIntroduction à Python
Introduction à Python
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
Lecture 16 17 code-generation
Lecture 16 17 code-generationLecture 16 17 code-generation
Lecture 16 17 code-generation
 
Les algorithmes de génération des règles d association
Les algorithmes de génération des règles d associationLes algorithmes de génération des règles d association
Les algorithmes de génération des règles d association
 
Datagram vs. virtual circuit
Datagram vs. virtual circuitDatagram vs. virtual circuit
Datagram vs. virtual circuit
 
Code generation
Code generationCode generation
Code generation
 
Deep learning
Deep learningDeep learning
Deep learning
 
Drools et les moteurs de règles
Drools et les moteurs de règlesDrools et les moteurs de règles
Drools et les moteurs de règles
 
Chap 03 poo en java partie1
Chap 03 poo en java partie1Chap 03 poo en java partie1
Chap 03 poo en java partie1
 
Introduction au Deep Learning
Introduction au Deep Learning Introduction au Deep Learning
Introduction au Deep Learning
 
Méthodologie de tests et qualité
Méthodologie de tests et qualitéMéthodologie de tests et qualité
Méthodologie de tests et qualité
 

Viewers also liked

Machine Learning for Software Maintainability
Machine Learning for Software MaintainabilityMachine Learning for Software Maintainability
Machine Learning for Software MaintainabilityValerio Maggio
 
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...Kamiya Toshihiro
 
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon Berlin
 
Unsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detectionUnsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detectionValerio Maggio
 
Android Malware Detection Mechanisms
Android Malware Detection MechanismsAndroid Malware Detection Mechanisms
Android Malware Detection MechanismsTalha Kabakus
 
Climbing Mt. Metagenome
Climbing Mt. MetagenomeClimbing Mt. Metagenome
Climbing Mt. Metagenomec.titus.brown
 
PyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filtersPyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filtersc.titus.brown
 

Viewers also liked (9)

Machine Learning for Software Maintainability
Machine Learning for Software MaintainabilityMachine Learning for Software Maintainability
Machine Learning for Software Maintainability
 
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...
 
Clonedigger-Python
Clonedigger-PythonClonedigger-Python
Clonedigger-Python
 
Empirical Results on Cloning and Clone Detection
Empirical Results on Cloning and Clone DetectionEmpirical Results on Cloning and Clone Detection
Empirical Results on Cloning and Clone Detection
 
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
 
Unsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detectionUnsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detection
 
Android Malware Detection Mechanisms
Android Malware Detection MechanismsAndroid Malware Detection Mechanisms
Android Malware Detection Mechanisms
 
Climbing Mt. Metagenome
Climbing Mt. MetagenomeClimbing Mt. Metagenome
Climbing Mt. Metagenome
 
PyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filtersPyCon 2011 talk - ngram assembly with Bloom filters
PyCon 2011 talk - ngram assembly with Bloom filters
 

Similar to Clone detection in Python

Similar to Clone detection in Python (20)

presentation_intro_to_python
presentation_intro_to_pythonpresentation_intro_to_python
presentation_intro_to_python
 
presentation_intro_to_python_1462930390_181219.ppt
presentation_intro_to_python_1462930390_181219.pptpresentation_intro_to_python_1462930390_181219.ppt
presentation_intro_to_python_1462930390_181219.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
Ch3 gnu make
Ch3 gnu makeCh3 gnu make
Ch3 gnu make
 
Parsing
ParsingParsing
Parsing
 
ENGLISH PYTHON.ppt
ENGLISH PYTHON.pptENGLISH PYTHON.ppt
ENGLISH PYTHON.ppt
 
Pcd question bank
Pcd question bank Pcd question bank
Pcd question bank
 
manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptx
 
Kavitha_python.ppt
Kavitha_python.pptKavitha_python.ppt
Kavitha_python.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python Basics
Python BasicsPython Basics
Python Basics
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Lenguaje Python
Lenguaje PythonLenguaje Python
Lenguaje Python
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
 
coolstuff.ppt
coolstuff.pptcoolstuff.ppt
coolstuff.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Introductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.pptIntroductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 

More from Valerio Maggio

Improving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniquesImproving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniquesValerio Maggio
 
Number Crunching in Python
Number Crunching in PythonNumber Crunching in Python
Number Crunching in PythonValerio Maggio
 
LINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviationsLINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviationsValerio Maggio
 
A Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detectionA Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detectionValerio Maggio
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeValerio Maggio
 
Scaffolding with JMock
Scaffolding with JMockScaffolding with JMock
Scaffolding with JMockValerio Maggio
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with JunitValerio Maggio
 
Design patterns and Refactoring
Design patterns and RefactoringDesign patterns and Refactoring
Design patterns and RefactoringValerio Maggio
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentValerio Maggio
 
Unit testing and scaffolding
Unit testing and scaffoldingUnit testing and scaffolding
Unit testing and scaffoldingValerio Maggio
 

More from Valerio Maggio (12)

Improving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniquesImproving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniques
 
Number Crunching in Python
Number Crunching in PythonNumber Crunching in Python
Number Crunching in Python
 
LINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviationsLINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviations
 
A Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detectionA Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detection
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing code
 
Scaffolding with JMock
Scaffolding with JMockScaffolding with JMock
Scaffolding with JMock
 
Junit in action
Junit in actionJunit in action
Junit in action
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Design patterns and Refactoring
Design patterns and RefactoringDesign patterns and Refactoring
Design patterns and Refactoring
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Unit testing and scaffolding
Unit testing and scaffoldingUnit testing and scaffolding
Unit testing and scaffolding
 
Web frameworks
Web frameworksWeb frameworks
Web frameworks
 

Recently uploaded

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Clone detection in Python

  • 1. DATE: May 13, 2013Florence, Italy Clone Detection in Python Valerio Maggio (valerio.maggio@unina.it)
  • 2. Introduction Duplicated Code Number one in the stink parade is duplicated code. If you see the same code structure in more than one place, you can be sure that your program will be better if you find a way to unify them. 2
  • 11. Introduction Duplicated Code ‣ Exists: 5% to 30% of code is similar • In extreme cases, even up to 50% - This is the case of Payroll, a COBOL system 5
  • 12. Introduction Duplicated Code ‣ Exists: 5% to 30% of code is similar • In extreme cases, even up to 50% - This is the case of Payroll, a COBOL system ‣ Is often created during development 5
  • 13. Introduction Duplicated Code ‣ Exists: 5% to 30% of code is similar • In extreme cases, even up to 50% - This is the case of Payroll, a COBOL system ‣ Is often created during development • due to time pressure for an upcoming deadline 5
  • 14. Introduction Duplicated Code ‣ Exists: 5% to 30% of code is similar • In extreme cases, even up to 50% - This is the case of Payroll, a COBOL system ‣ Is often created during development • due to time pressure for an upcoming deadline • to overcome limitations of the programming language 5
  • 15. Introduction Duplicated Code ‣ Exists: 5% to 30% of code is similar • In extreme cases, even up to 50% - This is the case of Payroll, a COBOL system ‣ Is often created during development • due to time pressure for an upcoming deadline • to overcome limitations of the programming language ‣ Three Public Enemies: 5
  • 16. Introduction Duplicated Code ‣ Exists: 5% to 30% of code is similar • In extreme cases, even up to 50% - This is the case of Payroll, a COBOL system ‣ Is often created during development • due to time pressure for an upcoming deadline • to overcome limitations of the programming language ‣ Three Public Enemies: • Copy, Paste and Modify 5
  • 17. DATE: May 13, 2013Part I: Clone Detection Clone Detection in Python
  • 18. DATE: May 13, 2013Part I: Clone Detection Clone Detection in Python
  • 19. Part I: Clone Detection Code Clones ‣ There can be different definitions of similarity, based on: • Program Text (text, syntax) • Semantics 7 (Def.) “Software Clones are segments of code that are similar according to some definition of similarity” (I.D. Baxter, 1998)
  • 20. Part I: Clone Detection Code Clones ‣ There can be different definitions of similarity, based on: • Program Text (text, syntax) • Semantics ‣ Four Different Types of Clones 7 (Def.) “Software Clones are segments of code that are similar according to some definition of similarity” (I.D. Baxter, 1998)
  • 21. Part I: Clone Detection The original one 8 # Original Fragment def do_something_cool_in_Python(filepath, marker='---end---'): lines = list() with open(filepath) as report: for l in report: if l.endswith(marker): lines.append(l) # Stores only lines that ends with "marker" return lines #Return the list of different lines
  • 22. Part I: Clone Detection Type 1: Exact Copy ‣ Identical code segments except for differences in layout, whitespace, and comments 9
  • 23. Part I: Clone Detection Type 1: Exact Copy ‣ Identical code segments except for differences in layout, whitespace, and comments 9 # Original Fragment def do_something_cool_in_Python(filepath, marker='---end---'): lines = list() with open(filepath) as report: for l in report: if l.endswith(marker): lines.append(l) # Stores only lines that ends with "marker" return lines #Return the list of different lines def do_something_cool_in_Python (filepath, marker='---end---'): lines = list() # This list is initially empty with open(filepath) as report: for l in report: # It goes through the lines of the file if l.endswith(marker): lines.append(l) return lines
  • 24. Part I: Clone Detection Type 2: Parameter Substituted Clones ‣ Structurally identical segments except for differences in identifiers, literals, layout, whitespace, and comments 10
  • 25. Part I: Clone Detection Type 2: Parameter Substituted Clones ‣ Structurally identical segments except for differences in identifiers, literals, layout, whitespace, and comments 10 # Type 2 Clone def do_something_cool_in_Python(path, end='---end---'): targets = list() with open(path) as data_file: for t in data_file: if l.endswith(end): targets.append(t) # Stores only lines that ends with "marker" #Return the list of different lines return targets # Original Fragment def do_something_cool_in_Python(filepath, marker='---end---'): lines = list() with open(filepath) as report: for l in report: if l.endswith(marker): lines.append(l) # Stores only lines that ends with "marker" return lines #Return the list of different lines
  • 26. Part I: Clone Detection Type 3: Structure Substituted Clones ‣ Similar segments with further modifications such as changed, added (or deleted) statements, in additions to variations in identifiers, literals, layout and comments 11
  • 27. Part I: Clone Detection Type 3: Structure Substituted Clones ‣ Similar segments with further modifications such as changed, added (or deleted) statements, in additions to variations in identifiers, literals, layout and comments 11 import os def do_something_with(path, marker='---end---'): # Check if the input path corresponds to a file if not os.path.isfile(path): return None bad_ones = list() good_ones = list() with open(path) as report: for line in report: line = line.strip() if line.endswith(marker): good_ones.append(line) else: bad_ones.append(line) #Return the lists of different lines return good_ones, bad_ones
  • 28. Part I: Clone Detection Type 3: Structure Substituted Clones ‣ Similar segments with further modifications such as changed, added (or deleted) statements, in additions to variations in identifiers, literals, layout and comments 11 import os def do_something_with(path, marker='---end---'): # Check if the input path corresponds to a file if not os.path.isfile(path): return None bad_ones = list() good_ones = list() with open(path) as report: for line in report: line = line.strip() if line.endswith(marker): good_ones.append(line) else: bad_ones.append(line) #Return the lists of different lines return good_ones, bad_ones
  • 29. Part I: Clone Detection Type 3: Structure Substituted Clones ‣ Similar segments with further modifications such as changed, added (or deleted) statements, in additions to variations in identifiers, literals, layout and comments 11 import os def do_something_with(path, marker='---end---'): # Check if the input path corresponds to a file if not os.path.isfile(path): return None bad_ones = list() good_ones = list() with open(path) as report: for line in report: line = line.strip() if line.endswith(marker): good_ones.append(line) else: bad_ones.append(line) #Return the lists of different lines return good_ones, bad_ones
  • 30. Part I: Clone Detection Type 3: Structure Substituted Clones ‣ Similar segments with further modifications such as changed, added (or deleted) statements, in additions to variations in identifiers, literals, layout and comments 11 import os def do_something_with(path, marker='---end---'): # Check if the input path corresponds to a file if not os.path.isfile(path): return None bad_ones = list() good_ones = list() with open(path) as report: for line in report: line = line.strip() if line.endswith(marker): good_ones.append(line) else: bad_ones.append(line) #Return the lists of different lines return good_ones, bad_ones
  • 31. Part I: Clone Detection Type 4: “Semantic” Clones ‣ Semantically equivalent segments that perform the same computation but are implemented by different syntactic variants 12
  • 32. Part I: Clone Detection Type 4: “Semantic” Clones ‣ Semantically equivalent segments that perform the same computation but are implemented by different syntactic variants 12 # Original Fragment def do_something_cool_in_Python(filepath, marker='---end---'): lines = list() with open(filepath) as report: for l in report: if l.endswith(marker): lines.append(l) # Stores only lines that ends with "marker" return lines #Return the list of different lines def do_always_the_same_stuff(filepath, marker='---end---'): report = open(filepath) file_lines = report.readlines() report.close() #Filters only the lines ending with marker return filter(lambda l: len(l) and l.endswith(marker), file_lines)
  • 33. Part I: Clone Detection What are the consequences? ‣ Do clones increase the maintenance effort? ‣ Hypothesis: • Cloned code increases code size • A fix to a clone must be applied to all similar fragments • Bugs are duplicated together with their clones ‣ However: it is not always possible to remove clones • Removal of Clones is harder if variations exist. 13
  • 34. Part I: Clone Detection 14 Duplix Scorpio PMD CCFinder Dup CPD Duplix Shinobi Clone Detective Gemini iClones KClone ConQAT Deckard Clone Digger JCCD CloneDr SimScan CLICS NiCAD Simian Duploc Dude SDD Clone Detection Tools
  • 35. Part I: Clone Detection 14 Duplix Scorpio PMD CCFinder Dup CPD Duplix Shinobi Clone Detective Gemini iClones KClone ConQAT Deckard Clone Digger JCCD CloneDr SimScan CLICS NiCAD Simian Duploc Dude SDD ‣ Text Based Tools: • Lines are compared to other lines Clone Detection Tools
  • 36. Part I: Clone Detection 14 Duplix Scorpio PMD CCFinder Dup CPD Duplix Shinobi Clone Detective Gemini iClones KClone ConQAT Deckard Clone Digger JCCD CloneDr SimScan CLICS NiCAD Simian Duploc Dude SDD ‣ Token Based Tools: • Token sequences are compared to sequences Clone Detection Tools
  • 37. Part I: Clone Detection 14 Duplix Scorpio PMD CCFinder Dup CPD Duplix Shinobi Clone Detective Gemini iClones KClone ConQAT Deckard Clone Digger JCCD CloneDr SimScan CLICS NiCAD Simian Duploc Dude SDD ‣ Syntax Based Tools: • Syntax subtrees are compared to each other Clone Detection Tools
  • 38. Part I: Clone Detection 14 Duplix Scorpio PMD CCFinder Dup CPD Duplix Shinobi Clone Detective Gemini iClones KClone ConQAT Deckard Clone Digger JCCD CloneDr SimScan CLICS NiCAD Simian Duploc Dude SDD ‣ Graph Based Tools: • (sub) graphs are compared to each other Clone Detection Tools
  • 39. Part I: Clone Detection Clone Detection Techniques 15 ‣ String/Token based Techiniques: • Pros: Run very fast • Cons: Too many false clones ‣ Syntax based (AST) Techniques: • Pros: Well suited to detect structural similarities • Cons: Not Properly suited to detect Type 3 Clones ‣ Graph based Techniques: • Pros: The only one able to deal with Type 4 Clones • Cons: Performance Issues
  • 40. Part I: Clone Detection The idea: Use Machine Learning, Luke ‣ Use Machine Learning Techniques to compute similarity of fragments by exploiting specific features of the code. ‣ Combine different sources of Information • Structural Information: ASTs, PDGs • Lexical Information: Program Text 16
  • 41. Part I: Clone Detection Kernel Methods for Structured Data ‣ Well-grounded on solid and awful Math ‣ Based on the idea that objects can be described in terms of their constituent Parts ‣ Can be easily tailored to specific domains • Tree Kernels • Graph Kernels • .... 17
  • 42. Part I: Clone Detection Defining a Kernel for Structured Data 18
  • 43. Part I: Clone Detection Defining a Kernel for Structured Data The definition of a new Kernel for a Structured Object requires the definition of: 18
  • 44. Part I: Clone Detection Defining a Kernel for Structured Data The definition of a new Kernel for a Structured Object requires the definition of: ‣ Set of features to annotate each part of the object 18
  • 45. Part I: Clone Detection Defining a Kernel for Structured Data The definition of a new Kernel for a Structured Object requires the definition of: ‣ Set of features to annotate each part of the object ‣ A Kernel function to measure the similarity on the smallest part of the object 18
  • 46. Part I: Clone Detection Defining a Kernel for Structured Data The definition of a new Kernel for a Structured Object requires the definition of: ‣ Set of features to annotate each part of the object ‣ A Kernel function to measure the similarity on the smallest part of the object • e.g., Nodes for AST and Graphs 18
  • 47. Part I: Clone Detection Defining a Kernel for Structured Data The definition of a new Kernel for a Structured Object requires the definition of: ‣ Set of features to annotate each part of the object ‣ A Kernel function to measure the similarity on the smallest part of the object • e.g., Nodes for AST and Graphs ‣ A Kernel function to apply the computation on the different (sub)parts of the structured object 18
  • 48. Part I: Clone Detection Kernel Methods for Clones: Tree Kernels Example on AST ‣ Features: We annotate each node by a set of 4 features • Instruction Class - i.e., LOOP, CONDITIONAL_STATEMENT, CALL • Instruction - i.e., FOR, IF, WHILE, RETURN • Context - i.e. Instruction Class of the closer statement node • Lexemes - Lexical information gathered (recursively) from leaves - i.e., Lexical Information 19 FOR
  • 49. Part I: Clone Detection Kernel Methods for Clones: Tree Kernels Example on AST ‣ Kernel Function: • Aims at identify the maximum isomorphic Tree/Subtree 20 K(T1, T2) = X n2T1 X n02T2 (n, n0 ) · Ksubt(n, n0 ) block print p0.0s = 1.0 = p s f block print y1.0x = x = y x f Ksubt(n, n0 ) = sim(n, n0 ) + (1 ) X (n1,n2)2Ch(n,n0) k(n1, n2)
  • 50. DATE: May 13, 2013Part II: Clones and Python Clone Detection in Python
  • 51. DATE: May 13, 2013Part II: Clones and Python Clone Detection in Python
  • 52. Part II: In Python The Overall Process Sketch 22 1. Pre Processing
  • 53. Part II: In Python The Overall Process Sketch 22 block print p0.0s = 1.0 = p s f block print y1.0x = x = y x f 1. Pre Processing 2. Extraction
  • 54. Part II: In Python The Overall Process Sketch 22 block print p0.0s = 1.0 = p s f block print y1.0x = x = y x f block print p0.0s = 1.0 = p s f block print y1.0x = x = y x f 1. Pre Processing 2. Extraction 3. Detection
  • 55. Part II: In Python The Overall Process Sketch 22 block print p0.0s = 1.0 = p s f block print y1.0x = x = y x f block print p0.0s = 1.0 = p s f block print y1.0x = x = y x f 1. Pre Processing 2. Extraction 3. Detection 4. Aggregation
  • 56. Part II: In Python Detection Process 23
  • 57. Part II: In Python Empirical Evaluation ‣ Comparison with another (pure) AST-based: Clone Digger • It has been the first Clone detector for and in Python :-) • Presented at EuroPython 2006 ‣ Comparison on a system with randomly seeded clones 24 ‣ Results refer only to Type 3 Clones ‣ On Type 1 and Type 2 we got the same results
  • 58. Part II: In Python Precision/Recall Plot 25 0 0.25 0.50 0.75 1.00 0.6 0.62 0.64 0.66 0.68 0.7 0.72 0.74 0.76 0.78 0.8 0.82 0.84 0.86 0.88 0.9 0.92 0.94 0.96 0.98 Precision, Recall and F-Measure Precision Recall F1 Precision: How accurate are the obtained results? (Altern.) How many errors do they contain? Recall: How complete are the obtained results? (Altern.) How many clones have been retrieved w.r.t. Total Clones?
  • 59. Part II: In Python Is Python less clone prone? 26 Roy et. al., IWSC, 2010
  • 60. Part II: In Python Clones in CPython 2.5.1 27
  • 61. DATE: May 13, 2013Florence, Italy Thank you!