I am working on the file "Exclusive OR (XOR).ipynb".
The first task is:
Find general rule from specific case

What will be returned for 1 True $\oplus$ 100 False
What will be returned for 2 True $\oplus$ 100 False
What will be returned for 3 True $\oplus$ 100 False
What will be returned for 101 True $\oplus$ 10000 False

What is the general rule ?
Bit operation
When 2 integers are calculated with XOR operator, each bit is calculated separately. (Same as AND, OR, NOT)
```
10(0b1010) xor 6(0b0110) = 12 (0b1100)
10(0b1010) and 6(0b0110) =  2 (0b0010)
10(0b1010) or  6(0b0110) = 14 (0b1110)
NOT 10(0b1010)           = 5  (0b0101)
0b1010    0b1010    0b1010    0b1010
0b0110    0b0110    0b0110
-(XOR)-   -(AND)-   -(OR)-    -(NOT)-
0b1100    0b0010    0b1110    0b0101
```
Can you write Python code for it?

# CONSTANT is not supported in Python, Upper case variable is typically used as Constant

INT10 = 0b1010
INT06 = 0b0110
REV_MASK = 0b1111

print('INT10:', INT10, 'INT06:', INT06)
print('Bit XOR:', INT10^INT06)
print('Bit AND:', INT10&INT06)
print('Bit OR: ', INT10|INT06)
print('Bit NOT', INT10, ':', (~INT10)&0x0f)
print('Reverse INT10:', INT10^REV_MASK)
print('Reverse INT06:', INT06^REV_MASK)


I am working on the file "Exclusive OR (XOR).ipynb".
The first task is:
XOR parity recalculation

Initialization: XOR of every data
Update:
Calculate $OldData \oplus NewData = Diff$
$NewParity=OldParity \oplus Diff$
Can you write Python code for it?

import random

data = [random.randrange(1000000) for i in range(5)]
print(data)

# Initialize Parity
parity = 0
for x in data:
    parity ^= x

# Update data[2]
olddata = data[2]
newdata = random.randrange(1000000)
print('data[2] is updated from:', olddata, 'to', newdata)
data[2] = newdata
diff = olddata ^ newdata

# Calc new parity
newparity = parity ^ diff
print('old parity:', parity)
parity = newparity
print('new parity:', parity)

# Check if parity is correct
chk_parity = 0
for x in data:
    chk_parity ^= x

print('updated parity:', chk_parity)


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
Colormap
Plotting the colormap with the grains boundaries
Full ColorWheel
Advantages
1. The full colorwheel has unique relation between color and orientation.
Inconveniants
1. The color are discountinous for $v=\left[x,y,z=0 \pm \varepsilon\right]$
Can you write Python code for it?

plt.figure(figsize=(8,8))
data.plot()
data.micro.plotBoundary(dilatation=2)
plt.title('Colormap')


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
Filter the data
This function filter the bad indexed value. Using G50 analyser a quelity factor is given between 0 and 100. Usualy using data with a quality factor higher than 75 is a good option.
Can you write Python code for it?


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
Grelon function
The grelon function compute the angle between the c-axis at each pixel and the unit radial vector from the center. The center is given by the user.
Using the interactive_grelon function you can click as many time as you want. When you push export, it will compute the angle using the last click (input)
Can you write Python code for it?

grelon=data.interactive_grelon()

#You can plot the angle map in degree using.
plt.figure()
grelon.map.plot()
#You can find the center use for the computation
plt.plot(grelon.center[0],grelon.center[1],'ks')


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
Kernel Density Estimation
If you want to have an idea of a basic KDE in one dimention refer to https://mathisonian.github.io/kde/
Here there is some specificities du to the fact that we are computing KDE on a sphere. To do so we are using sklearn.neighbors.KernelDensity (https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KernelDensity.html).
The 'metric' is set to 'haversine' for spherical computation (for exemple see https://scikit-learn.org/stable/auto_examples/neighbors/plot_species_kde.html#sphx-glr-auto-examples-neighbors-plot-species-kde-py)
We are using a gaussian kernel.
Warning : The 'bandwidth' parameter is crutial parameter to set. It can have a strong influence on your pole figure and you interpretation. You should set it up carefully and be critic on your pole figure. Here we show different pole figure for different bandwidth value using the same data as input.
Can you write Python code for it?

plt.figure(figsize=(7,7),dpi=160)
plt.subplot(2,2,1)
data.plotpdf(contourf=True,angle=0,bw=0.05)
plt.title('bw=0.05')
plt.subplot(2,2,2)
data.plotpdf(contourf=True,angle=0,bw=0.1)
plt.title('bw=0.1')
plt.subplot(2,2,3)
data.plotpdf(contourf=True,angle=0,bw=0.3)
plt.title('bw=0.3')
plt.subplot(2,2,4)
data.plotpdf(contourf=True,angle=0,bw=2.0)
plt.title('bw=2')


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
Misorientation profile
Can you write Python code for it?

res=data.interactive_misorientation_profile()

plt.figure()
plt.plot(res.x,res.mis2o,'b-',label='mis2o')
plt.plot(res.x,res.mis2p,'k-',label='mis2p')
plt.grid()
plt.legend()
plt.xlabel('Distance')
plt.ylabel('Angle')


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
Once you did 'Export AITA' you can save the microstrucuture using :
python
data.micro.save_bmp('micro')
You can also see the parameter used for the segmentation in res.
Can you write Python code for it?

print('Use scharr:',seg.use_scharr)
print('Value scharr:',seg.val_scharr)
print('Use canny:',seg.use_canny)
print('Value canny:',seg.val_canny)
print('Images canny:',seg.img_canny)
print('Use quality:',seg.use_quality)
print('Value quality:',seg.val_quality)
print('Include border:',seg.include_border)


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
Once you did 'Export crop' the position of the rectangle can be find in :
python
out.pos=np.array([xmin,xmax,ymin,ymax])
Can you write Python code for it?

ss=np.shape(data.phi.field)
res=data.phi.res

fig,ax=plt.subplots()
data.phi1.plot()
rect=patches.Rectangle((out.pos[0]*res, (ss[0]-out.pos[3])*res), (out.pos[1]-out.pos[0])*res, (out.pos[3]-out.pos[2])*res, linewidth=1, edgecolor='b', facecolor='none')
plt.title('Full data with crop area')
ax.add_patch(rect)
plt.subplots()
out.crop_data.phi1.plot()
plt.title('Crop data')


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
Segmentation of microstrucuture
If you want to do it. It should not be use if you already load the microstrucure.
Can you write Python code for it?


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
The associated full colorwheel :
Can you write Python code for it?

plt.figure(figsize=(2,2))
plt.imshow(lda.aita.lut())
plt.axis('off')
plt.title('LUT')


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
With 'micro_test.bmp'
The ‘micro_test.bmp’ file should be a black and white image with the grains boundaries being white. Therefore you should use :
python
data=lda.aita5col('orientation_test.dat','micro.test.bmp')
Basic treatment
Croping
It can be usefull to select a sub area. Within a juptyter notebook use interactive_crop(). In ipython use just crop function.
Can you write Python code for it?


I am working on the file "Exemple/.ipynb_checkpoints/Documentation-checkpoint.ipynb".
The first task is:
Without 'micro_test.bmp'
Can you write Python code for it?


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Colormap
Plotting the colormap with the grains boundaries
Full ColorWheel
Advantages
1. The full colorwheel has unique relation between color and orientation.
Inconveniants
1. The color are discountinous for $v=\left[x,y,z=0 \pm \varepsilon\right]$
Can you write Python code for it?


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Filter the data
This function filter the bad indexed value. Using G50 analyser a quelity factor is given between 0 and 100. Usualy using data with a quality factor higher than 75 is a good option.
Can you write Python code for it?


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Kernel Density Estimation
If you want to have an idea of a basic KDE in one dimention refer to https://mathisonian.github.io/kde/
Here there is some specificities du to the fact that we are computing KDE on a sphere. To do so we are using sklearn.neighbors.KernelDensity (https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KernelDensity.html).
The 'metric' is set to 'haversine' for spherical computation (for exemple see https://scikit-learn.org/stable/auto_examples/neighbors/plot_species_kde.html#sphx-glr-auto-examples-neighbors-plot-species-kde-py)
We are using a gaussian kernel.
Warning : The 'bandwidth' parameter is crutial parameter to set. It can have a strong influence on your pole figure and you interpretation. You should set it up carefully and be critic on your pole figure. Here we show different pole figure for different bandwidth value using the same data as input.
Can you write Python code for it?


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Misorientation function
Can you write Python code for it?

angle=out.crop_data.misorientation(filter_angle=5*math.pi/180)
random_angle=out.crop_data.misorientation(filter_angle=5*math.pi/180,random=True)

kernel_a = scipy.stats.gaussian_kde(angle)
xeval_a=np.linspace(0,math.pi/2,180)
yeval_a=kernel_a(xeval_a)

kernel_ra = scipy.stats.gaussian_kde(random_angle)
xeval_ra=np.linspace(0,math.pi/2,180)
yeval_ra=kernel_ra(xeval_ra)

plt.figure()
plt.plot(xeval_a,yeval_a)
plt.plot(xeval_ra,yeval_ra)

angle.shape


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Misorientation profile
Can you write Python code for it?


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Once you did 'Export AITA' you can save the microstrucuture using :
python
data.micro.save_bmp('micro')
You can also see the parameter used for the segmentation in res.
Can you write Python code for it?


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Once you did 'Export crop' the position of the rectangle can be find in :
python
out.pos=np.array([xmin,xmax,ymin,ymax])
Can you write Python code for it?


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Pole figure
There is various option to plot the pole figure here we focus on some of them but to see all of them refer to the documentation of plotpdf function.
The color coding of the pole figure is obtain using a Kernel Density Estimation (KDE). This KDE has to be manipulating carrefully. If you want to have a basic idea of what is a KDE you can look at https://mathisonian.github.io/kde/.
Representation
Pole figure all sample
Here some of the option are shown as contour plot, and with or without circle for specific angle.
Be aware that to reduce the computation time we only used by default 10000 orientations selected randomly. You can modify this using 'nbp' value. If you set nbp to 0 it use all the data.
Can you write Python code for it?

plt.figure(figsize=(7,7),dpi=160)
plt.subplot(2,2,1)
data.plotpdf(contourf=True,angle=0,cm2=cm.gray)
plt.subplot(2,2,2)
data.plotpdf(contourf=True)
plt.subplot(2,2,3)
data.plotpdf(angle=0)
plt.subplot(2,2,4)
data.plotpdf()


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Segmentation of microstrucuture
If you want to do it. It should not be use if you already load the microstrucure.
Can you write Python code for it?


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Semi ColorWheel
Advantage
1. No color discontinuity for $v=\left[x,y,z=0 \pm \varepsilon\right]$
Inconvinent

The semi colorwheel has non unique relation between color and orientation.
Can you write Python code for it?

plt.figure(figsize=(8,8))
data.plot(semi=True)
data.micro.plotBoundary(dilatation=2)
plt.title('Colormap')


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
The associated full colorwheel :
Can you write Python code for it?


plt.figure(figsize=(2,2))
plt.imshow(lda.aita.lut(semi=True))
plt.axis('off')
plt.title('LUT')


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
With 'micro_test.bmp'
The ‘micro_test.bmp’ file should be a black and white image with the grains boundaries being white. Therefore you should use :
python
data=lda.aita5col('orientation_test.dat','micro.test.bmp')
Basic treatment
Croping
It can be usefull to select a sub area. Within a juptyter notebook use interactive_crop(). In ipython use just crop function.
Can you write Python code for it?


I am working on the file "Exemple/Documentation.ipynb".
The first task is:
Without 'micro_test.bmp'
Can you write Python code for it?


I am working on the file "ExemplesJouet/Apprent-Python-Blobs.ipynb".
The first task is:
3 Les classifieurs de Scikit-learn
Tous les algorithmes et méthodes de Scikit-learn se présentent sous la forme d'une combinaison de 3 "interfaces":
* estimation pour ajuster des modèles,
* prévision pour de nouvelles observations,
* transformation pour convertir des données.
Celles-ci peuvent être facilement combinées et enchaînées en un pipeline.
3.1 k plus proches voisins
Estimation
Can you write Python code for it?

# Importation de la fonction
from sklearn.neighbors import KNeighborsClassifier
# Détermination des paramètres et définition de l'estimateur
knnF = KNeighborsClassifier(n_neighbors=5)

# Apprentissage ou estimation du modèle sur l'échantillon d'apprentissage
# mais il ne se passe rien  dans le cas de *k*-nn avant en dehors de la phase de prévision.
knnF.fit(X, y)
# Les options de cet algorithmes:


I am working on the file "ExemplesJouet/Apprent-Python-Blobs.ipynb".
The first task is:
3.3 Forêts aléatoires
Obtenues par agrégation d'arbres, une forêt arrondit les frontières. Avec seulement 2 variables (dans R2), cela revient à faire du bagging. Faire variaer le nombre d'arbres: n_estimators (1 à 20), de la forêt.
Can you write Python code for it?

from sklearn.ensemble import RandomForestClassifier
rfF = RandomForestClassifier(n_estimators=200)
rfF.fit(X, y)
plot_surface(rfF, X, y)


I am working on the file "ExemplesJouet/Apprent-Python-Blobs.ipynb".
The first task is:
3.4 Séparateur à Vaste Marge (SVM)
SVM linéaire, pas très intéressant sur ces données, puis gaussien. Faire varier la pénalisation C et l'étendue du noyau gaussien.
Can you write Python code for it?

# Noyau linéaire
from sklearn.svm import SVC
svmF = SVC(kernel="linear",C=1)  # try kernel="rbf" instead
svmF.fit(X, y)
plot_surface(svmF, X, y)


I am working on the file "ExemplesJouet/Apprent-Python-Blobs.ipynb".
The first task is:
3.5 Perceptron multicouches
Faire varier le nombre de couches cachées, le nombe de neurones sur ces couches, la pénalisation l2 alpha.
Can you write Python code for it?

# Trois couches de 100 neurones avec alpha par défaut
from sklearn.neural_network import MLPClassifier
nnetF = MLPClassifier(hidden_layer_sizes=(100, 100, 100),alpha=0.0001)
nnetF.fit(X, y)
plot_surface(nnetF, X, y)


I am working on the file "ExemplesJouet/Apprent-Python-Blobs.ipynb".
The first task is:
3.6 Processus gaussien
Consulter la doc en ligne.
Can you write Python code for it?

from sklearn.gaussian_process import GaussianProcessClassifier
pgF = GaussianProcessClassifier()
pgF.fit(X, y)
plot_surface(pgF, X, y)


I am working on the file "ExemplesJouet/Apprent-Python-Blobs.ipynb".
The first task is:
Ce qui donne une bonne idée de  la forme des frontières estimées entre les classes.
Faire varier le paramère n_neighbors (1 à 500) et observer l'impact sur la forme des classes.
3.2 Arbre binaire de décision
Les frontières sont construites à partir de parallèles aux axes. Faire varier la profondeur maximale max_depth de l'arbre.
Can you write Python code for it?

from sklearn.tree import DecisionTreeClassifier
treeF = DecisionTreeClassifier(max_depth=10)
treeF.fit(X, y)
plot_surface(treeF, X, y)


I am working on the file "ExemplesJouet/Apprent-Python-Blobs.ipynb".
The first task is:
La fonction définie ci-dessous prévoit chaque point d'une grille du plan et trace un graphe de contour des probabilités.
Can you write Python code for it?

def plot_surface(clf, X, y, xlim=(-10, 10), ylim=(-10, 10), n_steps=250):
    fig = plt.figure()
    xx, yy = np.meshgrid(np.linspace(xlim[0], xlim[1], n_steps), np.linspace(ylim[0], ylim[1], n_steps))
    if hasattr(clf, "decision_function"):
        z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
    else:
        z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
    z = z.reshape(xx.shape)
    plt.contourf(xx, yy, z, alpha=0.8, cmap=plt.cm.RdBu_r)
    plt.scatter(X[:, 0], X[:, 1], c=y)
    plt.xlim(*xlim)
    plt.ylim(*ylim)
    plt.show()

knnF = KNeighborsClassifier(n_neighbors=70)
knnF.fit(X, y)
plot_surface(knnF, X, y)


I am working on the file "ExemplesJouet/Apprent-Python-Blobs.ipynb".
The first task is:
Représentation des données dans le plan.
Can you write Python code for it?

plt.figure()
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()


I am working on the file "Exemplo.ipynb".
The first task is:
Massa e rigidez modais:
Can you write Python code for it?

Mn = np.diag(Fn.T@MM@Fn)
Kn = np.diag(Fn.T@KK@Fn)
print(Mn)
print(Kn)


I am working on the file "Exemplo.ipynb".
The first task is:
Normalização dos modos de vibração relativamente à matriz de massa:
Can you write Python code for it?

Fn = F1/np.sqrt(np.diag(F1.T@MM@F1))
print(Fn)


I am working on the file "Exemplo.ipynb".
The first task is:
Ordenação dos modos:
Can you write Python code for it?

ix = np.argsort(W2)[::-1]
W2 = 1./W2[ix]
F1 = F1[:,ix]
Wn = np.sqrt(W2)
print(W2)
print(Wn)
print(F1)


I am working on the file "Exemplo.ipynb".
The first task is:
Solução alternativa
Can you write Python code for it?

ust = KK.I@sp
print(ust)

qn_st_t = []
plt.figure()
for n in range(3):
    an = Fn.T[n]@MM@ust/Mn[n]
    bn = wp/Wn[n]
    qst = qn(an[0,0], wp, bn, 0.05, tt)
    qn_st_t.append(qst)
    plt.plot(tt, qst, label='an={:.2e},bn={:.2f}'.format(an[0,0], bn))
plt.legend()
plt.xlabel('Tempo (s)')
plt.ylabel('Deslocamento modal (m)')
plt.show()

plt.figure()
u_t = Fn@qn_st_t
for n in range(3):
    plt.plot(tt, u_t[n].T, label='{:.2e}'.format(np.max(u_t[n])))
plt.legend()
plt.xlabel('Tempo (s)')
plt.ylabel('Deslocamento (m)')
plt.show()


I am working on the file "Exemplo.ipynb".
The first task is:
Solução clássica
Can you write Python code for it?

Gn = np.diag(1./Mn)@Fn.T@sp
print(Gn)

qn_t = []
plt.figure()
for n in range(3):
    an = Gn[n]/Kn[n]
    bn = wp/Wn[n]
    q = qn(an[0,0], wp, bn, 0.05, tt)
    qn_t.append(q)
    plt.plot(tt, q, label='an={:.2e},bn={:.2f}'.format(an[0,0], bn))
plt.legend()
plt.xlabel('Tempo (s)')
plt.ylabel('Deslocamento modal (m)')
plt.show()

plt.figure()
u_t = Fn@qn_t
for n in range(3):
    plt.plot(tt, u_t[n].T, label='{:.2e}'.format(np.max(u_t[n])))
plt.legend()
plt.xlabel('Tempo (s)')
plt.ylabel('Deslocamento (m)')
plt.show()


I am working on the file "Exercice 2.ipynb".
The first task is:
La masse accrochée serait d'environ 320g
Exercice 3
Dans cette exercice, on doit créer des fonctions à l'intérieur de notre classe frame afin de récupérer l'effort normal(N), l'effort tangentielle (T) et le moment sur z (M).
Can you write Python code for it?

def find_N(self,element):
        """
        Returns the normal force of an element.
        """
        F = self.assemble_F()
        N = F[3*element]
        return N

def find_T(self,element):
        """
        Returns the tangential force of an element.
        """
        F = self.assemble_F()
        T = F[3*element+1]
        return T

def find_M(self,element):
        """
        Returns the moment of an element.
        """
        F = self.assemble_F()
        M = F[3*element+2]
        return M


I am working on the file "Exercice 2.ipynb".
The first task is:
Nous allons maintenant créer les noeuds et les éléments de la structure :
Can you write Python code for it?

nodes= np.array([[0.,0.],[0.,Lyb],[0.,Lyh+Lyb],[Lx/2,Lyh+Lyb],[Lx,Lyh+Lyb],[Lx,Lyb],[Lx,0.]])
elements=np.array([[0,1],[1,5],[1,2],[2,3],[3,4],[4,5],[5,6]])

frame=LinearFrame(nodes,elements)
frame.plot_with_label()

ne = frame.nelements
ndof = frame.ndof
EI = np.ones(ne)*E*I
ES = np.ones(ne)*E*S
f_x = 0*np.ones(7)
f_y = 0*np.ones(7)
frame.set_distributed_loads(f_x, f_y)
frame.set_stiffness(EI, ES)
blocked_dof = np.array([0, 1, 2, ndof-3, ndof-2, ndof-1])
bc_values = np.array([0, 0, 0, 0, 0, 0])

K = frame.assemble_K()

u=np.array([0.,0.,0.,
            2.,0.,0.,
            5.,0.,0.,
            0.,-3.,0.,
            -3.,0.,0.,
            -2.,0.,0.,
            0.,0.,0.])

print (u)

F= np.dot(K,np.transpose(u))
F

m=F[10]/g
m


I am working on the file "ExercicioFacil2.ipynb".
The first task is:
Exercício 01: Calcule a distância média, o diâmetro e o coeficiente de agrupamento das redes abaixo.
Can you write Python code for it?

G1 = nx.erdos_renyi_graph(5,0.4)
nx.draw_shell(G1)

print "Dist. media: ", nx.average_shortest_path_length(G1)
print "Diametro: ", nx.diameter(G1)
print "Coef. Agrupamento médio: ", nx.average_clustering(G1)

G2 = nx.barabasi_albert_graph(6,3)
nx.draw_shell(G2)

print "Dist. media: ", nx.average_shortest_path_length(G2)
print "Diametro: ", nx.diameter(G2)
print "Coef. Agrupamento médio: ", nx.average_clustering(G2)

G3 = nx.barabasi_albert_graph(6,4)
nx.draw_shell(G3)

print "Dist. media: ", nx.average_shortest_path_length(G3)
print "Diametro: ", nx.diameter(G3)
print "Coef. Agrupamento médio: ", nx.average_clustering(G3)


I am working on the file "ExercicioFacil2.ipynb".
The first task is:
Exercício 02: Calcule a centralidade de grau, betweenness e proximidade dos nós das redes abaixo:
Can you write Python code for it?

G4 = nx.barabasi_albert_graph(6,3)
plt.pyplot.figure(figsize=(10,10))
pos = nx.shell_layout(G4)
nx.draw_networkx_nodes(G4,pos);
nx.draw_networkx_edges(G4,pos);
nx.draw_networkx_labels(G4,pos);
plt.pyplot.axis('off')

print "Centralidades de grau:"
for ni,dc in nx.degree_centrality(G4).items():
    print ni, dc

print "Centralidades de proximidade:"
for ni,dc in nx.closeness_centrality(G4).items():
    print ni, dc

print "Centralidades de betweenness:"
for ni,dc in nx.betweenness_centrality(G4).items():
    print ni, dc


I am working on the file "ExercicioRec.ipynb".
The first task is:
Exercício 02: Calcule a centralidade de grau, betweenness e proximidade dos nós das redes abaixo:
Can you write Python code for it?

print "Centralidades de grau:"
for ni,dc in nx.degree_centrality(G2).items():
    print ni, dc

print "Centralidades de proximidade:"
for ni,dc in nx.closeness_centrality(G2).items():
    print ni, dc

print "Centralidades de betweenness:"
for ni,dc in nx.betweenness_centrality(G2).items():
    print ni, dc


I am working on the file "ExercicioRec.ipynb".
The first task is:
Exercício 04: Calcule a assortatividade de grau da rede
Can you write Python code for it?

print "Assortatividade: ", nx.degree_assortativity_coefficient(G2)


I am working on the file "Exercise Solutions.ipynb".
The first task is:
2**X is a shortcut for getting the binary number with 1 at the (X + 1)th position, and zeros elsewhere. (2**X) - 1 returns the binary number of size X with 1s in all positions. We use these shortcuts to get masks for the leftmost bit, and for every bit except the leftmost bit, respectively.
Can you write Python code for it?


I am working on the file "Exercise Solutions.ipynb".
The first task is:
4. Cryptography
1.
Given four sets of characters (lowercase, uppercase, digits, punctuation) there are 15 different combinations of character sets we can choose (assuming we have to choose at least one set). One way to indicate our choice is to use a binary mask, where a number like 0b1010 indicates that we'd like a random password with lowercase letters and digits only. Likewise, the number 0b11 indicates we only want digits and punctuation. Here's one way to implement this securely:
Can you write Python code for it?

from itertools import compress
import random
import string

char_list = [string.ascii_lowercase, string.ascii_uppercase,
                 string.digits, string.punctuation + " "]

def gen_password(char_no, length):

    # 0b1010 -> [1, 0, 1, 0]
    bitmask = [(char_no >> bit) & 1 for bit in range(3, -1, -1)]

    # apply bitmask to char_list
    chars = "".join(compress(char_list, bitmask))

    # generate a random password
    return "".join(random.SystemRandom().choice(chars) for _ in range(length))

gen_password(0b1010, 20)

gen_password(0b1100, 60)

gen_password(0b11, 16)


I am working on the file "Exercise Solutions.ipynb".
The first task is:
5.
There are several ways of doing this, but the fastest way I've found so far (that doesn't involve writing C code or anything crazy) uses bitwise operations. This encoder is based on code for a base32 encoder taken from the base64 module.
We first need to generate a base64 dictionary. To avoid mistakes, I've copied out the standard base64 dictionary, but you could generate this programmatically:
Can you write Python code for it?


I am working on the file "Exercise Solutions.ipynb".
The first task is:
7.
Can you write Python code for it?

import socket

# carriage return + line feed
CRLF = "\r\n"

# create a socket using the AF_INET (*IPv4*) address family
# and the SOCK_STREAM transport protocol (*TCP*)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect to port 80 (the HTTP port) on www.google.com
s.connect(('www.google.com', 80))

# print the remote IP address
print "IP Address:", s.getpeername()[0]

# form and send an HTTP GET request
s.send("GET / HTTP/1.1{n}Host: www.google.com{n}{n}".format(n=CRLF))

# receive data in two chunks of 4096 bytes,
# which should be enough to get the <title>
response = s.recv(4096)
response += s.recv(4096)

# finally, close the TCP connection
s.close()

print response[:2000]

from bs4 import BeautifulSoup

soup = BeautifulSoup(response, "lxml")
print soup.title.text


I am working on the file "Exercise Solutions.ipynb".
The first task is:
For a module with IP utilities, see ipaddress, which is part of the Python 3 standard library, and is available for Python 2 with $ pip install ipaddress.
5.
There are a few ways you could do this. I prefer to use the dig command because it tends to be the most informative of all DNS utilities. For the root servers:
Can you write Python code for it?


I am working on the file "Exercise Solutions.ipynb".
The first task is:
If you're having trouble understanding the bitwise operations, think of them this way:
1. Identify the rightmost bit with (num & 1).
2. Create a new number by shifting the rightmost bit to the left by (size - 1) spots. For example, if the last bit is 1 and size = 8, then we have 0b10000000.
3. Shift the original number to the right by one spot with (num >> 1) so the last bit "falls off" the end.
4. Combine the numbers found in steps 2 and 3. The original rightmost bit is now the leftmost bit.

The equivalent ROL function is slightly more complicated:
Can you write Python code for it?

def ROL(num, size=None):
    if size is None:
        size = num.bit_length()
    else:
        size = max(size, num.bit_length())

    return bin((num << 1) & ((2**size) - 1) | ((num & (2**(size - 1))) >> (size - 1)))


I am working on the file "Exercise Solutions.ipynb".
The first task is:
If you're on a "narrow" Python build (i.e., UCS-2 under the hood), unicodedata.name will not support Unicode code points above \uffff, so this function won't work for, say, \U0001F330. You can find the highest-supported Unicode code point on your system by calling sys.maxunicode:
Can you write Python code for it?


I am working on the file "Exercise Solutions.ipynb".
The first task is:
Note that we could also write functions that efficiently shift more than one bit at the same time. For instance, see https://www.falatic.com/index.php/108/python-and-bitwise-rotation
8.
One way to do this is to register a new encoding error option with the codecs module:
Can you write Python code for it?

from __future__ import unicode_literals
import codecs
import unicodedata

def unicode_name(ex):
    """The object `ex` follows the
    UnicodeError exception format. See:
    https://docs.python.org/2/library/exceptions.html#exceptions.UnicodeError"""

    char = ex.object[ex.start:ex.end]
    return "{" + unicodedata.name(char, "unknown") + "}", ex.end

codecs.register_error("name", unicode_name)


I am working on the file "Exercise Solutions.ipynb".
The first task is:
Python 3 has no such limitations, as most Python 3 versions (>=3.3) support code points up to 0x10FFFF (the maximum possible code point). Since our script is compatible with Python 3, we can run it with the cell magic %%python3 (you may need to install Python 3 on your system):
Can you write Python code for it?

%%python3
# from __future__ import unicode_literals
import codecs
import unicodedata

def unicode_name(ex):
    """The object `ex` follows the UnicodeError exception format. See:
    https://docs.python.org/2/library/exceptions.html#exceptions.UnicodeError"""

    char = ex.object[ex.start:ex.end]
    return "{" + unicodedata.name(char, "unknown") + "}", ex.end

codecs.register_error("name", unicode_name)

def to_ascii(string):
    return string.encode("ascii", errors="name")

print(to_ascii(u"A \U0001F330"))


I am working on the file "Exercise Solutions.ipynb".
The first task is:
Remember that if the string's character length isn't a multiple of three, we'll have to pad the encoded string with =. Notice how we build the encoded string by analyzing it in chunks of three bytes (24 bits) at a time. The struct.unpack(3B, string) function is the same as calling ord on all three characters in string (but faster). The bitwise operations simply shift and concatenate each set of 24 bits to convert them from three sets of 8 bits to four sets of 6 bits.
Can you write Python code for it?

def slow_b64encode(string):

    encode = []
    quanta, leftover = divmod(len(string), 3)

    if leftover:
        string += '\0' * (3 - leftover)
        quanta += 1

    for i in xrange(quanta):
        b0, b1, b2 = struct.unpack('3B', string[i*3:(i+1)*3])
        encode.extend([b64[b0 >> 2],
                       b64[(b0 & 0b11) << 4 | b1 >> 4],
                       b64[(b1 & 0b1111) << 2 | b2 >> 6],
                       b64[(b2 &  0b111111)]])

    encoded = ''.join(encode)

    if leftover == 1:
        return encoded[:-2] + "=="
    elif leftover == 2:
        return encoded[:-1] + "="
    return encoded


I am working on the file "Exercise Solutions.ipynb".
The first task is:
Testing:
Can you write Python code for it?

from base64 import b64encode

string = "Please encode me"
slow_b64encode(string) == b64encode(string)


I am working on the file "Exercise Solutions.ipynb".
The first task is:
The exercise says that we should only output the two other formats. As far as I'm aware, it's not possible for a Python script to distinguish between integer literals (without hacking the Python parser), so we'll use a string as the input instead:
Can you write Python code for it?

def convert2(string_number):
    if string_number[1] == "x":
        num = int(string_number, 16)
        return str(num), bin(num)
    elif string_number[1] == "b":
        num = int(string_number, 2)
        return str(num), hex(num)
    else:
        num = int(string_number)
        return bin(num), hex(num)

convert2("0b1001")


I am working on the file "Exercise Solutions.ipynb".
The first task is:
The function ROR takes an integer num and rotates it to right by one bit. If size is not given, the function assumes that the intended size of the integer is num.bit_length(). If you specify a different size, the function will use that size as the integer bit length (with max used to avoid truncation in case the given size is smaller than num.bit_length()). For example:
Can you write Python code for it?


I am working on the file "Exercise Solutions.ipynb".
The first task is:
This means we can easily reverse the encryption process by taking the eth root of the ciphertext:
Can you write Python code for it?


I am working on the file "Exercise Solutions.ipynb".
The first task is:
We also need the struct module:
Can you write Python code for it?


I am working on the file "Exercise Solutions.ipynb".
The first task is:
We use a list comprehension to turn the binary char_no into a "bit array" (so 0b1010 becomes [1, 0, 1, 0]). The itertools.compress function applies the bitmask to the list of character sets.
If you need a quick command line function, you can use the following one-liner (with modifications depending on your desired password length and character set):
Can you write Python code for it?

''.join(random.SystemRandom().choice(string.printable) for _ in range(20))


I am working on the file "Exercise Solutions.ipynb".
The first task is:
b. Since we're using a 3-bit block size, we have to encrypt our data 3 bits at a time. We won't go through the trouble of building a function that regroups bytes (see exercise 1.5, which shows you how to make 6-bit groups out of regular bytes using bitwise operations). This encrypt function works with 3-bit numbers directly:
Can you write Python code for it?

from itertools import islice

def encrypt(data, key):
    """data is a 3-bit number and key is
    an integer in range(40321)"""

    p = ({i:j for i, j in zip(range(8), i)} for i in permutations(range(8)))

    return next(islice(p, key, None))[data]

encrypt(4, 2210)


I am working on the file "Exercise Solutions.ipynb".
The first task is:
unicode_name is an error handler that takes a UnicodeError object as an argument, and returns the name of the Unicode character that raised the encoding error. See https://docs.python.org/2/library/codecs.html#codecs.register_error for more information. The unicodedata module is used to produce the name of the Unicode character.
to_asicii encodes string using the ASCII encoding, handling errors with unicode_name, which we registered previously as an error option called name:
Can you write Python code for it?

def to_ascii(string):
    return string.encode("ascii", errors="name")

print to_ascii(u"† and ►")
print to_ascii(u"\u00A5 and \u00A3")


I am working on the file "Exercise-4-intro-to-recommendation.ipynb".
The first task is:
Filter out video games which have no title
Filter out video games which have less than 5 ratings
Filter out users which have less than 5 ratings
Merge ratings and videogames dataframe on productID and set to df dataframe
Create a pivot matrix with index userID, columns productID and values ratings
Set columns to productID variable
Set index to userID variable
Can you write Python code for it?

correlated_items = ratings_pivot.corr()["B002I0JZOC"].sort_values(ascending=False).head(5)
correlated_items.index


I am working on the file "Exercise-5-celery-basics.ipynb".
The first task is:
Sum 1 to 2
Can you write Python code for it?

res = add.apply_async(args=(1, 2))
results = res.get()
results


I am working on the file "Exercise1.ipynb".
The first task is:
Use the above and modify our program
Can you write Python code for it?

#Version 2

from datetime import date
def main():
    name, age = input("Enter name") , int( input("Enter age"))
    thisYear = find_years()
    for i in range( int(input("Enter a number"))):
         print("You will turn 100 in {}".format(thisYear-age+100))

def find_years():
    today = str(date.today()).split('-')
    return int(today[0])
main()

from datetime import date

def main():
    name, age = get_name() , get_age()
    thisYear = find_years()
    print("Hi {} ! You will turn 100 in {} \n".format(name,thisYear-age+100))
    for i in range( int(input("Please enter how many times the above message should show : \n"))):
         print("Hi {} ! You will turn 100 in {}".format(name,thisYear-age+100))

def get_name():
    return input("Please enter your name : \n")

def get_age():
    return int(input("Please enter your age : \n"))

def find_years():
    today = str(date.today()).split('-')
    return int(today[0])

if __name__ == '__main__':
    main()

from datetime import date

def main():

    name = get_name()
    age = get_age()

    thisYear = find_years()
    turns100Year = calculate_year(age,thisYear)
    show_msg(name,turns100Year)

    for i in range( int(input("Please enter how many times the above message should show : \n"))):
         print("Hi {} ! You will turn 100 in {}".format(name,thisYear-age+100))

def get_name():
    return input("Please enter your name : \n")

def get_age():
    return int(input("Please enter your age : \n"))

def find_years():
    today = str(date.today()).split('-')
    return int(today[0])

def show_msg(name,turns100Year):
    print("Hi {} ! You will turn 100 in {} \n".format(name,turns100Year))

def calculate_year(age,thisYear):
    assert age >= 0 , "Age is not allowed to be less than zero"
    return thisYear-age+100

if __name__ == '__main__':
    main()


I am working on the file "Exercise1.ipynb".
The first task is:
Using datetime module to find current date and extracting year from the current date
Can you write Python code for it?

from datetime import date
today = str(date.today()).split("-")
print(type(today))
print(today[0])


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
Adorable, but was our classification correct?
Can you write Python code for it?

# load labels
imagenet_labels_filename = caffe_root + 'data/ilsvrc12/synset_words.txt'
try:
    labels = np.loadtxt(imagenet_labels_filename, str, delimiter='\t')
except:
    !../data/ilsvrc12/get_ilsvrc_aux.sh
    labels = np.loadtxt(imagenet_labels_filename, str, delimiter='\t')

# sort top k predictions from softmax output
top_k = net.blobs['prob'].data[0].flatten().argsort()[-1:-6:-1]
print labels[top_k]


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
Feed in the image (with some preprocessing) and classify with a forward pass.
Can you write Python code for it?

net.blobs['data'].data[...] = transformer.preprocess('data', caffe.io.load_image(caffe_root + 'examples/images/elephants.jpg'))
out = net.forward()
print("Predicted class is #{}.".format(out['prob'][0].argmax()))


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
Helper functions for visualization
Can you write Python code for it?

# take an array of shape (n, height, width) or (n, height, width, channels)
# and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)
def vis_square(data, padsize=1, padval=0):
    data -= data.min()
    data /= data.max()

    # force the number of filters to be square
    n = int(np.ceil(np.sqrt(data.shape[0])))
    padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
    data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))

    # tile the filters into an image
    data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
    data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])

    plt.imshow(data)


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
Indeed! But how long did it take?
Can you write Python code for it?

# CPU mode
net.forward()  # call once for allocation
%timeit net.forward()


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
Let's see the top 5 predicted labels.
Can you write Python code for it?


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
Let's start with a simple classification. We'll set a batch of 50 to demonstrate batch processing, even though we'll only be classifying one image. (Note that the batch size can also be changed on-the-fly.)
Can you write Python code for it?

# set net to batch size of 50
net.blobs['data'].reshape(50,3,227,227)


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
Set Caffe to CPU mode, load the net in the test phase for inference, and configure input preprocessing.
Can you write Python code for it?

caffe.set_mode_cpu()
net = caffe.Net(caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt',
                caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel',
                caffe.TEST)

# input preprocessing: 'data' is the name of the input blob == net.inputs[0]
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2,0,1))
transformer.set_mean('data', np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1)) # mean pixel
transformer.set_raw_scale('data', 255)  # the reference model operates on images in [0,255] range instead of [0,1]
transformer.set_channel_swap('data', (2,1,0))  # the reference model has channels in BGR order instead of RGB


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
That's a while, even for a batch size of 50 images. Let's switch to GPU mode.
Can you write Python code for it?

# GPU mode
caffe.set_device(0)
caffe.set_mode_gpu()
net.forward()  # call once for allocation
%timeit net.forward()


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
The fifth layer after pooling, pool5
Can you write Python code for it?

feat = net.blobs['pool5'].data[0]
vis_square(feat, padval=1)


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
The fifth layer output, conv5 (rectified, all 256 channels)
Can you write Python code for it?

feat = net.blobs['conv5'].data[0]
vis_square(feat, padval=0.5)


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
The first layer output, conv1 (rectified responses of the filters above, first 36 only)
Can you write Python code for it?

feat = net.blobs['conv1'].data[0, :36]
vis_square(feat, padval=1)


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
The fourth layer output, conv4 (rectified, all 384 channels)
Can you write Python code for it?

feat = net.blobs['conv4'].data[0]
vis_square(feat, padval=0.5)


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
The input image
The first layer filters, conv1
Can you write Python code for it?

# the parameters are a list of [weights, biases]
filters = net.params['conv1'][0].data
vis_square(filters.transpose(0, 2, 3, 1))


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
The parameters and their shapes. The parameters are net.params['name'][0] while biases are net.params['name'][1].
Can you write Python code for it?

[(k, v[0].data.shape) for k, v in net.params.items()]


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
The second layer filters, conv2
There are 256 filters, each of which has dimension 5 x 5 x 48. We show only the first 48 filters, with each channel shown separately, so that each filter is a row.
Can you write Python code for it?

filters = net.params['conv2'][0].data
vis_square(filters[:48].reshape(48**2, 5, 5))


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
The second layer output, conv2 (rectified, only the first 36 of 256 channels)
Can you write Python code for it?

feat = net.blobs['conv2'].data[0, :36]
vis_square(feat, padval=1)


I am working on the file "Exercise10/00-classification.ipynb".
The first task is:
The third layer output, conv3 (rectified, all 384 channels)
Can you write Python code for it?

feat = net.blobs['conv3'].data[0]
vis_square(feat, padval=0.5)


I am working on the file "Exercises-1.ipynb".
The first task is:
106867
How many leading roles (n=1) were available from the beginning of film history through 1980?
Can you write Python code for it?

c = cast
c = c[c.year <= 1980]
c = c[c.n == 1]
c.count()


I am working on the file "Exercises-1.ipynb".
The first task is:
1423
How many movies were made from 1950 through 1959?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
147404
How many roles were avilable for actresses in the 1950s?
Can you write Python code for it?

c = cast
c = c[c.type == 'actress']
len(c.n)


I am working on the file "Exercises-1.ipynb".
The first task is:
21
But how many roles in the movie "Inception" did receive an "n" value?
Can you write Python code for it?

c =  cast
c = c[c.title == 'Inception']
c = c[c.n.notnull()]
len(c)


I am working on the file "Exercises-1.ipynb".
The first task is:
212811
What are the earliest two films listed in the titles dataframe?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
51
Display the cast of "North by Northwest" in their correct "n"-value order, ignoring roles that did not earn a numeric "n" value.
Can you write Python code for it?

c = cast
c = c[c.title == "North by Northwest"]
c = c[c.n.notnull()]
c.sort('n')


I am working on the file "Exercises-1.ipynb".
The first task is:
51
List the supporting roles (having n=2) played by Cary Grant in the 1940s, in order by year.
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
55
How many "Hamlet" roles have been listed in all film credits through history?
Can you write Python code for it?

c = cast
c = c[c.character == 'Hamlet']
len(c)


I am working on the file "Exercises-1.ipynb".
The first task is:
630932
How many roles through 1980 were minor enough that they did not warrant a numeric "n" rank?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
81
How many people have played an "Ophelia"?
Can you write Python code for it?

c = cast
c = c[c.character == 'Ophelia']
len(c)


I am working on the file "Exercises-1.ipynb".
The first task is:
9
How many roles were credited in Branagh’s 1996 Hamlet?
Can you write Python code for it?

c = cast
c = c[(c.title == 'Hamlet') & (c.year == 1996)]
len(c.n)


I am working on the file "Exercises-1.ipynb".
The first task is:
But how many roles in the movie "Inception" did receive an "n" value?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
Display the cast of "North by Northwest" in their correct "n"-value order, ignoring roles that did not earn a numeric "n" value.
Can you write Python code for it?

cast[cast.title == "North by Northwest" ][cast.n.notnull()].sort('n')


I am working on the file "Exercises-1.ipynb".
The first task is:
How many "Hamlet" roles have been listed in all film credits through history?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
How many leading roles (n=1) were available from the beginning of film history through 1980?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
How many movies are listed in the titles dataframe?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
How many movies are titled "North by Northwest"?
Can you write Python code for it?

len(titles[titles['title'] == "North by Northwest"])


I am working on the file "Exercises-1.ipynb".
The first task is:
How many movies have the title "Hamlet"?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
How many movies were made in the year 1950?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
How many movies were made in the year 1960?
Can you write Python code for it?

movies_of_1960 = titles[titles.year == 1960]
len(movies_of_1960)


I am working on the file "Exercises-1.ipynb".
The first task is:
How many non-leading roles were available through from the beginning of film history through 1980?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
How many people have played a role called "The Dude"?
Can you write Python code for it?

len(cast[cast.character == "The Dude"] )


I am working on the file "Exercises-1.ipynb".
The first task is:
How many people have played a role called "The Stranger"?
Can you write Python code for it?

len(cast[cast.character == "The Stranger"] )


I am working on the file "Exercises-1.ipynb".
The first task is:
How many people have played an "Ophelia"?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
How many roles in the movie "Inception" are NOT ranked by an "n" value?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
How many roles through 1980 were minor enough that they did not warrant a numeric "n" rank?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
How many roles were available for actors in the 1950s?
Can you write Python code for it?

c = cast
c = c[(c.name == 'Cary Grant') & (c.n == 1) &(c.year >=1940) & (c.year<1950)].sort("year")
c


c = cast
c = c[(c.year >= 1950) & (c.year < 1960)]
c = c[c.type == 'actor']
len(c.n)


I am working on the file "Exercises-1.ipynb".
The first task is:
How many roles were avilable for actresses in the 1950s?
Can you write Python code for it?

len(cast[(cast.type == "actress") &(cast.year >=1940) & (cast.year <1950)])


I am working on the file "Exercises-1.ipynb".
The first task is:
How many roles were credited in Branagh’s 1996 Hamlet?
Can you write Python code for it?

len(cast[(cast.title == "Hamlet") & (cast.year == 1996)][cast.n.notnull()])


I am working on the file "Exercises-1.ipynb".
The first task is:
How many roles were credited in the silent 1921 version of Hamlet?
Can you write Python code for it?

c = cast
c = c[(c.title == 'Hamlet') & (c.year == 1921)]
len(c.n)


len(cast[(cast.title == "Hamlet") & (cast.year == 1921)][cast.n.notnull()])


I am working on the file "Exercises-1.ipynb".
The first task is:
In what years has a movie titled "Batman" been released?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
In what years has a movie titled "Batman" been released?
How many roles were there in the movie "Inception"?
How many roles in the movie "Inception" are NOT ranked by an "n" value?
But how many roles in the movie "Inception" did receive an "n" value?
Display the cast of "North by Northwest" in their correct "n"-value order, ignoring roles that did not earn a numeric "n" value.
Display the entire cast, in "n"-order, of the 1972 film "Sleuth".
Now display the entire cast, in "n"-order, of the 2007 version of "Sleuth".
How many roles were credited in the silent 1921 version of Hamlet?
How many roles were credited in Branagh’s 1996 Hamlet?
How many "Hamlet" roles have been listed in all film credits through history?
How many people have played an "Ophelia"?
How many people have played a role called "The Dude"?
How many people have played a role called "The Stranger"?
How many roles has Sidney Poitier played throughout his career?
How many roles has Judi Dench played?
List the supporting roles (having n=2) played by Cary Grant in the 1940s, in order by year.
List the leading roles that Cary Grant played in the 1940s in order by year.
How many roles were available for actors in the 1950s?
How many roles were avilable for actresses in the 1950s?
How many leading roles (n=1) were available from the beginning of film history through 1980?
How many non-leading roles were available through from the beginning of film history through 1980?
How many roles through 1980 were minor enough that they did not warrant a numeric "n" rank?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
List all of the "Treasure Island" movies from earliest to most recent.
Can you write Python code for it?

titles[titles.title == 'Treasure Island'].sort('year')


titles[titles.title == 'Treasure Island'].sort("year")


I am working on the file "Exercises-1.ipynb".
The first task is:
List the leading roles that Cary Grant played in the 1940s in order by year.
Can you write Python code for it?


c = cast
c = c[c.name == 'Cary Grant']
c = c[(c.year >= 1940) & (c.year < 1950)]
c.sort('year')


I am working on the file "Exercises-1.ipynb".
The first task is:
Now display the entire cast, in "n"-order, of the 2007 version of "Sleuth".
Can you write Python code for it?

c = cast
c = c[(c.title == 'Sleuth') & (c.year == 2007)]
c.sort(['n'])


I am working on the file "Exercises-1.ipynb".
The first task is:
Reproduction of the Corbett and Fitzimmons Fight, Miss Jerry
How many movies have the title "Hamlet"?
Can you write Python code for it?

t = titles
t[t.title == 'Hamlet'].count()


I am working on the file "Exercises-1.ipynb".
The first task is:
What are the earliest two films listed in the titles dataframe?
Can you write Python code for it?


I am working on the file "Exercises-1.ipynb".
The first task is:
When was the first movie titled "Hamlet" made?
Can you write Python code for it?


I am working on the file "Exercises-2.ipynb".
The first task is:
How many leading (n=1) roles were available to actors, and how many to actresses, in the 1950s?
Can you write Python code for it?

c = cast
c = c[c.year // 10 == 195]
c = c[(c.n == 1) ]
c.type.value_counts()


I am working on the file "Exercises-2.ipynb".
The first task is:
How many supporting (n=2) roles were available to actors, and how many to actresses, in the 1950s?
Can you write Python code for it?

c = cast
c = c[c.year // 10 == 195]
c = c[(c.n == 2) ]
c.type.value_counts()


I am working on the file "Exercises-2.ipynb".
The first task is:
Plot how many roles Mammootty has played in each year of his career.
Can you write Python code for it?

# (cast[cast.name == "Mammootty"].character // 1 * 1).value_counts().sort_index().plot(kind='bar')

cast[cast.name == 'Mammootty'].year.value_counts().sort_index().plot()


I am working on the file "Exercises-2.ipynb".
The first task is:
Plot the n-value of the roles that Sidney Poitier has acted over the years.
Can you write Python code for it?

char = cast[cast["name"]== "Sidney Poitier"]
char = char[char.n.notnull()]
char.plot(x="year",y="n",kind="scatter")


I am working on the file "Exercises-2.ipynb".
The first task is:
Plot the n-values of Cary Grant's roles through his career.
Can you write Python code for it?

char = cast[cast.name == "Cary Grant"].sort("year")
char = char[char.n.notnull()]
char.plot(x="year",y ="n", kind="scatter")


I am working on the file "Exercises-2.ipynb".
The first task is:
Plot the n-values of the roles that Judi Dench has played over her career.
Can you write Python code for it?

char = cast[cast.name == "Judi Dench"].sort("year")
char = char[char.n.notnull()]
char.plot(x="year",y ="n", kind="scatter")


I am working on the file "Exercises-2.ipynb".
The first task is:
Plot the number of "Hamlet" characters each decade.
Can you write Python code for it?

t = cast[cast.character == 'Hamlet']
(t.year // 10 * 10).value_counts().sort_index().plot(kind='bar')


I am working on the file "Exercises-2.ipynb".
The first task is:
Plot the number of "Hamlet" films made each decade.
Can you write Python code for it?

t = titles[titles.title == 'Hamlet']
(t.year // 10 * 10).value_counts().sort_index().plot(kind='bar')


t = titles
t = t[t.title == 'Hamlet']
t = t.groupby(t.year // 10 * 10)
t.size().plot(kind="bar")


I am working on the file "Exercises-2.ipynb".
The first task is:
Plot the number of "Rustler" characters in each decade of the history of film.
Plot the number of "Batman" characters each decade.
What are the 11 most common character names in movie history?
Who are the 10 people most often credited as "Herself" in film history?
Who are the 10 people most often credited as "Himself" in film history?
Which actors or actresses appeared in the most movies in the year 1945?
Which actors or actresses appeared in the most movies in the year 1985?
Plot how many roles Mammootty has played in each year of his career.
What are the 10 most frequent roles that start with the phrase "Patron in"?
What are the 10 most frequent roles that start with the word "Science"?
Plot the n-values of the roles that Judi Dench has played over her career.
Plot the n-values of Cary Grant's roles through his career.
Plot the n-value of the roles that Sidney Poitier has acted over the years.
How many leading (n=1) roles were available to actors, and how many to actresses, in the 1950s?
How many supporting (n=2) roles were available to actors, and how many to actresses, in the 1950s?
Can you write Python code for it?

c = cast
c = c[c.name == "George Clooney"]
c.groupby(['year']).size().plot(kind='hist')
del c


I am working on the file "Exercises-2.ipynb".
The first task is:
Plot the number of films that have been released each decade over the history of cinema.
Can you write Python code for it?

t = titles
(t.year // 10 * 10).value_counts().sort_index().plot(kind='bar')


t = titles
t.groupby(t.year // 10 * 10).size().plot(kind='bar')
del t


I am working on the file "Exercises-2.ipynb".
The first task is:
What are the 10 most frequent roles that start with the phrase "Patron in"?
Can you write Python code for it?


I am working on the file "Exercises-2.ipynb".
The first task is:
What are the 10 most frequent roles that start with the word "Science"?
Can you write Python code for it?


I am working on the file "Exercises-2.ipynb".
The first task is:
What are the 11 most common character names in movie history?
Can you write Python code for it?


I am working on the file "Exercises-2.ipynb".
The first task is:
What are the ten most common movie names of all time?
Can you write Python code for it?


titles['title'].value_counts().head()

titles['title'][titles.title == 'xXx']


t = titles
t = t.title.value_counts()
t.head(10)


I am working on the file "Exercises-2.ipynb".
The first task is:
Which actors or actresses appeared in the most movies in the year 1945?
Can you write Python code for it?


I am working on the file "Exercises-2.ipynb".
The first task is:
Which actors or actresses appeared in the most movies in the year 1985?
Can you write Python code for it?


I am working on the file "Exercises-2.ipynb".
The first task is:
Which three years of the 1930s saw the most films released?
Can you write Python code for it?

moviesOf1930s = titles[(titles.year >= 1930) & (titles.year < 1940)]

moviesOf1930s.year.value_counts().sort_index().plot()


t = titles
t = t[(t.year >= 1930) & (t.year < 1940)]
t = t.year.value_counts()
t.head(3)


I am working on the file "Exercises-2.ipynb".
The first task is:
Who are the 10 people most often credited as "Herself" in film history?
Can you write Python code for it?


I am working on the file "Exercises-3.ipynb".
The first task is:
How many leading (n=1) roles were available to actors, and how many to actresses, in each year of the 1950s?
Can you write Python code for it?

c = cast
c = c[c.year // 10 == 195]
c = c[c.n == 1]
c.groupby(['year', 'type']).size()


I am working on the file "Exercises-3.ipynb".
The first task is:
List, in order by year, each of the films in which Frank Oz has played more than 1 role.
Can you write Python code for it?

c = cast
c = c[c.name == 'Frank Oz']
g = c.groupby(['year','title']).size()
g[g > 1].order()


I am working on the file "Exercises-3.ipynb".
The first task is:
Use groupby() to determine how many roles are listed for each of the Pink Panther movies.
Can you write Python code for it?

c = cast
c = c[c.title == 'The Pink Panther']
c = c.sort('n').groupby(['year'])[['n']].max()
c


I am working on the file "Exercises-3.ipynb".
The first task is:
Use groupby() to plot the number of "Hamlet" films made each decade.
Can you write Python code for it?

t = titles[titles.title == "Hamlet"]
t.groupby(t.year // 10 * 10).size().plot(kind='bar')


I am working on the file "Exercises-3.ipynb".
The first task is:
Using groupby(), plot the number of films that have been released each decade in the history of cinema.
Can you write Python code for it?

t = titles
t.groupby(t.year // 10 * 10).size().plot(kind='bar')


I am working on the file "Exercises-4.ipynb".
The first task is:
Build a plot with a line for each rank n=1 through n=3, where the line shows what fraction of that rank's roles were 'actor' roles for each year in the history of film.
Can you write Python code for it?

c = cast
c = c[c.n <= 3]
c = c.groupby(['year', 'type', 'n']).size()
c = c.unstack('type')
r = c.actor / (c.actor + c.actress)
r = r.unstack('n')
r.plot(ylim=[0,1])


I am working on the file "Exercises-4.ipynb".
The first task is:
Define a year as a "Superman year" whose films feature more Superman characters than Batman. How many years in film history have been Superman years?
Can you write Python code for it?

c = cast
c = c[(c.character == 'Superman') | (c.character == 'Batman')]
c = c.groupby(['year', 'character']).size()
c = c.unstack()
c = c.fillna(0)
c.head()

d = c.Superman - c.Batman
print('Superman years:')
print(len(d[d > 0.0]))


I am working on the file "Exercises-4.ipynb".
The first task is:
How many years have been "Batman years", with more Batman characters than Superman characters?
Can you write Python code for it?

d = c.Superman - c.Batman
print('Batman years:')
print(len(d[d < 0.0]))


I am working on the file "Exercises-4.ipynb".
The first task is:
Plot the difference between the number of actor roles each year and the number of actress roles each year over the history of film.
Can you write Python code for it?

c = cast
c = c.groupby(['year', 'type']).size()
c = c.unstack('type')
(c.actor - c.actress).plot()


I am working on the file "Exercises-4.ipynb".
The first task is:
Plot the number of actor roles each year and the number of actress roles each year over the history of film.
Can you write Python code for it?

c = cast
#c = c[(c.character == 'Superman') | (c.character == 'Batman')]
c = c.groupby(['year', 'type']).size()
c = c.unstack()
c = c.fillna(0)
c.plot()


I am working on the file "Exercises-5.ipynb".
The first task is:
In which months do films with Judi Dench tend to be released in the USA?
Can you write Python code for it?

c = cast
c = c[c.name == 'Judi Dench']
m = c.merge(usa).sort('date')
m.date.dt.month.value_counts().sort_index().plot(kind='bar')

c = cast
c = c[c.name == 'Tom Cruise']
m = c.merge(usa).sort('date')
m.date.dt.month.value_counts().sort_index().plot(kind='bar')


I am working on the file "Exercises-5.ipynb".
The first task is:
Make a bar plot of the day of the week on which movies with "Action" in their title tend to be released in the USA.
Can you write Python code for it?

r_d = release_dates[(release_dates.title.str.contains("Action")) ]
r_d

r_d.date.dt.dayofweek.value_counts().sort_index().plot(kind="bar")


I am working on the file "Exercises-5.ipynb".
The first task is:
Make a bar plot of the months in which movies with "Christmas" in their title tend to be released in the USA.
Can you write Python code for it?

r_d = release_dates[(release_dates.title.str.contains("Christmas")) & (release_dates.country == "USA")]

r_d.date.dt.month.value_counts().sort_index().plot(kind="bar")


I am working on the file "Exercises.ipynb".
The first task is:
4) The linear fit with outliers, with outliers.
In the notebook we saw how to fit a slope and intercept to points with errors in the vertical direction. We reproduce the data set here:
Can you write Python code for it?


I am working on the file "Exercises.ipynb".
The first task is:
Exercises on Bayesian statistics and inference
These are exercises belonging to the workshop material on Bayesian statistics and inference "Bayesian Statistics: the what, the why, and the how". I leave it totally up to you whether you do any if this or not. In the Solutions notebook you will find one way to tackle the problems posed here. Most, if not all, problems can be solved in a plethora of ways. Feel free to experiment around, it will only teach you more in the end.
1) Testing positively to a serious disease
Here are the equations for the disease testing exercise. Plug in some numbers and play around if you like.
Can you write Python code for it?

P_positive_if_ill = .99
P_positive_if_notill = .01
P_ill = 1.e-3

def P_ill_if_positive(P_positive_if_ill=.99, P_positive_if_notill=.01, P_ill=1.e-3):
    """Function that simply plugs the numbers into Bayes' theorem"""
    P_notill = 1 - P_ill
    return P_positive_if_ill * P_ill / (P_positive_if_ill * P_ill + P_positive_if_notill * P_notill )

# Feel free to play around with these numbers!
print(P_ill_if_positive(P_positive_if_ill=.99, P_positive_if_notill=.01, P_ill=1.e-3))


I am working on the file "Exercises.ipynb".
The first task is:
Intermediate Level
This exercise is designed for those who are already somewhat comfortable with python and want to learn more about exploiting its capabilities. It asks you to read in a file containing 10 time series, each containing a gaussian radio pulse. Then, using numpy and matplotlib, it asks you to plot the pulse, measure the pulse's signal to noise ratio, and output values in a nicely formatted table.

Read in the file "intermediate.txt" in this directory.
The file contains 10 rows of comma separated numbers. Each row represents the amount of signal output from a radio antenna as a function of time (in 1 second time intervals). Loop through the lines in the file (f.readlines() will be useful here). For each line, do the following:
Convert the line from one long string into a numpy array of floats.
Using matplotlib.pyplot make a plot of the data you just read in as a function of time (hint: you'll have to figure out how many time steps are present in the data).
Using the capabilities of numpy, find the value of the maximum flux in your time series.
Excluding your pulse, (the pulse is in the first half of the time series, so you can cheat and just limit yourself to the second half of the time series) calculate the rms noise in your spectrum. (Recall that the rms is the root mean square - find the mean of the squares of all the points, then take the square root. You might also use np.std() and compare the results (and think about why they are different, if they are different)).
Do a simple estimate of the signal to noise ratio of the pulse as peakflux/rms.
Using a formatted string, print the output signal to noise, peakflux and rms to a descriptive table, rounding each number to two decimal places.

If time permits figure out how to display all your time series on top of one another at the end, rather than having the plots pop up one at a time.
If time permits mess around with fitting the gaussian pulse and come up with other estimates of the signal to noise ratio.
Can you write Python code for it?

# Put your code here
pass

# only run this cell after you finished writing your code
%load beginner_soln.py


I am working on the file "Exercises.ipynb".
The first task is:
Questions you could ask yourself are:
- What number would the pharmaceutical industry like to see optimized compared to the example?
- Most people guess a much higher probability than 0.09 when given the question. What aspect are they forgetting about, and how/where does this appear in Bayes' theorem?
- What happens when you forget the terms about false positives?
- Investigate the dependence of the posterior probability graphically.
2) Updating one's knowledge of a system
Given the numbers in the original example, as stated above, how many positive tests do you need to get before your certainty about being ill rises above 99%?
It's probably easiest to write a while-loop (or a for-loop with a break statement) in which Bayes' theorem is used to update the knowledge with the new data every time.
3) A world of Gaussians
For the situation where we try to determine the mean flux of that star, while it is itself fluctuating in brightness, please recreate the sampler, try to do so from scratch, but if that is too much to ask, then find some inspiration in the notebook.
If that works well: try the following:
- Play with the number of walkers. Does it make much of a difference if you use only one (hint: emcee will tell you!)?
- Try to not use a flat prior, but a very wide Gaussian for the mean, still flat for the standard deviation. Try this with the gaussian centered at the "correct" value, and with Gaussians that do include the correct value at a low but non-zero number of standard deviations from the correct values and one that is far off. Discuss outcomes! It may help to make the intrinsic distribution of fluxes wider (and/or the sample really small).
Can you write Python code for it?

# First, here's the code that generates the data set:
np.random.seed(42)
N = 100
mu_true, sigma_true = 1000, 10  # True flux at time of measurement is distributed following a gaussian.

F_true = stats.norm(mu_true, sigma_true).rvs(N)  # Onbekende werkelijke aantallen, nu met scatter
F = stats.poisson(F_true).rvs()  # Waargenomen aantallen, met errors
e = np.sqrt(F)  # root-N error

# For the visual, a graph of that:
fig, ax = plt.subplots()
ax.errorbar(F, np.arange(N), xerr=e, fmt='ok', ecolor='gray', alpha=0.5)
ax.vlines([F_true], 0, N, linewidth=5, alpha=0.1)
ax.set_xlabel("F");ax.set_ylabel("Measurement number");

# The likelihood, prior and resulting posterior:

# Setting up the emcee run (think of dimensions, walkers, starting guesses)

# Use the tab completion help from the docstring to see how to call the run!


I am working on the file "Exercises.ipynb".
The first task is:
The definition of the posterior shows what will need to go into the prior and what comes. What is it?
Also define the prior as a function. Think of the allowed parameter ranges, don't cheat and look the solutions notebook.
Now let's run the MCMC, in the same set-up as in the notebook, to make sure we get the weird points:
Can you write Python code for it?

ndim = 2 + len(x)  # number of parameters in the model
nwalkers = 50  # number of MCMC walkers
nburn = 10000  # "burn-in" period to let chains stabilize
nsteps = 15000  # number of MCMC steps to take

# set theta near the maximum likelihood, with

from scipy import optimize

def squared_loss(theta, x=x, y=y, e=e):
    dy = y - theta[0] - theta[1] * x
    return np.sum(0.5 * (dy / e) ** 2)

theta1 = optimize.fmin(squared_loss, [0, 0], disp=False)

np.random.seed(42)
starting_guesses = np.zeros((nwalkers, ndim))
starting_guesses[:, :2] = np.random.normal(theta1, 1, (nwalkers, 2))
starting_guesses[:, 2:] = np.random.normal(0.5, 0.1, (nwalkers, ndim - 2))

import emcee
sampler = emcee.EnsembleSampler(nwalkers, ndim, log_posterior, args=[x, y, e, 50])
sampler.run_mcmc(starting_guesses, nsteps)

sample = sampler.chain  # shape = (nwalkers, nsteps, ndim)
sample = sampler.chain[:, nburn:, :].reshape(-1, ndim)

fig = plt.figure()
ax = plot_mcmc(sample[:,:2].T, fig=fig, labels=[r'Intercept', r'slope'], colors='k')
ax[0].plot(sample[:, 0], sample[:, 1], '.k', alpha=0.1, ms=4);
ax[0].plot([mu_true], [sigma_true], 'o', color='red', ms=10);


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
Questão 1
Demonstrar graficamente a propriedade comutativa da adição de vetores, ou seja, que u + v = v + u.
Can you write Python code for it?

def line_limits(x, y, length, axes_size):
    """
    Função utilitária para calcular as dimensões da seta do vetor nos eixos x e y.
    A seta representa um triângulo retângulo, cuja hipotenusa é o comprimento da seta.
    """
    v = [x, y]
    # O coseno diretor do vetor v é o mesmo da seta
    dc = dcos(v)
    # x e y são aproximados em função dos valores do coseno diretor
    x, y = (v[0] + dc[0] * length), (v[1] + dc[1] * length)

    return (x, y, x / axes_size, y / axes_size)

def draw_vector(name:str, origin_x, origin_y, x, y, axes_size, fc='k', lc='b',
                labelPos=dict(ha="right", va="bottom"), withProjs=True, immediate=False):
    """
    Desenha o vetor especificado.
    """

    # Propriedades da ponta das setas dos vetores
    arrowtip  = dict(head_width=0.2, head_length=0.2)
    # Propriedades das linhas de projeção aos eixos
    lineprops = dict(linewidth=0.5, ls='--')
    # Posição da nota com nome do vetor.
    notexy = (x / 2 + origin_x, y / 2 + origin_y)
    # Recupera os eixos de coordenadas.
    ax = plt.axes()
    plt.axis([0, axes_size, 0, axes_size])

    # Vetor
    limits = line_limits(x, y, arrowtip['head_width'], axes_size)
    ax.arrow(origin_x, origin_y, x, y, **arrowtip, fc=fc, ec=fc)
    ax.annotate(name, xy=notexy, xytext=notexy, **labelPos, color=fc,
                family="serif", weight="semibold", size="x-large")
    if withProjs:
        plt.axhline(limits[1], xmax=limits[2], color=lc, **lineprops)
        plt.axvline(limits[0], ymax=limits[3], color=lc, **lineprops)

    if immediate:
        plt.show()

# Solução da questão 1
#
axessize = 5

# Vetor u
u = [2, 3]
draw_vector('u', 0, 0, *u, axessize, 'k', 'g')

# Vetor v
v = [3, 1.5]
draw_vector('v', 0, 0, *v, axessize, 'b', 'b')

plt.show()

## Plotagem de u + v
#
axessize = 6

# Desenha u novamente
draw_vector('u', 0, 0, *u, axessize, 'k', 'g')

# Desenha v a partir de u
draw_vector('v', *u, *v, axessize, 'b', withProjs=False)

# Vetor u + v
uv = [u[0] + v[0], u[1] +...


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
Questão 2
Calcular os cossenos diretores para os vetores indicados.
Can you write Python code for it?

def print_dcos(dcos: Vector):
    """
    Faz uma impressão "bonita" da sequência dos cosenos diretores guardados no vetor dcos.
    """
    indices = ['i', 'j', 'k']
    print('\n'.join('Coseno diretor {} é {:.4}'.format(indices[k], v) for k, v in list(enumerate(dcos))))


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
Questão 4
Sendo a = ax.i + ay.j + az.k e b = bx.i + by.j + bz.k, apresentar a X b na forma de matriz.

Sugestão: usar  o conceito de determinante de uma matriz.
Can you write Python code for it?


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
Questão 5
Sendo a = 3i + 5j e b = 2i + j, calcular o ângulo entre a e b, usando o produto interno.
Can you write Python code for it?

def intern_angle(a: Vector, b: Vector, verbose=False, degrees=True):
    """
    Calcula o ângulo interno entre dois vetores a partir do produto interno entre eles.
    O produto interno é dado por ||a||.||b||.cos(tetha), sendo tetha o ângulo entre os vetores a e b.
    Logo, temos que tetha = arccos((a.b)/(||a||.||b||))
    """
    #a, b = np.array(a), np.array(b)

    # Produto interno entre a e b
    dp = np.dot(a, b)

    # Normas dos vetores a e b
    na, nb = np.linalg.norm(a), np.linalg.norm(b)

    # Cosseno de tetha
    cosin = dp / (na * nb)

    if verbose:
        print("O produto interno entre {} e {} é: {}".format(a, b, dp))
        print("As normas dos vetores a e b são, respectivamente: {:.4} e {:.4}".format(na, nb))
        print("O cosseno do ângulo entre a e b é {:.6}".format(cosin))

    ac = np.arccos(cosin) # ângulo em radianos [0, pi]
    if degrees:
        result = ac * 180 / np.pi
        if verbose:
            print("O ângulo {:.4} radianos corresponde a {:.8}º".format(ac, result))
        return result
    return ac

## Solução da questão 5.
#
a, b = [3, 5], [2, 1]
print("O ângulo interno entre a e b é de {:.8}º".format(intern_angle(a, b, True)))


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
Questão 8
Calcular os comprimentos dos cossenos diretores dos vetores AB, abaixo, determinando também os ângulos alpha, beta e gama formados entre esses vetores e os eixos de coordenadas na direção positiva. E, por fim, mostrar que, em cada caso, cos2(alpha) + cos2(beta) + cos2(gama) = 1.
Can you write Python code for it?

def q8(v):
    """
    Rotina para a questão 8.
    """
    # Cossenos diretores.
    dc = dcos(v, True)
    print_dcos(dc)

    # Cálculo dos ângulos "diretores".
    angles_names = ['alpha', 'beta', 'gamma']
    angles = {}
    for k, name in enumerate(angles_names):
        angles[name] = np.arccos(dc[k]) * 180/np.pi
        print("O ângulo {} tem o valor de {:.6}".format(name, angles[name]))

    # Verificação da combinação afim.
    sum, output = 0, ""
    for c in dc:
        part = c*c
        sum += part
        if (output != ""):
            output += " + "
        output += "({:.4})^2".format(c)
    print("{} = {:.2}".format(output, sum))


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
a) A(1,1,1) e B(2,0,1)
Can you write Python code for it?


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
a) P(4, 8), Q(3, 7)
Can you write Python code for it?


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
b) A(2, -1, 1) e B(-2, -2, 2)
Can you write Python code for it?


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
b) P(3, -5), Q(-4, -7)
Can you write Python code for it?


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
b) k = [-4, 8]
Can you write Python code for it?


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
c) A(-1, 3, 1) e B(-2, -1, 0)
Can you write Python code for it?


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
c) P(-5, 0), Q(-3, 1)
Can you write Python code for it?


I am working on the file "Exercises/Exercícios#1.ipynb".
The first task is:
d) P(3, 3), Q(4, 4)
Can you write Python code for it?


I am working on the file "Exercises/Exercícios#2.ipynb".
The first task is:
Questão #2
Considere a curva planar dada pela equação vetorial: r(u) = - u i + 1/u j, u ≠ 0.

Construa uma tabela de valores para u e, então, esboce esta curva para -10 ≤ u ≤ 10.

Inclua considerações sobre -1 < u < 0 e 0 < u < 1.
Can you write Python code for it?

INF = float('Inf')

# Valores de u
u_table = [np.linspace(-10, 10, 21), np.linspace(-1, 1, 11)]

# Impressão das tabelas
#
for u in u_table:
    print('\nValores para u = {}...', u)
    # Equações paramétricas correspondentes
    x = -u
    y = [1/ui for ui in u - [0]]

    # Equação de y em função de x
    yx = [-1/xi for xi in x - [0]];

    # Os vetores devem possuir o mesmo tamanho.
    assert len(u) == len(x) == len(y) == len(yx)
    print('Foram gerados {:d} pontos.'.format(len(u)))

    # Gerar o código LaTex da tabela de valores.
    print('$u$\t&$x$\t&$y$\t&$r(u)$\\\\ \midrule')
    for k, ui in enumerate(u):
        if y[k] == INF:
            continue
        print('{u:6.2}\t&{x:6.2}\t&{y:6.2f}\t&${x:6.2}\\mathbf{{i}} {signal} {yabs:6.2f}\\mathbf{{j}}$\\\\'.
              format(
                k=k+1, u=ui,
                x=x[k],
                y=y[k],
                signal=('-' if y[k] < 0 else '+'),
                yabs=np.abs(y[k])
              )
             )

## Desenho do gráfico da função.
#

# Valores de u
u_plot  = [np.linspace(-10, 10, 200), np.linspace(-1, 1, 200)]
u = u_plot[0] # Mude de 0 para 1 aqui para plotar o gráfico entre -10 e 10 ou entre -1 e 1, respectivamente.

# Equações paramétricas da curva
x = -u
y = [1/ui for ui in u - [0]]

# Equação de y em função de x
yx = [-1/xi for xi in x - [0]]

# Desenha o gráfico.
ax = prep_axis()
ax.plot(x, yx)

plt.show()


I am working on the file "Exercises/Exercícios#2.ipynb".
The first task is:
Questão #3
A curva 3D abaixo tem a seguinte equação vetorial: r(θ) = θ / 360 i + 5 cos θ j + 3 sen θ k**, onde θ é medido em graus.<br>
Identifique esta curva e descreva suas principais características.
Can you write Python code for it?

from mpl_toolkits.mplot3d import Axes3D

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')

circle = 2 * np.pi
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)

x = theta / circle
y = 5 * np.cos(theta)
z = 3 * np.sin(theta)

plot_directors = True # Mude para True para plotar as retas diretoras.
if plot_directors:
    ax.plot(x, y, z, label='curva paramétrica')
    ax.plot(x, [5 for xi in x], [0 for xi in x], label='$\mathbf{D}_y$')
    ax.plot(x, [-5 for xi in x], [0 for xi in x], label='$\mathbf{D\'}_y$')
    ax.plot(x, [0 for xi in x], [3 for xi in x], label='$\mathbf{D}_z$')
    ax.plot(x, [0 for xi in x], [-3 for xi in x], label='$\mathbf{D\'}_z$')
    ax.legend()
else:
    ax.plot(x, y, z)

fig = plt.figure()

plt.show()


I am working on the file "Exercises/Grammar2HTML-Antlr/Grammar-2-HTML.ipynb".
The first task is:
Converting a Grammar into Html
You should store the  stored in the file Grammar.g4.  This grammar should describe the lexical structure of the grammar for the language
C that is contained in the file
<tt>c-grammar.g</tt>.
Your grammar must not use the string rule as a variable name.  The reason is that rule is a variable that is already used in the parser generated by
Antlr.
You grammar should generate an abstract syntax tree that conforms to the following type specification:
Grammar: List<Rule>
Rule:    Pair<String, List<Body>>
Body:    List<Item>
Item:    Pair<'var', String> + Pair<'token', String> + Pair<'literal', String>
Can you write Python code for it?


I am working on the file "Exercises/Grammar2HTML-Antlr/Grammar-2-HTML.ipynb".
The first task is:
Converting a Grammar into Html
You should store the grammar in the file Grammar.g4.  This grammar should describe the lexical structure of the grammar for the language
C that is contained in the file
<tt>c-grammar.g</tt>.
Your grammar must not use the string rule as a variable name.  The reason is that rule is a variable that is already used in the parser generated by
Antlr.
You grammar should generate an abstract syntax tree that conforms to the following type specification:
Grammar: List<Rule>
Rule:    Pair<String, List<Body>>
Body:    List<Item>
Item:    Pair<'var', String> + Pair<'token', String> + Pair<'literal', String>
Can you write Python code for it?


I am working on the file "Exercises/Grammar2HTML-Antlr/Grammar-2-HTML.ipynb".
The first task is:
Our goal is to convert this grammar into an Html file.
We start by generating both scanner and parser.
Can you write Python code for it?

!antlr4 -Dlanguage=Python3 Grammar.g4

from GrammarLexer  import GrammarLexer
from GrammarParser import GrammarParser
import antlr4


I am working on the file "Exercises/Grammar2HTML-Antlr/Grammar-2-HTML.ipynb".
The first task is:
The command below cleans the directory.  If you are running windows, you have to replace rmwith del.
Can you write Python code for it?


I am working on the file "Exercises/Grammar2HTML-Antlr/Grammar-2-HTML.ipynb".
The first task is:
The file c-grammar.g contains a context-free grammar for the language C.
Can you write Python code for it?


I am working on the file "Exercises/Grammar2HTML-Antlr/Grammar-2-HTML.ipynb".
The first task is:
The function body_2_string takes a list of grammar items as its inputs and turns them into an Html string.
Can you write Python code for it?

def body_2_string(body):
    result = ''
    if len(body) > 0:
        for item in body:
            result += item_2_string(item) + ' '
    else:
        result += '<code>/* empty */</code>'
    return result


I am working on the file "Exercises/Grammar2HTML-Antlr/Grammar-2-HTML.ipynb".
The first task is:
The function grammar_2_string takes a list of grammar rules as its input and renders these rules as an Html file.
Can you write Python code for it?

def grammar_2_string(grammar):
        result  = ''
        result += '\n'
        result += '\n'
        result += '<title>Grammar</title>\n'
        result += '\n'
        result += '\n'
        result += '
\n'
        for rule in grammar:
            result += rule_2_string(rule)
        result += '
\n'
        result += '\n'
        result += '\n'
        return result


I am working on the file "Exercises/Grammar2HTML-Antlr/Grammar-2-HTML.ipynb".
The first task is:
The function item_2_string takes a grammar item as its inputs and turns the item into an Html string.
An item represents either a non-terminal or a terminal.  If it represents a non-terminal it has the form
$$(\texttt{'var'}, \textrm{name}) $$
where $\textrm{name}$ is the name of the variable. Otherwise it has the form
$$(\textrm{kind}, \textrm{name}), $$
where $\textrm{kind}$ is either token or literal.
Can you write Python code for it?

def item_2_string(item):
    kind, contend = item
    if kind == 'var':
        return '' + contend + ''
    else:
        return '' + contend + ''

def main():
    input_stream  = antlr4.FileStream('c-grammar.g')
    lexer         = GrammarLexer(input_stream)
    token_stream  = antlr4.CommonTokenStream(lexer)
    parser        = GrammarParser(token_stream)
    grammar       = parser.start()
    result        = grammar_2_string(grammar.g)
    file = open('c-grammar.html', 'w')
    file.write(result)

main()

!open c-grammar.html


def item_2_string(item):
    kind, contend = item
    if kind == 'var':
        return '' + contend + ''
    else:
        return '' + contend + ''

def main():
    input_stream  = antlr4.FileStream('c-grammar.g')
    lexer         = GrammarLexer(input_stream)
    token_stream  = antlr4.CommonTokenStream(lexer)
    parser        = GrammarParser(token_stream)
    grammar       = parser.start()
    result        = grammar_2_string(grammar.result)
    file = open('c-grammar.html', 'w')
    file.write(result)

main()

!open c-grammar.html

!explorer c-grammar.html


I am working on the file "Exercises/Grammar2HTML-Antlr/Grammar-2-HTML.ipynb".
The first task is:
The function rule_2_string takes a grammar rule $r$ as its input and transforms this rule into an Html
string.  Here the grammar rule $r$ has the form
$$ r = (V, L) $$
where $V$ is the name of the variable defined by $r$ and $L$ is a list of grammar rule bodies.  A single grammar rule
body is a list of grammar items.  A grammar item is either a non-terminal, a token or a literal.
Can you write Python code for it?

def rule_2_string(rule):
    head, body = rule
    result  = ''
    result += '
\n'
    result += '' + head + '	\n'
    result += ':	\n'
    result += '' +  body_2_string(body[0]) + '	'
    result += '
\n'
    for i in range(1, len(body)):
        result += '
	|	'
        result += body_2_string(body[i])
        result += '
\n'
    result += '
	;
\n\n'
    return result


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
$$ c = \sqrt{a^{2}+b^{2}} $$
Let us look at the output file example.pdf that is produced if we run $\LaTeX$ on this file.
Depending on your operating system, you might have to exchange the command start for another command
that is able to open the file example.pdf.
Can you write Python code for it?


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
$\cdots$ lots of token definitions $\cdots$
Can you write Python code for it?

def formula_LEQ(t):
    r'\\leq'
    write_leq()

def t_formula_GEQ(t):
    r'\\geq'
    write_geq()

def t_formula_PI(t):
    r'\\pi'
    write_pi()

def t_formula_OPERATOR(t):
    r'[.,()+<>=-]'
    write_operator(t.value)

def t_formula_WS(t):
    r'[ \t]'
    pass

def t_formula_error(t):
    print(f"Illegal character in state 'formula': '{t.value[0]}'")
    t.lexer.skip(1)


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:

Below are some predefined functions that you can use to create the Html file.

The function start_html writes the header of the Html file
and the opening <body> tag to the file opened above.
Can you write Python code for it?

def start_html():
    outfile.write('<!doctype html>\n')
    outfile.write('<html>\n')
    outfile.write('<head>\n')
    outfile.write('<script type="text/javascript" ')
    outfile.write('src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">\n')
    outfile.write('</script>\n')
    outfile.write('<head>\n\n')
    outfile.write('<body>\n\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
Converting $\LaTeX$ to Html
The purpose of the following exercise is to implement a translator from $\LaTeX$ to
MathML.  $\LaTeX$ is a document markup language
that is especially well suited to present text that contains mathematical formulas.  MathML is the part of Html that deals with the representation of mathematical formulas.  As $\LaTeX$ provides a very rich
document markup language and we can only afford to spend a few hours on this exercise, we confine
ourselves to a small subset of $\LaTeX$.  The file example.tex contains some $\LaTeX$.  The goal of this exercise is to implement a translator that is able to transform this file into MathML.
We start with reading the file.
Can you write Python code for it?

with open('example.tex') as f:
    data = f.read()


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
In order to scan the data that we provided in the last line, we iterate over all tokens generated by our scanner.
Can you write Python code for it?

def scan(lexer):
    for t in lexer:
        pass

scan(lexer)

outfile.close()


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
In order to write exponents we have to use the tag <msup>.  For example, the expression $a^2$
is equivalent to the following markup:
<msup>
<mi>a</mi>
<mrow>
<mn>2</mn>
</mrow>
</msup>
Note that the exponent is enclosed in <mrow> </mrow> tags.
<b>Note</b> that everything, i.e. both the variable and the exponent is enclosed in <msup> </msup> tags.
Can you write Python code for it?

def start_super():
    outfile.write('<msup>\n')

def end_super():
    outfile.write('</msup>\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
Let us look at the output file example.pdf that is produced if we run $\LaTeX$ on this file.
Depending on your operating system, you might have to exchange the command start for another command
that is able to open the file example.pdf.
Can you write Python code for it?


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
Mathematical operators should be enclosed in pairs of <mo> and </mo> tags.  For example, the operator $+$ is displayed by the following MathML:
<mo>+</mo>
Can you write Python code for it?

def write_operator(op):
    outfile.write('<mo>' + op + '</mo>\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
Next, we feed our input string into the generated scanner.
Can you write Python code for it?


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
Next, we open the file example.html.  The scanner we are going to implement has to write its output into this file.
Can you write Python code for it?


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
Now the variable data contains the text that is stored in this file.
Can you write Python code for it?


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
Numbers should be enclosed in pairs of <mn> and </mn> tags.  For example, the number $6$ is displayed by the following MathML:
<mn>6</mn>
Can you write Python code for it?

def write_number(n):
    outfile.write('<mn>' + n + '</mn>\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The function end_html writes the closing </body> and </html> tags.
Can you write Python code for it?

def end_html():
    outfile.write('\n')
    outfile.write('\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The function start_math_block starts a math block.  This is useful for formulas enclosed in $$.  This type of formulas is displayed in a line by itself.
Can you write Python code for it?

def start_math_block():
    outfile.write('<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The function start_math_inline starts an inline formula, i.e. a formula enclosed in $.  Formulas of this type are part of the surrounding text.
Can you write Python code for it?

def start_math_inline():
    outfile.write('<math xmlns="http://www.w3.org/1998/Math/MathML" display="inline">\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The function write_any writes a single character unadorned to the output file.
Can you write Python code for it?

def write_any(char):
    outfile.write(char)


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The functions start_sqrt and end_sqrt write code to display formulas involving square roots.  For example, to display  the expression
$$ \sqrt{a^2 + b^2} $$
we can use the following MathML:
<msqrt>
<mrow>
<msup>
<mi>a</mi>
<mrow>
<mn>2</mn>
</mrow>
</msup>
<mo>+</mo>
<msup>
<mi>b</mi>
<mrow>
<mn>2</mn>
</mrow>
</msup>
</mrow>
</msqrt>
Can you write Python code for it?

def start_sqrt():
    outfile.write('<msqrt>\n')

def end_sqrt():
    outfile.write('</msqrt>\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The functions start_sum and end_sum write code to display formulas involving sums.  For example, to display  the expression
$$ \sum\limits_{i=1}^n i^2 $$
we can use the following MathML:
<munderover>
<mo>&sum;</mo>
<mrow>
<mi>i</mi>
<mo>=</mo>
<mn>1</mn>
</mrow>
<mrow>
<mi>n</mi>
</mrow>
</munderover>
<msup>
<mi>i</mi>
<mrow>
<mn>2</mn>
</mrow>
</msup>
Can you write Python code for it?

def start_sum():
    outfile.write('<munderover>\n')
    outfile.write('<mo>∑</mo>\n')

def end_sum():
    outfile.write('</munderover>\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The line below generates the scanner.
Can you write Python code for it?


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The line below is necessary to trick ply.lex into assuming this program is written in an ordinary python file instead of a Jupyter notebook.
Can you write Python code for it?


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The symbol $\cdot$ is created by the following MathML:
<mo>&sdot;</mo>
Can you write Python code for it?

def write_times():
    outfile.write('<mo>⋅</mo>\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The symbol $\geq$ is created by the following MathML:
<mn>&ge;</mn>
Can you write Python code for it?

def write_geq():
    outfile.write('<mo>≥</mo>\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The symbol $\leq$ is created by the following MathML:
<mn>&le;</mn>
Can you write Python code for it?

def write_leq():
    outfile.write('<mo>≤</mo>\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
The symbol $\pi$ is created by the following MathML:
<mn>&pi;</mn>
Can you write Python code for it?

def write_pi():
    outfile.write('<mn>π</mn>\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
Variable names should be enclosed in pairs of <mi> and </mi> tags.  For example, the variable $x$ is displayed by the following MathML:
<mi>x</mi>
The tag name mi is short for math italics.
Can you write Python code for it?

def write_var(v):
    outfile.write('<mi>' + v + '</mi>\n')


I am working on the file "Exercises/LaTeX2HTML/LaTeX2HTML.ipynb".
The first task is:
We have to declare all tokens below.  We will need tokens for the following parts of the $\LaTeX$ file:
 - The $\LaTeX$ file starts with the string \documentclass{article}.
 - Next, there is the string \begin{document} that starts the content.
 - The string \end{document} ends the content.
 - The string $$ starts and ends a formula that is displayed on a line by itself.
 - The string $ starts and ends a formula that is displayed as part of the text.
 - The string \sum\limits_{ starts the definition of a sum.
 - The string \sqrt{ starts the definition of a square root.
 - The string \frac{ starts the definition of a fraction.
 - A variable taken to a power starts something like a^{.
 - $\vdots$
Can you write Python code for it?

tokens = [ 'HEAD',            # r'\\documentclass\{article\}'
           'BEGIN_DOCUMENT',  # r'\\begin\{document\}'
           'END_DOCUMENT',    # r'\\end\{document\}'
           'DOLLAR_DOLLAR',   # r'\$\$'
           'DOLLAR',          # r'\$'
           '...' # many more token declarations here
           'ANY',             # r'.|\n'
           'WS'               # r'[ \t]'
         ]