Merge remote-tracking branch 'origin/master'

This commit is contained in:
2019-11-29 14:03:28 +01:00
65 changed files with 1034 additions and 1910 deletions
Vendored
BIN
View File
Binary file not shown.
View File
+24
View File
@@ -0,0 +1,24 @@
import cv2
cap = cv2.VideoCapture(0)
print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
cap.set(3, 3000)
cap.set(4, 3000)
print(cap.get(3))
print(cap.get(4))
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows()
+29
View File
@@ -0,0 +1,29 @@
import pygame
from pygame.locals import *
import cv2
import numpy as np
import sys
camera = cv2.VideoCapture(0)
pygame.init()
pygame.display.set_caption("OpenCV camera stream on Pygame")
screen = pygame.display.set_mode([1280,720])
try:
while True:
ret, frame = camera.read()
screen.fill([0,0,0])
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = np.rot90(frame)
frame = pygame.surfarray.make_surface(frame)
screen.blit(frame, (0,0))
pygame.display.update()
for event in pygame.event.get():
if event.type == KEYDOWN:
sys.exit(0)
except (KeyboardInterrupt,SystemExit):
pygame.quit()
cv2.destroyAllWindows()
+6 -1
View File
@@ -2,6 +2,8 @@ from selenium import webdriver
from PIL import Image
import numpy as np
import time
import os
url="https://patrickhlauke.github.io/recaptcha/"
@@ -28,7 +30,10 @@ def searchCaptcha(filename):
def resolveCaptcha(url):
driver=webdriver.Chrome('/Users/olivierpartensky/Programs/Library/Selenium/chromedriver')
path = os.path.("/chromedriver")
# dir_path = os.path.dirname(os.path.realpath(__file__))
print(path)
driver=webdriver.Chrome(path)
action=webdriver.common.action_chains.ActionChains(driver)
driver.get(url)
#action.move_by_offset(36,156)
@@ -0,0 +1,8 @@
import os
db_user = os.environ.get('DB_USER')
db_password = os.environ.get('DB_PASSWORD')
print(db_user)
print(db_password)
+26
View File
@@ -0,0 +1,26 @@
import cv2
import numpy as np
sj="saint jalm.jpg"
vl="valentin.png"
tm="tetedemarc.png"
pm="profiledemarc.jpg"
img = cv2.imread(tm,0)
img = cv2.medianBlur(img,5)
img = cv2.Canny(img,50,150)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,
param1=50,param2=30,minRadius=0,maxRadius=200)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
# draw the outer circle
cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
+18
View File
@@ -0,0 +1,18 @@
import cv2
import numpy as np
sj="saint jalm.jpg"
vl="valentin.png"
tm="tetedemarc.png"
pm="profiledemarc.jpg"
img = cv2.imread(tm)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
minLineLength = 100
maxLineGap = 10
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)
for (x1,y1,x2,y2) in lines[0]:
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imwrite('houghlines5.jpg',img)
-130
View File
@@ -1,130 +0,0 @@
import random
"""Partie 1: Tri par sélection."""
def reperer(liste,n):
"""Repere la position du plus grand element parmi les n premiers elements d'une liste."""
maximum=liste[0] #Affecte a maximum la valeur du premier élément de la liste.
position=0 #Affecte a position la valeur de 0.
for i in range(1,n): #Fait varier les valeurs de i de 1 à n.
if liste[i]>maximum: #Verifie si la ie valeur de la liste est supérieur a la valeur de maximum.
maximum=liste[i] #Si oui, affecte a maximum la valeur du ie valeur de la liste.
position=i #Recupere la position de cet élément.
return position #Renvoie la position de cet élément.
def echanger(liste,position1,position2):
"""Echange 2 éléments d'une liste de positions données."""
valeur=liste[position1] #Affecte a valeur la valeur de position1e terme de la liste.
liste[position1]=liste[position2] #Mets en position1 le position2e terme de la liste.
liste[position2]=valeur #Affecte au position2e terme de la liste la valeur de valeur.
return liste #Renvoie la nouvelle liste de termes échangés.
def TriParSelection(liste):
"""Tri une liste."""
for n in range(len(liste)-1,0,-1): #Fait varier les valeurs de n de len(liste)-1 à 1.
r=reperer(liste,n) #Recupere la position du plus grand élément parmi les n premiers.
liste=echanger(liste,n,r) #Echange les éléments de position n et r.
return liste #Renvoie la liste triée.
def test(a,b,taille,nombre=10):
"""Test:"""
for i in range(nombre): #Fait nombre tests et affiche les résultats.
liste=[random.randint(a,b) for i in range(taille)]
print("Test:",i+1)
print(liste)
print(principale(liste))
print("")
#test(0,10,100)
"""Partie 2: Tri par insertion
10)
ALGORITHME: TRIPARINSERTION:
DONNES: L :
LT <- []
POUR i DE 0 JUSQU A LA LONGUEUR DE LA LONGUEUR DE L FAIRE
AJOUTER A LT LA VALEUR L[i]
k <- i
cle <- LT[-1]
TANT QUE cle<LT[k-1] and k>0 FAIRE
LT[k] <- LT[k-1]
k <- k-1
FIN TANT QUE
LT[k] <- cle
FIN POUR
AFFICHER LT
11)
"""
def TriParInsertion(L):
"""Tri une liste par insertion."""
LT=[]
#Recupere les éléments de L et les ajoute dans LT de façon a ce que LT soit triée
for i in range(len(L)):
#Ajoute la valeur de L considérée et stocke la valeur de la clé
LT.append(L[i])
k=i
cle=LT[-1]
#Décale la valeur de la clé dans LT tant que la clé est supérieur a ses éléments en partant de la fin
while cle<LT[k-1] and k>0:
LT[k]=LT[k-1] #Réaffecte la valeur de l'élément k a la valeur de l'élément k-1.
k-=1
#Une fois que l'on trouve que la clé est inférieure à un élément ou que l'on a considéré tous les éléments de LT
LT[k]=cle
#Renvoie la liste triée
return LT
"""
13) Justesse du tri par sélection
Algorithme: Reperer
Pas de boucle
Algorithme: Echanger
Pas de boucle
Algorithme: TriParSelection
Invariant de boucle: ...
Algorithme: Test
Invariant de boucle: ...
14) Justesse du tri par insertion
Algorithme: Tri par insertion
Invariant de boucle: ...
15)
"""
def TriParInsertionEtComplexite(L):
complexite=0
LT=[]
complexite+=1
for i in range(len(L)):
LT.append(L[i])
k=i
cle=LT[-1]
complexite+=4
while cle<LT[k-1] and k>0:
LT[k]=LT[k-1]
k-=1
complexite+=4
complexite+=1
LT[k]=cle
complexite+=1
complexite+=1
return [LT,complexite]
#16)
L=[random.randint(0,10) for e in range(100)]
Trie,complexite=TriParInsertionEtComplexite(L)
print("Liste triee:",Trie)
print("Complexite:",complexite)
-164
View File
@@ -1,164 +0,0 @@
import random
#1
A= [[1,2,-1],
[-2,0,3],
[4,1,-1]]
print("Matrice:",A)
#2
#print(A[1])
#3
#print(A[1][2])
#4
#print(A[:][1])
#5a
def MatNulle(n,p):
"""Cree la matrice nulle de taille np."""
return [[0 for j in range(p)] for i in range(n)]
#5b
print("Matrice Nulle de taille (n,p):",MatNulle(3,4))
#5c
def MatNulleBis(n,p=None):
"""Cree la matrice nulle de taille np."""
if not p: p=n
return [[0 for j in range(p)] for i in range(n)]
#5d
print("Matrice nulle carre:",MatNulleBis(5))
#5e
def MAlea(k,n,p=None):
"""Cree la matrice comporant n lignes, p colonnes et dont les coefficients sont des entiers aleatoires de [-k,k]."""
if not p: p=n
return [[random.randint(-k,k) for j in range(p)] for i in range(n)]
#6
def Pivot(M,j):
"""Renvoie l'index de la ligne i qui contient l'élément de la colonne M d'indice j qui a la plus grande valeur absolue."""
m=abs(M[j][j])
p=j
for i in range(j+1,len(M)):
t=M[i][j]
if abs(t)>m:
m=t
p=i
return p
print("pivot:",Pivot(A,0))
#7
def EchangerLigne(M,i,l):
"""Permet d'echanger la i-eme ligne et la l-eme ligne de la matrice M."""
M[i],M[l]=M[l],M[i]
EchangerLigne(A,0,1)
print(A)
#8
def CombLigne(M,i,l,r):
"""Permet de remplacer la ligne i de la matrice M par Li-r*Ll."""
M[i]=[M[i][j]-r*M[l][j] for j in range(len(M[i]))]
#CombLigne(A,1,0,A[Pivot(A,0)][0])
p=Pivot(A,0)
print(p)
EchangerLigne(A,0,p)
print(A)
CombLigne(A,1,0,A[1][0]/p)
print("Combine les lignes i et l:",A)
#9 Algorithme
"""Pivot Triangulaire Sup:
Donnees: M une matrice
l<-nombre de lignes de la matrice M
Pour j de 0 a l-1 FAIRE:
p<-Pivot de la matrice m a partir de la colonne 0
Echanger les lignes j et p de la matrice M
Pour i de j+1 a l-1 FAIRE:
Realise Li <- Li-r*Lj pour la matrice M
"""
#9
def PivotTriangulaireSup(M):
"""Permet de triangulariser la matrice."""
l=len(M)
for j in range(l):
p=Pivot(M,j)
EchangerLigne(M,j,p)
if p!=0:
for i in range(j+1,l):
CombLigne(M,i,j,M[i][j]/M[j][j])
#10
def Afficher(B,precision=3):
for i in range(len(B)):
text=""
for j in range(len(B[i])):
text+=str(float(B[i][j]))[:precision]
if j<len(B[i])-1:
text+="|"
print(text)
#11
B=MAlea(5,5)
PivotTriangulaireSup(B)
print("Triangularise")
Afficher(B)
#print(B)
#12
def MaxIndice(l):
"""Renvoie la liste des indices des termes de la liste dans l'ordre croissant."""
M=[[l[i],i] for i in range(len(l))]
indices=[]
for i in range(len(l)):
p=M[i].index(min(M[i]))
indices.append(M[p][1])
del M[p]
return [indices[-j-1] for j in range(len(indices))]
a=[random.randint(0,100) for i in range(10)]
print(a)
print(MaxIndice(a))
#13
def TriTabCL(M,i):
"""Permet de trie un tableau selon l'ordre croissant d'une ligne."""
indices=MaxIndice(M[i])
n,p=len(M),len(M[0])
nM=MatNulle(n,p)
for i in range(n):
for j in range(p):
nM[i][j]=M[i][indices[j]]
print("\n13:")
C=MAlea(5,5)
Afficher(C)
print(C[2])
print(MaxIndice(C[2]))
TriTabCL(C,2)
Afficher(C)
@@ -1,138 +0,0 @@
#Représentation des flottants en machine.
import math
#I) Représentation des réels
#1) Quel mot code 25? et 25.0?
#25 : 11001
#en 64 bits: 0000000000000000000000000000000000000000000000000000000000011001
#25. : 0,0*48,11001,1,000000100
#en 64 bits: 010110000000000000000000000000000000000000000000000000000000100
#2)Quel mot code le plus grand réel positif normalisé? Quel réel représente-t-il? En donner un ordre de grandeur.
#0111111111111111111111111111111111111111111111111111111111111111
#Ordre de grandeur 2**1023
#3) Quel mot code le plus petit réel positif normalisé? Quel réel représente-t-il? En donner un ordre de grandeur.
#0,0*53,1,0*10
#0000000000000000000000000000000000000000000000000000010000000000
#Ordre de grandeur 2**-1023
#4) Quel mot code le plus petit réel positif dénormalisé? Quel réel représente-t-il? En donner un ordre de grandeur.
#0000000000000000000000000000000000000000000000000000000000000000
#Représente zéro
#II) Provoquer l'erreur
#5)Donner un calcul dont le résultat produit un dépassement de capacité par valeurs inférieurs.
#print(math.log(0.))
#print(-1./2**1024)
#6) Donner un calcul dont le résultat produit -inf
print(-2 * (2.**1023))
#7) Donner un calcul dont le résultat produit à tord 0.0
print(2.**(-2**11))
#8) Donner un calcul dont le résultat ne produit pas à tord 0.0
#print(1/10-math.log(math.exp(1/10)))
print(1-(2.**-1023+1))
#III) Comprendre les erreurs
#9) Quelle précision perd-on si on diviser un nombre à virgule flottante par deux puis qu'on le multiplie à nouveau par deux?
#On perd une précision de 2**1022
#10) On considère le script Python suivant:
def Algo10():
x=1.0
y=x+1.0
while y-x==1.0:
x=x*2.0
y=x+1.0
Algo10()
#a)Ecrire l'algorithme correspondant à ce programme. Quel problème y a t'il?
"""Algorithme:
Donnees: Rien
x <- 0
y <- x+1
TANT QUE y-x = 1:
x <- x*2
y <- x+1
"""
#Le problème est que cet algorithme est infini.
#b)Recopier ce programme dans un interpréterur et l'exécuter. Que constate-t-on? Quelle en est la raison?
#On constate que cet algorithme se fini.
#c) Modifier ce programme afin d'introduire un compteur qui détermine le nombre d'itérations effectuées.
def Algo10Iteration():
x=1.0
y=x+1.0
i=0
while y-x==1.0:
i+=1
x=x*2.0
y=x+1.0
print(x)
print(i)
Algo10Iteration()
# On compte 53 itérations
#d) Interpréter précisément la différence de comportement entre l'algorithme et le programme
#A la 53e itération l'erreur a été dépassée.
#e) Que se passerait-il si on initialisait x à 1 et y a x+1
#Théoriquement: Le calcul continuerait jusqu'à atteindre le dépassement de capacité mémoire de l'ordinateur
#11) Affecter 2.0 **1023 à la variable a puis interpréter ce qu'affiche python pour chacun des calculs suivants:
a=2.0**1023
#a) 2*a
print(2*a)
#Le dépassement de capacité en valeur négatif à été atteint donc le résultat est inf
#b) b=2*a puis b/2
b=2*a
print(b/2)
#Comme le dépassement de capacité en valeur négatif à été atteint la valeur de b
#correspond à l'infini et diviser l'infini par 2 donne toujours l'infini.
#c) 3*a-3*a
print(3*a-3*a)
#Comme le résultat de 3*a est considéré comme l'infini par python la différence des 2
#correspond à une forme indéterminée, d'où le résultat.
#d) 1/(2*a)
print(1/(2*a))
#Comme le résultat de 2*a est considéré comme l'infini par python, lors du passage
#à l'inverse python fait le quotient de 1 par l'infini ce qui lui donne 0.
#IV) Les nombres dénormalisés
#12) On note x1 le plus petit réel positif normalisé représentable et x2 le plus
#petit réel strictement supérieur à x1 normalisé représentable. Déterminer x1, x2
#et (x2-x1)/(x1-0)
#
x1=2.**-1023
print(x1)
x2=2.**-1022
print(x2)
#(x2-x1)/(x1-0)=1
print((x2-x1)/(x1-0))
#13)
#y1=2**-1074
y1=2.**-1074
print(y1)
#y2=2**-1073
y2=2.**-1073
print(y2)
print((y2-y1)/(x2-x1))
#Ce résultat devrait valoir 2**-52 mais vaut 2**-51 à cause de l'erreur d'approximation lors de la division
Binary file not shown.
-260
View File
@@ -1,260 +0,0 @@
import inspect
def test(arg1,arg2):
a = arg1 + arg2
return a
#do something with args
keywords=["assert","break","class","continue","def","del","elif","else","except","finally","for",
"from","global","if","import","in","pass","print","raise","return","try","while","yield"]
conversion1 = {"assert":"ASSERT",
"break":"SORTIR DE LA BOUCLE",
"class":"CLASSE",
"continue":"CONTINER",
"def":"DONNEES",
"del":"SUPPRIMER",
"elif":["SINON SI","FAIRE"],
"else":["SINON","FAIRE"],
"except":"EXCEPTE",
"finally":"FINALLEMENT",
"for":["POUR","FAIRE"],
"from":"DEPUIS",
"global":"GLOBAL",
"if":"SI",
"import":"IMPORTER",
"in":"DANS",
"pass":"PASSER",
"print":"AFFICHER",
"raise":"RELEVER",
"return":"AFFICHER",
"try":"ESSAYER",
"while":["TANT QUE","FAIRE"],
"yield":"PASSER AU TOUR SUIVANT",
"==":"=",
"=":"<-"}
def algorithm(name):
lines = inspect.getsource(name)
print(lines)
output = []
lines = lines.split("\n")
lines=removeUselessIndent(lines)
lines=Converter(lines)
for line in lines:
output.append(Converter(line)())
#print("output: ",output)
return "\n".join(output)
class Converter:
def __init__(self,name):
self.name=name
self.code=inspect.getsource(name)
print(self.code)
self.lines=self.code.split("\n")
self.indent_historic=[]
self.indent=0
self.cleanCode()
self.conversion= {"assert": [[None,"assert",None], [None,"ASSERT",None]],
"break": [[None,"break"], [None,"SORTIR DE LA BOUCLE"]],
"class": [["class",None], ["CLASS",None]],
"continue": [[None,"continue",None], [None,"CONTINUER",None]],
"def": [["def",None,"(",None,"):"], [None,":\nDONNES: ",None," :"]],
"del": [[None,"del",None], [None,"SUPPRIMER",None]],
"elif": [[None,"elif",None,":"], [None,"SINON SI",None," FAIRE"]],
"else": [[None,"else:",None], [None,"SINON",None," FAIRE"]],
"except": [[None,"except:",None], [None,"EXCEPTE",None]],
"finally": [[None,"finally:",None], [None,"FINALLEMENT",None]],
"for": [["for",None," in ",None,":"], ["POUR",None," DANS ",None," FAIRE"]],
"from": [["from",None,"import",None], ["DEPUIS",None,"IMPORTER",None]],
"global": [["global",None], ["GLOBAL",None]],
"if": [[None,"if",None], [None,"SI",None]],
"import": [[None,"import",None], [None,"IMPORTER",None]],
" in ": [[None," in ",None], [None, "DANS ",None]],
" is ": [[None," is ",None], [None," EST ",None]],
"lambda": [[None,"lambda",None,":",None], [None,":\nDONNEES: ",None," :\nRENVOIE",None]],
"pass": [[None,"pass"], [None,"PASSER",None]],
"print": [[None,"print",None,"(",None,")"], [None,"AFFICHER: ",None,None]],
"raise": [[None,"raise",None], [None,"RELEVER",None]],
"return": [[None,"return",None], [None,"AFFICHER",None]],
"try": [[None,"try:",None], [None,"ESSAYER",None]],
"while": [["while ",None,":"], ["TANT QUE ",None," FAIRE"]],
"yield": [[None,"yield"], [None,"PASSER AU TOUR SUIVANT"]],
"True": [[None,"True",None], [None,"VRAI",None]],
"False": [[None,"False",None], [None,"FAUX",None]],
"==": [[None,"==",None], [None,"=",None]],
"!=": [[None,"!=",None], [None,"≠",None]],
"=": [[None,"=",None], [None," <- ",None]],
"append": [[None,".append(",None,")"], ["AJOUTER A ",None," LA VALEUR ",None]],
"not": [[None,"not",None], [None,"NON",None]]}
def cleanCode(self):
self.cleanIndents()
def cleanIndents(self):
self.line=self.lines[0]
count=self.countIndent(self.line)
for i in range(len(self.lines)):
self.lines[i]=self.lines[i][4*count:]
def trackIndent(self,i):
print(i)
indent=self.countIndent(self.lines[i])
if indent>len(self.indent_historic):
self.addElementIndentHistoric(i)
if indent<len(self.indent_historic):
self.delElementIndentHistoric(i)
print("i:",i)
print("self.lines[i]:",self.lines[i])
print("indent:",indent)
print("historic:",self.indent_historic)
print("")
self.indent=indent
self.removeIndent(i)
#self.indent_historic.append()
def addElementIndentHistoric(self,i):
l={ " while ":" TANT QUE ",
" for ": " POUR ",
" if ": " SI "}
for e in l:
if e in self.lines[i]:
self.indent_historic.append(l[e])
print(self.lines[i])
print(e)
print(e in self.lines[i])
def delElementIndentHistoric(self,i):
print(len(self.lines))
print(i+1)
self.lines[i]+="\n"+" "*4*(self.countIndent(self.lines[i+1])+1)+"FIN "+self.indent_historic[-1]
del self.indent_historic[-1]
def countIndent(self,line):
i=0
for i in range(len(line)):
if line[i]!=" ":
break
return int(i/4)
def removeIndent(self,i):
count=self.countIndent(self.lines[i])
self.line=self.line[count*4:]
def removeCommentaries(self):
self.commentaries=""
if "#" in self.line:
i=self.next(self.line,"#")
self.commentaries=self.line[i:]
self.line=self.line[:i]
if "\"\"\"" in self.line:
i=self.next(self.line,"\"\"\"")
self.commentaries=self.line[i:]
self.line=self.line[:i]
def convert(self):
breaking=False
for key in self.conversion:
if key=="==":
breaking=True
if key in self.line:
self.apply(key)
if breaking:
break
def apply(self,key):
#print("key:",key)
l=self.missing(self.conversion[key][0])
#print("l:",l)
filled=self.fill(self.conversion[key][1],l)
#print("filled:",filled)
self.line="".join(filled)
#print(self.line)
def missing(self,l):
"""
l= ["def ",None,"(",None,"):"]
self.line= "def algorithm(name):"
l1=["def","(","):"]
"""
line=[]
if l[0]==None:
i=self.next(self.line,l[1])
line.append(self.line[:i])
for i in range(1,len(l)-1):
#print("missing loop:",l[i-1],l[i],l[i+1])
if l[i]==None:
a=self.between(self.line,l[i-1],l[i+1])
line.append(a)
#print("a",a)
if l[-1]==None:
i=self.next(self.line,l[-2])+len(l[-2])
line.append(self.line[i:])
return line
def removeNone(self,l):
l1=[]
for word in l:
if word!=None:
l1.append(word)
return l1
def between(self,text,word1,word2):
i1=self.next(text,word1)+len(word1)
i2=i1+self.next(text[i1:],word2)
return text[i1:i2]
def cut(self,text,word):
for i in range(len(text)-len(word)+1):
if text[i:i+len(word)]==word:
break
return [text[:i],word,text[i+len(word):]]
def next(self,text,word):
for i in range(len(text)-len(word)+1):
if text[i:i+len(word)]==word:
break
return i
def fill(self,l1,l2):
line=[]
for e1 in l1:
if e1==None:
line.append(l2[0])
del l2[0]
else:
line.append(e1)
return line
def assemble(self):
pass
def __call__(self):
for i in range(len(self.lines)):
if i<len(self.lines)-1:
self.trackIndent(i)
self.indent=self.countIndent(self.lines[i])
self.line=self.lines[i]
self.removeCommentaries()
self.convert()
self.lines[i]= " "*4*self.indent+self.line+" "+self.commentaries
self.cleanCode()
l1,l2=self.lines[0].split("\n")
l1="ALGORITHME: "+l1.upper() +"\n\n"
self.lines[0]=l1+l2
return "\n".join(self.lines)
if __name__=="__main__":
print(Converter(test)())
#c=Converter("def test(arg1,arg2):")
#print(c.between("def test(arg1,arg2):","(",")"))
@@ -1,126 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 16:23:27 2019
@author: hurc60248
"""
"""
I) Choisir le bon type de données
1) a) Chaîne de caractère
b) t uple
c) chaîne de caractére
d) chaîne de caractére
II)Prévoir ce que fait un script
2) Ce script affichera un message d'erreur car t=(1,2,3) est un t uple et t+4 est une opération sur les entiers
3) Ce script affichera "str"
4) Ce script affichera "isepparis"
5) Ce script affichera le crochet quand on demande a[0], et la virgule, quand on demande a[2]
III) Listes
6)a) "randint(self, a, b) method of random.Random instance
Return random integer in range [a, b], including both end points."
1er methode
b) import random
a=[]
for i in range(50):
a.append(random.randint(0,1))
2eme methode
a=[random.randint(0,1) for i in range(50)]
7)a) Données : liste, element
compteur <- 0
Pour e dans liste FAIRE
Si e=element FAIRE
compteur <- compteur + 1
Fin si
Fin pour
Afficher compteur
FIN
b) def compter(liste, élément):
compteur=0
for e in liste:
if e==element:
compteur+=1
return compteur
8)a) Données : liste, element
sortie <- []
pour i dans (0,longueur(liste)) faire
si liste(i)=element FAIRE
Ajouter a sortie l'indice i
FIN si
Afficher(sortie)
FIN
b)def Compter(liste, element):
sortie=[]
for i in range(len(liste)):
if liste[i]==element:
sortie.append(i)
return sortie
9)a)Données : liste
somme=0
Pour element dans liste FAIRE
somme <- element + somme
Fin pour
moyenne=somme/longueur(liste)
somme2=0
Pour element dans liste FAIRE
somme2 <- somme2 + (element-moyenne)²
variance=somme2/longueur(liste)
Afficher moyenne, variance
FIN
b)def stats(liste):
moyenne=sum(liste)/len(liste)
variance=sum([(x-moyenne)**2 for x in liste])/len(liste)
return (moyenne, variance)
10)a) Données : entnat1, entnat2
Si entnat1 divise entnat2 FAIRE
res <- vrai
Sinon FAIRE
res <-faux
fin si
Afficher resultat
b) Divise=lambda a,b:(b%a==0)
11)a) Données : entier
liste=[]
Pour element dans liste qui prend toutes les valeurs entre 1 et entier Faire
Si element divise entier Faire
Ajouter element dans liste
fin si
fin pour
Afficher liste
b) ListeDiv=lambda a:[e for e in range(1,a+1) if Divise(e,a)]
12)a) Données : liste1, liste2
commun=[]
pour element dans liste1 faire
Si element dans liste2 faire
Ajouter element a commun
fin si
fin pour
Afficher commun
b) ComListe=lambda a,b:list(set([e for e in a if e in b]))
13)a)
PGCDN=lambda a,b:max(ComListe(ListDiv(a),ListDiv(b)))
"""
-308
View File
@@ -1,308 +0,0 @@
import inspect
def test(arg1,arg2):
a = arg1 + arg2
return a
#do something with args
keywords=["assert","break","class","continue","def","del","elif","else","except","finally","for",
"from","global","if","import","in","pass","print","raise","return","try","while","yield"]
conversion1 = {"assert":"ASSERT",
"break":"SORTIR DE LA BOUCLE",
"class":"CLASSE",
"continue":"CONTINER",
"def":"DONNEES",
"del":"SUPPRIMER",
"elif":["SINON SI","FAIRE"],
"else":["SINON","FAIRE"],
"except":"EXCEPTE",
"finally":"FINALLEMENT",
"for":["POUR","FAIRE"],
"from":"DEPUIS",
"global":"GLOBAL",
"if":"SI",
"import":"IMPORTER",
"in":"DANS",
"pass":"PASSER",
"print":"AFFICHER",
"raise":"RELEVER",
"return":"AFFICHER",
"try":"ESSAYER",
"while":["TANT QUE","FAIRE"],
"yield":"PASSER AU TOUR SUIVANT",
"==":"=",
"=":"<-"}
def algorithm(name):
lines = inspect.getsource(name)
print(lines)
output = []
lines = lines.split("\n")
lines=removeUselessIndent(lines)
lines=Converter(lines)
for line in lines:
output.append(Converter(line)())
#print("output: ",output)
return "\n".join(output)
class Converter:
def __init__(self,name):
self.name=name
self.code=inspect.getsource(name)
print(self.code)
self.lines=self.code.split("\n")
self.indent_historic=[]
self.indent=0
self.cleanCode()
self.conversion= {"assert": [[None,"assert",None], [None,"ASSERT",None]],
"break": [[None,"break"], [None,"SORTIR DE LA BOUCLE"]],
"class": [["class",None], ["CLASS",None]],
"continue": [[None,"continue",None], [None,"CONTINUER",None]],
"def": [["def",None,"(",None,"):"], [None,":\nDONNES: ",None," :"]],
"del": [[None,"del",None], [None,"SUPPRIMER",None]],
"elif": [[None,"elif",None,":"], [None,"SINON SI",None," FAIRE"]],
"else": [[None,"else:",None], [None,"SINON",None," FAIRE"]],
"except": [[None,"except:",None], [None,"EXCEPTE",None]],
"finally": [[None,"finally:",None], [None,"FINALLEMENT",None]],
"for": [["for",None," in ",None,":"], ["POUR",None," DANS ",None," FAIRE"]],
"from": [["from",None,"import",None], ["DEPUIS",None,"IMPORTER",None]],
"global": [["global",None], ["GLOBAL",None]],
"if": [[None,"if",None], [None,"SI",None]],
"import": [[None,"import",None], [None,"IMPORTER",None]],
" in ": [[None," in ",None], [None, "DANS ",None]],
" is ": [[None," is ",None], [None," EST ",None]],
"lambda": [[None,"lambda",None,":",None], [None,":\nDONNEES: ",None," :\nRENVOIE",None]],
"pass": [[None,"pass"], [None,"PASSER",None]],
"print": [[None,"print",None,"(",None,")"], [None,"AFFICHER: ",None,None]],
"raise": [[None,"raise",None], [None,"RELEVER",None]],
"return": [[None,"return",None], [None,"AFFICHER",None]],
"try": [[None,"try:",None], [None,"ESSAYER",None]],
"while": [["while ",None,":"], ["TANT QUE ",None," FAIRE"]],
"yield": [[None,"yield"], [None,"PASSER AU TOUR SUIVANT"]],
"True": [[None,"True",None], [None,"VRAI",None]],
"False": [[None,"False",None], [None,"FAUX",None]],
"==": [[None,"==",None], [None,"=",None]],
"!=": [[None,"!=",None], [None,"≠",None]],
"=": [[None,"=",None], [None," <- ",None]],
"append": [[None,".append(",None,")"], ["AJOUTER A ",None," LA VALEUR ",None]],
"not": [[None,"not",None], [None,"NON",None]]}
def cleanCode(self):
self.cleanIndents()
def cleanIndents(self):
self.line=self.lines[0]
count=self.countIndent(self.line)
for i in range(len(self.lines)):
self.lines[i]=self.lines[i][4*count:]
def trackIndent(self,i):
print(i)
indent=self.countIndent(self.lines[i])
if indent>len(self.indent_historic):
self.addElementIndentHistoric(i)
if indent<len(self.indent_historic):
self.delElementIndentHistoric(i)
print("i:",i)
print("self.lines[i]:",self.lines[i])
print("indent:",indent)
print("historic:",self.indent_historic)
print("")
self.indent=indent
self.removeIndent(i)
#self.indent_historic.append()
def addElementIndentHistoric(self,i):
l={ " while ":" TANT QUE ",
" for ": " POUR ",
" if ": " SI "}
for e in l:
if e in self.lines[i]:
self.indent_historic.append(l[e])
print(self.lines[i])
print(e)
print(e in self.lines[i])
def delElementIndentHistoric(self,i):
print(len(self.lines))
print(i+1)
self.lines[i]+="\n"+" "*4*(self.countIndent(self.lines[i+1])+1)+"FIN "+self.indent_historic[-1]
del self.indent_historic[-1]
def countIndent(self,line):
i=0
for i in range(len(line)):
if line[i]!=" ":
break
return int(i/4)
def removeIndent(self,i):
count=self.countIndent(self.lines[i])
self.line=self.line[count*4:]
def removeCommentaries(self):
self.commentaries=""
if "#" in self.line:
i=self.next(self.line,"#")
self.commentaries=self.line[i:]
self.line=self.line[:i]
if "\"\"\"" in self.line:
i=self.next(self.line,"\"\"\"")
self.commentaries=self.line[i:]
self.line=self.line[:i]
def convert(self):
breaking=False
for key in self.conversion:
if key=="==":
breaking=True
if key in self.line:
self.apply(key)
if breaking:
break
def apply(self,key):
#print("key:",key)
l=self.missing(self.conversion[key][0])
#print("l:",l)
filled=self.fill(self.conversion[key][1],l)
#print("filled:",filled)
self.line="".join(filled)
#print(self.line)
def missing(self,l):
"""
l= ["def ",None,"(",None,"):"]
self.line= "def algorithm(name):"
l1=["def","(","):"]
"""
line=[]
if l[0]==None:
i=self.next(self.line,l[1])
line.append(self.line[:i])
for i in range(1,len(l)-1):
#print("missing loop:",l[i-1],l[i],l[i+1])
if l[i]==None:
a=self.between(self.line,l[i-1],l[i+1])
line.append(a)
#print("a",a)
if l[-1]==None:
i=self.next(self.line,l[-2])+len(l[-2])
line.append(self.line[i:])
return line
def removeNone(self,l):
l1=[]
for word in l:
if word!=None:
l1.append(word)
return l1
def between(self,text,word1,word2):
i1=self.next(text,word1)+len(word1)
i2=i1+self.next(text[i1:],word2)
return text[i1:i2]
def cut(self,text,word):
for i in range(len(text)-len(word)+1):
if text[i:i+len(word)]==word:
break
return [text[:i],word,text[i+len(word):]]
def next(self,text,word):
for i in range(len(text)-len(word)+1):
if text[i:i+len(word)]==word:
break
return i
def fill(self,l1,l2):
line=[]
for e1 in l1:
if e1==None:
line.append(l2[0])
del l2[0]
else:
line.append(e1)
return line
def assemble(self):
pass
def __call__(self):
for i in range(len(self.lines)):
if i<len(self.lines)-1:
self.trackIndent(i)
self.indent=self.countIndent(self.lines[i])
self.line=self.lines[i]
self.removeCommentaries()
self.convert()
self.lines[i]= " "*4*self.indent+self.line+" "+self.commentaries
self.cleanCode()
l1,l2=self.lines[0].split("\n")
l1="ALGORITHME: "+l1.upper() +"\n\n"
self.lines[0]=l1+l2
return "\n".join(self.lines)
if __name__=="__main__":
print(Converter(test)())
#c=Converter("def test(arg1,arg2):")
#print(c.between("def test(arg1,arg2):","(",")"))
from random import randint
#6b
liste1=[]
for i in range(50):
liste1.append(randint(0,10))
liste2=[randint(0,10) for i in range(50)]
#7b
def Compter1(liste,valeur):
compteur=0
for element in liste:
if element==valeur:
compteur+=1
return compteur
Compter2=lambda liste,valeur:sum([element==valeur for element in liste])
#8b
def Positionner(liste,valeur):
positions=[]
for i in range(liste):
if liste[i]==valeur:
positions.append(i)
return positions
Positionner2=lambda liste,valeur:[n for n,element in enumerate(liste) if element==valeur]
def puissancede2(number):
if number<2:
return 0
else:
a=1
while a*2<number:
a*=2
return a
#print(Converter(Positionner)())
a=[1,2,3,5,1,3,5,4,4,2]
print(puissancede2(4))
-14
View File
@@ -1,14 +0,0 @@
import math
def puissancede2(number):
a=1
while a*2<number:
a*=2
return a
print(puissancede2(513))
puissance=lambda x:2**int(math.log(x)/math.log(2))
print(puissance(513))
+4
View File
@@ -0,0 +1,4 @@
level=0
while not (level in [1,2,3]):
level=int(input("Sélectionner votre level:"))
+20
View File
@@ -0,0 +1,20 @@
"""
x| |o
| |x
| |x
"""
class Morpion:
def __init__(self):
self.grille=[[0,0,0],
[0,0,0],
[0,0,0]]
self.symboles=[" ","x","o"]
def aff(self):
for y in range(3):
a="|".join(map(lambda x:self.symboles[x],self.grille[y]))
print(a)
m.aff()
+2 -3
View File
@@ -9,8 +9,6 @@ import matplotlib.dates as mdates
import sys
print(sys.version)
"""
x=[1,2,3]
y=[5,7,4]
@@ -92,7 +90,8 @@ plt.plot(x,y,label="loaded from file")
x,y=np.loadtxt("text.txt",delimiter=",",unpack=True)
plt.plot(x,y,label="loaded from file")
"""
#
def bytespdate2num(fmt,encoding="utf-8"):
strconverter=mdates.strpdate2num(fmt)
+2
View File
@@ -0,0 +1,2 @@
import sys
from PyQt4 import QtGui
Binary file not shown.
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
class Employee:
"""A sample Employee class"""
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
@property
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
def __repr__(self):
return "Employee('{}','{}','{}')".format(self.first,self.last,self.pay)
#e=Employee("machin","truc",500)
#r=print(e.fullname)
+53
View File
@@ -0,0 +1,53 @@
import sqlite3
from employee import Employee
#conn = sqlite3.connect('employee.db')
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("""CREATE TABLE employees (
first text,
last text,
pay integer
)""")
def insert_emp(emp):
with conn:
c.execute(" INSERT INTO employees VALUES (?, ?, ?)", (emp.first,emp.last,emp.pay))
def get_emps_by_name(lastname):
c.execute("SELECT * FROM employees WHERE last=?", (lastname,))
return c.fetchall()
def update_pay(emp, pay):
with conn:
c.execute("""UPDATE employees SET pay = :pay
WHERE first = :first AND last = :last""",
{'first': emp.first, 'last': emp.last, 'pay': pay})
def remove_emp(emp):
with conn:
c.execute("DELETE from employees WHERE first=:first AND last=:last",
{'first':emp.first, 'last':emp.last})
emp_1 = Employee('John', 'Doe', 8000)
emp_2 = Employee('Jane', 'Doe', 9000)
insert_emp(emp_1)
insert_emp(emp_2)
emps=get_emps_by_name('Doe')
print(emps)
update_pay(emp_1,500)
print(emp_1)
conn.commit()
conn.close()
+30 -24
View File
@@ -1,43 +1,46 @@
import socket
import select
HEADER_LENGTH=10
IP="172.16.0.27."
#IP="86.242.99.166"
#IP='192.168.1.11'
IP=socket.gethostname()
IP=''
HEADER_LENGTH = 10
IP = "172.16.0.27."
# IP="86.242.99.166"
# IP='192.168.1.11'
IP = socket.gethostname()
IP = ''
print(IP)
PORT=1236
PORT = 1236
server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((IP,PORT))
server_socket.bind((IP, PORT))
server_socket.listen()
sockets_list=[server_socket]
sockets_list = [server_socket]
clients = {}
clients={}
def receive_message(client_socket):
try:
message_header=client_socket.recv(HEADER_LENGTH)
message_header = client_socket.recv(HEADER_LENGTH)
if not len(message_header):
return False
else:
message_length=int(message_header.decode("utf-8").strip())
return {"header":message_header,"data":client_socket.recv(message_length)}
message_length = int(message_header.decode("utf-8").strip())
return {"header": message_header, "data": client_socket.recv(message_length)}
except:
return False
while True:
read_sockets,_,exception_sockets=select.select(sockets_list,[],sockets_list)
read_sockets, _, exception_sockets = select.select(
sockets_list, [], sockets_list)
for notified_socket in read_sockets:
if notified_socket==server_socket:
client_socket,client_address=server_socket
if notified_socket == server_socket:
client_socket, client_address = server_socket
user = receive_message(client_socket)
if user is False:
@@ -45,14 +48,15 @@ while True:
sockets_list.append(client_socket)
clients[client_socket]=user
clients[client_socket] = user
print(f"Accepted new connection from {client_address[0]}:{client_address[1]} username: {user['data'].decode('utf-8')}")
print(
f"Accepted new connection from {client_address[0]}:{client_address[1]} username: {user['data'].decode('utf-8')}")
else:
message=receive_message(notified_socket)
message = receive_message(notified_socket)
if message is False:
m=clients[notified_socket]['data'].decode('utf-8')
m = clients[notified_socket]['data'].decode('utf-8')
print("Closed connection from {}".format(m))
sockets_list.remove(notified_socket)
del clients[notified_sockets]
@@ -60,10 +64,12 @@ while True:
user = clients[notified_socket]
print(f"Received message from {user['data'].decode('utf-8')}: {message['data'].decode('utf-8')}")
print(
f"Received message from {user['data'].decode('utf-8')}: {message['data'].decode('utf-8')}")
for client_socket in clients:
if client_socket != notified_socket:
client_socket.send(user['header']+user['data']+message['header']+message['data'])
client_socket.send(
user['header'] + user['data'] + message['header'] + message['data'])
for notified_socket in exception_sockets:
sockets_list.remove(notified_socket)
+23
View File
@@ -0,0 +1,23 @@
import socket
import time
t0=time.time()
duration=5
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = '192.168.0.1'
port = 1234
s.connect((ip,port))
while time.time()-t0<duration:
full_msg = ''
while time.time()-t0<duration:
print(time.time()-t0)
msg = s.recv(8)
if len(msg) <= 0:
break
full_msg += msg.decode("utf-8")
if len(full_msg) > 0:
print(full_msg)
+21
View File
@@ -0,0 +1,21 @@
import socket
hote = "localhost"
port = 12800
connexion_avec_serveur = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connexion_avec_serveur.connect((hote, port))
print("Connexion établie avec le serveur sur le port {}".format(port))
msg_a_envoyer = b""
while msg_a_envoyer != b"fin":
msg_a_envoyer = input("> ")
# Peut planter si vous tapez des caractères spéciaux
msg_a_envoyer = msg_a_envoyer.encode()
# On envoie le message
connexion_avec_serveur.send(msg_a_envoyer)
msg_recu = connexion_avec_serveur.recv(1024)
print(msg_recu.decode()) # Là encore, peut planter s'il y a des accents
print("Fermeture de la connexion")
connexion_avec_serveur.close()
+22
View File
@@ -0,0 +1,22 @@
import socket
import time
t0=time.time()
duration=5
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = ''
port = 1234
s.bind((ip, port))
s.listen(5)
while time.time()-t0<duration:
# now our endpoint knows about the OTHER endpoint.
clientsocket, address = s.accept()
print(f"Connection from {address} has been established.")
clientsocket.send(bytes("Hey there!!!", "utf-8"))
clientsocket.close()
print('server ended')
+23
View File
@@ -0,0 +1,23 @@
import socket
hote = ''
port = 12800
connexion_principale = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connexion_principale.bind((hote, port))
connexion_principale.listen(5)
print("Le serveur écoute à présent sur le port {}".format(port))
connexion_avec_client, infos_connexion = connexion_principale.accept()
msg_recu = b""
while msg_recu != b"fin":
msg_recu = connexion_avec_client.recv(1024)
# L'instruction ci-dessous peut lever une exception si le message
# Réceptionné comporte des accents
print(msg_recu.decode())
connexion_avec_client.send(b"5 / 5")
print("Fermeture de la connexion")
connexion_avec_client.close()
connexion_principale.close()
+8
View File
@@ -0,0 +1,8 @@
import os
from subprocess import call
os.system("echo slt")
+17
View File
@@ -0,0 +1,17 @@
import subprocess
import sys
command = "open -a Terminal -n\n echo test"
ssh = subprocess.Popen(["ssh", "%s" % host, command],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print("ERROR: %s" % error )
else:
print( result )
-133
View File
@@ -1,133 +0,0 @@
#Hugues de Rubin de Cervens
#Marc Partensky
#Louise De Servigny
from scipy.optimize import bisect,newton
import math
f=lambda x:x**2-2
#1)a) On définit f : x-->x^2-2. f s'annule en sqrt(2) et -sqrt(2). Or leurs valeurs décimales ne sont pas fini.
"""b)DONNEES (a,b,e)
x<-(a+b)/2
TANT QUE abs(x^2-2)>e FAIRE:
SI f(a)*f(b)>0: FAIRE:
a<-x
SINON FAIRE:
b<-x
x<-(a+b)/2
FIN TANT QUE
AFFICHER x
"""
#c)
def ZeroD(f,a,b,e):
x=(a+b)/2
while abs(f(x))>e:
if f(a)*f(x)>0:
a=x
else:
b=x
x=(a+b)/2
return x
#d)
print("ZeroD:",ZeroD(f,1,2,e=10**(-12)))
print(math.sqrt(2))
#2)a))
print(bisect(f,1,2))
#b)
print("ZeroD:",ZeroD(f,1,2,e=10**(-12)))
#II) a)
#b)Données(f,a,b,n)
"""
t : x-->(-f(a)*(b-a))/(f(b)-f(a))+a
c=t(a,b)
Pour i parcourant n
c=t(a,b)
Si f(a)f(c)>0
a=c
Sinon
b=c
Afficher c
"""
#c)
def ZeroL(f,a,b,n):
t=lambda a,b:-f(a)*(b-a)/(f(b)-f(a))+a
c=t(a,b)
for i in range(n):
c=t(a,b)
if f(a)*f(c)>0:
a=c
else:
b=c
return c
#d)
print("ZeroL:",ZeroL(f,1,2,10))
print(math.sqrt(2))
#e)
def ZeroDC(f,a,b,e):
x=(a+b)/2
t=0
while abs(f(x))>e:
t+=1
if f(a)*f(x)>0:
a=x
else:
b=x
x=(a+b)/2
return (x,t)
#f)
print("ZeroDC:",ZeroDC(f,1,2,10**(-12)))
#4)
print(newton(f,1,maxiter=20))
#III)
#a) Figure...
#b) Algorithme
"""Données(f,a,b,n)
fp : a-->(f(a+h)-f(a))/h
e=10^-10
c=b
Pour i parcourant n
c=c-f(c)/fp(c,e)
Si f(a)f(c)>0
a=c
SINON
b=c
Afficher c
"""
#c)
def ZeroN(f,a,b,n):
fp=lambda a,h:(f(a+h)-f(a))/h
e=10**(-10)
c=b
for i in range(n):
c=c-f(c)/fp(c,e)
if f(a)*f(c)>0:
a=c
else:
b=c
return c
#d)
print("ZeroN:",ZeroN(f,1,2,20))
print(math.sqrt(2))
#6)
#a)
print(newton(f,1,maxiter=20))
#b)
print("ZeroN:",ZeroN(f,1,2,20))
+355 -136
View File
@@ -6,8 +6,8 @@ Features:
4:COMPLETED: derive #renvoie un Polynomial
5:COMPLETED: division #renvoie couple de Polynomial
6:COMPLETED: pgcd #renvoie Polynomial
7: ppcm #renvoie Polynomial
8: taylor #renvoie str ou liste "je sais pas encore"
7:COMPLETED: ppcm #renvoie Polynomial
8:COMPLETED: taylor #renvoie Polynomial
9: factoriser #renvoie str ou liste de liste des coefficients "pareil"
10: racines reelles #renvoie liste des racines reelles
11: racines complexes #renvoie liste des racines complexes
@@ -16,57 +16,102 @@ Features:
"""
from copy import deepcopy
#import matplotlib.pyplot as plt #Old way to show the polynome on screen. Not very nice though...
# import matplotlib.pyplot as plt #Old way to show the polynomials on screen. Not very nice though...
from mygrapher.grapher import Grapher #Used to show the polynome on screen with the ability to move within it.
# from mygrapher.grapher import Grapher #Used to show the polynome on screen with the ability to move within it.
import random #Used only to generate random polynomes.
import random # Used only to generate random polynomials.
import functools
# Changing the type of the coefficients
#from decimal import Decimal
#from numpy import float128
# p=Polynomial.createFromInterpolation(x,y)
def prod(l): return functools.reduce(lambda a, b: a * b, l)
class Polynomial:
def __init__(self, coefficients):
def null():
"""Return the null polynomial."""
return Polynomial([0])
def sum(ps):
"""Sum polynomials between themselves."""
v = Polynomial([0]) # Addition neutral
for p in ps:
v += p
return v
def prod(ps):
"""Multiply polynomials between themselves."""
v = Polynomial([1]) # Multiplication neutral
for p in ps:
v *= p
return v
def createFromInterpolation(x, y):
"""Create a polynomial using the lagrangian interpolation."""
n = max(len(x), len(y))
p = Polynomial.sum([Polynomial([y[j]]) * Polynomial.prod([Polynomial([-x[i] / (
x[j] - x[i]), 1 / (x[j] - x[i])]) for i in range(n) if x[i] != x[j]]) for j in range(n)])
return Polynomial(p.coefficients)
def __init__(self, coefficients, definition=[-10**20, 10**20]):
"""Create a polynomial using its coefficients."""
self.coefficients = coefficients
self.definition=[-10**20,10**20]
def __repr__(self):
self.definition = definition
def make(self, f):
"""Transform all the coefficients into a decimal type."""
self.coefficients = [f(c) for c in self.coefficients]
self.definition = [f(d) for d in self.definition]
def __str__(self):
"""Return the usual representation of a polynomial."""
if self.coefficients==[]:
if self.coefficients == []:
return "0"
liste = []
if self.coefficients[0]!=0:
if self.coefficients[0] != 0:
liste.append(str(self.coefficients[0]))
for degre,coefficient in enumerate(self.coefficients[1:],1):
if coefficient!=0:
for degre, coefficient in enumerate(self.coefficients[1:], 1):
if coefficient != 0:
liste.append(str(coefficient) + "X^" + str(degre))
liste.reverse()
text = "+".join(liste)
text = text.replace("^1","").replace("+-","-").replace("1X","X")
text = text.replace("^1", "").replace("+-", "-").replace("1X", "X")
return text
def adapt(self,coefficients,size):
def adapt(coefficients, size):
"""Add zeros to the coefficients using coefficients and size."""
coefficients += [0]*(size-len(coefficients))
return coefficients
return coefficients + [0] * (size - len(coefficients))
def __eq__(self, other):
"""Determine if two polynomials are equals by checking if the coefficients
are the same."""
return self.coefficients == other.coefficients
def __add__(self, other):
"""Add 2 polynomials together by adding their coefficients."""
maxdegree = max(self.degree()+1,other.degree()+1)
cA = self.adapt(self.coefficients,maxdegree)
cB = self.adapt(other.coefficients,maxdegree)
newcoefficients = [a+b for (a,b) in zip(cA, cB)]
A=Polynomial(newcoefficients)
maxdegree = max(self.degree + 1, other.degree + 1)
cA = Polynomial.adapt(self.coefficients, maxdegree)
cB = Polynomial.adapt(other.coefficients, maxdegree)
coefficients = [a + b for (a, b) in zip(cA, cB)]
A = Polynomial(coefficients)
A.correct()
return A
def __sub__(self, other):
"""Substract 2 polynomials together by multiplying the second polynomial by -1 and adding it to the first using add method."""
return self+other*Polynomial([-1])
return self + other * Polynomial([-1])
def __mul__(self, other):
"""Multiply 2 polynomials together using the formula for the coefficients."""
degree = len(self.coefficients) + len(other.coefficients)
A = self.coefficients + [0]*(degree-len(self.coefficients)+1)
B = other.coefficients + [0]*(degree-len(other.coefficients)+1)
A = self.coefficients + [0] * (degree - len(self.coefficients) + 1)
B = other.coefficients + [0] * (degree - len(other.coefficients) + 1)
newcoefficients = []
for k in range(degree + 1):
coeff = 0
@@ -77,19 +122,23 @@ class Polynomial:
C.correct()
return C
def __pow__(self, n):
"""Does an ~exponentiation of the polynomial."""
return Polynomial.mul([self for i in range(n)])
def correct(self):
"""Correct the coefficients of the polynomial by deleting useless zeros at the end,"""
while len(self.coefficients)>1:
while len(self.coefficients) > 1:
if self.coefficients[-1] == 0:
del self.coefficients[-1]
else:
break
if self.coefficients==[0]:
self.coefficients=[]
if self.coefficients == [0]:
self.coefficients = []
"""and then replace float coefficients by int coefficients if possible."""
for i in range(len(self.coefficients)):
if self.coefficients[i]==int(self.coefficients[i]):
self.coefficients[i]=int(self.coefficients[i])
if self.coefficients[i] == int(self.coefficients[i]):
self.coefficients[i] = int(self.coefficients[i])
def __len__(self):
"""Return the number of coefficients.
@@ -97,78 +146,78 @@ class Polynomial:
the polynomial might have a degree of -inf and the len method must have positive values.
In such a case this method will raise an error.
It is why it is better to use the degree method in the general case."""
A=deepcopy(self)
A = deepcopy(self)
A.correct()
return len(A.coefficients)-1
return len(A.coefficients) - 1
def degree(self):
def getDegree(self):
"""Return the degree of a polynomial.
It will return -1 if the degree is -inf to be computer friendly."""
A=deepcopy(self)
A = deepcopy(self)
A.correct()
return len(A.coefficients)-1
return len(A.coefficients) - 1
def __getitem__(self,index):
def __getitem__(self, index):
"""Return a coefficient of the polynomial."""
return self.coefficients[index]
def __setitem__(self,index,value):
def __setitem__(self, index, value):
"""Change a coefficient of the polynomial."""
self.coefficients[index] = value
def __delitem__(self,index):
def __delitem__(self, index):
"""Delete a coefficient of the polynomial."""
del self.coefficients[index]
def derivate(self):
"""Derivate the polynomial."""
self.coefficients = [i*c for (i,c) in enumerate(self.coefficients)]
self.coefficients = [i * c for (i, c) in enumerate(self.coefficients)]
del self.coefficients[0]
def derivative(self):
"""Return the derivative polynomial."""
newcoefficients = [i*c for (i,c) in enumerate(self.coefficients)]
newcoefficients = [i * c for (i, c) in enumerate(self.coefficients)]
del newcoefficients[0]
return Polynomial(newcoefficients)
def unit(self):
"""Return the polynomial unit form."""
k=self.coefficients[-1]
newcoefficients=[]
k = self.coefficients[-1]
newcoefficients = []
for i in range(len(self.coefficients)):
newcoefficients.append(self.coefficients[i]/k)
A=Polynomial(newcoefficients)
newcoefficients.append(self.coefficients[i] / k)
A = Polynomial(newcoefficients)
A.correct()
return A
def unitarize(self):
"""Convert the polynomial into its unit form."""
self=self.unit()
self.coefficients = self.unit().coefficients
def __xor__(self,other):
def __xor__(self, other):
"""Return the HCF (PGCD en francais) of self and other by Euclide algorithm. Make use of "^" operator."""
R0 = deepcopy(self)
R1 = deepcopy(other)
R0.correct()
R1.correct()
listR=[R0,R1]
while listR[-1].degree()>0:
R,Q=listR[-2]/listR[-1]
listR = [R0, R1]
while listR[-1].degree > 0:
R, Q = listR[-2] / listR[-1]
listR.append(R)
return listR[-2]
#Resultat d'une enorme galere de 2h...
#Algorithme d'Euclide:
#a=b*q0+r0
#b=r*q1+r1
#r=r1*q2+r2
#r1=r2*q3+r3
#...
#ri=r(i-1)*q(i-1)+1+0
# Resultat d'une enorme galere de 2h...
# Algorithme d'Euclide:
# a=b*q0+r0
# b=r*q1+r1
# r=r1*q2+r2
# r1=r2*q3+r3
# ...
# ri=r(i-1)*q(i-1)+1+0
def __or__(self,other):
def __or__(self, other):
"""Return the LCM (PPCM en francais) using "i have absolutely no clue how to do this so figure it out!" Make use of "|" operator."""
#On sent la (tres) grosse fatigue apres minuit.
# On sent la (tres) grosse fatigue apres minuit.
return "Figure it out!"
def __truediv__(self, other):
@@ -178,113 +227,283 @@ class Polynomial:
R.correct()
B.correct()
Q = Polynomial([])
while R.degree()>=B.degree():
d = R.degree()-B.degree()+1
while R.degree >= B.degree:
d = R.degree - B.degree + 1
C = Polynomial([0 for i in range(d)])
C[-1] = R[-1]/B[-1]
R = R-B*C
Q = Q+C
return [R,Q]
C[-1] = R[-1] / B[-1]
R = R - B * C
Q = Q + C
return [R, Q]
#Ce que j'ai du faire pour trouver l'implementation...
#On a: A=BQ+R
#[3,2,4,5,1]/[1,4,1]
#[3,2,3,1,0]=[3,2,4,5,1]-[0,0,1]*[1,4,1] #[0,0,1,4,1]
#[3,1,-1,0]=[3,2,3,1]-[0,1]*[1,4,1] #[0,1,4,1]
#[4,5,0]=[3,1,-1]-[-1]*[1,4,1] #[-1,-4,-1]
#[4,5]
# Ce que j'ai du faire pour trouver l'implementation...
# On a: A=BQ+R
# [3,2,4,5,1]/[1,4,1]
# [3,2,3,1,0]=[3,2,4,5,1]-[0,0,1]*[1,4,1] #[0,0,1,4,1]
# [3,1,-1,0]=[3,2,3,1]-[0,1]*[1,4,1] #[0,1,4,1]
# [4,5,0]=[3,1,-1]-[-1]*[1,4,1] #[-1,-4,-1]
# [4,5]
#5=8*0+5 cas particulier de la division euclidienne
# 5=8*0+5 cas particulier de la division euclidienne
def __call__(self,x):
def isDivisible(self, other):
"""Determine if the polynomial is divisible by other."""
q, r = self / other
return r == Polynomial.zero
def __call__(self, x):
"""Evaluate the polynomial given an x value."""
sum=0
for n,c in enumerate(self.coefficients):
sum+=c*x**n
return sum
return sum([c * x**n for (n, c) in enumerate(self.coefficients)])
def getFactoredForm(self):
"""Return the list of the factors of the factored form of the polynomial."""
return
def allDerivatives(self):
"""Return the list of all derivatives of the polynome until the zero polynome."""
B=deepcopy(self)
derivatives=[deepcopy(self)]
while B.degree()>1:
B = deepcopy(self)
derivatives = [deepcopy(self)]
while B.degree > 1:
B.derivate()
derivatives.append(deepcopy(B))
return derivatives
def roots(self):
def getRootsByDichotomy(self, precision=1e-15):
"""Return the list of all the roots of the polynomial."""
"""Does that by finding where all the derivates cancel, to find new extrema and applying tvi."""
roots=[]
derivatives=self.allDerivatives()
print(derivatives)
roots = []
derivatives = self.allDerivatives()
derivatives.reverse()
old_extrema=[]
old_extrema = []
for derivative in derivatives:
new_extrema=[]
neglim=self.definition[0]
poslim=self.definition[1]
extrema=[neglim]+old_extrema+[poslim]
for i in range(len(extrema)-1):
if derivative(extrema[i])*derivative(extrema[i+1])<=0:
new_extrema.append(derivative.TVI(extrema[i],extrema[i+1]))
old_extrema=new_extrema[:]
new_extrema = []
neglim = self.definition[0]
poslim = self.definition[1]
extrema = [neglim] + old_extrema + [poslim]
for i in range(len(extrema) - 1):
if derivative(extrema[i]) * derivative(extrema[i + 1]) <= 0:
new_extrema.append(derivative.dichotomy(
extrema[i], extrema[i + 1], precision))
old_extrema = new_extrema[:]
return new_extrema
def TVI(self,xa,xb,precision=10e-10):
"""Return a float value x between a and b for which the polynomial canceled itself."""
"""Does that based on theoreme of intermediate value with dichotomy."""
if self(xa)*self(xb)>0:
raise Exception("The polynomial cannot cancel itself within this interval.")
a=min(xa,xb)
b=max(xa,xb)
x=(a+b)/2
while abs(self(x))>precision:
if self(x)*self(b)>0:
b=x
if self(x)*self(a)>0:
a=x
x=(a+b)/2
def dichotomy(self, xa, xb, precision=1e-15):
"""Return a float value x between a and b for which the polynomial canceled itself.
Does that based on theoreme of intermediate value with dichotomy."""
if self(xa) * self(xb) > 0:
raise Exception(
"The polynomial cannot cancel itself within this interval.")
a = min(xa, xb)
b = max(xa, xb)
x = (a + b) / 2
while abs(self(x)) > precision:
print(x, self(x), abs(self(x)), precision)
if self(x) * self(b) > 0:
b = x
if self(x) * self(a) > 0:
a = x
x = (a + b) / 2
return x
def getRoots(self, precision=1e-15):
"""
Return the roots of the polynomial by doing the best possible calculation
that combines precision and efficiency.
"""
degree = self.degree # There are less calculations by selecting the degree
if degree == 0:
if self.coefficients[0] == 0:
raise Exception("Every number is a root of p.")
else:
return []
elif self.degree == 1:
b, a = self.coefficients
return [-b / a] # a cannot be null
elif self.degree == 2:
c, b, a = self.coefficients
discriminant = b**2 - 4 * a * c
x1 = (-b - discriminant**(1 / 2)) / (2 * a) # a cannot be null
x2 = (-b + discriminant**(1 / 2)) / (2 * a) # a cannot be null
return [x1, x2]
else:
return self.getRootsByDichotomy(precision)
def _floordiv__(self,other):
"""Return a string of the decomposition in simple elements of the polynomial."""
pass
def getMultiplicity(self, root):
"""Return the multiplicity of a root."""
b = self
n = 0
while b.coefficients != [1]:
q, b = b / Polynomial([-root, 1])
n += 1
return n
def getRootsWithMultiplicity(self):
"""Return a list of couples of roots with their multiplicity associated.
Example: [(r1,m1),(r2,m2),...] """
return [(r, self.getMultiplicity(r)) for r in list(set(self.roots))]
def __floordiv__(self, other):
"""Return a rational function of numerator the polynomial, and the denominator the other."""
return RationalFunction(self, other)
def show(self):
"""Show the polynomial with grapher."""
Grapher([self])() #Instance Grapher only takes the list of the functions in parameter and can be called to display them.
Grapher([self])() # Instance Grapher only takes the list of the functions in parameter and can be called to display them.
def matplotlibShow(self,zone=[-5,5],precision=0.1):
def matplotlibShow(self, zone=[-5, 5], precision=0.1):
"""Show the polynomial with matplotlib using optional zone and precision."""
z,Z=zone
X=list([precision*x for x in range(int(z/precision),int(Z/precision))])
Y=list([self(x) for x in X])
plt.plot(X,Y,label="Polynomial")
z, Z = zone
X = list(
[precision * x for x in range(int(z / precision), int(Z / precision))])
Y = list([self(x) for x in X])
plt.plot(X, Y, label="Polynomial")
plt.show()
degree = property(getDegree)
roots = property(getRoots)
class FactoredPolynomial(Polynomial):
"""For factored of a polynomial."""
def __init__(self, roots_and_multiplicity):
"""Define the factored polynomial with its roots."""
self.roots = roots
def __str__(self):
"""Return a string representation of the factored polynomial."""
def getCoefficients(self):
"""Return the coefficients of the polynomial."""
class RationalFunction:
"""Wikipedia: In algebra, the partial fraction decomposition or partial
fraction expansion of a rational function (that is, a fraction such that the
numerator and the denominator are both polynomials) is an operation that
consists of expressing the fraction as a sum of a polynomial (possibly zero)
and one or several fractions with a simpler denominator"""
def __init__(self, p, q):
"""Define a rational function using two polynomials p: the numerator
and q: the denominator."""
self.p = p
self.q = q
def __str__(self):
"""String representation of a rational function."""
return "(" + str(self.p) + ")/(" + str(self.q) + ")"
def __call__(self, x):
"""Evaluate in x the rational function."""
return self.p(x) / self.q(x)
def __add__(self, other):
"""Add two rational functions."""
p = self.p * other.q + other.p * self.q
q = self.q * other.q
return RationalFunction(p, q)
def __sub__(self, other):
"""Substract two rational functions."""
p = self.p * other.q - other.p * self.q
q = self.q * other.q
return RationalFunction(p, q)
def __mul__(self, other):
"""Multiply two rational functions."""
p = self.p * other.p
q = self.q * other.q
return RationalFunction(p, q)
def __invert__(self, other):
"""Return the inverse of the rational function. (This operation is optional.)"""
return RationalFunction(self.q, self.p)
def __truediv__(self, other):
"""Divide a rational function by another."""
p = self.p * other.q
q = self.q * other.p
return RationalFunction(p, q)
def getDegree(self):
"""Return the degree of the rational function."""
return self.p.degree - self.q.degree
def getPoles(self):
"""Return the poles of the rational function."""
return self.q.roots
def getRoots(self):
"""Return the roots of the rational function."""
return self.p.roots
def decompose(self): # Not implemented
"""Return the partial fraction decomposition."""
# Note this method is supposed to work with complexes
# So it is not always valid and needs a more general case
e, r = self.p / self.q
roots = self.q.getRoots()
l = [e]
for (j, xj) in enumerate(roots):
p = Polynomial([self.p(xj) / self.q.derivative(xj)])
q = Polynomial([-xj, 1])
fp = RationalFunction(p, q)
l.append(fp)
return l
def getWholePart(self): # Not finished
"""Return the whole part of the fraction."""
e, r = self.p / self.q
return e
def getFractionalPart(self): # Not finished
"""Return the fractional part of the fraction."""
e, r = self.p / self.q
return r
degree = property(getDegree)
poles = property(getPoles)
class PartialFraction(RationalFunction): # This is just an idea
"""The only difference with the rational function is that the denominator is
of the form: [a,b] which corresponds to q=(x-a)**b."""
# It might not be a good idea.
def __init__(self, p, q):
"""Define a rational function using two polynomials p: the numerator
and q: the denominator."""
self.p = p
self.q = q
if __name__ == "__main__":
#suite_random = [random.randint(0,10) for i in range(10)] #Create polynome as big as needed.
#X=Polynomial(suite_random)
suite1 = [3,2,4,5,1]
suite2 = [1,4,1]
suite3 = [4,5]
# suite_random = [random.randint(0,10) for i in range(10)] #Create polynome as big as needed.
# X=Polynomial(suite_random)
# t=float128
suite1 = [3, 2, 4, 5, 1]
suite2 = [1, -2, 1]
suite3 = [4, 5]
A = Polynomial(suite1)
B = Polynomial(suite2)
C = Polynomial(suite3)
print("A =",A)
print("B =",B)
print("C =",C)
print("A+B =",A+B)
print("A*B =",A*B)
print("Derivative of A =",A.derivative())
print("A/B :",A/B)
print("Unit polynomial of C =",C.unit())
print("HCF (PGCD en francais) of A and B (written A^B) =",A^B)
print("LCM (PPCM en francais) of A and B (written A|B) =",A|B)
print("Roots of A:",A.roots())
print("Show A on screen:")
A.show()
FP = RationalFunction(A, B)
print("A =", A)
print("B =", B)
print("C =", C)
print("A+B =", A + B)
print("A*B =", A * B)
print("Derivative of A =", A.derivative())
print("A/B :", A / B)
print("A//B:", A // B)
print("Unit polynomial of C =", C.unit())
print("HCF (PGCD en francais) of A and B (written A^B) =", A ^ B)
print("LCM (PPCM en francais) of A and B (written A|B) =", A | B)
print("Roots of B:", B.roots)
print("Multiplicity of the root 2 of B:", B.getMultiplicity(2))
print("Roots with multiplicities of B:", B.getRootsWithMultiplicity())
#print("Show A on screen:")
# C=Polynomial.createFromInterpolation([1,2,-4,-6,4],[1,-3,-2,5,-2])
print(C.coefficients)
print(FP.decompose())
# C.show()
+18
View File
@@ -0,0 +1,18 @@
#from __future__ import *
simple_stmt ::= expression_stmt
| assert_stmt
| assignment_stmt
| augmented_assignment_stmt
| annotated_assignment_stmt
| pass_stmt
| del_stmt
| return_stmt
| yield_stmt
| raise_stmt
| break_stmt
| continue_stmt
| import_stmt
| future_stmt
| global_stmt
| nonlocal_stmt
+13
View File
@@ -0,0 +1,13 @@
a=8*3600
b=1*60+12
print(a/b)
print(b*15)
c=(1e13/200)**(1/1000)
print(c)
print(1080/8/60)
+11
View File
@@ -0,0 +1,11 @@
class Test:
v=1
def __init__(self):
self.v=1
@staticmethod
def test(cls,self):
print(cls.v,self.v)
t=Test()
print(t.test())
+17
View File
@@ -0,0 +1,17 @@
from collections import deque
d = deque('hello', maxlen=5)
d.append('4')
d.append(4)
d.appendleft(2)
d.pop()
d.popleft()
d.clear()
d.extend(iter([1,2,3]))
print(d)
d.extendleft('hey')
print(d)
d.rotate(2) #useful
print(d)
+45
View File
@@ -0,0 +1,45 @@
def creer_personne(personne, nom, prenom):
"""La fonction qui jouera le rôle de constructeur pour notre classe Personne.
Elle prend en paramètre, outre la personne :
nom -- son nom
prenom -- son prenom"""
personne.nom = nom
personne.prenom = prenom
personne.age = 21
personne.lieu_residence = "Lyon"
def presenter_personne(personne):
"""Fonction présentant la personne.
Elle affiche son prénom et son nom"""
print("{} {}".format(personne.prenom, personne.nom))
# Dictionnaire des méthodes
methodes = {
"__init__": creer_personne,
"presenter": presenter_personne,
}
# Création dynamique de la classe
Personne = type("Personne", (), methodes)
print(Personne)
#---------------------#
class MaMetaClasse(type):
"""Exemple d'une métaclasse."""
def __new__(metacls, nom, bases, dict):
"""Création de notre classe."""
print("On cree la classe {}".format(nom))
return type.__new__(metacls, nom, bases, dict)
class MaClasse(metaclass=MaMetaClasse):
pass
print()
+80
View File
@@ -0,0 +1,80 @@
import pygame
import cv2
pygame.init()
# --- create PyGame image ---
pg_img = pygame.Surface((400, 200))
pygame.draw.circle(pg_img, (255,0,0), (0,0), 200)
# --- display PyGame image ---
screen = pygame.display.set_mode((400, 400))
screen.fill((255,255,255))
screen.blit(pg_img, pg_img.get_rect())
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
running = False
pygame.quit()
# --- move from PyGame to CV2 ---
color_image = pygame.surfarray.array3d(pg_img)
color_image = cv2.transpose(color_image)
color_image = cv2.cvtColor(color_image, cv2.COLOR_RGB2BGR)
# --- display CV2 image ---
cv2.imshow('Color', color_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# --- change CV2 image ---
color_image = cv2.rotate(color_image, cv2.ROTATE_90_CLOCKWISE)
gray_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY)
# --- display CV2 image ---
cv2.imshow('Gray', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# --- save in file in CV2 ---
cv2.imwrite('test.png', color_image)
# --- move back from CV2 to PyGame ---
gray_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2RGB)
gray_image = cv2.transpose(gray_image)
pg_img = pygame.surfarray.make_surface(gray_image)
# --- display PyGame image ---
screen = pygame.display.set_mode((400, 400))
screen.fill((255,255,255))
screen.blit(pg_img, pg_img.get_rect())
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
running = False
pygame.quit()
+29
View File
@@ -0,0 +1,29 @@
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Get the Default resolutions
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
# Define the codec and filename.
out = cv2.VideoWriter('output.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
# write the frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
+27
View File
@@ -0,0 +1,27 @@
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter("output.mp4",
cv2.VideoWriter_fourcc(*'MP4V'), 10,(640,480))
while(cap.isOpened()):
ret, frame = cap.read()
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
+13
View File
@@ -0,0 +1,13 @@
import cv2
import numpy as np
a="MPEG"
b='MP4V'
writer = cv2.VideoWriter("output.mp4",
cv2.VideoWriter_fourcc(*a), 100,(640,480))
for frame in range(1000):
writer.write(np.random.randint(0, 255, (480,640,3)).astype('uint8'))
writer.release()
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
import math
N=200
a1=sum([1-math.exp(1/n) for n in range(1,N)])
a1b=sum([-1/n for n in range(1,N)])
a2=sum([math.cosh(n)/math.cosh(2*n) for n in range(1,N)])
a3=sum([math.factorial(n)/n**n for n in range(1,N)])
print(a1,a1b,a2,a3)
+23
View File
@@ -0,0 +1,23 @@
from math import sin
from sympy import Symbol,sin,sqrt
from sympy import *
x=Symbol('x')
#f=sin(x)/x
f=sqrt(sin(x)/(2*x))
a=5
print(f)
#x=2
print(f)
print("\n".join(map(str,Symbol.__dict__.items())))
a=(1/x)~(1/x**2)
print(a)
Binary file not shown.
-256
View File
@@ -1,256 +0,0 @@
"""mots=[]
determinants=["le","la","un","une"]
determinants={"avant":[],
"apres":[],
"masculin":None,
"singulier":None}
#print(determinants)"""
words=[]
articles=["a","an","the"]
a=["I","you","he","she","it","we","they"]
class List(list):
def __init__(self,object):
super().__init__(object)
def removeall(self,element):
while element in self:
self.remove(element)
def purge(self,elements):
for element in elements:
self.removeall(element)
def keep(self,elements):
for element in self[:]:
if not (element in elements):
self.removeall(element)
def whipe(self):
accumulator=[]
for e in self:
accumulator+=e
return accumulator
class Str(str):
def __init__(self,object):
super().__init__()
self.alphabet="abcdefghijklmnopqrstuvwxyz"
self.consonants="bcdfghjklmnpqrstvwxyz"
self.vowels="aeiouy"
self.numbers="0123456789"
def remove(self,element):
self.replace(element,"")
def removeall(self,element):
while element in self:
self.replace(element,"")
def purge(self,elements):
a=Str("")
l=List(self)
l.purge(elements)
return Str(a.join(l))
def keep(self,elements):
a=Str("")
l=List(self)
l.keep(elements)
return Str(a.join(l))
def reverse(self):
self=[l for l in self[-1:]]
#for i in range(len(self)//2):
# self[i]=self[-i-1]
def append(self,element):
self+=element
def apphead(self,element):
self.reverse()
self.append(element)
self.reverse()
def __sub__(self,element):
return self.replace(element,"")
def __isub__(self,element):
self.replace(element,"")
def __truediv__(self,elements):
for element in elements:
self.replace(element,"")
def __floordiv__(self,element):
for element in elements:
self.removeall(element,"")
def decompose(self):
accumulator=[]
for i in range(1,len(self)):
for j in range(len(self)-i):
accumulator.append(self[j:j+i])
return accumulator
def union(self,l1,l2):
accumulator=[]
for e1 in l1:
if e1 in l2:
accumulator.append(e1)
return set(accumulator)
def __mod__(self,other):
other=Str(other)
own_dec=self.decompose()
other_dec=other.decompose()
result=len(self.union(own_dec,other_dec))/len(own_dec+other_dec)*100
return result #in [0,1]
def reverse(self):
data=list(self)
data.reverse()
return Str("".join(data))
class Sentence(Str):
def __init__(self,object):
super().__init__(object)
self.words=self.wordsplit()
def wordsplit(self):
text=self[:]
text=text.lower()
text=Str(text.replace("'"," "))
text=text.keep(" "+self.alphabet)
words=List(text.split(" "))
words.removeall('')
words=[Word(word) for word in words]
return words
def __mod__(self,other):
other=Sentence(other)
own_dec=self.wordsplit()
other_dec=other.wordsplit()
print(own_dec,other_dec)
union=self.union(own_dec,other_dec)
print(union)
result=len(union)/len(own_dec+other_dec)*100
return result #in [0,1]
class Word(Str):
def __init__(self,object):
super().__init__(object)
self.syllables=self.syllablesplit()
def syllablesplit(self):
syllables=[]
word=self[:]
while word!="":
syllable=self.firstsyllable(word)
syllables.append(syllable)
word=word[len(syllable):]
return syllables
def firstsyllable(self,word):
vowelfound=False
for i in range(len(word)-1):
if word[i] in self.vowels: vowelfound=True
if (word[i] in self.consonants) and (word[i+1] in self.vowels):
if i>0 and vowelfound: return word[:i]
return word
class MutableString(object):
def __init__(self, data):
self.data = list(data)
def __str__(self):
return "".join(self.data)
def append(self,element):
self.data+=list(element)
def appstart(self,element):
self.data.reverse()
element.reverse()
self.data.append(element)
self.data.reverse()
def __repr__(self):
return "".join(self.data)
def __setitem__(self, index, value):
self.data[index] = value
def __getitem__(self, index):
if type(index) == slice:
return "".join(self.data[index])
return self.data[index]
def __delitem__(self, index):
del self.data[index]
def __add__(self, other):
self.data.extend(list(other))
def __len__(self):
return len(self.data)
def __reverse__(self):
self.data.reverse()
noun={"nature":None,
"singular":None,
"synonyms":[]}
if __name__=="__main__":
sentence=Sentence("you're a fucking asshole you dumbass, you are a scrotumbag")
#b=Str([1,2])
#a=a.remove(".")
#print(a)
#print(sentence.words)
#print([word.syllables for word in sentence.words])
#print(sentence-"fucking ")
#sentence=MutableString(sentence)
#print(sentence)
#print(Str(sentence).title())
#print(list(a))
#print(a.remove("s"))
#print(b.remove(1))
other=Sentence("you are a fucking asshole and a dumbass")
other.words.reverse()
other=Sentence(" ".join(other.words))
#other=other.reverse()
print(other)
print(sentence%other)
#def decomposeSentence(Str):
#return words
#decomposeSentence(a)
-176
View File
@@ -1,176 +0,0 @@
import inspect
def test(arg1,arg2):
a = arg1 + arg2
return a
#do something with args
keywords=["assert","break","class","continue","def","del","elif","else","except","finally","for",
"from","global","if","import","in","pass","print","raise","return","try","while","yield"]
conversion1 = {"assert":"ASSERT",
"break":"SORTIR DE LA BOUCLE",
"class":"CLASSE",
"continue":"CONTINER",
"def":"DONNEES",
"del":"SUPPRIMER",
"elif":["SINON SI","FAIRE"],
"else":["SINON","FAIRE"],
"except":"EXCEPTE",
"finally":"FINALLEMENT",
"for":["POUR","FAIRE"],
"from":"DEPUIS",
"global":"GLOBAL",
"if":"SI",
"import":"IMPORTER",
"in":"DANS",
"pass":"PASSER",
"print":"AFFICHER",
"raise":"RELEVER",
"return":"AFFICHER",
"try":"ESSAYER",
"while":["TANT QUE","FAIRE"],
"yield":"PASSER AU TOUR SUIVANT",
"==":"=",
"=":"<-"}
def algorithm(name):
lines = inspect.getsource(name)
output = []
lines = lines.split("\n")
for line in lines:
output.append(Converter(line)())
#print("output: ",output)
return "\n".join(output)
class Converter:
def __init__(self,line):
self.line=line
self.alphabet="abcdefghijklmnopqrstuvwxyz"
self.numbers="0123456789"
self.punctuation="():.,"
self.conversion= {"assert": [[None,"assert",None], [None,"ASSERT",None]],
"break": [[None,"break"], [None,"SORTIR DE LA BOUCLE"]],
"class": [["class",None], ["CLASS",None]],
"continue": [[None,"continue",None], [None,"CONTINUER",None]],
"def": [["def",None,"(",None,"):"], [None,":\nDONNES: ",None," :"]],
"del": [[None,"del",None], [None,"SUPPRIMER",None]],
"elif": [[None,"elif",None,":"], [None,"SINON SI",None," FAIRE"]],
"else": [[None,"else:",None], [None,"SINON",None," FAIRE"]],
"except": [[None,"except:",None], [None,"EXCEPTE",None]],
"finally": [[None,"finally:",None], [None,"FINALLEMENT",None]],
"for": [["for",None," in ",None,":"], ["POUR",None," DANS ",None," FAIRE"]],
"from": [["from",None], ["DEPUIS",None]],
"global": [["global",None], ["GLOBAL",None]],
"if": [[None,"if ",None], [None,"SI",None]],
"import": [[None,"import",None], [None,"IMPORTER",None]],
" in ": [[None," in ",None], [None, "DANS ",None]],
" is ": [[None," is ",None], [None," EST ",None]],
"pass": [[None,"pass"], [None,"PASSER",None]],
"print": [[None,"print",None,"(",None,")"], [None,"AFFICHER: ",None,None]],
"raise": [[None,"raise",None], [None,"RELEVER",None]],
"return": [[None,"return",None], [None,"AFFICHER",None]],
"try": [[None,"try:",None], [None,"ESSAYER",None]],
"while": [["while ",None,":"], ["TANT QUE ",None," FAIRE"]],
"yield": [[None,"yield"], [None,"PASSER AU TOUR SUIVANT"]],
"==": [[None,"==",None], [None,"=",None]],
"!=": [[None,"!=",None], [None,"≠",None]],
"=": [[None,"=",None], [None,"<=",None]],
"append": [[None,".append(",None,")"], ["AJOUTER A ",None," LA VALEUR ",None]]}
self.removeIndent()
def removeIndent(self):
self.indent=0
if self.line!="":
while self.line[0]==" ":
self.indent+=1
self.line=self.line[1:]
def convert(self):
if not ("#" in self.line):
for key in self.conversion:
if key in self.line:
self.apply(key)
def apply(self,key):
#print("key:",key)
l=self.missing(self.conversion[key][0])
#print("l:",l)
filled=self.fill(self.conversion[key][1],l)
#print("filled:",filled)
self.line="".join(filled)
#print(self.line)
def missing(self,l):
"""
l= ["def ",None,"(",None,"):"]
self.line= "def algorithm(name):"
l1=["def","(","):"]
"""
line=[]
if l[0]==None:
i=self.next(self.line,l[1])
line.append(self.line[:i])
for i in range(1,len(l)-1):
#print("missing loop:",l[i-1],l[i],l[i+1])
if l[i]==None:
a=self.between(self.line,l[i-1],l[i+1])
line.append(a)
#print("a",a)
if l[-1]==None:
i=self.next(self.line,l[-2])+len(l[-2])
line.append(self.line[i:])
return line
def removeNone(self,l):
l1=[]
for word in l:
if word!=None:
l1.append(word)
return l1
def between(self,text,word1,word2):
i1=self.next(text,word1)+len(word1)
i2=i1+self.next(text[i1:],word2)
return text[i1:i2]
def cut(self,text,word):
for i in range(len(text)-len(word)+1):
if text[i:i+len(word)]==word:
break
return [text[:i],word,text[i+len(word):]]
def next(self,text,word):
for i in range(len(text)-len(word)+1):
if text[i:i+len(word)]==word:
break
return i
def fill(self,l1,l2):
line=[]
for e1 in l1:
if e1==None:
line.append(l2[0])
del l2[0]
else:
line.append(e1)
return line
def __call__(self):
self.convert()
return " "*self.indent+self.line
print(algorithm(algorithm))
#c=Converter("def test(arg1,arg2):")
#print(c.between("def test(arg1,arg2):","(",")"))
-31
View File
@@ -1,31 +0,0 @@
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
print(lines.split("\n"))
def convertir(nom):
import inspect
lines = inspect.getsource(foo)
lines=Str(lines)
output=[]
for line in lines:
output.append(convert(line))
return "".join(output)
def convert(line):
if word_split():
#import dis
#print(dis.dis(foo))
#from dill.source import getsource
#print(getsource(list.remove))
+36
View File
@@ -0,0 +1,36 @@
import numpy as np
import pylab
# elephant parameters
p1, p2, p3, p4 = (50 - 30j, 18 + 8j, 12 - 10j, -14 - 60j )
p5 = 40 + 20j # eyepiece
def fourier(t, C):
f = np.zeros(t.shape)
A, B = C.real, C.imag
for k in range(len(C)):
f = f + A[k]*np.cos(k*t) + B[k]*np.sin(k*t)
return f
def elephant(t, p1, p2, p3, p4, p5):
npar = 6
Cx = np.zeros((npar,), dtype='complex')
Cy = np.zeros((npar,), dtype='complex')
Cx[1] = p1.real*1j
Cx[2] = p2.real*1j
Cx[3] = p3.real
Cx[5] = p4.real
Cy[1] = p4.imag + p1.imag*1j
Cy[2] = p2.imag*1j
Cy[3] = p3.imag*1j
x = np.append(fourier(t,Cx), [-p5.imag])
y = np.append(fourier(t,Cy), [p5.imag])
return x,y
x, y = elephant(np.linspace(0,2*np.pi,1000), p1, p2, p3, p4, p5)
pylab.plot(y,-x,'.')
pylab.show()
-3
View File
@@ -1,3 +0,0 @@
def f(a,b):
if a==0: return b
else: return (b+1)
-2
View File
@@ -1,2 +0,0 @@
def __+__(a,b):
return a+b
-2
View File
@@ -1,2 +0,0 @@
import sys
print(sys.version)
-3
View File
@@ -1,3 +0,0 @@
#--coding:utf-8--
print('é')