pastebin - collaborative debugging

pastebin is a collaborative debugging tool allowing you to share and modify code snippets while chatting on IRC, IM or a message board.

This site is developed to XHTML and CSS2 W3C standards. If you see this paragraph, your browser does not support those standards and you need to upgrade. Visit WaSP for a variety of options.

pastebin private pastebin - collaborative debugging tool What's a private pastebin?

Posted by frymaster on Wed 1st Jan 17:30
download | new post

  1. #!/usr/bin/python
  2.  
  3. import urllib
  4. import collections
  5. import json
  6. import time
  7. import memcache
  8.  
  9. TableEntry = collections.namedtuple("TableEntry", "Item_ID Item_Name Maximum_Buy Minimum_Sell Flippable Profit")
  10.  
  11. #cacheOrCall("server_status_JSON",get_statusJSON)
  12. def cacheOrCall(key,function,args=(),kwargs=None):
  13.     if kwargs is None:
  14.         kwargs = {}
  15.     mc = memcache.Client(['127.0.0.1:11211'], debug=0)
  16.     storedResult = mc.get(key)
  17.     if storedResult: print "Value found",key
  18.     while not storedResult:
  19.         print "Value not stored",key,
  20.         if not mc.get(key+"_mutex"):
  21.             mc.set(key+"_mutex","mooo...tex",2)
  22.             storedResult,timeout = function(*args,**kwargs)
  23.             mc.set(key,storedResult,timeout)
  24.             print "stored with timeout",timeout
  25.             mc.delete(key+"_mutex")
  26.         else:
  27.             time.sleep(0.1)
  28.             storedResult = mc.get(key)
  29.     return storedResult
  30.  
  31.  
  32. #X-Varnish-TTL: 300.000\r\n
  33. #Searches through headers for the ttl of the cache
  34. def getCacheTTL(headers,default=300):
  35.     current = default
  36.     for header in headers:
  37.         if header[:15]=="X-Varnish-TTL: ":
  38.             try:
  39.                 current = int(header[15:-6])
  40.             except:
  41.                 pass
  42.     return current
  43.  
  44. #Age: 80\r\n
  45. #Searches through the headers for how old the cache is, and uses the ttl to work out how long the data will remain unchanged
  46. def getCacheRemaining(headers,ttl,default=300,min=60,max=300):
  47.     current=default
  48.     for header in headers:
  49.         if header[:5]=="Age: ":
  50.             try:
  51.                 current = ttl - int(header[5:-2])
  52.             except:
  53.                 pass
  54.             if current < min: current = min
  55.             if current > max: current = max
  56.     return current
  57.  
  58. def getItemData_real(itemID, flipMargin = 0.85):
  59.     #Accepts an itemID and queries the gw2spidy API
  60.     #Returns a tuple containting a json response as a named tuple, and the timeout on the result
  61.     #http://docs.python.org/2/library/collections.html#collections.namedtuple
  62.     gw2spidy = "http://www.gw2spidy.com/api/v0.9/json/item/"
  63.     f = urllib.urlopen(gw2spidy+str(itemID))
  64.     jsonResponse = f.read()
  65.     f.close()
  66.     timeout = getCacheRemaining(f.info().headers,getCacheTTL(f.info().headers)) + 1
  67.     response = json.loads(jsonResponse)
  68.     #Extract sell and buy order information from the response + convert to silver from copper.
  69.     minSell = response["result"]["min_sale_unit_price"]/100.0
  70.     maxBuy =  response["result"]["max_offer_unit_price"]/100.0
  71.  
  72.     if (minSell*flipMargin) < maxBuy:
  73.         flip = "No"
  74.     else: flip = "Yes"
  75.  
  76.     profit = (minSell*flipMargin) - maxBuy
  77.  
  78.     itemData = TableEntry((itemID),
  79.                           (response["result"]["name"]),
  80.                           (maxBuy),
  81.                           (minSell),
  82.                           (flip),
  83.                           (profit))
  84.     time.sleep(0.1)
  85.     return (itemData,timeout)
  86.  
  87. def getItemData(itemID,flipMargin = 0.85):
  88.     args = (itemID,)
  89.     kwargs = {"flipMargin":flipMargin}
  90.     return cacheOrCall("gw2itemdata" + str(itemID),getItemData_real,args=args,kwargs=kwargs)
  91.  
  92. def buildTable(itemIDs):
  93.     items = []
  94.     for itemID in itemIDs:
  95.         items.append(getItemData(itemID))
  96.     return items
  97.  
  98. def outputTable(name,table):
  99.  
  100.     width = len(table[0])
  101.     output = ['<table><tr><th colspan=',str(width),'>',name,'</th></tr>\n']
  102.     output.append('<tr>')
  103.     for field in table[0]._fields:
  104.         output.append('<th>' + field.replace('_',' ') + '</th>')
  105.     output.append('</tr>\n')
  106.     for row in table:
  107.         output.append('<tr>')
  108.         for element in row:
  109.             output.append('<td>' + str(element) + '</td>')
  110.         output.append('<tr>\n')
  111.     output.append('</table>\n<br />\n')
  112.     return "".join(output)
  113.  
  114. def outputSection(name,section):
  115.     output = ['<div class="section"><h1 class="sectionHeading">' , name , '</h1>\n']
  116.     for table in section:
  117.         output.append(outputTable(table,section[table]))
  118.     output.append('</div>\n')
  119.     return "".join(output)
  120.  
  121. def outputAll(damnThing):
  122.     output = ['<html>\n<head></head>\n<body>\n']
  123.     for section in damnThing:
  124.         output.append(outputSection(section,damnThing[section]))
  125.     output.append("</body>\n</html>")
  126.     return "".join(output)
  127.  
  128. def writeFile(output):
  129.     f = open('gw2TP.html', 'w')
  130.     f.write(output)
  131.     f.close()
  132.  
  133.  
  134. if __name__ == "__main__":
  135.  
  136.     #Build Common Materials section
  137.     ore     = buildTable( [19697, 19703, 19699, 19698, 19702, 19700, 19701 ] )
  138.     wood    = buildTable( [19723, 19726, 19727, 19724, 19722, 19725 ] )
  139.     cloth   = buildTable( [19718, 19739, 19741, 19743, 19748, 19745 ] )
  140.     leather = buildTable( [19719, 19728, 19730, 19731, 19729, 19732 ] )
  141.     common = {"Ore": ore, "Wood": wood, "Cloth": cloth, "Leather": leather}
  142.     #Build Fine Materials section
  143.     blood   = buildTable( [24290, 24291, 24292, 24293, 24294, 24295] )
  144.     bone    = buildTable( [24343, 24343, 24344, 24345, 24341, 24358] )
  145.     claw    = buildTable( [24346, 24347, 24348, 24349, 24350, 24351] )
  146.     dust    = buildTable( [24272, 24273, 24274, 24275, 24276, 24277] )
  147.     fang    = buildTable( [24352, 24353, 24354, 24355, 24356, 24357] )
  148.     scale   = buildTable( [24284, 24285, 24286, 24287, 24288, 24289] )
  149.     totem   = buildTable( [24296, 24297, 24298, 24363, 24299, 24300] )
  150.     sac     = buildTable( [24278, 24279, 24280, 24281, 24282, 24283] )
  151.     fine = {"Blood": blood, "Bone": bone, "Claw": claw, "Dust": dust,
  152.             "Fang": fang, "Scale": scale, "Totem": totem, "Venom Sac": sac}
  153.     #Build Rare Materials section
  154.     crystal   = buildTable( [24326, 24327, 24328, 24329, 24330] )
  155.     corrupted = buildTable( [24336, 24337, 24338, 24339, 24340] )
  156.     destroyer = buildTable( [24321, 24322, 24323, 24324, 24325] )
  157.     essence   = buildTable( [24331, 24332, 24333, 24334, 24335] )
  158.     glacial   = buildTable( [24316, 24317, 24318, 24319, 24319] )
  159.     molten    = buildTable( [24311, 24312, 24313, 24314, 24315] )
  160.     onyx      = buildTable( [24306, 24307, 24308, 24309, 24310] )
  161.     charged   = buildTable( [24301, 24302, 24303, 24304, 24305] )
  162.     rare = {"Crystal" : crystal, "Corrupted" : corrupted,
  163.             "Destroyer" : destroyer, "Essence" : essence,
  164.             "Glacial" :glacial, "Molten" : molten,
  165.             "Onyx" : onyx, "Charged" : charged}
  166.  
  167.  
  168.     wholeDamnThing = { "Common Materials" : common,
  169.                        "Fine Materials" : fine,
  170.                        "Rare Materials" : rare
  171.                        }
  172.     output = outputAll(wholeDamnThing)
  173.     print output,
  174.     writeFile(output)

Submit a correction or amendment below. (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Use syntax highlighting

To highlight particular lines, prefix each line with @@


Remember my settings