本文整理汇总了Python中Function类的典型用法代码示例。如果您正苦于以下问题:Python Function类的具体用法?Python Function怎么用?Python Function使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Function类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _sim_matrix
def _sim_matrix(self, algts, D, gap):
"""
@summary: Calculates the similarity matrix for the set of alignments
@param algts: A list of alignments
@type algts: ListType
@param D: Retention time tolerance parameter for pairwise alignments
@type D: FloatType
@param gap: Gap parameter for pairwise alignments
@type gap: FloatType
@author: Woon Wai Keen
@author: Vladimir Likic
"""
n = len(algts)
total_n = n * (n - 1) / 2
print " Calculating pairwise alignments for %d alignments (D=%.2f, gap=%.2f)" % \
(n, D, gap)
sim_matrix = numpy.zeros((n,n), dtype='f')
for i in range(n - 1):
for j in range(i + 1, n):
ma = Function.align(algts[i], algts[j], D, gap)
sim_matrix[i,j] = sim_matrix[j,i] = ma.similarity
total_n = total_n - 1
print " -> %d pairs remaining" % total_n
return sim_matrix
示例2: updateReference
def updateReference(self):
""" Set up the position when the local node move."""
# The node is the center of a local bench mark.
relative_position = Function.relativePosition(self.position, globalvars.me.position)
self.local_position = [
long(relative_position[0] - globalvars.me.position[0]),
long(relative_position[1] - globalvars.me.position[1]),
]
示例3: __init__
def __init__(self):
wpf.LoadComponent(self, 'WpfApplication1.xaml')
self.CommandTextBox.IsEnabled = False
self.ScenarioRadio.IsEnabled = False
self.ScenariolistView.IsEnabled = False
self.PlaybackRadio.IsEnabled = False
self.RecordFilePathTextBox.IsEnabled = False
self.LoadRecordFileButton.IsEnabled = False
self.CommandTextBox.IsEnabled = False
self.GUIRadio.IsEnabled = False
self.CommandRadio.IsEnabled = False
self.ExcuteScriptButton.IsEnabled = False
self.ExecPlaybackButton.IsEnabled = False
self.PhoneSelect_1.IsEnabled = False
self.PhoneSelect_2.IsEnabled = False
self.PlaybackNumTextBox.IsEnabled = False
Function.mkdir_p(self.__auto_log_root)
self.__auto_save_path = self.__auto_log_root+'\\'+time.strftime('%Y-%m-%d-%H-%M-%S')+'.txt'
示例4: query
def query(ip, query):
pk_id = func.random_pktid(const.LENGTH_PKTID)
port = func.format_string(const.PORT, const.LENGTH_PORT, "0")
step = func.format_string(const.TTL, const.LENGTH_TTL, "0")
query = func.format_string(query, const.LENGTH_QUERY, " ")
pack = bytes(const.CODE_QUERY, "ascii") + bytes(pk_id, "ascii") + bytes(ip, "ascii") + bytes(port, "ascii") + bytes(step, "ascii") + bytes(query, "ascii")
return pack
示例5: logout
def logout(ip55, t_host, sessionID):
tfunc.warning("\n>>> LOGOUT")
result = -1
pk = pack.request_logout(sessionID)
s = sFunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]);
if s is None:
tfunc.error("Errore nella creazione della socket per il logout.")
else:
try:
s.sendall(pk)
ricevutoByte = s.recv(const.LENGTH_PACK)
if str(ricevutoByte[:4], "ascii") == pack.CODE_LOGOUT_DENIED:
tfunc.error("Siamo spiacenti ma il logout risulta impossibile poichè si è in possesso di parti di file uniche.\n" + \
"Sono state scaricate " + str(int(ricevutoByte[4:])) + " parti del file, fatevi il conto di quante ne mancano.")
elif str(ricevutoByte[:4], "ascii") == pack.CODE_ANSWER_LOGOUT:
tfunc.success("Logout eseguito con successo.\nAvevi " + str(int(ricevutoByte[4:])) + " parti, peccato tu te ne vada, addio.\nAttendi " + str(const.TIME_TO_UPDATE) + " secondi e potrai scomparire.")
time.sleep(const.TIME_TO_UPDATE)
pk = pack.close()
sD = sFunc.create_socket_client(func.roll_the_dice(ip55), const.PORT);
if sD is None:
pass
#tfunc.error("Errore nella chiusura del demone")
else:
sD.sendall(pk)
sD.close()
tfunc.success("Chiusura del peer eseguito con successo, arrivederci.\n\n")
result = 1
else:
tfunc.error("Errore nel codice di logout.")
s.close()
except:
tfunc.error("Errore nel logout a causa del tracker.")
s.close()
return result
示例6: forward
def forward(pk, addr, l): # Non andrebbe fatto generico?
if pk != bytes(const.ERROR_PKT, "ascii"):
for x in l:
if addr != x[0]:
s = func.create_socket_client(func.roll_the_dice(x[0]), x[1])
if not(s is None):
s.sendall(pk)
#write_daemon_success("Daemon", "-", "Forward da " + addr + " a " + x[0])
s.close()
示例7: forward
def forward(pk, addr, listNeighbor):
if pk != bytes(const.ERROR_PKT, "ascii"):
if not [pk[20:75], pk[75:80]] in listNeighbor:
for x in listNeighbor:
if addr != x[0]:
s = func.create_socket_client(func.roll_the_dice(x[0]), x[1])
if not(s is None):
s.sendall(pk)
s.close()
示例8: writeHelp
def writeHelp():
func.warning("\nPOSSIBILI ARGOMENTI:")
print("Super Nodo\t-sn")
print("Set Default Ip\t-ip group identifier")
print("Change Port\t-p port")
print("Change Port SN\t-pSN port")
print("Change time\t-t time")
print("Change ttl\t-ttl ttl")
print("")
sys.exit(-1)
示例9: login
def login(host, SN, SN_host, listPkt):
s = func.create_socket_client(func.roll_the_dice(SN_host[0]), SN_host[1])
pk = pack.request_login(host)
if s is None:
func.error("Errore nell'apertura della socket per il login")
update_network(host, SN, listPkt)
else:
s.sendall(pk)
ricevutoByte = s.recv(const.LENGTH_PACK)
sessionID = ricevutoByte[4:20]
s.close()
return sessionID
示例10: download
def download(selectFile):
print ("\n>>> DOWNLOAD")
md5 = selectFile[1]
nomeFile = selectFile[2].decode("ascii").strip()
ip = selectFile[3]
port = selectFile[4]
# Con probabilità 0.5 invio su IPv4, else IPv6
ip = func.roll_the_dice(ip.decode("ascii"))
print("Connessione con:", ip)
# Mi connetto al peer
sP = func.create_socket_client(ip, port)
if sP is None:
print ('Error: could not open socket in download')
else:
pk = pack.request_download(md5)
sP.sendall(pk)
nChunk = int(sP.recv(const.LENGTH_HEADER)[4:10])
ricevutoByte = b''
i = 0
while i != nChunk:
ricevutoLen = sP.recv(const.LENGTH_NCHUNK)
while (len(ricevutoLen) < const.LENGTH_NCHUNK):
ricevutoLen = ricevutoLen + sP.recv(const.LENGTH_NCHUNK - len(ricevutoLen))
buff = sP.recv(int(ricevutoLen))
while(len(buff) < int(ricevutoLen)):
buff = buff + sP.recv(int(ricevutoLen) - len(buff))
ricevutoByte = ricevutoByte + buff
i = i + 1
sP.close()
# Salvare il file data
open((const.FILE_COND + nomeFile),'wb').write(ricevutoByte)
print("File scaricato correttamente, apertura in corso...")
try:
os.system("open " + const.FILE_COND + nomeFile)
except:
try:
os.system("start " + const.FILE_COND + nomeFile)
except:
print("Apertura non riuscita")
示例11: add
def add(ip55, sessionID, t_host, listPartOwned):
tfunc.warning("\n>>> ADD FILE")
fileName = input("Quale file vuoi inserire?\n")
if fileName != "0":
if os.path.exists(const.FILE_COND + fileName):
fileToRead = open((const.FILE_COND + fileName),'rb')
lenFile = os.stat(const.FILE_COND + fileName).st_size
m = hashlib.md5()
for x in range(0, pfunc.calculate_part(lenFile, const.LENGTH_PART)):
m.update(fileToRead.read(const.LENGTH_PART))
m.update(bytes(ip55, "ascii"))
md5File = m.hexdigest()
fileToRead.close()
pk = pack.request_add_file(sessionID, lenFile, md5File, tfunc.format_string(fileName, const.LENGTH_FILENAME, " "))
s = sfunc.create_socket_client(func.roll_the_dice(t_host[0]), t_host[1]);
if s is None:
tfunc.error("Errore, tracker non attivo.")
else:
s.sendall(pk)
ricevutoByte = s.recv(const.LENGTH_PACK)
if(ricevutoByte[:4].decode("ascii") == pack.CODE_ANSWER_ADDFILE):
tfunc.success("Il file " + fileName + " è stato aggiunto con successo.\nÈ stato diviso in " + str(int(ricevutoByte[4:])) + " parti.")
pfunc.add_to_list_owner(md5File, lenFile, const.LENGTH_PART, listPartOwned, fileName)
else:
tfunc.error("Errore nella ricezione del codice di aggiunta file.")
s.close()
else:
tfunc.error("Errore: file non esistente.")
示例12: run
def run(self):
global mutex
sP = sfunc.create_socket_client(func.roll_the_dice(self.peer[0]), self.peer[1])
if sP is None:
#tfunc.error('Error: could not open socket in download')
var = "" # giusto per fargli fare qualcosa
else:
try:
if mutex.acquire(timeout = const.TIME_TO_UPDATE):
dnl.update_own_memory(self.md5, self.partN, self.listPartOwned, "2")
mutex.release()
#tfunc.gtext("Start download della parte " + str(self.partN) + " da " + str(self.peer[0], "ascii"))
pk = pack.request_download(self.md5, self.partN)
sP.sendall(pk)
ricevutoByte = sP.recv(const.LENGTH_HEADER)
if str(ricevutoByte[0:4], "ascii") == pack.CODE_ANSWER_DOWNLOAD:
nChunk = int(ricevutoByte[4:10])
ricevutoByte = b''
i = 0
while i != nChunk:
ricevutoLen = sP.recv(const.LENGTH_NCHUNK)
while (len(ricevutoLen) < const.LENGTH_NCHUNK):
ricevutoLen = ricevutoLen + sP.recv(const.LENGTH_NCHUNK - len(ricevutoLen))
buff = sP.recv(int(ricevutoLen))
while(len(buff) < int(ricevutoLen)):
buff = buff + sP.recv(int(ricevutoLen) - len(buff))
ricevutoByte = ricevutoByte + buff
i = i + 1
sP.close()
# Modifico nel file la parte che ho appena scaricato, se il file non esiste lo creo (es b'00000')
dnl.create_part(ricevutoByte, self.fileName, self.partN, self.lenFile, self.lenPart)
if mutex.acquire(timeout = const.TIME_TO_UPDATE):
# Aggiorno la mia memoria
dnl.update_own_memory(self.md5, self.partN, self.listPartOwned, "1")
mutex.release()
pfunc.part_all(self.listPartOwned[self.md5][0])
# Invio l'update al tracker
send_update(self.t_host, self.sessionID, self.md5, self.partN, self.listPartOwned, self.peer)
else:
raise Exception("Error Download Code")
else:
raise Exception("Error Download Code")
else:
raise Exception("Error Download Code")
except Exception as e:
#tfunc.write_daemon_error(self.name, str(self.peer[0], "ascii"), "ERRORE DOWNLOAD: {0}".format(e))
dnl.update_own_memory(self.md5, self.partN, self.listPartOwned, "0")
示例13: try_connection
def try_connection(host):
s = sfunc.create_socket_client(func.roll_the_dice(host), const.TPORT)
pk = pack.confirm()
if s is None:
sys.exit(-1)
else:
s.sendall(pk)
s.close()
示例14: forward_neighbor
def forward_neighbor(pack):
step = modify_ttl(pack[80:82])
if step != 0:
step = func.format_string(str(step), const.LENGTH_TTL, "0")
pack = pack[0:80] + bytes(step, "ascii")
return pack
else:
return bytes(const.ERROR_PKT, "ascii")
示例15: search_file
def search_file(query, listFiles, listUsers):
listResultQuery = []
for f in listFiles:
if query in f[1]:
for i in listUsers:
if i[2] == f[2]:
listResultQuery.append([f[0], bytes(func.format_string(str(f[1],"ascii"), const.LENGTH_FILENAME, " "),"ascii"), i[0], i[1]])
break
return listResultQuery