code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
from random import shuffle
from Carta import Carta
class Mazo(object):
"""Representa a un mazo de barajas inglesas"""
def __init__(self):
"""Inicializa un mazo con sus 52 cartas"""
self.cartas = []
for numero in xrange(1, 13 + 1):
for palo in (Carta.CORAZONES, Carta.DIAMANTES, Carta.PICAS, Carta.TREBOLES):
self.cartas.append(Carta(numero, palo))
def mezclar(self):
"""Mezcla el mazo"""
shuffle(self.cartas)
def obtener_tope(self):
"""Quita la carta que esta encima del mazo y la devuelve"""
return self.cartas.pop()
def es_vacio(self):
"""Devuelve True si al mazo no le quedan cartas, False caso contrario"""
return len(self.cartas) == 0
| [
[
1,
0,
0.0417,
0.0417,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0833,
0.0417,
0,
0.66,
0.5,
238,
0,
1,
0,
0,
238,
0,
0
],
[
3,
0,
0.5833,
0.875,
0,
0.66... | [
"from random import shuffle",
"from Carta import Carta",
"class Mazo(object):\n\t\"\"\"Representa a un mazo de barajas inglesas\"\"\"\n\tdef __init__(self):\n\t\t\"\"\"Inicializa un mazo con sus 52 cartas\"\"\"\n\t\tself.cartas = []\n\n\t\tfor numero in xrange(1, 13 + 1):\n\t\t\tfor palo in (Carta.CORAZONES, Ca... |
from string import upper
import re
from sys import stdin
SCORES = {'A':1, 'E':1, 'I':1, 'L':1, 'N':1, 'O':1, 'R':1, 'S':1, 'T':1, 'U':1,
'D':2, 'G':2, 'B':3, 'C':3, 'M':3, 'P':3, 'F':4, 'H':4, 'V':4, 'W':4,
'Y':4, 'K':5, 'J':8, 'X':8, 'Q':10, 'Z':10}
def read_dictionary_from_file():
k, n, i = 0, 0, 0
dictionary = []
scores = {}
def word_score(word):
score = 0
for i in range(len(word)):
score += SCORES[word[i]]
return score
while True:
line = raw_input()
if i == 0:
k = int(line)
elif i == 1:
n = int(line)
elif len(line) == k:
dictionary.append(line)
scores[line] = word_score(line)
i += 1
if i == n + 2:
break
return k, dictionary, scores
def compute_neighbours_list(dictionary):
neighbours = {}
def is1CharDiff(word1, word2):
diff_count = 0
for l1, l2 in zip(word1, word2):
if l1 != l2:
diff_count += 1
if diff_count > 1:
return False
return True
for i in range(len(dictionary)):
for j in range(i + 1, len(dictionary)):
if is1CharDiff(dictionary[i],
dictionary[j]):
if dictionary[i] in neighbours:
neighbours[dictionary[i]].append(dictionary[j])
else:
neighbours[dictionary[i]] = [dictionary[j]]
if dictionary[j] in neighbours:
neighbours[dictionary[j]].append(dictionary[i])
else:
neighbours[dictionary[j]] = [dictionary[i]]
if not dictionary[i] in neighbours:
neighbours[dictionary[i]] = []
return neighbours
def highest_score_stepladder():
word_length, dictionary, scores = read_dictionary_from_file()
dictionary = sorted([w for w in dictionary if len(w) == word_length], key=lambda w: scores[w], reverse=True)
neighbours = compute_neighbours_list(dictionary)
highest_score = 0
for w in dictionary:
s_w = scores[w]
if highest_score >= s_w ** 2:
continue
stack = [(w, w, [], -scores[w])]
s_append = stack.append
s_pop = stack.pop
while len(stack) > 0:
bottom, top, old_ladder, score = s_pop()
score += scores[top] + scores[bottom]
ladder = old_ladder[:]
ladder.append(bottom)
ladder.append(top)
if score > highest_score:
highest_score = score
bottom_neighbours = [w for w in neighbours[bottom]
if (not w in ladder)
and scores[w] < scores[bottom]]
top_neighbours = [w for w in neighbours[top]
if (not w in ladder)
and scores[w] < scores[top]]
for wb in bottom_neighbours:
for wt in top_neighbours:
s_wt = scores[wt]
s_wb = scores[wb]
if wb != wt and score + s_wb * (s_wb + 1) / 2 + s_wt * (s_wt + 1) / 2 > highest_score: # Upper bound on possible score
s_append((wb, wt, ladder, score))
return highest_score
if __name__ == '__main__':
highest_score = highest_score_stepladder()
print highest_score
| [
[
1,
0,
0.009,
0.009,
0,
0.66,
0,
890,
0,
1,
0,
0,
890,
0,
0
],
[
1,
0,
0.018,
0.009,
0,
0.66,
0.1429,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.027,
0.009,
0,
0.66,
... | [
"from string import upper",
"import re",
"from sys import stdin",
"SCORES = {'A':1, 'E':1, 'I':1, 'L':1, 'N':1, 'O':1, 'R':1, 'S':1, 'T':1, 'U':1,\n 'D':2, 'G':2, 'B':3, 'C':3, 'M':3, 'P':3, 'F':4, 'H':4, 'V':4, 'W':4,\n 'Y':4, 'K':5, 'J':8, 'X':8, 'Q':10, 'Z':10}",
"def read_dictionary_fr... |
from time import clock, time
import heapq
POINTS_TABLE = { 'A': 1, 'E': 1, 'I': 1, 'L': 1, 'N': 1, 'O': 1, 'R': 1, 'S': 1,
'T': 1, 'U': 1, 'D': 2, 'G': 2, 'B': 3, 'C': 3, 'M': 3, 'P': 3,
'F': 4, 'H': 4, 'V': 4, 'W': 4, 'Y': 4, 'K': 5, 'J': 8, 'X': 8,
'Q': 10, 'Z': 10 }
class WordNode(object):
def __init__(self, word):
self.word = word
self.score = 0
for letter in word:
self.score += POINTS_TABLE[letter]
def getWord(self):
return self.word
def getScore(self):
return self.score
def __str__(self):
return self.word
class Edge(object):
def __init__(self, src, dst):
self.src = src
self.dst = dst
def getSource(self):
return self.src
def getDestination(self):
return self.dst
def __str__(self):
return self.src + ' -> ' + self.dst
class Graph(object):
def __init__(self):
self.nodes = set([])
self.edges = {}
self.depths = {}
self.largest_paths = {}
self.largest_ladders = {}
def addNode(self, word_node):
if word_node.getWord() in self.nodes:
raise ValueError('Duplicate')
else:
self.nodes.add(word_node)
self.edges[word_node] = set([])
self.depths[word_node] = [0]
self.largest_paths[word_node] = { 0 : (word_node.score, []) }
self.largest_ladders[word_node] = {0 : (True, word_node.score)}
#print type(self.edges[word_node]) # set
#print type(self.depths[word_node]) # list
#print type(self.largest_paths[word_node]) #dict
#print type(self.largest_ladders[word_node]) #dict
def addEdge(self, edge):
src = edge.getSource()
dst = edge.getDestination()
self.edges[src].add(dst)
def getNodes(self):
return self.nodes
def getEdges(self):
return self.edges
def getChildren(self, word_node):
return self.edges[word_node]
def hasWordNode(self, word_node):
return word_node in self.nodes
def getNodeDepths(self, word_node):
return self.depths[word_node]
def getLargestPath(self, word_node):
return self.largest_paths[word_node]
def getLargestLadders(self, word_node):
return self.largest_ladders[word_node]
def __str__(self):
res = ''
for node in self.nodes:
res += str(node) + '\n'
for depth in self.depths[node]:
res += '{' + str(depth) + ': ' + str(self.largest_paths[node][depth][0]) + ', ['
for n in self.largest_paths[node][depth][1]:
res += str(n) + ', '
res = res + '] }' + '\n'
res += '\n'
for node, neighbors in self.edges.iteritems():
for n in neighbors:
res += str(node) + '->' + str(n) + '\n'
return res[:-1]
def is1CharDiff(word1, word2):
diff_count = 0
for l1, l2 in zip(word1, word2):
if l1 != l2:
diff_count += 1
if diff_count > 1:
return False
return True
def addToGraph(word_graph, node_lst):
stack_node = sorted(node_lst, key=lambda x: x.score)
while stack_node:
node_src = stack_node.pop()
word_graph.addNode(node_src)
for node_dst in stack_node:
if node_src.getScore() != node_dst.getScore() and \
is1CharDiff(node_src.getWord(), node_dst.getWord()):
edge = Edge(node_src, node_dst)
word_graph.addEdge(edge)
def explore(node, depth, word_graph):
if depth == 0:
return True
children = word_graph.getChildren(node)
print children
if not children:
return False
max_path = (0, [])
for child in children:
child_largest_path = word_graph.getLargestPath(child)
if (depth-1) in child_largest_path or explore(child, depth-1, word_graph):
child_largest_score = child_largest_path[depth-1][0]
child_path = child_largest_path[depth-1][1]
node_largest_score = child_largest_score + node.getScore()
if node_largest_score > max_path[0]:
max_path = (node_largest_score, [child] + child_path)
if max_path[0] == 0:
return False
node_largest_path = word_graph.getLargestPath(node)
node_largest_path[depth] = (max_path[0], max_path[1])
return True
def calDepth(word_graph):
print 'calPath '
for node in word_graph.getNodes():
print 'node = ' , node
for depth in range(51):
print 'depth = ', depth
node_largest_path = word_graph.getLargestPath(node)
print node_largest_path
if depth in node_largest_path:
continue
if explore(node, depth, word_graph):
word_graph.getNodeDepths(node).append(depth)
else:
break
def reExplore(node, depth, visited, word_graph):
if depth == 0:
return node.getScore()
if node in visited:
return None
score = 0
children = word_graph.getChildren(node)
for child in children:
if not child in visited:
res_reExplore = reExplore(child, depth-1, visited, word_graph)
if res_reExplore is not None:
if (res_reExplore + node.getScore()) > score:
score = res_reExplore + node.getScore()
if score != 0:
return score
else:
return None
def calLadders(word_graph):
max_score_ladder = 0
for node in word_graph.getNodes():
word_ladders = word_graph.getLargestLadders(node)
children = word_graph.getChildren(node)
depth_lst = word_graph.getNodeDepths(node)
while depth_lst:
depth = depth_lst.pop()
if depth == 0:
if word_ladders[depth][1] > max_score_ladder:
max_score_ladder = word_ladders[depth][1]
continue
if len(children) <= 1:
word_ladders[depth] = (False)
continue
if len(children) > 1:
score_ladder = calLaddersHelper(word_ladders, node, children, depth, word_graph)
if score_ladder is None:
word_ladders[depth] = (False)
else:
word_ladders[depth] = (True, score_ladder)
if score_ladder > max_score_ladder:
max_score_ladder = score_ladder
break
return max_score_ladder
def calLaddersHelper(word_ladders, node, children, depth, word_graph):
max_score = 0
for childA in children:
if not (depth-1) in word_graph.getLargestPath(childA):
continue
for childB in children:
if childA is not childB:
if not (depth-1) in word_graph.getLargestPath(childB):
continue
childA_path_score, childA_path = word_graph.getLargestPath(childA)[depth-1]
childB_path_score, childB_path = word_graph.getLargestPath(childB)[depth-1]
pathA = [childA] + childA_path
pathB = [childB] + childB_path
intersection = set(filter(lambda x: x in pathB, pathA))
if intersection:
new_childB_path_score = reExplore(childB, depth-1, intersection, word_graph)
if new_childB_path_score is not None:
if max_score < (childA_path_score + new_childB_path_score):
max_score = childA_path_score + new_childB_path_score
else:
if max_score < (childA_path_score + childB_path_score):
max_score = childA_path_score + childB_path_score
if max_score != 0:
return max_score + node.getScore()
return None
def getInput():
k, n, node_lst = 0, 0, []
i = 0
while True:
line = raw_input()
if i == 0:
k = int(line)
elif i == 1:
n = int(line)
elif len(line) == k:
word_node = WordNode(line.upper())
node_lst.append(word_node)
i += 1
if i == n + 2:
break
return node_lst
def main():
node_lst = getInput()
word_graph = Graph()
addToGraph(word_graph, node_lst)
print word_graph
calDepth(word_graph)
print(calLadders(word_graph))
if __name__ == '__main__':
main()
"""4
10
SOUR
SPUR
SPUD
STUD
STUN
APES
APED
AXED
AXES
EXES""" | [
[
1,
0,
0.0035,
0.0035,
0,
0.66,
0,
654,
0,
2,
0,
0,
654,
0,
0
],
[
1,
0,
0.007,
0.0035,
0,
0.66,
0.0625,
251,
0,
1,
0,
0,
251,
0,
0
],
[
14,
0,
0.0194,
0.0141,
0,
... | [
"from time import clock, time",
"import heapq",
"POINTS_TABLE = { 'A': 1, 'E': 1, 'I': 1, 'L': 1, 'N': 1, 'O': 1, 'R': 1, 'S': 1,\n 'T': 1, 'U': 1, 'D': 2, 'G': 2, 'B': 3, 'C': 3, 'M': 3, 'P': 3,\n 'F': 4, 'H': 4, 'V': 4, 'W': 4, 'Y': 4, 'K': 5, 'J': 8, 'X': 8,\n 'Q': 10, 'Z': 10 }... |
import matplotlib.pyplot as plt
import fib1,fib2,fib3,fib4,fib5
from monitor import monitorFib
def showFigure(module,n):
x = []
y = []
print "?????"
for i in range(n):
print i
x.append(i)
y.append(monitorFib(module,i))
plt.plot(x,y)
print x
print y
plt.show()
if __name__ == '__main__':
showFigure(fib4,200)
| [
[
1,
0,
0.1,
0.05,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
1,
0,
0.15,
0.05,
0,
0.66,
0.25,
843,
0,
5,
0,
0,
843,
0,
0
],
[
1,
0,
0.2,
0.05,
0,
0.66,
0.5,
... | [
"import matplotlib.pyplot as plt",
"import fib1,fib2,fib3,fib4,fib5",
"from monitor import monitorFib",
"def showFigure(module,n):\n x = []\n y = []\n print(\"?????\")\n for i in range(n):\n print(i)\n x.append(i)\n y.append(monitorFib(module,i))",
" x = []",
" y = [... |
#!/usr/bin/python
# -*- coding: utf8 -*-
from math import sqrt
# 存储运算中需要用到的两个常量
a = (1+sqrt(5))/2.0
b = (1-sqrt(5))/2.0
def fib(n):
""" Standard Formula """
# 特殊情况:n为0或1
if(n == 0):
return 0
elif(n == 1):
return 1
else:
index = 2
c = a
d = b
# 根据公式计算
for index in range(2,n+1):
c = c * a
d = d * b
return round((c-d)/sqrt(5))
| [
[
1,
0,
0.16,
0.04,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.28,
0.04,
0,
0.66,
0.3333,
475,
4,
0,
0,
0,
0,
0,
1
],
[
14,
0,
0.32,
0.04,
0,
0.66,
0.... | [
"from math import sqrt",
"a = (1+sqrt(5))/2.0",
"b = (1-sqrt(5))/2.0",
"def fib(n):\n \"\"\" Standard Formula \"\"\"\n # 特殊情况:n为0或1\n if(n == 0):\n return 0\n elif(n == 1):\n return 1\n else:",
" \"\"\" Standard Formula \"\"\"",
" if(n == 0):\n return 0\n elif(... |
#!/usr/bin/python
# -*- coding: utf8 -*-
def square(m):
""" 求矩阵m的平方 """
r2 = m[2]*m[2]+m[1]*m[1]
r1 = m[2]*m[1]+m[1]*m[0]
r0 = m[1]*m[1]+m[0]*m[0]
m[2] = r2
m[1] = r1
m[0] = r0
def recur(matrix,n):
# 递归结束条件
if n == 1:
return matrix
else:
recur(matrix,n/2) # Divide and Conquer
# Combine
square(matrix)
if(n % 2 == 1): # 处理n为奇数的情况
matrix[0] = matrix[1]
matrix[1] = matrix[2]
matrix[2] = matrix[0] + matrix[1]
def fib(n):
""" Matrix """
# 特殊情况:n=0,1,2
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
# matrix[0]为F(n-1),matrix[1]为F(n),matrix[2]为F(n+1)
matrix = [0,1,1]
recur(matrix,n)
return matrix[1]
if __name__ == '__main__':
print fib(30)
| [
[
2,
0,
0.1875,
0.2,
0,
0.66,
0,
342,
0,
1,
0,
0,
0,
0,
0
],
[
8,
1,
0.125,
0.025,
1,
0.93,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.15,
0.025,
1,
0.93,
0.1667,
... | [
"def square(m):\n \"\"\" 求矩阵m的平方 \"\"\"\n r2 = m[2]*m[2]+m[1]*m[1]\n r1 = m[2]*m[1]+m[1]*m[0]\n r0 = m[1]*m[1]+m[0]*m[0]\n m[2] = r2\n m[1] = r1\n m[0] = r0",
" \"\"\" 求矩阵m的平方 \"\"\"",
" r2 = m[2]*m[2]+m[1]*m[1]",
" r1 = m[2]*m[1]+m[1]*m[0]",
" r0 = m[1]*m[1]+m[0]*m[0]",
"... |
#!/usr/bin/python
# -*- coding: utf8 -*-
from math import sqrt
# 存储运算中需要用到的两个常量
a = (1+sqrt(5))/2.0
b = (1-sqrt(5))/2.0
def fib(n):
""" Standard Formula """
# 特殊情况:n为0或1
if(n == 0):
return 0
elif(n == 1):
return 1
else:
index = 2
c = a
d = b
# 根据公式计算
for index in range(2,n+1):
c = c * a
d = d * b
return round((c-d)/sqrt(5))
| [
[
1,
0,
0.16,
0.04,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.28,
0.04,
0,
0.66,
0.3333,
475,
4,
0,
0,
0,
0,
0,
1
],
[
14,
0,
0.32,
0.04,
0,
0.66,
0.... | [
"from math import sqrt",
"a = (1+sqrt(5))/2.0",
"b = (1-sqrt(5))/2.0",
"def fib(n):\n \"\"\" Standard Formula \"\"\"\n # 特殊情况:n为0或1\n if(n == 0):\n return 0\n elif(n == 1):\n return 1\n else:",
" \"\"\" Standard Formula \"\"\"",
" if(n == 0):\n return 0\n elif(... |
#!/usr/bin/python
# -*- coding: utf8 -*-
from math import sqrt
a = (1+sqrt(5))/2
def recur(n):
# 递归结束条件
if(n == 0):
return 1
elif(n == 1):
return a
else:
b = recur(n/2) #递归调用,Divide and Conquer
# Combine
b = b * b
if(n % 2 == 1): #处理n为奇数的情况
b = b * a
return b
def fib(n):
""" F(n) = ((1+sqrt(5))/2)^n/sqrt(5) """
if(n == 0):
return 0
elif(n == 1):
return 1
else:
return round(recur(n)/sqrt(5))
| [
[
1,
0,
0.1379,
0.0345,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.2069,
0.0345,
0,
0.66,
0.3333,
475,
4,
0,
0,
0,
0,
0,
1
],
[
2,
0,
0.4828,
0.4483,
0,
0... | [
"from math import sqrt",
"a = (1+sqrt(5))/2",
"def recur(n):\n # 递归结束条件\n if(n == 0):\n return 1\n elif(n == 1):\n return a\n else:\n b = recur(n/2) #递归调用,Divide and Conquer",
" if(n == 0):\n return 1\n elif(n == 1):\n return a\n else:\n b = recu... |
#!/usr/bin/python
# -*- coding: utf8 -*-
def square(m):
""" 求矩阵m的平方 """
r2 = m[2]*m[2]+m[1]*m[1]
r1 = m[2]*m[1]+m[1]*m[0]
r0 = m[1]*m[1]+m[0]*m[0]
m[2] = r2
m[1] = r1
m[0] = r0
def recur(matrix,n):
# 递归结束条件
if n == 1:
return matrix
else:
recur(matrix,n/2) # Divide and Conquer
# Combine
square(matrix)
if(n % 2 == 1): # 处理n为奇数的情况
matrix[0] = matrix[1]
matrix[1] = matrix[2]
matrix[2] = matrix[0] + matrix[1]
def fib(n):
""" Matrix """
# 特殊情况:n=0,1,2
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
# matrix[0]为F(n-1),matrix[1]为F(n),matrix[2]为F(n+1)
matrix = [0,1,1]
recur(matrix,n)
return matrix[1]
if __name__ == '__main__':
print fib(30)
| [
[
2,
0,
0.1875,
0.2,
0,
0.66,
0,
342,
0,
1,
0,
0,
0,
0,
0
],
[
8,
1,
0.125,
0.025,
1,
0.06,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
1,
0.15,
0.025,
1,
0.06,
0.1667,
... | [
"def square(m):\n \"\"\" 求矩阵m的平方 \"\"\"\n r2 = m[2]*m[2]+m[1]*m[1]\n r1 = m[2]*m[1]+m[1]*m[0]\n r0 = m[1]*m[1]+m[0]*m[0]\n m[2] = r2\n m[1] = r1\n m[0] = r0",
" \"\"\" 求矩阵m的平方 \"\"\"",
" r2 = m[2]*m[2]+m[1]*m[1]",
" r1 = m[2]*m[1]+m[1]*m[0]",
" r0 = m[1]*m[1]+m[0]*m[0]",
"... |
#!/usr/bin/python
# -*- coding: utf8 -*-
def fib(n):
""" Recursion """
# 递归结束条件: n为0或1
if(n == 0):
return 0
elif(n == 1):
return 1
else:
return fib(n-1)+fib(n-2) # 递归调用
| [
[
2,
0,
0.6667,
0.75,
0,
0.66,
0,
604,
0,
1,
1,
0,
0,
0,
2
],
[
8,
1,
0.4167,
0.0833,
1,
0.02,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
4,
1,
0.7917,
0.5,
1,
0.02,
1,
... | [
"def fib(n):\n \"\"\" Recursion \"\"\"\n # 递归结束条件: n为0或1\n if(n == 0):\n return 0\n elif(n == 1):\n return 1\n else:",
" \"\"\" Recursion \"\"\"",
" if(n == 0):\n return 0\n elif(n == 1):\n return 1\n else:\n return fib(n-1)+fib(n-2) # 递归调用",
" ... |
#!/usr/bin/python
# -*- coding: utf8 -*-
def fib(n):
""" Bottom-up """
# 特殊情况: n为0或1
if(n == 0):
return 0
elif(n == 1):
return 1
else:
# 用f(0)表示F(n-2),f1表示F(n-1),f2表示F(n)
f0 = 0
f1 = 1
f2 = f0+f1
index = 2
while(index < n):
# 每个循环前进一步
f0 = f1
f1 = f2
f2 = f0+f1
index = index + 1
return f2
| [
[
2,
0,
0.5625,
0.8333,
0,
0.66,
0,
604,
0,
1,
1,
0,
0,
0,
0
],
[
8,
1,
0.2083,
0.0417,
1,
0.08,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
4,
1,
0.625,
0.7083,
1,
0.08,
1,... | [
"def fib(n):\n \"\"\" Bottom-up \"\"\"\n # 特殊情况: n为0或1\n if(n == 0):\n return 0\n elif(n == 1):\n return 1\n else:",
" \"\"\" Bottom-up \"\"\"",
" if(n == 0):\n return 0\n elif(n == 1):\n return 1\n else:\n # 用f(0)表示F(n-2),f1表示F(n-1),f2表示F(n)\n ... |
#!/usr/bin/python
# -*- coding: utf8 -*-
import sys
from time import time
import fib1,fib2,fib3,fib4,fib5
def monitorFib(module,n):
start = time()
result = module.fib(n)
elapsed = time()-start
print "%s took %0.3f ms :%d (%s)" % (module.__name__,elapsed*1000.0,result,module.fib.__doc__)
return elapsed
if __name__ == '__main__':
if len(sys.argv) < 2:
print u'请输入参数n\n'
arg = sys.argv[1]
arg = int(arg)
print 'n=%d'%(arg)
monitorFib(fib1,arg);
#monitorFib(fib2,arg);
monitorFib(fib3,arg);
monitorFib(fib4,arg);
monitorFib(fib5,arg);
| [
[
1,
0,
0.1481,
0.037,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.1852,
0.037,
0,
0.66,
0.25,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.2222,
0.037,
0,
0.66,... | [
"import sys",
"from time import time",
"import fib1,fib2,fib3,fib4,fib5",
"def monitorFib(module,n):\n start = time()\n result = module.fib(n)\n elapsed = time()-start\n print(\"%s took %0.3f ms :%d (%s)\" % (module.__name__,elapsed*1000.0,result,module.fib.__doc__))\n return elapsed",
" s... |
#!/usr/bin/python
# -*- coding: utf8 -*-
import sys
from time import time
import fib1,fib2,fib3,fib4,fib5
def monitorFib(module,n):
start = time()
result = module.fib(n)
elapsed = time()-start
print "%s took %0.3f ms :%d (%s)" % (module.__name__,elapsed*1000.0,result,module.fib.__doc__)
return elapsed
if __name__ == '__main__':
if len(sys.argv) < 2:
print u'请输入参数n\n'
arg = sys.argv[1]
arg = int(arg)
print 'n=%d'%(arg)
monitorFib(fib1,arg);
#monitorFib(fib2,arg);
monitorFib(fib3,arg);
monitorFib(fib4,arg);
monitorFib(fib5,arg);
| [
[
1,
0,
0.1481,
0.037,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.1852,
0.037,
0,
0.66,
0.25,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.2222,
0.037,
0,
0.66,... | [
"import sys",
"from time import time",
"import fib1,fib2,fib3,fib4,fib5",
"def monitorFib(module,n):\n start = time()\n result = module.fib(n)\n elapsed = time()-start\n print(\"%s took %0.3f ms :%d (%s)\" % (module.__name__,elapsed*1000.0,result,module.fib.__doc__))\n return elapsed",
" s... |
#!/usr/bin/python
# -*- coding: utf8 -*-
def fib(n):
""" Bottom-up """
# 特殊情况: n为0或1
if(n == 0):
return 0
elif(n == 1):
return 1
else:
# 用f(0)表示F(n-2),f1表示F(n-1),f2表示F(n)
f0 = 0
f1 = 1
f2 = f0+f1
index = 2
while(index < n):
# 每个循环前进一步
f0 = f1
f1 = f2
f2 = f0+f1
index = index + 1
return f2
| [
[
2,
0,
0.5625,
0.8333,
0,
0.66,
0,
604,
0,
1,
1,
0,
0,
0,
0
],
[
8,
1,
0.2083,
0.0417,
1,
0.53,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
4,
1,
0.625,
0.7083,
1,
0.53,
1,... | [
"def fib(n):\n \"\"\" Bottom-up \"\"\"\n # 特殊情况: n为0或1\n if(n == 0):\n return 0\n elif(n == 1):\n return 1\n else:",
" \"\"\" Bottom-up \"\"\"",
" if(n == 0):\n return 0\n elif(n == 1):\n return 1\n else:\n # 用f(0)表示F(n-2),f1表示F(n-1),f2表示F(n)\n ... |
#!/usr/bin/python
# -*- coding: utf8 -*-
from math import sqrt
a = (1+sqrt(5))/2
def recur(n):
# 递归结束条件
if(n == 0):
return 1
elif(n == 1):
return a
else:
b = recur(n/2) #递归调用,Divide and Conquer
# Combine
b = b * b
if(n % 2 == 1): #处理n为奇数的情况
b = b * a
return b
def fib(n):
""" F(n) = ((1+sqrt(5))/2)^n/sqrt(5) """
if(n == 0):
return 0
elif(n == 1):
return 1
else:
return round(recur(n)/sqrt(5))
| [
[
1,
0,
0.1379,
0.0345,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.2069,
0.0345,
0,
0.66,
0.3333,
475,
4,
0,
0,
0,
0,
0,
1
],
[
2,
0,
0.4828,
0.4483,
0,
0... | [
"from math import sqrt",
"a = (1+sqrt(5))/2",
"def recur(n):\n # 递归结束条件\n if(n == 0):\n return 1\n elif(n == 1):\n return a\n else:\n b = recur(n/2) #递归调用,Divide and Conquer",
" if(n == 0):\n return 1\n elif(n == 1):\n return a\n else:\n b = recu... |
#!/usr/bin/python
# -*- coding: utf8 -*-
def fib(n):
""" Recursion """
# 递归结束条件: n为0或1
if(n == 0):
return 0
elif(n == 1):
return 1
else:
return fib(n-1)+fib(n-2) # 递归调用
| [
[
2,
0,
0.6667,
0.75,
0,
0.66,
0,
604,
0,
1,
1,
0,
0,
0,
2
],
[
8,
1,
0.4167,
0.0833,
1,
0.7,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
4,
1,
0.7917,
0.5,
1,
0.7,
1,
0... | [
"def fib(n):\n \"\"\" Recursion \"\"\"\n # 递归结束条件: n为0或1\n if(n == 0):\n return 0\n elif(n == 1):\n return 1\n else:",
" \"\"\" Recursion \"\"\"",
" if(n == 0):\n return 0\n elif(n == 1):\n return 1\n else:\n return fib(n-1)+fib(n-2) # 递归调用",
" ... |
#!/usr/bin/env python2
import random
import math
n = 1
count = 100
rate = 20
for V in range(5, count):
filename = "test-" + str(n) + ".txt"
n = n + 1
fle = open(filename, "w+")
print "Generating test: " + filename + "..."
nodos = V + 1
fabricas = int(math.ceil(rate * nodos / 100))
clientes = nodos - fabricas
aristas = (nodos * (nodos-1)) / 2
fle.write(str(fabricas) + " " + str(clientes) + " " + str(aristas) + "\n")
for i in range(nodos):
for j in range(i+1, nodos):
fle.write(str(i+1) + " " + str(j+1) + " " + str(random.randint(0,50)) + "\n")
fle.close()
| [
[
1,
0,
0.0968,
0.0323,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.129,
0.0323,
0,
0.66,
0.2,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.1935,
0.0323,
0,
0.6... | [
"import random",
"import math",
"n = 1",
"count = 100",
"rate = 20",
"for V in range(5, count):\n\t\n\tfilename = \"test-\" + str(n) + \".txt\"\n\t\n\tn = n + 1\n\t\n\tfle = open(filename, \"w+\")",
"\tfilename = \"test-\" + str(n) + \".txt\"",
"\tn = n + 1",
"\tfle = open(filename, \"w+\")",
"\tp... |
#!/usr/bin/env python2
import random
import math
n = 1
count = 100
rate = 20
for V in range(5, count):
filename = "test-" + str(n) + ".txt"
n = n + 1
fle = open(filename, "w+")
print "Generating test: " + filename + "..."
nodos = V + 1
fabricas = int(math.ceil(rate * nodos / 100))
clientes = nodos - fabricas
aristas = (nodos * (nodos-1)) / 2
fle.write(str(fabricas) + " " + str(clientes) + " " + str(aristas) + "\n")
for i in range(nodos):
for j in range(i+1, nodos):
fle.write(str(i+1) + " " + str(j+1) + " " + str(random.randint(0,50)) + "\n")
fle.close()
| [
[
1,
0,
0.0968,
0.0323,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.129,
0.0323,
0,
0.66,
0.2,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.1935,
0.0323,
0,
0.6... | [
"import random",
"import math",
"n = 1",
"count = 100",
"rate = 20",
"for V in range(5, count):\n\t\n\tfilename = \"test-\" + str(n) + \".txt\"\n\t\n\tn = n + 1\n\t\n\tfle = open(filename, \"w+\")",
"\tfilename = \"test-\" + str(n) + \".txt\"",
"\tn = n + 1",
"\tfle = open(filename, \"w+\")",
"\tp... |
#!/usr/bin/env python2
import subprocess, time, os, sys
def instanceFromFile(path):
f = open(path)
text = ""
for line in f:
text += line
return text
def launch(input):
command = ["./problema3-test"]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip().split()
iterations = 1000
test_count = 95
tests = []
for test in range(test_count):
tests.append("test-" + str(test+1) + ".txt")
for test in tests:
instance = instanceFromFile(test)
fabricas, clientes, edges = instance.split("\n")[0].strip().split()
fabricas = int(fabricas)
clientes = int(clientes)
edges = int(edges)
solveA = 0
for i in range(iterations):
clocks = launch(instance)
solveA += int(clocks[0])
solveA = solveA / iterations
print str(fabricas) + "\t" + str(clientes) + "\t" + str(edges) + "\t" + str(solveA)
| [
[
1,
0,
0.0952,
0.0238,
0,
0.66,
0,
394,
0,
4,
0,
0,
394,
0,
0
],
[
2,
0,
0.2024,
0.1429,
0,
0.66,
0.1429,
709,
0,
1,
1,
0,
0,
0,
1
],
[
14,
1,
0.1667,
0.0238,
1,
0... | [
"import subprocess, time, os, sys",
"def instanceFromFile(path):\n\tf = open(path)\n\ttext = \"\"\n\tfor line in f:\n\t\ttext += line\n\treturn text",
"\tf = open(path)",
"\ttext = \"\"",
"\tfor line in f:\n\t\ttext += line",
"\treturn text",
"def launch(input):\n\tcommand = [\"./problema3-test\"]\n\tsu... |
#!/usr/bin/env python2
import subprocess, time, os, sys
def instanceFromFile(path):
f = open(path)
text = ""
for line in f:
text += line
return text
def launch(input):
command = ["./problema3-test"]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip().split()
iterations = 1000
test_count = 95
tests = []
for test in range(test_count):
tests.append("test-" + str(test+1) + ".txt")
for test in tests:
instance = instanceFromFile(test)
fabricas, clientes, edges = instance.split("\n")[0].strip().split()
fabricas = int(fabricas)
clientes = int(clientes)
edges = int(edges)
solveA = 0
for i in range(iterations):
clocks = launch(instance)
solveA += int(clocks[0])
solveA = solveA / iterations
print str(fabricas) + "\t" + str(clientes) + "\t" + str(edges) + "\t" + str(solveA)
| [
[
1,
0,
0.0952,
0.0238,
0,
0.66,
0,
394,
0,
4,
0,
0,
394,
0,
0
],
[
2,
0,
0.2024,
0.1429,
0,
0.66,
0.1429,
709,
0,
1,
1,
0,
0,
0,
1
],
[
14,
1,
0.1667,
0.0238,
1,
0... | [
"import subprocess, time, os, sys",
"def instanceFromFile(path):\n\tf = open(path)\n\ttext = \"\"\n\tfor line in f:\n\t\ttext += line\n\treturn text",
"\tf = open(path)",
"\ttext = \"\"",
"\tfor line in f:\n\t\ttext += line",
"\treturn text",
"def launch(input):\n\tcommand = [\"./problema3-test\"]\n\tsu... |
#!/usr/bin/env python2
import subprocess, time, os, sys
def instanceFromFile(path):
f = open(path)
text = ""
for line in f:
text += line
return text
def launch(input):
command = ["./problema2-test"]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip().split()
iterations = 1000
test_count = 100
tests = []
for test in range(test_count):
tests.append("test-" + str(test+1) + ".txt")
for test in tests:
instance = instanceFromFile(test)
nodes, edges = instance.split("\n")[0].strip().split()
nodes = int(nodes)
edges = int(edges)
solveA = 0
solveB = 0
for i in range(iterations):
clocks = launch(instance)
solveA += int(clocks[0])
solveB += int(clocks[1])
solveA = solveA / iterations
solveB = solveB / iterations
print str(nodes) + "\t" + str(edges) + "\t" + str(solveA) + "\t" + str(solveB) | [
[
1,
0,
0.0952,
0.0238,
0,
0.66,
0,
394,
0,
4,
0,
0,
394,
0,
0
],
[
2,
0,
0.2024,
0.1429,
0,
0.66,
0.1429,
709,
0,
1,
1,
0,
0,
0,
1
],
[
14,
1,
0.1667,
0.0238,
1,
0... | [
"import subprocess, time, os, sys",
"def instanceFromFile(path):\n\tf = open(path)\n\ttext = \"\"\n\tfor line in f:\n\t\ttext += line\n\treturn text",
"\tf = open(path)",
"\ttext = \"\"",
"\tfor line in f:\n\t\ttext += line",
"\treturn text",
"def launch(input):\n\tcommand = [\"./problema2-test\"]\n\tsu... |
#!/usr/bin/env python2
import random
#~ i = 1
#~
#~ for nodos in range(100):
#~ name = "test-" + str(i) + ".txt"
#~ i = i + 1
#~ f = open(name, "w+")
#~
#~ print "Generating " + name + "..."
#~
#~ f.write(str(nodos+1) + " " + str(nodos) + "\n")
#~
#~ for j in range(nodos):
#~ f.write(str(j+1) + " " + str(j+2) + " " + str(random.randint(0,50)) + "\n")
#~
#~ f.close()
n = 1
count = 100
for V in range(count):
filename = "test-" + str(n) + ".txt"
n = n + 1
fle = open(filename, "w+")
print "Generating test: " + filename + "..."
nodos = V + 1
aristas = (nodos * (nodos-1)) / 2
fle.write(str(nodos) + " " + str(aristas) + "\n")
for i in range(nodos):
for j in range(i+1, nodos):
fle.write(str(i+1) + " " + str(j+1) + " " + str(random.randint(0,50)) + "\n")
fle.close()
| [
[
1,
0,
0.0698,
0.0233,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.4884,
0.0233,
0,
0.66,
0.3333,
773,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.5116,
0.0233,
0,
... | [
"import random",
"n = 1",
"count = 100",
"for V in range(count):\n\t\n\tfilename = \"test-\" + str(n) + \".txt\"\n\t\n\tn = n + 1\n\t\n\tfle = open(filename, \"w+\")",
"\tfilename = \"test-\" + str(n) + \".txt\"",
"\tn = n + 1",
"\tfle = open(filename, \"w+\")",
"\tprint(\"Generating test: \" + filena... |
#!/usr/bin/env python2
import subprocess, time, os, sys
def instanceFromFile(path):
f = open(path)
text = ""
for line in f:
text += line
return text
def launch(input):
command = ["./problema2-test"]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip().split()
iterations = 1000
test_count = 100
tests = []
for test in range(test_count):
tests.append("test-" + str(test+1) + ".txt")
for test in tests:
instance = instanceFromFile(test)
nodes, edges = instance.split("\n")[0].strip().split()
nodes = int(nodes)
edges = int(edges)
solveA = 0
solveB = 0
for i in range(iterations):
clocks = launch(instance)
solveA += int(clocks[0])
solveB += int(clocks[1])
solveA = solveA / iterations
solveB = solveB / iterations
print str(nodes) + "\t" + str(edges) + "\t" + str(solveA) + "\t" + str(solveB) | [
[
1,
0,
0.0952,
0.0238,
0,
0.66,
0,
394,
0,
4,
0,
0,
394,
0,
0
],
[
2,
0,
0.2024,
0.1429,
0,
0.66,
0.1429,
709,
0,
1,
1,
0,
0,
0,
1
],
[
14,
1,
0.1667,
0.0238,
1,
0... | [
"import subprocess, time, os, sys",
"def instanceFromFile(path):\n\tf = open(path)\n\ttext = \"\"\n\tfor line in f:\n\t\ttext += line\n\treturn text",
"\tf = open(path)",
"\ttext = \"\"",
"\tfor line in f:\n\t\ttext += line",
"\treturn text",
"def launch(input):\n\tcommand = [\"./problema2-test\"]\n\tsu... |
#!/usr/bin/env python2
import random
#~ i = 1
#~
#~ for nodos in range(100):
#~ name = "test-" + str(i) + ".txt"
#~ i = i + 1
#~ f = open(name, "w+")
#~
#~ print "Generating " + name + "..."
#~
#~ f.write(str(nodos+1) + " " + str(nodos) + "\n")
#~
#~ for j in range(nodos):
#~ f.write(str(j+1) + " " + str(j+2) + " " + str(random.randint(0,50)) + "\n")
#~
#~ f.close()
n = 1
count = 100
for V in range(count):
filename = "test-" + str(n) + ".txt"
n = n + 1
fle = open(filename, "w+")
print "Generating test: " + filename + "..."
nodos = V + 1
aristas = (nodos * (nodos-1)) / 2
fle.write(str(nodos) + " " + str(aristas) + "\n")
for i in range(nodos):
for j in range(i+1, nodos):
fle.write(str(i+1) + " " + str(j+1) + " " + str(random.randint(0,50)) + "\n")
fle.close()
| [
[
1,
0,
0.0698,
0.0233,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
14,
0,
0.4884,
0.0233,
0,
0.66,
0.3333,
773,
1,
0,
0,
0,
0,
1,
0
],
[
14,
0,
0.5116,
0.0233,
0,
... | [
"import random",
"n = 1",
"count = 100",
"for V in range(count):\n\t\n\tfilename = \"test-\" + str(n) + \".txt\"\n\t\n\tn = n + 1\n\t\n\tfle = open(filename, \"w+\")",
"\tfilename = \"test-\" + str(n) + \".txt\"",
"\tn = n + 1",
"\tfle = open(filename, \"w+\")",
"\tprint(\"Generating test: \" + filena... |
import re
import config
import common
import random
import array
# Step 1: Choose a starting point of MarkovOrder (2 or 3) notes.
# Choose from list of states that have a non-empty successor list.
# Step 2: Find a note randomly(?) from the list of successors.
# There's scope for improvement(?) here - we can choose to take the
# more likely notes more often. Or choose the next note based on more
# than just the current markov state - like using a pre-defined mood
# (happy, sad, etc) and choosing a high or a low note based on that.
# But as a first step, we can go head and choose the note randomly.
# Step 3: Update the state and repeat 2 until a certain number of
# notes are composed.
SuccessorList = {};
NumVerses = 12; # Num of verses in the composition. 1 Verse = 1 cycle of tala
def ReadAnalytics():
f = open(config.OutFile,'r');
for line in f:
temp = re.split('\s+',line);
def cutempty(x): return x!="" and x!="\n";
slist = filter(cutempty, temp[1:]);
SuccessorList[int(temp[0])] = slist;
def GetNotesFromState(s):
notes = [];
for i in range(0,config.MarkovOrder,1):
temp = config.MarkovOrder - i - 1;
notes.append(s/common.NumNotes**temp);
s = s%(common.NumNotes**temp);
return notes;
def GetStartState():
global SuccessorList;
state = SuccessorList.keys()[random.randrange(len(SuccessorList.keys()))]
state = GetNotesFromState(state);
return state;
def compose():
state = GetStartState();
for x in state:
print common.NoteRevIndex[x],
versecount = 0;
symcount = config.MarkovOrder; #number of notes in state
while(versecount < 12):
if(symcount == 8):
symcount = 0;
versecount += 1
print;
while (versecount < 12 and symcount < 8): #assuming adi talam for now
temp = common.FindMarkovMatrixIndex(state);
if(SuccessorList.has_key(temp)):
nextnote = SuccessorList[temp][random.randrange(len(SuccessorList[temp]))];
print common.NoteRevIndex[int(nextnote)],
state.pop(0);
state.append(int(nextnote));
symcount += 1;
continue;
# print "<Split>"
state = GetStartState();
for x in state:
print common.NoteRevIndex[x],
symcount +=1;
if(symcount == 8):
versecount += 1;
symcount = 0;
print;
common.CreateNoteIndex();
ReadAnalytics();
compose();
| [
[
1,
0,
0.0132,
0.0132,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.0263,
0.0132,
0,
0.66,
0.0769,
308,
0,
1,
0,
0,
308,
0,
0
],
[
1,
0,
0.0395,
0.0132,
0,
... | [
"import re",
"import config",
"import common",
"import random",
"import array",
"SuccessorList = {};",
"NumVerses = 12; # Num of verses in the composition. 1 Verse = 1 cycle of tala",
"def ReadAnalytics():\n\tf = open(config.OutFile,'r');\n\tfor line in f:\n\t\ttemp = re.split('\\s+',line);\n\t\tdef c... |
RagaDef = {};
RagaDef['Mohana'] = ['Sa','Re','Ga','Pa','Da'];
RagaDef['SriRanjani'] = ['Sa','Re','Ga','Ma','Da','Ni'];
| [
[
14,
0,
0.4,
0.2,
0,
0.66,
0,
689,
0,
0,
0,
0,
0,
6,
0
],
[
14,
0,
0.8,
0.2,
0,
0.66,
0.5,
0,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
1,
0.2,
0,
0.66,
1,
0,
0,... | [
"RagaDef = {};",
"RagaDef['Mohana'] = ['Sa','Re','Ga','Pa','Da'];",
"RagaDef['SriRanjani'] = ['Sa','Re','Ga','Ma','Da','Ni'];"
] |
Path='../corpus/Mohana'
Raga='Mohana'
Tala='Adi'
Instrument='Piano'
MarkovOrder=3;
OutFile='Analytics.txt'
| [
[
14,
0,
0.1667,
0.1667,
0,
0.66,
0,
754,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.3333,
0.1667,
0,
0.66,
0.2,
99,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.5,
0.1667,
0,
0.66,
... | [
"Path='../corpus/Mohana'",
"Raga='Mohana'",
"Tala='Adi'",
"Instrument='Piano'",
"MarkovOrder=3;",
"OutFile='Analytics.txt'"
] |
#Archivo: Modulo Serial
#Version:1
#Autores: Yimy Juarez, Manuel Arana, Irrael Eduardo
#Descripcion: Este programa es un modulo que permite enviar los
#datos al puerto serial, mediante el parametro ingresado.
#Modificacion: 22 de Mayo de 2011
#----------------Se importan los modulos
import time
import serial
def envio(dato):
dato=str(dato)#Se convierte el dato a str
dato=dato[::-1]#Se da vuelta al dato recibido
aux1=list(dato)#Se convierte en una lista el dato
ser = serial.Serial(0)#Se abre el puerto serial numero 0
for contador in aux1:#Bucle encargado del envio de los datos uno a uno
print contador
ser.write(contador) #Se envia cada dato al puerto serial
time.sleep(1)#Se espera cierto tiempo para enviar el siguiente dato
ser.close()
| [
[
1,
0,
0.4,
0.05,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.45,
0.05,
0,
0.66,
0.5,
601,
0,
1,
0,
0,
601,
0,
0
],
[
2,
0,
0.725,
0.5,
0,
0.66,
1,
... | [
"import time",
"import serial",
"def envio(dato):\n dato=str(dato)#Se convierte el dato a str\n dato=dato[::-1]#Se da vuelta al dato recibido\n aux1=list(dato)#Se convierte en una lista el dato\n ser = serial.Serial(0)#Se abre el puerto serial numero 0\n for contador in aux1:#Bucle encargado del ... |
#!/usr/bin/env python2
import subprocess, time, os, sys, random
def instanceFromFile(path):
f = open(path)
input = ""
for line in f:
input += line
return input.strip()
def toDot(path):
f = open(path)
input = []
for line in f:
input.append(line.strip())
input = input[1:]
dotFile = ""
dotFile += "Graph G {\n"
for line in input:
dotFile += line.replace(" ", " -- ", 1) + ";\n"
dotFile += "}\n"
subp = subprocess.Popen(["dot", "-Tpng", "-o"+path+".png"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=dotFile)[0]
def launch(cmd, input):
command = [cmd]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip()
folder = "tests/"
n = 2
count = 100
output1 = ""
output2 = ""
output3 = ""
output4 = ""
res = open("resultados.txt", "w+")
while n < 100:
m = ((n-1)*(n-2)/2) +1
matriz = []
for i in range(n):
matriz.append([])
for j in range(n):
matriz[i].append(0)
i = 0
while i < m:
x = random.randint(0,n-1)
y = random.randint(0,n-1)
if((y == x) or (matriz[x][y] == 1)):
continue
matriz[x][y] = 1
matriz[y][x] = 1
i = i+1
filename = folder + "test-" + str(n) + ".txt"
fle = open(filename, "w+")
print "Generating test: " + filename + "..."
fle.write(str(n) + " " + str(m) + "\n")
for i in range (n):
for j in range(i,n):
if matriz[i][j] == 1:
fle.write(str(i+1) + " " + str(j+1) + "\n")
fle.close()
toDot(filename)
output1 = launch("./exacto", instanceFromFile(filename))
output2 = launch("./goloso", instanceFromFile(filename))
output3 = launch("./local", instanceFromFile(filename))
output4 = launch("./tabu", instanceFromFile(filename))
res.write(filename + " -- Exacto: " + output1 + "\n")
res.write(filename + " -- Goloso: " + output2 + "\n")
res.write(filename + " -- Local: " + output3 + "\n")
res.write(filename + " -- Tabu: " + output4 + "\n")
res.write("------------------------------------------------------------------\n")
n = n+1
res.close()
| [
[
1,
0,
0.0316,
0.0105,
0,
0.66,
0,
394,
0,
5,
0,
0,
394,
0,
0
],
[
2,
0,
0.0789,
0.0632,
0,
0.66,
0.0769,
709,
0,
1,
1,
0,
0,
0,
2
],
[
14,
1,
0.0632,
0.0105,
1,
0... | [
"import subprocess, time, os, sys, random",
"def instanceFromFile(path):\n\tf = open(path)\n\tinput = \"\"\n\tfor line in f:\n\t\tinput += line\n\treturn input.strip()",
"\tf = open(path)",
"\tinput = \"\"",
"\tfor line in f:\n\t\tinput += line",
"\treturn input.strip()",
"def toDot(path):\n\tf = open(p... |
#!/usr/bin/env python2
import subprocess, time, os, sys, random
def instanceFromFile(path):
f = open(path)
input = ""
for line in f:
input += line
return input.strip()
def toDot(path):
f = open(path)
input = []
for line in f:
input.append(line.strip())
input = input[1:]
dotFile = ""
dotFile += "Graph G {\n"
for line in input:
dotFile += line.replace(" ", " -- ", 1) + ";\n"
dotFile += "}\n"
subp = subprocess.Popen(["dot", "-Tpng", "-o"+path+".png"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=dotFile)[0]
def launch(cmd, input):
command = [cmd]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip()
folder = "tests/"
n = 2
count = 100
output1 = ""
output2 = ""
output3 = ""
output4 = ""
res = open("resultados.txt", "w+")
while n < 100:
m = ((n-1)*(n-2)/2) +1
matriz = []
for i in range(n):
matriz.append([])
for j in range(n):
matriz[i].append(0)
i = 0
while i < m:
x = random.randint(0,n-1)
y = random.randint(0,n-1)
if((y == x) or (matriz[x][y] == 1)):
continue
matriz[x][y] = 1
matriz[y][x] = 1
i = i+1
filename = folder + "test-" + str(n) + ".txt"
fle = open(filename, "w+")
print "Generating test: " + filename + "..."
fle.write(str(n) + " " + str(m) + "\n")
for i in range (n):
for j in range(i,n):
if matriz[i][j] == 1:
fle.write(str(i+1) + " " + str(j+1) + "\n")
fle.close()
toDot(filename)
output1 = launch("./exacto", instanceFromFile(filename))
output2 = launch("./goloso", instanceFromFile(filename))
output3 = launch("./local", instanceFromFile(filename))
output4 = launch("./tabu", instanceFromFile(filename))
res.write(filename + " -- Exacto: " + output1 + "\n")
res.write(filename + " -- Goloso: " + output2 + "\n")
res.write(filename + " -- Local: " + output3 + "\n")
res.write(filename + " -- Tabu: " + output4 + "\n")
res.write("------------------------------------------------------------------\n")
n = n+1
res.close()
| [
[
1,
0,
0.0316,
0.0105,
0,
0.66,
0,
394,
0,
5,
0,
0,
394,
0,
0
],
[
2,
0,
0.0789,
0.0632,
0,
0.66,
0.0769,
709,
0,
1,
1,
0,
0,
0,
2
],
[
14,
1,
0.0632,
0.0105,
1,
0... | [
"import subprocess, time, os, sys, random",
"def instanceFromFile(path):\n\tf = open(path)\n\tinput = \"\"\n\tfor line in f:\n\t\tinput += line\n\treturn input.strip()",
"\tf = open(path)",
"\tinput = \"\"",
"\tfor line in f:\n\t\tinput += line",
"\treturn input.strip()",
"def toDot(path):\n\tf = open(p... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import subprocess, time, os, sys
cmf = "./cmf"
iterations = 1000
def instanceFromFile(path):
f = open(path)
input = ""
for line in f:
input += line
return input.strip()
def getTestFiles(folder, ext):
testFiles = []
for root, dirs, files in os.walk(folder):
for file in files:
if file.endswith(ext):
testFiles.append(os.path.join(root, file)[:-3])
return testFiles
def launch(input):
command = [cmf]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip()
def testSerie(dir):
hits = 0
miss = 0
maxdiff = 0
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
predicted = instanceFromFile(inputFiles[i] + ".out")
maxdiff = max(maxdiff, abs(int(output.split()[0]) - int(predicted.split()[0])))
if(output.split()[0] == predicted.split()[0]):
hits += 1
print inputFiles[i] + " aprobado!"
else:
miss += 1
print inputFiles[i] + " falló!"
print "\toutput > " + output
print "\tpredicted > " + predicted
print str(hits) + " hits / " + str(miss) + " miss / max-diff: " + str(maxdiff)
def testTimeSerie(dir):
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
totalTime = 0
for j in range(iterations):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
totalTime += int(output)
totalTime = totalTime / iterations
print inputFiles[i] + "\t" + str(totalTime)
#testSerie("SerieA1")
#testSerie("SerieA2")
#testSerie("SerieB")
testTimeSerie("SerieA1")
testTimeSerie("SerieA2")
testTimeSerie("SerieB") | [
[
1,
0,
0.0494,
0.0123,
0,
0.66,
0,
394,
0,
4,
0,
0,
394,
0,
0
],
[
14,
0,
0.0741,
0.0123,
0,
0.66,
0.1,
517,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0864,
0.0123,
0,
0.6... | [
"import subprocess, time, os, sys",
"cmf = \"./cmf\"",
"iterations = 1000",
"def instanceFromFile(path):\n\tf = open(path)\n\tinput = \"\"\n\tfor line in f:\n\t\tinput += line\n\treturn input.strip()",
"\tf = open(path)",
"\tinput = \"\"",
"\tfor line in f:\n\t\tinput += line",
"\treturn input.strip()... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import subprocess, time, os, sys
cmf = "./cmf"
iterations = 1000
def instanceFromFile(path):
f = open(path)
input = ""
for line in f:
input += line
return input.strip()
def getTestFiles(folder, ext):
testFiles = []
for root, dirs, files in os.walk(folder):
for file in files:
if file.endswith(ext):
testFiles.append(os.path.join(root, file)[:-3])
return testFiles
def launch(input):
command = [cmf]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip()
def testSerie(dir):
hits = 0
miss = 0
maxdiff = 0
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
predicted = instanceFromFile(inputFiles[i] + ".out")
maxdiff = max(maxdiff, abs(int(output.split()[0]) - int(predicted.split()[0])))
if(output.split()[0] == predicted.split()[0]):
hits += 1
print inputFiles[i] + " aprobado!"
else:
miss += 1
print inputFiles[i] + " falló!"
print "\toutput > " + output
print "\tpredicted > " + predicted
print str(hits) + " hits / " + str(miss) + " miss / max-diff: " + str(maxdiff)
def testTimeSerie(dir):
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
totalTime = 0
for j in range(iterations):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
totalTime += int(output)
totalTime = totalTime / iterations
print inputFiles[i] + "\t" + str(totalTime)
#testSerie("SerieA1")
#testSerie("SerieA2")
#testSerie("SerieB")
testTimeSerie("SerieA1")
testTimeSerie("SerieA2")
testTimeSerie("SerieB") | [
[
1,
0,
0.0494,
0.0123,
0,
0.66,
0,
394,
0,
4,
0,
0,
394,
0,
0
],
[
14,
0,
0.0741,
0.0123,
0,
0.66,
0.1,
517,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0864,
0.0123,
0,
0.6... | [
"import subprocess, time, os, sys",
"cmf = \"./cmf\"",
"iterations = 1000",
"def instanceFromFile(path):\n\tf = open(path)\n\tinput = \"\"\n\tfor line in f:\n\t\tinput += line\n\treturn input.strip()",
"\tf = open(path)",
"\tinput = \"\"",
"\tfor line in f:\n\t\tinput += line",
"\treturn input.strip()... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import subprocess, time, os, sys
cmf = "./cmf"
iterations = 50
def instanceFromFile(path):
f = open(path)
input = ""
for line in f:
input += line
return input.strip()
def getTestFiles(folder, ext):
testFiles = []
for root, dirs, files in os.walk(folder):
for file in files:
if file.endswith(ext):
testFiles.append(os.path.join(root, file)[:-3])
return testFiles
def launch(input):
command = [cmf]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip()
def testSerie(dir):
hits = 0
miss = 0
maxdiff = 0
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
predicted = instanceFromFile(inputFiles[i] + ".out")
maxdiff = max(maxdiff, abs(int(output.split()[0]) - int(predicted.split()[0])))
if(output.split()[0] == predicted.split()[0]):
hits += 1
print inputFiles[i] + " aprobado!"
else:
miss += 1
print inputFiles[i] + " falló!"
print "\toutput > " + output
print "\tpredicted > " + predicted
print str(hits) + " hits / " + str(miss) + " miss / max-diff: " + str(maxdiff)
def testTimeSerie(dir):
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
totalTime = 0
for j in range(iterations):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
totalTime += int(output)
totalTime = totalTime / iterations
print inputFiles[i] + "\t" + str(totalTime)
#testSerie("SerieA1")
#testSerie("SerieA2")
#testSerie("SerieB")
testTimeSerie("SerieA1")
testTimeSerie("SerieA2")
testTimeSerie("SerieB")
| [
[
1,
0,
0.0494,
0.0123,
0,
0.66,
0,
394,
0,
4,
0,
0,
394,
0,
0
],
[
14,
0,
0.0741,
0.0123,
0,
0.66,
0.1,
517,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0864,
0.0123,
0,
0.6... | [
"import subprocess, time, os, sys",
"cmf = \"./cmf\"",
"iterations = 50",
"def instanceFromFile(path):\n\tf = open(path)\n\tinput = \"\"\n\tfor line in f:\n\t\tinput += line\n\treturn input.strip()",
"\tf = open(path)",
"\tinput = \"\"",
"\tfor line in f:\n\t\tinput += line",
"\treturn input.strip()",... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import subprocess, time, os, sys
cmf = "./cmf"
iterations = 50
def instanceFromFile(path):
f = open(path)
input = ""
for line in f:
input += line
return input.strip()
def getTestFiles(folder, ext):
testFiles = []
for root, dirs, files in os.walk(folder):
for file in files:
if file.endswith(ext):
testFiles.append(os.path.join(root, file)[:-3])
return testFiles
def launch(input):
command = [cmf]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip()
def testSerie(dir):
hits = 0
miss = 0
maxdiff = 0
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
predicted = instanceFromFile(inputFiles[i] + ".out")
maxdiff = max(maxdiff, abs(int(output.split()[0]) - int(predicted.split()[0])))
if(output.split()[0] == predicted.split()[0]):
hits += 1
print inputFiles[i] + " aprobado!"
else:
miss += 1
print inputFiles[i] + " falló!"
print "\toutput > " + output
print "\tpredicted > " + predicted
print str(hits) + " hits / " + str(miss) + " miss / max-diff: " + str(maxdiff)
def testTimeSerie(dir):
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
totalTime = 0
for j in range(iterations):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
totalTime += int(output)
totalTime = totalTime / iterations
print inputFiles[i] + "\t" + str(totalTime)
#testSerie("SerieA1")
#testSerie("SerieA2")
#testSerie("SerieB")
testTimeSerie("SerieA1")
testTimeSerie("SerieA2")
testTimeSerie("SerieB")
| [
[
1,
0,
0.0494,
0.0123,
0,
0.66,
0,
394,
0,
4,
0,
0,
394,
0,
0
],
[
14,
0,
0.0741,
0.0123,
0,
0.66,
0.1,
517,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0864,
0.0123,
0,
0.6... | [
"import subprocess, time, os, sys",
"cmf = \"./cmf\"",
"iterations = 50",
"def instanceFromFile(path):\n\tf = open(path)\n\tinput = \"\"\n\tfor line in f:\n\t\tinput += line\n\treturn input.strip()",
"\tf = open(path)",
"\tinput = \"\"",
"\tfor line in f:\n\t\tinput += line",
"\treturn input.strip()",... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import subprocess, time, os, sys
cmf = "./cmf"
iterations = 1000
def instanceFromFile(path):
f = open(path)
input = ""
for line in f:
input += line
return input.strip()
def getTestFiles(folder, ext):
testFiles = []
for root, dirs, files in os.walk(folder):
for file in files:
if file.endswith(ext):
testFiles.append(os.path.join(root, file)[:-3])
return testFiles
def launch(input):
command = [cmf]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip()
def testSerie(dir):
hits = 0
miss = 0
maxdiff = 0
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
predicted = instanceFromFile(inputFiles[i] + ".out")
maxdiff = max(maxdiff, abs(int(output.split()[0]) - int(predicted.split()[0])))
if(output.split()[0] == predicted.split()[0]):
hits += 1
print inputFiles[i] + " aprobado!"
else:
miss += 1
print inputFiles[i] + " falló!"
print "\toutput > " + output
print "\tpredicted > " + predicted
print str(hits) + " hits / " + str(miss) + " miss / max-diff: " + str(maxdiff)
def testTimeSerie(dir):
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
totalTime = 0
for j in range(iterations):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
totalTime += int(output)
totalTime = totalTime / iterations
print inputFiles[i] + "\t" + str(totalTime)
#testSerie("SerieA1")
#testSerie("SerieA2")
#testSerie("SerieB")
testTimeSerie("SerieA1")
testTimeSerie("SerieA2")
testTimeSerie("SerieB") | [
[
1,
0,
0.0494,
0.0123,
0,
0.66,
0,
394,
0,
4,
0,
0,
394,
0,
0
],
[
14,
0,
0.0741,
0.0123,
0,
0.66,
0.1,
517,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0864,
0.0123,
0,
0.6... | [
"import subprocess, time, os, sys",
"cmf = \"./cmf\"",
"iterations = 1000",
"def instanceFromFile(path):\n\tf = open(path)\n\tinput = \"\"\n\tfor line in f:\n\t\tinput += line\n\treturn input.strip()",
"\tf = open(path)",
"\tinput = \"\"",
"\tfor line in f:\n\t\tinput += line",
"\treturn input.strip()... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import subprocess, time, os, sys
cmf = "./cmf"
iterations = 1000
def instanceFromFile(path):
f = open(path)
input = ""
for line in f:
input += line
return input.strip()
def getTestFiles(folder, ext):
testFiles = []
for root, dirs, files in os.walk(folder):
for file in files:
if file.endswith(ext):
testFiles.append(os.path.join(root, file)[:-3])
return testFiles
def launch(input):
command = [cmf]
subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = subp.communicate(input=input)[0]
return stdout.strip()
def testSerie(dir):
hits = 0
miss = 0
maxdiff = 0
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
predicted = instanceFromFile(inputFiles[i] + ".out")
maxdiff = max(maxdiff, abs(int(output.split()[0]) - int(predicted.split()[0])))
if(output.split()[0] == predicted.split()[0]):
hits += 1
print inputFiles[i] + " aprobado!"
else:
miss += 1
print inputFiles[i] + " falló!"
print "\toutput > " + output
print "\tpredicted > " + predicted
print str(hits) + " hits / " + str(miss) + " miss / max-diff: " + str(maxdiff)
def testTimeSerie(dir):
inputFiles = getTestFiles("./" + dir, ".in")
inputFiles.sort()
for i in range(len(inputFiles)):
totalTime = 0
for j in range(iterations):
input = instanceFromFile(inputFiles[i] + ".in")
output = launch(input)
totalTime += int(output)
totalTime = totalTime / iterations
print inputFiles[i] + "\t" + str(totalTime)
#testSerie("SerieA1")
#testSerie("SerieA2")
#testSerie("SerieB")
testTimeSerie("SerieA1")
testTimeSerie("SerieA2")
testTimeSerie("SerieB") | [
[
1,
0,
0.0494,
0.0123,
0,
0.66,
0,
394,
0,
4,
0,
0,
394,
0,
0
],
[
14,
0,
0.0741,
0.0123,
0,
0.66,
0.1,
517,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0864,
0.0123,
0,
0.6... | [
"import subprocess, time, os, sys",
"cmf = \"./cmf\"",
"iterations = 1000",
"def instanceFromFile(path):\n\tf = open(path)\n\tinput = \"\"\n\tfor line in f:\n\t\tinput += line\n\treturn input.strip()",
"\tf = open(path)",
"\tinput = \"\"",
"\tfor line in f:\n\t\tinput += line",
"\treturn input.strip()... |
__all__=["bubblesort","insertionsort"]
| [
[
14,
0,
1,
1,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
]
] | [
"__all__=[\"bubblesort\",\"insertionsort\"]"
] |
#!/usr/bin/python
"""
Heapsort implementation
"""
def siftup(x, n):
i = n
c = x[i] #x[i] == c
while True:
p = i / 2
if x[p] >= c:
break
x[i] = x[p]
i = p
x[i] = c
def siftdown(x, n):
if n <= 1: return
i = 1
c = x[i]
while True:
p = 2 * i
if p > n: break
if p + 1 <= n and x[p+1] > x[p]:
p += 1
if x[p] <= c:
break
x[i] = x[p]
i = p # x[i] is imaginarily c
x[i] = c
def swap(x, i, j):
tmp = x[i]
x[i] = x[j]
x[j] = tmp
def Heapsort(x, n):
"""
x is an array with x[0] as sentinel, x[1] to x[n] as valid values
"""
for i in range(2, n+1):
siftup(x, i)
for i in range(n, 1, -1):
swap(x, 1, i)
siftdown(x, i-1)
if __name__ == '__main__':
import unittest
try:
treePainter = True
from btree import *
except ImportError:
treePainter = False
class heapTest(unittest.TestCase):
@staticmethod
def checkSorted(x):
y = x[1:]
y.sort()
y.insert(0, x[0])
if x == y:
return True
else:
return False
@staticmethod
def printHeap(x, n):
if not treePainter: return
tree = binSearchTree()
tree.buildFromArray(x[1:n+1])
painter = BinTreeTextPainter()
tree.paintTree(painter)
painter.display()
def runOneCase(self):
minv = -99
maxv = 99
x = [maxv]
from random import randint
n = randint(1, 19)
for i in range(0, n):
x.append(randint(minv+1, maxv))
Heapsort(x, n)
heapTest.printHeap(x, n)
self.assertTrue(heapTest.checkSorted(x))
del x
def testHeapSort(self):
for i in range(1, 19):
self.runOneCase()
unittest.main()
| [
[
8,
0,
0.04,
0.03,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
2,
0,
0.12,
0.11,
0,
0.66,
0.2,
356,
0,
2,
0,
0,
0,
0,
0
],
[
14,
1,
0.08,
0.01,
1,
0.87,
0,
826... | [
"\"\"\"\nHeapsort implementation\n\"\"\"",
"def siftup(x, n):\n i = n\n c = x[i] #x[i] == c\n while True:\n p = i / 2\n if x[p] >= c:\n break\n x[i] = x[p]",
" i = n",
" c = x[i] #x[i] == c",
" while True:\n p = i / 2\n if x[p] >= c:\n ... |
#!/usr/bin/python
"""
Binary Tree implementation and visualization
"""
import os
import sys
pygraphvizOk = True
try:
import pygraphviz
except ImportError:
pygraphvizOk = False
__metaclass__ = type
class BinTree:
def __init__(self, value = 0, parent = None, label='', left=None, right=None):
self.value=value
self.left=left
self.right=right
self.parent = parent
self.count = 1
if label == '':
self.label = str(value)
else:
self.label = label
def __del__(self):
if self.right:
del self.right
if self.left:
del self.left
def buildFromArray(self, array):
"""
Build a binary tree from linear array, s.t. root value is set to array[0];
for nodes with value array[i], its left child has value array[i*2+1] and right child has array[i*2+2]
"""
self.insertFromArray(array, 0)
def insertFromArray(self, array, array_pos):
"""
recursively set tree node value from array,
so that self get value array[array_pos] and conforms to rules for buildFromArray
"""
array_len = len(array)
self.value = array[array_pos]
self.label = str(self.value)
left_pos = array_pos * 2 + 1
right_pos = left_pos + 1
if right_pos < array_len:
child = self.insertLeft()
child.insertFromArray(array, left_pos)
child = self.insertRight()
child.insertFromArray(array, right_pos)
elif left_pos < array_len:
child = self.insertLeft()
child.insertFromArray(array, left_pos)
def insertLeft(self,value = 0):
if not self.left:
self.left=BinTree(value, self)
child = self.left
child.value = value
child.label = str(value)
return child
def insertRight(self,value=0):
if not self.right:
self.right=BinTree()
child = self.right
child.value = value
child.parent = self
child.label = str(value)
return child
def getNodeCount(self):
"""
Number of nodes in the tree with self as root
"""
count = 1
if self.right:
count += self.right.getNodeCount()
if self.left:
count += self.left.getNodeCount()
return count
def getTreeHeight(tree):
"""
Return height of a tree, s.t. a single-node-tree has height 1
"""
if tree.right == None:
rightH = 0
else:
rightH = tree.right.getTreeHeight()
if tree.left == None:
leftH = 0
else:
leftH = tree.left.getTreeHeight()
return max([leftH, rightH]) + 1
def paintTree(self, painter):
"""
Visualize the tree with any object featuring obj.paint(tree) interface
"""
painter.paint(self)
def inOrderFuncTraverse(self, func):
if self.left:
self.left.inOrderFuncTraverse(func)
func(self)
if self.right:
self.right.inOrderTraverse(func)
def preOrderFuncTraverse(self, func):
func(self)
if self.left:
self.left.preOrderFuncTraverse(func)
if self.right:
self.right.preOrderFuncTraverse(func)
def postOrderFuncTraverse(self, func):
if self.left:
self.left.postOrderFuncTraverse(func)
if self.right:
self.right.postOrderFuncTraverse(func)
func(self)
class binSearchTree(BinTree):
pass
class BinTreePainterBase:
"""
Base class of binary tree painters that visualize BinTree objects
"""
def __clear__(self):
self.scriptFile = None
def __init__(self, imageName, scriptSuffix='', imageType='png'):
self.scriptName = imageName + '.' +scriptSuffix
self.scriptFile = None
self.imageType = imageType
self.imageName = imageName+'.'+imageType
self.__clear__()
def display(self):
if not os.path.isfile(self.imageName):
return
if self.imageType == 'pdf':
os.system('evince %s' % self.imageName)
elif self.imageType == 'png':
os.system('eog %s' % self.imageName)
def paintNode(self, node):
pass
def paintBegin(self, tree):
pass
def paintEnd(self, tree):
pass
def paint(self, tree):
self.paintBegin(tree)
tree.preOrderFuncTraverse(self.paintNode)
self.paintEnd(tree)
class BinTreeTikztreePainter(BinTreePainterBase):
"""
Binary tree painter, which can visualize a BinTree Object with latex's tikz tree drawing functionality
"""
def __init__(self, imageName='tikzTree', imageType='pdf', sep=20):
super(BinTreeTikztreePainter, self).__init__(imageName, 'tex', imageType)
self.sep = sep
def paintBegin(self, tree):
height = tree.getTreeHeight()
self.scriptFile.write("\\documentclass[11pt,a4paper]{article}\n\n")
self.scriptFile.write("\\uself.sepackage{tikz}\n\n")
self.scriptFile.write("\\begin{document}\n\n")
self.scriptFile.write("\\tikzset{ box/.style={\n")
self.scriptFile.write("rectangle, minimum width=.001\\textwidth, very thick, draw=gray!50!black!50, text centered,\n")
self.scriptFile.write("top color=white, bottom color=gray!50!black!20},\n")
self.scriptFile.write("every node/.style={text centered, font=\\footnotesize, text width=0.03\\textwidth}\n")
self.scriptFile.write("}\n\n")
self.scriptFile.write("\\begin{tikzpicture}[")
while height > 1:
self.scriptFile.write("level %d/.style={sibling distance=%dpt},\n"%(height, self.sep))
height -= 1
self.sep *= 2
self.scriptFile.write("level 1/.style={sibling distance=%dpt}]\n\n\\"%self.sep)
def paintEnd(self):
self.scriptFile.write(";\n\\end{tikzpicture}\n")
self.scriptFile.write("\\end{document}\n")
def doPaint(self, node):
assert node
self.scriptFile.write("node[box] {%s}\n" % node.label)
if node.left:
self.scriptFile.write("child {\n")
self.doPaint(node.left)
self.scriptFile.write("}\n")
if node.right:
self.scriptFile.write("child {\n")
self.doPaint(node.right)
self.scriptFile.write("}\n")
def __runTex__(self):
if self.imageType == 'pdf':
os.system('pdflatex %s' % self.scriptName)
os.system('rm -f %s' % self.scriptName)
else:
print 'Formats other than PDF not supported'
def paint(self, tree):
with open(self.scriptName, 'w') as self.scriptFile:
self.paintBegin(tree)
if tree:
self.doPaint(tree)
self.paintEnd()
self.scriptFile.close()
self.__runTex__()
self.__clear__()
class BinTreeGraphvizPainter(BinTreePainterBase):
"""
Binary tree painter, which visualizes a BinTree Object with Graphviz's dot language
"""
def __init__(self, imageName='graphvizTree', imageType='png'):
super(BinTreeGraphvizPainter, self).__init__(imageName, 'dot', imageType)
def paintNode(self, node):
if not node: return
self.scriptFile.write('%d[label="%s"];\n' % (id(node), node.label))
if node.left and node.right:
self.scriptFile.write('%d->{%d; %d};\n' % (id(node), id(node.left), id(node.right)))
elif node.left:
self.scriptFile.write('%d->%d;\n' % (id(node), id(node.left)))
elif node.right:
self.scriptFile.write('%d->%d;\n' % (id(node), id(node.right)))
def paintBegin(self, tree):
if not tree: return
self.scriptFile = open(self.scriptName, 'w')
self.scriptFile.write('digraph g {\n')
self.scriptFile.write(' node[shape=record];\n')
def paintEnd(self, tree):
self.scriptFile.write('}')
self.scriptFile.close()
os.system('dot -T%s -o %s %s' % (self.imageType, self.imageName, self.scriptName))
self.__clear__()
class BinTreePinpointPainter(BinTreePainterBase):
"""
Base to some binary tree painters,
which visualize a BinTree Object with precise tree node X-Y positioning
"""
def __clear__(self):
self.curXpos = 0
self.curYpos = 0
self.graphMap = []
def __init__(self, imageName='absPosTree', scriptSuffix='dot', imageType='png'):
super(BinTreePinpointPainter, self).__init__(imageName, scriptSuffix, imageType)
self.__clear__()
def doPinPoint(self, node):
assert node
if node.left:
self.curYpos -= 1
self.doPinPoint(node.left)
self.curYpos += 1
self.graphMap[self.curYpos].append((node, self.curXpos))
if node.right:
self.curXpos += 1
self.curYpos -= 1
self.doPinPoint(node.right)
self.curYpos += 1
def pinPoint(self, tree):
if not tree: return
self.__clear__()
height = tree.getTreeHeight()
for i in range(0, height):
self.graphMap.append([])
self.curYpos = height - 1
self.doPinPoint(tree)
def paintBegin(self, tree):
pass
def paintEnd(self, tree):
pass
def paintNode(self, node, xpos, ypos):
pass
def paint(self, tree):
self.pinPoint(tree)
height = tree.getTreeHeight()
self.paintBegin(tree)
while height > 0:
height -= 1
for mapNode in self.graphMap[height]:
self.paintNode(mapNode[0], mapNode[1], height)
self.paintEnd(tree)
self.__clear__()
if pygraphvizOk:
#Only when python-pygraphviz is installed
class BinTreePygraphvizPainter(BinTreePinpointPainter):
"""
Binary tree painter, which visualizes a BinTree Object with Pygraphviz module
"""
def __init__(self, imageName='pygraphvizTree', imageType='png'):
super(BinTreePygraphvizPainter, self).__init__(imageName, 'dot', imageType)
def paintBegin(self, tree):
self.graph = pygraphviz.AGraph(directed=True)
def paintEnd(self, tree):
self.graph.layout()
self.graph.draw(self.imageName, self.imageType)
self.graph = None
def paintNode(self, node, xpos, ypos):
self.graph.add_node(id(node), label=node.label)
graphNode = self.graph.get_node(id(node))
graphNode.attr['pos'] = '%d,%d!'%(xpos, ypos*1.5)
if node.left:
self.graph.add_node(id(node.left), label=node.left.label)
self.graph.add_edge(id(node), id(node.left))
if node.right:
self.graph.add_node(id(node.right), label=node.right.label)
self.graph.add_edge(id(node), id(node.right))
class BinTreeTextPainter(BinTreePinpointPainter):
"""
Binary tree text painter. Paints on stdout.
"""
def __init__(self, imageName='textTree', imageType='txt'):
super(BinTreeTextPainter, self).__init__(imageName, 'txt', imageType)
def paintBegin(self, tree):
self.curXpos = 0
self.curYpos = tree.getTreeHeight() - 1
def paintEnd(self, tree):
print '\n'
def paintNode(self, node, xpos, ypos):
if self.curYpos == ypos + 1:
print '\n'
self.curYpos -= 1
self.curXpos = 0
if self.curYpos != ypos: return
assert self.curXpos <= xpos
while self.curXpos < xpos:
self.curXpos += 1
print ' ',
print '%4s'%node.label,
self.curXpos += 1
class BinTreeTikzPainter(BinTreePinpointPainter):
"""
Binary tree painter, which visualizes a BinTree Object with latex's tikz node drawing functionality
"""
def __init__(self, imageName='tikznodeTree', imageType='pdf'):
super(BinTreeTikzPainter, self).__init__(imageName, 'tex', imageType)
def __runTex__(self):
if self.imageType == 'pdf':
os.system('pdflatex %s' % self.scriptName)
os.system('rm -f %s' % self.scriptName)
else:
print 'Formats other than PDF not supported'
def paintBegin(self, tree):
self.scriptFile = open(self.scriptName, 'w')
self.scriptFile.write("\\documentclass[11pt,a4paper]{article}\n\n")
self.scriptFile.write("\\usepackage{tikz}\n\n")
self.scriptFile.write("\\begin{document}\n\n")
self.scriptFile.write("\\tikzset{ box/.style={\n")
self.scriptFile.write("rectangle, minimum width=.001\\textwidth, very thick, draw=gray!50!black!50, text centered,\n")
self.scriptFile.write("top color=white, bottom color=gray!50!black!20},\n")
self.scriptFile.write("every node/.style={text centered, font=\\footnotesize, text width=0.03\\textwidth}\n")
self.scriptFile.write("}\n\n")
self.scriptFile.write("\\begin{tikzpicture}[every path/.style={draw, thick, ->}]")
def paintEnd(self, tree):
self.scriptFile.write("\n\\end{tikzpicture}\n")
self.scriptFile.write("\\end{document}\n")
self.scriptFile.close()
self.__runTex__()
def paintNode(self, node, xpos, ypos):
self.scriptFile.write("\\node[box] at(%f, %f) (%s) {%s};\n\n" % (xpos, ypos, id(node), node.label))
if node.parent:
self.scriptFile.write("\path(%s) -- (%s);\n\n" % (id(node.parent), id(node)))
if __name__ == '__main__':
import unittest
class painterTest(unittest.TestCase):
def testPainter(self):
minv = -99
maxv = 99
x = [maxv]
from random import randint
n = randint(1, 19)
for i in range(0, n):
x.append(randint(minv+1, maxv))
tree = binSearchTree()
tree.buildFromArray(x[1:n+1])
txtPainter = BinTreeTextPainter()
tree.paintTree(txtPainter)
if pygraphvizOk:
painter = BinTreePygraphvizPainter()
tree.paintTree(painter)
painter.display()
unittest.main()
| [
[
8,
0,
0.0087,
0.0065,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0152,
0.0022,
0,
0.66,
0.0667,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0174,
0.0022,
0,
0.66... | [
"\"\"\"\nBinary Tree implementation and visualization\n\"\"\"",
"import os",
"import sys",
"pygraphvizOk = True",
"try:\n import pygraphviz\nexcept ImportError:\n pygraphvizOk = False",
" import pygraphviz",
" pygraphvizOk = False",
"__metaclass__ = type",
"class BinTree:\n def __... |
#!/usr/bin/python
import sys
import os, commands
"""
Run program from source code directly. Support C, C++, Java, etc
"""
if len(sys.argv) < 2:
print 'Usage: %s sourcefile' % os.path.basename(sys.argv[0])
sourcename = sys.argv[1]
handler = None
if len(sourcename.split('.')) > 1:
suffix = sourcename.split('.')[1]
if suffix == 'cpp' or suffix == 'cxx':
handler = 'g++'
elif suffix == 'c':
handler = 'gcc'
elif suffix == 'py' or suffix == 'pyw':
handler = 'python'
elif suffix == 'java':
handler = 'javac'
else:
handler = suffix
if handler is None:
os.system('./%s' % sourcename)
sys.exit(0)
fpath = commands.getoutput('which %s'% handler)
if not (os.path.isfile(fpath) and os.access(fpath, os.X_OK)):
print 'You did not have compiler/interpreter for %s installed' % suffix
sys.exit(1)
if handler == 'g++' or handler == 'gcc':
sourcebase = sourcename.split('.')[0]
os.system('%s -o %s %s' % (handler, sourcebase, sourcename))
os.system('./%s' % sourcebase)
os.system('rm -f %s' % sourcebase)
elif handler == 'javac':
sourcebase = sourcename.split('.')[0]
os.system('%s %s' % (handler, sourcename))
os.system('java %s' % sourcebase)
else:
os.system('%s %s' % (handler, sourcename))
| [
[
1,
0,
0.0441,
0.0147,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0588,
0.0147,
0,
0.66,
0.1,
688,
0,
2,
0,
0,
688,
0,
0
],
[
8,
0,
0.1029,
0.0441,
0,
0.6... | [
"import sys",
"import os, commands",
"\"\"\"\nRun program from source code directly. Support C, C++, Java, etc\n\"\"\"",
"if len(sys.argv) < 2:\n print('Usage: %s sourcefile' % os.path.basename(sys.argv[0]))",
" print('Usage: %s sourcefile' % os.path.basename(sys.argv[0]))",
"sourcename = sys.argv[1... |
#!/usr/bin/python
"""
for the non-integral part of fraction a/b, found the n-th occurence of digit m, where 0 <= m <= 9
2013 Yahoo competition question 1
"""
def getNthPosViolent(a, b, m, n):
import decimal
precision = 2000
decimal.getcontext().prec = precision
a %= b
q = decimal.Decimal(a)/decimal.Decimal(b)
strRep = str(q)
pointPos = strRep.find('.')
pos = 1
nFound = 0
while True:
if int(strRep[pointPos+pos]) == m:
nFound += 1
if nFound == n:
break
pos += 1
if pos >= precision:
break
if nFound == n:
print pos
else:
print 0
def fracDecompose(a, b):
a %= b
divdend = a*10
remainderList = [a]
qDigitList = [0]
pos = 1
RecurStart = -1
RecurEnd = -1
while True:
qDigit = divdend / b
remainder = divdend % b
qDigitList.append(qDigit)
if remainder == 0:
break
if remainder in remainderList:
RecurStart = remainderList.index(remainder) + 1
RecurEnd = pos+1
break
remainderList.append(remainder)
divdend = remainder * 10
pos += 1
if RecurStart == -1:
return qDigitList[1:], []
else:
return qDigitList[1:RecurStart], qDigitList[RecurStart:RecurEnd]
def listNIndex(aList, aElem, nCount):
aPos = 0
assert aList.count(aElem) >= nCount
for elem in aList:
if aElem == elem:
nCount -= 1
if nCount == 0:
return aPos
aPos += 1
def getNthPos(a, b, m, n):
prefix, repetend = fracDecompose(a, b)
if prefix.count(m) >= n:
return 1 + listNIndex(prefix, m, n)
else:
if m not in repetend:
return 0
else:
countLeft = n - prefix.count(m)
if countLeft % repetend.count(m):
nRepetend = countLeft/repetend.count(m) #number of complete repetends to go
else:
nRepetend = countLeft/repetend.count(m)-1 #number of complete repetends to go
countLeft -= nRepetend*repetend.count(m)
return 1 + len(prefix) + nRepetend*len(repetend) + listNIndex(repetend, m, countLeft)
if __name__ == '__main__':
#TO RUN: cat input01.txt | python frac2Digits.py
import sys
firstLine = sys.stdin.readline()
words = firstLine.split()
ntestcase = int(words[0])
for lineno in range(0, ntestcase):
line = sys.stdin.readline()
words = line.split()
a, b, n, m = int(words[0]), int(words[1]),int(words[2]),int(words[3])
print getNthPos(a, b, m, n)
#getNthPosViolent(a, b, m, n)
| [
[
8,
0,
0.0421,
0.0374,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
2,
0,
0.1869,
0.215,
0,
0.66,
0.2,
865,
0,
4,
0,
0,
0,
0,
8
],
[
1,
1,
0.0935,
0.0093,
1,
0.98,
... | [
"\"\"\"\nfor the non-integral part of fraction a/b, found the n-th occurence of digit m, where 0 <= m <= 9\n2013 Yahoo competition question 1\n\"\"\"",
"def getNthPosViolent(a, b, m, n):\n import decimal\n precision = 2000\n decimal.getcontext().prec = precision\n a %= b\n q = decimal.Decimal(a)/de... |
# -*- coding: utf-8 -*-
import partie_1_diff as tn
import numpy as np
# Question 1 :
def elastic_force(k, xo = 0, yo = 0):
"define a k-elastic force"
return lambda x, y: np.array([[-k*x], [-k*y]])
def centrifugal_force(k, xo, yo):
"define a k-elastic force"
return lambda x, y: np.array([[k*(x-xo)], [k*(y-yo)]])
def gravitational_force(k, xo, yo):
"define a k-elastic force"
return lambda x, y: np.array([[-k*(x-xo)/((np.sqrt((x-xo)**2 + (y-yo)**2))**3)], [-k*(y-yo)/((np.sqrt((x-xo)**2 + (y-yo)**2))**3)]])
# Question 2 :
# System : satellite considered as a point with a mass m
# I.F.: - attraction of the sun : f1 with k = 1
# - attraction of the earth : f2 with k = 0,01
# - repulsion of the barycentre (wich may traduce
# the global rotation around the sun): f3 with k = 1
# Newton last postulate:
# equilibrum if and only if : f1 + f2 + f3 = 0
# wich means to look for F.[x y z] 's zeros with F's
# coefficients
# Afin d'éviter de réinstancier à les fonctions f1, f2
# et f3 à chaque appel de F, nous définissons globalement :
f1 = gravitational_force(1, 0.0, 0.0)
f2 = gravitational_force(0.01, 1, 0)
f3 = centrifugal_force(1, 0.01/1.01, 0)
def F (X):
return f1(X[0][0], X[1][0]) + f2(X[0][0], X[1][0]) + f3(X[0][0], X[1][0])
print F(np.array([[1],[1]]))
print "coordonnées de L1 :"
print tn.methode_de_Newton(F, np.array([[0.5],[0]]), 100, 1e-10)
print "\nvaleur de la forcex"
print F(tn.methode_de_Newton(F, np.array([[0.5],[0]]), 100, 1e-10))
#Obtention du point L1 :
#la composée y n'étant pas pertinente, nous allons utiliser l'affichage de la composante y en fonction du temps :
#tn.methode_de_Newton(F, np.array([[0.5],[0]]), 100, 1e-15, 1)
#***************************PARTIE TESTS********************************
print "Obtention du point L1 :"
tn.methode_de_Newton(F, np.array([[0.5],[0.01]]), 100, 1e-10, 2)
print "Obtention du point L2 :"
tn.methode_de_Newton(F, np.array([[1.5],[0.1]]), 100, 1e-10, 2)
print "Obtention du point L3 :"
tn.methode_de_Newton(F, np.array([[-0.5],[0.1]]), 100, 1e-10, 2)
print "Obtention du point L4 :"
tn.methode_de_Newton(F, np.array([[0.5],[0.5]]), 100, 1e-10, 2)
print "Obtention du point L5 :"
tn.methode_de_Newton(F, np.array([[0.5],[-0.5]]), 100, 1e-10, 2)
| [
[
1,
0,
0.0441,
0.0147,
0,
0.66,
0,
570,
0,
1,
0,
0,
570,
0,
0
],
[
1,
0,
0.0588,
0.0147,
0,
0.66,
0.0435,
954,
0,
1,
0,
0,
954,
0,
0
],
[
2,
0,
0.1324,
0.0441,
0,
... | [
"import partie_1_diff as tn",
"import numpy as np",
"def elastic_force(k, xo = 0, yo = 0):\n \"define a k-elastic force\"\n return lambda x, y: np.array([[-k*x], [-k*y]])",
" \"define a k-elastic force\"",
" return lambda x, y: np.array([[-k*x], [-k*y]])",
"def centrifugal_force(k, xo, yo):\n ... |
# -*- coding:utf-8 -*-
# Entry : (f::function, J::jacobian of f, U0::initial value, N::maximum of iteration, epsilon::accuracy)
# Return : U::position vector
import numpy as np
import matplotlib.pyplot as plt
# precision de la derivee :
derivate_accuracy = pow(10, -15)
def methode_de_Newton (f, Uo, N, epsilon, show = 0):
"applies Newton methode to the arguments in parameter"
plt.clf()
cpt = 0
U = Uo
n = len(f(Uo))
m = len(Uo)
v = []
X = []
X.append(U[0][0])
Y = []
Y.append(U[1][0])
while(cpt < N and np.linalg.norm(f(U)) > epsilon):
J = jacobi_of_f_at_U(f, U, n, m)
# solving the equation JX = U,
# we obtain a new point :
U += np.linalg.lstsq(J, -f(U))[0]
if (show == 2):
X.append(U[0][0])
Y.append(U[1][0])
if (show == 1):
v.append(np.abs(f(U)[0][0]))
cpt += 1
if(cpt == N):
print "error: unfinished resolution"
if(show == 1):
plt.semilogy()
plt.plot(range(cpt), v)
plt.show()
if(show == 2):
plt.axis([-2,2,-1.5,1.5])
for i in range(cpt):
plt.scatter(X[i], Y[i], alpha=float(i)/cpt, marker='o')
plt.plot([0],[0], linestyle='None', marker='D', color='yellow')
plt.plot([1], [0], linestyle='None', marker='D', color='green')
plt.show()
return U
# intialy, I thought about defining :
# def derivate(f, x, dir):
# "derivate f in x"
# return lambda dx: (f(x + dx*dir) - f(x))
# But this implies that Jacobi matrix would be a matrix of function.
# Thus matricial product with a vector became an application for this vector.
# It makes linalg.lstq useless, so we have to redo the resolution of an
# matricial equation...
# Then, we choose :
def derivate(f, x, m, j):
"computes the derivate of f at x with with a dx-accuracy"
dx = np.zeros(shape = (m,1))
dx[j,0] = derivate_accuracy
return (f(x+dx)-f(x))/derivate_accuracy
def jacobi_of_f_at_U(f, U, n, m):
"computes jacobi matrix of f at the vector U"
J = np.zeros(shape = (n, m))
for i in range(n):
for j in range(m):
func = lambda X: f(X)[i][0] # fi : R^n -> R
J[i, j] = derivate(func, U, m, j)
return J
if(__name__ == '__main__'):
# On derive fi en U selon la direction de la j-ieme composante
# Remarque : f1 s'exprime telle que : lambda x: f(x)[1]
# et np.identity est bien un vecteur elementaire caracterisant
# une direction donnee
# Defines g which is a function from R^3 to R^3
g = lambda x: np.array([[x[0][0]*x[0][0]-3], [x[1][0]*x[1][0]-5], [x[2][0]*x[2][0]-8], [0]])
print "\nDéfinition puis Application d'une fonction de R3 dans R4"
print g([[0],[1],[2]] - np.zeros(shape = (3, 1)))
# np.array([[,,],[,,],[,,]]) renvoie une matrice 3*3
# Utiliser np.dot pour le produit matriciel !!!
# Computes jacobi matrix of g at vector
print "Calcul de la matrice Jacobienne en un point donné"
vector = np.array([[1.],[1.],[1.]])
print jacobi_of_f_at_U(g, vector, 4, 3)
# Here we want to find (sqrt(3), sqrt(5), sqrt(8))
print "Méthode de Newton-Raphson à partir de [[1],[1],[1]]"
print methode_de_Newton(g, vector, 1000, pow(10,-5))
# done !!!!
| [
[
1,
0,
0.0612,
0.0102,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.0714,
0.0102,
0,
0.66,
0.1667,
596,
0,
1,
0,
0,
596,
0,
0
],
[
14,
0,
0.102,
0.0102,
0,
... | [
"import numpy as np",
"import matplotlib.pyplot as plt",
"derivate_accuracy = pow(10, -15)",
"def methode_de_Newton (f, Uo, N, epsilon, show = 0):\n \"applies Newton methode to the arguments in parameter\"\n plt.clf()\n cpt = 0\n U = Uo\n n = len(f(Uo))\n m = len(Uo)\n v = []",
" \"a... |
import numpy as np
import matplotlib.pyplot as plt
def Newton_Raphson (f, fJ, Uo, N, epsilon, show = 0, name="figure", E = None):
"applies Newton methode to the function f and its jacobian matrix J beginning from the vector Uo, looping at max at N and with an accuracy of epsilon"
if(E == None):
E = lambda X: np.abs(f(X)[0][0])
cpt = 0
U = Uo
n = len(f(Uo))
m = len(Uo)
v = []
if(show > 1 and show < 5):
X = []
X.append(U[0][0])
Y = []
Y.append(U[1][0])
while(cpt < N and np.linalg.norm(f(U)) > epsilon):
J = fJ(U)
# solving the equation JX = U,
# we obtain a new point :
VAR = np.linalg.lstsq(J, -f(U))[0]
step = 1.
while(np.linalg.norm(f(U + step * VAR)) > np.linalg.norm(f(U))):
step *= 2./3
U = U + step*VAR
# below this point, you'll only find displaying functions
cpt += 1
if (show > 1 and show < 5):
X.append(U[0][0])
Y.append(U[1][0])
if (show == 1 or show == 5):
v.append(E(U))
if(cpt == N):
print "error: unfinished resolution"
if(show == 1):
plt.semilogy()
plt.plot(range(cpt), v)
plt.show()
if(show == 5):
plt.xlabel("temps/iterations")
plt.ylabel("E(X)")
plt.title("L'evolution de l'energie de X quand X tend vers la racine")
plt.plot(range(cpt), v)
plt.savefig("Energy")
plt.show()
if(show >= 2 and show < 5):
plt.axis([-2,2,-1.5,1.5])
for i in range(cpt):
plt.scatter(X[i], Y[i], alpha=float(i)/cpt, marker='o')
plt.plot([0], [0], linestyle='None', marker='D', color='yellow')
plt.plot([1], [0], linestyle='None', marker='D', color='green')
if(show == 2):
plt.show()
if(show == 3):
plt.savefig(name + ".png")
if(show == 4):
plt.savefig(name + ".png")
plt.show()
return U
#********************** Tests ***********************
if(__name__ == '__main__'):
# Defines g which is a function from R^3 to R^4
g = lambda x: np.array([[x[0][0]*x[0][0]-3],
[x[1][0]*x[1][0]-5],
[x[2][0]*x[2][0]-8],
[0]])
# Defines its jacobian :
gJ = lambda x: np.array([[2*x[0][0], 0, 0],
[0, 2*x[1][0], 0],
[0, 0, 2*x[2][0]],
[0, 0, 0]])
# Defines an initial vector :
vector = np.array([[1.],[1.],[1.]])
res = Newton_Raphson (g, gJ, vector, 100, 1e-10)
print "Application of the Newton-Raphson algorithm"
print res
print "Value of force at this point :"
print g(res)
print "Defines h (which is a function from R to R) and its jacobian..."
h = lambda x: np.array([[x[0][0]*x[0][0]-3]])
hJ = lambda x : np.array([[2*x[0][0]]])
vect = np.array([[1.]])
print "...done"
print "Application of the Newton-Raphson algorithm"
res = Newton_Raphson (h, hJ, vect, 100, 1e-10)
print res
print "Value of force at this point :"
print h(res)
print "Convergence speed of Newton-Raphson algorithm"
Newton_Raphson (h, hJ, vect, 100, 1e-10, 1)
| [
[
1,
0,
0.0103,
0.0103,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.0206,
0.0103,
0,
0.66,
0.3333,
596,
0,
1,
0,
0,
596,
0,
0
],
[
2,
0,
0.3299,
0.567,
0,
0... | [
"import numpy as np",
"import matplotlib.pyplot as plt",
"def Newton_Raphson (f, fJ, Uo, N, epsilon, show = 0, name=\"figure\", E = None):\n \"applies Newton methode to the function f and its jacobian matrix J beginning from the vector Uo, looping at max at N and with an accuracy of epsilon\"\n if(E == No... |
##SECTION 4: ELECTROSTATIC EQUILIBRIUM ##
# -*- coding: utf-8 -*-
import numpy as np
import partie_1 as nr
from numpy import polynomial as P
import matplotlib.pyplot as plt
def ElecEnergy(X):
"Calcule l'énergie totale du système "
n=X.shape[0]
r =0.
for i in range(n):
cpt =0.
for j in range(n):
if (i!=j):
cpt +=np.log(abs(X[i,0]-X[j,0]))
r+=np.log(abs(X[i,0]+1))+np.log(abs(X[i,0]-1))+cpt/2
return r
#Complexité: O(n²)
def f (X,i):
"Calcule la dérivée de l'énergie par rapport à xi"
n=X.shape[0]
cpt=0.;
for j in np.arange(n):
if (j!=i):
cpt += 1/(X[i,0]-X[j,0])
return (1./(X[i,0]+1)+1/(X[i,0]-1)+cpt)
#Complexité: O(n)
def F(X):
"Renvoie un tableau des dérivées de l'énergie par rapport à tout les xi"
n=X.shape[0]
t=np.zeros((n,1))
for i in np.arange(n):
t[i,0]=f(X,i)
return t
#Complexité: O(n²)
def J(X):
"Calcule la matrice jacobienne de la fonction dérivée de l'energie électrostatique"
n=X.shape[0]
M=np.zeros((n,n))
for i in np.arange(n):
cpt=0.
for j in np.arange(n):
if (i!=j):
cpt += -1./(pow((X[i,0]-X[j,0]),2))
M[i,j]=1./(pow((X[i,0]-X[j,0]),2))
M[i,i]=-1./pow((X[i,0]+1),2)-1./pow((X[i,0]-1),2)+cpt
return M
#Complexité: O(n²)
def LegderRoots(n):
"Calcule les racines de la dérivée du polynôme de Legendre de degré n+1"
t=np.zeros(n+2)
t[n+1]=1
return P.legroots(P.legder(t))
###Tests###
print "affichage des 10 premières racines de la dérivée du polynome de Legendre"
for i in range(1,11):
X=np.transpose(np.asmatrix(2*np.random.ranf(i)-1))
R=nr.Newton_Raphson(F,J,X,100,1e-5)
while (np.linalg.norm(R) > i):
X=np.transpose(np.asmatrix(2*np.random.ranf(i)-1))
R=nr.Newton_Raphson(F,J,X,100,1e-5)
for j in range(i):
plt.scatter(i, R[j][0])
plt.show()
X=np.transpose(np.asmatrix(2*np.random.ranf(5)-1))
print "X=\n",X
print "Application de la fonction au vecteur:\n", np.around(F(X),1)
print "Application de la fonction jacobienne au vecteur:\n", np.around(J(X),2)
#Ce qui est mis en commentaire dans la ligne suivante est pour tracer
#l'évolution de l'énergie de X quand X tend vers la racine .
R=nr.Newton_Raphson(F,J,X,100,1e-5)#,5,"energy",ElecEnergy)
print "Application de la méthode de Newton-Raphson\n", np.around(R,2)
print "Test de la fonction sur les racines \n", np.around(F(R),2)
print "Energie de X \n",ElecEnergy(X)
print "Energie du vecteur racines \n",ElecEnergy(R)
print "Racines de la dérivée du polynôme de Legendre:\n",np.round(LegderRoots(5),2)
| [
[
1,
0,
0.043,
0.0108,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.0538,
0.0108,
0,
0.66,
0.0476,
210,
0,
1,
0,
0,
210,
0,
0
],
[
1,
0,
0.0645,
0.0108,
0,
0... | [
"import numpy as np",
"import partie_1 as nr",
"from numpy import polynomial as P",
"import matplotlib.pyplot as plt",
"def ElecEnergy(X):\n \"Calcule l'énergie totale du système \"\n n=X.shape[0]\n r =0.\n for i in range(n):\n cpt =0.\n for j in range(n):\n if (i!=j):",... |
# -*- coding: utf-8 -*-
import partie_1 as tn
import numpy as np
# Question 1 :
def elastic_force(k, xo = 0, yo = 0):
"defines a k-elastic force"
return lambda x, y: np.array([[-k*x], [-k*y]])
def centrifugal_force(k, xo, yo):
"defines a k-elastic force"
return lambda x, y: np.array([[k*(x-xo)],
[k*(y-yo)]])
def gravitational_force(k, xo, yo):
"defines a k-elastic force"
return lambda x, y: np.array([[-k*(x-xo)/((np.sqrt((x-xo)**2 + (y-yo)**2))**3)],
[-k*(y-yo)/((np.sqrt((x-xo)**2 + (y-yo)**2))**3)]])
# And here are the jacobian matrix :
def jacobian_centrifugal_force(k, xo=0, yo=0):
"defines jacobian matrix of a centrifugal force"
return lambda X: np.array([[k,0],
[0,k]])
def jacobian_gravitational_force(k, xo, yo):
"defines jacobian matrix of a gravitational force"
return lambda x: np.array([[ -k/(np.sqrt((x[0][0]-xo)**2+(x[1][0]-yo)**2))**3 + (3*k*(x[0][0] - xo)**2)/(np.sqrt((x[0][0]-xo)**2+(x[1][0]-yo)**2))**5,
k*(x[0][0] - xo)*(x[1][0]-yo)*3/(np.sqrt((x[0][0]-xo)**2+(x[1][0]-yo)**2))**5],
[ k*(x[0][0] - xo)*(x[1][0]-yo)*3/(np.sqrt((x[0][0]-xo)**2+(x[1][0]-yo)**2))**5,
-k/np.sqrt((x[0][0]-xo)**2+(x[1][0]-yo)**2)**3 + (3*k*(x[1][0] - yo)**2)/np.sqrt((x[0][0]-xo)**2+(x[1][0]-yo)**2)**5]])
# Question 2 :
# System : satellite considered as a point with a mass m
# I.F.: - attraction of the sun : f1 with k = 1
# - attraction of the earth : f2 with k = 0,01
# - repulsion of the barycentre (wich may traduce
# the global rotation around the sun): f3 with k = 1
# Newton last postulate:
# equilibrum if and only if : f1 + f2 + f3 = 0
# wich means to look for F.[x y z] 's zeros with F's
# coefficients
# Afin d'éviter de réinstancier à les fonctions f1, f2
# et f3 à chaque appel de F, nous définissons globalement :
f1 = gravitational_force(1, 0.0, 0.0)
f2 = gravitational_force(0.01, 1.0, 0.0)
f3 = centrifugal_force(1, 0.01/1.01, 0.0)
f1J = jacobian_gravitational_force(1, 0.0, 0.0)
f2J = jacobian_gravitational_force(0.01, 1.0, 0.0)
f3J = jacobian_centrifugal_force(1, 0.01/1.01, 0.0)
def F (X):
return f1(X[0][0], X[1][0]) + f2(X[0][0], X[1][0]) + f3(X[0][0], X[1][0])
def FJ(X):
return f1J(X)+f2J(X)+f3J(X)
# print "coordonnées de L1 :"
# print tn.Newton_Raphson(F, FJ, np.array([[0.5],[0]]), 100, 1e-10)
# print "\nvaleur de la forcex"
# print F(tn.Newton_Raphson(F, FJ, np.array([[0.5],[0]]), 100, 1e-10))
#Obtention du point L1 :
#la composée y n'étant pas pertinente, nous allons utiliser l'affichage de la composante y en fonction du temps :
#tn.Newton_Raphson(F, FJ, np.array([[0.5],[0]]), 100, 1e-15, 1)
#***************************PARTIE TESTS********************************
print "Obtention du point L1 :"
tn.Newton_Raphson(F, FJ, np.array([[0.5],[0.01]]), 100, 1e-10, 2)
print "ok"
print "Obtention du point L2 :"
tn.Newton_Raphson(F, FJ, np.array([[1.5],[0.1]]), 100, 1e-10, 2)
print "ok"
print "Obtention du point L3 :"
tn.Newton_Raphson(F, FJ, np.array([[-0.5],[0.1]]), 100, 1e-10, 2)
print "ok"
print "Obtention du point L4 :"
tn.Newton_Raphson(F, FJ, np.array([[0.5],[0.5]]), 100, 1e-10, 2)
print "ok"
print "Obtention du point L5 :"
tn.Newton_Raphson(F, FJ, np.array([[0.5],[-0.5]]), 100, 1e-10, 2)
print "ok"
| [
[
1,
0,
0.0217,
0.0109,
0,
0.66,
0,
210,
0,
1,
0,
0,
210,
0,
0
],
[
1,
0,
0.0326,
0.0109,
0,
0.66,
0.0345,
954,
0,
1,
0,
0,
954,
0,
0
],
[
2,
0,
0.0761,
0.0326,
0,
... | [
"import partie_1 as tn",
"import numpy as np",
"def elastic_force(k, xo = 0, yo = 0):\n \"defines a k-elastic force\"\n return lambda x, y: np.array([[-k*x], [-k*y]])",
" \"defines a k-elastic force\"",
" return lambda x, y: np.array([[-k*x], [-k*y]])",
"def centrifugal_force(k, xo, yo):\n ... |
# -*- coding: utf-8 -*-
vowels = 'aAiIuUfFxXeEoOMH'
consonants = 'kKgGNcCjJYwWqQRtTdDnpPbBmyrlvSzsh'
other = ". |-\r\n\t"
virama = u'\u094d'
map_vowels = {'a':u'\u0905', 'A':u'\u0906', 'i':u'\u0907', 'I':u'\u0908', 'u':u'\u0909', \
'U':u'\u090a', 'f':u'\u090b', 'F':u'\u0960', 'x':u'\u090c', 'X':u'\u0961', \
'e':u'\u090f', 'E':u'\u0910', 'o':u'\u0913', 'O':u'\u0914', \
'M':u'\u0902', 'H':u'\u0903'}
#x -> 0960?
map_vowel_signs = {'a':'', 'A':u'\u093e', 'i':u'\u093f', 'I':u'\u0940', 'u':u'\u0941', \
'U':u'\u0942', 'f':u'\u0943', 'F':u'\u0944', 'x':u'\u0902', 'X':u'\u0963', \
'e':u'\u0947', 'E':u'\u0948', 'o':u'\u094b', 'O':u'\u094c', \
'M':u'\u0902', 'H':u'\u0903', '_':u'\u094d'}
map_consonants = {'k':u'\u0915', 'K':u'\u0916', 'g':u'\u0917', 'G':u'\u0918', 'N':u'\u0919', \
'c':u'\u091a', 'C':u'\u091b', 'j':u'\u091c', 'J':u'\u091d', 'Y':u'\u091e', \
'w':u'\u091f', 'W':u'\u0920', 'q':u'\u0921', 'Q':u'\u0922', 'R':u'\u0923', \
't':u'\u0924', 'T':u'\u0925', 'd':u'\u0926', 'D':u'\u0927', 'n':u'\u0928', \
'p':u'\u092a', 'P':u'\u092b', 'b':u'\u092c', 'B':u'\u092d', 'm':u'\u092e', \
'y':u'\u092f', 'r':u'\u0930', 'l':u'\u0932', 'v':u'\u0935', 'S':u'\u0936', \
'z':u'\u0937', 's':u'\u0938', 'h':u'\u0939'}
def isVowel(ch):
return ch in vowels
def isConsonant(ch):
return ch in consonants
def atomize(source_text_slp1):
index = 0
text_length = len(source_text_slp1)
array = []
while index < text_length:
ch = source_text_slp1[index]
if (index+1) < text_length:
ch1 = source_text_slp1[index+1]
else:
ch1 = ''
if isVowel(ch):
array.append(ch)
index = index + 1
elif isConsonant(ch) and isVowel(ch1):
array.append(ch+ch1)
index = index + 2
else:
array.append(ch)
index = index + 1
return array
def devanagari_l(src_txt_slp1):
arr = atomize(src_txt_slp1)
deva_str = []
for ch in arr:
if len(ch) == 1:
if isVowel(ch):
deva_str.append(map_vowels[ch])
elif isConsonant(ch):
deva_str.append(map_consonants[ch] + virama)
else:
deva_str.append(ch)
else:
deva_str.append(map_consonants[ch[0]]+map_vowel_signs[ch[1]])
return "".join(deva_str)
| [
[
14,
0,
0.0469,
0.0156,
0,
0.66,
0,
841,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0625,
0.0156,
0,
0.66,
0.1,
416,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0781,
0.0156,
0,
0.66... | [
"vowels = 'aAiIuUfFxXeEoOMH'",
"consonants = 'kKgGNcCjJYwWqQRtTdDnpPbBmyrlvSzsh'",
"other = \". |-\\r\\n\\t\"",
"virama = u'\\u094d'",
"map_vowels = {'a':u'\\u0905', 'A':u'\\u0906', 'i':u'\\u0907', 'I':u'\\u0908', 'u':u'\\u0909', \\\n 'U':u'\\u090a', 'f':u'\\u090b', 'F':u'\\u0960', 'x':u'\\u090... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Devanagari Editor
import pygtk, pango
pygtk.require('2.0')
import gtk
from decoders import devanagari
help_string = '''
अ आ इ ई उ ऊ ऋ ॠ ऌ ॡ ए ऐ ओ औ अं अः
a A i I u U R RR lR lRR e ai o au M H
क ख ग घ ङ | य र ल व
k kh g gh G | y r l v
च छ ज झ ञ | श ष स ह
c ch j jh J | z S s h
ट ठ ड ढ ण |
T Th D Dh N | ० १ २ ३ ४ ५ ६ ७ ८ ९
त थ द ध न | 0 1 2 3 4 5 6 7 8 9
t th d dh n |
प फ ब भ म |
p ph b bh m |
'''
class DevanagariTextEditor:
def close_application(self, widget):
gtk.main_quit()
def key_pressed(self, widget, event):
# F5
if event.keyval == 65474:
start, end = self.textbuffer_src.get_bounds()
hk_string = self.textbuffer_src.get_text(start, end)
devanagari_string = devanagari("hk", hk_string)
self.textbuffer.set_text(devanagari_string)
self.textview.set_buffer(self.textbuffer)
# F1 to display transliteration help
elif event.keyval == 65470:
self.textbuffer.set_text(help_string)
self.textview.set_buffer(self.textbuffer)
# F2 to save the source file
elif event.keyval == 65471:
self.save_src_file()
# F3 to save the destination file
elif event.keyval == 65472:
self.save_devanagari_file()
# CTRL + s
elif event.keyval == 115:
if event.state & gtk.gdk.CONTROL_MASK:
self.save_src_file()
def save_src_file(self):
start, end = self.textbuffer_src.get_bounds()
string_src = self.textbuffer_src.get_text(start, end)
filechooserdialog = gtk.FileChooserDialog("Save Source File",
None, gtk.FILE_CHOOSER_ACTION_SAVE,
(gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL,
gtk.STOCK_OK, gtk.RESPONSE_OK))
response = filechooserdialog.run()
if response == gtk.RESPONSE_OK:
filename = filechooserdialog.get_filename()
FILE = open(filename, 'w')
FILE.write(string_src)
FILE.close()
filechooserdialog.destroy()
def save_devanagari_file(self):
start, end = self.textbuffer.get_bounds()
string = self.textbuffer.get_text(start, end)
filechooserdialog = gtk.FileChooserDialog("Save Destination File",
None, gtk.FILE_CHOOSER_ACTION_SAVE,
(gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL,
gtk.STOCK_OK, gtk.RESPONSE_OK))
filechooserdialog.set_filename(".rtf")
response = filechooserdialog.run()
if response == gtk.RESPONSE_OK:
filename = filechooserdialog.get_filename()
FILE = open(filename, 'w')
FILE.write(string)
FILE.close()
filechooserdialog.destroy()
def transcode_the_text(self, widget):
start, end = self.textbuffer_src.get_bounds()
hk_string = self.textbuffer_src.get_text(start, end)
devanagari_string = devanagari("hk", hk_string)
self.textbuffer.set_text(devanagari_string)
self.textview.set_buffer(self.textbuffer)
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_resizable(True)
window.set_size_request(450,540)
window.connect("destroy", self.close_application)
window.connect("key_press_event", self.key_pressed)
window.set_title("Devanagari Editor")
window.set_border_width(0)
window.set_icon_from_file("DElogo.ico")
self.box1 = gtk.VBox(False, 0)
window.add(self.box1)
self.box1.show()
box2 = gtk.VBox(False, 10)
box2.set_border_width(10)
self.box1.pack_start(box2, True, True, 0)
box2.show()
# the source text buffer
sw_src = gtk.ScrolledWindow()
sw_src.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.textview_src = gtk.TextView()
self.textbuffer_src = self.textview_src.get_buffer()
self.textview_src.set_wrap_mode(gtk.WRAP_WORD)
self.textview_src.modify_font(pango.FontDescription("Courier New 12"))
sw_src.add(self.textview_src)
sw_src.show()
self.textview_src.show()
box2.pack_start(sw_src)
# the display text buffer
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.textview = gtk.TextView()
self.textbuffer = self.textview.get_buffer()
self.textview.set_wrap_mode(gtk.WRAP_WORD)
self.textview.modify_font(pango.FontDescription("Sans 12"))
sw.add(self.textview)
sw.show()
self.textview.show()
box2.pack_start(sw)
# clipboard
self.clipboard = gtk.Clipboard(gtk.gdk.display_get_default(), "CLIPBOARD")
# show the window
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
DevanagariTextEditor()
main()
| [
[
1,
0,
0.039,
0.0065,
0,
0.66,
0,
106,
0,
2,
0,
0,
106,
0,
0
],
[
8,
0,
0.0455,
0.0065,
0,
0.66,
0.1429,
66,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0519,
0.0065,
0,
0.66... | [
"import pygtk, pango",
"pygtk.require('2.0')",
"import gtk",
"from decoders import devanagari",
"help_string = '''\nअ\tआ\tइ\tई\tउ\tऊ\tऋ\tॠ\tऌ\tॡ\tए\tऐ\tओ\tऔ\tअं\tअः\na\tA\ti\tI\tu\tU\tR\tRR\tlR\tlRR\te\tai\to\tau\tM\tH\n\nक\tख\tग\tघ\tङ\t|\tय\tर\tल\tव\nk\tkh\tg\tgh\tG\t|\ty\tr\tl\tv\nच\tछ\tज\tझ\tञ\t|\tश\tष\t... |
# -*- coding: utf-8 -*-
# Devanagari Editor
import pygtk, pango
pygtk.require('2.0')
import gtk
from decoders import devanagari
Vowels = 'aAiIuUReoMH'
Consonants = 'kgGcjJTDNtdnpbmyrlvzSsh'
Numbers = '0123456789'
other = ". |-\r\n\t"
virama = u'\u094d'
map_vowels = {'a':u'\u0905', 'A':u'\u0906', 'i':u'\u0907', 'I':u'\u0908', 'u':u'\u0909', \
'U':u'\u090a', 'R':u'\u090b', 'RR':u'\u0960', 'lR':u'\u090c', 'lRR':u'\u0961', \
'e':u'\u090f', 'ai':u'\u0910', 'o':u'\u0913', 'au':u'\u0914', \
'M':u'\u0902', 'H':u'\u0903'}
#x -> 0960?
map_vowel_signs = {'a':'', 'A':u'\u093e', 'i':u'\u093f', 'I':u'\u0940', 'u':u'\u0941', \
'U':u'\u0942', 'R':u'\u0943', 'RR':u'\u0944', 'lR':u'\u0962', 'lRR':u'\u0963', \
'e':u'\u0947', 'ai':u'\u0948', 'o':u'\u094b', 'au':u'\u094c', \
'M':u'\u0902', 'H':u'\u0903', '_':u'\u094d'}
map_consonants = {'k':u'\u0915', 'kh':u'\u0916', 'g':u'\u0917', 'gh':u'\u0918', 'G':u'\u0919', \
'c':u'\u091a', 'ch':u'\u091b', 'j':u'\u091c', 'jh':u'\u091d', 'J':u'\u091e', \
'T':u'\u091f', 'Th':u'\u0920', 'D':u'\u0921', 'Dh':u'\u0922', 'N':u'\u0923', \
't':u'\u0924', 'th':u'\u0925', 'd':u'\u0926', 'dh':u'\u0927', 'n':u'\u0928', \
'p':u'\u092a', 'ph':u'\u092b', 'b':u'\u092c', 'bh':u'\u092d', 'm':u'\u092e', \
'y':u'\u092f', 'r':u'\u0930', 'l':u'\u0932', 'v':u'\u0935', 'z':u'\u0936', \
'S':u'\u0937', 's':u'\u0938', 'h':u'\u0939'}
map_numbers = {'0':u'\u0966', '1':u'\u0967', '2':u'\u0968', '3':u'\u0969', '4':u'\u096A', \
'5':u'\u096B', '6':u'\u096C', '7':u'\u096D', '8':u'\u096E', '9':u'\u096F'}
def isVowel(ch):
return ch in Vowels
def isConsonant(ch):
return ch in Consonants
def isNumber(ch):
return ch in Numbers
def isUVowel(ch):
if ch > u'\u0901' and ch < u'\u0915':
return True
elif ch == u'\u0960' or ch == u'\u0961':
return True
else:
return False
def isUConsonant(ch):
if isUVowel(ch):
return False
elif ch > u'\u0914' and ch < u'\u0940':
return True
else:
return False
class DevanagariTextEditor:
def close_application(self, widget):
gtk.main_quit()
def key_pressed(self, widget, event):
# F2 to convert the selected text to devanagari
if event.keyval == 65471:
try:
start, end = self.textbuffer.get_selection_bounds()
text = start.get_text(end)
self.textbuffer.delete(start, end)
devanagari_string = devanagari("hk", text)
self.textbuffer.insert_at_cursor(devanagari_string)
except ValueError:
pass
# F5 to toggle editing mode
elif event.keyval == 65474:
if self.Mode == 'Devanagari':
self.window.disconnect(self.handler)
self.Mode = 'Roman'
else:
self.handler = self.window.connect("key_release_event", self.key_released)
self.Mode = 'Devanagari'
def delete_previous_char(self, Start, End):
start = self.textbuffer.get_iter_at_mark(self.textbuffer.get_insert())
end = self.textbuffer.get_iter_at_mark(self.textbuffer.get_insert())
start.backward_chars(Start)
end.backward_chars(End)
self.textbuffer.delete(start, end)
def get_previous_char(self, Start, End):
start = self.textbuffer.get_iter_at_mark(self.textbuffer.get_insert())
end = self.textbuffer.get_iter_at_mark(self.textbuffer.get_insert())
start.backward_chars(Start)
end.backward_chars(End)
return start.get_text(end)
def key_released(self, widget, event):
if event.keyval > 255:
return
ch = self.get_previous_char(1,0) #check for null
if ch == '':
return
if ord(ch) <= 255:
if isVowel(ch):
self.delete_previous_char(1,0)
if self.get_previous_char(1,0) == u'\u094d': # is virama?
if self.get_previous_char(2,1) == u'\u0932' and ch == 'R': # for lR
if self.get_previous_char(3,2) == u'\u094d':
self.delete_previous_char(3,0)
self.textbuffer.insert_at_cursor(u'\u0962') # sign lR
else:
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(u'\u090c') # lR
else:
self.delete_previous_char(1,0)
self.textbuffer.insert_at_cursor(map_vowel_signs[ch])
else:
if self.get_previous_char(1,0) == u'\u090b' and ch == 'R': # RR
self.delete_previous_char(1,0)
self.textbuffer.insert_at_cursor(u'\u0960')
elif self.get_previous_char(1,0) == u'\u0943' and ch == 'R': # sign R + R
self.delete_previous_char(1,0)
self.textbuffer.insert_at_cursor(u'\u0944') # sign RR
elif self.get_previous_char(1,0) == u'\u0962' and ch == 'R': # sign l + R
self.delete_previous_char(1,0)
self.textbuffer.insert_at_cursor(u'\u0963') # sign lRR
elif self.get_previous_char(1,0) == u'\u0905' and ch == 'u':
self.delete_previous_char(1,0)
self.textbuffer.insert_at_cursor(map_vowels['au'])
elif self.get_previous_char(1,0) == u'\u0905' and ch == 'i':
self.delete_previous_char(1,0)
self.textbuffer.insert_at_cursor(map_vowels['ai'])
elif isUConsonant(self.get_previous_char(1,0)):
if ch == 'u':
self.textbuffer.insert_at_cursor(map_vowel_signs['au'])
elif ch == 'i':
self.textbuffer.insert_at_cursor(map_vowel_signs['ai'])
else:
self.textbuffer.insert_at_cursor(map_vowels[ch])
else:
self.textbuffer.insert_at_cursor(map_vowels[ch])
if isConsonant(ch):
self.delete_previous_char(1,0)
if ch == 'h':
if self.get_previous_char(2,1) == u'\u0915': # kh
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(map_consonants['kh'])
elif self.get_previous_char(2,1) == u'\u0917': # gh
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(map_consonants['gh'])
elif self.get_previous_char(2,1) == u'\u091a': # ch
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(map_consonants['ch'])
elif self.get_previous_char(2,1) == u'\u091c': # jh
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(map_consonants['jh'])
elif self.get_previous_char(2,1) == u'\u091f': # Th
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(map_consonants['Th'])
elif self.get_previous_char(2,1) == u'\u0921': # Dh
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(map_consonants['Dh'])
elif self.get_previous_char(2,1) == u'\u0924': # th
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(map_consonants['th'])
elif self.get_previous_char(2,1) == u'\u0926':# dh
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(map_consonants['dh'])
elif self.get_previous_char(2,1) == u'\u092a':# ph
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(map_consonants['ph'])
elif self.get_previous_char(2,1) == u'\u092c':# bh
self.delete_previous_char(2,0)
self.textbuffer.insert_at_cursor(map_consonants['bh'])
else:
self.textbuffer.insert_at_cursor(map_consonants['h'])
else:
self.textbuffer.insert_at_cursor(map_consonants[ch])
self.textbuffer.insert_at_cursor(u'\u094d')
if isNumber(ch):
self.delete_previous_char(1,0)
self.textbuffer.insert_at_cursor(map_numbers[ch])
def save_devanagari_file(self, widget):
start, end = self.textbuffer.get_bounds()
string = self.textbuffer.get_text(start, end)
filechooserdialog = gtk.FileChooserDialog("Save Destination File",
None, gtk.FILE_CHOOSER_ACTION_SAVE,
(gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL,
gtk.STOCK_OK, gtk.RESPONSE_OK))
response = filechooserdialog.run()
if response == gtk.RESPONSE_OK:
filename = filechooserdialog.get_filename()
FILE = open(filename, 'w')
FILE.write(string)
FILE.close()
filechooserdialog.destroy()
def open_devanagari_file(self, widget):
filechooserdialog = gtk.FileChooserDialog("Save Destination File",
None, gtk.FILE_CHOOSER_ACTION_OPEN,
(gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL,
gtk.STOCK_OK, gtk.RESPONSE_OK))
response = filechooserdialog.run()
if response == gtk.RESPONSE_OK:
filename = filechooserdialog.get_filename()
FILE = open(filename, 'r')
string = FILE.read()
FILE.close()
self.textbuffer.set_text(string)
filechooserdialog.destroy()
def transcode_the_text(self, widget):
start, end = self.textbuffer.get_bounds()
hk_string = self.textbuffer.get_text(start, end)
devanagari_string = devanagari("hk", hk_string)
self.textbuffer.set_text(devanagari_string)
self.textview.set_buffer(self.textbuffer)
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_resizable(True)
self.window.set_size_request(450,540)
self.window.connect("destroy", self.close_application)
self.window.connect("key_press_event", self.key_pressed)
self.handler = self.window.connect("key_release_event", self.key_released)
self.window.set_title("Devanagari Editor")
self.window.set_border_width(0)
self.window.set_icon_from_file("DElogo.ico")
menubar = gtk.MenuBar()
menu_file = gtk.Menu()
menu_edit = gtk.Menu()
menu_help = gtk.Menu()
item_open = gtk.MenuItem("Open")
item_open.connect("activate", self.open_devanagari_file)
item_save = gtk.MenuItem("Save")
item_save.connect("activate", self.save_devanagari_file)
item_quit = gtk.MenuItem("Quit")
item_quit.connect("activate", self.close_application)
menu_file.append(item_open)
menu_file.append(item_save)
menu_file.append(item_quit)
item_cut = gtk.MenuItem("Cut")
item_copy = gtk.MenuItem("Copy")
item_paste = gtk.MenuItem("Paste")
menu_edit.append(item_cut)
menu_edit.append(item_copy)
menu_edit.append(item_paste)
item_about = gtk.MenuItem("About")
menu_help.append(item_about)
item_file = gtk.MenuItem("File")
item_edit = gtk.MenuItem("Edit")
item_help = gtk.MenuItem("Help")
item_file.set_submenu(menu_file)
item_edit.set_submenu(menu_edit)
item_help.set_submenu(menu_help)
menubar.append(item_file)
menubar.append(item_edit)
menubar.append(item_help)
self.box1 = gtk.VBox(False, 0)
self.window.add(self.box1)
self.box1.show()
self.box1.pack_start(menubar, False, False, 0)
box2 = gtk.VBox(False, 0)
box2.set_border_width(0)
self.box1.pack_start(box2, True, True, 0)
box2.show()
# the source text buffer
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.textview = gtk.TextView()
self.textbuffer = self.textview.get_buffer()
self.textview.set_wrap_mode(gtk.WRAP_WORD)
self.textview.modify_font(pango.FontDescription("Sans 12"))
sw.add(self.textview)
sw.show()
self.textview.show()
box2.pack_start(sw)
self.Mode = 'Devanagari'
# clipboard
self.clipboard = gtk.Clipboard(gtk.gdk.display_get_default(), "CLIPBOARD")
# show the window
self.window.show_all()
def main():
gtk.main()
return 0
if __name__ == "__main__":
DevanagariTextEditor()
main()
| [
[
1,
0,
0.0161,
0.0032,
0,
0.66,
0,
106,
0,
2,
0,
0,
106,
0,
0
],
[
8,
0,
0.0193,
0.0032,
0,
0.66,
0.05,
66,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0225,
0.0032,
0,
0.66,... | [
"import pygtk, pango",
"pygtk.require('2.0')",
"import gtk",
"from decoders import devanagari",
"Vowels = 'aAiIuUReoMH'",
"Consonants = 'kgGcjJTDNtdnpbmyrlvzSsh'",
"Numbers = '0123456789'",
"other = \". |-\\r\\n\\t\"",
"virama = u'\\u094d'",
"map_vowels = {'a':u'\\u0905', 'A':u'\\u0906', 'i':u'\\u... |
hk_map = [['X', 'LRR'],
['F', 'RR'], ['E', 'ai'], ['O', 'au'], ['K', 'kh'], ['G', 'gh'],
['C', 'ch'], ['J', 'jh'], ['W', 'Th'], ['Q', 'Dh'], ['T', 'th'],
['D', 'dh'], ['P', 'ph'], ['B', 'bh'],
['a', 'a'], ['A', 'A'], ['i', 'i'], ['I', 'I'], ['u', 'u'],
['U', 'U'], ['f', 'R'], ['x', 'L'], ['e', 'e'], ['o', 'o'],
['M', 'M'], ['H', 'H'], ['k', 'k'], ['g', 'g'], ['N', 'G'],
['c', 'c'], ['j', 'j'], ['Y', 'J'], ['w', 'T'], ['q', 'D'],
['R', 'N'], ['t', 't'], ['d', 'd'], ['n', 'n'], ['p', 'p'],
['b', 'b'], ['m', 'm'], ['y', 'y'], ['r', 'r'], ['l', 'l'],
['v', 'v'], ['S', 'z'], ['z', 'S'], ['s', 's'], ['h', 'h'],
['.', '.']]
wx_map = [['X', 'LY'],
['a', 'a'], ['A', 'A'], ['i', 'i'], ['I', 'I'], ['u', 'u'],
['U', 'U'], ['f', 'q'], ['F', 'Q'], ['x', 'L'], ['e', 'e'],
['E', 'E'], ['o', 'o'], ['O', 'O'], ['M', 'M'], ['H', 'H'],
['k', 'k'], ['K', 'K'], ['g', 'g'], ['G', 'G'], ['N', 'f'],
['c', 'c'], ['C', 'C'], ['j', 'j'], ['J', 'J'], ['Y', 'F'],
['w', 't'], ['W', 'T'], ['q', 'd'], ['Q', 'D'], ['R', 'N'],
['t', 'w'], ['T', 'W'], ['d', 'x'], ['D', 'X'], ['n', 'n'],
['p', 'p'], ['P', 'P'], ['b', 'b'], ['B', 'B'], ['m', 'm'],
['y', 'y'], ['r', 'r'], ['l', 'l'], ['v', 'v'], ['S', 'S'],
['z', 'R'], ['s', 's'], ['h', 'h'], ['.', '.']]
itrans_map = [['A', 'aa'], ['I', 'ii'], ['U', 'uu'], ['f', 'Ri'], ['F', 'RI'],
['x', 'Li'], ['X', 'LI'], ['E', 'ai'], ['O', 'au'], ['K', 'kh'],
['G', 'gh'], ['N', '~N'], ['c', 'ch'], ['C', 'Ch'], ['J', 'jh'],
['Y', '~n'], ['W', 'Th'], ['Q', 'Dh'], ['T', 'th'], ['D', 'dh'],
['P', 'ph'], ['B', 'bh'], ['S', 'sh'], ['z', 'Sh'], ['a', 'a'],
['i', 'i'], ['u', 'u'], ['e', 'e'], ['o', 'o'], ['M', 'M'],
['H', 'H'], ['k', 'k'], ['g', 'g'], ['j', 'j'], ['w', 'T'],
['q', 'D'], ['R', 'N'], ['t', 't'], ['d', 'd'], ['n', 'n'],
['p', 'p'], ['b', 'b'], ['m', 'm'], ['y', 'y'], ['r', 'r'],
['l', 'l'], ['v', 'v'], ['s', 's'], ['h', 'h'], ['.', '.']]
| [
[
14,
0,
0.1857,
0.3429,
0,
0.66,
0,
9,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
0.5429,
0.3143,
0,
0.66,
0.5,
110,
0,
0,
0,
0,
0,
5,
0
],
[
14,
0,
0.8714,
0.2857,
0,
0.66,
... | [
"hk_map = [['X', 'LRR'],\n ['F', 'RR'], ['E', 'ai'], ['O', 'au'], ['K', 'kh'], ['G', 'gh'],\n ['C', 'ch'], ['J', 'jh'], ['W', 'Th'], ['Q', 'Dh'], ['T', 'th'],\n ['D', 'dh'], ['P', 'ph'], ['B', 'bh'],\n ['a', 'a'], ['A', 'A'], ['i', 'i'], ['I', 'I'], ['u', 'u'],\n ['U', '... |
# -*- coding: utf-8 -*-
#the program encodes text between slp1, hk, wx and itrans formats
##Usage Guidelines:
##1) Copy the module to your
## working directory
##2) import Transcode
##3) use the methods as per your need
##
##example: if you have your source byte stream
## in HK transliteration format, you can
## encode it to slp1 by the command
## 'Transcode.slp1('hk', stream), which returns
## the encoded slp1 stream of data
#import the pickle module for loading the encoding map files
import pickle
import t_map
#implementation does not notify source encoding errors
def slp1(src_format, source_text):
#load the mappings file for slp1 and the source format
if src_format == 'hk':
maplist = t_map.hk_map
elif src_format == 'wx':
maplist = t_map.wx_map
elif src_format == 'itrans':
maplist = t_map.itrans_map
else:
return ''
index = 0
#encode the source text to an intermediate format
for slp1, src_fmt in maplist:
source_text = source_text.replace(src_fmt, ('#' + str(index) + '#'))
index = index + 1
index = 0
#decode the SLP1 format from the encoded intermediate format
for slp1, src_fmt in maplist:
source_text = source_text.replace(('#' + str(index) + '#'), slp1)
index = index + 1
return source_text
def hk(src_format, source_txt):
#convert the source to SLP1 format
if src_format != 'slp1':
source_txt = slp1(src_format, source_txt)
#load the HK SLP1 mapping
maplist = t_map.hk_map
index = 0
#encode the source text to an intermediate format
for slp1_v, src_fmt in maplist:
source_txt = source_txt.replace(slp1_v, ('#' + str(index) + '#'))
index = index + 1
index = 0
#decode the SLP1 format from the encoded intermediate format
for slp1_v, src_fmt in maplist:
source_txt = source_txt.replace(('#' + str(index) + '#'), src_fmt)
index = index + 1
return source_txt
def wx(src_format, source_txt):
#convert the source to SLP1 format
if src_format != 'slp1':
source_txt = slp1(src_format, source_txt)
#load SLP1 WX format
maplist = t_map.wx_map
index = 0
#encode the source text to an intermediate format
for slp1_v, src_fmt in maplist:
source_txt = source_txt.replace(slp1_v, ('#' + str(index) + '#'))
index = index + 1
index = 0
#decode the SLP1 format from the encoded intermediate format
for slp1_v, src_fmt in maplist:
source_txt = source_txt.replace(('#' + str(index) + '#'), src_fmt)
index = index + 1
return source_txt
def itrans(src_format, source_txt):
#convert the source to SLP1 format
if src_format != 'slp1':
source_txt = slp1(src_format, source_txt)
#load SLP1 ITRANS mapping
maplist = t_map.itrans_map
index = 0
#encode the source text to an intermediate format
for slp1_v, src_fmt in maplist:
source_txt = source_txt.replace(slp1_v, ('#' + str(index) + '#'))
index = index + 1
index = 0
#decode the SLP1 format from the encoded intermediate format
for slp1_v, src_fmt in maplist:
source_txt = source_txt.replace(('#' + str(index) + '#'), src_fmt)
index = index + 1
return source_txt
def devanagari(src_format, source_txt):
#convert the source to SLP1 format
if src_format != 'slp1':
source_txt = slp1(src_format, source_txt)
from u_ import devanagari_l
return devanagari_l(source_txt)
| [
[
1,
0,
0.1731,
0.0096,
0,
0.66,
0,
848,
0,
1,
0,
0,
848,
0,
0
],
[
1,
0,
0.1827,
0.0096,
0,
0.66,
0.1667,
575,
0,
1,
0,
0,
575,
0,
0
],
[
2,
0,
0.3173,
0.2019,
0,
... | [
"import pickle",
"import t_map",
"def slp1(src_format, source_text):\n #load the mappings file for slp1 and the source format\n if src_format == 'hk':\n maplist = t_map.hk_map \n elif src_format == 'wx':\n maplist = t_map.wx_map\n elif src_format == 'itrans':\n maplist = t_map.i... |
# -*- coding: utf-8 -*
''' Hare Krsna '''
''' om namo Bhagavate Vasudevaya '''
#to find dictonary entries in the given ver
'''
find the dictonary matches in the MW dictonary
and NITAI VEDA and Glossary
'''
#function to sort the list according to the index
def add_index_tag(in_list,in_string):
length = len(in_list)
out_list = in_list
for i in range(length):
entry = out_list[i]
index = str(in_string.index(entry[0:len(entry)-1]))
out_list[i] = index.rjust(3,'0')+entry
out_list.sort()
return out_list
def refine_list(in_list):
out_list = in_list
i=0
while 1:
if i>=len(out_list):
break
if len(out_list[i])<7:
out_list[i]=' '
i+=1
return out_list
#Input string
string_to_translate = raw_input(':>')
#string converted to words
string_to_translate=string_to_translate.replace('-',' ')
string_to_translate=string_to_translate.replace('|',' ')
words = string_to_translate.split()
#an output list with the string is initialized
listed=[]
#the monier williams sanskrit - english dictonary was loaded to list
FILE = open('_MW.txt', 'r')
lines = FILE.readlines()
FILE.close()
#each dictonary word is searched in the given string, is found, added to list
for line in lines:
if len(line)>1:
if string_to_translate.find(line[0:len(line)-1])>-1:
listed.append(line)
#the given list is not regular but is with all the dictonary matches listed
listed = add_index_tag(listed, string_to_translate)
listed = refine_list(listed)
length = len(listed)
for i in range(length):
entry = listed[i]
listed[i] = entry[3:len(entry)]
# print the matches sorted
lines = []
for word in words:
tmp_list = []
out_format=''
for one in listed:
if word.find(one[0:len(one)-1])>-1 and len(one)>2:
tmp_list.append(one[0:len(one)-1]+' ')
for once in tmp_list:
if len(word)==(len(once)-1):
tmp_list = []
tmp_list.append(once)
line = word+'::\t'+out_format.join(tmp_list)
print line
lines.append(line)
#write lines to file
FILE = open('iText.txt','w')
FILE.writelines(string_to_translate)
FILE.writelines(lines)
FILE.close()
| [
[
8,
0,
0.0247,
0.0123,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.037,
0.0123,
0,
0.66,
0.0435,
0,
1,
0,
0,
0,
0,
0,
0
],
[
8,
0,
0.0926,
0.0741,
0,
0.66,
... | [
"''' Hare Krsna '''",
"''' om namo Bhagavate Vasudevaya '''",
"'''\n find the dictonary matches in the MW dictonary\n\n and NITAI VEDA and Glossary\n\n'''",
"def add_index_tag(in_list,in_string):\n length = len(in_list)\n out_list = in_list\n for i in range(length):\n ent... |
#! usr/bin/env python
#-*- coding: UTF-8 -*-
import heapq
import math
def distancia_entre_puntos(x1,x2,y1,y2):
return math.sqrt((x1-y1)**2+(x2-y2)**2)
def dijkstra(grafo, origen, destino=None, p=0):
if origen == destino: return (0, [origen])
distancias = {} # diccionario con las distancias finales
caminos = {} # diccionario de caminos
pesos = {}
heap = [] # usa heapq con tuplas de (distancia,nodo)
heapq.heappush(heap,(0,origen, []))
padre = origen
while heap:
(peso,vert,camino)=heapq.heappop(heap)
if vert in pesos: continue # ya está listo
pesos[vert] = peso
caminos[vert] = camino
distancias[vert] = distancia_entre_puntos(float(vert.datos[1]), float(vert.datos[2]),float(padre.datos[1]), float(padre.datos[2]))
if vert == destino: break # Si ya llegue salgo
for dest, datos in grafo.aristas(vert):
v_peso = pesos[vert] + int(datos[p]) #p = posición del valor peso en datos
camino = caminos[vert]+[dest]
padre = vert
heapq.heappush(heap,(v_peso, dest, camino))
return (pesos, distancias,caminos)
| [
[
1,
0,
0.0938,
0.0312,
0,
0.66,
0,
251,
0,
1,
0,
0,
251,
0,
0
],
[
1,
0,
0.125,
0.0312,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
2,
0,
0.2031,
0.0625,
0,
0... | [
"import heapq",
"import math",
"def distancia_entre_puntos(x1,x2,y1,y2):\n\treturn math.sqrt((x1-y1)**2+(x2-y2)**2)",
"\treturn math.sqrt((x1-y1)**2+(x2-y2)**2)",
"def dijkstra(grafo, origen, destino=None, p=0):\n\t\n if origen == destino: return (0, [origen])\n distancias = {} # diccionario con las ... |
#! usr/bin/env python
#-*- coding: UTF-8 -*-
import heapq
import math
def distancia_entre_puntos(x1,x2,y1,y2):
return math.sqrt((x1-y1)**2+(x2-y2)**2)
def dijkstra(grafo, origen, destino=None, p=0):
if origen == destino: return (0, [origen])
distancias = {} # diccionario con las distancias finales
caminos = {} # diccionario de caminos
pesos = {}
heap = [] # usa heapq con tuplas de (distancia,nodo)
heapq.heappush(heap,(0,origen, []))
padre = origen
while heap:
(peso,vert,camino)=heapq.heappop(heap)
if vert in pesos: continue # ya está listo
pesos[vert] = peso
caminos[vert] = camino
distancias[vert] = distancia_entre_puntos(float(vert.datos[1]), float(vert.datos[2]),float(padre.datos[1]), float(padre.datos[2]))
if vert == destino: break # Si ya llegue salgo
for dest, datos in grafo.aristas(vert):
v_peso = pesos[vert] + int(datos[p]) #p = posición del valor peso en datos
camino = caminos[vert]+[dest]
padre = vert
heapq.heappush(heap,(v_peso, dest, camino))
return (pesos, distancias,caminos)
| [
[
1,
0,
0.0938,
0.0312,
0,
0.66,
0,
251,
0,
1,
0,
0,
251,
0,
0
],
[
1,
0,
0.125,
0.0312,
0,
0.66,
0.3333,
526,
0,
1,
0,
0,
526,
0,
0
],
[
2,
0,
0.2031,
0.0625,
0,
0... | [
"import heapq",
"import math",
"def distancia_entre_puntos(x1,x2,y1,y2):\n\treturn math.sqrt((x1-y1)**2+(x2-y2)**2)",
"\treturn math.sqrt((x1-y1)**2+(x2-y2)**2)",
"def dijkstra(grafo, origen, destino=None, p=0):\n\t\n if origen == destino: return (0, [origen])\n distancias = {} # diccionario con las ... |
#! usr/bin/env python
#-*- coding: UTF-8 -*-
class Vertice(object):
def __init__(self, id, datos):
self.adyacentes = {}
self.datos = datos
self.id = id
def __cmp__(self, otro):
if self.id == otro.id:
return 0
if self.id > otro.id:
return 1
if self.id < otro.id:
return -1
def ver_adyacentes(self):
'''Devuelve un diccionario con los vértices adyacentes al vértice'''
return self.adyacentes.keys()
class Grafo(object):
def __init__(self):
self.vertices = {}
def esta_vertice(self, vertice):
'''Devuelve true or false según el vértice esté en el grafo o no'''
if not vertice:
return False
return self.vertices.has_key(vertice.id)
def agregar_vertice(self,vertice):
#Agrega un vértice al grafo. Si ya existía, devuelve false
if self.esta_vertice(vertice):
return False
self.vertices[vertice.id] = vertice
return True
def obtener_vertice(self,id):
'''Dado un id devuelve el objeto vértice correspondiente'''
if id in self.vertices.keys():
return self.vertices[id]
return None
def agregar_arista(self, vertice1, vertice2, datos):
'''Agrega la arista que va desde vértice1 hacia vértice2'''
if (not self.esta_vertice(vertice1)) or (not self.esta_vertice(vertice2)):
return False
vertice1.adyacentes[vertice2.id] = datos
return True
def borrar_vertice(self, vertice):
if not self.esta_vertice(vertice):
return False
del self.vertices[vertice.id]
return True
def borrar_arista (self, vertice1, vertice2):
'''Borra la arista que va desde el vertice1 hacia el vertice2'''
if not self.esta_vertice(vertice1) or not self.esta_vertice(vertice2):
return False
ady = vertice1.adyacentes
if vertice2.id in ady.keys():
del ady[vertice2.id]
return True
def aristas(self, vertice):
'''Devuelve una lista de tuplas (vértice adyacente, datos) de cada arista que sale del vértice. '''
aristas = []
adyacentes = vertice.adyacentes
for id in adyacentes.keys():
vertice = self.obtener_vertice(id)
datos = adyacentes[id]
aristas.append((vertice, datos))
return aristas
| [
[
3,
0,
0.15,
0.2125,
0,
0.66,
0,
519,
0,
3,
0,
0,
186,
0,
1
],
[
2,
1,
0.0813,
0.05,
1,
0.66,
0,
555,
0,
3,
0,
0,
0,
0,
0
],
[
14,
2,
0.075,
0.0125,
2,
0.32,
0... | [
"class Vertice(object):\n\tdef __init__(self, id, datos):\n\t\tself.adyacentes = {}\n\t\tself.datos = datos\n\t\tself.id = id\n\n\tdef __cmp__(self, otro):\n\t\tif self.id == otro.id:",
"\tdef __init__(self, id, datos):\n\t\tself.adyacentes = {}\n\t\tself.datos = datos\n\t\tself.id = id",
"\t\tself.adyacentes =... |
#! usr/bin/env python
#-*- coding: UTF-8 -*-
import sys
import grafo
import math
import heapq
def guardar_vertices(archivo, Grafo):
'''Lee la cantidad de lineas equivalente a las intersecciones y
agrega el vértice con el primer campo como id, y el resto como datos'''
linea = archivo.readline()
for i in range (int(linea)):
linea = archivo.readline()
campos = linea.split(',')
v = grafo.Vertice(int(campos[0]),campos)
Grafo.agregar_vertice(v)
def guardar_aristas(archivo, Grafo):
'''Lee la cantidad de lineas equivalente a las calles y
agrega las aristas con la información correspondiente'''
linea = archivo.readline()
for i in range (int(linea)):
linea = archivo.readline()
campos = linea.split(',')
v_inicial = Grafo.obtener_vertice(int(campos[4]))
v_final = Grafo.obtener_vertice(int(campos[5]))
Grafo.agregar_arista(v_inicial, v_final, campos)
#Si es doble mano agrego la arista hacia el vértice final
if ( int(campos[3]) == 0):
Grafo.agregar_arista(v_final, v_inicial, campos)
def cargar_grafo(Grafo, archivo):
'''Dado un archivo con los datos de los vértices y aristas, lo abre y lee linea a linea
guardando en el grafo la información correspondiente'''
try:
archivo = open(archivo, "r")
except IOError:
print "Archivo inexistente"
sys.exit()
guardar_vertices(archivo,Grafo)
guardar_aristas(archivo,Grafo)
archivo.close()
return True
def mejor_camino(vert_origen, vert_destino, g, limite):
'''Calcula el mejor camino entre dos vértices mediante el algoritmo
de Dijstra. Devuelve un diccionario con las distancias y otro con
los caminos. Si se ingresó un valor de distancia máximo (límite) y la distancia
entre vértices lo supera, el diccionario de caminos no contendrá al vértice destino.'''
if (not vert_origen) or (not vert_destino):
return ({},{})
#2 = posición del valor "peso" (tipo de calle) en la lista de datos de la arista que sale del vértice.
#datos = [calle1,nombre,tipo de calle, mano única, nodo inicial, nodo final]
return dijkstra(g, vert_origen, vert_destino, 2, limite)
def coordenadas_ruta(caminos,origen, destino):
'''Obtiene las coordenadas de los vértices en la ruta hasta llegar
a destino y las devuelve en una cadena'''
coordenadas = []
coordenadas.append(origen.datos[3])
coordenadas.append((origen.datos[4]).replace('\n',' '))
if not caminos.has_key(destino):
#en el caso que no haya camino, por ej si se restringió la distancia
#devuelve una cadena vacía para escribir espacio en blanco en el archivo de rutas
return " "
for vertice in caminos[destino]:
coordenadas.append(vertice.datos[3])
coordenadas.append((vertice.datos[4]).replace('\n',' '))
coordenadas = ",".join(coordenadas)
return coordenadas
def crear_archivo_rutas(origen):
'''Crea un nuevo archivo "rutas.kml" donde se escribirán todos los caminos.
Escribe un encabezado y las coordenadas del origen (pizzeria) '''
try:
arch_rutas = open("rutas.kml", "w")
except IOError:
print "Error al crear el archivo\n"
sys.exit()
#Escribo en el archivo el título , encabezado y coordenadas de la pizzería
encabezado = """<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>\n\n\n"""
arch_rutas.write(encabezado)
titulo = "\n\t<name> CAMINOS </name>\n"
arch_rutas.write(titulo)
#Escribo el marcador de la pizzería
marcador_origen = """ \n<Placemark>
<name>Pizzería</name>
<Point>
<coordinates>""",origen.datos[3],origen.datos[4],"""</coordinates>
</Point>
</Placemark>\n"""
marcador_origen = " ".join(marcador_origen)
arch_rutas.write(marcador_origen)
arch_rutas.close()
def agregar_pie_arch_rutas():
'''Agrega el pie al archivo_rutas.kml'''
try:
arch_rutas = open("rutas.kml", "a+")
except IOError:
print "Error al abrir el archivo\n"
sys.exit()
pie = """\n</Document>
</kml>"""
arch_rutas.write(pie)
arch_rutas.close()
def escribir_ruta_en_archivo(caminos,origen,destino):
'''Escribe en un archivo la ruta desde el origen hacia el destino'''
try:
arch_rutas = open("rutas.kml", "a+")
except IOError:
print "Error al abrir el archivo\n"
sys.exit()
coordenadas= coordenadas_ruta(caminos,origen, destino)
linea= [""" \n<Placemark>
<name>Marche una grande de muzza</name>
<LineString>
<coordinates>\n""",coordenadas, """ \n</coordinates>
</LineString>
</Placemark>\n"""]
linea = " ".join(linea)
marcador_destino = """\n <Placemark>
<name>Cliente</name>
<Point>
<coordinates>""",destino.datos[3],destino.datos[4],"""</coordinates>
</Point>
</Placemark>\n"""
marcador_destino = " ".join(marcador_destino)
arch_rutas.write(linea)
arch_rutas.write(marcador_destino)
arch_rutas.close()
def obtener_vertice(grafo):
'''Devuelve el vértice correspondiente a la intersección de calles
ingresada por el usuario, si no existe la intersección se vuelve a pedir
el ingreso de la dirección'''
vertice = obtener_interseccion(grafo)
while not vertice:
print "Intersección inválida"
vertice = obtener_interseccion(grafo)
return vertice
def obtener_interseccion(grafo):
'''Pide el ingreso los nombres de dos calles, busca en el grafo el objeto vértice
cuyas aristas tengan el nombre de ambas calles, si lo encuentra lo devuelve
sino devuelve None'''
calle1 = raw_input("Ingrese primer calle que genera la intersección:\n")
calle2 = raw_input("Ingrese la segunda calle que genera la intersección:\n")
calles= []
for vertice_id in grafo.vertices.keys():
vertice = grafo.obtener_vertice(vertice_id)
aristas = grafo.aristas(vertice)
for arista in aristas:
datos = arista[1] #arista = (vertice, datos)
calles.append(datos[1]) #datos = (calle, nombre, tipo, mano, n_ini, n_fin)
if calle1 in calles:
if calle2 in calles:
return vertice
calles = []
return None
def distancia_entre_puntos(x1,x2,y1,y2):
'''Calcula la distancia entre dos puntos'''
return math.sqrt((x1-y1)**2+(x2-y2)**2)
def dijkstra(grafo, origen, destino=None, p=0, limite = None):
'''Devuelve un diccionario con las distancias entre origen y destino
y otro diccionario con los caminos entre ellos. Límite es un valor ingresado por el usuario
el cual representa la distancia máxima que se puede recorrer. p es la posición del valor peso
en la lista de datos de la arista'''
if origen == destino: return (0, [origen])
distancias = {} # diccionario con las distancias finales
caminos = {} # diccionario de caminos
pesos = {}
heap = [] # usa heapq con tuplas de (distancia,nodo)
heapq.heappush(heap,(0,origen, []))
padre = origen
while heap:
(peso,vert,camino)=heapq.heappop(heap)
if vert in pesos: continue # ya está listo
pesos[vert] = peso
caminos[vert] = camino
distancias[vert] = distancia_entre_puntos(float(vert.datos[1]), float(vert.datos[2]),float(padre.datos[1]), float(padre.datos[2]))
if vert == destino: break # Si ya llegue salgo
for dest, datos in grafo.aristas(vert):
v_peso = pesos[vert] + int(datos[p]) #p = posición del valor peso en lista de datos de la arista
camino = caminos[vert]+[dest]
padre = vert
if limite and distancias[vert] > limite:
continue
else:
heapq.heappush(heap,(v_peso, dest, camino))
return (pesos, distancias,caminos)
def informar_distancia(distancias, destino):
'''Informa si se puede llegar o no a destino, en caso que se pueda llegar
imprime la distancia hasta destino'''
if not distancias.has_key(destino):
print "No se puede llegar a destino\n"
else:
print "Distancia:" ,distancias[destino]
def main():
if len(sys.argv) < 2:
print "Error: Cantidad de parámetros incorrecta\n"
sys.exit()
#argv1 = archivo de avellaneda
archivo = sys.argv[1]
graph = grafo.Grafo()
cargar_grafo(graph, archivo)
print "DIRECCIÓN DE LA PIZZERÍA"
vert_pizzeria = obtener_vertice(graph)
crear_archivo_rutas(vert_pizzeria)
seguir = "s"
while (seguir != "n"):
print "DIRECCIÓN DEL CLIENTE"
vert_destino = obtener_vertice(graph)
aux = raw_input("Restringir distancia? s/n: ")
if aux == "s" or aux == "S":
limite = input("Ingrese valor distancia máxima:\n ")
pesos,distancias,caminos = mejor_camino(vert_pizzeria, vert_destino, graph,limite)
else:
pesos,distancias,caminos = mejor_camino(vert_pizzeria, vert_destino, graph, None)
escribir_ruta_en_archivo(caminos,vert_pizzeria, vert_destino)
informar_distancia(distancias, vert_destino)
seguir = raw_input("Desea continuar(s/n)?\n")
agregar_pie_arch_rutas()
main()
| [
[
1,
0,
0.0154,
0.0038,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0192,
0.0038,
0,
0.66,
0.0556,
503,
0,
1,
0,
0,
503,
0,
0
],
[
1,
0,
0.0231,
0.0038,
0,
... | [
"import sys",
"import grafo",
"import math",
"import heapq",
"def guardar_vertices(archivo, Grafo):\n\t'''Lee la cantidad de lineas equivalente a las intersecciones y\n\tagrega el vértice con el primer campo como id, y el resto como datos'''\n\tlinea = archivo.readline()\n\tfor i in range (int(linea)):\n\t\... |
#! usr/bin/env python
#-*- coding: UTF-8 -*-
import sys
import grafo
import math
import heapq
def guardar_vertices(archivo, Grafo):
'''Lee la cantidad de lineas equivalente a las intersecciones y
agrega el vértice con el primer campo como id, y el resto como datos'''
linea = archivo.readline()
for i in range (int(linea)):
linea = archivo.readline()
campos = linea.split(',')
v = grafo.Vertice(int(campos[0]),campos)
Grafo.agregar_vertice(v)
def guardar_aristas(archivo, Grafo):
'''Lee la cantidad de lineas equivalente a las calles y
agrega las aristas con la información correspondiente'''
linea = archivo.readline()
for i in range (int(linea)):
linea = archivo.readline()
campos = linea.split(',')
v_inicial = Grafo.obtener_vertice(int(campos[4]))
v_final = Grafo.obtener_vertice(int(campos[5]))
Grafo.agregar_arista(v_inicial, v_final, campos)
#Si es doble mano agrego la arista hacia el vértice final
if ( int(campos[3]) == 0):
Grafo.agregar_arista(v_final, v_inicial, campos)
def cargar_grafo(Grafo, archivo):
'''Dado un archivo con los datos de los vértices y aristas, lo abre y lee linea a linea
guardando en el grafo la información correspondiente'''
try:
archivo = open(archivo, "r")
except IOError:
print "Archivo inexistente"
sys.exit()
guardar_vertices(archivo,Grafo)
guardar_aristas(archivo,Grafo)
archivo.close()
return True
def mejor_camino(vert_origen, vert_destino, g, limite):
'''Calcula el mejor camino entre dos vértices mediante el algoritmo
de Dijstra. Devuelve un diccionario con las distancias y otro con
los caminos. Si se ingresó un valor de distancia máximo (límite) y la distancia
entre vértices lo supera, el diccionario de caminos no contendrá al vértice destino.'''
if (not vert_origen) or (not vert_destino):
return ({},{})
#2 = posición del valor "peso" (tipo de calle) en la lista de datos de la arista que sale del vértice.
#datos = [calle1,nombre,tipo de calle, mano única, nodo inicial, nodo final]
return dijkstra(g, vert_origen, vert_destino, 2, limite)
def coordenadas_ruta(caminos,origen, destino):
'''Obtiene las coordenadas de los vértices en la ruta hasta llegar
a destino y las devuelve en una cadena'''
coordenadas = []
coordenadas.append(origen.datos[3])
coordenadas.append((origen.datos[4]).replace('\n',' '))
if not caminos.has_key(destino):
#en el caso que no haya camino, por ej si se restringió la distancia
#devuelve una cadena vacía para escribir espacio en blanco en el archivo de rutas
return " "
for vertice in caminos[destino]:
coordenadas.append(vertice.datos[3])
coordenadas.append((vertice.datos[4]).replace('\n',' '))
coordenadas = ",".join(coordenadas)
return coordenadas
def crear_archivo_rutas(origen):
'''Crea un nuevo archivo "rutas.kml" donde se escribirán todos los caminos.
Escribe un encabezado y las coordenadas del origen (pizzeria) '''
try:
arch_rutas = open("rutas.kml", "w")
except IOError:
print "Error al crear el archivo\n"
sys.exit()
#Escribo en el archivo el título , encabezado y coordenadas de la pizzería
encabezado = """<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>\n\n\n"""
arch_rutas.write(encabezado)
titulo = "\n\t<name> CAMINOS </name>\n"
arch_rutas.write(titulo)
#Escribo el marcador de la pizzería
marcador_origen = """ \n<Placemark>
<name>Pizzería</name>
<Point>
<coordinates>""",origen.datos[3],origen.datos[4],"""</coordinates>
</Point>
</Placemark>\n"""
marcador_origen = " ".join(marcador_origen)
arch_rutas.write(marcador_origen)
arch_rutas.close()
def agregar_pie_arch_rutas():
'''Agrega el pie al archivo_rutas.kml'''
try:
arch_rutas = open("rutas.kml", "a+")
except IOError:
print "Error al abrir el archivo\n"
sys.exit()
pie = """\n</Document>
</kml>"""
arch_rutas.write(pie)
arch_rutas.close()
def escribir_ruta_en_archivo(caminos,origen,destino):
'''Escribe en un archivo la ruta desde el origen hacia el destino'''
try:
arch_rutas = open("rutas.kml", "a+")
except IOError:
print "Error al abrir el archivo\n"
sys.exit()
coordenadas= coordenadas_ruta(caminos,origen, destino)
linea= [""" \n<Placemark>
<name>Marche una grande de muzza</name>
<LineString>
<coordinates>\n""",coordenadas, """ \n</coordinates>
</LineString>
</Placemark>\n"""]
linea = " ".join(linea)
marcador_destino = """\n <Placemark>
<name>Cliente</name>
<Point>
<coordinates>""",destino.datos[3],destino.datos[4],"""</coordinates>
</Point>
</Placemark>\n"""
marcador_destino = " ".join(marcador_destino)
arch_rutas.write(linea)
arch_rutas.write(marcador_destino)
arch_rutas.close()
def obtener_vertice(grafo):
'''Devuelve el vértice correspondiente a la intersección de calles
ingresada por el usuario, si no existe la intersección se vuelve a pedir
el ingreso de la dirección'''
vertice = obtener_interseccion(grafo)
while not vertice:
print "Intersección inválida"
vertice = obtener_interseccion(grafo)
return vertice
def obtener_interseccion(grafo):
'''Pide el ingreso los nombres de dos calles, busca en el grafo el objeto vértice
cuyas aristas tengan el nombre de ambas calles, si lo encuentra lo devuelve
sino devuelve None'''
calle1 = raw_input("Ingrese primer calle que genera la intersección:\n")
calle2 = raw_input("Ingrese la segunda calle que genera la intersección:\n")
calles= []
for vertice_id in grafo.vertices.keys():
vertice = grafo.obtener_vertice(vertice_id)
aristas = grafo.aristas(vertice)
for arista in aristas:
datos = arista[1] #arista = (vertice, datos)
calles.append(datos[1]) #datos = (calle, nombre, tipo, mano, n_ini, n_fin)
if calle1 in calles:
if calle2 in calles:
return vertice
calles = []
return None
def distancia_entre_puntos(x1,x2,y1,y2):
'''Calcula la distancia entre dos puntos'''
return math.sqrt((x1-y1)**2+(x2-y2)**2)
def dijkstra(grafo, origen, destino=None, p=0, limite = None):
'''Devuelve un diccionario con las distancias entre origen y destino
y otro diccionario con los caminos entre ellos. Límite es un valor ingresado por el usuario
el cual representa la distancia máxima que se puede recorrer. p es la posición del valor peso
en la lista de datos de la arista'''
if origen == destino: return (0, [origen])
distancias = {} # diccionario con las distancias finales
caminos = {} # diccionario de caminos
pesos = {}
heap = [] # usa heapq con tuplas de (distancia,nodo)
heapq.heappush(heap,(0,origen, []))
padre = origen
while heap:
(peso,vert,camino)=heapq.heappop(heap)
if vert in pesos: continue # ya está listo
pesos[vert] = peso
caminos[vert] = camino
distancias[vert] = distancia_entre_puntos(float(vert.datos[1]), float(vert.datos[2]),float(padre.datos[1]), float(padre.datos[2]))
if vert == destino: break # Si ya llegue salgo
for dest, datos in grafo.aristas(vert):
v_peso = pesos[vert] + int(datos[p]) #p = posición del valor peso en lista de datos de la arista
camino = caminos[vert]+[dest]
padre = vert
if limite and distancias[vert] > limite:
continue
else:
heapq.heappush(heap,(v_peso, dest, camino))
return (pesos, distancias,caminos)
def informar_distancia(distancias, destino):
'''Informa si se puede llegar o no a destino, en caso que se pueda llegar
imprime la distancia hasta destino'''
if not distancias.has_key(destino):
print "No se puede llegar a destino\n"
else:
print "Distancia:" ,distancias[destino]
def main():
if len(sys.argv) < 2:
print "Error: Cantidad de parámetros incorrecta\n"
sys.exit()
#argv1 = archivo de avellaneda
archivo = sys.argv[1]
graph = grafo.Grafo()
cargar_grafo(graph, archivo)
print "DIRECCIÓN DE LA PIZZERÍA"
vert_pizzeria = obtener_vertice(graph)
crear_archivo_rutas(vert_pizzeria)
seguir = "s"
while (seguir != "n"):
print "DIRECCIÓN DEL CLIENTE"
vert_destino = obtener_vertice(graph)
aux = raw_input("Restringir distancia? s/n: ")
if aux == "s" or aux == "S":
limite = input("Ingrese valor distancia máxima:\n ")
pesos,distancias,caminos = mejor_camino(vert_pizzeria, vert_destino, graph,limite)
else:
pesos,distancias,caminos = mejor_camino(vert_pizzeria, vert_destino, graph, None)
escribir_ruta_en_archivo(caminos,vert_pizzeria, vert_destino)
informar_distancia(distancias, vert_destino)
seguir = raw_input("Desea continuar(s/n)?\n")
agregar_pie_arch_rutas()
main()
| [
[
1,
0,
0.0154,
0.0038,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0192,
0.0038,
0,
0.66,
0.0556,
503,
0,
1,
0,
0,
503,
0,
0
],
[
1,
0,
0.0231,
0.0038,
0,
... | [
"import sys",
"import grafo",
"import math",
"import heapq",
"def guardar_vertices(archivo, Grafo):\n\t'''Lee la cantidad de lineas equivalente a las intersecciones y\n\tagrega el vértice con el primer campo como id, y el resto como datos'''\n\tlinea = archivo.readline()\n\tfor i in range (int(linea)):\n\t\... |
#! usr/bin/env python
#-*- coding: UTF-8 -*-
class Vertice(object):
def __init__(self, id, datos):
self.adyacentes = {}
self.datos = datos
self.id = id
def __cmp__(self, otro):
if self.id == otro.id:
return 0
if self.id > otro.id:
return 1
if self.id < otro.id:
return -1
def ver_adyacentes(self):
'''Devuelve un diccionario con los vértices adyacentes al vértice'''
return self.adyacentes.keys()
class Grafo(object):
def __init__(self):
self.vertices = {}
def esta_vertice(self, vertice):
'''Devuelve true or false según el vértice esté en el grafo o no'''
if not vertice:
return False
return self.vertices.has_key(vertice.id)
def agregar_vertice(self,vertice):
#Agrega un vértice al grafo. Si ya existía, devuelve false
if self.esta_vertice(vertice):
return False
self.vertices[vertice.id] = vertice
return True
def obtener_vertice(self,id):
'''Dado un id devuelve el objeto vértice correspondiente'''
if id in self.vertices.keys():
return self.vertices[id]
return None
def agregar_arista(self, vertice1, vertice2, datos):
'''Agrega la arista que va desde vértice1 hacia vértice2'''
if (not self.esta_vertice(vertice1)) or (not self.esta_vertice(vertice2)):
return False
vertice1.adyacentes[vertice2.id] = datos
return True
def borrar_vertice(self, vertice):
if not self.esta_vertice(vertice):
return False
del self.vertices[vertice.id]
return True
def borrar_arista (self, vertice1, vertice2):
'''Borra la arista que va desde el vertice1 hacia el vertice2'''
if not self.esta_vertice(vertice1) or not self.esta_vertice(vertice2):
return False
ady = vertice1.adyacentes
if vertice2.id in ady.keys():
del ady[vertice2.id]
return True
def aristas(self, vertice):
'''Devuelve una lista de tuplas (vértice adyacente, datos) de cada arista que sale del vértice. '''
aristas = []
adyacentes = vertice.adyacentes
for id in adyacentes.keys():
vertice = self.obtener_vertice(id)
datos = adyacentes[id]
aristas.append((vertice, datos))
return aristas
| [
[
3,
0,
0.15,
0.2125,
0,
0.66,
0,
519,
0,
3,
0,
0,
186,
0,
1
],
[
2,
1,
0.0813,
0.05,
1,
0.22,
0,
555,
0,
3,
0,
0,
0,
0,
0
],
[
14,
2,
0.075,
0.0125,
2,
0.62,
0... | [
"class Vertice(object):\n\tdef __init__(self, id, datos):\n\t\tself.adyacentes = {}\n\t\tself.datos = datos\n\t\tself.id = id\n\n\tdef __cmp__(self, otro):\n\t\tif self.id == otro.id:",
"\tdef __init__(self, id, datos):\n\t\tself.adyacentes = {}\n\t\tself.datos = datos\n\t\tself.id = id",
"\t\tself.adyacentes =... |
#!/usr/bin/python
'''
@author: Manuel F Martinez <manpaz@bashlinux.com>
@organization: Bashlinux
@copyright: Copyright (c) 2012 Bashlinux
@license: GPL
'''
import Image
import time
from constants import *
from exceptions import *
class Escpos:
""" ESC/POS Printer object """
device = None
def _check_image_size(self, size):
""" Check and fix the size of the image to 32 bits """
if size % 32 == 0:
return (0, 0)
else:
image_border = 32 - (size % 32)
if (image_border % 2) == 0:
return (image_border / 2, image_border / 2)
else:
return (image_border / 2, (image_border / 2) + 1)
def _print_image(self, line, size):
""" Print formatted image """
i = 0
cont = 0
buffer = ""
self._raw(S_RASTER_N)
buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1], 0)
self._raw(buffer.decode('hex'))
buffer = ""
while i < len(line):
hex_string = int(line[i:i+8],2)
buffer += "%02X" % hex_string
i += 8
cont += 1
if cont % 4 == 0:
self._raw(buffer.decode("hex"))
buffer = ""
cont = 0
def image(self, img):
""" Parse image and prepare it to a printable format """
pixels = []
pix_line = ""
im_left = ""
im_right = ""
switch = 0
img_size = [ 0, 0 ]
im_open = Image.open(img)
im = im_open.convert("RGB")
if im.size[0] > 512:
print "WARNING: Image is wider than 512 and could be truncated at print time "
if im.size[1] > 255:
raise ImageSizeError()
im_border = self._check_image_size(im.size[0])
for i in range(im_border[0]):
im_left += "0"
for i in range(im_border[1]):
im_right += "0"
for y in range(im.size[1]):
img_size[1] += 1
pix_line += im_left
img_size[0] += im_border[0]
for x in range(im.size[0]):
img_size[0] += 1
RGB = im.getpixel((x, y))
im_color = (RGB[0] + RGB[1] + RGB[2])
im_pattern = "1X0"
pattern_len = len(im_pattern)
switch = (switch - 1 ) * (-1)
for x in range(pattern_len):
if im_color <= (255 * 3 / pattern_len * (x+1)):
if im_pattern[x] == "X":
pix_line += "%d" % switch
else:
pix_line += im_pattern[x]
break
elif im_color > (255 * 3 / pattern_len * pattern_len) and im_color <= (255 * 3):
pix_line += im_pattern[-1]
break
pix_line += im_right
img_size[0] += im_border[1]
self._print_image(pix_line, img_size)
def barcode(self, code, bc, width, height, pos, font):
""" Print Barcode """
# Align Bar Code()
self._raw(TXT_ALIGN_CT)
# Height
if height >=2 or height <=6:
self._raw(BARCODE_HEIGHT)
else:
raise BarcodeSizeError()
# Width
if width >= 1 or width <=255:
self._raw(BARCODE_WIDTH)
else:
raise BarcodeSizeError()
# Font
if font.upper() == "B":
self._raw(BARCODE_FONT_B)
else: # DEFAULT FONT: A
self._raw(BARCODE_FONT_A)
# Position
if pos.upper() == "OFF":
self._raw(BARCODE_TXT_OFF)
elif pos.upper() == "BOTH":
self._raw(BARCODE_TXT_BTH)
elif pos.upper() == "ABOVE":
self._raw(BARCODE_TXT_ABV)
else: # DEFAULT POSITION: BELOW
self._raw(BARCODE_TXT_BLW)
# Type
if bc.upper() == "UPC-A":
self._raw(BARCODE_UPC_A)
elif bc.upper() == "UPC-E":
self._raw(BARCODE_UPC_E)
elif bc.upper() == "EAN13":
self._raw(BARCODE_EAN13)
elif bc.upper() == "EAN8":
self._raw(BARCODE_EAN8)
elif bc.upper() == "CODE39":
self._raw(BARCODE_CODE39)
elif bc.upper() == "ITF":
self._raw(BARCODE_ITF)
elif bc.upper() == "NW7":
self._raw(BARCODE_NW7)
else:
raise BarcodeTypeError()
# Print Code
if code:
self._raw(code)
else:
raise exception.BarcodeCodeError()
def text(self, txt):
""" Print alpha-numeric text """
if txt:
self._raw(txt)
else:
raise TextError()
def set(self, align='left', font='a', type='normal', width=1, height=1):
""" Set text properties """
# Align
if align.upper() == "CENTER":
self._raw(TXT_ALIGN_CT)
elif align.upper() == "RIGHT":
self._raw(TXT_ALIGN_RT)
elif align.upper() == "LEFT":
self._raw(TXT_ALIGN_LT)
# Font
if font.upper() == "B":
self._raw(TXT_FONT_B)
else: # DEFAULT FONT: A
self._raw(TXT_FONT_A)
# Type
if type.upper() == "B":
self._raw(TXT_BOLD_ON)
self._raw(TXT_UNDERL_OFF)
elif type.upper() == "U":
self._raw(TXT_BOLD_OFF)
self._raw(TXT_UNDERL_ON)
elif type.upper() == "U2":
self._raw(TXT_BOLD_OFF)
self._raw(TXT_UNDERL2_ON)
elif type.upper() == "BU":
self._raw(TXT_BOLD_ON)
self._raw(TXT_UNDERL_ON)
elif type.upper() == "BU2":
self._raw(TXT_BOLD_ON)
self._raw(TXT_UNDERL2_ON)
elif type.upper == "NORMAL":
self._raw(TXT_BOLD_OFF)
self._raw(TXT_UNDERL_OFF)
# Width
if width == 2 and height != 2:
self._raw(TXT_NORMAL)
self._raw(TXT_2WIDTH)
elif height == 2 and width != 2:
self._raw(TXT_NORMAL)
self._raw(TXT_2HEIGHT)
elif height == 2 and width == 2:
self._raw(TXT_2WIDTH)
self._raw(TXT_2HEIGHT)
else: # DEFAULT SIZE: NORMAL
self._raw(TXT_NORMAL)
def cut(self, mode=''):
""" Cut paper """
# Fix the size between last line and cut
# TODO: handle this with a line feed
self._raw("\n\n\n\n\n\n")
if mode.upper() == "PART":
self._raw(PAPER_PART_CUT)
else: # DEFAULT MODE: FULL CUT
self._raw(PAPER_FULL_CUT)
def cashdraw(self, pin):
""" Send pulse to kick the cash drawer """
if pin == 2:
self._raw(CD_KICK_2)
elif pin == 5:
self._raw(CD_KICK_5)
else:
raise CashDrawerError()
def hw(self, hw):
""" Hardware operations """
if hw.upper() == "INIT":
self._raw(HW_INIT)
elif hw.upper() == "SELECT":
self._raw(HW_SELECT)
elif hw.upper() == "RESET":
self._raw(HW_RESET)
else: # DEFAULT: DOES NOTHING
pass
def control(self, ctl):
""" Feed control sequences """
if ctl.upper() == "LF":
self._raw(CTL_LF)
elif ctl.upper() == "FF":
self._raw(CTL_FF)
elif ctl.upper() == "CR":
self._raw(CTL_CR)
elif ctl.upper() == "HT":
self._raw(CTL_HT)
elif ctl.upper() == "VT":
delf._raw(CTL_VT)
| [
[
8,
0,
0.0176,
0.0235,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0353,
0.0039,
0,
0.66,
0.2,
721,
0,
1,
0,
0,
721,
0,
0
],
[
1,
0,
0.0392,
0.0039,
0,
0.66,
... | [
"'''\n@author: Manuel F Martinez <manpaz@bashlinux.com>\n@organization: Bashlinux\n@copyright: Copyright (c) 2012 Bashlinux\n@license: GPL\n'''",
"import Image",
"import time",
"from constants import *",
"from exceptions import *",
"class Escpos:\n \"\"\" ESC/POS Printer object \"\"\"\n device = ... |
#!/usr/bin/python
'''
@author: Manuel F Martinez <manpaz@bashlinux.com>
@organization: Bashlinux
@copyright: Copyright (c) 2012 Bashlinux
@license: GPL
'''
import usb.core
import usb.util
import serial
import socket
from escpos import *
from constants import *
from exceptions import *
class Usb(Escpos):
""" Define USB printer """
def __init__(self, idVendor, idProduct, interface=0, in_ep=0x82, out_ep=0x01):
"""
@param idVendor : Vendor ID
@param idProduct : Product ID
@param interface : USB device interface
@param in_ep : Input end point
@param out_ep : Output end point
"""
self.idVendor = idVendor
self.idProduct = idProduct
self.interface = interface
self.in_ep = in_ep
self.out_ep = out_ep
self.open()
def open(self):
""" Search device on USB tree and set is as escpos device """
self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct)
if self.device is None:
print "Cable isn't plugged in"
if self.device.is_kernel_driver_active(0):
try:
self.device.detach_kernel_driver(0)
except usb.core.USBError as e:
print "Could not detatch kernel driver: %s" % str(e)
try:
self.device.set_configuration()
self.device.reset()
except usb.core.USBError as e:
print "Could not set configuration: %s" % str(e)
def _raw(self, msg):
""" Print any command sent in raw format """
self.device.write(self.out_ep, msg, self.interface)
def __del__(self):
""" Release USB interface """
if self.device:
usb.util.dispose_resources(self.device)
self.device = None
class Serial(Escpos):
""" Define Serial printer """
def __init__(self, devfile="/dev/ttyS0", baudrate=9600, bytesize=8, timeout=1):
"""
@param devfile : Device file under dev filesystem
@param baudrate : Baud rate for serial transmission
@param bytesize : Serial buffer size
@param timeout : Read/Write timeout
"""
self.devfile = devfile
self.baudrate = baudrate
self.bytesize = bytesize
self.timeout = timeout
self.open()
def open(self):
""" Setup serial port and set is as escpos device """
self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=self.timeout, dsrdtr=True)
if self.device is not None:
print "Serial printer enabled"
else:
print "Unable to open serial printer on: %s" % self.devfile
def _raw(self, msg):
""" Print any command sent in raw format """
self.device.write(msg)
def __del__(self):
""" Close Serial interface """
if self.device is not None:
self.device.close()
class Network(Escpos):
""" Define Network printer """
def __init__(self,host,port=9100):
"""
@param host : Printer's hostname or IP address
@param port : Port to write to
"""
self.host = host
self.port = port
self.open()
def open(self):
""" Open TCP socket and set it as escpos device """
self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.device.connect((self.host, self.port))
if self.device is None:
print "Could not open socket for %s" % self.host
def _raw(self, msg):
self.device.send(msg)
def __del__(self):
""" Close TCP connection """
self.device.close()
| [
[
8,
0,
0.0333,
0.0444,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0667,
0.0074,
0,
0.66,
0.1,
60,
0,
1,
0,
0,
60,
0,
0
],
[
1,
0,
0.0741,
0.0074,
0,
0.66,
... | [
"'''\n@author: Manuel F Martinez <manpaz@bashlinux.com>\n@organization: Bashlinux\n@copyright: Copyright (c) 2012 Bashlinux\n@license: GPL\n'''",
"import usb.core",
"import usb.util",
"import serial",
"import socket",
"from escpos import *",
"from constants import *",
"from exceptions import *",
"cl... |
""" ESC/POS Exceptions classes """
import os
class Error(Exception):
""" Base class for ESC/POS errors """
def __init__(self, msg, status=None):
Exception.__init__(self)
self.msg = msg
self.resultcode = 1
if status is not None:
self.resultcode = status
def __str__(self):
return self.msg
# Result/Exit codes
# 0 = success
# 10 = No Barcode type defined
# 20 = Barcode size values are out of range
# 30 = Barcode text not supplied
# 40 = Image height is too large
# 50 = No string supplied to be printed
# 60 = Invalid pin to send Cash Drawer pulse
class BarcodeTypeError(Error):
def __init__(self, msg=""):
Error.__init__(self, msg)
self.msg = msg
self.resultcode = 10
def __str__(self):
return "No Barcode type is defined"
class BarcodeSizeError(Error):
def __init__(self, msg=""):
Error.__init__(self, msg)
self.msg = msg
self.resultcode = 20
def __str__(self):
return "Barcode size is out of range"
class BarcodeCodeError(Error):
def __init__(self, msg=""):
Error.__init__(self, msg)
self.msg = msg
self.resultcode = 30
def __str__(self):
return "Code was not supplied"
class ImageSizeError(Error):
def __init__(self, msg=""):
Error.__init__(self, msg)
self.msg = msg
self.resultcode = 40
def __str__(self):
return "Image height is longer than 255px and can't be printed"
class TextError(Error):
def __init__(self, msg=""):
Error.__init__(self, msg)
self.msg = msg
self.resultcode = 50
def __str__(self):
return "Text string must be supplied to the text() method"
class CashDrawerError(Error):
def __init__(self, msg=""):
Error.__init__(self, msg)
self.msg = msg
self.resultcode = 60
def __str__(self):
return "Valid pin must be set to send pulse"
| [
[
8,
0,
0.0125,
0.0125,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0375,
0.0125,
0,
0.66,
0.125,
688,
0,
1,
0,
0,
688,
0,
0
],
[
3,
0,
0.125,
0.1375,
0,
0.66,
... | [
"\"\"\" ESC/POS Exceptions classes \"\"\"",
"import os",
"class Error(Exception):\n \"\"\" Base class for ESC/POS errors \"\"\"\n def __init__(self, msg, status=None):\n Exception.__init__(self)\n self.msg = msg\n self.resultcode = 1\n if status is not None:\n self.r... |
""" ESC/POS Commands (Constants) """
# Feed control sequences
CTL_LF = '\x0a' # Print and line feed
CTL_FF = '\x0c' # Form feed
CTL_CR = '\x0d' # Carriage return
CTL_HT = '\x09' # Horizontal tab
CTL_VT = '\x0b' # Vertical tab
# Printer hardware
HW_INIT = '\x1b\x40' # Clear data in buffer and reset modes
HW_SELECT = '\x1b\x3d\x01' # Printer select
HW_RESET = '\x1b\x3f\x0a\x00' # Reset printer hardware
# Cash Drawer
CD_KICK_2 = '\x1b\x70\x00' # Sends a pulse to pin 2 []
CD_KICK_5 = '\x1b\x70\x01' # Sends a pulse to pin 5 []
# Paper
PAPER_FULL_CUT = '\x1d\x56\x00' # Full cut paper
PAPER_PART_CUT = '\x1d\x56\x01' # Partial cut paper
# Text format
TXT_NORMAL = '\x1b\x21\x00' # Normal text
TXT_2HEIGHT = '\x1b\x21\x10' # Double height text
TXT_2WIDTH = '\x1b\x21\x20' # Double width text
TXT_UNDERL_OFF = '\x1b\x2d\x00' # Underline font OFF
TXT_UNDERL_ON = '\x1b\x2d\x01' # Underline font 1-dot ON
TXT_UNDERL2_ON = '\x1b\x2d\x02' # Underline font 2-dot ON
TXT_BOLD_OFF = '\x1b\x45\x00' # Bold font OFF
TXT_BOLD_ON = '\x1b\x45\x01' # Bold font ON
TXT_FONT_A = '\x1b\x4d\x00' # Font type A
TXT_FONT_B = '\x1b\x4d\x01' # Font type B
TXT_ALIGN_LT = '\x1b\x61\x00' # Left justification
TXT_ALIGN_CT = '\x1b\x61\x01' # Centering
TXT_ALIGN_RT = '\x1b\x61\x02' # Right justification
# Barcode format
BARCODE_TXT_OFF = '\x1d\x48\x00' # HRI barcode chars OFF
BARCODE_TXT_ABV = '\x1d\x48\x01' # HRI barcode chars above
BARCODE_TXT_BLW = '\x1d\x48\x02' # HRI barcode chars below
BARCODE_TXT_BTH = '\x1d\x48\x03' # HRI barcode chars both above and below
BARCODE_FONT_A = '\x1d\x66\x00' # Font type A for HRI barcode chars
BARCODE_FONT_B = '\x1d\x66\x01' # Font type B for HRI barcode chars
BARCODE_HEIGHT = '\x1d\x68\x64' # Barcode Height [1-255]
BARCODE_WIDTH = '\x1d\x77\x03' # Barcode Width [2-6]
BARCODE_UPC_A = '\x1d\x6b\x00' # Barcode type UPC-A
BARCODE_UPC_E = '\x1d\x6b\x01' # Barcode type UPC-E
BARCODE_EAN13 = '\x1d\x6b\x02' # Barcode type EAN13
BARCODE_EAN8 = '\x1d\x6b\x03' # Barcode type EAN8
BARCODE_CODE39 = '\x1d\x6b\x04' # Barcode type CODE39
BARCODE_ITF = '\x1d\x6b\x05' # Barcode type ITF
BARCODE_NW7 = '\x1d\x6b\x06' # Barcode type NW7
# Image format
S_RASTER_N = '\x1d\x76\x30\x00' # Set raster image normal size
S_RASTER_2W = '\x1d\x76\x30\x01' # Set raster image double width
S_RASTER_2H = '\x1d\x76\x30\x02' # Set raster image double height
S_RASTER_Q = '\x1d\x76\x30\x03' # Set raster image quadruple
| [
[
8,
0,
0.0189,
0.0189,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0755,
0.0189,
0,
0.66,
0.0227,
373,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0943,
0.0189,
0,
0.66... | [
"\"\"\" ESC/POS Commands (Constants) \"\"\"",
"CTL_LF = '\\x0a' # Print and line feed",
"CTL_FF = '\\x0c' # Form feed",
"CTL_CR = '\\x0d' # Carriage return",
"CTL_HT = '\\x09' # Horizontal tab",
"CTL_VT = '\\x0b' # Vertical tab",
... |
__all__ = ["constants","escpos","exceptions","printer"]
| [
[
14,
0,
1,
1,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
]
] | [
"__all__ = [\"constants\",\"escpos\",\"exceptions\",\"printer\"]"
] |
#!/usr/bin/env python
# This file is part of django_ip2country.
# django_ip2country is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# django_ip2country is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with django_ip2country. If not, see <http://www.gnu.org/licenses/>.
# Author: Esteban Feldman esteban.feldman@gmail.com
import urllib
from zipfile import ZipFile
TARGET = 'http://ip-to-country.webhosting.info/downloads/ip-to-country.csv.zip'
OUT_FILE_NAME = 'ip-to-country.zip'
def reporthook(blocknum, bs, size):
elapsed = (blocknum * bs) * 100 / size
if elapsed > 100: elapsed = 100
print '%s%%' % elapsed
def main():
print 'Downloading ip2country database file'
urllib.urlretrieve(TARGET, OUT_FILE_NAME, reporthook=reporthook)
print 'Extracting data file'
zf = ZipFile(OUT_FILE_NAME)
zf.extractall()
if __name__ == '__main__':
main() | [
[
1,
0,
0.4615,
0.0256,
0,
0.66,
0,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.4872,
0.0256,
0,
0.66,
0.1667,
93,
0,
1,
0,
0,
93,
0,
0
],
[
14,
0,
0.5641,
0.0256,
0,
0... | [
"import urllib",
"from zipfile import ZipFile",
"TARGET = 'http://ip-to-country.webhosting.info/downloads/ip-to-country.csv.zip'",
"OUT_FILE_NAME = 'ip-to-country.zip'",
"def reporthook(blocknum, bs, size):\n\telapsed = (blocknum * bs) * 100 / size\n\tif elapsed > 100: elapsed = 100\n\tprint('%s%%' % elapse... |
#!/usr/bin/env python
# This file is part of django_ip2country.
# django_ip2country is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# django_ip2country is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with django_ip2country. If not, see <http://www.gnu.org/licenses/>.
# Author: Esteban Feldman esteban.feldman@gmail.com
import csv
import os
import sys
from optparse import OptionParser
from django.conf import settings
from django_ip2country import models
def main():
if not 'DJANGO_SETTINGS_MODULE' in os.environ:
print 'DJANGO_SETTINGS_MODULE should be set, exiting.'
sys.exit(0)
usage = "usage: %prog -p PATH_TO_DB | --path=PATH_TO_DB"
parser = OptionParser(usage)
parser.add_option('-p', '--path', dest='db_path',
help="The path to the project directory.")
(options, args) = parser.parse_args()
if settings.DATABASE_ENGINE is 'sqlite3':
if not options.db_path:
parser.error("You must specify the project directory path.")
project_dir = os.path.abspath(options.db_path) # or path to the dir. that the db should be in.
settings.DATABASE_NAME = os.path.join( project_dir, settings.DATABASE_NAME )
CSV_FILE = 'ip-to-country.csv'
# delete all objects
print 'This will take a while, so sit back and relax.'
models.Ip2Country.objects.all().delete()
reader = csv.reader(open(CSV_FILE))
count = 0
for ipf, ipt, cc2, cc3, cname in reader:
count += 1
object = models.Ip2Country(count,ipf, ipt, cc2, cc3, cname)
object.save()
if count % 10000 == 0:
print count
print count , "inserted. :)"
del reader
if __name__ == '__main__':
main()
| [
[
1,
0,
0.2857,
0.0159,
0,
0.66,
0,
312,
0,
1,
0,
0,
312,
0,
0
],
[
1,
0,
0.3016,
0.0159,
0,
0.66,
0.1429,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3175,
0.0159,
0,
... | [
"import csv",
"import os",
"import sys",
"from optparse import OptionParser",
"from django.conf import settings",
"from django_ip2country import models",
"def main():\n if not 'DJANGO_SETTINGS_MODULE' in os.environ:\n print('DJANGO_SETTINGS_MODULE should be set, exiting.')\n sys.exit(0)... |
# This file is part of django_ip2country.
# django_ip2country is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# django_ip2country is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with django_ip2country. If not, see <http://www.gnu.org/licenses/>.
# Author: Esteban Feldman esteban.feldman@gmail.com
import bigint_patch
from django.db import models
class Ip2Country(models.Model):
#ip_from = models.PositiveIntegerField()
#ip_to = models.PositiveIntegerField()
ip_from = bigint_patch.BigIntegerField()
ip_to = bigint_patch.BigIntegerField()
country_code2 = models.CharField(max_length = 2)
country_code3 = models.CharField(max_length = 3)
country_name = models.CharField(max_length = 50)
class Meta:
ordering = ['ip_from']
def __unicode__(self):
return "%s %s %s" % (self.ip_from ,self.ip_to, self.country_name)
| [
[
1,
0,
0.4474,
0.0263,
0,
0.66,
0,
521,
0,
1,
0,
0,
521,
0,
0
],
[
1,
0,
0.5,
0.0263,
0,
0.66,
0.5,
40,
0,
1,
0,
0,
40,
0,
0
],
[
3,
0,
0.7632,
0.3947,
0,
0.66,
... | [
"import bigint_patch",
"from django.db import models",
"class Ip2Country(models.Model):\n #ip_from = models.PositiveIntegerField()\n #ip_to = models.PositiveIntegerField()\n ip_from = bigint_patch.BigIntegerField()\n ip_to = bigint_patch.BigIntegerField()\n \n country_code2 = models.CharField(... |
# This file is part of django_ip2country.
# django_ip2country is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# django_ip2country is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with django_ip2country. If not, see <http://www.gnu.org/licenses/>.
# Author: Esteban Feldman esteban.feldman@gmail.com
from django.contrib import admin
from django_ip2country.models import Ip2Country
admin.site.register(Ip2Country) | [
[
1,
0,
0.85,
0.05,
0,
0.66,
0,
302,
0,
1,
0,
0,
302,
0,
0
],
[
1,
0,
0.9,
0.05,
0,
0.66,
0.5,
6,
0,
1,
0,
0,
6,
0,
0
],
[
8,
0,
1,
0.05,
0,
0.66,
1,
276,
... | [
"from django.contrib import admin",
"from django_ip2country.models import Ip2Country",
"admin.site.register(Ip2Country)"
] |
# This file is part of django_ip2country.
# django_ip2country is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# django_ip2country is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with django_ip2country. If not, see <http://www.gnu.org/licenses/>.
# Author: Esteban Feldman esteban.feldman@gmail.com
from django_ip2country.models import Ip2Country
def ip2long(ip):
ip_array = ip.split('.')
ip_long = int(ip_array[0]) * 16777216 + int(ip_array[1]) * 65536 + int(ip_array[2]) * 256 + int(ip_array[3])
return ip_long
def get_country(value):
value = ip2long(value)
try:
# ip of comment has to be in a range of an ip-to-country object IP_FROM and IP_TO
iptc = Ip2Country.objects.get(ip_from__lte=value, ip_to__gte=value)
except Ip2Country.DoesNotExist:
return None
return iptc
| [
[
1,
0,
0.5312,
0.0312,
0,
0.66,
0,
6,
0,
1,
0,
0,
6,
0,
0
],
[
2,
0,
0.6406,
0.125,
0,
0.66,
0.5,
337,
0,
1,
1,
0,
0,
0,
5
],
[
14,
1,
0.625,
0.0312,
1,
0.04,
... | [
"from django_ip2country.models import Ip2Country",
"def ip2long(ip):\n ip_array = ip.split('.')\n ip_long = int(ip_array[0]) * 16777216 + int(ip_array[1]) * 65536 + int(ip_array[2]) * 256 + int(ip_array[3])\n return ip_long",
" ip_array = ip.split('.')",
" ip_long = int(ip_array[0]) * 16777216 ... |
# This file is part of django_ip2country.
# django_ip2country is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# django_ip2country is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with django_ip2country. If not, see <http://www.gnu.org/licenses/>.
# Author: Esteban Feldman esteban.feldman@gmail.com | [] | [] |
# This file is part of django_ip2country.
# django_ip2country is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# django_ip2country is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with django_ip2country. If not, see <http://www.gnu.org/licenses/>.
# Author: Esteban Feldman esteban.feldman@gmail.com
"""module mydjangolib.bigint_patch
A fix for the rather well-known ticket #399 in the django project.
Create and link to auto-incrementing primary keys of type bigint without
having to reload the model instance after saving it to get the ID set in
the instance.
"""
from django.core import exceptions
from django.conf import settings
from django.db import connection
from django.db.models import fields
from django.utils.translation import ugettext as _
__version__ = "1.0"
__author__ = "Florian Leitner"
class BigIntegerField(fields.IntegerField):
def db_type(self):
if settings.DATABASE_ENGINE == 'mysql':
return "bigint"
elif settings.DATABASE_ENGINE == 'oracle':
return "NUMBER(19)"
elif settings.DATABASE_ENGINE[:8] == 'postgres':
return "bigint"
elif settings.DATABASE_ENGINE == 'sqlite3':
return "bigint"
else:
raise NotImplemented
def get_internal_type(self):
return "BigIntegerField"
def to_python(self, value):
if value is None:
return value
try:
return long(value)
except (TypeError, ValueError):
raise exceptions.ValidationError(
_("This value must be a long integer."))
class BigAutoField(fields.AutoField):
def db_type(self):
if settings.DATABASE_ENGINE == 'mysql':
return "bigint AUTO_INCREMENT"
elif settings.DATABASE_ENGINE == 'oracle':
return "NUMBER(19)"
elif settings.DATABASE_ENGINE[:8] == 'postgres':
return "bigserial"
else:
raise NotImplemented
def get_internal_type(self):
return "BigAutoField"
def to_python(self, value):
if value is None:
return value
try:
return long(value)
except (TypeError, ValueError):
raise exceptions.ValidationError(
_("This value must be a long integer."))
class BigForeignKey(fields.related.ForeignKey):
def db_type(self):
rel_field = self.rel.get_related_field()
# next lines are the "bad tooth" in the original code:
if (isinstance(rel_field, BigAutoField) or
(not connection.features.related_fields_match_type and
isinstance(rel_field, BigIntegerField))):
# because it continues here in the django code:
# return IntegerField().db_type()
# thereby fixing any AutoField as IntegerField
return BigIntegerField().db_type()
return rel_field.db_type()
| [
[
8,
0,
0.2158,
0.0842,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2737,
0.0105,
0,
0.66,
0.1,
913,
0,
1,
0,
0,
913,
0,
0
],
[
1,
0,
0.2842,
0.0105,
0,
0.66,
... | [
"\"\"\"module mydjangolib.bigint_patch\n\nA fix for the rather well-known ticket #399 in the django project.\n\nCreate and link to auto-incrementing primary keys of type bigint without\nhaving to reload the model instance after saving it to get the ID set in\nthe instance.\n\"\"\"",
"from django.core import excep... |
#!/usr/bin/env python
import sys
import os
import datetime
import shutil
import dateutil.tz
if len(sys.argv) != 8:
sys.exit();
srm = str('SRM') + sys.argv[1]
num1 = sys.argv[2]
num2 = sys.argv[3]
num3 = sys.argv[4]
num4 = sys.argv[5]
num5 = sys.argv[6]
num6 = sys.argv[7]
os.mkdir(srm, 0777);
os.chdir(os.getcwd() + str('/') + srm);
tz = datetime.datetime.now(dateutil.tz.tzlocal())
now = tz.strftime("%A, %B %d, %Y %H:%M %Z")
for i in [num1, num2, num3]:
string = srm + str('_DIV1_') + str(i) + str('.java');
dst = open(string, 'w');
dst.write("//" + now + "\n" );
dst.close();
for i in [num4, num5, num6]:
string = srm + str('_DIV2_') + str(i) + str('.java');
dst = open(string, 'w');
dst.write("//" + now + "\n" );
dst.close();
| [
[
1,
0,
0.0833,
0.0278,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.1111,
0.0278,
0,
0.66,
0.0588,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.1389,
0.0278,
0,
... | [
"import sys",
"import os",
"import datetime",
"import shutil",
"import dateutil.tz",
"if len(sys.argv) != 8:\n\tsys.exit();",
"\tsys.exit();",
"srm = str('SRM') + sys.argv[1]",
"num1 = sys.argv[2]",
"num2 = sys.argv[3]",
"num3 = sys.argv[4]",
"num4 = sys.argv[5]",
"num5 = sys.argv[6]",
"nu... |
#!/usr/bin/env python
import sys, os
if os.path.exists('output.txt'):
os.remove('output.txt')
top = './'
fd = open('output.txt', 'w+')
for root, dirs, files in os.walk(top, topdown=False):
for name in dirs:
if name[:-4] == 'Volumn':
fd.write(name + ' has : ')
count = 0
for root, dirs, files in os.walk(name):
for f in files:
count = count + 1
fd.write(str(count) + '\n')
fd.close()
| [
[
1,
0,
0.15,
0.05,
0,
0.66,
0,
509,
0,
2,
0,
0,
509,
0,
0
],
[
4,
0,
0.275,
0.1,
0,
0.66,
0.2,
0,
3,
0,
0,
0,
0,
0,
2
],
[
8,
1,
0.3,
0.05,
1,
0.82,
0,
185... | [
"import sys, os",
"if os.path.exists('output.txt'):\n\t\tos.remove('output.txt')",
"\t\tos.remove('output.txt')",
"top = './'",
"fd = open('output.txt', 'w+')",
"for root, dirs, files in os.walk(top, topdown=False):\n\tfor name in dirs:\n\t\t\tif name[:-4] == 'Volumn':\n\t\t\t\tfd.write(name + ' has : ')\... |
cnt = int(raw_input())
rectlst=[]
for i in xrange(cnt):
tmplst = []
for k in xrange(3):
input = raw_input()
tmplst.append([int(j) for j in input.split()])
rectlst.append(tmplst)
for i in xrange(cnt):
coor=rectlst[i]
result=[]
center=reduce(lambda a,b:[a[0]+b[0], a[1]+b[1]], coor)
center=[center[0]/3.0,center[1]/3.0]
biggerx = [x for x in coor if center[0] < x[0]]
biggery = [x for x in coor if center[1] < x[1]]
smallerx = [x for x in coor if center[0] > x[0]]
smallery = [x for x in coor if center[1] > x[1]]
xx = biggerx if len(biggerx) < len(smallerx) else smallerx
yy = biggery if len(biggery) < len(smallery) else smallery
print xx[0][0], yy[0][1]
| [
[
14,
0,
0.05,
0.05,
0,
0.66,
0,
307,
3,
1,
0,
0,
901,
10,
2
],
[
14,
0,
0.1,
0.05,
0,
0.66,
0.3333,
375,
0,
0,
0,
0,
0,
5,
0
],
[
6,
0,
0.275,
0.3,
0,
0.66,
0.... | [
"cnt = int(raw_input())",
"rectlst=[]",
"for i in xrange(cnt):\n\ttmplst = []\n\tfor k in xrange(3):\n\t\tinput = raw_input()\n\t\ttmplst.append([int(j) for j in input.split()])\n\trectlst.append(tmplst)",
"\ttmplst = []",
"\tfor k in xrange(3):\n\t\tinput = raw_input()\n\t\ttmplst.append([int(j) for j in i... |
from Queue import Queue
count = int(raw_input())
class Stack(Queue):
def _get(self):
item = self.queue[-1]
del self.queue[-1]
return item
a = Stack();
b = Stack();
c = Stack();
k=[a,b,c]
def move(src,dest):
k[dest-1].put(k[src-1].get())
if(count<=20):
print src,dest
def other(h1,h2):
temp=[1,2,3]
temp.remove(h1)
temp.remove(h2)
return temp[0]
def hanoi(src,dest,length): #5 4 3 2 1
if length==1:
move(src,dest)
return
hanoi(src,other(src,dest),length-1)
hanoi(src,dest,1)
hanoi(other(src,dest),dest,length-1)
for i in range(count):
a.put(count-i)
print pow(2,count)-1
hanoi(1,3,a.qsize())
#for i in range(c.qsize()):
# print c.get()
| [
[
1,
0,
0.027,
0.027,
0,
0.66,
0,
952,
0,
1,
0,
0,
952,
0,
0
],
[
14,
0,
0.0811,
0.027,
0,
0.66,
0.0833,
778,
3,
1,
0,
0,
901,
10,
2
],
[
3,
0,
0.1622,
0.1351,
0,
0... | [
"from Queue import Queue",
"count = int(raw_input())",
"class Stack(Queue):\n def _get(self):\n item = self.queue[-1]\n del self.queue[-1]\n return item",
" def _get(self):\n item = self.queue[-1]\n del self.queue[-1]\n return item",
" item = self.queue... |
__author__ = 'changwoncheo'
a0=(0,'zero')
a1=(1,'one')
a2=(2,'two')
a3=(3,'three')
a4=(4,'four')
a5=(5,'five')
a6=(6,'six')
a7=(7,'seven')
a8=(8,'eight')
a9=(9,'nine')
alist = [a0,a1,a2,a3,a4,a5,a6,a7,a8,a9]
biglist =[];
def compareNum(string):
for i in alist:
temp = ''
com = i[1]
l = list(com)
for k in range(len(l)):
if l[k] in string:
pass
else:
break
if k == len(l)-1:
return i[0]
exlist=['+','-','*']
exexex = ''
def result(exp):
index = -1;
for i in exlist:
index = exp.find(i)
if(index != -1):
exexex = i
break
startrange = [0,index-1]
index = -1;
for i in ['=']:
index = exp.find(i)
if(index != -1):
break
endrange = [startrange[1]+3,index-1]
answerrange = [index+2,-1]
a= compareNum(exp[startrange[0]:startrange[1]])
b= compareNum(exp[endrange[0]:endrange[1]])
c= compareNum(exp[answerrange[0]:])
if exexex=='+':
if (a+b) ==c:
print 'Yes'
else:
print 'No'
if exexex=='-':
if (a-b) ==c:
print 'Yes'
else:
print 'No'
if exexex=='*':
if (a*b) ==c:
print 'Yes'
else:
print 'No'
cnt = raw_input()
for aa in range(int(cnt)):
exp = raw_input()
result(exp)
| [
[
14,
0,
0.0132,
0.0132,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0263,
0.0132,
0,
0.66,
0.0556,
599,
0,
0,
0,
0,
0,
8,
0
],
[
14,
0,
0.0395,
0.0132,
0,
0... | [
"__author__ = 'changwoncheo'",
"a0=(0,'zero')",
"a1=(1,'one')",
"a2=(2,'two')",
"a3=(3,'three')",
"a4=(4,'four')",
"a5=(5,'five')",
"a6=(6,'six')",
"a7=(7,'seven')",
"a8=(8,'eight')",
"a9=(9,'nine')",
"alist = [a0,a1,a2,a3,a4,a5,a6,a7,a8,a9]",
"biglist =[];",
"def compareNum(string):\n ... |
def sort(_list):
for i in range(len(_list)):
target = _list[i]
for k in range(len(_list)):
if( (k+1) != len(_list)):
if (_list[k] > _list[k+1]):
swap(_list,k,k+1)
else :
k+=1
def printMax(_list):
temp = 0
for i in _list:
if i>temp:
temp = i
print '%.1f'%(temp)
def swap(_list,sindex,dindex):
temp = _list[sindex]
_list[sindex] = _list[dindex]
_list[dindex] = temp
count = int(raw_input())
case_list = []
for i in range(count):
case_count = int(raw_input())
case_item = raw_input()
case_item = (int(item) for item in case_item.split(' '))
case_item = list(case_item)
case_list.append((case_count, case_item))
result = []
for i in range(count):
sort(case_list[i][1])
_list = []
for k in range(len(case_list[i][1])/2):
avg = (case_list[i][1][k] + case_list[i][1][len(case_list[i][1])-k-1]) /2.0
_list.append(avg)
if(len(case_list[i][1]))%2 == 1:
_list.append(case_list[i][1][len(case_list[i][1])/2])
sort(_list)
result.append(_list)
for i in result:
printMax(i)
| [
[
2,
0,
0.1064,
0.1915,
0,
0.66,
0,
489,
0,
1,
0,
0,
0,
0,
6
],
[
6,
1,
0.117,
0.1702,
1,
0.09,
0,
826,
3,
0,
0,
0,
0,
0,
6
],
[
14,
2,
0.0638,
0.0213,
2,
0.06,
... | [
"def sort(_list):\n\tfor i in range(len(_list)):\n\t\ttarget = _list[i]\n\t\tfor k in range(len(_list)):\n\t\t\tif( (k+1) != len(_list)):\n\t\t\t\tif (_list[k] > _list[k+1]):\n\t\t\t\t\tswap(_list,k,k+1)\n\t\t\t\telse :",
"\tfor i in range(len(_list)):\n\t\ttarget = _list[i]\n\t\tfor k in range(len(_list)):\n\t\t... |
from django.db import models
from django.contrib.auth.models import User
class ProgrammingLanguage(models.Model):
name = models.CharField(max_length=10)
def __unicode__(self):
return u'%s' % self.name
class Classification(models.Model):
name = models.CharField(max_length=35)
uri = models.URLField()
def get_show_url(self):
return "http://localhost:8000/show/cat/id/%i" % self.id
def __unicode__(self):
return u'%s' % self.name
class Algorithm(models.Model):
name = models.CharField(max_length=30)
description = models.TextField()
classification = models.ForeignKey(Classification, null=True, blank=True)
uri = models.URLField()
visible = models.BooleanField()
reputation = models.FloatField()
def get_show_url(self):
return "http://localhost:8000/show/alg/id/%i" % self.id
def __unicode__(self):
return u'%s' % self.name.lower().title()
class Implementation(models.Model):
# an algorithm can have many implementations
algorithm = models.ForeignKey(Algorithm)
code = models.TextField()
programming_language = models.ForeignKey(ProgrammingLanguage)
visible = models.BooleanField()
reputation = models.FloatField()
def __unicode__(self):
return u'%s' % self.code
def get_show_url(self):
return "http://localhost:8000/show/imp/id/%i" % self.id
###################
# Relacionamento de interesse entre usuario e uma classificacao
class Interest(models.Model):
classification = models.ForeignKey(Classification)
user = models.ForeignKey(User)
#Classe base de proeficiencia do usuario em algo
class ProeficiencyScale(models.Model):
user = models.ForeignKey(User)
value = models.IntegerField()
class ProgrammingLanguageProeficiencyScale(ProeficiencyScale):
programming_language = models.ForeignKey(ProgrammingLanguage)
class ClassificationProeficiencyScale(ProeficiencyScale):
classification = models.ForeignKey(Classification)
# Questao de escala em relacao a algo
class Question(models.Model):
text = models.TextField()
priority = models.IntegerField()
# Respostas validas para as perguntas
class QuestionAnswer(models.Model):
question = models.ForeignKey(Question)
value = models.IntegerField()
text = models.TextField()
# Pergunta em relacao ao usuario
class UserQuestion(Question):
pass
class UserQuestionAnswer(models.Model):
user = models.ForeignKey(User)
user_question = models.ForeignKey(UserQuestion)
question_answer = models.ForeignKey(QuestionAnswer)
# Pergunta em relacao a uma implementacao
class ImplementationQuestion(Question):
pass
# Resposta de um usuario a uma determinada pergunta sobre uma determinada implementacao
class ImplementationQuestionAnswer(models.Model):
user = models.ForeignKey(User)
implementation = models.ForeignKey(Implementation)
implementation_question = models.ForeignKey(ImplementationQuestion)
question_answer = models.ForeignKey(QuestionAnswer)
| [
[
1,
0,
0.0105,
0.0105,
0,
0.66,
0,
40,
0,
1,
0,
0,
40,
0,
0
],
[
1,
0,
0.0211,
0.0105,
0,
0.66,
0.0667,
808,
0,
1,
0,
0,
808,
0,
0
],
[
3,
0,
0.0632,
0.0526,
0,
0.... | [
"from django.db import models",
"from django.contrib.auth.models import User",
"class ProgrammingLanguage(models.Model):\n\tname = models.CharField(max_length=10)\n\t\n\tdef __unicode__(self):\n\t\treturn u'%s' % self.name",
"\tname = models.CharField(max_length=10)",
"\tdef __unicode__(self):\n\t\treturn u... |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| [
[
8,
0,
0.2188,
0.375,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0625,
0,
0.66,
0.5,
944,
0,
1,
0,
0,
944,
0,
0
],
[
3,
0,
0.8438,
0.375,
0,
0.66,
1,... | [
"\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"",
"from django.test import TestCase",
"class SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\... |
from algorithm.models import Algorithm
from django import forms
from django.forms import Textarea
class AlgorithmForm(forms.ModelForm):
class Meta:
model = Algorithm
fields = ('name','description','classification')
widgets = {
'description': Textarea(attrs={'cols': 240, 'rows': 10}),
}
def save(self, commit=True):
algorithm = super(AlgorithmForm, self).save(commit=False)
if commit:
algorithm.save()
return algorithm | [
[
1,
0,
0.0588,
0.0588,
0,
0.66,
0,
363,
0,
1,
0,
0,
363,
0,
0
],
[
1,
0,
0.1176,
0.0588,
0,
0.66,
0.3333,
294,
0,
1,
0,
0,
294,
0,
0
],
[
1,
0,
0.1765,
0.0588,
0,
... | [
"from algorithm.models import Algorithm",
"from django import forms",
"from django.forms import Textarea",
"class AlgorithmForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Algorithm\n\t\tfields = ('name','description','classification')\n\t\twidgets = {\n 'description': Textarea(attrs={'cols': 240... |
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
sender = forms.EmailField()
#cc_myself = forms.BooleanField(required=False) | [
[
1,
0,
0.1429,
0.1429,
0,
0.66,
0,
294,
0,
1,
0,
0,
294,
0,
0
],
[
3,
0,
0.6429,
0.5714,
0,
0.66,
1,
340,
0,
0,
0,
0,
953,
0,
3
],
[
14,
1,
0.5714,
0.1429,
1,
0.29... | [
"from django import forms",
"class ContactForm(forms.Form):\n subject = forms.CharField(max_length=100)\n message = forms.CharField(widget=forms.Textarea)\n sender = forms.EmailField()",
" subject = forms.CharField(max_length=100)",
" message = forms.CharField(widget=forms.Textarea)",
" se... |
import os
from algorithm.models import Classification, Implementation, Algorithm, ProgrammingLanguage, Interest, ProeficiencyScale, ProgrammingLanguageProeficiencyScale, ClassificationProeficiencyScale, Question,QuestionAnswer,UserQuestion,ImplementationQuestion,ImplementationQuestionAnswer,UserQuestionAnswer
from extractor.FileWriters import RDFWriter
from django.contrib.auth.models import User
from django.db import connection
def is_database_empty():
empty = 0
empty += Classification.objects.count()
empty += Implementation.objects.count()
empty += Algorithm.objects.count()
empty += ProgrammingLanguage.objects.count()
return False if empty > 0 else True
def wipe_database():
Algorithm.objects.all().delete()
Classification.objects.all().delete()
Implementation.objects.all().delete()
ProgrammingLanguage.objects.all().delete()
#returns user interested classifications
def get_user_interested_classifications(username=None):
if username == None:
return []
names = []
links = []
user = User.objects.get(username=username)
user_interests = Interest.objects.filter(user=user).only("classification").order_by("classification__name")
for interest in user_interests:
names.append(interest.classification.name)
links.append("http://localhost:8000/show/cat/id/" + str(interest.classification.id))
#collection[classification.name] = "http://localhost:8000/show/cat/id/" + str(classification.id)
classif = [{'name' : t[0], 'link' : t[1]} for t in zip(names, links)]
return classif
#returns a tuple (names, links) of classifications
def get_all_classifications_name_link():
#collection = dict()
names = []
links = []
ids = []
classifications = Classification.objects.order_by("name")
for classification in classifications:
names.append(classification.name)
links.append("http://localhost:8000/show/cat/id/" + str(classification.id))
ids.append(classification.id)
#collection[classification.name] = "http://localhost:8000/show/cat/id/" + str(classification.id)
classif = [{'name' : t[0], 'link' : t[1], 'id': t[2]} for t in zip(names, links, ids)]
return classif
def get_all_classifications_ordered_name_link(username=None):
all_classifications = get_all_classifications_name_link()
user_interested_classifications = get_user_interested_classifications(username)
#ordered_classifications = list(user_interested_classifications)
ordered_classifications = []
for classification in all_classifications:
if classification not in ordered_classifications:
ordered_classifications.append(classification)
return ordered_classifications
# returns a classification object
def get_classification_by_id(c_id):
try:
classification = Classification.objects.get(id=c_id)
return classification
except Classification.DoesNotExist:
return []
# returns a user question answer by question
def get_questionaswer_by_question_id(question_id):
try:
questionaswer = QuestionAnswer.objects.filter(question__id=question_id)
return questionaswer
except QuestionAnswer.DoesNotExist:
return []
def get_userquestionanswer_by_question_id_and_user(username, question_id):
try:
user_question_answer = UserQuestionAnswer.objects.get(user__username=username, user_question__id=question_id)
return user_question_answer.question_answer
except:
return []
def get_algorithms_by_classification(a_classification):
try:
algs = Algorithm.objects.filter(classification=a_classification).order_by("-reputation")
return algs
except Algorithm.DoesNotExist:
return []
def insert_classification_db(c_name, c_uri):
try:
classif = Classification.objects.get(name=c_name)
return classif
except Classification.DoesNotExist:
aux = Classification(name=c_name, uri=c_uri)
aux.save()
return aux
def delete_algorithm_db(alg):
try:
Algorithm.objects.filter(id=alg.id).delete()
except Algorithm.DoesNotExist:
return None
return True
def insert_algorithm(alg_name, alg_about,alg_classification, alg_visible):
algorithm = Algorithm(name=alg_name, description=alg_about, classification=alg_classification, visible=alg_visible)
algorithm.save()
return algorithm
def insert_algorithm_db(a_name, a_about, a_classif, a_uri, a_visible):
alg, created = Algorithm.objects.get_or_create(name=a_name, description=a_about, classification=a_classif, uri=a_uri, visible=a_visible)
return alg
def insert_programming_langage_db(i_language):
p_lang, created = ProgrammingLanguage.objects.get_or_create(name=i_language.upper())
return p_lang
def insert_implementation_db(i_alg, i_language_id, i_code, i_visible):
p_lang = insert_programming_langage_db(i_language_id)
implementation = Implementation(algorithm=i_alg, code=i_code, programming_language=p_lang, visible=i_visible)
implementation.save()
return implementation
def get_all_algorithms():
return Algorithm.objects.order_by("name")
def get_all_userquestions():
return UserQuestion.objects.order_by("text")
def insert_user_question_answer(username, question_id, question_answer_id):
user = User.objects.get(username=username)
try:
question = UserQuestion.objects.get(id=question_id)
existing_question_answer = UserQuestionAnswer.objects.get(user=user, user_question=question)
if question_answer_id and existing_question_answer.question_answer.id != question_answer_id:
question_answer = QuestionAnswer.objects.get(id=question_answer_id)
existing_question_answer.question_answer = question_answer
existing_question_answer.save()
except UserQuestionAnswer.DoesNotExist:
question_answer = QuestionAnswer.objects.get(id=question_answer_id)
UserQuestionAnswer.objects.create(user=user, user_question=question, question_answer=question_answer)
def delete_user_question_answer(username, question_id):
try:
existing_question_answer = UserQuestionAnswer.objects.get(user__username=username, user_question__id=question_id)
existing_question_answer.delete()
except UserQuestionAnswer.DoesNotExist:
pass
def exec_sp_update_user_evaluation_contribution(implementation_id, user_id):
cursor = connection.cursor()
cursor.callproc('calculate_user_evaluation_contribution', (implementation_id, user_id))
cursor.close()
def insert_user_impl_question_answer(username, impl_id, question_id, question_answer_id):
user = User.objects.get(username=username)
try:
question = ImplementationQuestion.objects.get(id=question_id)
existing_question_answer = ImplementationQuestionAnswer.objects.get(user=user, implementation__id=impl_id, implementation_question=question)
if question_answer_id and existing_question_answer.question_answer.id != question_answer_id:
question_answer = QuestionAnswer.objects.get(id=question_answer_id)
existing_question_answer.question_answer = question_answer
existing_question_answer.save()
except ImplementationQuestionAnswer.DoesNotExist:
implementation = Implementation.objects.get(id=impl_id)
question_answer = QuestionAnswer.objects.get(id=question_answer_id)
ImplementationQuestionAnswer.objects.create(user=user, implementation=implementation, implementation_question=question, question_answer=question_answer)
exec_sp_update_user_evaluation_contribution(impl_id, user.id)
def get_user_votes_by_algorithm(username, algorithm_id):
user = User.objects.get(username=username)
algorithm = Algorithm.objects.get(id=algorithm_id)
try:
#impl_questions = ImplementationQuestion.objects.get()
implementations = Implementation.objects.filter(algorithm=algorithm)
impl_question_answers = []
for impl in implementations:
answer = ImplementationQuestionAnswer.objects.filter(user=user, implementation=impl)
if answer:
impl_question_answers.append({"iq" : int(impl.id), "iqa" : ImplementationQuestionAnswer.objects.filter(user=user, implementation=impl)})
if len(impl_question_answers) == 0:
return []
return impl_question_answers
except ImplementationQuestionAnswer.DoesNotExist:
return []
def get_user_programming_languages_proeficiencies_ids(username):
try:
pls = []
for pl in ProgrammingLanguageProeficiencyScale.objects.filter(user__username=username).only("programming_language"):
pls.append(pl.programming_language.id)
return pls
except ProgrammingLanguageProeficiencyScale.DoesNotExist:
return []
def get_user_classifications_interests_ids(username):
try:
classifications = []
for i in Interest.objects.filter(user__username=username).only("classification"):
classifications.append(i.classification.id)
return classifications
except Interest.DoesNotExist:
return []
def get_user_classifications_proeficiencies_ids(username):
try:
classifications = []
for cps in ClassificationProeficiencyScale.objects.filter(user__username=username).only("classification"):
classifications.append(cps.classification.id)
return classifications
except ClassificationProeficiencyScale.DoesNotExist:
return []
def update_programming_languages_proeficiencies(username, programming_languages_ids):
user_proeficiencies = set(get_user_programming_languages_proeficiencies_ids(username))
programming_languages_ids = set(programming_languages_ids)
#Vou remover todas as existentes menos as que ele selecionou
to_remove = user_proeficiencies - programming_languages_ids
to_insert = programming_languages_ids - user_proeficiencies
ProgrammingLanguageProeficiencyScale.objects.filter(user__username=username, programming_language__id__in=to_remove).delete()
#print "programming_language!"
#print "to remove: ", to_remove
#print "to_insert: ", to_insert
if to_insert:
insert_programming_languages_proeficiencies(username, to_insert)
def insert_programming_languages_proeficiencies(username, programming_languages_ids):
user = User.objects.get(username=username)
for programming_language_id in programming_languages_ids:
programming_language = ProgrammingLanguage.objects.get(id=programming_language_id)
ProgrammingLanguageProeficiencyScale.objects.get_or_create(user=user, programming_language=programming_language, value=1)
def update_classifications_proeficiencies(username, classifications_ids):
user_proeficiencies = set(get_user_classifications_proeficiencies_ids(username))
classifications_ids = set(classifications_ids)
#Vou remover todas as existentes menos as que ele selecionou
to_remove = user_proeficiencies - classifications_ids
to_insert = classifications_ids - user_proeficiencies
#print "proeficiencies!"
#print "to remove: ", to_remove
#print "to_insert: ", to_insert
ClassificationProeficiencyScale.objects.filter(user__username=username, classification__id__in=to_remove).delete()
if to_insert:
insert_classifications_proeficiencies(username, to_insert)
def insert_classifications_proeficiencies(username, classifications_ids):
user = User.objects.get(username=username)
for classification_id in classifications_ids:
classification = Classification.objects.get(id=classification_id)
ClassificationProeficiencyScale.objects.get_or_create(user=user, classification=classification, value=1)
def update_classifications_interests(username, classifications_ids):
user_interests = set(get_user_classifications_interests_ids(username))
classifications_ids = set(classifications_ids)
to_remove = user_interests - classifications_ids
to_insert = classifications_ids - user_interests
#print "interests!"
#print "to remove: ", to_remove
#print "to_insert: ", to_insert
Interest.objects.filter(user__username=username, classification__id__in=to_remove).delete()
if to_insert:
insert_classifications_interests(username, to_insert)
def insert_classifications_interests(username, classifications_ids):
user = User.objects.get(username=username)
for classification_id in classifications_ids:
classification = Classification.objects.get(id=classification_id)
Interest.objects.get_or_create(user=user, classification=classification)
def get_all_implementationquestions():
return ImplementationQuestion.objects.order_by("text")
def get_algorithm_by_id(a_id):
try:
alg = Algorithm.objects.get(id=a_id)
return alg
except Algorithm.DoesNotExist:
return None
def get_all_programming_languages():
return ProgrammingLanguage.objects.order_by("name")
def insert_implementation_alg_p_lang(i_alg, i_p_lang, i_code, i_visible):
imp = Implementation(algorithm=i_alg, programming_language=i_p_lang, code=i_code, visible=i_visible )
imp.save()
return imp
def get_programming_language_by_id(p_lang_id):
try:
p_lang = ProgrammingLanguage.objects.get(id=p_lang_id)
return p_lang
except ProgrammingLanguage.DoesNotExist:
return None
def get_implementations_by_alg_id(a_id):
try:
implementations = Implementation.objects.filter(algorithm__id=a_id).order_by("-reputation")
return implementations
except Algorithm.DoesNotExist:
return []
def get_top5_algorithms():
try:
algorithms = Algorithm.objects.filter(reputation__isnull=False).order_by("-reputation")[0:5]
#algorithms = Algorithm.objects.order_by("-reputation")[0:5]
algs = [ (alg.get_show_url(), alg.name) for alg in algorithms]
algorithms = [{'link' : a[0], 'name' : a[1]} for a in algs]
return algorithms
except Algorithm.DoesNotExist:
return []
def get_top5_algorithms_by_classification(a_classification):
try:
algorithms = Algorithm.objects.filter(classification=a_classification, reputation__isnull=False).order_by("-reputation")[0:5]
#algorithms = Algorithm.objects.filter(classification=a_classification).order_by("-reputation")[0:5]
algs = [ (alg.get_show_url(), alg.name) for alg in algorithms]
algorithms = [{'link' : a[0], 'name' : a[1]} for a in algs]
return algorithms
except Algorithm.DoesNotExist:
return []
# Returns a dict with the difference between the two dicts
def dict_diff(list1, list2):
rest = []
for d in list1:
has_element = False
for dd in list2:
if dd['name'] == d['name']:
has_element = True
break
if not has_element:
rest.append(d)
return rest
def try_create_algorithm_rdf(a_id):
base_path = os.path.dirname(__file__)
file_name = os.path.join(base_path, 'static/rdf/').replace('\\', '/')
file_name = file_name+'rdf_alg_%i.xml' %a_id
if not os.path.exists(file_name):
algorithm = get_algorithm_by_id(a_id)
rdf_writer = RDFWriter(algorithm, file_name)
rdf_name = rdf_writer.create_rdf_file()
return rdf_name
else:
file_parts = file_name.split('/')
file_name = '/'.join(file_parts[-2:])
return file_name
def make_classification_link(c_id):
#base_link = get_classification_display_url()
#return base_link.replace("#", c_id)
return ''
def make_algorithm_link(a_id):
#base_link = get_algorithm_display_url()
#return base_link.replace("#", c_id)
return ''
def get_classification_display_url():
return "http://localhost:8000/show/cat/id/#"
def get_algorithm_display_url():
return "http://localhost:8000/show/alg/id/#" | [
[
1,
0,
0.0023,
0.0023,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0047,
0.0023,
0,
0.66,
0.0204,
363,
0,
14,
0,
0,
363,
0,
0
],
[
1,
0,
0.007,
0.0023,
0,
... | [
"import os",
"from algorithm.models import Classification, Implementation, Algorithm, ProgrammingLanguage, Interest, ProeficiencyScale, ProgrammingLanguageProeficiencyScale, ClassificationProeficiencyScale, Question,QuestionAnswer,UserQuestion,ImplementationQuestion,ImplementationQuestionAnswer,UserQuestionAnswer... |
from django.contrib import admin
from algorithm.models import ProgrammingLanguage, Classification, Algorithm, Implementation, Interest, ProeficiencyScale, ProgrammingLanguageProeficiencyScale, ClassificationProeficiencyScale, Question,QuestionAnswer,UserQuestion,ImplementationQuestion,ImplementationQuestionAnswer,UserQuestionAnswer
class ClassificationAdmin(admin.ModelAdmin):
list_display = ('name', 'uri')
search_fields = ('name',)
class AlgorithmAdmin(admin.ModelAdmin):
list_display = ('name', 'description', 'classification')
search_fields = ('name', 'classification__name')
class ImplementationAdmin(admin.ModelAdmin):
list_display = ('algorithm', 'programming_language')
search_fields = ('algorithm', 'programming_language')
###################ALGPEDIA_PERFIL###################
###################REGISTER###################
admin.site.register(ProgrammingLanguage)
admin.site.register(UserQuestionAnswer)
admin.site.register(Classification, ClassificationAdmin)
admin.site.register(Algorithm, AlgorithmAdmin)
admin.site.register(Implementation, ImplementationAdmin)
admin.site.register(Interest)
admin.site.register(ProeficiencyScale)
admin.site.register(ProgrammingLanguageProeficiencyScale)
admin.site.register(ClassificationProeficiencyScale)
admin.site.register(Question)
admin.site.register(QuestionAnswer)
admin.site.register(UserQuestion)
admin.site.register(ImplementationQuestion)
admin.site.register(ImplementationQuestionAnswer)
| [
[
1,
0,
0.0303,
0.0303,
0,
0.66,
0,
302,
0,
1,
0,
0,
302,
0,
0
],
[
1,
0,
0.0606,
0.0303,
0,
0.66,
0.0556,
363,
0,
14,
0,
0,
363,
0,
0
],
[
3,
0,
0.1515,
0.0909,
0,
... | [
"from django.contrib import admin",
"from algorithm.models import ProgrammingLanguage, Classification, Algorithm, Implementation, Interest, ProeficiencyScale, ProgrammingLanguageProeficiencyScale, ClassificationProeficiencyScale, Question,QuestionAnswer,UserQuestion,ImplementationQuestion,ImplementationQuestionAn... |
# Create your views here.
from django.contrib import auth
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseRedirect
from django.template import Context
from django.template.loader import get_template
from algorithm.models import Classification, Implementation,Algorithm, ProgrammingLanguage
from algorithm.controllers import *
#get_all_classifications_name_link, wipe_database, is_database_empty, get_classification_by_id
from extractor.Bootstrapping import Bootstrapper
from django.template import RequestContext
from algorithm.UserCreateForm import UserCreateForm
from algorithm.ContactForm import ContactForm
from algorithm.algorithmForm import AlgorithmForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
from django.shortcuts import render_to_response, render
from django.core.mail import send_mail
import json
def show_main_page(request):
return HttpResponse(get_template('default_debug.html').render(Context({'logged': request.user.is_authenticated(),'message' : 'Welcome to AlgPedia - the free encyclopedia that anyone can edit.', 'top5_algorithms' : get_top5_algorithms()})))
def sync_database(request):
sync_message = ''
# do this check for all the
if(is_database_empty()):
boot_strapper = Bootstrapper()
boot_strapper.doDatabaseImporting()
sync_message = 'Synched!'
else:
sync_message = 'Nothing to synch here!'
t = get_template('default_debug.html')
ctx = Context({'message' : sync_message})
html = t.render(ctx)
return HttpResponse(html)
def clear_database(request):
wipe_database()
t = get_template('default_debug.html')
ctx = Context({'message' : 'Database Clean!'})
html = t.render(ctx)
return HttpResponse(html)
def signin(request):
if request.method == 'POST':
form = UserCreateForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponse(get_template('default_debug.html').render(Context({'logged': request.user.is_authenticated()})))
else:
c = {'logged': request.user.is_authenticated(), 'form' : form}
c.update(csrf(request))
return render_to_response("accounts/signin.html", c)
else:
c = {'logged': request.user.is_authenticated(), 'form' : UserCreateForm()}
c.update(csrf(request))
return render_to_response("accounts/signin.html", c)
def logout(request):
auth.logout(request)
return HttpResponse(get_template('default_debug.html').render(Context({'logged': request.user.is_authenticated(),'logout': True})))
def about(request):
return HttpResponse(get_template('about.html').render(Context({'logged': request.user.is_authenticated()})))
def contact(request):
if request.method == 'POST':
print("Aqui")
recipients = ['thaisnviana@gmail.com']
print(request.POST['subject'])
print(request.POST['message'])
print(request.POST['sender'])
print(recipients)
try:
send_mail(request.POST['subject'], request.POST['message'], request.POST['sender'], recipients, fail_silently=False)
except BadHeaderError:
return HttpResponse(get_template('about.html').render(Context({'logged': request.user.is_authenticated()})))
return HttpResponse(get_template('default_debug.html').render(Context({'logged': request.user.is_authenticated()})))
else:
c = {'logged': request.user.is_authenticated(), 'form' : ContactForm()}
c.update(csrf(request))
return render_to_response("contact.html", c)
@login_required
def profile(request):
user_questions = get_all_userquestions()
question_answers = []
username = request.user.username
classifications = get_all_classifications_name_link()
programming_languages = get_all_programming_languages()
# Recupero as perguntas com as respostas possiveis e as respostas que o usuario ja respondeu
for user_question in user_questions :
question_answers.append({"q": user_question, "qa" : get_questionaswer_by_question_id(user_question.id), "u_qa": get_userquestionanswer_by_question_id_and_user(username, user_question.id)})
if request.method == "POST":
# Insere as respostas para as perguntas
for q in user_questions:
q_data = request.POST["profile_" + str(q.id)]
if q_data:
if q_data.isdigit():
int_q_answer_id = int(q_data)
insert_user_question_answer(username, q.id, int_q_answer_id)
else:
delete_user_question_answer(username, q.id)
data = request.POST.getlist("classifications_interest")
ids = []
for classification_id in data:
if classification_id.isdigit():
int_c = int(classification_id)
ids.append(int_c)
# Insere as classificacoes de interesse
update_classifications_interests(username, ids)
#insert_classifications_interests(username, ids)
data = request.POST.getlist("classifications_knowledge")
ids = []
for classification_id in data:
if classification_id.isdigit():
int_c = int(classification_id)
ids.append(int_c)
update_classifications_proeficiencies(username, ids)
#insert_classifications_proeficiencies(username, ids)
data = request.POST.getlist("programming_languages")
ids = []
for programming_language_id in data:
if programming_language_id.isdigit():
int_c = int(programming_language_id)
ids.append(int_c)
# Insere as linguagens de programcao que o usuario e proeficiente
update_programming_languages_proeficiencies(username, ids)
#insert_programming_languages_proeficiencies(username, ids)
if "ajax-request" in request.POST:
return HttpResponse()
# Recupero todas as classificacoes e linguagens de programacao que o usuario e proeficiente
u_c_p = get_user_classifications_proeficiencies_ids(username)
u_p_l_p = get_user_programming_languages_proeficiencies_ids(username)
# Recupero todas as classificacoes que o usuario tem interesse
u_c_i = get_user_classifications_interests_ids(username)
c = Context({
'logged': request.user.is_authenticated(),
'name' : request.user.username,
'question_answers' : question_answers,
'classifications' : classifications,
'user_classifications_interests': u_c_i,
'user_classification_proeficiencies' : u_c_p,
'user_programming_languages_proeficiencies' : u_p_l_p,
'programming_languages' : programming_languages,
'questions': get_all_userquestions()})
c.update(csrf(request))
return HttpResponse(get_template('accounts/profile.html').render(c))
def rules(request):
return HttpResponse(get_template('rules.html').render(Context({'logged': request.user.is_authenticated()})))
def show_all_classifications(request):
username = str(request.user) if request.user.is_authenticated() else None
ordered_classifications = get_all_classifications_ordered_name_link(username)
user_interested_classifications = get_user_interested_classifications(username)
ordered_classifications = dict_diff(ordered_classifications, user_interested_classifications)
return render_to_response('display_all_classifications.html', {'classifications' : ordered_classifications,#get_all_classifications_name_link(),
'logged': request.user.is_authenticated(),'user_interested_classifications': user_interested_classifications},context_instance=RequestContext(request))
def show_all_algorithms(request):
algorithms = get_all_algorithms()
ctx_variables = {}
algs = [ (alg.get_show_url(), alg.name) for alg in algorithms]
algorithms = [{'link' : a[0], 'name' : a[1]} for a in algs]
ctx_variables['algorithms'] = algorithms
ctx_variables['logged'] = request.user.is_authenticated()
return HttpResponse(get_template('display_all_algorithms.html').render(Context(ctx_variables)))
def show_algorithm_by_id(request, id):
alg = get_algorithm_by_id(int(id))
impl_question_answers = []
implementationquestions = get_all_implementationquestions()
for implementation_question in implementationquestions :
impl_question_answers.append({"i_q": implementation_question, "i_q_a" : get_questionaswer_by_question_id(implementation_question.id)})
user_votes = []
username = request.user.username
# Only get the user votes when the user is logged in
if username != '':
user_votes = get_user_votes_by_algorithm(username, int(id))
classification = alg.classification
# Reading request to insert the vote of an user for a specific implementation
if request.method == "POST":
username = request.user.username
impl_id = int(request.POST['implId'])
# Parsing JSON with questions ids and answers
questions = json.loads(request.POST['questions'])
for iq in questions:
question_id = int(iq[u'id'])
question_answer = int(iq[u'answerId'])
insert_user_impl_question_answer(username, impl_id, question_id, question_answer)
return HttpResponse('success')
# Try and create an rdf file for the required algorithm
# returns the name of the file so we can show it later
rdf_path = try_create_algorithm_rdf(int(id))
ctx_variables = {}
ctx_variables['algorithm_name'] = alg.name
ctx_variables['algorithm_id'] = alg.id
ctx_variables['algorithm_classification'] = classification.name
ctx_variables['algorithm_about'] = alg.description
ctx_variables['classification_algp_url'] = classification.get_show_url()
#make_classification_link(classification.id)
ctx_variables['classification_dbp_url'] = classification.uri
ctx_variables['rdf_path'] = rdf_path
ctx_variables['implementations'] = get_implementations_by_alg_id(int(id))
ctx_variables['logged'] = request.user.is_authenticated()
ctx_variables['impl_question_answers'] = impl_question_answers
ctx_variables['user_votes'] = user_votes
ctx_variables.update(csrf(request))
return HttpResponse(get_template('display_algorithm_by_id.html').render(Context(ctx_variables)))
@login_required
def display_add_implementation(request, id):
if request.method == 'POST':
algorithm = get_algorithm_by_id(int(request.POST['algorithm_id']))
p_lang = get_programming_language_by_id(int(request.POST['programming_languages']))
implementation = insert_implementation_alg_p_lang(algorithm, p_lang, request.POST['algorithm_code'], False)
return HttpResponseRedirect(algorithm.get_show_url())
else:
c = {'logged': request.user.is_authenticated(),'programming_languages' : get_all_programming_languages(), 'algorithm' : get_algorithm_by_id(int(id))}
c.update(csrf(request))
return render_to_response("add_algorithm_implementation.html", c)
def show_classification_by_id(request, id):
classification = get_classification_by_id(int(id))
algs = get_algorithms_by_classification(classification)
algs_names = map(lambda alg: alg.name, algs)
algs = [{'name' : t[0], 'link' : t[1]} for t in zip(algs_names, [get_algorithm_display_url().replace('#',str(id)) for id in map(lambda alg: alg.id, algs)])]
top5_algs = get_top5_algorithms_by_classification(classification)
return HttpResponse(get_template('display_classification.html').render(Context({'classif' : classification,
'top5_algorithms' : top5_algs,
#'algorithms' : algs,
'algorithms' : dict_diff(algs, top5_algs),
'logged': request.user.is_authenticated()})))
@login_required
def display_add_algorithm(request, id):
if request.method == 'POST':
form = AlgorithmForm(request.POST)
algorithm = insert_algorithm(request.POST['name'], request.POST['description'], get_classification_by_id(int(request.POST['classification'])), False)
return HttpResponseRedirect(algorithm.get_show_url())
else:
c = {'form' : AlgorithmForm(),
'classif' : get_classification_by_id(int(id)),
'programming_languages' : get_all_programming_languages(),
'logged': request.user.is_authenticated()}
c.update(csrf(request))
return render_to_response("add_algorithm.html", c)
| [
[
1,
0,
0.0066,
0.0033,
0,
0.66,
0,
302,
0,
1,
0,
0,
302,
0,
0
],
[
1,
0,
0.0099,
0.0033,
0,
0.66,
0.0312,
456,
0,
1,
0,
0,
456,
0,
0
],
[
1,
0,
0.0132,
0.0033,
0,
... | [
"from django.contrib import auth",
"from django.views.decorators.csrf import csrf_exempt",
"from django.http import HttpResponse, HttpResponseRedirect",
"from django.template import Context",
"from django.template.loader import get_template",
"from algorithm.models import Classification, Implementation,Al... |
from __future__ import unicode_literals
from django import forms
from django.forms.util import flatatt
from django.template import loader
from django.utils.datastructures import SortedDict
from django.utils.html import format_html, format_html_join
from django.utils.http import int_to_base36
from django.utils.safestring import mark_safe
from django.utils.text import capfirst
from django.utils.translation import ugettext, ugettext_lazy as _
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.models import User
from django.contrib.auth.hashers import UNUSABLE_PASSWORD, identify_hasher
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.models import get_current_site
class UserCreateForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and
password.
"""
error_messages = {
'duplicate_username': _("A user with that username already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
username = forms.RegexField(label=_("Username"), max_length=30,
regex=r'^[\w.@+-]+$',
help_text=_("Required. 30 characters or fewer. Letters, digits and "
"@/./+/-/_ only."),
error_messages={
'invalid': _("This value may contain only letters, numbers and "
"@/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as above, for verification."))
class Meta:
model = User
fields = ("username",)
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
def save(self, commit=True):
user = super(UserCreateForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
| [
[
1,
0,
0.0147,
0.0147,
0,
0.66,
0,
777,
0,
1,
0,
0,
777,
0,
0
],
[
1,
0,
0.0441,
0.0147,
0,
0.66,
0.0667,
294,
0,
1,
0,
0,
294,
0,
0
],
[
1,
0,
0.0588,
0.0147,
0,
... | [
"from __future__ import unicode_literals",
"from django import forms",
"from django.forms.util import flatatt",
"from django.template import loader",
"from django.utils.datastructures import SortedDict",
"from django.utils.html import format_html, format_html_join",
"from django.utils.http import int_to... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AlgPedia.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| [
[
1,
0,
0.2,
0.1,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3,
0.1,
0,
0.66,
0.5,
509,
0,
1,
0,
0,
509,
0,
0
],
[
4,
0,
0.75,
0.6,
0,
0.66,
1,
0,
... | [
"import os",
"import sys",
"if __name__ == \"__main__\":\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"AlgPedia.settings\")\n\n from django.core.management import execute_from_command_line\n\n execute_from_command_line(sys.argv)",
" os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"AlgPe... |
from django.db import models
# Create your models here.
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
40,
0,
1,
0,
0,
40,
0,
0
]
] | [
"from django.db import models"
] |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| [
[
8,
0,
0.2188,
0.375,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0625,
0,
0.66,
0.5,
944,
0,
1,
0,
0,
944,
0,
0
],
[
3,
0,
0.8438,
0.375,
0,
0.66,
1,... | [
"\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"",
"from django.test import TestCase",
"class SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\... |
'''
Created on 20/02/2013
@author: Pericolo
'''
from DBPediaQueryFetcher import QueryFetcher
from FileWriters import TXTWriter
import os
from algorithm.models import Classification
class ColumnExtractor:
def __init__(self, file_name):
self.file_name = file_name
def extractColumn(self, column_index):
F_H = open(self.file_name, 'r')
lines = F_H.readlines()
F_H.close()
column = map(lambda x: x.split(',')[column_index], lines)
return column
# http://live.dbpedia.org/page/Category:Algorithms -> pegar categorias dessa pagina e procurar infoboxes de codigo na wikipedia
def doMain():
# if no second parameter is passed then the QueryFetcher assumes that there exists ./temp
query_fetcher = QueryFetcher('csv')
dbpedia_master_query = '''select * where{
?classification skos:broader <http://dbpedia.org/resource/Category:Algorithms>.
?algorithm dcterms:subject ?classification.
?algorithm foaf:isPrimaryTopicOf ?wikipedia
}'''
filename = query_fetcher.fetchResult(dbpedia_master_query)
# always 0-based, baby
insertClassifications(filename, 0)
# returns a list of beautiful names.
# each name only appears once in this list.
def extractNames(classif_list):
beautiful_names = dict()
names = map(lambda x: x.split(':')[-1], classif_list)
names = map(lambda x: x.replace('_', ' ').title(), names)
for i in range(0, len(names)):
beautiful_names[names[i]] = classif_list[i] if names[i] not in beautiful_names else None
#for name in names:
# beautiful_names[name] = '' if name not in beautiful_names else None
return beautiful_names
def insertClassifications(filename, col_number):
print filename
col_extractor = ColumnExtractor(filename)
col_classification = col_extractor.extractColumn(col_number)
classif_names = extractNames(col_classification)
txt_Writer = TXTWriter('./')
file_name = txt_Writer.writeDictKeysToFile(classif_names, 'classif')
for key, val in classif_names.iteritems():
aux_classification = Classification(name=key, uri=val)
aux_classification.save()
if __name__ == '__main__':
doMain(); | [
[
8,
0,
0.0345,
0.0575,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.0805,
0.0115,
0,
0.66,
0.1111,
322,
0,
1,
0,
0,
322,
0,
0
],
[
1,
0,
0.092,
0.0115,
0,
0.66,... | [
"'''\nCreated on 20/02/2013\n\n@author: Pericolo\n'''",
"from DBPediaQueryFetcher import QueryFetcher",
"from FileWriters import TXTWriter",
"import os",
"from algorithm.models import Classification",
"class ColumnExtractor:\n\tdef __init__(self, file_name):\n\t\tself.file_name = file_name\n\t\t\n\tdef ex... |
class CSVColumnExtractor:
def __init__(self, file_name):
self.file_name = file_name
def extract_column(self, column_index):
F_H = open(self.file_name, 'r')
lines = F_H.readlines()
F_H.close()
column = map(lambda x: x.split(';')[column_index], lines)
return column | [
[
3,
0,
0.5357,
1,
0,
0.66,
0,
877,
0,
2,
0,
0,
0,
0,
5
],
[
2,
1,
0.1786,
0.1429,
1,
0.43,
0,
555,
0,
2,
0,
0,
0,
0,
0
],
[
14,
2,
0.2143,
0.0714,
2,
0.41,
0,
... | [
"class CSVColumnExtractor:\n\tdef __init__(self, file_name):\n\t\tself.file_name = file_name\n\t\t\n\tdef extract_column(self, column_index):\n\t\tF_H = open(self.file_name, 'r')\n\t\t\n\t\tlines = F_H.readlines()",
"\tdef __init__(self, file_name):\n\t\tself.file_name = file_name",
"\t\tself.file_name = file_n... |
# Create your views here.
| [] | [] |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AlgPedia.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| [
[
1,
0,
0.2,
0.1,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3,
0.1,
0,
0.66,
0.5,
509,
0,
1,
0,
0,
509,
0,
0
],
[
4,
0,
0.75,
0.6,
0,
0.66,
1,
0,
... | [
"import os",
"import sys",
"if __name__ == \"__main__\":\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"AlgPedia.settings\")\n\n from django.core.management import execute_from_command_line\n\n execute_from_command_line(sys.argv)",
" os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"AlgPe... |
from django.conf.urls import patterns, include, url
from django.contrib.auth.views import login, logout
from algorithm.views import *
#show_main_page, sync_database, clear_database, show_all_classifications, show_classification_by_id
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', show_main_page),
url(r'^sync/$', sync_database),
url(r'^clearDB/$', clear_database),
url(r'^accounts/profile/$', profile),
url(r'^accounts/login/$', 'django.contrib.auth.views.login',{'template_name': 'accounts/login.html'}),
url(r'^accounts/logout/$', logout),
url(r'^signin/$', signin),
url(r'^contact/$', contact),
url(r'^rules/$', rules),
url(r'^about/$', about),
url(r'^show/cat/all$', show_all_classifications),
url(r'^show/cat/id/(\d+)', show_classification_by_id),
url(r'^add/cat/id/(\d+)', display_add_algorithm), #shows the page where we can add an algorithm by category
url(r'^show/alg/id/(\d+)', show_algorithm_by_id),
url(r'^show/alg/all$', show_all_algorithms),
url(r'^add/alg/id/(\d+)$', display_add_implementation),
# serving static files in development
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : './algorithm/static/'}),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
| [
[
1,
0,
0.0263,
0.0263,
0,
0.66,
0,
528,
0,
3,
0,
0,
528,
0,
0
],
[
1,
0,
0.0526,
0.0263,
0,
0.66,
0.2,
745,
0,
2,
0,
0,
745,
0,
0
],
[
1,
0,
0.0789,
0.0263,
0,
0.6... | [
"from django.conf.urls import patterns, include, url",
"from django.contrib.auth.views import login, logout",
"from algorithm.views import *",
"from django.contrib import admin",
"admin.autodiscover()",
"urlpatterns = patterns('',\n # Examples:\n\n\turl(r'^$', show_main_page),\n\turl(r'^sync/$', sync_d... |
# Django settings for AlgPedia project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'AlgPedia',
'USER': 'root',
'PASSWORD': '',
'HOST': '127.0.0.1', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '3306', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['*']
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
LOCALE_PATHS = ()
LANGUAGE_COOKIE_NAME = 'django_language'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
"./../algorithm/static",
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '99fr=jsvq3$8u639h=s^at@*pj7=ty8@n*x_g213-wmv*kd9b9'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'AlgPedia.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'AlgPedia.wsgi.application'
TEMPLATE_DIRS = (
'./../algorithm/templates/',
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'algorithm',
'extractor',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'me@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
TEMPLATE_CONTEXT_PROCESSOR = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.media',
'django.core.context_processors.csrf',
)
LOGIN_URL = '/accounts/login/'
USE_I18N = False
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| [
[
1,
0,
0.016,
0.0053,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
14,
0,
0.0267,
0.0053,
0,
0.66,
0.027,
309,
1,
0,
0,
0,
0,
4,
0
],
[
14,
0,
0.0321,
0.0053,
0,
0.... | [
"import os",
"DEBUG = True",
"TEMPLATE_DEBUG = DEBUG",
"ADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)",
"MANAGERS = ADMINS",
"DATABASES = {\n\t'default': {\n\t'ENGINE': 'django.db.backends.mysql',\n\t'NAME': 'AlgPedia',\n\t'USER': 'root',\n\t'PASSWORD': '',\n\t'HOST': '127.0.0.1', # Empty ... |
"""
WSGI config for AlgPedia project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "AlgPedia.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AlgPedia.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| [
[
8,
0,
0.25,
0.4688,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0312,
0,
0.66,
0.25,
688,
0,
1,
0,
0,
688,
0,
0
],
[
8,
0,
0.6875,
0.0312,
0,
0.66,
0... | [
"\"\"\"\nWSGI config for AlgPedia project.\n\nThis module contains the WSGI application used by Django's development server\nand any production WSGI deployments. It should expose a module-level variable\nnamed ``application``. Django's ``runserver`` and ``runfcgi`` commands discover\nthis application via the ``WSGI... |
import sys
f = open(sys.argv[2], "w")
out = sys.argv[3] + "<<-c("+','.join(open(sys.argv[1]).read().split("\n"))+")"
f.write(out[:-2]+')')
f.close() | [
[
1,
0,
0.25,
0.125,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
14,
0,
0.5,
0.125,
0,
0.66,
0.25,
899,
3,
2,
0,
0,
693,
10,
1
],
[
14,
0,
0.75,
0.125,
0,
0.66,
... | [
"import sys",
"f = open(sys.argv[2], \"w\")",
"out = sys.argv[3] + \"<<-c(\"+','.join(open(sys.argv[1]).read().split(\"\\n\"))+\")\"",
"f.write(out[:-2]+')')",
"f.close()"
] |
#!/usr/bin/env python
# Copyright (c) 2009, Prashanth Ellina
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <organization> nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY Prashanth Ellina ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL Prashanth Ellina BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import dbm
import time
import random
from cmd import Cmd
HOME_DIR = os.environ.get('HOME', '/tmp')
DATA_DIR = os.path.join(HOME_DIR, '.aliaser')
ALIASES_DB = os.path.join(DATA_DIR, 'aliases')
IGNORED_DB = os.path.join(DATA_DIR, 'ignored')
ALIASES_SH = os.path.join(DATA_DIR, 'aliases.sh')
BASH_HISTORY = os.path.join(HOME_DIR, '.bash_history')
DEFAULT_NUM_PREFIXES = 20
FREQ_THRESHOLD = 10
PREFIX_CHOOSERS = [
lambda count, ngram: count > 1,
lambda count, ngram: len(ngram) > 8 or ' ' in ngram,
]
def ensure_data_dir():
if not os.path.exists(DATA_DIR):
os.mkdir(DATA_DIR)
print 'aliaser created directory "%s" ...' % DATA_DIR
ensure_data_dir()
if not os.path.exists(ALIASES_SH):
open(ALIASES_SH, 'w').write('')
ALIASES = dbm.open(ALIASES_DB, 'c')
IGNORED = dbm.open(IGNORED_DB, 'c')
def process_history_lines(bh_file):
freq = {}
for line in bh_file:
line = line[:-1]
count = freq.setdefault(line, '0')
count = str(int(count) + 1)
freq[line] = count
return freq
def generate_ngrams(text):
parts = text.split(' ')
ngrams = []
for i in range(len(parts)):
cur_parts = parts[0:i]
ngram = ' '.join(cur_parts)
ngrams.append(ngram)
return ngrams
def perform_ngram(freq):
ngrams = {}
for command in freq.keys():
count = int(freq[command])
cur_ngrams = generate_ngrams(command)
for cngram in cur_ngrams:
ncount = ngrams.setdefault(cngram, 0)
ncount = ncount + count
ngrams[cngram] = ncount
return ngrams
def regenerate_aliases_sh(aliases):
keys = aliases.keys()
keys.sort()
f = open(ALIASES_SH, 'w')
for k in keys:
command = aliases[k]
command = command.replace('"', r'\"')
entry = 'alias %s="%s"' % (k, command)
f.write('%s\n' % entry)
f.close()
def choose_prefixes(prefixes):
selected_prefixes = []
for count, prefix in prefixes:
reject = True
for chooser in PREFIX_CHOOSERS:
if not chooser(count, prefix):
break
else:
reject = False
if not reject:
selected_prefixes.append((count, prefix))
return selected_prefixes
def analyse(num, frequencies):
aliases = set(ALIASES.keys())
aliased = [ALIASES[a] for a in aliases]
aliases = set()
ignored = set(IGNORED.keys())
ngrams = perform_ngram(frequencies)
prefixes = [(v, k) for k, v in ngrams.iteritems()]
# don't enumerate "aliased" prefixes
firstterm = lambda x: x.split(' ')[0]
prefixes = [(count, prefix) for count, prefix in prefixes \
if firstterm(prefix) not in aliases]
prefixes = [(count, prefix) for count, prefix in prefixes \
if prefix not in aliased]
# don't enumerate "ignored" prefixes
prefixes = [(count, prefix) for count, prefix in prefixes \
if prefix not in ignored]
# ignore prefixes below frequency threshold
prefixes = [(count, prefix) for count, prefix in prefixes \
if count >= FREQ_THRESHOLD]
prefixes = choose_prefixes(prefixes)
prefixes.sort()
prefixes.reverse()
prefixes = prefixes[:num]
return prefixes
def add_to_ignored(command):
ignored = set(IGNORED.keys())
if command not in ignored:
IGNORED[command] = '1'
print 'command/prefix "%s" added to ignore list' % command
def ignore_all(prefixes):
for command in prefixes:
add_to_ignored(command)
def do_showfreq(args):
'''
Analyses bash history and show frequency of commands.
aliaser show-freq [commands_file]
eg: aliaser show-freq
aliaser show-freq sample.commands
'''
infile = None
if args:
infile = args[0]
bh = infile or BASH_HISTORY
bh = open(bh)
frequency = process_history_lines(bh)
entries = []
for key in frequency.keys():
value = frequency[key]
entries.append((int(value), key))
entries.sort()
for count, command in entries:
print count, command
def do_showanalysis(args):
'''
Analyses bash history and shows prefix frequency.
aliaser show-analysis <num> [commands_file]
eg: aliaser show-analysis 10
aliaser show-analysis 20 sample.commands
'''
infile = None
if len(args) == 0:
num = 10
elif len(args) == 1:
num = args[0]
else:
num, infile = args
num = int(num)
bh = infile or BASH_HISTORY
bh = open(bh)
frequency = process_history_lines(bh)
prefixes = analyse(num, frequency)
for p in prefixes:
print p
def do_doalias(args):
'''
Analyses bash history and prompts you to create aliases
for most frequent commands.
eg: aliaser
'''
bh = open(BASH_HISTORY)
frequency = process_history_lines(bh)
while 1:
prefixes = analyse(DEFAULT_NUM_PREFIXES, frequency)
if not prefixes:
break
for index, (count, prefix) in enumerate(prefixes):
print '[%2s]\t%03d times\t%s' % (index, count, prefix)
prefixes = [prefix for count, prefix in prefixes]
choice = raw_input('Choice (empty to ignore all, CTRL+C to cancel): ')
if not choice:
ignore_all(prefixes)
continue
if not choice.isdigit():
print 'bad choice'
continue
choice = int(choice)
if choice >= len(prefixes):
print 'bad choice'
continue
alias = raw_input('Alias (empty to ignore, CTRL+C to cancel): ').strip()
if not alias:
command = prefixes[choice]
add_to_ignored(command)
continue
command = prefixes[choice]
do_addalias([alias, command])
def do_showaliases(args):
'''
Show aliases which are active.
eg: aliaser show
'''
aliases = ALIASES.keys()
aliases.sort()
for a in aliases:
command = ALIASES[a]
print '\'%s\'\t --> \t%s' % (a, command)
def do_addalias(args):
'''
Add a new alias.
aliaser <alias> "<command>"
eg: aliaser add ssh43 "ssh root@192.168.1.43"
'''
if len(args) == 2:
alias, command = args
else:
alias = raw_input('alias: ')
command = raw_input('command: ')
_command = ALIASES.get(alias)
if _command:
print 'Alias already used for command:'
print _command
return False
ALIASES[alias] = command
regenerate_aliases_sh(ALIASES)
return True
def do_deletealias(args):
'''
Delete an existing alias.
aliaser '<alias>'
eg: aliaser delete 'ssh43'
'''
i = args[0]
if ALIASES.has_key(i):
del ALIASES[i]
def do_showrandom_alias(args):
'''
Show a random alias from the ones you created.
eg: aliaser show-random
'''
if args and args[0].isdigit():
num = int(args[0])
else:
num = 1
aliases = ALIASES.keys()
if aliases:
aliases = random.sample(aliases, num)
for a in aliases:
command = ALIASES[a]
print '\'%s\'\t --> \t%s' % (a, command)
def do_showtips(args):
'''
Show useful usage tips.
eg: aliaser show-tips
'''
print 'Use aliases to become more productive:'
do_showrandom_alias(args)
def do_showignored(args):
'''
Show list of ignored commands.
eg: aliaser show-ignored
'''
ignored = list(IGNORED.keys())
ignored.sort()
for i in ignored:
print repr(i)
def do_deleteignored(args):
'''
Delete an ignore command from list.
aliaser '<ignore_command>'
eg: aliaser delete-ignored 'sudo apt-get install'
'''
i = args[0]
if IGNORED.has_key(i):
del IGNORED[i]
null_command = lambda args: None
null_command.__doc__ = ''
COMMANDS = {
'do': do_doalias,
'show': do_showaliases,
'delete': do_deletealias,
'add': do_addalias,
'show-freq': do_showfreq,
'show-analysis': do_showanalysis,
'show-ignored': do_showignored,
'delete-ignored': do_deleteignored,
'show-random': do_showrandom_alias,
'show-tips': do_showtips,
'install': null_command,
}
def show_help():
print 'usage: %s <command> <args>' % sys.argv[0]
commands = COMMANDS.keys()
commands.sort()
for c in commands:
print c
print '-' * len(c)
print COMMANDS[c].__doc__.strip()
print
print 'help'
print '----'
print 'prints the above.'
print 'eg: aliaser help'
def main(command, args):
if command == 'help':
show_help()
else:
cmd_fn = COMMANDS.get(command, None)
if not cmd_fn:
show_help()
return
cmd_fn(args)
if __name__ == '__main__':
if len(sys.argv) > 1:
command = sys.argv[1]
args = sys.argv[2:]
else:
command = 'do'
args = []
try:
main(command, args)
except SystemExit:
raise
except KeyboardInterrupt:
print
| [
[
1,
0,
0.0628,
0.0023,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0651,
0.0023,
0,
0.66,
0.0233,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0674,
0.0023,
0,
... | [
"import os",
"import sys",
"import dbm",
"import time",
"import random",
"from cmd import Cmd",
"HOME_DIR = os.environ.get('HOME', '/tmp')",
"DATA_DIR = os.path.join(HOME_DIR, '.aliaser')",
"ALIASES_DB = os.path.join(DATA_DIR, 'aliases')",
"IGNORED_DB = os.path.join(DATA_DIR, 'ignored')",
"ALIAS... |
#!/usr/bin/env python
# Copyright (c) 2009, Prashanth Ellina
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <organization> nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY Prashanth Ellina ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL Prashanth Ellina BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import sys
import dbm
import time
import random
from cmd import Cmd
HOME_DIR = os.environ.get('HOME', '/tmp')
DATA_DIR = os.path.join(HOME_DIR, '.aliaser')
ALIASES_DB = os.path.join(DATA_DIR, 'aliases')
IGNORED_DB = os.path.join(DATA_DIR, 'ignored')
ALIASES_SH = os.path.join(DATA_DIR, 'aliases.sh')
BASH_HISTORY = os.path.join(HOME_DIR, '.bash_history')
DEFAULT_NUM_PREFIXES = 20
FREQ_THRESHOLD = 10
PREFIX_CHOOSERS = [
lambda count, ngram: count > 1,
lambda count, ngram: len(ngram) > 8 or ' ' in ngram,
]
def ensure_data_dir():
if not os.path.exists(DATA_DIR):
os.mkdir(DATA_DIR)
print 'aliaser created directory "%s" ...' % DATA_DIR
ensure_data_dir()
if not os.path.exists(ALIASES_SH):
open(ALIASES_SH, 'w').write('')
ALIASES = dbm.open(ALIASES_DB, 'c')
IGNORED = dbm.open(IGNORED_DB, 'c')
def process_history_lines(bh_file):
freq = {}
for line in bh_file:
line = line[:-1]
count = freq.setdefault(line, '0')
count = str(int(count) + 1)
freq[line] = count
return freq
def generate_ngrams(text):
parts = text.split(' ')
ngrams = []
for i in range(len(parts)):
cur_parts = parts[0:i]
ngram = ' '.join(cur_parts)
ngrams.append(ngram)
return ngrams
def perform_ngram(freq):
ngrams = {}
for command in freq.keys():
count = int(freq[command])
cur_ngrams = generate_ngrams(command)
for cngram in cur_ngrams:
ncount = ngrams.setdefault(cngram, 0)
ncount = ncount + count
ngrams[cngram] = ncount
return ngrams
def regenerate_aliases_sh(aliases):
keys = aliases.keys()
keys.sort()
f = open(ALIASES_SH, 'w')
for k in keys:
command = aliases[k]
command = command.replace('"', r'\"')
entry = 'alias %s="%s"' % (k, command)
f.write('%s\n' % entry)
f.close()
def choose_prefixes(prefixes):
selected_prefixes = []
for count, prefix in prefixes:
reject = True
for chooser in PREFIX_CHOOSERS:
if not chooser(count, prefix):
break
else:
reject = False
if not reject:
selected_prefixes.append((count, prefix))
return selected_prefixes
def analyse(num, frequencies):
aliases = set(ALIASES.keys())
aliased = [ALIASES[a] for a in aliases]
aliases = set()
ignored = set(IGNORED.keys())
ngrams = perform_ngram(frequencies)
prefixes = [(v, k) for k, v in ngrams.iteritems()]
# don't enumerate "aliased" prefixes
firstterm = lambda x: x.split(' ')[0]
prefixes = [(count, prefix) for count, prefix in prefixes \
if firstterm(prefix) not in aliases]
prefixes = [(count, prefix) for count, prefix in prefixes \
if prefix not in aliased]
# don't enumerate "ignored" prefixes
prefixes = [(count, prefix) for count, prefix in prefixes \
if prefix not in ignored]
# ignore prefixes below frequency threshold
prefixes = [(count, prefix) for count, prefix in prefixes \
if count >= FREQ_THRESHOLD]
prefixes = choose_prefixes(prefixes)
prefixes.sort()
prefixes.reverse()
prefixes = prefixes[:num]
return prefixes
def add_to_ignored(command):
ignored = set(IGNORED.keys())
if command not in ignored:
IGNORED[command] = '1'
print 'command/prefix "%s" added to ignore list' % command
def ignore_all(prefixes):
for command in prefixes:
add_to_ignored(command)
def do_showfreq(args):
'''
Analyses bash history and show frequency of commands.
aliaser show-freq [commands_file]
eg: aliaser show-freq
aliaser show-freq sample.commands
'''
infile = None
if args:
infile = args[0]
bh = infile or BASH_HISTORY
bh = open(bh)
frequency = process_history_lines(bh)
entries = []
for key in frequency.keys():
value = frequency[key]
entries.append((int(value), key))
entries.sort()
for count, command in entries:
print count, command
def do_showanalysis(args):
'''
Analyses bash history and shows prefix frequency.
aliaser show-analysis <num> [commands_file]
eg: aliaser show-analysis 10
aliaser show-analysis 20 sample.commands
'''
infile = None
if len(args) == 0:
num = 10
elif len(args) == 1:
num = args[0]
else:
num, infile = args
num = int(num)
bh = infile or BASH_HISTORY
bh = open(bh)
frequency = process_history_lines(bh)
prefixes = analyse(num, frequency)
for p in prefixes:
print p
def do_doalias(args):
'''
Analyses bash history and prompts you to create aliases
for most frequent commands.
eg: aliaser
'''
bh = open(BASH_HISTORY)
frequency = process_history_lines(bh)
while 1:
prefixes = analyse(DEFAULT_NUM_PREFIXES, frequency)
if not prefixes:
break
for index, (count, prefix) in enumerate(prefixes):
print '[%2s]\t%03d times\t%s' % (index, count, prefix)
prefixes = [prefix for count, prefix in prefixes]
choice = raw_input('Choice (empty to ignore all, CTRL+C to cancel): ')
if not choice:
ignore_all(prefixes)
continue
if not choice.isdigit():
print 'bad choice'
continue
choice = int(choice)
if choice >= len(prefixes):
print 'bad choice'
continue
alias = raw_input('Alias (empty to ignore, CTRL+C to cancel): ').strip()
if not alias:
command = prefixes[choice]
add_to_ignored(command)
continue
command = prefixes[choice]
do_addalias([alias, command])
def do_showaliases(args):
'''
Show aliases which are active.
eg: aliaser show
'''
aliases = ALIASES.keys()
aliases.sort()
for a in aliases:
command = ALIASES[a]
print '\'%s\'\t --> \t%s' % (a, command)
def do_addalias(args):
'''
Add a new alias.
aliaser <alias> "<command>"
eg: aliaser add ssh43 "ssh root@192.168.1.43"
'''
if len(args) == 2:
alias, command = args
else:
alias = raw_input('alias: ')
command = raw_input('command: ')
_command = ALIASES.get(alias)
if _command:
print 'Alias already used for command:'
print _command
return False
ALIASES[alias] = command
regenerate_aliases_sh(ALIASES)
return True
def do_deletealias(args):
'''
Delete an existing alias.
aliaser '<alias>'
eg: aliaser delete 'ssh43'
'''
i = args[0]
if ALIASES.has_key(i):
del ALIASES[i]
def do_showrandom_alias(args):
'''
Show a random alias from the ones you created.
eg: aliaser show-random
'''
if args and args[0].isdigit():
num = int(args[0])
else:
num = 1
aliases = ALIASES.keys()
if aliases:
aliases = random.sample(aliases, num)
for a in aliases:
command = ALIASES[a]
print '\'%s\'\t --> \t%s' % (a, command)
def do_showtips(args):
'''
Show useful usage tips.
eg: aliaser show-tips
'''
print 'Use aliases to become more productive:'
do_showrandom_alias(args)
def do_showignored(args):
'''
Show list of ignored commands.
eg: aliaser show-ignored
'''
ignored = list(IGNORED.keys())
ignored.sort()
for i in ignored:
print repr(i)
def do_deleteignored(args):
'''
Delete an ignore command from list.
aliaser '<ignore_command>'
eg: aliaser delete-ignored 'sudo apt-get install'
'''
i = args[0]
if IGNORED.has_key(i):
del IGNORED[i]
null_command = lambda args: None
null_command.__doc__ = ''
COMMANDS = {
'do': do_doalias,
'show': do_showaliases,
'delete': do_deletealias,
'add': do_addalias,
'show-freq': do_showfreq,
'show-analysis': do_showanalysis,
'show-ignored': do_showignored,
'delete-ignored': do_deleteignored,
'show-random': do_showrandom_alias,
'show-tips': do_showtips,
'install': null_command,
}
def show_help():
print 'usage: %s <command> <args>' % sys.argv[0]
commands = COMMANDS.keys()
commands.sort()
for c in commands:
print c
print '-' * len(c)
print COMMANDS[c].__doc__.strip()
print
print 'help'
print '----'
print 'prints the above.'
print 'eg: aliaser help'
def main(command, args):
if command == 'help':
show_help()
else:
cmd_fn = COMMANDS.get(command, None)
if not cmd_fn:
show_help()
return
cmd_fn(args)
if __name__ == '__main__':
if len(sys.argv) > 1:
command = sys.argv[1]
args = sys.argv[2:]
else:
command = 'do'
args = []
try:
main(command, args)
except SystemExit:
raise
except KeyboardInterrupt:
print
| [
[
1,
0,
0.0628,
0.0023,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0651,
0.0023,
0,
0.66,
0.0233,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0674,
0.0023,
0,
... | [
"import os",
"import sys",
"import dbm",
"import time",
"import random",
"from cmd import Cmd",
"HOME_DIR = os.environ.get('HOME', '/tmp')",
"DATA_DIR = os.path.join(HOME_DIR, '.aliaser')",
"ALIASES_DB = os.path.join(DATA_DIR, 'aliases')",
"IGNORED_DB = os.path.join(DATA_DIR, 'ignored')",
"ALIAS... |
import sys
import os
import re
def getQ(fin, query, N_dom):
qseq = ''
miss = False
for line in fin:
if miss == False:
if re.match("(>%s)\sD(%d).*Query: start\s(\d+)\send\s(\d+).*\n(.*)" %(query,int(N_dom)), line):
Qid = re.match("(>%s)\sD(%d).*Query: start\s(\d+)\send\s(\d+).*\n(.*)" %(query, int(N_dom)), line)
miss = True
else:
if line.startswith('>') == False:
q_seq = line
else:
break
return Qid, q_seq
def decompile(fin, Qid, q_seq, fout):
click = False
for line in fin:
if click == False:
seq_set = re.match(">(\S+).*Query: start\s(\d+)\send\s(\d+).*\n",line)
if seq_set:
fout.write(seq_set.group())
click = True
else:
if line.startswith('>') == False:
ali_seq = truncate(line, Qid, q_seq)
print ali_seq
fout.write(ali_seq)
if line.startswith('>'):
click = False
return 0
def truncate(line, Qid, q_seq):
seq_scan = []
seq_main = []
form = ''
for char in line:
seq_scan.append(char)
if '\r' in seq_scan:
seq_scan = seq_scan[:-2]
else:
seq_scan = seq_scan[:-1]
for char in q_seq:
seq_main.append(char)
if '\r' in seq_main:
seq_main = seq_main[:-2]
else:
seq_main = seq_main[:-1]
ali_seq = best_match(seq_scan, seq_main, p1, p2)
for char in ali_seq:
form = form + char
form = form + '\n'
return form
def best_match(seq_scan, seq_main, p1, p2):
mover = 0
count = 0
best_score = 0
best_slice = ''
main_slice = seq_main[int(p1):int(p2)]
if len(seq_scan) < len(main_slice):
flank = (len(main_slice) - len(seq_scan))
seq_scan.extend(['-' for i in range(flank)])
seq_scan[:0] = ('-' * flank)
max_range = len(seq_scan) - len(main_slice)
while count != max_range + 1:
seq_slice = seq_scan[int(mover):len(main_slice) + mover]
plus_score = 2 * (len([(i) for i,j in zip(main_slice, seq_slice) if i == j]))
minus_score = (len([(i) for i,j in zip(main_slice, seq_slice) if i == j]))
hit_score = plus_score - minus_score
if hit_score > best_score:
best_score = hit_score
best_slice = seq_slice
count = count + 1
mover = mover + 1
return best_slice
def mainFunx(fin, query, fout, N_dom):
Qid, q_seq = getQ(fin, query, N_dom)
decompile(fin,Qid, q_seq, fout)
return 0
if __name__ == '__main__':
fin = open(sys.argv[1], 'rb')
fout = open(sys.argv[2], 'ab')
query = sys.argv[3]
N_dom = sys.argv[4]
p1 = sys.argv[5]
p2 = sys.argv[6]
# print fin
if os.stat(sys.argv[1])[6]==0:
print "file empty"
else:
mainFunx(fin, query, fout,N_dom) | [
[
1,
0,
0.0105,
0.0105,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0211,
0.0105,
0,
0.66,
0.125,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0316,
0.0105,
0,
0... | [
"import sys",
"import os",
"import re",
"def getQ(fin, query, N_dom):\n\t\n\tqseq = ''\n\tmiss = False\n\tfor line in fin:\n\t\tif miss == False:\n\t\t\tif re.match(\"(>%s)\\sD(%d).*Query: start\\s(\\d+)\\send\\s(\\d+).*\\n(.*)\" %(query,int(N_dom)), line):\n\t\t\t\tQid = re.match(\"(>%s)\\sD(%d).*Query: star... |
#!/usr/bin/env python
##########################
# FASTA PARCER #
# prints fasfa file #
# for domain hit #
# match. Optional #
# matching parameters #
# allow for parameter #
# specific domain hit #
# results. Options #
# allow for creation #
# of summary and #
# detail description #
# as well #
# #
# #
#By:Anatoliy Liberman #
#For: Genome Center UCD #
#Supervisor: #
# Alexander Kozik #
# #
##########################
import sys
import re
import fileinput
import os
from optparse import OptionParser
from math import e
def domain_hits(fin):
hmm_FILE = open(fin, "rb")
for line in hmm_FILE:
pos = line.find('Domain search space ')
if pos != -1:
domainValueString = str(line)
domainValue = re.findall('\d+',domainValueString)
if domainValue:
domainValue = int(domainValue[0])
return domainValue
def getProteinType(fin):
hmm_FILE = open(fin, "r")
q_str = ''
a_str = ''
d_str = ''
for line in hmm_FILE:
query = re.match('Query:[\s\t]+(\S+)[\s\t]+\[(\w+)\=\d+\]',line)
if query:
q_str= query.group(1)
acces = re.match("Accession:[\s\t]+(\S+)[\s\t\n]+",line)
if acces:
a_str = acces.group(1)
desc = re.match("Description:[\s\t]+(.*)",line)
if desc:
d_str = desc.group(1)
break
proteinType = (q_str,a_str,d_str)
return proteinType
def get_rows(fin, opts):
arr_rows = []
arr_row = []
finder = True
skipper = False
hmm_f = open(fin, 'r')
for line in hmm_f:
if finder:
pos= line.find('E-value score bias E-value score bias exp N Sequence ')
if pos !=-1:
hmm_f.next()
finder = False
# elif skipper == False:
# print line
# continue
# skipper = True
else:
items = line.split()
arr_rows.append(items)
arr_row = []
if line =='\n':
break
arr_rows = arr_rows[:-1]
return arr_rows
def get_ids(arr_rows):
seq_ids = []
for row in arr_rows:
seq_ids.append(row[8])
return seq_ids
def get_det(fin, ids):
hmm_f = open(fin, 'r')
finder = False
maxstep = len(ids)
all_desc = []
arr_desc = []
step = 0
for line in hmm_f:
if step != maxstep:
if not finder:
if line.find('>> ' + ids[step]) != -1:
hmm_f.next()
hmm_f.next()
finder = True
else:
if line != '\n':
line = ids[step] + line
line = line.split()
all_desc.append(line)
if line == '\n':
step += 1
finder = False
else:
break
return all_desc
def get_aminos(fin, desc_arr, proteinType):
hmm_f = open(fin, 'r')
limit = len(desc_arr)
sequence =''
fasfa_arr = []
step = 0
d_num = ''
found = False
id_match = False
for line in hmm_f:
if step != limit:
if not found:
if not id_match:
if line.find('>> ' + desc_arr[step][0]) != -1:
id_match = True
else:
if re.match('.*== domain (\d+).*', line):
l = re.match('.*== domain (\d+).*', line)
d_num = l.group(1)
if d_num == desc_arr[step][1]:
found = True
if found:
if not re.match('.*== domain (\d+).*', line):
if re.match('.*%s[\s]+\d+\s+(.*)\s+\d+\s+.*' %desc_arr[step][0], line):
fmatch = re.match('.*%s[\s]+\d+\s+(.*)\s+(\d+)\s+.*' %desc_arr[step][0], line)
if fmatch.group(2) != desc_arr[step][11]:
sequence = sequence + fmatch.group(1)
else:
sequence = sequence + fmatch.group(1)
sequence = re.sub('-','',sequence)
fasfa_arr.append('>' + desc_arr[step][0] + ' ' + 'D' + desc_arr[step][1] + ' ' + desc_arr[step][10]+ ' ' + desc_arr[step][11] + ' ' + proteinType[1] + ' [' +' '.join(proteinType[2:]) + ']' + ' ' +proteinType[0] + ' ' + 'Query: start ' + desc_arr[step][7] + ' end ' + desc_arr[step][8] + '\n' + sequence)
step += 1
sequence = ''
if step == limit:
break
if desc_arr[step][0] != desc_arr[(step - 1)][0]:
id_match = False
found = False
return fasfa_arr
def fasta_former(data):
format = ''
for line in data:
format = format + line + '\n'
return format
def options():
opts = OptionParser()
opts.add_option("-a","--acc", dest="o_acc", help ="sets a min accuracy for sequence match(enter percentage)")
opts.add_option("-l","--len", dest="o_len", help = "set min sequence lenght for bps(enter length)")
opts.add_option("-i","--ival", dest="ivalue",help="sets max for i-values(enter i-value)")
opts.add_option("-c","--cval", dest="cvalue", help = "sets max for c-values(enter c-value")
opts.add_option("-s","--out2", dest="o_sum", help = "returns a summary file of the domain hits")
opts.add_option("-d","--out3", dest="dom", help = "prints domain details to outfile")
(opts, args) = opts.parse_args()
return opts.__dict__, args
def opts_filter(fin, seq_det,proteinType, sum_rows, opts):
if opts["cvalue"]:
for row in seq_det:
if float(row[5]) >= float(opts["cvalue"]):
seq_det.remove(row)
if opts["ivalue"]:
for row in seq_det:
if float(row[6]) >= float(opts["ivalue"]):
seq_det.remove(row)
if opts["o_acc"]:
for row in seq_det:
if float(row[16]) <= float(opts["o_acc"]):
seq_det.remove(row)
if opts["o_len"]:
reader = open(fin,'rb')
finder = True
for line in reader:
if finder:
found = re.match('Query:[\s\t]+(\S+)[\s\t]+\[(\w+)\=(\d+)\]',line)
if found:
for row in seq_det:
if int(row[11]) - int(row[10]) <= int(opts["o_len"]):
seq_det.remove(row)
finder = False
else:
break
print str(len(seq_det)) + ' sequence matches extracted from ' + `fin`
if opts["dom"]:
dom_form = ''
out_f2 = open(opts["dom"], 'a')
dom_det = seq_det[:]
query, accession, description = proteinType[0], proteinType[1], proteinType[2]
if os.stat(opts["dom"])[6]==0:
headers = "Query Accession Description ID # certainty score bias c-Evalue i-Evalue hmmfrom hmmto alitype alifrom alito alitype envfrom envto alitype acc"
headers = re.sub('\s','\t', headers)
out_f2.write(headers + '\n')
for line in dom_det:
line = '\t'.join(line)
line = re.sub('\.\.','P',line)
line = re.sub('\[\]','C',line)
line = re.sub('\.\]','R',line)
line = re.sub('\[\.','F',line)
out_f2.write(proteinType[0]+'\t'+ proteinType[1]+'\t'+ proteinType[2]+'\t' + line + '\n')
if opts["o_sum"]:
sum_mark = seq_det[:]
sum_ids = []
filt_sum = []
fout_sum = ''
out_f3 = open(opts["o_sum"], 'a')
for line in sum_mark:
sum_ids.append(line[0])
for line in sum_rows:
if line[8] in sum_ids:
line[7] = sum_ids.count(line[8])
filt_sum.append(line)
for line in filt_sum:
# re.
line[:0] = proteinType
if line[-6] == '(':
insert = ((line[-5] + ' ') + (line[-4]+ ' ') + (line[-1]))
del line[12:]
line.append(insert)
else:
line[-4:] = [''.join(str(line[-4:]))]
line = '\t'.join(str(el) for el in line)
fout_sum = fout_sum + line + '\n'
if os.stat(opts["o_sum"])[6]==0 and fout_sum != 0:
header = "Query Accession Description E-value score bias E-value score bias exp N Sequence Description".split()
header = '\t'.join(header) + '\n'
out_f3.write(header)
out_f3.write(fout_sum)
return seq_det
def real_main(fin, fout):
hits = domain_hits(fin)
if hits == 0:
print "0 sequence matches found " + fin
return 0
opts,args = options()
proteinType = getProteinType(fin)
sum_rows = get_rows(fin, opts)
seq_ids = get_ids(sum_rows)
seq_det = get_det(fin, seq_ids)
if opts:
opts_filter(fin, seq_det, proteinType, sum_rows, opts)
fasta_data = get_aminos(fin, seq_det, proteinType)
fasta_format =fasta_former(fasta_data)
f = open(fout, 'a')
f.write(fasta_format)
if __name__ == '__main__':
if len(sys.argv) <3:
print "1 = fasfa_hmm_parcer, 2 = Hmm_profile 3 = out_file"
print "for options input command arguements followed by -h"
sys.exit(1)
fin = sys.argv[1]
fout = sys.argv[2]
len(sys.argv)
if os.path.isdir(fin):
for subdir, dirs, files in os.walk(fin):
for file in files:
path = os.path.join(subdir, file)
real_main(path, fout)
else:
real_main(fin, fout)
| [
[
1,
0,
0.0947,
0.0035,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0982,
0.0035,
0,
0.66,
0.0625,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.1018,
0.0035,
0,
... | [
"import sys",
"import re",
"import fileinput",
"import os",
"from optparse import OptionParser",
"from math import e",
"def domain_hits(fin):\n\thmm_FILE = open(fin, \"rb\")\n\tfor line in hmm_FILE:\n\t\tpos = line.find('Domain search space ')\n\t\tif pos != -1:\n\t\t\tdomainValueString = str(line)\n\... |
#!/usr/bin/env python
##########################
# FASTA PARCER #
# prints fasfa file #
# for domain hit #
# match. Optional #
# matching parameters #
# allow for parameter #
# specific domain hit #
# results. Options #
# allow for creation #
# of summary and #
# detail description #
# as well #
# #
# #
#By:Anatoliy Liberman #
#For: Genome Center UCD #
#Supervisor: #
# Alexander Kozik #
# #
##########################
import sys
import re
import fileinput
import os
from optparse import OptionParser
from math import e
def domain_hits(fin):
hmm_FILE = open(fin, "rb")
for line in hmm_FILE:
pos = line.find('Domain search space ')
if pos != -1:
domainValueString = str(line)
domainValue = re.findall('\d+',domainValueString)
if domainValue:
domainValue = int(domainValue[0])
return domainValue
def getProteinType(fin):
hmm_FILE = open(fin, "r")
q_str = ''
a_str = ''
d_str = ''
for line in hmm_FILE:
query = re.match('Query:[\s\t]+(\S+)[\s\t]+\[(\w+)\=\d+\]',line)
if query:
q_str= query.group(1)
acces = re.match("Accession:[\s\t]+(\S+)[\s\t\n]+",line)
if acces:
a_str = acces.group(1)
desc = re.match("Description:[\s\t]+(.*)",line)
if desc:
d_str = desc.group(1)
break
proteinType = (q_str,a_str,d_str)
return proteinType
def get_rows(fin, opts):
arr_rows = []
arr_row = []
finder = True
skipper = False
hmm_f = open(fin, 'r')
for line in hmm_f:
if finder:
pos= line.find('E-value score bias E-value score bias exp N Sequence ')
if pos !=-1:
hmm_f.next()
finder = False
# elif skipper == False:
# print line
# continue
# skipper = True
else:
items = line.split()
arr_rows.append(items)
arr_row = []
if line =='\n':
break
arr_rows = arr_rows[:-1]
return arr_rows
def get_ids(arr_rows):
seq_ids = []
for row in arr_rows:
seq_ids.append(row[8])
return seq_ids
def get_det(fin, ids):
hmm_f = open(fin, 'r')
finder = False
maxstep = len(ids)
all_desc = []
arr_desc = []
step = 0
for line in hmm_f:
if step != maxstep:
if not finder:
if line.find('>> ' + ids[step]) != -1:
hmm_f.next()
hmm_f.next()
finder = True
else:
if line != '\n':
line = ids[step] + line
line = line.split()
all_desc.append(line)
if line == '\n':
step += 1
finder = False
else:
break
return all_desc
def get_aminos(fin, desc_arr, proteinType):
hmm_f = open(fin, 'r')
limit = len(desc_arr)
sequence =''
fasfa_arr = []
step = 0
d_num = ''
found = False
id_match = False
for line in hmm_f:
if step != limit:
if not found:
if not id_match:
if line.find('>> ' + desc_arr[step][0]) != -1:
id_match = True
else:
if re.match('.*== domain (\d+).*', line):
l = re.match('.*== domain (\d+).*', line)
d_num = l.group(1)
if d_num == desc_arr[step][1]:
found = True
if found:
if not re.match('.*== domain (\d+).*', line):
if re.match('.*%s[\s]+\d+\s+(.*)\s+\d+\s+.*' %desc_arr[step][0], line):
fmatch = re.match('.*%s[\s]+\d+\s+(.*)\s+(\d+)\s+.*' %desc_arr[step][0], line)
if fmatch.group(2) != desc_arr[step][11]:
sequence = sequence + fmatch.group(1)
else:
sequence = sequence + fmatch.group(1)
sequence = re.sub('-','',sequence)
fasfa_arr.append('>' + desc_arr[step][0] + ' ' + 'D' + desc_arr[step][1] + ' ' + desc_arr[step][10]+ ' ' + desc_arr[step][11] + ' ' + proteinType[1] + ' [' +' '.join(proteinType[2:]) + ']' + ' ' +proteinType[0] + ' ' + 'Query: start ' + desc_arr[step][7] + ' end ' + desc_arr[step][8] + '\n' + sequence)
step += 1
sequence = ''
if step == limit:
break
if desc_arr[step][0] != desc_arr[(step - 1)][0]:
id_match = False
found = False
return fasfa_arr
def fasta_former(data):
format = ''
for line in data:
format = format + line + '\n'
return format
def options():
opts = OptionParser()
opts.add_option("-a","--acc", dest="o_acc", help ="sets a min accuracy for sequence match(enter percentage)")
opts.add_option("-l","--len", dest="o_len", help = "set min sequence lenght for bps(enter length)")
opts.add_option("-i","--ival", dest="ivalue",help="sets max for i-values(enter i-value)")
opts.add_option("-c","--cval", dest="cvalue", help = "sets max for c-values(enter c-value")
opts.add_option("-s","--out2", dest="o_sum", help = "returns a summary file of the domain hits")
opts.add_option("-d","--out3", dest="dom", help = "prints domain details to outfile")
(opts, args) = opts.parse_args()
return opts.__dict__, args
def opts_filter(fin, seq_det,proteinType, sum_rows, opts):
if opts["cvalue"]:
for row in seq_det:
if float(row[5]) >= float(opts["cvalue"]):
seq_det.remove(row)
if opts["ivalue"]:
for row in seq_det:
if float(row[6]) >= float(opts["ivalue"]):
seq_det.remove(row)
if opts["o_acc"]:
for row in seq_det:
if float(row[16]) <= float(opts["o_acc"]):
seq_det.remove(row)
if opts["o_len"]:
reader = open(fin,'rb')
finder = True
for line in reader:
if finder:
found = re.match('Query:[\s\t]+(\S+)[\s\t]+\[(\w+)\=(\d+)\]',line)
if found:
for row in seq_det:
if int(row[11]) - int(row[10]) <= int(opts["o_len"]):
seq_det.remove(row)
finder = False
else:
break
print str(len(seq_det)) + ' sequence matches extracted from ' + `fin`
if opts["dom"]:
dom_form = ''
out_f2 = open(opts["dom"], 'a')
dom_det = seq_det[:]
query, accession, description = proteinType[0], proteinType[1], proteinType[2]
if os.stat(opts["dom"])[6]==0:
headers = "Query Accession Description ID # certainty score bias c-Evalue i-Evalue hmmfrom hmmto alitype alifrom alito alitype envfrom envto alitype acc"
headers = re.sub('\s','\t', headers)
out_f2.write(headers + '\n')
for line in dom_det:
line = '\t'.join(line)
line = re.sub('\.\.','P',line)
line = re.sub('\[\]','C',line)
line = re.sub('\.\]','R',line)
line = re.sub('\[\.','F',line)
out_f2.write(proteinType[0]+'\t'+ proteinType[1]+'\t'+ proteinType[2]+'\t' + line + '\n')
if opts["o_sum"]:
sum_mark = seq_det[:]
sum_ids = []
filt_sum = []
fout_sum = ''
out_f3 = open(opts["o_sum"], 'a')
for line in sum_mark:
sum_ids.append(line[0])
for line in sum_rows:
if line[8] in sum_ids:
line[7] = sum_ids.count(line[8])
filt_sum.append(line)
for line in filt_sum:
# re.
line[:0] = proteinType
if line[-6] == '(':
insert = ((line[-5] + ' ') + (line[-4]+ ' ') + (line[-1]))
del line[12:]
line.append(insert)
else:
line[-4:] = [''.join(str(line[-4:]))]
line = '\t'.join(str(el) for el in line)
fout_sum = fout_sum + line + '\n'
if os.stat(opts["o_sum"])[6]==0 and fout_sum != 0:
header = "Query Accession Description E-value score bias E-value score bias exp N Sequence Description".split()
header = '\t'.join(header) + '\n'
out_f3.write(header)
out_f3.write(fout_sum)
return seq_det
def real_main(fin, fout):
hits = domain_hits(fin)
if hits == 0:
print "0 sequence matches found " + fin
return 0
opts,args = options()
proteinType = getProteinType(fin)
sum_rows = get_rows(fin, opts)
seq_ids = get_ids(sum_rows)
seq_det = get_det(fin, seq_ids)
if opts:
opts_filter(fin, seq_det, proteinType, sum_rows, opts)
fasta_data = get_aminos(fin, seq_det, proteinType)
fasta_format =fasta_former(fasta_data)
f = open(fout, 'a')
f.write(fasta_format)
if __name__ == '__main__':
if len(sys.argv) <3:
print "1 = fasfa_hmm_parcer, 2 = Hmm_profile 3 = out_file"
print "for options input command arguements followed by -h"
sys.exit(1)
fin = sys.argv[1]
fout = sys.argv[2]
len(sys.argv)
if os.path.isdir(fin):
for subdir, dirs, files in os.walk(fin):
for file in files:
path = os.path.join(subdir, file)
real_main(path, fout)
else:
real_main(fin, fout)
| [
[
1,
0,
0.0947,
0.0035,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0982,
0.0035,
0,
0.66,
0.0625,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.1018,
0.0035,
0,
... | [
"import sys",
"import re",
"import fileinput",
"import os",
"from optparse import OptionParser",
"from math import e",
"def domain_hits(fin):\n\thmm_FILE = open(fin, \"rb\")\n\tfor line in hmm_FILE:\n\t\tpos = line.find('Domain search space ')\n\t\tif pos != -1:\n\t\t\tdomainValueString = str(line)\n\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.