=====online cocktail napkin===== ""links and notes for later organization"">>[[CocktailNapkin2011 2011 Napkin]] [[CocktailNapkin2010 2010 Napkin]] [[CocktailNapkin2009 2009 Napkin]] [[CocktailNapkin2008 2008 Napkin]] [[CocktailNapkin2007 2007 Napkin]] SpecialReading WordsIReallyLike ThumbDrive [[CocktailQuestions Questions for Strangers]]>> **String Data Structures (for when your JSON lib is a PITA)** %% )( - 1:a,b,c,d )( 2:a,b,c,d )( 3:a-b-c-d ][ - 1:a,b,c,d )( 2:a,b,c,d )( 3:a-b-c-d ][ 1:a,b,c,d )( 2:a,b,c,d )( 3:a-b-c-d ][ 1:a,b,c,d )( 2:a,b,c,d )( 3:a-b-c-d }{ - 1:a,b,c,d )( 2:a,b,c,d )( 3:a-b-c-d ][ 1:a,b,c,d )( 2:a,b,c,d )( 3:a-b-c-d ][ 1:a,b,c,d )( 2:a,b,c,d )( 3:a-b-c-d }{ 1:a,b,c,d )( 2:a,b,c,d )( 3:a-b-c-d ][ 1:a,b,c,d )( 2:a,b,c,d )( 3:a-b-c-d ][ 1:a,b,c,d )( 2:a,b,c,d )( 3:a-b-c-d %% **init not found try passing init=bootargs** ~- On Asus EEE Netbook ~- To Fix ~~- Insert Ubuntu thumbdrive (on keychain) ~~- Reboot > Press ESC until you get Boot Menu ~~- Run without Installing ~~- See this post: http://askubuntu.com/a/73983/46766 **atta dict!** %%(python) """ ref: http://news.ycombinator.com/item?id=3881341 """ from collections import defaultdict from pprint import pprint import pdb class attrdict(defaultdict): def __getattr__(self, key): return self[key] def __setattr__(self, key, val): self[key]=val def tree(): return attrdict(tree) ca = tree() ca.orange.santa_ana = 92704 ca.orange.anaheim = 92807 pprint(ca) pdb.set_trace() %% **matplotlib custom color sequence** %%(python) """ A series of circle with custom colormap (red to green) USAGE python .dev/colormap.py REFERENCES: http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.patches.Circle http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps http://stackoverflow.com/questions/9215658/plot-a-circle-with-pyplot http://stackoverflow.com/a/9544600/1093087 """ import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from matplotlib import cm from numpy import arange import math SOLID = 'solid' GREY = (.75,.75,.75) clamp = lambda v: min(max(0, v), 1) def main(): # simulate a smartphone h, w = 15.0/8.0, 51.0/16.0 hpx, wpx = 480.0, 800.0 dpi = math.sqrt(hpx*wpx) / math.sqrt(h*w) # or my laptop lhpx, lwpx = 1600.0, 900.0 lhw = 17.3 ldpi = math.sqrt(lhpx*lwpx) / math.sqrt(lhw) # set up color map colors = cm.gist_rainbow(arange(200)) rg_map = ListedColormap(colors[:100], 'red-green') colors = rg_map.colors # circle params minR, maxR = 4,8 x,y = 2,0 # build image fig = plt.Figure(figsize=(w,h), dpi=dpi) for n in range(0,100,3): radius = minR + ((maxR-minR) * (n/100.0)) x += maxR pt = (x,y) x += maxR + 4 r = clamp(1 - (.66*n / 100.0)) g = clamp(0 + (1.0*n / 100.0)) b = 0 # alternately, using a colormap #ci = math.floor((n/100.0)*len(colors)) #rgba = colors[ci] #r,g,b = map(lambda n: int(round(n*255)), [v for v in rgba[:3]]) # circle and edge c = plt.Circle(pt, radius, color=(r,g,b)) o = plt.Circle(pt, maxR, fill=False, lw=1, ls=SOLID, edgecolor=GREY) plt.axes().add_artist(c) plt.axes().add_artist(o) print (pt, radius), (r,g,b) # label a few if (n/3) % 11 == 0: rv,gv,bv = map(lambda n: int(round(n*255)), [v for v in (r,g,b)]) label = 'RGB: (%d,%d,%d)' % (rv,gv,bv) plt.axes().annotate(label, (x-radius, n+minR+12), size=12) plt.axes().set_xlim((0,wpx), auto=False) plt.axes().set_ylim((-hpx/2,hpx/2), auto=False) plt.axes().set_aspect('equal') plt.show() def example(): """source: http://stackoverflow.com/a/9216646/1093087""" circle1=plt.Circle((0,0),.2,color='r') circle2=plt.Circle((.5,.5),.2,color='b') circle3=plt.Circle((1,1),.2,color='g',clip_on=False) fig = plt.gcf() fig.gca().add_artist(circle1) fig.gca().add_artist(circle2) fig.gca().add_artist(circle3) plt.show() main() %% **Soup Request Test** %%(python) #!/usr/bin/python """ proto.py PURPOSE Prototyping gyro (requests experiment). USAGE $ venv/bin/python dev/gyro/tests/dev/proto.py NOTES Uses requests, beautifulsoup REFERENCES http://docs.python-requests.org/en/latest/user/quickstart/#make-a-get-request http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#Quick%20Start """ # # IMPORTS # # Python Imports import unittest, sys, os, time from os.path import (abspath, dirname, join as pathjoin, exists) from datetime import(datetime, date, timedelta) from random import (choice, sample) import pdb import re # External Imports import requests from BeautifulSoup import BeautifulSoup as soup, Tag, NavigableString # Extend sys.path PROJECT_PATH = abspath(pathjoin(dirname(__file__), '../..')) # Project Imports # # MODULE PARAMETERS # # Exception Classes class NullException(Exception): pass # # Test Class # class PrototypeTest(unittest.TestCase): data_dir = pathjoin(PROJECT_PATH, 'test/data') # # Harness # def setUp(self): pass def tearDown(self): pass # # New Methods # # # Unit Tests # # # Dev Tests # def testLastPageGoogleNoOmissions(self): url = "http://www.google.com/search" query = "hello world" start_at = 990 # # REQUESTS # # prepare payload = dict( q = query, hl = "en", start = start_at, filter = 0 ) # get site = requests.get(url, params=payload) raw = site.content # test needle = "to show you the most relevant results" self.assertFalse(needle in raw) self.assertTrue("Page 100" in raw) # # SOUP # # parser html = soup(site.content) results_block = html.findAll("li", { "class" : "g" }) last_result = results_block[-1] # parse last result links = last_result.findAll("a") result_link = links[0].get("href") result_url = result_link.split('/url?q=')[1].split('&')[0] print result_url # test request self.assertTrue(results_block) # interact time.sleep(2) def testLastPageGoogleOmitted(self): url = "http://www.google.com/search" query = "python language" start_at = 990 # # REQUESTS # # prepare payload = dict( q = query, hl = "en", start = start_at ) # get site = requests.get(url, params=payload) raw = site.content # test needle = "to show you the most relevant results" self.assertTrue(needle in raw) # # SOUP # # parser html = soup(site.content) results_block = html.findAll("li", { "class" : "g" }) last_result = results_block[-1] # parse last result links = last_result.findAll("a") result_link = links[0].get("href") result_url = result_link.split('/url?q=')[1].split('&')[0] print result_url # test request self.assertTrue(results_block) # interact #import pdb; pdb.set_trace() # don't arouse suspicion time.sleep(2) def testBeautifulSoup(self): """parse my special wiki page""" url = "http://localhost/wikka/Gyro" site = requests.get(url) html = soup(site.content) # these work haystack = html.find("h3", { "id" : "hn_Haystack" }) needle = html.find(text=re.compile('a beautiful needle')) # these don't work nostack = html.find("h4", { "id" : "hn_Haystack" }) # wrong tag noneedle = html.findAll(text="a beautiful needle") self.assertEqual(type(haystack), Tag) self.assertEqual(type(needle), NavigableString) self.assertFalse(nostack) self.assertFalse(noneedle) self.assertTrue("a beautiful needle" in str(html)) self.assertTrue("a beautiful needle" in str(needle)) def testRequests(self): """pull my wiki""" url = "http://localhost/wikka/Gyro" site = requests.get(url) self.assertTrue(site.ok) self.assertTrue("a beautiful needle" in site.content) # # Smoke Tests # def testInstance(self): self.assertTrue(isinstance(self, unittest.TestCase)) # # Main # if __name__ == "__main__": mod = sys.modules[globals()['__name__']] suite = unittest.TestLoader().loadTestsFromModule(mod) unittest.TextTestRunner(verbosity=2).run(suite) %% **Programming Collective Intelligence** Source code: http://blog.kiwitobes.com/?p=44 **Install gevent to virtualenv Directory** [[http://mirnazim.org/writings/python-ecosystem-introduction/ mirnazim.org]] [[http://stackoverflow.com/questions/6431096/gevent-does-not-install-properly-on-ubuntu stackoverflow.com]] [[https://groups.google.com/d/msg/gevent/GsRmocqmgN8/XUtWnIKJVHIJ groups.google.com]] %% # set up virtual env source bin/activate # install gevent sudo apt-get install libevent-dev export C_INCLUDE_PATH=/usr/include:/usr/local/include:/opt/local/include pip install greenlet pip install gevent %% **Python Temp Files** Simple case: %%(python) import tempfile ... temp_file_name = tempfile.NamedTemporaryFile().name f = open(temp_file_name) %% Write to temp file: %%(python) file_contents = """hello world""" temp_file = tempfile.NamedTemporaryFile() temp_file.write(file_contents) temp_file.seek(0) f = open(temp_file.name) %% **Getting Setup with Virtualenv** http://mirnazim.org/writings/python-ecosystem-introduction/ %% # Install pip and virtualenv sudo apt-get install python-pip python-dev build-essential sudo pip install pip --upgrade sudo pip install virtualenv # Setup a virtualenv mkdir venv virtualenv --distribute --no-site-packages venv # Run from virtualenv venv/bin/python venv/bin/python myscript.py # To activate/deactivate env source bin/activate (venv)$ deactivate %% **Draw Circle to Canvas in PlayN** Stack Overflow Question: http://stackoverflow.com/questions/9478065/ **GWT Plugin for Eclipse** Problem: http://stackoverflow.com/questions/8363560 Solution: http://askubuntu.com/questions/49557#94341 **Install Eclipse with ADT Plugin on Ubuntu 11.10** [[http://askubuntu.com/questions/107192/how-can-i-install-eclipse-with-the-adt-android-development-tool-on-ubuntu-11-1 Ask Ubuntu]] Pastebin20120223 http://stackoverflow.com/questions/9426715 [[http://code.google.com/p/google-web-toolkit/issues/detail?id=6887 related?]] [[http://stackoverflow.com/questions/6482268/eclipse-indigo-cannot-install-android-adt-plugin possible solution?]] **Color Maps** http://matplotlib.sourceforge.net/examples/api/colorbar_only.html http://matplotlib.sourceforge.net/examples/pylab_examples/show_colormaps.html **""RdYlGn""** **Installing Ubuntu 11.10 on [[http://www.google.com/products/catalog?hl=en&safe=off&q=HP+g7-1310us&gs_sm=12&gs_upl=1557545l1557545l6l1558924l1l1l0l0l0l0l146l146l0.1l2l0&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&biw=1168&bih=593&um=1&ie=UTF-8&tbm=shop&cid=16780769756561576303&sa=X&ei=g0Q7T9maHcmr2AWbm9m0Cg&ved=0CF0Q8wIwAg HP G71310US]]** HP Pavilion g7-1310us Intel Core i3-2350M Notebook Chose [[http://www.ubuntu.com/download/ubuntu/download Ubuntu 11.10 64-Bit]] Needed to deal with black screen issue detailed [[http://ubuntuforums.org/showthread.php?t=1613132 here]] ~- See **How to enable kernel options on the livecd (before install)** ~- Choose nomodeset (x will appear next to it) ~- Then select Install Ubuntu ~- After installation, need to follow direction for temporarily and then permanently modifying grub config with nomodeset flag. Hold down shift on boot to get to grub config. ~- On IRC chat, ludwin01 suggested 10.04 lts version did not have this problem. I'm working around it for now with grub flag. ~- My Ubuntu Forum post on issue: [[http://ubuntuforums.org/showthread.php?p=11695329#post11695329 http://ubuntuforums.org/showthread.php?p=11695329#post11695329]] ~- ""AskUbuntu"" Post: http://askubuntu.com/questions/105651/ ~~- [[Pastebin20120219 Draft of Response]] **Python Inheritance** %%(python) class Reveal(object): def __repr__(self): return "<%s %s>" % (self.__class__.__name__, self.__dict__) class Yin(Reveal): def __init__(self, yin=100): self.yin = yin self.lightness = True self.darkness = False self.balance = False class Yan(Reveal): def __init__(self, yan=100): self.yan = yan self.lightness = False self.darkness = True self.balance = False class YinYan(Yin, Yan): def __init__(self, yin, yan): Yin.__init__(self, yin) Yan.__init__(self, yan) self.balance = True yin = Yin(50) yan = Yan(50) yinyan = YinYan(50, 50) print yin print yan print yinyan # Prints %% **Send Email through Gmail with Python** %%(python) """ Send an email programmatically through Gmail. REFERENCES http://snippets.dzone.com/posts/show/757 http://www.nixtutor.com/linux/send-mail-through-gmail-with-python/ http://stackoverflow.com/questions/399129/#comment8985407_399240 """ import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import os from os.path import abspath, dirname, join SMTP_SERVER = 'smtp.gmail.com:587' SMTP_USER = 'USER@gmail.com' SMTP_PASS = 'PASS' EMAIL_FROM = 'USER <%s>' % (SMTP_USER) def send_gmail(to, subject, text, files=[]): assert type(to) == list assert type(files) == list from_ = EMAIL_FROM msg = MIMEMultipart() msg['From'] = EMAIL_FROM msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(file,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) smtp = smtplib.SMTP(SMTP_SERVER) #smtp.set_debuglevel(1) smtp.ehlo() # apparently this is required in python 2.5 smtp.starttls() smtp.login(SMTP_USER, SMTP_PASS) smtp.sendmail(from_, to, msg.as_string() ) smtp.close() def test_email(): to = 'YOUR_RECEPIENT@some_domain.com' subject = "Python Gmail Test" text = 'This is simply a test.' send_gmail([to], subject, text) print 'simple test complete' %% **Method Decorator** %%(python) def check_some_flag(method): def wrapper(self, *args, **kwargs): if not self.some_flag: raise Exception("some_flag not set") else: result = method(self, *args, **kwargs) return result return wrapper %% **Find Equation for Set of Points** [[https://www.google.com/search?hl=en&output=search&sclient=psy-ab&q=python+find+equation&btnK= python find roots of equation]] %%(python) >>> import numpy >>> x = [1,50,99] >>> y = [2,1,0.5] >>> a,b,c = numpy.polyfit(x,y,2) >>> f = lambda x: a*x**2 + b*x + c >>> f(1) 2.0 >>> f(20) 1.5528946272386506 >>> f(50) 1.0000000000000002 >>> f(90) 0.55435235318617249 >>> f(100) 0.49500208246563937 >>> f(99) 0.5 %% Verizon Opt-Out Site: http://www.vzw.com/myprivacy **Somewhat Improved Wikka Installer Routine** Diff for wikka.php: %% diff -r c8f8537f5e21 -r 4e091af5eacf php/wikka/wikka.php --- a/php/wikka/wikka.php Tue Jan 17 10:01:24 2012 -0800 +++ b/php/wikka/wikka.php Tue Jan 17 11:43:38 2012 -0800 @@ -509,11 +509,15 @@ /** * Compare versions, start installer if necessary. + * Wait to start installer below if this is an upgrade so we can limit access + * to admin users. */ -if (!isset($wakkaConfig['wakka_version'])) $wakkaConfig['wakka_version'] = 0; -if ($wakkaConfig['wakka_version'] !== WAKKA_VERSION) -{ - /** +$is_new_install = ! isset($wakkaConfig['wakka_version']); +$is_upgrade = $wakkaConfig['wakka_version'] !== WAKKA_VERSION; + +if ( $is_new_install ) { + $wakkaConfig['wakka_version'] = 0; + /** * Start installer. * * Data entered by the user is submitted in $_POST, next action for the @@ -590,6 +594,7 @@ exit; } + /** * Save session ID */ @@ -611,6 +616,39 @@ } /** + * Check for upgrade. If so an user is admin, show setup page, else show + * a maintenance message to all other visitors. + */ +$is_admin = $wakka->IsAdmin($user); +$at_install_step = ($_GET['installAction'] == 'writeconfig') && (isset($_POST['config'])); +$upgrade_allowed = $is_admin || $at_install_step; + +if ( $is_upgrade && $upgrade_allowed ) { + $installAction = 'default'; + if (isset($_GET['installAction'])) $installAction = trim($_GET['installAction']); #312 + if (file_exists('setup'.DIRECTORY_SEPARATOR.'header.php')) + include('setup'.DIRECTORY_SEPARATOR.'header.php'); else print ''.ERROR_SETUP_HEADER_MISSING.''; #89 + if + (file_exists('setup'.DIRECTORY_SEPARATOR.$installAction.'.php')) + include('setup'.DIRECTORY_SEPARATOR.$installAction.'.php'); else print ''.ERROR_SETUP_FILE_MISSING.''; #89 + if (file_exists('setup'.DIRECTORY_SEPARATOR.'footer.php')) + include('setup'.DIRECTORY_SEPARATOR.'footer.php'); else print ''.ERROR_SETUP_FOOTER_MISSING.''; #89 + exit; +} +elseif ( $is_upgrade && $_GET['install_help'] ) { + print "

POST,GET, SESSION variables

"; + print '
';
+    var_dump($_POST);
+    var_dump($_GET);
+    var_dump($_SESSION);
+    print '
'; +} +elseif ( $is_upgrade ) { + die('

Site Undergoing Temporary Maintenance

Please check back shortly.

'); +} + + +/** * Run the engine. */ if (!isset($handler)) $handler=''; %% **IKEA Stand-Up Desks** http://news.ycombinator.com/item?id=3442809 http://www.ikea.com/us/en/catalog/products/00115992/ http://www.ikea.com/us/en/catalog/products/60111123/ ---- [[CategorySpecial]]