def sell(self,player): """ Display the list of items in the inventory to sell """ while 1: common.version() print "Shop - Sell items ("+str(player.pocket)+"G)\n" for i in range(len(player.inventory)):print str(i+1)+".- "+player.inventory[i].name+" ("+str(round(player.inventory[i].price/self.pricecalc(player)))+"G)" print "--" print "0.- Back" print "\n->", try: sellmenuc=common.getch() if sellmenuc=="0": print "Nothing else? I can pay you with roaches!" common.getch() break player.pocket+=round(player.inventory[int(sellmenuc)-1].price/self.pricecalc(player)) player.totalgld+=round(player.inventory[int(sellmenuc)-1].price/self.pricecalc(player)) player.totalsll+=1 self.forsale.append(copy.copy(player.inventory[int(sellmenuc)-1])) del player.inventory[int(sellmenuc)-1] self.keeper.rel+=1 print random.choice(vendordata["okmsg"]) common.getch() except (ValueError, IndexError): pass
def testm(): """ Test menu """ while 1: common.version() print "Test utilities\n" print "1.- Test character sheet" print "2.- Test combat system" print "3.- Test vendor" print "4.- Test parser" print "5.- Test chat" print "6.- Test generator" print "---" print "0.- Go back" testmen=common.getch() if testmen=="1": testcharsh() if testmen=="2": testfight() if testmen=="3": testvend() if testmen=="4": testparse() if testmen=="5": testchat() if testmen=="6": testgen() if testmen=="0": break
def crawlingh(): """ description of the crawling screen elements """ common.version() print "Help - Using kirino - crawling screen (1/2)\n" print "The crawling screen is where most of the action happens. It gives you information about you and the environment.\n" print "From top to bottom, you can see:" print "minimap; floor and location, level, race and class; experience and gold." print "HP, MP, primary and secondary attributes, including the attribute boost from items." print "keys available. They can be configured in the option menu\n" print "press any key to continue" common.getch() common.version() print "Help - Using kirino - crawling screen (2/2)\n" print "The minimap is composed by ascii characters:\n" print "8 - your current position" print "# - A rock tile. You can't walk through" print ". - A floor tile. These are empty" print "_ - A trap you have stepped on previously\n" print "$ - Money. Walk over this tile to pick it up" print "/ - Item. Walk over to pick it up\n" print "p - Peddler. They appear on random floors and they allow you to buy and sell things" print "i - Zombie\n" print "A - Stairs up. This is where you start on a level" print "X - Floor exit. Move here to go to the the next floor\n" print "press any key to go back" common.getch()
def mainmenu(): """ Main menu function. Loads the configuration file and enters the menu loop. """ #Main menu while 1: common.version() print "Main menu\n" print "%i.- Play" %(1) print "%s.- Quick play\n" %(2) print "%s.- Credits" %(4) #print "%s.- Help" %(9) print "%s.- Exit\n->" %(0) menu=common.getch() if menu in ["1","2"]: launch.setup(int(menu)-1) launch.crawl() elif menu=="4": scroll(15) #if menu=="9": help() elif menu=="0": print "Close kirino (y/n)?" if common.getch()=="y": os.system('clear') exit()
def showachievements(player): """ Shows a list of completed achievements. """ common.version() print "%s - Character sheet - Achievements\n" %(player.name) print "Exploration" tfl=player.totalfl floors=4 if tfl>=500 else 3 if tfl>=250 else 2 if tfl>=100 else 1 if tfl>=10 else 0 print "Elevator",["0/4", "1/4", "2/4", "3/4", "4/4"][floors] tst=player.steps steps=4 if tst>=10000 else 3 if tst>=5000 else 2 if tst>=1000 else 1 if tst>=500 else 0 print ["0/4", "1/4", "2/4", "3/4", "4/4"][steps] print "\nCombat" kills=4 if tst>=500 else 3 if tst>=250 else 2 if tst>=100 else 1 if tst>=10 else 0 print ["0/4", "1/4", "2/4", "3/4", "4/4"][kills] traps=4 if tst>=100 else 3 if tst>=50 else 2 if tst>=20 else 1 if tst>=5 else 0 print ["0/4", "1/4", "2/4", "3/4", "4/4"][traps] print "\nItems" picks=4 if tst>=100 else 3 if tst>=50 else 2 if tst>=20 else 1 if tst>=5 else 0 print ["0/4", "1/4", "2/4", "3/4", "4/4"][picks] destroys=4 if tst>=100 else 3 if tst>=50 else 2 if tst>=20 else 1 if tst>=5 else 0 print ["0/4", "1/4", "2/4", "3/4", "4/4"][destroys] enchants=4 if tst>=100 else 3 if tst>=50 else 2 if tst>=20 else 1 if tst>=5 else 0 print ["0/4", "1/4", "2/4", "3/4", "4/4"][enchants] print "\nEconomy" gold=4 if tst>=10000 else 3 if tst>=5000 else 2 if tst>=2500 else 1 if tst>=1000 else 0 print ["0/4", "1/4", "2/4", "3/4", "4/4"][gold] common.getch()
def newgame(quick=0): """ This function displays the menu to create a new character. Receives an optionanl quick parameter. if 1, it generates a 40x40 dungeon and a random player. """ cfg=config.config() #If quick is 1, generate everything randomly if quick: dung=dungeon.dungeon(50,50,1) hero=player.player() hero.enter(dung) #If not, go through the usual process elif not quick: while 1: #purge() try: common.version() print "New game [1/5] Dungeon size\n~40x40 recommended\n" xsize=int(raw_input("Horizontal size: ")) ysize=int(raw_input("Vertical size: ")) if xsize<40 or ysize<20: print "Minimum size 40x20" else: print "%ix%i dungeon created"%(xsize,ysize) common.getch() break except ValueError: pass
def sell(vendor,player): """ Display the list of items in the inventory to sell """ while 1: common.version() print "Shop - Sell items (%iG)\n"%player.pocket for i,j in enumerate(player.inventory): print "%i.- %s (%iG)"%(i, j.name, round(player.inventory[i].price/vendor.pricecalc(player))) print "--\n0.- Back\n->", try: sellmenuc=common.getch() if sellmenuc=="0": print "Nothing else? I can pay you with roaches!" common.getch() break try: choice=int(sellmenuc) except: pass player.pocket+=round(player.inventory[choice-1].price/vendor.pricecalc(player)) player.totalgld+=round(player.inventory[choice-1].price/vendor.pricecalc(player)) player.totalsll+=1 vendor.forsale.append(copy.copy(player.inventory[choice-1])) del player.inventory[choice-1] vendor.keeper.rel+=1 print random.choice(msg.okay) common.getch() except (ValueError, IndexError): pass
def keyhelp(): """ Displays all the keys that can be used while crawling and their function. """ cfg=config.config() common.version() print "Key help\n" print "Movement\n" print " "+cfg.northwest+" "+cfg.north+" "+cfg.northeast print " \|/" print " "+cfg.west+"-X-"+cfg.east print " /|\ " print " "+cfg.southwest+" "+cfg.south+" "+cfg.southeast print "Next floor: "+cfg.nextf+"\n" print "Inventory\n" print "Belt item 1: "+cfg.quick1 print "Belt item 2: "+cfg.quick2 print "Belt item 3: "+cfg.quick3+"\n" print "Actions\n" print "Show map: "+cfg.showmap print "Input mode: "+cfg.console print "Character sheet: "+cfg.charsh print "Options menu: "+cfg.opt print "Quit: "+cfg.quit print "Report dungeon: "+cfg.report+"\n" print "Press any key to continue" common.getch()
def parserh(): """ Information about the word parser """ common.version() print "Help - Using kirino - Word parser\n" print "Kirino has a very simple word parser that processes basic instructions, such as move, look, hit and such" print "The parser needs, however, certain syntax requirements in the sentences that are passed to it\n" print "First, the first word must be a verb. 'Go north' is an accepted expression, while 'I want to go north' it's not." print "Second, the simpler the sentences are, the better. 'Drop sword' will have the same effect as 'Drop sword from inventory to the ground'." print "Third, some of the words in a sentence can be ignored. The parser does not analyze the full sentence, it only examines the first word and processes the rest accordingly.\n" print "press any key to go back" common.getch()
def about(): """ Gives information about the game """ common.version() print "Help - About kirino" print "" print "This is kirino, a console-based dungeon crawler\n" print "If you have played nethack, you should already be familiar with the mechanics. If you haven't it may look confusing at first due to the text-only nature of it, but you will probably get used to it soon as it is not very different from similar 3D games.\n" print "The goal of the game is to crawl through as many dungeon floors as possible, collecting loot and money. If your HP reaches zero, you will die and the game will end. As simple as that!\n" print "Please note that this is currently in a very early development phase and some basic features may not be implemented yet." print "If you have any suggestions or you want to report a bug or weird behaviour, feel free to do it using github issues at https://github.com/Achifaifa/kirino or contacting me at twitter (@Achifaifa) or via email (achi[at]hush[dot]ai)\n" raw_input("Go back")
def introh(): """ Small introduction to the game and basic controls """ common.version() print "Help - Using kirino - General introduction\n" print "Welcome to kirino!" print "kirino is a basic console-based dungeon crawler. The main goal is to survive for as long as possible while crawling through endless dungeons.\n" print "To start a game, select 'new game' in the main menu, and then input the size of the dungeon you would like to play in." print "After being prompted for your name, the game will begin and you will find yourself in a randomly generated dungeon. Your race and class will be randomly chosen so you don't lose any time thinking about it ;)" print "Crawl through the dungeon, grab the loot, kill the monsters (soon) and locate the exit to the next floor!" print "If you have played any kind of RPG game before, all the elements in the screen will look familiar to you. If you are totally lost, feel free to try the tutorial out." print "For information on specific functions, please check the rest of the help\n" raw_input("Go back")
def buypot(self,player): """ Sells potions to the player. Three random potions are generated by the vendor. """ while 1: common.version() print "Shop - Buy potions (%iG)\n"%player.pocket for i in range(len(self.potforsale)): print str(i+1)+".- "+self.potforsale[i].name+" ("+str(round(self.pricecalc(player)*self.potforsale[i].price))+"G)" print "--" print "0.- Back" print "\n->", buypotmenu=common.getch() if buypotmenu=="0": print "Nice doing business with you!" common.getch() break try: if len(self.potforsale)!=0: if player.pocket>=round(self.pricecalc(player)*self.potforsale[int(buypotmenu)-1].price): if player.belt[0].name=="--EMPTY--": player.belt[0]=copy.copy(self.potforsale[int(buypotmenu)-1]) elif player.belt[1].name=="--EMPTY--": player.belt[1]=copy.copy(self.potforsale[int(buypotmenu)-1]) elif player.belt[2].name=="--EMPTY--": player.belt[2]=copy.copy(self.potforsale[int(buypotmenu)-1]) elif player.belt[3].name=="--EMPTY--": player.belt[3]=copy.copy(self.potforsale[int(buypotmenu)-1]) elif player.belt[3].name=="--EMPTY--": player.belt[3]=copy.copy(self.potforsale[int(buypotmenu)-1]) elif player.belt[3].name=="--EMPTY--": player.belt[3]=copy.copy(self.potforsale[int(buypotmenu)-1]) player.pocket-=self.potforsale[int(buypotmenu)-1].price player.totalspn+=self.potforsale[int(buypotmenu)-1].price del self.potforsale[int(buypotmenu)-1] self.keeper.rel+=1 print random.choice(vendordata["okmsg"]) player.totalbuy+=1 common.getch() else: print random.choice(vendordata["failmsg"]) common.getch() except (ValueError,IndexError): pass
def optmenu(self): """ Player options menu """ coptmen=-1 while coptmen!="0": common.version() print "%s - Character sheet \n"%(self.name) print "1.- Change name" print "---" print "0.- Back" print "->", coptmen=common.getch() if coptmen=="1": self.name=raw_input("New name? ") if coptmen=="0": break
def main(): os.chdir(os.path.join(os.path.dirname(__file__), os.pardir, 'skia')) version = common.version() build_type = common.build_type() machine = common.machine() system = common.system() classifier = common.classifier() os.chdir(os.pardir) zip = 'Skia-' + version + '-' + system + '-' + build_type + '-' + machine + classifier + '.zip' if not os.path.exists(zip): print('Can\'t find "' + zip + '"') return 1 headers = common.github_headers() try: resp = urllib.request.urlopen(urllib.request.Request('https://api.github.com/repos/olonho/skia-build/releases/tags/' + version, headers=headers)).read() except urllib.error.URLError as e: data = '{"tag_name":"' + version + '","name":"' + version + '"}' resp = urllib.request.urlopen(urllib.request.Request('https://api.github.com/repos/olonho/skia-build/releases', data=data.encode('utf-8'), headers=headers)).read() upload_url = re.match('https://.*/assets', json.loads(resp.decode('utf-8'))['upload_url']).group(0) print('Uploading', zip, 'to', upload_url) headers['Content-Type'] = 'application/zip' headers['Content-Length'] = os.path.getsize(zip) with open(zip, 'rb') as data: urllib.request.urlopen(urllib.request.Request(upload_url + '?name=' + zip, data=data, headers=headers)) return 0
def testgen(): """ Test environment for the dungeon generator. It generates a dungeon and displayes the full map in the screen """ while 1: os.system('clear') common.version() print "Dungeon generator test. 0 to exit, other key to generate dungeon" try: new=dungeon.dungeon(40,40,1) new.map() except: print "\n\nError" bla=common.getch() if bla=="0": break
def saveh(): """ Information about saving and loading characters and configuration """ common.version() print "Help - Using kirino - Saving and loading\n" print "-Saving and loading characters" print " Once you are done playing, you may want to save your character for the next time. To do that, go to the character sheet and select 'save'." print " All the information will be saved in a file located in ./player/save. This information includes things like your name, level, attributes and gold in your stash, but (at the moment) it does not save your inventory data, so all your items will be lost." print " Saving a character will overwrite anything contained in the save file, so make sure you make a manual backup if you want one." print " To load a previously saved character, simply select 'load' from the character sheet menu. The character will be replaced with the data you previously saved.\n" print " kirino also has an autosave function. If enabled, it will automatically save your character every time you progress to the next dungeon. To enable it, simply go to the game options menu and switch it to [on]\n" print "-Saving and loading configuration" print "Most of the controls can be customised. They are saved automatically to a text file in ./player/config. The configuration from this text file is automatically loaded when kirino starts." print "The options will save automatically (overwriting the previous file) whenever you exit an option menu\n" print "press any key to go back" common.getch()
def charh(): """ Information about the character sheet and the options in it """ common.version() print "Help - Using kirino - Character sheet\n" print "The character sheet is where you can manage your character.\n" print "It shows the same information as the crawl screen, and it gives you options to:\n" print "-Spend your points to improve your attributes" print " Simply go to the point spending menu. You will see all your attributes, your attribute levels and how much it will cost you to upgrade a certain attribute.\n" print "-Manage your inventory" print " See 'inventory' on the menu\n" print "-Configure your character" print " Select the characteristic you wish to modify and input the new value\n" print "-Save and load your character" print " See 'saving and loading'\n" print "press any key to go back" common.getch()
def buypot(self,player): """ Sells potions to the player. Three random potions are generated by the vendor. """ while 1: common.version() print "Shop - Buy potions (%iG)\n"%player.pocket for i,j in enumerate(self.potforsale): print "%i.- %s (%iG)"%(i, j.name, round(self.pricecalc(player)*self.potforsale[i].price)) print "--" print "0.- Back" print "\n->", buypotmenu=common.getch() if buypotmenu=="0": print "Nice doing business with you!" common.getch() break try: if len(self.potforsale): if player.pocket>=round(self.pricecalc(player)*self.potforsale[int(buypotmenu)-1].price): if player.belt[0].name=="--EMPTY--": player.belt[0]=copy.deepcopy(self.potforsale[int(buypotmenu)-1]) elif player.belt[1].name=="--EMPTY--": player.belt[1]=copy.deepcopy(self.potforsale[int(buypotmenu)-1]) elif player.belt[2].name=="--EMPTY--": player.belt[2]=copy.deepcopy(self.potforsale[int(buypotmenu)-1]) elif player.belt[3].name=="--EMPTY--": player.belt[3]=copy.deepcopy(self.potforsale[int(buypotmenu)-1]) elif player.belt[4].name=="--EMPTY--": player.belt[4]=copy.deepcopy(self.potforsale[int(buypotmenu)-1]) elif player.belt[5].name=="--EMPTY--": player.belt[5]=copy.deepcopy(self.potforsale[int(buypotmenu)-1]) player.pocket-=self.potforsale[int(buypotmenu)-1].price player.totalspn+=self.potforsale[int(buypotmenu)-1].price del self.potforsale[int(buypotmenu)-1] self.keeper.rel+=1 print random.choice(msg.success) player.totalbuy+=1 common.getch() else: print random.choice(msg.fail) common.getch() except (ValueError,IndexError): pass
def help(): """ Help main menu. Gives access to the tutorial, descriptions and such """ while 1: os.system('clear') common.version() print "Help\n" print "1.- About this game" print "2.- Using kirino" print "3.- Tutorial" print "---" print "0.- Back\n" print "->", helpmen=common.getch() if helpmen=="2": funchelp() if helpmen=="1": about() if helpmen=="3": tutorial() if helpmen=="0": break else: pass
def charsheet(self): """ Character sheet. Main menu to edit, view and configure characters and player options """ menu=0 while 1: self.secondary() common.version() print "%s - Character sheet\n" %(self.name) print "Level %i %s %s" %(self.lv,self.race,self.charclass) if self.lv==1: print "%i/5 xp, %i points" %(self.exp,self.points) if self.lv>1: print "%i/%i xp, %i points" %(self.exp,3*self.lv+(2*(self.lv-1)),self.points) print "%i floors explored" %(self.totalfl) print "Stomach is %i%% full\n" %(self.stomach) playerattrs(self) print "\n1.- Spend points" print "2.- Inventory" print "3.- Character options" print "4.- Stats" print "5.- Achievements" print "\n8.- Save" print "9.- Load" print "\n0.- Exit" print "->", menu=common.getch() if menu=="1": spend() elif menu=="2": invmenu() elif menu=="3": optmenu() elif menu=="4": statmenu() elif menu=="5": achievements() elif menu=="8": print "saving... "+self.save() common.getch() elif menu=="9": print "loading... "+self.load() common.getch() elif menu=="0": break pass
def chat(dude,player): """ Starts a ""conversation"" with an NPC or other ""intelligent"" creature. Needs an object, with information that can be used (NPC/mob) and a player object """ common.version() os.system('clear') print "Conversation with vendor - "+dude.name print "Type 'exit' to exit" if dude.rel<=10: print "\nHello stranger!" if dude.rel>10: print "\nHello "+player.name while 1: conv=raw_input(">>>") if conv=="exit": break else: print parseconv(conv,dude,player)
def buyitem(vendor,player): """ Display the list of items available for buying from the vendor """ while 1: common.version() print "Shop - Buy items (%iG)\n" %player.pocket for i in range(len(vendor.forsale)): print str(i+1)+".- "+vendor.forsale[i].name+" ("+str(round(vendor.pricecalc(player)*vendor.forsale[i].price))+"G)" print "--" print "0.- Back" print "\n->", try: buymenuc=common.getch() if buymenuc=="0": print "Nice doing business with you!" common.getch() break try: choice=int(buymenuc) except: pass itemprice=round(vendor.pricecalc(player)*vendor.forsale[choice-1].price) if player.pocket>itemprice: player.pocket-=itemprice player.totalspn+=itemprice if player.pickobject(vendor.forsale[choice-1]): print random.choice(msg.okay) vendor.keeper.rel+=1 del vendor.forsale[choice-1] player.totalbuy+=1 common.getch() else: print random.choice(msg.fail) common.getch() else: print random.choice(msg.fail) common.getch() except (ValueError, IndexError): pass
def itemh(): """ Information about items, inventory, enchanting, etc """ common.version() print "Help - Using kirino - Items and inventory\n" print "Once in the inventory menu, you can equip, unequip, destroy and enchant items\n" print "-Equipping, unequipping and destroying items" print " To equip an item, simply write the inventory numbers it is assgined to (1-9) and the item will be equipped, automatically returning to your inventory any item you previously had in the slot it is assigned to" print " To unequip an item, select 'unequip item' (Default a) and then write the equip number it has assigned (1-11). The item will then return to your inventory" print " Destroying items is easy: Select the option in the menu (Default q) and then select the item you wish to destroy. The item must be in your inventory\n" print "-Echanting items" print " To enchant an item, select enchant item (Default w) and then select an item in your inventory. Enchanting an item costs the current item price and doubles its price (minimum 1G)" print " Enchanting an item increases its attack or defense rating by 1 and adds random attribute boosts. Items can only be enchanted up to level 10 (item +10)" print " Enchanting an item has a failure rate of 1%. If the enchanting fails, the item is destroyed.\n" print "-Consumable items" print " There are also items you can use during your adventure, such as potions, tomes and attack boosters." print " This items are not found in the floor and they must be purchased from sellers." print " To use these items, you only have to press the quick use keys you have specified while crawling." print "press any key to go back" common.getch()
def options(self,restricted): """ Game options menu. This allows modification of the general options, such as key mappings, autosave, etc. If the restricted parameter is 1, it hides the options that should not be changed during the game (fog, etc) """ global autosave global fog while 1: common.version() print "Options \n" if not self.autosave: print "1.- Autosave [off]" if self.autosave: print "1.- Autosave [on]" print " Saves the character between floors" if not self.fog and not restricted: print "2.- Fog [off]" if self.fog and not restricted: print "2.- Fog [on]" if restricted and self.fog: print "2.- Fog [on] [Locked]" if restricted and not self.fog: print "2.- Fog [off] [Locked]" print " Hides the dungeon out of view range" print "3.- Game over message: %s"%(self.gomsg) print " Message displayed when the game ends" print "4.- Key mapping \n" print "--" print "9.- Help" print "0.- Go back" print "->", opmen=common.getch() if opmen=="1": self.autosave=not self.autosave if opmen=="2" and not restricted: self.fog=not self.fog if opmen=="3": self.gomsg=raw_input("New message?>") if opmen=="4": self.keymap(restricted) if opmen=="9": help.help() if opmen=="0": self.saveoptions() break
def showstats(player): """ Displays character stats on screen """ avgdmg=round(player.totaldmg/player.totalhits) if player.totalhits else 0 hitrate=str(int(round((100*player.totalhits)/player.totalatks))) if player.totalatks else "--" common.version() print "%s - Character sheet - Stats\n" %(player.name) print "Exploration" print "Floors explored: %i" %player.totalfl print "Steps: %i" %player.steps print "\nCombat" print "Attacks launched: %i" %player.totalatks print "Hits: %i (%i%%)"%(player.totalhits, hitrate) print "Total damage: %i" %(layer.totaldmg) print "Average damage: %i" %avgdmg print "Total damage taken: %i" %player.totalrcv print "Traps stepped on: %i" %player.totaltrp print "Mobs killed: %i" %player.kills print "Max hit damage: %i" %player.maxdmg print "\nItems" print "Items picked: %i" %player.itemspck print "Items destroyed: %i" %player.itemsdst print "Items enchanted: %i" %player.itemsenc print "Maximum enchant lv: %i" %player.maxench print "Potions taken: %i" %player.totalpot print "\nEconomy" print "Gold earned: %i" %player.totalgld print "Gold spent: %i" %player.totalspn print "Items sold: %i" %player.totalsll print "Items bought: %i" %player.totalbuy common.getch()
def commerce(self,player): while 1: common.version() print "Shop\n" print random.choice(vendordata["welcomemsg"]) print "\n1.- Sell" print "2.- Buy items" print "3.- Buy food/potions" print "4.- Chat" print "--" print "0.- Back" print "\n->", commenu=common.getch() if commenu=="1":self.sell(player) if commenu=="2":self.buyit(player) if commenu=="3":self.buypot(player) if commenu=="4":parser.chat(self.keeper,player) if commenu=="0": print random.choice(vendordata["byemsg"]) common.getch() break else: pass
def main(): headers = common.github_headers() version = common.version() build_type = common.build_type() try: resp = urllib.request.urlopen(urllib.request.Request('https://api.github.com/repos/JetBrains/skia-build/releases/tags/' + version, headers=headers)).read() artifacts = [x['name'] for x in json.loads(resp.decode('utf-8'))['assets']] zip = 'Skia-' + version + '-' + common.system + '-' + build_type + '-' + common.machine + common.classifier() + '.zip' if zip in artifacts: print('> Artifact "' + zip + '" exists, stopping') return 1 return 0 except urllib.error.URLError as e: return 0
def funchelp(): """ Gives information about specific game functions and options """ while 1: common.version() print "Help - Using kirino\n" print "1.- General introduction" print "2.- Crawling screen" print "3.- Character sheet" print "4.- Items and inventory" print "5.- Saving and loading" print "6.- Word parser" print "---" print "0.- Back" print "->", fhmen=common.getch() if fhmen=="1": introh() if fhmen=="2": crawlingh() if fhmen=="3": charh() if fhmen=="4": itemh() if fhmen=="5": saveh() if fhmen=="6": parserh() if fhmen=="0": break
def buyit(self,player): """ Display the list of items available for buying from the vendor """ while 1: common.version() print "Shop - Buy items ("+str(player.pocket)+"G)\n" for i in range(len(self.forsale)): print str(i+1)+".- "+self.forsale[i].name+" ("+str(round(self.pricecalc(player)*self.forsale[i].price))+"G)" print "--" print "0.- Back" print "\n->", try: buymenuc=common.getch() if buymenuc=="0": print "Nice doing business with you!" common.getch() break if player.pocket>=round(self.pricecalc(player)*self.forsale[int(buymenuc)-1].price): player.pocket-=(round(self.pricecalc(player)*self.forsale[int(buymenuc)-1].price)) player.totalspn+=(round(self.pricecalc(player)*self.forsale[int(buymenuc)-1].price)) if player.pickobject(self.forsale[int(buymenuc)-1]): print random.choice(vendordata["okmsg"]) self.keeper.rel+=1 del self.forsale[int(buymenuc)-1] player.totalbuy+=1 common.getch() else: print random.choice(vendordata["failmsg"]) common.getch() else: print random.choice(vendordata["failmsg"]) common.getch() except (ValueError, IndexError): pass
def main(): """Process command line args.""" clrm.init() args = sys.argv[1:] if args: args_set = set(args) max_args = 2 # -q and one other doc_arg_set = set(['-d', '--doc']) help_arg_set = set(['-h', '--help']) license_arg_set = set(['-l', '--license']) quiet_arg_set = set(['-q', '--quiet']) reference_arg_set = set(['-r', '--reference']) version_arg_set = set(['-V', '--version']) legal_args_set = (doc_arg_set | help_arg_set | license_arg_set | quiet_arg_set | reference_arg_set | version_arg_set) # if any wrong arg, too many args or (max args and -q not among them) if (args_set - legal_args_set or len(args) > max_args or (len(args) == max_args and not (quiet_arg_set & args_set))): print(common.banner()) print(clrm.Fore.RED + lcl.WRONG_ARG + '\n') print(clrm.Fore.RESET + common.usage()) else: if not (quiet_arg_set & args_set): print(common.banner()) if doc_arg_set & args_set: get_app_info() update_doc() elif license_arg_set & args_set: print(common.license_()) elif help_arg_set & args_set: print(common.usage()) elif reference_arg_set & args_set: get_app_info() update_ref() elif version_arg_set & args_set: print(lcl.VERSION, common.version()) else: # only -q create_setup() else: print(common.banner()) create_setup()
def main(): os.chdir(os.path.join(os.path.dirname(__file__), os.pardir, 'skia')) version = common.version() build_type = common.build_type() is_android = common.is_android() os.chdir(os.pardir) zip = common.archive_name() if zip is None: print('--android was defined but --android-target-cpu wasn\'t.') if not os.path.exists(zip): print('Can\'t find "' + zip + '"') return 1 headers = common.github_headers() try: resp = urllib.request.urlopen( urllib.request.Request( 'https://api.github.com/repos/JetBrains/skia-build/releases/tags/' + version, headers=headers)).read() except urllib.error.URLError as e: data = '{"tag_name":"' + version + '","name":"' + version + '"}' resp = urllib.request.urlopen( urllib.request.Request( 'https://api.github.com/repos/JetBrains/skia-build/releases', data=data.encode('utf-8'), headers=headers)).read() upload_url = re.match('https://.*/assets', json.loads( resp.decode('utf-8'))['upload_url']).group(0) print('Uploading', zip, 'to', upload_url) headers['Content-Type'] = 'application/zip' headers['Content-Length'] = os.path.getsize(zip) with open(zip, 'rb') as data: urllib.request.urlopen( urllib.request.Request(upload_url + '?name=' + zip, data=data, headers=headers)) return 0
def start(argv): """Print banner, read/create data & log file and process args.""" clrm.init() print(common.banner()) childs, last_upd = shrd.open_create_datafile() arg0 = argv[0] if arg0 in ['-a', '--auto']: auto_upd(childs, last_upd) elif arg0 in ['-h', '--help']: print(common.usage()) elif arg0 in ['-l', '--license']: print(common.license_()) elif arg0 in ['-V', '--version']: print(lcl.VERSION, common.version()) else: man_upd(argv, childs, last_upd) sys.exit(0) # ToDo: other return codes
def start(argv): """Print banner and process args.""" ansi.init() print(common.banner()) if not argv: print_ips() else: arg0 = argv[0] if arg0 in ['-h', '--help']: print(common.usage()) elif arg0 in ['-l', '--license']: print(common.license_()) elif arg0 in ['-p', '--pause']: print_ips() input(lcl.PRESS_ANY_KEY) elif arg0 in ['-V', '--version']: print(lcl.VERSION, common.version()) else: print(ansi.Fore.RED + lcl.WRONG_ARG + arg0 + '\n') print(ansi.Fore.RESET + common.usage()) sys.exit(0) # ToDo: other return codes
def main(): headers = common.github_headers() version = common.version() build_type = common.build_type() try: resp = urllib.request.urlopen( urllib.request.Request( 'https://api.github.com/repos/JetBrains/skia-build/releases/tags/' + version, headers=headers)).read() artifacts = [ x['name'] for x in json.loads(resp.decode('utf-8'))['assets'] ] zip = common.archive_name() if zip is None: print('--android was specified but --android-target-cpu was not.') return -1 if zip in artifacts: print('> Artifact "' + zip + '" exists, stopping') return 1 return 0 except urllib.error.URLError as e: return 0
def main(): os.chdir(os.path.join(os.path.dirname(__file__), os.pardir, 'skia')) build_type = common.build_type() version = common.version() machine = common.machine() system = common.system() classifier = common.classifier() globs = [ 'out/' + build_type + '-' + machine + '/*.a', 'out/' + build_type + '-' + machine + '/*.lib', 'out/' + build_type + '-' + machine + '/icudtl.dat', 'include/**/*', 'modules/particles/include/*.h', 'modules/skottie/include/*.h', 'modules/skottie/src/*.h', 'modules/skottie/src/animator/*.h', 'modules/skottie/src/effects/*.h', 'modules/skottie/src/layers/*.h', 'modules/skottie/src/layers/shapelayer/*.h', 'modules/skottie/src/text/*.h', 'modules/skparagraph/include/*.h', 'modules/skplaintexteditor/include/*.h', 'modules/skresources/include/*.h', 'modules/sksg/include/*.h', 'modules/skshaper/include/*.h', 'modules/skshaper/src/*.h', 'modules/svg/include/*.h', 'src/core/*.h', 'src/gpu/gl/*.h', 'src/utils/*.h', 'third_party/externals/angle2/LICENSE', 'third_party/externals/angle2/include/**/*', 'third_party/externals/freetype/docs/FTL.TXT', 'third_party/externals/freetype/docs/GPLv2.TXT', 'third_party/externals/freetype/docs/LICENSE.TXT', 'third_party/externals/freetype/include/**/*', 'third_party/externals/icu/source/common/**/*.h', 'third_party/externals/libpng/LICENSE', 'third_party/externals/libpng/*.h', 'third_party/externals/libwebp/COPYING', 'third_party/externals/libwebp/PATENTS', 'third_party/externals/libwebp/src/dec/*.h', 'third_party/externals/libwebp/src/dsp/*.h', 'third_party/externals/libwebp/src/enc/*.h', 'third_party/externals/libwebp/src/mux/*.h', 'third_party/externals/libwebp/src/utils/*.h', 'third_party/externals/libwebp/src/webp/*.h', 'third_party/externals/harfbuzz/COPYING', 'third_party/externals/harfbuzz/src/*.h', 'third_party/externals/swiftshader/LICENSE.txt', 'third_party/externals/swiftshader/include/**/*', 'third_party/externals/zlib/LICENSE', 'third_party/externals/zlib/*.h', "third_party/icu/*.h" ] target = 'Skia-' + version + '-' + system + '-' + build_type + '-' + machine + classifier + '.zip' print('> Writing', target) with zipfile.ZipFile(os.path.join(os.pardir, target), 'w', compression=zipfile.ZIP_DEFLATED) as zip: dirs = set() for glob in globs: for path in pathlib.Path().glob(glob): if not path.is_dir(): for dir in parents(path): if not dir in dirs: zip.write(str(dir)) dirs.add(dir) zip.write(str(path)) return 0
#! /usr/bin/env python3 import common, os, re, subprocess, sys def update_version(major, minor, src): print(f"update_version: {major}.{minor} in {src}") with open(src, 'r') as f: contents = f.read() contents = re.sub(r"versionMajor\s+=\s+\d+;", f"versionMajor = {major};", contents) contents = re.sub(r"versionMinor\s+=\s+\d+;", f"versionMinor = {minor};", contents) with open(src, 'w') as f: f.write(contents) if __name__ == '__main__': os.chdir(common.root) (major, minor) = common.version().split(".") update_version(major, minor, 'FiraCode.glyphs') sys.exit(0)
print("npm_publish: Skip") @log_errors("update_homebrew") def update_homebrew(version): print("update_homebrew: Skip" ) # Update https://github.com/Homebrew/homebrew-cask-fonts @log_errors("update_scoop") def update_scoop(version): print( "update_scoop: Skip" ) # Update https://github.com/matthewjberger/scoop-nerd-fonts/blob/master/bucket/FiraCode.json @log_errors("update_google_fonts") def update_google_fonts(version): print("update_google_fonts: Skip") if __name__ == '__main__': os.chdir(common.root) version = common.version() package(version) github_release(version) npm_publish(version) update_homebrew(version) update_scoop(version) update_google_fonts(version) sys.exit(0)
def main(): os.chdir(os.path.join(os.path.dirname(__file__), os.pardir, 'skia')) build_type = common.build_type() version = common.version() is_android = common.is_android() target = common.archive_name() if target is None: print('--android was defined but --android-target-cpu wasn\'t.') return -1 if is_android: target_cpu = common.android_target_cpu() globs = [ 'out/' + build_type + '-android-' + target_cpu + '/*.a', 'out/' + build_type + '-android-' + target_cpu + '/*.lib', 'out/' + build_type + '-android-' + target_cpu + '/icudtl.dat', ] else: globs = [ 'out/' + build_type + '-' + common.machine + '/*.a', 'out/' + build_type + '-' + common.machine + '/*.lib', 'out/' + build_type + '-' + common.machine + '/icudtl.dat', ] globs += [ 'modules/particles/include/*.h', 'modules/skottie/include/*.h', 'modules/skottie/src/*.h', 'modules/skottie/src/animator/*.h', 'modules/skottie/src/effects/*.h', 'modules/skottie/src/layers/*.h', 'modules/skottie/src/layers/shapelayer/*.h', 'modules/skottie/src/text/*.h', 'modules/skparagraph/include/*.h', 'modules/skplaintexteditor/include/*.h', 'modules/skresources/include/*.h', 'modules/sksg/include/*.h', 'modules/skshaper/include/*.h', 'modules/skshaper/src/*.h', 'modules/svg/include/*.h', 'src/core/*.h', 'src/gpu/gl/*.h', 'src/utils/*.h', 'third_party/externals/angle2/LICENSE', 'third_party/externals/angle2/include/**/*', 'third_party/externals/freetype/docs/FTL.TXT', 'third_party/externals/freetype/docs/GPLv2.TXT', 'third_party/externals/freetype/docs/LICENSE.TXT', 'third_party/externals/freetype/include/**/*', 'third_party/externals/icu/source/common/**/*.h', 'third_party/externals/libpng/LICENSE', 'third_party/externals/libpng/*.h', 'third_party/externals/libwebp/COPYING', 'third_party/externals/libwebp/PATENTS', 'third_party/externals/libwebp/src/dec/*.h', 'third_party/externals/libwebp/src/dsp/*.h', 'third_party/externals/libwebp/src/enc/*.h', 'third_party/externals/libwebp/src/mux/*.h', 'third_party/externals/libwebp/src/utils/*.h', 'third_party/externals/libwebp/src/webp/*.h', 'third_party/externals/harfbuzz/COPYING', 'third_party/externals/harfbuzz/src/*.h', 'third_party/externals/swiftshader/LICENSE.txt', 'third_party/externals/swiftshader/include/**/*', 'third_party/externals/zlib/LICENSE', 'third_party/externals/zlib/*.h', "third_party/icu/*.h" ] print('> Writing', target) with zipfile.ZipFile(os.path.join(os.pardir, target), 'w', compression=zipfile.ZIP_DEFLATED) as zip: dirs = set() for glob in globs: for path in pathlib.Path().glob(glob): if not path.is_dir(): for dir in parents(path): if not dir in dirs: zip.write(str(dir)) dirs.add(dir) zip.write(str(path)) return 0
def definePage(c, config, receiver, path, message, duedate, subject, reference, i, logo=None): """ Args: config = config list, receiver = invoice receiver object path = path to output folder message = message to be attached to the invoice duedate = due date of the invoice as a string subject = subject line of the invoice reference = Reference number for the invoice i = index number for barcode logo = path to the logo file if spesified. Default None """ try: sg.theme(config[0]) #measurements leveys, korkeus = A4 transSizeX = leveys / 210 transSizeY = korkeus / 297 base = common.resource_path("Tilisiirto_pohja.jpg") margin = transSizeX * 27 margin2 = transSizeX * 119 margin3 = margin2 + transSizeX * 18 # Document settings c.setAuthor(config[2]) c.setTitle(subject) c.setSubject(subject) c.setCreator(("Haukiposti " + common.version())) if logo != "": c.drawImage(logo, 25, korkeus - 110, width=110, height=110, preserveAspectRatio=True) c.line(25, korkeus - 100, leveys - 25, korkeus - 100) c.drawImage(base, 0, 10, width=(transSizeX * 210), height=(transSizeY * 101.6), preserveAspectRatio=True) # bank transfer base c.setFont("Helvetica-Bold", 18) c.drawString(250, korkeus - 60, subject) c.setFont("Helvetica", 11) # TODO Saate m = c.beginText() m.setTextOrigin(25, korkeus - 135) newLines = message.split('\n') for item in newLines: line = common.markdownParserPDF(item, receiver) if line == -1: sg.PopupOK( "Viallinen muotoilu saatteessa. Tarkista, että suljet ja aloitat tagit oikein. Keskeytetään." ) return -1 logging.debug(line) if line == []: break elif len(line) == 2 and type(line[1]) == str: if line[0] == [False, False, False ] or line[0] == [False, False, True]: m.setFont("Helvetica", 12) elif line[0] == [True, False, False ] or line[0] == [True, False, True]: m.setFont("Helvetica-Bold", 12) elif line[0] == [False, True, False ] or line[0] == [False, True, True]: m.setFont("Helvetica-Oblique", 12) elif line[0] == [True, True, False ] or line[0] == [True, True, True]: m.setFont("Helvetica-BoldOblique", 12) m.textOut(line[1]) else: for text in line: if text[0] == [False, False, False ] or text[0] == [False, False, True]: m.setFont("Helvetica", 12) elif text[0] == [True, False, False ] or text[0] == [True, False, True]: m.setFont("Helvetica-Bold", 12) elif text[0] == [False, True, False ] or text[0] == [False, True, True]: m.setFont("Helvetica-Oblique", 12) elif text[0] == [True, True, False ] or text[0] == [True, True, True]: m.setFont("Helvetica-BoldOblique", 12) m.textOut(text[1]) m.moveCursor(0, 12) c.drawText(m) # Receiver information account = config[3].replace(' ', '') account = account[:4] + " " + account[4:8] + " " + account[ 8:12] + " " + account[12:16] + " " + account[16:] c.drawString(margin, getY(5), account) # receiver account number c.drawString(margin, getY(11), config[2]) # payment receiver c.setFontSize(15) c.drawString(margin2, getY(5), config[5]) # Payer information textObject = c.beginText() textObject.setTextOrigin(margin, getY(16)) textObject.setFont("Helvetica", 11) textObject.textLine( (receiver.firstname + " " + receiver.lastname)) # payer name if receiver.contact != "": textObject.textLine(receiver.contact) # payer contact, if any textObject.textLine(receiver.address) # payer address textObject.textLine((receiver.postalno + " " + receiver.city)) # payer postalno and city c.drawText(textObject) c.setFontSize(11) # Reference information c.drawString(margin2, getY(25), "Käytäthän maksaessasi viitenumeroa.") ref = reference[:5] + " " + reference[5:] c.drawString(margin3, getY(30), ref) c.drawString(margin3, getY(34), duedate) # Amount amount = None memberList = [config[4]] parser = csv.reader(memberList) memberString = [] for fields in parser: for field in fields: string = field.split(",") member = string[0] + ":" + string[1] memberString.append(member) for item in memberString: cl = item.split(':') if cl[0].lower() == receiver.membertype.lower(): if len(cl[1].split('.')) > 1: amount = cl[1] else: amount = cl[1] + ".00" if amount == None: amount = "" c.drawString((margin3 + transSizeX * 40), getY(34), amount) virtualbc, bc_img = createBarcode(reference, config[3], amount, duedate, i) c.setFontSize(9.4) c.drawString(37, 22 + transSizeY * 12, virtualbc) c.drawImage(bc_img, 30, 17, transSizeX * 105, transSizeY * 12, preserveAspectRatio=False) c.showPage() except Exception as e: logging.exception(e)
def stickersheet(path, receivers, paper, sx, sy, div, emailBool): """Makes a stickersheet. Args: path = Path to output folder receivers = list of receiver objects paper = paper size sx = number of stickers in x direction sy = number of stickers in y direction div = amount of empty space between stickers in mm in x direction Returns path to file on success, -1 if PermissionError, -2 if other error""" logging.info("Create stickersheet {0}, {1}, {2}, {3}, {4}, {5}".format( path, receivers, paper, sx, sy, div)) if paper == "A4": page = A4 leveys, korkeus = A4 transSizeX = leveys / 210 transSizeY = korkeus / 297 else: return -2 date = datetime.date.today().strftime("%d-%m-%Y") clock = time.strftime("%H-%M-%S") year = datetime.date.today().strftime("%Y") name = "Tarra-arkki_" + date + "_" + clock + ".pdf" pdfPath = os.path.join(path, name) c = canvas.Canvas(pdfPath, pagesize=page) # c.translate(leveys, korkeus) c.setSubject("Tarra-arkit") c.setCreator(("Haukiposti " + common.version())) stickerx = ((210 - ((sx - 1) * div)) / sx) * mm stickery = ((297 - sy) / sy) * mm totalPerPage = sx * sy marginx = 5 * mm marginy = 4 * mm div = div * mm # font if sx < 5: fontsize = 12 elif sx < 6: fontsize = 9 elif sx < 7: fontsize = 5 i = 1 j = 1 k = 1 x = marginx y = korkeus - marginy - 3 * mm for receiver in receivers: if emailBool == True and receiver.email != "": continue logging.debug("begin, {0}".format(k)) postal = receiver.postalno + " " + receiver.city sticker(c, receiver.firstname, receiver.lastname, receiver.address, postal, receiver.contact, x, y, fontsize) k += 1 if j == sy and i == sx: c.showPage() i = 1 j = 1 x = marginx y = korkeus - marginy - 4 * mm logging.debug("j == sy, {0}, {1}".format(x, y)) elif i < sx: x += stickerx + div i += 1 logging.debug("i<sx, {0}".format(x)) elif i == sx: x = marginx y -= stickery i = 1 j += 1 logging.debug("i == sx, {0}, {1}, {2}, {3}".format(x, y, j, sy)) try: c.save() except PermissionError as e: logging.exception(e) return -1 return pdfPath
def settings(configs): # -- Theme -- sg.theme(configs[0]) if configs[0] == "reddit": light = True dark = False else: light = False dark = True # -- List of member classes converted to a string -- memberList = [configs[4]] parser = csv.reader(memberList) memberString = "" for fields in parser: for field in fields: string = field.split(",") memberString = memberString + string[0] + ": " + string[1] + "\n" # -- Menu definition -- menu_def = [["Tiedosto", ["Poistu"]], ["Tietoa", ["Apua", "Tietoa", "Lisenssit"]]] # -- The layout -- layout = [ [sg.Menu(menu_def)], [sg.Text("Haukiposti - asetukset", font=("Verdana", 14, "bold"))], [ sg.Text("Teema", font=("Verdana", 12)), sg.Radio("Vaalea", "THEME", key="themelight", font=("Verdana", 12), default=light), sg.Radio("Tumma", "THEME", key="themedark", font=("Verdana", 12), default=dark) ], [sg.Text("Huom! Vaatii uudelleenkäynnistyksen", font=("Verdana", 12))], [ sg.Button("Poista kirjautumistiedot", font=("Verdana", 12), pad=(0, 20)) ], [ sg.Text("Maksunsaaja", font=("Verdana", 12), size=(20, 1)), sg.InputText(configs[2], key="paymentreceiver") ], [ sg.Text("Pankki", font=("Verdana", 12), size=(20, 1)), sg.Combo([ "Aktia", "POP", "Danske Bank", "Handelsbanken", "Nordea", "OP", "SEB", "S-Pankki", "Säästöpankki", "Ålandsbanken" ], key="bank", default_value=BICToBank(configs[5])) ], [ sg.Text("Tilinumero", font=("Verdana", 12), size=(20, 1)), sg.InputText(configs[3], key="accnum") ], [sg.Text("Jäsenlajit", font=("Verdana", 12))], [sg.Multiline(memberString, key="memberClasses", size=(60, 6))], [ sg.Text("Kirjoita jäsenlajit muodossa (jäsenlaji): (hinta)", font=("Verdana", 9)) ], [ sg.Text( "Kirjoita yhteisöjäsenet muodossa Yhteisöjäsen.(laji): (hinta)", font=("Verdana", 9)) ], [ sg.Text("Erota jäsenlajit toisistaan rivin vaihdolla (enter)", font=("Verdana", 9)) ], [sg.Text("Esim.", font=("Verdana", 9))], [sg.Text("Perusjäsen: 10.00", font=("Verdana", 9))], [sg.Text("Yhteisöjäsen.kunnat: 50", font=("Verdana", 9))], [ sg.Text( "Käytä senttierottimena pistettä! Senttejä ei ole kuitenkaan pakko merkitä.", font=("Verdana", 9)) ], [ sg.Button("Tallenna", font=("Verdana", 12)), sg.Button("Peruuta", font=("Verdana", 12)) ] ] window = sg.Window("Haukiposti - asetukset", layout) # -- Window functionality -- while True: event, values = window.read() if event == "Peruuta": break elif event == "Poista kirjautumistiedot": deleteLogin() elif event == "Tallenna": try: if values["themelight"]: theme = "reddit" else: theme = "darkblue14" if values["accnum"][2:].replace( ' ', '').isdigit() == False or len( values["accnum"].replace(' ', '')) != 18: sg.PopupOK("Tarkista tilinumero.") continue #Parses the member classes input field and creates a string to be written to the configs file, #passing the string to createSettingFile writeString = '' string = values["memberClasses"].split("\n") i = 0 while string[i] != "": k = string[i].split(":") writeString = writeString + '"' + k[0] + ',' + k[1].strip( ) + '"' i = i + 1 if string[i] != "": writeString = writeString + ',' bankBIC = bankToBIC(values["bank"]) createSettingFile(theme, values["paymentreceiver"], values["accnum"], writeString, bankBIC) sg.PopupOK("Tallennettu", font=("Verdana", 12)) break except: sg.PopupOK( "Jokin meni pieleen tallennettaessa, todennäköisesti jäsenluokissa.\nTarkista, että ne ovat kirjoitettu oikeassa muodossa.", font=("Verdana", 10)) logging.error("Error in memberclass parsing") elif event == "Apua": sg.PopupOK( "Asetukset. Muokkaa sovelluksen asetuksia.\n\nKirjoita jäsenlajit muodossa (jäsenlaji): (hinta)\nKirjoita yhteisöjäsenet muodossa Yhteisöjäsen.(laji): (hinta)\nErota jäsenlajit toisistaan rivin vaihdolla (enter)\nEsim\nPerusjäsen: 10.00\nYhteisöjäsen.kunnat: 50\nKäytä senttierottimena pistettä! Senttejä ei ole kuitenkaan pakko merkitä.", font=("Verdana", 10)) elif event == "Tietoa": sg.PopupOK( "Haukiposti {0}\n\nRami Saarivuori\nAarne Savolainen\n(c) 2020" .format(common.version()), font=("Verdana", 12)) elif event == "Lisenssit": sg.popup_scrolled(common.licenses(), font=("Verdana", 12), title="Haukiposti - Lisenssit") elif event in (None, "Poistu"): exit(0) window.close()
def massPost(configs, service): # -- Theme -- sg.theme(configs[0]) # -- Menu definition -- menu_def = [["Tiedosto", ["Poistu"]], ["Tietoa", ["Apua", "Tietoa", "Lisenssit"]]] # -- The layout -- layout = [ [sg.Menu(menu_def)], [sg.Text("Haukiposti - massaposti", font=("Verdana", 12, "bold"))], [sg.Text("Vastaanottajat", font=("Verdana", 12))], [sg.Input("", key="receivers"), sg.FileBrowse("Tuo vastaanottajat", file_types=(('CSV taulukot', '*.csv'),))], [sg.Text("Aihe", font=("Verdana", 12))], [sg.InputText("", key="subject")], [sg.Text("Viesti", font=("Verdana", 12))], [sg.Multiline(key="messageText", size=(60,10))], [sg.Text("Liitteet", font=("Verdana", 12)), sg.Input("", key="attachment"), sg.FilesBrowse("Selaa...", font=("Verdana", 12))], [sg.Button("Lähetä", font=("Verdana", 12)), sg.Button("Esikatsele", font=("Verdana", 12)), sg.Button("Peruuta", font=("Verdana", 12))]] window = sg.Window("Haukiposti - massaposti", layout) # -- Window functionality -- while True: event, values = window.read() if event == "Peruuta": break elif event == "Esikatsele": logging.info("Preview") attachments = values["attachment"].split(';') text = values["messageText"] if preview(text, attachments) == -1: sg.PopupOK("Tekstin muunnos epäonnistui. Todennäköisesti jotakin tiedostoa ei voitu avata.") elif event == "Lähetä": logging.info("Send messages") if service == None: yesno = sg.Popup("Et ole kirjautunut sisään. Haluatko kirjautua sisään nyt?", custom_text=("Kyllä", "Ei")) if yesno == "Kyllä": service = mail.authenticate() else: continue ok = sg.Popup("Haluatko varmasti lähettää viestin?", custom_text=("Kyllä", "Ei")) if ok == "Kyllä": attachments = values["attachment"].split(';') size = 0 if attachments[0] != '': for item in attachments: size += os.path.getsize(item) if size > 24000000: sg.PopupOK("Liitteiden koko on suurempi kuin salittu 23 Mt.") logging.error("Attachments too big") else: text = values["messageText"] htmlText = common.markdownParserHTML(text, attachments,receiver=None, preview=0) receivers = common.CSVparser(values["receivers"]) emailString = "" if receivers: for item in receivers: emailString = emailString + item.email + ";" encMsg = mail.createMail("", emailString, values["subject"], htmlText, attachments) if encMsg: msg = mail.sendMail(service, 'me', encMsg) if msg: sg.PopupOK("Viestin lähetys onnistui.") logging.debug(msg) logging.info("Message sent.") else: sg.PopupOK("Jokin meni vikaan viestiä luotaessa. Viestiä ei lähetetty.") logging.error("Error in message creation") else: sg.PopupOK("CSV tiedostoa lukiessa tapahtui virhe.") logging.error("CSV read error") else: text = values["messageText"] htmlText = common.markdownParserHTML(text, attachments, receiver=None, preview=0) receivers = common.CSVparser(values["receivers"]) emailString = "" if receivers: for item in receivers: emailString = emailString + item.email + ";" encMsg = mail.createMail(configs[1], emailString, values["subject"], htmlText, attachments) if encMsg: msg = mail.sendMail(service, 'me', encMsg) if msg: sg.PopupOK("Viestin lähetys onnistui.") logging.debug(msg) logging.info("Message sent.") else: sg.PopupOK("Jokin meni vikaan viestiä luotaessa. Viestiä ei lähetetty.") logging.error("Error in message creation") else: sg.PopupOK("CSV tiedostoa lukiessa tapahtui virhe.") logging.error("CSV read error") elif event == "Apua": apua = """Massaposti. Täältä voit lähettää massapostia.\n Valitse vastaanottajat sisältävä CSV tiedosto, mahdolliset liitteet, kirjoita heille viesti ja lähetä.\n\n Tekstin erikoismerkit:\n **tekstiä** == Lihavoitu\n ||tekstiä|| == Kursivoitu\n __tekstiä__ == Alleviivattu\n @@linkki@@tekstiä@@ == Tekstin seassa oleva linkki. Mikäli haluat linkin näkyvän linkkinä, kopioi linkki myös tekstin paikalle.\n $$img$$ == Tekstin seassa olevat kuvat määritetään tällä tagilla. Valitse kuvat liitteeksi. Liitteiden järjestyksellä ei ole väliä.\n Jos haluat kuvan olevan linkki, laita $$img$$ tägi tekstin paikalle linkkitägissä. (eli @@linkki@@$$img$$@@)""" sg.PopupOK(apua, title="Apua", font=("Verdana", 12)) elif event == "Tietoa": sg.PopupOK("Haukiposti {0}\n\nRami Saarivuori\nAarne Savolainen\n(c) 2020".format(common.version()), font=("Verdana", 12)) elif event == "Lisenssit": sg.popup_scrolled(common.licenses(), font=("Verdana", 12), title="Haukiposti - Lisenssit") elif event in (None, "Poistu"): exit(0) window.close()
def stickersheet(configs): # -- Theme -- sg.theme(configs[0]) # -- Menu definition -- menu_def = [["Tiedosto", ["Poistu"]], ["Tietoa", ["Apua", "Tietoa", "Lisenssit"]]] # -- The layout -- frame_layout = [[sg.Text("Tarroja leveyssuunnassa", size=(22,1), font=("Verdana", 12)), sg.Spin([i for i in range(1,7)], size=(2,1), key="x")], [sg.Text("Tarroja korkeussuunnassa", size=(22,1), font=("Verdana", 12)), sg.Spin([i for i in range(1,16)], size=(2,1), key="y")], [sg.Text("Tarraväli (mm)", font=("Verdana", 12)), sg.Slider(range=(0,10), default_value=0, resolution=(0.1), size=(20,15), orientation="horizontal", font=("Verdana", 9), key="div")], [sg.Text("", font=("Verdana", 4))]] layout = [ [sg.Menu(menu_def)], [sg.Text("Haukiposti - tarra-arkki", font=("Verdana", 15, "bold"))], [sg.Text("Jäsentiedot", font=("Verdana", 12))], [sg.Input("", key="receivers"), sg.FileBrowse("Tuo jäsentiedot", file_types=(('CSV taulukot', '*.csv'),))], [sg.Checkbox("Vain ilman sähköpostia", font=("Verdana", 12), key="email")], [sg.Text("Paperikoko", font=("Verdana", 12), pad=(1,25)), sg.Combo(["A4"], key="paper")], [sg.Frame("Tarrakoko", frame_layout, font=("Verdana", 12))], [sg.Text("")], # some space between stuff [sg.Text("Kohdekansio:", font=("Verdana", 12)), sg.Input("", key="targetfolder"), sg.FolderBrowse("Selaa...", target="targetfolder")], [sg.Button("Luo", size=(7,1)), sg.Button("Peruuta", size=(7,1))]] window = sg.Window("Haukiposti - tarra-arkki", layout) # -- Window functionality -- while True: event, values = window.read() if event == "Peruuta": break elif event == "Luo": try: receivers = common.CSVparser(values['receivers']) if receivers: if values['targetfolder'] != "" and values['paper'] != "": path = pdf.stickersheet(values['targetfolder'], receivers, values['paper'], int(values['x']), int(values['y']), values['div'], values['email']) if path == -1: sg.PopupOK("Tiedostoa ei voitu luoda, tiedosto on jonkin toisen prosessin käytössä.") elif path == -2: sg.PopupOK("Jokin meni vikaan arkkia luodessa.") else: command = 'cmd /c "start "" "' + path + '"' os.system(command) else: sg.PopupOK("Tarkista, kaikki kentät on täytetty.") logging.info("Some fields empty") else: sg.PopupOK("CSV-tiedoston lukemisessa tapahtui virhe.") logging.error("CSV read error") except Exception as e: logging.exception(e) elif event == "Apua": sg.PopupOK("Tarra-arkkien luonti. Määritä arkin koko, tarrojen lukumäärä (leveys- ja korkeussuunnassa)\nsekä anna vastaanottajat sisältävä CSV tiedosto. Tarra-arkit luodaan yhteen tiedostoon antamaasi kohdekansioon.", font=("Verdana", 12)) elif event == "Tietoa": sg.PopupOK("Haukiposti {0}\n\nRami Saarivuori\nAarne Savolainen\n(c) 2020".format(common.version()), font=("Verdana", 12)) elif event == "Lisenssit": sg.popup_scrolled(common.licenses(), font=("Verdana", 12), title="Haukiposti - Lisenssit") elif event in (None, "Poistu"): exit() window.close()
def __init__(self, parent=None): """ Create dialog. Arguments: parent (Optional[QWidget]): Parent widget. Defaults to *None*. """ super(AboutDlg, self).__init__(parent) self.setModal(True) text = translate("AboutDlg", "About {}").format("AsterStudy") self.setWindowTitle(text) icon_lbl = Q.QLabel(self) title_lbl = Q.QLabel(self) version_lbl = Q.QLabel(self) description_lbl = Q.QLabel(self) license_lbl = Q.QLabel(self) credits_lbl = Q.QLabel(self) copyright_lbl = Q.QLabel(self) self.info_te = Q.QTextEdit(self) ok_btn = Q.QPushButton(self) main_wg = Q.QWidget(self) info_wg = Q.QWidget(self) hlayout = Q.QHBoxLayout() hlayout.addWidget(license_lbl) hlayout.addWidget(credits_lbl) glayout = Q.QGridLayout(main_wg) glayout.setContentsMargins(0, 0, 0, 0) glayout.addWidget(icon_lbl, 1, 1, 5, 1) glayout.addWidget(title_lbl, 1, 2) glayout.addWidget(version_lbl, 2, 2) glayout.addWidget(description_lbl, 4, 2) glayout.addLayout(hlayout, 6, 1, 1, 2) glayout.addWidget(copyright_lbl, 7, 0, 1, 4) glayout.setRowMinimumHeight(0, 10) glayout.setRowMinimumHeight(3, 10) glayout.setRowMinimumHeight(5, 20) glayout.setRowStretch(5, 10) glayout.setRowMinimumHeight(7, 40) glayout.setColumnMinimumWidth(0, 10) glayout.setColumnMinimumWidth(3, 10) hlayout = Q.QHBoxLayout() hlayout.addStretch() hlayout.addWidget(ok_btn) hlayout.addStretch() vlayout = Q.QVBoxLayout(info_wg) vlayout.addWidget(self.info_te) vlayout.addLayout(hlayout) slayout = Q.QStackedLayout() slayout.addWidget(main_wg) slayout.addWidget(info_wg) self.setLayout(slayout) pixmap = load_pixmap("asterstudy.png") icon_lbl.setPixmap(pixmap) icon_lbl.setFixedSize(pixmap.size() * 1.2) icon_lbl.setAlignment(Q.Qt.AlignCenter) title_lbl.setText(wrap_html("AsterStudy", "h1")) text = translate("AboutDlg", "Version: {}").format(version()) version_lbl.setText(wrap_html(text, "h4")) text = translate("AboutDlg", "GUI framework for {code_aster}") text = text.format( code_aster=wrap_html("code_aster", "a", href="code_aster")) description_lbl.setText(wrap_html(text, "h3")) description_lbl.setTextInteractionFlags(Q.Qt.LinksAccessibleByMouse) description_lbl.linkActivated.connect(self._browseCodeAster) text = translate("AboutDlg", "License Information") license_lbl.setText(wrap_html(text, "a", href="license")) license_lbl.setAlignment(Q.Qt.AlignCenter) license_lbl.setTextInteractionFlags(Q.Qt.LinksAccessibleByMouse) license_lbl.linkActivated.connect(self._showLicense) text = translate("AboutDlg", "Credits") credits_lbl.setText(wrap_html(text, "a", href="credits")) credits_lbl.setAlignment(Q.Qt.AlignCenter) credits_lbl.setTextInteractionFlags(Q.Qt.LinksAccessibleByMouse) credits_lbl.linkActivated.connect(self._showCredits) text = "Copyright 2016 EDF R&D" copyright_lbl.setText(italic(text)) copyright_lbl.setAlignment(Q.Qt.AlignCenter) self.info_te.setReadOnly(True) self.info_te.setMinimumWidth(450) ok_btn.setText(translate("AsterStudy", "&OK")) ok_btn.clicked.connect(self._showMain) palette = self.palette() palette.setColor(Q.QPalette.Window, Q.QColor("#f7f7f7")) self.setPalette(palette) palette.setColor(Q.QPalette.Window, Q.QColor("#ebebeb")) copyright_lbl.setPalette(palette) copyright_lbl.setAutoFillBackground(True) self.resize(self.minimumSizeHint())
# See the License for the specific language governing permissions and # limitations under the License. # # ***************************************************************************** import sys import jpype import common import types import functools import inspect have_jedi = False try: import jedi have_jedi = (common.version(jedi.__version__) > (0, 14)) except: pass class JediTestCase(common.JPypeTestCase): """Test tab completion on JPype objects """ def setUp(self): common.JPypeTestCase.setUp(self) self.cls = jpype.JClass('java.lang.String') self.obj = self.cls('foo') @common.unittest.skipUnless(have_jedi, "jedi not available") def testCompleteClass(self):
def main(): try: logname = os.path.join((os.getenv("APPDATA") + "\\Haukiposti"), "haukilog.log") logpath = (os.getenv("APPDATA") + "\\Haukiposti") if os.path.exists(logpath) == False: os.mkdir(logpath) logging.basicConfig(filename=logname, level=logging.INFO, format='%(asctime)s %(levelname)s - %(message)s', datefmt='%d/%m/%Y %H:%M:%S') logging.info("HaukiPosti {0} - Rami Saarivuori & Aarne Savolainen (c) 2020".format(common.version())) configs = configParsing() # -- Theme -- sg.theme(configs[0]) # -- Menu definition -- menu_def = [["Tiedosto", ["Poistu"]], ["Tietoa", ["Apua", "Tietoa", "Lisenssit"]]] # -- The layout -- layout = [ [sg.Menu(menu_def)], [sg.Image(common.resource_path(r"haukiposti_small.png"), pad=(26,0))], [sg.Text("Haukiposti", font=("Verdana", 15, "bold"), size=(10,1), justification="center")], [sg.Button("Kirjaudu", font=("Verdana", 12), size=(15, 1), key="login")], [sg.Button("Massaposti", font=("Verdana", 12), size=(15, 1))], [sg.Button("Laskutus", font=("Verdana", 12), size=(15, 1))], [sg.Button("Tarra-arkit", font=("Verdana", 12), size=(15, 1))], [sg.Button("Asetukset", font=("Verdana", 12), size=(15, 1))], [sg.Button("Poistu", font=("Verdana", 12), size=(15, 1))]] # -- Window creation -- window1 = sg.Window("Haukiposti", layout) # -- Window functionality -- service = None while True: event, values = window1.read() if event == "Massaposti": window1.Hide() logging.info("Masspost") masspost.massPost(configs, service) window1.UnHide() elif event == "Laskutus": window1.Hide() logging.info("Billing") billing.billing(configs, service) window1.UnHide() elif event == "Tarra-arkit": window1.Hide() logging.info("Stickerheet") stickersheet.stickersheet(configs) window1.UnHide() elif event == "Asetukset": window1.Hide() logging.info("Settings") settings.settings(configs) configs = updateConfig(configs) if os.path.exists(os.getenv("APPDATA") + "\\Haukiposti\\token.pickle") == False: window1["login"].update("Kirjaudu", disabled=False) service = None window1.UnHide() elif event == "login": service = mail.authenticate() if service: sg.PopupOK("Todennus onnistui.", font=("Verdana", 12)) window1["login"].update("Kirjauduttu", disabled=True) logging.info("Login succesful") else: sg.PopupOK("Todennus epäonnistui.", font=("Verdana", 12)) logging.error("Login unsuccesful") elif event == "Apua": sg.PopupOK("Tämä on päänäkymä. Valitse mitä haluat tehdä painamalla nappia.", font=("Verdana", 12)) elif event == "Tietoa": sg.PopupOK("Haukiposti {0}\n\nRami Saarivuori\nAarne Savolainen\n(c) 2020".format(common.version()), font=("Verdana", 12)) elif event == "Lisenssit": sg.popup_scrolled(common.licenses(), font=("Verdana", 12), title="Haukiposti - Lisenssit") elif event in (None, "Poistu"): break if os.path.exists(os.path.join((os.getenv("APPDATA") + "\\Haukiposti"), "preview.html")): os.remove(os.path.join((os.getenv("APPDATA") + "\\Haukiposti"), "preview.html")) folderpath = os.path.join((os.getenv("APPDATA") + "\\Haukiposti"), "images") for i in os.listdir(folderpath): os.remove(folderpath+ "/"+i) os.rmdir(folderpath) logging.info("Message previews deleted.") if os.path.exists(os.path.join((os.getenv("APPDATA") + "\\Haukiposti"), "barcodes")): folderpath = os.path.join((os.getenv("APPDATA") + "\\Haukiposti"), "barcodes") for i in os.listdir(folderpath): os.remove(folderpath+ "/"+i) os.rmdir(folderpath) logging.info("Barcodes deleted.") if os.path.exists(os.path.join((os.getenv("APPDATA") + "\\Haukiposti"), "preview.pdf")): os.remove(os.path.join((os.getenv("APPDATA") + "\\Haukiposti"), "preview.pdf")) logging.info("Invoice preview deleted.") window1.close() logging.info("Exit, Code 0") sys.exit(0) except Exception as e: logging.exception(e)