code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
#! /usr/bin/python
from random import randint
from random import choice
INSTANCIAS = 70
MAX_CLAUS = 300
MAX_VARS = 40
MAX_VARS_POR_CLAUS = 10
f = open("hard_big.in",'w')
clausulas=open("hard_big_tamanios",'w')
for i in xrange(INSTANCIAS):
c = randint(1,MAX_CLAUS)
clausulas.write(str(c)+"\n")
v = randint(1,MAX_VARS)
f.write("%d %d\r\n"%(c,v))
mvpc=randint(3,MAX_VARS_POR_CLAUS)
for j in xrange(c):
l = randint(1,mvpc)
f.write(" %d\t\t"%l)
for k in xrange(l):
s = choice([-1,1])
f.write((s>0 and " " or "")+"%d\t"%(s*randint(1,v)))
f.write('\r\n')
f.write('-1 -1\r\n')
f.close()
| [
[
1,
0,
0.0667,
0.0333,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.1,
0.0333,
0,
0.66,
0.1,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.1667,
0.0333,
0,
0.66,... | [
"from random import randint",
"from random import choice",
"INSTANCIAS = 70",
"MAX_CLAUS = 300",
"MAX_VARS = 40",
"MAX_VARS_POR_CLAUS = 10",
"f = open(\"hard_big.in\",'w')",
"clausulas=open(\"hard_big_tamanios\",'w')",
"for i in xrange(INSTANCIAS):\n\tc = randint(1,MAX_CLAUS)\n\tclausulas.write(str(... |
#! /usr/bin/python
files=["exacto.out","constructiva.out","busq_local.out","tabu.out"]
f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
| [
[
14,
0,
0.75,
0.25,
0,
0.66,
0,
598,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
1,
0.25,
0,
0.66,
1,
899,
3,
1,
0,
0,
837,
10,
9
]
] | [
"files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]",
"f=open(\"data.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))"
] |
#! /usr/bin/python
from random import randint
from random import choice
INSTANCIAS = 1
MAX_CLAUS = 300
MAX_VARS = 300
MAX_VARS_POR_CLAUS = 3
f = open("hard.in",'w')
for i in xrange(INSTANCIAS):
c = randint(1,MAX_CLAUS)
v = randint(1,MAX_VARS)
f.write("%d %d\r\n"%(c,v))
for j in xrange(c):
l = randint(1,randint(2,MAX_VARS_POR_CLAUS))
f.write(" %d\t\t"%l)
for k in xrange(l):
s = choice([-1,1])
f.write((s>0 and " " or "")+"%d\t"%(s*randint(1,v)))
f.write('\r\n')
f.write('-1 -1\r\n')
f.close()
| [
[
1,
0,
0.0741,
0.037,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.1111,
0.037,
0,
0.66,
0.1111,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.1852,
0.037,
0,
0.... | [
"from random import randint",
"from random import choice",
"INSTANCIAS = 1",
"MAX_CLAUS = 300",
"MAX_VARS = 300",
"MAX_VARS_POR_CLAUS = 3",
"f = open(\"hard.in\",'w')",
"for i in xrange(INSTANCIAS):\n\tc = randint(1,MAX_CLAUS)\n\tv = randint(1,MAX_VARS)\n\tf.write(\"%d %d\\r\\n\"%(c,v))\n\tfor j in xr... |
#!/usr/bin/env python
from matplotlib.pyplot import *
fin=open('instance80_24/data.dat')
todo=fin.read().strip().split('\n')
xs=[int(x.split()[0]) for x in todo if x]
exacto=[int(x.split()[0]) for x in todo if x]
constru=[int(x.split()[1]) for x in todo if x]
local=[int(x.split()[2]) for x in todo if x]
tabu=[int(x.split()[3]) for x in todo if x]
#title("Cantidad de operaciones de $matching$")
xlabel("exacto")
ylabel("cs")
#plot(xs,exacto,'k.',label="exacto")
plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva")
plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local")
plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu")
#plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
ylim(ymax=1.1)
#savefig('ej1_counts.png',dpi=640./8)
show()
| [
[
1,
0,
0.0909,
0.0455,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.1818,
0.0455,
0,
0.66,
0.0667,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.2273,
0.0455,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('instance80_24/data.dat')",
"todo=fin.read().strip().split('\\n')",
"xs=[int(x.split()[0]) for x in todo if x]",
"exacto=[int(x.split()[0]) for x in todo if x]",
"constru=[int(x.split()[1]) for x in todo if x]",
"local=[int(x.split()[2]) for x in todo if x]",... |
#! /usr/bin/python
files=["constructiva_big.out","busq_local_big.out","tabu_big.out"]
f=open("data_big.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
| [
[
14,
0,
0.75,
0.25,
0,
0.66,
0,
598,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
1,
0.25,
0,
0.66,
1,
899,
3,
1,
0,
0,
837,
10,
9
]
] | [
"files=[\"constructiva_big.out\",\"busq_local_big.out\",\"tabu_big.out\"]",
"f=open(\"data_big.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))"
] |
#!/usr/bin/env python
from matplotlib.pyplot import *
fin=open('data_big.dat')
tam=open('hard_big_tamanios')
todo=fin.read().strip().split('\n')
#xs=tam.read().split()
constru=[int(x.split()[0]) for x in todo if x]
local=[int(x.split()[1]) for x in todo if x]
xs=tabu=[int(x.split()[2]) for x in todo if x]
title("Comparacion de los algoritmos vs Tabu Search")
xlabel("# Clausulas satisfechas por tabu")
ylabel("fraccion de # Clausulas satisfechas por tabu")
#plot(xs,exacto,'k.',label="exacto")
plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva")
plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local")
plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu")
#plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
ylim(ymax=1.01)
savefig('plot_todos_vs_tabu.png',dpi=640./8)
show()
| [
[
1,
0,
0.087,
0.0435,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.1739,
0.0435,
0,
0.66,
0.0625,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.2174,
0.0435,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('data_big.dat')",
"tam=open('hard_big_tamanios')",
"todo=fin.read().strip().split('\\n')",
"constru=[int(x.split()[0]) for x in todo if x]",
"local=[int(x.split()[1]) for x in todo if x]",
"xs=tabu=[int(x.split()[2]) for x in todo if x]",
"title(\"Comparaci... |
#!/usr/bin/env python
from matplotlib.pyplot import *
files=["exacto.out","constructiva.out","busq_local.out","tabu.out"]
data = "\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])])
todo=data.strip().split('\n')
xs=[int(x.split()[0]) for x in todo if x]
exacto=[int(x.split()[0]) for x in todo if x]
constru=[int(x.split()[1]) for x in todo if x]
local=[int(x.split()[2]) for x in todo if x]
tabu=[int(x.split()[3]) for x in todo if x]
title("Comparacion de algoritmos de max-sat")
xlabel("# Clausulas satisfacibles")
ylabel("# Clausulas satisfechas")
#plot(xs,exacto,'k.',label="exacto")
plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva")
plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local")
plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu")
#plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
ylim(ymax=1.02)
savefig('plot_todos_vs_exacto.png',dpi=640./8)
show()
| [
[
1,
0,
0.087,
0.0435,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.1739,
0.0435,
0,
0.66,
0.0556,
598,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
0.2174,
0.0435,
0,
0... | [
"from matplotlib.pyplot import *",
"files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]",
"data = \"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])])",
"todo=data.strip().split('\\n')",
"xs=[int(x.split()[0]) for x in todo if x]",... |
#! /usr/bin/python
files=["exacto.out","constructiva.out","busq_local.out","tabu.out"]
f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
| [
[
14,
0,
0.75,
0.25,
0,
0.66,
0,
598,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
1,
0.25,
0,
0.66,
1,
899,
3,
1,
0,
0,
837,
10,
9
]
] | [
"files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]",
"f=open(\"data.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))"
] |
#!/usr/bin/env python
from matplotlib.pyplot import *
files=["exacto.out","constructiva.out","busq_local.out","tabu.out"]
data = "\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])])
todo=data.strip().split('\n')
xs=[int(x.split()[0]) for x in todo if x]
exacto=[int(x.split()[0]) for x in todo if x]
constru=[int(x.split()[1]) for x in todo if x]
local=[int(x.split()[2]) for x in todo if x]
tabu=[int(x.split()[3]) for x in todo if x]
title("Comparacion de algoritmos de max-sat")
xlabel("# Clausulas satisfacibles")
ylabel("# Clausulas satisfechas")
#plot(xs,exacto,'k.',label="exacto")
plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva")
plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local")
plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu")
#plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
ylim(ymax=1.02)
savefig('plot_todos_vs_exacto.png',dpi=640./8)
show()
| [
[
1,
0,
0.087,
0.0435,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.1739,
0.0435,
0,
0.66,
0.0556,
598,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
0.2174,
0.0435,
0,
0... | [
"from matplotlib.pyplot import *",
"files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]",
"data = \"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])])",
"todo=data.strip().split('\\n')",
"xs=[int(x.split()[0]) for x in todo if x]",... |
#! /usr/bin/python
files=["exacto.out","constructiva.out","busq_local.out","tabu.out"]
f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
| [
[
14,
0,
0.75,
0.25,
0,
0.66,
0,
598,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
1,
0.25,
0,
0.66,
1,
899,
3,
1,
0,
0,
837,
10,
9
]
] | [
"files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]",
"f=open(\"data.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))"
] |
#!/usr/bin/env python
from matplotlib.pyplot import *
#fin=open('instance80_24/data.dat')
fin=open('p_iter1.dat')
todo=fin.read().strip().split('\n')
xs=[int(x.split()[0]) for x in todo if x]
ys=[int(x.split()[1]) for x in todo if x]
#title("Cantidad de operaciones de $matching$")
xlabel("MAX_ITER")
ylabel("clausulas satisfechas")
#plot(xs,exacto,'k.',label="exacto")
plot(xs,ys,'ro',label="tabu")
#plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
#ylim(ymax=89,ymin=83)
savefig('MAX_ITER.png',dpi=640./8)
show()
| [
[
1,
0,
0.1111,
0.0556,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2778,
0.0556,
0,
0.66,
0.1,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3333,
0.0556,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('p_iter1.dat')",
"todo=fin.read().strip().split('\\n')",
"xs=[int(x.split()[0]) for x in todo if x]",
"ys=[int(x.split()[1]) for x in todo if x]",
"xlabel(\"MAX_ITER\")",
"ylabel(\"clausulas satisfechas\")",
"plot(xs,ys,'ro',label=\"tabu\")",
"legend(loc=... |
#!/usr/bin/env python
from matplotlib.pyplot import *
#fin=open('instance80_24/data.dat')
fin=open('p_iter1.dat')
todo=fin.read().strip().split('\n')
xs=[int(x.split()[0]) for x in todo if x]
ys=[int(x.split()[1]) for x in todo if x]
#title("Cantidad de operaciones de $matching$")
xlabel("MAX_ITER")
ylabel("clausulas satisfechas")
#plot(xs,exacto,'k.',label="exacto")
plot(xs,ys,'ro',label="tabu")
#plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
#ylim(ymax=89,ymin=83)
savefig('MAX_ITER.png',dpi=640./8)
show()
| [
[
1,
0,
0.1111,
0.0556,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2778,
0.0556,
0,
0.66,
0.1,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.3333,
0.0556,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('p_iter1.dat')",
"todo=fin.read().strip().split('\\n')",
"xs=[int(x.split()[0]) for x in todo if x]",
"ys=[int(x.split()[1]) for x in todo if x]",
"xlabel(\"MAX_ITER\")",
"ylabel(\"clausulas satisfechas\")",
"plot(xs,ys,'ro',label=\"tabu\")",
"legend(loc=... |
#! /usr/bin/python
from random import randint
from random import choice
INSTANCIAS = 1
MAX_CLAUS = 300
MAX_VARS = 300
MAX_VARS_POR_CLAUS = 3
f = open("hard.in",'w')
for i in xrange(INSTANCIAS):
c = randint(1,MAX_CLAUS)
v = randint(1,MAX_VARS)
f.write("%d %d\r\n"%(c,v))
for j in xrange(c):
l = randint(1,randint(2,MAX_VARS_POR_CLAUS))
f.write(" %d\t\t"%l)
for k in xrange(l):
s = choice([-1,1])
f.write((s>0 and " " or "")+"%d\t"%(s*randint(1,v)))
f.write('\r\n')
f.write('-1 -1\r\n')
f.close()
| [
[
1,
0,
0.0741,
0.037,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.1111,
0.037,
0,
0.66,
0.1111,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.1852,
0.037,
0,
0.... | [
"from random import randint",
"from random import choice",
"INSTANCIAS = 1",
"MAX_CLAUS = 300",
"MAX_VARS = 300",
"MAX_VARS_POR_CLAUS = 3",
"f = open(\"hard.in\",'w')",
"for i in xrange(INSTANCIAS):\n\tc = randint(1,MAX_CLAUS)\n\tv = randint(1,MAX_VARS)\n\tf.write(\"%d %d\\r\\n\"%(c,v))\n\tfor j in xr... |
#!/usr/bin/env python
from matplotlib.pyplot import *
#fin=open('instance80_24/data.dat')
fin=open('data_tiempos.dat')
todo=fin.read().strip().split('\n')
xs=[int(x.split()[0]) for x in todo if x]
exacto=[int(x.split()[0]) for x in todo if x]
constru=[int(x.split()[1]) for x in todo if x]
local=[int(x.split()[2]) for x in todo if x]
tabu=[int(x.split()[3]) for x in todo if x]
#title("Cantidad de operaciones de $matching$")
xlabel("exacto")
ylabel("cs")
#plot(xs,exacto,'k.',label="exacto")
plot(xs,constru,'gx',label="constructiva")
plot(xs,local,'b+',label="busqueda local")
plot(xs,tabu,'r.',label="tabu")
#plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
#ylim(ymax=1.1)
savefig('tiempos.png',dpi=640./8)
show()
| [
[
1,
0,
0.087,
0.0435,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2174,
0.0435,
0,
0.66,
0.0667,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.2609,
0.0435,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('data_tiempos.dat')",
"todo=fin.read().strip().split('\\n')",
"xs=[int(x.split()[0]) for x in todo if x]",
"exacto=[int(x.split()[0]) for x in todo if x]",
"constru=[int(x.split()[1]) for x in todo if x]",
"local=[int(x.split()[2]) for x in todo if x]",
"ta... |
#! /usr/bin/python
#files=["exacto.out","constructiva.out","busq_local.out","tabu.out"]
#f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
files=["exacto.log","constructiva.log","busq_local.log","tabu.log"]
f=open("data_tiempos.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n") for f in files])]))
| [
[
14,
0,
0.8571,
0.1429,
0,
0.66,
0,
598,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
1,
0.1429,
0,
0.66,
1,
899,
3,
1,
0,
0,
837,
10,
9
]
] | [
"files=[\"exacto.log\",\"constructiva.log\",\"busq_local.log\",\"tabu.log\"]",
"f=open(\"data_tiempos.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\") for f in files])]))"
] |
#!/usr/bin/env python
from matplotlib.pyplot import *
#fin=open('instance80_24/data.dat')
fin=open('data_tiempos.dat')
todo=fin.read().strip().split('\n')
xs=[int(x.split()[0]) for x in todo if x]
exacto=[int(x.split()[0]) for x in todo if x]
constru=[int(x.split()[1]) for x in todo if x]
local=[int(x.split()[2]) for x in todo if x]
tabu=[int(x.split()[3]) for x in todo if x]
#title("Cantidad de operaciones de $matching$")
xlabel("exacto")
ylabel("cs")
#plot(xs,exacto,'k.',label="exacto")
plot(xs,constru,'gx',label="constructiva")
plot(xs,local,'b+',label="busqueda local")
plot(xs,tabu,'r.',label="tabu")
#plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
#ylim(ymax=1.1)
savefig('tiempos.png',dpi=640./8)
show()
| [
[
1,
0,
0.087,
0.0435,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.2174,
0.0435,
0,
0.66,
0.0667,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.2609,
0.0435,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('data_tiempos.dat')",
"todo=fin.read().strip().split('\\n')",
"xs=[int(x.split()[0]) for x in todo if x]",
"exacto=[int(x.split()[0]) for x in todo if x]",
"constru=[int(x.split()[1]) for x in todo if x]",
"local=[int(x.split()[2]) for x in todo if x]",
"ta... |
#! /usr/bin/python
#files=["exacto.out","constructiva.out","busq_local.out","tabu.out"]
#f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
files=["exacto.log","constructiva.log","busq_local.log","tabu.log"]
f=open("data_tiempos.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n") for f in files])]))
| [
[
14,
0,
0.8571,
0.1429,
0,
0.66,
0,
598,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
1,
0.1429,
0,
0.66,
1,
899,
3,
1,
0,
0,
837,
10,
9
]
] | [
"files=[\"exacto.log\",\"constructiva.log\",\"busq_local.log\",\"tabu.log\"]",
"f=open(\"data_tiempos.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\") for f in files])]))"
] |
#! /usr/bin/python
files=["exacto.out","constructiva.out","busq_local.out","tabu.out"]
f=open("data.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
| [
[
14,
0,
0.75,
0.25,
0,
0.66,
0,
598,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
1,
0.25,
0,
0.66,
1,
899,
3,
1,
0,
0,
837,
10,
9
]
] | [
"files=[\"exacto.out\",\"constructiva.out\",\"busq_local.out\",\"tabu.out\"]",
"f=open(\"data.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))"
] |
#! /usr/bin/python
files=["constructiva_big.out","busq_local_big.out","tabu_big.out"]
f=open("data_big.dat",'w').write("\n".join([" ".join(map(str,z)) for z in zip(*[open(f).read().split("\n")[::3] for f in files])]))
| [
[
14,
0,
0.75,
0.25,
0,
0.66,
0,
598,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
1,
0.25,
0,
0.66,
1,
899,
3,
1,
0,
0,
837,
10,
9
]
] | [
"files=[\"constructiva_big.out\",\"busq_local_big.out\",\"tabu_big.out\"]",
"f=open(\"data_big.dat\",'w').write(\"\\n\".join([\" \".join(map(str,z)) for z in zip(*[open(f).read().split(\"\\n\")[::3] for f in files])]))"
] |
#!/usr/bin/env python
from matplotlib.pyplot import *
fin=open('data_big.dat')
tam=open('hard_big_tamanios')
todo=fin.read().strip().split('\n')
#xs=tam.read().split()
constru=[int(x.split()[0]) for x in todo if x]
local=[int(x.split()[1]) for x in todo if x]
xs=tabu=[int(x.split()[2]) for x in todo if x]
title("Comparacion de los algoritmos vs Tabu Search")
xlabel("# Clausulas satisfechas por tabu")
ylabel("fraccion de # Clausulas satisfechas por tabu")
#plot(xs,exacto,'k.',label="exacto")
plot(xs,[constru[i]/float(xs[i]) for i in xrange(len(xs))],'gx',label="constructiva")
plot(xs,[local[i]/float(xs[i]) for i in xrange(len(xs))],'b+',label="busqueda local")
plot(xs,[tabu[i]/float(xs[i]) for i in xrange(len(xs))],'r.',label="tabu")
#plot(xs,[x*5.5+60 for x in xs],label=r"$c \times x$")
legend(loc=0)
ylim(ymax=1.01)
savefig('plot_todos_vs_tabu.png',dpi=640./8)
show()
| [
[
1,
0,
0.087,
0.0435,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.1739,
0.0435,
0,
0.66,
0.0625,
225,
3,
1,
0,
0,
693,
10,
1
],
[
14,
0,
0.2174,
0.0435,
0,
... | [
"from matplotlib.pyplot import *",
"fin=open('data_big.dat')",
"tam=open('hard_big_tamanios')",
"todo=fin.read().strip().split('\\n')",
"constru=[int(x.split()[0]) for x in todo if x]",
"local=[int(x.split()[1]) for x in todo if x]",
"xs=tabu=[int(x.split()[2]) for x in todo if x]",
"title(\"Comparaci... |
from random import randint
def mprint(m):
return '\n'.join(map(lambda x:''.join([el and '#' or '_' for el in x]),m))
fout=open('test_sanos.in','w')
for n in range(6,40):
for caso in range(10):
M=[[0]*n for el in range(n)]
ks=[]
for cuad in range(randint(5,2*n)):
ki=randint(2,n/4+1)
if ki%2==1: ki+=randint(0,10)<5 and 1 or -1
kj=randint(2,n/4+1)
i,j=randint(0,n-ki),randint(0,n-kj)
ok=True
for unki,unkj,uni,unj in ks:
#if (unj-1<=j<=unkj+unj+1 and uni-1<=i<=unki+uni+1) or (unj-1<=kj+j<=unkj+unj+1 and uni-1<=ki+i<=unki+uni+1) or (unj-1<=kj+j<=unkj+unj+1 and uni-1<=i<=unki+uni+1) or (unj-1<=j<=unkj+unj+1 and uni-1<=ki+i<=unki+uni+1): ok=False
for ii in range(i,i+ki):
for jj in range(j,j+kj):
if M[ii][jj] or (ii<n-1 and M[ii+1][jj]) or (jj<n-1 and M[ii][jj+1]) or (ii>0 and M[ii-1][jj]) or (jj>0 and M[ii][jj-1]): ok=False
if ok:
ks.append((ki,kj,i,j))
for p in range(i,i+ki):
for l in range(j,j+kj):
M[p][l]=1
fout.write(str(n)+"\n"+mprint(M)+"\n")
fout.write("-1\n\n")
| [
[
1,
0,
0.0333,
0.0333,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
2,
0,
0.1167,
0.0667,
0,
0.66,
0.25,
184,
0,
1,
1,
0,
0,
0,
3
],
[
13,
1,
0.1333,
0.0333,
1,
0.9... | [
"from random import randint",
"def mprint(m):\n\treturn '\\n'.join(map(lambda x:''.join([el and '#' or '_' for el in x]),m))",
"\treturn '\\n'.join(map(lambda x:''.join([el and '#' or '_' for el in x]),m))",
"fout=open('test_sanos.in','w')",
"for n in range(6,40):\n\tfor caso in range(10):\n\t\tM=[[0]*n for... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import random,randint,seed
from math import sqrt
seed(123) # defino el seed para hacer el experimento reproducible
def runtest(li,args):
# abro ./domino con parametros args
fp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for caso,p in li:
fp.stdin.write(str(len(caso))+"\n") # le mando el tamanio
for line in caso:
fp.stdin.write(line+"\n") # le mando la linea de la matriz
r=fp.stdout.readline().rstrip() # recibo el resultado
print "n=",len(caso)," p=",p," ",args[0],"=",r
yield len(caso),p,r # lo devuelvo
fp.stdin.write("-1\n") # le mando un -1 para que termine
def runarchivo(archivo,args):
# abro ./domino con parametros args
fp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
fin=open(archivo)
while 1:
sze=int(fin.readline().rstrip())
if sze<0: break
fp.stdin.write(str(sze)+"\n") # le mando el tamanio
for line in range(sze):
fp.stdin.write(fin.readline()) # le mando la linea de la matriz
r=fp.stdout.readline().rstrip() # recibo el resultado
print "n=",sze," ",args[0],"=",r
yield sze,r # lo devuelvo
fp.stdin.write("-1\n") # le mando un -1 para que termine
def int2matrix(n,l):
res=''
while n>1:
res=(n%2 and '#' or '_') + res
n/=2
res=(n and '#' or '_') + res
return [('_'*(l**2-len(res)) + res)[i:i+l] for i in range(0,l**2,l)]
def randMatrix(n,p): #una matriz al azar con probabilidad p de que cada casilla sea sana
res=[]
for i in range(n):
res.append('')
for j in range(n):
res[i]=(random()<p and '#' or '_') + res[i]
return res
def usage():
print "Usage:"
print "-t (o --time) para calcular tiempos"
print "-c (o --count) para contar operaciones"
sys.exit(2)
try:
opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"])
except getopt.GetoptError, err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
if not opts: usage()
opts=map(lambda x: x[0],opts)
# genero la lista de los casos de prueba
ms=[(randMatrix(n,p/20.),p/20.) for n in range(1,9) for p in range(1,20,1) for re in range(15)]
out=""
if "--time" in opts or "-t" in opts:
for i in runarchivo("test_sanos.in",['time','0.003','3']): # para cada caso de prueba...
vals=map(float,i[1].split()) # obtengo la lista de los tiempos
val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el promedio
err=max([abs(x-val) for x in vals]) # calculo el error
dat = (str(i[0])+"\t" + "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida
out += dat
open('time_err_sanos.dat','w').write("# N\tP\tTIEMPO\tERROR\n"+out) # lo guardo en el archivo
print "\nOutput escrito a time_err_sanos.dat"
out=""
if "--count" in opts or "-c" in opts:
for i in runarchivo("test_sanos.in",['count']): #para cada caso de prueba..
dat = str(i[0])+"\t"+"\t"+i[1]+"\n" # lo formateo para la salida
out += dat
open('counts_sanos.dat','w').write("# N\tP\tCOUNT\n"+out) # lo guardo en el archivo
print "\nOutput escrito a counts_sanos.dat"
out=""
notli=[303,305,318,325,328,331,338,360,362,363,370,374,376,383,384,385,391,393,397,400,403,411,414,415,417,423,425,428,431,436,438,441,442,450,452,457,458,459,462,466,470,471,473,474,475,481,485,491,492,496,498,500,505,507,511,512,513,514,515,516,518,519,522,524,525,526,527,529,531,532,534,536,537,538,539,540,541,542,546,548,550,553,554,556,557,558,559,560,562,563,564,565,566,567,568,569,594,605,606,607,618,626,629,639,649,650,651,653,656,659,670,675,680,685,687,696,700,703,704,711,722,729,731,735,742,745,746,752,753,754,756,758,769,773,776,779,786,790,792,793,794,801,802,803,806,812,815,817,821,834,841,849,851,859,880,882,886,892,894,895,900,901,908,918,923,925,926,931,938,941,948,954,961,967,971,975,979,988,991,993,994,1002,1007,1008,1012,1017,1021,1023,1038,1041,1042,1045,1050,1056,1060,1062,1063,1075,1086,1101,1102,1106,1110,1111,1112,1120,1122,1127,1129,1131,1132,1133,1134,1135,1136,1137,1138,1141,1144,1153,1156,1164,1165,1167,1168,1177,1183,1184,1185,1189,1193,1194,1201,1214,1221,1231,1239,1260,1275,1285,1286,1294,1308,1310,1326,1327,1344,1347,1356,1362,1379,1380,1390,1415,1418,1420,1426,1428,1429,1431,1432,1437,1447,1456,1460,1464,1469,1475,1481,1488,1497,1503,1513,1515,1527,1529,1532,1534,1538,1555,1579,1584,1622,1648,1649,1671,1677,1678,1681,1688,1692,1695,1700,1701,1706,1707,1713,1715,1716,1721,1734,1735,1738,1750,1751,1762,1765,1777,1779,1793,1794,1808,1829,1830,1837,1843,1846,1850,1856,1882,1884,1889,1890,1908,1912,1917,1919,1934,1938,1939,1943,1958,1968,1976,1977,1981,1992,1994,1995,1999,2002,2003,2009,2027,2035,2039,2040,2042,2048,2066,2071,2079,2080,2081,2086,2109,2113,2130,2131,2137,2139,2141,2150,2151,2166,2175,2176,2178,2192,2199,2200,2208,2213,2232,2246,2263,2265,2266,2273,2277,2278,2279]
for m in range(len(ms)):
if m not in notli:
out+=str(len(ms[m][0]))+"\n"
for line in ms[m][0]:
out+=line+"\n"
open('test_imposibles.in','w').write(out+"-1\n")
| [
[
1,
0,
0.0179,
0.0179,
0,
0.66,
0,
588,
0,
2,
0,
0,
588,
0,
0
],
[
1,
0,
0.0357,
0.0179,
0,
0.66,
0.125,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.0536,
0.0179,
0,
0... | [
"import getopt,sys",
"import subprocess",
"from random import random,randint,seed",
"from math import sqrt",
"def runtest(li,args):\n\t# abro ./domino con parametros args\n\tfp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n\tfor caso,p in li:\n\t\tfp.stdin.w... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import random,randint,seed
from math import sqrt
def runtest(li,args):
# abro ./domino con parametros args
fp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for caso,p in li:
fp.stdin.write(str(len(caso))+"\n") # le mando el tamanio
for line in caso:
fp.stdin.write(line+"\n") # le mando la linea de la matriz
r=fp.stdout.readline().rstrip() # recibo el resultado
print "n=",len(caso)," p=",p," ",args[0],"=",r
yield len(caso),p,r # lo devuelvo
fp.stdin.write("-1\n") # le mando un -1 para que termine
def int2matrix(n,l):
res=''
while n>1:
res=(n%2 and '#' or '_') + res
n/=2
res=(n and '#' or '_') + res
return [('_'*(l**2-len(res)) + res)[i:i+l] for i in range(0,l**2,l)]
def randMatrix(n,p): #una matriz al azar con probabilidad p de que cada casilla sea sana
res=[]
for i in range(n):
res.append('')
for j in range(n):
res[i]=(random()<p and '#' or '_') + res[i]
return res
def usage():
print "Usage:"
print "-t (o --time) para calcular tiempos"
print "-c (o --count) para contar operaciones"
sys.exit(2)
try:
opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"])
except getopt.GetoptError, err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
if not opts: usage()
opts=map(lambda x: x[0],opts)
seed(123) # defino el seed para hacer el experimento reproducible
# genero la lista de los casos de prueba
ms=[(randMatrix(n,p/20.),p/20.) for n in range(1,9) for p in range(1,20,1) for re in range(15)]
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(ms,['time','0.003','3']): # para cada caso de prueba...
vals=map(float,i[2].split()) # obtengo la lista de los tiempos
val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el promedio
err=max([abs(x-val) for x in vals]) # calculo el error
dat = (str(i[0])+"\t"+ "%.1f"%i[1] +"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida
out += dat
open('time_err.dat','w').write("# N\tP\tTIEMPO\tERROR\n"+out) # lo guardo en el archivo
print "\nOutput escrito a time_err.dat"
out=""
if "--count" in opts or "-c" in opts:
for i in runtest(ms,['count']): #para cada caso de prueba..
dat = str(i[0])+"\t"+("%.1f"%i[1])+"\t"+i[2]+"\n" # lo formateo para la salida
out += dat
open('counts.dat','w').write("# N\tP\tCOUNT\n"+out) # lo guardo en el archivo
print "\nOutput escrito a counts.dat"
out=""
for caso,p in ms:
out+=str(len(caso))+"\n"
for line in caso:
out+=line+"\n"
open('test.in','w').write(out+"-1\n")
| [
[
1,
0,
0.0244,
0.0244,
0,
0.66,
0,
588,
0,
2,
0,
0,
588,
0,
0
],
[
1,
0,
0.0488,
0.0244,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.0732,
0.0244,
0,
... | [
"import getopt,sys",
"import subprocess",
"from random import random,randint,seed",
"from math import sqrt",
"def runtest(li,args):\n\t# abro ./domino con parametros args\n\tfp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n\tfor caso,p in li:\n\t\tfp.stdin.w... |
from math import cos,pi,sqrt
def pretty(m):
#funcion que imprime una matriz
print '\n'.join([' '.join(map(str,line)) for line in m])
def productoria(li):
return reduce(lambda x,y:x*y, li, 1)
def sano(n):
#algoritmo magico :D
return int(round(productoria([sqrt(sqrt(4*cos(pi*j/(n+1))**2+4*cos(pi*k/(n+1))**2)) for k in range(1,n+1) for j in range(1,n+1)])))
f=open('Tp1Ej3.in') #abro archivo de entrada
while True: #recorro los casos de prueba
n=int(f.readline()) #n es el tamanio del array
if n<0: break #n==-1 significa que se acabaron los casos
m=[[x=='#' and 1 or 0 for x in f.readline().strip()] for line in range(n)] # en m guardo la matriz (lista de listas)
# 1 es una celda sana libre. 0 es una celda rota. x es celda ocupada. v es ficha vertical. h es ficha horizontal
if reduce(lambda x,y: x and y,reduce(lambda x,y:x+y, m)): #chequeo si esta toda sana
print sano(n) #si esta toda sana uso el algoritmo copado :P
continue #y paso al proximo caso
acc=0 # contador de las distintas posibilidades
pos=0 # posicion en la que estoy parado (entre 0 y n*n) (pos%n es la columna, pos/n es la fila)
direccion=1 #direccion en la que estoy recorriendo. empiezo yendo para adelante
while True:
if pos==n*n: # se termino el tablero!
acc+=1 # es porque encontre una solucion
pos-=1 #vuelvo 1
direccion=-1 #empiezo a ir para atras (para cambiar algunas fichas de lugar)
elif pos==-1: #termine!!!!
break #salgo del loop
i,j=pos/n,pos%n # i,j son los indices en la matriz (dada la pos)
if direccion==1: #si estoy yendo para adelante..
if m[i][j]==1: #si esta posicion esta sana..
if i<n-1 and m[i+1][j]==1: #si hay espacio para poner una ficha verticalmente
m[i][j]='v' # marco esta posicion con una v
m[i+1][j]='x' # y marco la posicion de abajo como ocupada
elif j<n-1 and m[i][j+1]==1: #si hay espacio para poner una ficha horizontalmente
m[i][j]='h' # marco esta posicion con una h
m[i][j+1]='x' # y marco la posicion de al lado como ocupada
pos+=1 # de paso aumento el pos porque es obvio que la proxima esta ocupada..
i,j=pos/n,pos%n #actualizo los indices..
else: # no hay espacio para poner una ficha!! este camino no anduvo!
i,j=pos/n,pos%n #actualizo los indices..
direccion=-1 # empiezo a ir para atras.
else: # si estaba ocupada o rota
pass #no hago nada :P
else: #si estoy yendo para atras..
if m[i][j]=='v': #si me encuentro con una ficha puesta verticalmente..
#voy a probar de poner esta ficha horizontalmente
if j<n-1 and m[i][j+1]:
m[i+1][j]=1 #saco la ficha vertical que estaba
m[i][j]='h' #pongo una horizontal
m[i][j+1]='x' #(y ocupo la proxima celda)
direccion=1 # y empiezo a ir para adelante buscando combinaciones nuevas
else: #si no puedo ponerla horizontalmente
m[i][j]=1 #saco la anterior
m[i+1][j]=1
elif m[i][j]=='h': #si me encuentro con una ficha puesta horizontalmente..
m[i][j]=1 # la saco
m[i][j+1]=1
pos+=direccion #me muevo una celda en el sentido de la direccion
print acc
| [
[
1,
0,
0.0139,
0.0139,
0,
0.66,
0,
526,
0,
3,
0,
0,
526,
0,
0
],
[
2,
0,
0.0556,
0.0417,
0,
0.66,
0.2,
369,
0,
1,
0,
0,
0,
0,
4
],
[
8,
1,
0.0694,
0.0139,
1,
0.28,... | [
"from math import cos,pi,sqrt",
"def pretty(m):\n\t#funcion que imprime una matriz\n\tprint('\\n'.join([' '.join(map(str,line)) for line in m]))",
"\tprint('\\n'.join([' '.join(map(str,line)) for line in m]))",
"def productoria(li):\n\treturn reduce(lambda x,y:x*y, li, 1)",
"\treturn reduce(lambda x,y:x*y, ... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import random,randint,seed
from math import sqrt
def runtest(li,args):
# abro ./domino con parametros args
fp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for caso,p in li:
fp.stdin.write(str(len(caso))+"\n") # le mando el tamanio
for line in caso:
fp.stdin.write(line+"\n") # le mando la linea de la matriz
r=fp.stdout.readline().rstrip() # recibo el resultado
print "n=",len(caso)," p=",p," ",args[0],"=",r
yield len(caso),p,r # lo devuelvo
fp.stdin.write("-1\n") # le mando un -1 para que termine
def int2matrix(n,l):
res=''
while n>1:
res=(n%2 and '#' or '_') + res
n/=2
res=(n and '#' or '_') + res
return [('_'*(l**2-len(res)) + res)[i:i+l] for i in range(0,l**2,l)]
def randMatrix(n,p): #una matriz al azar con probabilidad p de que cada casilla sea sana
res=[]
for i in range(n):
res.append('')
for j in range(n):
res[i]=(random()<p and '#' or '_') + res[i]
return res
def usage():
print "Usage:"
print "-t (o --time) para calcular tiempos"
print "-c (o --count) para contar operaciones"
sys.exit(2)
try:
opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"])
except getopt.GetoptError, err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
if not opts: usage()
opts=map(lambda x: x[0],opts)
seed(123) # defino el seed para hacer el experimento reproducible
# genero la lista de los casos de prueba
ms=[(randMatrix(n,p/20.),p/20.) for n in range(1,9) for p in range(1,20,1) for re in range(15)]
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(ms,['time','0.003','3']): # para cada caso de prueba...
vals=map(float,i[2].split()) # obtengo la lista de los tiempos
val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el promedio
err=max([abs(x-val) for x in vals]) # calculo el error
dat = (str(i[0])+"\t"+ "%.1f"%i[1] +"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida
out += dat
open('time_err.dat','w').write("# N\tP\tTIEMPO\tERROR\n"+out) # lo guardo en el archivo
print "\nOutput escrito a time_err.dat"
out=""
if "--count" in opts or "-c" in opts:
for i in runtest(ms,['count']): #para cada caso de prueba..
dat = str(i[0])+"\t"+("%.1f"%i[1])+"\t"+i[2]+"\n" # lo formateo para la salida
out += dat
open('counts.dat','w').write("# N\tP\tCOUNT\n"+out) # lo guardo en el archivo
print "\nOutput escrito a counts.dat"
out=""
for caso,p in ms:
out+=str(len(caso))+"\n"
for line in caso:
out+=line+"\n"
open('test.in','w').write(out+"-1\n")
| [
[
1,
0,
0.0244,
0.0244,
0,
0.66,
0,
588,
0,
2,
0,
0,
588,
0,
0
],
[
1,
0,
0.0488,
0.0244,
0,
0.66,
0.1429,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.0732,
0.0244,
0,
... | [
"import getopt,sys",
"import subprocess",
"from random import random,randint,seed",
"from math import sqrt",
"def runtest(li,args):\n\t# abro ./domino con parametros args\n\tfp=subprocess.Popen(['./domino']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n\tfor caso,p in li:\n\t\tfp.stdin.w... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import randint,seed
from math import sqrt
def runtest(li,args):
# abro ./amigos con parametros: time 0.1 3
fp=subprocess.Popen(['./intervalos']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for i in li:
fp.stdin.write(str(len(i))+"\n"+' '.join(map(str,i))+"\n") # le manda la instancia
r=fp.stdout.readline().rstrip() # recibo el resultado
print "n=",len(i)," ",args[0],"=",r
yield len(i),r # lo devuelvo
fp.stdin.write("-1\n")
def usage():
print "Usage:"
print "-t (o --time) para calcular tiempos"
print "-c (o --count) para contar operaciones"
sys.exit(2)
try:
opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"])
except getopt.GetoptError, err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
if not opts: usage()
opts=map(lambda x: x[0],opts)
seed(1234) # defino el seed para hacer el experimento reproducible
test=open('test.in')
li=[]
while 1:
inst=map(int,test.readline().split())
if inst[0]==-1: break
li.append(inst[1:])
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(li,['time','0.1','3']): # para cada caso de prueba...
vals=map(float,i[1].split()) # obtengo la lista de los tiempos
val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio
err=max([abs(x-val) for x in vals]) # calculo el error
dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida
out += dat
open('time_err.dat','w').write(out) # lo guardo en el archivo
print "\nOutput escrito a time_err.dat"
out=""
if "--count" in opts or "-c" in opts:
for i in runtest(li,['count']): #para cada caso de prueba..
dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida
out += dat
open('counts.dat','w').write(out) # lo guardo en el archivo
print "\nOutput escrito a counts.dat"
| [
[
1,
0,
0.0476,
0.0476,
0,
0.66,
0,
588,
0,
2,
0,
0,
588,
0,
0
],
[
1,
0,
0.0952,
0.0476,
0,
0.66,
0.2,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1429,
0.0476,
0,
0.6... | [
"import getopt,sys",
"import subprocess",
"from random import randint,seed",
"from math import sqrt",
"def runtest(li,args):\n\t# abro ./amigos con parametros: time 0.1 3\n\tfp=subprocess.Popen(['./intervalos']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n\tfor i in li:\n\t\tfp.stdin.wr... |
f=open('Tp1Ej1.in')
while True:
li=map(float,f.readline().rsplit())
if li[0]<0: break
li.pop(0)
li.sort()
mi,count=li.pop(0)+1,1
for x in li:
if x>mi:
count+=1
mi=x+1
print count
| [
[
14,
0,
0.0833,
0.0833,
0,
0.66,
0,
899,
3,
1,
0,
0,
693,
10,
1
],
[
5,
0,
0.5833,
0.9167,
0,
0.66,
1,
0,
1,
0,
0,
0,
0,
0,
7
],
[
14,
1,
0.25,
0.0833,
1,
0.09,
... | [
"f=open('Tp1Ej1.in')",
"while True:\n\tli=map(float,f.readline().rsplit())\n\tif li[0]<0: break\n\tli.pop(0)\n\tli.sort()\n\tmi,count=li.pop(0)+1,1\n\tfor x in li:\n\t\tif x>mi:",
"\tli=map(float,f.readline().rsplit())",
"\tif li[0]<0: break",
"\tli.pop(0)",
"\tli.sort()",
"\tmi,count=li.pop(0)+1,1",
... |
#!/usr/bin/env python
import getopt,sys
import subprocess
from random import randint,seed
from math import sqrt
def runtest(li,args):
# abro ./amigos con parametros: time 0.1 3
fp=subprocess.Popen(['./intervalos']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
for i in li:
fp.stdin.write(str(len(i))+"\n"+' '.join(map(str,i))+"\n") # le manda la instancia
r=fp.stdout.readline().rstrip() # recibo el resultado
print "n=",len(i)," ",args[0],"=",r
yield len(i),r # lo devuelvo
fp.stdin.write("-1\n")
def usage():
print "Usage:"
print "-t (o --time) para calcular tiempos"
print "-c (o --count) para contar operaciones"
sys.exit(2)
try:
opts, args = getopt.getopt(sys.argv[1:], "tc", ["time", "count"])
except getopt.GetoptError, err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
if not opts: usage()
opts=map(lambda x: x[0],opts)
seed(1234) # defino el seed para hacer el experimento reproducible
test=open('test.in')
li=[]
while 1:
inst=map(int,test.readline().split())
if inst[0]==-1: break
li.append(inst[1:])
out=""
if "--time" in opts or "-t" in opts:
for i in runtest(li,['time','0.1','3']): # para cada caso de prueba...
vals=map(float,i[1].split()) # obtengo la lista de los tiempos
val=reduce(lambda x,y:x+y,vals)/len(vals) # tomo el primedio
err=max([abs(x-val) for x in vals]) # calculo el error
dat = (str(i[0])+"\t"+ "%.8f"%val +"\t"+ "%.8f"%err +"\n") # lo preparo para el archivo de salida
out += dat
open('time_err.dat','w').write(out) # lo guardo en el archivo
print "\nOutput escrito a time_err.dat"
out=""
if "--count" in opts or "-c" in opts:
for i in runtest(li,['count']): #para cada caso de prueba..
dat = str(i[0])+"\t"+i[1]+"\n" # lo formateo para la salida
out += dat
open('counts.dat','w').write(out) # lo guardo en el archivo
print "\nOutput escrito a counts.dat"
| [
[
1,
0,
0.0476,
0.0476,
0,
0.66,
0,
588,
0,
2,
0,
0,
588,
0,
0
],
[
1,
0,
0.0952,
0.0476,
0,
0.66,
0.2,
394,
0,
1,
0,
0,
394,
0,
0
],
[
1,
0,
0.1429,
0.0476,
0,
0.6... | [
"import getopt,sys",
"import subprocess",
"from random import randint,seed",
"from math import sqrt",
"def runtest(li,args):\n\t# abro ./amigos con parametros: time 0.1 3\n\tfp=subprocess.Popen(['./intervalos']+args, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE)\n\tfor i in li:\n\t\tfp.stdin.wr... |
#!/usr/bin/python
import random
import sys
for i in range(1):
tanda = random.randint(15,30)
for i in range(tanda):
if i == 0 :
sys.stdout.write('%d' % tanda)
sys.stdout.write(' %d' % random.randint(-20,10))
sys.stdout.write("\n")
| [
[
1,
0,
0.2308,
0.0769,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.3077,
0.0769,
0,
0.66,
0.5,
509,
0,
1,
0,
0,
509,
0,
0
],
[
6,
0,
0.7692,
0.5385,
0,
0.6... | [
"import random",
"import sys",
"for i in range(1):\n\ttanda = random.randint(15,30)\n\tfor i in range(tanda):\n\t\tif i == 0 :\n\t\t\tsys.stdout.write('%d' % tanda)\n\t\tsys.stdout.write(' %d' % random.randint(-20,10))\n\tsys.stdout.write(\"\\n\")",
"\ttanda = random.randint(15,30)",
"\tfor i in range(tanda... |
#!/usr/bin/python
import random
import sys
for i in range(1):
tanda = random.randint(15,30)
for i in range(tanda):
if i == 0 :
sys.stdout.write('%d' % tanda)
sys.stdout.write(' %d' % random.randint(-20,10))
sys.stdout.write("\n")
| [
[
1,
0,
0.2308,
0.0769,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.3077,
0.0769,
0,
0.66,
0.5,
509,
0,
1,
0,
0,
509,
0,
0
],
[
6,
0,
0.7692,
0.5385,
0,
0.6... | [
"import random",
"import sys",
"for i in range(1):\n\ttanda = random.randint(15,30)\n\tfor i in range(tanda):\n\t\tif i == 0 :\n\t\t\tsys.stdout.write('%d' % tanda)\n\t\tsys.stdout.write(' %d' % random.randint(-20,10))\n\tsys.stdout.write(\"\\n\")",
"\ttanda = random.randint(15,30)",
"\tfor i in range(tanda... |
#!/usr/bin/python
#este es el grafo de ejemplo que me genera la matris
# 0 -> 3
# 1 -> 3
# 2 -> 3
# 4 -> 3
# 2 - > 5
adjacencyMatix = [ [0,0,0,1,0,0] , \
[0,0,0,1,0,0] , \
[0,0,0,1,0,0] , \
[1,1,1,0,1,0] , \
[0,0,0,1,0,0] , \
[0,0,1,0,0,0] ]
stations = [0]
def nodeIsConnected(node,parent=None):
global adjacencyMatix
if node in stations:
return True
for i in range(len(adjacencyMatix)):
if i == node or i == parent:
continue
if adjacencyMatix[node][i] and nodeIsConnected(i,node):
return True
# if adjacencyMatix[i][node] && nodeIsConnected(node):
# return True
return False
#aca tengo los 2 nodos mas el peso del eje desordenados
axis = [(0,3,1),(1,3,2),(2,3,5),(2,5,2),(3,4,1)]
#ordeno
axisSorted = sorted(axis, key=lambda a: a[2] )
axisSorted.reverse()
for i in range(len(axis)):
print "%d tiene estacion? -> %d, %d tiene estacion? -> %d" % (axisSorted[i][0],\
nodeIsConnected(axisSorted[i][0]),\
axisSorted[i][1],\
nodeIsConnected(axisSorted[i][1]))
estacionesCant = 3
#para 1 sola estacion esto no se ejecuta
#en el loop parto de la premisa que siempre que saco un eje dejo
#2 componentes en la que de un lado hay una estacion
#en el primer caso tiro la estacion en cualquier nodo
#la primera no me importa
print axisSorted
for i in range(estacionesCant-1):
ax = axisSorted[i]
#tomo el eje lo desconecto
adjacencyMatix[ax[0]][ax[1]] = 0
adjacencyMatix[ax[1]][ax[0]] = 0
#la matriz hay que optimizarla
if nodeIsConnected(ax[0]):
stations.append(ax[1])
else:
stations.append(ax[0])
print stations
print adjacencyMatix | [
[
2,
0,
0.5,
0.9375,
0,
0.66,
0,
292,
0,
2,
1,
0,
0,
0,
3
],
[
4,
1,
0.2812,
0.125,
1,
0.23,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
13,
2,
0.3125,
0.0625,
2,
0.96,
0,
... | [
"def nodeIsConnected(node,parent=None):\n\tglobal adjacencyMatix\n\t\n\tif node in stations:\n\t\treturn True\n\n\tfor i in range(len(adjacencyMatix)):\n\t\tif i == node or i == parent:",
"\tif node in stations:\n\t\treturn True",
"\t\treturn True",
"\tfor i in range(len(adjacencyMatix)):\n\t\tif i == node or... |
#! /usr/bin/env python
import math
def distancia(a,b):
return math.sqrt((int(b[0])-int(a[0]))**2 + (int(b[1])-int(a[1]))**2 )
fo = open("testej2.in", "r")
primeraLinea = fo.readline().split()
#Trato la entrada
n = int(primeraLinea[0])
k = int(primeraLinea[1])
puntos = [] # este es mi arreglo de puntos no se toca
#print n
#print k
for line in fo:
if line != "0":
a = line.split()
puntos.append((int(a[0]),int(a[1])))
fo.close()
#print puntos #Esta es la entrada de puntos
#Recorro siempre de la diagonal para arriba porque no tiene sentido sacar la distancia de del nodo A y B , y despues sacar la del B y A
#ESTO ES SOLO PARA CONTROL son todas las distancias entre aristas diferentes sin repetir calculos
aristas = []
for i in range(0,n-1):
#for j in range(0,n): # para verificar todos los nodos
for j in range(i+1,n):
if i != j:
d = distancia(puntos[i], puntos[j])
aristas.append([i,j,d])
#Recorro siempre de la diagonal para arriba porque no tiene sentido sacar la distancia de del nodo A y B , y despues sacar la del B y A
#ESTA ES LA SOLUCION DEL EJERCICIO
puntosxDist = []# numero de nodo , indice y distancia
for i in range(0,n):
puntosxDist.append([i,-1,-1])
for i in range(0,n-1):
for j in range(i+1,n):
d = distancia(puntos[i], puntos[j])
#encontre una distancia mas corta entonces actualizo el nuevo minimo
if puntosxDist[j][2] == -1 or puntosxDist[j][2] > d :
#Actualizo mis datos
puntosxDist[j][1] = i
puntosxDist[j][2]= d
#Complejidad O(n^2)
#print puntosxDist
#print aristas
fo = open("testej2.out", "wb")
fo.write("Tengo estos puntos\n")
for i in range(0,n):
fo.write(str(puntos[i]))
fo.write("\n\n\n")
fo.write("todas las distancias de todos contra todos\n")
elem = aristas[0][0]
for i in range(0,len(aristas)):
if elem == aristas[i][0]:
fo.write( str(aristas[i]))
else:
elem = aristas[i][0]
fo.write("\n"+ str(aristas[i]))
fo.write("\n\n\n")
fo.write("Nuestra Solucion\n")
for i in range(0,len(puntosxDist)):
fo.write( "nodo " + str(i) + " con: " + str(puntosxDist[i]) + "\n")
| [
[
1,
0,
0.0238,
0.0119,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
2,
0,
0.0536,
0.0238,
0,
0.66,
0.0435,
476,
0,
2,
1,
0,
0,
0,
5
],
[
13,
1,
0.0595,
0.0119,
1,
0... | [
"import math",
"def distancia(a,b):\n\treturn math.sqrt((int(b[0])-int(a[0]))**2 + (int(b[1])-int(a[1]))**2 )",
"\treturn math.sqrt((int(b[0])-int(a[0]))**2 + (int(b[1])-int(a[1]))**2 )",
"fo = open(\"testej2.in\", \"r\")",
"primeraLinea = fo.readline().split()",
"n = int(primeraLinea[0])",
"k = int(pri... |
#!/usr/bin/python
#este es el grafo de ejemplo que me genera la matris
# 0 -> 3
# 1 -> 3
# 2 -> 3
# 4 -> 3
# 2 - > 5
adjacencyMatix = [ [0,0,0,1,0,0] , \
[0,0,0,1,0,0] , \
[0,0,0,1,0,0] , \
[1,1,1,0,1,0] , \
[0,0,0,1,0,0] , \
[0,0,1,0,0,0] ]
stations = [0]
def nodeIsConnected(node,parent=None):
global adjacencyMatix
if node in stations:
return True
for i in range(len(adjacencyMatix)):
if i == node or i == parent:
continue
if adjacencyMatix[node][i] and nodeIsConnected(i,node):
return True
# if adjacencyMatix[i][node] && nodeIsConnected(node):
# return True
return False
#aca tengo los 2 nodos mas el peso del eje desordenados
axis = [(0,3,1),(1,3,2),(2,3,5),(2,5,2),(3,4,1)]
#ordeno
axisSorted = sorted(axis, key=lambda a: a[2] )
axisSorted.reverse()
for i in range(len(axis)):
print "%d tiene estacion? -> %d, %d tiene estacion? -> %d" % (axisSorted[i][0],\
nodeIsConnected(axisSorted[i][0]),\
axisSorted[i][1],\
nodeIsConnected(axisSorted[i][1]))
estacionesCant = 3
#para 1 sola estacion esto no se ejecuta
#en el loop parto de la premisa que siempre que saco un eje dejo
#2 componentes en la que de un lado hay una estacion
#en el primer caso tiro la estacion en cualquier nodo
#la primera no me importa
print axisSorted
for i in range(estacionesCant-1):
ax = axisSorted[i]
#tomo el eje lo desconecto
adjacencyMatix[ax[0]][ax[1]] = 0
adjacencyMatix[ax[1]][ax[0]] = 0
#la matriz hay que optimizarla
if nodeIsConnected(ax[0]):
stations.append(ax[1])
else:
stations.append(ax[0])
print stations
print adjacencyMatix | [
[
2,
0,
0.5,
0.9375,
0,
0.66,
0,
292,
0,
2,
1,
0,
0,
0,
3
],
[
4,
1,
0.2812,
0.125,
1,
0.41,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
13,
2,
0.3125,
0.0625,
2,
0.36,
0,
... | [
"def nodeIsConnected(node,parent=None):\n\tglobal adjacencyMatix\n\t\n\tif node in stations:\n\t\treturn True\n\n\tfor i in range(len(adjacencyMatix)):\n\t\tif i == node or i == parent:",
"\tif node in stations:\n\t\treturn True",
"\t\treturn True",
"\tfor i in range(len(adjacencyMatix)):\n\t\tif i == node or... |
#! /usr/bin/env python
import math
def distancia(a,b):
return math.sqrt((int(b[0])-int(a[0]))**2 + (int(b[1])-int(a[1]))**2 )
fo = open("testej2.in", "r")
primeraLinea = fo.readline().split()
#Trato la entrada
n = int(primeraLinea[0])
k = int(primeraLinea[1])
puntos = [] # este es mi arreglo de puntos no se toca
#print n
#print k
for line in fo:
if line != "0":
a = line.split()
puntos.append((int(a[0]),int(a[1])))
fo.close()
#print puntos #Esta es la entrada de puntos
#Recorro siempre de la diagonal para arriba porque no tiene sentido sacar la distancia de del nodo A y B , y despues sacar la del B y A
#ESTO ES SOLO PARA CONTROL son todas las distancias entre aristas diferentes sin repetir calculos
aristas = []
for i in range(0,n-1):
#for j in range(0,n): # para verificar todos los nodos
for j in range(i+1,n):
if i != j:
d = distancia(puntos[i], puntos[j])
aristas.append([i,j,d])
#Recorro siempre de la diagonal para arriba porque no tiene sentido sacar la distancia de del nodo A y B , y despues sacar la del B y A
#ESTA ES LA SOLUCION DEL EJERCICIO
puntosxDist = []# numero de nodo , indice y distancia
for i in range(0,n):
puntosxDist.append([i,-1,-1])
for i in range(0,n-1):
for j in range(i+1,n):
d = distancia(puntos[i], puntos[j])
#encontre una distancia mas corta entonces actualizo el nuevo minimo
if puntosxDist[j][2] == -1 or puntosxDist[j][2] > d :
#Actualizo mis datos
puntosxDist[j][1] = i
puntosxDist[j][2]= d
#Complejidad O(n^2)
#print puntosxDist
#print aristas
fo = open("testej2.out", "wb")
fo.write("Tengo estos puntos\n")
for i in range(0,n):
fo.write(str(puntos[i]))
fo.write("\n\n\n")
fo.write("todas las distancias de todos contra todos\n")
elem = aristas[0][0]
for i in range(0,len(aristas)):
if elem == aristas[i][0]:
fo.write( str(aristas[i]))
else:
elem = aristas[i][0]
fo.write("\n"+ str(aristas[i]))
fo.write("\n\n\n")
fo.write("Nuestra Solucion\n")
for i in range(0,len(puntosxDist)):
fo.write( "nodo " + str(i) + " con: " + str(puntosxDist[i]) + "\n")
| [
[
1,
0,
0.0238,
0.0119,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
2,
0,
0.0536,
0.0238,
0,
0.66,
0.0435,
476,
0,
2,
1,
0,
0,
0,
5
],
[
13,
1,
0.0595,
0.0119,
1,
0... | [
"import math",
"def distancia(a,b):\n\treturn math.sqrt((int(b[0])-int(a[0]))**2 + (int(b[1])-int(a[1]))**2 )",
"\treturn math.sqrt((int(b[0])-int(a[0]))**2 + (int(b[1])-int(a[1]))**2 )",
"fo = open(\"testej2.in\", \"r\")",
"primeraLinea = fo.readline().split()",
"n = int(primeraLinea[0])",
"k = int(pri... |
#! /usr/bin/env python
from random import randint
#defino el nombre de cada archivo
fo = open("testej2.in", "wb")
n = randint(100,3000) #cantidad de pueblos
k = randint(50,1000) #cantidad de entradas
#primer linea la cantidad de pueblos y centrales
fo.write( str(n) + " " + str(k) +"\n")
#para cada pueblo genero su coordenada x y
for i in range(n):
x = randint(1,1000)
y = randint(1,1000)
fo.write( str(x) + " " + str(y) + "\n")
#ultima linea es un 0 y cierro el archivo
fo.write("0")
fo.close()
| [
[
1,
0,
0.1429,
0.0476,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.3333,
0.0476,
0,
0.66,
0.1429,
542,
3,
2,
0,
0,
693,
10,
1
],
[
14,
0,
0.381,
0.0476,
0,
... | [
"from random import randint",
"fo = open(\"testej2.in\", \"wb\")",
"n = randint(100,3000) #cantidad de pueblos",
"k = randint(50,1000) #cantidad de entradas",
"fo.write( str(n) + \" \" + str(k) +\"\\n\")",
"for i in range(n):\n\tx = randint(1,1000)\n\ty = randint(1,1000)\n\tfo.write( str(x) + \" \" + str(... |
#! /usr/bin/env python
from random import randint
#defino el nombre de cada archivo
fo = open("testej2.in", "wb")
n = randint(100,3000) #cantidad de pueblos
k = randint(50,1000) #cantidad de entradas
#primer linea la cantidad de pueblos y centrales
fo.write( str(n) + " " + str(k) +"\n")
#para cada pueblo genero su coordenada x y
for i in range(n):
x = randint(1,1000)
y = randint(1,1000)
fo.write( str(x) + " " + str(y) + "\n")
#ultima linea es un 0 y cierro el archivo
fo.write("0")
fo.close()
| [
[
1,
0,
0.1429,
0.0476,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.3333,
0.0476,
0,
0.66,
0.1429,
542,
3,
2,
0,
0,
693,
10,
1
],
[
14,
0,
0.381,
0.0476,
0,
... | [
"from random import randint",
"fo = open(\"testej2.in\", \"wb\")",
"n = randint(100,3000) #cantidad de pueblos",
"k = randint(50,1000) #cantidad de entradas",
"fo.write( str(n) + \" \" + str(k) +\"\\n\")",
"for i in range(n):\n\tx = randint(1,1000)\n\ty = randint(1,1000)\n\tfo.write( str(x) + \" \" + str(... |
#!/usr/bin/python
import random
import sys
import string
import os
import time
print sys.getrecursionlimit()
sys.setrecursionlimit(5000)
print sys.getrecursionlimit()
#sys.exit()
#filas
n = 10
#columnas
m = 10
DEBUG=0
def debug(s):
if DEBUG :
print s
# las fichas se numeran asi en sus coordenadas
# 2
# 1 3
# 4
def crearFicha():
return [ random.randint(1,4) for i in range(4) ]
def crearFichaComodin():
return [ 0 for i in range(4) ]
def crearFichaDebug():
return [ 8 for i in range(4) ]
def fichaEncaja(ficha,izquierda=None ,arriba=None):
return ( ( not izquierda or izquierda[2] == ficha[0] or izquierda[2] == 0 ) and
( not arriba or arriba[3] == ficha[1] or arriba[3] == 0 ) )
def printTablero(tablero, index=None):
global n, m, comodinesActual, mejorSolucionComodines
os.system('clear')
defaultBackground = ' '
currentBackground = defaultBackground
for i in range(n):
for t in range(m*6):
sys.stdout.write('-')
sys.stdout.write('\n')
for ii in range(3):
for j in range(m):
if (i*m + j) == index :
currentBackground = chr(64)
else:
currentBackground = defaultBackground
for jj in range(3):
if ii == 0 and jj == 0 :
sys.stdout.write(currentBackground)
if ii == 0 and jj == 2 :
sys.stdout.write(currentBackground)
if ii == 2 and jj == 0 :
sys.stdout.write(currentBackground)
if ii == 2 and jj == 2 :
sys.stdout.write(currentBackground)
if ii == 1 and jj == 1 :
sys.stdout.write(currentBackground)
if ii == 1 and jj == 0:
sys.stdout.write('%s' % tablero[i*m + j][0] )
if ii == 1 and jj == 2:
sys.stdout.write('%s' % tablero[i*m + j][2] )
if ii == 0 and jj == 1:
sys.stdout.write( '%s' % tablero[i*m + j][1] )
if jj == 1 and ii == 2:
sys.stdout.write( '%s' % tablero[i*m + j][3] )
#else:
sys.stdout.write(' | ')
sys.stdout.write("\n")
for t in range(m*6):
sys.stdout.write('-')
sys.stdout.write('- current [%s] mejor [%s]\n' % (comodinesActual,mejorSolucionComodines) )
debug(" ")
time.sleep(0.1)
def esComodin(ficha):
return ficha[0] == 0
def dameFichaQueEncaje(izquierda=None,arriba=None):
global fichas
ficha = None
otras = 0
for f in range(len(fichas)):
if f < len(fichas) and fichaEncaja(fichas[f],izquierda,arriba):
otras += 1
if otras == 1:
ficha=fichas[f]
fichas.remove(ficha)
if otras:
return (otras,ficha)
return (1, crearFichaComodin())
def posicionarFicha(tablero,i,ficha):
tablero[i] = ficha
def getArriba(tablero,i):
if i >= m:
return tablero[i-m]
return crearFichaComodin()
def getIzquierda(tablero,i):
if (i % m ) != 0 :
return tablero[i-1]
return crearFichaComodin()
def encontrarTablero(i):
global comodinesActual, n, m, mejorTablero,mejorSolucionComodines, comodinesUsados
while True:
debug("---------------------- paso %s intento %s comodines %s " % \
(i, intentosPorPosicion[i] if i in intentosPorPosicion else 0 ,comodinesActual))
com = crearFichaComodin()
if com in fichas:
fichas.remove(com)
if i >= n*m:
if comodinesActual < mejorSolucionComodines:
mejorSolucionComodines = comodinesActual
mejorTablero = tableroActual[0:len(tableroActual)]
if len(comodinesUsados):
debug("llegue al final busco mejor solucion")
posUltimoComodin = comodinesUsados.pop_back();
comodinesActual -= 1
for t in range(posUltimoComodin,n*m):
debug("devuelvo fincha ")
intentosPorPosicion[t] = 0
if i != posUltimoComodin:
fichas.push_back(tableroActual[t]);
d = crearFichaDebug()
posicionarFicha(tableroActual,t,d)
#encontrarTablero(posUltimoComodin-1)
#return
i = posUltimoComodin-1
continue
else:
debug("solucion sin comodines !!!!!")
break
debug("cantidad de comodines %s" % mejorSolucionComodines)
break
if i < 0:
debug( "cantidad de comodines %s end" % mejorSolucionComodines)
printTablero(mejorTablero)
break
#############################
if i not in intentosPorPosicion or intentosPorPosicion[i] == 0 :
#avanzo en una rama
izquierda=getIzquierda(tableroActual,i)
arriba=getArriba(tableroActual,i)
ficha = dameFichaQueEncaje(izquierda,arriba)
intentosPorPosicion[i] = ficha[0]
else:
#tuve que volver hacia atras
intentosPorPosicion[i] -= 1
if intentosPorPosicion[i] < 1:
if i == 0:
debug( "cantidad de comodines %s end" % mejorSolucionComodines)
printTablero(mejorTablero)
break
else:
#devuelvo la ficha anterior al las disponibles
intentosPorPosicion[i] = 0
if esComodin(tableroActual[i-1]):
comodinesActual -= 1
comodinesUsados.remove(i-1)
else:
fichas.append(tableroActual[i-1] )
d = crearFichaDebug()
posicionarFicha(tableroActual,i,d)
debug( string.join( [ '%s=>%s ' % (k,v) for k, v in intentosPorPosicion.items() ], ''))
debug("------------------------------ retrocedo por intentos")
#encontrarTablero(i-1)
i = i-1
continue
#return
else:
izquierda=getIzquierda(tableroActual,i)
arriba=getArriba(tableroActual,i)
ficha = dameFichaQueEncaje(izquierda,arriba)
#############################
if esComodin(ficha[1]) :
debug("comodines actual %s comodines mejor %s " % (comodinesActual, mejorSolucionComodines))
if comodinesActual + 1 >= mejorSolucionComodines:
#devuelvo la ficha anterior al las disponibles
if esComodin(tableroActual[i-1]):
comodinesActual -= 1
comodinesUsados.remove(i-1)
else:
fichas.append(tableroActual[i-1] )
intentosPorPosicion[i] = 0
d = crearFichaDebug()
posicionarFicha(tableroActual,i,d)
printTablero(tableroActual,i)
debug(string.join( [ '%s=>%s ' % (k,v) for k, v in intentosPorPosicion.items() ], ''))
debug("------------------------------- retrocedo por comodin")
#intentosPorPosicion[i] = ficha[0]
#encontrarTablero(i-1)
i = i-1
continue
#return
else:
posicionarFicha(tableroActual,i,ficha[1])
comodinesActual += 1
comodinesUsados.append(i)
printTablero(tableroActual,i)
debug(string.join( [ '%s=>%s ' % (k,v) for k, v in intentosPorPosicion.items() ], '') )
debug("=================================== pongo comodin")
#encontrarTablero(i+1)
#return
i = i+1
continue
else:
posicionarFicha(tableroActual,i,ficha[1])
#intentosPorPosicion[i] = ficha[0]
printTablero(tableroActual,i)
debug( string.join( [ '%s=>%s ' % (k,v) for k, v in intentosPorPosicion.items() ], '') )
debug("###################################### pongo ficha")
#encontrarTablero(i+1)
#return
i = i+1
continue
fichas = [ crearFicha() for i in range(n*m) ]
mejorSolucionComodines = n*m
mejorTablero = [ crearFichaComodin() for i in range(n*m)]
comodinesActual = 0
tableroActual = [ crearFichaDebug() for i in range(n*m) ]
comodinesUsados = []
printTablero(tableroActual)
empezarEn=random.randint(0,n*m-1)
primeraFicha = fichas[empezarEn]
fichas.remove(fichas[empezarEn])
posicionarFicha(tableroActual,0,primeraFicha)
intentosPorPosicion=dict({0:n*m-1})
encontrarTablero(1)
| [
[
1,
0,
0.0115,
0.0038,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0153,
0.0038,
0,
0.66,
0.0286,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0192,
0.0038,
0,
... | [
"import random",
"import sys",
"import string",
"import os",
"import time",
"print(sys.getrecursionlimit())",
"sys.setrecursionlimit(5000)",
"print(sys.getrecursionlimit())",
"n = 10",
"m = 10",
"DEBUG=0",
"def debug(s):\n\tif DEBUG :\n\t\tprint(s)",
"\tif DEBUG :\n\t\tprint(s)",
"\t\tprin... |
#!/usr/bin/python
import random
import sys
import string
import os
import time
print sys.getrecursionlimit()
sys.setrecursionlimit(5000)
print sys.getrecursionlimit()
#sys.exit()
#filas
n = 10
#columnas
m = 10
DEBUG=0
def debug(s):
if DEBUG :
print s
# las fichas se numeran asi en sus coordenadas
# 2
# 1 3
# 4
def crearFicha():
return [ random.randint(1,4) for i in range(4) ]
def crearFichaComodin():
return [ 0 for i in range(4) ]
def crearFichaDebug():
return [ 8 for i in range(4) ]
def fichaEncaja(ficha,izquierda=None ,arriba=None):
return ( ( not izquierda or izquierda[2] == ficha[0] or izquierda[2] == 0 ) and
( not arriba or arriba[3] == ficha[1] or arriba[3] == 0 ) )
def printTablero(tablero, index=None):
global n, m, comodinesActual, mejorSolucionComodines
os.system('clear')
defaultBackground = ' '
currentBackground = defaultBackground
for i in range(n):
for t in range(m*6):
sys.stdout.write('-')
sys.stdout.write('\n')
for ii in range(3):
for j in range(m):
if (i*m + j) == index :
currentBackground = chr(64)
else:
currentBackground = defaultBackground
for jj in range(3):
if ii == 0 and jj == 0 :
sys.stdout.write(currentBackground)
if ii == 0 and jj == 2 :
sys.stdout.write(currentBackground)
if ii == 2 and jj == 0 :
sys.stdout.write(currentBackground)
if ii == 2 and jj == 2 :
sys.stdout.write(currentBackground)
if ii == 1 and jj == 1 :
sys.stdout.write(currentBackground)
if ii == 1 and jj == 0:
sys.stdout.write('%s' % tablero[i*m + j][0] )
if ii == 1 and jj == 2:
sys.stdout.write('%s' % tablero[i*m + j][2] )
if ii == 0 and jj == 1:
sys.stdout.write( '%s' % tablero[i*m + j][1] )
if jj == 1 and ii == 2:
sys.stdout.write( '%s' % tablero[i*m + j][3] )
#else:
sys.stdout.write(' | ')
sys.stdout.write("\n")
for t in range(m*6):
sys.stdout.write('-')
sys.stdout.write('- current [%s] mejor [%s]\n' % (comodinesActual,mejorSolucionComodines) )
debug(" ")
time.sleep(0.1)
def esComodin(ficha):
return ficha[0] == 0
def dameFichaQueEncaje(izquierda=None,arriba=None):
global fichas
ficha = None
otras = 0
for f in range(len(fichas)):
if f < len(fichas) and fichaEncaja(fichas[f],izquierda,arriba):
otras += 1
if otras == 1:
ficha=fichas[f]
fichas.remove(ficha)
if otras:
return (otras,ficha)
return (1, crearFichaComodin())
def posicionarFicha(tablero,i,ficha):
tablero[i] = ficha
def getArriba(tablero,i):
if i >= m:
return tablero[i-m]
return crearFichaComodin()
def getIzquierda(tablero,i):
if (i % m ) != 0 :
return tablero[i-1]
return crearFichaComodin()
def encontrarTablero(i):
global comodinesActual, n, m, mejorTablero,mejorSolucionComodines, comodinesUsados
while True:
debug("---------------------- paso %s intento %s comodines %s " % \
(i, intentosPorPosicion[i] if i in intentosPorPosicion else 0 ,comodinesActual))
com = crearFichaComodin()
if com in fichas:
fichas.remove(com)
if i >= n*m:
if comodinesActual < mejorSolucionComodines:
mejorSolucionComodines = comodinesActual
mejorTablero = tableroActual[0:len(tableroActual)]
if len(comodinesUsados):
debug("llegue al final busco mejor solucion")
posUltimoComodin = comodinesUsados.pop_back();
comodinesActual -= 1
for t in range(posUltimoComodin,n*m):
debug("devuelvo fincha ")
intentosPorPosicion[t] = 0
if i != posUltimoComodin:
fichas.push_back(tableroActual[t]);
d = crearFichaDebug()
posicionarFicha(tableroActual,t,d)
#encontrarTablero(posUltimoComodin-1)
#return
i = posUltimoComodin-1
continue
else:
debug("solucion sin comodines !!!!!")
break
debug("cantidad de comodines %s" % mejorSolucionComodines)
break
if i < 0:
debug( "cantidad de comodines %s end" % mejorSolucionComodines)
printTablero(mejorTablero)
break
#############################
if i not in intentosPorPosicion or intentosPorPosicion[i] == 0 :
#avanzo en una rama
izquierda=getIzquierda(tableroActual,i)
arriba=getArriba(tableroActual,i)
ficha = dameFichaQueEncaje(izquierda,arriba)
intentosPorPosicion[i] = ficha[0]
else:
#tuve que volver hacia atras
intentosPorPosicion[i] -= 1
if intentosPorPosicion[i] < 1:
if i == 0:
debug( "cantidad de comodines %s end" % mejorSolucionComodines)
printTablero(mejorTablero)
break
else:
#devuelvo la ficha anterior al las disponibles
intentosPorPosicion[i] = 0
if esComodin(tableroActual[i-1]):
comodinesActual -= 1
comodinesUsados.remove(i-1)
else:
fichas.append(tableroActual[i-1] )
d = crearFichaDebug()
posicionarFicha(tableroActual,i,d)
debug( string.join( [ '%s=>%s ' % (k,v) for k, v in intentosPorPosicion.items() ], ''))
debug("------------------------------ retrocedo por intentos")
#encontrarTablero(i-1)
i = i-1
continue
#return
else:
izquierda=getIzquierda(tableroActual,i)
arriba=getArriba(tableroActual,i)
ficha = dameFichaQueEncaje(izquierda,arriba)
#############################
if esComodin(ficha[1]) :
debug("comodines actual %s comodines mejor %s " % (comodinesActual, mejorSolucionComodines))
if comodinesActual + 1 >= mejorSolucionComodines:
#devuelvo la ficha anterior al las disponibles
if esComodin(tableroActual[i-1]):
comodinesActual -= 1
comodinesUsados.remove(i-1)
else:
fichas.append(tableroActual[i-1] )
intentosPorPosicion[i] = 0
d = crearFichaDebug()
posicionarFicha(tableroActual,i,d)
printTablero(tableroActual,i)
debug(string.join( [ '%s=>%s ' % (k,v) for k, v in intentosPorPosicion.items() ], ''))
debug("------------------------------- retrocedo por comodin")
#intentosPorPosicion[i] = ficha[0]
#encontrarTablero(i-1)
i = i-1
continue
#return
else:
posicionarFicha(tableroActual,i,ficha[1])
comodinesActual += 1
comodinesUsados.append(i)
printTablero(tableroActual,i)
debug(string.join( [ '%s=>%s ' % (k,v) for k, v in intentosPorPosicion.items() ], '') )
debug("=================================== pongo comodin")
#encontrarTablero(i+1)
#return
i = i+1
continue
else:
posicionarFicha(tableroActual,i,ficha[1])
#intentosPorPosicion[i] = ficha[0]
printTablero(tableroActual,i)
debug( string.join( [ '%s=>%s ' % (k,v) for k, v in intentosPorPosicion.items() ], '') )
debug("###################################### pongo ficha")
#encontrarTablero(i+1)
#return
i = i+1
continue
fichas = [ crearFicha() for i in range(n*m) ]
mejorSolucionComodines = n*m
mejorTablero = [ crearFichaComodin() for i in range(n*m)]
comodinesActual = 0
tableroActual = [ crearFichaDebug() for i in range(n*m) ]
comodinesUsados = []
printTablero(tableroActual)
empezarEn=random.randint(0,n*m-1)
primeraFicha = fichas[empezarEn]
fichas.remove(fichas[empezarEn])
posicionarFicha(tableroActual,0,primeraFicha)
intentosPorPosicion=dict({0:n*m-1})
encontrarTablero(1)
| [
[
1,
0,
0.0115,
0.0038,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0153,
0.0038,
0,
0.66,
0.0286,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0192,
0.0038,
0,
... | [
"import random",
"import sys",
"import string",
"import os",
"import time",
"print(sys.getrecursionlimit())",
"sys.setrecursionlimit(5000)",
"print(sys.getrecursionlimit())",
"n = 10",
"m = 10",
"DEBUG=0",
"def debug(s):\n\tif DEBUG :\n\t\tprint(s)",
"\tif DEBUG :\n\t\tprint(s)",
"\t\tprin... |
#! /usr/bin/env python
from random import randint
#defino el nombre del unico archivo con varias instancias
fo = open("ej1/1.in", "wb")
#genero m instancias del problema
for j in range(randint(1,100)):
#obtengo un random para la cantidad de camiones
n = randint(1,200)
D = randint(1,200)
# formato D n d1....dn
fo.write(str(D) + " " + str(n))
#para cada joya genero un di ti random y lo escribo
for i in range(n):
dn = randint(1,D)
fo.write(" " + str(dn))
fo.write("\n")
#ultima linea es un 0 y cierro el archivo
fo.write("0")
fo.close()
| [
[
1,
0,
0.087,
0.0435,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.2174,
0.0435,
0,
0.66,
0.25,
542,
3,
2,
0,
0,
693,
10,
1
],
[
6,
0,
0.587,
0.6087,
0,
0.... | [
"from random import randint",
"fo = open(\"ej1/1.in\", \"wb\")",
"for j in range(randint(1,100)):\n\t#obtengo un random para la cantidad de camiones\n\tn = randint(1,200) \n\tD = randint(1,200)\n\t# formato D n d1....dn \n\n\tfo.write(str(D) + \" \" + str(n))",
"\tn = randint(1,200)",
"\tD = randint(1,2... |
#! /usr/bin/env python
from random import randint
#defino el nombre de cada archivo
fo = open("ej2/" + "testej2.txt", "wb")
for j in range(200):
#obtengo un random para la cantidad de joyas
n = randint(1,100000)
#primer linea la cantidad de joyas n
fo.write( str(n) + "\n")
#para cada joya genero un di ti random y lo escribo
for i in range(n):
di = randint(1,1000000)
ti = randint(1,1000000)
fo.write( str(di) + " " + str(ti) + "\n")
#ultima linea es un 0 y cierro el archivo
fo.write("0")
fo.close()
| [
[
1,
0,
0.15,
0.05,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.35,
0.05,
0,
0.66,
0.25,
542,
3,
2,
0,
0,
693,
10,
1
],
[
6,
0,
0.625,
0.5,
0,
0.66,
0.... | [
"from random import randint",
"fo = open(\"ej2/\" + \"testej2.txt\", \"wb\")",
"for j in range(200):\n\t#obtengo un random para la cantidad de joyas\n\tn = randint(1,100000)\n\t#primer linea la cantidad de joyas n\n\tfo.write( str(n) + \"\\n\")\n\t#para cada joya genero un di ti random y lo escribo\n\tfor i in... |
#! /usr/bin/env python
from random import randint
#defino el nombre de cada archivo
fo = open("ej3/1.in", "wb")
#obtengo cantidad de filas, columnas y colores
n = randint(2,6)
m = randint(2,6)
c = randint(1,8)
#primer linea filas,columnas y colores
fo.write( str(n) + " " + str(m) + " " + str(c) + "\n")
#para cada ficha coloco los valores de los colores de los lados
for i in range(n*m):
sup = str(randint(1,c))
izq = str(randint(1,c))
der = str(randint(1,c))
inf = str(randint(1,c))
fo.write( sup + " " + izq + " " + der + " " + inf + "\n")
fo.close()
| [
[
1,
0,
0.1304,
0.0435,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.3043,
0.0435,
0,
0.66,
0.1429,
542,
3,
2,
0,
0,
693,
10,
1
],
[
14,
0,
0.3913,
0.0435,
0,
... | [
"from random import randint",
"fo = open(\"ej3/1.in\", \"wb\")",
"n = randint(2,6)",
"m = randint(2,6)",
"c = randint(1,8)",
"fo.write( str(n) + \" \" + str(m) + \" \" + str(c) + \"\\n\")",
"for i in range(n*m):\n\tsup = str(randint(1,c))\n\tizq = str(randint(1,c))\n\tder = str(randint(1,c))\n\tinf =... |
#! /usr/bin/env python
from random import randint
#defino el nombre de cada archivo
fo = open("ej2/" + "testej2.txt", "wb")
for j in range(200):
#obtengo un random para la cantidad de joyas
n = randint(1,100000)
#primer linea la cantidad de joyas n
fo.write( str(n) + "\n")
#para cada joya genero un di ti random y lo escribo
for i in range(n):
di = randint(1,1000000)
ti = randint(1,1000000)
fo.write( str(di) + " " + str(ti) + "\n")
#ultima linea es un 0 y cierro el archivo
fo.write("0")
fo.close()
| [
[
1,
0,
0.15,
0.05,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.35,
0.05,
0,
0.66,
0.25,
542,
3,
2,
0,
0,
693,
10,
1
],
[
6,
0,
0.625,
0.5,
0,
0.66,
0.... | [
"from random import randint",
"fo = open(\"ej2/\" + \"testej2.txt\", \"wb\")",
"for j in range(200):\n\t#obtengo un random para la cantidad de joyas\n\tn = randint(1,100000)\n\t#primer linea la cantidad de joyas n\n\tfo.write( str(n) + \"\\n\")\n\t#para cada joya genero un di ti random y lo escribo\n\tfor i in... |
#! /usr/bin/env python
from random import randint
#defino el nombre del unico archivo con varias instancias
fo = open("ej1/1.in", "wb")
#genero m instancias del problema
for j in range(randint(1,100)):
#obtengo un random para la cantidad de camiones
n = randint(1,200)
D = randint(1,200)
# formato D n d1....dn
fo.write(str(D) + " " + str(n))
#para cada joya genero un di ti random y lo escribo
for i in range(n):
dn = randint(1,D)
fo.write(" " + str(dn))
fo.write("\n")
#ultima linea es un 0 y cierro el archivo
fo.write("0")
fo.close()
| [
[
1,
0,
0.087,
0.0435,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.2174,
0.0435,
0,
0.66,
0.25,
542,
3,
2,
0,
0,
693,
10,
1
],
[
6,
0,
0.587,
0.6087,
0,
0.... | [
"from random import randint",
"fo = open(\"ej1/1.in\", \"wb\")",
"for j in range(randint(1,100)):\n\t#obtengo un random para la cantidad de camiones\n\tn = randint(1,200) \n\tD = randint(1,200)\n\t# formato D n d1....dn \n\n\tfo.write(str(D) + \" \" + str(n))",
"\tn = randint(1,200)",
"\tD = randint(1,2... |
#! /usr/bin/env python
from random import randint
#defino el nombre de cada archivo
fo = open("ej3/1.in", "wb")
#obtengo cantidad de filas, columnas y colores
n = randint(2,6)
m = randint(2,6)
c = randint(1,8)
#primer linea filas,columnas y colores
fo.write( str(n) + " " + str(m) + " " + str(c) + "\n")
#para cada ficha coloco los valores de los colores de los lados
for i in range(n*m):
sup = str(randint(1,c))
izq = str(randint(1,c))
der = str(randint(1,c))
inf = str(randint(1,c))
fo.write( sup + " " + izq + " " + der + " " + inf + "\n")
fo.close()
| [
[
1,
0,
0.1304,
0.0435,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.3043,
0.0435,
0,
0.66,
0.1429,
542,
3,
2,
0,
0,
693,
10,
1
],
[
14,
0,
0.3913,
0.0435,
0,
... | [
"from random import randint",
"fo = open(\"ej3/1.in\", \"wb\")",
"n = randint(2,6)",
"m = randint(2,6)",
"c = randint(1,8)",
"fo.write( str(n) + \" \" + str(m) + \" \" + str(c) + \"\\n\")",
"for i in range(n*m):\n\tsup = str(randint(1,c))\n\tizq = str(randint(1,c))\n\tder = str(randint(1,c))\n\tinf =... |
#! /usr/bin/env python
import numpy as np;
import re; # regexp
import matplotlib.pyplot as mp;
################################################################
# Airfoil : load profile of a wing
#
# Reads a file whose lines contain coordinates of points,
# separated by an empty line.
# Every line not containing a couple of floats is discarded.
# Returns a couple constitued of the list of points of the
# extrados and the intrados.
def load_foil(file):
f = open(file, 'r')
matchline = lambda line: re.match(r"\s*([\d\.-]+)\s*([\d\.-]+)", line)
extra = []; intra = []
rextra = False; rintra = False
for line in f:
m = matchline(line)
if (m != None) and not(rextra):
rextra = True
if (m != None) and rextra and not(rintra):
extra.append(m.groups())
if (m != None) and rextra and rintra:
intra.append(m.groups())
if (m == None) and rextra:
rintra = True
ex = np.array(map(lambda t: float(t[0]),extra))
ey = np.array(map(lambda t: float(t[1]),extra))
ix = np.array(map(lambda t: float(t[0]),intra))
iy = np.array(map(lambda t: float(t[1]),intra))
return(ex,ey,ix,iy)
#------------------------------------------------------------------------#
# INTERPOLATION COMPUTING #
#------------------------------------------------------------------------#
def spline_interpolation(ax,ay,n,adv1,advn):
"""Computes the sequence of polynomials storing the value of each second derivates of polynomials evaluated on ax"""
u = np.zeros(n-1)
ap2 = np.zeros(len(ex))
if (adv1 > 0.99e30):
ap2[0] = 0.
u[0] = 0.
else:
ap2[0]=-0.5
u[0]=(3./(ax[1]-ax[0]))*((ay[1]-ay[0])/(ax[1]-ax[0])-adv1)
for i in np.arange(1,n-2,1):
sig=(ax[i]-ax[i-1])/(ax[i+1]-ax[i-1])
p=sig*ap2[i-1]+2.
ap2[i]=(sig-1.)/p
u[i]=(ay[i+1]-ay[i])/(ax[i+1]-ax[i]) - (ay[i]-ay[i-1])/(ax[i]-ax[i-1])
u[i]=(6.*u[i]/(ax[i+1]-ax[i-1])-sig*u[i-1])/p
if (advn > 0.99e30):
qn=0.
un=0.
else:
qn=0.5
un=(3./(ax[n-1]-ax[n-2]))*(advn-(ay[n-1]-ay[n-2])/(ax[n-1]-ax[n-2]))
ap2[n-1]=(un-qn*u[n-2])/(qn*ap2[n-2]+1.)
for k in np.arange(n-2,0,-1):
ap2[k]=ap2[k]*ap2[k+1]+u[k]
return ap2
def point_to_function(ax,ay,res):
"""Computes the polynomials coefficients corresponding with the value of its second derivate"""
n = len(ax)
Pol = np.zeros([n-1,4])
for i in np.arange(0,n-1,1):
tmp1 = (res[i+1]-res[i])/(ax[i+1]-ax[i])
tmp2 = (ay[i+1]-ay[i])/(ax[i+1]-ax[i])
Pol[i][0] = (1./6.)*tmp1
Pol[i][1] = (1./2.)*(res[i]-ax[i]*tmp1)
Pol[i][2] = tmp2 - Pol[i][0]*(ax[i+1]**3-ax[i]**3)/(ax[i+1]-ax[i]) - Pol[i][1]*(ax[i+1]**2-ax[i]**2)/(ax[i+1]-ax[i])
Pol[i][3] = ay[i] - Pol[i][0]*ax[i]**3 - Pol[i][1]*ax[i]**2 - Pol[i][2]*ax[i]
return Pol
def general_function(x,ax,Pol):
"""Piecewise function of polynomials"""
n = len(ax)
for i in np.arange(0,n-1,1):
if(x <= ax[i+1]):
return Pol[i][0]*(x**3)+Pol[i][1]*(x**2)+Pol[i][2]*x+Pol[i][3]
return Pol[n-1][0]*(x**3)+Pol[n-1][1]*(x**2)+Pol[n-1][2]*x+Pol[n-1][3]
#------------------------------------------------------------------------#
# GLOBAL VALUES #
#------------------------------------------------------------------------#
(ex,ey,ix,iy) = load_foil("2032c.dat")
n = len(ex)
x = np.arange(0., 1.01, 0.01)
resulte = spline_interpolation(ex,ey,n,1e30,0)
Pole = point_to_function(ex,ey,resulte)
resulti = spline_interpolation(ix,iy,n,1e30,0)
Poli = point_to_function(ix,iy,resulti)
#------------------------------------------------------------------------#
# INTERPOLATION DRAWING #
#------------------------------------------------------------------------#
def display():
ye = np.arange(0., 1.01, 0.01)
yi = np.arange(0., 1.01, 0.01)
for i in np.arange(0,len(x),1):
ye[i] = general_function(x[i],ex,Pole)
yi[i] = general_function(x[i],ix,Poli)
mp.clf()
mp.plot(x,ye,'b')
mp.plot(x,yi,'b')
mp.plot(ex,ey,'ro')
mp.plot(ix,iy,'ro')
mp.axis([0,1,-0.3,0.3])
display()
| [
[
1,
0,
0.024,
0.008,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.032,
0.008,
0,
0.66,
0.0667,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.04,
0.008,
0,
0.66,
... | [
"import numpy as np;",
"import re; # regexp",
"import matplotlib.pyplot as mp;",
"def load_foil(file):\n f = open(file, 'r')\n matchline = lambda line: re.match(r\"\\s*([\\d\\.-]+)\\s*([\\d\\.-]+)\", line)\n extra = []; intra = []\n rextra = False; rintra = False\n for line in f:\n m... |
#! /usr/bin/env python
import numpy as np;
import re; # regexp
import matplotlib.pyplot as mp;
################################################################
# Airfoil : load profile of a wing
#
# Reads a file whose lines contain coordinates of points,
# separated by an empty line.
# Every line not containing a couple of floats is discarded.
# Returns a couple constitued of the list of points of the
# extrados and the intrados.
def load_foil(file):
f = open(file, 'r')
matchline = lambda line: re.match(r"\s*([\d\.-]+)\s*([\d\.-]+)", line)
extra = []; intra = []
rextra = False; rintra = False
for line in f:
m = matchline(line)
if (m != None) and not(rextra):
rextra = True
if (m != None) and rextra and not(rintra):
extra.append(m.groups())
if (m != None) and rextra and rintra:
intra.append(m.groups())
if (m == None) and rextra:
rintra = True
ex = np.array(map(lambda t: float(t[0]),extra))
ey = np.array(map(lambda t: float(t[1]),extra))
ix = np.array(map(lambda t: float(t[0]),intra))
iy = np.array(map(lambda t: float(t[1]),intra))
return(ex,ey,ix,iy)
#------------------------------------------------------------------------#
# INTERPOLATION COMPUTING #
#------------------------------------------------------------------------#
def spline_interpolation(ax,ay,n,adv1,advn):
"""Computes the sequence of polynomials storing the value of each second derivates of polynomials evaluated on ax"""
u = np.zeros(n-1)
ap2 = np.zeros(len(ex))
if (adv1 > 0.99e30):
ap2[0] = 0.
u[0] = 0.
else:
ap2[0]=-0.5
u[0]=(3./(ax[1]-ax[0]))*((ay[1]-ay[0])/(ax[1]-ax[0])-adv1)
for i in np.arange(1,n-2,1):
sig=(ax[i]-ax[i-1])/(ax[i+1]-ax[i-1])
p=sig*ap2[i-1]+2.
ap2[i]=(sig-1.)/p
u[i]=(ay[i+1]-ay[i])/(ax[i+1]-ax[i]) - (ay[i]-ay[i-1])/(ax[i]-ax[i-1])
u[i]=(6.*u[i]/(ax[i+1]-ax[i-1])-sig*u[i-1])/p
if (advn > 0.99e30):
qn=0.
un=0.
else:
qn=0.5
un=(3./(ax[n-1]-ax[n-2]))*(advn-(ay[n-1]-ay[n-2])/(ax[n-1]-ax[n-2]))
ap2[n-1]=(un-qn*u[n-2])/(qn*ap2[n-2]+1.)
for k in np.arange(n-2,0,-1):
ap2[k]=ap2[k]*ap2[k+1]+u[k]
return ap2
def point_to_function(ax,ay,res):
"""Computes the polynomials coefficients corresponding with the value of its second derivate"""
n = len(ax)
Pol = np.zeros([n-1,4])
for i in np.arange(0,n-1,1):
tmp1 = (res[i+1]-res[i])/(ax[i+1]-ax[i])
tmp2 = (ay[i+1]-ay[i])/(ax[i+1]-ax[i])
Pol[i][0] = (1./6.)*tmp1
Pol[i][1] = (1./2.)*(res[i]-ax[i]*tmp1)
Pol[i][2] = tmp2 - Pol[i][0]*(ax[i+1]**3-ax[i]**3)/(ax[i+1]-ax[i]) - Pol[i][1]*(ax[i+1]**2-ax[i]**2)/(ax[i+1]-ax[i])
Pol[i][3] = ay[i] - Pol[i][0]*ax[i]**3 - Pol[i][1]*ax[i]**2 - Pol[i][2]*ax[i]
return Pol
def general_function(x,ax,Pol):
"""Piecewise function of polynomials"""
n = len(ax)
for i in np.arange(0,n-1,1):
if(x <= ax[i+1]):
return Pol[i][0]*(x**3)+Pol[i][1]*(x**2)+Pol[i][2]*x+Pol[i][3]
return Pol[n-1][0]*(x**3)+Pol[n-1][1]*(x**2)+Pol[n-1][2]*x+Pol[n-1][3]
#------------------------------------------------------------------------#
# GLOBAL VALUES #
#------------------------------------------------------------------------#
(ex,ey,ix,iy) = load_foil("2032c.dat")
n = len(ex)
x = np.arange(0., 1.01, 0.01)
resulte = spline_interpolation(ex,ey,n,1e30,0)
Pole = point_to_function(ex,ey,resulte)
resulti = spline_interpolation(ix,iy,n,1e30,0)
Poli = point_to_function(ix,iy,resulti)
#------------------------------------------------------------------------#
# INTERPOLATION DRAWING #
#------------------------------------------------------------------------#
def display():
ye = np.arange(0., 1.01, 0.01)
yi = np.arange(0., 1.01, 0.01)
for i in np.arange(0,len(x),1):
ye[i] = general_function(x[i],ex,Pole)
yi[i] = general_function(x[i],ix,Poli)
mp.clf()
mp.plot(x,ye,'b')
mp.plot(x,yi,'b')
mp.plot(ex,ey,'ro')
mp.plot(ix,iy,'ro')
mp.axis([0,1,-0.3,0.3])
display()
| [
[
1,
0,
0.024,
0.008,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.032,
0.008,
0,
0.66,
0.0667,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.04,
0.008,
0,
0.66,
... | [
"import numpy as np;",
"import re; # regexp",
"import matplotlib.pyplot as mp;",
"def load_foil(file):\n f = open(file, 'r')\n matchline = lambda line: re.match(r\"\\s*([\\d\\.-]+)\\s*([\\d\\.-]+)\", line)\n extra = []; intra = []\n rextra = False; rintra = False\n for line in f:\n m... |
import numpy as np
import matplotlib.pyplot as mp
import load_foil as lf
#------------------------------------------------------------------------#
# INTEGRAL METHODS #
#------------------------------------------------------------------------#
def rectangle_method(x,y,n,f):
"""Computes the integral of the function f between x and y with the rectangle method (n subdivisions)"""
alpha = (y-x)/n
s = 0.
for k in np.arange(0,n):
s = s + f(x+k*alpha)
return alpha*s
def trapezoidal_method(x,y,n,f):
"""Computes the integral of the function f between x and y with the trapezoidal method (n subdivisions)"""
alpha = (y-x)/n
s = 0.
for k in np.arange(0,n):
s = s + f(x+k*alpha)
s = s + 0.5*(f(y)-f(x))
return alpha*s
def simpson_method(x,y,n,f):
"""Computes the integral of the function f between x and y with the Simpson method (n subdivisions)"""
s1 = 0.
s2 = 0.
alpha = (y-x)/n
for k in np.arange(1,n/2):
s1 = s1 + f(x+2*k*alpha)
s1 = 2*s1
for k in np.arange(1,(n/2)+1):
s2 = s2 + f(x+(2*k-1)*alpha)
s2 = 4*s2
return (alpha/3)*(f(x)+s1+s2+f(y))
def midpoint_method(x,y,n,f):
"""Computes the integral of the function f between x and y with the midpoint method (n subdivisions)"""
s = 0.
alpha = (y-x)/n
for k in np.arange(0,n):
s = s + f(x+(k*alpha)+(alpha/2.))
return alpha*s
#------------------------------------------------------------------------#
# TEST AND COMPARAISON #
#------------------------------------------------------------------------#
def comparaison(f,a,b):
nmax = 100
x = np.arange(1., nmax, 1.)
t = np.arange(1., nmax, 1.)
u = np.arange(1., nmax, 1.)
v = np.arange(1., nmax, 1.)
w = np.arange(1., nmax, 1.)
for i in np.arange(0.,t.size):
t[i] = rectangle_method(a,b,x[i],f)
for i in np.arange(0.,u.size):
u[i] = trapezoidal_method(a,b,x[i],f)
for i in np.arange(0.,v.size):
v[i] = simpson_method(a,b,x[i],f)
for i in np.arange(0.,w.size):
w[i] = midpoint_method(a,b,x[i],f)
mp.clf()
mp.semilogx()
g = mp.plot(x, t, linewidth=1.0)
h = mp.plot(x, u, linewidth=1.0)
i = mp.plot(x, v, linewidth=1.0)
j = mp.plot(x, w, linewidth=1.0)
mp.xlabel('Number of subdivision points')
mp.ylabel('Integral of f between a and b')
mp.legend((g,h,i,j),("Rectangle","Trapezoidal","Simpson","Midpoint"))
mp.show()
#comparaison(lambda x: np.log(x),1.,10.)
#------------------------------------------------------------------------#
# LENGTH COMPUTING #
#------------------------------------------------------------------------#
print "------------------------------------------------------------------------"
print " LENGTH COMPUTING "
print "------------------------------------------------------------------------"
print "\n"
def derivate(Pol):
n = Pol.shape[0]
m = Pol.shape[1]
dPol = np.zeros([n,m])
for i in np.arange(0,n):
dPol[i][0] = 0
dPol[i][1] = 3*Pol[i][0]
dPol[i][2] = 2*Pol[i][1]
dPol[i][3] = Pol[i][2]
return dPol
def length(I,n,df,x,y):
"""Computes the length of f with the I integral method between x and y with a precision of n"""
length = lambda x: np.sqrt(1+(df(x)*df(x)))
return I(x,y,n,length)
dfi = lambda x: lf.general_function(x,lf.ix,derivate(lf.Poli))
dfe = lambda x: lf.general_function(x,lf.ex,derivate(lf.Pole))
print "Intrados length: ",length(midpoint_method,100,lambda x: lf.general_function(x,lf.ix,derivate(lf.Poli)),0.,1.)
print "Extrados length: ",length(midpoint_method,100,lambda x: lf.general_function(x,lf.ex,derivate(lf.Pole)),0.,1.)
comparaison(lambda x: np.sqrt(1+(dfi(x)*dfi(x))),0.,1.)
comparaison(lambda x: np.sqrt(1+(dfe(x)*dfe(x))),0.,1.)
| [
[
1,
0,
0.0082,
0.0082,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.0164,
0.0082,
0,
0.66,
0.0526,
596,
0,
1,
0,
0,
596,
0,
0
],
[
1,
0,
0.0246,
0.0082,
0,
... | [
"import numpy as np",
"import matplotlib.pyplot as mp",
"import load_foil as lf",
"def rectangle_method(x,y,n,f):\n \"\"\"Computes the integral of the function f between x and y with the rectangle method (n subdivisions)\"\"\"\n alpha = (y-x)/n\n s = 0.\n for k in np.arange(0,n):\n s = s + ... |
#!/usr/bin/env python
from sys import platform
requires = {}
try:
from setuptools import setup
if not platform.startswith('java'):
requires = {
'install_requires': ['robotframework', 'paramiko >= 1.8.0'],
}
except ImportError:
from distutils.core import setup
from os.path import abspath, dirname, join
CURDIR = dirname(abspath(__file__))
execfile(join(CURDIR, 'src', 'SSHLibrary', 'version.py'))
with open(join(CURDIR, 'README.rst')) as readme:
README = readme.read()
CLASSIFIERS = """
Development Status :: 5 - Production/Stable
License :: OSI Approved :: Apache Software License
Operating System :: OS Independent
Programming Language :: Python
Topic :: Software Development :: Testing
"""[1:-1]
setup(
name='robotframework-sshlibrary',
version=VERSION, # resolved with execfile
description='Robot Framework test library for SSH and SFTP',
long_description=README,
author='Robot Framework Developers',
author_email='robotframework@gmail.com',
url='http://code.google.com/p/robotframework-sshlibrary/',
license='Apache License 2.0',
keywords='robotframework testing testautomation ssh sftp',
platforms='any',
classifiers=CLASSIFIERS.splitlines(),
package_dir={'': 'src'},
packages=['SSHLibrary'],
**requires
)
| [
[
1,
0,
0.0638,
0.0213,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.1064,
0.0213,
0,
0.66,
0.1429,
151,
0,
0,
0,
0,
0,
6,
0
],
[
7,
0,
0.234,
0.1915,
0,
0.... | [
"from sys import platform",
"requires = {}",
"try:\n from setuptools import setup\n\n if not platform.startswith('java'):\n requires = {\n 'install_requires': ['robotframework', 'paramiko >= 1.8.0'],\n }\nexcept ImportError:",
" from setuptools import setup",
" if not pl... |
# Copyright 2008-2013 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from com.trilead.ssh2 import (Connection, SFTPException, SFTPv3Client,
SFTPv3DirectoryEntry, StreamGobbler)
except ImportError:
raise ImportError(
'Importing Trilead SSH library failed. '
'Make sure you have the Trilead JAR distribution in your CLASSPATH.'
)
import jarray
from java.io import (BufferedReader, File, FileOutputStream, InputStreamReader,
IOException)
from .abstractclient import (AbstractShell, AbstractSSHClient,
AbstractSFTPClient, AbstractCommand,
SSHClientException, SFTPFileInfo)
class JavaSSHClient(AbstractSSHClient):
def _get_client(self):
client = Connection(self.config.host, self.config.port)
client.connect()
return client
@staticmethod
def enable_logging(logfile):
return False
def _login(self, username, password):
if not self.client.authenticateWithPassword(username, password):
raise SSHClientException
def _login_with_public_key(self, username, key_file, password):
try:
success = self.client.authenticateWithPublicKey(username,
File(key_file),
password)
if not success:
raise SSHClientException
except IOError:
# IOError is raised also when the keyfile is invalid
raise SSHClientException
def _start_command(self, command):
cmd = RemoteCommand(command, self.config.encoding)
new_shell = self.client.openSession()
cmd.run_in(new_shell)
return cmd
def _create_sftp_client(self):
return SFTPClient(self.client, self.config.encoding)
def _create_shell(self):
return Shell(self.client, self.config.term_type,
self.config.width, self.config.height)
class Shell(AbstractShell):
def __init__(self, client, term_type, term_width, term_height):
shell = client.openSession()
shell.requestPTY(term_type, term_width, term_height, 0, 0, None)
shell.startShell()
self._stdout = shell.getStdout()
self._stdin = shell.getStdin()
def read(self):
if self._output_available():
read_bytes = jarray.zeros(self._output_available(), 'b')
self._stdout.read(read_bytes)
return ''.join(chr(b & 0xFF) for b in read_bytes)
return ''
def read_byte(self):
if self._output_available():
return chr(self._stdout.read())
return ''
def _output_available(self):
return self._stdout.available()
def write(self, text):
self._stdin.write(text)
self._stdin.flush()
class SFTPClient(AbstractSFTPClient):
def __init__(self, ssh_client, encoding):
self._client = SFTPv3Client(ssh_client)
self._client.setCharset(encoding)
super(SFTPClient, self).__init__()
def _list(self, path):
for item in self._client.ls(path):
if item.filename not in ('.', '..'):
yield SFTPFileInfo(item.filename, item.attributes.permissions)
def _stat(self, path):
attributes = self._client.stat(path)
return SFTPFileInfo('', attributes.permissions)
def _create_remote_file(self, destination, mode):
remote_file = self._client.createFile(destination)
try:
file_stat = self._client.fstat(remote_file)
file_stat.permissions = mode
self._client.fsetstat(remote_file, file_stat)
except SFTPException:
pass
return remote_file
def _write_to_remote_file(self, remote_file, data, position):
self._client.write(remote_file, position, data, 0, len(data))
def _close_remote_file(self, remote_file):
self._client.closeFile(remote_file)
def _get_file(self, remote_path, local_path):
local_file = FileOutputStream(local_path)
remote_file_size = self._client.stat(remote_path).size
remote_file = self._client.openFileRO(remote_path)
array_size_bytes = 4096
data = jarray.zeros(array_size_bytes, 'b')
offset = 0
while True:
read_bytes = self._client.read(remote_file, offset, data, 0,
array_size_bytes)
data_length = len(data)
if read_bytes == -1:
break
if remote_file_size - offset < array_size_bytes:
data_length = remote_file_size - offset
local_file.write(data, 0, data_length)
offset += data_length
self._client.closeFile(remote_file)
local_file.flush()
local_file.close()
def _absolute_path(self, path):
return self._client.canonicalPath(path)
class RemoteCommand(AbstractCommand):
def read_outputs(self):
stdout = self._read_from_stream(self._shell.getStdout())
stderr = self._read_from_stream(self._shell.getStderr())
rc = self._shell.getExitStatus() or 0
self._shell.close()
return stdout, stderr, rc
def _read_from_stream(self, stream):
reader = BufferedReader(InputStreamReader(StreamGobbler(stream),
self._encoding))
result = ''
line = reader.readLine()
while line is not None:
result += line + '\n'
line = reader.readLine()
return result
def _execute(self):
self._shell.execCommand(self._command)
| [
[
7,
0,
0.1039,
0.0449,
0,
0.66,
0,
0,
0,
1,
0,
0,
0,
0,
1
],
[
1,
1,
0.0927,
0.0112,
1,
0.65,
0,
514,
0,
5,
0,
0,
514,
0,
0
],
[
1,
0,
0.1292,
0.0056,
0,
0.66,
... | [
"try:\n from com.trilead.ssh2 import (Connection, SFTPException, SFTPv3Client,\n SFTPv3DirectoryEntry, StreamGobbler)\nexcept ImportError:\n raise ImportError(\n 'Importing Trilead SSH library failed. '\n 'Make sure you have the Trilead JAR distribution in your C... |
# Copyright 2008-2013 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
if sys.platform.startswith('java'):
from javaclient import JavaSSHClient as SSHClient
else:
from pythonclient import PythonSSHClient as SSHClient
| [
[
1,
0,
0.75,
0.05,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
4,
0,
0.925,
0.2,
0,
0.66,
1,
0,
3,
0,
0,
0,
0,
0,
1
],
[
1,
1,
0.9,
0.05,
1,
0.05,
0,
209,
... | [
"import sys",
"if sys.platform.startswith('java'):\n from javaclient import JavaSSHClient as SSHClient\nelse:\n from pythonclient import PythonSSHClient as SSHClient",
" from javaclient import JavaSSHClient as SSHClient",
" from pythonclient import PythonSSHClient as SSHClient"
] |
# Copyright 2008-2013 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
try:
import paramiko
except ImportError:
raise ImportError(
'Importing Paramiko library failed. '
'Make sure you have Paramiko installed.'
)
from .abstractclient import (AbstractShell, AbstractSFTPClient,
AbstractSSHClient, AbstractCommand,
SSHClientException, SFTPFileInfo)
# There doesn't seem to be a simpler way to increase banner timeout
def _custom_start_client(self, event=None):
self.banner_timeout = 45
self._orig_start_client(event)
paramiko.transport.Transport._orig_start_client = \
paramiko.transport.Transport.start_client
paramiko.transport.Transport.start_client = _custom_start_client
# See http://code.google.com/p/robotframework-sshlibrary/issues/detail?id=55
def _custom_log(self, level, msg, *args):
escape = lambda s: s.replace('%', '%%')
if isinstance(msg, basestring):
msg = escape(msg)
else:
msg = [escape(m) for m in msg]
return self._orig_log(level, msg, *args)
paramiko.sftp_client.SFTPClient._orig_log = paramiko.sftp_client.SFTPClient._log
paramiko.sftp_client.SFTPClient._log = _custom_log
class PythonSSHClient(AbstractSSHClient):
def _get_client(self):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
return client
@staticmethod
def enable_logging(path):
paramiko.util.log_to_file(path)
return True
def _login(self, username, password):
try:
self.client.connect(self.config.host, self.config.port, username,
password, look_for_keys=False)
except paramiko.AuthenticationException:
raise SSHClientException
def _login_with_public_key(self, username, key_file, password):
try:
self.client.connect(self.config.host, self.config.port, username,
password, key_filename=key_file)
except paramiko.AuthenticationException:
raise SSHClientException
def _start_command(self, command):
cmd = RemoteCommand(command, self.config.encoding)
new_shell = self.client.get_transport().open_session()
cmd.run_in(new_shell)
return cmd
def _create_sftp_client(self):
return SFTPClient(self.client, self.config.encoding)
def _create_shell(self):
return Shell(self.client, self.config.term_type,
self.config.width, self.config.height)
class Shell(AbstractShell):
def __init__(self, client, term_type, term_width, term_height):
self._shell = client.invoke_shell(term_type, term_width, term_height)
def read(self):
data = ''
while self._output_available():
data += self._shell.recv(4096)
return data
def read_byte(self):
if self._output_available():
return self._shell.recv(1)
return ''
def _output_available(self):
return self._shell.recv_ready()
def write(self, text):
self._shell.sendall(text)
class SFTPClient(AbstractSFTPClient):
def __init__(self, ssh_client, encoding):
self._client = ssh_client.open_sftp()
self._encoding = encoding
super(SFTPClient, self).__init__()
def _list(self, path):
path = path.encode(self._encoding)
for item in self._client.listdir_attr(path):
filename = item.filename
if not isinstance(filename, unicode):
filename = unicode(filename, self._encoding)
yield SFTPFileInfo(filename, item.st_mode)
def _stat(self, path):
path = path.encode(self._encoding)
attributes = self._client.stat(path)
return SFTPFileInfo('', attributes.st_mode)
def _create_missing_remote_path(self, path):
path = path.encode(self._encoding)
return super(SFTPClient, self)._create_missing_remote_path(path)
def _create_remote_file(self, destination, mode):
destination = destination.encode(self._encoding)
remote_file = self._client.file(destination, 'wb')
remote_file.set_pipelined(True)
self._client.chmod(destination, mode)
return remote_file
def _write_to_remote_file(self, remote_file, data, position):
remote_file.write(data)
def _close_remote_file(self, remote_file):
remote_file.close()
def _get_file(self, remote_path, local_path):
remote_path = remote_path.encode(self._encoding)
self._client.get(remote_path, local_path)
def _absolute_path(self, path):
path = path.encode(self._encoding)
normalized_path = self._client.normalize(path)
if not isinstance(normalized_path, unicode):
normalized_path = unicode(normalized_path, self._encoding)
return normalized_path
class RemoteCommand(AbstractCommand):
def read_outputs(self):
stderr, stdout = self._receive_stdout_and_stderr()
rc = self._shell.recv_exit_status()
self._shell.close()
return stdout, stderr, rc
def _receive_stdout_and_stderr(self):
stdout_filebuffer = self._shell.makefile('rb', -1)
stderr_filebuffer = self._shell.makefile_stderr('rb', -1)
stdouts = []
stderrs = []
while self._shell_open():
self._flush_stdout_and_stderr(stderr_filebuffer, stderrs, stdout_filebuffer, stdouts)
time.sleep(0.01) # lets not be so busy
stdout = (''.join(stdouts) + stdout_filebuffer.read()).decode(self._encoding)
stderr = (''.join(stderrs) + stderr_filebuffer.read()).decode(self._encoding)
return stderr, stdout
def _flush_stdout_and_stderr(self, stderr_filebuffer, stderrs, stdout_filebuffer, stdouts):
if self._shell.recv_ready():
stdouts.append(stdout_filebuffer.read(len(self._shell.in_buffer)))
if self._shell.recv_stderr_ready():
stderrs.append(stderr_filebuffer.read(len(self._shell.in_stderr_buffer)))
def _shell_open(self):
return not (self._shell.closed or
self._shell.eof_received or
self._shell.eof_sent or
not self._shell.active)
def _execute(self):
self._shell.exec_command(self._command)
| [
[
1,
0,
0.0714,
0.0051,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
7,
0,
0.0969,
0.0357,
0,
0.66,
0.0833,
0,
0,
1,
0,
0,
0,
0,
1
],
[
1,
1,
0.0867,
0.0051,
1,
0.62... | [
"import time",
"try:\n import paramiko\nexcept ImportError:\n raise ImportError(\n 'Importing Paramiko library failed. '\n 'Make sure you have Paramiko installed.'\n )",
" import paramiko",
"from .abstractclient import (AbstractShell, AbstractSFTPClient,\n ... |
from robot import utils
class ConfigurationException(Exception):
"""Raised when creating, updating or accessing a Configuration entry fails.
"""
pass
class Configuration(object):
"""A simple configuration class.
Configuration is defined with keyword arguments, in which the value must
be an instance of :py:class:`Entry`. Different subclasses of `Entry` can
be used to handle common types and conversions.
Example::
cfg = Configuration(name=StringEntry('initial'),
age=IntegerEntry('42'))
assert cfg.name == initial
assert cfg.age == 42
cfg.update(name='John Doe')
assert cfg.name == 'John Doe'
"""
def __init__(self, **entries):
self._config = entries
def __str__(self):
return '\n'.join(['%s=%s' % (k, v) for k, v in self._config.items()])
def update(self, **entries):
"""Update configuration entries.
:param entries: entries to be updated, keyword argument names must
match existing entry names. If any value in `**entries` is None,
the corresponding entry is *not* updated.
See `__init__` for an example.
"""
for name, value in entries.items():
if value is not None:
self._config[name].set(value)
def get(self, name):
"""Return entry corresponding to name."""
return self._config[name]
def __getattr__(self, name):
if name in self._config:
return self._config[name].value
msg = "Configuration parameter '%s' is not defined." % name
raise ConfigurationException(msg)
class Entry(object):
"""A base class for values stored in :py:class:`Configuration`.
:param:`initial` the initial value of this entry.
"""
def __init__(self, initial=None):
self._value = self._create_value(initial)
def __str__(self):
return str(self._value)
@property
def value(self):
return self._value
def set(self, value):
self._value = self._parse_value(value)
def _create_value(self, value):
if value is None:
return None
return self._parse_value(value)
class StringEntry(Entry):
"""String value to be stored in :py:class:`Configuration`."""
def _parse_value(self, value):
return str(value)
class IntegerEntry(Entry):
"""Integer value to be stored in stored in :py:class:`Configuration`.
Given value is converted to string using `int()`.
"""
def _parse_value(self, value):
return int(value)
class TimeEntry(Entry):
"""Time string to be stored in :py:class:`Configuration`.
Given time string will be converted to seconds using
:py:func:`robot.utils.timestr_to_secs`.
"""
def _parse_value(self, value):
value = str(value)
return utils.timestr_to_secs(value) if value else None
def __str__(self):
return utils.secs_to_timestr(self._value)
class LogLevelEntry(Entry):
"""Log level to be stored in :py:class:`Configuration`.
Given string must be on of 'TRACE', 'DEBUG', 'INFO' or 'WARN', case
insensitively.
"""
LEVELS = ('TRACE', 'DEBUG', 'INFO', 'WARN')
def _parse_value(self, value):
value = str(value).upper()
if value not in self.LEVELS:
raise ConfigurationException("Invalid log level '%s'." % value)
return value
class NewlineEntry(Entry):
"""New line sequence to be stored in :py:class:`Configuration`.
Following conversion are performed on the given string:
* 'LF' -> '\n'
* 'CR' -> '\r'
"""
def _parse_value(self, value):
value = str(value).upper()
return value.replace('LF', '\n').replace('CR', '\r')
| [
[
1,
0,
0.0075,
0.0075,
0,
0.66,
0,
735,
0,
1,
0,
0,
735,
0,
0
],
[
3,
0,
0.0414,
0.0301,
0,
0.66,
0.125,
151,
0,
0,
0,
0,
645,
0,
0
],
[
8,
1,
0.0414,
0.015,
1,
0.... | [
"from robot import utils",
"class ConfigurationException(Exception):\n \"\"\"Raised when creating, updating or accessing a Configuration entry fails.\n \"\"\"\n pass",
" \"\"\"Raised when creating, updating or accessing a Configuration entry fails.\n \"\"\"",
"class Configuration(object):\n ... |
VERSION = '2.0.2'
| [
[
14,
0,
1,
1,
0,
0.66,
0,
557,
1,
0,
0,
0,
0,
3,
0
]
] | [
"VERSION = '2.0.2'"
] |
# Copyright 2008-2013 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .library import SSHLibrary
from .client import SSHClient
| [
[
1,
0,
0.9375,
0.0625,
0,
0.66,
0,
860,
0,
1,
0,
0,
860,
0,
0
],
[
1,
0,
1,
0.0625,
0,
0.66,
1,
608,
0,
1,
0,
0,
608,
0,
0
]
] | [
"from .library import SSHLibrary",
"from .client import SSHClient"
] |
#!/usr/bin/env python
import sys
import os
from robot.libdoc import libdoc
ROOT = os.path.normpath(os.path.join(os.path.abspath(__file__), '..', '..'))
sys.path.insert(0, os.path.join(ROOT, 'src'))
if __name__ == '__main__':
ipath = os.path.join(ROOT, 'src', 'SSHLibrary')
opath = os.path.join(ROOT, 'doc', 'SSHLibrary.html')
try:
libdoc(ipath, opath)
except (IndexError, KeyError):
print __doc__
| [
[
1,
0,
0.1667,
0.0556,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.2222,
0.0556,
0,
0.66,
0.2,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3333,
0.0556,
0,
0.6... | [
"import sys",
"import os",
"from robot.libdoc import libdoc",
"ROOT = os.path.normpath(os.path.join(os.path.abspath(__file__), '..', '..'))",
"sys.path.insert(0, os.path.join(ROOT, 'src'))",
"if __name__ == '__main__':\n ipath = os.path.join(ROOT, 'src', 'SSHLibrary')\n opath = os.path.join(ROOT, 'd... |
import math
class LineGeometry:
def abscurve(self, p1, p2, p3):
(x1,y1), (x2,y2), (x3,y3) = p1, p2, p3
a, b, c = self.line2d_in_general_form(p1, p3)
if a == b == 0: return 0
return abs((a*x2+b*y2+c)/math.sqrt(a**2+b**2))
def line2d_in_general_form(self, p1, p2):
"""Ax+By+C=0"""
(x1,y1), (x2,y2) = p1, p2
# multiply eq.1 by x2, and eq.2 by x1
"""Ax1x2+By1x2+Cx2=0
Ax1x2+By2x1+Cx1=0"""
# subtract
"""B(y1x2-y2x1)+C(x2-x1)=0"""
if y1*x2 - y2*x1 == 0:
return y2, -x2, 0
c = 1.0
b = -c*(x2-x1) / (y1*x2 - y2*x1)
# multiply eq.1 by y2, and eq.2 by y1
"""Ax1y2+By1y2+Cy2=0
Ax2y1+By1y2+Cy1=0"""
# subtract
"""A(x1y2-x2y1)+C(y2-y1)=0"""
a = -c*(y2-y1) / (x1*y2 - x2*y1)
return a, b, c
| [
[
1,
0,
0.0323,
0.0323,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
3,
0,
0.5484,
0.871,
0,
0.66,
1,
843,
0,
2,
0,
0,
0,
0,
3
],
[
2,
1,
0.2581,
0.1613,
1,
0.95,
... | [
"import math",
"class LineGeometry:\n\n def abscurve(self, p1, p2, p3):\n (x1,y1), (x2,y2), (x3,y3) = p1, p2, p3\n a, b, c = self.line2d_in_general_form(p1, p3)\n if a == b == 0: return 0\n return abs((a*x2+b*y2+c)/math.sqrt(a**2+b**2))",
" def abscurve(self, p1, p2, p3):\n ... |
import thread
import weakref
import time
import gobject
class Timer:
def alarmIn(self, delay, instance, action, *args):
gobject.timeout_add(int(delay*1000), self.delayed_response, delay,
weakref.ref(instance), action, args)
#thread.start_new(self.delayed_response,
# (delay, weakref.ref(instance), action, args))
def delayed_response(self, delay, winstance, action, args):
#time.sleep(delay)
instance = winstance()
if instance is not None:
try:
action(instance, *args)
except:
import traceback
print "Oh! Error in Timer thread"
traceback.print_exc()
timer = Timer()
| [
[
1,
0,
0.037,
0.037,
0,
0.66,
0,
260,
0,
1,
0,
0,
260,
0,
0
],
[
1,
0,
0.0741,
0.037,
0,
0.66,
0.2,
708,
0,
1,
0,
0,
708,
0,
0
],
[
1,
0,
0.1111,
0.037,
0,
0.66,
... | [
"import thread",
"import weakref",
"import time",
"import gobject",
"class Timer:\n\n def alarmIn(self, delay, instance, action, *args):\n gobject.timeout_add(int(delay*1000), self.delayed_response, delay,\n weakref.ref(instance), action, args)\n #thread.start_new... |
import weakref
class Control(object):
def isOutlet(self, connectionpoint, outlet):
if hasattr(connectionpoint, 'attachment'):
if repr(connectionpoint.attachment) == outlet:
return True
if hasattr(connectionpoint, 'tag'):
if connectionpoint.tag == outlet:
return True
for connection in connectionpoint.xref:
if hasattr(connection(), 'caption'):
if connection().caption == outlet:
return True
return False
def acquireOutlet(self, event, outlet):
for connectionpoint in event.shape.xref:
if self.isOutlet(connectionpoint(), outlet):
return connectionpoint()
def acquireInterfaces(self, event, outlet):
return event.window.acquireInterfaces(event, outlet)
def acquireInterface(self, event, outlet):
return (self.acquireInterfaces(event, outlet) + [None])[0]
def acquireSubcomponents(self, event):
interest = set()
for connectionpoint in event.shape.xref:
for anchor in connectionpoint().xref:
if isinstance(anchor(), event.window.Point):
for anchored in anchor().xref:
interest.add(SubBridge(event.window,
connectionpoint, anchored,
event.trail, event.frame))
return interest
def getCaption(self, point):
for connection in point.xref:
if hasattr(connection(), 'caption'):
return connection().caption
class Bridge(object):
def __init__(self, window, source, connector, trail=None, frame=None):
self.window = weakref.ref(window)
self.source = source
self.connector = connector
self.trail = trail or Trail()
self.frame = (frame or Frame()).copy()
def push(self, *args):
window = self.window()
source = self.source()
if window is not None and source is not None:
for other_side in self.connector().points():
if other_side is not source:
window.emit(other_side.shape(), "incoming",
point = other_side, wire = self.connector,
trail = self.trail, frame = self.frame,
data = args)
def pull(self, *args):
window = self.window()
source = self.source()
if window is not None and source is not None:
for other_side in self.connector().points():
if other_side is not source:
r = window.call(other_side.shape(), "please",
point = other_side, wire = self.connector,
trail = self.trail, frame = self.frame,
data = args)
return r
class SubBridge(Bridge):
"""
A bridge between a container component and a sub-component.
In this case, there is no connector between the components, and no target
connection point at the sub-component, so fake ones are created for
uniformity of interface.
"""
class FauxConnector:
def __init__(self, points): self.points = lambda: points
def __call__(self): return self
class FauxConnectionPoint:
def __init__(self, shape): self.shape = shape
def __init__(self, window, container_anchor, sub, trail=None, frame=None):
"""
@param window
@param container_anchor the connection point at the side of the
container serving as origin for sub-component
@param sub weak reference to sub-component
@param trail
@param frame
"""
Bridge.__init__(self,
window,
container_anchor,
self.FauxConnector([container_anchor(),
self.FauxConnectionPoint(sub)]),
trail=trail, frame=frame)
class Trail:
pass
class Frame:
def __init__(self):
self.on = { }
def copy(self):
clone = Frame()
clone.on = self.on.copy()
return clone
class Event(object):
def __init__(self):
self.trail = Trail()
self.frame = Frame()
def __getattr__(self, attr):
wattr = "_weak_" + attr
if wattr in self.__dict__:
return self.__dict__[wattr]()
else:
raise AttributeError, "'%s' object has no attribute '%s'" % \
(self.__class__.__name__, attr)
| [
[
1,
0,
0.0075,
0.0075,
0,
0.66,
0,
708,
0,
1,
0,
0,
708,
0,
0
],
[
3,
0,
0.1791,
0.306,
0,
0.66,
0.1667,
834,
0,
6,
0,
0,
186,
0,
21
],
[
2,
1,
0.0858,
0.0896,
1,
... | [
"import weakref",
"class Control(object):\n\n def isOutlet(self, connectionpoint, outlet):\n if hasattr(connectionpoint, 'attachment'):\n if repr(connectionpoint.attachment) == outlet:\n return True\n if hasattr(connectionpoint, 'tag'):\n if connectionpoint.tag ... |
import pickle
import new
import StringIO
import pattern.crossref
def code(*args, **kwargs):
return new.code(*args, **kwargs)
def function(*args, **kwargs):
return new.function(*args, **kwargs)
class PluggablePickler(pickle.Pickler):
def __init__(self, *args):
pickle.Pickler.__init__(self, *args)
self.dispatch = self.dispatch.copy()
@classmethod
def dumps(cls, obj):
buf = StringIO.StringIO()
cls(buf).dump(obj)
return buf.getvalue()
class PicklerWithCode(PluggablePickler):
def __init__(self, *args):
PluggablePickler.__init__(self, *args)
self.dispatch[new.code] = self.save_code.im_func
self.dispatch[new.function] = self.save_function.im_func
self.functions_to_fully = set()
def save_code(self, codeobj):
self.save_reduce(code, self._code_to_tuple(codeobj), obj=codeobj)
def save_function(self, funcobj):
if funcobj in self.functions_to_fully:
self.save_reduce(function, (funcobj.func_code,{}), obj=funcobj)
else:
self.save_global(funcobj)
def _code_to_tuple(self, code):
ctor_order = ["co_argcount", "co_nlocals", "co_stacksize",
"co_flags", "co_code", "co_consts", "co_names",
"co_varnames", "co_filename", "co_name",
"co_firstlineno", "co_lnotab", "co_freevars", "co_cellvars"]
return tuple([getattr(code, x) for x in ctor_order])
class PicklerWithRestrictedXRef(PluggablePickler):
def __init__(self, *args):
PluggablePickler.__init__(self, *args)
self.dispatch[pattern.crossref.XRef] = self.save_xref.im_func
self.allowed_xrefs = set()
def save_xref(self, xref):
if xref() in self.allowed_xrefs:
self.save_reduce(obj=xref, *xref.__reduce__())
else:
self.save_none(None)
class ShapesPickler(PicklerWithRestrictedXRef):
def dump(self, shapes):
"""
@param shapes either a list of shapes, or a tuple of such lists
"""
if isinstance(shapes, tuple):
for x in shapes:
self.allowed_xrefs.update(x)
else:
self.allowed_xrefs.update(shapes)
PicklerWithRestrictedXRef.dump(self, shapes)
@staticmethod
def cleanup(shapes):
for shape in shapes:
if None in shape.xref:
del shape.xref[None]
| [
[
1,
0,
0.0118,
0.0118,
0,
0.66,
0,
848,
0,
1,
0,
0,
848,
0,
0
],
[
1,
0,
0.0235,
0.0118,
0,
0.66,
0.1111,
145,
0,
1,
0,
0,
145,
0,
0
],
[
1,
0,
0.0353,
0.0118,
0,
... | [
"import pickle",
"import new",
"import StringIO",
"import pattern.crossref",
"def code(*args, **kwargs):\n return new.code(*args, **kwargs)",
" return new.code(*args, **kwargs)",
"def function(*args, **kwargs):\n return new.function(*args, **kwargs)",
" return new.function(*args, **kwargs)... |
"""A package of useful stuff."""
| [
[
8,
0,
1,
1,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
]
] | [
"\"\"\"A package of useful stuff.\"\"\""
] |
"""Allows easy run-time tracing of references to objects. Each 'sink' deploys
an 'xref' dictionary attribute which is updated whenever CrossReferences to
the object are created and destroyed. By reading the current value of 'xref',
one can tell which objects are referring the given object via the cross-
reference mechanism."""
import weakref
class CrossReference(object):
def __init__(self, source, referencee):
self._set(source, referencee)
self._assemble()
def __getstate__(self):
return self.source(), self.referencee
def __setstate__(self, state):
source, referencee = state
self._set(source, referencee)
def _set(self, source, referencee):
self.source = XRef(source)
self.referencee = referencee
def _assemble(self):
if hasattr(self.referencee, "xref"):
self.referencee.xref[self.source] = 1
def __call__(self):
return self.referencee
def __del__(self):
if hasattr(self.referencee, "xref"):
try:
del self.referencee.xref[self.source]
except KeyError:
print "CrossReference.__del__ failed for %r -> %r %r" % (self.source(), self.referencee, self.referencee.__dict__)
class XRef(object):
"""This internal type is used instead of weakref to monitor references
without creating loops, also allowing cross-referenced objects to be saved
with 'pickle'."""
def __init__(self, referencee): self._set(referencee)
def _set(self, referencee):
if referencee is None: print "WARN > None referencee"
self.ref = weakref.ref(referencee)
self.id = id(referencee)
def __getstate__(self): return (self.ref())
def __setstate__(self, state): self._set(state)
def __hash__(self): return self.id
def __cmp__(self, other): return cmp(self.id, other.id)
def __call__(self): return self.ref()
| [
[
8,
0,
0.0526,
0.0877,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1228,
0.0175,
0,
0.66,
0.3333,
708,
0,
1,
0,
0,
708,
0,
0
],
[
3,
0,
0.4123,
0.5263,
0,
0.66... | [
"\"\"\"Allows easy run-time tracing of references to objects. Each 'sink' deploys\nan 'xref' dictionary attribute which is updated whenever CrossReferences to\nthe object are created and destroyed. By reading the current value of 'xref',\none can tell which objects are referring the given object via the cross-\nref... |
import os, imp
import plugins.foolish
import gobject
class CodeBase(object):
EDITOR = plugins.foolish.FoolishEditor()
EDITOR_ARGS = []
ROOT = os.getcwd()
TMPDIR = os.path.join(ROOT, "tmp")
components = { }
class NullComponent(object):
def selected(self, *args):
pass
class EditSession(gobject.GObject):
pass
gobject.type_register(EditSession)
gobject.signal_new("edited", EditSession, 0, None, ())
def relativeToFullPath(relative_path):
return os.path.join(CodeBase.ROOT, relative_path)
def fullToRelativePath(full_path):
full_path = full_path.replace("\\", "/")
if full_path.startswith(CodeBase.ROOT.replace("\\", "/") + "/"):
return full_path[len(CodeBase.ROOT)+1:]
else:
return full_path
def editComponent(block_element, session=None):
if hasattr(block_element, "code"):
filename = relativeToFullPath(block_element.code)
else:
import tempfile
filename = tempfile.mktemp(dir = CodeBase.TMPDIR, suffix = ".py")
block_element.code = fullToRelativePath(filename)
#args = CodeBase.EDITOR_ARGS + [filename]
#os.spawnl(os.P_WAIT, CodeBase.EDITOR, CodeBase.EDITOR, *args)
CodeBase.EDITOR.edit(filename, session)
def reloadComponent(block_element):
import os.path
bye(block_element)
if hasattr(block_element, 'code'):
filename = relativeToFullPath(block_element.code)
if os.path.isfile(filename):
J = imp.load_source("J", filename)
j = CodeBase.components[id(block_element)] = J.entry()
def getComponent(block_element):
try:
return CodeBase.components[id(block_element)]
except KeyError:
return NullComponent()
def bye(block_element):
try:
del CodeBase.components[id(block_element)]
except KeyError:
pass
| [
[
1,
0,
0.0147,
0.0147,
0,
0.66,
0,
688,
0,
2,
0,
0,
688,
0,
0
],
[
1,
0,
0.0294,
0.0147,
0,
0.66,
0.0769,
991,
0,
1,
0,
0,
991,
0,
0
],
[
1,
0,
0.0441,
0.0147,
0,
... | [
"import os, imp",
"import plugins.foolish",
"import gobject",
"class CodeBase(object):\n\n EDITOR = plugins.foolish.FoolishEditor()\n EDITOR_ARGS = []\n ROOT = os.getcwd()\n TMPDIR = os.path.join(ROOT, \"tmp\")\n\n components = { }",
" EDITOR = plugins.foolish.FoolishEditor()",
" EDIT... |
from pattern.circuit import Control
class entry(Control):
def please(self, event):
page = ""
for c in ["1", "2", "3", "4", "5"]:
bridge = self.acquireInterface(event, c)
if bridge is not None:
page += str(bridge.pull(*event.data))
return page
| [
[
1,
0,
0.0909,
0.0909,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6364,
0.8182,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
3
],
[
2,
1,
0.7273,
0.6364,
1,
0.94,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\n def please(self, event):\n page = \"\"\n for c in [\"1\", \"2\", \"3\", \"4\", \"5\"]:\n bridge = self.acquireInterface(event, c)\n if bridge is not None:\n page += str(bridge.pull(*event.data))... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
temporal, node = event.data
if temporal == "post":
bridge = self.acquireInterface(event, "output")
if bridge is not None:
bridge.push(event.trail.operands.pop())
| [
[
1,
0,
0.1,
0.1,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.7,
0.7,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
3
],
[
2,
1,
0.75,
0.6,
1,
0.05,
0,
787,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n def incoming(self, event):\n temporal, node = event.data\n if temporal == \"post\":\n bridge = self.acquireInterface(event, \"output\")\n if bridge is not None:\n bridge.push(event.trail.operands.... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
destination, message = event.data
bridge = self.acquireInterface(event, "users")
if bridge is not None:
users = bridge.pull()
for username in self.getUserList(event, destination):
connection = users.get(username, None)
if connection is not None:
connection.wfile.write(message + "\r\n")
connection.wfile.flush()
def getUserList(self, event, destination):
bridge = self.acquireInterface(event, "channels")
if bridge is not None:
channels = bridge.pull()
return channels.get(destination, [destination]) | [
[
1,
0,
0.0476,
0.0476,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.5952,
0.8571,
0,
0.66,
1,
812,
0,
2,
0,
0,
834,
0,
9
],
[
2,
1,
0.5,
0.4762,
1,
0.98,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\t\n\tdef incoming(self, event):\n\t\tdestination, message = event.data\n\t\tbridge = self.acquireInterface(event, \"users\")\n\t\tif bridge is not None:\n\t\t\tusers = bridge.pull()\n\t\t\tfor username in self.getUserList(event, destination):",
"\t... |
from pattern.circuit import Control
class entry(Control):
def please(self, event):
bridge = self.acquireInterface(event, "contents")
if bridge is not None:
bridge.trail.key = event.shape.key
return bridge.pull()
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6667,
0.7778,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
2
],
[
2,
1,
0.7778,
0.5556,
1,
0.58,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n def please(self, event):\n bridge = self.acquireInterface(event, \"contents\")\n if bridge is not None:\n bridge.trail.key = event.shape.key\n return bridge.pull()",
" def please(self, event):\n ... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
username, = event.data
bridge = self.acquireInterface(event, "left:20%")
if bridge is not None:
bridge.push("leave", username)
bridge = self.acquireInterface(event, "left:80%")
if bridge is not None:
bridge.push("part", None, username)
| [
[
1,
0,
0.0769,
0.0769,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6538,
0.7692,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
4
],
[
2,
1,
0.7308,
0.6154,
1,
0.73,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\t\n\tdef incoming(self, event):\n\t\tusername, = event.data\n\t\tbridge = self.acquireInterface(event, \"left:20%\")\n\t\tif bridge is not None:\n\t\t\tbridge.push(\"leave\", username)\n\t\tbridge = self.acquireInterface(event, \"left:80%\")",
"\td... |
class entry:
def incoming(self, event):
for item in event.data:
print item | [
[
3,
0,
0.625,
1,
0,
0.66,
0,
812,
0,
1,
0,
0,
0,
0,
1
],
[
2,
1,
0.75,
0.75,
1,
0.33,
0,
787,
0,
2,
0,
0,
0,
0,
1
],
[
6,
2,
0.875,
0.5,
2,
0.87,
0,
434,
... | [
"class entry:\n def incoming(self, event):\n for item in event.data:\n print(item)",
" def incoming(self, event):\n for item in event.data:\n print(item)",
" for item in event.data:\n print(item)",
" print(item)"
] |
from pattern.circuit import Control
class entry(Control):
def please(self, event):
bridge = self.acquireInterface(event, "from")
if bridge is not None:
return bridge.pull(event.trail.key)
| [
[
1,
0,
0.125,
0.125,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6875,
0.75,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
2
],
[
2,
1,
0.8125,
0.5,
1,
0.55,
0,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n def please(self, event):\n bridge = self.acquireInterface(event, \"from\")\n if bridge is not None:\n return bridge.pull(event.trail.key)",
" def please(self, event):\n bridge = self.acquireInterface(even... |
class entry(object):
VERBS = ["Edit Content"]
PAGE = "<html><body>Hi There</body></html>"
def __init__(self):
self.page = self.PAGE
def realize(self, event):
self.realized = event
if hasattr(event.shape, 'page'):
self.page = event.shape.page
def incoming(self, event):
print event.data
import os.path
if self.page and self.page[0] == '@':
pf = open(os.path.join(event.trail.root, self.page[1:]))
page = pf.read()
else:
page = self.page
length = len(page)
event.trail.send_response(200)
event.trail.send_header("Content-type", "text/html")
event.trail.send_header("Content-Length", str(length))
event.trail.end_headers()
event.trail.wfile.write(page)
def verb(self, event):
import gtk
d = gtk.MessageDialog(message_format = "Page",
buttons = gtk.BUTTONS_OK_CANCEL)
b = gtk.TextBuffer()
e = gtk.TextView(b)
sw = gtk.ScrolledWindow()
sw.add_with_viewport(e)
b.set_text(self.page)
def fine(x,r):
self.page = b.get_text(b.get_start_iter(), b.get_end_iter())
self.realized.shape.page = self.page
x.destroy()
d.connect("response", fine)
d.vbox.add(sw)
e.show()
sw.show()
d.run()
| [
[
3,
0,
0.5102,
0.9592,
0,
0.66,
0,
812,
0,
5,
0,
0,
186,
0,
27
],
[
14,
1,
0.0816,
0.0204,
1,
0.72,
0,
295,
0,
0,
0,
0,
0,
5,
0
],
[
14,
1,
0.102,
0.0204,
1,
0.72,... | [
"class entry(object):\n \n VERBS = [\"Edit Content\"]\n PAGE = \"<html><body>Hi There</body></html>\"\n \n def __init__(self):\n self.page = self.PAGE",
" VERBS = [\"Edit Content\"]",
" PAGE = \"<html><body>Hi There</body></html>\"",
" def __init__(self):\n self.page = se... |
class entry:
class rvalue:
def __init__(self, v): self._v = v
def get(self): return self._v
def incoming(self, event):
temporal, node = event.data
if temporal == "post":
event.trail.operands.append(self.rvalue(node.literal))
| [
[
3,
0,
0.5625,
1,
0,
0.66,
0,
812,
0,
3,
0,
0,
0,
0,
2
],
[
3,
1,
0.375,
0.375,
1,
0,
0,
996,
0,
2,
0,
0,
0,
0,
0
],
[
2,
2,
0.375,
0.125,
2,
0.66,
0,
555,... | [
"class entry:\n class rvalue:\n def __init__(self, v): self._v = v\n def get(self): return self._v\n def incoming(self, event):\n temporal, node = event.data\n if temporal == \"post\":\n event.trail.operands.append(self.rvalue(node.literal))",
" class rvalue:\n ... |
from pattern.circuit import Control
import re
class entry(Control):
MULTIPART = re.compile('Content-Disposition: form-data; name="(.*)"\r\n([^\0]*)', re.MULTILINE)
def incoming(self, event):
ct = event.trail.headers["content-type"]
cl = int(event.trail.headers["content-length"])
request = event.trail.rfile.read(cl)
bridge = self.acquireInterface(event, "request")
if bridge is not None:
if ct.startswith("multipart/form-data"):
self.multipart(request, bridge)
else:
self.singlepart(request, bridge)
# Send OK
bridge = self.acquireInterface(event, "page")
if bridge is not None:
bridge.push()
else:
self._sendOK(event)
def _sendOK(self, event):
page = "OK"
event.trail.send_response(200)
event.trail.send_header("Content-type", "text/plain")
event.trail.send_header("Content-Length", str(len(page)))
event.trail.end_headers()
event.trail.wfile.write(page)
def multipart(self, request, bridge):
delimiter = request.split("\r\n",1)[0] #@@@
for part in request.split(delimiter):
mo = self.MULTIPART.match(part.strip())
if mo:
name = mo.group(1)
value = mo.group(2)
bridge.push(name + "=" + value)
def singlepart(self, request, bridge):
bridge.push(request)
| [
[
1,
0,
0.0233,
0.0233,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
1,
0,
0.0465,
0.0233,
0,
0.66,
0.5,
540,
0,
1,
0,
0,
540,
0,
0
],
[
3,
0,
0.5465,
0.9302,
0,
0.66,... | [
"from pattern.circuit import Control",
"import re",
"class entry(Control):\n\n MULTIPART = re.compile('Content-Disposition: form-data; name=\"(.*)\"\\r\\n([^\\0]*)', re.MULTILINE)\n\n def incoming(self, event):\n ct = event.trail.headers[\"content-type\"]\n cl = int(event.trail.headers[\"con... |
from pattern.circuit import Control
class entry(Control):
class User(object):
pass
def __init__(self):
self.users = { }
def realize(self, event):
self.updated(event)
def incoming(self, event):
action, user = event.data
if action == "enter":
self.enter(event, user)
elif action == "leave":
self.leave(event, user)
def enter(self, event, user):
userobj = self.User(); userobj.wfile = event.trail.wfile
self.users[user] = userobj
self.updated(event)
def leave(self, event, user):
try:
del self.users[user]
self.updated(event)
except KeyError:
pass
def updated(self, event):
bridge = self.acquireInterface(event, "Users")
if bridge is not None:
bridge.push(self)
def please(self, event):
return self.users
def __repr__(self):
return str(self.users.keys())
| [
[
1,
0,
0.0222,
0.0222,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.5222,
0.8889,
0,
0.66,
1,
812,
0,
8,
0,
0,
834,
0,
10
],
[
3,
1,
0.1444,
0.0444,
1,
0.98,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\t\n\tclass User(object):\n\t\tpass\n\t\n\tdef __init__(self):\n\t\tself.users = { }",
"\tclass User(object):\n\t\tpass",
"\tdef __init__(self):\n\t\tself.users = { }",
"\t\tself.users = { }",
"\tdef realize(self, event):\n\t\tself.updated(eve... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
temporal, node = event.data
bridge = self.acquireInterface(event, node.value())
if bridge is not None:
bridge.push(temporal, node)
| [
[
1,
0,
0.1,
0.1,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.7,
0.7,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
3
],
[
2,
1,
0.8,
0.5,
1,
0.93,
0,
787,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n def incoming(self, event):\n temporal, node = event.data\n bridge = self.acquireInterface(event, node.value())\n if bridge is not None:\n bridge.push(temporal, node)",
" def incoming(self, event):\n ... |
from pattern.circuit import Control
class entry(Control):
def realize(self, event):
if not hasattr(event.shape, "label"):
event.shape.label = "Update"
def please(self, event):
key, = event.data
label = event.shape.label
return '<a class="wikilet_update" href="/update.html#%s">%s</a>' % (key, label) | [
[
1,
0,
0.0833,
0.0833,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.625,
0.8333,
0,
0.66,
1,
812,
0,
2,
0,
0,
834,
0,
1
],
[
2,
1,
0.5,
0.25,
1,
0.99,
0,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n def realize(self, event):\n if not hasattr(event.shape, \"label\"):\n event.shape.label = \"Update\"\n \n def please(self, event):\n key, = event.data",
" def realize(self, event):\n if not hasattr(... |
class entry(object):
VERBS = ["Clear"]
def incoming(self, event):
child = self.fetch(event)
data = event.data
if len(data) == 1: data = data[0]
event.window.manipulate(child, lambda x: setattr(x, 'caption', str(data)))
def realize(self, event):
child = self.fetch(event)
def verb(self, event):
child = self.fetch(event)
event.window.manipulate(child, lambda x: setattr(x, 'caption', "Hi there"))
def fetch(self, event):
for x in event.shape.xref:
for y in x().xref:
child = y()
if isinstance(child, event.window.Label):
return child
| [
[
3,
0,
0.5417,
0.9583,
0,
0.66,
0,
812,
0,
4,
0,
0,
186,
0,
12
],
[
14,
1,
0.1667,
0.0417,
1,
0.29,
0,
295,
0,
0,
0,
0,
0,
5,
0
],
[
2,
1,
0.3333,
0.2083,
1,
0.29,... | [
"class entry(object):\n\n VERBS = [\"Clear\"]\n\n def incoming(self, event):\n child = self.fetch(event)\n data = event.data\n if len(data) == 1: data = data[0]",
" VERBS = [\"Clear\"]",
" def incoming(self, event):\n child = self.fetch(event)\n data = event.data\n... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
cmd = event.data[0]
elements = cmd.split()
if elements:
cmdname = elements[0].lower()
bridge = self.acquireInterface(event, cmdname)
if bridge is not None:
bridge.push(elements[1:])
| [
[
1,
0,
0.0833,
0.0833,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.625,
0.8333,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
4
],
[
2,
1,
0.7083,
0.6667,
1,
0.08,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\n def incoming(self, event):\n cmd = event.data[0]\n elements = cmd.split()\n if elements:\n cmdname = elements[0].lower()\n bridge = self.acquireInterface(event, cmdname)",
" def incoming(self, even... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
print event.data
bridge = self.acquireInterface(event, "left:50%")
if bridge is not None:
command = ":" + event.trail.username + \
"!localhost PRIVMSG " + \
" ".join(event.data[0])
destination = event.data[0][0]
bridge.push(destination, command)
| [
[
1,
0,
0.0625,
0.0625,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.5625,
0.6875,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
4
],
[
2,
1,
0.625,
0.5625,
1,
0.56,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\t\n\tdef incoming(self, event):\n\t\tprint(event.data)\n\t\tbridge = self.acquireInterface(event, \"left:50%\")\n\t\tif bridge is not None:\n\t\t\tcommand = \":\" + event.trail.username + \\\n\t\t\t\t\t\"!localhost PRIVMSG \" + \\",
"\tdef incoming... |
from pattern.circuit import Control
class entry(Control):
DEFAULT_REPLY = ":%(username)s!%(user)s PART :%(channel)s\r\n"
def incoming(self, event):
channel = event.data[0][0]
username = event.trail.username
self.onPart(event, channel.split(","), username)
#event.trail.wfile.write(self.DEFAULT_REPLY \
# % {'channel': channel,
# 'username': username,
# 'user': username + "!here",
# 'servername': "localhost"})
def onPart(self, event, channels, username):
bridge = self.acquireInterface(event, "onPart")
if bridge is not None:
bridge.push("part", channels, username)
| [
[
1,
0,
0.0476,
0.0476,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.5952,
0.8571,
0,
0.66,
1,
812,
0,
2,
0,
0,
834,
0,
4
],
[
14,
1,
0.2857,
0.0476,
1,
0.11,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\n DEFAULT_REPLY = \":%(username)s!%(user)s PART :%(channel)s\\r\\n\"\n\n def incoming(self, event):\n channel = event.data[0][0]\n username = event.trail.username\n self.onPart(event, channel.split(\",\"), username)",
" ... |
class entry:
class lvalue:
def __init__(self, scope, rname):
self._scope = scope
self._rname = rname
def get(self):
return self._scope.get(self._rname, None)
def set(self, value):
self._scope[self._rname] = value
def incoming(self, event):
temporal, node = event.data
if temporal == "post":
event.trail.operands.append(self.lvalue(event.trail.vars, node.ref.name))
| [
[
3,
0,
0.5333,
1,
0,
0.66,
0,
812,
0,
4,
0,
0,
0,
0,
3
],
[
3,
1,
0.4333,
0.5333,
1,
0.5,
0,
502,
0,
3,
0,
0,
0,
0,
1
],
[
2,
2,
0.3333,
0.2,
2,
0.29,
0,
5... | [
"class entry:\n \n class lvalue:\n def __init__(self, scope, rname):\n self._scope = scope\n self._rname = rname\n def get(self):\n return self._scope.get(self._rname, None)",
" class lvalue:\n def __init__(self, scope, rname):\n self._scop... |
class entry:
class rvalue:
def __init__(self, v): self._v = v
def get(self): return self._v
def __repr__(self): return "|%r|" % self._v
def incoming(self, event):
temporal, node = event.data
if temporal == "post":
p2 = event.trail.operands.pop()
p1 = event.trail.operands.pop()
event.trail.operands.append(self.rvalue(p1.get() * p2.get()))
| [
[
3,
0,
0.5417,
1,
0,
0.66,
0,
812,
0,
4,
0,
0,
0,
0,
6
],
[
3,
1,
0.2917,
0.3333,
1,
0.08,
0,
996,
0,
3,
0,
0,
0,
0,
0
],
[
2,
2,
0.25,
0.0833,
2,
0.86,
0,
... | [
"class entry:\n class rvalue:\n def __init__(self, v): self._v = v\n def get(self): return self._v\n def __repr__(self): return \"|%r|\" % self._v\n \n def incoming(self, event):\n temporal, node = event.data",
" class rvalue:\n def __init__(self, v): self._v... |
from pattern.circuit import Control
class entry(Control):
DEFAULT_REPLY = ":localhost guest2171 :- information. Thank you for using freenode!\r\n:localhost 376 guest2171 :End of /MOTD command.\r\n"
def incoming(self, event):
event.trail.wfile.write(self.DEFAULT_REPLY)
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.7222,
0.6667,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
1
],
[
14,
1,
0.6667,
0.1111,
1,
0.3,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\n DEFAULT_REPLY = \":localhost guest2171 :- information. Thank you for using freenode!\\r\\n:localhost 376 guest2171 :End of /MOTD command.\\r\\n\"\n\n def incoming(self, event):\n event.trail.wfile.write(self.DEFAULT_REPLY)",
" DE... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
temporal, node = event.data
bridge = self.acquireInterface(event, "out")
if temporal == event.shape.temporal:
bridge.push(node)
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.7222,
0.6667,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
2
],
[
2,
1,
0.7778,
0.5556,
1,
0.23,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n def incoming(self, event):\n temporal, node = event.data\n bridge = self.acquireInterface(event, \"out\")\n if temporal == event.shape.temporal:\n bridge.push(node)",
" def incoming(self, event):\n tempo... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
for out in ["1", "2"]:
bridge = self.acquireInterface(event, out)
if bridge is not None:
bridge.push(*event.data)
| [
[
1,
0,
0.1,
0.1,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6,
0.7,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
2
],
[
2,
1,
0.7,
0.5,
1,
0.82,
0,
787,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\t\n def incoming(self, event):\n for out in [\"1\", \"2\"]:\n bridge = self.acquireInterface(event, out)\n if bridge is not None:\n bridge.push(*event.data)",
" def incoming(self, event):\n f... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
root, = event.data
bridge = self.acquireInterface(event, "out")
if bridge is not None:
bridge.push(self.walk(root))
def walk(self, root):
return "(" + "\n".join([root.value()] + [self.walk(node) for node in root.childNodes()]) + ")" | [
[
1,
0,
0.0769,
0.0769,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6538,
0.7692,
0,
0.66,
1,
812,
0,
2,
0,
0,
834,
0,
7
],
[
2,
1,
0.6154,
0.3846,
1,
0.46,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n def incoming(self, event):\n root, = event.data\n bridge = self.acquireInterface(event, \"out\")\n if bridge is not None:\n bridge.push(self.walk(root))",
" def incoming(self, event):\n root, = eve... |
from pattern.circuit import Control
class entry(Control):
VERBS = ["Push"]
def verb(self, event):
inbridge = self.acquireInterface(event, "in")
outbridge = self.acquireInterface(event, "out")
if inbridge is not None and outbridge is not None:
outbridge.push(inbridge.pull())
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6667,
0.7778,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
4
],
[
14,
1,
0.4444,
0.1111,
1,
0.39,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n VERBS = [\"Push\"]\n def verb(self, event):\n inbridge = self.acquireInterface(event, \"in\")\n outbridge = self.acquireInterface(event, \"out\")\n if inbridge is not None and outbridge is not None:\n outbridge.p... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
root, = event.data
self.walk(event, root)
def walk(self, event, root):
self.visit(event, "pre", root)
for child in root.childNodes():
self.walk(event, child)
self.visit(event, "post", root)
def visit(self, event, temporal, root):
bridge = self.acquireInterface(event, "visitor")
if bridge is not None:
bridge.push(temporal, root)
| [
[
1,
0,
0.0556,
0.0556,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.5833,
0.8889,
0,
0.66,
1,
812,
0,
3,
0,
0,
834,
0,
7
],
[
2,
1,
0.3333,
0.1667,
1,
0.24,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n def incoming(self, event):\n root, = event.data\n self.walk(event, root)\n \n def walk(self, event, root):\n self.visit(event, \"pre\", root)",
" def incoming(self, event):\n root, = event.data\n ... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
bridge = self.acquireInterface(event, "out")
if bridge is not None:
bridge.push(event.data[0].value())
| [
[
1,
0,
0.1111,
0.1111,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.7222,
0.6667,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
3
],
[
2,
1,
0.8333,
0.4444,
1,
0.37,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n def incoming(self, event):\n bridge = self.acquireInterface(event, \"out\")\n if bridge is not None:\n bridge.push(event.data[0].value())",
" def incoming(self, event):\n bridge = self.acquireInterface(ev... |
class entry:
def incoming(self, event):
temporal, node = event.data
if temporal == "post":
r = event.trail.operands.pop()
l = event.trail.operands.pop()
l.set(r.get())
| [
[
3,
0,
0.5,
0.875,
0,
0.66,
0,
812,
0,
1,
0,
0,
0,
0,
4
],
[
2,
1,
0.5625,
0.75,
1,
0.66,
0,
787,
0,
2,
0,
0,
0,
0,
4
],
[
14,
2,
0.375,
0.125,
2,
0.68,
0,
... | [
"class entry:\n def incoming(self, event):\n temporal, node = event.data\n if temporal == \"post\":\n r = event.trail.operands.pop()\n l = event.trail.operands.pop()\n l.set(r.get())",
" def incoming(self, event):\n temporal, node = event.data\n i... |
from pattern.circuit import Control
import weakref, gobject
import os.path, posixpath, urllib
import BaseHTTPServer, SimpleHTTPServer
class SimpleHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def get_root_path(self):
s = self.server
if s is not None and hasattr(s, 'getRootPath'):
return s.getRootPath()
else:
return os.getcwd()
def do_GET(self):
s = self.server
if s is not None and hasattr(s, 'notify'):
s.notify(self.path)
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
This method is overridden to allow starting from a path other than
the current working directory, as is the behaviour of SimpleHTTPServer.
"""
path = posixpath.normpath(urllib.unquote(path))
words = path.split('/')
words = filter(None, words)
path = self.get_root_path()
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir): continue
path = os.path.join(path, word)
return path
class entry(Control):
def realize(self, event):
if not hasattr(event.shape, 'port'):
event.shape.port = 8080
self.port = event.shape.port
self.realized = event
self.initiate(event)
def initiate(self, event):
import thread
self.server = BaseHTTPServer.HTTPServer(('', self.port),
SimpleHTTPRequestHandler)
shape = weakref.ref(event.shape)
self.server.getRootPath = lambda: self().getRootPath(shape)
self.server.notify = self.notify
self = weakref.ref(self)
onConnect = lambda source, condition: self().incomingConnection()
self().watch = gobject.io_add_watch(self().server.socket,\
gobject.IO_IN | gobject.IO_HUP,
onConnect)
del event
def incomingConnection(self):
self.server.handle_request()
return True
def shutdown(self, event):
gobject.source_remove(self.watch)
def getRootPath(self, shape):
shape = shape()
if shape is None:
return os.getcwd()
else:
if not hasattr(shape, 'root'):
shape.root = "/"
return shape.root
def notify(self, *args):
bridge = self.acquireInterface(self.realized, "onGet")
if bridge is not None:
bridge.push(*args)
| [
[
1,
0,
0.0114,
0.0114,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
1,
0,
0.0227,
0.0114,
0,
0.66,
0.2,
708,
0,
2,
0,
0,
708,
0,
0
],
[
1,
0,
0.0341,
0.0114,
0,
0.66,... | [
"from pattern.circuit import Control",
"import weakref, gobject",
"import os.path, posixpath, urllib",
"import BaseHTTPServer, SimpleHTTPServer",
"class SimpleHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):\n\n def get_root_path(self):\n s = self.server\n if s is not None and... |
class entry:
def incoming(self, event):
event.trail.operands = []
event.trail.vars = { }
| [
[
3,
0,
0.625,
1,
0,
0.66,
0,
812,
0,
1,
0,
0,
0,
0,
0
],
[
2,
1,
0.75,
0.75,
1,
0.69,
0,
787,
0,
2,
0,
0,
0,
0,
0
],
[
14,
2,
0.75,
0.25,
2,
0.69,
0,
583,
... | [
"class entry:\n def incoming(self, event):\n event.trail.operands = []\n event.trail.vars = { }",
" def incoming(self, event):\n event.trail.operands = []\n event.trail.vars = { }",
" event.trail.operands = []",
" event.trail.vars = { }"
] |
from pattern.circuit import Control
class entry(Control):
VERBS = ["Go"]
def verb(self, event):
bridge = self.acquireInterface(event, "go")
if bridge is not None:
bridge.push()
| [
[
1,
0,
0.0833,
0.0833,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6667,
0.75,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
2
],
[
14,
1,
0.5,
0.0833,
1,
0.15,
0... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n VERBS = [\"Go\"]\n \n def verb(self, event):\n \n bridge = self.acquireInterface(event, \"go\")\n if bridge is not None:",
" VERBS = [\"Go\"]",
" def verb(self, event):\n \n bridge = self.ac... |
from pattern.circuit import Control
class entry(Control):
JOIN_MSG = ":%(username)s!%(user)s JOIN :%(channel)s"
NAMES_RPL = ":%(servername)s 353 %(username)s = %(channel)s :%(userlist)s\r\n:%(servername)s 366 %(username)s %(channel)s :End of /NAMES list.\r\n"
def incoming(self, event):
channels = event.data[0][0].split(",")
username = event.trail.username
self.onJoin(event, channels, username)
for channel in channels:
users = " ".join(self.listMembers(event, channel))
info = {'channel': channel, 'username': username,
'user': username + "!here",
'userlist': users,
'servername': "localhost"}
event.trail.wfile.write(self.NAMES_RPL % info)
def onJoin(self, event, channels, username):
bridge = self.acquireInterface(event, "onJoin")
if bridge is not None:
bridge.push("join", channels, username)
def listMembers(self, event, channel):
bridge = self.acquireInterface(event, "onJoin")
if bridge is not None:
return bridge.pull().get(channel, [])
| [
[
1,
0,
0.0333,
0.0333,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.5667,
0.9,
0,
0.66,
1,
812,
0,
3,
0,
0,
834,
0,
10
],
[
14,
1,
0.2,
0.0333,
1,
0.26,
0... | [
"from pattern.circuit import Control",
"class entry(Control):\n\n JOIN_MSG = \":%(username)s!%(user)s JOIN :%(channel)s\"\n NAMES_RPL = \":%(servername)s 353 %(username)s = %(channel)s :%(userlist)s\\r\\n:%(servername)s 366 %(username)s %(channel)s :End of /NAMES list.\\r\\n\"\n\n def incoming(self, even... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
path, = event.data
print path
while path and path[0] == '/': path = path[1:]
if path == "": path = "index.html"
bridge = self.acquireInterface(event, path)
if bridge is not None:
bridge.push(path)
else:
bridge = self.acquireInterface(event, "default")
if bridge is not None:
bridge.push(path)
| [
[
1,
0,
0.0625,
0.0625,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.5938,
0.875,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
5
],
[
2,
1,
0.6562,
0.75,
1,
0.65,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n def incoming(self, event):\n path, = event.data\n print(path)\n while path and path[0] == '/': path = path[1:]\n if path == \"\": path = \"index.html\"\n bridge = self.acquireInterface(event, path)",
" ... |
import pattern.circuit
import SocketServer
import gobject
import weakref, time, socket, select
class entry(pattern.circuit.Control):
class EchoRequest(SocketServer.StreamRequestHandler):
def handle(self):
self.server.notify("on", self)
self.line = ""
gobject.io_add_watch(self.rfile, gobject.IO_IN | gobject.IO_HUP, self.readline)
def poll(self, rfile):
i, o, e = select.select([rfile], [], [rfile])
return len(i) or len(e)
def readline(self, source, condition):
try:
b = self.rfile.read(1)
b += self.rfile.read(len(self.rfile._rbuf))
if b == "":
self.release()
return False
for c in b:
if c in "\n\r":
if self.line:
self.server.process(self)
self.line = ""
else:
self.line += c
return True
except:
self.release()
raise
def release(self):
self.server.notify("off", self)
SocketServer.StreamRequestHandler.finish(self)
print "Closed socket!"
def finish(self): pass
def __del__(self): self.release()
def realize(self, event):
if not hasattr(event.shape, 'port'): event.shape.port = 8889
# Bring server up
try:
self.connect(event.shape.port)
except socket.error:
print "Connection failed, retrying..."
time.sleep(1)
self.connect(event.shape.port)
print "Server Hooked."
self.s.notify = self.notify
self.s.process = self.process
self.realized = event
self = weakref.ref(self)
self().watch = gobject.io_add_watch(self().s.socket, gobject.IO_IN,
lambda source, condition: self().incomingConnection(event))
def connect(self, port):
self.s = SocketServer.TCPServer(("", port), self.EchoRequest)
def notify(self, op, request):
self.realized.trail = request
bridge = self.acquireInterface(self.realized, "community")
del self.realized.trail
if bridge is not None:
bridge.push(op, request)
def process(self, request):
self.realized.trail = request
bridge = self.acquireInterface(self.realized, "line out")
del self.realized.trail
if bridge is not None:
bridge.push(request.line)
def shutdown(self, event = None):
try:
del self.s
gobject.source_remove(self.watch)
except AttributeError:
pass
def incomingConnection(self, event):
self.s.handle_request()
return True
def incoming(self, event):
event.trail.wfile.write(str(event.data) + "\r\n")
def please(self, event):
return "Telnet Server"
def __del__(self):
# Safety precautions
self.shutdown()
| [
[
1,
0,
0.0102,
0.0102,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
1,
0,
0.0204,
0.0102,
0,
0.66,
0.25,
646,
0,
1,
0,
0,
646,
0,
0
],
[
1,
0,
0.0306,
0.0102,
0,
0.66... | [
"import pattern.circuit",
"import SocketServer",
"import gobject",
"import weakref, time, socket, select",
"class entry(pattern.circuit.Control):\n\t\n\tclass EchoRequest(SocketServer.StreamRequestHandler):\n\t\tdef handle(self):\n\t\t\tself.server.notify(\"on\", self)\n\t\t\tself.line = \"\"\n\t\t\tgobject... |
from pattern.circuit import Control
class entry(Control):
DEFAULT_REPLY = ":%(servername)s 375 %(username)s\r\n:%(servername)s 372 %(username)s :- information. Thank you for using freenode!\r\n:%(servername)s 376 %(username)s :End of /MOTD command.\r\n"
def incoming(self, event):
event.trail.username = event.data[0][0]
event.trail.wfile.write(self.DEFAULT_REPLY \
% {'servername': "localhost",
'username': event.trail.username})
self.onEnter(event, event.trail.username)
def onEnter(self, event, user):
bridge = self.acquireInterface(event, "onEnter")
if bridge is not None:
bridge.push("enter", user)
| [
[
1,
0,
0.0625,
0.0625,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.625,
0.8125,
0,
0.66,
1,
812,
0,
2,
0,
0,
834,
0,
3
],
[
14,
1,
0.375,
0.0625,
1,
0.87,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\n DEFAULT_REPLY = \":%(servername)s 375 %(username)s\\r\\n:%(servername)s 372 %(username)s :- information. Thank you for using freenode!\\r\\n:%(servername)s 376 %(username)s :End of /MOTD command.\\r\\n\"\n\n def incoming(self, event):\n ... |
from pattern.circuit import Control
class entry(Control):
class Variable(object):
def __init__(self):
self.name = None
def __init__(self):
self.var = self.Variable()
def please(self, event):
outlet = self.acquireOutlet(event, "name")
if outlet is not None:
self.var.name = self.getCaption(outlet)
return self.var
| [
[
1,
0,
0.0556,
0.0556,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6111,
0.8333,
0,
0.66,
1,
812,
0,
3,
0,
0,
834,
0,
3
],
[
3,
1,
0.3889,
0.1667,
1,
0.77,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n class Variable(object):\n def __init__(self):\n self.name = None\n \n \n def __init__(self):",
" class Variable(object):\n def __init__(self):\n self.name = None",
" ... |
from pattern.circuit import Control
class entry(Control):
def incoming(self, event):
username = event.trail.username
self.onQuit(event, username)
event.trail.release()
def onQuit(self, event, username):
bridge = self.acquireInterface(event, "onQuit")
if bridge is not None:
bridge.push(username)
| [
[
1,
0,
0.0714,
0.0714,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6429,
0.7857,
0,
0.66,
1,
812,
0,
2,
0,
0,
834,
0,
4
],
[
2,
1,
0.5357,
0.2857,
1,
0.97,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n\n def incoming(self, event):\n username = event.trail.username\n self.onQuit(event, username)\n event.trail.release()\n\n def onQuit(self, event, username):",
" def incoming(self, event):\n username = event.trai... |
from pattern.circuit import Control
class entry(Control):
def realize(self, event):
if not hasattr(event.shape, "key"):
event.shape.key = "default"
def please(self, event):
bridge = self.acquireInterface(event, "bottom:50%")
if bridge is None:
return "No storage."
else:
return bridge.pull().get(event.shape.key, "Key not found.")
| [
[
1,
0,
0.0714,
0.0714,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6071,
0.8571,
0,
0.66,
1,
812,
0,
2,
0,
0,
834,
0,
4
],
[
2,
1,
0.4286,
0.2143,
1,
0.94,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n def realize(self, event):\n if not hasattr(event.shape, \"key\"):\n event.shape.key = \"default\"\n\n def please(self, event):\n bridge = self.acquireInterface(event, \"bottom:50%\")",
" def realize(self, eve... |
from pattern.circuit import Control
class entry(Control):
def please(self, event):
key, = event.data
bridge = self.acquireInterface(event, "storage")
if bridge is None:
return "No storage."
else:
return bridge.pull().get(key, "Key not found.")
| [
[
1,
0,
0.0909,
0.0909,
0,
0.66,
0,
53,
0,
1,
0,
0,
53,
0,
0
],
[
3,
0,
0.6364,
0.8182,
0,
0.66,
1,
812,
0,
1,
0,
0,
834,
0,
3
],
[
2,
1,
0.7273,
0.6364,
1,
0.12,
... | [
"from pattern.circuit import Control",
"class entry(Control):\n \n def please(self, event):\n key, = event.data\n bridge = self.acquireInterface(event, \"storage\")\n if bridge is None:\n return \"No storage.\"\n else:",
" def please(self, event):\n key, = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.