Merge branch 'master' of git://git.assembla.com/fpdboz

This commit is contained in:
sqlcoder 2009-11-24 19:51:21 +00:00
commit 339a0133a9
19 changed files with 572 additions and 1108 deletions

View File

@ -10,7 +10,8 @@ Architecture: all
Section: games Section: games
Priority: extra Priority: extra
Depends: ${python:Depends}, python-gtk2, python-matplotlib, Depends: ${python:Depends}, python-gtk2, python-matplotlib,
python-support, mysql-server | postgresql | python-pysqlite2, python-support, python-xlib,
mysql-server | postgresql | python-pysqlite2,
python-psycopg2 | python-mysqldb python-psycopg2 | python-mysqldb
Suggests: wine Suggests: wine
Description: free poker database with HUD Description: free poker database with HUD

View File

@ -51,7 +51,7 @@ if __name__ == "__main__":
parser.add_option("-x", "--failOnError", action="store_true", parser.add_option("-x", "--failOnError", action="store_true",
help="If this option is passed it quits when it encounters any error") help="If this option is passed it quits when it encounters any error")
(options, sys.argv) = parser.parse_args() (options, argv) = parser.parse_args()
settings={'callFpdbHud':False, 'db-backend':2} settings={'callFpdbHud':False, 'db-backend':2}
settings['db-host']=options.server settings['db-host']=options.server

View File

@ -55,15 +55,18 @@ def get_exec_path():
if hasattr(sys, "frozen"): # compiled by py2exe if hasattr(sys, "frozen"): # compiled by py2exe
return os.path.dirname(sys.executable) return os.path.dirname(sys.executable)
else: else:
return os.path.dirname(sys.path[0]) pathname = os.path.dirname(sys.argv[0])
return os.path.abspath(pathname)
def get_config(file_name, fallback = True): def get_config(file_name, fallback = True):
"""Looks in cwd and in self.default_config_path for a config file.""" """Looks in cwd and in self.default_config_path for a config file."""
config_path = os.path.join(get_exec_path(), file_name) config_path = os.path.join(get_exec_path(), file_name)
# print "config_path=", config_path
if os.path.exists(config_path): # there is a file in the cwd if os.path.exists(config_path): # there is a file in the cwd
return config_path # so we use it return config_path # so we use it
else: # no file in the cwd, look where it should be in the first place else: # no file in the cwd, look where it should be in the first place
config_path = os.path.join(get_default_config_path(), file_name) config_path = os.path.join(get_default_config_path(), file_name)
# print "config path 2=", config_path
if os.path.exists(config_path): if os.path.exists(config_path):
return config_path return config_path

View File

@ -454,6 +454,10 @@ class Database:
stylekey = '0000000' # all stylekey values should be higher than this stylekey = '0000000' # all stylekey values should be higher than this
elif hud_style == 'S': elif hud_style == 'S':
stylekey = 'zzzzzzz' # all stylekey values should be lower than this stylekey = 'zzzzzzz' # all stylekey values should be lower than this
else:
stylekey = '0000000'
log.info('hud_style: %s' % hud_style)
#elif hud_style == 'H': #elif hud_style == 'H':
# stylekey = date_nhands_ago needs array by player here ... # stylekey = date_nhands_ago needs array by player here ...
@ -463,6 +467,10 @@ class Database:
h_stylekey = '0000000' # all stylekey values should be higher than this h_stylekey = '0000000' # all stylekey values should be higher than this
elif h_hud_style == 'S': elif h_hud_style == 'S':
h_stylekey = 'zzzzzzz' # all stylekey values should be lower than this h_stylekey = 'zzzzzzz' # all stylekey values should be lower than this
else:
h_stylekey = '000000'
log.info('h_hud_style: %s' % h_hud_style)
#elif h_hud_style == 'H': #elif h_hud_style == 'H':
# h_stylekey = date_nhands_ago needs array by player here ... # h_stylekey = date_nhands_ago needs array by player here ...
@ -1335,7 +1343,9 @@ class Database:
q = q.replace('%s', self.sql.query['placeholder']) q = q.replace('%s', self.sql.query['placeholder'])
self.cursor.execute(q, ( c = self.connection.cursor()
c.execute(q, (
p['tableName'], p['tableName'],
p['gameTypeId'], p['gameTypeId'],
p['siteHandNo'], p['siteHandNo'],
@ -1366,7 +1376,7 @@ class Database:
p['street4Pot'], p['street4Pot'],
p['showdownPot'] p['showdownPot']
)) ))
return self.get_last_insert_id(self.cursor) return self.get_last_insert_id(c)
# def storeHand # def storeHand
def storeHandsPlayers(self, hid, pids, pdata): def storeHandsPlayers(self, hid, pids, pdata):
@ -1377,17 +1387,39 @@ class Database:
pids[p], pids[p],
pdata[p]['startCash'], pdata[p]['startCash'],
pdata[p]['seatNo'], pdata[p]['seatNo'],
pdata[p]['card1'],
pdata[p]['card2'],
pdata[p]['card3'],
pdata[p]['card4'],
pdata[p]['card5'],
pdata[p]['card6'],
pdata[p]['card7'],
pdata[p]['winnings'], pdata[p]['winnings'],
pdata[p]['rake'],
pdata[p]['totalProfit'],
pdata[p]['street0VPI'], pdata[p]['street0VPI'],
pdata[p]['street1Seen'], pdata[p]['street1Seen'],
pdata[p]['street2Seen'], pdata[p]['street2Seen'],
pdata[p]['street3Seen'], pdata[p]['street3Seen'],
pdata[p]['street4Seen'], pdata[p]['street4Seen'],
pdata[p]['sawShowdown'],
pdata[p]['wonAtSD'],
pdata[p]['street0Aggr'], pdata[p]['street0Aggr'],
pdata[p]['street1Aggr'], pdata[p]['street1Aggr'],
pdata[p]['street2Aggr'], pdata[p]['street2Aggr'],
pdata[p]['street3Aggr'], pdata[p]['street3Aggr'],
pdata[p]['street4Aggr'] pdata[p]['street4Aggr'],
pdata[p]['wonWhenSeenStreet1'],
pdata[p]['street0Calls'],
pdata[p]['street1Calls'],
pdata[p]['street2Calls'],
pdata[p]['street3Calls'],
pdata[p]['street4Calls'],
pdata[p]['street0Bets'],
pdata[p]['street1Bets'],
pdata[p]['street2Bets'],
pdata[p]['street3Bets'],
pdata[p]['street4Bets'],
) ) ) )
q = """INSERT INTO HandsPlayers ( q = """INSERT INTO HandsPlayers (
@ -1395,19 +1427,46 @@ class Database:
playerId, playerId,
startCash, startCash,
seatNo, seatNo,
card1,
card2,
card3,
card4,
card5,
card6,
card7,
winnings, winnings,
rake,
totalProfit,
street0VPI, street0VPI,
street1Seen, street1Seen,
street2Seen, street2Seen,
street3Seen, street3Seen,
street4Seen, street4Seen,
sawShowdown,
wonAtSD,
street0Aggr, street0Aggr,
street1Aggr, street1Aggr,
street2Aggr, street2Aggr,
street3Aggr, street3Aggr,
street4Aggr street4Aggr,
wonWhenSeenStreet1,
street0Calls,
street1Calls,
street2Calls,
street3Calls,
street4Calls,
street0Bets,
street1Bets,
street2Bets,
street3Bets,
street4Bets
) )
VALUES ( VALUES (
%s, %s,
%s, %s, %s, %s, %s,
%s, %s, %s, %s, %s,
%s, %s, %s, %s, %s,
%s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
%s, %s, %s, %s, %s %s, %s, %s, %s, %s
@ -1415,16 +1474,9 @@ class Database:
# position, # position,
# tourneyTypeId, # tourneyTypeId,
# card1,
# card2,
# card3,
# card4,
# startCards, # startCards,
# rake,
# totalProfit,
# street0_3BChance, # street0_3BChance,
# street0_3BDone, # street0_3BDone,
# sawShowdown,
# otherRaisedStreet1, # otherRaisedStreet1,
# otherRaisedStreet2, # otherRaisedStreet2,
# otherRaisedStreet3, # otherRaisedStreet3,
@ -1433,8 +1485,6 @@ class Database:
# foldToOtherRaisedStreet2, # foldToOtherRaisedStreet2,
# foldToOtherRaisedStreet3, # foldToOtherRaisedStreet3,
# foldToOtherRaisedStreet4, # foldToOtherRaisedStreet4,
# wonWhenSeenStreet1,
# wonAtSD,
# stealAttemptChance, # stealAttemptChance,
# stealAttempted, # stealAttempted,
# foldBbToStealChance, # foldBbToStealChance,
@ -1465,21 +1515,13 @@ class Database:
# street3CheckCallRaiseDone, # street3CheckCallRaiseDone,
# street4CheckCallRaiseChance, # street4CheckCallRaiseChance,
# street4CheckCallRaiseDone, # street4CheckCallRaiseDone,
# street0Calls,
# street1Calls,
# street2Calls,
# street3Calls,
# street4Calls,
# street0Bets,
# street1Bets,
# street2Bets,
# street3Bets,
# street4Bets
q = q.replace('%s', self.sql.query['placeholder']) q = q.replace('%s', self.sql.query['placeholder'])
#print "DEBUG: inserts: %s" %inserts #print "DEBUG: inserts: %s" %inserts
self.cursor.executemany(q, inserts) #print "DEBUG: q: %s" % q
c = self.connection.cursor()
c.executemany(q, inserts)
def storeHudCacheNew(self, gid, pid, hc): def storeHudCacheNew(self, gid, pid, hc):
q = """INSERT INTO HudCache ( q = """INSERT INTO HudCache (

View File

@ -43,7 +43,7 @@ class DatabaseManager(gobject.GObject):
import Options import Options
import Configuration import Configuration
#NOTE: fpdb should perform this globally #NOTE: fpdb should perform this globally
(options, sys.argv) = Options.fpdb_options() (options, argv) = Options.fpdb_options()
config = Configuration.Config(file=options.config, dbname=options.dbname) config = Configuration.Config(file=options.config, dbname=options.dbname)
#TODO: handle no database present #TODO: handle no database present
defaultDatabaseName = config.get_db_parameters().get('db-databaseName', None) defaultDatabaseName = config.get_db_parameters().get('db-databaseName', None)
@ -808,5 +808,3 @@ if __name__ == '__main__':
d.connect("destroy", gtk.main_quit) d.connect("destroy", gtk.main_quit)
d.run() d.run()
#gtk.main() #gtk.main()

View File

@ -18,7 +18,7 @@
#fpdb modules #fpdb modules
import Card import Card
DEBUG = True DEBUG = False
if DEBUG: if DEBUG:
import pprint import pprint
@ -39,8 +39,16 @@ class DerivedStats():
#Init vars that may not be used, but still need to be inserted. #Init vars that may not be used, but still need to be inserted.
# All stud street4 need this when importing holdem # All stud street4 need this when importing holdem
self.handsplayers[player[1]]['winnings'] = 0 self.handsplayers[player[1]]['winnings'] = 0
self.handsplayers[player[1]]['rake'] = 0
self.handsplayers[player[1]]['totalProfit'] = 0
self.handsplayers[player[1]]['street4Seen'] = False self.handsplayers[player[1]]['street4Seen'] = False
self.handsplayers[player[1]]['street4Aggr'] = False self.handsplayers[player[1]]['street4Aggr'] = False
self.handsplayers[player[1]]['wonWhenSeenStreet1'] = False
self.handsplayers[player[1]]['sawShowdown'] = False
self.handsplayers[player[1]]['wonAtSD'] = False
for i in range(5):
self.handsplayers[player[1]]['street%dCalls' % i] = 0
self.handsplayers[player[1]]['street%dBets' % i] = 0
self.assembleHands(self.hand) self.assembleHands(self.hand)
self.assembleHandsPlayers(self.hand) self.assembleHandsPlayers(self.hand)
@ -81,12 +89,13 @@ class DerivedStats():
self.hands['boardcard5'] = cards[4] self.hands['boardcard5'] = cards[4]
#print "DEBUG: self.getStreetTotals = (%s, %s, %s, %s, %s)" % hand.getStreetTotals() #print "DEBUG: self.getStreetTotals = (%s, %s, %s, %s, %s)" % hand.getStreetTotals()
#FIXME: Pot size still in decimal, needs to be converted to cents totals = hand.getStreetTotals()
(self.hands['street1Pot'], totals = [int(100*i) for i in totals]
self.hands['street2Pot'], self.hands['street1Pot'] = totals[0]
self.hands['street3Pot'], self.hands['street2Pot'] = totals[1]
self.hands['street4Pot'], self.hands['street3Pot'] = totals[2]
self.hands['showdownPot']) = hand.getStreetTotals() self.hands['street4Pot'] = totals[3]
self.hands['showdownPot'] = totals[4]
self.vpip(hand) # Gives playersVpi (num of players vpip) self.vpip(hand) # Gives playersVpi (num of players vpip)
#print "DEBUG: vpip: %s" %(self.hands['playersVpi']) #print "DEBUG: vpip: %s" %(self.hands['playersVpi'])
@ -94,716 +103,64 @@ class DerivedStats():
#print "DEBUG: playersAtStreet 1:'%s' 2:'%s' 3:'%s' 4:'%s'" %(self.hands['playersAtStreet1'],self.hands['playersAtStreet2'],self.hands['playersAtStreet3'],self.hands['playersAtStreet4']) #print "DEBUG: playersAtStreet 1:'%s' 2:'%s' 3:'%s' 4:'%s'" %(self.hands['playersAtStreet1'],self.hands['playersAtStreet2'],self.hands['playersAtStreet3'],self.hands['playersAtStreet4'])
self.streetXRaises(hand) # Empty function currently self.streetXRaises(hand) # Empty function currently
# comment TEXT,
# commentTs DATETIME
def assembleHandsPlayers(self, hand): def assembleHandsPlayers(self, hand):
#street0VPI/vpip already called in Hand #street0VPI/vpip already called in Hand
# sawShowdown is calculated in playersAtStreetX, as that calculation gives us a convenient list of names
#hand.players = [[seat, name, chips],[seat, name, chips]] #hand.players = [[seat, name, chips],[seat, name, chips]]
for player in hand.players: for player in hand.players:
self.handsplayers[player[1]]['seatNo'] = player[0] self.handsplayers[player[1]]['seatNo'] = player[0]
self.handsplayers[player[1]]['startCash'] = player[2] self.handsplayers[player[1]]['startCash'] = player[2]
# Winnings is a non-negative value of money collected from the pot, which already includes the
# rake taken out. hand.collectees is Decimal, database requires cents
for player in hand.collectees:
self.handsplayers[player]['winnings'] = int(100 * hand.collectees[player])
for i, street in enumerate(hand.actionStreets[2:]): for i, street in enumerate(hand.actionStreets[2:]):
self.seen(self.hand, i+1) self.seen(self.hand, i+1)
for i, street in enumerate(hand.actionStreets[1:]): for i, street in enumerate(hand.actionStreets[1:]):
self.aggr(self.hand, i) self.aggr(self.hand, i)
self.calls(self.hand, i)
self.bets(self.hand, i)
# Winnings is a non-negative value of money collected from the pot, which already includes the
# rake taken out. hand.collectees is Decimal, database requires cents
for player in hand.collectees:
self.handsplayers[player]['winnings'] = int(100 * hand.collectees[player])
#FIXME: This is pretty dodgy, rake = hand.rake/#collectees
# You can really only pay rake when you collect money, but
# different sites calculate rake differently.
# Should be fine for split-pots, but won't be accurate for multi-way pots
self.handsplayers[player]['rake'] = int(100* hand.rake)/len(hand.collectees)
if self.handsplayers[player]['street1Seen'] == True:
self.handsplayers[player]['wonWhenSeenStreet1'] = True
if self.handsplayers[player]['sawShowdown'] == True:
self.handsplayers[player]['wonAtSD'] = True
for player in hand.pot.committed:
self.handsplayers[player]['totalProfit'] = int(self.handsplayers[player]['winnings'] - (100*hand.pot.committed[player]))
#default_holecards = ["Xx", "Xx", "Xx", "Xx"]
#if hand.gametype['base'] == "hold":
# pass
#elif hand.gametype['base'] == "stud":
# pass
#else:
# # Flop hopefully...
# pass
for street in hand.holeStreets:
for player in hand.players:
for i in range(1,8): self.handsplayers[player[1]]['card%d' % i] = 0
#print "DEBUG: hand.holecards[%s]: %s" % (street, hand.holecards[street])
if player[1] in hand.holecards[street].keys() and hand.gametype['base'] == "hold":
self.handsplayers[player[1]]['card1'] = Card.encodeCard(hand.holecards[street][player[1]][1][0])
self.handsplayers[player[1]]['card2'] = Card.encodeCard(hand.holecards[street][player[1]][1][1])
try:
self.handsplayers[player[1]]['card3'] = Card.encodeCard(hand.holecards[street][player[1]][1][2])
self.handsplayers[player[1]]['card4'] = Card.encodeCard(hand.holecards[street][player[1]][1][3])
except IndexError:
# Just means no player cards for that street/game - continue
pass
def assembleHudCache(self, hand): def assembleHudCache(self, hand):
# # def generateHudCacheData(player_ids, base, category, action_types, allIns, actionTypeByNo
# # ,winnings, totalWinnings, positions, actionTypes, actionAmounts, antes):
# #"""calculates data for the HUD during import. IMPORTANT: if you change this method make
# # sure to also change the following storage method and table_viewer.prepare_data if necessary
# #"""
# #print "generateHudCacheData, len(player_ids)=", len(player_ids)
# #setup subarrays of the result dictionary.
# street0VPI=[]
# street0Aggr=[]
# street0_3BChance=[]
# street0_3BDone=[]
# street1Seen=[]
# street2Seen=[]
# street3Seen=[]
# street4Seen=[]
# sawShowdown=[]
# street1Aggr=[]
# street2Aggr=[]
# street3Aggr=[]
# street4Aggr=[]
# otherRaisedStreet1=[]
# otherRaisedStreet2=[]
# otherRaisedStreet3=[]
# otherRaisedStreet4=[]
# foldToOtherRaisedStreet1=[]
# foldToOtherRaisedStreet2=[]
# foldToOtherRaisedStreet3=[]
# foldToOtherRaisedStreet4=[]
# wonWhenSeenStreet1=[]
#
# wonAtSD=[]
# stealAttemptChance=[]
# stealAttempted=[]
# hudDataPositions=[]
#
# street0Calls=[]
# street1Calls=[]
# street2Calls=[]
# street3Calls=[]
# street4Calls=[]
# street0Bets=[]
# street1Bets=[]
# street2Bets=[]
# street3Bets=[]
# street4Bets=[]
# #street0Raises=[]
# #street1Raises=[]
# #street2Raises=[]
# #street3Raises=[]
# #street4Raises=[]
#
# # Summary figures for hand table:
# result={}
# result['playersVpi']=0
# result['playersAtStreet1']=0
# result['playersAtStreet2']=0
# result['playersAtStreet3']=0
# result['playersAtStreet4']=0
# result['playersAtShowdown']=0
# result['street0Raises']=0
# result['street1Raises']=0
# result['street2Raises']=0
# result['street3Raises']=0
# result['street4Raises']=0
# result['street1Pot']=0
# result['street2Pot']=0
# result['street3Pot']=0
# result['street4Pot']=0
# result['showdownPot']=0
#
# firstPfRaiseByNo=-1
# firstPfRaiserId=-1
# firstPfRaiserNo=-1
# firstPfCallByNo=-1
# firstPfCallerId=-1
#
# for i, action in enumerate(actionTypeByNo[0]):
# if action[1] == "bet":
# firstPfRaiseByNo = i
# firstPfRaiserId = action[0]
# for j, pid in enumerate(player_ids):
# if pid == firstPfRaiserId:
# firstPfRaiserNo = j
# break
# break
# for i, action in enumerate(actionTypeByNo[0]):
# if action[1] == "call":
# firstPfCallByNo = i
# firstPfCallerId = action[0]
# break
# firstPlayId = firstPfCallerId
# if firstPfRaiseByNo <> -1:
# if firstPfRaiseByNo < firstPfCallByNo or firstPfCallByNo == -1:
# firstPlayId = firstPfRaiserId
#
#
# cutoffId=-1
# buttonId=-1
# sbId=-1
# bbId=-1
# if base=="hold":
# for player, pos in enumerate(positions):
# if pos == 1:
# cutoffId = player_ids[player]
# if pos == 0:
# buttonId = player_ids[player]
# if pos == 'S':
# sbId = player_ids[player]
# if pos == 'B':
# bbId = player_ids[player]
#
# someoneStole=False
#
# #run a loop for each player preparing the actual values that will be commited to SQL
# for player in xrange(len(player_ids)):
# #set default values
# myStreet0VPI=False
# myStreet0Aggr=False
# myStreet0_3BChance=False
# myStreet0_3BDone=False
# myStreet1Seen=False
# myStreet2Seen=False
# myStreet3Seen=False
# myStreet4Seen=False
# mySawShowdown=False
# myStreet1Aggr=False
# myStreet2Aggr=False
# myStreet3Aggr=False
# myStreet4Aggr=False
# myOtherRaisedStreet1=False
# myOtherRaisedStreet2=False
# myOtherRaisedStreet3=False
# myOtherRaisedStreet4=False
# myFoldToOtherRaisedStreet1=False
# myFoldToOtherRaisedStreet2=False
# myFoldToOtherRaisedStreet3=False
# myFoldToOtherRaisedStreet4=False
# myWonWhenSeenStreet1=0.0
# myWonAtSD=0.0
# myStealAttemptChance=False
# myStealAttempted=False
# myStreet0Calls=0
# myStreet1Calls=0
# myStreet2Calls=0
# myStreet3Calls=0
# myStreet4Calls=0
# myStreet0Bets=0
# myStreet1Bets=0
# myStreet2Bets=0
# myStreet3Bets=0
# myStreet4Bets=0
# #myStreet0Raises=0
# #myStreet1Raises=0
# #myStreet2Raises=0
# #myStreet3Raises=0
# #myStreet4Raises=0
#
# #calculate VPIP and PFR
# street=0
# heroPfRaiseCount=0
# for currentAction in action_types[street][player]: # finally individual actions
# if currentAction == "bet":
# myStreet0Aggr = True
# if currentAction == "bet" or currentAction == "call":
# myStreet0VPI = True
#
# if myStreet0VPI:
# result['playersVpi'] += 1
# myStreet0Calls = action_types[street][player].count('call')
# myStreet0Bets = action_types[street][player].count('bet')
# # street0Raises = action_types[street][player].count('raise') bet count includes raises for now
# result['street0Raises'] += myStreet0Bets
#
# #PF3BChance and PF3B
# pfFold=-1
# pfRaise=-1
# if firstPfRaiseByNo != -1:
# for i, actionType in enumerate(actionTypeByNo[0]):
# if actionType[0] == player_ids[player]:
# if actionType[1] == "bet" and pfRaise == -1 and i > firstPfRaiseByNo:
# pfRaise = i
# if actionType[1] == "fold" and pfFold == -1:
# pfFold = i
# if pfFold == -1 or pfFold > firstPfRaiseByNo:
# myStreet0_3BChance = True
# if pfRaise > firstPfRaiseByNo:
# myStreet0_3BDone = True
#
# #steal calculations
# if base=="hold":
# if len(player_ids)>=3: # no point otherwise # was 5, use 3 to match pokertracker definition
# if positions[player]==1:
# if firstPfRaiserId==player_ids[player] \
# and (firstPfCallByNo==-1 or firstPfCallByNo>firstPfRaiseByNo):
# myStealAttempted=True
# myStealAttemptChance=True
# if firstPlayId==cutoffId or firstPlayId==buttonId or firstPlayId==sbId or firstPlayId==bbId or firstPlayId==-1:
# myStealAttemptChance=True
# if positions[player]==0:
# if firstPfRaiserId==player_ids[player] \
# and (firstPfCallByNo==-1 or firstPfCallByNo>firstPfRaiseByNo):
# myStealAttempted=True
# myStealAttemptChance=True
# if firstPlayId==buttonId or firstPlayId==sbId or firstPlayId==bbId or firstPlayId==-1:
# myStealAttemptChance=True
# if positions[player]=='S':
# if firstPfRaiserId==player_ids[player] \
# and (firstPfCallByNo==-1 or firstPfCallByNo>firstPfRaiseByNo):
# myStealAttempted=True
# myStealAttemptChance=True
# if firstPlayId==sbId or firstPlayId==bbId or firstPlayId==-1:
# myStealAttemptChance=True
# if positions[player]=='B':
# pass
#
# if myStealAttempted:
# someoneStole=True
#
#
# #calculate saw* values
# isAllIn = False
# if any(i for i in allIns[0][player]):
# isAllIn = True
# if (len(action_types[1][player])>0 or isAllIn):
# myStreet1Seen = True
#
# if any(i for i in allIns[1][player]):
# isAllIn = True
# if (len(action_types[2][player])>0 or isAllIn):
# myStreet2Seen = True
#
# if any(i for i in allIns[2][player]):
# isAllIn = True
# if (len(action_types[3][player])>0 or isAllIn):
# myStreet3Seen = True
#
# #print "base:", base
# if base=="hold":
# mySawShowdown = True
# if any(actiontype == "fold" for actiontype in action_types[3][player]):
# mySawShowdown = False
# else:
# #print "in else"
# if any(i for i in allIns[3][player]):
# isAllIn = True
# if (len(action_types[4][player])>0 or isAllIn):
# #print "in if"
# myStreet4Seen = True
#
# mySawShowdown = True
# if any(actiontype == "fold" for actiontype in action_types[4][player]):
# mySawShowdown = False
#
# if myStreet1Seen:
# result['playersAtStreet1'] += 1
# if myStreet2Seen:
# result['playersAtStreet2'] += 1
# if myStreet3Seen:
# result['playersAtStreet3'] += 1
# if myStreet4Seen:
# result['playersAtStreet4'] += 1
# if mySawShowdown:
# result['playersAtShowdown'] += 1
#
# #flop stuff
# street=1
# if myStreet1Seen:
# if any(actiontype == "bet" for actiontype in action_types[street][player]):
# myStreet1Aggr = True
#
# myStreet1Calls = action_types[street][player].count('call')
# myStreet1Bets = action_types[street][player].count('bet')
# # street1Raises = action_types[street][player].count('raise') bet count includes raises for now
# result['street1Raises'] += myStreet1Bets
#
# for otherPlayer in xrange(len(player_ids)):
# if player==otherPlayer:
# pass
# else:
# for countOther in xrange(len(action_types[street][otherPlayer])):
# if action_types[street][otherPlayer][countOther]=="bet":
# myOtherRaisedStreet1=True
# for countOtherFold in xrange(len(action_types[street][player])):
# if action_types[street][player][countOtherFold]=="fold":
# myFoldToOtherRaisedStreet1=True
#
# #turn stuff - copy of flop with different vars
# street=2
# if myStreet2Seen:
# if any(actiontype == "bet" for actiontype in action_types[street][player]):
# myStreet2Aggr = True
#
# myStreet2Calls = action_types[street][player].count('call')
# myStreet2Bets = action_types[street][player].count('bet')
# # street2Raises = action_types[street][player].count('raise') bet count includes raises for now
# result['street2Raises'] += myStreet2Bets
#
# for otherPlayer in xrange(len(player_ids)):
# if player==otherPlayer:
# pass
# else:
# for countOther in xrange(len(action_types[street][otherPlayer])):
# if action_types[street][otherPlayer][countOther]=="bet":
# myOtherRaisedStreet2=True
# for countOtherFold in xrange(len(action_types[street][player])):
# if action_types[street][player][countOtherFold]=="fold":
# myFoldToOtherRaisedStreet2=True
#
# #river stuff - copy of flop with different vars
# street=3
# if myStreet3Seen:
# if any(actiontype == "bet" for actiontype in action_types[street][player]):
# myStreet3Aggr = True
#
# myStreet3Calls = action_types[street][player].count('call')
# myStreet3Bets = action_types[street][player].count('bet')
# # street3Raises = action_types[street][player].count('raise') bet count includes raises for now
# result['street3Raises'] += myStreet3Bets
#
# for otherPlayer in xrange(len(player_ids)):
# if player==otherPlayer:
# pass
# else:
# for countOther in xrange(len(action_types[street][otherPlayer])):
# if action_types[street][otherPlayer][countOther]=="bet":
# myOtherRaisedStreet3=True
# for countOtherFold in xrange(len(action_types[street][player])):
# if action_types[street][player][countOtherFold]=="fold":
# myFoldToOtherRaisedStreet3=True
#
# #stud river stuff - copy of flop with different vars
# street=4
# if myStreet4Seen:
# if any(actiontype == "bet" for actiontype in action_types[street][player]):
# myStreet4Aggr=True
#
# myStreet4Calls = action_types[street][player].count('call')
# myStreet4Bets = action_types[street][player].count('bet')
# # street4Raises = action_types[street][player].count('raise') bet count includes raises for now
# result['street4Raises'] += myStreet4Bets
#
# for otherPlayer in xrange(len(player_ids)):
# if player==otherPlayer:
# pass
# else:
# for countOther in xrange(len(action_types[street][otherPlayer])):
# if action_types[street][otherPlayer][countOther]=="bet":
# myOtherRaisedStreet4=True
# for countOtherFold in xrange(len(action_types[street][player])):
# if action_types[street][player][countOtherFold]=="fold":
# myFoldToOtherRaisedStreet4=True
#
# if winnings[player] != 0:
# if myStreet1Seen:
# myWonWhenSeenStreet1 = winnings[player] / float(totalWinnings)
# if mySawShowdown:
# myWonAtSD=myWonWhenSeenStreet1
#
# #add each value to the appropriate array
# street0VPI.append(myStreet0VPI)
# street0Aggr.append(myStreet0Aggr)
# street0_3BChance.append(myStreet0_3BChance)
# street0_3BDone.append(myStreet0_3BDone)
# street1Seen.append(myStreet1Seen)
# street2Seen.append(myStreet2Seen)
# street3Seen.append(myStreet3Seen)
# street4Seen.append(myStreet4Seen)
# sawShowdown.append(mySawShowdown)
# street1Aggr.append(myStreet1Aggr)
# street2Aggr.append(myStreet2Aggr)
# street3Aggr.append(myStreet3Aggr)
# street4Aggr.append(myStreet4Aggr)
# otherRaisedStreet1.append(myOtherRaisedStreet1)
# otherRaisedStreet2.append(myOtherRaisedStreet2)
# otherRaisedStreet3.append(myOtherRaisedStreet3)
# otherRaisedStreet4.append(myOtherRaisedStreet4)
# foldToOtherRaisedStreet1.append(myFoldToOtherRaisedStreet1)
# foldToOtherRaisedStreet2.append(myFoldToOtherRaisedStreet2)
# foldToOtherRaisedStreet3.append(myFoldToOtherRaisedStreet3)
# foldToOtherRaisedStreet4.append(myFoldToOtherRaisedStreet4)
# wonWhenSeenStreet1.append(myWonWhenSeenStreet1)
# wonAtSD.append(myWonAtSD)
# stealAttemptChance.append(myStealAttemptChance)
# stealAttempted.append(myStealAttempted)
# if base=="hold":
# pos=positions[player]
# if pos=='B':
# hudDataPositions.append('B')
# elif pos=='S':
# hudDataPositions.append('S')
# elif pos==0:
# hudDataPositions.append('D')
# elif pos==1:
# hudDataPositions.append('C')
# elif pos>=2 and pos<=4:
# hudDataPositions.append('M')
# elif pos>=5 and pos<=8:
# hudDataPositions.append('E')
# ### RHH Added this elif to handle being a dead hand before the BB (pos==9)
# elif pos==9:
# hudDataPositions.append('X')
# else:
# raise FpdbError("invalid position")
# elif base=="stud":
# #todo: stud positions and steals
# pass
#
# street0Calls.append(myStreet0Calls)
# street1Calls.append(myStreet1Calls)
# street2Calls.append(myStreet2Calls)
# street3Calls.append(myStreet3Calls)
# street4Calls.append(myStreet4Calls)
# street0Bets.append(myStreet0Bets)
# street1Bets.append(myStreet1Bets)
# street2Bets.append(myStreet2Bets)
# street3Bets.append(myStreet3Bets)
# street4Bets.append(myStreet4Bets)
# #street0Raises.append(myStreet0Raises)
# #street1Raises.append(myStreet1Raises)
# #street2Raises.append(myStreet2Raises)
# #street3Raises.append(myStreet3Raises)
# #street4Raises.append(myStreet4Raises)
#
# #add each array to the to-be-returned dictionary
# result['street0VPI']=street0VPI
# result['street0Aggr']=street0Aggr
# result['street0_3BChance']=street0_3BChance
# result['street0_3BDone']=street0_3BDone
# result['street1Seen']=street1Seen
# result['street2Seen']=street2Seen
# result['street3Seen']=street3Seen
# result['street4Seen']=street4Seen
# result['sawShowdown']=sawShowdown
#
# result['street1Aggr']=street1Aggr
# result['otherRaisedStreet1']=otherRaisedStreet1
# result['foldToOtherRaisedStreet1']=foldToOtherRaisedStreet1
# result['street2Aggr']=street2Aggr
# result['otherRaisedStreet2']=otherRaisedStreet2
# result['foldToOtherRaisedStreet2']=foldToOtherRaisedStreet2
# result['street3Aggr']=street3Aggr
# result['otherRaisedStreet3']=otherRaisedStreet3
# result['foldToOtherRaisedStreet3']=foldToOtherRaisedStreet3
# result['street4Aggr']=street4Aggr
# result['otherRaisedStreet4']=otherRaisedStreet4
# result['foldToOtherRaisedStreet4']=foldToOtherRaisedStreet4
# result['wonWhenSeenStreet1']=wonWhenSeenStreet1
# result['wonAtSD']=wonAtSD
# result['stealAttemptChance']=stealAttemptChance
# result['stealAttempted']=stealAttempted
# result['street0Calls']=street0Calls
# result['street1Calls']=street1Calls
# result['street2Calls']=street2Calls
# result['street3Calls']=street3Calls
# result['street4Calls']=street4Calls
# result['street0Bets']=street0Bets
# result['street1Bets']=street1Bets
# result['street2Bets']=street2Bets
# result['street3Bets']=street3Bets
# result['street4Bets']=street4Bets
# #result['street0Raises']=street0Raises
# #result['street1Raises']=street1Raises
# #result['street2Raises']=street2Raises
# #result['street3Raises']=street3Raises
# #result['street4Raises']=street4Raises
#
# #now the various steal values
# foldBbToStealChance=[]
# foldedBbToSteal=[]
# foldSbToStealChance=[]
# foldedSbToSteal=[]
# for player in xrange(len(player_ids)):
# myFoldBbToStealChance=False
# myFoldedBbToSteal=False
# myFoldSbToStealChance=False
# myFoldedSbToSteal=False
#
# if base=="hold":
# if someoneStole and (positions[player]=='B' or positions[player]=='S') and firstPfRaiserId!=player_ids[player]:
# street=0
# for count in xrange(len(action_types[street][player])):#individual actions
# if positions[player]=='B':
# myFoldBbToStealChance=True
# if action_types[street][player][count]=="fold":
# myFoldedBbToSteal=True
# if positions[player]=='S':
# myFoldSbToStealChance=True
# if action_types[street][player][count]=="fold":
# myFoldedSbToSteal=True
#
#
# foldBbToStealChance.append(myFoldBbToStealChance)
# foldedBbToSteal.append(myFoldedBbToSteal)
# foldSbToStealChance.append(myFoldSbToStealChance)
# foldedSbToSteal.append(myFoldedSbToSteal)
# result['foldBbToStealChance']=foldBbToStealChance
# result['foldedBbToSteal']=foldedBbToSteal
# result['foldSbToStealChance']=foldSbToStealChance
# result['foldedSbToSteal']=foldedSbToSteal
#
# #now CB
# street1CBChance=[]
# street1CBDone=[]
# didStreet1CB=[]
# for player in xrange(len(player_ids)):
# myStreet1CBChance=False
# myStreet1CBDone=False
#
# if street0VPI[player]:
# myStreet1CBChance=True
# if street1Aggr[player]:
# myStreet1CBDone=True
# didStreet1CB.append(player_ids[player])
#
# street1CBChance.append(myStreet1CBChance)
# street1CBDone.append(myStreet1CBDone)
# result['street1CBChance']=street1CBChance
# result['street1CBDone']=street1CBDone
#
# #now 2B
# street2CBChance=[]
# street2CBDone=[]
# didStreet2CB=[]
# for player in xrange(len(player_ids)):
# myStreet2CBChance=False
# myStreet2CBDone=False
#
# if street1CBDone[player]:
# myStreet2CBChance=True
# if street2Aggr[player]:
# myStreet2CBDone=True
# didStreet2CB.append(player_ids[player])
#
# street2CBChance.append(myStreet2CBChance)
# street2CBDone.append(myStreet2CBDone)
# result['street2CBChance']=street2CBChance
# result['street2CBDone']=street2CBDone
#
# #now 3B
# street3CBChance=[]
# street3CBDone=[]
# didStreet3CB=[]
# for player in xrange(len(player_ids)):
# myStreet3CBChance=False
# myStreet3CBDone=False
#
# if street2CBDone[player]:
# myStreet3CBChance=True
# if street3Aggr[player]:
# myStreet3CBDone=True
# didStreet3CB.append(player_ids[player])
#
# street3CBChance.append(myStreet3CBChance)
# street3CBDone.append(myStreet3CBDone)
# result['street3CBChance']=street3CBChance
# result['street3CBDone']=street3CBDone
#
# #and 4B
# street4CBChance=[]
# street4CBDone=[]
# didStreet4CB=[]
# for player in xrange(len(player_ids)):
# myStreet4CBChance=False
# myStreet4CBDone=False
#
# if street3CBDone[player]:
# myStreet4CBChance=True
# if street4Aggr[player]:
# myStreet4CBDone=True
# didStreet4CB.append(player_ids[player])
#
# street4CBChance.append(myStreet4CBChance)
# street4CBDone.append(myStreet4CBDone)
# result['street4CBChance']=street4CBChance
# result['street4CBDone']=street4CBDone
#
#
# result['position']=hudDataPositions
#
# foldToStreet1CBChance=[]
# foldToStreet1CBDone=[]
# foldToStreet2CBChance=[]
# foldToStreet2CBDone=[]
# foldToStreet3CBChance=[]
# foldToStreet3CBDone=[]
# foldToStreet4CBChance=[]
# foldToStreet4CBDone=[]
#
# for player in xrange(len(player_ids)):
# myFoldToStreet1CBChance=False
# myFoldToStreet1CBDone=False
# foldToStreet1CBChance.append(myFoldToStreet1CBChance)
# foldToStreet1CBDone.append(myFoldToStreet1CBDone)
#
# myFoldToStreet2CBChance=False
# myFoldToStreet2CBDone=False
# foldToStreet2CBChance.append(myFoldToStreet2CBChance)
# foldToStreet2CBDone.append(myFoldToStreet2CBDone)
#
# myFoldToStreet3CBChance=False
# myFoldToStreet3CBDone=False
# foldToStreet3CBChance.append(myFoldToStreet3CBChance)
# foldToStreet3CBDone.append(myFoldToStreet3CBDone)
#
# myFoldToStreet4CBChance=False
# myFoldToStreet4CBDone=False
# foldToStreet4CBChance.append(myFoldToStreet4CBChance)
# foldToStreet4CBDone.append(myFoldToStreet4CBDone)
#
# if len(didStreet1CB)>=1:
# generateFoldToCB(1, player_ids, didStreet1CB, street1CBDone, foldToStreet1CBChance, foldToStreet1CBDone, actionTypeByNo)
#
# if len(didStreet2CB)>=1:
# generateFoldToCB(2, player_ids, didStreet2CB, street2CBDone, foldToStreet2CBChance, foldToStreet2CBDone, actionTypeByNo)
#
# if len(didStreet3CB)>=1:
# generateFoldToCB(3, player_ids, didStreet3CB, street3CBDone, foldToStreet3CBChance, foldToStreet3CBDone, actionTypeByNo)
#
# if len(didStreet4CB)>=1:
# generateFoldToCB(4, player_ids, didStreet4CB, street4CBDone, foldToStreet4CBChance, foldToStreet4CBDone, actionTypeByNo)
#
# result['foldToStreet1CBChance']=foldToStreet1CBChance
# result['foldToStreet1CBDone']=foldToStreet1CBDone
# result['foldToStreet2CBChance']=foldToStreet2CBChance
# result['foldToStreet2CBDone']=foldToStreet2CBDone
# result['foldToStreet3CBChance']=foldToStreet3CBChance
# result['foldToStreet3CBDone']=foldToStreet3CBDone
# result['foldToStreet4CBChance']=foldToStreet4CBChance
# result['foldToStreet4CBDone']=foldToStreet4CBDone
#
#
# totalProfit=[]
#
# street1CheckCallRaiseChance=[]
# street1CheckCallRaiseDone=[]
# street2CheckCallRaiseChance=[]
# street2CheckCallRaiseDone=[]
# street3CheckCallRaiseChance=[]
# street3CheckCallRaiseDone=[]
# street4CheckCallRaiseChance=[]
# street4CheckCallRaiseDone=[]
# #print "b4 totprof calc, len(playerIds)=", len(player_ids)
# for pl in xrange(len(player_ids)):
# #print "pl=", pl
# myTotalProfit=winnings[pl] # still need to deduct other costs
# if antes:
# myTotalProfit=winnings[pl] - antes[pl]
# for i in xrange(len(actionTypes)): #iterate through streets
# #for j in xrange(len(actionTypes[i])): #iterate through names (using pl loop above)
# for k in xrange(len(actionTypes[i][pl])): #iterate through individual actions of that player on that street
# myTotalProfit -= actionAmounts[i][pl][k]
#
# myStreet1CheckCallRaiseChance=False
# myStreet1CheckCallRaiseDone=False
# myStreet2CheckCallRaiseChance=False
# myStreet2CheckCallRaiseDone=False
# myStreet3CheckCallRaiseChance=False
# myStreet3CheckCallRaiseDone=False
# myStreet4CheckCallRaiseChance=False
# myStreet4CheckCallRaiseDone=False
#
# #print "myTotalProfit=", myTotalProfit
# totalProfit.append(myTotalProfit)
# #print "totalProfit[]=", totalProfit
#
# street1CheckCallRaiseChance.append(myStreet1CheckCallRaiseChance)
# street1CheckCallRaiseDone.append(myStreet1CheckCallRaiseDone)
# street2CheckCallRaiseChance.append(myStreet2CheckCallRaiseChance)
# street2CheckCallRaiseDone.append(myStreet2CheckCallRaiseDone)
# street3CheckCallRaiseChance.append(myStreet3CheckCallRaiseChance)
# street3CheckCallRaiseDone.append(myStreet3CheckCallRaiseDone)
# street4CheckCallRaiseChance.append(myStreet4CheckCallRaiseChance)
# street4CheckCallRaiseDone.append(myStreet4CheckCallRaiseDone)
#
# result['totalProfit']=totalProfit
# #print "res[totalProfit]=", result['totalProfit']
#
# result['street1CheckCallRaiseChance']=street1CheckCallRaiseChance
# result['street1CheckCallRaiseDone']=street1CheckCallRaiseDone
# result['street2CheckCallRaiseChance']=street2CheckCallRaiseChance
# result['street2CheckCallRaiseDone']=street2CheckCallRaiseDone
# result['street3CheckCallRaiseChance']=street3CheckCallRaiseChance
# result['street3CheckCallRaiseDone']=street3CheckCallRaiseDone
# result['street4CheckCallRaiseChance']=street4CheckCallRaiseChance
# result['street4CheckCallRaiseDone']=street4CheckCallRaiseDone
# return result
# #end def generateHudCacheData
pass pass
def vpip(self, hand): def vpip(self, hand):
@ -834,14 +191,23 @@ class DerivedStats():
self.hands['playersAtStreet4'] = 0 self.hands['playersAtStreet4'] = 0
self.hands['playersAtShowdown'] = 0 self.hands['playersAtShowdown'] = 0
alliners = set()
for (i, street) in enumerate(hand.actionStreets[2:]): for (i, street) in enumerate(hand.actionStreets[2:]):
actors = {} actors = set()
for act in hand.actions[street]: for action in hand.actions[street]:
actors[act[0]] = 1 if len(action) > 2 and action[-1]: # allin
self.hands['playersAtStreet%s' % str(i+1)] = len(actors.keys()) alliners.add(action[0])
actors.add(action[0])
if len(actors)==0 and len(alliners)<2:
alliners = set()
self.hands['playersAtStreet%d' % (i+1)] = len(set.union(alliners, actors))
#Need playersAtShowdown actions = hand.actions[hand.actionStreets[-1]]
pas = set.union(self.pfba(actions) - self.pfba(actions, l=('folds',)), alliners)
self.hands['playersAtShowdown'] = len(pas)
for player in pas:
self.handsplayers[player]['sawShowdown'] = True
def streetXRaises(self, hand): def streetXRaises(self, hand):
# self.actions[street] is a list of all actions in a tuple, contining the action as the second element # self.actions[street] is a list of all actions in a tuple, contining the action as the second element
@ -849,11 +215,11 @@ class DerivedStats():
# No idea what this value is actually supposed to be # No idea what this value is actually supposed to be
# In theory its "num small bets paid to see flop/street4, including blind" which makes sense for limit. Not so useful for nl # In theory its "num small bets paid to see flop/street4, including blind" which makes sense for limit. Not so useful for nl
# Leaving empty for the moment, # Leaving empty for the moment,
self.hands['street0Raises'] = 0 # /* num small bets paid to see flop/street4, including blind */
self.hands['street1Raises'] = 0 # /* num small bets paid to see turn/street5 */ for i in range(5): self.hands['street%dRaises' % i] = 0
self.hands['street2Raises'] = 0 # /* num big bets paid to see river/street6 */
self.hands['street3Raises'] = 0 # /* num big bets paid to see sd/street7 */ for (i, street) in enumerate(hand.actionStreets[1:]):
self.hands['street4Raises'] = 0 # /* num big bets paid to see showdown */ self.hands['street%dRaises' % i] = len(filter( lambda action: action[1] in ('raises','bets'), hand.actions[street]))
def seen(self, hand, i): def seen(self, hand, i):
pas = set() pas = set()
@ -878,5 +244,32 @@ class DerivedStats():
else: else:
self.handsplayers[player[1]]['street%sAggr' % i] = False self.handsplayers[player[1]]['street%sAggr' % i] = False
def calls(self, hand, i):
callers = []
for act in hand.actions[hand.actionStreets[i+1]]:
if act[1] in ('calls'):
self.handsplayers[act[0]]['street%sCalls' % i] = 1 + self.handsplayers[act[0]]['street%sCalls' % i]
# CG - I'm sure this stat is wrong
# Best guess is that raise = 2 bets
def bets(self, hand, i):
betters = []
for act in hand.actions[hand.actionStreets[i+1]]:
if act[1] in ('bets'):
self.handsplayers[act[0]]['street%sBets' % i] = 1 + self.handsplayers[act[0]]['street%sBets' % i]
def countPlayers(self, hand): def countPlayers(self, hand):
pass pass
def pfba(self, actions, f=None, l=None):
"""Helper method. Returns set of PlayersFilteredByActions
f - forbidden actions
l - limited to actions
"""
players = set()
for action in actions:
if l is not None and action[1] not in l: continue
if f is not None and action[1] in f: continue
players.add(action[0])
return players

View File

@ -17,8 +17,15 @@ class FpdbParseError(FpdbError):
class FpdbDatabaseError(FpdbError): class FpdbDatabaseError(FpdbError):
pass pass
class FpdbMySQLFailedError(FpdbDatabaseError): class FpdbMySQLError(FpdbDatabaseError):
pass pass
class FpdbMySQLAccessDenied(FpdbDatabaseError):
def __init__(self, value='', errmsg=''):
self.value = value
self.errmsg = errmsg
def __str__(self):
return repr(self.value +" " + self.errmsg)
class DuplicateError(FpdbError): class DuplicateError(FpdbError):
pass pass

View File

@ -731,7 +731,7 @@ def main(argv=None):
gtk.main_quit() gtk.main_quit()
parser = OptionParser() parser = OptionParser()
(options, sys.argv) = parser.parse_args(args = argv) (options, argv) = parser.parse_args(args = argv)
config = Configuration.Config() config = Configuration.Config()
db = None db = None
@ -750,5 +750,3 @@ def main(argv=None):
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main()) sys.exit(main())

View File

@ -281,7 +281,7 @@ if __name__== "__main__":
parser.add_option("-q", "--quiet", action="store_false", dest="gui", default=True, help="don't start gui") parser.add_option("-q", "--quiet", action="store_false", dest="gui", default=True, help="don't start gui")
parser.add_option("-m", "--minPrint", "--status", dest="minPrint", default="0", type="int", parser.add_option("-m", "--minPrint", "--status", dest="minPrint", default="0", type="int",
help="How often to print a one-line status report (0 (default) means never)") help="How often to print a one-line status report (0 (default) means never)")
(options, sys.argv) = parser.parse_args() (options, argv) = parser.parse_args()
config = Configuration.Config() config = Configuration.Config()
# db = fpdb_db.fpdb_db() # db = fpdb_db.fpdb_db()
@ -305,4 +305,3 @@ if __name__== "__main__":
gtk.main() gtk.main()
else: else:
pass pass

View File

@ -53,7 +53,7 @@ class GuiBulkImport():
# Does the lock acquisition need to be more sophisticated for multiple dirs? # Does the lock acquisition need to be more sophisticated for multiple dirs?
# (see comment above about what to do if pipe already open) # (see comment above about what to do if pipe already open)
if self.settings['global_lock'].acquire(False): # returns false immediately if lock not acquired if self.settings['global_lock'].acquire(False): # returns false immediately if lock not acquired
try: #try:
print "\nGlobal lock taken ..." print "\nGlobal lock taken ..."
self.progressbar.set_text("Importing...") self.progressbar.set_text("Importing...")
self.progressbar.pulse() self.progressbar.pulse()
@ -116,10 +116,11 @@ class GuiBulkImport():
self.progressbar.set_text("Import Complete") self.progressbar.set_text("Import Complete")
self.progressbar.set_fraction(0) self.progressbar.set_fraction(0)
except: #except:
err = traceback.extract_tb(sys.exc_info()[2])[-1] #err = traceback.extract_tb(sys.exc_info()[2])[-1]
print "*** BulkImport Error: "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1]) #print "*** BulkImport Error: "+err[2]+"("+str(err[1])+"): "+str(sys.exc_info()[1])
self.settings['global_lock'].release() #self.settings['global_lock'].release()
self.settings['global_lock'].release()
else: else:
print "bulk-import aborted - global lock not available" print "bulk-import aborted - global lock not available"
@ -325,7 +326,7 @@ def main(argv=None):
help="How often to print a one-line status report (0 (default) means never)") help="How often to print a one-line status report (0 (default) means never)")
parser.add_option("-u", "--usage", action="store_true", dest="usage", default=False, parser.add_option("-u", "--usage", action="store_true", dest="usage", default=False,
help="Print some useful one liners") help="Print some useful one liners")
(options, sys.argv) = parser.parse_args(args = argv) (options, argv) = parser.parse_args(args = argv)
if options.usage == True: if options.usage == True:
#Print usage examples and exit #Print usage examples and exit
@ -376,4 +377,3 @@ def main(argv=None):
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main()) sys.exit(main())

View File

@ -216,6 +216,7 @@ class GuiGraphViewer (threading.Thread):
#nametest = nametest.replace("L", "") #nametest = nametest.replace("L", "")
lims = [int(x) for x in limits if x.isdigit()] lims = [int(x) for x in limits if x.isdigit()]
potlims = [int(x[0:-2]) for x in limits if len(x) > 2 and x[-2:] == 'pl']
nolims = [int(x[0:-2]) for x in limits if len(x) > 2 and x[-2:] == 'nl'] nolims = [int(x[0:-2]) for x in limits if len(x) > 2 and x[-2:] == 'nl']
limittest = "and ( (gt.limitType = 'fl' and gt.bigBlind in " limittest = "and ( (gt.limitType = 'fl' and gt.bigBlind in "
# and ( (limit and bb in()) or (nolimit and bb in ()) ) # and ( (limit and bb in()) or (nolimit and bb in ()) )
@ -226,6 +227,14 @@ class GuiGraphViewer (threading.Thread):
limittest = limittest + blindtest + ' ) ' limittest = limittest + blindtest + ' ) '
else: else:
limittest = limittest + '(-1) ) ' limittest = limittest + '(-1) ) '
limittest = limittest + " or (gt.limitType = 'pl' and gt.bigBlind in "
if potlims:
blindtest = str(tuple(potlims))
blindtest = blindtest.replace("L", "")
blindtest = blindtest.replace(",)",")")
limittest = limittest + blindtest + ' ) '
else:
limittest = limittest + '(-1) ) '
limittest = limittest + " or (gt.limitType = 'nl' and gt.bigBlind in " limittest = limittest + " or (gt.limitType = 'nl' and gt.bigBlind in "
if nolims: if nolims:
blindtest = str(tuple(nolims)) blindtest = str(tuple(nolims))
@ -234,6 +243,7 @@ class GuiGraphViewer (threading.Thread):
limittest = limittest + blindtest + ' ) )' limittest = limittest + blindtest + ' ) )'
else: else:
limittest = limittest + '(-1) ) )' limittest = limittest + '(-1) ) )'
if type == 'ring': if type == 'ring':
limittest = limittest + " and gt.type = 'ring' " limittest = limittest + " and gt.type = 'ring' "
elif type == 'tour': elif type == 'tour':

View File

@ -480,6 +480,7 @@ class GuiPlayerStats (threading.Thread):
query = query.replace('<orderbyseats>', '') query = query.replace('<orderbyseats>', '')
lims = [int(x) for x in limits if x.isdigit()] lims = [int(x) for x in limits if x.isdigit()]
potlims = [int(x[0:-2]) for x in limits if len(x) > 2 and x[-2:] == 'pl']
nolims = [int(x[0:-2]) for x in limits if len(x) > 2 and x[-2:] == 'nl'] nolims = [int(x[0:-2]) for x in limits if len(x) > 2 and x[-2:] == 'nl']
bbtest = "and ( (gt.limitType = 'fl' and gt.bigBlind in " bbtest = "and ( (gt.limitType = 'fl' and gt.bigBlind in "
# and ( (limit and bb in()) or (nolimit and bb in ()) ) # and ( (limit and bb in()) or (nolimit and bb in ()) )
@ -490,6 +491,14 @@ class GuiPlayerStats (threading.Thread):
bbtest = bbtest + blindtest + ' ) ' bbtest = bbtest + blindtest + ' ) '
else: else:
bbtest = bbtest + '(-1) ) ' bbtest = bbtest + '(-1) ) '
bbtest = bbtest + " or (gt.limitType = 'pl' and gt.bigBlind in "
if potlims:
blindtest = str(tuple(potlims))
blindtest = blindtest.replace("L", "")
blindtest = blindtest.replace(",)",")")
bbtest = bbtest + blindtest + ' ) '
else:
bbtest = bbtest + '(-1) ) '
bbtest = bbtest + " or (gt.limitType = 'nl' and gt.bigBlind in " bbtest = bbtest + " or (gt.limitType = 'nl' and gt.bigBlind in "
if nolims: if nolims:
blindtest = str(tuple(nolims)) blindtest = str(tuple(nolims))

View File

@ -33,7 +33,7 @@ import os
import Options import Options
import traceback import traceback
(options, sys.argv) = Options.fpdb_options() (options, argv) = Options.fpdb_options()
if not options.errorsToConsole: if not options.errorsToConsole:
print "Note: error output is being diverted to fpdb-error-log.txt and HUD-error.txt. Any major error will be reported there _only_." print "Note: error output is being diverted to fpdb-error-log.txt and HUD-error.txt. Any major error will be reported there _only_."

View File

@ -94,7 +94,7 @@ follow : whether to tail -f the input"""
else: else:
log.info("Created directory '%s'" % out_dir) log.info("Created directory '%s'" % out_dir)
try: try:
self.out_fh = codecs.open(self.out_path, 'w', 'cp1252') self.out_fh = codecs.open(self.out_path, 'w', 'utf8')
except: except:
log.error("out_path %s couldn't be opened" % (self.out_path)) log.error("out_path %s couldn't be opened" % (self.out_path))
else: else:

View File

@ -35,11 +35,11 @@ def fpdb_options():
parser.add_option("-r", "--rerunPython", parser.add_option("-r", "--rerunPython",
action="store_true", action="store_true",
help="Indicates program was restarted with a different path (only allowed once).") help="Indicates program was restarted with a different path (only allowed once).")
(options, sys.argv) = parser.parse_args() (options, argv) = parser.parse_args()
return (options, sys.argv) return (options, argv)
if __name__== "__main__": if __name__== "__main__":
(options, sys.argv) = fpdb_options() (options, argv) = fpdb_options()
print "errorsToConsole =", options.errorsToConsole print "errorsToConsole =", options.errorsToConsole
print "database name =", options.dbname print "database name =", options.dbname
print "config file =", options.config print "config file =", options.config

View File

@ -31,18 +31,18 @@ class PokerStars(HandHistoryConverter):
sitename = "PokerStars" sitename = "PokerStars"
filetype = "text" filetype = "text"
codepage = "cp1252" codepage = ("utf8", "cp1252")
siteId = 2 # Needs to match id entry in Sites database siteId = 2 # Needs to match id entry in Sites database
mixes = { 'HORSE': 'horse', '8-Game': '8game', 'HOSE': 'hose'} # Legal mixed games mixes = { 'HORSE': 'horse', '8-Game': '8game', 'HOSE': 'hose'} # Legal mixed games
sym = {'USD': "\$", 'CAD': "\$", 'T$': "", "EUR": "\x80", "GBP": "\xa3"} # ADD Euro, Sterling, etc HERE sym = {'USD': "\$", 'CAD': "\$", 'T$': "", "EUR": "\xe2\x82\xac", "GBP": "\xa3"} # ADD Euro, Sterling, etc HERE
substitutions = { substitutions = {
'LEGAL_ISO' : "USD|EUR|GBP|CAD|FPP", # legal ISO currency codes 'LEGAL_ISO' : "USD|EUR|GBP|CAD|FPP", # legal ISO currency codes
'LS' : "\$|\x80|\xa3" # legal currency symbols ADD Euro, Sterling, etc HERE 'LS' : "\$|\xe2\x82\xac|" # legal currency symbols - Euro(cp1252, utf-8)
} }
# Static regexes # Static regexes
re_GameInfo = re.compile(""" re_GameInfo = re.compile(u"""
PokerStars\sGame\s\#(?P<HID>[0-9]+):\s+ PokerStars\sGame\s\#(?P<HID>[0-9]+):\s+
(Tournament\s\# # open paren of tournament info (Tournament\s\# # open paren of tournament info
(?P<TOURNO>\d+),\s (?P<TOURNO>\d+),\s
@ -62,7 +62,7 @@ class PokerStars(HandHistoryConverter):
(?P<DATETIME>.*$)""" % substitutions, (?P<DATETIME>.*$)""" % substitutions,
re.MULTILINE|re.VERBOSE) re.MULTILINE|re.VERBOSE)
re_PlayerInfo = re.compile(""" re_PlayerInfo = re.compile(u"""
^Seat\s(?P<SEAT>[0-9]+):\s ^Seat\s(?P<SEAT>[0-9]+):\s
(?P<PNAME>.*)\s (?P<PNAME>.*)\s
\((%(LS)s)?(?P<CASH>[.0-9]+)\sin\schips\)""" % substitutions, \((%(LS)s)?(?P<CASH>[.0-9]+)\sin\schips\)""" % substitutions,
@ -373,12 +373,9 @@ if __name__ == "__main__":
parser.add_option("-i", "--input", dest="ipath", help="parse input hand history", default="regression-test-files/stars/horse/HH20090226 Natalie V - $0.10-$0.20 - HORSE.txt") parser.add_option("-i", "--input", dest="ipath", help="parse input hand history", default="regression-test-files/stars/horse/HH20090226 Natalie V - $0.10-$0.20 - HORSE.txt")
parser.add_option("-o", "--output", dest="opath", help="output translation to", default="-") parser.add_option("-o", "--output", dest="opath", help="output translation to", default="-")
parser.add_option("-f", "--follow", dest="follow", help="follow (tail -f) the input", action="store_true", default=False) parser.add_option("-f", "--follow", dest="follow", help="follow (tail -f) the input", action="store_true", default=False)
parser.add_option("-q", "--quiet", #parser.add_option("-q", "--quiet", action="store_const", const=logging.CRITICAL, dest="verbosity", default=logging.INFO)
action="store_const", const=logging.CRITICAL, dest="verbosity", default=logging.INFO) #parser.add_option("-v", "--verbose", action="store_const", const=logging.INFO, dest="verbosity")
parser.add_option("-v", "--verbose", #parser.add_option("--vv", action="store_const", const=logging.DEBUG, dest="verbosity")
action="store_const", const=logging.INFO, dest="verbosity")
parser.add_option("--vv",
action="store_const", const=logging.DEBUG, dest="verbosity")
(options, args) = parser.parse_args() (options, args) = parser.parse_args()

View File

@ -31,7 +31,7 @@ import os
import Options import Options
import traceback import traceback
(options, sys.argv) = Options.fpdb_options() (options, argv) = Options.fpdb_options()
if not options.errorsToConsole: if not options.errorsToConsole:
print "Note: error output is being diverted to fpdb-error-log.txt and HUD-error.txt. Any major error will be reported there _only_." print "Note: error output is being diverted to fpdb-error-log.txt and HUD-error.txt. Any major error will be reported there _only_."

View File

@ -53,7 +53,7 @@ import threading
import Options import Options
import string import string
cl_options = string.join(sys.argv[1:]) cl_options = string.join(sys.argv[1:])
(options, sys.argv) = Options.fpdb_options() (options, argv) = Options.fpdb_options()
if not options.errorsToConsole: if not options.errorsToConsole:
print "Note: error output is being diverted to fpdb-error-log.txt and HUD-error.txt. Any major error will be reported there _only_." print "Note: error output is being diverted to fpdb-error-log.txt and HUD-error.txt. Any major error will be reported there _only_."
@ -81,7 +81,7 @@ import SQL
import Database import Database
import FpdbSQLQueries import FpdbSQLQueries
import Configuration import Configuration
from Exceptions import * import Exceptions
VERSION = "0.12" VERSION = "0.12"
@ -470,21 +470,25 @@ class fpdb:
self.sql = SQL.Sql(db_server = self.settings['db-server']) self.sql = SQL.Sql(db_server = self.settings['db-server'])
try: try:
self.db = Database.Database(self.config, sql = self.sql) self.db = Database.Database(self.config, sql = self.sql)
except FpdbMySQLFailedError: except Exceptions.FpdbMySQLAccessDenied:
self.warning_box("Unable to connect to MySQL! Is the MySQL server running?!", "FPDB ERROR") self.warning_box("MySQL Server reports: Access denied. Are your permissions set correctly?")
exit() exit()
except FpdbError:
#print "Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user']) # except FpdbMySQLFailedError:
self.warning_box("Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user']), "FPDB ERROR") # self.warning_box("Unable to connect to MySQL! Is the MySQL server running?!", "FPDB ERROR")
err = traceback.extract_tb(sys.exc_info()[2])[-1] # exit()
print "*** Error: " + err[2] + "(" + str(err[1]) + "): " + str(sys.exc_info()[1]) # except FpdbError:
sys.stderr.write("Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user'])) # #print "Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user'])
except: # self.warning_box("Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user']), "FPDB ERROR")
#print "Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user']) # err = traceback.extract_tb(sys.exc_info()[2])[-1]
self.warning_box("Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user']), "FPDB ERROR") # print "*** Error: " + err[2] + "(" + str(err[1]) + "): " + str(sys.exc_info()[1])
err = traceback.extract_tb(sys.exc_info()[2])[-1] # sys.stderr.write("Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user']))
print "*** Error: " + err[2] + "(" + str(err[1]) + "): " + str(sys.exc_info()[1]) # except:
sys.stderr.write("Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user'])) # #print "Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user'])
# self.warning_box("Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user']), "FPDB ERROR")
# err = traceback.extract_tb(sys.exc_info()[2])[-1]
# print "*** Error: " + err[2] + "(" + str(err[1]) + "): " + str(sys.exc_info()[1])
# sys.stderr.write("Failed to connect to %s database with username %s." % (self.settings['db-server'], self.settings['db-user']))
if self.db.wrongDbVersion: if self.db.wrongDbVersion:
diaDbVersionWarning = gtk.Dialog(title="Strong Warning - Invalid database version", parent=None, flags=0, buttons=(gtk.STOCK_OK,gtk.RESPONSE_OK)) diaDbVersionWarning = gtk.Dialog(title="Strong Warning - Invalid database version", parent=None, flags=0, buttons=(gtk.STOCK_OK,gtk.RESPONSE_OK))

View File

@ -100,12 +100,15 @@ class fpdb_db:
import MySQLdb import MySQLdb
if use_pool: if use_pool:
MySQLdb = pool.manage(MySQLdb, pool_size=5) MySQLdb = pool.manage(MySQLdb, pool_size=5)
# try: try:
self.db = MySQLdb.connect(host=host, user=user, passwd=password, db=database, use_unicode=True) self.db = MySQLdb.connect(host=host, user=user, passwd=password, db=database, use_unicode=True)
#TODO: Add port option #TODO: Add port option
# except: except MySQLdb.Error, ex:
# raise FpdbMySQLFailedError("MySQL connection failed") if ex.args[0] == 1045:
elif backend==fpdb_db.PGSQL: raise FpdbMySQLAccessDenied(ex.args[0], ex.args[1])
else:
print "*** WARNING UNKNOWN MYSQL ERROR", ex
elif backend == fpdb_db.PGSQL:
import psycopg2 import psycopg2
import psycopg2.extensions import psycopg2.extensions
if use_pool: if use_pool: