Giulio's Notes about programming
Shell
Command |
description |
chmod +x fileName.sh |
compile the code and make it executable |
./fileName.sh |
execute fileName.sh |
source fileName.sh |
execute as source code (equivalent to chmod +x and ./ but as source) |
Basic Shell Commands
Command |
description |
echo something |
print something. It is equivalent to echo "something" |
read VAR |
equivalent to c++ std::cint. It read VAR as "VAR" |
Variables
Command |
description |
${VAR:-pippo} |
use the variable VAR. If VAR has not been declared, use pippo |
${VAR:=pippo} |
use the variable VAR. If VAR has not been declared, set VAR = pippo |
shift |
delete $1 Record $2 as $1, record $3 as $2, etc... |
$@ |
list all the position parameters |
$# |
return the number of position parameters |
$IFS" |
Internal Field Separator. It is the char(letter) that divide different parameters in reading (look the example below). |
Array
Declarization is initializazione and can be given in three ways:
arr=([2]="Hello" [3]="World!")
arr=("I" "am" "a" "Programm")
Command |
description |
unset arr[1] |
delete the element arr[1]. The other elements will keep the position |
${array[@]:1:2} |
delete the element arr[1]. The other elements will keep the position |
${#array[@]} |
delete the element arr[1]. The other elements will keep the position |
Some simple bash programmes
To find what tree is missing:
for i in $(seq 0 1 333); do ls skimmed_tree_$i.root; done | grep cann
There is a IFS manipolation example here:
#!/bin/bash
old_IFS="$IFS"
IFS=:
echo "Inserisci tre dati separati da due punti ..."
read x y z
IFS=$old_IFS
echo "x è $x y è $y z è $z"
If you want to enlist some files with a space in between:
`ls ${path}/tree_*.root`
python macro.py `ls ${path}/tree_*.root`
C++
TLorentzVector TLV;
TLorentzVector TLV;
TLV.SetPxPyPzE(px, py, pz, e)
TLV.SetPtEtaPhiM(pt, eta, phi, m)
theta = TLV.Theta();
cost = TLV.CosTheta();
phi = TLV.Phi();
eta = TLV.PseudoRapidity ()
m2 = TLV.Mag2() = TLV.M2();
m = TLV.Mag() = TLV.M();
s = TLV1*TLV2; = v1.Dot(v2);
TVector3 v = TLV.Vect()
Reading and writing files
#include <stdio.h>
int main(int argc, char **argv) {
FILE *in, *out;
int c;
in = fopen("input.txt", "r");
out = fopen("output.txt", "w");
while ((c = fgetc(in)) != EOF) {
fputc(c, out);
}
fclose(out);
fclose(in);
}
atoi
#include <stdlib.h> /* atoi is in stdlib.h */
int i;
char c = "1";
i = atoi (c);
ofstream
The official page is
here
ofstream out_name;
out_name.open("out_name.txt");
out_name << std::setprecision(8) << histos[0]->Integral(0,histos[0]->GetNbinsX()+1) << endl;
out_name.close();
String
A page is
here
. You have to include:
#include <string>
Command |
description |
str.find(str2) |
return the position of the first character of the first match. If no matches were found, the function returns string::npos. |
list.insert(6,"Golf") |
insert "Golf" as list[6] and shift the following |
For any doubt about Lorentz Vector there is the
official page
. You have to include
#include "TLorentzVector.h"
TLorentzVector TLV;
TLorentzVector TLV;
TLV.SetPxPyPzE(px, py, pz, e)
TLV.SetPtEtaPhiM(pt, eta, phi, m)
theta = TLV.Theta();
cost = TLV.CosTheta();
phi = TLV.Phi();
eta = TLV.PseudoRapidity ()
m2 = TLV.Mag2() = TLV.M2();
m = TLV.Mag() = TLV.M();
s = TLV1*TLV2; = v1.Dot(v2);
TVector3 v = TLV.Vect()
TLorentzVector MyParticle1(P1_PX, P1_PY, P1_PZ, P1_E);
TLorentzVector MyParticle2(P2_PX ,P2_PY, P2_PZ, P2_E);
TLorentzVector Particle_CM = MyParticle1 + MyParticle2;
TVector3 Particle_CM_BoostVector = Particle_CM.BoostVector();
TLorentzVector MyParticle1_newSys = MyParticle1_CMS;
MyParticle1_newSys.Boost(Particle_CM_BoostVector);
Python
You can find everything about python
here
import
Command |
description |
import somefile |
Everything in somefile.py gets imported. To refer to something in the file, append the text “somefile.” to the front of its name. |
from somefile import * |
Everything in somefile.py gets imported. To refer to anything in the module, just use its name. Every-thing in the module is now in the current namespace. NB Using this import command can easily overwrite the definition of an existing function or variable! |
from somefile import className |
Only the item className in somefile.py gets imported. After importing className, you can just use it without a module prefix. It’s brought into the current namespace. NB Overwrites the definition of this name if already defined in the current namespace! |
The help() and dir() builtins allow you to check what you have included so far and how to use it ( notice
the __ of modules imported by default)
dir() [-5:] #enlist the last 5 variable declared
help(math.sqrt) #describe math.sqrt
Basic commands
Some common commands are:
Command |
description |
print(a, b) |
print a and b |
a = input("Enter a string: ") |
print "Enter a string: " and inizialize a |
3//2 |
equivalent to int(3./2.) |
3%2 |
remainder of the division |
Every word can be used except for :
and, as, assert, break, class, continue, def, del, elif, else, except,
exec, finally, for, from, global, if, import, in, is, lambda, not, or,
pass, print, raise, return, try, while, with, yield
Builtins
Command |
description |
type(object) |
return the type of object |
range(start,end,step) |
return integers from start to end. start=0, step=1 are default |
enumerate(N) |
range(1,N,1) |
sum([1,2,3,4.]) |
return 10.0 |
abs(x) |
absolute value |
sorted([5, 2, 3, 1, 4]) |
return [1, 2, 3, 4, 5], a useful page about sorting is here |
sorted(iterable, key=None, reverse=False) |
the iterable can be sorted with a key function and in ascending or descending order |
map(function_to_apply, list_of_inputs) |
it returns a list. the elements of list_of_inputs are passed to function_to_apply one by one |
filter(function_to_apply, list_of_inputs) |
creates a list of list_of_inputs'elements for which function_to_apply returns true |
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
Write in a text file
outputFile = "source.txt"
outputName = open(outputFile, 'w') # 'w' = rewrite , 'a' = append
print >> outputName , " variable \t", x
outputName.close()
String
"qwe"+"rty" == "qwerty"
"qwe"*3 == "qweqweqwe"
mystring = "qwerty" , mystring[3] == "r"
Let mystring be a string
Command |
description |
mystring.capitalize() |
return mystring with the first letter capitalized |
mystring.replace(" ","++") |
replace each " " with "++" in mystring |
mystring.lower() |
return mystring with all the letters tined |
mystring.upper() |
return mystring with all the letters capitalized |
mystring.isalpha() |
True if there are only alphabetic char |
mystring.isdigit() |
True if there are only numerical char |
mystring.islower() |
True if there are only tiny letters |
mystring.isspace() |
True if there are only spaces e.g. " ".isspace() = true |
mystring.isupper() |
True if there are only capital letters |
mystring.count("test") |
count how many "test" there are in mystring |
mylist = list(mystring) |
return a list made of the letters of mystring |
mystring.join(sequence) |
|
mystring.startswith("x") |
return True if the string begin with "x" |
mystring.endswith("x") |
return True if the string end with "x" |
mystring.find() |
|
mylist = mystring.split() |
return a list of strings. Each string in the list is a word of mystring |
mylist = mystring.split("x") |
return a list of strings. Strings in the list are pieces of mystring separated by "x" |
Lists
L = [] #or L = list()
list = range(0,4)
list + ["a", "b", "c"] == [0, 1, 2, 3, 'a', 'b', 'c']
list[2] == 2
Command |
description |
list.append("Golf") |
add "Golf" as element in the end |
list.insert(6,"Golf") |
insert "Golf" as list[6] and shift the following |
list.len() |
number of element in the list |
list[start:stop:step] |
enlist as range() do. Defaults are: start = 0, stop = -1, step = 1 |
list [-1::-1] |
reverse the list |
list.sort() |
sort the elements |
list.pop() |
return the lastelement of list and delete it from the list |
Tuples
A tuple is a sequence object like a list or a string. It’s constructed by grouping a sequence of objects together with commas, either without brackets, or with parentheses. At variance with list, tuples are immutable, they don’t have append, insert or pop methods
T = () #or T = tuple()
t = (0,1,2,3)
t + ("a", "b", "c") == [0, 1, 2, 3, 'a', 'b', 'c']
t[2] == "2"
You cannot set
t[2] = 2
Dictionaries
D=dict(); D1= {}; D2={0:"q",1:"w"} # 3 different declaration and initialization
D['A'] = 2.1
D['ab'] ='proline'
D[1] = 2.1
"A" in D == True
Command |
description |
dict.keys() |
enlist all the keys |
dict.values() |
enlist all the values |
del dict["A"] |
delete element with key "A" |
dict.items()( |
enlist all objects in couple (key,value) |
dict.values( |
enlist all the values |
dict.values( |
enlist all the values |
dict.values( |
enlist all the values |
Loop over a dictionary
for k,val in dict.items() :
if k == WantedKeys :
V = val
Set
Command |
description |
%run script.py |
execute script.py |
myset = set(not_a_set) |
return a set with the element of la list, a tuple or a string |
set1.union(set2) |
return the set union. It does not modify set1 |
set1.intersection(set2) |
return the set intersection. It does not modify set1 |
set1.difference(set2) |
return the set difference. It does not modify set1 |
set1.symmetric_difference(set2) |
return the set symmetric difference. It does not modify set1 |
Regular expressions
Interactive Python (IPython)
Command |
description |
%run script.py |
execute script.py |
%reset |
clear all namespace |
%hist |
print history |
%xdel |
delete variables |
%who |
list objects in enviroment (use in combo with ? to know who is who) |
Reading and writing files
Command |
Description |
open(filename, mode) |
‘r’ (Read), ‘w’ (Write), ‘a’ (Append). If a file opened for ‘w’ does not exist it will be created |
f.readline() |
read a single line from a file. Returns a string. |
f.readlines([size]) |
read all the lines up to size bytes and return them in a iterator of s |
f.read([size]) |
read up to size bytes; returns a string |
f.write(text) |
write text to file |
This is an exmple of how write a file into an other
in = open("input.txt", "r")
out = open("output.txt", "w")
out.writelines.(in)
in = close()
out = close()
or
open("output.txt", "w").writelines.(open("input.txt", "r"))
You can also write silngle lines
out.writelines.("This is line 1\nThis is line 2")
Time
import time
start_time = time.time()
do something ....
timeElapsed = time.time() - start_time
Numpy
import numpy as np
Command |
Description |
a=np.array([(1,2,3,4),(5,6,7,8)]) |
|
a.size |
|
a.shape |
return the shape (the dimansions) |
a=a-10; a=a*2 |
operations on numpy array |
a.T |
transpose. Equivalent to a.transpose() |
np.max(a) |
max. Also a.max() |
np.mean(a) |
mean. Also a.mean() |
np.mean(a[0]) |
mean on the first row |
a.std() |
max |
b=a[1].copy() |
make a copy. If you reassign b, a will not change |
unionArray = np.concatenate((a1,a2,a3)) |
merge several arrays |
Creation of numpy array
np.zeros((3,3),'d') |
3x3 numpy array made of 0 |
np.ones((3,3)) |
3x3 numpy array made of 1 |
np.eye(3) |
3x3 identity |
np.arange(1,10) |
array([1, 2, 3, 4, 5, 6, 7, 8, 9]) |
np.arange(2.3,3.3,.1) |
array([ 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2]) 0.1is the space |
np.linspace(2.3,3.2,10)) |
array([ 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2]) 10 is the number of elements |
a=np.array(list(map(bool,(0,1,0,1,1,0,1)))) |
a=np.array(list(map(bool,(0,1,0,1,1,0,1)))) |
np.arange(2.3,3.3,.1) |
array([ 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2]) |
np.arange(2.3,3.3,.1) |
array([ 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2]) |
If "table.txt" contains
0 1 2
3 4 5
6 7 8
Then you can read it and create a numby array simply by:
np.loadtxt("table.txt")
How to plot in jupyter notebook
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
npoints = int(10e2)
x = np.random.rand(npoints)
y = np.random.rand(npoints)
plt.scatter(x,y,marker='o',s=10,color='r')
colorInNumpyArray= np.ones(1000)
plt.scatter(x,y, c = colorInNumpyArray)
Skipy
import scipy as sp
import sklearn
from sklearn import datasets
import sklearn.preprocessing
from sklearn.decomposition import PCA
Creation of
from sklearn import datasets
import sklearn.preprocessing
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
A tutorial is
here
from matplotlib import pyplot as plt
plt.plot(xList, yList) |
plot a graph of (xList, yList) |
plt.plot(xList, yList, color='b', linestyle='--', marker='.', linewidth=2, label='thisPlot') |
plot a graph of (xList, yList) |
plt.xlabel('Ages') |
set the x label |
plt.ylabel('Efficiency') |
set the y label |
plt.title('This is ....') |
set the title |
plt.grid(True) |
set the title |
plt.xscale('log') |
set log scale in x axis |
plt.legend() |
plot the legend |
plt.legend(loc = "upper left") |
plot the legend in the upper left |
plt.legend(loc =(0.01, 0.9)) |
plot the legend in the upper left |
plt.savefig('plot.png') |
save the plot |
plt.show() |
show the canvas |
Plot types
plt.plot(xList, yList) |
plot a graph of (xList, yList) |
plt.plot(xList, yList, color='b', linestyle='--', marker='.', linewidth=2, label='thisPlot') |
plot a graph of (xList, yList) |
plt.bar(xList, yList) |
plot a histogram of (xList, yList) |
plt.bar(xList, yList, width = 0.25, color='b', label='thisPlot') |
plot a histogram of (xList, yList) |
plt.barh(xList, yList) |
plot a histogram of xList as a function of yList |
plt.pie(pieList) |
plot a pie of pieList |
plt.pie(pieList, labels=labelList, colors=colList, wedgeprops={"edgecolor":"black"}) |
plot a pie of pieList |
plt.pie(pieList, labels=labelList, explode=[0,0,01,0,....]) |
plot a pie of pieList with some enlighted slices |
plt.pie(pieList, labels=labelList,shadow=True, startangle=90) |
plot a pie of pieList |
plt.pie(pieList, labels=labelList,autopc='%1.1f%%') |
plot a pie of pieList with percent values |
plt.stackplot(xList, y1List, y2List, y3LIst) |
plot a stack plot |
plt.stackplot(xList, y1List, y2List, labels=labList, colors=colList) |
plot a stack plot |
plt.hist(List, bins=5) |
plot a histogram with 5 bins |
plt.hist(ages, bins=bins, edgecolor='black', log=True) |
plot a histogram with 5 bins |
plt.scatter(xList, yList) |
2D plot of x-y lists |
plt.scatter(xList, yList, s = 2, c="green", marker="X") |
2D plot of x-y lists of green X of size 2 |
plt.scatter(xList, yList, edgecolor='black', linewidth=1, alpha=0.75) |
2D plot of x-y lists |
plt.scatter(view_count, likes, c=ratio, cmap='summer') |
2D plot of x-y lists, example of colormap |
plt.plot_date(dateList, yList) |
plot line histogram with dates |
Set the axis
plt.xlabel('Ages') |
set the x label |
plt.ylabel('Efficiency') |
set the y label |
plt.xticks(ticks = xTick, label = xLab) |
Draw the label xLab but use xTick as ticks |
Set the Style
print(plt.style.available) |
print the list of available styles |
plt.style.use("ggplot") |
set ggplot style |
plt.style.use("seaborn") |
set seaborn style |
plt.xkcd() |
set xkcd comic style |
plt.tight_layout() |
set tighter pad |
fig, ax = plt.subplots() |
create a canvas |
fig, ax = plt.subplots(nrow=2, ncol=2) |
create a canvas with 2x2 pads |
fig, ax = plt.subplots(nrow=2, ncol=2, sharex=True) |
create a canvas shared x axis |
fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()
ax1.plot(xList1, yList1, label='All Devs')
ax2.plot(xList2, yList2, label='Python')
ax1.legend()
ax1.set_title('title') #setting titles has different function for a
ax1.set_ylabel('yLabel')
ax2.legend()
ax2.set_xlabel('xLabel')
plt.show()
fig1.savefig('fig1.png')
fig2.savefig('fig2.png')
Plotting dates
dates = [
datetime(2020, 6, 24),
datetime(2020, 6, 27),
datetime(2020, 6, 30)
]
y = [0, 1, 3]
plt.plot_date(dateList, yList)
plt.gcf().autofmt_xdate() # GetCurrentFigure automatic format for dates
from matplotlib import dates as mpl_dates
date_format = mpl_dates.DateFormatter("%d %b %Y") # decide the format, https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
plt.gca().xaxis.set_major_formatter(date_format) # set the format
dates = pd.to_datetime(datesStringList) # create a list of string of dates "2020-05-30" in list of datetime(2020, 5, 30)
dates.sort_values('Date') # sort dates by date
#newDates.sort_values('Date', inplace=True) # equivalent to dates = dates.sort_values('Date')
Live data in real time example:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')
def animate(i):
data = pd.read_csv('data.csv')
x = data['x_value']
y1 = data['total_1']
y2 = data['total_2']
plt.cla()
plt.plot(x, y1, label='Channel 1')
plt.plot(x, y2, label='Channel 2')
plt.legend(loc='upper left')
plt.tight_layout()
ani = FuncAnimation(plt.gcf(), animate, interval=1000) # execute animate function avery interval: 1000 is one second (I think ani= is useless)
Other
plt.fill_between(xList, y1List, Aconstant) |
fill the area between a line and a constant or another line. Default constant is 0 |
plt.fill_between(ages, y1List, y2List, where=(y1List<= y1List),interpolate=True, color='red', alpha=0.25, label='Below Avg') |
fill the area between two lines |
Draw a vertical line:
median_age = 29
color = '#fc4f30'
plt.axvline(median_age, color=color, label='Age Median', linewidth=2)
colorbar:
cbar = plt.colorbar()
cbar.set_label('Like/Dislike Ratio')
Pandas temporaney position
data = pd.read_csv('2019-05-31-data.csv')
view_count = data['view_count']
likes = data['likes']
ratio = data['ratio']
Deep Learning
Supervised Learning
%matplotlib inline
import sklearn
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data #data
Y = iris.target #true
iris.target_names #it shows the names the number in target mean
from sklearn.svm import LinearSVC
clf = LinearSVC()
clf.fit(X,Y)
X_new = [[1,2,3,4]]
X_new = np.asarray(X_new)
clf.predit(X_new)
iris = datasets.load_iris()
X = iris.data #data
Y = iris.target #true
iris.target_names #it shows the names the number in target mean
from sklearn.svm import linearSVC
clf = linearSVC()
clf.fit(X,Y)
X_new = [[1,2,3,4]]
X_new = np.asarray(X_new)
clf.predict(X_new)
iris = datasets.load_iris()
X = iris.data #data
Y = iris.target #true
iris.target_names #it shows the names the number in target mean
from sklearn.svm import linearSVC
clf = linearSVC()
clf.fit(X,Y)
X_new = [[1,2,3,4]]
X_new = np.asarray(X_new)
clf.predit(X_new)
Unsupervised Learning
There are many methods, one of them is Principle Component Analysis (PCA).
Here there is an example of unsupervised learning using KMeans.
%matplotlib inline
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data #data
Y = iris.target
kmea = KMeans(n_clusters = 2) # 'n_clusters' is the number of cluster you will have
kmea.fit_predict(X)
plt.scatter(X[:,0], X[:,1], c=kmea.labels_)
Here there is an example of unsupervised learning using DBSCAN.
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
data = some data in a numpy array
estimator = DBSCAN(eps=0.35, min_samples=12,metric="euclidean")
clusters = estimator.fit_predict(data)
print(set(clusters))
plt.scatter(data[clusters==0,0],data[clusters==0,1],c="r")
plt.scatter(data[clusters==1,0],data[clusters==1,1],c="b",alpha=0.5)
plt.axis("equal")
MadGraph
First you have to say the events
generate p p > mu+ mu-
generate p p > z > mu+ mu- QED=2 QCD=0
generate p p > z h , z > mu+ mu- , (h > z l+ l-, z > l+ l-)
generate p p > mu+ mu- /a if you don't want to have photon in the diagrams
Adding other source is possible
add process p p > b b~
Then you must create the folder
output folderName
Then you launch madgraph
launch folderName
Display
Command |
description |
display particles |
return the names al all trhe particel in the model |
display multiparticles |
return the name of the sets of particel (e.g. l = e,mu) |
display diagrams |
draw feymnan dyagrams |
display processes |
show the process from inital to final states |
Set parameters without editing the cards
set ebeam1 65000
set ebeam2 65000
set MT 172.
done
Event generation in CMSSW
In
this page and
this other page there are the instruction to generate events with CMSSW environment.
First step: GridPack production
At first, without set cms environment:
git clone http://github.com/cms-sw/genproductions.git genproductions
cd genproductions/bin/MadGraph5_aMCatNLO/
./gridpack_generation.sh <name of process card without _proc_card.dat> <folder containing cards relative to current location> <queue>
./gridpack_generation.sh DYJets_4f_LO cards/examples/DYJets_4f_LO local
gridpackTest (you have to do cmsenv)
tar -xavf <path of gridpack creation>/DYJets_4f_LO_tarball.tar.xz
bash
./runcmsgrid.sh <NEvents> <RandomSeed> <NumberOfCPUs>
lhe to root without hadronization
In a new area (but the same
CMS release):
cmsenv
git cms-addpkg GeneratorInterface/LHEInterface
curl -s --insecure http://cmsdoc.cern.ch/~vciulli/CMSDASBari/run_generic_tarball_cvmfs.sh --retry 2 --create-dirs -o GeneratorInterface/LHEInterface/data/run_generic_tarball_cvmfs.sh
chmod u+x GeneratorInterface/LHEInterface/data/run_generic_tarball_cvmfs.sh
curl -s --insecure http://cmsdoc.cern.ch/~vciulli/CMSDASBari/wellnu012j_5f_LO_MLM_7TeV-fragment.py --retry 2 --create-dirs -o Configuration/GenProduction/python/wellnu012j_5f_LO_MLM_7TeV-fragment.py
scram b
cd $CMSSW_BASE
mkdir work
cd work
I renamed wellnu012j_5f_LO_MLM_7TeV in DYJets_4f_LO_MLM_13TeV.
Put the right gridPack in the configuration file Configuration/GenProduction/python/wellnu012j_5f_LO_MLM_7TeV-fragment.py and
cmsDriver.py Configuration/GenProduction/python/DYJets_4f_LO_MLM_13TeV-fragment.py --fileout file:DYJets_4f_LO_MLM_13TeV.root --mc --eventcontent LHE --datatier GEN --conditions auto:mc --step LHE --python_filename DYJets_4f_LO_MLM_13TeV_1_cfg.py -n 1000
Second step: hadronization
Now you should generate hadronization.
First thing to di is to copy the configuration file you need from
here and put it in Configuration/GenProduction/python/.
Then, in a new area (but the same
CMS release):
cd $CMSSW_BASE/src
scram b
cd $CMSSW_BASE/work
if the config file is
Configuration/GenProduction/python/Hadronizer_DYJets_4f_LO_MLM_13TeV_qcut20_cff.py
:
cmsDriver.py Configuration/GenProduction/python/Hadronizer_DYJets_4f_LO_MLM_13TeV_qcut20_cff.py --fileout file:DYJets_4f_LO_MLM_13TeV_qcut20_GEN.root --mc --eventcontent RAWSIM --datatier GEN-SIM --conditions auto:mc --beamspot NominalCollision2015 --step GEN --python_filename DYJets_4f_LO_MLM_13TeV_qcut20_GEN_1_cfg.py --filein file:DYJets_4f_LO_MLM_13TeV.root -n 1000
HTML5
<header></header>
<footer></footer>
<aside></aside>
<main></main>
<article></article>
<nav></nav>
<section></section>
<details></details>
Basics
head |
make a head of the page |
body |
make the body of the page |
br |
break line. It doesn't need |
hr |
make an horizontal line |
div |
make a division. It's a block |
<!DOCTYPE html>
<html>
<head>
<title> title of the page </title>
<script src="https://twiki.cern.ch/twiki/pub/TWiki/ChecklistPlugin/itemstatechange.js" language="javascript" type="text/javascript"></script></head>
<body>
<!-- Headings -->
<h1> head1 </h1>
<h2> head2 </h2>
<h3> <strong> head13 </strong> </h3><!-- bold -->
<h4> <em>head14 </em></h4> <!-- Italics -->
<h5> head15 </h5>
<h6> head16 </h6>
<small> some details in small </small>
<p>
<!-- Paragraph -->
<a href="https://it.wikipedia.org/wiki/Lorem_ipsum" target="_blank">Lorem ipsum</a> dolor sit amet, consectetur adipisci elit, sed do eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrum exercitationem ullamco laboriosam, nisi ut aliquid ex ea commodi consequatur. Duis aute irure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</p>
</body>
</html>
Table
table |
make a new table |
thead |
make the head of the table |
tbody |
make the bosy of the table |
th |
make an entry in the table head |
tr |
make a new row in the body of the table |
td |
make a data in the raw of the body |
<!DOCTYPE html>
<table>
<thead> <!-- Table head -->
<th> name </th>
<th> surname </th>
</thead>
<tbody> <!-- Table body -->
<tr> <!-- Table row -->
<td> Giulio </td>
<td> Mandorli </td>
</tr>
<tr>
<td> Gianni </td>
<td> Morandi </td>
</tr>
</tbody>
</table>
Form
<!DOCTYPE html>
<!-- Form: submit the information to something.php -->
<form action="something.php" method="POST">
<div>
<label> first name </label>
<input type = "text" name="firstName" placeholder="Eneter first name">
</div>
<div>
<label> first name </label>
<input type = "text" name="lastName">
</div>
<div>
<label> Email </label>
<input type = "email" name="email">
</div>
<div>
<label> Message </label>
<textarea name="message"></textarea>
</div>
<div>
<label> Gender </label>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
<div>
<label>Age </label>
<input type="number" name="age">
</div>
<div>
<label>Birthday </label>
<input type="date" name="birthdate">
</div>
<input type="submit" name="submit" value="Submit Request">
</form>
Quotation
<!DOCTYPE html>
<!-- Quotation -->
<a href="https://it.wikipedia.org/wiki/Lorem_ipsum" target="_blank">Lorem ipsum</a>
<blockquote cite="https://it.wikipedia.org/wiki/Lorem_ipsum">
Lorem ipsum dolor sit amet
</blockquote>
The <abbr title="Compact Muon Solenoid">CMS</abbr> is awesome <!-- abbreviation -->
<cite>GiulioProgrammingLanguages</cite> is the best page for dummies
Image
img src="littleWhale.jpg" |
put an image. Self closing tag |
img src="littleWhale.jpg alt="myIma" |
put an image. Write "myIma" if file is not fiund |
img src="littleWhale.jpg" width=200 height=100 |
put an image. Set width and height in pixels |
<a href="Whale.jpg"><img src="Whale.jpg"></a> <!-- put an image. When you click on it, it shows only the image -->
Other
ul |
make unordered list |
ol |
make ordered list |
li |
entry of the list |
"<"button">" click here "</"button">" |
it creates a useless button |
© |
© |
css
<!DOCTYPE html>
<!-- --------------------------- Inline --------------------------- -->
<h1 style="color:red">Hello</h1>
<!-- --------------------------- Insight --------------------------- -->
<head>
<title>MyTitle</title>
<style type="text/css">
h1{
color:red;
}
</style>
</head>
<!-- --------------------------- External --------------------------- -->
<head>
<title>MyTitle</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
Basics
body{
background-color:#f4f4f4; /* */
color:#999999; /*text color */
font-family:Arial, Helvetica; /*font style. Helvetica only if Arial is not found */
font-size:20px; /*set 20 pixels */
font-weight: bold, normal; /*set bold*/
line-height:1.6em; /*1.6 times normal line space*/
}
class
.container{ /* container class defined in the html*/
width:80%;
margin:auto;
border-radio:15px; /* border with curves edges*/
border-right:5px red solid;
border-left:5px red solid;
border-top:5px red solid;
border-bottom:5px red solid;
/*same as*/
border:5px red solid;
/*same for margin and padding*/
margin:20px;
padding:20px;
font-style:italic;
font-size:50px;
text-decoration:underline;
text-transform:uppercase;
letter-spacing:0.2em;
word-spacing:1.2em;
}
.container{
h1{ .... }
}
/* equivalent to */
.container h1{
....
}
Link style
a{
text-decoration:none /*no default underline*/
color:black;
}
a:hover{
color:red;
}
a:active{
color:green;
}
a:visited{
color:yellow;
}
Form
.my-form{
padding:20px;
}
.my-form .form-group{ /* form-group class inside my-form class */
padding-bottom:15px;
}
.my-form label{ /* nicer */
display:block;
}
.my-form input[type="text"], .my-form textarea{ /* same style for two classes */
margin:auto;
padding:8px;
width:100%
}
.my-form input[type="submit"] { /* style for inputs with type submit */
background-color:#333;
color:white;
padding:10px 15px;
border:none;
}
Flexbox
.block1{
float:left;
width:33.3%;
border:1px dotted;
pading:10px;
box-sizing:border-box; /* get the width of the whole box, not just the content */
}
// you have to use <div class="clr"> <div> for clearing, with the style
.clr{
clear:both;
}
Example of side bar and call by id
<div id="mainBlock">
<h3>head </h3>
<p>Con il termine lorem ipsum si indica un testo segnaposto utilizzato da grafici, designer, programmatori e tipografi a modo riempitivo per bozzetti e prove grafiche. </p>
</div>
<div id="sideBar">
<p>Con il termine lorem ipsum si indica un testo segnaposto utilizzato da grafici, designer, programmatori e tipografi a modo riempitivo per bozzetti e prove grafiche. </p>
</div>
in the css
#mainBlock{
float:left;
width:70%;
box-sizing:border-box;
}
#sideBar{
float:right;
width:30%;
box-sizing:border-box;
}
Positioning
Static
Relaltive
Absolute
Fixed
Initial
Inherit
h1 position is relative to p-box
.p-box{
width:800px;
height:500px;
border:2px solid black;
margin-top:30px;
position:relative;
}
.p-box h1{
position:absolute;
top:150px;
left:20px
}
Position is fixed in scrolling the page
.fixedButton{
position:fixed;
top:50px;
}
Other
ol{
list-style:square;
border:10px;
}
.my-list li:first-child{
background:red;
}
.my-list li:last-child{
background:blue;
}
.my-list li:nth-child(3){
background:red;
}
.my-list li:nth-child(odd){
background:#aaaaaa;
}
.aBlock{
background-image:url("Whale.jpg");
background-position:100px 200px;
background-repeate:none;
}
@media(max-width=600px){
#mainBlock{
width:100%;
float:none;
}
#sideBar{
width:100%;
float:none;
}
}
<script>
alert("Hello World") <!-- in the html file -->
</script>
<script src="example.js"></script> <!-- from an external file -->
Here
there is a documentation of some methods for java
Variables are
//var, let, const can be used to declare variables
let n = 0; // number
let s = "Hello World"; // string
let b = false //boolean
let u=undefined; // undefined
let x = null; //null
g = "Hi World"; // without var keyword the variable is global
let n = 0;
const = 0;
console.log(typeof x) |
print the type of x |
String
s.lenght |
lenght of the string s |
s[0] |
first element of the string s |
s[0] = "A" |
not allowed. Strings are immutable |
s.toUpperCase() |
set the string to upper case |
s.substring(2,5) |
return the substring |
s.split(" ") |
split and return the array with the substrings |
JSON.stringify(arrayExample) |
transform the array into a string |
var s = "I am $(person.age) years old" //works only with quotation marks instead of "
Arrays and dictionaries
Arrays
var arrayExample = ["pizza", 5, ["nested", 1]];
arrayExample[2][1] = "one";
arrayExample[2][1] = "one" |
change the element of an array |
arrayExample.push(2.5) |
push back 2.5 as last element of the array |
arrayExample.pop() |
remove last element of the array. It returns the removed element |
arrayExample.shift() |
remove first element of the array. It returns the removed element |
arrayExample.unshift("new first element") |
add the element as first |
arr1.concat(arr2) |
concatenate the arrays |
newA = arr.filter(x => x=0) |
filter function for arrays |
newA = arr.map(x => x*x) |
map function for arrays |
var [x,y, , z, ...arr] = [1,2,3,4,5,6,7] |
copy the elements: x=1, y=2, z=4, arr=[5,6,7] |
Dictionaries
var ourDict = {
"prova1" : "pizza",
"metro" : [1,2,3],
"x": "uu",
12: "dodici"
}
//Equivalent to
var ourDict = {
prova1 : "pizza",
metro : [1,2,3],
x: "uu",
12: "dodici"
}
ourDict.x |
access the variable identified with "x" keyword |
ourDict["x"] |
access the variable identified with "x" keyword |
ourDict.newProperty = 5 |
create a new key "newProperty" and assign 5 |
delete ourDict.x |
remove a key from the dictionary |
ourDict.hasOwnProperty("y") |
check if ourDict has the property "y" |
var {"x": xVal} = ourDict |
copy the value ourDict.x in the variable xVal |
Array methods
// Loop
for (let x of arrayExample) { ... }
arrayExample.forEach(function(x) { ... } );
let new = arrayExample.map(function(x) { return x*x } );
let newA =arrayExample.filter(function(x) { return x>0 } );
Functions
Sintax for function is
function exampleFunction (v, a=1) {
console.log(v, a)
}
exampleFunction("a");
exampleFunction(2);
var myV = (a,b) => {return a+b};
var myV = (a,b) => a+b \\ equivalent to the previous
var exampleFunction = (function () {
return function increment exampleFunction (a,b) {
return a+b;
};
console.log(v, a)
})();
var myV = (...AAAA) => {return AAAA[0]}; // gather all the inputs of the function in a array named AAAA. The operator ... is the "rest operator"
Prototypes and classes
function Person (name, surname, age) {
this.name = name;
this.surname=surname;
this.age=age;
this.GetAge = function() { return this.age;}
}
//equivalent to
Person.this.GetAge = function() { return this.age;}
const p1 = new Person("giuseppe", "conte", "56")
// class
class Person {
costructor (name, surname, age) {
this.name = name;
this.surname=surname;
this.age=age;
}
GetAge() { return this.age;}
}
const p1 = new Person("giuseppe", "conte", "56")
DOM
// Single element
document.getElementsById("my-form") //select the first elements of that id
let ul = document.querySelector(".item") //select the first elements of any class/tag
// Multiple element
document.querySelectorAll(".item"); //select all elements of any class/tag. you can loop array methods on results
document.getElementByClassName();
document.getElementByTagName();
// element menage
ul.remove()
ul.lastElementChild.remove()
ul.lastElementChild.innerHTML = '<h1>New Title </h1>'
ul.firstElementChild.textContent = 'Hello World'
ul.children[1] = 'Hello World'
ul.value // get the value
// element style
ul.style:background = "red"
Button response
const bnt = document.querySelector(".bnt") // bnt is how the class of the button has been called
bnt.addEventListener('click', (e) => { // the parameter (called 'e') is the event
e.preventDefault(); // you need this not to vanish the function just after the click
document.querySelector("#my-form").style.background = 'red'; // change the color of the form
document.querySelector('body').addClass('.new_class'); // add the class new_class in the body
document.querySelector('body').classList.add('.new_class'); // add the class new_class in the body
setTimeout(() => ul.remove(), 3000); // do ul.remove() after 3000 ms, (like sleep but in ms)
}
)
bnt.addEventListener('click', (e) => { ... }) |
activate when click |
bnt.addEventListener('mouseover', (e) => { ... }) |
activate when mouse go over it |
bnt.addEventListener('mouseout', (e) => { ... }) |
activate when mouse go over and go out |
Other
Math.random() |
return random numer between 0 and 1 |
Math.floor(5.6) |
round 5.5 to 5 |
parseInt("12") |
convert a string into a number |
Object.freeze(objExample) |
set as const objExample. If it is an array or dict, set as const all objects inside |
conditional example
if (a===b) {return true;}
else if (a>b+10 || a < b-5) {return false}
else {return true;}
return a===b ? true : false;
// date format
let d = new Date("20-11-1991")
PHP 7
<?php
include "something.php"; //it continues if the file is not found
require "something.php"; //it crashes if the file is not found
echo $a , $b; //not possible with print
print $a;
print_r $a;
printf("%c %d %.2f %s", 65, 65, 1.234, "string"); // 65 is the char A
var_dump($a); //it shows also the type
echo "<a> link </a>"; // shows the link
echo htmlspecialchars("<a> link </a>"); // shows the string as it is
?>
Variables
$a = (int) $a |
pasing to float |
$a = (float) $a |
pasing to float |
$a = (bool) $a |
pasing to bool |
$a = (str) $a |
pasing to string |
$a = "hello world"; // string
$a = 10; // integer and float
$a = TRUE; // bool
$arr1 = array("giulio", 2.3, 10); // array
$arr1 = array("name"=> "giulio", "notes" => "giulioNotes"); // array
$arr2 = ["name"=> "giulio", "notes" => "giulioNotes"]; // equivalent array
define("PI", 3.14); // constant
Operatori
if ($a == 2) { }
else if ($a == 3) { }
else { }
($age>18) ? echo "can vote" : echo "cannot vote"
switch ($a) {
case 4 :
....
break;
default :
....
}
while($a<5) { ... }
$arr = [....];
foreach($arr as $element) { ... }
foreach($arr as $k => $v) { ... }
for ($i = 0; $i < 20 ; i++) { ... }
String
strlen($a) |
lenght |
substr($str, 0, 5) |
extract the sbstring |
str_word_count($a) |
word count |
str_rev($a) |
reverse the string |
str_pos($a, "ciao") |
return the position of "ciao" |
str_replace("ciao", "salve", $a) |
replace "ciao" with "salve" |
strtoupper($str) |
make all upper case characters |
"I am $name" |
works only with double apices " |
nl2br(str) |
transform the line in html readable |
$str = trim ($str, "toErase") |
remove "toErase" from the string $str. Also ltrim and rtrim exist |
$arr = explode("_", $str) |
split the string in an array. The string is divided by the _ inside |
$str = implode("_", $arr) |
opposite of explode |
$str = strip_tags($str) |
remove all the html tags from the string |
$str = strip_tags($str, '') |
remove all the html tags from the string except the ones among '' |
$str = 'hello world';
$str = <<<IDT
I live in Italy
but I work in Japan
IDT;
$str ="I live in Italy \n but I work in Japan";
Array
range(3,10) |
make an array from 3 to 10 |
in_array($age, range(0,18)) |
return true if $age is less than 18 |
$arr1 + $arr2 |
concatenate the arrays |
array_key_exists('name', $arr) |
true fi 'name' is a key in $arr |
sort($arr) |
sort the array |
rsort($arr) |
sort the array in descending order |
asort($arr) |
sort the associative array by values. arsort($arr) for descending order |
ksort($arr) |
sort the associative array by keys. krsort($arr) for descending order |
|
|
function square($x) {return $x*$x;}
$newA = array_map($arr, 'square'); // the functino has to be in quotes '
function multi($x, $y){
$x *= $y;
return $x;
}
$newA = array_reduce($arr, 'multi', 1);
$newA = array_filter($arr, 'isEven');
Function
function addNumb(a, b=0) { return a+b;}
Date
date_default_timezone_set(Europe/Rome');
echo 'Date : ' . date('I F Y-m-d h:i:s A');
$newDate = mkdate(0,0,0,12,21,2012);
echo 'Date : ' . date('I F Y-m-d h:i:s A', $newDate);
$d = date("Y-m-d");
$t = date("h:i:s");
$d = strtotime("1 May 2020"); // string -> time in ms from 1970
$d = date(4718401); // time in ms from 1970 -> string
class
class Animal {
private $name;
protected $food;
public $id;
public static $sound='roar'; //same for all the elements of the class
function getName(){return this->$name;}
function __get($x){ return this->$x;}
function __costructor(){
this->id = rand(10, 20);
}
function __decostructor() {}
}
Other
Helpful links
Links accross the page:
Others:
--
GiulioMandorli1 - 2017-03-23