-
Notifications
You must be signed in to change notification settings - Fork 1
/
utility.py
83 lines (72 loc) · 2.62 KB
/
utility.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import random
import socket
import struct
import csv
import os, fnmatch
def createIp():
return socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
def createPort():
port = random.randint(0, 49151)
return str(port)
def createId(ip, port, bitsNumber):
id = extractKBits(int(hash(ip + port)), bitsNumber)
if id == 0:
id = id + 1
if id < 0 :
id *= -1
return id
def extractKBits(num, k, p = 0):
binary = bin(num)
# remove first two characters
binary = binary[2:]
end = len(binary) - p
start = end - k + 1
# extract k bit sub-string
kBitSubStr = binary[start : end+1]
# convert extracted sub-string into decimal again
return int(kBitSubStr,2)
def writeEdgeCsv(nodeList):
with open('edge.csv', mode='w') as node_file:
node_writer = csv.writer(node_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for i in nodeList:
if i is not None:
for n in i['node']._routingTable:
listNodeEdge = []
for k in n:
if k is not None:
listNodeEdge.append(i['id'])
listNodeEdge.append(k['id'])
node_writer.writerow(listNodeEdge)
def writeSnapshotCsv(nodeList, counter):
with open('snapshot'+str(counter)+'.csv', mode='w') as node_file:
node_writer = csv.writer(node_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for i in nodeList:
if i is not None:
for n in i['node']._routingTable:
listNodeEdge = []
for k in n:
if k is not None:
listNodeEdge.append(i['id'])
listNodeEdge.append(k['id'])
node_writer.writerow(listNodeEdge)
def writeNodeCsv(nodeList):
with open('node.csv', mode='w') as node_file:
node_writer = csv.writer(node_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
new_list = [i["id"] for i in nodeList]
node_writer.writerow(new_list)
def openCsv(name):
with open(name, 'r') as f:
reader = csv.reader(f)
node = list(reader)
return node
def findFile(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name).replace('../kademlia/', ''))
return result
def removeFile(list):
for i in list:
os.remove(i)
print("File Removed!")