socket, youtube-dl pyglet, td, hackerank

This commit is contained in:
2019-07-07 14:55:28 +02:00
parent 75a4803a5b
commit f7050f845c
28 changed files with 1037 additions and 5 deletions
Vendored
BIN
View File
Binary file not shown.
+81
View File
@@ -0,0 +1,81 @@
def pgcd(a,b):
if a==0:
return b
if b==0:
return a
a=abs(a)
b=abs(b)
mi=min(a,b)
ma=max(a,b)
if ma%mi==0:
return mi
else:
return pgcd(ma-mi,mi)
def pgcds(l):
a=float("inf")
for i in range(len(l)):
for j in range(i+1,len(l)):
na=pgcd(l[i],l[j])
if na<a:
a=na
return na
def ppcm(a,b):
a=abs(a)
b=abs(b)
p=max(a,b)
while not (p%a==0 and p%b==0):
if not p%a==0:
p+=b
if not p%b==0:
p+=a
return p
def ppcms(l):
a=0
for i in range(len(l)):
for j in range(i+1,len(l)):
na=ppcm(l[i],l[j])
if na>a:
a=na
return na
a=[2,4]
b=[16,32,96]
def divideAll(d,l):
for e in l:
if e%d!=0:
return False
return True
def multipleOfAll(m,l):
for e in l:
if m%e!=0:
return False
return True
"""l=[]
pa=pab=ppcms(a)
pb=pgcds(b)
print(pa)
print(pb)
while pa<=min(b):
if divideAll(pa,b):
l.append(pa)
pa+=pab
print(pa,divideAll(pa,b))"""
l=list(range(max(a),min(b)+1))
fl=[]
for e in l:
if divideAll(e,b) and multipleOfAll(e,a):
fl.append(e)
print(len(fl))
+18
View File
@@ -0,0 +1,18 @@
import itertools
s=list(range(6))
scy=itertools.cycle(iter(s))
def extract(it,mi,ma):
it1,it = itertools.tee(it)
return ([next(it1) for i in range(ma)][mi:],it)
a,scy=extract(scy,1,3)
print(a)
print(extract(scy,1,3))
print(" ".join(map(str,s)))
+28
View File
@@ -0,0 +1,28 @@
import random
def queensAttack(n, k, r_q, c_q, obstacles):
f=lambda o:(1<=o[0]<=n and 1<=o[1]<=n)
obstacles=list(filter(f,obstacles))
nob=[[x-r_q,y-c_q] for [x,y] in obstacles]
obstacles=[[x,y] for (x,y) in list(set([(x,y) for (x,y) in obstacles]))]
def polar(x,y):
n=math.sqrt(x**2+y**2)
directions=[[x,y] for x in [-1,0,1] for y in [-1,0,1] if (x,y)!=(0,0)]
a=0
for direction in directions:
dx,dy=direction
x,y=r_q+dx,c_q+dy
while f([x,y]):
if [x,y] in obstacles:
break
x+=dx
y+=dy
a+=1
return a
print(queensAttack(100,50,6,7,[[random.randint(1,100),random.randint(1,100)] for i in range(50)]))
+14
View File
@@ -0,0 +1,14 @@
import functools
binary=lambda x,m:list(reversed([int((x%2**(i+1))//2**i) for i in range(m)]))
xor=lambda l:list(map(lambda x:1-x,l))
decimal=lambda l:sum([v*2**i for (i,v) in enumerate(list(reversed(l)))])
prod=lambda l:functools.reduce(lambda a,b:a*b,l)
n=5
a=prod(list(range(1,n+1)))
print(a)
a=binary(a,32)
a=xor(a)
a=decimal(a)
+53
View File
@@ -0,0 +1,53 @@
import random
def getNewPosition(x,y,w,h,r):
d=min(min(w-1-x,x),min(h-1-y,y))
while r>0 and not(h==w==0):
r-=1
if x==d and y!=h-1-d:
x,y=(x,y+1)
continue
if y==d and x!=d:
x,y=(x-1,y)
continue
if x==w-1-d and y!=d:
x,y=(x,y-1)
continue
if y==h-1-d and x!=w-1-d:
x,y=(x+1,y)
continue
return (x,y)
def rotate(m,r=1):
h=len(m)
w=len(m[0])
if w>1 and h>1: r%=(2*(h+w-2))
nm=[[0 for x in range(w)] for y in range(h)]
for x in range(w):
for y in range(h):
nx,ny=getNewPosition(x,y,w,h,r)
nm[ny][nx]=m[y][x]
return nm
def toSpaceStr(m):
t=[]
for y in range(len(m)):
t.append(" ".join([str(e) for e in m[y]]))
return "\n".join(str(e) for e in t)
x1,y1=[random.randrange(2,10,2) for i in range(2)]
m=[[random.randint(1,9) for x in range(5)] for y in range(4)]
m=[[y*4+x+1 for x in range(4)] for y in range(4)]
#m=[[0]]
tm=toSpaceStr(m)
print(tm,end='\n\n')
rm=rotate(m,2)
trm=toSpaceStr(rm)
print(trm,end='')
BIN
View File
Binary file not shown.
+164
View File
@@ -0,0 +1,164 @@
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)
@@ -0,0 +1,138 @@
#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
+1 -1
View File
@@ -1,7 +1,7 @@
from pyglet.gl import *
from pyglet.window import key
import math
import sys
class Model:
+127
View File
@@ -0,0 +1,127 @@
from pyglet.gl import *
from pyglet.window import key
import math
from main import Model
class Model2(Model):
def get_tex(self,file):
tex = pyglet.image.load(file).texture
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST)
return pyglet.graphics.TextureGroup(tex)
def __init__(self):
self.top = self.get_tex('grass_top.png')
self.side = self.get_tex('grass_side.png')
self.bottom = self.get_tex('dirt.png')
self.batch = pyglet.graphics.Batch()
tex_coords = ('t2f',(0,0, 1,0, 1,1, 0,1, ))
for zi in range(-10,10):
for yi in range(-10,10):
for xi in range(-10,10):
self.addCube(xi,yi,zi)
yi=-10
for zi in range(-100,100):
for xi in range(-100,100):
self.addCube(xi,yi,zi)
def addCube(self,xi,yi,zi):
x,y,z = xi,yi,zi-1
X,Y,Z = x+1,y+1,z+1
self.batch.add(4,GL_QUADS,self.side,('v3f',(x,y,z, x,y,Z, x,Y,Z, x,Y,z, )),tex_coords)
self.batch.add(4,GL_QUADS,self.side,('v3f',(X,y,Z, X,y,z, X,Y,z, X,Y,Z, )),tex_coords)
self.batch.add(4,GL_QUADS,self.bottom,('v3f',(x,y,z, X,y,z, X,y,Z, x,y,Z, )),tex_coords)
self.batch.add(4,GL_QUADS,self.top,('v3f',(x,Y,Z, X,Y,Z, X,Y,z, x,Y,z, )),tex_coords)
self.batch.add(4,GL_QUADS,self.side,('v3f',(X,y,z, x,y,z, x,Y,z, X,Y,z, )),tex_coords)
self.batch.add(4,GL_QUADS,self.side,('v3f',(x,y,Z, X,y,Z, X,Y,Z, x,Y,Z, )),tex_coords)
def draw(self):
self.batch.draw()
class Player:
def __init__(self,pos=(0,0,0),rot=(0,0)):
self.pos = list(pos)
self.rot = list(rot)
def mouse_motion(self,dx,dy):
dx/=8; dy/=8; self.rot[0]+=dy; self.rot[1]-=dx
if self.rot[0]>90: self.rot[0] = 90
elif self.rot[0]<-90: self.rot[0] = -90
def update(self,dt,keys):
s = dt*10
rotY = -self.rot[1]/180*math.pi
dx,dz = s*math.sin(rotY),s*math.cos(rotY)
if keys[key.W]: self.pos[0]+=dx; self.pos[2]-=dz
if keys[key.S]: self.pos[0]-=dx; self.pos[2]+=dz
if keys[key.A]: self.pos[0]-=dz; self.pos[2]-=dx
if keys[key.D]: self.pos[0]+=dz; self.pos[2]+=dx
if keys[key.SPACE]: self.pos[1]+=s
if keys[key.LSHIFT]: self.pos[1]-=s
class Window(pyglet.window.Window):
def push(self,pos,rot): glPushMatrix(); glRotatef(-rot[0],1,0,0); glRotatef(-rot[1],0,1,0); glTranslatef(-pos[0],-pos[1],-pos[2],)
def Projection(self): glMatrixMode(GL_PROJECTION); glLoadIdentity()
def Model(self): glMatrixMode(GL_MODELVIEW); glLoadIdentity()
def set2d(self): self.Projection(); gluOrtho2D(0,self.width,0,self.height); self.Model()
def set3d(self): self.Projection(); gluPerspective(70,self.width/self.height,0.05,1000); self.Model()
def setLock(self,state): self.lock = state; self.set_exclusive_mouse(state)
lock = False; mouse_lock = property(lambda self:self.lock,setLock)
def __init__(self,*args,**kwargs):
"""Create pyglet window."""
super().__init__(*args,**kwargs)
self.set_minimum_size(300,200)
self.keys = key.KeyStateHandler()
self.push_handlers(self.keys)
pyglet.clock.schedule(self.update)
self.model=Model2()
self.player=Player((0.5,1.5,1.5),(-30,0))
def on_mouse_motion(self,x,y,dx,dy):
"""Set the parameters of the view of the player using the position of the mouse."""
if self.mouse_lock: self.player.mouse_motion(dx,dy)
def on_key_press(self,KEY,MOD):
"""Determine if the window must be closed."""
if KEY == key.ESCAPE: self.close()
#elif KEY == key.E: self.mouse_lock = not self.mouse_lock
self.mouse_lock=True
def update(self,dt):
"""Update the player's view using time dt and knowning keys."""
self.player.update(dt,self.keys)
def on_draw(self):
"""Overload function automatically called by the pyglet window while running."""
self.clear()
self.set3d()
self.push(self.player.pos,self.player.rot)
self.model.draw()
glPopMatrix()
if __name__ == '__main__':
window = Window(width=1440,height=900,caption='Minecraft',fullscreen=True)
r,g,b,alpha=0,0,0,1 #Color of the background and transparency alpha, each component's value must be between 0 and 1
glClearColor(r,g,b,alpha) #Apply the background
#glEnable allows to change the parameters of the opengl interface
glEnable(GL_DEPTH_TEST) #Allow the objects not to be displayed when behing others, must be enabled to prevent weird bugs
#glEnable(GL_CULL_FACE)
pyglet.app.run()
View File
+64
View File
@@ -0,0 +1,64 @@
import socket
import select
HEADER_LENGTH=10
IP="127.0.0.1"
PORT=1234
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.listen()
sockets_list=[server_socket]
clients={}
def receive_message(client_socket):
try:
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)}
except:
return False
while True:
read_sockets,_,exception_sockets=select.select(sockets_list,[],sockets_lists)
for notified_socket in read_sockets:
if notified_socket==server_socket:
client_socket,client_address=server_socket
user = receive_message(client_socket)
if user is False:
continue
sockets_list.append(client_socket)
clients[client_socket]=user
print(f"Accepted new connection from {client_address[0]}:{client_address[1]} username: {user['data'].decode('utf-8')}")
else:
message=receive_message(notified_socket)
if message is False:
print(f"Closed connection from {clients[notified_socket]['data'].decode('utf-8')})
sockets_list.remove(notified_socket)
del clients[notified_sockets]
continue
user = clients[notified_socket]
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'])
for notified_socket in exception_sockets:
sockets_list.remove(notified_socket)
del clients[notified_socket]
+31
View File
@@ -0,0 +1,31 @@
import socket
import pickle
HEADERSIZE=10
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((socket.gethostname(),1234))
while True:
full_msg=b''
new_msg=True
while True:
msg=s.recv(16)
if new_msg:
print(f"new message length: {msg[:HEADERSIZE]}")
msglen=int(msg[:HEADERSIZE])
new_msg=False
full_msg+=msg
if len(full_msg)-HEADERSIZE==msglen:
print("fullmsg recvd")
print(full_msg[HEADERSIZE:])
d=pickle.loads(full_msg[HEADERSIZE:])
print(d)
new_msg=True
full_msg=b''
print(full_msg)
+21
View File
@@ -0,0 +1,21 @@
import socket
import time
import pickle
HEADERSIZE=10
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((socket.gethostname(),1234))
s.listen(5)
while True:
clientsocket,address=s.accept()
print(f"Connection from {address} has been established!")
d={1:"Hey",2:"There"}
msg=pickle.dumps(d)
msg=bytes(f'{len(msg):<{HEADERSIZE}}',"utf-8")+msg
clientsocket.send(msg)
+2
View File
@@ -0,0 +1,2 @@
while True:
print("Shut me off!")
+3
View File
@@ -0,0 +1,3 @@
import errno
print(errno.E2BIG)
+7
View File
@@ -0,0 +1,7 @@
#-utf8:# -*- coding: utf-8 -*-
import pwd
print(pwd.getpwall())
#print(len(pwd.getpwnam("olivierpartensky").pw_passwd))
+6 -4
View File
@@ -15,7 +15,7 @@ ydl_opts = {
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'
#'preferredquality': '192' #Makes no difference at all.
}],
'postprocessor_args': [
'-ar', '16000'
@@ -46,14 +46,16 @@ def download(url,options):
if __name__=="__main__":
#Choose your directory
DIRECTORY='/Users/olivierpartensky/Videos/2019/Youtube/Downloads'
DIRECTORY='/Users/olivierpartensky/Videos/2019/Youtube/JJD'
os.chdir(DIRECTORY)
print(DIRECTORY)
#Choose your musics
#jjd_ocean="https://www.youtube.com/watch?v=XGyrclIGB9E"
jjd_ocean="https://www.youtube.com/watch?v=XGyrclIGB9E"
url=jjd_ocean
#playlist='https://www.youtube.com/playlist?list=UUMOgdURr7d8pOVlc-alkfRg'
url="https://www.youtube.com/playlist?list=UUMOgdURr7d8pOVlc-alkfRg"
#url="https://www.youtube.com/playlist?list=UUMOgdURr7d8pOVlc-alkfRg"
#url="https://www.youtube.com/playlist?list=UU9IdQzchnAAwsjQb6DCugPw"
#Download them
download(url,ydl_opts)
+165
View File
@@ -0,0 +1,165 @@
from __future__ import unicode_literals
import youtube_dl
from pydub import AudioSegment
from pydub.playback import play
import os
import subprocess
"""I tried all the codecs on my machine but none is able to convert ogg nor webm into mp3 without loss of audio quality."""
#import audiotools
#os.system("""/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)""""")
#os.system("brew install ffmpeg")
#os.system("pip3.6 install youtube-dl")
#Choose the youtube-dl downloading options
#https://github.com/ytdl-org/youtube-dl for more informations
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
#'preferredcodec': 'mp3',
'preferredquality': '192'
}],
'postprocessor_args': [
'-ar', '16000'
],
'prefer_ffmpeg': True,
'keepvideo': False,
'ignoreerrors':True
}
#Main functions used
def clean():
"""Delete all the webm files and rename the mp3 files with the original youtube names."""
l=os.listdir()
for i,f in enumerate(l):
if f[-4:]=="webm":
os.remove(f)
if f[-3:]=="mp3":
nf=f[:-16]+".mp3"
os.rename(f,nf)
def clean2():
"""Convert all the files into mp3."""
l=os.listdir()
for i,f in enumerate(l):
#nf=f[:-16]+".mp3"
nf=f[:-4]+".mp4"
print(nf)
convert_video(f,nf)
def clean3():
"""Convert all the files into mp3."""
l=os.listdir()
for i,f in enumerate(l):
#nf=f[:-16]+".mp3"
nf=f[:-5]+".mp3"
print(f,nf)
convert_music_absoletely(f,nf)
def convert_video(video_input, video_output):
#"-b:v","1M" unknown argument
#cmds = ['ffmpeg', '-i', video_input,"-b:a","192", video_output]
cmds = ['ffmpeg', '-i', video_input, video_output]
#avconv -i test.webm test.mp3
#ffmpeg -i input.webm -acodec libmp3lame -aq 4 output.mp3
#cmds ['ffmpeg','-i',video_input,'-acodec','libmp3lame','-aq','4',video_output]
#os.system("ffmpeg -i "+video_input+" -acodec libmp3lame -aq 4 "+video_output)
subprocess.Popen(cmds)
def convert_music_absoletely(input,output):
"""Try to convert the input into the output format using all the codes available."""
sound = AudioSegment.from_file(input)
codecs=getCodecs()
for codec in codecs:
try:
sound.export(output,codec=codec)#, codec="libmp3lame")
print("Codec: "+codec+" worked.")
break
except:
print("Codec: "+codec+" failed.")
def convert_music(input,output):
sound = AudioSegment.from_ogg(input)
#play(sound)
sound.export(output,format="mp3")#,codec="avui")#, codec="libmp3lame")
def convert_using_audiotools(input,output):
pass
#def convert_to_audio(video_input,video_output)
def clear():
"""Delete all the files in the actual directory."""
l=os.listdir()
for i,f in enumerate(l):
os.remove(f)
def download(url,options={}):
"""Download all the musics using a youtube playlist url."""
print("clearing")
clear()
print("downloading")
with youtube_dl.YoutubeDL(options) as ydl:
ydl.download([url])
print("cleaning")
clean3()
print("Download is over.")
def showFormats(url):
"""Show the different formats."""
cmd=["youtube-dl","-F",url]
output=subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
output=str(output)
l=output.split("\\n")
for e in l:
print(e)
def showCodecs():
"""Show the different formats."""
cmd=["ffmpeg","-codecs"]
output=subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
output=str(output)
l=output.split("\\n")
for e in l[10:]:
print(e[8:].split(" ")[0])
def getCodecs():
"""Show the different formats."""
cmd=["ffmpeg","-codecs"]
output=subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
output=str(output)
l=output.split("\\n")
nl=[]
for e in l[10:]:
nl.append(e[8:].split(" ")[0])
return nl
if __name__=="__main__":
#Choose your directory
DIRECTORY='/Users/olivierpartensky/Videos/2019/Youtube/JJD'
os.chdir(DIRECTORY)
print(DIRECTORY)
#Choose your musics
jjd_ocean="https://www.youtube.com/watch?v=XGyrclIGB9E"
url=jjd_ocean
#playlist='https://www.youtube.com/playlist?list=UUMOgdURr7d8pOVlc-alkfRg'
#url="https://www.youtube.com/playlist?list=UUMOgdURr7d8pOVlc-alkfRg"
#url="https://www.youtube.com/playlist?list=UU9IdQzchnAAwsjQb6DCugPw"
#Download them
#showFormats(url)
showCodecs()
download(url,ydl_opts)
#clean()
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 665 B

+109
View File
@@ -0,0 +1,109 @@
import random
import itertools
def getRandomMatrix():
return [[random.randint(1,3) for i in range(3)] for i in range(3)]
def isMagicSquare(s):
return sum(s[0][i] for i in range(3))==sum(s[1][i] for i in range(3))==sum(s[2][i] for i in range(3))==sum(s[i][0] for i in range(3))==sum(s[i][1] for i in range(3))==sum(s[i][2] for i in range(3))==sum([s[i][i] for i in range(3)])==sum([s[2-i][i] for i in range(3)])
def isMagicSquare15(s):
return sum(s[0][:])==sum(s[1][:])==sum(s[2][:])==sum(s[:][0])==sum(s[:][1])==sum(s[:][2])==sum([s[i][i] for i in range(3)])==sum([s[2-i][i] for i in range(3)])==15
def getSquareFromList(l):
return [[l[3*i],l[3*i+1],l[3*i+2]] for i in range(3)]
def getSquaresFromLists(ls):
return [getSquareFromList(l) for l in ls]
def getListFromSquare(m):
return m[0][:]+m[1][:]+m[2][:]
def getListsFromSquares(ms):
return [getListFromSquare(m) for m in ms]
def getRandomSudokuList():
a=list(range(1,10))
l=[]
for i in range(9):
r=random.randint(0,8-i)
l.append(a[r])
del a[r]
return l
def getRandomSudokuSquare():
l=getRandomSudokuList()
return getSquareFromList(l)
def filterMagicSquares(ms):
return [m for m in ms if isMagicSquare(m)]
def filterMagicSquares15(ms):
return [m for m in ms if isMagicSquare15(m)]
def getMinimumCost(m,qs):
c=8*9
for q in qs:
nc=compare(q,m)
if nc<c:
c=nc
return c
def compare(m1,m2):
l1=getListFromSquare(m1)
l2=getListFromSquare(m2)
cost=0
for i in range(9):
cost+=abs(l1[i]-l2[i])
return cost
m=getRandomMatrix()
ls=itertools.permutations(list(range(1,10)))
ms=getSquaresFromLists(ls)
ms=filterMagicSquares(ms)
#ms=filterMagicSquares15(ms)
ms=[[[2, 7, 6], [9, 5, 1], [4, 3, 8]], [[2, 9, 4], [7, 5, 3], [6, 1, 8]], [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[4, 9, 2], [3, 5, 7], [8, 1, 6]], [[6, 1, 8], [7, 5, 3], [2, 9, 4]], [[6, 7, 2], [1, 5, 9], [8, 3, 4]], [[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[8, 3, 4], [1, 5, 9], [6, 7, 2]]]
#qs=[[[1, 6, 8], [3, 5, 7], [2, 4, 9]], [[1, 6, 8], [7, 5, 3], [2, 4, 9]], [[1, 8, 6], [3, 5, 7], [4, 2, 9]], [[1, 8, 6], [7, 5, 3], [4, 2, 9]], [[1, 9, 5], [2, 6, 7], [4, 3, 8]], [[1, 9, 5], [3, 8, 4], [2, 7, 6]], [[1, 9, 5], [4, 8, 3], [2, 7, 6]], [[1, 9, 5], [7, 6, 2], [4, 3, 8]], [[2, 4, 9], [3, 5, 7], [1, 6, 8]], [[2, 4, 9], [7, 5, 3], [1, 6, 8]], [[2, 6, 7], [1, 5, 9], [3, 4, 8]], [[2, 6, 7], [9, 5, 1], [3, 4, 8]], [[2, 7, 6], [1, 5, 9], [4, 3, 8]], [[2, 7, 6], [3, 4, 8], [5, 1, 9]], [[2, 7, 6], [3, 8, 4], [1, 9, 5]], [[2, 7, 6], [4, 8, 3], [1, 9, 5]], [[2, 7, 6], [8, 4, 3], [5, 1, 9]], [[2, 7, 6], [9, 5, 1], [4, 3, 8]], [[2, 9, 4], [1, 6, 8], [5, 3, 7]], [[2, 9, 4], [1, 8, 6], [3, 7, 5]], [[2, 9, 4], [3, 5, 7], [6, 1, 8]], [[2, 9, 4], [6, 8, 1], [3, 7, 5]], [[2, 9, 4], [7, 5, 3], [6, 1, 8]], [[2, 9, 4], [8, 6, 1], [5, 3, 7]], [[3, 4, 8], [1, 5, 9], [2, 6, 7]], [[3, 4, 8], [9, 5, 1], [2, 6, 7]], [[3, 7, 5], [1, 8, 6], [2, 9, 4]], [[3, 7, 5], [2, 4, 9], [6, 1, 8]], [[3, 7, 5], [6, 8, 1], [2, 9, 4]], [[3, 7, 5], [9, 4, 2], [6, 1, 8]], [[3, 8, 4], [1, 5, 9], [6, 2, 7]], [[3, 8, 4], [9, 5, 1], [6, 2, 7]], [[4, 2, 9], [3, 5, 7], [1, 8, 6]], [[4, 2, 9], [7, 5, 3], [1, 8, 6]], [[4, 3, 8], [1, 5, 9], [2, 7, 6]], [[4, 3, 8], [2, 6, 7], [1, 9, 5]], [[4, 3, 8], [6, 2, 7], [5, 1, 9]], [[4, 3, 8], [7, 2, 6], [5, 1, 9]], [[4, 3, 8], [7, 6, 2], [1, 9, 5]], [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[4, 8, 3], [1, 5, 9], [7, 2, 6]], [[4, 8, 3], [9, 5, 1], [7, 2, 6]], [[4, 9, 2], [1, 6, 8], [7, 3, 5]], [[4, 9, 2], [1, 8, 6], [5, 7, 3]], [[4, 9, 2], [3, 5, 7], [8, 1, 6]], [[4, 9, 2], [6, 8, 1], [5, 7, 3]], [[4, 9, 2], [7, 5, 3], [8, 1, 6]], [[4, 9, 2], [8, 6, 1], [7, 3, 5]], [[5, 1, 9], [3, 4, 8], [2, 7, 6]], [[5, 1, 9], [6, 2, 7], [4, 3, 8]], [[5, 1, 9], [7, 2, 6], [4, 3, 8]], [[5, 1, 9], [8, 4, 3], [2, 7, 6]], [[5, 3, 7], [1, 6, 8], [2, 9, 4]], [[5, 3, 7], [4, 2, 9], [6, 1, 8]], [[5, 3, 7], [8, 6, 1], [2, 9, 4]], [[5, 3, 7], [9, 2, 4], [6, 1, 8]], [[5, 7, 3], [1, 8, 6], [4, 9, 2]], [[5, 7, 3], [2, 4, 9], [8, 1, 6]], [[5, 7, 3], [6, 8, 1], [4, 9, 2]], [[5, 7, 3], [9, 4, 2], [8, 1, 6]], [[5, 9, 1], [2, 6, 7], [8, 3, 4]], [[5, 9, 1], [3, 8, 4], [6, 7, 2]], [[5, 9, 1], [4, 8, 3], [6, 7, 2]], [[5, 9, 1], [7, 6, 2], [8, 3, 4]], [[6, 1, 8], [2, 4, 9], [3, 7, 5]], [[6, 1, 8], [3, 5, 7], [2, 9, 4]], [[6, 1, 8], [4, 2, 9], [5, 3, 7]], [[6, 1, 8], [7, 5, 3], [2, 9, 4]], [[6, 1, 8], [9, 2, 4], [5, 3, 7]], [[6, 1, 8], [9, 4, 2], [3, 7, 5]], [[6, 2, 7], [1, 5, 9], [3, 8, 4]], [[6, 2, 7], [9, 5, 1], [3, 8, 4]], [[6, 7, 2], [1, 5, 9], [8, 3, 4]], [[6, 7, 2], [3, 4, 8], [9, 1, 5]], [[6, 7, 2], [3, 8, 4], [5, 9, 1]], [[6, 7, 2], [4, 8, 3], [5, 9, 1]], [[6, 7, 2], [8, 4, 3], [9, 1, 5]], [[6, 7, 2], [9, 5, 1], [8, 3, 4]], [[6, 8, 1], [3, 5, 7], [9, 2, 4]], [[6, 8, 1], [7, 5, 3], [9, 2, 4]], [[7, 2, 6], [1, 5, 9], [4, 8, 3]], [[7, 2, 6], [9, 5, 1], [4, 8, 3]], [[7, 3, 5], [1, 6, 8], [4, 9, 2]], [[7, 3, 5], [4, 2, 9], [8, 1, 6]], [[7, 3, 5], [8, 6, 1], [4, 9, 2]], [[7, 3, 5], [9, 2, 4], [8, 1, 6]], [[7, 6, 2], [1, 5, 9], [8, 4, 3]], [[7, 6, 2], [9, 5, 1], [8, 4, 3]], [[8, 1, 6], [2, 4, 9], [5, 7, 3]], [[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[8, 1, 6], [4, 2, 9], [7, 3, 5]], [[8, 1, 6], [7, 5, 3], [4, 9, 2]], [[8, 1, 6], [9, 2, 4], [7, 3, 5]], [[8, 1, 6], [9, 4, 2], [5, 7, 3]], [[8, 3, 4], [1, 5, 9], [6, 7, 2]], [[8, 3, 4], [2, 6, 7], [5, 9, 1]], [[8, 3, 4], [6, 2, 7], [9, 1, 5]], [[8, 3, 4], [7, 2, 6], [9, 1, 5]], [[8, 3, 4], [7, 6, 2], [5, 9, 1]], [[8, 3, 4], [9, 5, 1], [6, 7, 2]], [[8, 4, 3], [1, 5, 9], [7, 6, 2]], [[8, 4, 3], [9, 5, 1], [7, 6, 2]], [[8, 6, 1], [3, 5, 7], [9, 4, 2]], [[8, 6, 1], [7, 5, 3], [9, 4, 2]], [[9, 1, 5], [3, 4, 8], [6, 7, 2]], [[9, 1, 5], [6, 2, 7], [8, 3, 4]], [[9, 1, 5], [7, 2, 6], [8, 3, 4]], [[9, 1, 5], [8, 4, 3], [6, 7, 2]], [[9, 2, 4], [3, 5, 7], [6, 8, 1]], [[9, 2, 4], [7, 5, 3], [6, 8, 1]], [[9, 4, 2], [3, 5, 7], [8, 6, 1]], [[9, 4, 2], [7, 5, 3], [8, 6, 1]]]
c=getMinimumCost(m,ms)
#print(c)
a1=[[4,9,2],
[3,5,7],
[8,1,5]]
a2=[[4,8,2],
[4,5,7],
[6,1,6]]
a3=[[5,3,4],
[1,5,8],
[6,4,2]]
a4=[[1, 6, 8], [3, 5, 7], [2, 4, 9]]
print(a4[:][0])
print(a4[:][1])
print(a4[0][:])
print(isMagicSquare(a4))
c=getMinimumCost(a3,ms)
print(c)
#a=getRandomSudokuSquare()
#print(a)
#print(isMagicSquare(a))
+2
View File
@@ -0,0 +1,2 @@
import sys
print(sys.version)
+3
View File
@@ -0,0 +1,3 @@
#--coding:utf-8--
print('é')