code
stringlengths
1
1.72M
language
stringclasses
1 value
class Rune(): def __init__(self): self.parent=None self.Name="Glyph of Acumen" self.Icon="b_3_3.png" self.IconData=None self.Tags=['energy','glyph'] self.Costs = 820 self.Description="Increases your Energy by 2.2" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Energy += 2.2 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Glyph of Celerity" self.Icon="b_2_3.png" self.IconData=None self.Tags=['energy','glyph'] self.Costs = 820 self.Description="Reduces your Spell Cooldown by 0.0532% per level" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Cooldown_Reduction += 0.0532 * self.parent.Level self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Quintessence of Regeneration" self.Icon="bl_2_3.png" self.IconData=None self.Tags=['health_regen','quintessence'] self.Costs = 2050 self.Description="Increases your Health Regen by 0.28 per Level" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Healh_Regen_per_5_seconds += 0.28 * self.parent.Level self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Seal of Force" self.Icon="y_2_3.png" self.IconData=None self.Tags=['energy','seal'] self.Costs = 410 self.Description="Increases your Ability Power for 0.10 per level" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Ability_Power += 0.10 * self.parent.Level self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Mark of Replentishment" self.Icon="r_3_3.png" self.IconData=None self.Tags=['mana_regen','mark'] self.Costs = 205 self.Description="Increases your Mana Regen by 0.26" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Mana_Regen_per_5_seconds += 0.26 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Seal of Focus" self.Icon="y_1_3.png" self.IconData=None self.Tags=['energy','seal'] self.Costs = 410 self.Description="Increases your Spell Cooldown Reduction by 0.29%" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Cooldown_Reduction += 0.29 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Glyph of Replentishment" self.Icon="b_3_3.png" self.IconData=None self.Tags=['mana_regen','glyph'] self.Costs = 410 self.Description="Increases your Mana Regen by 0.31" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Mana_Regen_per_5_seconds += 0.31 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
import os import sys import re __all__ = [] dirList=os.listdir(sys.path[0] + "/ftllibs/runes") for i in dirList: m = re.match("(r_.+?).py$",i) if m: __all__.append(m.groups()[0])
Python
class Rune(): def __init__(self): self.parent=None self.Name="Quintessence of Resilience" self.Icon="bl_1_3.png" self.IconData=None self.Tags=['armor','quintessence'] self.Costs = 1025 self.Description="Increases your Armor by 4.26" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Armor += 4.26 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Quintessence of Strength" self.Icon="bl_1_3.png" self.IconData=None self.Tags=['attack_damage','quintessence'] self.Costs = 1025 self.Description="Increases your attack damage by 2.25" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Attack_Damage += 2.25 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Glyph of Knowledge" self.Icon="b_2_3.png" self.IconData=None self.Tags=['mana','glyph'] self.Costs = 410 self.Description="Increases your Mana by 1.42 per level" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Mana += 1.42 * self.parent.Level self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Quintessence of Replentishment" self.Icon="bl_3_3.png" self.IconData=None self.Tags=['mana_regen','quintessence'] self.Costs = 1025 self.Description="Increases your Mana Regen by 1.25" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Mana_Regen_per_5_seconds += 1.25 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Glyph of Shielding" self.Icon="b_4_3.png" self.IconData=None self.Tags=['magic_resist','Glyph'] self.Costs = 205 self.Description="Increases your magic resist by 0.15 per level" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Magic_Resist += 0.15 * self.parent.Level self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Glyph of Resilience" self.Icon="b_1_3.png" self.IconData=None self.Tags=['armor','glyph'] self.Costs = 205 self.Description="Increases your Armor by 0.7" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Armor += 0.7 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Seal of Fortitude" self.Icon="y_3_3.png" self.IconData=None self.Tags=['energy','seal'] self.Costs = 820 self.Description="Increases your Health by 5.35" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Health += 5.35 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Quintessence of Clarity" self.Icon="bl_4_3.png" self.IconData=None self.Tags=['energy','quintessence'] self.Costs = 820 self.Description="Increases your Mana Reg. by 0.24 per Level" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Mana_Regen_per_5_seconds += 0.24 * self.parent.Level self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Quintessence of Fortitude" self.Icon="bl_3_3.png" self.IconData=None self.Tags=['energy','quintessence'] self.Costs = 2050 self.Description="Increases your Health by 26" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Health += 26 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Quintessence of Endurance" self.Icon="bl_2_3.png" self.IconData=None self.Tags=['energy','quintessence'] self.Costs = 820 self.Description="Increases your Health by 1.5%" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Health_Percentage += 1.5 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Seal of Fortitude" self.Icon="y_1_3.png" self.IconData=None self.Tags=['critical_damage','seal'] self.Costs = 820 self.Description="Increases your Critical Damage by 0.78%" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Critical_Damage_Percentage += 0.78 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Quintessence of Focus" self.Icon="bl_1_3.png" self.IconData=None self.Tags=['energy','quintessence'] self.Costs = 820 self.Description="Increases your Spell Cooldown Reduction by 1.64%" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Cooldown_Reduction += 1.64 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Glyph of Focus" self.Icon="b_1_3.png" self.IconData=None self.Tags=['energy','glyph'] self.Costs = 820 self.Description="Increases your Spell Cooldown Reduction by 0.655%" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Cooldown_Reduction += 0.655 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Quintessence of Alacrity" self.Icon="bl_3_3.png" self.IconData=None self.Tags=['attack_speed','quintessence'] self.Costs = 1025 self.Description="Increases your Attack Speed by 3.4%" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Attack_Speed_Percentage += 3.4 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Mark of Resilience" self.Icon="r_1_3.png" self.IconData=None self.Tags=['armor','mark'] self.Costs = 205 self.Description="Increases your Armor by 0.91" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Armor += 0.91 self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Seal of Defense" self.Icon="y_2_3.png" self.IconData=None self.Tags=['energy','seal'] self.Costs = 820 self.Description="Increases your Armor by 0.15 per Level" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Armor += 0.15 * self.parent.Level self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
class Rune(): def __init__(self): self.parent=None self.Name="Seal of Knowledge" self.Icon="y_2_3.png" self.IconData=None self.Tags=['mana','seal'] self.Costs = 410 self.Description="Increases your Mana by 1.17 per level" self.RichText_Description="" self.LoadIcons() self.Custom() def LoadIcons(self): f = open('images/runes/%s' % (self.Icon)) self.IconData = f.read() f.close() def UpdateStats(self): self.parent.Mana += 1.17 * self.parent.Level self.UpdateStats_Custom() def Custom(self): pass def UpdateStats_Custom(self): pass
Python
from ftllibs.champions import * import sys import re import copy class Champs(): def __init__(self,parent): self.parent=parent self.CHAMPS={} self.ChampIndex=[] self.ModuleIndex=[] for i in sys.modules.keys(): m = re.match('ftllibs.champions.(c_\w+)',i) if m: self.ModuleIndex.append(m.groups(0)[0]) self.InitChamps() self.CreateLists() def InitChamps(self): temp=[] for j in self.ModuleIndex: cmd = "temp.append(%s.Champ())" % (j) exec cmd for x in temp: cid = x.ID self.ChampIndex.append(str(cid)) self.CHAMPS[str(cid)]=x def GetChamp(self,champid): return self.CHAMPS[str(champid)] def GetChampCopy(self,champid): return copy.deepcopy(self.CHAMPS[str(champid)]) def CreateLists(self): self.ChampList=[] self.ChampName2ID={} self.ChampID2Name={} for ChampID in self.ChampIndex: self.ChampList.append(self.CHAMPS[ChampID].Name) self.ChampID2Name[ChampID]=self.CHAMPS[ChampID].Name self.ChampName2ID[self.CHAMPS[ChampID].Name]=ChampID def GetChampList(self): return sorted(self.ChampList) def GetChampID(self,name): return int(self.ChampName2ID[str(name)]) def GetChampName(self,champid): print "champID:", champid return str(self.ChampID2Name[str(champid)])
Python
import sys from .. FTL import ITEMS from .. FTL import MASTERIES class Champ: def __init__(self): self.ID=84 self.Name="Akali" self.InternalName="akali" self.Title="The Fist of Shadow" self.Icon="Akali.png" self.IconData=None self.IconSmall="84.jpg" self.IconSmallData=None self.Level=1 self.Build={'1':False,'2':False,'3':False,'4':False,'5':False,'6':False} self.Masteries={} self.BaseAttack_Damage=53 self.BaseAttack_Damage_delta=3.2 self.Attack_Damage=0.0 self.BaseHealth=445 self.BaseHealth_delta = 85 self.Health=0 self.BaseMana=200 self.BaseMana_delta = 30 self.Mana=0 self.BaseMovement_Speed=325 self.Movement_Speed=0 self.BaseArmor=16.5 self.BaseArmor_delta = 3.5 self.Armor=0 self.BaseMagic_Resist=30 self.BaseMagic_Resist_delta = 1.25 self.Magic_Resist=0 self.BaseHealth_Regen_per_5_seconds=7.25 self.BaseHealth_Regen_delta = 0.65 self.Health_Regen_per_5_seconds=0 self.BaseMana_Regen_per_5_seconds=50 self.BaseMana_Regen_delta = 0 self.Mana_Regen_per_5_seconds=0 self.BaseAbility_Power=0 self.Ability_Power=0 self.BaseSpell_Vamp=0 self.Spell_Vamp=0 self.BaseAttack_Speed=0.694 self.BaseAttack_Speed_delta=3.1 self.Attack_Speed=0 self.BaseLife_Steal=0 self.Life_Steal=0 self.BaseCooldown_Reduction=0 self.Cooldown_Reduction=0 self.BaseCritical_Strike_Chance=0 self.Critical_Strike_Chance=0 self.BaseMagic_Penetration_Flat=0 self.BaseMagic_Penetration_Percentage=0 self.Magic_Penetration_Flat=0 self.Magic_Penetration_Percentage=0 self.BaseArmor_Penetration_Flat=0 self.BaseArmor_Penetration_Percentage=0 self.Armor_Penetration_Flat=0 self.Armor_Penetration_Percentage=0 self.ManaIsSpecial=True # Percentage Bonuses self.Movement_Speed_Percentage=0 self.Attack_Damage_Percentage=0 self.Mana_Percentage=0 self.Ability_Power_Percentage=0 self.Attack_Speed_Percentage=0 self.Health_Percentage=0 self.Tenacity=False # specials for masteries self.SummonersWrath=False self.SummonersResolve=False self.SummonersInsight=False self.ExtraMinionDamage=0 self.Demolitionist=False self.BasePhysical_Damage_Percentage=0 self.Physical_Damage_Percentage=0 self.BaseMagical_Damage_Percentage=0 self.Magical_Damage_Percentage=0 self.Executioner=False self.ToughSkin=0 self.Indomitable=0 self.Evasion=0 self.BladedArmor=False self.SiegeCommander=False self.Juggernaut=False self.Mastermind=False # score self.CreepScore=0 self.Kills=0 self.Deaths=0 self.Assists=0 # Skills self.Skill_Q_Name="Mark of the Assassin" self.Skill_Q_Icon="84-1.jpg" self.Skill_Q_MaxStack=False self.Skill_Q_Stack=0 self.Skill_Q_Level=False self.Skill_Q_has_Passive=False self.Skill_Q_Cooldown=[6,5.5,5,4.5,4] self.Skill_Q_Cost=[60,60,60,60,60] self.Skill_Q_Priority=[] self.Skill_W_Name="Twilight Shroud" self.Skill_W_Icon="84-2.jpg" self.Skill_W_MaxStack=False self.Skill_W_Stack=0 self.Skill_W_Level=False self.Skill_W_has_Passive=False self.Skill_W_Cooldown=[20,20,20,20,20] self.Skill_W_Cost=[80,75,70,65,60] self.Skill_W_Priority=[] self.Skill_E_Name="Crescent Slash" self.Skill_E_Icon="84-3.jpg" self.Skill_E_MaxStack=False self.Skill_E_Stack=0 self.Skill_E_Level=False self.Skill_E_has_Passive=False self.Skill_E_Cooldown=[7,6,5,4,3] self.Skill_E_Cost=[60,55,50,45,40] self.Skill_E_Priority=[] self.Skill_R_Name="Shadow Dance" self.Skill_R_Icon="84-4.jpg" self.Skill_R_MaxStack=False self.Skill_R_Stack=0 self.Skill_R_Level=False self.Skill_R_has_Passive=False self.Skill_R_Cooldown=[2,1.5,1] self.Skill_R_Cost=[1,1,1,1,1] self.Skill_R_Priority=[] self.Skill_P_Name="Twin Disciplines" self.Skill_P_Icon="84-5.jpg" self.Skill_P_MaxStack=3 self.Skill_P_Stack=0 self.Skill_P_Level=False self.Skill_P_has_Passive=True self.Skill_P_Cooldown=[] self.Skill_P_Cost=[] self.Skill_P_Priority=[] self.LoadIcons() self.Custom() self.CalcStats() self.ResetCurrentStats() def ResetStats(self): self.Custom() self.Attack_Damage=self.BaseAttack_Damage + self.BaseAttack_Damage_delta * self.Level self.Health=self.BaseHealth + self.BaseHealth_delta * self.Level self.Mana=self.BaseMana + self.BaseMana_delta * self.Level self.Health=self.BaseHealth + self.BaseHealth_delta * self.Level self.Movement_Speed=self.BaseMovement_Speed self.Armor=self.BaseArmor + self.BaseArmor_delta * self.Level self.Magic_Resist=self.BaseMagic_Resist + self.BaseMagic_Resist_delta * self.Level self.Health_Regen_per_5_seconds=self.BaseHealth_Regen_per_5_seconds + self.BaseHealth_Regen_delta * self.Level self.Mana_Regen_per_5_seconds=self.BaseMana_Regen_per_5_seconds + self.BaseMana_Regen_delta * self.Level self.Ability_Power=0 self.Ability_Power_Percentage=0 self.Spell_Vamp=self.BaseSpell_Vamp self.Attack_Speed=self.BaseAttack_Speed * (1.0+((self.BaseAttack_Speed_delta * self.Level)/100)) self.Attack_Speed_Percentage=0 self.Life_Steal=self.BaseLife_Steal self.Cooldown_Reduction=0 self.Armor_Penetration_Flat=self.BaseArmor_Penetration_Flat self.Armor_Penetration_Percentage=self.BaseArmor_Penetration_Percentage self.Critical_Strike_Chance=0 self.Magic_Penetration_Flat=self.BaseMagic_Penetration_Flat self.Magic_Penetration_Percentage=self.BaseMagic_Penetration_Percentage self.Physical_Damage_Percentage=self.BasePhysical_Damage_Percentage self.Magical_Damage_Percentage=self.BaseMagical_Damage_Percentage def LoadIcons(self): print "c_poppy: LoadIcons: Called" f = open('images/champs/%s' % (self.Icon)) self.IconData = f.read() f.close() f = open('images/champs/small/%s' % (self.IconSmall)) self.IconSmallData = f.read() f.close() print "c_poppy: LoadIcons: Done" def ResetCurrentStats(self): self.CurrentHealth = self.Health self.CurrentMana = self.Mana def SetChampLevel(self,level): self.Level=int(level) self.CalcStats() def SetMasteries(self,masteries): self.Masteries=masteries self.CalcStats() def DumpStats(self): print "Attack_Damage ", self.Attack_Damage print "Health ", self.Health print "Mana ", self.Mana print "Movement_Speed " ,self.Movement_Speed print "Armor ", self.Armor print "Magic_Resist ", self.Magic_Resist print "Health_Regen ", self.Health_Regen_per_5_seconds print "Mana_Regen ", self.Mana_Regen_per_5_seconds print "Ability_Power ", self.Ability_Power print "Spell_Vamp ", self.Spell_Vamp print "Attack_Speed ", self.Attack_Speed print "Life_Steal ", self.Life_Steal print "Cooldown_Reduction ", self.Cooldown_Reduction print "Armor_Penetration_Flat ", self.Armor_Penetration_Flat print "Magic_Penetration_Flat ", self.Magic_Penetration_Flat print "Armor_Penetration_Percentage ", self.Armor_Penetration_Percentage print "Magic_Penetration_Percentage ", self.Magic_Penetration_Percentage print "Critical_Strike_Chance ", self.Critical_Strike_Chance print "Move_Speed_Percentage ", self.Movement_Speed_Percentage print "Attack_Speed_Percentage ", self.Attack_Speed_Percentage print "Physical_Damage_Percentage ", self.Physical_Damage_Percentage print "Magical_Damage_Percentage ",self.Magical_Damage_Percentage print "-------- Skills -------" self.Skill_Q(True) self.Skill_W(True) self.Skill_E(True) self.Skill_R(True) def CalcStats(self): # Reset stats self.ResetStats() # Add Runes #self.ProcessRunes() # Add Masteries MASTERIES.UpdateStats(self) #self.ProcessMasteries() # loop through skills passives self.Skill_Q(False) self.Skill_W(False) self.Skill_E(False) self.Skill_R(False) # loop through items for item in self.Build.itervalues(): if item: item.UpdateStats() self.Skill_P(False) self.CustomCalcStats() # Percentage Bonuses self.Movement_Speed = self.Movement_Speed * (1+self.Movement_Speed_Percentage/100) self.Attack_Damage = self.Attack_Damage * (1+self.Attack_Damage_Percentage/100) self.Attack_Speed = self.Attack_Speed * (1+self.Attack_Speed_Percentage/100) self.Mana = self.Mana * (1+self.Mana_Percentage/100) self.Ability_Power = self.Ability_Power * (1+self.Ability_Power_Percentage/100) self.Health = self.Health * (1+self.Health_Percentage/100) self.Power_Percentage=0 self.Health_Percentage=0 # Limits Check if self.Attack_Speed > 2.50: self.Attack_Speed=2.50 if self.Cooldown_Reduction > 40.0: self.Cooldown_Reduction=40.0 def AddItem(self,pos,itemid): self.Build[pos]=ITEMS.GetItem(itemid) self.Build[pos].parent=self self.CalcStats() def DelItem(self,pos): self.Build[pos]=False self.CalcStats() def ClearBuild(self): for i in range(1,7): self.Build[str(i)]=False self.CalcStats() def Custom(self): pass def CustomCalcStats(self): pass def Skill_Q(self,active): DAMAGE={} DAMAGE['physical']=0 DAMAGE['magical']=0 DAMAGE['true']=0 return DAMAGE def Skill_W(self,active): DAMAGE={} DAMAGE['physical']=0 DAMAGE['magical']=0 DAMAGE['true']=0 return DAMAGE def Skill_E(self,active): DAMAGE={} DAMAGE['physical']=0 DAMAGE['magical']=0 DAMAGE['true']=0 return DAMAGE def Skill_R(self,active): DAMAGE={} DAMAGE['physical']=0 DAMAGE['magical']=0 DAMAGE['true']=0 return DAMAGE def Skill_P(self,active): DAMAGE={} DAMAGE['physical']=0 DAMAGE['magical']=0 DAMAGE['true']=0 if (self.Ability_Power - self.BaseAbility_Power) >= 19.5: percent = 7.916 percent += int((self.Ability_Power - self.BaseAbility_Power - 19.5)/6) dmg = (self.Attack_Damage/100) * percent self.disciplinesofforcebonusdamage = dmg temp = self.BaseAttack_Damage + self.BaseAttack_Damage_delta * self.Level if (self.Attack_Damage - temp) >= 9.5: percent = 7.916 percent += int((self.Attack_Damage - temp - 9.5)/6) print percent spellvamp = (self.Attack_Damage/100) * percent self.Spell_Vamp += spellvamp return DAMAGE def AADamage(self): DAMAGE={} DAMAGE['physical']=self.Attack_Damage DAMAGE['physical'] *= (1 + self.Physical_Damage_Percentage/100) DAMAGE['magical']=self.disciplinesofforcebonusdamage DAMAGE['true']=0 return DAMAGE
Python
import os import sys import re __all__ = [] dirList=os.listdir(sys.path[0] + "/ftllibs/champions") for i in dirList: m = re.match("(c_\w+?).py$",i) if m: __all__.append(m.groups()[0])
Python
import sys from .. FTL import ITEMS from .. FTL import MASTERIES class Champ: def __init__(self): self.ID=78 self.Name="Poppy" self.InternalName="poppy" self.Title="The Iron Ambassador" self.Icon="Poppy.png" self.IconData=None self.IconSmall="78.jpg" self.IconSmallData=None self.Level=1 self.Build={'1':False,'2':False,'3':False,'4':False,'5':False,'6':False} self.Masteries={} self.BaseAttack_Damage=56.3 self.BaseAttack_Damage_delta=3.375 self.Attack_Damage=0.0 self.BaseHealth=423 self.BaseHealth_delta = 81 self.Health=0 self.BaseMana=185 self.BaseMana_delta = 30 self.Mana=0 self.BaseMovement_Speed=320 self.Movement_Speed=0 self.BaseArmor=18 self.BaseArmor_delta = 4 self.Armor=0 self.BaseMagic_Resist=30 self.BaseMagic_Resist_delta = 0 self.Magic_Resist=0 self.BaseHealth_Regen_per_5_seconds=7.45 self.BaseHealth_Regen_delta = 0.55 self.Health_Regen_per_5_seconds=0 self.BaseMana_Regen_per_5_seconds=6.4 self.BaseMana_Regen_delta = 0.45 self.Mana_Regen_per_5_seconds=0 self.BaseAbility_Power=0 self.Ability_Power=0 self.BaseSpell_Vamp=0 self.Spell_Vamp=0 self.BaseAttack_Speed=0.638 self.BaseAttack_Speed_delta=3.35 self.Attack_Speed=0 self.BaseLife_Steal=0 self.Life_Steal=0 self.BaseCooldown_Reduction=0 self.Cooldown_Reduction=0 self.BaseCritical_Strike_Chance=0 self.Critical_Strike_Chance=0 self.BaseMagic_Penetration_Flat=0 self.BaseMagic_Penetration_Percentage=0 self.Magic_Penetration_Flat=0 self.Magic_Penetration_Percentage=0 self.BaseArmor_Penetration_Flat=0 self.BaseArmor_Penetration_Percentage=0 self.Armor_Penetration_Flat=0 self.Armor_Penetration_Percentage=0 # Percentage Bonuses self.Movement_Speed_Percentage=0 self.Attack_Damage_Percentage=0 self.Mana_Percentage=0 self.Ability_Power_Percentage=0 self.Attack_Speed_Percentage=0 self.Health_Percentage=0 self.Tenacity=False # specials for masteries self.SummonersWrath=False self.SummonersResolve=False self.SummonersInsight=False self.ExtraMinionDamage=0 self.Demolitionist=False self.BasePhysical_Damage_Percentage=0 self.Physical_Damage_Percentage=0 self.BaseMagical_Damage_Percentage=0 self.Magical_Damage_Percentage=0 self.Executioner=False self.ToughSkin=0 self.Indomitable=0 self.Evasion=0 self.BladedArmor=False self.SiegeCommander=False self.Juggernaut=False self.Mastermind=False # score self.CreepScore=0 self.Kills=0 self.Deaths=0 self.Assists=0 # Skills self.Skill_Q_Name="Devastating Blow" self.Skill_Q_Icon="78-1.jpg" self.Skill_Q_MaxStack=False self.Skill_Q_Stack=0 self.Skill_Q_Level=False self.Skill_Q_has_Passive=False self.Skill_Q_Cooldown=[] self.Skill_Q_Cost=[] self.Skill_Q_Priority=[] self.Skill_W_Name="Paragon of Demacia" self.Skill_W_Icon="78-2.jpg" self.Skill_W_MaxStack=False self.Skill_W_Stack=0 self.Skill_W_Level=False self.Skill_W_has_Passive=False self.Skill_W_Cooldown=[] self.Skill_W_Cost=[] self.Skill_W_Priority=[] self.Skill_E_Name="Heroic Charge" self.Skill_E_Icon="78-3.jpg" self.Skill_E_MaxStack=False self.Skill_E_Stack=0 self.Skill_E_Level=False self.Skill_E_has_Passive=False self.Skill_E_Cooldown=[] self.Skill_E_Cost=[] self.Skill_E_Priority=[] self.Skill_R_Name="Diplomatic Immunity" self.Skill_R_Icon="78-4.jpg" self.Skill_R_MaxStack=False self.Skill_R_Stack=0 self.Skill_R_Level=False self.Skill_R_has_Passive=False self.Skill_R_Cooldown=[] self.Skill_R_Cost=[] self.Skill_R_Priority=[] self.Skill_P_Name="Valiant Fighter" self.Skill_P_Icon="78-5.jpg" self.Skill_P_MaxStack=False self.Skill_P_Stack=0 self.Skill_P_Level=False self.Skill_P_has_Passive=False self.Skill_P_Cooldown=[] self.Skill_P_Cost=[] self.Skill_P_Priority=[] self.LoadIcons() self.Custom() self.CalcStats() self.ResetCurrentStats() def LoadIcons(self): print "c_poppy: LoadIcons: Called" f = open('images/champs/%s' % (self.Icon)) self.IconData = f.read() f.close() f = open('images/champs/small/%s' % (self.IconSmall)) self.IconSmallData = f.read() f.close() print "c_poppy: LoadIcons: Done" def ResetStats(self): self.Custom() self.Attack_Damage=self.BaseAttack_Damage + self.BaseAttack_Damage_delta * self.Level self.Health=self.BaseHealth + self.BaseHealth_delta * self.Level self.Mana=self.BaseMana + self.BaseMana_delta * self.Level self.Health=self.BaseHealth + self.BaseHealth_delta * self.Level self.Movement_Speed=self.BaseMovement_Speed self.Armor=self.BaseArmor + self.BaseArmor_delta * self.Level self.Magic_Resist=self.BaseMagic_Resist + self.BaseMagic_Resist_delta * self.Level self.Health_Regen_per_5_seconds=self.BaseHealth_Regen_per_5_seconds + self.BaseHealth_Regen_delta * self.Level self.Mana_Regen_per_5_seconds=self.BaseMana_Regen_per_5_seconds + self.BaseMana_Regen_delta * self.Level self.Ability_Power=0 self.Ability_Power_Percentage=0 self.Spell_Vamp=self.BaseSpell_Vamp self.Attack_Speed=self.BaseAttack_Speed * (1.0+((self.BaseAttack_Speed_delta * self.Level)/100)) self.Attack_Speed_Percentage=0 self.Life_Steal=self.BaseLife_Steal self.Cooldown_Reduction=0 self.Armor_Penetration_Flat=self.BaseArmor_Penetration_Flat self.Armor_Penetration_Percentage=self.BaseArmor_Penetration_Percentage self.Critical_Strike_Chance=0 self.Magic_Penetration_Flat=self.BaseMagic_Penetration_Flat self.Magic_Penetration_Percentage=self.BaseMagic_Penetration_Percentage self.Physical_Damage_Percentage=self.BasePhysical_Damage_Percentage self.Magical_Damage_Percentage=self.BaseMagical_Damage_Percentage def ResetCurrentStats(self): self.CurrentHealth = self.Health self.CurrentMana = self.Mana def SetChampLevel(self,level): self.Level=int(level) self.CalcStats() def SetMasteries(self,masteries): self.Masteries=masteries self.CalcStats() def DumpStats(self): print "Attack_Damage ", self.Attack_Damage print "Health ", self.Health print "Mana ", self.Mana print "Movement_Speed " ,self.Movement_Speed print "Armor ", self.Armor print "Magic_Resist ", self.Magic_Resist print "Health_Regen ", self.Health_Regen_per_5_seconds print "Mana_Regen ", self.Mana_Regen_per_5_seconds print "Ability_Power ", self.Ability_Power print "Spell_Vamp ", self.Spell_Vamp print "Attack_Speed ", self.Attack_Speed print "Life_Steal ", self.Life_Steal print "Cooldown_Reduction ", self.Cooldown_Reduction print "Armor_Penetration_Flat ", self.Armor_Penetration_Flat print "Magic_Penetration_Flat ", self.Magic_Penetration_Flat print "Armor_Penetration_Percentage ", self.Armor_Penetration_Percentage print "Magic_Penetration_Percentage ", self.Magic_Penetration_Percentage print "Critical_Strike_Chance ", self.Critical_Strike_Chance print "Move_Speed_Percentage ", self.Movement_Speed_Percentage print "Attack_Speed_Percentage ", self.Attack_Speed_Percentage print "Physical_Damage_Percentage ", self.Physical_Damage_Percentage print "Magical_Damage_Percentage ",self.Magical_Damage_Percentage print "-------- Skills -------" self.Skill_Q(True) self.Skill_W(True) self.Skill_E(True) self.Skill_R(True) def CalcStats(self): # Reset stats self.ResetStats() # Add Runes #self.ProcessRunes() # Add Masteries MASTERIES.UpdateStats(self) #self.ProcessMasteries() # loop through skills passives self.Skill_Q(False) self.Skill_W(False) self.Skill_E(False) self.Skill_R(False) self.Skill_P(False) # loop through items for item in self.Build.itervalues(): if item: item.UpdateStats() self.CustomCalcStats() # Percentage Bonuses self.Movement_Speed = self.Movement_Speed * (1+self.Movement_Speed_Percentage/100) self.Attack_Damage = self.Attack_Damage * (1+self.Attack_Damage_Percentage/100) self.Attack_Speed = self.Attack_Speed * (1+self.Attack_Speed_Percentage/100) self.Mana = self.Mana * (1+self.Mana_Percentage/100) print "APP: ",self.Ability_Power_Percentage self.Ability_Power = self.Ability_Power * (1+float(self.Ability_Power_Percentage)/100.0) print "AP;", self.Ability_Power self.Health = self.Health * (1+self.Health_Percentage/100) self.Power_Percentage=0 self.Health_Percentage=0 # Limits Check if self.Attack_Speed > 2.50: self.Attack_Speed=2.50 if self.Cooldown_Reduction > 40.0: self.Cooldown_Reduction=40.0 def AddItem(self,pos,itemid): self.Build[pos]=ITEMS.GetItem(itemid) self.Build[pos].parent=self self.CalcStats() def DelItem(self,pos): self.Build[pos]=False self.CalcStats() def ClearBuild(self): for i in range(1,7): self.Build[str(i)]=False self.CalcStats() def Custom(self): pass def CustomCalcStats(self): pass def Skill_Q(self,active): NMYMaxHealth=2000.0 DAMAGE={} DAMAGE['physical']=0 DAMAGE['magical']=0 DAMAGE['true']=0 if active: bonus=NMYMaxHealth * 0.08 if bonus > (75*self.Skill_Q_Level): bonus=75*self.Skill_Q_Level DAMAGE['magical']=self.Attack_Damage + self.Ability_Power*0.6 + 20*self.Skill_Q_MaxStack + bonus DAMAGE['magical'] *= (1 + self.Magical_Damage_Percentage/100) print "Q:", DAMAGE return DAMAGE def Skill_W(self,active): NMYMaxHealth=2000.0 DAMAGE={} DAMAGE['physical']=0 DAMAGE['magical']=0 DAMAGE['true']=0 if active: self.Armor += (1.0 + 0.5*self.Skill_W_Level)*self.Skill_W_MaxStack self.Attack_Damage += (1.0 + 0.5*self.Skill_W_Level)*self.Skill_W_MaxStack self.Movement_Speed += 15.0 + 2.0*self.Skill_W_Level else: self.Armor += (1.0 + 0.5*self.Skill_W_Level)*self.Skill_W_MaxStack self.Attack_Damage += (1.0 + 0.5*self.Skill_W_Level)*self.Skill_W_MaxStack #print DAMAGE return DAMAGE def Skill_E(self,active): NMYMaxHealth=2000.0 DAMAGE={} DAMAGE['physical']=0 DAMAGE['magical']=0 DAMAGE['true']=0 if active: DAMAGE['magical'] += 25.0 + 25.0*self.Skill_E_Level + self.Ability_Power*0.4 + 25.0 + 50.0*self.Skill_E_Level + self.Ability_Power*0.4 DAMAGE['magical'] *= (1 + self.Magical_Damage_Percentage/100) print "E:", DAMAGE return DAMAGE def Skill_R(self,active): NMYMaxHealth=2000.0 DAMAGE={} DAMAGE['physical']=0 DAMAGE['magical']=0 DAMAGE['true']=0 if active: self.Movement_Speed += 10.0 + 10.0*self.Skill_R_Level return DAMAGE def Skill_P(self,active): DAMAGE={} DAMAGE['physical']=0 DAMAGE['magical']=0 DAMAGE['true']=0 return DAMAGE def AADamage(self): DAMAGE={} DAMAGE['physical']=self.Attack_Damage DAMAGE['physical'] *= (1 + self.Physical_Damage_Percentage/100) DAMAGE['magical']=0 DAMAGE['true']=0 return DAMAGE
Python
class Masteries(object): def __init__(self,parent): self.Masteries={} self.parent=parent self.InitMasteriesLimitList() self.InitOffensiveMasteriesList() self.InitDefensiveMasteriesList() self.InitUtilityMasteriesList() def SetMasteries(self,mastery): self.Masteries=mastery def InitMasteriesLimitList(self): self.MasteriesLimitList={} self.MasteriesLimitList["SummonersWrath"]=1 self.MasteriesLimitList["BruteForce"]=3 self.MasteriesLimitList["MentalForce"]=4 self.MasteriesLimitList["Butcher"]=2 self.MasteriesLimitList["Alacrity"]=4 self.MasteriesLimitList["Sorcery"]=4 self.MasteriesLimitList["Demolitionist"]=1 self.MasteriesLimitList["Deadliness"]=4 self.MasteriesLimitList["WeaponsExpertise"]=1 self.MasteriesLimitList["ArcaneKnowledge"]=1 self.MasteriesLimitList["Havoc"]=3 self.MasteriesLimitList["Lethality"]=1 self.MasteriesLimitList["Vampirism"]=3 self.MasteriesLimitList["Blast"]=4 self.MasteriesLimitList["Sunder"]=3 self.MasteriesLimitList["Archmage"]=4 self.MasteriesLimitList["Executioner"]=1 self.MasteriesLimitList["SummonersResolve"]=1 self.MasteriesLimitList["Resistance"]=3 self.MasteriesLimitList["Hardiness"]=3 self.MasteriesLimitList["ToughSkin"]=2 self.MasteriesLimitList["Durability"]=4 self.MasteriesLimitList["Vigor"]=3 self.MasteriesLimitList["Indomitable"]=2 self.MasteriesLimitList["VeteransScars"]=1 self.MasteriesLimitList["Evasion"]=3 self.MasteriesLimitList["BladedArmor"]=1 self.MasteriesLimitList["SiegeCommander"]=1 self.MasteriesLimitList["Initiator"]=3 self.MasteriesLimitList["Enlightenment"]=3 self.MasteriesLimitList["HonorGuard"]=3 self.MasteriesLimitList["Mercenary"]=3 self.MasteriesLimitList["Juggernaut"]=1 self.MasteriesLimitList["SummonersInsight"]=1 self.MasteriesLimitList["GoodHands"]=3 self.MasteriesLimitList["ExpandedMind"]=3 self.MasteriesLimitList["ImprovedRecall"]=1 self.MasteriesLimitList["Swiftness"]=4 self.MasteriesLimitList["Meditation"]=3 self.MasteriesLimitList["Scout"]=1 self.MasteriesLimitList["Greed"]=4 self.MasteriesLimitList["Transmutation"]=3 self.MasteriesLimitList["RunicAffinity"]=1 self.MasteriesLimitList["Wealth"]=2 self.MasteriesLimitList["Awareness"]=4 self.MasteriesLimitList["Sage"]=1 self.MasteriesLimitList["StrengthOfSpirit"]=3 self.MasteriesLimitList["Intelligence"]=3 self.MasteriesLimitList["Mastermind"]=1 def InitOffensiveMasteriesList(self): self.OffensiveMasteriesList=[] self.OffensiveMasteriesList.append('SummonersWrath') self.OffensiveMasteriesList.append('BruteForce') self.OffensiveMasteriesList.append('MentalForce') self.OffensiveMasteriesList.append('Butcher') self.OffensiveMasteriesList.append('Alacrity') self.OffensiveMasteriesList.append('Sorcery') self.OffensiveMasteriesList.append('Demolitionist') self.OffensiveMasteriesList.append('Deadliness') self.OffensiveMasteriesList.append('WeaponsExpertise') self.OffensiveMasteriesList.append('ArcaneKnowledge') self.OffensiveMasteriesList.append('Havoc') self.OffensiveMasteriesList.append('Lethality') self.OffensiveMasteriesList.append('Vampirism') self.OffensiveMasteriesList.append('Blast') self.OffensiveMasteriesList.append('Sunder') self.OffensiveMasteriesList.append('Archmage') self.OffensiveMasteriesList.append('Executioner') def InitDefensiveMasteriesList(self): self.DefensiveMasteriesList=[] self.DefensiveMasteriesList.append('SummonersResolve') self.DefensiveMasteriesList.append('Resistance') self.DefensiveMasteriesList.append('Hardiness') self.DefensiveMasteriesList.append('ToughSkin') self.DefensiveMasteriesList.append('Durability') self.DefensiveMasteriesList.append('Vigor') self.DefensiveMasteriesList.append('Indomitable') self.DefensiveMasteriesList.append('VeteransScars') self.DefensiveMasteriesList.append('Evasion') self.DefensiveMasteriesList.append('BladedArmor') self.DefensiveMasteriesList.append('SiegeCommander') self.DefensiveMasteriesList.append('Initiator') self.DefensiveMasteriesList.append('Enlightenment') self.DefensiveMasteriesList.append('HonorGuard') self.DefensiveMasteriesList.append('Mercenary') self.DefensiveMasteriesList.append('Juggernaut') def InitUtilityMasteriesList(self): self.UtilityMasteriesList=[] self.UtilityMasteriesList.append('SummonersInsight') self.UtilityMasteriesList.append('GoodHands') self.UtilityMasteriesList.append('ExpandedMind') self.UtilityMasteriesList.append('ImprovedRecall') self.UtilityMasteriesList.append('Swiftness') self.UtilityMasteriesList.append('Meditation') self.UtilityMasteriesList.append('Scout') self.UtilityMasteriesList.append('Greed') self.UtilityMasteriesList.append('Transmutation') self.UtilityMasteriesList.append('RunicAffinity') self.UtilityMasteriesList.append('Wealth') self.UtilityMasteriesList.append('Awareness') self.UtilityMasteriesList.append('Sage') self.UtilityMasteriesList.append('StrengthOfSpirit') self.UtilityMasteriesList.append('Intelligence') self.UtilityMasteriesList.append('Mastermind') def UpdateStats(self,parent): for key,value in parent.Masteries.iteritems(): if key == "SummonersWrath" and value == "1": parent.SummonersWrath=True if key == "BruteForce": parent.Attack_Damage += int(value) if key == "MentalForce": parent.Ability_Power += int(value) if key == "Butcher": parent.ExtraMinionDamage += int(value)*2 if key == "Alacrity": parent.Attack_Speed_Percentage += int(value) if key == "Sorcery": parent.Cooldown_Reduction += int(value) if key == "Demolitionist" and value == "1": parent.Demolitionist = True if key == "Deadliness": parent.Attack_Damage += (0.125 * float(value))*parent.Level if key == "WeaponsExpertise": parent.Armor_Penetration_Percentage += 10.0 if key == "ArcaneKnowledge": parent.Magic_Penetration_Percentage += 10.0 if key == "Havoc": parent.Physical_Damage_Percentage += (0.5 * float(value)) parent.Magical_Damage_Percentage += (0.5 * float(value)) if key == "Lethality": parent.Critical_Strike_Chance += 10.0 if key == "Vampirism": parent.Life_Steal += float(value) if key == "Blast": parent.Ability_Power += (0.25 * float(value))*parent.Level if key == "Sunder": parent.Armor_Penetration_Flat += 2*int(value) if key == "Archmage": parent.Ability_Power_Percentage += 1.25 *float(value) if key == "Executioner": parent.Executioner=True # defensive if key == "SummonersResolve" and value == "1": parent.SummonersResolve=True if key == "Resistance": parent.Magic_Resist += 2*int(value) if key == "Hardiness": parent.Armor += 2*int(value) if key == "ToughSkin": parent.ToughSkin = int(value) if key == "Durability": parent.Health += (1.5 * float(value)) * parent.Level if key == "Vigor": parent.Health_Regen_per_5_seconds += int(value) if key == "Indomitable": parent.Indomitable= int(value) if key == "VeteransScars": parent.Health += 30 if key == "Evasion": parent.Evasion=int(value) if key == "BladedArmor" and value == "1": parent.BladedArmor=True if key == "SiegeCommander" and value == "1": parent.SiegeCommander=True if key == "Initiator": parent.Initiator = int(value) if key == "Enlightenment": parent.Cooldown_Reduction += (0.15 * float(value)) * parent.Level if key == "HonorGuard": parent.HonorGuard = (0.5 * float(value)) if key == "Mercenary": pass if key == "Juggernaut": parent.Juggernaut = True parent.Health_Percentage += 3 # utility if key == "SummonersInsight" and value == '1': parent.SummonersInsight=True if key == "GoodHands": pass if key == "ExpandedMind": parent.Mana += (4 * int(value)) * parent.Level # da gehoert noch engery dazu # On champions that use energy, increases energy by 4 / 7 / 10. if key == "ImprovedRecall": pass if key == "Swiftness": parent.Movement_Speed_Percentage += 0.5 * float(value) if key == "Meditation": parent.Mana_Regen_per_5_seconds += int(value) if key == "Scout": pass if key == "Greed": pass if key == "Transmutation": parent.Spell_Vamp += int(value) if key == "RunicAffinity": pass # buff +20% if key == "Wealth": pass if key == "Awareness": pass if key == "Sage": pass if key == "StrengthOfSpirit": parent.Health_Regen_per_5_seconds += ((0.1 + (0.3*float(value)))/100) * parent.Mana if key == "Intelligence": parent.Cooldown_Reduction += 2*int(value) if key == "Mastermind": parent.Mastermind = True
Python
from ftllibs.ITEMS import Items ITEMS = Items(None) from ftllibs.MASTERIES import Masteries MASTERIES = Masteries(None) from ftllibs.RUNES import Runes RUNES = Runes(None) from ftllibs.CHAMPS import Champs from ftllibs.SavedDataStore import BuildDataStore,MasteriesDataStore,RunesDataStore,RecommendedDataStore # globals CHAMPS = Champs(None) BuildDS = BuildDataStore() MasteriesDS = MasteriesDataStore() RunesDS = RunesDataStore() RecommendedDS = RecommendedDataStore()
Python
from PyQt4 import QtGui,QtCore from ftllibs.FTL import RUNES from ftllibs.ui.UI_Runes_Menu import RunesMenu from ftllibs.FTL import RunesDS class RunesTab(QtGui.QWidget): def __init__(self,parent=None): super(RunesTab,self).__init__() self.MasterLayout = QtGui.QGridLayout() self.setLayout(self.MasterLayout) self.unsaved=False self.NewRunes=True self.parent=parent self.initUI() def initUI(self): self.RunesMenu = RunesMenu() self.MasterLayout.addWidget(self.RunesMenu) self.view = QtGui.QListView() self.model=RunesDS.GetRunesDataModel() self.view.setModel(self.model) self.view.setFixedWidth(300) self.view.setContextMenuPolicy(3) # Qt.CustomContextMenu self.RunesDisplay = RunesDisplay() self.RunesNameLabel = QtGui.QLabel('<h1>New Unsaved Runes</h1>') self.AddRunesButton=QtGui.QPushButton('Add') self.SaveRunesButton=QtGui.QPushButton('Save') self.ButtonLayout=QtGui.QGridLayout() self.ButtonLayout.addWidget(self.AddRunesButton,0,0,1,2) self.ButtonLayout.addWidget(self.SaveRunesButton,1,0,1,2) self.MasterLayout.addLayout(self.ButtonLayout,0,0,1,1) self.MasterLayout.addWidget(self.view,1,0,2,1) # self.MasterLayout.addWidget(self.Build,1,2,1,1,QtCore.Qt.AlignHCenter) # self.MasterLayout.addWidget(self.NumberedStats,2,2,1,1) self.MasterLayout.addWidget(self.RunesDisplay,0,1,2,1) self.MasterLayout.addWidget(self.RunesMenu,0,2,3,1) self.AddRunesButton.clicked.connect(self.AddRunes) self.SaveRunesButton.clicked.connect(self.SaveRunes) def CustomContext(self,pos): index=self.view.indexAt(pos) if index.isValid(): self.ContextMenu.exec_(self.view.mapToGlobal(pos)) else: self.AddContextMenu.exec_(self.view.mapToGlobal(pos)) def ClearRunes(self): # self.Champ.ClearBuild() self.unsaved=True def Update(self): pass def AddRunes(self): text,ok = QtGui.QInputDialog.getText(self,'Add New Rune Page','Name your Layout:',text='Unnamed Runes') if ok: lastrow=self.model.rowCount() print "AddRunes: lastrow: ", lastrow self.model.insertRows(lastrow,1,text) index = self.model.createIndex(lastrow,0) self.view.setCurrentIndex(index) if self.NewRunes: self.NewRunes=False self.SaveRunes() self.LoadRunes() else: self.LoadRunes() def SetChampLevel(self,lvl): self.Champ.SetChampLevel(lvl) self.NumberedStats.UpdateStats() def SetChampMasteries(self,masteriesID): MID=self.MasteriesModel.getMID(masteriesID) masteries=self.MasteriesModel.loadMasteries(MID) self.Champ.SetMasteries(masteries) self.NumberedStats.UpdateStats() def DeleteRunes(self): ok = QtGui.QMessageBox.question(self,'Delete Runes',"Do you realy want to delete\nInsert Runes name here\n","Yes","No") if ok == 0: index = self.view.currentIndex() self.model.removeRows(index.row(),1) def SaveRunes(self): if self.NewRunes: self.AddRunes() else: build = self.Runes.getRunes() self.model.saveRunes(build) self.unsaved=False def LoadRunes(self): self.CheckSave() # self.Runes.clearRunes() index=self.view.currentIndex() RID=self.model.getRID(index.row()) # self.Runes.setRunes(self.model.loadRunes(RID)) self.RunesNameLabel.setText(self.Runes.Name) self.NewRunes=False self.unsaved=False def RequestClose(self): print "RunesTab -> RequestClose called" self.close() def CheckSave(self): if self.unsaved: ok = QtGui.QMessageBox.question(self,'Save Changes ?',"Do you want to save your changes ?","Yes","No") if ok == 0: self.SaveRunes() class RunesDisplay(QtGui.QWidget): def __init__(self,parent=None): super(RunesDisplay,self).__init__() self.RunesBG=QtGui.QPixmap('images/ui/RunesBG.png') self.setFixedSize(self.RunesBG.size()) self.InitRunePositions() self.InitRunes() def InitRunes(self): self.Runes={} self.Runes['mark1']=None self.Runes['mark2']=None self.Runes['mark3']=None self.Runes['mark4']=None self.Runes['mark5']=None self.Runes['mark6']=None self.Runes['mark7']=None self.Runes['mark8']=None self.Runes['mark9']=None self.Runes['seal1']=None self.Runes['seal2']=None self.Runes['seal3']=None self.Runes['seal4']=None self.Runes['seal5']=None self.Runes['seal6']=None self.Runes['seal7']=None self.Runes['seal8']=None self.Runes['seal9']=None self.Runes['glyph1']=None self.Runes['glyph2']=None self.Runes['glyph3']=None self.Runes['glyph4']=None self.Runes['glyph5']=None self.Runes['glyph6']=None self.Runes['glyph7']=None self.Runes['glyph8']=None self.Runes['glyph9']=None self.Runes['quintessence1']=None self.Runes['quintessence2']=None self.Runes['quintessence3']=None def InitRunePositions(self): self.RunePositions = {} self.RunePositions['mark1']=QtCore.QPoint(29,417) self.RunePositions['mark2']=QtCore.QPoint(103,417) self.RunePositions['mark3']=QtCore.QPoint(192,417) self.RunePositions['mark4']=QtCore.QPoint(10,353) self.RunePositions['mark5']=QtCore.QPoint(84,352) self.RunePositions['mark6']=QtCore.QPoint(151,365) self.RunePositions['mark7']=QtCore.QPoint(35,287) self.RunePositions['mark8']=QtCore.QPoint(135,300) self.RunePositions['mark9']=QtCore.QPoint(90,250) self.RuneDropRectangles = {} for runename,point in self.RunePositions.iteritems(): self.RuneDropRectangles[runename]=QtCore.QRect(self.RunePositions[runename],QtCore.QSize(64,64)) def paintEvent(self,e): painter = QtGui.QPainter(self) painter.drawPixmap(0,0,self.RunesBG) for rune,point in self.RunePositions.iteritems(): img = QtGui.QPixmap(64,64) img.loadFromData(RUNES.RUNES['r_m__resilience'].IconData) painter.drawPixmap(point,img) for rune,rec in self.RuneDropRectangles.iteritems(): painter.drawRect(rec)
Python
from PyQt4 import QtGui,QtCore #from ftllibs.FTL import CHAMPS as CHAMPS import ftllibs.FTL as FTL class ChampTab(QtGui.QWidget): S_OpenChampBuild = QtCore.pyqtSignal([int]) def __init__(self): super(ChampTab,self).__init__() self.MasterLayout = QtGui.QHBoxLayout() self.setLayout(self.MasterLayout) self.initUI() def initUI(self): CO=ChampOverview(self) CI=ChampInfo(self) self.MasterLayout.addWidget(CO) self.MasterLayout.addWidget(CI) CO.S_ChampDoubleClicked[int].connect(self.EmitOpenBuild) def EmitOpenBuild(self,ChampID): print "ChampTab -> EmitOpenBuild -> ChampID: ",ChampID self.S_OpenChampBuild.emit(ChampID) class ChampInfo(QtGui.QWidget): def __init__(self,parent): super(ChampInfo,self).__init__() self.parent=parent self.setFixedWidth(200) self.B_NewBuild = QtGui.QPushButton('New Build') self.B_LoadBuilds = QtGui.QPushButton('Load Builds') self.L_NumOfBuilds = QtGui.QLabel('Build Count: 0') self.ChampPix = QtGui.QPixmap(200,400) self.L_ChampPix= QtGui.QLabel() self.L_ChampPix.setPixmap(self.ChampPix) self.MasterLayout = QtGui.QVBoxLayout() self.MasterLayout.addWidget(self.L_ChampPix) self.MasterLayout.addWidget(self.B_NewBuild) self.MasterLayout.addWidget(self.B_LoadBuilds) self.setLayout(self.MasterLayout) class ChampOverview(QtGui.QWidget): S_ChampSelected = QtCore.pyqtSignal([int]) S_ChampDoubleClicked = QtCore.pyqtSignal([int]) # TODO: Scroll Area + wenn resized wird muss die breite ( X ) neu berechnetwerden, an der breite von self.rect und hintergrund und max_x wert neu gezeichnet,berechnet def __init__(self,parent): super(ChampOverview,self).__init__() self.parent = parent self.setMouseTracking(True) self.ChampList = FTL.CHAMPS.GetChampList() self.champcount = len(self.ChampList) self.highlight_x = 0 self.highlight_y = 0 self.Pen=QtGui.QPen() self.Pen.setColor(QtGui.QColor("#AA0000")) self.Pen.setWidth(3) # self.BG = QtGui.QPixmap(1,1) def BGImage(self): y=0 x=0 x_off=10 y_off=10 if self.rect().size().height() == 0 or self.rect().size().width() == 0: return img = QtGui.QPixmap(self.rect().size()) img.fill(QtCore.Qt.transparent) p = QtGui.QPainter(img) for i in self.ChampList: if x > 5: x=0 y+=1 p.drawPixmap(90*x+x_off,90*y+y_off,QtGui.QPixmap("images/champs/small/%s" % (FTL.CHAMPS.CHAMPS[str(FTL.CHAMPS.GetChampID(i))].IconSmall))) x += 1 p.end() self.BG=img def paintEvent(self,e): x_off=10 y_off=10 p = QtGui.QPainter(self) p.setPen(self.Pen) HighRect = QtCore.QRect() HighRect.setRect(x_off+90*(self.highlight_x),y_off+90*(self.highlight_y),80,80) p.drawPixmap(0,0,self.BG) if (self.highlight_y*6 + self.highlight_x) > self.champcount-1: pass else: p.drawRect(HighRect) def resizeEvent(self,e): self.BGImage() def mouseMoveEvent(self,e): x = e.pos().x() y = e.pos().y() x= int(x/90.0) y= int(y/90.0) if x != self.highlight_x or y != self.highlight_y: self.highlight_x = x self.highlight_y = y self.update() def mousePressEvent(self,e): temp = self.highlight_y*6 + self.highlight_x if not temp > len(self.ChampList): ChampID=FTL.CHAMPS.GetChampID(self.ChampList[temp]) print "Emit -> S_ChampSelected -> ",ChampID self.S_ChampSelected.emit(ChampID) def mouseDoubleClickEvent(self,e): temp = self.highlight_y*6 + self.highlight_x if not temp > len(self.ChampList): ChampID=FTL.CHAMPS.GetChampID(self.ChampList[temp]) print "Emit -> S_ChampDoubleClicked -> ",ChampID self.S_ChampDoubleClicked.emit(ChampID)
Python
from PyQt4 import QtGui,QtCore from ftllibs.FTL import CHAMPS as CHAMPS from ftllibs.FTL import ITEMS as ITEMS from ftllibs.FTL import RecommendedDS as RecommendedDS from ftllibs.ui.UI_ChampDisplay import UI_ChampDisplay from ftllibs.ui.UI_ItemMenu import ItemMenu import copy class RecommendedTab(QtGui.QWidget): def __init__(self,ChampID): super(RecommendedTab,self).__init__() self.MasterLayout = QtGui.QGridLayout() self.setLayout(self.MasterLayout) self.ChampID=ChampID self.Champ = CHAMPS.GetChampCopy(ChampID) self.unsaved=False self.NewBuild=True self.initUI() self.recomm={} def initUI(self): self.view = QtGui.QListView() self.model=RecommendedDS.GetRecommendedDataModel() self.view.setModel(self.model) self.view.setFixedWidth(300) self.view.setContextMenuPolicy(3) # Qt.CustomContextMenu self.BuildNameLabel = QtGui.QLabel('<h1>New Unsaved Build</h1>') self.AddButton=QtGui.QPushButton('Add') self.SaveButton=QtGui.QPushButton('Save') self.ButtonLayout=QtGui.QGridLayout() self.ButtonLayout.addWidget(self.AddButton,0,0,1,2) self.ButtonLayout.addWidget(self.SaveButton,1,0,1,2) self.ItemMenu=ItemMenu(self) self.IconAndNameLayout=QtGui.QHBoxLayout() self.ChampDisplay=UI_ChampDisplay(parent=self,ChampID=self.ChampID) print "RecommendedTab: self.ChampDisplay: ",self.ChampDisplay self.IconAndNameLayout.addWidget(self.ChampDisplay) self.MasterLayout.addWidget(self.AddButton,0,1,1,1) self.MasterLayout.addWidget(self.SaveButton,1,1,1,1) self.MasterLayout.addWidget(self.view,2,1,3,1) self.MasterLayout.addLayout(self.IconAndNameLayout,0,2,1,1,QtCore.Qt.AlignHCenter) self.Section1=RecommendedItemDisplay(self) self.Section2=RecommendedItemDisplay(self) self.Section3=RecommendedItemDisplay(self) self.Section4=RecommendedItemDisplay(self) self.MasterLayout.addWidget(self.Section1,1,2,1,1) self.MasterLayout.addWidget(self.Section2,2,2,1,1) self.MasterLayout.addWidget(self.Section3,3,2,1,1) self.MasterLayout.addWidget(self.Section4,4,2,1,1) self.MasterLayout.addWidget(self.ItemMenu,0,3,5,1) self.AddButton.clicked.connect(self.AddRecommended) self.SaveButton.clicked.connect(self.SaveRecommended) self.view.clicked.connect(self.LoadRecommended) def CustomContext(self,pos): index=self.view.indexAt(pos) if index.isValid(): self.ContextMenu.exec_(self.view.mapToGlobal(pos)) else: self.AddContextMenu.exec_(self.view.mapToGlobal(pos)) def AddRecommended(self): text,ok = QtGui.QInputDialog.getText(self,'Add New Build','Name your build:',text='Unnamed Build') if ok: lastrow=self.model.rowCount() print "AddRecommended: lastrow: ", lastrow self.model.insertRows(lastrow,1,text) index = self.model.createIndex(lastrow,0) self.view.setCurrentIndex(index) if self.NewBuild: self.NewBuild=False self.recomm=self.model.loadRecommended(self.model.CurrentRCID) self.SaveRecommended() self.LoadRecommended() else: self.LoadRecommended() def SaveRecommended(self): if self.NewBuild: self.AddRecommended() else: for i in range(1,7): self.recomm["champion"]=self.Champ.InternalName self.recomm["section1item%s" % str(i)]=self.Section1.ItemList[str(i)] self.recomm["section2item%s" % str(i)]=self.Section2.ItemList[str(i)] self.recomm["section3item%s" % str(i)]=self.Section3.ItemList[str(i)] self.recomm["section4item%s" % str(i)]=self.Section4.ItemList[str(i)] self.model.saveRecommended(self.recomm) self.unsaved=False def LoadRecommended(self): self.CheckSave() index=self.view.currentIndex() RCID=self.model.getRCID(index.row()) self.recomm=self.model.loadRecommended(RCID) sec1 = [] sec2 = [] sec3 = [] sec4 = [] for i in range(1,7): sec1.append(self.recomm["section1item%s" % str(i)]) sec2.append(self.recomm["section2item%s" % str(i)]) sec3.append(self.recomm["section3item%s" % str(i)]) sec4.append(self.recomm["section4item%s" % str(i)]) print self.recomm print sec1 self.Section1.setItems(sec1) self.Section2.setItems(sec2) self.Section3.setItems(sec3) self.Section4.setItems(sec4) self.NewBuild=False self.unsaved=False def RequestClose(self): print "BuildTab -> RequestClose called" self.close() def CheckSave(self): if self.unsaved: ok = QtGui.QMessageBox.question(self,'Save Changes ?',"Do you want to save your changes ?","Yes","No") if ok == 0: self.SaveBuild() class RecommendedItemDisplay(QtGui.QWidget): ItemChange = QtCore.pyqtSignal() def __init__(self,parent=None): super(RecommendedItemDisplay,self).__init__() # self.setAutoFillBackground(False) # self.setStyleSheet("QWidget { background-color: red }") self.parent = parent self.setFixedSize(500,74) self.setAcceptDrops(True) self.MasterLayout = QtGui.QGridLayout() self.ItemLayout = QtGui.QHBoxLayout() self.ItemLayout.setSpacing(1) self.ItemLayout.setAlignment(QtCore.Qt.AlignLeft) self.setLayout(self.MasterLayout) self.NoItemPix=QtGui.QPixmap("images/icons/cross_normal_hover.png") self.Title="" self.ItemList = {"1":"None","2":"None","3":"None","4":"None","5":"None","6":"None","7":"None","8":"None"} def paintEvent(self,e): painter = QtGui.QPainter(self) pen = QtGui.QPen() brush = QtGui.QBrush() brush.setColor(QtGui.QColor(0,0,0)) brush.setStyle(1) pen.setWidth(3) pen.setBrush(brush) pen.setColor(QtGui.QColor(0,200,0)) painter.setPen(pen) painter.drawRoundedRect(4,0,72,72,6,6) painter.drawRoundedRect(88,0,72,72,6,6) painter.drawRoundedRect(172,0,72,72,6,6) painter.drawRoundedRect(256,0,72,72,6,6) painter.drawRoundedRect(340,0,72,72,6,6) painter.drawRoundedRect(424,0,72,72,6,6) for i in range(1,7): if self.ItemList[str(i)] == "None": painter.drawPixmap(26+84*(i-1),20,self.NoItemPix) else: painter.drawPixmap(9+84*(i-1),4,ITEMS.ITEMS[self.ItemList[str(i)]].IconData.Default) def dragEnterEvent(self,e): e.accept() def mouseReleaseEvent(self,e): position = e.pos() pos = False print "BuildItemDisplay: mouseReleaseEvent: \"%s\"" % (position) if position.x() > 4 and position.x() < 72: pos = 1 elif position.x() >= 88 and position.x() < 88+77: pos = 2 elif position.x() >= 172 and position.x() < 172+77: pos = 3 elif position.x() >= 256 and position.x() < 256+77: pos = 4 elif position.x() >= 340 and position.x() < 340+77: pos = 5 elif position.x() >= 424 and position.x() < 424+77: pos = 6 if pos: self.delItem(pos) self.update() def dropEvent(self,e): item = e.mimeData().text() position = e.pos() pos = 1 print "BuildItemDisplay: drop action: \"%s\";\"%s\"" % (item,position) if position.x() > 4 and position.x() < 72: pos = 1 elif position.x() >= 88 and position.x() < 88+77: pos = 2 elif position.x() >= 172 and position.x() < 172+77: pos = 3 elif position.x() >= 256 and position.x() < 256+77: pos = 4 elif position.x() >= 340 and position.x() < 340+77: pos = 5 elif position.x() >= 424 and position.x() < 424+77: pos = 6 self.addItem(pos,item) self.update() def setItems(self,items): self.clearItems() print "RecommendedItemDisplay: setItems: 'items':" ,items for i in range(0,len(items)): itemid=items[i] if not itemid == "None": self.addItem(i,itemid) #self.Title="<h1>%s</h1>" % (items['title']) self.update() def clearItems(self): self.ItemList = {"1":"None","2":"None","3":"None","4":"None","5":"None","6":"None","7":"None","8":"None"} self.update() # self.parent.unsaved=True def addItem(self,pos,itemid): self.ItemList[str(pos)]=str(itemid) self.update() self.ItemChange.emit() self.parent.unsaved=True def delItem(self,pos): self.ItemList[str(pos)]="None" self.update() self.ItemChange.emit() self.parent.unsaved=True
Python
from PyQt4 import QtGui,QtCore from ftllibs.FTL import CHAMPS as CHAMPS class UI_SlotItemDisplay(QtGui.QWidget): def __init__(self,parent=None): super(UI_SlotItemDisplay,self).__init__() self.Champ=None self.Build=None self.IconList=[] def SetChamp(self,Champ): self.Champ=Champ self.LoadIcons() def paintEvent(self,e): # print "UI_SlotItemDisplay: paintEvent: Called" painter=QtGui.QPainter(self) for i in self.IconList: painter.drawPixmap(0,0,i) def LoadIcons(self): print "UI_SlotItemDisplay: LoadIcons: Called" self.IconList=[] print self.Champ.Build for i in range(1,7): if self.Champ.Build[str(i)] == False: continue else: pix = QtGui.QPixmap(64,64) pix.loadFromData(self.Champ.Build[str(i)].IconData) self.IconList.append(pix) self.update()
Python
from PyQt4 import QtGui,QtCore from ftllibs.FTL import CHAMPS as CHAMPS import copy class UI_ChampDisplay(QtGui.QWidget): ChampLevelChange = QtCore.pyqtSignal([str]) def __init__(self,parent=None,ChampID=None,ChampLevel=18): super(UI_ChampDisplay,self).__init__() self.Champ=parent.Champ self.ChampID=ChampID self.ChampDefaultPixmap=QtGui.QPixmap('images/ui/NoChamp.jpg') # print "Defaultpix: ",self.ChampDefaultPixmap self.ChampPixmap = QtGui.QPixmap(128,128) self.ChampPixmap.fill() # print "Champpixmap: ",self.ChampPixmap if not self.ChampID == None: self.SetChamp(self.ChampID) else: self.ChampPixmap = self.ChampDefaultPixmap # print "Defaultpix: ",self.ChampDefaultPixmap # print "Champpixmap: ",self.ChampPixmap self.ChampLevel=ChampLevel self.ChampLevelComboBox=QtGui.QComboBox(self) self.ChampLevelComboBox.addItem('1') self.ChampLevelComboBox.addItem('6') self.ChampLevelComboBox.addItem('12') self.ChampLevelComboBox.addItem('16') self.ChampLevelComboBox.addItem('18') self.ChampLevelComboBox.insertSeparator(6) self.ChampLevelComboBox.addItem('1') self.ChampLevelComboBox.addItem('2') self.ChampLevelComboBox.addItem('3') self.ChampLevelComboBox.addItem('4') self.ChampLevelComboBox.addItem('5') self.ChampLevelComboBox.addItem('6') self.ChampLevelComboBox.addItem('7') self.ChampLevelComboBox.addItem('8') self.ChampLevelComboBox.addItem('9') self.ChampLevelComboBox.addItem('10') self.ChampLevelComboBox.addItem('11') self.ChampLevelComboBox.addItem('12') self.ChampLevelComboBox.addItem('13') self.ChampLevelComboBox.addItem('14') self.ChampLevelComboBox.addItem('15') self.ChampLevelComboBox.addItem('16') self.ChampLevelComboBox.addItem('17') self.ChampLevelComboBox.addItem('18') self.setFixedSize(120,140) self.ChampLevelComboBox.move(71,91) self.ChampLevelComboBox.setCurrentIndex(4) self.ChampLevelComboBox.currentIndexChanged[str].connect(self.SetChampLevel) def SetChampLevel(self,lvl): self.ChampLevelChange.emit(lvl) def SetChamp(self,ChampID): self.ChampID=ChampID self.SetChampPixmap(self.ChampID) def SetChampPixmap(self,ChampID): self.ChampPixmap=QtGui.QPixmap(128,128) self.pix = CHAMPS.CHAMPS[str(ChampID)].IconData self.ChampPixmap.loadFromData(self.pix) self.update() def paintEvent(self,e): painter = QtGui.QPainter(self) painter.drawPixmap(0,0,self.ChampPixmap) painter.drawText(QtCore.QRectF(0,128,128,12),"%s - %s/%s/%s" % (self.Champ.CreepScore,self.Champ.Kills,self.Champ.Deaths,self.Champ.Assists),QtGui.QTextOption(QtCore.Qt.AlignCenter)) def mouseDoubleClickEvent(self,e): dlg = ScoreDialog(self) dlg.exec_() ok,cs,kills,deaths,assists = dlg.getReturn() if ok: self.Champ.CreepScore = int(cs) self.Champ.Kills = int(kills) self.Champ.Deaths = int(deaths) self.Champ.Assists = int(assists) self.update() class ScoreDialog(QtGui.QDialog): def __init__(self,parent=None): super(ScoreDialog,self).__init__() self.parent=parent self.Champ=parent.Champ self.ok=False self.MasterLayout=QtGui.QGridLayout() self.CreepScoreLayout=QtGui.QHBoxLayout() self.CreepScoreLabel=QtGui.QLabel('CreepScore:') self.CreepScoreLineEdit=QtGui.QLineEdit(str(self.Champ.CreepScore)) self.CreepScoreLayout.addWidget(self.CreepScoreLabel) self.CreepScoreLayout.addWidget(self.CreepScoreLineEdit) self.KillsLayout=QtGui.QHBoxLayout() self.KillsLabel=QtGui.QLabel('Kills:') self.KillsLineEdit=QtGui.QLineEdit(str(self.Champ.Kills)) self.KillsLayout.addWidget(self.KillsLabel) self.KillsLayout.addWidget(self.KillsLineEdit) self.DeathsLayout=QtGui.QHBoxLayout() self.DeathsLabel=QtGui.QLabel('Deaths:') self.DeathsLineEdit=QtGui.QLineEdit(str(self.Champ.Deaths)) self.DeathsLayout.addWidget(self.DeathsLabel) self.DeathsLayout.addWidget(self.DeathsLineEdit) self.AssistsLayout=QtGui.QHBoxLayout() self.AssistsLabel=QtGui.QLabel('Assists:') self.AssistsLineEdit=QtGui.QLineEdit(str(self.Champ.Assists)) self.AssistsLayout.addWidget(self.AssistsLabel) self.AssistsLayout.addWidget(self.AssistsLineEdit) self.OKButton=QtGui.QPushButton('OK') self.CancelButton=QtGui.QPushButton('Cancel') self.OKButton.clicked.connect(self.OKClicked) self.CancelButton.clicked.connect(self.CancelClicked) self.MasterLayout.addLayout(self.CreepScoreLayout,0,0) self.MasterLayout.addLayout(self.KillsLayout,1,0,1,2) self.MasterLayout.addLayout(self.DeathsLayout,2,0,1,2) self.MasterLayout.addLayout(self.AssistsLayout,3,0,1,2) self.MasterLayout.addWidget(self.OKButton,4,0,1,1) self.MasterLayout.addWidget(self.CancelButton,4,1,1,1) self.setLayout(self.MasterLayout) def OKClicked(self): self.ok = True self.close() def CancelClicked(self): self.ok= False self.close() def getReturn(self): return self.ok,int(self.CreepScoreLineEdit.text()),int(self.KillsLineEdit.text()),int(self.DeathsLineEdit.text()),int(self.AssistsLineEdit.text())
Python
from PyQt4 import QtGui,QtCore from ftllibs.FTL import CHAMPS as CHAMPS from ftllibs.FTL import ITEMS as ITEMS from ftllibs.FTL import BuildDS as BuildDS from ftllibs.FTL import MasteriesDS as MasteriesDS from ftllibs.ui.UI_ChampDisplay import UI_ChampDisplay from ftllibs.ui.UI_ItemMenu import ItemMenu import copy class BuildTab(QtGui.QWidget): def __init__(self,ChampID): super(BuildTab,self).__init__() self.MasterLayout = QtGui.QGridLayout() self.setLayout(self.MasterLayout) self.ChampID=ChampID self.Champ = CHAMPS.GetChampCopy(ChampID) self.unsaved=False self.NewBuild=True self.initUI() def initUI(self): self.view = QtGui.QListView() self.model=BuildDS.GetBuildDataModel(self.ChampID) self.view.setModel(self.model) self.view.setFixedWidth(300) self.view.setContextMenuPolicy(3) # Qt.CustomContextMenu self.BuildNameLabel = QtGui.QLabel('<h1>New Unsaved Build</h1>') self.AddBuildButton=QtGui.QPushButton('Add') self.SaveBuildButton=QtGui.QPushButton('Save') self.ButtonLayout=QtGui.QGridLayout() self.ButtonLayout.addWidget(self.AddBuildButton,0,0,1,2) self.ButtonLayout.addWidget(self.SaveBuildButton,1,0,1,2) self.ItemMenu=ItemMenu(self) self.Build=BuildDisplay(self) self.NumberedStats = NumberedStats(self) self.MasterLayout.addLayout(self.ButtonLayout,0,0,1,1) self.MasterLayout.addWidget(self.view,1,0,2,1) self.IconAndNameLayout=QtGui.QHBoxLayout() self.ChampDisplay=UI_ChampDisplay(parent=self,ChampID=self.ChampID) print "BuildTab: self.ChampDisplay: ",self.ChampDisplay self.SetChampLevel(18) self.IconAndNameLayout.addWidget(self.ChampDisplay) self.IconAndNameLayout.addWidget(self.BuildNameLabel,QtCore.Qt.AlignHCenter) self.MasterLayout.addLayout(self.IconAndNameLayout,0,2,1,1,QtCore.Qt.AlignHCenter) self.MasterLayout.addWidget(self.Build,1,2,1,1,QtCore.Qt.AlignHCenter) self.MasterLayout.addWidget(self.NumberedStats,2,2,1,1) self.MasterLayout.addWidget(self.ItemMenu,0,3,3,1) self.AddBuildButton.clicked.connect(self.AddBuild) self.SaveBuildButton.clicked.connect(self.SaveBuild) self.Build.BuildChange.connect(self.NumberedStats.UpdateStats) self.MasteriesSelect=QtGui.QComboBox() self.MasteriesModel=MasteriesDS.GetMasteriesDataModel() self.MasteriesSelect.setModel(self.MasteriesModel) self.MasteriesSelect.currentIndexChanged[int].connect(self.SetChampMasteries) self.MasterLayout.addWidget(self.MasteriesSelect,3,2,1,1) self.view.clicked.connect(self.LoadBuild) self.view.customContextMenuRequested.connect(self.CustomContext) self.ChampDisplay.ChampLevelChange.connect(self.SetChampLevel) # send to Compare Mennu self.SendToCompMenu=QtGui.QMenu(self) self.SendToCompMenu.setTitle('Compare') sendtoCompareSlot1Action = QtGui.QAction('Slot 1',self) sendtoCompareSlot2Action = QtGui.QAction('Slot 2',self) sendtoCompareSlot3Action = QtGui.QAction('Slot 3',self) sendtoCompareSlot4Action = QtGui.QAction('Slot 4',self) self.SendToCompMenu.addAction(sendtoCompareSlot1Action) self.SendToCompMenu.addAction(sendtoCompareSlot2Action) self.SendToCompMenu.addAction(sendtoCompareSlot3Action) self.SendToCompMenu.addAction(sendtoCompareSlot4Action) self.SendToVSMenu=QtGui.QMenu(self) self.SendToVSMenu.setTitle('Versus') sendtoVSPlayer1Action = QtGui.QAction('Player 1',self) sendtoVSPlayer2Action = QtGui.QAction('Player 2',self) self.SendToVSMenu.addAction(sendtoVSPlayer1Action) self.SendToVSMenu.addAction(sendtoVSPlayer2Action) # main context menu self.ContextMenu=QtGui.QMenu(self) exportToLOLAction = QtGui.QAction('Export',self) renameAction = QtGui.QAction('Rename', self) clearAction = QtGui.QAction('Clear',self) clearAction.triggered.connect(self.ClearBuild) copyAction = QtGui.QAction('Copy',self) deleteAction = QtGui.QAction('Delete',self) deleteAction.triggered.connect(self.DeleteBuild) self.ContextMenu.addMenu(self.SendToCompMenu) self.ContextMenu.addMenu(self.SendToVSMenu) self.ContextMenu.addSeparator() self.ContextMenu.addAction(exportToLOLAction) self.ContextMenu.addSeparator() self.ContextMenu.addAction(renameAction) self.ContextMenu.addAction(copyAction) self.ContextMenu.addAction(clearAction) self.ContextMenu.addSeparator() self.ContextMenu.addAction(deleteAction) # special add only context menu for non valid viewlist indexes self.AddContextMenu=QtGui.QMenu(self) addAction = QtGui.QAction('Add Build',self) self.AddContextMenu.addAction(addAction) addAction.triggered.connect(self.AddBuild) def CustomContext(self,pos): index=self.view.indexAt(pos) if index.isValid(): self.ContextMenu.exec_(self.view.mapToGlobal(pos)) else: self.AddContextMenu.exec_(self.view.mapToGlobal(pos)) def ClearBuild(self): self.Champ.ClearBuild() self.unsaved=True def Update(self): pass def AddBuild(self): text,ok = QtGui.QInputDialog.getText(self,'Add New Build','Name your build:',text='Unnamed Build') if ok: lastrow=self.model.rowCount() print "AddBuild: lastrow: ", lastrow self.model.insertRows(lastrow,1,text) index = self.model.createIndex(lastrow,0) self.view.setCurrentIndex(index) if self.NewBuild: self.NewBuild=False self.SaveBuild() self.LoadBuild() else: self.LoadBuild() def SetChampLevel(self,lvl): self.Champ.SetChampLevel(lvl) self.NumberedStats.UpdateStats() def SetChampMasteries(self,masteriesID): MID=self.MasteriesModel.getMID(masteriesID) masteries=self.MasteriesModel.loadMasteries(MID) self.Champ.SetMasteries(masteries) self.NumberedStats.UpdateStats() def DeleteBuild(self): ok = QtGui.QMessageBox.question(self,'Delete Build',"Do you realy want to delete\nInsert Build name here\n","Yes","No") if ok == 0: index = self.view.currentIndex() self.model.removeRows(index.row(),1) def SaveBuild(self): if self.NewBuild: self.AddBuild() else: build = self.Build.getBuild() self.model.saveBuild(build) self.unsaved=False def LoadBuild(self): self.CheckSave() self.Build.clearBuild() index=self.view.currentIndex() BID=self.model.getBID(index.row()) self.Build.setBuild(self.model.loadBuild(BID)) self.BuildNameLabel.setText(self.Build.Name) self.NewBuild=False self.unsaved=False def RequestClose(self): print "BuildTab -> RequestClose called" self.close() def CheckSave(self): if self.unsaved: ok = QtGui.QMessageBox.question(self,'Save Changes ?',"Do you want to save your changes ?","Yes","No") if ok == 0: self.SaveBuild() class BuildDisplay(QtGui.QWidget): BuildChange = QtCore.pyqtSignal() def __init__(self,parent): super(BuildDisplay,self).__init__() # self.setAutoFillBackground(False) # self.setStyleSheet("QWidget { background-color: red }") self.ChampID = parent.ChampID self.Champ = parent.Champ self.parent = parent self.setFixedSize(500,74) self.setAcceptDrops(True) self.MasterLayout = QtGui.QGridLayout() self.ItemLayout = QtGui.QHBoxLayout() self.ItemLayout.setSpacing(1) self.ItemLayout.setAlignment(QtCore.Qt.AlignLeft) self.setLayout(self.MasterLayout) self.BID="" self.NoItemPix=QtGui.QPixmap("images/icons/cross_normal_hover.png") self.Name="" def paintEvent(self,e): painter = QtGui.QPainter(self) pen = QtGui.QPen() brush = QtGui.QBrush() brush.setColor(QtGui.QColor(0,0,0)) brush.setStyle(1) pen.setWidth(3) pen.setBrush(brush) pen.setColor(QtGui.QColor(0,200,0)) painter.setPen(pen) painter.drawRoundedRect(4,0,72,72,6,6) painter.drawRoundedRect(88,0,72,72,6,6) painter.drawRoundedRect(172,0,72,72,6,6) painter.drawRoundedRect(256,0,72,72,6,6) painter.drawRoundedRect(340,0,72,72,6,6) painter.drawRoundedRect(424,0,72,72,6,6) for i in range(1,7): if not self.Champ.Build[str(i)]: painter.drawPixmap(26+84*(i-1),20,self.NoItemPix) else: painter.drawPixmap(9+84*(i-1),4,self.Champ.Build[str(i)].IconData.Default) def dragEnterEvent(self,e): e.accept() def mouseReleaseEvent(self,e): position = e.pos() pos = False print "BuildItemDisplay: mouseReleaseEvent: \"%s\"" % (position) if position.x() > 4 and position.x() < 72: pos = 1 elif position.x() >= 88 and position.x() < 88+77: pos = 2 elif position.x() >= 172 and position.x() < 172+77: pos = 3 elif position.x() >= 256 and position.x() < 256+77: pos = 4 elif position.x() >= 340 and position.x() < 340+77: pos = 5 elif position.x() >= 424 and position.x() < 424+77: pos = 6 if pos: self.delItem(pos) self.update() def dropEvent(self,e): item = e.mimeData().text() position = e.pos() pos = 1 print "BuildItemDisplay: drop action: \"%s\";\"%s\"" % (item,position) if position.x() > 4 and position.x() < 72: pos = 1 elif position.x() >= 88 and position.x() < 88+77: pos = 2 elif position.x() >= 172 and position.x() < 172+77: pos = 3 elif position.x() >= 256 and position.x() < 256+77: pos = 4 elif position.x() >= 340 and position.x() < 340+77: pos = 5 elif position.x() >= 424 and position.x() < 424+77: pos = 6 self.addItem(pos,item) self.update() def setBuild(self,build): self.clearBuild() print "BuildDisplay: setBuild: 'build':" ,build for i in range(1,7): itemid=build["Item%s" % (i)] if not itemid == "None": self.addItem(i,itemid) self.Name="<h1>%s</h1>" % (build['Name']) def clearBuild(self): self.Champ.ClearBuild() self.BuildChange.emit() self.update() # self.parent.unsaved=True def addItem(self,pos,itemid): self.Champ.AddItem(str(pos),itemid) self.update() self.BuildChange.emit() self.parent.unsaved=True def delItem(self,pos): self.Champ.DelItem(str(pos)) self.update() self.BuildChange.emit() self.parent.unsaved=True def getBuild(self): return self.Champ.Build class NumberedSkillDamage(QtGui.QWidget): def __init__(self,parent): super(NumberedSkillDamage,self).__init__() self.MasterLayout.QtGui.QGridLayout() self.setLayout(self.MasterLayout) self.Champ=parent.Champ self.InitUI() def InitUI(self): pass class NumberedStats(QtGui.QWidget): def __init__(self,parent): super(NumberedStats,self).__init__() self.MasterLayout=QtGui.QGridLayout() self.MasterLayout.setVerticalSpacing(30) self.setLayout(self.MasterLayout) self.Champ=parent.Champ self.InitUI() self.UpdateStats() def InitUI(self): # health self.L_Health=QtGui.QVBoxLayout() self.LBL_Health=QtGui.QLabel('Health\n') self.LE_Health=QtGui.QLineEdit() self.LE_Health.setReadOnly(True) self.LE_Health.setText('0') self.LE_Health.setMaximumWidth(100) self.L_Health.addWidget(self.LBL_Health) self.L_Health.addWidget(self.LE_Health) self.L_Health.addStretch() # mana self.L_Mana=QtGui.QVBoxLayout() self.LBL_Mana=QtGui.QLabel('Mana\n') self.LE_Mana=QtGui.QLineEdit() self.LE_Mana.setReadOnly(True) self.LE_Mana.setText('0') self.LE_Mana.setMaximumWidth(100) self.L_Mana.addWidget(self.LBL_Mana) self.L_Mana.addWidget(self.LE_Mana) self.L_Mana.addStretch() # Health Regen self.L_Health_Regen_per_5_seconds=QtGui.QVBoxLayout() self.LBL_Health_Regen_per_5_seconds=QtGui.QLabel('Health Regen\nper 5s (per 1s)') self.LE_Health_Regen_per_5_seconds=QtGui.QLineEdit() self.LE_Health_Regen_per_5_seconds.setReadOnly(True) self.LE_Health_Regen_per_5_seconds.setText('0') self.LE_Health_Regen_per_5_seconds.setMaximumWidth(100) self.L_Health_Regen_per_5_seconds.addWidget(self.LBL_Health_Regen_per_5_seconds) self.L_Health_Regen_per_5_seconds.addWidget(self.LE_Health_Regen_per_5_seconds) self.L_Health_Regen_per_5_seconds.addStretch() # Mana Regen self.L_Mana_Regen_per_5_seconds=QtGui.QVBoxLayout() self.LBL_Mana_Regen_per_5_seconds=QtGui.QLabel('Mana Regen\nper 5s (per 1s)') self.LE_Mana_Regen_per_5_seconds=QtGui.QLineEdit() self.LE_Mana_Regen_per_5_seconds.setReadOnly(True) self.LE_Mana_Regen_per_5_seconds.setText('0') self.LE_Mana_Regen_per_5_seconds.setMaximumWidth(100) self.L_Mana_Regen_per_5_seconds.addWidget(self.LBL_Mana_Regen_per_5_seconds) self.L_Mana_Regen_per_5_seconds.addWidget(self.LE_Mana_Regen_per_5_seconds) self.L_Mana_Regen_per_5_seconds.addStretch() # Attack Damage self.L_Attack_Damage=QtGui.QVBoxLayout() self.LBL_Attack_Damage=QtGui.QLabel('Attack Damage\n') self.LE_Attack_Damage=QtGui.QLineEdit() self.LE_Attack_Damage.setReadOnly(True) self.LE_Attack_Damage.setText('0') self.LE_Attack_Damage.setMaximumWidth(100) self.L_Attack_Damage.addWidget(self.LBL_Attack_Damage) self.L_Attack_Damage.addWidget(self.LE_Attack_Damage) self.L_Attack_Damage.addStretch() # Armor self.L_Armor=QtGui.QVBoxLayout() self.LBL_Armor=QtGui.QLabel('Armor\n') self.LE_Armor=QtGui.QLineEdit() self.LE_Armor.setReadOnly(True) self.LE_Armor.setText('0') self.LE_Armor.setMaximumWidth(100) self.L_Armor.addWidget(self.LBL_Armor) self.L_Armor.addWidget(self.LE_Armor) self.L_Armor.addStretch() # Ability Power self.L_Ability_Power=QtGui.QVBoxLayout() self.LBL_Ability_Power=QtGui.QLabel('Ability Power\n') self.LE_Ability_Power=QtGui.QLineEdit() self.LE_Ability_Power.setReadOnly(True) self.LE_Ability_Power.setText('0') self.LE_Ability_Power.setMaximumWidth(100) self.L_Ability_Power.addWidget(self.LBL_Ability_Power) self.L_Ability_Power.addWidget(self.LE_Ability_Power) self.L_Ability_Power.addStretch() # Magic Resist self.L_Magic_Resist=QtGui.QVBoxLayout() self.LBL_Magic_Resist=QtGui.QLabel('Magic Resist\n') self.LE_Magic_Resist=QtGui.QLineEdit() self.LE_Magic_Resist.setReadOnly(True) self.LE_Magic_Resist.setText('0') self.LE_Magic_Resist.setMaximumWidth(100) self.L_Magic_Resist.addWidget(self.LBL_Magic_Resist) self.L_Magic_Resist.addWidget(self.LE_Magic_Resist) self.L_Magic_Resist.addStretch() # Movement_speed self.L_Movement_Speed=QtGui.QVBoxLayout() self.LBL_Movement_Speed=QtGui.QLabel('Movement Speed\n') self.LE_Movement_Speed=QtGui.QLineEdit() self.LE_Movement_Speed.setReadOnly(True) self.LE_Movement_Speed.setText('0') self.LE_Movement_Speed.setMaximumWidth(100) self.L_Movement_Speed.addWidget(self.LBL_Movement_Speed) self.L_Movement_Speed.addWidget(self.LE_Movement_Speed) self.L_Movement_Speed.addStretch() # Attack_Speed self.L_Attack_Speed=QtGui.QVBoxLayout() self.LBL_Attack_Speed=QtGui.QLabel('Attack Speed\n') self.LE_Attack_Speed=QtGui.QLineEdit() self.LE_Attack_Speed.setReadOnly(True) self.LE_Attack_Speed.setText('0') self.LE_Attack_Speed.setMaximumWidth(100) self.L_Attack_Speed.addWidget(self.LBL_Attack_Speed) self.L_Attack_Speed.addWidget(self.LE_Attack_Speed) self.L_Attack_Speed.addStretch() # Spell_Vamp self.L_Spell_Vamp=QtGui.QVBoxLayout() self.LBL_Spell_Vamp=QtGui.QLabel('Spell Vamp\n') self.LE_Spell_Vamp=QtGui.QLineEdit() self.LE_Spell_Vamp.setReadOnly(True) self.LE_Spell_Vamp.setText('0') self.LE_Spell_Vamp.setMaximumWidth(100) self.L_Spell_Vamp.addWidget(self.LBL_Spell_Vamp) self.L_Spell_Vamp.addWidget(self.LE_Spell_Vamp) self.L_Spell_Vamp.addStretch() # Life_Steal self.L_Life_Steal=QtGui.QVBoxLayout() self.LBL_Life_Steal=QtGui.QLabel('Life Steal\n') self.LE_Life_Steal=QtGui.QLineEdit() self.LE_Life_Steal.setReadOnly(True) self.LE_Life_Steal.setText('0') self.LE_Life_Steal.setMaximumWidth(100) self.L_Life_Steal.addWidget(self.LBL_Life_Steal) self.L_Life_Steal.addWidget(self.LE_Life_Steal) self.L_Life_Steal.addStretch() # Cooldown_Reduction self.L_Cooldown_Reduction=QtGui.QVBoxLayout() self.LBL_Cooldown_Reduction=QtGui.QLabel('Cooldown\nReduction') self.LE_Cooldown_Reduction=QtGui.QLineEdit() self.LE_Cooldown_Reduction.setReadOnly(True) self.LE_Cooldown_Reduction.setText('0') self.LE_Cooldown_Reduction.setMaximumWidth(100) self.L_Cooldown_Reduction.addWidget(self.LBL_Cooldown_Reduction) self.L_Cooldown_Reduction.addWidget(self.LE_Cooldown_Reduction) self.L_Cooldown_Reduction.addStretch() # Armor_Penetration # Armor_Penetration self.L_Armor_Penetration=QtGui.QVBoxLayout() self.LBL_Armor_Penetration=QtGui.QLabel('Armor\nPenetration') self.LE_Armor_Penetration=QtGui.QLineEdit() self.LE_Armor_Penetration.setReadOnly(True) self.LE_Armor_Penetration.setText('0') self.LE_Armor_Penetration.setMaximumWidth(100) self.L_Armor_Penetration.addWidget(self.LBL_Armor_Penetration) self.L_Armor_Penetration.addWidget(self.LE_Armor_Penetration) self.L_Armor_Penetration.addStretch() # Magic_Penetration self.L_Magic_Penetration=QtGui.QVBoxLayout() self.LBL_Magic_Penetration=QtGui.QLabel('Magic\nPenetration') self.LE_Magic_Penetration=QtGui.QLineEdit() self.LE_Magic_Penetration.setReadOnly(True) self.LE_Magic_Penetration.setText('0') self.LE_Magic_Penetration.setMaximumWidth(100) self.L_Magic_Penetration.addWidget(self.LBL_Magic_Penetration) self.L_Magic_Penetration.addWidget(self.LE_Magic_Penetration) self.L_Magic_Penetration.addStretch() # Critical_Strike_Chance self.L_Critical_Strike_Chance=QtGui.QVBoxLayout() self.LBL_Critical_Strike_Chance=QtGui.QLabel('Critical\nStrike Chance') self.LE_Critical_Strike_Chance=QtGui.QLineEdit() self.LE_Critical_Strike_Chance.setReadOnly(True) self.LE_Critical_Strike_Chance.setText('0') self.LE_Critical_Strike_Chance.setMaximumWidth(100) self.L_Critical_Strike_Chance.addWidget(self.LBL_Critical_Strike_Chance) self.L_Critical_Strike_Chance.addWidget(self.LE_Critical_Strike_Chance) self.L_Critical_Strike_Chance.addStretch() # put into masterlayout # first row self.MasterLayout.addLayout(self.L_Health,0,0,1,1) self.MasterLayout.addLayout(self.L_Health_Regen_per_5_seconds,0,1,1,1) self.MasterLayout.addLayout(self.L_Mana,0,2,1,1) self.MasterLayout.addLayout(self.L_Mana_Regen_per_5_seconds,0,3,1,1) # second row self.MasterLayout.addLayout(self.L_Attack_Damage,1,0,1,1) self.MasterLayout.addLayout(self.L_Armor,1,1,1,1) self.MasterLayout.addLayout(self.L_Ability_Power,1,2,1,1) self.MasterLayout.addLayout(self.L_Magic_Resist,1,3,1,1) # third row self.MasterLayout.addLayout(self.L_Movement_Speed,2,0,1,1) self.MasterLayout.addLayout(self.L_Attack_Speed,2,1,1,1) self.MasterLayout.addLayout(self.L_Critical_Strike_Chance,2,2,1,1) self.MasterLayout.addLayout(self.L_Cooldown_Reduction,2,3,1,1) # fourth row self.MasterLayout.addLayout(self.L_Armor_Penetration,3,0,1,1) self.MasterLayout.addLayout(self.L_Magic_Penetration,3,1,1,1) self.MasterLayout.addLayout(self.L_Life_Steal,3,2,1,1) self.MasterLayout.addLayout(self.L_Spell_Vamp,3,3,1,1) # fifth (spacer) self.MasterLayout.setRowStretch(4,1) def setChamp(self,Champ): self.Champ = Champ self.UpdateStats() def UpdateStats(self): self.LE_Health.setText(str(self.Champ.Health)) self.LE_Mana.setText(str(self.Champ.Mana)) self.LE_Health_Regen_per_5_seconds.setText("%s (%s)" % (str(self.Champ.Health_Regen_per_5_seconds),str(self.Champ.Health_Regen_per_5_seconds/5.0))) self.LE_Mana_Regen_per_5_seconds.setText("%s (%s)" % (str(self.Champ.Mana_Regen_per_5_seconds),str(self.Champ.Mana_Regen_per_5_seconds/5.0))) self.LE_Attack_Damage.setText(str(self.Champ.Attack_Damage)) self.LE_Armor.setText(str(self.Champ.Armor)) self.LE_Ability_Power.setText(str(self.Champ.Ability_Power)) self.LE_Magic_Resist.setText(str(self.Champ.Magic_Resist)) self.LE_Magic_Penetration.setText("%s | %s" % (str(self.Champ.Magic_Penetration_Flat),str(self.Champ.Magic_Penetration_Percentage)+"%")) self.LE_Armor_Penetration.setText("%s | %s" % (str(self.Champ.Armor_Penetration_Flat),str(self.Champ.Armor_Penetration_Percentage)+"%")) self.LE_Spell_Vamp.setText(str(self.Champ.Spell_Vamp)) self.LE_Life_Steal.setText(str(self.Champ.Life_Steal)) self.LE_Movement_Speed.setText(str(self.Champ.Movement_Speed)) self.LE_Critical_Strike_Chance.setText(str(self.Champ.Critical_Strike_Chance)) self.LE_Attack_Speed.setText(str(self.Champ.Attack_Speed)) self.LE_Cooldown_Reduction.setText(str(self.Champ.Cooldown_Reduction))
Python
from PyQt4 import QtGui,QtCore from ftllibs.FTL import RUNES class RunesMenu_Button(QtGui.QWidget): clicked = QtCore.pyqtSignal(['QString']) def __init__(self,runename): super(RunesMenu_Button, self).__init__() self.runename = runename self.setFixedSize(390,84) self.setContentsMargins(0,0,0,0) self.setStyleSheet('margin: 0px;border 0px') self.initUI() def initUI(self): self.MasterLayout = QtGui.QGridLayout() self.PixMapLabel = QtGui.QLabel() # Icon # ItemIcon=ITEMS.ITEMS[self.itemid].Icon self.RunesIcon = QtGui.QPixmap() self.RunesIcon.loadFromData(RUNES.RUNES[self.runename].IconData) self.PixMapLabel.setPixmap(self.RunesIcon) # Name # RunesName=ITEMS.ITEMS[self.itemid].Name self.RunesNameLabel=QtGui.QLabel() self.RunesNameLabel.setText("<h3>%s</h3>" % (RUNES.RUNES[self.runename].Name)) self.RunesNameLabel.setStyleSheet('color: Black') self.RunesNameLabel.setFixedWidth(300) # self.RunesNameLabel.setWordWrap(True) # TotalCosts RunesDescription=str(RUNES.RUNES[self.runename].Description) self.RunesTotalCostsLabel=QtGui.QLabel() self.RunesTotalCostsLabel.setText("<h4>%s</h4>" % (RunesDescription)) self.RunesTotalCostsLabel.setStyleSheet('color: red') self.RunesTotalCostsLabel.setWordWrap(True) # Layout self.MasterLayout.addWidget(self.PixMapLabel,0,0,2,1,QtCore.Qt.AlignLeft) self.TextLayout = QtGui.QVBoxLayout() self.TextLayout.addWidget(self.RunesNameLabel) self.TextLayout.addWidget(self.RunesTotalCostsLabel) self.TextLayoutSpacer=QtGui.QHBoxLayout() self.TextLayoutSpacer.addLayout(self.TextLayout) self.TextLayoutSpacer.addStretch(1) self.MasterLayout.addLayout(self.TextLayoutSpacer,0,1,1,1,QtCore.Qt.AlignLeft) # self.MasterLayout.addWidget(self.RunesTotalCostsLabel,1,1,1,1,QtCore.Qt.AlignLeft) self.setLayout(self.MasterLayout) self.setToolTip(RUNES.RUNES[self.runename].Description) def mousePressEvent(self, event): print "RunesMenu_Button: Emitting 'clicked':\"%s\"" % (self.runename) self.clicked.emit(self.runename) def mouseMoveEvent(self,e): print "RunesMenu_Button: Emittig 'dragEvent':\"%s\"" % (self.runename) mimeData = QtCore.QMimeData() mimeData.setData('text/plain',self.runename) drag = QtGui.QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(self.RunesIcon) drag.setHotSpot(e.pos() - self.rect().topLeft()) drag.start(QtCore.Qt.IgnoreAction) ## RunesMenu ## These are All Runess in the Game, split up in tabs for each tag class RunesMenu(QtGui.QWidget): addRunesPressed = QtCore.pyqtSignal(['QString']) def __init__(self,parent=None): super(RunesMenu,self).__init__() self.MasterLayout = QtGui.QHBoxLayout() self.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Expanding) self.setLayout(self.MasterLayout) self.setFixedWidth(440) self.initUI() def initUI(self): self.RunesTabs = QtGui.QTabWidget() # defense -> health self.MarkScroll = QtGui.QScrollArea() self.MarkWidget = QtGui.QWidget() self.MarkWidget.setContentsMargins(0,0,0,0) self.MarkWidget.setStyleSheet('margin: 0px; border: 0px') self.MarkLayout = QtGui.QGridLayout() self.MarkLayout.setHorizontalSpacing(0) self.MarkLayout.setVerticalSpacing(0) self.SealScroll = QtGui.QScrollArea() self.SealWidget = QtGui.QWidget() self.SealWidget.setContentsMargins(0,0,0,0) self.SealWidget.setStyleSheet('margin: 0px; border: 0px') self.SealLayout = QtGui.QGridLayout() self.SealLayout.setHorizontalSpacing(0) self.SealLayout.setVerticalSpacing(0) self.GlyphScroll = QtGui.QScrollArea() self.GlyphWidget = QtGui.QWidget() self.GlyphWidget.setContentsMargins(0,0,0,0) self.GlyphWidget.setStyleSheet('margin: 0px; border: 0px') self.GlyphLayout = QtGui.QGridLayout() self.GlyphLayout.setHorizontalSpacing(0) self.GlyphLayout.setVerticalSpacing(0) self.QuintessenceScroll = QtGui.QScrollArea() self.QuintessenceWidget = QtGui.QWidget() self.QuintessenceWidget.setContentsMargins(0,0,0,0) self.QuintessenceWidget.setStyleSheet('margin: 0px; border: 0px') self.QuintessenceLayout = QtGui.QGridLayout() self.QuintessenceLayout.setHorizontalSpacing(0) self.QuintessenceLayout.setVerticalSpacing(0) self.Buttons = [] for i in RUNES.GetList('mark'): self.Buttons.append(RunesMenu_Button(i)) x = 0 y = 1 for i in self.Buttons: if x == 1: x = 0 y += 1 self.MarkLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.RunesMenu_Button_clicked) self.MarkWidget.setLayout(self.MarkLayout) self.MarkScroll.setWidget(self.MarkWidget) self.Buttons = [] for i in RUNES.GetList('seal'): self.Buttons.append(RunesMenu_Button(i)) x = 0 y = 1 for i in self.Buttons: if x == 1: x = 0 y += 1 self.SealLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.RunesMenu_Button_clicked) self.SealWidget.setLayout(self.SealLayout) self.SealScroll.setWidget(self.SealWidget) self.Buttons = [] for i in RUNES.GetList('glyph'): self.Buttons.append(RunesMenu_Button(i)) x = 0 y = 1 for i in self.Buttons: if x == 1: x = 0 y += 1 self.GlyphLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.RunesMenu_Button_clicked) self.GlyphWidget.setLayout(self.GlyphLayout) self.GlyphScroll.setWidget(self.GlyphWidget) self.Buttons = [] for i in RUNES.GetList('quintessence'): self.Buttons.append(RunesMenu_Button(i)) x = 0 y = 1 for i in self.Buttons: if x == 1: x = 0 y += 1 self.QuintessenceLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.RunesMenu_Button_clicked) self.QuintessenceWidget.setLayout(self.QuintessenceLayout) self.QuintessenceScroll.setWidget(self.QuintessenceWidget) self.RunesTabs.addTab(self.MarkScroll,"Marks") self.RunesTabs.addTab(self.SealScroll,"Seal") self.RunesTabs.addTab(self.GlyphScroll,"Glyph") self.RunesTabs.addTab(self.QuintessenceScroll,"Quintessence") self.MasterLayout.addWidget(self.RunesTabs) def RunesMenu_Button_clicked(self,runename): print runename self.addRunesPressed.emit(runename) #######################################################
Python
from PyQt4 import QtGui,QtCore from ftllibs.FTL import MasteriesDS from ftllibs.FTL import MASTERIES class MasteriesTab(QtGui.QWidget): def __init__(self,parent = None): super(MasteriesTab,self).__init__() self.MasterLayout = QtGui.QGridLayout() self.setLayout(self.MasterLayout) self.view = QtGui.QListView() self.model=MasteriesDS.GetMasteriesDataModel() self.view.setModel(self.model) self.MasteriesDisplay=MasteriesDisplay(self) self.AddButton = QtGui.QPushButton('Add') self.SaveButton = QtGui.QPushButton('Save') self.MasterLayout.addWidget(self.AddButton,0,0,1,1) self.MasterLayout.addWidget(self.SaveButton,1,0,1,1) self.MasterLayout.addWidget(self.view,2,0,1,1) self.DisplayGrid=QtGui.QGridLayout() self.PointsAvailableLabel = QtGui.QLabel("<h1>Points Available: %s</h1>" % (30)) self.MasteriesNameLabel=QtGui.QLabel("<h1>Unnamed Masteries</h1>") self.DisplayGrid.addWidget(self.MasteriesNameLabel,0,0,1,1) self.DisplayGrid.addWidget(self.MasteriesDisplay,1,0,1,1) self.DisplayGrid.addWidget(self.PointsAvailableLabel,2,0,1,1,QtCore.Qt.AlignRight) self.DisplayGrid.setRowStretch(3,1) self.MasterLayout.addLayout(self.DisplayGrid,0,1,3,1) self.unsaved=False self.NewMasteries=True self.AddButton.clicked.connect(self.AddMastery) self.SaveButton.clicked.connect(self.SaveMastery) self.view.clicked.connect(self.LoadMasteries) def AddMastery(self): text,ok = QtGui.QInputDialog.getText(self,'Add New Masteries','Name your Masteries setup:',text='Unsaved Masteries') if ok: lastrow=self.model.rowCount() print "AddMastery: lastrow: ", lastrow self.model.insertRows(lastrow,1,text) index = self.model.createIndex(lastrow,0) self.view.setCurrentIndex(index) if self.NewMasteries: self.NewMasteries=False self.SaveMastery() self.LoadMasteries() else: self.LoadMasteries() def DeleteMastery(self): ok = QtGui.QMessageBox.question(self,'Delete Mastery',"Do you realy want to delete: %s" % (self.MasteriesDisplay.name),"Yes","No") if ok == 0: index = self.view.currentIndex() self.model.removeRows(index.row(),1) def SaveMastery(self): if self.NewMasteries: self.AddMastery() else: masteries = self.MasteriesDisplay.GetMasteries() self.model.saveMasteries(masteries) self.unsaved=False def LoadMasteries(self): print "Load Masteries Called" self.CheckSave() # self.MasteriesDisplay.ResetMasteries() index=self.view.currentIndex() MID=self.model.getMID(index.row()) masteries=self.model.loadMasteries(MID) self.MasteriesDisplay.SetMasteries(masteries) self.MasteriesNameLabel.setText("<h1>%s</h1>" % (masteries['name'])) self.NewMasteries=False self.unsaved=False # def RequestClose(self): # print "BuildTab -> RequestClose called" # self.close() def CheckSave(self): if self.unsaved: ok = QtGui.QMessageBox.question(self,'Save Changes ?',"Do you want to save your changes ?","Yes","No") if ok == 0: self.SaveMastery() class MasteriesDisplay(QtGui.QWidget): def __init__(self,parent = None): super(MasteriesDisplay,self).__init__() self.parent=parent self.setFixedSize(828,479) self.MasteriesBG = QtGui.QPixmap('images/ui/MasteriesBG.png') self.InitClickRecs() self.InitIcons() self.TotalPoints=0 self.MaxPoints=30 self.OffensivePoints=0 self.DefensivePoints=0 self.UtilityPoints=0 self.OffensivePointsRect=QtCore.QRectF(23,444,236,26) self.DefensivePointsRect=QtCore.QRectF(297,444,236,26) self.UtilityPointsRect=QtCore.QRectF(570,444,236,26) self.pen = QtGui.QPen() self.pen.setColor(QtGui.QColor(0,240,0)) self.pen.setWidth(2) self.whitepen = QtGui.QPen() self.whitepen.setColor(QtGui.QColor(255,255,255)) self.whitepen.setWidth(2) self.redpen = QtGui.QPen() self.redpen.setColor(QtGui.QColor(240,0,0)) self.redpen.setWidth(2) self.bluepen = QtGui.QPen() self.bluepen.setColor(QtGui.QColor(0,0,240)) self.bluepen.setWidth(2) self.brush = QtGui.QBrush() self.brush.setColor(QtGui.QColor(0,0,0)) self.brush.setStyle(1) def InitIcons(self): self.IconList={} for i in self.ClickRects.keys(): self.IconList[i]=MasteriesIcon(i,MASTERIES.MasteriesLimitList[i],parent=self) self.IconList[i].move(self.ClickRects[i].x(),self.ClickRects[i].y()) self.IconList[i].LeftClicked.connect(self.addMasteryPoint) self.IconList[i].RightClicked.connect(self.removeMasteryPoint) # enable first set of icons #attack self.IconList['SummonersWrath'].SetEnable() self.IconList['BruteForce'].SetEnable() self.IconList['MentalForce'].SetEnable() self.IconList['Butcher'].SetEnable() # defense self.IconList['SummonersResolve'].SetEnable() self.IconList['Resistance'].SetEnable() self.IconList['Hardiness'].SetEnable() self.IconList['ToughSkin'].SetEnable() # utility self.IconList['SummonersInsight'].SetEnable() self.IconList['GoodHands'].SetEnable() self.IconList['ExpandedMind'].SetEnable() self.IconList['ImprovedRecall'].SetEnable() def SetMasteries(self,masteries): self.ResetMasteries() for key,value in masteries.iteritems(): print key,value if key == "MID" or key == "name" or key == "position": continue if int(value) != 0: self.IconList[key].SetEnable() for i in range(int(value)): self.addMasteryPoint(key) # self.IconList[key].currentvalue=int(value) self.update() def ResetMasteries(self): for i in self.IconList: self.IconList[i].SetDisable() self.IconList[i].currentvalue=0 self.TotalPoints=0 self.OffensivePoints=0 self.DefensivePoints=0 self.UtilityPoints=0 self.IconList['SummonersWrath'].SetEnable() self.IconList['BruteForce'].SetEnable() self.IconList['MentalForce'].SetEnable() self.IconList['Butcher'].SetEnable() # defense self.IconList['SummonersResolve'].SetEnable() self.IconList['Resistance'].SetEnable() self.IconList['Hardiness'].SetEnable() self.IconList['ToughSkin'].SetEnable() # utility self.IconList['SummonersInsight'].SetEnable() self.IconList['GoodHands'].SetEnable() self.IconList['ExpandedMind'].SetEnable() self.IconList['ImprovedRecall'].SetEnable() self.parent.PointsAvailableLabel.setText("<h1>Points Available: %s</h1>" % (30)) def addMasteryPoint(self,mastery): if self.TotalPoints < self.MaxPoints: if self.IconList[str(mastery)].addPoint(): self.TotalPoints += 1 if mastery in MASTERIES.OffensiveMasteriesList: self.OffensivePoints +=1 if mastery in MASTERIES.DefensiveMasteriesList: self.DefensivePoints +=1 if mastery in MASTERIES.UtilityMasteriesList: self.UtilityPoints += 1 self.CheckEnableStatus() self.parent.PointsAvailableLabel.setText("<h1>Points Available: %s</h1>" % (int(self.MaxPoints) - int(self.TotalPoints))) def removeMasteryPoint(self,mastery): if self.TotalPoints > 0: if self.IconList[str(mastery)].removePoint(): self.TotalPoints -= 1 if mastery in MASTERIES.OffensiveMasteriesList: self.OffensivePoints -=1 if mastery in MASTERIES.DefensiveMasteriesList: self.DefensivePoints -=1 if mastery in MASTERIES.UtilityMasteriesList: self.UtilityPoints -= 1 self.CheckEnableStatus() def GetMasteries(self): masteries = {} for i in self.IconList: masteries[i]=self.IconList[i].currentvalue return masteries def CheckEnableStatus(self): print self.OffensivePoints print self.DefensivePoints print self.UtilityPoints print self.TotalPoints if self.OffensivePoints >= 4: self.IconList['Alacrity'].SetEnable() self.IconList['Sorcery'].SetEnable() self.IconList['Demolitionist'].SetEnable() else: self.IconList['Alacrity'].SetDisable() self.IconList['Sorcery'].SetDisable() self.IconList['Demolitionist'].SetDisable() if self.OffensivePoints >= 8: self.IconList['Deadliness'].SetEnable() if self.IconList['Alacrity'].isMaxed(): self.IconList['WeaponsExpertise'].SetEnable() else: self.IconList['WeaponsExpertise'].SetDisable() if self.IconList['Sorcery'].isMaxed(): self.IconList['ArcaneKnowledge'].SetEnable() else: self.IconList['ArcaneKnowledge'].SetDisable() self.IconList['Havoc'].SetEnable() else: self.IconList['Deadliness'].SetDisable() self.IconList['WeaponsExpertise'].SetDisable() self.IconList['ArcaneKnowledge'].SetDisable() self.IconList['Havoc'].SetDisable() if self.OffensivePoints >= 12: if self.IconList['Deadliness'].isMaxed(): self.IconList['Lethality'].SetEnable() else: self.IconList['Lethality'].SetDisable() self.IconList['Vampirism'].SetEnable() self.IconList['Blast'].SetEnable() else: self.IconList['Lethality'].SetDisable() self.IconList['Vampirism'].SetDisable() self.IconList['Blast'].SetDisable() if self.OffensivePoints >= 16: self.IconList['Sunder'].SetEnable() self.IconList['Archmage'].SetEnable() else: self.IconList['Sunder'].SetDisable() self.IconList['Archmage'].SetDisable() if self.OffensivePoints >= 20: self.IconList['Executioner'].SetEnable() if self.DefensivePoints >= 4: self.IconList['Durability'].SetEnable() self.IconList['Vigor'].SetEnable() else: self.IconList['Durability'].SetDisable() self.IconList['Vigor'].SetDisable() if self.DefensivePoints >= 8: self.IconList['Indomitable'].SetEnable() self.IconList['Evasion'].SetEnable() if self.IconList['ToughSkin'].isMaxed(): self.IconList['BladedArmor'].SetEnable() else: self.IconList['BladedArmor'].SetDisable() if self.IconList['Durability'].isMaxed(): self.IconList['VeteransScars'].SetEnable() else: self.IconList['VeteransScars'].SetDisable() else: self.IconList['Indomitable'].SetDisable() self.IconList['Evasion'].SetDisable() self.IconList['BladedArmor'].SetDisable() self.IconList['VeteransScars'].SetDisable() if self.DefensivePoints >= 12: self.IconList['SiegeCommander'].SetEnable() self.IconList['Initiator'].SetEnable() self.IconList['Enlightenment'].SetEnable() else: self.IconList['SiegeCommander'].SetDisable() self.IconList['Initiator'].SetDisable() self.IconList['Enlightenment'].SetDisable() if self.DefensivePoints >= 16: self.IconList['Mercenary'].SetEnable() self.IconList['HonorGuard'].SetEnable() else: self.IconList['Mercenary'].SetDisable() self.IconList['HonorGuard'].SetDisable() if self.DefensivePoints >= 20: self.IconList['Juggernaut'].SetEnable() else: self.IconList['Juggernaut'].SetDisable() if self.UtilityPoints >= 4: self.IconList['Swiftness'].SetEnable() self.IconList['Meditation'].SetEnable() self.IconList['Scout'].SetEnable() else: self.IconList['Swiftness'].SetDisable() self.IconList['Meditation'].SetDisable() self.IconList['Scout'].SetDisable() if self.UtilityPoints >= 8: self.IconList['Greed'].SetEnable() self.IconList['Transmutation'].SetEnable() self.IconList['RunicAffinity'].SetEnable() else: self.IconList['Greed'].SetDisable() self.IconList['Transmutation'].SetDisable() self.IconList['RunicAffinity'].SetDisable() if self.UtilityPoints >= 12: if self.IconList['Greed'].isMaxed(): self.IconList['Wealth'].SetEnable() else: self.IconList['Wealth'].SetDisable() self.IconList['Awareness'].SetEnable() self.IconList['Sage'].SetEnable() else: self.IconList['Wealth'].SetDisable() self.IconList['Awareness'].SetDisable() self.IconList['Sage'].SetDisable() if self.UtilityPoints >= 16: self.IconList['StrengthOfSpirit'].SetEnable() self.IconList['Intelligence'].SetEnable() else: self.IconList['StrengthOfSpirit'].SetDisable() self.IconList['Intelligence'].SetDisable() if self.UtilityPoints >= 20: self.IconList['Mastermind'].SetEnable() else: self.IconList['Mastermind'].SetDisable() self.update() def InitClickRecs(self): self.ClickRects={} self.ClickRects['SummonersWrath']=QtCore.QRect(20,12,58,58) self.ClickRects['BruteForce']=QtCore.QRect(82,12,58,58) self.ClickRects['MentalForce']=QtCore.QRect(144,12,58,58) self.ClickRects['Butcher']=QtCore.QRect(206,12,58,58) self.ClickRects['Alacrity']=QtCore.QRect(82,82,58,58) self.ClickRects['Sorcery']=QtCore.QRect(144,82,58,58) self.ClickRects['Demolitionist']=QtCore.QRect(206,82,58,58) self.ClickRects['Deadliness']=QtCore.QRect(20,154,58,58) self.ClickRects['WeaponsExpertise']=QtCore.QRect(82,154,58,58) self.ClickRects['ArcaneKnowledge']=QtCore.QRect(144,154,58,58) self.ClickRects['Havoc']=QtCore.QRect(206,154,58,58) self.ClickRects['Lethality']=QtCore.QRect(20,226,58,58) self.ClickRects['Vampirism']=QtCore.QRect(82,226,58,58) self.ClickRects['Blast']=QtCore.QRect(144,226,58,58) self.ClickRects['Sunder']=QtCore.QRect(82,298,58,58) self.ClickRects['Archmage']=QtCore.QRect(144,298,58,58) self.ClickRects['Executioner']=QtCore.QRect(82,368,58,58) #defensive self.ClickRects['SummonersResolve']=QtCore.QRect(294,12,58,58) self.ClickRects['Resistance']=QtCore.QRect(356,12,58,58) self.ClickRects['Hardiness']=QtCore.QRect(418,12,58,58) self.ClickRects['ToughSkin']=QtCore.QRect(480,12,58,58) self.ClickRects['Durability']=QtCore.QRect(356,82,58,58) self.ClickRects['Vigor']=QtCore.QRect(418,82,58,58) self.ClickRects['Indomitable']=QtCore.QRect(294,154,58,58) self.ClickRects['VeteransScars']=QtCore.QRect(356,154,58,58) self.ClickRects['Evasion']=QtCore.QRect(418,154,58,58) self.ClickRects['BladedArmor']=QtCore.QRect(480,154,58,58) self.ClickRects['SiegeCommander']=QtCore.QRect(294,226,58,58) self.ClickRects['Initiator']=QtCore.QRect(356,226,58,58) self.ClickRects['Enlightenment']=QtCore.QRect(418,226,58,58) self.ClickRects['HonorGuard']=QtCore.QRect(356,298,58,58) self.ClickRects['Mercenary']=QtCore.QRect(418,298,58,58) self.ClickRects['Juggernaut']=QtCore.QRect(356,368,58,58) # util self.ClickRects['SummonersInsight']=QtCore.QRect(568,12,58,58) self.ClickRects['GoodHands']=QtCore.QRect(630,12,58,58) self.ClickRects['ExpandedMind']=QtCore.QRect(692,12,58,58) self.ClickRects['ImprovedRecall']=QtCore.QRect(754,12,58,58) self.ClickRects['Swiftness']=QtCore.QRect(630,82,58,58) self.ClickRects['Meditation']=QtCore.QRect(692,82,58,58) self.ClickRects['Scout']=QtCore.QRect(754,82,58,58) self.ClickRects['Greed']=QtCore.QRect(630,154,58,58) self.ClickRects['Transmutation']=QtCore.QRect(692,154,58,58) self.ClickRects['RunicAffinity']=QtCore.QRect(754,154,58,58) self.ClickRects['Wealth']=QtCore.QRect(630,226,58,58) self.ClickRects['Awareness']=QtCore.QRect(692,226,58,58) self.ClickRects['Sage']=QtCore.QRect(754,226,58,58) self.ClickRects['StrengthOfSpirit']=QtCore.QRect(630,298,58,58) self.ClickRects['Intelligence']=QtCore.QRect(692,298,58,58) self.ClickRects['Mastermind']=QtCore.QRect(692,368,58,58) def paintEvent(self,e): painter = QtGui.QPainter(self) painter.setPen(self.pen) painter.setBrush(self.brush) painter.drawPixmap(0,0,self.MasteriesBG) painter.fillRect(self.OffensivePointsRect,self.brush) painter.fillRect(self.DefensivePointsRect,self.brush) painter.fillRect(self.UtilityPointsRect,self.brush) painter.drawRect(self.OffensivePointsRect) painter.drawRect(self.DefensivePointsRect) painter.drawRect(self.UtilityPointsRect) painter.setPen(self.whitepen) painter.drawText(self.OffensivePointsRect,"Offense: %s" % (self.OffensivePoints),QtGui.QTextOption(QtCore.Qt.AlignCenter)) painter.drawText(self.DefensivePointsRect,"Defense: %s" % (self.DefensivePoints),QtGui.QTextOption(QtCore.Qt.AlignCenter)) painter.drawText(self.UtilityPointsRect,"Utility: %s" % (self.UtilityPoints),QtGui.QTextOption(QtCore.Qt.AlignCenter)) class MasteriesIcon(QtGui.QWidget): LeftClicked = QtCore.pyqtSignal([str]) RightClicked = QtCore.pyqtSignal([str]) def __init__(self,name,maxvalue,parent = None): super(MasteriesIcon,self).__init__(parent) self.parent=parent self.setFixedSize(58,58) self.name = name self.Pixmap=QtGui.QPixmap('images/masteries/%s.png' % (self.name)) self.im = self.Pixmap.toImage() for i in range(self.im.width()): for j in range(self.im.height()): col = self.im.pixel(i,j) gray = QtGui.qGray(col) self.im.setPixel(i,j,QtGui.qRgb(gray,gray,gray)) self.maxvalue = maxvalue self.currentvalue = 0 self.enabled = False self.PointsRect=QtCore.QRectF(30,42,27,15) self.pen = QtGui.QPen() self.pen.setColor(QtGui.QColor(0,240,0)) self.pen.setWidth(2) self.GrayPen = QtGui.QPen() self.GrayPen.setColor(QtGui.QColor(128,128,128)) self.GrayPen.setWidth(2) self.brush = QtGui.QBrush() self.brush.setColor(QtGui.QColor(0,0,0)) self.brush.setStyle(1) def enterEvent(self,e): print "entered: ",self.name def mouseReleaseEvent(self,e): if self.enabled: if e.button() == QtCore.Qt.LeftButton: self.LeftClicked.emit(self.name) if e.button() == QtCore.Qt.RightButton: self.RightClicked.emit(self.name) def isMaxed(self): if self.currentvalue == self.maxvalue: return True else: return False def addPoint(self): if self.currentvalue == self.maxvalue: return False else: self.currentvalue += 1 self.update() return True def removePoint(self): if self.currentvalue == 0: return False else: self.currentvalue -= 1 # print self.currentvalue self.update() return True def paintEvent(self,e): painter = QtGui.QPainter(self) painter.setPen(self.pen) if self.enabled: painter.drawPixmap(0,0,self.Pixmap) else: painter.setPen(self.GrayPen) painter.drawImage(0,0,self.im) painter.fillRect(self.PointsRect,self.brush) painter.drawRect(self.PointsRect) painter.drawText(self.PointsRect,"%s/%s" % (self.currentvalue,self.maxvalue),QtGui.QTextOption(QtCore.Qt.AlignCenter)) def SetEnable(self): self.enabled = True def SetDisable(self): self.enabled = False
Python
from PyQt4 import QtGui,QtCore from ftllibs.FTL import CHAMPS as CHAMPS from ftllibs.FTL import ITEMS as ITEMS from ftllibs.FTL import BuildDS as BuildDS from ftllibs.ui.UI_ChampDisplay import UI_ChampDisplay from ftllibs.ui.UI_SlotItemDisplay import UI_SlotItemDisplay import math class CompareTab(QtGui.QWidget): def __init__(self,parent=None): super(CompareTab,self).__init__() self.Slot1=SlotDisplay(1) self.Slot2=SlotDisplay(2) self.Slot3=SlotDisplay(3) self.Slot4=SlotDisplay(4) self.StatTab = QtGui.QTabWidget() self.StatTab.setTabsClosable(False) self.StatTab.setMovable(True) self.GraphicalTab=CompareGraphical(self) self.NumericalTab=CompareNumerical(self) self.StatTab.addTab(self.NumericalTab,"Numerical") self.StatTab.addTab(self.GraphicalTab,"Graphical") self.MasterLayout=QtGui.QGridLayout() self.setLayout(self.MasterLayout) self.initUI() def initUI(self): self.LoadSlotButton=QtGui.QPushButton('LoadMe') self.LoadSlotButton.clicked.connect(self.loadIntoSlotDialog) # self.MasterLayout.addWidget(self.LoadSlotButton) self.SlotLayout=QtGui.QGridLayout() self.Slot1LoadButton=QtGui.QPushButton('Load') self.Slot1ClearButton=QtGui.QPushButton('Clear') self.Slot1Layout=QtGui.QGridLayout() self.Slot1Layout.addWidget(self.Slot1,0,0,1,2) self.Slot1Layout.addWidget(self.Slot1LoadButton,1,0,1,1) self.Slot1Layout.addWidget(self.Slot1ClearButton,1,1,1,1) self.Slot1Layout.setColumnStretch(2,1) self.Slot1LoadButton.clicked.connect(self.LoadSlot1) self.Slot1ClearButton.clicked.connect(self.ClearSlot2) self.Slot2LoadButton=QtGui.QPushButton('Load') self.Slot2ClearButton=QtGui.QPushButton('Clear') self.Slot2Layout=QtGui.QGridLayout() self.Slot2Layout.addWidget(self.Slot2,0,0,1,2) self.Slot2Layout.addWidget(self.Slot2LoadButton,1,0,1,1) self.Slot2Layout.addWidget(self.Slot2ClearButton,1,1,1,1) self.Slot2Layout.setColumnStretch(2,1) self.Slot2LoadButton.clicked.connect(self.LoadSlot2) self.Slot2ClearButton.clicked.connect(self.ClearSlot2) self.Slot3LoadButton=QtGui.QPushButton('Load') self.Slot3ClearButton=QtGui.QPushButton('Clear') self.Slot3Layout=QtGui.QGridLayout() self.Slot3Layout.addWidget(self.Slot3,0,0,1,2) self.Slot3Layout.addWidget(self.Slot3LoadButton,1,0,1,1) self.Slot3Layout.addWidget(self.Slot3ClearButton,1,1,1,1) self.Slot3Layout.setColumnStretch(2,1) self.Slot3LoadButton.clicked.connect(self.LoadSlot3) self.Slot3ClearButton.clicked.connect(self.ClearSlot3) self.Slot4LoadButton=QtGui.QPushButton('Load') self.Slot4ClearButton=QtGui.QPushButton('Clear') self.Slot4Layout=QtGui.QGridLayout() self.Slot4Layout.addWidget(self.Slot4,0,0,1,2) self.Slot4Layout.addWidget(self.Slot4LoadButton,1,0,1,1) self.Slot4Layout.addWidget(self.Slot4ClearButton,1,1,1,1) self.Slot4Layout.setColumnStretch(2,1) self.Slot4LoadButton.clicked.connect(self.LoadSlot4) self.Slot4ClearButton.clicked.connect(self.ClearSlot4) self.SlotLayout.addLayout(self.Slot1Layout,0,0,1,1) self.SlotLayout.addLayout(self.Slot2Layout,1,0,1,1) self.SlotLayout.addLayout(self.Slot3Layout,2,0,1,1) self.SlotLayout.addLayout(self.Slot4Layout,3,0,1,1) self.MasterLayout.addLayout(self.SlotLayout,0,0,1,1) self.MasterLayout.addWidget(self.StatTab,0,1,1,1) def LoadSlot1(self): dlg = loadSlotDialog(self) dlg.exec_() champ,build,ok=dlg.getReturn() self.Slot1.SetChampS(champ,build) self.GraphicalTab.UpdateGraph() self.NumericalTab.UpdateStatsC1() def ClearSlot1(self): pass def LoadSlot2(self): dlg = loadSlotDialog(self) dlg.exec_() champ,build,ok=dlg.getReturn() print champ self.Slot2.SetChampS(champ,build) self.GraphicalTab.UpdateGraph() self.NumericalTab.UpdateStatsC2() def ClearSlot2(self): pass def LoadSlot3(self): dlg = loadSlotDialog(self) dlg.exec_() champ,build,ok=dlg.getReturn() print champ self.Slot3.SetChampS(champ,build) self.GraphicalTab.UpdateGraph() self.NumericalTab.UpdateStatsC3() def ClearSlot3(self): pass def LoadSlot4(self): dlg = loadSlotDialog(self) dlg.exec_() champ,build,ok=dlg.getReturn() print champ self.Slot4.SetChampS(champ,build) self.GraphicalTab.UpdateGraph() self.NumericalTab.UpdateStatsC4() def ClearSlot4(self): pass def loadIntoSlotDialog(self,slot): pass class SlotDisplay(QtGui.QWidget): def __init__(self,SlotID,parent=None): super(SlotDisplay,self).__init__() self.ChampID=None self.BID=None self.Champ=None self.setFixedSize(400,200) self.SlotID=SlotID self.MasterLayout=QtGui.QGridLayout() self.setLayout(self.MasterLayout) self.BuildName=QtGui.QLabel('ss') self.SlotChampDisplay=UI_ChampDisplay(self) print "SlotDisplay: SlotChampDisplay: ",self.SlotChampDisplay self.SlotItemDisplay=UI_SlotItemDisplay() self.MasterLayout.addWidget(self.SlotChampDisplay,0,0,1,1) self.MasterLayout.addWidget(self.BuildName,0,1,1,1) self.MasterLayout.addWidget(self.SlotItemDisplay,1,0,1,2) # self.SlotChampDisplay.SetChamp(78) def SetChampS(self,ChampID,BID): self.ChampID=int(ChampID) self.Champ=CHAMPS.GetChampCopy(self.ChampID) buildmodel = BuildDS.GetBuildDataModel(self.ChampID) build = buildmodel.loadBuild(BID) for i in range(1,7): if build['Item%s' % (i)] == 'None': continue else: self.Champ.AddItem(i,build['Item%s' % (i)]) self.SlotChampDisplay.SetChamp(self.Champ.ID) self.SlotItemDisplay.SetChamp(self.Champ) self.update() # def SetBuild(self,) def paintEvent(self,e): painter = QtGui.QPainter(self) pen = QtGui.QPen() pen.setWidth(6) if self.SlotID == 1: pen.setColor(QtGui.QColor(200,0,0)) if self.SlotID == 2: pen.setColor(QtGui.QColor(0,200,0)) if self.SlotID == 3: pen.setColor(QtGui.QColor(0,0,200)) if self.SlotID == 4: pen.setColor(QtGui.QColor(150,150,0)) painter.setPen(pen) painter.drawRect(self.rect()) class loadSlotDialog(QtGui.QDialog): def __init__(self,parent=None): super(loadSlotDialog,self).__init__() self.MasterLayout=QtGui.QGridLayout() self.ChampLabel=QtGui.QLabel('Select a Champion:') self.ChampComboBox=QtGui.QComboBox() self.ChampComboBox.addItem('Choose a Champ') self.BuildLabel=QtGui.QLabel('Select a Build:') self.BuildComboBox=QtGui.QComboBox() self.BuildComboBox.addItem('Select a Champ First') self.LoadButton=QtGui.QPushButton('Load') self.CancelButton=QtGui.QPushButton('Cancel') self.LoadButton.clicked.connect(self.LoadClicked) self.CancelButton.clicked.connect(self.CancelClicked) self.MasterLayout.addWidget(self.ChampLabel) self.MasterLayout.addWidget(self.ChampComboBox) self.MasterLayout.addWidget(self.BuildLabel) self.MasterLayout.addWidget(self.BuildComboBox) self.MasterLayout.addWidget(self.LoadButton) self.MasterLayout.addWidget(self.CancelButton) self.setLayout(self.MasterLayout) self.model=None self.champ=None self.build=None self.PopulateChampComboBox() self.ChampComboBox.currentIndexChanged[str].connect(self.PopulateBuildComboBox) self.BuildComboBox.currentIndexChanged[int].connect(self.SetBID) def SetBID(self,pos): if self.model == None: self.build=None return else: self.build=self.model.getBID(pos) return def PopulateChampComboBox(self): for i in BuildDS.GetAvailableChampSaves(): print i self.ChampComboBox.addItem(CHAMPS.GetChampName(i)) def PopulateBuildComboBox(self,ChampID): print "populatebuildcombobox: ",ChampID if ChampID == "Select a Champ": return ChampID = CHAMPS.GetChampID(ChampID) self.model=BuildDS.GetBuildDataModel(ChampID) self.BuildComboBox.setModel(self.model) self.BuildComboBox.update() self.update() self.champ=ChampID def LoadClicked(self): # self.champ=CHAMPS.GetChampID(self.ChampComboBox.currentText()) # self.build=self.BuildComboBox.currentText() self.ok = True self.close() def CancelClicked(self): self.ok= False self.champ=None self.build=None self.close() def getReturn(self): return self.champ,self.build,self.ok class CompareGraphical(QtGui.QWidget): def __init__(self,parent=None): super(CompareGraphical,self).__init__() self.parent = parent self.setFixedWidth(700) self.initUI() def initUI(self): self.GraphBG1 = QtGui.QPixmap("images/ui/StatsGrid.png") self.GraphLines = QtGui.QPixmap(self.GraphBG1) self.Champ1Color=QtGui.QColor(200,0,0) self.Champ2Color=QtGui.QColor(0,200,0) self.Champ3Color=QtGui.QColor(0,0,200) self.Champ4Color=QtGui.QColor(150,150,0) self.lay = QtGui.QHBoxLayout() self.setLayout(self.lay) def UpdateGraph(self): # Collect Champs from slots Champ1 = self.parent.Slot1.Champ Champ2 = self.parent.Slot2.Champ Champ3 = self.parent.Slot3.Champ Champ4 = self.parent.Slot4.Champ self.ListOfBuilds = {} if not Champ1 == None: self.ListOfBuilds[self.Champ1Color]=Champ1 if not Champ2 == None: self.ListOfBuilds[self.Champ2Color]=Champ2 if not Champ3 == None: self.ListOfBuilds[self.Champ3Color]=Champ3 if not Champ4 == None: self.ListOfBuilds[self.Champ4Color]=Champ4 # octagon graph health_delta = 4000.0 / 216.0 armor_delta = 400.0 / 216.0 damage_delta = 400.0 / 216.0 mana_delta = 4000.0 / 216.0 resist_delta = 400.0 / 216.0 power_delta = 400.0 / 216.0 health_regen_delta = 100.0 / 216.0 mana_regen_delta = 100.0 / 216.0 #bar chart speed_delta = 500.0 / 140.0 armor_penetration_delta = 100.0 / 140.0 life_steal_delta = 100.0 / 140.0 attack_speed_delta = 2.5 / 140.0 critical_delta = 100.0 / 140.0 spell_penetration_delta = 100.0 / 140.0 spell_vamp_delta = 100.0 / 140.0 cooldown_reduction_delta = 40.0 / 140.0 # graph 1 polygonF = QtGui.QPolygonF() BuildNum=1 x_offset = 343 y_offset = 267 self.GraphLines = QtGui.QPixmap(self.GraphBG1) # self.GraphLines.fill(QtGui.QColor('transpar)) painter = QtGui.QPainter(self.GraphLines) pen = QtGui.QPen() for color,champ in self.ListOfBuilds.iteritems(): pen.setWidth(3) painter.setPen(pen) print "GraphItem Loop: Champ: " ,champ pen.setColor(color) painter.setPen(pen) #octagon chart health_length = champ.Health/health_delta h_y = math.sin(math.radians(247.5)) * health_length + y_offset h_x = math.cos(math.radians(247.5)) * health_length + x_offset health_regen_length = champ.Health_Regen_per_5_seconds/health_regen_delta hr_y = math.sin(math.radians(202.5)) * health_regen_length + y_offset hr_x = math.cos(math.radians(202.5)) * health_regen_length + x_offset damage_length = champ.Attack_Damage/damage_delta d_y = math.sin(math.radians(157.5)) * damage_length + y_offset d_x = math.cos(math.radians(157.5)) * damage_length + x_offset armor_length = champ.Armor/armor_delta a_y = math.sin(math.radians(112.5)) * armor_length + y_offset a_x = math.cos(math.radians(112.5)) * armor_length + x_offset resist_length = champ.Magic_Resist/resist_delta r_y = math.sin(math.radians(67.5)) * resist_length + y_offset r_x = math.cos(math.radians(67.5)) * resist_length + x_offset power_length = champ.Ability_Power/power_delta p_y = math.sin(math.radians(22.5)) * power_length + y_offset p_x = math.cos(math.radians(22.5)) * power_length + x_offset mana_regen_length = champ.Mana_Regen_per_5_seconds/mana_regen_delta mr_y = math.sin(math.radians(337.5)) * mana_regen_length + y_offset mr_x = math.cos(math.radians(337.5)) * mana_regen_length + x_offset mana_length = champ.Mana/mana_delta m_y = math.sin(math.radians(292.5)) * mana_length + y_offset m_x = math.cos(math.radians(292.5)) * mana_length + x_offset # column chart speed_length = champ.Movement_Speed/speed_delta armor_penetration_length = champ.Armor_Penetration_Flat/armor_penetration_delta life_steal_length=champ.Life_Steal/life_steal_delta attack_speed_length =champ.Attack_Speed/attack_speed_delta critical_length = champ.Critical_Strike_Chance/critical_delta spell_penetration_length = champ.Magic_Penetration_Flat/spell_penetration_delta spell_vamp_length = champ.Spell_Vamp/spell_vamp_delta cooldown_reduction_length = champ.Cooldown_Reduction/cooldown_reduction_delta polygonF.clear() polygonF.append(QtCore.QPointF(h_x,h_y)) polygonF.append(QtCore.QPointF(hr_x,hr_y)) polygonF.append(QtCore.QPointF(d_x,d_y)) polygonF.append(QtCore.QPointF(a_x,a_y)) polygonF.append(QtCore.QPointF(r_x,r_y)) polygonF.append(QtCore.QPointF(p_x,p_y)) polygonF.append(QtCore.QPointF(mr_x,mr_y)) polygonF.append(QtCore.QPointF(m_x,m_y)) polygonF.append(QtCore.QPointF(h_x,h_y)) painter.drawPolygon(polygonF) # column charts # speed pen.setWidth(7) painter.setPen(pen) offx = 20 offy = 600 painter.drawLine(offx+(8*BuildNum),offy,offx+(8*BuildNum),offy-speed_length) painter.drawLine(offx+(8*BuildNum)+55,offy,offx+(8*BuildNum)+55,offy-armor_penetration_length) painter.drawLine(offx+(8*BuildNum)+110,offy,offx+(8*BuildNum)+110,offy-life_steal_length) painter.drawLine(offx+(8*BuildNum)+165,offy,offx+(8*BuildNum)+165,offy-attack_speed_length) painter.drawLine(offx+(8*BuildNum)+220,offy,offx+(8*BuildNum)+220,offy-critical_length) painter.drawLine(offx+(8*BuildNum)+275,offy,offx+(8*BuildNum)+275,offy-spell_penetration_length) painter.drawLine(offx+(8*BuildNum)+330,offy,offx+(8*BuildNum)+330,offy-spell_vamp_length) painter.drawLine(offx+(8*BuildNum)+385,offy,offx+(8*BuildNum)+385,offy-cooldown_reduction_length) # print "##### Stats #####",BuildNum,"#########" # print "Health: ", health_length * health_delta # print "Health Regen: ", health_regen_length * health_regen_delta # print "Damage: ",damage_length * damage_delta # print "Armor: ",armor_length * armor_delta # print "Power: ", power_length * power_delta # print "Resist: ",resist_length * resist_delta # print "Mana Regen: ",mana_regen_length * mana_regen_delta # print "Mana: ", mana_length * mana_delta # print "Speed: ", speed_length * speed_delta # print "Life Steal ",armor_penetration_length * armor_penetration_delta # print "Attack Speed ",attack_speed_length * attack_speed_delta # print "Critical ",critical_length * critical_delta # print "Spell Pen: ",spell_penetration_length * spell_penetration_delta # print "Spell Vamp: ",spell_vamp_length * spell_vamp_delta # print "CDR: ",cooldown_reduction_length * cooldown_reduction_delta # print "##################" print "########### Stats #####",champ.Name,"##############" champ.DumpStats() print "" BuildNum += 1 painter.end() # repaint self.update() def paintEvent(self,e): painter = QtGui.QPainter(self) painter.fillRect(self.rect(),QtGui.QColor("#DDAA00")) # painter.drawPixmap(0,0,self.GraphBG1) painter.drawPixmap(0,0,self.GraphLines) class CompareNumerical(QtGui.QWidget): def __init__(self,parent): super(CompareNumerical,self).__init__() self.MasterLayout=QtGui.QGridLayout() self.MasterLayout.setVerticalSpacing(30) self.setLayout(self.MasterLayout) # self.Champ=parent.Champ self.parent = parent self.InitUI() # self.UpdateStats() def InitUI(self): # health self.L_Health=QtGui.QVBoxLayout() self.LBL_Health=QtGui.QLabel('Health\n') self.LE_HealthC1=QtGui.QLineEdit() self.LE_HealthC1.setReadOnly(True) self.LE_HealthC1.setText('0') self.LE_HealthC1.setMaximumWidth(100) self.LE_HealthC2=QtGui.QLineEdit() self.LE_HealthC2.setReadOnly(True) self.LE_HealthC2.setText('0') self.LE_HealthC2.setMaximumWidth(100) self.LE_HealthC3=QtGui.QLineEdit() self.LE_HealthC3.setReadOnly(True) self.LE_HealthC3.setText('0') self.LE_HealthC3.setMaximumWidth(100) self.LE_HealthC4=QtGui.QLineEdit() self.LE_HealthC4.setReadOnly(True) self.LE_HealthC4.setText('0') self.LE_HealthC4.setMaximumWidth(100) self.L_Health.addWidget(self.LBL_Health) self.L_Health.addWidget(self.LE_HealthC1) self.L_Health.addWidget(self.LE_HealthC2) self.L_Health.addWidget(self.LE_HealthC3) self.L_Health.addWidget(self.LE_HealthC4) self.L_Health.addStretch() # mana self.L_Mana=QtGui.QVBoxLayout() self.LBL_Mana=QtGui.QLabel('Mana\n') self.LE_ManaC1=QtGui.QLineEdit() self.LE_ManaC1.setReadOnly(True) self.LE_ManaC1.setText('0') self.LE_ManaC1.setMaximumWidth(100) self.LE_ManaC2=QtGui.QLineEdit() self.LE_ManaC2.setReadOnly(True) self.LE_ManaC2.setText('0') self.LE_ManaC2.setMaximumWidth(100) self.LE_ManaC3=QtGui.QLineEdit() self.LE_ManaC3.setReadOnly(True) self.LE_ManaC3.setText('0') self.LE_ManaC3.setMaximumWidth(100) self.LE_ManaC4=QtGui.QLineEdit() self.LE_ManaC4.setReadOnly(True) self.LE_ManaC4.setText('0') self.LE_ManaC4.setMaximumWidth(100) self.L_Mana.addWidget(self.LBL_Mana) self.L_Mana.addWidget(self.LE_ManaC1) self.L_Mana.addWidget(self.LE_ManaC2) self.L_Mana.addWidget(self.LE_ManaC3) self.L_Mana.addWidget(self.LE_ManaC4) self.L_Mana.addStretch() # Health Regen self.L_Health_Regen_per_5_seconds=QtGui.QVBoxLayout() self.LBL_Health_Regen_per_5_seconds=QtGui.QLabel('Health Regen\nper 5s (per 1s)') self.LE_Health_Regen_per_5_secondsC1=QtGui.QLineEdit() self.LE_Health_Regen_per_5_secondsC1.setReadOnly(True) self.LE_Health_Regen_per_5_secondsC1.setText('0') self.LE_Health_Regen_per_5_secondsC1.setMaximumWidth(100) self.LE_Health_Regen_per_5_secondsC2=QtGui.QLineEdit() self.LE_Health_Regen_per_5_secondsC2.setReadOnly(True) self.LE_Health_Regen_per_5_secondsC2.setText('0') self.LE_Health_Regen_per_5_secondsC2.setMaximumWidth(100) self.LE_Health_Regen_per_5_secondsC3=QtGui.QLineEdit() self.LE_Health_Regen_per_5_secondsC3.setReadOnly(True) self.LE_Health_Regen_per_5_secondsC3.setText('0') self.LE_Health_Regen_per_5_secondsC3.setMaximumWidth(100) self.LE_Health_Regen_per_5_secondsC4=QtGui.QLineEdit() self.LE_Health_Regen_per_5_secondsC4.setReadOnly(True) self.LE_Health_Regen_per_5_secondsC4.setText('0') self.LE_Health_Regen_per_5_secondsC4.setMaximumWidth(100) self.L_Health_Regen_per_5_seconds.addWidget(self.LBL_Health_Regen_per_5_seconds) self.L_Health_Regen_per_5_seconds.addWidget(self.LE_Health_Regen_per_5_secondsC1) self.L_Health_Regen_per_5_seconds.addWidget(self.LE_Health_Regen_per_5_secondsC2) self.L_Health_Regen_per_5_seconds.addWidget(self.LE_Health_Regen_per_5_secondsC3) self.L_Health_Regen_per_5_seconds.addWidget(self.LE_Health_Regen_per_5_secondsC4) self.L_Health_Regen_per_5_seconds.addStretch() # Mana Regen self.L_Mana_Regen_per_5_seconds=QtGui.QVBoxLayout() self.LBL_Mana_Regen_per_5_seconds=QtGui.QLabel('Mana Regen\nper 5s (per 1s)') self.LE_Mana_Regen_per_5_secondsC1=QtGui.QLineEdit() self.LE_Mana_Regen_per_5_secondsC1.setReadOnly(True) self.LE_Mana_Regen_per_5_secondsC1.setText('0') self.LE_Mana_Regen_per_5_secondsC1.setMaximumWidth(100) self.LE_Mana_Regen_per_5_secondsC2=QtGui.QLineEdit() self.LE_Mana_Regen_per_5_secondsC2.setReadOnly(True) self.LE_Mana_Regen_per_5_secondsC2.setText('0') self.LE_Mana_Regen_per_5_secondsC2.setMaximumWidth(100) self.LE_Mana_Regen_per_5_secondsC3=QtGui.QLineEdit() self.LE_Mana_Regen_per_5_secondsC3.setReadOnly(True) self.LE_Mana_Regen_per_5_secondsC3.setText('0') self.LE_Mana_Regen_per_5_secondsC3.setMaximumWidth(100) self.LE_Mana_Regen_per_5_secondsC4=QtGui.QLineEdit() self.LE_Mana_Regen_per_5_secondsC4.setReadOnly(True) self.LE_Mana_Regen_per_5_secondsC4.setText('0') self.LE_Mana_Regen_per_5_secondsC4.setMaximumWidth(100) self.L_Mana_Regen_per_5_seconds.addWidget(self.LBL_Mana_Regen_per_5_seconds) self.L_Mana_Regen_per_5_seconds.addWidget(self.LE_Mana_Regen_per_5_secondsC1) self.L_Mana_Regen_per_5_seconds.addWidget(self.LE_Mana_Regen_per_5_secondsC2) self.L_Mana_Regen_per_5_seconds.addWidget(self.LE_Mana_Regen_per_5_secondsC3) self.L_Mana_Regen_per_5_seconds.addWidget(self.LE_Mana_Regen_per_5_secondsC4) self.L_Mana_Regen_per_5_seconds.addStretch() # Attack Damage self.L_Attack_Damage=QtGui.QVBoxLayout() self.LBL_Attack_Damage=QtGui.QLabel('Attack Damage\n') self.LE_Attack_DamageC1=QtGui.QLineEdit() self.LE_Attack_DamageC1.setReadOnly(True) self.LE_Attack_DamageC1.setText('0') self.LE_Attack_DamageC1.setMaximumWidth(100) self.LE_Attack_DamageC2=QtGui.QLineEdit() self.LE_Attack_DamageC2.setReadOnly(True) self.LE_Attack_DamageC2.setText('0') self.LE_Attack_DamageC2.setMaximumWidth(100) self.LE_Attack_DamageC3=QtGui.QLineEdit() self.LE_Attack_DamageC3.setReadOnly(True) self.LE_Attack_DamageC3.setText('0') self.LE_Attack_DamageC3.setMaximumWidth(100) self.LE_Attack_DamageC4=QtGui.QLineEdit() self.LE_Attack_DamageC4.setReadOnly(True) self.LE_Attack_DamageC4.setText('0') self.LE_Attack_DamageC4.setMaximumWidth(100) self.L_Attack_Damage.addWidget(self.LBL_Attack_Damage) self.L_Attack_Damage.addWidget(self.LE_Attack_DamageC1) self.L_Attack_Damage.addWidget(self.LE_Attack_DamageC2) self.L_Attack_Damage.addWidget(self.LE_Attack_DamageC3) self.L_Attack_Damage.addWidget(self.LE_Attack_DamageC4) self.L_Attack_Damage.addStretch() # Armor self.L_Armor=QtGui.QVBoxLayout() self.LBL_Armor=QtGui.QLabel('Armor\n') self.LE_ArmorC1=QtGui.QLineEdit() self.LE_ArmorC1.setReadOnly(True) self.LE_ArmorC1.setText('0') self.LE_ArmorC1.setMaximumWidth(100) self.LE_ArmorC2=QtGui.QLineEdit() self.LE_ArmorC2.setReadOnly(True) self.LE_ArmorC2.setText('0') self.LE_ArmorC2.setMaximumWidth(100) self.LE_ArmorC3=QtGui.QLineEdit() self.LE_ArmorC3.setReadOnly(True) self.LE_ArmorC3.setText('0') self.LE_ArmorC3.setMaximumWidth(100) self.LE_ArmorC4=QtGui.QLineEdit() self.LE_ArmorC4.setReadOnly(True) self.LE_ArmorC4.setText('0') self.LE_ArmorC4.setMaximumWidth(100) self.L_Armor.addWidget(self.LBL_Armor) self.L_Armor.addWidget(self.LE_ArmorC1) self.L_Armor.addWidget(self.LE_ArmorC2) self.L_Armor.addWidget(self.LE_ArmorC3) self.L_Armor.addWidget(self.LE_ArmorC4) self.L_Armor.addStretch() # Ability Power self.L_Ability_Power=QtGui.QVBoxLayout() self.LBL_Ability_Power=QtGui.QLabel('Ability Power\n') self.LE_Ability_PowerC1=QtGui.QLineEdit() self.LE_Ability_PowerC1.setReadOnly(True) self.LE_Ability_PowerC1.setText('0') self.LE_Ability_PowerC1.setMaximumWidth(100) self.LE_Ability_PowerC2=QtGui.QLineEdit() self.LE_Ability_PowerC2.setReadOnly(True) self.LE_Ability_PowerC2.setText('0') self.LE_Ability_PowerC2.setMaximumWidth(100) self.LE_Ability_PowerC3=QtGui.QLineEdit() self.LE_Ability_PowerC3.setReadOnly(True) self.LE_Ability_PowerC3.setText('0') self.LE_Ability_PowerC3.setMaximumWidth(100) self.LE_Ability_PowerC4=QtGui.QLineEdit() self.LE_Ability_PowerC4.setReadOnly(True) self.LE_Ability_PowerC4.setText('0') self.LE_Ability_PowerC4.setMaximumWidth(100) self.L_Ability_Power.addWidget(self.LBL_Ability_Power) self.L_Ability_Power.addWidget(self.LE_Ability_PowerC1) self.L_Ability_Power.addWidget(self.LE_Ability_PowerC2) self.L_Ability_Power.addWidget(self.LE_Ability_PowerC3) self.L_Ability_Power.addWidget(self.LE_Ability_PowerC4) self.L_Ability_Power.addStretch() # Magic Resist self.L_Magic_Resist=QtGui.QVBoxLayout() self.LBL_Magic_Resist=QtGui.QLabel('Magic Resist\n') self.LE_Magic_ResistC1=QtGui.QLineEdit() self.LE_Magic_ResistC1.setReadOnly(True) self.LE_Magic_ResistC1.setText('0') self.LE_Magic_ResistC1.setMaximumWidth(100) self.LE_Magic_ResistC2=QtGui.QLineEdit() self.LE_Magic_ResistC2.setReadOnly(True) self.LE_Magic_ResistC2.setText('0') self.LE_Magic_ResistC2.setMaximumWidth(100) self.LE_Magic_ResistC3=QtGui.QLineEdit() self.LE_Magic_ResistC3.setReadOnly(True) self.LE_Magic_ResistC3.setText('0') self.LE_Magic_ResistC3.setMaximumWidth(100) self.LE_Magic_ResistC4=QtGui.QLineEdit() self.LE_Magic_ResistC4.setReadOnly(True) self.LE_Magic_ResistC4.setText('0') self.LE_Magic_ResistC4.setMaximumWidth(100) self.L_Magic_Resist.addWidget(self.LBL_Magic_Resist) self.L_Magic_Resist.addWidget(self.LE_Magic_ResistC1) self.L_Magic_Resist.addWidget(self.LE_Magic_ResistC2) self.L_Magic_Resist.addWidget(self.LE_Magic_ResistC3) self.L_Magic_Resist.addWidget(self.LE_Magic_ResistC4) self.L_Magic_Resist.addStretch() # Movement_speed self.L_Movement_Speed=QtGui.QVBoxLayout() self.LBL_Movement_Speed=QtGui.QLabel('Movement Speed\n') self.LE_Movement_SpeedC1=QtGui.QLineEdit() self.LE_Movement_SpeedC1.setReadOnly(True) self.LE_Movement_SpeedC1.setText('0') self.LE_Movement_SpeedC1.setMaximumWidth(100) self.LE_Movement_SpeedC2=QtGui.QLineEdit() self.LE_Movement_SpeedC2.setReadOnly(True) self.LE_Movement_SpeedC2.setText('0') self.LE_Movement_SpeedC2.setMaximumWidth(100) self.LE_Movement_SpeedC3=QtGui.QLineEdit() self.LE_Movement_SpeedC3.setReadOnly(True) self.LE_Movement_SpeedC3.setText('0') self.LE_Movement_SpeedC3.setMaximumWidth(100) self.LE_Movement_SpeedC4=QtGui.QLineEdit() self.LE_Movement_SpeedC4.setReadOnly(True) self.LE_Movement_SpeedC4.setText('0') self.LE_Movement_SpeedC4.setMaximumWidth(100) self.L_Movement_Speed.addWidget(self.LBL_Movement_Speed) self.L_Movement_Speed.addWidget(self.LE_Movement_SpeedC1) self.L_Movement_Speed.addWidget(self.LE_Movement_SpeedC2) self.L_Movement_Speed.addWidget(self.LE_Movement_SpeedC3) self.L_Movement_Speed.addWidget(self.LE_Movement_SpeedC4) self.L_Movement_Speed.addStretch() # Attack_Speed self.L_Attack_Speed=QtGui.QVBoxLayout() self.LBL_Attack_Speed=QtGui.QLabel('Attack Speed\n') self.LE_Attack_SpeedC1=QtGui.QLineEdit() self.LE_Attack_SpeedC1.setReadOnly(True) self.LE_Attack_SpeedC1.setText('0') self.LE_Attack_SpeedC1.setMaximumWidth(100) self.LE_Attack_SpeedC2=QtGui.QLineEdit() self.LE_Attack_SpeedC2.setReadOnly(True) self.LE_Attack_SpeedC2.setText('0') self.LE_Attack_SpeedC2.setMaximumWidth(100) self.LE_Attack_SpeedC3=QtGui.QLineEdit() self.LE_Attack_SpeedC3.setReadOnly(True) self.LE_Attack_SpeedC3.setText('0') self.LE_Attack_SpeedC3.setMaximumWidth(100) self.LE_Attack_SpeedC4=QtGui.QLineEdit() self.LE_Attack_SpeedC4.setReadOnly(True) self.LE_Attack_SpeedC4.setText('0') self.LE_Attack_SpeedC4.setMaximumWidth(100) self.L_Attack_Speed.addWidget(self.LBL_Attack_Speed) self.L_Attack_Speed.addWidget(self.LE_Attack_SpeedC1) self.L_Attack_Speed.addWidget(self.LE_Attack_SpeedC2) self.L_Attack_Speed.addWidget(self.LE_Attack_SpeedC3) self.L_Attack_Speed.addWidget(self.LE_Attack_SpeedC4) self.L_Attack_Speed.addStretch() # Spell_Vamp self.L_Spell_Vamp=QtGui.QVBoxLayout() self.LBL_Spell_Vamp=QtGui.QLabel('Spell Vamp\n') self.LE_Spell_VampC1=QtGui.QLineEdit() self.LE_Spell_VampC1.setReadOnly(True) self.LE_Spell_VampC1.setText('0') self.LE_Spell_VampC1.setMaximumWidth(100) self.LE_Spell_VampC2=QtGui.QLineEdit() self.LE_Spell_VampC2.setReadOnly(True) self.LE_Spell_VampC2.setText('0') self.LE_Spell_VampC2.setMaximumWidth(100) self.LE_Spell_VampC3=QtGui.QLineEdit() self.LE_Spell_VampC3.setReadOnly(True) self.LE_Spell_VampC3.setText('0') self.LE_Spell_VampC3.setMaximumWidth(100) self.LE_Spell_VampC4=QtGui.QLineEdit() self.LE_Spell_VampC4.setReadOnly(True) self.LE_Spell_VampC4.setText('0') self.LE_Spell_VampC4.setMaximumWidth(100) self.L_Spell_Vamp.addWidget(self.LBL_Spell_Vamp) self.L_Spell_Vamp.addWidget(self.LE_Spell_VampC1) self.L_Spell_Vamp.addWidget(self.LE_Spell_VampC2) self.L_Spell_Vamp.addWidget(self.LE_Spell_VampC3) self.L_Spell_Vamp.addWidget(self.LE_Spell_VampC4) self.L_Spell_Vamp.addStretch() # Life_Steal self.L_Life_Steal=QtGui.QVBoxLayout() self.LBL_Life_Steal=QtGui.QLabel('Life Steal\n') self.LE_Life_StealC1=QtGui.QLineEdit() self.LE_Life_StealC1.setReadOnly(True) self.LE_Life_StealC1.setText('0') self.LE_Life_StealC1.setMaximumWidth(100) self.LE_Life_StealC2=QtGui.QLineEdit() self.LE_Life_StealC2.setReadOnly(True) self.LE_Life_StealC2.setText('0') self.LE_Life_StealC2.setMaximumWidth(100) self.LE_Life_StealC3=QtGui.QLineEdit() self.LE_Life_StealC3.setReadOnly(True) self.LE_Life_StealC3.setText('0') self.LE_Life_StealC3.setMaximumWidth(100) self.LE_Life_StealC4=QtGui.QLineEdit() self.LE_Life_StealC4.setReadOnly(True) self.LE_Life_StealC4.setText('0') self.LE_Life_StealC4.setMaximumWidth(100) self.L_Life_Steal.addWidget(self.LBL_Life_Steal) self.L_Life_Steal.addWidget(self.LE_Life_StealC1) self.L_Life_Steal.addWidget(self.LE_Life_StealC2) self.L_Life_Steal.addWidget(self.LE_Life_StealC3) self.L_Life_Steal.addWidget(self.LE_Life_StealC4) self.L_Life_Steal.addStretch() # Cooldown_Reduction self.L_Cooldown_Reduction=QtGui.QVBoxLayout() self.LBL_Cooldown_Reduction=QtGui.QLabel('Cooldown\nReduction') self.LE_Cooldown_ReductionC1=QtGui.QLineEdit() self.LE_Cooldown_ReductionC1.setReadOnly(True) self.LE_Cooldown_ReductionC1.setText('0') self.LE_Cooldown_ReductionC1.setMaximumWidth(100) self.LE_Cooldown_ReductionC2=QtGui.QLineEdit() self.LE_Cooldown_ReductionC2.setReadOnly(True) self.LE_Cooldown_ReductionC2.setText('0') self.LE_Cooldown_ReductionC2.setMaximumWidth(100) self.LE_Cooldown_ReductionC3=QtGui.QLineEdit() self.LE_Cooldown_ReductionC3.setReadOnly(True) self.LE_Cooldown_ReductionC3.setText('0') self.LE_Cooldown_ReductionC3.setMaximumWidth(100) self.LE_Cooldown_ReductionC4=QtGui.QLineEdit() self.LE_Cooldown_ReductionC4.setReadOnly(True) self.LE_Cooldown_ReductionC4.setText('0') self.LE_Cooldown_ReductionC4.setMaximumWidth(100) self.L_Cooldown_Reduction.addWidget(self.LBL_Cooldown_Reduction) self.L_Cooldown_Reduction.addWidget(self.LE_Cooldown_ReductionC1) self.L_Cooldown_Reduction.addWidget(self.LE_Cooldown_ReductionC2) self.L_Cooldown_Reduction.addWidget(self.LE_Cooldown_ReductionC3) self.L_Cooldown_Reduction.addWidget(self.LE_Cooldown_ReductionC4) self.L_Cooldown_Reduction.addStretch() # Armor_Penetration # Armor_Penetration self.L_Armor_Penetration=QtGui.QVBoxLayout() self.LBL_Armor_Penetration=QtGui.QLabel('Armor\nPenetration') self.LE_Armor_PenetrationC1=QtGui.QLineEdit() self.LE_Armor_PenetrationC1.setReadOnly(True) self.LE_Armor_PenetrationC1.setText('0') self.LE_Armor_PenetrationC1.setMaximumWidth(100) self.LE_Armor_PenetrationC2=QtGui.QLineEdit() self.LE_Armor_PenetrationC2.setReadOnly(True) self.LE_Armor_PenetrationC2.setText('0') self.LE_Armor_PenetrationC2.setMaximumWidth(100) self.LE_Armor_PenetrationC3=QtGui.QLineEdit() self.LE_Armor_PenetrationC3.setReadOnly(True) self.LE_Armor_PenetrationC3.setText('0') self.LE_Armor_PenetrationC3.setMaximumWidth(100) self.LE_Armor_PenetrationC4=QtGui.QLineEdit() self.LE_Armor_PenetrationC4.setReadOnly(True) self.LE_Armor_PenetrationC4.setText('0') self.LE_Armor_PenetrationC4.setMaximumWidth(100) self.L_Armor_Penetration.addWidget(self.LBL_Armor_Penetration) self.L_Armor_Penetration.addWidget(self.LE_Armor_PenetrationC1) self.L_Armor_Penetration.addWidget(self.LE_Armor_PenetrationC2) self.L_Armor_Penetration.addWidget(self.LE_Armor_PenetrationC3) self.L_Armor_Penetration.addWidget(self.LE_Armor_PenetrationC4) self.L_Armor_Penetration.addStretch() # Magic_Penetration self.L_Magic_Penetration=QtGui.QVBoxLayout() self.LBL_Magic_Penetration=QtGui.QLabel('Magic\nPenetration') self.LE_Magic_PenetrationC1=QtGui.QLineEdit() self.LE_Magic_PenetrationC1.setReadOnly(True) self.LE_Magic_PenetrationC1.setText('0') self.LE_Magic_PenetrationC1.setMaximumWidth(100) self.LE_Magic_PenetrationC2=QtGui.QLineEdit() self.LE_Magic_PenetrationC2.setReadOnly(True) self.LE_Magic_PenetrationC2.setText('0') self.LE_Magic_PenetrationC2.setMaximumWidth(100) self.LE_Magic_PenetrationC3=QtGui.QLineEdit() self.LE_Magic_PenetrationC3.setReadOnly(True) self.LE_Magic_PenetrationC3.setText('0') self.LE_Magic_PenetrationC3.setMaximumWidth(100) self.LE_Magic_PenetrationC4=QtGui.QLineEdit() self.LE_Magic_PenetrationC4.setReadOnly(True) self.LE_Magic_PenetrationC4.setText('0') self.LE_Magic_PenetrationC4.setMaximumWidth(100) self.L_Magic_Penetration.addWidget(self.LBL_Magic_Penetration) self.L_Magic_Penetration.addWidget(self.LE_Magic_PenetrationC1) self.L_Magic_Penetration.addWidget(self.LE_Magic_PenetrationC2) self.L_Magic_Penetration.addWidget(self.LE_Magic_PenetrationC3) self.L_Magic_Penetration.addWidget(self.LE_Magic_PenetrationC4) self.L_Magic_Penetration.addStretch() # Critical_Strike_Chance self.L_Critical_Strike_Chance=QtGui.QVBoxLayout() self.LBL_Critical_Strike_Chance=QtGui.QLabel('Critical\nStrike Chance') self.LE_Critical_Strike_ChanceC1=QtGui.QLineEdit() self.LE_Critical_Strike_ChanceC1.setReadOnly(True) self.LE_Critical_Strike_ChanceC1.setText('0') self.LE_Critical_Strike_ChanceC1.setMaximumWidth(100) self.LE_Critical_Strike_ChanceC2=QtGui.QLineEdit() self.LE_Critical_Strike_ChanceC2.setReadOnly(True) self.LE_Critical_Strike_ChanceC2.setText('0') self.LE_Critical_Strike_ChanceC2.setMaximumWidth(100) self.LE_Critical_Strike_ChanceC3=QtGui.QLineEdit() self.LE_Critical_Strike_ChanceC3.setReadOnly(True) self.LE_Critical_Strike_ChanceC3.setText('0') self.LE_Critical_Strike_ChanceC3.setMaximumWidth(100) self.LE_Critical_Strike_ChanceC4=QtGui.QLineEdit() self.LE_Critical_Strike_ChanceC4.setReadOnly(True) self.LE_Critical_Strike_ChanceC4.setText('0') self.LE_Critical_Strike_ChanceC4.setMaximumWidth(100) self.L_Critical_Strike_Chance.addWidget(self.LBL_Critical_Strike_Chance) self.L_Critical_Strike_Chance.addWidget(self.LE_Critical_Strike_ChanceC1) self.L_Critical_Strike_Chance.addWidget(self.LE_Critical_Strike_ChanceC2) self.L_Critical_Strike_Chance.addWidget(self.LE_Critical_Strike_ChanceC3) self.L_Critical_Strike_Chance.addWidget(self.LE_Critical_Strike_ChanceC4) self.L_Critical_Strike_Chance.addStretch() # put into masterlayout # first row self.MasterLayout.addLayout(self.L_Health,0,0,1,1) self.MasterLayout.addLayout(self.L_Health_Regen_per_5_seconds,0,1,1,1) self.MasterLayout.addLayout(self.L_Mana,0,2,1,1) self.MasterLayout.addLayout(self.L_Mana_Regen_per_5_seconds,0,3,1,1) # second row self.MasterLayout.addLayout(self.L_Attack_Damage,1,0,1,1) self.MasterLayout.addLayout(self.L_Armor,1,1,1,1) self.MasterLayout.addLayout(self.L_Ability_Power,1,2,1,1) self.MasterLayout.addLayout(self.L_Magic_Resist,1,3,1,1) # third row self.MasterLayout.addLayout(self.L_Movement_Speed,2,0,1,1) self.MasterLayout.addLayout(self.L_Attack_Speed,2,1,1,1) self.MasterLayout.addLayout(self.L_Critical_Strike_Chance,2,2,1,1) self.MasterLayout.addLayout(self.L_Cooldown_Reduction,2,3,1,1) # fourth row self.MasterLayout.addLayout(self.L_Armor_Penetration,3,0,1,1) self.MasterLayout.addLayout(self.L_Magic_Penetration,3,1,1,1) self.MasterLayout.addLayout(self.L_Life_Steal,3,2,1,1) self.MasterLayout.addLayout(self.L_Spell_Vamp,3,3,1,1) # fifth (spacer) self.MasterLayout.setRowStretch(4,1) def setChamp(self,Champ): self.Champ = Champ self.UpdateStats() def UpdateStatsC1(self): Champ=self.parent.Slot1.Champ self.LE_HealthC1.setText(str(Champ.Health)) self.LE_ManaC1.setText(str(Champ.Mana)) self.LE_Health_Regen_per_5_secondsC1.setText("%s (%s)" % (str(Champ.Health_Regen_per_5_seconds),str(Champ.Health_Regen_per_5_seconds/5.0))) self.LE_Mana_Regen_per_5_secondsC1.setText("%s (%s)" % (str(Champ.Mana_Regen_per_5_seconds),str(Champ.Mana_Regen_per_5_seconds/5.0))) self.LE_Attack_DamageC1.setText(str(Champ.Attack_Damage)) self.LE_ArmorC1.setText(str(Champ.Armor)) self.LE_Ability_PowerC1.setText(str(Champ.Ability_Power)) self.LE_Magic_ResistC1.setText(str(Champ.Magic_Resist)) self.LE_Magic_PenetrationC1.setText("%s | %s" % (str(Champ.Magic_Penetration_Flat),str(Champ.Magic_Penetration_Percentage)+"%")) self.LE_Armor_PenetrationC1.setText("%s | %s" % (str(Champ.Armor_Penetration_Flat),str(Champ.Armor_Penetration_Percentage)+"%")) self.LE_Spell_VampC1.setText(str(Champ.Spell_Vamp)) self.LE_Life_StealC1.setText(str(Champ.Life_Steal)) self.LE_Movement_SpeedC1.setText(str(Champ.Movement_Speed)) self.LE_Critical_Strike_ChanceC1.setText(str(Champ.Critical_Strike_Chance)) self.LE_Attack_SpeedC1.setText(str(Champ.Attack_Speed)) self.LE_Cooldown_ReductionC1.setText(str(Champ.Cooldown_Reduction)) def UpdateStatsC2(self): Champ=self.parent.Slot2.Champ self.LE_HealthC2.setText(str(Champ.Health)) self.LE_ManaC2.setText(str(Champ.Mana)) self.LE_Health_Regen_per_5_secondsC2.setText("%s (%s)" % (str(Champ.Health_Regen_per_5_seconds),str(Champ.Health_Regen_per_5_seconds/5.0))) self.LE_Mana_Regen_per_5_secondsC2.setText("%s (%s)" % (str(Champ.Mana_Regen_per_5_seconds),str(Champ.Mana_Regen_per_5_seconds/5.0))) self.LE_Attack_DamageC2.setText(str(Champ.Attack_Damage)) self.LE_ArmorC2.setText(str(Champ.Armor)) self.LE_Ability_PowerC2.setText(str(Champ.Ability_Power)) self.LE_Magic_ResistC2.setText(str(Champ.Magic_Resist)) self.LE_Magic_PenetrationC2.setText("%s | %s" % (str(Champ.Magic_Penetration_Flat),str(Champ.Magic_Penetration_Percentage)+"%")) self.LE_Armor_PenetrationC2.setText("%s | %s" % (str(Champ.Armor_Penetration_Flat),str(Champ.Armor_Penetration_Percentage)+"%")) self.LE_Spell_VampC2.setText(str(Champ.Spell_Vamp)) self.LE_Life_StealC2.setText(str(Champ.Life_Steal)) self.LE_Movement_SpeedC2.setText(str(Champ.Movement_Speed)) self.LE_Critical_Strike_ChanceC2.setText(str(Champ.Critical_Strike_Chance)) self.LE_Attack_SpeedC2.setText(str(Champ.Attack_Speed)) self.LE_Cooldown_ReductionC2.setText(str(Champ.Cooldown_Reduction)) def UpdateStatsC3(self): Champ=self.parent.Slot3.Champ self.LE_HealthC3.setText(str(Champ.Health)) self.LE_ManaC3.setText(str(Champ.Mana)) self.LE_Health_Regen_per_5_secondsC3.setText("%s (%s)" % (str(Champ.Health_Regen_per_5_seconds),str(Champ.Health_Regen_per_5_seconds/5.0))) self.LE_Mana_Regen_per_5_secondsC3.setText("%s (%s)" % (str(Champ.Mana_Regen_per_5_seconds),str(Champ.Mana_Regen_per_5_seconds/5.0))) self.LE_Attack_DamageC3.setText(str(Champ.Attack_Damage)) self.LE_ArmorC3.setText(str(Champ.Armor)) self.LE_Ability_PowerC3.setText(str(Champ.Ability_Power)) self.LE_Magic_ResistC3.setText(str(Champ.Magic_Resist)) self.LE_Magic_PenetrationC3.setText("%s | %s" % (str(Champ.Magic_Penetration_Flat),str(Champ.Magic_Penetration_Percentage)+"%")) self.LE_Armor_PenetrationC3.setText("%s | %s" % (str(Champ.Armor_Penetration_Flat),str(Champ.Armor_Penetration_Percentage)+"%")) self.LE_Spell_VampC3.setText(str(Champ.Spell_Vamp)) self.LE_Life_StealC3.setText(str(Champ.Life_Steal)) self.LE_Movement_SpeedC3.setText(str(Champ.Movement_Speed)) self.LE_Critical_Strike_ChanceC3.setText(str(Champ.Critical_Strike_Chance)) self.LE_Cooldown_ReductionC3.setText(str(Champ.Cooldown_Reduction)) self.LE_Attack_SpeedC3.setText(str(Champ.Attack_Speed)) def UpdateStatsC4(self): Champ=self.parent.Slot4.Champ self.LE_HealthC4.setText(str(Champ.Health)) self.LE_ManaC4.setText(str(Champ.Mana)) self.LE_Health_Regen_per_5_secondsC4.setText("%s (%s)" % (str(Champ.Health_Regen_per_5_seconds),str(Champ.Health_Regen_per_5_seconds/5.0))) self.LE_Mana_Regen_per_5_secondsC4.setText("%s (%s)" % (str(Champ.Mana_Regen_per_5_seconds),str(Champ.Mana_Regen_per_5_seconds/5.0))) self.LE_Attack_DamageC4.setText(str(Champ.Attack_Damage)) self.LE_ArmorC4.setText(str(Champ.Armor)) self.LE_Ability_PowerC4.setText(str(Champ.Ability_Power)) self.LE_Magic_ResistC4.setText(str(Champ.Magic_Resist)) self.LE_Magic_PenetrationC4.setText("%s | %s" % (str(Champ.Magic_Penetration_Flat),str(Champ.Magic_Penetration_Percentage)+"%")) self.LE_Armor_PenetrationC4.setText("%s | %s" % (str(Champ.Armor_Penetration_Flat),str(Champ.Armor_Penetration_Percentage)+"%")) self.LE_Spell_VampC4.setText(str(Champ.Spell_Vamp)) self.LE_Life_StealC4.setText(str(Champ.Life_Steal)) self.LE_Movement_SpeedC4.setText(str(Champ.Movement_Speed)) self.LE_Critical_Strike_ChanceC4.setText(str(Champ.Critical_Strike_Chance)) self.LE_Attack_SpeedC4.setText(str(Champ.Attack_Speed)) self.LE_Cooldown_ReductionC4.setText(str(Champ.Cooldown_Reduction))
Python
from PyQt4 import QtGui,QtCore from ftllibs.FTL import ITEMS ## ItemMenu_Button ## The Buttons For the ItemMenu class ItemMenu_Button(QtGui.QWidget): clicked = QtCore.pyqtSignal(['QString']) ItemIconHighLightEvent = QtCore.pyqtSignal([str]) def __init__(self,itemid): super(ItemMenu_Button, self).__init__() self.itemid = str(itemid) self.setFixedSize(180,84) self.setContentsMargins(0,0,0,0) self.setStyleSheet('margin: 0px;border 0px') self.isEnabled=True self.initUI() def initUI(self): self.MasterLayout = QtGui.QGridLayout() self.PixMapLabel = QtGui.QLabel() # Icon self.ItemIcon=ITEMS.ITEMS[self.itemid].IconData.Default self.ItemIconGray=ITEMS.ITEMS[self.itemid].IconData.DefaultGrayScale #self.ItemIcon = QtGui.QPixmap("images/items/%s" % (ItemIcon)) # TODO: Options parameter for item Icon PATH self.PixMapLabel.setPixmap(self.ItemIcon) # Name ItemName=ITEMS.ITEMS[self.itemid].Name self.ItemNameLabel=QtGui.QLabel() self.ItemNameLabel.setText("<h4>%s</h4>" % (ItemName)) self.ItemNameLabel.setStyleSheet('color: Black') self.ItemNameLabel.setWordWrap(True) # TotalCosts ItemTotalCosts=str(ITEMS.ITEMS[self.itemid].Total_Costs) self.ItemTotalCostsLabel=QtGui.QLabel() self.ItemTotalCostsLabel.setText("<h5>%s</h5>" % (ItemTotalCosts)) self.ItemTotalCostsLabel.setStyleSheet('color: red') # Layout self.MasterLayout.addWidget(self.PixMapLabel,0,0,2,1,QtCore.Qt.AlignLeft) self.MasterLayout.addWidget(self.ItemNameLabel,0,1,1,1,QtCore.Qt.AlignLeft) self.MasterLayout.addWidget(self.ItemTotalCostsLabel,1,1,1,1,QtCore.Qt.AlignRight) self.setLayout(self.MasterLayout) self.setToolTip(ITEMS.ITEMS[self.itemid].Description) def Enabled(self): self.isEnabled=True self.PixMapLabel.setPixmap(self.ItemIcon) self.update() def Disabled(self): self.isEnabled=False self.PixMapLabel.setPixmap(self.ItemIconGray) self.update() def mousePressEvent(self, event): if self.isEnabled: print "ItemMenu_Button: Emitting 'clicked':\"%s\"" % (self.itemid) self.clicked.emit(self.itemid) else: pass def mouseMoveEvent(self,e): if self.isEnabled: print "ItemMenu_Button: Emittig 'dragEvent':\"%s\"" % (self.itemid) mimeData = QtCore.QMimeData() mimeData.setData('text/plain',self.itemid) drag = QtGui.QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(self.ItemIcon) drag.setHotSpot(e.pos() - self.rect().topLeft()) drag.start(QtCore.Qt.IgnoreAction) def enterEvent(self,e): print "ItemIcon: EnterEvent: ",self.itemid self.ItemIconHighLightEvent.emit(self.itemid) class ItemDetails(QtGui.QWidget): def __init__(self,parent=None): super(ItemDetails,self).__init__() self.MasterLayout = QtGui.QGridLayout() self.setFixedSize(480,200) self.StatsDescriptionLabel=QtGui.QLabel("hurga") self.MasterLayout.addWidget(self.StatsDescriptionLabel,0,0,1,1) self.setLayout(self.MasterLayout) def SetItemID(self,itemid): if self.sender().isEnabled: print "SetItemID Called :", itemid self.currentItemID=itemid if ITEMS.ITEMS[str(itemid)].RichText_Description != "": self.StatsDescriptionLabel.setTextFormat(1) self.StatsDescriptionLabel.setText(QtCore.QString(ITEMS.ITEMS[str(itemid)].RichText_Description)) else: self.StatsDescriptionLabel.setTextFormat(0) self.StatsDescriptionLabel.setText(QtCore.QString(ITEMS.ITEMS[str(itemid)].Description)) else: self.StatsDescriptionLabel.setText('Not available on this map') self.update() ## ItemMenu ## These are All Items in the Game, split up in tabs for each tag class ItemMenu(QtGui.QWidget): addItemPressed = QtCore.pyqtSignal(['QString']) def __init__(self,parent): super(ItemMenu,self).__init__() self.MasterLayout = QtGui.QVBoxLayout() self.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Expanding) self.setLayout(self.MasterLayout) self.setFixedWidth(440) self.AllButtons=[] self.initUI() def ChangeAvailability(self,indexnumber): if indexnumber == 0: for i in self.AllButtons: i.Enabled() if indexnumber == 1: for i in self.AllButtons: i.Disabled() for i in self.AllButtons: if i.itemid in ITEMS.GetAvailabilityList('summonersrift'): i.Enabled() def initUI(self): self.ItemAvailabilitySelect = QtGui.QComboBox() self.ItemAvailabilitySelect.addItem('All') self.ItemAvailabilitySelect.addItem('Summoners Rift') self.ItemAvailabilitySelect.addItem('Twisted Treeline') self.ItemAvailabilitySelect.addItem('Dominion') self.ItemAvailabilitySelect.setCurrentIndex(0) self.ItemAvailabilitySelect.currentIndexChanged[int].connect(self.ChangeAvailability) self.MasterLayout.addWidget(self.ItemAvailabilitySelect) self.ItemTabs = QtGui.QTabWidget() # defense self.DefenseTab = QtGui.QTabWidget() # defense -> health self.HealthScroll = QtGui.QScrollArea() self.HealthWidget = QtGui.QWidget() self.HealthWidget.setContentsMargins(0,0,0,0) self.HealthWidget.setStyleSheet('margin: 0px; border: 0px') self.HealthLayout = QtGui.QGridLayout() self.HealthLayout.setHorizontalSpacing(0) self.HealthLayout.setVerticalSpacing(0) # print self.AllButtons self.Buttons = [] for i in ITEMS.GetList('health'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) print self.Buttons x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.HealthLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.HealthWidget.setLayout(self.HealthLayout) self.HealthScroll.setWidget(self.HealthWidget) # defense -> armor self.ArmorScroll = QtGui.QScrollArea() self.ArmorWidget = QtGui.QWidget() self.ArmorLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('armor'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.ArmorLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.ArmorWidget.setLayout(self.ArmorLayout) self.ArmorScroll.setWidget(self.ArmorWidget) # defense -> spell block (resist) self.ResistScroll = QtGui.QScrollArea() self.ResistWidget = QtGui.QWidget() self.ResistLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('spell_block'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.ResistLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.ResistWidget.setLayout(self.ResistLayout) self.ResistScroll.setWidget(self.ResistWidget) # defense -> Health Regen self.HealthRegenScroll = QtGui.QScrollArea() self.HealthRegenWidget = QtGui.QWidget() self.HealthRegenLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('health_regen'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.HealthRegenLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.HealthRegenWidget.setLayout(self.HealthRegenLayout) self.HealthRegenScroll.setWidget(self.HealthRegenWidget) # attack self.AttackTab = QtGui.QTabWidget() # attack -> damage self.DamageScroll = QtGui.QScrollArea() self.DamageWidget = QtGui.QWidget() self.DamageLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('damage'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.DamageLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.DamageWidget.setLayout(self.DamageLayout) self.DamageScroll.setWidget(self.DamageWidget) # attack -> Critical Strike self.CriticalStrikeScroll = QtGui.QScrollArea() self.CriticalStrikeWidget = QtGui.QWidget() self.CriticalStrikeLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('critical_strike'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.CriticalStrikeLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.CriticalStrikeWidget.setLayout(self.CriticalStrikeLayout) self.CriticalStrikeScroll.setWidget(self.CriticalStrikeWidget) # attack -> Attack Speed self.AttackSpeedScroll = QtGui.QScrollArea() self.AttackSpeedWidget = QtGui.QWidget() self.AttackSpeedLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('attack_speed'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.AttackSpeedLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.AttackSpeedWidget.setLayout(self.AttackSpeedLayout) self.AttackSpeedScroll.setWidget(self.AttackSpeedWidget) # attack -> Life Steal self.LifeStealScroll = QtGui.QScrollArea() self.LifeStealWidget = QtGui.QWidget() self.LifeStealLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('life_steal'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.LifeStealLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.LifeStealWidget.setLayout(self.LifeStealLayout) self.LifeStealScroll.setWidget(self.LifeStealWidget) # magic self.MagicTab = QtGui.QTabWidget() # magic -> spell_damage self.PowerScroll = QtGui.QScrollArea() self.PowerWidget = QtGui.QWidget() self.PowerLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('spell_damage'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.PowerLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.PowerWidget.setLayout(self.PowerLayout) self.PowerScroll.setWidget(self.PowerWidget) # magic -> CooldownReduction self.CRScroll = QtGui.QScrollArea() self.CRWidget = QtGui.QWidget() self.CRLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('cooldown_reduction'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.CRLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.CRWidget.setLayout(self.CRLayout) self.CRScroll.setWidget(self.CRWidget) # magic -> Mana self.ManaScroll = QtGui.QScrollArea() self.ManaWidget = QtGui.QWidget() self.ManaLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('mana'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.ManaLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.ManaWidget.setLayout(self.ManaLayout) self.ManaScroll.setWidget(self.ManaWidget) # magic -> Mana_Regen self.ManaRegenScroll = QtGui.QScrollArea() self.ManaRegenWidget = QtGui.QWidget() self.ManaRegenLayout = QtGui.QGridLayout() self.Buttons = [] for i in ITEMS.GetList('mana_regen'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.ManaRegenLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.ManaRegenWidget.setLayout(self.ManaRegenLayout) self.ManaRegenScroll.setWidget(self.ManaRegenWidget) # Movement # Movement -> Movement self.MovementScroll = QtGui.QScrollArea() self.MovementLayout = QtGui.QGridLayout() self.MovementWidget = QtGui.QWidget() self.Buttons = [] for i in ITEMS.GetList('movement'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.MovementLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.MovementWidget.setLayout(self.MovementLayout) self.MovementScroll.setWidget(self.MovementWidget) # Consumeables # Consumeables -> Consumeables self.ConsumScroll = QtGui.QScrollArea() self.ConsumLayout = QtGui.QGridLayout() self.ConsumWidget = QtGui.QWidget() self.Buttons = [] for i in ITEMS.GetList('consumeable'): button = ItemMenu_Button(i) self.Buttons.append(button) self.AllButtons.append(button) x = 0 y = 1 for i in self.Buttons: if x == 2: x = 0 y += 1 self.ConsumLayout.addWidget(i,y,x) x += 1 i.clicked.connect(self.ItemMenu_Button_clicked) self.ConsumWidget.setLayout(self.ConsumLayout) self.ConsumScroll.setWidget(self.ConsumWidget) # # build tab tree self.ItemTabs.addTab(self.DefenseTab,"Defense") self.DefenseTab.addTab(self.HealthScroll,"Health") self.DefenseTab.addTab(self.ResistScroll,"Spell Block") self.DefenseTab.addTab(self.HealthRegenScroll,"Health Regen") self.DefenseTab.addTab(self.ArmorScroll,"Armor") self.ItemTabs.addTab(self.AttackTab,"Attack") self.AttackTab.addTab(self.DamageScroll,"Damage") self.AttackTab.addTab(self.CriticalStrikeScroll,"Critical Strike") self.AttackTab.addTab(self.AttackSpeedScroll,"Attack Speed") self.AttackTab.addTab(self.LifeStealScroll,"Life Steal") self.ItemTabs.addTab(self.MagicTab,"Magic") self.MagicTab.addTab(self.PowerScroll,"Power") self.MagicTab.addTab(self.CRScroll,"Cooldown") self.MagicTab.addTab(self.ManaScroll,"Mana") self.MagicTab.addTab(self.ManaRegenScroll,"Mana Regen") self.ItemTabs.addTab(self.MovementScroll,"Movement") self.ItemTabs.addTab(self.ConsumScroll,"Consumable") self.MasterLayout.addWidget(self.ItemTabs) self.ItemDetails=ItemDetails(self) self.MasterLayout.addWidget(self.ItemDetails) for i in self.AllButtons: i.ItemIconHighLightEvent.connect(self.ItemDetails.SetItemID) # highlight event def ItemMenu_Button_clicked(self,itemid): print itemid self.addItemPressed.emit(itemid) #######################################################
Python
from ftllibs.runes import * import operator import copy import sys import re class Runes(): def __init__(self,parent): self.parent=parent self.RUNES={} self.RunesIndex=[] for i in sys.modules.keys(): m = re.match('ftllibs.runes.(r_[a-z_.]+)',i) if m: self.RunesIndex.append(m.groups(0)[0]) self.InitRunes() self.CreateLists() def InitRunes(self): for i in self.RunesIndex: # rune = None cmd = "self.RUNES['%s']=%s.Rune()" % (i,i) exec cmd # self.RUNES[rune.Name]=rune # self.ITEMS['3001']=i3001.Item_3001() def GetRune(self,runename): return self.RUNES[runename] def GetRuneCopy(self,runename): return copy.deepcopy(self.RUNES[runename]) def CreateLists(self): self.SortedLists={} for runename in self.RunesIndex: for i in self.RUNES[runename].Tags: if not self.SortedLists.has_key(i): self.SortedLists[i]=[] self.SortedLists[i].append(runename) else: self.SortedLists[i].append(runename) for i in self.SortedLists: costs = {} #for var in collection: for j in self.SortedLists[i]: costs[j] = self.RUNES[j].Costs self.SortedLists[i] = [] for k,l in sorted(costs.iteritems(), key=operator.itemgetter(1)): self.SortedLists[i].append(k) def GetList(self,string): #attack_speed #life_steal #spell_damage #armor #magic_resist #damage #health_regen #mana #health #movement #mana_regen #critical_strike #cooldown_reduction #armor_penetration #magic_penetration return self.SortedLists[string]
Python
import ConfigParser import string import random import glob import re from PyQt4 import QtGui,QtCore class BuildDataStore(object): def __init__(self): super(BuildDataStore,self).__init__() self.openmodels={} def GetBuildDataModel(self,ChampID): if self.openmodels.has_key(ChampID): return self.openmodels[ChampID] else: build=BuildDataModel(ChampID) self.openmodels[ChampID]=build return self.openmodels[ChampID] def GetAvailableChampSaves(self): savelist=glob.glob("saves/builds/*.sav") for i in range(len(savelist)): m=re.search('(\d+)',savelist[i]) if m: savelist[i]=m.groups(1)[0] return savelist class RecommendedDataStore(object): def __init__(self): super(RecommendedDataStore,self).__init__() self.RecommendedModel=RecommendedDataModel() def GetRecommendedDataModel(self): return self.RecommendedModel class MasteriesDataStore(object): def __init__(self): super(MasteriesDataStore,self).__init__() self.MasteriesModel=MasteriesDataModel() def GetMasteriesDataModel(self): return self.MasteriesModel class MasteriesDataModel(QtCore.QAbstractListModel): def __init__(self): super(MasteriesDataModel,self).__init__() self.config=ConfigParser.SafeConfigParser() print "MasteriesdataModel Created" self.config.read("saves/masteries.sav") self.CurrentMasteries="" self.UpdateMasteriesIndex() def UpdateMasteriesIndex(self): MasteriesList={} self.MasteriesIndex=[] for i in self.config.sections(): MasteriesList[int(self.config.get(i,"position"))]=i for i in sorted(MasteriesList.keys()): self.MasteriesIndex.append(MasteriesList[i]) def UpdatePosition(self): pos = 1 for i in self.MasteriesIndex: self.config.set(i,"position",str(pos)) pos +=1 self.saveConfig() def rowCount(self,parent = QtCore.QModelIndex()): return len(self.config.sections()) def data(self,index,role): if role == QtCore.Qt.DisplayRole: MID=self.MasteriesIndex[index.row()] return self.config.get(MID,"name") def flags(self, index): return (QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) def insertRows(self,position,rows,name,parent = QtCore.QModelIndex()): self.beginInsertRows(parent, position, position + rows - 1) MID = GenerateRandomString() position = self.getLastPosition() self.config.add_section(MID) self.config.set(MID,"position",str(position)) self.config.set(MID,"name",str(name)) # offensive self.config.set(MID,"SummonersWrath","0") self.config.set(MID,"BruteForce","0") self.config.set(MID,"MentalForce","0") self.config.set(MID,"Butcher","0") self.config.set(MID,"Alacrity","0") self.config.set(MID,"Sorcery","0") self.config.set(MID,"Demolitionist","0") self.config.set(MID,"Deadliness","0") self.config.set(MID,"WeaponsExpertise","0") self.config.set(MID,"ArcaneKnowledge","0") self.config.set(MID,"Havoc","0") self.config.set(MID,"Lethality","0") self.config.set(MID,"Vampirism","0") self.config.set(MID,"Blast","0") self.config.set(MID,"Sunder","0") self.config.set(MID,"Archmage","0") self.config.set(MID,"Executioner","0") # defensive self.config.set(MID,"SummonersResolve","0") self.config.set(MID,"Resistance","0") self.config.set(MID,"Hardiness","0") self.config.set(MID,"ToughSkin","0") self.config.set(MID,"Durability","0") self.config.set(MID,"Vigor","0") self.config.set(MID,"Indomitable","0") self.config.set(MID,"VeteransScars","0") self.config.set(MID,"Evasion","0") self.config.set(MID,"BladedArmor","0") self.config.set(MID,"SiegeCommander","0") self.config.set(MID,"Initiator","0") self.config.set(MID,"Enlightenment","0") self.config.set(MID,"HonorGuard","0") self.config.set(MID,"Mercenary","0") self.config.set(MID,"Juggernaut","0") # utility self.config.set(MID,"SummonersInsight","0") self.config.set(MID,"GoodHands","0") self.config.set(MID,"ExpandedMind","0") self.config.set(MID,"ImprovedRecall","0") self.config.set(MID,"Swiftness","0") self.config.set(MID,"Meditation","0") self.config.set(MID,"Scout","0") self.config.set(MID,"Greed","0") self.config.set(MID,"Transmutation","0") self.config.set(MID,"RunicAffinity","0") self.config.set(MID,"Wealth","0") self.config.set(MID,"Awareness","0") self.config.set(MID,"Sage","0") self.config.set(MID,"StrengthOfSpirit","0") self.config.set(MID,"Intelligence","0") self.config.set(MID,"Mastermind","0") self.endInsertRows() self.saveConfig() self.UpdateMasteriesIndex() return True def getLastPosition(self): return len(self.MasteriesIndex)+1 def removeRows(self, position, rows, parent = QtCore.QModelIndex()): self.beginRemoveRows(parent, position, position + rows - 1) MID=self.MasteriesIndex[position] self.config.remove_section(MID) del self.MasteriesIndex[position] self.endRemoveRows() self.UpdatePosition() return True def getMID(self,pos): return self.MasteriesIndex[pos] def setData(self, index, value, role = QtCore.Qt.EditRole): if role == QtCore.Qt.EditRole: #row = index.row() #name=value MID=self.MasteriesIndex[index.row()] self.config.set(MID,"name",str(value.toString())) self.saveConfig() return True return False def saveConfig(self): FILE=open("saves/masteries.sav","w") self.config.write(FILE) FILE.close() print "SavedDataStore: saveConfig: Config written: Masteries.sav" def saveMasteries(self,mastery): print "SavedDataStore: saveMasteries: 'mastery': ",mastery for key,value in sorted(mastery.iteritems()): if value: self.config.set(self.CurrentMID,key,str(value)) else: self.config.set(self.CurrentMID,key,"0") self.saveConfig() def loadMasteries(self,MID): mastery = {} mastery["SummonersWrath"]=self.config.get(MID,"SummonersWrath") mastery["BruteForce"]=self.config.get(MID,"BruteForce") mastery["MentalForce"]=self.config.get(MID,"MentalForce") mastery["Butcher"]=self.config.get(MID,"Butcher") mastery["Alacrity"]=self.config.get(MID,"Alacrity") mastery["Sorcery"]=self.config.get(MID,"Sorcery") mastery["Demolitionist"]=self.config.get(MID,"Demolitionist") mastery["Deadliness"]=self.config.get(MID,"Deadliness") mastery["WeaponsExpertise"]=self.config.get(MID,"WeaponsExpertise") mastery["ArcaneKnowledge"]=self.config.get(MID,"ArcaneKnowledge") mastery["Havoc"]=self.config.get(MID,"Havoc") mastery["Lethality"]=self.config.get(MID,"Lethality") mastery["Vampirism"]=self.config.get(MID,"Vampirism") mastery["Blast"]=self.config.get(MID,"Blast") mastery["Sunder"]=self.config.get(MID,"Sunder") mastery["Archmage"]=self.config.get(MID,"Archmage") mastery["Executioner"]=self.config.get(MID,"Executioner") # defensive mastery["SummonersResolve"]=self.config.get(MID,"SummonersResolve") mastery["Resistance"]=self.config.get(MID,"Resistance") mastery["Hardiness"]=self.config.get(MID,"Hardiness") mastery["ToughSkin"]=self.config.get(MID,"ToughSkin") mastery["Durability"]=self.config.get(MID,"Durability") mastery["Vigor"]=self.config.get(MID,"Vigor") mastery["Indomitable"]=self.config.get(MID,"Indomitable") mastery["VeteransScars"]=self.config.get(MID,"VeteransScars") mastery["Evasion"]=self.config.get(MID,"Evasion") mastery["BladedArmor"]=self.config.get(MID,"BladedArmor") mastery["SiegeCommander"]=self.config.get(MID,"SiegeCommander") mastery["Initiator"]=self.config.get(MID,"Initiator") mastery["Enlightenment"]=self.config.get(MID,"Enlightenment") mastery["HonorGuard"]=self.config.get(MID,"HonorGuard") mastery["Mercenary"]=self.config.get(MID,"Mercenary") mastery["Juggernaut"]=self.config.get(MID,"Juggernaut") # utility mastery["SummonersInsight"]=self.config.get(MID,"SummonersInsight") mastery["GoodHands"]=self.config.get(MID,"GoodHands") mastery["ExpandedMind"]=self.config.get(MID,"ExpandedMind") mastery["ImprovedRecall"]=self.config.get(MID,"ImprovedRecall") mastery["Swiftness"]=self.config.get(MID,"Swiftness") mastery["Meditation"]=self.config.get(MID,"Meditation") mastery["Scout"]=self.config.get(MID,"Scout") mastery["Greed"]=self.config.get(MID,"Greed") mastery["Transmutation"]=self.config.get(MID,"Transmutation") mastery["RunicAffinity"]=self.config.get(MID,"RunicAffinity") mastery["Wealth"]=self.config.get(MID,"Wealth") mastery["Awareness"]=self.config.get(MID,"Awareness") mastery["Sage"]=self.config.get(MID,"Sage") mastery["StrengthOfSpirit"]=self.config.get(MID,"StrengthOfSpirit") mastery["Intelligence"]=self.config.get(MID,"Intelligence") mastery["Mastermind"]=self.config.get(MID,"Mastermind") mastery['MID']=MID mastery['position']=self.config.get(MID,"position") mastery['name']=self.config.get(MID,"name") self.CurrentMID=MID return mastery class BuildDataModel(QtCore.QAbstractListModel): def __init__(self,ChampID, parent = None): super(BuildDataModel,self).__init__() self.ChampID=ChampID self.config=ConfigParser.SafeConfigParser() print "BuildDataModel Created ->",ChampID self.config.read("saves/builds/%s.sav" % (self.ChampID)) self.CurrentBID="" self.UpdateBuildIndex() def UpdateBuildIndex(self): buildlist={} self.BuildIndex=[] for i in self.config.sections(): buildlist[int(self.config.get(i,"position"))]=i for i in sorted(buildlist.keys()): self.BuildIndex.append(buildlist[i]) # self.BuildIndex=self.config.sections() def UpdatePosition(self): pos = 1 for i in self.BuildIndex: self.config.set(i,"position",str(pos)) pos += 1 self.saveConfig() def rowCount(self,parent = QtCore.QModelIndex()): return len(self.config.sections()) def data(self,index,role): if role == QtCore.Qt.DisplayRole: # print "row: ",index.row() # print "len buildindex, ",len(self.BuildIndex) BID=self.BuildIndex[index.row()] return self.config.get(BID,"name") def flags(self, index): return (QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) def insertRows(self,position,rows,name,parent = QtCore.QModelIndex()): self.beginInsertRows(parent, position, position + rows - 1) BID = GenerateRandomString() position = self.getLastPosition() self.config.add_section(BID) self.config.set(BID,"name",str(name)) self.config.set(BID,"position",str(position)) self.config.set(BID,"Item1","None") self.config.set(BID,"Item2","None") self.config.set(BID,"Item3","None") self.config.set(BID,"Item4","None") self.config.set(BID,"Item5","None") self.config.set(BID,"Item6","None") self.endInsertRows() self.saveConfig() self.UpdateBuildIndex() return True def getLastPosition(self): return len(self.BuildIndex)+1 def removeRows(self, position, rows, parent = QtCore.QModelIndex()): self.beginRemoveRows(parent, position, position + rows - 1) BID=self.BuildIndex[position] self.config.remove_section(BID) del self.BuildIndex[position] self.endRemoveRows() self.UpdatePosition() return True def getBID(self,pos): return self.BuildIndex[pos] def setData(self, index, value, role = QtCore.Qt.EditRole): if role == QtCore.Qt.EditRole: #row = index.row() #name=value BID=self.BuildIndex[index.row()] self.config.set(BID,"name",str(value.toString())) self.saveConfig() return True return False def saveConfig(self): FILE=open("saves/builds/%s.sav" % (self.ChampID),"w") self.config.write(FILE) FILE.close() print "SavedDataStore: saveConfig: Config written: " def saveBuild(self,build): print "SavedDataStore: saveBuild: 'build': ",build for key,value in sorted(build.iteritems()): if value: self.config.set(self.CurrentBID,"Item%s" % key,str(value.ID)) else: self.config.set(self.CurrentBID,"Item%s" % key,"None") self.saveConfig() def loadBuild(self,BID): build = {} build['Item1']=self.config.get(BID,"Item1") build['Item2']=self.config.get(BID,"Item2") build['Item3']=self.config.get(BID,"Item3") build['Item4']=self.config.get(BID,"Item4") build['Item5']=self.config.get(BID,"Item5") build['Item6']=self.config.get(BID,"Item6") build['Name']=self.config.get(BID,"name") build['BID']=BID self.CurrentBID=BID return build def GenerateRandomString(size=20, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for i in range(size)) ############### #### Runes #### ############### class RunesDataStore(object): def __init__(self): super(RunesDataStore,self).__init__() self.RunesModel=RunesDataModel() def GetRunesDataModel(self): return self.RunesModel class RunesDataModel(QtCore.QAbstractListModel): def __init__(self): super(RunesDataModel,self).__init__() self.config=ConfigParser.SafeConfigParser() print "RunesdataModel Created" self.config.read("saves/runes.sav") self.CurrentRunes="" self.UpdateRunesIndex() def UpdateRunesIndex(self): RunesList={} self.RunesIndex=[] for i in self.config.sections(): RunesList[int(self.config.get(i,"position"))]=i for i in sorted(RunesList.keys()): self.RunesIndex.append(RunesList[i]) def UpdatePosition(self): pos = 1 for i in self.RunesIndex: self.config.set(i,"position",str(pos)) pos +=1 self.saveConfig() def rowCount(self,parent = QtCore.QModelIndex()): return len(self.config.sections()) def data(self,index,role): if role == QtCore.Qt.DisplayRole: RID=self.RunesIndex[index.row()] return self.config.get(RID,"name") def flags(self, index): return (QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) def insertRows(self,position,rows,name,parent = QtCore.QModelIndex()): self.beginInsertRows(parent, position, position + rows - 1) RID = GenerateRandomString() position = self.getLastPosition() self.config.add_section(RID) self.config.set(RID,"position",str(position)) self.config.set(RID,"name",str(name)) # marks self.config.set(RID,"mark1","None") self.config.set(RID,"mark2","None") self.config.set(RID,"mark3","None") self.config.set(RID,"mark4","None") self.config.set(RID,"mark5","None") self.config.set(RID,"mark6","None") self.config.set(RID,"mark7","None") self.config.set(RID,"mark8","None") self.config.set(RID,"mark9","None") # seals self.config.set(RID,"seal1","None") self.config.set(RID,"seal2","None") self.config.set(RID,"seal3","None") self.config.set(RID,"seal4","None") self.config.set(RID,"seal5","None") self.config.set(RID,"seal6","None") self.config.set(RID,"seal7","None") self.config.set(RID,"seal8","None") self.config.set(RID,"seal9","None") # glyphs self.config.set(RID,"glyph1","None") self.config.set(RID,"glyph2","None") self.config.set(RID,"glyph3","None") self.config.set(RID,"glyph4","None") self.config.set(RID,"glyph5","None") self.config.set(RID,"glyph6","None") self.config.set(RID,"glyph7","None") self.config.set(RID,"glyph8","None") self.config.set(RID,"glyph9","None") # quintessence self.config.set(RID,"quintessence1","None") self.config.set(RID,"quintessence2","None") self.config.set(RID,"quintessence3","None") self.endInsertRows() self.saveConfig() self.UpdateRunesIndex() return True def getLastPosition(self): return len(self.RunesIndex)+1 def removeRows(self, position, rows, parent = QtCore.QModelIndex()): self.beginRemoveRows(parent, position, position + rows - 1) RID=self.RunesIndex[position] self.config.remove_section(RID) del self.RunesIndex[position] self.endRemoveRows() self.UpdatePosition() return True def getRID(self,pos): return self.RunesIndex[pos] def setData(self, index, value, role = QtCore.Qt.EditRole): if role == QtCore.Qt.EditRole: #row = index.row() #name=value RID=self.RunesIndex[index.row()] self.config.set(RID,"name",str(value.toString())) self.saveConfig() return True return False def saveConfig(self): FILE=open("saves/runes.sav","w") self.config.write(FILE) FILE.close() print "SavedDataStore: saveConfig: Config written: runes.sav" def saveRunes(self,runes): print "SavedDataStore: saveRunes: 'runes': ",runes for key,value in sorted(runes.iteritems()): if value: self.config.set(self.CurrentRID,key,str(value)) else: self.config.set(self.CurrentRID,key,"None") self.saveConfig() def loadRunes(self,RID): runes = {} runes["mark1"]=self.config.get(RID,"mark1") runes["mark2"]=self.config.get(RID,"mark2") runes["mark3"]=self.config.get(RID,"mark3") runes["mark4"]=self.config.get(RID,"mark4") runes["mark5"]=self.config.get(RID,"mark5") runes["mark6"]=self.config.get(RID,"mark6") runes["mark7"]=self.config.get(RID,"mark7") runes["mark8"]=self.config.get(RID,"mark8") runes["mark9"]=self.config.get(RID,"mark9") runes["seal1"]=self.config.get(RID,"seal1") runes["seal2"]=self.config.get(RID,"seal2") runes["seal3"]=self.config.get(RID,"seal3") runes["seal4"]=self.config.get(RID,"seal4") runes["seal5"]=self.config.get(RID,"seal5") runes["seal6"]=self.config.get(RID,"seal6") runes["seal7"]=self.config.get(RID,"seal7") runes["seal8"]=self.config.get(RID,"seal8") runes["seal9"]=self.config.get(RID,"seal9") runes["glyph1"]=self.config.get(RID,"glyph1") runes["glyph2"]=self.config.get(RID,"glyph2") runes["glyph3"]=self.config.get(RID,"glyph3") runes["glyph4"]=self.config.get(RID,"glyph4") runes["glyph5"]=self.config.get(RID,"glyph5") runes["glyph6"]=self.config.get(RID,"glyph6") runes["glyph7"]=self.config.get(RID,"glyph7") runes["glyph8"]=self.config.get(RID,"glyph8") runes["glyph9"]=self.config.get(RID,"glyph9") runes["quintessence1"]=self.config.get(RID,"quintessence1") runes["quintessence2"]=self.config.get(RID,"quintessence2") runes["quintessence3"]=self.config.get(RID,"quintessence3") runes['RID']=RID runes['position']=self.config.get(RID,"position") runes['name']=self.config.get(RID,"name") self.CurrentRID=RID return runes class RecommendedDataModel(QtCore.QAbstractListModel): def __init__(self): super(RecommendedDataModel,self).__init__() self.config=ConfigParser.SafeConfigParser() print "RecommendeddataModel Created" self.config.read("saves/recommended.sav") self.CurrentRecommended="" self.CurrentRCID="" self.UpdateRecommendedIndex() def UpdateRecommendedIndex(self): RecommendedList={} self.RecommendedIndex=[] for i in self.config.sections(): RecommendedList[int(self.config.get(i,"position"))]=i for i in sorted(RecommendedList.keys()): self.RecommendedIndex.append(RecommendedList[i]) def UpdatePosition(self): pos = 1 for i in self.RecommendedIndex: self.config.set(i,"position",str(pos)) pos +=1 self.saveConfig() def rowCount(self,parent = QtCore.QModelIndex()): return len(self.config.sections()) def data(self,index,role): if role == QtCore.Qt.DisplayRole: RCID=self.RecommendedIndex[index.row()] return self.config.get(RCID,"title") def flags(self, index): return (QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) def insertRows(self,position,rows,name,parent = QtCore.QModelIndex()): self.beginInsertRows(parent, position, position + rows - 1) RCID = GenerateRandomString() position = self.getLastPosition() self.CurrentRCID=RCID self.config.add_section(RCID) self.config.set(RCID,"position",str(position)) self.config.set(RCID,"title",str(name)) self.config.set(RCID,"champion","None") self.config.set(RCID,"type","custom") self.config.set(RCID,"map","any") self.config.set(RCID,"priority","true") self.config.set(RCID,"section1name","starting") self.config.set(RCID,"section2name","essential") self.config.set(RCID,"section3name","offensive") self.config.set(RCID,"section4name","defensive") self.config.set(RCID,"section1item1","None") self.config.set(RCID,"section1item2","None") self.config.set(RCID,"section1item3","None") self.config.set(RCID,"section1item4","None") self.config.set(RCID,"section1item5","None") self.config.set(RCID,"section1item6","None") self.config.set(RCID,"section1item7","None") self.config.set(RCID,"section1item8","None") self.config.set(RCID,"section2item1","None") self.config.set(RCID,"section2item2","None") self.config.set(RCID,"section2item3","None") self.config.set(RCID,"section2item4","None") self.config.set(RCID,"section2item5","None") self.config.set(RCID,"section2item6","None") self.config.set(RCID,"section2item7","None") self.config.set(RCID,"section2item8","None") self.config.set(RCID,"section3item1","None") self.config.set(RCID,"section3item2","None") self.config.set(RCID,"section3item3","None") self.config.set(RCID,"section3item4","None") self.config.set(RCID,"section3item5","None") self.config.set(RCID,"section3item6","None") self.config.set(RCID,"section3item7","None") self.config.set(RCID,"section3item8","None") self.config.set(RCID,"section4item1","None") self.config.set(RCID,"section4item2","None") self.config.set(RCID,"section4item3","None") self.config.set(RCID,"section4item4","None") self.config.set(RCID,"section4item5","None") self.config.set(RCID,"section4item6","None") self.config.set(RCID,"section4item7","None") self.config.set(RCID,"section4item8","None") self.config.set(RCID,"section1count1","1") self.config.set(RCID,"section1count2","1") self.config.set(RCID,"section1count3","1") self.config.set(RCID,"section1count4","1") self.config.set(RCID,"section1count5","1") self.config.set(RCID,"section1count6","1") self.config.set(RCID,"section1count7","1") self.config.set(RCID,"section1count8","1") self.config.set(RCID,"section2count1","1") self.config.set(RCID,"section2count2","1") self.config.set(RCID,"section2count3","1") self.config.set(RCID,"section2count4","1") self.config.set(RCID,"section2count5","1") self.config.set(RCID,"section2count6","1") self.config.set(RCID,"section2count7","1") self.config.set(RCID,"section2count8","1") self.config.set(RCID,"section3count1","1") self.config.set(RCID,"section3count2","1") self.config.set(RCID,"section3count3","1") self.config.set(RCID,"section3count4","1") self.config.set(RCID,"section3count5","1") self.config.set(RCID,"section3count6","1") self.config.set(RCID,"section3count7","1") self.config.set(RCID,"section3count8","1") self.config.set(RCID,"section4count1","1") self.config.set(RCID,"section4count2","1") self.config.set(RCID,"section4count3","1") self.config.set(RCID,"section4count4","1") self.config.set(RCID,"section4count5","1") self.config.set(RCID,"section4count6","1") self.config.set(RCID,"section4count7","1") self.config.set(RCID,"section4count8","1") self.endInsertRows() self.saveConfig() self.UpdateRecommendedIndex() return True def getLastPosition(self): return len(self.RecommendedIndex)+1 def removeRows(self, position, rows, parent = QtCore.QModelIndex()): self.beginRemoveRows(parent, position, position + rows - 1) RCID=self.RecommendedIndex[position] self.config.remove_section(RCID) del self.RecommendedIndex[position] self.endRemoveRows() self.UpdatePosition() return True def getRCID(self,pos): return self.RecommendedIndex[pos] def setData(self, index, value, role = QtCore.Qt.EditRole): if role == QtCore.Qt.EditRole: #row = index.row() #name=value RCID=self.RecommendedIndex[index.row()] self.config.set(RCID,"title",str(value.toString())) self.saveConfig() return True return False def saveConfig(self): FILE=open("saves/recommended.sav","w") self.config.write(FILE) FILE.close() print "SavedDataStore: saveConfig: Config written: Recommended.sav" def saveRecommended(self,Recommended): print "SavedDataStore: saveRecommended: 'Recommended': ",Recommended for key,value in sorted(Recommended.iteritems()): if value: self.config.set(self.CurrentRCID,key,str(value)) else: self.config.set(self.CurrentRCID,key,"None") self.saveConfig() def loadRecommended(self,RCID): Recommended = {} Recommended["champion"]=self.config.get(RCID,"champion") Recommended["type"]=self.config.get(RCID,"type") Recommended["map"]=self.config.get(RCID,"map") Recommended["priority"]=self.config.get(RCID,"priority") Recommended["section1name"]=self.config.get(RCID,"section1name") Recommended["section2name"]=self.config.get(RCID,"section2name") Recommended["section3name"]=self.config.get(RCID,"section3name") Recommended["section4name"]=self.config.get(RCID,"section4name") #Recommended['RCID']=RCID Recommended['position']=self.config.get(RCID,"position") Recommended['title']=self.config.get(RCID,"title") Recommended["section1item1"]=self.config.get(RCID,"section1item1") Recommended["section1item2"]=self.config.get(RCID,"section1item2") Recommended["section1item3"]=self.config.get(RCID,"section1item3") Recommended["section1item4"]=self.config.get(RCID,"section1item4") Recommended["section1item5"]=self.config.get(RCID,"section1item5") Recommended["section1item6"]=self.config.get(RCID,"section1item6") Recommended["section1item7"]=self.config.get(RCID,"section1item7") Recommended["section1item8"]=self.config.get(RCID,"section1item8") Recommended["section2item1"]=self.config.get(RCID,"section2item1") Recommended["section2item2"]=self.config.get(RCID,"section2item2") Recommended["section2item3"]=self.config.get(RCID,"section2item3") Recommended["section2item4"]=self.config.get(RCID,"section2item4") Recommended["section2item5"]=self.config.get(RCID,"section2item5") Recommended["section2item6"]=self.config.get(RCID,"section2item6") Recommended["section2item7"]=self.config.get(RCID,"section2item7") Recommended["section2item8"]=self.config.get(RCID,"section2item8") Recommended["section3item1"]=self.config.get(RCID,"section3item1") Recommended["section3item2"]=self.config.get(RCID,"section3item2") Recommended["section3item3"]=self.config.get(RCID,"section3item3") Recommended["section3item4"]=self.config.get(RCID,"section3item4") Recommended["section3item5"]=self.config.get(RCID,"section3item5") Recommended["section3item6"]=self.config.get(RCID,"section3item6") Recommended["section3item7"]=self.config.get(RCID,"section3item7") Recommended["section3item8"]=self.config.get(RCID,"section3item8") Recommended["section4item1"]=self.config.get(RCID,"section4item1") Recommended["section4item2"]=self.config.get(RCID,"section4item2") Recommended["section4item3"]=self.config.get(RCID,"section4item3") Recommended["section4item4"]=self.config.get(RCID,"section4item4") Recommended["section4item5"]=self.config.get(RCID,"section4item5") Recommended["section4item6"]=self.config.get(RCID,"section4item6") Recommended["section4item7"]=self.config.get(RCID,"section4item7") Recommended["section4item8"]=self.config.get(RCID,"section4item8") Recommended["section1count1"]=self.config.get(RCID,"section1count1") Recommended["section1count2"]=self.config.get(RCID,"section1count2") Recommended["section1count3"]=self.config.get(RCID,"section1count3") Recommended["section1count4"]=self.config.get(RCID,"section1count4") Recommended["section1count5"]=self.config.get(RCID,"section1count5") Recommended["section1count6"]=self.config.get(RCID,"section1count6") Recommended["section1count7"]=self.config.get(RCID,"section1count7") Recommended["section1count8"]=self.config.get(RCID,"section1count8") Recommended["section2count1"]=self.config.get(RCID,"section2count1") Recommended["section2count2"]=self.config.get(RCID,"section2count2") Recommended["section2count3"]=self.config.get(RCID,"section2count3") Recommended["section2count4"]=self.config.get(RCID,"section2count4") Recommended["section2count5"]=self.config.get(RCID,"section2count5") Recommended["section2count6"]=self.config.get(RCID,"section2count6") Recommended["section2count7"]=self.config.get(RCID,"section2count7") Recommended["section2count8"]=self.config.get(RCID,"section2count8") Recommended["section3count1"]=self.config.get(RCID,"section3count1") Recommended["section3count2"]=self.config.get(RCID,"section3count2") Recommended["section3count3"]=self.config.get(RCID,"section3count3") Recommended["section3count4"]=self.config.get(RCID,"section3count4") Recommended["section3count5"]=self.config.get(RCID,"section3count5") Recommended["section3count6"]=self.config.get(RCID,"section3count6") Recommended["section3count7"]=self.config.get(RCID,"section3count7") Recommended["section3count8"]=self.config.get(RCID,"section3count8") Recommended["section4count1"]=self.config.get(RCID,"section4count1") Recommended["section4count2"]=self.config.get(RCID,"section4count2") Recommended["section4count3"]=self.config.get(RCID,"section4count3") Recommended["section4count4"]=self.config.get(RCID,"section4count4") Recommended["section4count5"]=self.config.get(RCID,"section4count5") Recommended["section4count6"]=self.config.get(RCID,"section4count6") Recommended["section4count7"]=self.config.get(RCID,"section4count7") Recommended["section4count8"]=self.config.get(RCID,"section4count8") self.CurrentRCID=RCID return Recommended
Python
#!/usr/bin/python import xml.parsers.expat; import sys; import re; parser=xml.parsers.expat.ParserCreate('UTF-8'); values_en = {} values_lang = {} values_hash = {} name='' def parse(lang, values): def start_element(n, attrs): global name; if n != u'string': return name=attrs[u'name'] def end_element(n): global name; name='' def char_data(value): global name; if name == '': return; if not name in values: values[name] = u''; values[name] += value; p = xml.parsers.expat.ParserCreate() p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data if lang == 'en': f=open('res/values/strings.xml'); else: f=open('res/values-%s/strings.xml' % lang); p.ParseFile(f); def parse_R(file, values): try: for line in open(file): match = re.search(".*public static final int (.*)=0x(.*);", line) if match: values[match.group(1)] = match.group(2) except: sys.exit(1) parse('en', values_en); parse_R('gen/com/volosyukivan/R.java', values_lang); page=open('html/key.html').read(); for num,(key,orig) in enumerate( sorted(values_en.iteritems(), key=lambda x:len(x[1]), reverse=True)): if not key in values_lang: continue; replacement = '##//$$$%s$$$//##' % num; values_hash[key] = replacement; page = page.replace(orig, replacement); for key,repl in values_lang.iteritems(): if not key in values_hash: continue; orig = values_hash[key]; replacement = '$' + values_lang[key]; page = page.replace(orig, replacement); old = None try: old = open("res/raw/key.html").read(); except: pass if (old != page): open("res/raw/key.html", "w").write(page.encode('UTF-8'));
Python
#!/usr/bin/python from optparse import OptionParser import re import subprocess import sys """ This script generates a release note from the output of git log between the specified tags. Options: --issues Show output the commits with issues associated with them. --issue-numbers Show outputs issue numbers of the commits with issues associated with them Arguments: since -- tag name until -- tag name Example Input: * <commit subject> + <commit message> Bug: issue 123 Change-Id: <change id> Signed-off-by: <name> Expected Output: * issue 123 <commit subject> + <commit message> """ parser = OptionParser(usage='usage: %prog [options] <since> <until>') parser.add_option('-i', '--issues', action='store_true', dest='issues_only', default=False, help='only output the commits with issues association') parser.add_option('-n', '--issue-numbers', action='store_true', dest='issue_numbers_only', default=False, help='only outputs issue numbers of the commits with \ issues association') (options, args) = parser.parse_args() if len(args) != 2: parser.error("wrong number of arguments") issues_only = options.issues_only issue_numbers_only = options.issue_numbers_only since_until = args[0] + '..' + args[1] proc = subprocess.Popen(['git', 'log', '--reverse', '--no-merges', since_until, "--format=* %s%n+%n%b"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,) stdout_value = proc.communicate()[0] subject = "" message = [] is_issue = False # regex pattern to match following cases such as Bug: 123, Issue Bug: 123, # Bug: GERRIT-123, Bug: issue 123, Bug issue: 123, issue: 123, issue: bug 123 p = re.compile('bug: GERRIT-|bug(:? issue)?:? |issue(:? bug)?:? ', re.IGNORECASE) if issue_numbers_only: for line in stdout_value.splitlines(True): if p.match(line): sys.stdout.write(p.sub('', line)) else: for line in stdout_value.splitlines(True): # Move issue number to subject line if p.match(line): line = p.sub('issue ', line).replace('\n',' ') subject = subject[:2] + line + subject[2:] is_issue = True elif line.startswith('* '): # Write change log for a commit if subject != "": if (not issues_only or is_issue): # Write subject sys.stdout.write(subject) # Write message lines if message != []: # Clear + from last line in commit message message[-1] = '\n' for m in message: sys.stdout.write(m) # Start new commit block message = [] subject = line is_issue = False # Remove commit footers elif re.match(r'((\w+-)+\w+:)', line): continue # Don't add extra blank line if last one is already blank elif line == '\n' and message and message[-1] != '+\n': message.append('+\n') elif line != '\n': message.append(line)
Python
#!/usr/bin/env python import commands import getopt import sys SSH_USER = 'bot' SSH_HOST = 'localhost' SSH_PORT = 29418 SSH_COMMAND = 'ssh %s@%s -p %d gerrit approve ' % (SSH_USER, SSH_HOST, SSH_PORT) FAILURE_SCORE = '--code-review=-2' FAILURE_MESSAGE = 'This commit message does not match the standard.' \ + ' Please correct the commit message and upload a replacement patch.' PASS_SCORE = '--code-review=0' PASS_MESSAGE = '' def main(): change = None project = None branch = None commit = None patchset = None try: opts, args = getopt.getopt(sys.argv[1:], '', \ ['change=', 'project=', 'branch=', 'commit=', 'patchset=']) except getopt.GetoptError, err: print 'Error: %s' % (err) usage() sys.exit(-1) for arg, value in opts: if arg == '--change': change = value elif arg == '--project': project = value elif arg == '--branch': branch = value elif arg == '--commit': commit = value elif arg == '--patchset': patchset = value else: print 'Error: option %s not recognized' % (arg) usage() sys.exit(-1) if change == None or project == None or branch == None \ or commit == None or patchset == None: usage() sys.exit(-1) command = 'git cat-file commit %s' % (commit) status, output = commands.getstatusoutput(command) if status != 0: print 'Error running \'%s\'. status: %s, output:\n\n%s' % \ (command, status, output) sys.exit(-1) commitMessage = output[(output.find('\n\n')+2):] commitLines = commitMessage.split('\n') if len(commitLines) > 1 and len(commitLines[1]) != 0: fail(commit, 'Invalid commit summary. The summary must be ' \ + 'one line followed by a blank line.') i = 0 for line in commitLines: i = i + 1 if len(line) > 80: fail(commit, 'Line %d is over 80 characters.' % i) passes(commit) def usage(): print 'Usage:\n' print sys.argv[0] + ' --change <change id> --project <project name> ' \ + '--branch <branch> --commit <sha1> --patchset <patchset id>' def fail( commit, message ): command = SSH_COMMAND + FAILURE_SCORE + ' -m \\\"' \ + _shell_escape( FAILURE_MESSAGE + '\n\n' + message) \ + '\\\" ' + commit commands.getstatusoutput(command) sys.exit(1) def passes( commit ): command = SSH_COMMAND + PASS_SCORE + ' -m \\\"' \ + _shell_escape(PASS_MESSAGE) + ' \\\" ' + commit commands.getstatusoutput(command) def _shell_escape(x): s = '' for c in x: if c in '\n': s = s + '\\\"$\'\\n\'\\\"' else: s = s + c return s if __name__ == '__main__': main()
Python
#!/usr/bin/env python2.6 # Copyright (c) 2010, Code Aurora Forum. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # Neither the name of Code Aurora Forum, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED # WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # This script is designed to detect when a patchset uploaded to Gerrit is # 'identical' (determined via git-patch-id) and reapply reviews onto the new # patchset from the previous patchset. # Get usage and help info by running: ./trivial_rebase.py --help # Documentation is available here: https://www.codeaurora.org/xwiki/bin/QAEP/Gerrit import json from optparse import OptionParser import subprocess from sys import exit class CheckCallError(OSError): """CheckCall() returned non-0.""" def __init__(self, command, cwd, retcode, stdout, stderr=None): OSError.__init__(self, command, cwd, retcode, stdout, stderr) self.command = command self.cwd = cwd self.retcode = retcode self.stdout = stdout self.stderr = stderr def CheckCall(command, cwd=None): """Like subprocess.check_call() but returns stdout. Works on python 2.4 """ try: process = subprocess.Popen(command, cwd=cwd, stdout=subprocess.PIPE) std_out, std_err = process.communicate() except OSError, e: raise CheckCallError(command, cwd, e.errno, None) if process.returncode: raise CheckCallError(command, cwd, process.returncode, std_out, std_err) return std_out, std_err def GsqlQuery(sql_query, server, port): """Runs a gerrit gsql query and returns the result""" gsql_cmd = ['ssh', '-p', port, server, 'gerrit', 'gsql', '--format', 'JSON', '-c', sql_query] try: (gsql_out, gsql_stderr) = CheckCall(gsql_cmd) except CheckCallError, e: print "return code is %s" % e.retcode print "stdout and stderr is\n%s%s" % (e.stdout, e.stderr) raise new_out = gsql_out.replace('}}\n', '}}\nsplit here\n') return new_out.split('split here\n') def FindPrevRev(changeId, patchset, server, port): """Finds the revision of the previous patch set on the change""" sql_query = ("\"SELECT revision FROM patch_sets,changes WHERE " "patch_sets.change_id = changes.change_id AND " "patch_sets.patch_set_id = %s AND " "changes.change_key = \'%s\'\"" % ((patchset - 1), changeId)) revisions = GsqlQuery(sql_query, server, port) json_dict = json.loads(revisions[0], strict=False) return json_dict["columns"]["revision"] def GetApprovals(changeId, patchset, server, port): """Get all the approvals on a specific patch set Returns a list of approval dicts""" sql_query = ("\"SELECT value,account_id,category_id FROM patch_set_approvals " "WHERE patch_set_id = %s AND change_id = (SELECT change_id FROM " "changes WHERE change_key = \'%s\') AND value <> 0\"" % ((patchset - 1), changeId)) gsql_out = GsqlQuery(sql_query, server, port) approvals = [] for json_str in gsql_out: dict = json.loads(json_str, strict=False) if dict["type"] == "row": approvals.append(dict["columns"]) return approvals def GetEmailFromAcctId(account_id, server, port): """Returns the preferred email address associated with the account_id""" sql_query = ("\"SELECT preferred_email FROM accounts WHERE account_id = %s\"" % account_id) email_addr = GsqlQuery(sql_query, server, port) json_dict = json.loads(email_addr[0], strict=False) return json_dict["columns"]["preferred_email"] def GetPatchId(revision): git_show_cmd = ['git', 'show', revision] patch_id_cmd = ['git', 'patch-id'] patch_id_process = subprocess.Popen(patch_id_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE) git_show_process = subprocess.Popen(git_show_cmd, stdout=subprocess.PIPE) return patch_id_process.communicate(git_show_process.communicate()[0])[0] def SuExec(server, port, private_key, as_user, cmd): suexec_cmd = ['ssh', '-l', "Gerrit Code Review", '-p', port, server, '-i', private_key, 'suexec', '--as', as_user, '--', cmd] CheckCall(suexec_cmd) def DiffCommitMessages(commit1, commit2): log_cmd1 = ['git', 'log', '--pretty=format:"%an %ae%n%s%n%b"', commit1 + '^!'] commit1_log = CheckCall(log_cmd1) log_cmd2 = ['git', 'log', '--pretty=format:"%an %ae%n%s%n%b"', commit2 + '^!'] commit2_log = CheckCall(log_cmd2) if commit1_log != commit2_log: return True return False def Main(): server = 'localhost' usage = "usage: %prog <required options> [--server-port=PORT]" parser = OptionParser(usage=usage) parser.add_option("--change", dest="changeId", help="Change identifier") parser.add_option("--project", help="Project path in Gerrit") parser.add_option("--commit", help="Git commit-ish for this patchset") parser.add_option("--patchset", type="int", help="The patchset number") parser.add_option("--private-key-path", dest="private_key_path", help="Full path to Gerrit SSH daemon's private host key") parser.add_option("--server-port", dest="port", default='29418', help="Port to connect to Gerrit's SSH daemon " "[default: %default]") (options, args) = parser.parse_args() if not options.changeId: parser.print_help() exit(0) if options.patchset == 1: # Nothing to detect on first patchset exit(0) prev_revision = None prev_revision = FindPrevRev(options.changeId, options.patchset, server, options.port) if not prev_revision: # Couldn't find a previous revision exit(0) prev_patch_id = GetPatchId(prev_revision) cur_patch_id = GetPatchId(options.commit) if cur_patch_id.split()[0] != prev_patch_id.split()[0]: # patch-ids don't match exit(0) # Patch ids match. This is a trivial rebase. # In addition to patch-id we should check if the commit message changed. Most # approvers would want to re-review changes when the commit message changes. changed = DiffCommitMessages(prev_revision, options.commit) if changed: # Insert a comment into the change letting the approvers know only the # commit message changed comment_msg = ("\'--message=New patchset patch-id matches previous patchset" ", but commit message has changed.'") comment_cmd = ['ssh', '-p', options.port, server, 'gerrit', 'approve', '--project', options.project, comment_msg, options.commit] CheckCall(comment_cmd) exit(0) # Need to get all approvals on prior patch set, then suexec them onto # this patchset. approvals = GetApprovals(options.changeId, options.patchset, server, options.port) gerrit_approve_msg = ("\'Automatically re-added by Gerrit trivial rebase " "detection script.\'") for approval in approvals: # Note: Sites with different 'copy_min_score' values in the # approval_categories DB table might want different behavior here. # Additional categories should also be added if desired. if approval["category_id"] == "CRVW": approve_category = '--code-review' elif approval["category_id"] == "VRIF": # Don't re-add verifies #approve_category = '--verified' continue elif approval["category_id"] == "SUBM": # We don't care about previous submit attempts continue else: print "Unsupported category: %s" % approval exit(0) score = approval["value"] gerrit_approve_cmd = ['gerrit', 'approve', '--project', options.project, '--message', gerrit_approve_msg, approve_category, score, options.commit] email_addr = GetEmailFromAcctId(approval["account_id"], server, options.port) SuExec(server, options.port, options.private_key_path, email_addr, ' '.join(gerrit_approve_cmd)) exit(0) if __name__ == "__main__": Main()
Python
#!/usr/bin/env python # # Repeats a command for each demo and reports the status. # The command is executed from the root directory of the demo. # # Example: # python demos.py "ant install" # python demos.py "android update project -p ." # import os import sys def demos(command): tools_directory, script = os.path.split(os.path.abspath(__file__)) root_directory, tools = os.path.split(tools_directory) demos_directory = os.path.join(root_directory, 'demos') demos = os.listdir(demos_directory) demos = list(filter(lambda x: not x.startswith('.'), demos)) results = [0] * len(demos) for index in range(len(demos)): demo = demos[index] os.chdir(os.path.join(demos_directory, demo)) results[index] = os.system(command) for index in range(len(demos)): demo = demos[index] result = 'ok' if results[index] == 0 else 'failed' print (demo, result) def main(): try: script, command = sys.argv demos(command); except ValueError: print('Usage: python demos.py <command>') print() print('Examples:') print(' python demos.py "ant install"') print(' python demos.py "android update project -p ."') if __name__ == '__main__': main()
Python
#!/usr/bin/env python # # Builds archives for SDK releases. # # Usage: # python tools/sdk.py <version> # import os import shutil import sys import tempfile def execute(command): status = os.system(command) if status != 0: raise Exception('unexpected result: %d' % status) def sdk(version, output): # Find the location of this script tools, script = os.path.split(os.path.abspath(__file__)) # Find the location of the working copy of the project workspace, tools = os.path.split(tools) # Create a root directory for the SDK directory = 'libs-for-android-%s' % version root = os.path.join(output, directory) # Export a clean copy of the source code execute('svn export http://libs-for-android.googlecode.com/svn/trunk/ %s' % root) # Build a clean copy of the JARs shutil.copy(os.path.join(workspace, 'local.properties'), os.path.join(root, 'local.properties')) execute('ant -f %s all javadoc' % os.path.join(root, 'build.xml')) shutil.rmtree(os.path.join(root, 'bin', 'classes')) os.remove(os.path.join(root, 'local.properties')) # Prepare (or remove) the demo files demos = os.path.join(root, 'demos') include = ['atom', 'rss', 'jamendo'] for demo in os.listdir(demos): if demo in include: os.mkdir(os.path.join(demos, demo, 'bin')) os.mkdir(os.path.join(demos, demo, 'gen')) else: shutil.rmtree(os.path.join(demos, demo)) # Remove the tests shutil.rmtree(os.path.join(root, 'tests')) # Remove this script from the output os.remove(os.path.join(root, 'tools', 'sdk.py')) # Create compressed archives in multiple formats os.chdir(output) execute('tar czf libs-for-android-%s.tar.gz %s' % (version, directory)) execute('zip -r libs-for-android-%s.zip %s' % (version, directory)) def main(): script, version = sys.argv temp = tempfile.mkdtemp() sdk(version, output=temp); print('SDK archives created in', temp) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # # Updates the JARs in the demo libs/ directories # with the current build output found in bin/. # import os import shutil import sys def listdir(path): """List files at the specified path excluding hidden files""" return filter(lambda x: not x.startswith('.'), os.listdir(path)) def libs(): tools = os.path.split(os.path.abspath(__file__))[0] root = os.path.split(tools)[0] bin = os.path.join(root, 'bin') demos = os.path.join(root, 'demos') directories = [os.path.join(demos, demo, 'libs') for demo in listdir(demos)] directories.append(os.path.join(root, 'tests', 'libs')) directories.sort() for directory in directories: for lib in listdir(directory): src = os.path.join(bin, lib); dst = os.path.join(directory, lib) if os.path.exists(src): shutil.copyfile(src, dst) else: print("WARNING:", lib, "does not exist") def main(): libs(); if __name__ == "__main__": main()
Python
import os.path def listdirectory2(path): fichier=[] for root, dirs, files in os.walk(path): for i in files: fichier.append(os.path.join(root, i)) return fichier def gen1(): for f in listdirectory2("."): if (f.find("svn")+f.find(".py"))== -2: f = f.replace(".java","") lastChar = f[-1] fileBase = f[:-1][2:] if lastChar == 'S': #print fileBase+'S'+" "+fileBase[1:]+"= new fileBase+'S'();" print fileBase+"S "+fileBase[:1].lower()+fileBase[1:]+"S = new "+fileBase+"S();" print fileBase[:1].lower()+fileBase[1:]+"S.setComposant(this);" print "addService("+fileBase[:1].lower()+fileBase[1:]+"S);" print fileBase[:1].lower()+fileBase[1:]+"S.getPort().setComposant(this);" print "addPort("+fileBase[:1].lower()+fileBase[1:]+"S.getPort());" print "" gen1()
Python
import os.path def listdirectory2(path): fichier=[] for root, dirs, files in os.walk(path): for i in files: fichier.append(os.path.join(root, i)) return fichier def chinois1(): for f in listdirectory2("."): if (f.find("svn")+f.find(".py"))== -2: f = f.replace(".java","") lastChar = f[-1] fileBase = f[:-1][2:] if lastChar == 'S': #print fileBase+'S'+" "+fileBase[1:]+"= new fileBase+'S'();" print fileBase+"S "+fileBase[:1].lower()+fileBase[1:]+"S = new "+fileBase+"S();" print fileBase[:1].lower()+fileBase[1:]+"S.setComposant(this);" print "addService("+fileBase[:1].lower()+fileBase[1:]+"S);" print fileBase[:1].lower()+fileBase[1:]+"S.getPort().setComposant(this);" print "addPort("+fileBase[:1].lower()+fileBase[1:]+"S.getPort());" print "" chinois1()
Python
import os.path def listdirectory2(path): fichier=[] for root, dirs, files in os.walk(path): for i in files: fichier.append(os.path.join(root, i)) return fichier def chinois1(): for f in listdirectory2("."): if (f.find("svn")+f.find(".py"))== -2: f = f.replace(".java","") lastChar = f[-1] fileBase = f[:-1][2:] if lastChar == 'S': #print fileBase+'S'+" "+fileBase[1:]+"= new fileBase+'S'();" print fileBase+"S "+fileBase[:1].lower()+fileBase[1:]+"S = new "+fileBase+"S();" print fileBase[:1].lower()+fileBase[1:]+"S.setComposant(this);" print "addService("+fileBase[:1].lower()+fileBase[1:]+"S);" print fileBase[:1].lower()+fileBase[1:]+"S.getPort().setComposant(this);" print "addPort("+fileBase[:1].lower()+fileBase[1:]+"S.getPort());" print "" chinois1()
Python
# -*- coding: utf-8 -*- from userapi import * USER = "test.vkontakte@mail.ru" PASS = "yi8zXpHIs" DID="41657126" def test_profile(id = None): profile = test.v_profile(id) print "Profile of user " + profile.name + " <" + str(profile.id) + "> " print "Mother: " + str(profile.mother) print "Status: " + str(profile.status) print "Sex: " + str(profile.sex) print "Pic: " + str(profile.avatar) print "Birthday: " + str(profile.birthday) print "State: " + str(profile.state.getStatus()) print "Political: " + str(profile.politics.getStatus()) print "Friends: " for friend in profile.friends.persons: print friend.name print friend.id print friend.name + " <" + str(friend.id) + ">" print "Friends on-line:" for friend in profile.friends_online.persons: print friend.name + " <" + str(friend.id) + ">" print "Friends shared:" for friend in profile.shared_friends.persons: print friend.name + " <" + str(friend.id) + ">" print "My photos:" for photo in profile.own_photos.photos: print str(photo.pic) print "Photos with me:" for photo in profile.mark_photos.photos: print str(photo.pic) print "Wall not yet implemented" print "On-line status: " + str(profile.online) print "Education statements not implemented fully yet:" print str(profile.education) def test_01(): print "Own ID: " + str(test.get_own_id()) def test_02(): Friends = test.v_friends(UserAPITypes.OnlineFirends, test.get_own_id(), 0, 100) for friend in Friends: print friend.name + "\t<" + str(friend.id) + ">" def test_03(): print test.v_friends(None, DID, 1, 100) print test.v_friends(UserAPITypes.OnlineFirends, DID, 1, 100) def test_04(): inbox = test.v_messages(UserAPITypes.Inbox, None, 0, 100) outbox = test.v_messages(UserAPITypes.Outbox, None, 0, 100) conversations = test.build_conversations(inbox.messages, outbox.messages) for conversation in conversations: print "conversation: " + conversation.mwith.name for message in conversation.messages: print "\t<" + message.text + ">" def test_05(): test_profile() def test_05_1(): test_profile(5368780) def test_05_2(): test_profile(9919546) def test_06(): wall = test.v_wall(test.get_own_id(), 0, 100) for message in wall.messages: print message.mfrom.name + "\t<" + message.text + ">" + "\t == " + (message.original_url or "--") tests = [test_01, test_05, test_05_1, test_05_2, test_06] try: session = Session() session.login(USER, PASS) test = UserAPI(session) for testcase in tests: print "---------------------------" testcase() session.logout() except UserAPIError as error: print "Get code: " + str(error.code) + " " + error.text except JSONProblemError as error: print "JSON data is a bullshit, storing to disk" f = file('bs', 'w') f.write(error.json_data) f.write("\n\n\n" + str(error.supplement)) f.close()
Python
class StoredObject: def __eq__(self, other): return int(self.id) == int(other.id) def __ne__(self, other): return int(self.id) != int(other.id) def __hash__(self): return int(self.id)
Python
import webbrowser class Captcha: def __init__(self): self.csid =4 # Chosed randomly! print "Look at browser and enter the captcha to console" webbrowser.open("http://userapi.com/data?act=captcha&csid=" + str(self.csid)) self.text = raw_input("VKontakte captcha: ")
Python
class UserAPIError: def __init__(this, code, action, text): this.code = code this.action = action this.text = text class JSONProblemError(Exception): def __init__(self, json_data, supplement): self.json_data = json_data self.supplement = supplement
Python
from StoredObject import * class Privacy: def __init__(self, may_look_profile, may_look_wall, may_leave_messages): self.may_look_profile = may_look_profile self.may_look_wall = may_look_wall self.may_leave_messages = may_leave_messages class Position: def __init__(self, id_country, iso, id_city, city): self.id_country = id_country self.iso = iso self.id_city = id_city self.city = city class MaritalStatus: def __init__(self, status): self.status = status def getStatus(self): return self.status class PoliticView: def __init__(self, status): self.status = status def getStatus(self): return self.status class UncheckedDate: def __init__(self, year, month, day): self.year = year self.month = month self.day = day class PersonsProfile: def __init__(self): self.mother = None self.position = None self.birthday = None self.state = None self.politics = None self.friends = None self.friends_online = None self.shared_friends = None self.status = None self.own_photos = None self.mark_photos= None self.privacy = None self.wall = None self.online = None self.education_list = None self.requester_id = None self.is_requester_friend = None self.is_requester_invited = None self.is_requester_favour = None class Person(StoredObject): def __init__(self, id, name, avatar, isOnline, # Always miniimg = None, sex = None, # Message Parse profile = None): # Other parameters if profile == None: profile = PersonsProfile() self.id = id self.name = name self.mother = profile.mother self.status = profile.status self.position = profile.position self.sex = sex self.avatar = avatar self.birthday = profile.birthday self.state = profile.state self.politics = profile.politics self.friends = profile.friends self.friends_online = profile.friends_online self.shared_friends = profile.shared_friends self.own_photos = profile.own_photos self.mark_photos= profile.mark_photos self.privacy = profile.privacy self.wall = profile.wall self.online = profile.online self.requester_id = profile.requester_id self.is_requester_friend = profile.is_requester_friend self.is_requester_invited = profile.is_requester_invited self.is_requester_favour = profile.is_requester_favour self.education = profile.education_list class Persons: def __init__(self, total, count, persons): self.total = total self.count = count self.persons = persons
Python
import json import datetime from Message import * from Person import * from Photo import * MSG_PERSON = 0 FRI_PERSON = 1 PRO_PERSON = 2 def listify(data, size): result = [None for i in range(0, size)] if isinstance(data, list): for i in range(0, len(data)): result[i] = data[i] elif isinstance(data, dict): for i in data: result[int(i)] = data[i] return result def convert(val, type, default = None): if val is not None: return type(val) return default class Parser: def __init__ (self, data): self.data = data def as_message(self): self.data = listify(self.data, 6) self.data[2] = listify(self.data[2], 8) return Message(int(self.data[0]), int(self.data[1]), self.data[2][0], Parser(self.data[3]).as_person(MSG_PERSON), Parser(self.data[4]).as_person(MSG_PERSON), convert(self.data[5], bool, False), convert(self.data[2][1], int, Message.TEXT), self.data[2][2], self.data[2][3], self.data[2][4], convert(self.data[2][5], int), convert(self.data[2][6], int), convert(self.data[2][7], int)) def as_messages(self): messages = [] for message_data in self.data['d']: messages.append(Parser(message_data).as_message()) if isinstance(self.data['h'], int): history = self.data['h'] else: history = Parser(self.data['h']).as_history() return Messages(int(self.data['n']), history, len(self.data['d']), messages) def as_person(self, parse_type): if parse_type == MSG_PERSON: id = self.data[0] name = None avatar = None miniimg = None sex = None isOnline = None if len(self.data) > 1: name = self.data[1] avatar = self.data[2] miniimg = self.data[3] sex = self.data[4] isOnline = self.data[5] return Person(id, name, avatar, isOnline, miniimg, sex) elif parse_type == FRI_PERSON: self.data = listify(self.data, 4) id = self.data[0] name = None avatar = None isOnline = None if len(self.data) > 1: name = self.data[1] avatar = self.data[2] isOnline = self.data[3] return Person(id, name, avatar, isOnline) elif parse_type == PRO_PERSON: prof = PersonsProfile() id = self.data['id'] name = self.data['fn'] + ' ' + self.data['ln'] sex = self.data['sx'] avatar = self.data['bp'] prof.mother = self.data['mn'] prof.status = self.data['actv'] #TODO: Parse it prof.position = Parser(self.data['ht']).as_position() prof.birthday = UncheckedDate(self.data['by'], self.data['bm'], self.data['bd']) prof.state = MaritalStatus(self.data['fs']) prof.politics = PoliticView(self.data['pv']) prof.friends = Parser(self.data['fr']).as_persons(FRI_PERSON) prof.friends_online = Parser(self.data['fro']).as_persons(FRI_PERSON) prof.shared_friends = Parser(self.data['frm']).as_persons(FRI_PERSON) prof.own_photos = Parser(self.data['ph']).as_photos() prof.mark_photos = Parser(self.data['phw']).as_photos() # TODO: Fix it ? # prof.privacy = Parser(self.data['pr']).as_privacy() prof.wall = None # TODO prof.online = self.data['on'] prof.requester_id = self.data['us'] prof.is_requester_friend = self.data['isf'] prof.is_requester_invited = self.data['isi'] prof.is_requester_favour = self.data['f'] prof.education_list = self.data['edu'] #TODO: Parse it return Person(id, name, avatar, None, None, sex, prof) def as_persons(self, person_type): persons = [] for person in self.data['d']: persons.append(Parser(person).as_person(person_type)) return Persons(int(self.data['n']), len(self.data['d']), persons) def as_position(self): return Position(self.data['coi'], self.data['con'], self.data['cii'], self.data['cin']) def as_photo(self): self.data = listify(self.data, 3) return Photo(self.data[0], self.data[2], self.data[1]) def as_uploadinfo(self): return PhotosUploadInfo(self.data['aid'], self.data['url'], self.data['hash'], self.data['rhash']) def as_photos(self): photos = [] for photo in self.data['d']: photos.append(Parser(photo).as_photo()) ts = self.data.get('ts', None) if (len(self.data) > 3): upload_info = self.as_uploadinfo() else: upload_info = None return Photos(self.data['n'], photos, ts, upload_info) def as_privacy(self): print self.a return Privacy(self.data['pa'], self.data['wa'], self.data['ms']) def as_history(self): self.data = listify(self.data) return History(int(self.data[0]), self.data[1], Parser(self.data[2]).as_message())
Python
import Captcha from Errors import UserAPIError import httplib import re ID="1" USERAPI_HOST="login.userapi.com" class Session: def __init__(self, filename = None, remixpass = None, sid = None): if filename: self.load_session(filename) self.renew_session() else: self.sid = None self.remixpass = remixpass self.sid = sid def login(self, user, password, captcha = None): connection = httplib.HTTPConnection(USERAPI_HOST) login_request = "/auth?login=force&site=" + str(ID)+ "&email=" + user + "&pass=" + password if captcha: login_request = login_request + "&fcsid=" + str(captcha.csid) + "&fccode=" + captcha.text connection.request('GET',login_request) response = connection.getresponse() connection.close() if response.status != 302: raise UserAPIError(0, "login", "Couldn't connect") match = re.search("sid=([\-0-9a-z]+)", response.getheader("location")) sid = match.group(1) if sid == "-2": return self.login(user, password, Captcha()) if sid == "0" or sid == "-1": raise UserAPIError(sid, "login", "Bad-bad error while login") match = re.search("remixpassword=([a-z0-9]+);", response.getheader("set-cookie")) if not match: raise UserAPIError(sid, "login", "Login incorrect (Full login)") self.remixpass = match.group(1) self.sid = sid return sid def logout(self): connection = httplib.HTTPConnection(USERAPI_HOST) login_request = "/auth?login=logout&site=" + str(ID) + "&sid=" + self.sid connection.request('GET',login_request) response = connection.getresponse() connection.close() if response.status != 302: raise UserAPIError(0, "login", "Couldn't connect") self.sid = None def save_session(self, file): save = open(file, "w") save.write(self.remixpass) save.close() def load_session(self, file): load = open(file, "r") self.remixpass = load.read() load.close() def renew_session(self): connection = httplib.HTTPConnection("login.userapi.com") login_request = "/auth?login=auto&site=" + str(ID) connection.request('GET',login_request, None, {"Cookie" : "remixpassword=" + self.remixpass}) response = connection.getresponse() connection.close() if response.status != 302: raise UserAPIError(0, "login", "Couldn't connect") match = re.search("remixpassword=([a-z0-9]+);", response.getheader("set-cookie")) match = re.search("sid=([\-0-9a-z]+)", response.getheader("location")) sid = match.group(1) if sid == "-2": return self.login(user, password, self.captcha()) if sid == "0" or sid == "-1": raise UserAPIError(sid, "login", "Bad-bad error while login") self.sid = sid return sid def get_sid(self): return self.sid
Python
from StoredObject import * class Message(StoredObject): TEXT = 0 PHOTO = 1 GRAPHITY = 2 VIDEO = 3 AUDIO = 4 def __init__(self, id, time, text, mfrom, mto, isReaded, # Parameters defined at wall's messages retrieval message_type = 0, message_name = None, thumb_url = None, original_url = None, owner_id = None, item_id = None, item_size = None): self.id = id self.time = time self.text = text self.mfrom = mfrom self.mto = mto self.isReaded = isReaded self.message_type = message_type self.message_name = message_name self.thumb_url = thumb_url self.original_url = original_url self.owner_id = owner_id self.item_id = item_id self.item_size = item_size class Messages: def __init__(self, total, history, count, messages): self.total = total self.history = history self.count = count self.messages = messages class History: def __init__(self, version, action, message): self.version = version self.action = action self.message = message class Conversation: def __init__(self, mwith, messages): self.mwith = mwith self.messages = messages
Python
from StoredObject import * class Photo(StoredObject): def __init__ (self, id, pic, small_pic): self.id = id self.pic = pic self.small_pic = small_pic class PhotosUploadInfo: def __init__(self, aid, upload_url = None, upload_hash = None, upload_rhash = None): self.upload_url = upload_url self.upload_hash = upload_hash self.upload_rhash = upload_rhash self.aid = aid class Photos: def __init__(self, total, photos, ts = None, upload_info = None): self.total = total self.photos = photos self.ts = ts self.upload = upload_info
Python
from UserAPI import Token from UserAPI import UserAPITypes from UserAPI import RetCodes from UserAPI import UserAPI from Session import Session from Errors import UserAPIError, JSONProblemError
Python
from Parser import * from Errors import * import Session import httplib import re import json class Token: Standard = None Login = 0 Action = 1 class RetCodes: NoError = 0 Error = 1 class UserAPITypes: Standard = None Outbox = "outbox" Inbox = "inbox" MutualFriends = "mutual" OnlineFirends = "online" NewFriends = "new" NewPhotos = "new" MyPhotos = "with" def fix_unicode(val, encoding = 'utf-8', exclude = []): if isinstance(val, unicode): tmp = val.encode('latin-1') return unicode(tmp, encoding) elif isinstance(val, dict): result = {} for key in val: if key not in exclude: result[key] = fix_unicode(val[key], encoding) else: result[key] = val[key] return result elif isinstance(val, list): result = list(val) for i in range(0, len(result)): if i not in exclude: result[i] = fix_unicode(result[i], encoding) return result else: return val class UserAPI: def __init__(self, session): self.session = session self.id = 0 def fix_json(self, data): res = "" state = "" number = "" for s in data: if state == "": if s == "\"": res = res + s state = "\"" elif s.isdigit(): number = s state = "n" else: res = res + s elif state == "\"": if s == "\"": res = res + s state = "" else: res = res + s elif state == "n": if s == ":": res = res + "\"" + number + "\":" state = "" elif s.isdigit(): number = number + s else: res = res + number + s state = "" return res def v_api(self, action, parameters): # self.renew_session() GET = "/data?act=" + action + "&sid=" + self.session.get_sid() for key,val in parameters.iteritems(): if val != None: GET = GET + "&" + str(key) + "=" + str(val) connection = httplib.HTTPConnection("userapi.com") connection.request('GET', GET, None, {"Cookie" : "remixpassword=" + self.session.remixpass}) response = connection.getresponse() data = response.read() connection.close() if response.status != 200: raise UserAPIError(0, action, "Couldn't connect") data = self.fix_json(data) data = re.sub("\\t|\\x13", " ", data) contenttype = response.getheader('Content-Type') m = re.search("charset=(?P<charset>.*)", contenttype) charset = m.group('charset').lower() if charset == 'utf-8': encoding = 'utf-8' else: encoding = 'latin-1' try: return json.loads(data, encoding), charset except StandardError as error: raise JSONProblemError(data, { "error" : error, "encoding" : encoding}) def v_friends(self, subtype, id, start, end): action = "friends" if subtype: action = action + "_" + subtype data, charset = self.v_api(action, { "from" : start, "to" : end, "id" : id}) if charset != 'utf-8': data = fix_unicode(data, 'cp1251') friends = [] for person in data: friends.append(Parser(person).as_person(FRI_PERSON)) return friends def v_messages(self, subtype, id, start, end, ts = None): action = "message" if subtype: action = subtype data, charset = self.v_api(action, { "from" : start, "to" : end, "id" : id, "ts" : ts}) if charset != 'utf-8': data = fix_unicode(data) return Parser(data).as_messages() def v_wall(self, id, start, end, ts = None): action = "wall" data, charset = self.v_api(action, { "from" : start, "to" : end, "id" : id, "ts" : ts}) if charset != 'utf-8': data = fix_unicode(data) return Parser(data).as_messages() def v_photos(self, subtype, id, start, end): action = "photos" if subtype: action = action + "_" + subtype data, charset = self.v_api(action, { "from" : start, "to" : end, "id" : id}) return Parser(data).as_photos() def v_profile(self, id = None): action = "profile" data, charset = self.v_api(action, { "id" : id}) if charset != 'utf-8': broken_keys = ['fr', 'fro', 'frm'] for key in broken_keys: data[key] = fix_unicode(data[key], 'cp1251') data = fix_unicode(data, exclude = broken_keys) return Parser(data).as_person(PRO_PERSON) def add_message(self, id, message, ts = None): action = "add_message" data, charset = self.v_api(action, { "id" : id, "ts" : ts, "message" : message}) return data["ok"] def get_own_id(self): if self.id == 0: data, charset = self.v_api('profile', { "id" : None }) self.id = data['us'] return self.id def build_conversations(self, inbox, outbox): conversations = {} for message in inbox + outbox: person = message.mfrom if message.mfrom.id != self.get_own_id() else message.mto try: conversation = conversations[person.id] except: conversation = Conversation(person, []) conversations[person.id] = conversation conversation.messages.append(message) return conversations.values()
Python
#!/usr/bin/python import sys, hashlib def write_file(fn, buf): fp = open(fn, "wb") fp.write(buf) fp.close() def usage(): print ("Usage: " + sys.argv[0] + " infile outfile label") def main(): if( len(sys.argv) != 4): usage() sys.exit() fp = open( sys.argv[1] , "rb") hash_str = hashlib.md5( fp.read() ).hexdigest() fp.close() out_str = "u8 " + sys.argv[3] + "[16] = { " i=0 for str in hash_str: if i % 2 == 0: out_str += "0x" + str else: out_str += str if i < 31: out_str += ", " i += 1 out_str += " };" print out_str write_file( sys.argv[2] , out_str ) if __name__ == "__main__": main()
Python
#!/usr/bin/python import sys, re, os def write_file(fn, buf): fp = open(fn, "wb") fp.write(buf) fp.close() def usage(): print ("Usage: " + os.path.split(__file__)[1] + " version outfile") def crete_version_str(ver): base = list("0.00") version = str(ver) ret = [] base[0] = version[0] base[2] = version[1] base[3] = version[2] ret.append("".join(base)) version = str(int(ver) + 1) base[0] = version[0] base[2] = version[1] base[3] = version[2] ret.append("".join(base)) return ret def main(): if( len(sys.argv) != 3): usage() sys.exit() if len( sys.argv[1]) != 3: print sys.argv[1] + ":Version error." sys.exit() fp = open( os.path.dirname(os.path.abspath(__file__)) + "/update_base.sfo" , "rb") sfo_buf = fp.read() fp.close() after_str = crete_version_str(sys.argv[1]) print "Target version:" + after_str[0] sfo_buf = re.sub("X.YZ", after_str[0], sfo_buf ) sfo_buf = re.sub("Z.YX", after_str[1], sfo_buf ) write_file( sys.argv[2] , sfo_buf ) if __name__ == "__main__": main()
Python
#!/usr/bin/python """ PRO build script""" import os, shutil, sys NIGHTLY=0 VERSION="B10" PRO_BUILD = [ { "fn": "620PRO-%s.rar", "config": "CONFIG_620=1" }, { "fn": "635PRO-%s.rar", "config": "CONFIG_635=1" }, { "fn": "639PRO-%s.rar", "config": "CONFIG_639=1" }, { "fn": "660PRO-%s.rar", "config": "CONFIG_660=1" }, # { "fn": "620PRO-%s.zip", "config": "CONFIG_620=1" }, # { "fn": "635PRO-%s.zip", "config": "CONFIG_635=1" }, # { "fn": "639PRO-%s.zip", "config": "CONFIG_639=1" }, # { "fn": "660PRO-%s.zip", "config": "CONFIG_660=1" }, # { "fn": "620PRO-%s.tar.gz", "config": "CONFIG_620=1" }, # { "fn": "635PRO-%s.tar.gz", "config": "CONFIG_635=1" }, # { "fn": "639PRO-%s.tar.gz", "config": "CONFIG_639=1" }, # { "fn": "660PRO-%s.tar.gz", "config": "CONFIG_660=1" }, # { "fn": "620PRO-%s.tar.bz2", "config": "CONFIG_620=1" }, # { "fn": "635PRO-%s.tar.bz2", "config": "CONFIG_635=1" }, # { "fn": "639PRO-%s.tar.bz2", "config": "CONFIG_639=1" }, # { "fn": "660PRO-%s.tar.bz2", "config": "CONFIG_660=1" }, ] OPT_FLAG = "" def build_pro(build_conf): global OPT_FLAG if NIGHTLY: build_conf += " " + "NIGHTLY=1" build_conf += " " + OPT_FLAG os.system("make clean %s" % (build_conf)) os.system("make deps %s" % (build_conf)) build_conf = "make " + build_conf os.system(build_conf) def copy_sdk(): try: os.mkdir("dist/sdk") os.mkdir("dist/sdk/lib") os.mkdir("dist/sdk/include") except OSError: pass shutil.copytree("kuBridgeTest", "dist/sdk/kuBridgeTest") shutil.copy("include/kubridge.h", "dist/sdk/include") shutil.copy("include/systemctrl.h", "dist/sdk/include") shutil.copy("include/systemctrl_se.h", "dist/sdk/include") shutil.copy("include/pspvshbridge.h", "dist/sdk/include") shutil.copy("libs/libpspkubridge.a", "dist/sdk/lib") shutil.copy("libs/libpspsystemctrl_kernel.a", "dist/sdk/lib") shutil.copy("libs/libpspsystemctrl_user.a", "dist/sdk/lib") def restore_chdir(): os.chdir(os.path.join(os.path.dirname(sys.argv[0]), "..")) def make_archive(fn): shutil.copy("credit.txt", "dist") copy_sdk() ext = os.path.splitext(fn)[-1].lower() try: os.remove(fn) except OSError: pass path = os.getcwd() os.chdir("dist"); if ext == ".rar": os.system("rar a -r ../%s ." % (fn)) elif ext == ".gz": os.system("tar -zcvf ../%s ." % (fn)) elif ext == ".bz2": os.system("tar -jcvf ../%s ." % (fn)) elif ext == ".zip": os.system("zip -r ../%s ." % (fn)) os.chdir(path) def main(): global OPT_FLAG OPT_FLAG = os.getenv("PRO_OPT_FLAG", "") restore_chdir() for conf in PRO_BUILD: build_pro(conf["config"]) make_archive(conf["fn"] % (VERSION)) if __name__ == "__main__": main()
Python
#!/usr/bin/python import sys, os, gzip, StringIO def dump_binary(fn, data): f = open(fn, "wb") f.write(data) f.close() def dec_prx(fn): f = open(fn, "rb") f.seek(0x150) dat = f.read() f.close() temp=StringIO.StringIO(dat) f=gzip.GzipFile(fileobj=temp, mode='rb') dec = f.read(f) f.close() fn = "%s.dec.prx" % os.path.splitext(fn)[0] print ("Decompressed to %s" %(fn)) dump_binary(fn, dec) def main(): if len(sys.argv) < 2: print ("Usage: %s <file>" % (sys.argv[0])) sys.exit(-1) dec_prx(sys.argv[1]) if __name__ == "__main__": main()
Python
#!/usr/bin/python class FakeTime: def time(self): return 1225856967.109 import sys, os, struct, gzip, hashlib, StringIO gzip.time = FakeTime() def binary_replace(data, newdata, offset): return data[0:offset] + newdata + data[offset+len(newdata):] def prx_compress(output, hdr, input, mod_name="", mod_attr=0xFFFFFFFF): a=open(hdr, "rb") fileheader = a.read(); a.close() a=open(input, "rb") elf = a.read(4); a.close() if (elf != '\x7fELF'.encode()): print ("not a ELF/PRX file!") return -1 uncompsize = os.stat(input).st_size f_in=open(input, 'rb') temp=StringIO.StringIO() f=gzip.GzipFile(fileobj=temp, mode='wb') f.writelines(f_in) f.close() f_in.close() prx=temp.getvalue() temp.close() digest=hashlib.md5(prx).digest() filesize = len(fileheader) + len(prx) if mod_name != "": if len(mod_name) < 28: mod_name += "\x00" * (28-len(mod_name)) else: mod_name = mod_name[0:28] fileheader = binary_replace(fileheader, mod_name.encode(), 0xA) if mod_attr != 0xFFFFFFFF: fileheader = binary_replace(fileheader, struct.pack('H', mod_attr), 0x4) fileheader = binary_replace(fileheader, struct.pack('L', uncompsize), 0x28) fileheader = binary_replace(fileheader, struct.pack('L', filesize), 0x2c) fileheader = binary_replace(fileheader, struct.pack('L', len(prx)), 0xb0) fileheader = binary_replace(fileheader, digest, 0x140) a=open(output, "wb") assert(len(fileheader) == 0x150) a.write(fileheader) a.write(prx) a.close() try: os.remove("tmp.gz") except OSError: pass return 0 def main(): if len(sys.argv) < 4: print ("Usage: %s outfile prxhdr infile [modname] [modattr]\n"%(sys.argv[0])) exit(-1) if len(sys.argv) < 5: prx_compress(sys.argv[1], sys.argv[2], sys.argv[3]) elif len(sys.argv) < 6: prx_compress(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]) else: prx_compress(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5], 16)) if __name__ == "__main__": main()
Python
#!/usr/bin/python # Copyright (c) 2011 by Virtuous Flame # Based BOOSTER 1.01 CSO Compressor # # GNU General Public Licence (GPL) # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 2 of the License, or (at your option) any later # version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 Temple # Place, Suite 330, Boston, MA 02111-1307 USA # __author__ = "Virtuous Flame" __license__ = "GPL" __version__ = "1.0" import sys, os from zlib import compress, decompress, error as zlibError from struct import pack, unpack from multiprocessing import Pool from getopt import * CISO_MAGIC = 0x4F534943 DEFAULT_ALIGN = 0 COMPRESS_THREHOLD = 100 DEFAULT_PADDING = br'X' MP = False MP_NR = 1024 * 16 def hexdump(data): for i in data: print("0x%02X" % ((ord(i)))), print("") def zip_compress(plain, level=9): compressed = compress(plain, level) # assert(compressed.startswith(b"\x78")) # We have to remove the 0xXX78 header return compressed[2:] def zip_compress_mp(i): try: return zip_compress(i[0], i[1]) except zlibError as e: print("%d block: %s" % (block, e)) sys.exit(-1) def zip_decompress(compressed): # hexdump(data) return decompress(compressed, -15) def usage(): print("Usage: ciso [-c level] [-m] [-t percent] [-h] infile outfile") print(" -c level: 1-9 compress ISO to CSO (1=fast/large - 9=small/slow") print(" 0 decompress CSO to ISO") print(" -m Use multiprocessing acceleration for compressing") print(" -t percent Compression Threshold (1-100)") print(" -a align Padding alignment 0=small/slow 6=fast/large") print(" -p pad Padding byte") print(" -h this help") def open_input_output(fname_in, fname_out): try: fin = open(fname_in, "rb") except IOError: print("Can't open %s" % (fname_in)) sys.exit(-1) try: fout = open(fname_out, "wb") except IOError: print("Can't create %s" % (fname_out)) sys.exit(-1) return fin, fout def seek_and_read(fin, offset, size): fin.seek(offset) return fin.read(size) def read_cso_header(fin): """CSO header has 0x18 bytes""" data = seek_and_read(fin, 0, 0x18) magic, header_size, total_bytes, block_size, ver, align = unpack('IIQIbbxx', data) return magic, header_size, total_bytes, block_size, ver, align def generate_cso_header(magic, header_size, total_bytes, block_size, ver, align): data = pack('IIQIbbxx', magic, header_size, total_bytes, block_size, ver, align) # assert(len(data) == 0x18) return data def show_cso_info(fname_in, fname_out, total_bytes, block_size, total_block, align): print("Decompress '%s' to '%s'" % (fname_in, fname_out)) print("Total File Size %ld bytes" %(total_bytes)) print("block size %d bytes" %(block_size)) print("total blocks %d blocks" %(total_block)) print("index align %d" % (1<<align)) def decompress_cso(fname_in, fname_out, level): fin, fout = open_input_output(fname_in, fname_out) magic, header_size, total_bytes, block_size, ver, align = read_cso_header(fin) if magic != CISO_MAGIC or block_size == 0 or total_bytes == 0: print("ciso file format error") return -1 total_block = total_bytes / block_size index_buf = [] for i in xrange(total_block + 1): index_buf.append(unpack('I', fin.read(4))[0]) show_cso_info(fname_in, fname_out, total_bytes, block_size, total_block, align) block = 0 percent_period = total_block/100 percent_cnt = 0 while block < total_block: percent_cnt += 1 if percent_cnt >= percent_period: percent_cnt = 0 print >> sys.stderr, ("decompress %d%%\r" % (block / percent_period)), index = index_buf[block] plain = index & 0x80000000 index &= 0x7fffffff read_pos = index << (align) if plain: read_size = block_size else: index2 = index_buf[block+1] & 0x7fffffff """ Have to read more bytes if align was set""" if align: read_size = (index2-index+1) << (align) else: read_size = (index2-index) << (align) cso_data = seek_and_read(fin, read_pos, read_size) if plain: dec_data = cso_data else: try: dec_data = zip_decompress(cso_data) except zlibError as e: print("%d block: 0x%08X %d %s" % (block, read_pos, read_size, e)) sys.exit(-1) fout.write(dec_data) block += 1 fin.close() fout.close() print("ciso decompress completed") def show_comp_info(fname_in, fname_out, total_bytes, block_size, align, level): print("Compress '%s' to '%s'" % (fname_in,fname_out)) print("Total File Size %ld bytes" % (total_bytes)) print("block size %d bytes" % (block_size)) print("index align %d" % (1<<align)) print("compress level %d" % (level)) if MP: print("multiprocessing %s" % (MP)) def set_align(fout, write_pos, align): if write_pos % (1<<align): align_len = (1<<align) - write_pos % (1<<align) fout.write(DEFAULT_PADDING * align_len) write_pos += align_len return write_pos def compress_cso(fname_in, fname_out, level): fin, fout = open_input_output(fname_in, fname_out) fin.seek(0, os.SEEK_END) total_bytes = fin.tell() fin.seek(0) magic, header_size, block_size, ver, align = CISO_MAGIC, 0x18, 0x800, 1, DEFAULT_ALIGN # We have to use alignment on any CSO files which > 2GB, for MSB bit of index as the plain indicator # If we don't then the index can be larger than 2GB, which its plain indicator was improperly set if total_bytes >= 2 ** 31 and align == 0: align = 1 header = generate_cso_header(magic, header_size, total_bytes, block_size, ver, align) fout.write(header) total_block = total_bytes / block_size index_buf = [ 0 for i in xrange(total_block + 1) ] fout.write(b"\x00\x00\x00\x00" * len(index_buf)) show_comp_info(fname_in, fname_out, total_bytes, block_size, align, level) write_pos = fout.tell() percent_period = total_block/100 percent_cnt = 0 if MP: pool = Pool() block = 0 while block < total_block: if MP: percent_cnt += min(total_block - block, MP_NR) else: percent_cnt += 1 if percent_cnt >= percent_period: percent_cnt = 0 if block == 0: print >> sys.stderr, ("compress %3d%% avarage rate %3d%%\r" % ( block / percent_period ,0)), else: print >> sys.stderr, ("compress %3d%% avarage rate %3d%%\r" % ( block / percent_period ,100*write_pos/(block*0x800))), if MP: iso_data = [ (fin.read(block_size), level) for i in xrange(min(total_block - block, MP_NR))] cso_data_all = pool.map_async(zip_compress_mp, iso_data).get(9999999) for i in xrange(len(cso_data_all)): write_pos = set_align(fout, write_pos, align) index_buf[block] = write_pos >> align cso_data = cso_data_all[i] if 100 * len(cso_data) / len(iso_data[i][0]) >= min(COMPRESS_THREHOLD, 100): cso_data = iso_data[i][0] index_buf[block] |= 0x80000000 # Mark as plain elif index_buf[block] & 0x80000000: print("Align error, you have to increase align by 1 or CFW won't be able to read offset above 2 ** 31 bytes") sys.exit(1) fout.write(cso_data) write_pos += len(cso_data) block += 1 else: iso_data = fin.read(block_size) try: cso_data = zip_compress(iso_data, level) except zlibError as e: print("%d block: %s" % (block, e)) sys.exit(-1) write_pos = set_align(fout, write_pos, align) index_buf[block] = write_pos >> align if 100 * len(cso_data) / len(iso_data) >= COMPRESS_THREHOLD: cso_data = iso_data index_buf[block] |= 0x80000000 # Mark as plain elif index_buf[block] & 0x80000000: print("Align error, you have to increase align by 1 or CFW won't be able to read offset above 2 ** 31 bytes") sys.exit(1) fout.write(cso_data) write_pos += len(cso_data) block += 1 # Last position (total size) index_buf[block] = write_pos >> align # Update index block fout.seek(len(header)) for i in index_buf: idx = pack('I', i) # assert(len(idx) == 4) fout.write(idx) print("ciso compress completed , total size = %8d bytes , rate %d%%" % (write_pos,(write_pos*100/total_bytes))) fin.close() fout.close() def parse_args(): global MP, COMPRESS_THREHOLD, DEFAULT_PADDING, DEFAULT_ALIGN if len(sys.argv) < 2: usage() sys.exit(-1) try: optlist, args = gnu_getopt(sys.argv, "c:mt:a:p:h") except GetoptError, err: print(str(err)) usage() sys.exit(-1) level = None for o, a in optlist: if o == '-c': level = int(a) elif o == '-m': MP = True elif o == '-t': COMPRESS_THREHOLD = min(int(a), 100) elif o == '-a': DEFAULT_ALIGN = int(a) elif o == '-p': DEFAULT_PADDING = bytes(a[0]) elif o == '-h': usage() sys.exit(0) if level == None: print("You have to specify compress level") sys.exit(-1) try: fname_in, fname_out = args[1:3] except ValueError as e: print("You have to specify input/output filename") sys.exit(-1) return level, fname_in, fname_out def load_sector_table(sector_table_fn, total_block, default_level = 9): """ In future we will support NC """ sectors = [default_level for i in range(total_block)] with open(sector_table_fn) as f: for line in f: line = line.strip() a = line.split(":") if len(a) < 2: raise ValueError("Invalid line founded: %s" % (line)) if -1 == a[0].find("-"): try: sector, level = int(a[0]), int(a[1]) except ValueError: raise ValueError("Invalid line founded: %s" % (line)) if level < 1 or level > 9: raise ValueError("Invalid line founded: %s" % (line)) sectors[sector] = level else: b = a[0].split("-") try: start, end, level = int(b[0]), int(b[1]), int(a[1]) except ValueError: raise ValueError("Invalid line founded: %s" % (line)) i = start while i < end: sectors[i] = level i += 1 return sectors def main(): print ("ciso-python %s by %s" % (__version__, __author__)) level, fname_in, fname_out = parse_args() if level == 0: decompress_cso(fname_in, fname_out, level) else: compress_cso(fname_in, fname_out, level) PROFILE = False if __name__ == "__main__": if PROFILE: import cProfile cProfile.run("main()") else: main()
Python
#!/usr/bin/python import sys, hashlib def toNID(name): hashstr = hashlib.sha1(name.encode()).hexdigest().upper() return "0x" + hashstr[6:8] + hashstr[4:6] + hashstr[2:4] + hashstr[0:2] if __name__ == "__main__": assert(toNID("sceKernelCpuSuspendIntr") == "0x092968F4") for name in sys.argv[1:]: print ("%s: %s"%(name, toNID(name)))
Python
#!/usr/bin/python from hashlib import * import sys, struct def sha512(psid): if len(psid) != 16: return "".encode() for i in range(512): psid = sha1(psid).digest() return psid def get_psid(str): if len(str) != 32: return "".encode() b = "".encode() for i in range(0, len(str), 2): b += struct.pack('B', int(str[i] + str[i+1], 16)) return b def main(): if len(sys.argv) < 2: print ("Usage: sha512.py psid") exit(0) psid = get_psid(sys.argv[1]) xhash = sha512(psid) if len(xhash) == 0: print ("wrong PSID") exit(0) print ("{\n\t"), for i in range(len(xhash)): if i != 0 and i % 8 == 0: print ("\n\t"), print ("0x%02X, "%(struct.unpack('B', xhash[i])[0])), print ("\n},") if __name__ == "__main__": main()
Python
#!/usr/bin/python """ pspbtcnf_editor: An script that add modules from pspbtcnf """ import sys, os, re from getopt import * from struct import * BTCNF_MAGIC=0x0F803001 verbose = False def print_usage(): print ("%s: pspbtcnf.bin [-o output.bin] [-a add_module_name:before_module_name:flag]" %(os.path.split(sys.argv[0]))[-1]) def replace_binary(data, offset, newdata): newdata = data[0:offset] + newdata + data[offset+len(newdata):] assert(len(data) == len(newdata)) return newdata def dump_binary(data, offset, size): newdata = data[offset:offset+size] assert(len(newdata) == size) return newdata def dump_binary_str(data, offset): ch = data[offset] tmp = b'' while ch != 0: tmp += pack('b', ch) offset += 1 ch = data[offset] return tmp.decode() def add_prx_to_bootconf(srcfn, before_modname, modname, modflag): "Return new bootconf data" fn=open(srcfn, "rb") bootconf = fn.read() fn.close() if len(bootconf) < 64: raise Exception("Bad bootconf") signature, devkit, modestart, nmodes, modulestart, nmodules, modnamestart, modnameend = unpack('LL8xLL8xLL8xLL8x', bootconf[:64]) if verbose: print ("Devkit: 0x%08X"%(devkit)) print ("modestart: 0x%08X"%(modestart)) print ("nmodes: %d"%(nmodes)) print ("modulestart: 0x%08X"%(modulestart)) print ("nmodules: 0x%08X"%(nmodules)) print ("modnamestart: 0x%08X"%(modnamestart)) print ("modnameend: 0x%08X"%(modnameend)) if signature != BTCNF_MAGIC or nmodules <= 0 or nmodes <= 0: raise Exception("Bad bootconf") bootconf = bootconf + modname.encode() + b'\0' modnameend += len(modname) + 1 i=0 while i < nmodules: module_path, module_flags = unpack('L4xL4x16x', bootconf[modulestart+i*32:modulestart+(i+1)*32]) module_name = dump_binary_str(bootconf, modnamestart+module_path) if verbose: print ("[%02d]: Module path: %s flag: 0x%08X"%(i, module_name, module_flags)) if before_modname == module_name: break i+=1 if i >= nmodules: raise Exception("module %s not found"%(before_modname)) module_path = modnameend - len(modname) - 1 - modnamestart module_flag = 0x80010000 | (modflag & 0xFFFF) newmod = dump_binary(bootconf, modulestart+i*32, 32) newmod = replace_binary(newmod, 0, pack('L', module_path)) newmod = replace_binary(newmod, 8, pack('L', module_flag)) bootconf = bootconf[0:modulestart+i*32] + newmod + bootconf[modulestart+i*32:] nmodules+=1 bootconf = replace_binary(bootconf, 0x24, pack('L', nmodules)) modnamestart += 32 bootconf = replace_binary(bootconf, 0x30, pack('L', modnamestart)) modnameend += 32 bootconf = replace_binary(bootconf, 0x34, pack('L', modnameend)) i = 0 while i < nmodes: num = unpack('H', bootconf[modestart+i*32:modestart+i*32+2])[0] num += 1 bootconf = replace_binary(bootconf, modestart + i * 32, pack('H', num)) i += 1 return bootconf def write_file(output_fn, data): fn = open(output_fn, "wb") fn.write(data) fn.close() def main(): global verbose try: optlist, args = gnu_getopt(sys.argv, "a:o:vh") except GetoptError as err: print(err) print_usage() sys.exit(1) # default configure verbose = False dst_filename = "-" add_module = "" for o, a in optlist: if o == "-v": verbose = True elif o == "-h": print_usage() sys.exit() elif o == "-o": dst_filename = a elif o == "-a": add_module = a else: assert False, "unhandled option" if verbose: print (optlist, args) if len(args) < 2: print ("Missing input pspbtcnf.bin") sys.exit(1) src_filename = args[1] if verbose: print ("src_filename: " + src_filename) print ("dst_filename: " + dst_filename) # check add_module if add_module != "": t = (re.split(":", add_module, re.I)) if len(t) != 3: print ("Bad add_module input") sys.exit(1) add_module, before_module, add_module_flag = (re.split(":", add_module, re.I)) if verbose: print ("add_module: " + add_module) print ("before_module: " + before_module) print ("add_module_flag: " + add_module_flag) if add_module != "": result = add_prx_to_bootconf(src_filename, before_module, add_module, int(add_module_flag, 16)) if dst_filename == "-": # print("Bootconf result:") # print(result) pass else: write_file(dst_filename, result) if __name__ == "__main__": main()
Python
#!/usr/bin/python import os def main(): lists = [ "ISODrivers/Galaxy/galaxy.prx", "ISODrivers/March33/march33.prx", "ISODrivers/March33/march33_620.prx", "ISODrivers/March33/march33_660.prx", "ISODrivers/Inferno/inferno.prx", "Popcorn/popcorn.prx", "Satelite/satelite.prx", "Stargate/stargate.prx", "SystemControl/systemctrl.prx", "usbdevice/usbdevice.prx", "Vshctrl/vshctrl.prx", "Recovery/recovery.prx", ] for fn in lists: path = "../" + fn name=os.path.split(fn)[-1] name=os.path.splitext(name)[0] ret = os.system("bin2c %s %s.h %s"%(path, name, name)) assert(ret == 0) if __name__ == "__main__": main()
Python
#!/usr/bin/python class FakeTime: def time(self): return 1225856967.109 import os, gzip, StringIO gzip.time = FakeTime() def create_gzip(input, output): f_in=open(input, 'rb') temp=StringIO.StringIO() f=gzip.GzipFile(fileobj=temp, mode='wb') f.writelines(f_in) f.close() f_in.close() fout=open(output, 'wb') temp.seek(0) fout.writelines(temp) fout.close() temp.close() def cleanup(): del_list = [ "installer.prx.gz", "Rebootex.prx.gz", ] for file in del_list: try: os.remove(file) except OSError: pass def main(): create_gzip("../../Installer/installer.prx", "installer.prx.gz") create_gzip("../../Rebootex/Rebootex.prx", "Rebootex.prx.gz") os.system("bin2c installer.prx.gz installer.h installer") os.system("bin2c Rebootex.prx.gz Rebootex_prx.h Rebootex_prx") cleanup() if __name__ == "__main__": main()
Python
#!/usr/bin/python import os, sys, getopt def usage(): print ("Usage: %s [-l size ] basefile input output" % (sys.argv[0])) def write_file(fn, buf): fp = open(fn, "wb") fp.write(buf) fp.close() def main(): inputsize = 0 try: optlist, args = getopt.getopt(sys.argv[1:], 'l:h') except getopt.GetoptError: usage() sys.exit(2) for o, a in optlist: if o == "-h": usage() sys.exit() if o == "-l": inputsize = int(a, 16) inputsize = max(inputsize, 0x4000); if len(args) < 3: usage() sys.exit(2) basefile = args[0] inputfile = args[1] outputfile = args[2] fp = open(basefile, "rb") buf = fp.read(0x1000) fp.close() if len(buf) < inputsize: buf += '\0' * (inputsize - len(buf)) assert(len(buf) == inputsize) fp = open(inputfile, "rb") ins = fp.read(0x3000) fp.close() buf = buf[0:0x1000] + ins + buf[0x1000+len(ins):] assert(len(buf) == inputsize) write_file(outputfile, buf) if __name__ == "__main__": main()
Python
# -*- coding: utf-8 -*- __author__ = "zoltan kochan" __date__ = "$28 june 2010 1:02:10$"
Python
# -*- coding: utf-8 -*- import unittest import test.core.test_constants as test_constants import test.core.lang.test_process as test_process import test.core.lang.test_translate as test_translate import test.core.compilers.test_gener_tools as test_gener_tools import test.core.models.test_lang as test_lang import test.core.compilers.test_atnl as test_atnl import test.core.compilers.test_cws as test_cws #ts = [test.core.pythologic.test_funcs.suite] #all_suites = unittest.TestSuite(ts) #unittest.TextTestRunner(verbosity=2).run(all_suites) ts = [unittest.TestLoader().loadTestsFromModule(test_constants)] ts += [unittest.TestLoader().loadTestsFromModule(test_gener_tools)] #ts += [unittest.TestLoader().loadTestsFromModule(test_process)] ts += [unittest.TestLoader().loadTestsFromModule(test_atnl)] ts += [unittest.TestLoader().loadTestsFromModule(test_cws)] #ts += [unittest.TestLoader().loadTestsFromModule(test_lang)] ts += [unittest.TestLoader().loadTestsFromModule(test_translate)] t = unittest.TestSuite(ts) unittest.TextTestRunner(verbosity=2).run(t)
Python
# -*- coding: utf-8 -*- __author__="zoltan kochan" __date__ ="$12 лют 2011 13:46:30$"
Python
__author__="zoltan kochan" __date__ ="$12 лют 2011 13:46:30$"
Python
__author__="zoltan kochan" __date__ ="$18 бер 2011 0:35:07$"
Python
__author__="Z-CORE" __date__ ="$5 бер 2011 21:28:15$"
Python
__author__ = "zoltan kochan" __date__ = "$28 june 2010 1:02:10$" __name__ = "fosay translator" __version_info__ = ("pre-alpha", 0, 0, 1, 239) __version__ = '.'.join([str(i) for i in __version_info__[1:]]) #testing #import test.core.__init__ from core.models.lang import Language import os, glob, sys def load_languages(): curr = str(os.path.dirname(sys.argv[0])) path = os.path.join(os.path.join(curr, "data"), "languages.txt") f = open(path, encoding = 'utf-8') lines = f.readlines() f.close() for line in lines: sn, ln = line.split(', ') yield sn.strip(), ln.strip() langs = {} long_names = {} short_name = {} for sn, ln in load_languages(): langs[sn] = Language(sn) long_names[sn] = ln short_name[ln] = sn print("%s dictionary has been loaded (%d words; %d meanings)." % (ln, len(langs[sn].vocabulary), len(langs[sn].meanings))) #hun = Language("hun") #print("Hungarian dictionary has been loaded (%d words; %d meanings)." % (len(hun.vocabulary), len(hun.meanings))) #eng = Language("eng") #print("English dictionary has been loaded (%d words; %d meanings)." % (len(eng.vocabulary), len(eng.meanings))) #ukr = Language("ukr") #print("Ukrainian dictionary has been loaded (%d words; %d meanings)." % (len(ukr.vocabulary), len(ukr.meanings))) #ww = [w for w in ukr.vocabulary] #ww.sort() #for w in ww: # print(w) #, ukr.vocabulary[w][0].meaning ######################################################################################################################### ######################################################################################################################### ######################################################################################################################### ##JUST TO CHACK#JUST TO CHACK#JUST TO CHACK#JUST TO CHACK#JUST TO CHACK#JUST TO CHACK#JUST TO CHACK#JUST TO CHACK#JUST TO #import sys #import os # #def save_words(file_name, lang): # f = open(str(os.path.dirname(sys.argv[0])) + "\\data\\" + file_name + "\\temp.txt", mode='w', encoding = 'utf-8') # #ww = [w for w in lang.vocabulary] # ww = [w + " " + str(len(lang.vocabulary[w])) + " " + str([x.descr() for x in lang.vocabulary[w]]) for w in lang.vocabulary] # ww.sort() # for w in ww: # f.write(w + "\n") #, ukr.vocabulary[w][0].meaning # f.close() # #save_words("hun", langs["hun"]) #save_words("eng", langs["eng"]) #save_words("ukr", langs["ukr"]) ######################################################################################################################### ######################################################################################################################### ######################################################################################################################### def friendly_output(t): if len(t) == 0: return """ THE TRANSLATOR WAS UNABLE TO TRANSLATE THE GIVEN TEXT You either made a mistake or it's too hard for the translator yet. """ if len(t) == 1: return t[0] alt = 1 out = "" for item in t: out += "alternative #" + str(alt) + ":\n" out += item + "\n\n" alt += 1 return out from core.lang.translate import translate, text_to_interlingua, interlingua_to_str try: from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_FosayForm(object): def setupUi(self, FosayForm): FosayForm.setObjectName(_fromUtf8("FosayForm")) FosayForm.resize(294, 438) self.gridLayout = QtGui.QGridLayout(FosayForm) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.sourceTextEdit = QtGui.QTextEdit(FosayForm) self.sourceTextEdit.setObjectName(_fromUtf8("sourceTextEdit")) self.gridLayout.addWidget(self.sourceTextEdit, 0, 0, 1, 3) self.sourceLangComboBox = QtGui.QComboBox(FosayForm) self.sourceLangComboBox.setObjectName(_fromUtf8("sourceLangComboBox")) self.sourceLangComboBox.addItems(sorted([key for key in long_names.values()])) self.gridLayout.addWidget(self.sourceLangComboBox, 1, 0, 1, 1) self.translateButton = QtGui.QPushButton(FosayForm) self.translateButton.setObjectName(_fromUtf8("translateButton")) self.gridLayout.addWidget(self.translateButton, 1, 1, 1, 1) self.targetLangComboBox = QtGui.QComboBox(FosayForm) self.targetLangComboBox.setObjectName(_fromUtf8("targetLangComboBox")) self.targetLangComboBox.addItems(sorted([key for key in long_names.values()]) + ["*caseframe"]) self.gridLayout.addWidget(self.targetLangComboBox, 1, 2, 1, 1) self.targetTextEdit = QtGui.QTextEdit(FosayForm) self.targetTextEdit.setObjectName(_fromUtf8("targetTextEdit")) self.gridLayout.addWidget(self.targetTextEdit, 2, 0, 1, 3) QtCore.QObject.connect(self.translateButton, QtCore.SIGNAL('clicked()'), self.translateButtonClicked) self.retranslateUi(FosayForm) QtCore.QMetaObject.connectSlotsByName(FosayForm) def translateButtonClicked(self): srclan = langs[short_name[self.sourceLangComboBox.currentText()]] text = self.sourceTextEdit.toPlainText().strip() first = 'ip' if self.targetLangComboBox.currentText() == "*caseframe": tr = text_to_interlingua(text, first, srclan) s = '' for item in tr: s += interlingua_to_str(item) + '\n' + '-'*50 + '\n' self.targetTextEdit.setText(s) else: trglan = langs[short_name[self.targetLangComboBox.currentText()]] tr = translate(text, first, srclan, [trglan]) self.targetTextEdit.setText(friendly_output(tr[0])) def retranslateUi(self, FosayForm): FosayForm.setWindowTitle(QtGui.QApplication.translate("FosayForm", "fosay translator " + __version_info__[0] + " " + __version__, None, QtGui.QApplication.UnicodeUTF8)) self.translateButton.setText(QtGui.QApplication.translate("FosayForm", ">>", None, QtGui.QApplication.UnicodeUTF8)) #if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) FosayForm = QtGui.QWidget() ui = Ui_FosayForm() ui.setupUi(FosayForm) FosayForm.show() sys.exit(app.exec_()) except ImportError: import tkinter; from tkinter import * from tkinter import ttk class TranslatorFrame(ttk.Frame): def __init__(self, parent): ttk.Frame.__init__(self, parent, padding="3 3 12 12") self.parent = parent self.initialize() def initialize(self): #init Frame self.grid(column=0, row=0, sticky=(N, W, E, S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) #init source_text self.source_text = Text(self, width=100, height=15, font=11) #self.source_text.pack(anchor=NE) self.source_text.grid(sticky=E+W) self.source_text.focus_set() # #init source_scrollbar # self.source_scrollbar = ttk.Scrollbar(self.parent, orient=VERTICAL) # #self.source_scrollbar.pack(side=RIGHT, fill=Y) # self.source_scrollbar.configure(command=self.source_text.yview) # self.source_text.configure(yscrollcommand=self.source_scrollbar.set) #init source_combo_box self.source_combo_box = ttk.Combobox(self, state="readonly", font=11) self.source_combo_box.config(width=10) self.source_combo_box.grid(row=16, sticky=W) self.source_combo_box['values'] = [key for key in long_names.values()] #init translate_button self.translate_button = ttk.Button(self, text=">>", command=self.trans) self.translate_button.config(width=10) self.translate_button.grid(row=17, sticky=W) #init target_combo_box self.target_combo_box = ttk.Combobox(self, state="readonly", font=11) self.target_combo_box.config(width=10) self.target_combo_box.grid(row=18, sticky=W) self.target_combo_box['values'] = [key for key in long_names.values()] + ["*caseframe"] #init target_text self.target_text = Text(self, width=80, height=10, font=11) self.target_text.config(state=DISABLED) #self.target_text.pack(anchor=S) self.target_text.grid(sticky="EW") for child in self.winfo_children(): child.grid_configure(padx=5, pady=5) def trans(self): srclan = langs[short_name[self.source_combo_box.get()]] text = self.source_text.get('1.0', 'end').strip() first = 'ip' self.target_text.config(state=NORMAL) self.target_text.delete('1.0', 'end') if self.target_combo_box.get() == "*caseframe": tr = text_to_interlingua(text, first, srclan) s = '' for item in tr: s += interlingua_to_str(item) + '\n' + '-'*50 + '\n' self.target_text.insert('end', s) else: trglan = langs[short_name[self.target_combo_box.get()]] tr = translate(text, first, srclan, [trglan]) self.target_text.insert('end', friendly_output(tr[0])) self.target_text.config(state=DISABLED) #feet_entry.focus() #root.bind('<Return>', calculate) root = Tk() root.title("fosay translator " + __version_info__[0] + " " + __version__) tf = TranslatorFrame(root) root.mainloop()
Python
# -*- coding: utf-8 -*- __author__="zoltan kochan" __date__ ="$3 apr 2011 1:25:43$" from setuptools import setup,find_packages setup ( name = 'fosay', version = '0.1', packages = find_packages(), # Declare your packages' dependencies here, for eg: #install_requires=['foo>=3'], # Fill in these to make your Egg ready for upload to # PyPI author = 'Zoltan Kochan', author_email = 'ZoltanKochan@gmail.com', summary = 'An Interlingual Machine Translator', url = 'http://code.google.com/p/fosay/', license = 'GNU GPL v3', long_description= '''Fosay is an interlingual machine translator written in Python. Fosay allows adding new languages by simply describing their grammar with ATNL (Augmented Transition Network Language) and their dictionary with CWS (Cascading Word Sheets).''', # could also include long_description, download_url, classifiers, etc. )
Python
# -*- coding: utf-8 -*- __author__="Z-CORE" __date__ ="$11 лют 2011 23:26:04$"
Python
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Knowladge base #------------------------------------------------------------------------------- __author__="zoltan kochan" __date__ ="$28 june 2010 1:02:10$" from core.models.ling_units import * import core.constants as const from core.constants import type as ltype from core.constants import is_terminalc from core.models.lang import Language from core.lang.process import lang_to_case_frame PRINT_TO_CONSOLE = False jbo = Language("jbo") #ANTONYM#ANTONYM#ANTONYM#ANTONYM#ANTONYM#ANTONYM#ANTONYM#ANTONYM#ANTONYM#ANTONYM#ANTONYM#ANTONYM #antonym = [ # ("man", "woman"), # ("girl", "boy"), #] #IS-A (is a type of) SUPERTYPE = "@supertype" SUBTYPE = "@subtype" #IN CASE FRAME!!!!!!!!!!!!! #diff = [ # ("mensi", "fema tunba"), #("fem-tunba", ["fema tunba"]), # ("bruna", "mefa tunba"), #("mef-tunba", ["mefa tunba"]), # ("tunba", "mensi o bruna"), ## ## ("homino", "fema homo"), ## ("homulo", "mefa homo"), ## ## ("yun-homo", "yuna homo"), # ("yun-homulo", "yuna homulo"), #boy = young male human ## ("yun-homino", "yuna homino"), ## ## ("adult-homo", "adulta homo"), ## ("adult-homulo", "adulta homulo"), ## ("adult-homino", "adulta homino"), ## ## ("pordoc", "pordo", "pordos"), ## ("pordos", "multa pordo"), #or more than one "pordo" # #] diff = [ ("mensi", "fetsi tunba"), #("fem-tunba", ["fema tunba"]), ("bruna", "nakni tunba"), #("mef-tunba", ["mefa tunba"]), ("tunba", "mensi a bruna"), #.inajo!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # # ("homino", "fema homo"), # ("homulo", "mefa homo"), # # ("yun-homo", "yuna homo"), # ("yun-homulo", "yuna homulo"), #boy = young male human # ("yun-homino", "yuna homino"), # # ("adult-homo", "adulta homo"), # ("adult-homulo", "adulta homulo"), # ("adult-homino", "adulta homino"), # # ("pordoc", "pordo", "pordos"), # ("pordos", "multa pordo"), #or more than one "pordo" ] def gen_cf_diff(diff): #raise NotImplementedError #intlin = Language("jbo")#....... temp = {} for w, d in diff: st = jbo.init_sentence(d, "np") #if len(st) > 1: #TODO:Drop comments # raise NotImplementedError temp[w] = lang_to_case_frame(st[-1]) if PRINT_TO_CONSOLE: print(5*" ", w, "<=>", temp[w]) return temp #but without dict cf_diff = gen_cf_diff(diff) ###cf_diff = { ### "yun-homo": {NONTERMINAL_EPITHET: {TERMINAL_ADJECTIVE: {CONCEPT_MEANING: "yuna"}}} ### } #diff = [ # ("mensi", ["fema tunba"]), #("fem-tunba", ["fema tunba"]), # ("bruna", ["mefa tunba"]), #("mef-tunba", ["mefa tunba"]), # ("tunba", ["mensi", "bruna"]), # # ("homino", ["fema homo"]), # ("homulo", ["mefa homo"]), # # ("yun-homo", ["yuna homo"]), # ("yun-homulo", ["yuna homulo"]), #boy = young male human # ("yun-homino", ["yuna homino"]), # # ("adult-homo", ["adulta homo"]), # ("adult-homulo", ["adulta homulo"]), # ("adult-homino", ["adulta homino"]), # # ("pordoc", ["pordo", "pordos"]), # ("pordos", ["multa pordo"]), #or more than one "pordo" # #] types_hierarchy = [ ("tunba", "mensi"), ("tunba", "bruna"), ("state", "like"), ("entity", "animate"), ("entity", "physical object"), ("animate", "animalo"), ("animalo", "hundo"), ("animalo", "hom'e"), ("hom'e", "homa"), ("evento", "akto"), ("akto", "bite"), ("tcika", "lunto"), ("tcika", "solto"), ("tcika", "avroro"), #dawn ("tcika", "mateno"), #morning #IT'S NOT A TYPE OF DAYTIME!! RATHER A PART OF ("tcika", "medisolto"), #noon #media solto #IT ALSO MEANS MIDNIGHT!!! I MUST USE AN ARTIFICIAL LANGUAGE!!! ("tcika", "posmeso"), #afternoon ("tcika", "vespero"), ("tcika", "medilunto"), #midnight ("tcika", "momento"), ("tcika", "milisekondo"), ("tcika", "snidu"), ("tcika", "mentu"), ("tcika", "cacra"), ("tcika", "djedi"), #"day" like day and night ("djedi", "padjed"), #monday ("tcika", "jeftu"), #week ("tcika", "masti"), #month ("tcika", "citsi"), #season ("tcika", "semestro"), #semester ("tcika", "anio"), #year ("tcika", "tsentano"), #century ("tcika", "milenio"), #millenium ("tcika", "epoko"), #era ("loko", "lokalito"), #place ("lokalito", "viladjeto"), #locality, hamlet ("lokalito", "viladjo"), # ("lokalito", "viladjego"), #urban village ("lokalito", "urbeto"), #town ("lokalito", "urbo"), #city ("lokalito", "urbego"), #megapolis ("loko", "lando"), ("lando", "la ukrayina"), ("lando", "la m'ady'arorsag"), ("lando", "la rasiya"), ("lando", "la slovakiya"), ("lando", "la gr'eyt brit'eyn"), ("urbego", "la lyviv"), ("urbego", "la k'eyiv"), ('tcadu', 'BUdapect'), ('tcadu', '.UJhorod'), ('tcadu', 'kiiev'), ('tcadu', 'lyndyn'), ('tcadu', 'moskov'), ('tcadu', 'nu,IORK'), ('tcadu', 'byLIN'), ] def is_supertype(sup, sub): if sup == SUPERTYPE or sub == SUBTYPE: return True if (sup, sub) in types_hierarchy: return True for sp, sb in types_hierarchy: if sb != sub: continue if is_supertype(sup, sp): return True return False def get_first_subtypes(sup): sub = [] for sp, sb in types_hierarchy: if sp == sup: sub += [sb] return sub case_frame = { #FROM, TO, WORD: SUPERTYPE, DEFAULT VALUE #(Case.INESSIVE, Case.ILLATIVE, SUPERTYPE): ["yuyi"], (ltype["clause"], ltype["subject"], "vidi"): (["animalo"], None), (ltype["clause"], ltype["instrumental"], "grafi"): (["grafanto"]) # (CONCEPT_PREDICATE, CONCEPT_AGENT, "akto"): (["animate"], None), # (CONCEPT_PREDICATE, CONCEPT_INSTRUMENT, "akto"): (["entity"], None), # (CONCEPT_PREDICATE, CONCEPT_OBJECT, "state"): (["entity"], None), } #prep_f = { # CASE_INESSIVE: ["place", ], # CASE_ILLATIVE: ["place", ] #} # #case_frame = { # "act": { # CONCEPT_AGENT: "animate", #maybe a default value... # CONCEPT_INSTRUMENT: "entity" # }, # "state": { # #CONCEPT_EXPERIENCER: "animate", #!!!!!!!!!!!!!!!!!!!!!???????????????? # CONCEPT_OBJECT: "entity" # }, # "event": { # CONCEPT_OBJECT: "entity" # }, # "imagine": # { # CONCEPT_AGENT: "person", # CONCEPT_OBJECT: "univ_type", # }, # "scan": # { # CONCEPT_AGENT: "machine", # CONCEPT_OBJECT: "univ_type", # }, # "see": # { # CONCEPT_AGENT: "animate", # CONCEPT_OBJECT: "univ_type", # }, # } #if there is not some word in the aim lang def meaning_shift(cf, lang): '''Interlingua approximation''' if type(cf) != type({}): return cf for key in [x for x in cf.keys()]: #beacause of conjunctions is the error! #print(key) if is_terminalc(key): if type(cf[key]) == type([]): r = [] for c in cf[key]: r += [meaning_shift(c, lang)] cf[key] = r else: lemma = cf[key][concept["lemma"]] if not lemma is None and not lemma in lang.meanings.keys() \ and cf[key][concept["lemma"]] in cf_diff: #replace with deffination #checking for properness #print(cf[key][concept["lemma"]], cf_diff[cf[key][concept["lemma"]]]) q = cf_diff[cf[key][concept["lemma"]]] temp = meaning_shift(q, lang) tt = cf[key][concept["order-number"]] del cf[key] h = temp[[k for k in temp.keys()][0]] #because of {16: {16: #WTF? IT WILL CHECK IT TWICE!!! for key in h.keys(): cf[key] = h[key] cf[concept["order-number"]] = tt #print(cf) ### elif type(cf[key]) == tuple: ### ci, children = cf[key] ### r = [] ### for c in children: ### r += [meaning_shift(c, lang)] ### cf[key] = ci, r else: cf[key] = meaning_shift(cf[key], lang) return cf
Python
# PLY package # Author: David Beazley (dave@dabeaz.com) __all__ = ['lex','yacc']
Python
# ----------------------------------------------------------------------------- # ply: yacc.py # # Copyright (C) 2001-2009, # David M. Beazley (Dabeaz LLC) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the David Beazley or Dabeaz LLC may be used to # endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ----------------------------------------------------------------------------- # # This implements an LR parser that is constructed from grammar rules defined # as Python functions. The grammer is specified by supplying the BNF inside # Python documentation strings. The inspiration for this technique was borrowed # from John Aycock's Spark parsing system. PLY might be viewed as cross between # Spark and the GNU bison utility. # # The current implementation is only somewhat object-oriented. The # LR parser itself is defined in terms of an object (which allows multiple # parsers to co-exist). However, most of the variables used during table # construction are defined in terms of global variables. Users shouldn't # notice unless they are trying to define multiple parsers at the same # time using threads (in which case they should have their head examined). # # This implementation supports both SLR and LALR(1) parsing. LALR(1) # support was originally implemented by Elias Ioup (ezioup@alumni.uchicago.edu), # using the algorithm found in Aho, Sethi, and Ullman "Compilers: Principles, # Techniques, and Tools" (The Dragon Book). LALR(1) has since been replaced # by the more efficient DeRemer and Pennello algorithm. # # :::::::: WARNING ::::::: # # Construction of LR parsing tables is fairly complicated and expensive. # To make this module run fast, a *LOT* of work has been put into # optimization---often at the expensive of readability and what might # consider to be good Python "coding style." Modify the code at your # own risk! # ---------------------------------------------------------------------------- __version__ = "3.3" __tabversion__ = "3.2" # Table version #----------------------------------------------------------------------------- # === User configurable parameters === # # Change these to modify the default behavior of yacc (if you wish) #----------------------------------------------------------------------------- yaccdebug = 1 # Debugging mode. If set, yacc generates a # a 'parser.out' file in the current directory debug_file = 'parser.out' # Default name of the debugging file tab_module = 'parsetab' # Default name of the table module default_lr = 'LALR' # Default LR table generation method error_count = 3 # Number of symbols that must be shifted to leave recovery mode yaccdevel = 0 # Set to True if developing yacc. This turns off optimized # implementations of certain functions. resultlimit = 40 # Size limit of results when running in debug mode. pickle_protocol = 0 # Protocol to use when writing pickle files import re, types, sys, os.path # Compatibility function for python 2.6/3.0 if sys.version_info[0] < 3: def func_code(f): return f.func_code else: def func_code(f): return f.__code__ # Compatibility try: MAXINT = sys.maxint except AttributeError: MAXINT = sys.maxsize # Python 2.x/3.0 compatibility. def load_ply_lex(): if sys.version_info[0] < 3: import lex else: import core.ply.lex as lex return lex # This object is a stand-in for a logging object created by the # logging module. PLY will use this by default to create things # such as the parser.out file. If a user wants more detailed # information, they can create their own logging object and pass # it into PLY. class PlyLogger(object): def __init__(self,f): self.f = f def debug(self,msg,*args,**kwargs): self.f.write((msg % args) + "\n") info = debug def warning(self,msg,*args,**kwargs): self.f.write("WARNING: "+ (msg % args) + "\n") def error(self,msg,*args,**kwargs): self.f.write("ERROR: " + (msg % args) + "\n") critical = debug # Null logger is used when no output is generated. Does nothing. class NullLogger(object): def __getattribute__(self,name): return self def __call__(self,*args,**kwargs): return self # Exception raised for yacc-related errors class YaccError(Exception): pass # Format the result message that the parser produces when running in debug mode. def format_result(r): repr_str = repr(r) if '\n' in repr_str: repr_str = repr(repr_str) if len(repr_str) > resultlimit: repr_str = repr_str[:resultlimit]+" ..." result = "<%s @ 0x%x> (%s)" % (type(r).__name__,id(r),repr_str) return result # Format stack entries when the parser is running in debug mode def format_stack_entry(r): repr_str = repr(r) if '\n' in repr_str: repr_str = repr(repr_str) if len(repr_str) < 16: return repr_str else: return "<%s @ 0x%x>" % (type(r).__name__,id(r)) #----------------------------------------------------------------------------- # === LR Parsing Engine === # # The following classes are used for the LR parser itself. These are not # used during table construction and are independent of the actual LR # table generation algorithm #----------------------------------------------------------------------------- # This class is used to hold non-terminal grammar symbols during parsing. # It normally has the following attributes set: # .type = Grammar symbol type # .value = Symbol value # .lineno = Starting line number # .endlineno = Ending line number (optional, set automatically) # .lexpos = Starting lex position # .endlexpos = Ending lex position (optional, set automatically) class YaccSymbol: def __str__(self): return self.type def __repr__(self): return str(self) # This class is a wrapper around the objects actually passed to each # grammar rule. Index lookup and assignment actually assign the # .value attribute of the underlying YaccSymbol object. # The lineno() method returns the line number of a given # item (or 0 if not defined). The linespan() method returns # a tuple of (startline,endline) representing the range of lines # for a symbol. The lexspan() method returns a tuple (lexpos,endlexpos) # representing the range of positional information for a symbol. class YaccProduction: def __init__(self,s,stack=None): self.slice = s self.stack = stack self.lexer = None self.parser= None def __getitem__(self,n): if n >= 0: return self.slice[n].value else: return self.stack[n].value def __setitem__(self,n,v): self.slice[n].value = v def __getslice__(self,i,j): return [s.value for s in self.slice[i:j]] def __len__(self): return len(self.slice) def lineno(self,n): return getattr(self.slice[n],"lineno",0) def set_lineno(self,n,lineno): self.slice[n].lineno = lineno def linespan(self,n): startline = getattr(self.slice[n],"lineno",0) endline = getattr(self.slice[n],"endlineno",startline) return startline,endline def lexpos(self,n): return getattr(self.slice[n],"lexpos",0) def lexspan(self,n): startpos = getattr(self.slice[n],"lexpos",0) endpos = getattr(self.slice[n],"endlexpos",startpos) return startpos,endpos def error(self): raise SyntaxError # ----------------------------------------------------------------------------- # == LRParser == # # The LR Parsing engine. # ----------------------------------------------------------------------------- class LRParser: def __init__(self,lrtab,errorf): self.productions = lrtab.lr_productions self.action = lrtab.lr_action self.goto = lrtab.lr_goto self.errorfunc = errorf def errok(self): self.errorok = 1 def restart(self): del self.statestack[:] del self.symstack[:] sym = YaccSymbol() sym.type = '$end' self.symstack.append(sym) self.statestack.append(0) def parse(self,input=None,lexer=None,debug=0,tracking=0,tokenfunc=None): if debug or yaccdevel: if isinstance(debug,int): debug = PlyLogger(sys.stderr) return self.parsedebug(input,lexer,debug,tracking,tokenfunc) elif tracking: return self.parseopt(input,lexer,debug,tracking,tokenfunc) else: return self.parseopt_notrack(input,lexer,debug,tracking,tokenfunc) # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # parsedebug(). # # This is the debugging enabled version of parse(). All changes made to the # parsing engine should be made here. For the non-debugging version, # copy this code to a method parseopt() and delete all of the sections # enclosed in: # # #--! DEBUG # statements # #--! DEBUG # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! def parsedebug(self,input=None,lexer=None,debug=None,tracking=0,tokenfunc=None): lookahead = None # Current lookahead symbol lookaheadstack = [ ] # Stack of lookahead symbols actions = self.action # Local reference to action table (to avoid lookup on self.) goto = self.goto # Local reference to goto table (to avoid lookup on self.) prod = self.productions # Local reference to production list (to avoid lookup on self.) pslice = YaccProduction(None) # Production object passed to grammar rules errorcount = 0 # Used during error recovery # --! DEBUG debug.info("PLY: PARSE DEBUG START") # --! DEBUG # If no lexer was given, we will try to use the lex module if not lexer: lex = load_ply_lex() lexer = lex.lexer # Set up the lexer and parser objects on pslice pslice.lexer = lexer pslice.parser = self # If input was supplied, pass to lexer if input is not None: lexer.input(input) if tokenfunc is None: # Tokenize function get_token = lexer.token else: get_token = tokenfunc # Set up the state and symbol stacks statestack = [ ] # Stack of parsing states self.statestack = statestack symstack = [ ] # Stack of grammar symbols self.symstack = symstack pslice.stack = symstack # Put in the production errtoken = None # Err token # The start state is assumed to be (0,$end) statestack.append(0) sym = YaccSymbol() sym.type = "$end" symstack.append(sym) state = 0 while 1: # Get the next symbol on the input. If a lookahead symbol # is already set, we just use that. Otherwise, we'll pull # the next token off of the lookaheadstack or from the lexer # --! DEBUG debug.debug('') debug.debug('State : %s', state) # --! DEBUG if not lookahead: if not lookaheadstack: lookahead = get_token() # Get the next token else: lookahead = lookaheadstack.pop() if not lookahead: lookahead = YaccSymbol() lookahead.type = "$end" # --! DEBUG debug.debug('Stack : %s', ("%s . %s" % (" ".join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip()) # --! DEBUG # Check the action table ltype = lookahead.type t = actions[state].get(ltype) if t is not None: if t > 0: # shift a symbol on the stack statestack.append(t) state = t # --! DEBUG debug.debug("Action : Shift and goto state %s", t) # --! DEBUG symstack.append(lookahead) lookahead = None # Decrease error count on successful shift if errorcount: errorcount -=1 continue if t < 0: # reduce a symbol on the stack, emit a production p = prod[-t] pname = p.name plen = p.len # Get production function sym = YaccSymbol() sym.type = pname # Production name sym.value = None # --! DEBUG if plen: debug.info("Action : Reduce rule [%s] with %s and goto state %d", p.str, "["+",".join([format_stack_entry(_v.value) for _v in symstack[-plen:]])+"]",-t) else: debug.info("Action : Reduce rule [%s] with %s and goto state %d", p.str, [],-t) # --! DEBUG if plen: targ = symstack[-plen-1:] targ[0] = sym # --! TRACKING if tracking: t1 = targ[1] sym.lineno = t1.lineno sym.lexpos = t1.lexpos t1 = targ[-1] sym.endlineno = getattr(t1,"endlineno",t1.lineno) sym.endlexpos = getattr(t1,"endlexpos",t1.lexpos) # --! TRACKING # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # The code enclosed in this section is duplicated # below as a performance optimization. Make sure # changes get made in both locations. pslice.slice = targ try: # Call the grammar rule with our special slice object del symstack[-plen:] del statestack[-plen:] p.callable(pslice) # --! DEBUG debug.info("Result : %s", format_result(pslice[0])) # --! DEBUG symstack.append(sym) state = goto[statestack[-1]][pname] statestack.append(state) except SyntaxError: # If an error was set. Enter error recovery state lookaheadstack.append(lookahead) symstack.pop() statestack.pop() state = statestack[-1] sym.type = 'error' lookahead = sym errorcount = error_count self.errorok = 0 continue # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! else: # --! TRACKING if tracking: sym.lineno = lexer.lineno sym.lexpos = lexer.lexpos # --! TRACKING targ = [ sym ] # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # The code enclosed in this section is duplicated # above as a performance optimization. Make sure # changes get made in both locations. pslice.slice = targ try: # Call the grammar rule with our special slice object p.callable(pslice) # --! DEBUG debug.info("Result : %s", format_result(pslice[0])) # --! DEBUG symstack.append(sym) state = goto[statestack[-1]][pname] statestack.append(state) except SyntaxError: # If an error was set. Enter error recovery state lookaheadstack.append(lookahead) symstack.pop() statestack.pop() state = statestack[-1] sym.type = 'error' lookahead = sym errorcount = error_count self.errorok = 0 continue # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if t == 0: n = symstack[-1] result = getattr(n,"value",None) # --! DEBUG debug.info("Done : Returning %s", format_result(result)) debug.info("PLY: PARSE DEBUG END") # --! DEBUG return result if t == None: # --! DEBUG debug.error('Error : %s', ("%s . %s" % (" ".join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip()) # --! DEBUG # We have some kind of parsing error here. To handle # this, we are going to push the current token onto # the tokenstack and replace it with an 'error' token. # If there are any synchronization rules, they may # catch it. # # In addition to pushing the error token, we call call # the user defined p_error() function if this is the # first syntax error. This function is only called if # errorcount == 0. if errorcount == 0 or self.errorok: errorcount = error_count self.errorok = 0 errtoken = lookahead if errtoken.type == "$end": errtoken = None # End of file! if self.errorfunc: global errok,token,restart errok = self.errok # Set some special functions available in error recovery token = get_token restart = self.restart if errtoken and not hasattr(errtoken,'lexer'): errtoken.lexer = lexer tok = self.errorfunc(errtoken) del errok, token, restart # Delete special functions if self.errorok: # User must have done some kind of panic # mode recovery on their own. The # returned token is the next lookahead lookahead = tok errtoken = None continue else: if errtoken: if hasattr(errtoken,"lineno"): lineno = lookahead.lineno else: lineno = 0 if lineno: sys.stderr.write("yacc: Syntax error at line %d, token=%s\n" % (lineno, errtoken.type)) else: sys.stderr.write("yacc: Syntax error, token=%s" % errtoken.type) else: sys.stderr.write("yacc: Parse error in input. EOF\n") return else: errorcount = error_count # case 1: the statestack only has 1 entry on it. If we're in this state, the # entire parse has been rolled back and we're completely hosed. The token is # discarded and we just keep going. if len(statestack) <= 1 and lookahead.type != "$end": lookahead = None errtoken = None state = 0 # Nuke the pushback stack del lookaheadstack[:] continue # case 2: the statestack has a couple of entries on it, but we're # at the end of the file. nuke the top entry and generate an error token # Start nuking entries on the stack if lookahead.type == "$end": # Whoa. We're really hosed here. Bail out return if lookahead.type != 'error': sym = symstack[-1] if sym.type == 'error': # Hmmm. Error is on top of stack, we'll just nuke input # symbol and continue lookahead = None continue t = YaccSymbol() t.type = 'error' if hasattr(lookahead,"lineno"): t.lineno = lookahead.lineno t.value = lookahead lookaheadstack.append(lookahead) lookahead = t else: symstack.pop() statestack.pop() state = statestack[-1] # Potential bug fix continue # Call an error function here raise RuntimeError("yacc: internal parser error!!!\n") # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # parseopt(). # # Optimized version of parse() method. DO NOT EDIT THIS CODE DIRECTLY. # Edit the debug version above, then copy any modifications to the method # below while removing #--! DEBUG sections. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! def parseopt(self,input=None,lexer=None,debug=0,tracking=0,tokenfunc=None): lookahead = None # Current lookahead symbol lookaheadstack = [ ] # Stack of lookahead symbols actions = self.action # Local reference to action table (to avoid lookup on self.) goto = self.goto # Local reference to goto table (to avoid lookup on self.) prod = self.productions # Local reference to production list (to avoid lookup on self.) pslice = YaccProduction(None) # Production object passed to grammar rules errorcount = 0 # Used during error recovery # If no lexer was given, we will try to use the lex module if not lexer: lex = load_ply_lex() lexer = lex.lexer # Set up the lexer and parser objects on pslice pslice.lexer = lexer pslice.parser = self # If input was supplied, pass to lexer if input is not None: lexer.input(input) if tokenfunc is None: # Tokenize function get_token = lexer.token else: get_token = tokenfunc # Set up the state and symbol stacks statestack = [ ] # Stack of parsing states self.statestack = statestack symstack = [ ] # Stack of grammar symbols self.symstack = symstack pslice.stack = symstack # Put in the production errtoken = None # Err token # The start state is assumed to be (0,$end) statestack.append(0) sym = YaccSymbol() sym.type = '$end' symstack.append(sym) state = 0 while 1: # Get the next symbol on the input. If a lookahead symbol # is already set, we just use that. Otherwise, we'll pull # the next token off of the lookaheadstack or from the lexer if not lookahead: if not lookaheadstack: lookahead = get_token() # Get the next token else: lookahead = lookaheadstack.pop() if not lookahead: lookahead = YaccSymbol() lookahead.type = '$end' # Check the action table ltype = lookahead.type t = actions[state].get(ltype) if t is not None: if t > 0: # shift a symbol on the stack statestack.append(t) state = t symstack.append(lookahead) lookahead = None # Decrease error count on successful shift if errorcount: errorcount -=1 continue if t < 0: # reduce a symbol on the stack, emit a production p = prod[-t] pname = p.name plen = p.len # Get production function sym = YaccSymbol() sym.type = pname # Production name sym.value = None if plen: targ = symstack[-plen-1:] targ[0] = sym # --! TRACKING if tracking: t1 = targ[1] sym.lineno = t1.lineno sym.lexpos = t1.lexpos t1 = targ[-1] sym.endlineno = getattr(t1,"endlineno",t1.lineno) sym.endlexpos = getattr(t1,"endlexpos",t1.lexpos) # --! TRACKING # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # The code enclosed in this section is duplicated # below as a performance optimization. Make sure # changes get made in both locations. pslice.slice = targ try: # Call the grammar rule with our special slice object del symstack[-plen:] del statestack[-plen:] p.callable(pslice) symstack.append(sym) state = goto[statestack[-1]][pname] statestack.append(state) except SyntaxError: # If an error was set. Enter error recovery state lookaheadstack.append(lookahead) symstack.pop() statestack.pop() state = statestack[-1] sym.type = 'error' lookahead = sym errorcount = error_count self.errorok = 0 continue # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! else: # --! TRACKING if tracking: sym.lineno = lexer.lineno sym.lexpos = lexer.lexpos # --! TRACKING targ = [ sym ] # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # The code enclosed in this section is duplicated # above as a performance optimization. Make sure # changes get made in both locations. pslice.slice = targ try: # Call the grammar rule with our special slice object p.callable(pslice) symstack.append(sym) state = goto[statestack[-1]][pname] statestack.append(state) except SyntaxError: # If an error was set. Enter error recovery state lookaheadstack.append(lookahead) symstack.pop() statestack.pop() state = statestack[-1] sym.type = 'error' lookahead = sym errorcount = error_count self.errorok = 0 continue # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if t == 0: n = symstack[-1] return getattr(n,"value",None) if t == None: # We have some kind of parsing error here. To handle # this, we are going to push the current token onto # the tokenstack and replace it with an 'error' token. # If there are any synchronization rules, they may # catch it. # # In addition to pushing the error token, we call call # the user defined p_error() function if this is the # first syntax error. This function is only called if # errorcount == 0. if errorcount == 0 or self.errorok: errorcount = error_count self.errorok = 0 errtoken = lookahead if errtoken.type == '$end': errtoken = None # End of file! if self.errorfunc: global errok,token,restart errok = self.errok # Set some special functions available in error recovery token = get_token restart = self.restart if errtoken and not hasattr(errtoken,'lexer'): errtoken.lexer = lexer tok = self.errorfunc(errtoken) del errok, token, restart # Delete special functions if self.errorok: # User must have done some kind of panic # mode recovery on their own. The # returned token is the next lookahead lookahead = tok errtoken = None continue else: if errtoken: if hasattr(errtoken,"lineno"): lineno = lookahead.lineno else: lineno = 0 if lineno: sys.stderr.write("yacc: Syntax error at line %d, token=%s\n" % (lineno, errtoken.type)) else: sys.stderr.write("yacc: Syntax error, token=%s" % errtoken.type) else: sys.stderr.write("yacc: Parse error in input. EOF\n") return else: errorcount = error_count # case 1: the statestack only has 1 entry on it. If we're in this state, the # entire parse has been rolled back and we're completely hosed. The token is # discarded and we just keep going. if len(statestack) <= 1 and lookahead.type != '$end': lookahead = None errtoken = None state = 0 # Nuke the pushback stack del lookaheadstack[:] continue # case 2: the statestack has a couple of entries on it, but we're # at the end of the file. nuke the top entry and generate an error token # Start nuking entries on the stack if lookahead.type == '$end': # Whoa. We're really hosed here. Bail out return if lookahead.type != 'error': sym = symstack[-1] if sym.type == 'error': # Hmmm. Error is on top of stack, we'll just nuke input # symbol and continue lookahead = None continue t = YaccSymbol() t.type = 'error' if hasattr(lookahead,"lineno"): t.lineno = lookahead.lineno t.value = lookahead lookaheadstack.append(lookahead) lookahead = t else: symstack.pop() statestack.pop() state = statestack[-1] # Potential bug fix continue # Call an error function here raise RuntimeError("yacc: internal parser error!!!\n") # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # parseopt_notrack(). # # Optimized version of parseopt() with line number tracking removed. # DO NOT EDIT THIS CODE DIRECTLY. Copy the optimized version and remove # code in the #--! TRACKING sections # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! def parseopt_notrack(self,input=None,lexer=None,debug=0,tracking=0,tokenfunc=None): lookahead = None # Current lookahead symbol lookaheadstack = [ ] # Stack of lookahead symbols actions = self.action # Local reference to action table (to avoid lookup on self.) goto = self.goto # Local reference to goto table (to avoid lookup on self.) prod = self.productions # Local reference to production list (to avoid lookup on self.) pslice = YaccProduction(None) # Production object passed to grammar rules errorcount = 0 # Used during error recovery # If no lexer was given, we will try to use the lex module if not lexer: lex = load_ply_lex() lexer = lex.lexer # Set up the lexer and parser objects on pslice pslice.lexer = lexer pslice.parser = self # If input was supplied, pass to lexer if input is not None: lexer.input(input) if tokenfunc is None: # Tokenize function get_token = lexer.token else: get_token = tokenfunc # Set up the state and symbol stacks statestack = [ ] # Stack of parsing states self.statestack = statestack symstack = [ ] # Stack of grammar symbols self.symstack = symstack pslice.stack = symstack # Put in the production errtoken = None # Err token # The start state is assumed to be (0,$end) statestack.append(0) sym = YaccSymbol() sym.type = '$end' symstack.append(sym) state = 0 while 1: # Get the next symbol on the input. If a lookahead symbol # is already set, we just use that. Otherwise, we'll pull # the next token off of the lookaheadstack or from the lexer if not lookahead: if not lookaheadstack: lookahead = get_token() # Get the next token else: lookahead = lookaheadstack.pop() if not lookahead: lookahead = YaccSymbol() lookahead.type = '$end' # Check the action table ltype = lookahead.type t = actions[state].get(ltype) if t is not None: if t > 0: # shift a symbol on the stack statestack.append(t) state = t symstack.append(lookahead) lookahead = None # Decrease error count on successful shift if errorcount: errorcount -=1 continue if t < 0: # reduce a symbol on the stack, emit a production p = prod[-t] pname = p.name plen = p.len # Get production function sym = YaccSymbol() sym.type = pname # Production name sym.value = None if plen: targ = symstack[-plen-1:] targ[0] = sym # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # The code enclosed in this section is duplicated # below as a performance optimization. Make sure # changes get made in both locations. pslice.slice = targ try: # Call the grammar rule with our special slice object del symstack[-plen:] del statestack[-plen:] p.callable(pslice) symstack.append(sym) state = goto[statestack[-1]][pname] statestack.append(state) except SyntaxError: # If an error was set. Enter error recovery state lookaheadstack.append(lookahead) symstack.pop() statestack.pop() state = statestack[-1] sym.type = 'error' lookahead = sym errorcount = error_count self.errorok = 0 continue # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! else: targ = [ sym ] # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # The code enclosed in this section is duplicated # above as a performance optimization. Make sure # changes get made in both locations. pslice.slice = targ try: # Call the grammar rule with our special slice object p.callable(pslice) symstack.append(sym) state = goto[statestack[-1]][pname] statestack.append(state) except SyntaxError: # If an error was set. Enter error recovery state lookaheadstack.append(lookahead) symstack.pop() statestack.pop() state = statestack[-1] sym.type = 'error' lookahead = sym errorcount = error_count self.errorok = 0 continue # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if t == 0: n = symstack[-1] return getattr(n,"value",None) if t == None: # We have some kind of parsing error here. To handle # this, we are going to push the current token onto # the tokenstack and replace it with an 'error' token. # If there are any synchronization rules, they may # catch it. # # In addition to pushing the error token, we call call # the user defined p_error() function if this is the # first syntax error. This function is only called if # errorcount == 0. if errorcount == 0 or self.errorok: errorcount = error_count self.errorok = 0 errtoken = lookahead if errtoken.type == '$end': errtoken = None # End of file! if self.errorfunc: global errok,token,restart errok = self.errok # Set some special functions available in error recovery token = get_token restart = self.restart if errtoken and not hasattr(errtoken,'lexer'): errtoken.lexer = lexer tok = self.errorfunc(errtoken) del errok, token, restart # Delete special functions if self.errorok: # User must have done some kind of panic # mode recovery on their own. The # returned token is the next lookahead lookahead = tok errtoken = None continue else: if errtoken: if hasattr(errtoken,"lineno"): lineno = lookahead.lineno else: lineno = 0 if lineno: sys.stderr.write("yacc: Syntax error at line %d, token=%s\n" % (lineno, errtoken.type)) else: sys.stderr.write("yacc: Syntax error, token=%s" % errtoken.type) else: sys.stderr.write("yacc: Parse error in input. EOF\n") return else: errorcount = error_count # case 1: the statestack only has 1 entry on it. If we're in this state, the # entire parse has been rolled back and we're completely hosed. The token is # discarded and we just keep going. if len(statestack) <= 1 and lookahead.type != '$end': lookahead = None errtoken = None state = 0 # Nuke the pushback stack del lookaheadstack[:] continue # case 2: the statestack has a couple of entries on it, but we're # at the end of the file. nuke the top entry and generate an error token # Start nuking entries on the stack if lookahead.type == '$end': # Whoa. We're really hosed here. Bail out return if lookahead.type != 'error': sym = symstack[-1] if sym.type == 'error': # Hmmm. Error is on top of stack, we'll just nuke input # symbol and continue lookahead = None continue t = YaccSymbol() t.type = 'error' if hasattr(lookahead,"lineno"): t.lineno = lookahead.lineno t.value = lookahead lookaheadstack.append(lookahead) lookahead = t else: symstack.pop() statestack.pop() state = statestack[-1] # Potential bug fix continue # Call an error function here raise RuntimeError("yacc: internal parser error!!!\n") # ----------------------------------------------------------------------------- # === Grammar Representation === # # The following functions, classes, and variables are used to represent and # manipulate the rules that make up a grammar. # ----------------------------------------------------------------------------- import re # regex matching identifiers _is_identifier = re.compile(r'^[a-zA-Z0-9_-]+$') # ----------------------------------------------------------------------------- # class Production: # # This class stores the raw information about a single production or grammar rule. # A grammar rule refers to a specification such as this: # # expr : expr PLUS term # # Here are the basic attributes defined on all productions # # name - Name of the production. For example 'expr' # prod - A list of symbols on the right side ['expr','PLUS','term'] # prec - Production precedence level # number - Production number. # func - Function that executes on reduce # file - File where production function is defined # lineno - Line number where production function is defined # # The following attributes are defined or optional. # # len - Length of the production (number of symbols on right hand side) # usyms - Set of unique symbols found in the production # ----------------------------------------------------------------------------- class Production(object): reduced = 0 def __init__(self,number,name,prod,precedence=('right',0),func=None,file='',line=0): self.name = name self.prod = tuple(prod) self.number = number self.func = func self.callable = None self.file = file self.line = line self.prec = precedence # Internal settings used during table construction self.len = len(self.prod) # Length of the production # Create a list of unique production symbols used in the production self.usyms = [ ] for s in self.prod: if s not in self.usyms: self.usyms.append(s) # List of all LR items for the production self.lr_items = [] self.lr_next = None # Create a string representation if self.prod: self.str = "%s -> %s" % (self.name," ".join(self.prod)) else: self.str = "%s -> <empty>" % self.name def __str__(self): return self.str def __repr__(self): return "Production("+str(self)+")" def __len__(self): return len(self.prod) def __nonzero__(self): return 1 def __getitem__(self,index): return self.prod[index] # Return the nth lr_item from the production (or None if at the end) def lr_item(self,n): if n > len(self.prod): return None p = LRItem(self,n) # Precompute the list of productions immediately following. Hack. Remove later try: p.lr_after = Prodnames[p.prod[n+1]] except (IndexError,KeyError): p.lr_after = [] try: p.lr_before = p.prod[n-1] except IndexError: p.lr_before = None return p # Bind the production function name to a callable def bind(self,pdict): if self.func: self.callable = pdict[self.func] # This class serves as a minimal standin for Production objects when # reading table data from files. It only contains information # actually used by the LR parsing engine, plus some additional # debugging information. class MiniProduction(object): def __init__(self,str,name,len,func,file,line): self.name = name self.len = len self.func = func self.callable = None self.file = file self.line = line self.str = str def __str__(self): return self.str def __repr__(self): return "MiniProduction(%s)" % self.str # Bind the production function name to a callable def bind(self,pdict): if self.func: self.callable = pdict[self.func] # ----------------------------------------------------------------------------- # class LRItem # # This class represents a specific stage of parsing a production rule. For # example: # # expr : expr . PLUS term # # In the above, the "." represents the current location of the parse. Here # basic attributes: # # name - Name of the production. For example 'expr' # prod - A list of symbols on the right side ['expr','.', 'PLUS','term'] # number - Production number. # # lr_next Next LR item. Example, if we are ' expr -> expr . PLUS term' # then lr_next refers to 'expr -> expr PLUS . term' # lr_index - LR item index (location of the ".") in the prod list. # lookaheads - LALR lookahead symbols for this item # len - Length of the production (number of symbols on right hand side) # lr_after - List of all productions that immediately follow # lr_before - Grammar symbol immediately before # ----------------------------------------------------------------------------- class LRItem(object): def __init__(self,p,n): self.name = p.name self.prod = list(p.prod) self.number = p.number self.lr_index = n self.lookaheads = { } self.prod.insert(n,".") self.prod = tuple(self.prod) self.len = len(self.prod) self.usyms = p.usyms def __str__(self): if self.prod: s = "%s -> %s" % (self.name," ".join(self.prod)) else: s = "%s -> <empty>" % self.name return s def __repr__(self): return "LRItem("+str(self)+")" # ----------------------------------------------------------------------------- # rightmost_terminal() # # Return the rightmost terminal from a list of symbols. Used in add_production() # ----------------------------------------------------------------------------- def rightmost_terminal(symbols, terminals): i = len(symbols) - 1 while i >= 0: if symbols[i] in terminals: return symbols[i] i -= 1 return None # ----------------------------------------------------------------------------- # === GRAMMAR CLASS === # # The following class represents the contents of the specified grammar along # with various computed properties such as first sets, follow sets, LR items, etc. # This data is used for critical parts of the table generation process later. # ----------------------------------------------------------------------------- class GrammarError(YaccError): pass class Grammar(object): def __init__(self,terminals): self.Productions = [None] # A list of all of the productions. The first # entry is always reserved for the purpose of # building an augmented grammar self.Prodnames = { } # A dictionary mapping the names of nonterminals to a list of all # productions of that nonterminal. self.Prodmap = { } # A dictionary that is only used to detect duplicate # productions. self.Terminals = { } # A dictionary mapping the names of terminal symbols to a # list of the rules where they are used. for term in terminals: self.Terminals[term] = [] self.Terminals['error'] = [] self.Nonterminals = { } # A dictionary mapping names of nonterminals to a list # of rule numbers where they are used. self.First = { } # A dictionary of precomputed FIRST(x) symbols self.Follow = { } # A dictionary of precomputed FOLLOW(x) symbols self.Precedence = { } # Precedence rules for each terminal. Contains tuples of the # form ('right',level) or ('nonassoc', level) or ('left',level) self.UsedPrecedence = { } # Precedence rules that were actually used by the grammer. # This is only used to provide error checking and to generate # a warning about unused precedence rules. self.Start = None # Starting symbol for the grammar def __len__(self): return len(self.Productions) def __getitem__(self,index): return self.Productions[index] # ----------------------------------------------------------------------------- # set_precedence() # # Sets the precedence for a given terminal. assoc is the associativity such as # 'left','right', or 'nonassoc'. level is a numeric level. # # ----------------------------------------------------------------------------- def set_precedence(self,term,assoc,level): assert self.Productions == [None],"Must call set_precedence() before add_production()" if term in self.Precedence: raise GrammarError("Precedence already specified for terminal '%s'" % term) if assoc not in ['left','right','nonassoc']: raise GrammarError("Associativity must be one of 'left','right', or 'nonassoc'") self.Precedence[term] = (assoc,level) # ----------------------------------------------------------------------------- # add_production() # # Given an action function, this function assembles a production rule and # computes its precedence level. # # The production rule is supplied as a list of symbols. For example, # a rule such as 'expr : expr PLUS term' has a production name of 'expr' and # symbols ['expr','PLUS','term']. # # Precedence is determined by the precedence of the right-most non-terminal # or the precedence of a terminal specified by %prec. # # A variety of error checks are performed to make sure production symbols # are valid and that %prec is used correctly. # ----------------------------------------------------------------------------- def add_production(self,prodname,syms,func=None,file='',line=0): if prodname in self.Terminals: raise GrammarError("%s:%d: Illegal rule name '%s'. Already defined as a token" % (file,line,prodname)) if prodname == 'error': raise GrammarError("%s:%d: Illegal rule name '%s'. error is a reserved word" % (file,line,prodname)) if not _is_identifier.match(prodname): raise GrammarError("%s:%d: Illegal rule name '%s'" % (file,line,prodname)) # Look for literal tokens for n,s in enumerate(syms): if s[0] in "'\"": try: c = eval(s) if (len(c) > 1): raise GrammarError("%s:%d: Literal token %s in rule '%s' may only be a single character" % (file,line,s, prodname)) if not c in self.Terminals: self.Terminals[c] = [] syms[n] = c continue except SyntaxError: pass if not _is_identifier.match(s) and s != '%prec': raise GrammarError("%s:%d: Illegal name '%s' in rule '%s'" % (file,line,s, prodname)) # Determine the precedence level if '%prec' in syms: if syms[-1] == '%prec': raise GrammarError("%s:%d: Syntax error. Nothing follows %%prec" % (file,line)) if syms[-2] != '%prec': raise GrammarError("%s:%d: Syntax error. %%prec can only appear at the end of a grammar rule" % (file,line)) precname = syms[-1] prodprec = self.Precedence.get(precname,None) if not prodprec: raise GrammarError("%s:%d: Nothing known about the precedence of '%s'" % (file,line,precname)) else: self.UsedPrecedence[precname] = 1 del syms[-2:] # Drop %prec from the rule else: # If no %prec, precedence is determined by the rightmost terminal symbol precname = rightmost_terminal(syms,self.Terminals) prodprec = self.Precedence.get(precname,('right',0)) # See if the rule is already in the rulemap map = "%s -> %s" % (prodname,syms) if map in self.Prodmap: m = self.Prodmap[map] raise GrammarError("%s:%d: Duplicate rule %s. " % (file,line, m) + "Previous definition at %s:%d" % (m.file, m.line)) # From this point on, everything is valid. Create a new Production instance pnumber = len(self.Productions) if not prodname in self.Nonterminals: self.Nonterminals[prodname] = [ ] # Add the production number to Terminals and Nonterminals for t in syms: if t in self.Terminals: self.Terminals[t].append(pnumber) else: if not t in self.Nonterminals: self.Nonterminals[t] = [ ] self.Nonterminals[t].append(pnumber) # Create a production and add it to the list of productions p = Production(pnumber,prodname,syms,prodprec,func,file,line) self.Productions.append(p) self.Prodmap[map] = p # Add to the global productions list try: self.Prodnames[prodname].append(p) except KeyError: self.Prodnames[prodname] = [ p ] return 0 # ----------------------------------------------------------------------------- # set_start() # # Sets the starting symbol and creates the augmented grammar. Production # rule 0 is S' -> start where start is the start symbol. # ----------------------------------------------------------------------------- def set_start(self,start=None): if not start: start = self.Productions[1].name if start not in self.Nonterminals: raise GrammarError("start symbol %s undefined" % start) self.Productions[0] = Production(0,"S'",[start]) self.Nonterminals[start].append(0) self.Start = start # ----------------------------------------------------------------------------- # find_unreachable() # # Find all of the nonterminal symbols that can't be reached from the starting # symbol. Returns a list of nonterminals that can't be reached. # ----------------------------------------------------------------------------- def find_unreachable(self): # Mark all symbols that are reachable from a symbol s def mark_reachable_from(s): if reachable[s]: # We've already reached symbol s. return reachable[s] = 1 for p in self.Prodnames.get(s,[]): for r in p.prod: mark_reachable_from(r) reachable = { } for s in list(self.Terminals) + list(self.Nonterminals): reachable[s] = 0 mark_reachable_from( self.Productions[0].prod[0] ) return [s for s in list(self.Nonterminals) if not reachable[s]] # ----------------------------------------------------------------------------- # infinite_cycles() # # This function looks at the various parsing rules and tries to detect # infinite recursion cycles (grammar rules where there is no possible way # to derive a string of only terminals). # ----------------------------------------------------------------------------- def infinite_cycles(self): terminates = {} # Terminals: for t in self.Terminals: terminates[t] = 1 terminates['$end'] = 1 # Nonterminals: # Initialize to false: for n in self.Nonterminals: terminates[n] = 0 # Then propagate termination until no change: while 1: some_change = 0 for (n,pl) in self.Prodnames.items(): # Nonterminal n terminates iff any of its productions terminates. for p in pl: # Production p terminates iff all of its rhs symbols terminate. for s in p.prod: if not terminates[s]: # The symbol s does not terminate, # so production p does not terminate. p_terminates = 0 break else: # didn't break from the loop, # so every symbol s terminates # so production p terminates. p_terminates = 1 if p_terminates: # symbol n terminates! if not terminates[n]: terminates[n] = 1 some_change = 1 # Don't need to consider any more productions for this n. break if not some_change: break infinite = [] for (s,term) in terminates.items(): if not term: if not s in self.Prodnames and not s in self.Terminals and s != 'error': # s is used-but-not-defined, and we've already warned of that, # so it would be overkill to say that it's also non-terminating. pass else: infinite.append(s) return infinite # ----------------------------------------------------------------------------- # undefined_symbols() # # Find all symbols that were used the grammar, but not defined as tokens or # grammar rules. Returns a list of tuples (sym, prod) where sym in the symbol # and prod is the production where the symbol was used. # ----------------------------------------------------------------------------- def undefined_symbols(self): result = [] for p in self.Productions: if not p: continue for s in p.prod: if not s in self.Prodnames and not s in self.Terminals and s != 'error': result.append((s,p)) return result # ----------------------------------------------------------------------------- # unused_terminals() # # Find all terminals that were defined, but not used by the grammar. Returns # a list of all symbols. # ----------------------------------------------------------------------------- def unused_terminals(self): unused_tok = [] for s,v in self.Terminals.items(): if s != 'error' and not v: unused_tok.append(s) return unused_tok # ------------------------------------------------------------------------------ # unused_rules() # # Find all grammar rules that were defined, but not used (maybe not reachable) # Returns a list of productions. # ------------------------------------------------------------------------------ def unused_rules(self): unused_prod = [] for s,v in self.Nonterminals.items(): if not v: p = self.Prodnames[s][0] unused_prod.append(p) return unused_prod # ----------------------------------------------------------------------------- # unused_precedence() # # Returns a list of tuples (term,precedence) corresponding to precedence # rules that were never used by the grammar. term is the name of the terminal # on which precedence was applied and precedence is a string such as 'left' or # 'right' corresponding to the type of precedence. # ----------------------------------------------------------------------------- def unused_precedence(self): unused = [] for termname in self.Precedence: if not (termname in self.Terminals or termname in self.UsedPrecedence): unused.append((termname,self.Precedence[termname][0])) return unused # ------------------------------------------------------------------------- # _first() # # Compute the value of FIRST1(beta) where beta is a tuple of symbols. # # During execution of compute_first1, the result may be incomplete. # Afterward (e.g., when called from compute_follow()), it will be complete. # ------------------------------------------------------------------------- def _first(self,beta): # We are computing First(x1,x2,x3,...,xn) result = [ ] for x in beta: x_produces_empty = 0 # Add all the non-<empty> symbols of First[x] to the result. for f in self.First[x]: if f == '<empty>': x_produces_empty = 1 else: if f not in result: result.append(f) if x_produces_empty: # We have to consider the next x in beta, # i.e. stay in the loop. pass else: # We don't have to consider any further symbols in beta. break else: # There was no 'break' from the loop, # so x_produces_empty was true for all x in beta, # so beta produces empty as well. result.append('<empty>') return result # ------------------------------------------------------------------------- # compute_first() # # Compute the value of FIRST1(X) for all symbols # ------------------------------------------------------------------------- def compute_first(self): if self.First: return self.First # Terminals: for t in self.Terminals: self.First[t] = [t] self.First['$end'] = ['$end'] # Nonterminals: # Initialize to the empty set: for n in self.Nonterminals: self.First[n] = [] # Then propagate symbols until no change: while 1: some_change = 0 for n in self.Nonterminals: for p in self.Prodnames[n]: for f in self._first(p.prod): if f not in self.First[n]: self.First[n].append( f ) some_change = 1 if not some_change: break return self.First # --------------------------------------------------------------------- # compute_follow() # # Computes all of the follow sets for every non-terminal symbol. The # follow set is the set of all symbols that might follow a given # non-terminal. See the Dragon book, 2nd Ed. p. 189. # --------------------------------------------------------------------- def compute_follow(self,start=None): # If already computed, return the result if self.Follow: return self.Follow # If first sets not computed yet, do that first. if not self.First: self.compute_first() # Add '$end' to the follow list of the start symbol for k in self.Nonterminals: self.Follow[k] = [ ] if not start: start = self.Productions[1].name self.Follow[start] = [ '$end' ] while 1: didadd = 0 for p in self.Productions[1:]: # Here is the production set for i in range(len(p.prod)): B = p.prod[i] if B in self.Nonterminals: # Okay. We got a non-terminal in a production fst = self._first(p.prod[i+1:]) hasempty = 0 for f in fst: if f != '<empty>' and f not in self.Follow[B]: self.Follow[B].append(f) didadd = 1 if f == '<empty>': hasempty = 1 if hasempty or i == (len(p.prod)-1): # Add elements of follow(a) to follow(b) for f in self.Follow[p.name]: if f not in self.Follow[B]: self.Follow[B].append(f) didadd = 1 if not didadd: break return self.Follow # ----------------------------------------------------------------------------- # build_lritems() # # This function walks the list of productions and builds a complete set of the # LR items. The LR items are stored in two ways: First, they are uniquely # numbered and placed in the list _lritems. Second, a linked list of LR items # is built for each production. For example: # # E -> E PLUS E # # Creates the list # # [E -> . E PLUS E, E -> E . PLUS E, E -> E PLUS . E, E -> E PLUS E . ] # ----------------------------------------------------------------------------- def build_lritems(self): for p in self.Productions: lastlri = p i = 0 lr_items = [] while 1: if i > len(p): lri = None else: lri = LRItem(p,i) # Precompute the list of productions immediately following try: lri.lr_after = self.Prodnames[lri.prod[i+1]] except (IndexError,KeyError): lri.lr_after = [] try: lri.lr_before = lri.prod[i-1] except IndexError: lri.lr_before = None lastlri.lr_next = lri if not lri: break lr_items.append(lri) lastlri = lri i += 1 p.lr_items = lr_items # ----------------------------------------------------------------------------- # == Class LRTable == # # This basic class represents a basic table of LR parsing information. # Methods for generating the tables are not defined here. They are defined # in the derived class LRGeneratedTable. # ----------------------------------------------------------------------------- class VersionError(YaccError): pass class LRTable(object): def __init__(self): self.lr_action = None self.lr_goto = None self.lr_productions = None self.lr_method = None def read_table(self,module): if isinstance(module,types.ModuleType): parsetab = module else: if sys.version_info[0] < 3: exec("import %s as parsetab" % module) else: env = { } exec("import %s as parsetab" % module, env, env) parsetab = env['parsetab'] if parsetab._tabversion != __tabversion__: raise VersionError("yacc table file version is out of date") self.lr_action = parsetab._lr_action self.lr_goto = parsetab._lr_goto self.lr_productions = [] for p in parsetab._lr_productions: self.lr_productions.append(MiniProduction(*p)) self.lr_method = parsetab._lr_method return parsetab._lr_signature def read_pickle(self,filename): try: import cPickle as pickle except ImportError: import pickle in_f = open(filename,"rb") tabversion = pickle.load(in_f) if tabversion != __tabversion__: raise VersionError("yacc table file version is out of date") self.lr_method = pickle.load(in_f) signature = pickle.load(in_f) self.lr_action = pickle.load(in_f) self.lr_goto = pickle.load(in_f) productions = pickle.load(in_f) self.lr_productions = [] for p in productions: self.lr_productions.append(MiniProduction(*p)) in_f.close() return signature # Bind all production function names to callable objects in pdict def bind_callables(self,pdict): for p in self.lr_productions: p.bind(pdict) # ----------------------------------------------------------------------------- # === LR Generator === # # The following classes and functions are used to generate LR parsing tables on # a grammar. # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # digraph() # traverse() # # The following two functions are used to compute set valued functions # of the form: # # F(x) = F'(x) U U{F(y) | x R y} # # This is used to compute the values of Read() sets as well as FOLLOW sets # in LALR(1) generation. # # Inputs: X - An input set # R - A relation # FP - Set-valued function # ------------------------------------------------------------------------------ def digraph(X,R,FP): N = { } for x in X: N[x] = 0 stack = [] F = { } for x in X: if N[x] == 0: traverse(x,N,stack,F,X,R,FP) return F def traverse(x,N,stack,F,X,R,FP): stack.append(x) d = len(stack) N[x] = d F[x] = FP(x) # F(X) <- F'(x) rel = R(x) # Get y's related to x for y in rel: if N[y] == 0: traverse(y,N,stack,F,X,R,FP) N[x] = min(N[x],N[y]) for a in F.get(y,[]): if a not in F[x]: F[x].append(a) if N[x] == d: N[stack[-1]] = MAXINT F[stack[-1]] = F[x] element = stack.pop() while element != x: N[stack[-1]] = MAXINT F[stack[-1]] = F[x] element = stack.pop() class LALRError(YaccError): pass # ----------------------------------------------------------------------------- # == LRGeneratedTable == # # This class implements the LR table generation algorithm. There are no # public methods except for write() # ----------------------------------------------------------------------------- class LRGeneratedTable(LRTable): def __init__(self,grammar,method='LALR',log=None): if method not in ['SLR','LALR']: raise LALRError("Unsupported method %s" % method) self.grammar = grammar self.lr_method = method # Set up the logger if not log: log = NullLogger() self.log = log # Internal attributes self.lr_action = {} # Action table self.lr_goto = {} # Goto table self.lr_productions = grammar.Productions # Copy of grammar Production array self.lr_goto_cache = {} # Cache of computed gotos self.lr0_cidhash = {} # Cache of closures self._add_count = 0 # Internal counter used to detect cycles # Diagonistic information filled in by the table generator self.sr_conflict = 0 self.rr_conflict = 0 self.conflicts = [] # List of conflicts self.sr_conflicts = [] self.rr_conflicts = [] # Build the tables self.grammar.build_lritems() self.grammar.compute_first() self.grammar.compute_follow() self.lr_parse_table() # Compute the LR(0) closure operation on I, where I is a set of LR(0) items. def lr0_closure(self,I): self._add_count += 1 # Add everything in I to J J = I[:] didadd = 1 while didadd: didadd = 0 for j in J: for x in j.lr_after: if getattr(x,"lr0_added",0) == self._add_count: continue # Add B --> .G to J J.append(x.lr_next) x.lr0_added = self._add_count didadd = 1 return J # Compute the LR(0) goto function goto(I,X) where I is a set # of LR(0) items and X is a grammar symbol. This function is written # in a way that guarantees uniqueness of the generated goto sets # (i.e. the same goto set will never be returned as two different Python # objects). With uniqueness, we can later do fast set comparisons using # id(obj) instead of element-wise comparison. def lr0_goto(self,I,x): # First we look for a previously cached entry g = self.lr_goto_cache.get((id(I),x),None) if g: return g # Now we generate the goto set in a way that guarantees uniqueness # of the result s = self.lr_goto_cache.get(x,None) if not s: s = { } self.lr_goto_cache[x] = s gs = [ ] for p in I: n = p.lr_next if n and n.lr_before == x: s1 = s.get(id(n),None) if not s1: s1 = { } s[id(n)] = s1 gs.append(n) s = s1 g = s.get('$end',None) if not g: if gs: g = self.lr0_closure(gs) s['$end'] = g else: s['$end'] = gs self.lr_goto_cache[(id(I),x)] = g return g # Compute the LR(0) sets of item function def lr0_items(self): C = [ self.lr0_closure([self.grammar.Productions[0].lr_next]) ] i = 0 for I in C: self.lr0_cidhash[id(I)] = i i += 1 # Loop over the items in C and each grammar symbols i = 0 while i < len(C): I = C[i] i += 1 # Collect all of the symbols that could possibly be in the goto(I,X) sets asyms = { } for ii in I: for s in ii.usyms: asyms[s] = None for x in asyms: g = self.lr0_goto(I,x) if not g: continue if id(g) in self.lr0_cidhash: continue self.lr0_cidhash[id(g)] = len(C) C.append(g) return C # ----------------------------------------------------------------------------- # ==== LALR(1) Parsing ==== # # LALR(1) parsing is almost exactly the same as SLR except that instead of # relying upon Follow() sets when performing reductions, a more selective # lookahead set that incorporates the state of the LR(0) machine is utilized. # Thus, we mainly just have to focus on calculating the lookahead sets. # # The method used here is due to DeRemer and Pennelo (1982). # # DeRemer, F. L., and T. J. Pennelo: "Efficient Computation of LALR(1) # Lookahead Sets", ACM Transactions on Programming Languages and Systems, # Vol. 4, No. 4, Oct. 1982, pp. 615-649 # # Further details can also be found in: # # J. Tremblay and P. Sorenson, "The Theory and Practice of Compiler Writing", # McGraw-Hill Book Company, (1985). # # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # compute_nullable_nonterminals() # # Creates a dictionary containing all of the non-terminals that might produce # an empty production. # ----------------------------------------------------------------------------- def compute_nullable_nonterminals(self): nullable = {} num_nullable = 0 while 1: for p in self.grammar.Productions[1:]: if p.len == 0: nullable[p.name] = 1 continue for t in p.prod: if not t in nullable: break else: nullable[p.name] = 1 if len(nullable) == num_nullable: break num_nullable = len(nullable) return nullable # ----------------------------------------------------------------------------- # find_nonterminal_trans(C) # # Given a set of LR(0) items, this functions finds all of the non-terminal # transitions. These are transitions in which a dot appears immediately before # a non-terminal. Returns a list of tuples of the form (state,N) where state # is the state number and N is the nonterminal symbol. # # The input C is the set of LR(0) items. # ----------------------------------------------------------------------------- def find_nonterminal_transitions(self,C): trans = [] for state in range(len(C)): for p in C[state]: if p.lr_index < p.len - 1: t = (state,p.prod[p.lr_index+1]) if t[1] in self.grammar.Nonterminals: if t not in trans: trans.append(t) state = state + 1 return trans # ----------------------------------------------------------------------------- # dr_relation() # # Computes the DR(p,A) relationships for non-terminal transitions. The input # is a tuple (state,N) where state is a number and N is a nonterminal symbol. # # Returns a list of terminals. # ----------------------------------------------------------------------------- def dr_relation(self,C,trans,nullable): dr_set = { } state,N = trans terms = [] g = self.lr0_goto(C[state],N) for p in g: if p.lr_index < p.len - 1: a = p.prod[p.lr_index+1] if a in self.grammar.Terminals: if a not in terms: terms.append(a) # This extra bit is to handle the start state if state == 0 and N == self.grammar.Productions[0].prod[0]: terms.append('$end') return terms # ----------------------------------------------------------------------------- # reads_relation() # # Computes the READS() relation (p,A) READS (t,C). # ----------------------------------------------------------------------------- def reads_relation(self,C, trans, empty): # Look for empty transitions rel = [] state, N = trans g = self.lr0_goto(C[state],N) j = self.lr0_cidhash.get(id(g),-1) for p in g: if p.lr_index < p.len - 1: a = p.prod[p.lr_index + 1] if a in empty: rel.append((j,a)) return rel # ----------------------------------------------------------------------------- # compute_lookback_includes() # # Determines the lookback and includes relations # # LOOKBACK: # # This relation is determined by running the LR(0) state machine forward. # For example, starting with a production "N : . A B C", we run it forward # to obtain "N : A B C ." We then build a relationship between this final # state and the starting state. These relationships are stored in a dictionary # lookdict. # # INCLUDES: # # Computes the INCLUDE() relation (p,A) INCLUDES (p',B). # # This relation is used to determine non-terminal transitions that occur # inside of other non-terminal transition states. (p,A) INCLUDES (p', B) # if the following holds: # # B -> LAT, where T -> epsilon and p' -L-> p # # L is essentially a prefix (which may be empty), T is a suffix that must be # able to derive an empty string. State p' must lead to state p with the string L. # # ----------------------------------------------------------------------------- def compute_lookback_includes(self,C,trans,nullable): lookdict = {} # Dictionary of lookback relations includedict = {} # Dictionary of include relations # Make a dictionary of non-terminal transitions dtrans = {} for t in trans: dtrans[t] = 1 # Loop over all transitions and compute lookbacks and includes for state,N in trans: lookb = [] includes = [] for p in C[state]: if p.name != N: continue # Okay, we have a name match. We now follow the production all the way # through the state machine until we get the . on the right hand side lr_index = p.lr_index j = state while lr_index < p.len - 1: lr_index = lr_index + 1 t = p.prod[lr_index] # Check to see if this symbol and state are a non-terminal transition if (j,t) in dtrans: # Yes. Okay, there is some chance that this is an includes relation # the only way to know for certain is whether the rest of the # production derives empty li = lr_index + 1 while li < p.len: if p.prod[li] in self.grammar.Terminals: break # No forget it if not p.prod[li] in nullable: break li = li + 1 else: # Appears to be a relation between (j,t) and (state,N) includes.append((j,t)) g = self.lr0_goto(C[j],t) # Go to next set j = self.lr0_cidhash.get(id(g),-1) # Go to next state # When we get here, j is the final state, now we have to locate the production for r in C[j]: if r.name != p.name: continue if r.len != p.len: continue i = 0 # This look is comparing a production ". A B C" with "A B C ." while i < r.lr_index: if r.prod[i] != p.prod[i+1]: break i = i + 1 else: lookb.append((j,r)) for i in includes: if not i in includedict: includedict[i] = [] includedict[i].append((state,N)) lookdict[(state,N)] = lookb return lookdict,includedict # ----------------------------------------------------------------------------- # compute_read_sets() # # Given a set of LR(0) items, this function computes the read sets. # # Inputs: C = Set of LR(0) items # ntrans = Set of nonterminal transitions # nullable = Set of empty transitions # # Returns a set containing the read sets # ----------------------------------------------------------------------------- def compute_read_sets(self,C, ntrans, nullable): FP = lambda x: self.dr_relation(C,x,nullable) R = lambda x: self.reads_relation(C,x,nullable) F = digraph(ntrans,R,FP) return F # ----------------------------------------------------------------------------- # compute_follow_sets() # # Given a set of LR(0) items, a set of non-terminal transitions, a readset, # and an include set, this function computes the follow sets # # Follow(p,A) = Read(p,A) U U {Follow(p',B) | (p,A) INCLUDES (p',B)} # # Inputs: # ntrans = Set of nonterminal transitions # readsets = Readset (previously computed) # inclsets = Include sets (previously computed) # # Returns a set containing the follow sets # ----------------------------------------------------------------------------- def compute_follow_sets(self,ntrans,readsets,inclsets): FP = lambda x: readsets[x] R = lambda x: inclsets.get(x,[]) F = digraph(ntrans,R,FP) return F # ----------------------------------------------------------------------------- # add_lookaheads() # # Attaches the lookahead symbols to grammar rules. # # Inputs: lookbacks - Set of lookback relations # followset - Computed follow set # # This function directly attaches the lookaheads to productions contained # in the lookbacks set # ----------------------------------------------------------------------------- def add_lookaheads(self,lookbacks,followset): for trans,lb in lookbacks.items(): # Loop over productions in lookback for state,p in lb: if not state in p.lookaheads: p.lookaheads[state] = [] f = followset.get(trans,[]) for a in f: if a not in p.lookaheads[state]: p.lookaheads[state].append(a) # ----------------------------------------------------------------------------- # add_lalr_lookaheads() # # This function does all of the work of adding lookahead information for use # with LALR parsing # ----------------------------------------------------------------------------- def add_lalr_lookaheads(self,C): # Determine all of the nullable nonterminals nullable = self.compute_nullable_nonterminals() # Find all non-terminal transitions trans = self.find_nonterminal_transitions(C) # Compute read sets readsets = self.compute_read_sets(C,trans,nullable) # Compute lookback/includes relations lookd, included = self.compute_lookback_includes(C,trans,nullable) # Compute LALR FOLLOW sets followsets = self.compute_follow_sets(trans,readsets,included) # Add all of the lookaheads self.add_lookaheads(lookd,followsets) # ----------------------------------------------------------------------------- # lr_parse_table() # # This function constructs the parse tables for SLR or LALR # ----------------------------------------------------------------------------- def lr_parse_table(self): Productions = self.grammar.Productions Precedence = self.grammar.Precedence goto = self.lr_goto # Goto array action = self.lr_action # Action array log = self.log # Logger for output actionp = { } # Action production array (temporary) log.info("Parsing method: %s", self.lr_method) # Step 1: Construct C = { I0, I1, ... IN}, collection of LR(0) items # This determines the number of states C = self.lr0_items() if self.lr_method == 'LALR': self.add_lalr_lookaheads(C) # Build the parser table, state by state st = 0 for I in C: # Loop over each production in I actlist = [ ] # List of actions st_action = { } st_actionp = { } st_goto = { } log.info("") log.info("state %d", st) log.info("") for p in I: log.info(" (%d) %s", p.number, str(p)) log.info("") for p in I: if p.len == p.lr_index + 1: if p.name == "S'": # Start symbol. Accept! st_action["$end"] = 0 st_actionp["$end"] = p else: # We are at the end of a production. Reduce! if self.lr_method == 'LALR': laheads = p.lookaheads[st] else: laheads = self.grammar.Follow[p.name] for a in laheads: actlist.append((a,p,"reduce using rule %d (%s)" % (p.number,p))) r = st_action.get(a,None) if r is not None: # Whoa. Have a shift/reduce or reduce/reduce conflict if r > 0: # Need to decide on shift or reduce here # By default we favor shifting. Need to add # some precedence rules here. sprec,slevel = Productions[st_actionp[a].number].prec rprec,rlevel = Precedence.get(a,('right',0)) if (slevel < rlevel) or ((slevel == rlevel) and (rprec == 'left')): # We really need to reduce here. st_action[a] = -p.number st_actionp[a] = p if not slevel and not rlevel: log.info(" ! shift/reduce conflict for %s resolved as reduce",a) self.sr_conflicts.append((st,a,'reduce')) Productions[p.number].reduced += 1 elif (slevel == rlevel) and (rprec == 'nonassoc'): st_action[a] = None else: # Hmmm. Guess we'll keep the shift if not rlevel: log.info(" ! shift/reduce conflict for %s resolved as shift",a) self.sr_conflicts.append((st,a,'shift')) elif r < 0: # Reduce/reduce conflict. In this case, we favor the rule # that was defined first in the grammar file oldp = Productions[-r] pp = Productions[p.number] if oldp.line > pp.line: st_action[a] = -p.number st_actionp[a] = p chosenp,rejectp = pp,oldp Productions[p.number].reduced += 1 Productions[oldp.number].reduced -= 1 else: chosenp,rejectp = oldp,pp self.rr_conflicts.append((st,chosenp,rejectp)) log.info(" ! reduce/reduce conflict for %s resolved using rule %d (%s)", a,st_actionp[a].number, st_actionp[a]) else: raise LALRError("Unknown conflict in state %d" % st) else: st_action[a] = -p.number st_actionp[a] = p Productions[p.number].reduced += 1 else: i = p.lr_index a = p.prod[i+1] # Get symbol right after the "." if a in self.grammar.Terminals: g = self.lr0_goto(I,a) j = self.lr0_cidhash.get(id(g),-1) if j >= 0: # We are in a shift state actlist.append((a,p,"shift and go to state %d" % j)) r = st_action.get(a,None) if r is not None: # Whoa have a shift/reduce or shift/shift conflict if r > 0: if r != j: raise LALRError("Shift/shift conflict in state %d" % st) elif r < 0: # Do a precedence check. # - if precedence of reduce rule is higher, we reduce. # - if precedence of reduce is same and left assoc, we reduce. # - otherwise we shift rprec,rlevel = Productions[st_actionp[a].number].prec sprec,slevel = Precedence.get(a,('right',0)) if (slevel > rlevel) or ((slevel == rlevel) and (rprec == 'right')): # We decide to shift here... highest precedence to shift Productions[st_actionp[a].number].reduced -= 1 st_action[a] = j st_actionp[a] = p if not rlevel: log.info(" ! shift/reduce conflict for %s resolved as shift",a) self.sr_conflicts.append((st,a,'shift')) elif (slevel == rlevel) and (rprec == 'nonassoc'): st_action[a] = None else: # Hmmm. Guess we'll keep the reduce if not slevel and not rlevel: log.info(" ! shift/reduce conflict for %s resolved as reduce",a) self.sr_conflicts.append((st,a,'reduce')) else: raise LALRError("Unknown conflict in state %d" % st) else: st_action[a] = j st_actionp[a] = p # Print the actions associated with each terminal _actprint = { } for a,p,m in actlist: if a in st_action: if p is st_actionp[a]: log.info(" %-15s %s",a,m) _actprint[(a,m)] = 1 log.info("") # Print the actions that were not used. (debugging) not_used = 0 for a,p,m in actlist: if a in st_action: if p is not st_actionp[a]: if not (a,m) in _actprint: log.debug(" ! %-15s [ %s ]",a,m) not_used = 1 _actprint[(a,m)] = 1 if not_used: log.debug("") # Construct the goto table for this state nkeys = { } for ii in I: for s in ii.usyms: if s in self.grammar.Nonterminals: nkeys[s] = None for n in nkeys: g = self.lr0_goto(I,n) j = self.lr0_cidhash.get(id(g),-1) if j >= 0: st_goto[n] = j log.info(" %-30s shift and go to state %d",n,j) action[st] = st_action actionp[st] = st_actionp goto[st] = st_goto st += 1 # ----------------------------------------------------------------------------- # write() # # This function writes the LR parsing tables to a file # ----------------------------------------------------------------------------- def write_table(self,modulename,outputdir='',signature=""): basemodulename = modulename.split(".")[-1] filename = os.path.join(outputdir,basemodulename) + ".py" try: f = open(filename,"w") f.write(""" # %s # This file is automatically generated. Do not edit. _tabversion = %r _lr_method = %r _lr_signature = %r """ % (filename, __tabversion__, self.lr_method, signature)) # Change smaller to 0 to go back to original tables smaller = 1 # Factor out names to try and make smaller if smaller: items = { } for s,nd in self.lr_action.items(): for name,v in nd.items(): i = items.get(name) if not i: i = ([],[]) items[name] = i i[0].append(s) i[1].append(v) f.write("\n_lr_action_items = {") for k,v in items.items(): f.write("%r:([" % k) for i in v[0]: f.write("%r," % i) f.write("],[") for i in v[1]: f.write("%r," % i) f.write("]),") f.write("}\n") f.write(""" _lr_action = { } for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = { } _lr_action[_x][_k] = _y del _lr_action_items """) else: f.write("\n_lr_action = { "); for k,v in self.lr_action.items(): f.write("(%r,%r):%r," % (k[0],k[1],v)) f.write("}\n"); if smaller: # Factor out names to try and make smaller items = { } for s,nd in self.lr_goto.items(): for name,v in nd.items(): i = items.get(name) if not i: i = ([],[]) items[name] = i i[0].append(s) i[1].append(v) f.write("\n_lr_goto_items = {") for k,v in items.items(): f.write("%r:([" % k) for i in v[0]: f.write("%r," % i) f.write("],[") for i in v[1]: f.write("%r," % i) f.write("]),") f.write("}\n") f.write(""" _lr_goto = { } for _k, _v in _lr_goto_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_goto: _lr_goto[_x] = { } _lr_goto[_x][_k] = _y del _lr_goto_items """) else: f.write("\n_lr_goto = { "); for k,v in self.lr_goto.items(): f.write("(%r,%r):%r," % (k[0],k[1],v)) f.write("}\n"); # Write production table f.write("_lr_productions = [\n") for p in self.lr_productions: if p.func: f.write(" (%r,%r,%d,%r,%r,%d),\n" % (p.str,p.name, p.len, p.func,p.file,p.line)) else: f.write(" (%r,%r,%d,None,None,None),\n" % (str(p),p.name, p.len)) f.write("]\n") f.close() except IOError: e = sys.exc_info()[1] sys.stderr.write("Unable to create '%s'\n" % filename) sys.stderr.write(str(e)+"\n") return # ----------------------------------------------------------------------------- # pickle_table() # # This function pickles the LR parsing tables to a supplied file object # ----------------------------------------------------------------------------- def pickle_table(self,filename,signature=""): try: import cPickle as pickle except ImportError: import pickle outf = open(filename,"wb") pickle.dump(__tabversion__,outf,pickle_protocol) pickle.dump(self.lr_method,outf,pickle_protocol) pickle.dump(signature,outf,pickle_protocol) pickle.dump(self.lr_action,outf,pickle_protocol) pickle.dump(self.lr_goto,outf,pickle_protocol) outp = [] for p in self.lr_productions: if p.func: outp.append((p.str,p.name, p.len, p.func,p.file,p.line)) else: outp.append((str(p),p.name,p.len,None,None,None)) pickle.dump(outp,outf,pickle_protocol) outf.close() # ----------------------------------------------------------------------------- # === INTROSPECTION === # # The following functions and classes are used to implement the PLY # introspection features followed by the yacc() function itself. # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # get_caller_module_dict() # # This function returns a dictionary containing all of the symbols defined within # a caller further down the call stack. This is used to get the environment # associated with the yacc() call if none was provided. # ----------------------------------------------------------------------------- def get_caller_module_dict(levels): try: raise RuntimeError except RuntimeError: e,b,t = sys.exc_info() f = t.tb_frame while levels > 0: f = f.f_back levels -= 1 ldict = f.f_globals.copy() if f.f_globals != f.f_locals: ldict.update(f.f_locals) return ldict # ----------------------------------------------------------------------------- # parse_grammar() # # This takes a raw grammar rule string and parses it into production data # ----------------------------------------------------------------------------- def parse_grammar(doc,file,line): grammar = [] # Split the doc string into lines pstrings = doc.splitlines() lastp = None dline = line for ps in pstrings: dline += 1 p = ps.split() if not p: continue try: if p[0] == '|': # This is a continuation of a previous rule if not lastp: raise SyntaxError("%s:%d: Misplaced '|'" % (file,dline)) prodname = lastp syms = p[1:] else: prodname = p[0] lastp = prodname syms = p[2:] assign = p[1] if assign != ':' and assign != '::=': raise SyntaxError("%s:%d: Syntax error. Expected ':'" % (file,dline)) grammar.append((file,dline,prodname,syms)) except SyntaxError: raise except Exception: raise SyntaxError("%s:%d: Syntax error in rule '%s'" % (file,dline,ps.strip())) return grammar # ----------------------------------------------------------------------------- # ParserReflect() # # This class represents information extracted for building a parser including # start symbol, error function, tokens, precedence list, action functions, # etc. # ----------------------------------------------------------------------------- class ParserReflect(object): def __init__(self,pdict,log=None): self.pdict = pdict self.start = None self.error_func = None self.tokens = None self.files = {} self.grammar = [] self.error = 0 if log is None: self.log = PlyLogger(sys.stderr) else: self.log = log # Get all of the basic information def get_all(self): self.get_start() self.get_error_func() self.get_tokens() self.get_precedence() self.get_pfunctions() # Validate all of the information def validate_all(self): self.validate_start() self.validate_error_func() self.validate_tokens() self.validate_precedence() self.validate_pfunctions() self.validate_files() return self.error # Compute a signature over the grammar def signature(self): try: from hashlib import md5 except ImportError: from md5 import md5 try: sig = md5() if self.start: sig.update(self.start.encode('latin-1')) if self.prec: sig.update("".join(["".join(p) for p in self.prec]).encode('latin-1')) if self.tokens: sig.update(" ".join(self.tokens).encode('latin-1')) for f in self.pfuncs: if f[3]: sig.update(f[3].encode('latin-1')) except (TypeError,ValueError): pass return sig.digest() # ----------------------------------------------------------------------------- # validate_file() # # This method checks to see if there are duplicated p_rulename() functions # in the parser module file. Without this function, it is really easy for # users to make mistakes by cutting and pasting code fragments (and it's a real # bugger to try and figure out why the resulting parser doesn't work). Therefore, # we just do a little regular expression pattern matching of def statements # to try and detect duplicates. # ----------------------------------------------------------------------------- def validate_files(self): # Match def p_funcname( fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(') for filename in self.files.keys(): base,ext = os.path.splitext(filename) if ext != '.py': return 1 # No idea. Assume it's okay. try: f = open(filename, encoding = 'utf-8') lines = f.readlines() f.close() except IOError: continue counthash = { } for linen,l in enumerate(lines): linen += 1 m = fre.match(l) if m: name = m.group(1) prev = counthash.get(name) if not prev: counthash[name] = linen else: self.log.warning("%s:%d: Function %s redefined. Previously defined on line %d", filename,linen,name,prev) # Get the start symbol def get_start(self): self.start = self.pdict.get('start') # Validate the start symbol def validate_start(self): if self.start is not None: if not isinstance(self.start,str): self.log.error("'start' must be a string") # Look for error handler def get_error_func(self): self.error_func = self.pdict.get('p_error') # Validate the error function def validate_error_func(self): if self.error_func: if isinstance(self.error_func,types.FunctionType): ismethod = 0 elif isinstance(self.error_func, types.MethodType): ismethod = 1 else: self.log.error("'p_error' defined, but is not a function or method") self.error = 1 return eline = func_code(self.error_func).co_firstlineno efile = func_code(self.error_func).co_filename self.files[efile] = 1 if (func_code(self.error_func).co_argcount != 1+ismethod): self.log.error("%s:%d: p_error() requires 1 argument",efile,eline) self.error = 1 # Get the tokens map def get_tokens(self): tokens = self.pdict.get("tokens",None) if not tokens: self.log.error("No token list is defined") self.error = 1 return if not isinstance(tokens,(list, tuple)): self.log.error("tokens must be a list or tuple") self.error = 1 return if not tokens: self.log.error("tokens is empty") self.error = 1 return self.tokens = tokens # Validate the tokens def validate_tokens(self): # Validate the tokens. if 'error' in self.tokens: self.log.error("Illegal token name 'error'. Is a reserved word") self.error = 1 return terminals = {} for n in self.tokens: if n in terminals: self.log.warning("Token '%s' multiply defined", n) terminals[n] = 1 # Get the precedence map (if any) def get_precedence(self): self.prec = self.pdict.get("precedence",None) # Validate and parse the precedence map def validate_precedence(self): preclist = [] if self.prec: if not isinstance(self.prec,(list,tuple)): self.log.error("precedence must be a list or tuple") self.error = 1 return for level,p in enumerate(self.prec): if not isinstance(p,(list,tuple)): self.log.error("Bad precedence table") self.error = 1 return if len(p) < 2: self.log.error("Malformed precedence entry %s. Must be (assoc, term, ..., term)",p) self.error = 1 return assoc = p[0] if not isinstance(assoc,str): self.log.error("precedence associativity must be a string") self.error = 1 return for term in p[1:]: if not isinstance(term,str): self.log.error("precedence items must be strings") self.error = 1 return preclist.append((term,assoc,level+1)) self.preclist = preclist # Get all p_functions from the grammar def get_pfunctions(self): p_functions = [] for name, item in self.pdict.items(): if name[:2] != 'p_': continue if name == 'p_error': continue if isinstance(item,(types.FunctionType,types.MethodType)): line = func_code(item).co_firstlineno file = func_code(item).co_filename p_functions.append((line,file,name,item.__doc__)) # Sort all of the actions by line number p_functions.sort() self.pfuncs = p_functions # Validate all of the p_functions def validate_pfunctions(self): grammar = [] # Check for non-empty symbols if len(self.pfuncs) == 0: self.log.error("no rules of the form p_rulename are defined") self.error = 1 return for line, file, name, doc in self.pfuncs: func = self.pdict[name] if isinstance(func, types.MethodType): reqargs = 2 else: reqargs = 1 if func_code(func).co_argcount > reqargs: self.log.error("%s:%d: Rule '%s' has too many arguments",file,line,func.__name__) self.error = 1 elif func_code(func).co_argcount < reqargs: self.log.error("%s:%d: Rule '%s' requires an argument",file,line,func.__name__) self.error = 1 elif not func.__doc__: self.log.warning("%s:%d: No documentation string specified in function '%s' (ignored)",file,line,func.__name__) else: try: parsed_g = parse_grammar(doc,file,line) for g in parsed_g: grammar.append((name, g)) except SyntaxError: e = sys.exc_info()[1] self.log.error(str(e)) self.error = 1 # Looks like a valid grammar rule # Mark the file in which defined. self.files[file] = 1 # Secondary validation step that looks for p_ definitions that are not functions # or functions that look like they might be grammar rules. for n,v in self.pdict.items(): if n[0:2] == 'p_' and isinstance(v, (types.FunctionType, types.MethodType)): continue if n[0:2] == 't_': continue if n[0:2] == 'p_' and n != 'p_error': self.log.warning("'%s' not defined as a function", n) if ((isinstance(v,types.FunctionType) and func_code(v).co_argcount == 1) or (isinstance(v,types.MethodType) and func_code(v).co_argcount == 2)): try: doc = v.__doc__.split(" ") if doc[1] == ':': self.log.warning("%s:%d: Possible grammar rule '%s' defined without p_ prefix", func_code(v).co_filename, func_code(v).co_firstlineno,n) except Exception: pass self.grammar = grammar # ----------------------------------------------------------------------------- # yacc(module) # # Build a parser # ----------------------------------------------------------------------------- def yacc(method='LALR', debug=yaccdebug, module=None, tabmodule=tab_module, start=None, check_recursion=1, optimize=0, write_tables=1, debugfile=debug_file,outputdir='', debuglog=None, errorlog = None, picklefile=None): global parse # Reference to the parsing method of the last built parser # If pickling is enabled, table files are not created if picklefile: write_tables = 0 if errorlog is None: errorlog = PlyLogger(sys.stderr) # Get the module dictionary used for the parser if module: _items = [(k,getattr(module,k)) for k in dir(module)] pdict = dict(_items) else: pdict = get_caller_module_dict(2) # Collect parser information from the dictionary pinfo = ParserReflect(pdict,log=errorlog) pinfo.get_all() if pinfo.error: raise YaccError("Unable to build parser") # Check signature against table files (if any) signature = pinfo.signature() # Read the tables try: lr = LRTable() if picklefile: read_signature = lr.read_pickle(picklefile) else: read_signature = lr.read_table(tabmodule) if optimize or (read_signature == signature): try: lr.bind_callables(pinfo.pdict) parser = LRParser(lr,pinfo.error_func) parse = parser.parse return parser except Exception: e = sys.exc_info()[1] errorlog.warning("There was a problem loading the table file: %s", repr(e)) except VersionError: e = sys.exc_info() errorlog.warning(str(e)) except Exception: pass if debuglog is None: if debug: debuglog = PlyLogger(open(debugfile,"w")) else: debuglog = NullLogger() debuglog.info("Created by PLY version %s (http://www.dabeaz.com/ply)", __version__) errors = 0 # Validate the parser information if pinfo.validate_all(): raise YaccError("Unable to build parser") if not pinfo.error_func: errorlog.warning("no p_error() function is defined") # Create a grammar object grammar = Grammar(pinfo.tokens) # Set precedence level for terminals for term, assoc, level in pinfo.preclist: try: grammar.set_precedence(term,assoc,level) except GrammarError: e = sys.exc_info()[1] errorlog.warning("%s",str(e)) # Add productions to the grammar for funcname, gram in pinfo.grammar: file, line, prodname, syms = gram try: grammar.add_production(prodname,syms,funcname,file,line) except GrammarError: e = sys.exc_info()[1] errorlog.error("%s",str(e)) errors = 1 # Set the grammar start symbols try: if start is None: grammar.set_start(pinfo.start) else: grammar.set_start(start) except GrammarError: e = sys.exc_info()[1] errorlog.error(str(e)) errors = 1 if errors: raise YaccError("Unable to build parser") # Verify the grammar structure undefined_symbols = grammar.undefined_symbols() for sym, prod in undefined_symbols: errorlog.error("%s:%d: Symbol '%s' used, but not defined as a token or a rule",prod.file,prod.line,sym) errors = 1 unused_terminals = grammar.unused_terminals() if unused_terminals: debuglog.info("") debuglog.info("Unused terminals:") debuglog.info("") for term in unused_terminals: errorlog.warning("Token '%s' defined, but not used", term) debuglog.info(" %s", term) # Print out all productions to the debug log if debug: debuglog.info("") debuglog.info("Grammar") debuglog.info("") for n,p in enumerate(grammar.Productions): debuglog.info("Rule %-5d %s", n, p) # Find unused non-terminals unused_rules = grammar.unused_rules() for prod in unused_rules: errorlog.warning("%s:%d: Rule '%s' defined, but not used", prod.file, prod.line, prod.name) if len(unused_terminals) == 1: errorlog.warning("There is 1 unused token") if len(unused_terminals) > 1: errorlog.warning("There are %d unused tokens", len(unused_terminals)) if len(unused_rules) == 1: errorlog.warning("There is 1 unused rule") if len(unused_rules) > 1: errorlog.warning("There are %d unused rules", len(unused_rules)) if debug: debuglog.info("") debuglog.info("Terminals, with rules where they appear") debuglog.info("") terms = list(grammar.Terminals) terms.sort() for term in terms: debuglog.info("%-20s : %s", term, " ".join([str(s) for s in grammar.Terminals[term]])) debuglog.info("") debuglog.info("Nonterminals, with rules where they appear") debuglog.info("") nonterms = list(grammar.Nonterminals) nonterms.sort() for nonterm in nonterms: debuglog.info("%-20s : %s", nonterm, " ".join([str(s) for s in grammar.Nonterminals[nonterm]])) debuglog.info("") if check_recursion: unreachable = grammar.find_unreachable() for u in unreachable: errorlog.warning("Symbol '%s' is unreachable",u) infinite = grammar.infinite_cycles() for inf in infinite: errorlog.error("Infinite recursion detected for symbol '%s'", inf) errors = 1 unused_prec = grammar.unused_precedence() for term, assoc in unused_prec: errorlog.error("Precedence rule '%s' defined for unknown symbol '%s'", assoc, term) errors = 1 if errors: raise YaccError("Unable to build parser") # Run the LRGeneratedTable on the grammar if debug: errorlog.debug("Generating %s tables", method) lr = LRGeneratedTable(grammar,method,debuglog) if debug: num_sr = len(lr.sr_conflicts) # Report shift/reduce and reduce/reduce conflicts if num_sr == 1: errorlog.warning("1 shift/reduce conflict") elif num_sr > 1: errorlog.warning("%d shift/reduce conflicts", num_sr) num_rr = len(lr.rr_conflicts) if num_rr == 1: errorlog.warning("1 reduce/reduce conflict") elif num_rr > 1: errorlog.warning("%d reduce/reduce conflicts", num_rr) # Write out conflicts to the output file if debug and (lr.sr_conflicts or lr.rr_conflicts): debuglog.warning("") debuglog.warning("Conflicts:") debuglog.warning("") for state, tok, resolution in lr.sr_conflicts: debuglog.warning("shift/reduce conflict for %s in state %d resolved as %s", tok, state, resolution) already_reported = {} for state, rule, rejected in lr.rr_conflicts: if (state,id(rule),id(rejected)) in already_reported: continue debuglog.warning("reduce/reduce conflict in state %d resolved using rule (%s)", state, rule) debuglog.warning("rejected rule (%s) in state %d", rejected,state) errorlog.warning("reduce/reduce conflict in state %d resolved using rule (%s)", state, rule) errorlog.warning("rejected rule (%s) in state %d", rejected, state) already_reported[state,id(rule),id(rejected)] = 1 warned_never = [] for state, rule, rejected in lr.rr_conflicts: if not rejected.reduced and (rejected not in warned_never): debuglog.warning("Rule (%s) is never reduced", rejected) errorlog.warning("Rule (%s) is never reduced", rejected) warned_never.append(rejected) # Write the table file if requested if write_tables: lr.write_table(tabmodule,outputdir,signature) # Write a pickled version of the tables if picklefile: lr.pickle_table(picklefile,signature) # Build the parser lr.bind_callables(pinfo.pdict) parser = LRParser(lr,pinfo.error_func) parse = parser.parse return parser
Python
# ----------------------------------------------------------------------------- # ply: lex.py # # Copyright (C) 2001-2009, # David M. Beazley (Dabeaz LLC) # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the David Beazley or Dabeaz LLC may be used to # endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ----------------------------------------------------------------------------- __version__ = "3.3" __tabversion__ = "3.2" # Version of table file used import re, sys, types, copy, os # This tuple contains known string types try: # Python 2.6 StringTypes = (types.StringType, types.UnicodeType) except AttributeError: # Python 3.0 StringTypes = (str, bytes) # Extract the code attribute of a function. Different implementations # are for Python 2/3 compatibility. if sys.version_info[0] < 3: def func_code(f): return f.func_code else: def func_code(f): return f.__code__ # This regular expression is used to match valid token names _is_identifier = re.compile(r'^[a-zA-Z0-9_]+$') # Exception thrown when invalid token encountered and no default error # handler is defined. class LexError(Exception): def __init__(self,message,s): self.args = (message,) self.text = s # Token class. This class is used to represent the tokens produced. class LexToken(object): def __str__(self): return "LexToken(%s,%r,%d,%d)" % (self.type,self.value,self.lineno,self.lexpos) def __repr__(self): return str(self) # This object is a stand-in for a logging object created by the # logging module. class PlyLogger(object): def __init__(self,f): self.f = f def critical(self,msg,*args,**kwargs): self.f.write((msg % args) + "\n") def warning(self,msg,*args,**kwargs): self.f.write("WARNING: "+ (msg % args) + "\n") def error(self,msg,*args,**kwargs): self.f.write("ERROR: " + (msg % args) + "\n") info = critical debug = critical # Null logger is used when no output is generated. Does nothing. class NullLogger(object): def __getattribute__(self,name): return self def __call__(self,*args,**kwargs): return self # ----------------------------------------------------------------------------- # === Lexing Engine === # # The following Lexer class implements the lexer runtime. There are only # a few public methods and attributes: # # input() - Store a new string in the lexer # token() - Get the next token # clone() - Clone the lexer # # lineno - Current line number # lexpos - Current position in the input string # ----------------------------------------------------------------------------- class Lexer: def __init__(self): self.lexre = None # Master regular expression. This is a list of # tuples (re,findex) where re is a compiled # regular expression and findex is a list # mapping regex group numbers to rules self.lexretext = None # Current regular expression strings self.lexstatere = {} # Dictionary mapping lexer states to master regexs self.lexstateretext = {} # Dictionary mapping lexer states to regex strings self.lexstaterenames = {} # Dictionary mapping lexer states to symbol names self.lexstate = "INITIAL" # Current lexer state self.lexstatestack = [] # Stack of lexer states self.lexstateinfo = None # State information self.lexstateignore = {} # Dictionary of ignored characters for each state self.lexstateerrorf = {} # Dictionary of error functions for each state self.lexreflags = 0 # Optional re compile flags self.lexdata = None # Actual input data (as a string) self.lexpos = 0 # Current position in input text self.lexlen = 0 # Length of the input text self.lexerrorf = None # Error rule (if any) self.lextokens = None # List of valid tokens self.lexignore = "" # Ignored characters self.lexliterals = "" # Literal characters that can be passed through self.lexmodule = None # Module self.lineno = 1 # Current line number self.lexoptimize = 0 # Optimized mode def clone(self,object=None): c = copy.copy(self) # If the object parameter has been supplied, it means we are attaching the # lexer to a new object. In this case, we have to rebind all methods in # the lexstatere and lexstateerrorf tables. if object: newtab = { } for key, ritem in self.lexstatere.items(): newre = [] for cre, findex in ritem: newfindex = [] for f in findex: if not f or not f[0]: newfindex.append(f) continue newfindex.append((getattr(object,f[0].__name__),f[1])) newre.append((cre,newfindex)) newtab[key] = newre c.lexstatere = newtab c.lexstateerrorf = { } for key, ef in self.lexstateerrorf.items(): c.lexstateerrorf[key] = getattr(object,ef.__name__) c.lexmodule = object return c # ------------------------------------------------------------ # writetab() - Write lexer information to a table file # ------------------------------------------------------------ def writetab(self,tabfile,outputdir=""): if isinstance(tabfile,types.ModuleType): return basetabfilename = tabfile.split(".")[-1] filename = os.path.join(outputdir,basetabfilename)+".py" tf = open(filename,"w") tf.write("# %s.py. This file automatically created by PLY (version %s). Don't edit!\n" % (tabfile,__version__)) tf.write("_tabversion = %s\n" % repr(__version__)) tf.write("_lextokens = %s\n" % repr(self.lextokens)) tf.write("_lexreflags = %s\n" % repr(self.lexreflags)) tf.write("_lexliterals = %s\n" % repr(self.lexliterals)) tf.write("_lexstateinfo = %s\n" % repr(self.lexstateinfo)) tabre = { } # Collect all functions in the initial state initial = self.lexstatere["INITIAL"] initialfuncs = [] for part in initial: for f in part[1]: if f and f[0]: initialfuncs.append(f) for key, lre in self.lexstatere.items(): titem = [] for i in range(len(lre)): titem.append((self.lexstateretext[key][i],_funcs_to_names(lre[i][1],self.lexstaterenames[key][i]))) tabre[key] = titem tf.write("_lexstatere = %s\n" % repr(tabre)) tf.write("_lexstateignore = %s\n" % repr(self.lexstateignore)) taberr = { } for key, ef in self.lexstateerrorf.items(): if ef: taberr[key] = ef.__name__ else: taberr[key] = None tf.write("_lexstateerrorf = %s\n" % repr(taberr)) tf.close() # ------------------------------------------------------------ # readtab() - Read lexer information from a tab file # ------------------------------------------------------------ def readtab(self,tabfile,fdict): if isinstance(tabfile,types.ModuleType): lextab = tabfile else: if sys.version_info[0] < 3: exec("import %s as lextab" % tabfile) else: env = { } exec("import %s as lextab" % tabfile, env,env) lextab = env['lextab'] if getattr(lextab,"_tabversion","0.0") != __version__: raise ImportError("Inconsistent PLY version") self.lextokens = lextab._lextokens self.lexreflags = lextab._lexreflags self.lexliterals = lextab._lexliterals self.lexstateinfo = lextab._lexstateinfo self.lexstateignore = lextab._lexstateignore self.lexstatere = { } self.lexstateretext = { } for key,lre in lextab._lexstatere.items(): titem = [] txtitem = [] for i in range(len(lre)): titem.append((re.compile(lre[i][0],lextab._lexreflags | re.VERBOSE),_names_to_funcs(lre[i][1],fdict))) txtitem.append(lre[i][0]) self.lexstatere[key] = titem self.lexstateretext[key] = txtitem self.lexstateerrorf = { } for key,ef in lextab._lexstateerrorf.items(): self.lexstateerrorf[key] = fdict[ef] self.begin('INITIAL') # ------------------------------------------------------------ # input() - Push a new string into the lexer # ------------------------------------------------------------ def input(self,s): # Pull off the first character to see if s looks like a string c = s[:1] if not isinstance(c,StringTypes): raise ValueError("Expected a string") self.lexdata = s self.lexpos = 0 self.lexlen = len(s) # ------------------------------------------------------------ # begin() - Changes the lexing state # ------------------------------------------------------------ def begin(self,state): if not state in self.lexstatere: raise ValueError("Undefined state") self.lexre = self.lexstatere[state] self.lexretext = self.lexstateretext[state] self.lexignore = self.lexstateignore.get(state,"") self.lexerrorf = self.lexstateerrorf.get(state,None) self.lexstate = state # ------------------------------------------------------------ # push_state() - Changes the lexing state and saves old on stack # ------------------------------------------------------------ def push_state(self,state): self.lexstatestack.append(self.lexstate) self.begin(state) # ------------------------------------------------------------ # pop_state() - Restores the previous state # ------------------------------------------------------------ def pop_state(self): self.begin(self.lexstatestack.pop()) # ------------------------------------------------------------ # current_state() - Returns the current lexing state # ------------------------------------------------------------ def current_state(self): return self.lexstate # ------------------------------------------------------------ # skip() - Skip ahead n characters # ------------------------------------------------------------ def skip(self,n): self.lexpos += n # ------------------------------------------------------------ # opttoken() - Return the next token from the Lexer # # Note: This function has been carefully implemented to be as fast # as possible. Don't make changes unless you really know what # you are doing # ------------------------------------------------------------ def token(self): # Make local copies of frequently referenced attributes lexpos = self.lexpos lexlen = self.lexlen lexignore = self.lexignore lexdata = self.lexdata while lexpos < lexlen: # This code provides some short-circuit code for whitespace, tabs, and other ignored characters if lexdata[lexpos] in lexignore: lexpos += 1 continue # Look for a regular expression match for lexre,lexindexfunc in self.lexre: m = lexre.match(lexdata,lexpos) if not m: continue # Create a token for return tok = LexToken() tok.value = m.group() tok.lineno = self.lineno tok.lexpos = lexpos i = m.lastindex func,tok.type = lexindexfunc[i] if not func: # If no token type was set, it's an ignored token if tok.type: self.lexpos = m.end() return tok else: lexpos = m.end() break lexpos = m.end() # If token is processed by a function, call it tok.lexer = self # Set additional attributes useful in token rules self.lexmatch = m self.lexpos = lexpos newtok = func(tok) # Every function must return a token, if nothing, we just move to next token if not newtok: lexpos = self.lexpos # This is here in case user has updated lexpos. lexignore = self.lexignore # This is here in case there was a state change break # Verify type of the token. If not in the token map, raise an error if not self.lexoptimize: if not newtok.type in self.lextokens: raise LexError("%s:%d: Rule '%s' returned an unknown token type '%s'" % ( func_code(func).co_filename, func_code(func).co_firstlineno, func.__name__, newtok.type),lexdata[lexpos:]) return newtok else: # No match, see if in literals if lexdata[lexpos] in self.lexliterals: tok = LexToken() tok.value = lexdata[lexpos] tok.lineno = self.lineno tok.type = tok.value tok.lexpos = lexpos self.lexpos = lexpos + 1 return tok # No match. Call t_error() if defined. if self.lexerrorf: tok = LexToken() tok.value = self.lexdata[lexpos:] tok.lineno = self.lineno tok.type = "error" tok.lexer = self tok.lexpos = lexpos self.lexpos = lexpos newtok = self.lexerrorf(tok) if lexpos == self.lexpos: # Error method didn't change text position at all. This is an error. raise LexError("Scanning error. Illegal character '%s'" % (lexdata[lexpos]), lexdata[lexpos:]) lexpos = self.lexpos if not newtok: continue return newtok self.lexpos = lexpos raise LexError("Illegal character '%s' at index %d" % (lexdata[lexpos],lexpos), lexdata[lexpos:]) self.lexpos = lexpos + 1 if self.lexdata is None: raise RuntimeError("No input string given with input()") return None # Iterator interface def __iter__(self): return self def next(self): t = self.token() if t is None: raise StopIteration return t __next__ = next # ----------------------------------------------------------------------------- # ==== Lex Builder === # # The functions and classes below are used to collect lexing information # and build a Lexer object from it. # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # get_caller_module_dict() # # This function returns a dictionary containing all of the symbols defined within # a caller further down the call stack. This is used to get the environment # associated with the yacc() call if none was provided. # ----------------------------------------------------------------------------- def get_caller_module_dict(levels): try: raise RuntimeError except RuntimeError: e,b,t = sys.exc_info() f = t.tb_frame while levels > 0: f = f.f_back levels -= 1 ldict = f.f_globals.copy() if f.f_globals != f.f_locals: ldict.update(f.f_locals) return ldict # ----------------------------------------------------------------------------- # _funcs_to_names() # # Given a list of regular expression functions, this converts it to a list # suitable for output to a table file # ----------------------------------------------------------------------------- def _funcs_to_names(funclist,namelist): result = [] for f,name in zip(funclist,namelist): if f and f[0]: result.append((name, f[1])) else: result.append(f) return result # ----------------------------------------------------------------------------- # _names_to_funcs() # # Given a list of regular expression function names, this converts it back to # functions. # ----------------------------------------------------------------------------- def _names_to_funcs(namelist,fdict): result = [] for n in namelist: if n and n[0]: result.append((fdict[n[0]],n[1])) else: result.append(n) return result # ----------------------------------------------------------------------------- # _form_master_re() # # This function takes a list of all of the regex components and attempts to # form the master regular expression. Given limitations in the Python re # module, it may be necessary to break the master regex into separate expressions. # ----------------------------------------------------------------------------- def _form_master_re(relist,reflags,ldict,toknames): if not relist: return [] regex = "|".join(relist) try: lexre = re.compile(regex,re.VERBOSE | reflags) # Build the index to function map for the matching engine lexindexfunc = [ None ] * (max(lexre.groupindex.values())+1) lexindexnames = lexindexfunc[:] for f,i in lexre.groupindex.items(): handle = ldict.get(f,None) if type(handle) in (types.FunctionType, types.MethodType): lexindexfunc[i] = (handle,toknames[f]) lexindexnames[i] = f elif handle is not None: lexindexnames[i] = f if f.find("ignore_") > 0: lexindexfunc[i] = (None,None) else: lexindexfunc[i] = (None, toknames[f]) return [(lexre,lexindexfunc)],[regex],[lexindexnames] except Exception: m = int(len(relist)/2) if m == 0: m = 1 llist, lre, lnames = _form_master_re(relist[:m],reflags,ldict,toknames) rlist, rre, rnames = _form_master_re(relist[m:],reflags,ldict,toknames) return llist+rlist, lre+rre, lnames+rnames # ----------------------------------------------------------------------------- # def _statetoken(s,names) # # Given a declaration name s of the form "t_" and a dictionary whose keys are # state names, this function returns a tuple (states,tokenname) where states # is a tuple of state names and tokenname is the name of the token. For example, # calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM') # ----------------------------------------------------------------------------- def _statetoken(s,names): nonstate = 1 parts = s.split("_") for i in range(1,len(parts)): if not parts[i] in names and parts[i] != 'ANY': break if i > 1: states = tuple(parts[1:i]) else: states = ('INITIAL',) if 'ANY' in states: states = tuple(names) tokenname = "_".join(parts[i:]) return (states,tokenname) # ----------------------------------------------------------------------------- # LexerReflect() # # This class represents information needed to build a lexer as extracted from a # user's input file. # ----------------------------------------------------------------------------- class LexerReflect(object): def __init__(self,ldict,log=None,reflags=0): self.ldict = ldict self.error_func = None self.tokens = [] self.reflags = reflags self.stateinfo = { 'INITIAL' : 'inclusive'} self.files = {} self.error = 0 if log is None: self.log = PlyLogger(sys.stderr) else: self.log = log # Get all of the basic information def get_all(self): self.get_tokens() self.get_literals() self.get_states() self.get_rules() # Validate all of the information def validate_all(self): self.validate_tokens() self.validate_literals() self.validate_rules() return self.error # Get the tokens map def get_tokens(self): tokens = self.ldict.get("tokens",None) if not tokens: self.log.error("No token list is defined") self.error = 1 return if not isinstance(tokens,(list, tuple)): self.log.error("tokens must be a list or tuple") self.error = 1 return if not tokens: self.log.error("tokens is empty") self.error = 1 return self.tokens = tokens # Validate the tokens def validate_tokens(self): terminals = {} for n in self.tokens: if not _is_identifier.match(n): self.log.error("Bad token name '%s'",n) self.error = 1 if n in terminals: self.log.warning("Token '%s' multiply defined", n) terminals[n] = 1 # Get the literals specifier def get_literals(self): self.literals = self.ldict.get("literals","") # Validate literals def validate_literals(self): try: for c in self.literals: if not isinstance(c,StringTypes) or len(c) > 1: self.log.error("Invalid literal %s. Must be a single character", repr(c)) self.error = 1 continue except TypeError: self.log.error("Invalid literals specification. literals must be a sequence of characters") self.error = 1 def get_states(self): self.states = self.ldict.get("states",None) # Build statemap if self.states: if not isinstance(self.states,(tuple,list)): self.log.error("states must be defined as a tuple or list") self.error = 1 else: for s in self.states: if not isinstance(s,tuple) or len(s) != 2: self.log.error("Invalid state specifier %s. Must be a tuple (statename,'exclusive|inclusive')",repr(s)) self.error = 1 continue name, statetype = s if not isinstance(name,StringTypes): self.log.error("State name %s must be a string", repr(name)) self.error = 1 continue if not (statetype == 'inclusive' or statetype == 'exclusive'): self.log.error("State type for state %s must be 'inclusive' or 'exclusive'",name) self.error = 1 continue if name in self.stateinfo: self.log.error("State '%s' already defined",name) self.error = 1 continue self.stateinfo[name] = statetype # Get all of the symbols with a t_ prefix and sort them into various # categories (functions, strings, error functions, and ignore characters) def get_rules(self): tsymbols = [f for f in self.ldict if f[:2] == 't_' ] # Now build up a list of functions and a list of strings self.toknames = { } # Mapping of symbols to token names self.funcsym = { } # Symbols defined as functions self.strsym = { } # Symbols defined as strings self.ignore = { } # Ignore strings by state self.errorf = { } # Error functions by state for s in self.stateinfo: self.funcsym[s] = [] self.strsym[s] = [] if len(tsymbols) == 0: self.log.error("No rules of the form t_rulename are defined") self.error = 1 return for f in tsymbols: t = self.ldict[f] states, tokname = _statetoken(f,self.stateinfo) self.toknames[f] = tokname if hasattr(t,"__call__"): if tokname == 'error': for s in states: self.errorf[s] = t elif tokname == 'ignore': line = func_code(t).co_firstlineno file = func_code(t).co_filename self.log.error("%s:%d: Rule '%s' must be defined as a string",file,line,t.__name__) self.error = 1 else: for s in states: self.funcsym[s].append((f,t)) elif isinstance(t, StringTypes): if tokname == 'ignore': for s in states: self.ignore[s] = t if "\\" in t: self.log.warning("%s contains a literal backslash '\\'",f) elif tokname == 'error': self.log.error("Rule '%s' must be defined as a function", f) self.error = 1 else: for s in states: self.strsym[s].append((f,t)) else: self.log.error("%s not defined as a function or string", f) self.error = 1 # Sort the functions by line number for f in self.funcsym.values(): if sys.version_info[0] < 3: f.sort(lambda x,y: cmp(func_code(x[1]).co_firstlineno,func_code(y[1]).co_firstlineno)) else: # Python 3.0 f.sort(key=lambda x: func_code(x[1]).co_firstlineno) # Sort the strings by regular expression length for s in self.strsym.values(): if sys.version_info[0] < 3: s.sort(lambda x,y: (len(x[1]) < len(y[1])) - (len(x[1]) > len(y[1]))) else: # Python 3.0 s.sort(key=lambda x: len(x[1]),reverse=True) # Validate all of the t_rules collected def validate_rules(self): for state in self.stateinfo: # Validate all rules defined by functions for fname, f in self.funcsym[state]: line = func_code(f).co_firstlineno file = func_code(f).co_filename self.files[file] = 1 tokname = self.toknames[fname] if isinstance(f, types.MethodType): reqargs = 2 else: reqargs = 1 nargs = func_code(f).co_argcount if nargs > reqargs: self.log.error("%s:%d: Rule '%s' has too many arguments",file,line,f.__name__) self.error = 1 continue if nargs < reqargs: self.log.error("%s:%d: Rule '%s' requires an argument", file,line,f.__name__) self.error = 1 continue if not f.__doc__: self.log.error("%s:%d: No regular expression defined for rule '%s'",file,line,f.__name__) self.error = 1 continue try: c = re.compile("(?P<%s>%s)" % (fname,f.__doc__), re.VERBOSE | self.reflags) if c.match(""): self.log.error("%s:%d: Regular expression for rule '%s' matches empty string", file,line,f.__name__) self.error = 1 except re.error: _etype, e, _etrace = sys.exc_info() self.log.error("%s:%d: Invalid regular expression for rule '%s'. %s", file,line,f.__name__,e) if '#' in f.__doc__: self.log.error("%s:%d. Make sure '#' in rule '%s' is escaped with '\\#'",file,line, f.__name__) self.error = 1 # Validate all rules defined by strings for name,r in self.strsym[state]: tokname = self.toknames[name] if tokname == 'error': self.log.error("Rule '%s' must be defined as a function", name) self.error = 1 continue if not tokname in self.tokens and tokname.find("ignore_") < 0: self.log.error("Rule '%s' defined for an unspecified token %s",name,tokname) self.error = 1 continue try: c = re.compile("(?P<%s>%s)" % (name,r),re.VERBOSE | self.reflags) if (c.match("")): self.log.error("Regular expression for rule '%s' matches empty string",name) self.error = 1 except re.error: _etype, e, _etrace = sys.exc_info() self.log.error("Invalid regular expression for rule '%s'. %s",name,e) if '#' in r: self.log.error("Make sure '#' in rule '%s' is escaped with '\\#'",name) self.error = 1 if not self.funcsym[state] and not self.strsym[state]: self.log.error("No rules defined for state '%s'",state) self.error = 1 # Validate the error function efunc = self.errorf.get(state,None) if efunc: f = efunc line = func_code(f).co_firstlineno file = func_code(f).co_filename self.files[file] = 1 if isinstance(f, types.MethodType): reqargs = 2 else: reqargs = 1 nargs = func_code(f).co_argcount if nargs > reqargs: self.log.error("%s:%d: Rule '%s' has too many arguments",file,line,f.__name__) self.error = 1 if nargs < reqargs: self.log.error("%s:%d: Rule '%s' requires an argument", file,line,f.__name__) self.error = 1 for f in self.files: self.validate_file(f) # ----------------------------------------------------------------------------- # validate_file() # # This checks to see if there are duplicated t_rulename() functions or strings # in the parser input file. This is done using a simple regular expression # match on each line in the given file. # ----------------------------------------------------------------------------- def validate_file(self,filename): import os.path base,ext = os.path.splitext(filename) if ext != '.py': return # No idea what the file is. Return OK try: f = open(filename, encoding = 'utf-8') lines = f.readlines() f.close() except IOError: return # Couldn't find the file. Don't worry about it fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(') sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=') counthash = { } linen = 1 for l in lines: m = fre.match(l) if not m: m = sre.match(l) if m: name = m.group(1) prev = counthash.get(name) if not prev: counthash[name] = linen else: self.log.error("%s:%d: Rule %s redefined. Previously defined on line %d",filename,linen,name,prev) self.error = 1 linen += 1 # ----------------------------------------------------------------------------- # lex(module) # # Build all of the regular expression rules from definitions in the supplied module # ----------------------------------------------------------------------------- def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,nowarn=0,outputdir="", debuglog=None, errorlog=None): global lexer ldict = None stateinfo = { 'INITIAL' : 'inclusive'} lexobj = Lexer() lexobj.lexoptimize = optimize global token,input if errorlog is None: errorlog = PlyLogger(sys.stderr) if debug: if debuglog is None: debuglog = PlyLogger(sys.stderr) # Get the module dictionary used for the lexer if object: module = object if module: _items = [(k,getattr(module,k)) for k in dir(module)] ldict = dict(_items) else: ldict = get_caller_module_dict(2) # Collect parser information from the dictionary linfo = LexerReflect(ldict,log=errorlog,reflags=reflags) linfo.get_all() if not optimize: if linfo.validate_all(): raise SyntaxError("Can't build lexer") if optimize and lextab: try: lexobj.readtab(lextab,ldict) token = lexobj.token input = lexobj.input lexer = lexobj return lexobj except ImportError: pass # Dump some basic debugging information if debug: debuglog.info("lex: tokens = %r", linfo.tokens) debuglog.info("lex: literals = %r", linfo.literals) debuglog.info("lex: states = %r", linfo.stateinfo) # Build a dictionary of valid token names lexobj.lextokens = { } for n in linfo.tokens: lexobj.lextokens[n] = 1 # Get literals specification if isinstance(linfo.literals,(list,tuple)): lexobj.lexliterals = type(linfo.literals[0])().join(linfo.literals) else: lexobj.lexliterals = linfo.literals # Get the stateinfo dictionary stateinfo = linfo.stateinfo regexs = { } # Build the master regular expressions for state in stateinfo: regex_list = [] # Add rules defined by functions first for fname, f in linfo.funcsym[state]: line = func_code(f).co_firstlineno file = func_code(f).co_filename regex_list.append("(?P<%s>%s)" % (fname,f.__doc__)) if debug: debuglog.info("lex: Adding rule %s -> '%s' (state '%s')",fname,f.__doc__, state) # Now add all of the simple rules for name,r in linfo.strsym[state]: regex_list.append("(?P<%s>%s)" % (name,r)) if debug: debuglog.info("lex: Adding rule %s -> '%s' (state '%s')",name,r, state) regexs[state] = regex_list # Build the master regular expressions if debug: debuglog.info("lex: ==== MASTER REGEXS FOLLOW ====") for state in regexs: lexre, re_text, re_names = _form_master_re(regexs[state],reflags,ldict,linfo.toknames) lexobj.lexstatere[state] = lexre lexobj.lexstateretext[state] = re_text lexobj.lexstaterenames[state] = re_names if debug: for i in range(len(re_text)): debuglog.info("lex: state '%s' : regex[%d] = '%s'",state, i, re_text[i]) # For inclusive states, we need to add the regular expressions from the INITIAL state for state,stype in stateinfo.items(): if state != "INITIAL" and stype == 'inclusive': lexobj.lexstatere[state].extend(lexobj.lexstatere['INITIAL']) lexobj.lexstateretext[state].extend(lexobj.lexstateretext['INITIAL']) lexobj.lexstaterenames[state].extend(lexobj.lexstaterenames['INITIAL']) lexobj.lexstateinfo = stateinfo lexobj.lexre = lexobj.lexstatere["INITIAL"] lexobj.lexretext = lexobj.lexstateretext["INITIAL"] lexobj.lexreflags = reflags # Set up ignore variables lexobj.lexstateignore = linfo.ignore lexobj.lexignore = lexobj.lexstateignore.get("INITIAL","") # Set up error functions lexobj.lexstateerrorf = linfo.errorf lexobj.lexerrorf = linfo.errorf.get("INITIAL",None) if not lexobj.lexerrorf: errorlog.warning("No t_error rule is defined") # Check state information for ignore and error rules for s,stype in stateinfo.items(): if stype == 'exclusive': if not s in linfo.errorf: errorlog.warning("No error rule is defined for exclusive state '%s'", s) if not s in linfo.ignore and lexobj.lexignore: errorlog.warning("No ignore rule is defined for exclusive state '%s'", s) elif stype == 'inclusive': if not s in linfo.errorf: linfo.errorf[s] = linfo.errorf.get("INITIAL",None) if not s in linfo.ignore: linfo.ignore[s] = linfo.ignore.get("INITIAL","") # Create global versions of the token() and input() functions token = lexobj.token input = lexobj.input lexer = lexobj # If in optimize mode, we write the lextab if lextab and optimize: lexobj.writetab(lextab,outputdir) return lexobj # ----------------------------------------------------------------------------- # runmain() # # This runs the lexer as a main program # ----------------------------------------------------------------------------- def runmain(lexer=None,data=None): if not data: try: filename = sys.argv[1] f = open(filename) data = f.read() f.close() except IndexError: sys.stdout.write("Reading from standard input (type EOF to end):\n") data = sys.stdin.read() if lexer: _input = lexer.input else: _input = input _input(data) if lexer: _token = lexer.token else: _token = token while 1: tok = _token() if not tok: break sys.stdout.write("(%s,%r,%d,%d)\n" % (tok.type, tok.value, tok.lineno,tok.lexpos)) # ----------------------------------------------------------------------------- # @TOKEN(regex) # # This decorator function can be used to set the regex expression on a function # when its docstring might need to be set in an alternative way # ----------------------------------------------------------------------------- def TOKEN(r): def set_doc(f): if hasattr(r,"__call__"): f.__doc__ = r.__doc__ else: f.__doc__ = r return f return set_doc # Alternative spelling of the TOKEN decorator Token = TOKEN
Python
__author__="zoltan kochan" __date__ ="$5 лют 2011 3:41:26$" from setuptools import setup,find_packages setup ( name = 'fosay', version = '0.1', packages = find_packages(), # Declare your packages' dependencies here, for eg: install_requires=['foo>=3'], # Fill in these to make your Egg ready for upload to # PyPI author = 'zoltan kochan', author_email = '', summary = 'Just another Python package for the cheese shop', url = '', license = '', long_description= 'Long description of the package', # could also include long_description, download_url, classifiers, etc. )
Python
__author__="zoltan kochan" __date__ ="$11 лют 2011 23:26:37$"
Python
__author__="zoltan kochan" __date__ ="$28 june 2010 1:02:10$" __name__ == "process" from ctypes import ArgumentError from core.constants import INDEFINITE from core.models.ling_units import * from copy import deepcopy import core.constants as const from core.constants import concept, difinity, form from core.constants import STATE_START, STATE_END, STATE_CONJ_A1, STATE_CONJ_A4 from core.constants import NONE_VALUE from core.constants import is_nonterminalc, is_terminalc, eqx, is_prop from core.constants import quantity from core.lang.scoring import * PRINT_TO_CONSOLE = False def gen_conj(lang, label, parent, f, fend, objs, conj): #print(len(objs)) for word in unparse(lang, label, STATE_START, objs.pop(0)): #print('*') #print(word.descr()) if len(objs) == 0: ts = lang.conj_str3(conj[0], conj[1], conj[2]) if ts == []: ts = lang.conj_str(conj[0], conj[1]) for c in ts: par = deepcopy(parent) par.relation = c tus = fend(lang, par, word) if fend else [par] for tt in tus: yield tt else: par = deepcopy(parent) tus = f(lang, par, word) if f else [par] for tt in tus: for res in gen_conj(lang, label, tt, f, fend, deepcopy(objs), conj): yield res #best_res = None ###TODO: required = { const.type["article"]: [concept["difinity"]], const.type["quantifier"]: [concept["quantity"]], }#thh ##maybe use subtype instead of determinerType!!!!!!!!!!!!!!? Or not!! # def req(clabl, caseframe): if not clabl in required.keys(): return True return all(x in caseframe.keys() and not caseframe[x] is None for x in required[clabl]) def find_maxposs(caseframe): res = 0 for c in caseframe.keys(): if not is_prop(c): if type(caseframe[c]) == type([]): res += len(caseframe[c]) else: res += 1 return res #synthesize def unparse(lang, label, state, caseframe, parent = None): "Uses generator to yield all possible sentences" if lang.to_type_code(label) == const.type["epsilon"]: ############ yield None ########################## if caseframe == None: return if is_terminal(label): w = Token() w.set_ghost(is_empty(label)) w.type = lang.to_type_code(label) for c in transferred_attributes[lang.to_type_code(label)]: if c == concept["real-number"] and not c in caseframe: continue w.attr(c, caseframe[c]) yield w elif state == STATE_END: if all(is_prop(key) for key in caseframe.keys()): yield parent else: net = lang.atn[label] if not parent: parent = FlowerLingUnit(lang.to_type_code(label), 0, 0) for key in caseframe.keys(): if is_prop(key): parent.attr(key, caseframe.get(key, None)) if lang.to_type_code(label) in caseframe and \ type(caseframe[lang.to_type_code(label)]) == list and \ concept["conj-function"] in caseframe and \ not caseframe[concept["conj-function"]] is None: if not STATE_CONJ_A1 in net: return ###it is needed when we go on a way of an empty alternative. Like NP:EMPTY objs = caseframe[lang.to_type_code(label)] conj = caseframe[concept["conj-function"]], caseframe[concept["conj-type"]], caseframe[concept["conj-str"]] for x in gen_conj(lang, label, deepcopy(parent), net[STATE_CONJ_A1][0][1], net[STATE_CONJ_A4][1][1], deepcopy(objs), conj): yield x else: p = net[state] q = {} mp = find_maxposs(caseframe) for labl, f, standard, nextState, maxel, minel in p: if maxel != INDEFINITE and not maxel >= mp >= minel: continue if standard in q.keys(): q[standard] += [(labl, f, nextState)] else: q[standard] = [(labl, f, nextState)] q = [value for key, value in sorted(q.items(), key = lambda x: -1*x[0])] i = 0 good_speed = False while not good_speed and i < len(q): for labl, f, nextState in q[i]: if nextState == STATE_CONJ_A1: continue cl = lang.to_type_code(labl) if cl in modificators and req(cl, caseframe): tmp = deepcopy(caseframe) words = [(Token(cl), tmp)] elif type(caseframe.get(cl)) == type([]): words = [] for i in range(len(caseframe.get(cl))): tmp = deepcopy(caseframe) if len(tmp[cl]) == 1: cf = tmp[cl][0] del tmp[cl] else: cf = tmp[cl].pop(i) words += [(word, deepcopy(tmp)) for word in unparse(lang, labl, STATE_START, cf, None)] else: tmp = deepcopy(caseframe) if cl in tmp: del tmp[cl] words = [(word, deepcopy(tmp)) for word in unparse(lang, labl, STATE_START, caseframe.get(cl), None)] for word, cf in words: par = deepcopy(parent) for x in f(lang, par, word) if f else [par]: for rest in unparse(lang, label, nextState, deepcopy(cf), x): good_speed = True yield rest i += 1 def is_terminal(symbol): return not symbol[0].islower() #return symbol <= LAST_TERMINAL def is_empty(n): return n[-6:].upper() == ":EMPTY" def empty_type(n): return n[:-6] def next_step(lang, label, state, mem, wc, parent, deep, u1, f): tus = f(lang, parent, u1) if f else [parent] for tt in tus: for mem, i2, u2 in parse(lang, label, state, mem, wc, tt, deepcopy(deep)): #deepcopy(deep) => deep yield mem, i2, u2 #match, analyze def parse(lang, label, state, mem, wc = 0, parent = None, deep = None): if not deep: deep = {} #print(" "*4*deep.get(label, 0), label) if state == STATE_END: yield mem, wc, parent elif wc == len(mem): return elif is_terminal(label): if is_empty(label): w = Token(lang.to_type_code(empty_type(label))) w.set_ghost(True) #w.meaning = "_" yield mem, wc, w elif lang.to_type_code(label) == const.type["epsilon"]: yield mem, wc, None elif label in mem[wc]: for w, l in mem[wc][label]: yield mem, l, w else: net = lang.atn[label] n = net[state] if not parent: parent = FlowerLingUnit(lang.to_type_code(label), 0, 0) m = [(deep.get(item[0], 0), item) for item in n] mr = [x[1] for x in sorted(m, key = lambda d: d[0])] for labl, f, standard, next_state, maxel, minel in mr: dp = deepcopy(deep) if labl in mem[wc]: for u1, to_ in mem[wc][labl]: for mem, i2, u2 in next_step(lang, label, next_state, \ mem, to_, deepcopy(parent), deepcopy(deep), deepcopy(u1), f): yield mem, i2, u2 elif not labl in deep.keys() or deep[labl] < 3: #2 dp[labl] = 1 if not labl in dp.keys() else dp[labl] + 1 tm = [] #hogyha a maximalis mejseg elerese miat nem ad ki semmit akkor nem szabad beirni!! es amugy is at kel #csinalni hogy ezen ne fugjon! for mem, i1, u1 in parse(lang, labl, STATE_START, \ mem, wc, None, deepcopy(dp)): tm += [(deepcopy(u1), i1)] #maybe witout deepcopy... for mem, i2, u2 in next_step(lang, label, next_state, \ mem, i1, deepcopy(parent), deepcopy(deep), deepcopy(u1), f): yield mem, i2, u2 if dp[labl] == 1: mem[wc][labl] = tm def parse1(lang, label, state, mem, wc = 0): for x, y, z in parse(lang, label, STATE_START, mem, wc): mem = x if z: if not mem[wc].has_key(label): mem[wc][label] = [(z, y)] yield mem, y, z def get_mem(lang, label, state, mem, wc = 0): for mem, y, z in parse1(lang, label, STATE_START, mem, wc): pass return mem #TODO: Add required and default min_str = { const.type["noun-phrase"]: [const.type["noun"]], const.type["epithet"]: [const.type["adjective"]], const.type["verb-phrase"]: [const.type["verb"]], const.type["clause"]: [const.type["subject"], const.type["verb-phrase"]] } transferred_attributes = { const.type["noun"]: [ concept["lemma"], concept["order-number"], concept["noun-type"], concept["real-number"], concept["form"], concept["tags"], concept["personal-name"], ], const.type["pronoun"]: [ concept["lemma"], concept["order-number"], concept["noun-type"], concept["real-number"], concept["form"], concept["pronoun-type"], concept["gender"] ], const.type["adjective"]: [ concept["lemma"], concept["order-number"], ], const.type["verb"]: [ concept["lemma"], concept["order-number"], ], const.type["adverb"]: [ concept["lemma"], concept["order-number"], ], const.type["sentence"]: [], const.type["clause"]: [], const.type["epithet"]: [], const.type["verb-phrase"]: [ concept["tense"], concept["mood"], concept["aspect"], concept["truth"] ], const.type["noun-phrase"]: [ concept["persone"], concept["difinity"], concept["quantity"], concept["quantity-number"] ], const.type["time"]: [ concept["tense"], ], const.type["subject"]: [], const.type["object"]: [concept["case"]], const.type["preposition-phrase"]: [], } default = { concept["form"]: form["formal"], ########## concept["truth"]: 1.0 } exclusions = [ concept["difinity"], concept["quantity"], concept["quantity-number"] ] def update_dict(a, b): if len(b.keys()) > 1: print(str(b)) raise ArgumentError() key = [item for item in b.keys()][0] if not key in a: a.update(b) else: c = [b[key]] if type(b[key]) != list else b[key] if type(a[key]) == list: a[key] += c else: a[key] = [a[key]] + c def lang_to_case_frame(unit): '''Translates the source language AST to Interlingua''' cf = {} if is_terminalc(unit.type): for c in transferred_attributes[unit.type]: cf[c] = unit.attr(c) if cf[c] == None and c in default.keys(): cf[c] = default[c] elif len(unit.blocks) > 1 and not unit.relation is None: t = unit.blocks[0].type cf[concept["conj-str"]] = unit.relation.conj_str cf[concept["conj-type"]] = unit.relation.conj_type cf[concept["conj-function"]] = unit.relation.function_number cf[t] = [lang_to_case_frame(y)[y.type] for y in unit.blocks] else: for e in unit.left + unit.right: if not e.type in modificators: ##and (e.type != TERMINAL_DETERMINER or not e.attr(concept["difinity"])): #OR JUST TERMINAL_ARTICLE update_dict(cf, lang_to_case_frame(e)) for c in transferred_attributes[unit.type]: if unit.attr(c) == None: if c in default: cf[c] = default[c] elif not c in exclusions: print(unit.type, c) raise NotImplementedError #continue else: cf[c] = unit.attr(c) if len(unit.blocks) == 1: if not cf.get(concept["quantity"], None) in [None, NONE_VALUE]: transferred_attributes[const.type["noun"]].remove(concept["real-number"]) cf.update(lang_to_case_frame(unit.blocks[0])) if not cf.get(concept["quantity"], None) in [None, NONE_VALUE]: transferred_attributes[const.type["noun"]].append(concept["real-number"]) else: for b in unit.blocks: if b.type in cf: cf[b.type] += [lang_to_case_frame(b)[b.type]] else: cf[b.type] = [lang_to_case_frame(b)[b.type]] # #mosaic translation # if not curr_type in cf.keys(): # for i in min_str.get(curr_type, []): # if not i in cf.keys(): # print(str(i), str(curr_type), cf) # raise NotImplementedError() return {unit.type: cf} def nouns(cfe, ord = None): p = [] #print(cf) ll = [cfe] if type(cfe) != type([]) else cfe for cf in ll: for key in cf.keys(): if key == const.type["noun-phrase"]: if concept['conj-str'] in cf[key].keys(): for x in cf[key][key]: if const.type["noun"] in x.keys(): p += [(x[const.type["noun"]].get(concept["order-number"], None) if ord == None else ord, x)] elif const.type["pronoun"] in x.keys(): p += [(x[const.type["pronoun"]].get(concept["order-number"], None) if ord == None else ord, x)] elif const.type["noun-phrase"] in x.keys(): p += nouns(x, cf[key].get(concept["order-number"], None)) else: if const.type["noun"] in cf[key].keys(): if type(cf[key][const.type["noun"]]) == type([]): for item in cf[key][const.type["noun"]]: p += [(item.get(concept["order-number"], None) if ord == None else ord, {key: item})] else: p += [(cf[key][const.type["noun"]].get(concept["order-number"], None) if ord == None else ord, cf[key])] elif const.type["pronoun"] in cf[key].keys(): p += [(cf[key][const.type["pronoun"]].get(concept["order-number"], None) if ord == None else ord, cf[key])] elif const.type["noun-phrase"] in cf[key].keys(): p += nouns(cf[key], cf.get(concept["order-number"], None)) elif is_nonterminalc(key): p += nouns(cf[key], cf.get(concept["order-number"], None)) return p #def nouns(cf, ord = None): # p = [] # for key in cf.keys(): # if not is_nonterminalc(key): # continue # if const.type["noun"] in cf[key].keys(): # p += [(cf[key][const.type["noun"]].get(concept["order_number"], None) if ord == None else ord, cf[key])] # elif const.type["pronoun"] in cf[key].keys(): # p += [(cf[key][const.type["pronoun"]].get(concept["order_number"], None) if ord == None else ord, cf[key])] # p += nouns(cf[key], cf.get(concept["order_number"], None)) # return p #there can't be pronouns in the case frame. (And general words should be changed with proper ones if it's possible) def referencing(cf): #words #print(cf) p = [x[1] for x in sorted(nouns(cf), key = lambda d: (d[0]))] #print(p) i = 0 while i < len(p): if const.type["noun"] in p[i].keys(): j = i + 1 if p[i].get(concept["quantity"], None) == quantity["none"] and p[i].get(concept["difinity"], None) == None: if p[i][const.type["noun"]][concept["noun-type"]] == noun_type["proper"] or const.type["epithet"] in p[i].keys(): p[i][concept["difinity"]] = difinity["difinite"] else: p[i][concept["difinity"]] = difinity["undifinite"] while j < len(p): if const.type["noun"] in p[j].keys() and \ p[j][const.type["noun"]][concept["lemma"]] == p[i][const.type["noun"]][concept["lemma"]] and \ p[i].get(concept["quantity"], None) == quantity["none"] and \ p[j].get(concept["difinity"], None) == None: p[j][concept["difinity"]] = difinity["difinite"] del p[j] else: j += 1 i += 1 #print("------------>", p) return cf #choosing the ones that match better the tags def eq_score(a, b): id = 0 t1 = [] if a is None else a t2 = [] if b is None else b for i in t1: for j in t2: if i == j: id += 1 if id == 0: return -(len(t1)+len(t2)) return id def props_score(token, st): s = 0 for key in st._attrs.keys(): if key == concept["tags"] or token.attr(key) == st.attr(key): s += 1 return s #choosing the ones that match better def score_tags(tokens, st): nncf = [] if len(tokens) == 0: return [] for c in tokens: nncf += [(eq_score(c.attr(concept["tags"]), st.attr(concept["tags"])), props_score(c, st), c)] nncf = sorted(nncf, key = lambda d: (d[0], d[1]), reverse = True) k = nncf[0][0], nncf[0][1] #print(k) i = 0 px = [] while i < len(nncf) and (nncf[i][0], nncf[i][1]) == k: px += [nncf[i][2]] i += 1 return px def is_empty_word(w): return w.get_ghost() def pre_morphen(lang, st, ind = 0): '''Init's the main morpho-groups before doing morphological generation''' st.parent = None if is_terminalc(st.type): if not st.fixed or is_empty_word(st): yield st return variants = [x for x in lang.words if all(y == concept["tags"] or eqx(y, x, st) for y in concept)] #musteq variants = score_tags(variants, st) new_variants = [] if PRINT_TO_CONSOLE and len(variants) > 1: print("CAUTION: Ambiguity in 'pre_morphen' at %s" % st.descr()) for variant in variants: for new_variant in new_variants: for f in st.fixed: if variant.attr(f) != new_variant.attr(f): break else: break else: for f in st.fixed: ################################################# if variant.attr(f) == NONE_VALUE: print("xxxxxxxxxxxpre_morphenpre_morphenpre_morphenpre_morphen") break############################################################################################################################# else: new_variants += [variant] variants = new_variants if variants == []: return for variant in variants: c = deepcopy(st) for f in c.fixed: c.attr(f, variant.attr(f)) yield c return res = [] for x in pre_morphen(lang, (st.left + st.blocks + st.right)[ind]): c = deepcopy(st) if ind < len(c.left): c.left[ind] = x elif ind < len(c.left + c.blocks): c.blocks[ind - len(c.left)] = x else: c.right[ind - len(c.left + c.blocks)] = x x.parent = c if not x.refresh(): continue res += [c] res = the_bests(lang, eupony_score, res) for c in res: if ind + 1 == len(c.left + c.blocks + c.right): yield c else: for y in pre_morphen(lang, c, ind + 1): yield y def morphen(lang, st, ind = 0): '''Morphological generation''' st.parent = None if is_terminalc(st.type): if is_empty_word(st): yield st return variants = [x for x in lang.words if all(y == concept["tags"] or eqx(y, x, st) for y in concept)] #musteq variants = score_tags(variants, st) if variants == [] or variants is None: raise Exception("Not found in the '%s' dictionary %s" % (lang.name, st.descr())) if PRINT_TO_CONSOLE and len(variants) > 1: tmp = str([x.descr() for x in variants]) print("CAUTION: Ambiguity in 'morphen' at %s alternatives %d (%s)" % (st.descr(), len(variants), tmp)) for variant in variants: c = deepcopy(st) if c.type is None: raise Exception('%s hasn\'t type' % str(st)) c.text = variant.text c.transcription = variant.transcription for p in concept: c.attr(p, variant.attr(p)) yield c return res = [] for x in morphen(lang, (st.left+st.blocks+st.right)[ind]): c = deepcopy(st) if ind < len(c.left): c.left[ind] = x elif ind < len(c.left + c.blocks): c.blocks[ind - len(c.left)] = x else: c.right[ind - len(c.left + c.blocks)] = x x.parent = c if not x.refresh(): continue res += [c] res = the_bests(lang, eupony_score, res) for c in res: if ind + 1 == len(c.left+c.blocks+c.right): yield c else: for y in morphen(lang, c, ind + 1): yield y def case_frame_to_lang(caseframe, target_lang, first=const.type['sentence']): '''Translates Interlingua to the target language AST''' for first_label in target_lang.type_labels(first): for x in unparse(target_lang, first_label, STATE_START, caseframe[first]): for y in pre_morphen(target_lang, x): for z in morphen(target_lang, y): yield z
Python
__author__="zoltan kochan" __date__ ="$28 june 2010 1:02:10$" from core.lang.process import referencing from core.lang.process import case_frame_to_lang, lang_to_case_frame from core.kb import meaning_shift from core.lang.scoring import eupony_score from core.lang.scoring import pithiness_score from core.lang.scoring import direct_pithiness_score #from core.lang.scoring import order_score from copy import deepcopy from core.constants import concept PRINT_TO_CONSOLE = False prm_only_the_best = False #UC = 35 def interlingua_to_str(dc, c = 0): d = 5 b = d*c*" " b1 = b + d*" " res = b + "{" + "\n" for key in dc.keys(): if dc[key] == None: continue if type(dc[key]) == list: if key == concept["tags"]: res += b1 + str(key) + ": " + ', '.join(dc[key]) + "\n" else: for item in dc[key]: res += b1 + str(key) + ":" + "\n" res += interlingua_to_str(item, c + 1) elif not isinstance(dc[key], int) and not isinstance(dc[key], float) and not isinstance(dc[key], str): #isinstance(dc, dict):!!!!!!!!!! res += b1 + str(key) + ":" + "\n" res += interlingua_to_str(dc[key], c + 1) else: res += b1 + str(key) + ": " + str(dc[key]) + "\n" return res + b + "}" + "\n" def print_interlingua(dc): print(interlingua_to_str(dc)) from datetime import datetime def text_to_interlingua(text, first, source_lang): """ Translates the given text written on the source language into interlingua. """ v = source_lang.init_sentence(text, first) for e in v: e.numerate(0) if PRINT_TO_CONSOLE: print() print("ways to understand", len(v)) # print(v) # #tree = v[0] #begin_time = datetime.now() cfs = [] for x in v: cfs += [lang_to_case_frame(x)] return cfs def translate(text, first, source_lang, tlangs): d = datetime.now() #source_lang = slang target_langs = [x for x in tlangs] #source_lang = cfs = text_to_interlingua(text, first, source_lang) ###############cfs = [x for x in cfs if is_proper_case_frame(x)] cfs = [referencing(x) for x in cfs] if PRINT_TO_CONSOLE: print() for c in cfs: print_interlingua(c) print(190*"=") #print(c) print() #region TESTING FOR IDENTICAL CASE FRAMES id = 0 for i in range(len(cfs) - 1): for j in range(i + 1, len(cfs)): #print(i, j) if str(cfs[i]) == str(cfs[j]): id += 1 if PRINT_TO_CONSOLE: if id > 0: print("WARNING: there are", id, "identical caseframes\n") #endregion shift = 3 * " " #pr = "translating:\n" #print("translating:") #pr += shift + text + "\n" #print(shift + text) #pr += UC*"_" + "\n" #print(40*"=") #building_cf = datetime.now() - begin_time #begin_time = datetime.now() tr = [] #ln = 1 for target_lang in target_langs: if PRINT_TO_CONSOLE: print("translating to:", target_lang.name) #target_lang_syntax_trees = [case_frame_to_lang(x, target_lang) for x in cfs] target_lang_syntax_trees = [] ct = 0 loc_cfs = [meaning_shift(deepcopy(x), target_lang) for x in cfs] #print(loc_cfs) # # print() # for c in loc_cfs: # print(c) # print() for x in loc_cfs: temp = [y for y in case_frame_to_lang(x, target_lang, source_lang.label_types[first])] #case_frame_to_lang(x, target_lang) ct += len(temp) target_lang_syntax_trees += [temp] if PRINT_TO_CONSOLE: print("alternatives:", ct) ## ct = 0 ## for x in target_lang_syntax_trees: ## if type(x) == list: ## ct += len(x) ## else: ## ct += 1 ## #ct = sum(len(x) for x in target_lang_syntax_trees) ## print(target_lang_syntax_trees, ct) ##################################### # ncf = [] # for x in target_lang_syntax_trees: # nncf = [] # for c in x: # nncf += [(eupony_score(target_lang, c), pithiness_score(target_lang, c), order_score(target_lang, c), c)] # #nncf = sorted(nncf, key = itemgetter(1), reverse = True) # nncf = sorted(nncf, key = lambda d: (d[1], d[0]), reverse = True) # k = nncf[0][0], nncf[0][1] # i = 0 # px = [] # while i < len(nncf) and (nncf[i][0], nncf[i][1]) == k: # px += [nncf[i]] # i += 1 # nncf = px # ncf += [nncf] #NEM J?, MERT NEM N?ZI A CONJUNCTION-OKAT!!!!!!!!!!!!!!!!!! #among, after... like words with transcription! ncf = [] for x in target_lang_syntax_trees: nncf = [] if len(x) == 0: if PRINT_TO_CONSOLE: print("WARNING: EMPTY ALTERNATIVE") continue for c in x: nncf += [(eupony_score(target_lang, c), pithiness_score(target_lang, c), direct_pithiness_score(target_lang, c), c)] #, order_score(target_lang, c) #nncf = sorted(nncf, key = itemgetter(1), reverse = True) #nncf = sorted(nncf, key = lambda d: (d[1], d[0], d[2]), reverse = True) nncf = sorted(nncf, key = lambda d: (d[1], d[2], d[0]), reverse = True) k = nncf[0][0], nncf[0][1], nncf[0][2] i = 0 px = [] while i < len(nncf) and (not prm_only_the_best or (nncf[i][0], nncf[i][1], nncf[i][2]) == k): px += [nncf[i]] i += 1 nncf = px ncf += [nncf] ########################################################## #case_frame_to_lang(None, None) #cfs = [case_frame_to_lang(x, ukr) for x in cfs] # #if len(cfs) == 1: # #we can teach Ester # pass #else: # #delete the uncorrect LLMs # pass # #pr += "\n" # #print() #print cfs #english_to_case_frame(tree) #print cfs[0] #[str(x) for x in cfs] tl = set([]) #pr += "translating to " + target_lang.name + ":\n" #; ln += 1 #print("translating #" + str(ln) + ":"); ln += 1 for x in ncf: temp = 0 for r, p, dr, t in x: #pr += shift + str(r) + ", " + str(p) + ": " + str(t) + "\n" #print((shift + str(ccfs[i])).encode("utf-8")) tl.add(str(t)) #tl += [t] #pr += shift + str(t) + "\n" #print((shift + str(ccfs[i])).encode("utf-8")) temp += 1 if PRINT_TO_CONSOLE: if temp > 1: print("There can't be more then one alternative with the same meaning!") #raise Exception("There can't be two alternatives with the same meaning!") #pr += "\n" #tkMessageBox.showinfo("Say Hello", str(ccfs[i])) #print(shift + str(r) + ": " + str(t)) tr += [list(tl)] if PRINT_TO_CONSOLE: print("translating duration =", datetime.now() - d) print() return tr
Python
__author__="zoltan kochan" __date__ ="$1 груд 2010 1:13:17$" from core.constants import is_terminalc def get_tranarr(st): if st.type is None: raise Exception('%s has None type' % st.meaning) if is_terminalc(st.type): return st.transcription r = [] for c in st.left + st.cblocks + st.right: t = get_tranarr(c) if t != None: r += t return r def get_wordarr(st): if is_terminalc(st.type): return st.text r = [] for c in st.left + st.blocks + st.right: if is_terminalc(c.type) and c.meaning == None: continue if get_wordarr(c) != None: r += get_wordarr(c) return r ipa_vow = ["a", "e", "u", "i", "o", "ø", "ɒ", "ɛ", "ɪ", "ə", "æ"] def eupony_score(lang, st): "Оцінює милозвучність текста" r = 0 v = None for w in get_tranarr(st): if (v == None): v = w[-1] in ipa_vow elif (w in [",", "-", "."]): v = None else: v1 = w[0] in ipa_vow if (v1 != v): r += 1 v = w[-1] in ipa_vow return r def pithiness_score(lang, st): return -1*len(get_wordarr(st)) def direct_pithiness_score(lang, st): return -1*len(str(st)) def order_score(lang, st): return -1*st.renumerate()[1] #cлова з меншою кількістю лексичних значень або #з ближчими за значення лексичними значеннями отримують вищий бал def unambiguity_score(lang, st): pass def the_bests(lang, f, q): if q == []: return q ws = [] for w in q: ws += [(f(lang, w), w)] ws = sorted(ws, key = lambda d: (d[0]), reverse = True) k = ws[0][0] i = 0 px = [] while i < len(ws) and (ws[i][0]) == k: px += [ws[i][1]] i += 1 return px import random def the_best(lang, f, q): tmp = the_bests(lang, f, q) return tmp[random.randint(0, len(tmp)-1)]
Python
__author__="zoltan kochan" __date__ ="$5 бер 2011 11:36:22$" #TODO: optimize = 0
Python
#------------------------------------------------------------------------------- # ATN generator. Contains functions for generating ATN. #------------------------------------------------------------------------------- __author__="zoltan kochan" __date__ ="$26 лист 2010 1:49:08$" from core.constants import STATE_START from core.constants import STATE_END from core.constants import type as ltype from core.constants import modificators from core.constants import preqconst from core.constants import STATE_CONJS, STATE_CONJ_A1, STATE_CONJ_A2, STATE_CONJ_A3, STATE_CONJ_A4 from core.constants import INDEFINITE from core.constants import position from core.constants import conj_str from copy import deepcopy def betwcheck(lang, pr, ch): #if it returns True then the model isn't proper return not (pr.relation and (pr.relation.max_items and pr.relation.max_items < len(pr.blocks) or \ ch.relation == pr.relation or \ ch.relation and pr.relation.order < ch.relation.order)) def has_nothing_conj(conjs, pr): for c in conjs: if c.conj_str == conj_str['nothing']: pr.relation = c return True return False def aftercheck(lang, pr, ch): #if it returns True then the model isn't proper return not (not pr.relation and not has_nothing_conj(lang.conjunctions, pr) or pr.relation and \ (pr.relation.max_items and pr.relation.max_items < len(pr.blocks) or \ pr.relation == ch.relation or len(pr.blocks) > 0 and (pr.blocks[0].relation == pr.relation or \ pr.blocks[0].relation and pr.relation.order < pr.blocks[0].relation.order))) def return_parent(lang, parent, child): return [parent] def add_to_blocks(lang, parent, child): parent.blocks += [child] child.parent = parent if not child.refresh(): return [] return [parent] def add_to_blocks_wr(lang, parent, child): parent.blocks += [child] child.parent = parent return [parent] def add_to_lorr(lang, parent, child): if parent.blocks == []: parent.left += [child] else: parent.right += [child] child.parent = parent if not child.refresh(): return [] return [parent] def add_to_left(lang, parent, child): parent.left += [child] child.parent = parent if not child.refresh(): return [] return [parent] def add_to_right(lang, parent, child): parent.right += [child] child.parent = parent if not child.refresh(): return [] return [parent] def add_to_conj_struct_before(lang, parent, conj): if conj.position != Position.BEFORE or \ not parent.type in [x.type for x in conj.conjuction_structure.por]: return [] parent.relation = conj.conjuction_structure return [parent] def add_to_conj_struct_among(lang, parent, conj): if conj.position != position["among"] or \ not parent.type in conj.conjuction_structure.por: return [] if not parent.relation: if conj.conjuction_structure.before != None: return [] parent.relation = conj.conjuction_structure return [parent] elif parent.relation != conj.conjuction_structure: return [] return [parent] def add_to_conj_struct_after(lang, parent, conj): pass def fg_bch(af): return \ lambda lang, par, ch: \ add_to_blocks_wr(lang, par, ch) \ if ch.add_attach(af.get('attach', [])) and \ ch.add_fixed(af.get('fixed', [])) and \ betwcheck(lang, par, ch) \ else [] def fg_ach(af): return \ lambda lang, par, ch: \ add_to_blocks(lang, par, ch) \ if ch.add_attach(af.get('attach', [])) and \ ch.add_fixed(af.get('fixed', [])) and \ aftercheck(lang, par, ch) \ else [] def fgen(f = add_to_lorr, attach=[], fixed=[], up=[], down=[]): '''Generates a standard arc-function.''' return lambda lang, par, ch: \ f(lang, par, ch) \ if \ all(preqconst(x, ch, y) for x, y in down) and \ all(preqconst(x, par, y) for x, y in up) and \ (ch == None and attach == fixed == [] or \ ch.add_attach(attach) and \ ch.add_fixed(fixed)) \ else [] def fcomma(lang, p, c): return [] def fconjmp(lang, p, c): return [] from itertools import combinations, permutations def all_combinations(p, lp): res = [] for i in range(0, lp + 1): res += combinations(p, i) return res def to_function(func): '''Generates function from lex info dictionary.''' if type(func) == dict: return fgen( f = to_function(func.get('f', add_to_lorr)), fixed = func.get("fixed", []), attach = func.get("attach", []), down = func.get("down", []), up = func.get("up", []) ) else: return func def dicts_to_funcs(atn): '''Generates functions from all lex info dictionaries in the ATN.''' natn = {} for atnkey in atn: states = atn[atnkey] nstates = {} for statekey in states: state = states[statekey] new_state = [] for item in state: new_state += [(item[0], to_function(item[1]), item[2], item[3])] nstates[statekey] = new_state natn[atnkey] = nstates return natn def any_sequence(atn, optional, maxop = None, standard = 1.0, standard_seqs = [], starts = STATE_START, ends = STATE_END): '''Generates an ATN in which the states can be achieved in any sequence.''' maxop = len(optional) if maxop is None else maxop res = {} #print([x for x in combinations_without_reiterations(atn)]) res[starts] = [] #print([x for x in combinations_without_reiterations(optional)]) shift = starts #for q in combinations_without_reiterations(optional): for q in all_combinations(optional, maxop): t = atn + [[i[0]] for i in q if len(i) > 0] for r in permutations(t, len(t)): curr = [m[0][0] for m in r] #print(curr) #if any([ss == curr for ss in standard_seqs]): print(curr) stn = standard if any([ss == curr for ss in standard_seqs]) else 0.0 #print(stn) #print(",,,,,,",r) shift += 1 #res[starts] += [("JMP", shift + 1, None)] #it would work with left too. (left = True) j = 1 p = r[0] if j == len(r): next = ends else: next = shift + j + 1 for m in p: res[starts] += [(m[0], m[1], stn, next)] j += 1 for p in r[1:]: res[shift + j] = [] if j == len(r): next = ends else: next = shift + j + 1 for m in p: res[shift + j] += [(m[0], m[1], stn, next)] j += 1 shift += len(t) #stn = 0.0 #print(len(res[1]), res) #res = compr(res) return res def equal_dfuncs(f, g): '''Retuns true if two dictionaries with lexical info are equal.''' if None in [f, g]: return f is None and g is None return f.get('f', None) == g.get('f', None) and \ set(f.get('up', [])) == set(g.get('up', [])) and \ set(f.get('down', [])) == set(g.get('down', [])) and \ set(f.get('attach', [])) == set(g.get('attach', [])) and \ set(f.get('fixed', [])) == set(g.get('fixed', [])) def compr(res, dug=False): '''Compress's ATN state sequences. @dug - delete unreachable groups from way.''' on_way = set([(STATE_START, STATE_START)]) for key in [x for x in sorted(res.keys())]:#sorted(res.keys()): if not key in res.keys(): continue i = 0 while i < len(res[key]) - 1: j = i + 1 while j < len(res[key]): if res[key][i][3] <= res[key][j][3]: ti = i tj = j else: ti = j tj = i if res[key][ti][0] == res[key][tj][0] and \ res[key][ti][2] == res[key][tj][2] and \ (not STATE_END in [res[key][ti][3], res[key][tj][3]] or STATE_END == res[key][ti][3] == res[key][tj][3]) and \ equal_dfuncs(res[key][ti][1], res[key][tj][1]): if res[key][ti][3] != STATE_END: res[res[key][ti][3]] += res[res[key][tj][3]] res[key][ti] = ( res[key][ti][0], res[key][ti][1], res[key][ti][2],#max(res[key][tj][2], res[key][ti][2]), res[key][ti][3] ) del res[key][tj] else: if res[key][tj][2] <= res[key][ti][2]: del res[key][tj] else: del res[key][ti] else: j += 1 on_way.add((key, res[key][i][3])) i += 1 on_way.add((key, res[key][-1][3])) # delete unreachable groups from on_way if dug: nw = [] next = [STATE_START] while next != []: nnext = [] for p, n in on_way: if n > p and p in next: nnext += [n] nw += next next = nnext else: nw = [n for p, n in on_way] # deleting unreachable states for key in [x for x in res]: if not key in nw: del res[key] return res def can_jump(label, func=None, next=None): '''When the 'label' state is not obvious''' if next is None: return [(label, func, 0.0), ("JMP", None, 0.0)] return [(label, func, 0.0, next), ("JMP", None, 0.0, next)] def jump(next): return ("JMP", None, next) def _add_row(d, num, next, m): if not num in d.keys(): d[num] = [] for item in m: if len(item) == 1 or type(item) != tuple: tmp = item[0] if type(item) == tuple else item label = tmp func = None standard = 0.0 shift = 0 elif len(item) == 2: label, func = item standard = 0.0 shift = 0 elif len(item) == 3: if not is_float(item[2]): label, func, shift = item standard = 0.0 shift -= 1 else: label, func, standard = item shift = 0 else: raise Exception(item) if next == STATE_END: shift = 0 d[num] += [(label, func, standard, next + shift)] def straight_sequences(xx): d = {} st = STATE_START + 1 for x in xx: i = st _add_row(d, STATE_START, i if len(x) > 1 else STATE_END, x[0]) for m in x[1:]: j = i + 1 if i - st + 2 == len(x): st = j j = STATE_END _add_row(d, i, j, m) i = j return d def straight_sequence(x): return straight_sequences([x]) def single(x): return straight_sequences([[x]]) def unite(b1, b2): '''Adds a way which starts at the begining.''' if STATE_CONJ_A1 in b1 and \ STATE_CONJ_A1 in b2: raise Exception("INTERNAL ERROR: Can't unite to ways with conjunctions.") a1, a2 = deepcopy(b1), deepcopy(b2) shift = max(a1.keys()) - 1 for label, f, standard, next in a2[STATE_START]: nxt = next + shift if next != STATE_END else next a1[STATE_START] += [(label, f, standard, nxt)] del a2[STATE_START] for key in a2.keys(): new = key + shift if not key in STATE_CONJS else key a1[new] = [] for label, f, standard, next in a2[key]: nxt = next + shift if next != STATE_END else next #if nxt == 18740: print(next, shift, STATE_END) a1[new] += [(label, f, standard, nxt)] #print("------", a1) return a1 def is_float(b): return type(b) == float# b is True or b is False def to_full_atn(atn): '''Adds the missing parts of the ATN.''' for key in atn.keys(): for k in atn[key].keys(): if not k + 1 in atn[key].keys(): next = STATE_END else: next = k + 1 temp = [] for i in atn[key][k]: if len(i) == 1: temp += [(i[0], None, 0.0, next)] elif len(i) == 2: temp += [(i[0], i[1], 0.0, next)] elif len(i) == 3: if is_float(i[2]): temp += [(i[0], i[1], i[2], next)] else: temp += [(i[0], i[1], 0.0, i[2])] elif len(i) == 4: temp += [i] else: raise Exception(str(i)) atn[key][k] = temp return atn POSITIVE_INFINITY = float('inf') def subnet_deepness(atn, to_type_code, num = STATE_START): #7 iyui78i if num == STATE_END: return atn, 0, 0 mx = -1 mn = POSITIVE_INFINITY for i in range(len(atn[num])): item = atn[num][i] if item[3] != STATE_CONJ_A1 and item[3] <= num: mx = INDEFINITE mn = INDEFINITE atn[num][i] = atn[num][i][0], atn[num][i][1], atn[num][i][2], atn[num][i][3], mx, mn continue atn, mxtmp, mntmp = subnet_deepness(atn, to_type_code, item[3]) mxtmp += 0 if to_type_code(item[0]) in modificators + [ltype["epsilon"]] else 1 mntmp += 0 if to_type_code(item[0]) in modificators + [ltype["epsilon"]] else 1 atn[num][i] = atn[num][i][0], atn[num][i][1], atn[num][i][2], atn[num][i][3], mxtmp, mntmp mx = max(mxtmp, mx) mn = min(mntmp, mn) return atn, mx, mn def init_weights(atn, to_type_code): '''Initializes the maximum and minimum number of tokens that can be on the rest of the way.''' for key in atn.keys(): atn[key], mx, mn = subnet_deepness(atn[key], to_type_code) return atn def finish_atn(atn, to_type_code): atn = to_full_atn(atn) for key in atn: atn[key] = compr(atn[key]) return init_weights(dicts_to_funcs(atn), to_type_code) def with_conj(key, w, d): '''Adds the ability to be tied with conjunctions to the structure.''' if STATE_CONJ_A1 in d: raise Exception('Only one conjstruct is possible for one subATN now.') d[STATE_START] += [("JMP", None, 0.0, STATE_CONJ_A1)] d[STATE_CONJ_A1] = [(key, fg_bch(w), 0.0, STATE_CONJ_A2)] d[STATE_CONJ_A2] = [("PUNCT", fcomma, 0.0, STATE_CONJ_A3), ("JMP", None, 0.0, STATE_CONJ_A3)] d[STATE_CONJ_A3] = [("CONJ", add_to_conj_struct_among, 0.0, STATE_CONJ_A4), ("JMP", fconjmp, 0.0, STATE_CONJ_A4)] d[STATE_CONJ_A4] = [(key, fg_bch(w), 0.0, STATE_CONJ_A2), (key, fg_ach(w), 0.0, STATE_END)] return d
Python
#------------------------------------------------------------------------------- # ATNL - an Augmented Transition Network Language (v0.1) #------------------------------------------------------------------------------- __author__="zoltan kochan" __date__ ="$6 бер 2011 1:32:14$" #quenya Quenya (qenya) import core.ply.lex as lex from core.ply.lex import TOKEN import core.ply.yacc as yacc from core.constants import concept import core.constants as const from core.compilers.gener_tools import add_to_lorr, add_to_blocks, return_parent from core.compilers.gener_tools import any_sequence, unite, straight_sequences, with_conj, finish_atn PRINT_TO_CONSOLE = True # Constants ATN_LABEL = 0 ATN_FUNCTION = 1 ATN_COEFF = 2 ATN_NEXT = 3 MAXOP = 3 # Error messages ERROR_INVALID_ATTACH = "'%s' is an invalid attachment attribute" ERROR_INVALID_ATTR = "'%s' is an invalid attribute" ERROR_INVALID_ATTR_PAR = "'%s' is an invalid attribute value" ERROR_INVALID_RULE_NAME = "'%s' is an invalid rule name" ERROR_INVALID_TYPE = "'%s' is an invalid type" ERROR_INVALID_IDENT_NUM = "'%s' is an invalid identifier. An identifier should start with a letter of the latin alphabet" ERROR_INVALID_IDENT_HYPH = "'%s' is an invalid identifier. An identifier can't contain hyphen sequences" ERROR_INVALID_IDENT_NUM_HYPH = "'%s' is an invalid identifier. An identifier should start with a letter of the latin alphabet and can't contain hyphen sequences" ERROR_INVALID_STRING = "'%s' is an invalid string. String should have a closing \"" ERROR_CONJ = "'%s' already is a conjunction structure" ERROR_CONJ_SUB = "a conjunction structure rule should consist of one element which is '%s'" # Compute column. # input is the input text string # token is a token instance def find_column(lexpos): global text last_cr = text.rfind('\n',0,lexpos) if last_cr < 0: last_cr = 0 column = (lexpos - last_cr) return column def print_error(line, col, errmsg): global path print("-"*80) print("File '%s', line %d, column %d" % (path, line, col)) print(" "*5, "ATNL ERROR:", errmsg) print("-"*80) class AtnlSyntaxError(SyntaxError): def __init__(self, errmsg, p, n, s): global PRINT_TO_CONSOLE if PRINT_TO_CONSOLE: print_error(p.lineno(n), find_column(p.lexpos(n)), errmsg % s) SyntaxError.__init__(self) reserved = { 'is' : 'IS' } tokens = [ 'CONJ_IDENTIFIER', 'DOLLAR_IDENTIFIER', 'DOLLAR_DOT_IDENTIFIER', 'DOT_IDENTIFIER', 'IDENTIFIER', 'ARROW', "STRING", "ASSIGN_RULE", "ASSIGN_CONST", "LANY", "RANY", "FLOAT", "ASSIGN_PRIOR", "IS", "ERROR_STRING", "ERROR_IDENTIFIER_NUM", "ERROR_IDENTIFIER_HYPH", "ERROR_IDENTIFIER_NUM_HYPH", ] # Tokens literals = [',', '(', ')', ':', '{', '}', '|', ';', '<', '>', '[', ']', '&'] LANY = "(" RANY = ")" ident = "[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*" t_ignore = " \t" t_CONJ_IDENTIFIER = r"&" + ident t_DOLLAR_IDENTIFIER = r"\$" + ident t_DOT_IDENTIFIER = r"\." + ident t_DOLLAR_DOT_IDENTIFIER = r"\$\." + ident t_STRING = r'\"([^\\\n]|(\\.))*?\"' t_ARROW = r"->" t_ASSIGN_RULE = r":-" t_ASSIGN_CONST = r":=" t_ASSIGN_PRIOR = r"::=" t_LANY = r"\(" t_RANY = r"\)" ident_hyph_suff = '''[a-zA-Z0-9]* ((-[a-zA-Z0-9]+)|(-{2,}[a-zA-Z0-9]+))* (-{2,}[a-zA-Z0-9]+)+ (-[a-zA-Z0-9]+)*''' t_ERROR_IDENTIFIER_NUM = r"[-0-9]+[a-zA-Z0-9]*([a-zA-Z]+|(-[a-zA-Z0-9]+)+)" t_ERROR_IDENTIFIER_HYPH = r'[a-zA-Z]' + ident_hyph_suff t_ERROR_IDENTIFIER_NUM_HYPH = r"[-0-9]+" + ident_hyph_suff t_ERROR_STRING = r'\"([^\\\n\"]|(\\.))+' @TOKEN(ident) def t_IDENTIFIER(t): t.type = reserved.get(t.value, 'IDENTIFIER') # Check for reserved words return t def t_FLOAT(t): '''(0\.[0-9]{1,4}|1\.0)''' t.value = float(t.value) return t # Comment def t_COMMENT(t): r'(/\*(.|\n)*?\*/)|(//.*?\n)' t.lexer.lineno += t.value.count("\n") pass def t_newline(t): r'\n+' t.lexer.lineno += len(t.value) # Error handling rule def t_error(t): t.lexer.skip(1) if not PRINT_TO_CONSOLE: return try: print_error(-1, -1, "Illegal character '%s'" % t.value[0]) except UnicodeEncodeError: print_error(-1, -1, "Illegal character") precedence = ( ('right', 'CONJ_IDENTIFIER', 'DOLLAR_IDENTIFIER', 'DOLLAR_DOT_IDENTIFIER', 'DOT_IDENTIFIER', 'IDENTIFIER', "ERROR_IDENTIFIER_NUM", "ERROR_IDENTIFIER_HYPH", "ERROR_IDENTIFIER_NUM_HYPH", "ERROR_STRING"), ('right', '<'), ('right', '{'), ('left', ','), ('left', 'ARROW'), ('left', ':'), ) lexer = lex.lex() # Parsing rules atn = {} prior = {} d = {} label = "" consts = {} label_types = {} def p_rules(p): '''rules : rule | assignment | priority | is_type | rules rule | rules assignment | rules priority | rules is_type''' #------------------------------------------------------------------------------- # Identifiers #------------------------------------------------------------------------------- def p_identifier(p): '''identifier : prop_identifier | error_ident''' p[0] = p[1] def p_prop_identifier(p): '''prop_identifier : IDENTIFIER''' p[0] = p[1] def p_error_ident(p): '''error_ident : error_ident_num | error_ident_hyph | error_ident_num_hyph''' def p_error_ident_num(p): '''error_ident_num : ERROR_IDENTIFIER_NUM''' raise AtnlSyntaxError(ERROR_INVALID_IDENT_NUM, p, 1, p[1]) def p_error_ident_hyph(p): '''error_ident_hyph : ERROR_IDENTIFIER_HYPH''' raise AtnlSyntaxError(ERROR_INVALID_IDENT_HYPH, p, 1, p[1]) def p_error_ident_num_hyph(p): '''error_ident_num_hyph : ERROR_IDENTIFIER_NUM_HYPH''' raise AtnlSyntaxError(ERROR_INVALID_IDENT_NUM_HYPH, p, 1, p[1]) #------------------------------------------------------------------------------- # String #------------------------------------------------------------------------------- def p_string(p): '''string : proper_string | invalid_string''' p[0] = p[1] def p_proper_string(p): '''proper_string : STRING''' p[0] = p[1][1:-1] def p_invalid_string(p): '''invalid_string : ERROR_STRING''' raise AtnlSyntaxError(ERROR_INVALID_STRING, p, 1, p[1]) #------------------------------------------------------------------------------- # is_type rules #------------------------------------------------------------------------------- def p_is_type(p): '''is_type : identifier IS rule_name_simple ";" | identifier IS rule_name_complex ";"''' global label_types, standard_attr label_types[p[1]], standard_attr[p[1]] = p[3] def p_rule_name_simple(p): '''rule_name_simple : identifier''' if not p[1] in const.type: AtnlSyntaxError(ERROR_INVALID_TYPE, p, 1, p[1]) p[0] = (const.type[p[1]], []) def p_rule_name_complex(p): '''rule_name_complex : identifier "{" attributes "}"''' if not p[1] in const.type: AtnlSyntaxError(ERROR_INVALID_TYPE, p, 1, p[1]) p[0] = (const.type[p[1]], p[3]) #------------------------------------------------------------------------------- # Priority rules #------------------------------------------------------------------------------- def p_priority(p): '''priority : priority_header priority_expressions ";"''' global prior prior = update_dict(prior, {p[1]: p[2]}) def p_priority_header(p): '''priority_header : identifier ASSIGN_PRIOR''' p[0] = p[1] def p_priority_expressions(p): '''priority_expressions : priority_expression_single | priority_expression_few''' p[0] = p[1] def p_priority_expression_single(p): '''priority_expression_single : priority_expression''' p[0] = [p[1]] def p_priority_expression_few(p): '''priority_expression_few : priority_expressions priority_expression_single''' p[0] = p[1] + p[2] def p_priority_expression(p): '''priority_expression : FLOAT ":" identifiers''' p[0] = (p[1], p[3]) def p_identifiers(p): '''identifiers : idents_all | ident_clue''' p[0] = p[1] def p_ident_all(p): '''idents_all : ident | dot_ident''' p[0] = p[1] def p_ident(p): '''ident : identifier''' p[0] = [p[1]] def p_dot_ident(p): '''dot_ident : DOT_IDENTIFIER''' p[0] = [p[1][1:]+":empty"] def p_ident_clue(p): '''ident_clue : identifiers idents_all''' p[0] = p[1] + p[2] #------------------------------------------------------------------------------- # Constant rules #------------------------------------------------------------------------------- def p_assignment(p): '''assignment : identifier ASSIGN_CONST attaches ";"''' global consts consts[p[1]] = p[3] #------------------------------------------------------------------------------- #Grammar rules #------------------------------------------------------------------------------- def add_up_attributes(rp, terms): if not rp[1] is None: new = [] for item in terms[const.STATE_START]: if item[1] is None: new += [(item[0], dict(f = return_parent, up = rp[1]), item[2], item[3])] else: new += [(item[0], dict(f = item[1], up = rp[1]), item[2], item[3])] terms[const.STATE_START] = new return terms def p_rule(p): '''rule : full_rule ";" | conj_rule ";"''' p[0] = p[1] def p_conj_rule(p): '''conj_rule : CONJ_IDENTIFIER ASSIGN_RULE conj_sub''' label = p[1][1:] global atn if const.STATE_CONJ_A1 in atn[label]: raise AtnlSyntaxError(ERROR_CONJ, p, 1, label) if p[3][0] != label: raise AtnlSyntaxError(ERROR_CONJ_SUB, p, 1, label) atn[label] = with_conj(label, p[3][1], atn[label]) def p_conj_sub(p): '''conj_sub : DOLLAR_IDENTIFIER "<" attaches ">"''' p[0] = (p[1][1:], p[3]) def p_full_rule(p): '''full_rule : rule_params ASSIGN_RULE terms''' global atn pars = p[1] terms = add_up_attributes(pars, p[3]) label = pars[0] if label in atn: atn[label] = unite(atn[label], terms) else: atn[label] = terms def p_rule_params(p): '''rule_params : rule_params_empty | rule_params_simple | rule_params_complex_empty | rule_params_complex''' p[0] = p[1] def p_rule_params_empty(p): '''rule_params_empty : DOT_IDENTIFIER''' global label_types if not p[1][1:] in label_types: raise AtnlSyntaxError(ERROR_INVALID_RULE_NAME, p, 1, p[1][1:]) p[0] = (p[1][1:]+":empty", None) def p_rule_params_simple(p): '''rule_params_simple : identifier''' global label_types if not p[1] in label_types: raise AtnlSyntaxError(ERROR_INVALID_RULE_NAME, p, 1, p[1]) p[0] = (p[1], None) def p_rule_params_complex_empty(p): '''rule_params_complex_empty : DOT_IDENTIFIER "{" attributes "}"''' global label_types if not p[1][1:] in label_types: raise AtnlSyntaxError(ERROR_INVALID_RULE_NAME, p, 1, p[1][1:]) p[0] = (p[1][1:]+":empty", p[3]) def p_rule_params_complex(p): '''rule_params_complex : identifier "{" attributes "}"''' global label_types if not p[1] in label_types: raise AtnlSyntaxError(ERROR_INVALID_RULE_NAME, p, 1, p[1]) p[0] = (p[1], p[3]) def contains_jump(lst, curr, is_last): for item in lst: if item[ATN_LABEL] != "JMP": continue if item[ATN_NEXT] != curr + 1 and \ (not is_last or item[ATN_NEXT] != const.STATE_END): raise Exception('In ANY only single elements could be optional') return True return False def div_to_op(seq): a, b = [], [] i = 0 for item in seq: i += 1 if contains_jump(seq[item], item, i == len(seq)): b += [seq[item]] else: a += [seq[item]] return a, b def concat(a, b): '''Adds a way to the end.''' last = max(a.keys()) next = last + 1 new = [] for item in a[last]: if item[ATN_NEXT] != const.STATE_END: raise Exception() else: new += [(item[0], item[1], item[2], next)] a[last] = new if type(b) == dict: for key in b: nont = [] for item in b[key]: if item[3] == const.STATE_END: nont += [item] else: nont += [(item[0], item[1], item[2], item[3] + last)] a[key + last] = nont else: if type(b) == tuple: b = [b] a[next] = [(item[0], item[1], 0.0, const.STATE_END) for item in b] return a def addjump(dc): dc[min(dc.keys())] += [('JMP', None, 0.0, const.STATE_END)] def p_terms(p): '''terms : term_1 | terms_clue''' p[0] = p[1] def p_term_1(p): '''term_1 : term_str | terms_not_required | terms_any''' p[0] = p[1] def p_terms_clue(p): '''terms_clue : terms term_1''' p[0] = concat(p[1], p[2]) def p_terms_not_required(p): '''terms_not_required : "[" terms "]"''' addjump(p[2]) p[0] = p[2] def p_terms_any(p): '''terms_any : LANY terms RANY''' ob, op = div_to_op(p[2]) p[0] = any_sequence(ob, op, MAXOP) def p_term_str(p): '''term_str : term''' p[0] = straight_sequences([[[p[1]]]]) def p_term(p): '''term : ling_unit | ling_unit_attaches | ling_unit_attr | ling_unit_comlex''' p[0] = p[1] def p_ling_unit(p): '''ling_unit : term_name''' global standard_attr p[0] = (p[1][0], dict(f = p[1][1], down = standard_attr[root_label(p[1][0])])) def p_ling_unit_attaches(p): '''ling_unit_attaches : term_name "<" attaches ">"''' global standard_attr func = dict(f = p[1][1], attach = p[3].get('attach', []), fixed = p[3].get('fixed', []), down = standard_attr[root_label(p[1][0])]) p[0] = (p[1][0], func) def p_ling_unit_attr(p): '''ling_unit_attr : term_name "{" attributes "}"''' global standard_attr p[0] = (p[1][0], dict(f = p[1][1], down = p[3] + standard_attr[root_label(p[1][0])])) def p_ling_unit_comlex(p): '''ling_unit_comlex : term_name "<" attaches ">" "{" attributes "}"''' global standard_attr func = dict(f = p[1][1], attach = p[3].get('attach', []), fixed = p[3].get('fixed', []), down = p[6] + standard_attr[root_label(p[1][0])]) p[0] = (p[1][0], func) def p_term_name(p): '''term_name : term_name_main | term_name_child | term_name_empty | term_name_empty_main''' p[0] = p[1] def p_term_name_main(p): '''term_name_main : DOLLAR_IDENTIFIER''' global label_types if not p[1][1:] in label_types: raise AtnlSyntaxError(ERROR_INVALID_RULE_NAME, p, 1, p[1][1:]) p[0] = (p[1][1:], add_to_blocks) def p_term_name_child(p): '''term_name_child : identifier''' global label_types if not p[1] in label_types: raise AtnlSyntaxError(ERROR_INVALID_RULE_NAME, p, 1, p[1]) p[0] = (p[1], add_to_lorr) def p_term_name_empty(p): '''term_name_empty : DOT_IDENTIFIER''' global label_types if not p[1][1:] in label_types: raise AtnlSyntaxError(ERROR_INVALID_RULE_NAME, p, 1, p[1][1:]) p[0] = (p[1][1:]+':empty', add_to_lorr) def p_term_name_empty_main(p): '''term_name_empty_main : DOLLAR_DOT_IDENTIFIER''' global label_types if not p[1][2:] in label_types: raise AtnlSyntaxError(ERROR_INVALID_RULE_NAME, p, 1, p[1][2:]) p[0] = (p[1][2:]+':empty', add_to_blocks) def p_attributes(p): '''attributes : attribute | attribute_clue''' p[0] = p[1] def p_attribute_clue(p): '''attribute_clue : attributes ";" attribute''' p[0] = p[1] + p[3] def p_attribute(p): '''attribute : attr_ident | attr_str | attr_float''' p[0] = [p[1]] def p_attr_ident(p): '''attr_ident : identifier ":" identifier''' if not p[1] in concept: raise AtnlSyntaxError(ERROR_INVALID_ATTR, p, 1, p[1]) if p[3] == 'true': p[0] = (concept[p[1]], True) elif p[3] == 'false': p[0] = (concept[p[1]], False) else: pd = const.__dict__[p[1].replace("-", "_")] if not p[3] in pd: raise AtnlSyntaxError(ERROR_INVALID_ATTR_PAR, p, 3, p[3]) p[0] = (concept[p[1]], pd[p[3]]) def p_attr_str(p): '''attr_str : identifier ":" string''' if not p[1] in concept: raise AtnlSyntaxError(ERROR_INVALID_ATTR, p, 1, p[1]) p[0] = (concept[p[1]], p[3]) def p_attr_float(p): '''attr_float : identifier ":" FLOAT''' if not p[1] in concept: raise AtnlSyntaxError(ERROR_INVALID_ATTR, p, 1, p[1]) p[0] = (concept[p[1]], p[3]) import copy def update_dict(c, b): '''Unites two dictionaries''' if c is None: return b if b is None: return c a = copy.deepcopy(c) for key in b: if key in a: a[key] += b[key] if type(b[key]) == list else [b[key]] else: a[key] = b[key] if type(b[key]) == list else [b[key]] return a def p_attaches(p): '''attaches : pair | attaches_clue''' p[0] = p[1] def p_attaches_clue(p): '''attaches_clue : attaches "," pair''' p[0] = update_dict(p[1], p[3]) def p_pair(p): '''pair : pair_complex_attached | pair_complex_fixed | pair_attached | pair_fixed''' p[0] = p[1] def p_pair_attached(p): '''pair_attached : identifier''' if p[1] in consts: p[0] = consts[p[1]] else: if not p[1] in concept: raise AtnlSyntaxError(ERROR_INVALID_ATTACH, p, 1, p[1]) p[0] = {'attach': [concept[p[1]]]} def p_pair_fixed(p): '''pair_fixed : DOLLAR_IDENTIFIER''' if p[1][1:] in consts: p[0] = {'fixed': consts[p[1][1:]]['attach']} else: if not p[1][1:] in concept: raise AtnlSyntaxError(ERROR_INVALID_ATTACH, p, 1, p[1][1:]) p[0] = {'fixed': [concept[p[1][1:]]]} def p_pair_complex_attached(p): '''pair_complex_attached : identifier ARROW identifier''' if not p[1] in concept: raise AtnlSyntaxError(ERROR_INVALID_ATTACH, p, 1, p[1]) if not p[3] in concept: raise AtnlSyntaxError(ERROR_INVALID_ATTACH, p, 3, p[3]) p[0] = {'attach': [(concept[p[1]], concept[p[3]])]} def p_pair_complex_fixed(p): '''pair_complex_fixed : DOLLAR_IDENTIFIER ARROW identifier''' if not p[1][1:] in concept: raise AtnlSyntaxError(ERROR_INVALID_ATTACH, p, 1, p[1][1:]) if not p[3] in concept: raise AtnlSyntaxError(ERROR_INVALID_ATTACH, p, 3, p[3]) p[0] = {'fixed': [(concept[p[1][1:]], concept[p[3]])]} #------------------------------------------------------------------------------- # Common rules #------------------------------------------------------------------------------- def p_error(p): if not PRINT_TO_CONSOLE: return try: if not p is None: print_error(p.lineno, find_column(p.lexpos), "Syntax error at '%s'" % p.value) else: print_error(-1, -1, "Syntax error") except UnicodeEncodeError: print_error(p.lineno, 0, "Syntax error") def search_path(sub_atn, state, path, weight): i = -1 b = False for label, function, lweight, next in sub_atn[state]: i += 1 jmplab = label == const.type['epsilon'] or label == 'JMP' ######### if len(path) == 0: if jmplab and (next == const.STATE_END or search_path(sub_atn, next, path, weight)): sub_atn[state][i] = label, function, max(weight, lweight), next b = True continue if label != path[0]: if not jmplab: continue jump = True else: jump = False if next == const.STATE_END: if len(path) == 1 and not jump: sub_atn[state][i] = label, function, max(weight, lweight), next b = True continue if search_path(sub_atn, next, path if jump else path[1:], weight): sub_atn[state][i] = label, function, max(weight, lweight), next b = True return b def add_priorities(atn, priorities): for nonterminal in priorities: if not nonterminal in atn: print(nonterminal,) raise Exception() sub_atn = atn[nonterminal] for weight, path in priorities[nonterminal]: search_path(sub_atn, const.STATE_START, path, weight) #################################################################### def print_interlingua(dc, c = 0): d = 5 b = d*c*" " b1 = b + d*" " if type(dc) in [int, str, tuple]: print(b + str(dc)) return print(b + "{") for key in dc.keys(): if dc[key] == None: continue if type(dc[key]) == list: if key == concept["tags"]: print(b1 + str(key) + ":", ', '.join(dc[key])) else: for item in dc[key]: print(b1 + str(key) + ":") print_interlingua(item, c + 2) elif not type(dc[key]) in [int, str, tuple]: #isinstance(dc, dict):!!!!!!!!!! print(b1 + str(key) + ":") print_interlingua(dc[key], c + 2) else: print(b1 + str(key) + ":", dc[key]) print(b + "}") #################################################################### yaccer = yacc.yacc() path = None def root_label(label): return label.split(":")[0] def gen_to_type_code(): global label_types return lambda label: label_types[root_label(label)] def _parse_text(s, print_to_console): global PRINT_TO_CONSOLE PRINT_TO_CONSOLE = print_to_console #global path global atn, text, prior, label_types, standard_attr atn = {} prior = {} label_types = {'JMP': const.type['epsilon'], 'CONJ': const.type['conjunction']} standard_attr = {} text = s lexer.lineno = 1 try: yaccer.parse(s, lexer=lexer, tracking=PRINT_TO_CONSOLE) add_priorities(atn, prior) ret = finish_atn(atn, gen_to_type_code()) except Exception: if PRINT_TO_CONSOLE: print("WARNING: internal ATNL compiler error") return None atn = ret if ret != {} else None if atn is None: return None return atn, label_types def parse(s, print_to_console=True): global path path = None return _parse_text(s, print_to_console) def _read_file(file_path): try: f = open(file_path, encoding = 'utf-8') s = f.read() except IOError: print("can't open file '" + os.path.join(self.path, file_path) + "'") finally: f.close() return s def parse_file(_path, print_to_console=True): global path path = _path return _parse_text(_read_file(path), print_to_console)
Python
# ----------------------------------------------------------------------------- # CWS - Cascading Word Sheets (v0.1) # ----------------------------------------------------------------------------- __author__="Z-CORE" __date__ ="$5 бер 2011 11:36:40$" from core.models.ling_units import Token import core.ply.lex as lex import core.ply.yacc as yacc from core.constants import concept, concept_type from copy import deepcopy import core.constants as const PRINT_TO_CONSOLE = True ERROR_MULT_VALUE = "attribute '%s' can't have multiple values" ERROR_INVALID_ATTR_PAR = "'%s' is an invalid attribute value" ERROR_INVALID_ATTR_PAR_TYPE = "'%s' has bad type" ERROR_INVALID_ATTR = "'%s' is an invalid attribute" ERROR_IMP_INHERIT_NAME = "it's impossible to inherit any name here" ERROR_INVALID_BASE_NAME = "base '%s' doesn't exist." ERROR_MISSING_FILE = "can't find '%s' .cws file." ERROR_DUPLICATE_FILE = "file '%s' .cws was already used." # Compute column. # input is the input text string # token is a token instance def find_column(lexpos): global Params last_cr = Params.text.rfind('\n',0,lexpos) if last_cr < 0: last_cr = 0 column = (lexpos - last_cr) return column def print_error(line, col, errmsg): global Params print("-"*80) print("File '%s', line %d, column %d" % (Params.path, line, col)) print(" "*5, "CWS ERROR:", errmsg) print("-"*80) class CWSSyntaxError(SyntaxError): def __init__(self, errmsg, p, n, s=None): global PRINT_TO_CONSOLE if PRINT_TO_CONSOLE: if s is None: print_error(p.lineno(n), find_column(p.lexpos(n)), errmsg) else: print_error(p.lineno(n), find_column(p.lexpos(n)), errmsg % s) SyntaxError.__init__(self) reserved = { 'using' : 'USING' } tokens = [ 'IDENTIFIER', 'DOT_IDENTIFIER', 'DCOLON', "STRING", "DOT_STRING", "NUMBER", "TRANSCR", "FLOAT", #"ERROR_STRING", "ERROR_IDENTIFIER_NUM", "ERROR_IDENTIFIER_HYPH", "ERROR_IDENTIFIER_NUM_HYPH", ] + list(reserved.values()) # Tokens literals = ['{', '}', ':', ';', ',', '[', ']', '(', ')'] t_ignore = " \t" t_TRANSCR = r"\[[^\[\]]+\]" t_DOT_IDENTIFIER = r"\.[a-zA-Z_][-a-zA-Z_0-9]*" t_DCOLON = r"::" t_STRING = r'\"([^\\\n]|(\\.))*?\"' t_DOT_STRING = r'\.\"([^\\\n]|(\\.))*?\"' ident_hyph_suff = '''[a-zA-Z0-9]* ((-[a-zA-Z0-9]+)|(-{2,}[a-zA-Z0-9]+))* (-{2,}[a-zA-Z0-9]+)+ (-[a-zA-Z0-9]+)*''' t_ERROR_IDENTIFIER_NUM = r"[-0-9]+[a-zA-Z0-9]*([a-zA-Z]+|(-[a-zA-Z0-9]+)+)" t_ERROR_IDENTIFIER_HYPH = r'[a-zA-Z]' + ident_hyph_suff t_ERROR_IDENTIFIER_NUM_HYPH = r"[-0-9]+" + ident_hyph_suff #t_ERROR_STRING = r'\"([^\\\n\"]|(\\.))+' def t_IDENTIFIER(t): r"[a-zA-Z_][-a-zA-Z_0-9]*" t.type = reserved.get(t.value, 'IDENTIFIER') # Check for reserved words return t def t_FLOAT(t): '''(0\.[0-9]{1,4}|1\.0)''' t.value = float(t.value) return t # Comment def t_COMMENT(t): r'(/\*(.|\n)*?\*/)|(//.*?\n)' t.lexer.lineno += t.value.count("\n") pass def t_newline(t): r'\n+' t.lexer.lineno += len(t.value) def t_NUMBER(t): r'\d+' t.value = int(t.value) return t # Error handling rule def t_error(t): #t.lexer.skip(1) if PRINT_TO_CONSOLE: try: print_error(-1, -1, "Illegal character '%s'" % t.value[0]) except UnicodeEncodeError: print_error(-1, -1, "Illegal character") raise Exception() #precedence = ( # ('right', # 'IDENTIFIER', # 'USING', # 'FLOAT', # "ERROR_IDENTIFIER_NUM", # "ERROR_IDENTIFIER_HYPH", # "ERROR_IDENTIFIER_NUM_HYPH",), # #"ERROR_STRING"), # ('right', '{'), # ('right', '}'), # #('right', 'USING') #) # Parsing rules def p_records(p): '''records : one_record | few_records''' global Params p[0] = (p[1][0], p[1][1], Params.funcs) def fill_dm(dictionary, meanings, tokens): for token in tokens: if token.text[0] in dictionary: dictionary[token.text[0]] += [token] else: dictionary[token.text[0]] = [token] if token.meaning != None: if token.meaning in meanings: #maybe do it in the end of the method meanings[token.meaning] += [token] else: meanings[token.meaning] = [token] return (dictionary, meanings) def p_one_record(p): '''one_record : record | using''' p[0] = p[1] def p_few_records(p): '''few_records : records record | records using''' p[0] = (update_dict(p[1][0], p[2][0]), update_dict(p[1][1], p[2][1])) def modif_word(n, props): w = deepcopy(n) for p, v in props: if p == concept["text"]: w.text[-1] = modif_text(v, w.text[-1]) elif p == concept["transcription"]: w.transcription[-1] = modif_text(v, w.transcription[-1]) elif p == concept["lemma"]: w.meaning = modif_text(v, w.meaning) else: w.attr(p, v) global Params if w.attr(concept['transcription']) is None and \ not w.attr(concept['text']) is None: w.transcription = Params.to_ipa(w.text) if w.meaning is None and not w.attr(concept['stem']) is None: w.meaning = w.attr(concept['stem']).rsplit('.', 1)[0] if not w.attr(concept['number']) is None \ and w.attr(concept['real-number']) is None: w.attr(concept['real-number'], w.attr(concept['number'])) return w def modify_token(base, word): return [modif_word(word, b) for b in get_base(base)] def modif_text(pattern, text): if pattern.find("|") != -1: left, right = pattern.split("|") text = modif_text(left, text) text = modif_text(right, text) return text if pattern.find(">") != -1: n, wo = pattern.split(">") temp = text if n == "0" else text[:-int(n)] if len(wo) > 1 and wo[0] == ":": if temp[-1] == "y": temp = temp[:-1] + temp[-2] + temp[-1] else: temp += temp[-1] wo = wo[1:] return temp + wo if pattern.find("<") != -1: wo, n = pattern.split("<") temp = text[int(n):] return wo + temp return pattern def mod(obj, base): n = deepcopy(obj) pattern = None for p in base: if p[0] == concept["text"]: pattern = p[1] continue for j in range(len(n)): if n[j][0] == p[0]: del n[j] break n += [p] if not pattern is None: for j in range(len(n)): if n[j][0] == concept["text"]: text = n[j][1] if text.find(">") != -1 and pattern.find("<") != -1: n[j] = (n[j][0], pattern + "|" + text) elif text.find("<") != -1 and pattern.find(">") != -1: n[j] = (n[j][0], text + "|" + pattern) else: n[j] = (n[j][0], modif_text(pattern, text)) break else: n += [(concept["text"], pattern)] return n def modify(object_name, base_name): res = [] global Params for base in Params.funcs[base_name]: if base is None: raise Exception() for obj in Params.funcs[object_name]: res += [mod(obj, base)] return res def get_base(base): if base[1] is None: return GetParams().funcs[base[0]] else: return modify(base[0], base[1]) def modify_base(has_dot, name, tomod, base): global Params for pr in get_base(base): if pr is None and has_dot: continue if name in Params.funcs.keys(): Params.funcs[name] += [mod(tomod, pr)] else: Params.funcs[name] = [mod(tomod, pr)] def attr_to_dict(l): d = {} for key, value in l: d[key] = value return d def p_using(p): '''using : USING DCOLON files "{" "}"''' p[0] = p[3] def p_files(p): '''files : one_file | few_files''' p[0] = p[1] def p_one_file(p): '''one_file : identifier''' global Params if not p[1] in Params.cws_files: raise CWSSyntaxError(ERROR_MISSING_FILE, p, 1, p[1]) if p[1] in Params.attached_files: raise CWSSyntaxError(ERROR_DUPLICATE_FILE, p, 1, p[1]) Params.attached_files += [p[1]] if p[1] in Params.all_funcs: Params.funcs = update_dict(Params.funcs, Params.all_funcs[p[1]]) return ({}, {}) global PRINT_TO_CONSOLE _path = Params.path _text = Params.text _funcs = Params.funcs Params.funcs = {} nme = p[1] tmp = _parse_file(Params.cws_files[nme], PRINT_TO_CONSOLE) Params.path = _path Params.text = _text Params.funcs = update_dict(_funcs, tmp[2]) p[0] = (tmp[0], tmp[1]) def p_few_files(p): '''few_files : files one_file''' p[0] = (update_dict(p[1][0], p[2][0]), update_dict(p[1][1], p[2][1])) def p_record(p): '''record : header "{" attributes "}" | header "{" attributes ";" "}" | header "{" "}"''' global Params res = [] header = p[1] attributes = p[3] if len(p) > 4 else [[]] for name, base in header: has_dot, is_word, nme, ipa = name if base is None and has_dot: continue if is_word: for attr in attributes: tok = Token(None, 0, 0) tok._attrs = attr_to_dict(attr) if not ipa is None: tok.attr(concept['transcription'], ipa) if not tok.attr(concept['transcription']) is None: tok.attr(concept['transcription'], [tok.attr(concept['transcription'])]) if tok.meaning is None and not tok.attr(concept['stem']) is None: tok.meaning = tok.attr(concept['stem']).rsplit('.', 1)[0] if not tok.attr(concept['number']) is None \ and tok.attr(concept['real-number']) is None: tok.attr(concept['real-number'], tok.attr(concept['number'])) tok.text = [nme] if not base is None: res += modify_token(base, tok) else: res += [tok] else: if not ipa is None: raise Exception() for attr in attributes: if not base is None: modify_base(has_dot, nme, attr, base) elif not has_dot and attr != []: if nme in Params.funcs.keys(): Params.funcs[nme] += [attr] else: Params.funcs[nme] = [attr] dictionary = {} meanings = {} p[0] = fill_dm(dictionary, meanings, res) #------------------------------------------------------------------------------- # Identifiers #------------------------------------------------------------------------------- def p_identifier(p): '''identifier : prop_identifier | error_ident''' p[0] = p[1] def p_prop_identifier(p): '''prop_identifier : IDENTIFIER''' p[0] = p[1] def p_error_ident(p): '''error_ident : error_ident_num | error_ident_hyph | error_ident_num_hyph''' def p_error_ident_num(p): '''error_ident_num : ERROR_IDENTIFIER_NUM''' raise CWSSyntaxError(ERROR_INVALID_IDENT_NUM, p, 1, p[1]) def p_error_ident_hyph(p): '''error_ident_hyph : ERROR_IDENTIFIER_HYPH''' raise CWSSyntaxError(ERROR_INVALID_IDENT_HYPH, p, 1, p[1]) def p_error_ident_num_hyph(p): '''error_ident_num_hyph : ERROR_IDENTIFIER_NUM_HYPH''' raise CWSSyntaxError(ERROR_INVALID_IDENT_NUM_HYPH, p, 1, p[1]) #------------------------------------------------------------------------------- #reqion header def p_header(p): '''header : simple_header | full_header | lil_full_header''' p[0] = p[1] def p_simple_header(p): '''simple_header : words''' p[0] = [(w, None) for w in p[1]] def p_full_header(p): '''full_header : words DCOLON base_tokens''' global Params Params.prev = p[1] p[0] = [(w, bt) for bt in [None] + p[3] for w in Params.prev] def p_lil_full_header(p): '''lil_full_header : DCOLON base_tokens''' global Params if Params.prev is None: raise CWSSyntaxError(ERROR_IMP_INHERIT_NAME, p, 1) p[0] = [(w, bt) for bt in [None] + p[2] for w in Params.prev] #endregion def p_words(p): '''words : word | few_words''' p[0] = p[1] def p_few_words(p): '''few_words : words word''' p[0] = p[1] + p[2] def p_word(p): '''word : word_txt | word_txtipa | identifier_head | dot_word_txt | dot_word_txtipa | dot_identifier_head''' p[0] = [p[1]] def p_identifier_head(p): '''identifier_head : identifier''' p[0] = (False, False, p[1], None) def p_word_txt(p): '''word_txt : STRING''' p[0] = (False, True, p[1][1:-1], None) def p_word_txtipa(p): '''word_txtipa : STRING TRANSCR''' p[0] = (False, True, p[1][1:-1], p[2][1:-1]) def p_dot_identifier_head(p): '''dot_identifier_head : DOT_IDENTIFIER''' p[0] = (True, False, p[1][1:], None) def p_dot_word_txt(p): '''dot_word_txt : DOT_STRING''' p[0] = (True, True, p[1][2:-1], None) def p_dot_word_txtipa(p): '''dot_word_txtipa : DOT_STRING TRANSCR''' p[0] = (True, True, p[1][2:-1], p[2][1:-1]) # string sequences region def p_strings(p): '''strings : one_string | few_strings''' p[0] = p[1] def p_one_string(p): '''one_string : STRING''' p[0] = [p[1][1:-1]] def p_few_strings(p): '''few_strings : strings STRING''' p[0] = p[1] + [p[2][1:-1]] # string sequences endregion #region base tokens def p_base_tokens(p): '''base_tokens : base_token | complex_base_token | few_base_tokens | few_complex_base_tokens''' p[0] = p[1] def p_base_token(p): '''base_token : identifier''' global Params if not p[1] in Params.funcs: raise CWSSyntaxError(ERROR_INVALID_BASE_NAME, p, 1, p[1]) p[0] = [(p[1], None)] def p_complex_base_token(p): '''complex_base_token : identifier "(" identifier ")"''' global Params if not p[1] in Params.funcs: raise CWSSyntaxError(ERROR_INVALID_BASE_NAME, p, 1, p[1]) if not p[3] in Params.funcs: raise CWSSyntaxError(ERROR_INVALID_BASE_NAME, p, 3, p[3]) p[0] = [(p[1], p[3])] def p_few_base_tokens(p): '''few_base_tokens : base_tokens identifier''' global Params if not p[2] in Params.funcs: raise CWSSyntaxError(ERROR_INVALID_BASE_NAME, p, 2, p[2]) p[0] = p[1] + [(p[2], None)] def p_few_complex_base_tokens(p): '''few_complex_base_tokens : base_tokens identifier "(" identifier ")" ''' global Params if not p[2] in Params.funcs: raise CWSSyntaxError(ERROR_INVALID_BASE_NAME, p, 2, p[2]) if not p[4] in Params.funcs: raise CWSSyntaxError(ERROR_INVALID_BASE_NAME, p, 4, p[4]) p[0] = p[1] + [(p[2], p[4])] def p_sem_identifiers(p): '''sem_identifiers : one_sem_identifier | few_sem_identifiers''' p[0] = p[1] def p_one_sem_identifier(p): '''one_sem_identifier : com_identifiers''' p[0] = [p[1]] def p_few_sem_identifiers(p): '''few_sem_identifiers : sem_identifiers com_identifiers''' p[0] = p[1] + [p[2]] def p_com_identifiers(p): '''com_identifiers : one_com_ident | few_com_ident''' p[0] = p[1] def p_one_com_ident(p): '''one_com_ident : identifier''' p[0] = [p[1]] def p_few_com_ident(p): '''few_com_ident : com_identifiers "," identifier''' p[0] = p[1] + [p[3]] #region attributes def p_attributes(p): '''attributes : one_attribute | few_attributes''' p[0] = p[1] def p_one_attribute(p): '''one_attribute : attribute''' p[0] = [p[1]] def p_few_attributes(p): '''few_attributes : attributes ";" attribute''' #p[0] = p[1] + [p[2]] p[0] = [] for head in p[1]: for end in p[3]: p[0] += [head + [end]] #endregion attributes def p_attribute(p): '''attribute : attr_ident | attr_str | attr_numb | attr_float''' p[0] = p[1] def p_attr_ident(p): '''attr_ident : identifier ":" sem_identifiers''' if not p[1] in concept: error_text = ERROR_INVALID_ATTR + ".\nValid attributes are: " + ', '.join(concept.keys()) + "." raise CWSSyntaxError(error_text, p, 1, p[1]) p[0] = [] for item in p[3]: if len(item) > 1 and concept[p[1]] != concept['tags']: raise CWSSyntaxError(ERROR_MULT_VALUE, p, 1, p[1]) else: val = item[0] if val in ['true', 'false']: if concept_type[p[1]] != 'bool': raise CWSSyntaxError(ERROR_INVALID_ATTR_PAR_TYPE, p, 3, p[3]) p[0] += [(concept[p[1]], val == 'true')] else: if concept_type[p[1]] != 'ident': raise CWSSyntaxError(ERROR_INVALID_ATTR_PAR_TYPE, p, 3, p[3]) pd = const.__dict__[p[1].replace("-", "_")] if not val in pd: error_text = ERROR_INVALID_ATTR_PAR + ".\nValid values are: " + ', '.join(pd.keys()) + "." raise CWSSyntaxError(error_text, p, 3, val) p[0] += [(concept[p[1]], pd[val])] def p_attr_str(p): '''attr_str : identifier ":" strings''' if not p[1] in concept and \ not p[1] in ['sufix', 'prefix']: raise CWSSyntaxError(ERROR_INVALID_ATTR, p, 1, p[1]) if len(p[3]) > 1: raise CWSSyntaxError(ERROR_MULT_VALUE, p, 1, p[1]) else: val = p[3][0] if p[1] == 'sufix': val = '0>' + val attr = concept['text'] elif p[1] == 'prefix': val = val + '<0' attr = concept['text'] else: attr = concept[p[1]] if concept_type[attr] != 'str': raise CWSSyntaxError(ERROR_INVALID_ATTR_PAR_TYPE, p, 3, p[3]) p[0] = [(attr, val)] def p_attr_float(p): '''attr_float : identifier ":" FLOAT''' if not p[1] in concept: raise CWSSyntaxError(ERROR_INVALID_ATTR, p, 1, p[1]) if concept_type[p[1]] != 'float': raise CWSSyntaxError(ERROR_INVALID_ATTR_PAR_TYPE, p, 3, p[3]) p[0] = [(concept[p[1]], p[3])] #region attr_number def p_attr_numb(p): '''attr_numb : identifier ":" numbers''' if not p[1] in concept: raise CWSSyntaxError(ERROR_INVALID_ATTR, p, 1, p[1]) if len(p[3]) > 1: raise CWSSyntaxError(ERROR_MULT_VALUE, p, 1, p[1]) else: val = p[3][0] if concept_type[p[1]] != 'int': raise CWSSyntaxError(ERROR_INVALID_ATTR_PAR_TYPE, p, 3, p[3]) p[0] = [(concept[p[1]], val)] def p_numbers(p): '''numbers : one_number | few_numbers''' p[0] = p[1] def p_one_number(p): '''one_number : NUMBER''' p[0] = [p[1]] def p_few_numbers(p): '''few_numbers : numbers NUMBER''' p[0] = p[1] + [p[2]] #endregion def p_error(p): global PRINT_TO_CONSOLE if PRINT_TO_CONSOLE: try: if not p is None: print_error(p.lineno, find_column(p.lexpos), "Syntax error at '%s'" % p.value) #global text #print(text) else: print_error(-1, -1, "Syntax error") #global text #print(text) except UnicodeEncodeError: print_error(p.lineno, find_column(p.lexpos), "Syntax error") raise Exception() glexer = lex.lex() yaccer = yacc.yacc() path = None def _parse_text(s, print_to_console): global PRINT_TO_CONSOLE PRINT_TO_CONSOLE = print_to_console global Params Params.prev = None Params.text = s res = None try: global glexer, yaccer lexer = glexer.clone() lexer.lineno = 1 res = yaccer.parse(s, lexer=lexer, tracking=PRINT_TO_CONSOLE) except Exception: if PRINT_TO_CONSOLE: print("WARNING: internal CWS compiler error") return None return res def parse(s, print_to_console): global Params Params.path = None return _parse_text(s, print_to_console) def _read_file(file_path): try: f = open(file_path, encoding = 'utf-8') s = f.read() except IOError: print("can't open file '" + file_path + "'") finally: f.close() return s def _parse_file(_path, print_to_console=True): global Params Params.path = _path return _parse_text(_read_file(Params.path), print_to_console) def parse_file(_path, _to_ipa, print_to_console=True): global Params Params.funcs = {} Params.to_ipa = _to_ipa return _parse_file(_path, print_to_console) def update_dict(c, b): a = deepcopy(c) for key in b: if key in a: a[key] += b[key] if type(b[key]) == list else [b[key]] else: a[key] = b[key] if type(b[key]) == list else [b[key]] return a Params = None def GetParams(): global Params return Params def SetParams(par): global Params Params = par class ParamsClass: def __init__(self, path, to_ipa): self.cws_files = {} self.find_all_cws(path) self.all_funcs = {} self.to_ipa = to_ipa self.funcs = {} self.attached_files = [] def find_all_cws(self, dirname, nme = ''): for f in os.listdir(dirname): fp = os.path.join(dirname, f) if os.path.isdir(fp): self.find_all_cws(fp, nme + f + '-') elif fp[-4:] == '.cws': self.cws_files[nme + f[:-4]] = fp import os def parse_files(path, _to_ipa, print_to_console=True): global Params Params = ParamsClass(path, _to_ipa) vocabulary, meanings = {}, {} for key in [x for x in Params.cws_files.keys()]: if key in Params.all_funcs: continue path = Params.cws_files[key] Params.funcs = {} Params.attached_files = [] tmp = _parse_file(path, print_to_console) vocabulary = update_dict(vocabulary, tmp[0]) meanings = update_dict(meanings, tmp[1]) return vocabulary, meanings
Python
# -*- coding: ISO-8859-5 -*- __author__="zoltan kochan" __date__ ="$28 june 2010 1:02:10$" # Standard states STATE_START = 1 STATE_END = 1000000 STATE_CONJ_A1, \ STATE_CONJ_A2, \ STATE_CONJ_A3, \ STATE_CONJ_A4 = range(-4, 0) STATE_CONJS = [ STATE_CONJ_A1, STATE_CONJ_A2, STATE_CONJ_A3, STATE_CONJ_A4, ] INDEFINITE = 100000 INHERIT_NAME = "inherit" INHERIT_VALUE = None #NEUTRAL_VALUE = "neutral"#0 NONE_VALUE = "none" def create_dict(list): d = {} for item in list: d[item] = item return d def create_dict_t(concept, list): d = {} for item in list: d[item] = item # d["@" + item] = (concept, item) ######## d["none"] = NONE_VALUE #d["@none"] = (concept, NONE) ########### d[INHERIT_NAME] = INHERIT_VALUE #d["@" + INHERIT_NAME] = (concept, INHERIT_VALUE) return d def is_terminalc(const): if const is None: raise Exception("Type can't be None") return const in terminal def is_nonterminalc(const): return const in nonterminal def is_prop(c): return c in concept terminal = create_dict([ "preposition", "auxiliary", "article", "quantifier", "noun", "pronoun", "adjective", "verb", "adverb", "numeral", "negative", "conjunction", "punctuation" ]) nonterminals = [ #"adverbial", "epithet", "preposition-phrase", "noun-phrase", "subject", "object", "verb-phrase", "numeral-phrase", "clause", "sentence", "paragraph", "text" ] concept = create_dict([ "personal-name", "use-of-to", "extra-1", "extra-2", "transcription", "text", "type", "truth", "quantity", "quantity-number", "quantity-case", "conj-type", "conj-str", "conj-function", "gender", "number", "participle", "voice", "mood", "persone", "clusivity", "modal", "poss-form", "clause-type", "pronoun-type", "adverb-type", "num-type", #"concept", "noun-type", "str-type", "position", "form", "object-persone", "subject-persone", "object-number", "object-difinity", "subject-number", "object-form", "subject-form", "stem", "lemma", "difinity", "case", "case-2", "tense", "transitivity", "aspect", "order-number", "real-number", "tags" ]) XFROM_FIRST,\ XFROM_LAST,\ XFROM_SUM,\ XFROM_NUMBER,\ XFROM_EVERY = range(1, 6) langs = [ "ukrainian", "hungarian", "russian", "rusyn", "english", ] tags = create_dict_t(concept["tags"], langs + \ [ "slang", "math", "archaic", "literary", "official", ]) personal_name = create_dict_t(concept["personal-name"], [ "first-name", "middle-name", "last-name", "surname", "given-name", "patronymic", "matronymic" ]) participle = create_dict_t(concept["participle"], [ "participle", "not-participle" ]) strtype = create_dict_t(concept["str-type"], [ "text", "digits", ]) sentence_end = create_dict( [ "point", "uncomplited", "question", "exclamation", "question-exclamation", "uncomplited-question", "uncomplited-exclamation", ]) sentence_type = create_dict( [ "declarative", "imperative", "interrogative", "exclamatory", ]) poss_form = create_dict_t(concept["poss-form"], [ "conjoint", "absolute", ]) transitivity = create_dict_t(concept["transitivity"], [ "intransitive", "transitive", #"ambitransitivity", = none ]) tense = create_dict_t(concept["tense"], [ "infinitive", "past", "present", "future", ]) aspect = create_dict_t(concept["aspect"], [ "indefinite", "continuous", #progressive "perfect", "perfect-continuous-durative", "perfect-continuous-not-durative", "indefinite-in-the-past", "perfect-in-the-past", "continuous-in-the-past" "prospective" ]) #http://en.wikipedia.org/wiki/grammatical_aspect #perfective: 'i struck the bell.' (a unitary event) #momentane: 'the mouse squeaked once.' (contrasted to 'the mouse squeaked/was squeaking.') #perfect (a common conflation of aspect and tense): 'i have arrived.' (brings attention to the consequences of a situation in the past) #recent perfect ~ after perfect: 'i just ate' or: 'i am after eating." (hiberno-english) #prospective (a conflation of aspect and tense): 'i am about to eat', 'i am going to eat." (brings attention to the anticipation of a future situation) #imperfective (an unfinished action, combines the meanings of both the progressive and the habitual aspects): 'i am walking to work' (progressive) or 'i walk to work every day' (habitual). #progressive ~ continuous: 'i am eating.' (action is in progress; a subtype of imperfective) #habitual: 'i used to walk home from work', 'i would walk home from work.' (past habitual) (a subtype of imperfective) #gnomic/generic: 'fish swim and birds fly' (general truths) #episodic: 'the bird flew' (non-gnomic) #continuative: 'i am still eating.' #inceptive ~ inchoative: 'i fell in love' #terminative ~ cessative: 'i finished my meal.' #defective : 'i almost fell.' #pausative: 'i stopped working for a while.' #resumptive: 'i resumed sleeping.' #punctual: 'i slept.' #durative: 'i slept and slept.' #delimitative: 'i slept for an hour.' #protractive: 'the argument went on and on.' #iterative: 'i read the same books again and again.' #frequentative: 'it sparkled', contrasted with 'it sparked'. or, 'i run around', vs. 'i run'. #experiential: 'i have gone to school many times.' #intentional: 'i listened carefully.' #accidental: 'i knocked over the chair.' #intensive: 'it glared.' #moderative: 'it shone.' #attenuative: 'it glimmered.' #aspect: #phase continue #iteration once #duration prolonged #telicity false voice = create_dict_t(concept["voice"], [ "active", "passive", ]) #what is: realis mood = create_dict_t(concept["mood"], [ "generic", "indicative", "mirative", "conditional", "subjunctive", "alethic", "deliberative", "hortative", "imperative", "jussive", "necessitative", "permissive", "precative", "prohibitive", "desiderative", "imprecative", "optative", "quotative-evidential", "sensory-evidential", "assumptive", "declarative", "deductive", "dubitative", "energetic", "hypothetical", "inferential", "renarrative", "interrogative", "potential", "presumptive", "speculative", ]) pronoun_type = create_dict_t(concept["pronoun-type"], [ "personal", "possessive", "reflexive", "reciprocal", "demonstrative", "interrogative", "conjunctive", "indefinite", "negative", "defining", "quantitative", ]) noun_type = create_dict_t(concept["noun-type"], [ "common", "proper", "abbreviation", ]) #for adverbs, pronouns and clauses adverb_types = \ [ "quality", "reason", "time", "repetition-and-frequency", "degree", "place", "manner", "association", "thing", "amount", "individual", ] #http://en.wikipedia.org/wiki/determiner_(linguistics) num_type = create_dict_t(concept["num-type"], [ "cardinal", "ordinal", ]) conj_type = create_dict_t(concept["conj-type"], [ "non-contrasting", #and, nor "contrasting", #but, yet "consequence", #so ########### ]) conj_str = create_dict_t(concept["conj-str"], [ "before", "among", "after", "before-among", "before-after", "before-among-after", "among-after", "nothing", ]) quantity = create_dict_t(concept["quantity"], [ "all", #всі/кожна "few", #кілька "many", #багато "no", #жодна/жодні "any", #будь-яка/будь-які "some" #якась/якісь/деякі ] ) clause_type = create_dict_t(concept["clause-type"], [ "principal", "subordinate", ]) clusivity = create_dict_t(concept["clusivity"], [ "exclusive", "inclusive" ]) gender = create_dict_t(concept["gender"], [ "lifeless", "vivacious", "divine", "masculine", "feminine", #"masculine_feminine", ]) ################################################### position = create_dict( [ "before", "before-1", "before-2", "before-3", "among", "after", ]) cases = [ "accusative", #házat "direct", "ergative", "intransitive", "nominative", "oblique", "ablative", #hazto'l (ha'ztul) "antessive", "dative", #indirect object, recipient, daval'nyj "distributive", #fejenk'ent "distributive-temporal", #naponta "essive", "essive-formal", #emberként "essive-modal", #emberül "formal", #emberk'eppen "genitive", "instructive", "instrumental", #valami -val -vel "instrumental-comitative", "ornative", "possessed", #(n''o) h'az'at (the opposite of possessive) "possessive", #john's, rodovyj "postpositional", "prepositional", "pertingent", "prolative", "prosecutive", "proximative", "sociative", #ruh'astul "temporal", "vialis", "adessive", #ha'zna'l "allative", #ha'zhoz "apudessive", "associative", "comitative", #emberrel "delative", #ha'zro'l "elative", #ha'zbo'l "exessive", "illative", #a fiu' megy a !ha'zba "inelative", "inessive", #ha'zban "inessive-time", #added by me!#added by me!#added by me!#added by me!#added by me!#added by me!#added by me!#added by me!#added by me!#added by me!#added by me! "intrative", "lative", "locative", "perlative", "subessive", "sublative", #ha'zra "superessive", #ha'zon "superlative", "terminative", #ha'zig (holnapig) "translative", #emberré (eredmény) "comparative", "equative", "aversive", "benefactive", "evitative", "abessive", "addirective", "adelative", "adverbial", ###### "caritive", "causal", "causal-final", "final", #emberért(ok, cél) "modal", "multiplicative", "partitive", "pegative", "privative", "postelative", "postdirective", "postessive", "separative", "subdirective", "vocative", "absolutive", ] ########################################################## #http://hu.wikipedia.org/wiki/esetek_a_magyar_nyelvben case = create_dict_t(concept["case"], cases) case_2 = create_dict_t(concept["case-2"], cases) quantity_case = create_dict_t(concept["quantity-case"], cases) adverb_type = create_dict_t(concept["adverb-type"], adverb_types) nonterminal = create_dict(nonterminals + adverb_types) from copy import copy type = copy(terminal) type.update(nonterminal) type.update(create_dict(cases)) type["epsilon"] = "epsilon" #type.update(concept) numbers = [ "uncountable", "singular", "dual", "trial", "quadral", "plural", ] number = create_dict_t(concept["number"], numbers) subject_number = create_dict_t(concept["subject-number"], numbers) object_number = create_dict_t(concept["object-number"], numbers) real_number = create_dict_t(concept["real-number"], numbers) quantity_number = create_dict_t(concept["quantity-number"], numbers) persones = [ "first", "second", "third", "infinitive", ] persone = create_dict_t(concept["persone"], persones) subject_persone = create_dict_t(concept["subject-persone"], persones) object_persone = create_dict_t(concept["object-persone"], persones) forms = [ "meek", #Юлічка "informal", #Юля "formal", #Юлія "insolent", #sértő, образливий ] form = create_dict_t(concept["form"], forms) subject_form = create_dict_t(concept["subject-form"], forms) object_form = create_dict_t(concept["object-form"], forms) difs = [ "difinite", "undifinite", "participle", "quantifier" ] difinity = create_dict_t(concept["difinity"], difs) object_difinity = create_dict_t(concept["object-difinity"], difs) modificators = [ terminal["preposition"], terminal["punctuation"], terminal["article"], terminal["quantifier"], terminal["auxiliary"], terminal["negative"] ] concept_type = { "personal-name": "ident", "use-of-to": "bool", "extra-1": "int", "extra-2": "int", "transcription": "str", "text": "str", "type": "ident", "truth": "float", "quantity": "ident", "quantity-number": "ident", "quantity-case": "ident", "conj-type": "ident", "conj-str": "ident", "conj-function": "ident", "gender": "ident", "number": "ident", "participle": "ident", "voice": "ident", "mood": "ident", "persone": "ident", "clusivity": "ident", "modal": "bool", "poss-form": "ident", "clause-type": "ident", "pronoun-type": "ident", "adverb-type": "ident", "num-type": "ident", "noun-type": "ident", "str-type": "ident", "position": "ident", "form": "ident", "object-persone": "ident", "subject-persone": "ident", "object-number": "ident", "object-difinity": "ident", "subject-number": "ident", "object-form": "ident", "subject-form": "ident", "stem": "str", "lemma": "str", "difinity": "ident", "case": "ident", "case-2": "ident", "tense": "ident", "transitivity": "ident", "aspect": "ident", "order-number": "int", "real-number": "ident", "tags": "ident", } def eq(a, b): #print(a, b) return a == b or \ a == INHERIT_VALUE or \ b == INHERIT_VALUE #a == INHERIT_VALUE and b != NONE_VALUE or \ #b == INHERIT_VALUE and a != NONE_VALUE def eqx(name, a, b): return eq(a.attr(name), b.attr(name)) neq = lambda a, b: not eq(a, b) #повертає істину, коли a чи b рівне value #def omega(name, a, b, value): # if a.attr(name) == None and b.attr(name) == None: # return False # if a.attr(name) != None: # return a.attr(name) == value # return b.attr(name) == value def preqconst(name, a, c): if a.attr(name) == None: a.attr(name, c) return True return eq(a.attr(name), c)
Python
__author__="zoltan kochan" __date__ ="$12 лют 2011 14:00:29$"
Python