assorted-commits Mailing List for Assorted projects (Page 16)
Brought to you by:
yangzhang
You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(9) |
Dec
(12) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(86) |
Feb
(265) |
Mar
(96) |
Apr
(47) |
May
(136) |
Jun
(28) |
Jul
(57) |
Aug
(42) |
Sep
(20) |
Oct
(67) |
Nov
(37) |
Dec
(34) |
2009 |
Jan
(39) |
Feb
(85) |
Mar
(96) |
Apr
(24) |
May
(82) |
Jun
(13) |
Jul
(10) |
Aug
(8) |
Sep
(2) |
Oct
(20) |
Nov
(31) |
Dec
(17) |
2010 |
Jan
(16) |
Feb
(11) |
Mar
(17) |
Apr
(53) |
May
(31) |
Jun
(13) |
Jul
(3) |
Aug
(6) |
Sep
(11) |
Oct
(4) |
Nov
(17) |
Dec
(17) |
2011 |
Jan
(3) |
Feb
(19) |
Mar
(5) |
Apr
(17) |
May
(3) |
Jun
(4) |
Jul
(14) |
Aug
(3) |
Sep
(2) |
Oct
(1) |
Nov
(3) |
Dec
(2) |
2012 |
Jan
(3) |
Feb
(7) |
Mar
(1) |
Apr
|
May
(1) |
Jun
|
Jul
(4) |
Aug
(5) |
Sep
(2) |
Oct
(3) |
Nov
|
Dec
|
2013 |
Jan
|
Feb
|
Mar
(9) |
Apr
(5) |
May
|
Jun
(2) |
Jul
(1) |
Aug
(10) |
Sep
(1) |
Oct
(2) |
Nov
|
Dec
|
2014 |
Jan
(1) |
Feb
(3) |
Mar
(3) |
Apr
(1) |
May
(4) |
Jun
|
Jul
|
Aug
|
Sep
(2) |
Oct
|
Nov
|
Dec
|
2015 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(1) |
Nov
|
Dec
|
2016 |
Jan
(1) |
Feb
|
Mar
(2) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(1) |
Oct
|
Nov
|
Dec
|
2017 |
Jan
|
Feb
|
Mar
(1) |
Apr
|
May
(5) |
Jun
(1) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(2) |
2018 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
(1) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <yan...@us...> - 2009-12-16 19:05:29
|
Revision: 1527 http://assorted.svn.sourceforge.net/assorted/?rev=1527&view=rev Author: yangzhang Date: 2009-12-16 19:05:16 +0000 (Wed, 16 Dec 2009) Log Message: ----------- updated subprocess demo Modified Paths: -------------- sandbox/trunk/src/py/subprocesses.py Modified: sandbox/trunk/src/py/subprocesses.py =================================================================== --- sandbox/trunk/src/py/subprocesses.py 2009-12-03 21:27:57 UTC (rev 1526) +++ sandbox/trunk/src/py/subprocesses.py 2009-12-16 19:05:16 UTC (rev 1527) @@ -1,23 +1,42 @@ #!/usr/bin/env python # vim:et:sw=2:ts=2 -# Try passing something as an arg, causing us to exit immediately without -# waiting for the subprocess to finish; notice the subproc lives. +# Try passing 'exit' as an arg, causing us to exit immediately without waiting +# for the subprocess to finish; notice the subproc lives. # Try launching this (without args) in bg and killing it; notice subproc lives. -# Try ctrl-c on this and wait; notice the subproc dies. +# Try ctrl-c on this; notice the subproc gets a sigint too and dies (even +# though we handle KeyboardInterrupt). Verify this (after hitting ctrl-c) by +# doing c-z, bg, ps f; notice the subproc is defunct, meaning it has exited but +# is still around because the parent process is still around and hasn't called +# `wait` on it. (It has to stick around to occupy the PID and retain the exit +# status; `wait` implicitly frees up the PID because now the parent knows the +# process has exited.) -# Try ctrl-c on this, then c-z, bg, ps; notice the subproc is defunct. - # Try launching this in bg and kill -s sigint on it; notice the subproc lives. +# This suggests that Python's default ctrl-c (sigint) handler (besides raising +# KeyboardInterrupt) kills subprocesses if and only if the current process is +# in the foreground. +# Try passing 'signal' as an arg to override the default sigint handler, and +# hitting ctrl-c on this; notice the subproc still dies. This shows our +# previous intuition was wrong, and that in fact the terminal shell (session +# leader) through which we're issuing ctrl-c's issues sigint to all processes +# in the group on a ctrl-c (i.e., we're not just sending sigint to the topmost +# processes in the pipeline). + +from signal import * from subprocess import * from sys import * from time import * -p = Popen(['sleep','5']) -if len(argv) == 1: +if len(argv) > 1 and argv[1] == 'signal': + def f(a,b): print 'got signal', a, b + signal( SIGTERM, f ) + signal( SIGINT, f ) +p = Popen(['sleep','50']) +if len(argv) == 1 or argv[1] != 'exit': try: p.wait() - except KeyboardInterrupt: print p.poll() - sleep(10) + except (KeyboardInterrupt, OSError), ex: print ex, p.poll() + sleep(2) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-12-03 21:28:16
|
Revision: 1526 http://assorted.svn.sourceforge.net/assorted/?rev=1526&view=rev Author: yangzhang Date: 2009-12-03 21:27:57 +0000 (Thu, 03 Dec 2009) Log Message: ----------- added tweetrec Added Paths: ----------- sandbox/trunk/src/one-off-scripts/tweetrec/ sandbox/trunk/src/one-off-scripts/tweetrec/README sandbox/trunk/src/one-off-scripts/tweetrec/tweetrec.py Added: sandbox/trunk/src/one-off-scripts/tweetrec/README =================================================================== --- sandbox/trunk/src/one-off-scripts/tweetrec/README (rev 0) +++ sandbox/trunk/src/one-off-scripts/tweetrec/README 2009-12-03 21:27:57 UTC (rev 1526) @@ -0,0 +1 @@ +Simply dumps the stream to stdout. Specify username and password in ~/.tweetrec.auth. Requires tweepy. Added: sandbox/trunk/src/one-off-scripts/tweetrec/tweetrec.py =================================================================== --- sandbox/trunk/src/one-off-scripts/tweetrec/tweetrec.py (rev 0) +++ sandbox/trunk/src/one-off-scripts/tweetrec/tweetrec.py 2009-12-03 21:27:57 UTC (rev 1526) @@ -0,0 +1,12 @@ +#!/usr/bin/env python + +from tweepy.streaming import * +import os, sys + +class MySl(StreamListener): + # on_data's dicts are actually more useful than on_sample's Sample objects. + def on_data(self, status): + print status, + +with file(os.path.expanduser('~/.tweetrec.auth')) as f: u,p = map(str.rstrip, f.readlines()) +Stream(u, p, MySl()).sample() Property changes on: sandbox/trunk/src/one-off-scripts/tweetrec/tweetrec.py ___________________________________________________________________ Added: svn:executable + * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-27 08:42:30
|
Revision: 1525 http://assorted.svn.sourceforge.net/assorted/?rev=1525&view=rev Author: yangzhang Date: 2009-11-27 08:42:16 +0000 (Fri, 27 Nov 2009) Log Message: ----------- added usage instructions Modified Paths: -------------- pitch-in/trunk/README Modified: pitch-in/trunk/README =================================================================== --- pitch-in/trunk/README 2009-11-27 08:04:53 UTC (rev 1524) +++ pitch-in/trunk/README 2009-11-27 08:42:16 UTC (rev 1525) @@ -7,12 +7,23 @@ Requirements ------------ -- [Django] 0.96 +- [Django] 1.1.1 (not included in GAE SDK) - [Google App Engine] [Django]: http://www.djangoproject.com/ [Google App Engine]: http://code.google.com/appengine/ +Usage +----- + +To start the GAE SDK's local development environment, run: + + dev_appserver.py src/pitchin + +To upload the code to your GAE account, run: + + appcfg.py update pitchin + Resources --------- This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-27 08:05:07
|
Revision: 1524 http://assorted.svn.sourceforge.net/assorted/?rev=1524&view=rev Author: yangzhang Date: 2009-11-27 08:04:53 +0000 (Fri, 27 Nov 2009) Log Message: ----------- forgot to add this in last commit Added Paths: ----------- pitch-in/trunk/src/pitchin/pitchin/common.py Added: pitch-in/trunk/src/pitchin/pitchin/common.py =================================================================== --- pitch-in/trunk/src/pitchin/pitchin/common.py (rev 0) +++ pitch-in/trunk/src/pitchin/pitchin/common.py 2009-11-27 08:04:53 UTC (rev 1524) @@ -0,0 +1,4 @@ +def isvalidnum(x): + try: float(x) + except ValueError: return False + else: return float(x) >= 0 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-27 08:04:49
|
Revision: 1523 http://assorted.svn.sourceforge.net/assorted/?rev=1523&view=rev Author: yangzhang Date: 2009-11-27 08:04:35 +0000 (Fri, 27 Nov 2009) Log Message: ----------- - using table layout for listing contributions - highlight contributions that are being counted in the aggregates - properly strip input - only count non-negative values - remove redundant escapes; django 1.0 introduced autoescape - updated todos - show min Modified Paths: -------------- pitch-in/trunk/README pitch-in/trunk/src/pitchin/pitchin/settings.py pitch-in/trunk/src/pitchin/pitchin/templates/pool.html pitch-in/trunk/src/pitchin/pitchin/views.py pitch-in/trunk/src/pitchin/static/default.css Added Paths: ----------- pitch-in/trunk/src/pitchin/pitchin/templatetags/ pitch-in/trunk/src/pitchin/pitchin/templatetags/__init__.py pitch-in/trunk/src/pitchin/pitchin/templatetags/filters.py Modified: pitch-in/trunk/README =================================================================== --- pitch-in/trunk/README 2009-11-27 06:35:23 UTC (rev 1522) +++ pitch-in/trunk/README 2009-11-27 08:04:35 UTC (rev 1523) @@ -31,10 +31,6 @@ - Other types of pools besides integers (decimals, unique strings, strings) - Comprehensive logging - Archiving/garbage collection -- Upgrade to Django 1.0. Nice new features in Django 1.0 include: - - new cycle syntax: cycle '0' '1' - - autoescape - - for key, value in collection Related ------- Modified: pitch-in/trunk/src/pitchin/pitchin/settings.py =================================================================== --- pitch-in/trunk/src/pitchin/pitchin/settings.py 2009-11-27 06:35:23 UTC (rev 1522) +++ pitch-in/trunk/src/pitchin/pitchin/settings.py 2009-11-27 08:04:35 UTC (rev 1523) @@ -81,6 +81,7 @@ 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', + 'pitchin', ) APPEND_SLASH = False Modified: pitch-in/trunk/src/pitchin/pitchin/templates/pool.html =================================================================== --- pitch-in/trunk/src/pitchin/pitchin/templates/pool.html 2009-11-27 06:35:23 UTC (rev 1522) +++ pitch-in/trunk/src/pitchin/pitchin/templates/pool.html 2009-11-27 08:04:35 UTC (rev 1523) @@ -1,21 +1,28 @@ {% extends 'base.html' %} +{% load filters %} {% block body %} - <p style="font-size: larger"><span style="font-weight: bold">Pool:</span> {{descrip|escape}}</p> + <p style="font-size: larger"><span style="font-weight: bold">Pool:</span> {{descrip}}</p> {% if not contribs %} <p style="font-style: italic;">(no participants yet)</p> {% else %} - {% for contrib in contribs %} - <div class="row{% cycle 0,1 %}">{{contrib.0|escape}}: {{contrib.1|escape}}</div> - {% endfor %} - {% for contrib in aggcontribs %} - <div class="aggrow">{{contrib.0|escape}}: {{contrib.1|escape}}</div> - {% endfor %} + <table class="contribs"> + <tr class="aggrow"><td>Name</td><td>Contribution</td></tr> + {% for name, val in contribs %} + {% comment %}<div class="row{% cycle 0,1 %}">{{name}}: {{val|boldnum}}</div>{% endcomment %} + <tr class="row{% cycle 0,1 %}"><td>{{name}}</td><td>{{val|boldnum}}</td></tr> + {% endfor %} + {% for name, val in aggcontribs %} + {% comment %}<div class="aggrow">{{name}}: {{val|boldnum}}</div>{% endcomment %} + <tr class="aggrow"><td>{{name}}</td><td>{{val|boldnum}}</td></tr> + {% endfor %} + </table> {% endif %} <p> To add or update your own contribution to the pool, enter the following information. </p> <form action="/pool" method="post"> + {% if form.errors %} <div class="errors"> {% comment %} <ul> @@ -26,12 +33,13 @@ {% endcomment %} {{form.errors}} </div> + {% endif %} {% comment %} {% for field in form %} {{field}} {% endfor %} {% endcomment %} - <div class="hideerrors">{{form}}</div> + <div class="hideerrors">{{form.as_p}}</div> <!-- <div> <input type="hidden" name="key" value="{{key|urlencode}}"/> @@ -39,13 +47,13 @@ <div> <label> Name: - <input type="text" name="name" value="{{name|escape}}"/> + <input type="text" name="name" value="{{name}}"/> </label> </div> <div> <label> Contribution: - <input type="text" name="contrib" value="{{contrib|escape}}"/> + <input type="text" name="contrib" value="{{contrib}}"/> </label> </div> --> Added: pitch-in/trunk/src/pitchin/pitchin/templatetags/filters.py =================================================================== --- pitch-in/trunk/src/pitchin/pitchin/templatetags/filters.py (rev 0) +++ pitch-in/trunk/src/pitchin/pitchin/templatetags/filters.py 2009-11-27 08:04:35 UTC (rev 1523) @@ -0,0 +1,12 @@ +from django import template +from django.template.defaultfilters import stringfilter +from django.utils.html import escape +from django.utils.safestring import mark_safe +from pitchin.common import isvalidnum + +register = template.Library() + +...@re...lter(name = 'boldnum') +@stringfilter +def boldnum(x): + return mark_safe('<strong>%s</strong>' % x) if isvalidnum(x) else escape(x) Modified: pitch-in/trunk/src/pitchin/pitchin/views.py =================================================================== --- pitch-in/trunk/src/pitchin/pitchin/views.py 2009-11-27 06:35:23 UTC (rev 1522) +++ pitch-in/trunk/src/pitchin/pitchin/views.py 2009-11-27 08:04:35 UTC (rev 1523) @@ -1,8 +1,9 @@ +from django import forms +from django.forms.util import ErrorList from django.http import HttpResponseRedirect from django.shortcuts import render_to_response -from django import forms -from django.forms.util import ErrorList from google.appengine.ext import db +from pitchin.common import isvalidnum from pitchin.models import Pool import cPickle, cgi @@ -14,14 +15,21 @@ return ( lambda *args, **kwargs: db.run_in_transaction_custom_retries(3, f, *args, **kwargs) ) -def isfloat(x): - try: float(x) - except ValueError: return False - else: return True - def mean(xs): return sum(xs) / len(xs) # +# General Django utilities. +# + +class StrippedCharField(forms.CharField): + """ + Newforms CharField that strips trailing and leading spaces + """ + def clean(self, value): + if value is not None: value = value.strip() + return super(StrippedCharField, self).clean(value) + +# # Application code. # @@ -34,12 +42,13 @@ def getContribs(pool): return cPickle.loads(str(pool.contribs)) def serContribs(contribs): return cPickle.dumps(contribs, 2) def aggContribs(contribs): - nums = map(float, filter(isfloat, contribs.itervalues())) - if len(nums) == 0 or len(nums) < len(contribs) / 2: + nums = [float(x) for x in contribs.itervalues() if isvalidnum(x)] + if len(nums) < 2: return [] else: return [ ( 'Total', '%.2f' % sum(nums) ), ( 'Average', '%.2f' % mean(nums) ), + ( 'Minimum', '%.2f' % min(nums) ), ( 'If everyone paid the minimum', '%.2f' % (len(contribs) * min(nums)) ) ] @@ -56,13 +65,13 @@ def as_divs(self): return u'' class ContactForm(forms.Form): - key = forms.CharField(required = True, + key = StrippedCharField(required = True, max_length = 100, widget = forms.HiddenInput) - name = forms.CharField(required = True, max_length = 100, + name = StrippedCharField(required = True, max_length = 100, label = 'Name', widget = forms.TextInput(attrs = {})) - contrib = forms.CharField(required = True, max_length = 100, label = 'Contribution') + contrib = StrippedCharField(required = True, max_length = 100, label = 'Contribution') def __init__(self, *args, **kwargs): #kwargs['error_class'] = CustomErrorList forms.Form.__init__(self, *args, **kwargs) @@ -112,7 +121,7 @@ try: form = ContactForm(request.REQUEST) if not form.is_valid(): raise invalid_submit(form.errors) - cleaned = form.clean_data + cleaned = form.cleaned_data except invalid_submit, ex: return view(request, form) else: Modified: pitch-in/trunk/src/pitchin/static/default.css =================================================================== --- pitch-in/trunk/src/pitchin/static/default.css 2009-11-27 06:35:23 UTC (rev 1522) +++ pitch-in/trunk/src/pitchin/static/default.css 2009-11-27 08:04:35 UTC (rev 1523) @@ -33,7 +33,7 @@ .text-input { width: 75%; } .quote { font-family: serif; font-size: 50pt; float: left; } .line { width: 75%; font-size: larger; font-style: italic; margin: 0 auto; margin-bottom: 50px; } -.rows { width: 75%; margin: 0 auto; } +.contribs { width: 50%; margin-left: 25%; margin-right: 25%; } .row0, .row1, .aggrow { padding-top: 3px; padding-bottom: 3px; } .row0 { background-color: #e3e3f8; } .row1 { background-color: #eeeeff; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-27 06:35:38
|
Revision: 1522 http://assorted.svn.sourceforge.net/assorted/?rev=1522&view=rev Author: yangzhang Date: 2009-11-27 06:35:23 +0000 (Fri, 27 Nov 2009) Log Message: ----------- - allow arbitrary contribution inputs, not just (integer) numbers - using django forms - migrated to django 1.1.1 - perform update from transaction - styled errors to be prettier - reorganized views.py Modified Paths: -------------- pitch-in/trunk/README pitch-in/trunk/src/pitchin/main.py pitch-in/trunk/src/pitchin/pitchin/templates/base.html pitch-in/trunk/src/pitchin/pitchin/templates/pool.html pitch-in/trunk/src/pitchin/pitchin/views.py pitch-in/trunk/src/pitchin/static/default.css Modified: pitch-in/trunk/README =================================================================== --- pitch-in/trunk/README 2009-11-26 09:57:59 UTC (rev 1521) +++ pitch-in/trunk/README 2009-11-27 06:35:23 UTC (rev 1522) @@ -35,3 +35,9 @@ - new cycle syntax: cycle '0' '1' - autoescape - for key, value in collection + +Related +------- + +- [ChipIn](http://www.chipin.com/) +- [KickStarter](http://www.kickstarter.com/) Modified: pitch-in/trunk/src/pitchin/main.py =================================================================== --- pitch-in/trunk/src/pitchin/main.py 2009-11-26 09:57:59 UTC (rev 1521) +++ pitch-in/trunk/src/pitchin/main.py 2009-11-27 06:35:23 UTC (rev 1522) @@ -1,3 +1,5 @@ +# main.py for Django 1.1: <http://tekpizza.blogspot.com/2009/11/mainpy-for-django-11-in-google-app.html> + import logging, os # Google App Engine imports. @@ -6,6 +8,9 @@ # Must set this env var before importing any part of Django os.environ['DJANGO_SETTINGS_MODULE'] = 'pitchin.settings' +from google.appengine.dist import use_library +use_library('django', '1.1') + # Force Django to reload its settings. from django.conf import settings settings._target = None @@ -19,14 +24,13 @@ def log_exception(*args, **kwds): logging.exception('Exception in request:') +dispatcher = django.dispatch.dispatcher.Signal() + # Log errors. -django.dispatch.dispatcher.connect( - log_exception, django.core.signals.got_request_exception) +dispatcher.connect(log_exception, django.core.signals.got_request_exception) # Unregister the rollback event handler. -django.dispatch.dispatcher.disconnect( - django.db._rollback_on_exception, - django.core.signals.got_request_exception) +dispatcher.disconnect(django.db._rollback_on_exception, django.core.signals.got_request_exception) def main(): # Create a Django application for WSGI. Modified: pitch-in/trunk/src/pitchin/pitchin/templates/base.html =================================================================== --- pitch-in/trunk/src/pitchin/pitchin/templates/base.html 2009-11-26 09:57:59 UTC (rev 1521) +++ pitch-in/trunk/src/pitchin/pitchin/templates/base.html 2009-11-27 06:35:23 UTC (rev 1522) @@ -16,8 +16,8 @@ {% block body %}{% endblock %} <div style="margin-top: 50px"> <small> - <strong>PitchIn</strong> © 2009 <a href="http://www.mit.edu/~y_z/">YZ</a> | - <a href="http://assorted.sf.net/pitch-in/">AGPL Source</a> <!--| + <strong>PitchIn</strong> © 2009 Yang Zhang, Richard West <!--<a href="http://www.mit.edu/~y_z/">YZ</a> | + <a href="http://assorted.sf.net/pitch-in/">AGPL Source</a> --><!--| <a href="sponsorship">Sponsorship</a>--> </small> </div> Modified: pitch-in/trunk/src/pitchin/pitchin/templates/pool.html =================================================================== --- pitch-in/trunk/src/pitchin/pitchin/templates/pool.html 2009-11-26 09:57:59 UTC (rev 1521) +++ pitch-in/trunk/src/pitchin/pitchin/templates/pool.html 2009-11-27 06:35:23 UTC (rev 1522) @@ -16,7 +16,23 @@ the following information. </p> <form action="/pool" method="post"> - <p class="error">{{error}}</p> + <div class="errors"> + {% comment %} + <ul> + {% for field, errors in form.errors.iteritems %} + <li>{{form.field.label}}: {{errors}}</li> + {% endfor %} + </ul> + {% endcomment %} + {{form.errors}} + </div> + {% comment %} + {% for field in form %} + {{field}} + {% endfor %} + {% endcomment %} + <div class="hideerrors">{{form}}</div> + <!-- <div> <input type="hidden" name="key" value="{{key|urlencode}}"/> </div> @@ -29,9 +45,10 @@ <div> <label> Contribution: - <input type="text" name="amount" value="{{amount|escape}}"/> + <input type="text" name="contrib" value="{{contrib|escape}}"/> </label> </div> + --> <div><input type="submit" value="Enter the pool!"/></div> </form> {% endblock %} Modified: pitch-in/trunk/src/pitchin/pitchin/views.py =================================================================== --- pitch-in/trunk/src/pitchin/pitchin/views.py 2009-11-26 09:57:59 UTC (rev 1521) +++ pitch-in/trunk/src/pitchin/pitchin/views.py 2009-11-27 06:35:23 UTC (rev 1522) @@ -1,9 +1,30 @@ from django.http import HttpResponseRedirect from django.shortcuts import render_to_response +from django import forms +from django.forms.util import ErrorList from google.appengine.ext import db from pitchin.models import Pool import cPickle, cgi +# +# General utilities. +# + +def txn(f): + return ( lambda *args, **kwargs: + db.run_in_transaction_custom_retries(3, f, *args, **kwargs) ) + +def isfloat(x): + try: float(x) + except ValueError: return False + else: return True + +def mean(xs): return sum(xs) / len(xs) + +# +# Application code. +# + class invalid_pool(Exception): pass def getPool(request): @@ -13,18 +34,64 @@ def getContribs(pool): return cPickle.loads(str(pool.contribs)) def serContribs(contribs): return cPickle.dumps(contribs, 2) def aggContribs(contribs): - if len(contribs) == 0: + nums = map(float, filter(isfloat, contribs.itervalues())) + if len(nums) == 0 or len(nums) < len(contribs) / 2: return [] else: - return [('Max total', sum(contribs.itervalues())), - ('If everyone paid the minimum', len(contribs) * min(contribs.itervalues()))] + return [ ( 'Total', '%.2f' % sum(nums) ), + ( 'Average', '%.2f' % mean(nums) ), + ( 'If everyone paid the minimum', + '%.2f' % (len(contribs) * min(nums)) ) ] class invalid_submit(Exception): pass def validate(pred, msg): if not pred: raise invalid_submit(msg) -### Views +# +# Forms. +# +class CustomErrorList(ErrorList): + def __unicode__(self): return self.as_divs() + def as_divs(self): return u'' + +class ContactForm(forms.Form): + key = forms.CharField(required = True, + max_length = 100, + widget = forms.HiddenInput) + name = forms.CharField(required = True, max_length = 100, + label = 'Name', + widget = forms.TextInput(attrs = {})) + contrib = forms.CharField(required = True, max_length = 100, label = 'Contribution') + def __init__(self, *args, **kwargs): + #kwargs['error_class'] = CustomErrorList + forms.Form.__init__(self, *args, **kwargs) + +# +# Common code for views. +# + +def bad_pool(request): + return render_to_response('main.html', dict(generror = 'Pool not found/invalid pool ID')) + +def view(request, form): + if 'key' not in request.REQUEST: + return HttpResponseRedirect('/') + try: + pool = getPool(request) + return render_to_response('pool.html', + dict(descrip = pool.descrip, + contribs = getContribs(pool).items(), + aggcontribs = aggContribs(getContribs(pool)), + key = request.REQUEST['key'], + form = form)) + except invalid_pool: + return bad_pool(request) + +# +# Views. +# + def main(request): return render_to_response('main.html') @@ -38,45 +105,28 @@ return render_to_response('created.html', {'key': pool.key()}) def pool(request): - if request.method == 'GET': return view(request) + if request.method == 'GET': return view(request, ContactForm(initial = request.REQUEST)) else: return update(request) -def view(request, **params): - if 'key' not in request.REQUEST: - return HttpResponseRedirect('/') - try: - pool = getPool(request) - return render_to_response('pool.html', - dict(descrip = pool.descrip, - contribs = getContribs(pool).iteritems(), - aggcontribs = aggContribs(getContribs(pool)), - key = request.REQUEST['key'], - **params)) - except invalid_pool: - return bad_pool(request) - def update(request): try: - validate(request.REQUEST['name'].strip() != '', - 'You must enter a name.') - try: amount = int(request.REQUEST['amount']) - except ValueError: raise invalid_submit('You must enter an integer dollar amount.') + form = ContactForm(request.REQUEST) + if not form.is_valid(): raise invalid_submit(form.errors) + cleaned = form.clean_data except invalid_submit, ex: - return view(request, error = ex, name = request.REQUEST['name'], amount = request.REQUEST['amount']) + return view(request, form) else: - try: + @txn + def f(): pool = getPool(request) - except invalid_pool: - return bad_pool(request) - else: contribs = getContribs(pool) - contribs[request.REQUEST['name']] = amount + contribs[cleaned['name']] = cleaned['contrib'] pool.contribs = cPickle.dumps(contribs) pool.put() - return HttpResponseRedirect('/pool?key=%s' % pool.key()) + return pool + try: pool = f() + except invalid_pool: return bad_pool(request) + else: return HttpResponseRedirect('/pool?key=%s' % pool.key()) def sponsorship(request): return render_to_response('sponsorship.html') - -def bad_pool(request): - return render_to_response('main.html', dict(generror = 'Pool not found/invalid pool ID')) Modified: pitch-in/trunk/src/pitchin/static/default.css =================================================================== --- pitch-in/trunk/src/pitchin/static/default.css 2009-11-26 09:57:59 UTC (rev 1521) +++ pitch-in/trunk/src/pitchin/static/default.css 2009-11-27 06:35:23 UTC (rev 1522) @@ -7,7 +7,16 @@ .boxtop { background: url(tr.png) no-repeat top right; } .header { text-align: center; width: 100%; } .body { margin: 0 30px; text-align: center; } -.error { color: red; } +.errors { + background-color: #eeeeee; text-align: left; font-style: italic; opacity: 50%; + /*border-top: 28px; /*border-right: 14px;*/ + margin-left: 25%; margin-right: 25%; padding-top: 5px; padding-bottom: 5px; + -webkit-border-bottom-left-radius: 14px 14px; + -webkit-border-bottom-right-radius: 14px 14px; + -webkit-border-top-left-radius: 14px 14px; + -webkit-border-top-right-radius: 14px 14px; +} +.hideerrors .errorlist { display: none; } .example { background-color: #ffffcc; margin: 50px 0; padding: 10px 0; } .boxbottom div { background: url(bl.png) no-repeat bottom left; } .boxbottom { background: url(br.png) no-repeat bottom right; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-26 09:58:09
|
Revision: 1521 http://assorted.svn.sourceforge.net/assorted/?rev=1521&view=rev Author: yangzhang Date: 2009-11-26 09:57:59 +0000 (Thu, 26 Nov 2009) Log Message: ----------- changed license Modified Paths: -------------- cpp-commons/trunk/publish.bash Modified: cpp-commons/trunk/publish.bash =================================================================== --- cpp-commons/trunk/publish.bash 2009-11-26 09:57:53 UTC (rev 1520) +++ cpp-commons/trunk/publish.bash 2009-11-26 09:57:59 UTC (rev 1521) @@ -4,7 +4,7 @@ fullname='C++ Commons' version=0.1 -license=gpl3 +license=boost websrcs=( README ) webfiles=( doc:doc/html ) rels=( src-tgz: ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-26 09:58:03
|
Revision: 1520 http://assorted.svn.sourceforge.net/assorted/?rev=1520&view=rev Author: yangzhang Date: 2009-11-26 09:57:53 +0000 (Thu, 26 Nov 2009) Log Message: ----------- added boost software license Modified Paths: -------------- shell-tools/trunk/src/bash-commons/assorted.bash Modified: shell-tools/trunk/src/bash-commons/assorted.bash =================================================================== --- shell-tools/trunk/src/bash-commons/assorted.bash 2009-11-26 09:57:22 UTC (rev 1519) +++ shell-tools/trunk/src/bash-commons/assorted.bash 2009-11-26 09:57:53 UTC (rev 1520) @@ -49,7 +49,7 @@ elif kind == 'pypi': # TODO this should be more robust yield ( '[download $version egg]', - 'http://pypi.python.org/packages/2.5/${project:0:1}/$project/$( echo $project | sed s/-/_/g )-$version-py2.5.egg' ) + 'http://pypi.python.org/packages/2.6/${project:0:1}/$project/$( echo $project | sed s/-/_/g )-$version-py2.6.egg' ) yield ( '[download $version src tgz]', 'http://pypi.python.org/packages/source/${project:0:1}/$project/$package.tar.gz' ) yield ( '[PyPI page]', @@ -108,6 +108,9 @@ local license_text license_links case $license in + boost ) + license_text='the [Boost Software License][BSL]' + license_links='[BSL]: http://www.boost.org/LICENSE_1_0.txt' ;; gpl3 ) license_text='the [GNU GPL3]' license_links='[GNU GPL3]: http://www.gnu.org/licenses/gpl.html' ;; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-26 09:57:34
|
Revision: 1519 http://assorted.svn.sourceforge.net/assorted/?rev=1519&view=rev Author: yangzhang Date: 2009-11-26 09:57:22 +0000 (Thu, 26 Nov 2009) Log Message: ----------- updatd overview list Modified Paths: -------------- cpp-commons/trunk/README Modified: cpp-commons/trunk/README =================================================================== --- cpp-commons/trunk/README 2009-11-23 08:00:47 UTC (rev 1518) +++ cpp-commons/trunk/README 2009-11-26 09:57:22 UTC (rev 1519) @@ -10,46 +10,51 @@ Features: -- C functions for string manipulation -- RAII utilities, such as for closing file descriptors and `finally` objects -- smart arrays: sized arrays, "managed" (moveable, conditionally - scope-destroyed) arrays - `pool`: fixed-size object pools - bit manipulation - bundles of header includes +- C functions for string manipulation +- C++ abstractions for `mmap` - C++ support for pthreads, but allowing the user to access the underlying `pthread_t` (a major annoyance of using boost threads was its complete encapsulation) - C++ support for [State Threads] - check macros (like assertions but never removed from compilation) +- concurrent queue +- convenience functions for [libcrypto] - `deque`: simpler deque implementation that uses coarse-grained allocation - error handling, such as `die()`, which leverages `strerror` - file I/O utilities, such as reading complete files or common operations like finding file sizes +- function composition combinators - function delegates (for use with C functions that take `(void*)(void*)`) - generic binary stream readers and writers that are more efficient than std::streambuf - hash functions - low-level system information from `cpuid` +- macros for compiler features, such as C++0x support (see also [Boost.Macro]) - micro-utilities: noncopyable, expander annotations +- name resolution convenience functions - `nullptr`: from C++0x - portable re-implementations of pthread primitives such as barriers - pseudo-random number generators +- RAII utilities, such as for closing file descriptors and `finally` objects - raw memory buffer readers and writers for simple serialization - region-based memory management -- socket utilities +- serializable object memory pool with coarse-grained versioned pages +- simple `atomic<T>` +- smart arrays: sized arrays, "managed" (moveable, conditionally + scope-destroyed) arrays +- socket (and related data structure) utilities +- stream formatters (e.g. for arrays) - time utilities, including timers and simpler interfaces to system clocks +- tmpstream: throw-away stream for easily building strings - utilities for streams - utilities for [tamer] - x86 architecture-specific tools -- serializable object memory pool with coarse-grained versioned pages -- C++ abstractions for `mmap` -- concurrent queue -- stream formatters (e.g. for arrays) -- bit manipulation -- simple `atomic<T>` -- convenience functions for [libcrypto] +[Boost.Macro]: http://www.boost.org/doc/libs/1_40_0/libs/config/doc/html/boost_config/boost_macro_reference.html#boost_config.boost_macro_reference.macros_that_describe_possible_c__0x_features + Third-party code: - GCC's [C++0x `unique_ptr`], backported from 144716 @@ -96,6 +101,7 @@ - [State Threads]: lightweight cooperative threads library that focuses on performance and provides network IO. +[GCC]: http://gcc.gnu.org/ [boost]: http://boost.org/ [libstdc++]: http://gcc.gnu.org/libstdc++/ [stlport]: http://www.stlport.org/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-23 08:00:56
|
Revision: 1518 http://assorted.svn.sourceforge.net/assorted/?rev=1518&view=rev Author: yangzhang Date: 2009-11-23 08:00:47 +0000 (Mon, 23 Nov 2009) Log Message: ----------- fixed to_utf8/to_utf16 calls Modified Paths: -------------- cpp-commons/trunk/src/commons/resolver.h Modified: cpp-commons/trunk/src/commons/resolver.h =================================================================== --- cpp-commons/trunk/src/commons/resolver.h 2009-11-23 08:00:21 UTC (rev 1517) +++ cpp-commons/trunk/src/commons/resolver.h 2009-11-23 08:00:47 UTC (rev 1518) @@ -21,7 +21,7 @@ /** Get the hostname's IPv4 address as an int in network byte order. */ inline uint32_t name2nl(DNS &dns, const wstring &name) { - return name2nl(dns, to_string(name)); + return name2nl(dns, to_utf8(name)); } /** Get the hostname's IPv4 address as an int in host byte order. */ @@ -31,7 +31,7 @@ /** Get the hostname's IPv4 address as an int in host byte order. */ inline uint32_t name2hl(DNS &dns, const wstring &name) { - return name2hl(dns, to_string(name)); + return name2hl(dns, to_utf8(name)); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-23 08:00:27
|
Revision: 1517 http://assorted.svn.sourceforge.net/assorted/?rev=1517&view=rev Author: yangzhang Date: 2009-11-23 08:00:21 +0000 (Mon, 23 Nov 2009) Log Message: ----------- added ostream formatter wchar_t and wostream formatter for char Modified Paths: -------------- cpp-commons/trunk/src/commons/streams.h Modified: cpp-commons/trunk/src/commons/streams.h =================================================================== --- cpp-commons/trunk/src/commons/streams.h 2009-11-23 07:59:25 UTC (rev 1516) +++ cpp-commons/trunk/src/commons/streams.h 2009-11-23 08:00:21 UTC (rev 1517) @@ -36,15 +36,27 @@ * Allow wstrings to be printed to ostreams. */ inline ostream &operator<<(ostream &o, const wstring &s) - { return o << to_string(s); } + { return o << to_utf8(s); } /** * Allow strings to be printed to wostreams. */ inline wostream &operator<<(wostream &o, const string &s) - { return o << to_wstring(s); } + { return o << to_utf16(s); } /** + * Allow wchar_t* to be printed to ostreams. + */ + inline ostream &operator<<(ostream &o, const wchar_t *s) + { return o << wstring(s); } + + /** + * Allow char* to be printed to wostreams. + */ + inline wostream &operator<<(wostream &o, const char *s) + { return o << string(s); } + + /** * Wrapper around integral types that enables pretty printing as hex numbers. */ template<typename T> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-23 07:59:36
|
Revision: 1516 http://assorted.svn.sourceforge.net/assorted/?rev=1516&view=rev Author: yangzhang Date: 2009-11-23 07:59:25 +0000 (Mon, 23 Nov 2009) Log Message: ----------- added ostream formatter for in_addrs; added nl_to_in_addr, hl_to_in_addr; const/doc tweaks Modified Paths: -------------- cpp-commons/trunk/src/commons/sockets.h Modified: cpp-commons/trunk/src/commons/sockets.h =================================================================== --- cpp-commons/trunk/src/commons/sockets.h 2009-11-23 07:58:04 UTC (rev 1515) +++ cpp-commons/trunk/src/commons/sockets.h 2009-11-23 07:59:25 UTC (rev 1516) @@ -19,6 +19,8 @@ #include <commons/closing.h> #include <commons/nullptr.h> +#include <Poco/Net/IPAddress.h> + namespace commons { @@ -121,14 +123,14 @@ * Initialize an inet address. */ inline void - sockaddr_init(sockaddr_in &a, in_addr host, uint16_t port) + sockaddr_init(sockaddr_in &a, const in_addr &host, uint16_t port) { sockaddr_init(a, port); a.sin_addr = host; } /** - * Initialize an inet addres. + * Initialize an inet address. host is in network byte order. */ inline void sockaddr_init(sockaddr_in &a, uint32_t host, uint16_t port) @@ -286,14 +288,45 @@ } #endif - /** Get the IPv4 address as an int in network byte order. */ + /** + * Convert an IPv4 address from an in_addr in network byte order to an int + * in network byte order. + */ inline uint32_t ipaddr2nl(const in_addr &a) { return IFWIN32(a.S_un.S_addr, a.s_addr); } - /** Get the IPv4 address as an int in host byte order. */ + /** + * Convert an IPv4 address from an in_addr in network byte order to an int + * in host byte order. + */ inline uint32_t ipaddr2hl(const in_addr &a) { return ntohl(ipaddr2nl(a)); } + /** + * Convert an IPv4 address from an int in network byte order to an in_addr + * in network byte order. + */ + inline in_addr nl_to_in_addr(uint32_t x) + { + in_addr y; + IFWIN32(y.S_un.S_addr, y.s_addr) = x; + return y; + } + + /** + * Convert an IPv4 address from an int in host byte order to an in_addr + * in network byte order. + */ + inline in_addr hl_to_in_addr(uint32_t x) + { + in_addr y = nl_to_in_addr(x); + htonl(IFWIN32(y.S_un.S_addr, y.s_addr)); + return y; + } + + inline ostream& operator <<(ostream &o, const in_addr &ip) + { return o << Poco::Net::IPAddress(&ip, sizeof ip).toString(); } + } #endif This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-23 07:58:14
|
Revision: 1515 http://assorted.svn.sourceforge.net/assorted/?rev=1515&view=rev Author: yangzhang Date: 2009-11-23 07:58:04 +0000 (Mon, 23 Nov 2009) Log Message: ----------- added C++ guards Modified Paths: -------------- cpp-commons/trunk/src/commons/strings.h Modified: cpp-commons/trunk/src/commons/strings.h =================================================================== --- cpp-commons/trunk/src/commons/strings.h 2009-11-23 07:57:04 UTC (rev 1514) +++ cpp-commons/trunk/src/commons/strings.h 2009-11-23 07:58:04 UTC (rev 1515) @@ -19,6 +19,8 @@ using namespace std; +#ifndef __cplusplus + /** * Search in p for the nth instance of c and return the character past it. */ @@ -106,6 +108,8 @@ // return NULL; // } +#endif + /** * Convert UTF-16 to UTF-8. */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-23 07:57:15
|
Revision: 1514 http://assorted.svn.sourceforge.net/assorted/?rev=1514&view=rev Author: yangzhang Date: 2009-11-23 07:57:04 +0000 (Mon, 23 Nov 2009) Log Message: ----------- only use if nullptr not already avail (VS2010) Modified Paths: -------------- cpp-commons/trunk/src/commons/nullptr.h Modified: cpp-commons/trunk/src/commons/nullptr.h =================================================================== --- cpp-commons/trunk/src/commons/nullptr.h 2009-11-20 07:19:26 UTC (rev 1513) +++ cpp-commons/trunk/src/commons/nullptr.h 2009-11-23 07:57:04 UTC (rev 1514) @@ -1,11 +1,15 @@ #ifndef COMMONS_NULLPTR_H #define COMMONS_NULLPTR_H +#include <boost/config.hpp> + // From <http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/nullptr> namespace commons { +#ifdef BOOST_NO_NULLPTR + const // It is a const object... class nullptr_t { @@ -23,6 +27,8 @@ } nullptr = {}; +#endif + } #endif This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-20 07:19:36
|
Revision: 1513 http://assorted.svn.sourceforge.net/assorted/?rev=1513&view=rev Author: yangzhang Date: 2009-11-20 07:19:26 +0000 (Fri, 20 Nov 2009) Log Message: ----------- added crawl-google-cache Added Paths: ----------- sandbox/trunk/src/one-off-scripts/crawl-google-cache/ sandbox/trunk/src/one-off-scripts/crawl-google-cache/README sandbox/trunk/src/one-off-scripts/crawl-google-cache/extract-urls.py Added: sandbox/trunk/src/one-off-scripts/crawl-google-cache/README =================================================================== --- sandbox/trunk/src/one-off-scripts/crawl-google-cache/README (rev 0) +++ sandbox/trunk/src/one-off-scripts/crawl-google-cache/README 2009-11-20 07:19:26 UTC (rev 1513) @@ -0,0 +1,12 @@ +This is for grabbing a bunch of Google Cache pages off of Google. + +Require BeautifulSoup 3.0.7a. + +First, do your search on Google, turn up the number of results per page so +you only have to load a few pages, and save each result page to disk. Now run +`extract-urls.py RESULTPAGES...` to extract the cached page URLs, piping the +output to a file `URLSFILE`. Finally, run + + wget -i URLSFILE -w 30 -U 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5' + +to grab all the files. Added: sandbox/trunk/src/one-off-scripts/crawl-google-cache/extract-urls.py =================================================================== --- sandbox/trunk/src/one-off-scripts/crawl-google-cache/extract-urls.py (rev 0) +++ sandbox/trunk/src/one-off-scripts/crawl-google-cache/extract-urls.py 2009-11-20 07:19:26 UTC (rev 1513) @@ -0,0 +1,12 @@ +#!/usr/bin/env python + +from BeautifulSoup import BeautifulSoup as BS +import sys + +def go(paths): + for path in paths: + with file(path) as f: bs = BS(f.read()) + print '\n'.join(t['href'] for t in bs('a') if t(text='Cached')) + return bs + +if __name__ == '__main__': go(sys.argv[1:]) Property changes on: sandbox/trunk/src/one-off-scripts/crawl-google-cache/extract-urls.py ___________________________________________________________________ Added: svn:executable + * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-20 06:06:05
|
Revision: 1512 http://assorted.svn.sourceforge.net/assorted/?rev=1512&view=rev Author: yangzhang Date: 2009-11-20 06:05:54 +0000 (Fri, 20 Nov 2009) Log Message: ----------- taint check Added Paths: ----------- sandbox/trunk/src/pl/taint.pl Added: sandbox/trunk/src/pl/taint.pl =================================================================== --- sandbox/trunk/src/pl/taint.pl (rev 0) +++ sandbox/trunk/src/pl/taint.pl 2009-11-20 06:05:54 UTC (rev 1512) @@ -0,0 +1,6 @@ +#!/usr/bin/env perl +# Test whether tainting is enabled. + +$arg = shift; +print "$arg\n"; +system "echo $arg"; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-09 04:18:55
|
Revision: 1511 http://assorted.svn.sourceforge.net/assorted/?rev=1511&view=rev Author: yangzhang Date: 2009-11-09 04:18:43 +0000 (Mon, 09 Nov 2009) Log Message: ----------- - added resolver.h, functions.h, cxx0x.h - added socket-related data structure converters - added hexfmt - added to_string, to_wstring for windows code page/wide char conversions - added to_utf8, to_utf16 converters - fixed stream formatter for vectors - conditional (non-WIN32) compilation of unique_ptr, array, files.h - more overloads in files.h - removed executable properties on files Modified Paths: -------------- cpp-commons/trunk/src/commons/array.h cpp-commons/trunk/src/commons/files.h cpp-commons/trunk/src/commons/sockets.h cpp-commons/trunk/src/commons/streams.h cpp-commons/trunk/src/commons/strings.h cpp-commons/trunk/src/commons/unique_ptr.h Added Paths: ----------- cpp-commons/trunk/src/commons/cxx0x.h cpp-commons/trunk/src/commons/functions.h cpp-commons/trunk/src/commons/resolver.h Property Changed: ---------------- cpp-commons/trunk/src/commons/win.h Modified: cpp-commons/trunk/src/commons/array.h =================================================================== --- cpp-commons/trunk/src/commons/array.h 2009-11-08 18:27:35 UTC (rev 1510) +++ cpp-commons/trunk/src/commons/array.h 2009-11-09 04:18:43 UTC (rev 1511) @@ -40,6 +40,20 @@ size_t n_; }; + // TODO: try just specifying a single templated function + /** + * Swap two arrays. + */ + template<typename T> + void + inline swap(sized_array<T> &a, sized_array<T> &b) + { + std::swap(a.p_, b.p_); + swap(a.n_, b.n_); + } + +#ifdef COMMONS_CXX0X + // TODO: rename /** * A thin wrapper around arrays. Like a fixed-size vector. Unlike array @@ -92,19 +106,7 @@ swap(a.n_, b.n_); } - // TODO: try just specifying a single templated function /** - * Swap two arrays. - */ - template<typename T> - void - inline swap(sized_array<T> &a, sized_array<T> &b) - { - std::swap(a.p_, b.p_); - swap(a.n_, b.n_); - } - - /** * Conditionally-scoped, move-able, release-able, un-sized array. */ template<typename T> @@ -128,6 +130,8 @@ bool scoped_; }; +#endif + /** * Checks if a pointer is in an array. */ Added: cpp-commons/trunk/src/commons/cxx0x.h =================================================================== --- cpp-commons/trunk/src/commons/cxx0x.h (rev 0) +++ cpp-commons/trunk/src/commons/cxx0x.h 2009-11-09 04:18:43 UTC (rev 1511) @@ -0,0 +1,8 @@ +#ifndef COMMONS_CXX0X_H +#define COMMONS_CXX0X_H + +#ifdef __GXX_EXPERIMENTAL_CXX0X__ +#define COMMONS_CXX0X +#endif + +#endif Modified: cpp-commons/trunk/src/commons/files.h =================================================================== --- cpp-commons/trunk/src/commons/files.h 2009-11-08 18:27:35 UTC (rev 1510) +++ cpp-commons/trunk/src/commons/files.h 2009-11-09 04:18:43 UTC (rev 1511) @@ -1,6 +1,7 @@ #ifndef COMMONS_FILES_H #define COMMONS_FILES_H +#include <cstdio> #include <exception> #include <fstream> #include <iostream> @@ -9,7 +10,9 @@ #include <sys/types.h> #include <sys/stat.h> +#ifndef WIN32 #include <unistd.h> +#endif #include <fcntl.h> #include <commons/array.h> @@ -21,10 +24,10 @@ using namespace std; - class file_not_found_exception : std::exception { + class file_open_exception : std::exception { public: - file_not_found_exception(const string & name) : name(name) {} - virtual ~file_not_found_exception() throw() {} + file_open_exception(const string & name) : name(name) {} + virtual ~file_open_exception() throw() {} private: const string name; }; @@ -52,25 +55,37 @@ /** * Read in a whole file as a string. */ - UNUSED static void read_file_as_string ( const string & name, string & out ) { - ifstream in ( name.c_str() ); - if (in.fail()) throw file_not_found_exception( name ); - out = string ( istreambuf_iterator<char> ( in ), istreambuf_iterator<char>() ); + inline void read_file_as_string(const char * name, string & out ) { + ifstream in ( name ); + if (in.fail()) throw file_open_exception( name ); + out.assign(istreambuf_iterator<char>(in), istreambuf_iterator<char>()); } /** + * Read in a whole file as a string. + */ + inline string read_file_as_string ( const char * name ) + { + string s; + read_file_as_string(name, s); + return s; + } + + /** * Read in a whole file as a vector of chars. */ - UNUSED static void read_file_as_vector ( const string & name, vector<char> & out ) { - ifstream in ( name.c_str() ); - if ( in.fail() ) throw file_not_found_exception( name ); - out = vector<char> ( istreambuf_iterator<char> ( in ), istreambuf_iterator<char>() ); + inline void read_file_as_vector(const char * name, vector<char> & out) { + ifstream in ( name ); + if ( in.fail() ) throw file_open_exception( name ); + out.assign(istreambuf_iterator<char>(in), istreambuf_iterator<char>()); } +#ifndef WIN32 + /** * Read in a whole file as an array. */ - UNUSED static array<char> read_file_as_array(const char *path) + inline array<char> read_file_as_array(const char *path) { closingfd fd(checknnegerr(open(path, O_RDONLY))); array<char> buf(file_size(fd)); @@ -78,7 +93,7 @@ return buf; } - UNUSED static void write_file(int fd, const void *buf, size_t len) + inline void write_file(int fd, const void *buf, size_t len) { checkeqnneg(write(fd, buf, len), ssize_t(len)); } @@ -86,7 +101,7 @@ /** * Write a whole array to disk. */ - UNUSED static void write_file(const char *path, const void *buf, size_t len) + inline void write_file(const char *path, const void *buf, size_t len) { closingfd fd(checknnegerr(creat(path, 0644))); write_file(fd, buf, len); @@ -95,7 +110,7 @@ /** * Write a whole array to disk. */ - UNUSED static void write_file(const char *path, const array<char> &buf) + inline void write_file(const char *path, const array<char> &buf) { write_file(path, buf, buf.size()); } @@ -106,7 +121,7 @@ * TODO this probably isn't very safe, since we're demoting an off_t to a * size_t. Is there a healthier approach? */ - UNUSED static char * + inline char * load_file(const char *path, size_t & len, unsigned int ncpus) { struct stat sb; @@ -148,6 +163,8 @@ errno = 0; } +#endif + } #endif Added: cpp-commons/trunk/src/commons/functions.h =================================================================== --- cpp-commons/trunk/src/commons/functions.h (rev 0) +++ cpp-commons/trunk/src/commons/functions.h 2009-11-09 04:18:43 UTC (rev 1511) @@ -0,0 +1,23 @@ +#ifndef COMMONS_FUNCTIONS_H +#define COMMONS_FUNCTIONS_H + +#include <boost/bind.hpp> +#include <boost/function.hpp> + +namespace commons +{ + + using boost::bind; + using boost::function; + + template<typename C, typename A, typename B> + function<C(A)> compose(function<C(A)> f, function<A(B)> g) + { return bind(f, bind(g, _1)); } + + template<typename B, typename A> + function<B> operator*(function<B> f, function<A> g) + { return compose(f, g); } + +} + +#endif Added: cpp-commons/trunk/src/commons/resolver.h =================================================================== --- cpp-commons/trunk/src/commons/resolver.h (rev 0) +++ cpp-commons/trunk/src/commons/resolver.h 2009-11-09 04:18:43 UTC (rev 1511) @@ -0,0 +1,39 @@ +#ifndef RESOLVER_H +#define RESOLVER_H + +#include <commons/sockets.h> +#include <commons/strings.h> +#include <Poco/Net/DNS.h> + +/** + * Convenience functions for resolving hostnames. + */ + +namespace commons +{ + + using namespace Poco::Net; + + /** Get the hostname's IPv4 address as an int in network byte order. */ + inline uint32_t name2nl(DNS &dns, const string &name) { + return ipaddr2nl(*reinterpret_cast<const in_addr*>(dns.resolveOne(name).addr())); + } + + /** Get the hostname's IPv4 address as an int in network byte order. */ + inline uint32_t name2nl(DNS &dns, const wstring &name) { + return name2nl(dns, to_string(name)); + } + + /** Get the hostname's IPv4 address as an int in host byte order. */ + inline uint32_t name2hl(DNS &dns, const string &name) { + return ipaddr2hl(*reinterpret_cast<const in_addr*>(dns.resolveOne(name).addr())); + } + + /** Get the hostname's IPv4 address as an int in host byte order. */ + inline uint32_t name2hl(DNS &dns, const wstring &name) { + return name2hl(dns, to_string(name)); + } + +} + +#endif Modified: cpp-commons/trunk/src/commons/sockets.h =================================================================== --- cpp-commons/trunk/src/commons/sockets.h 2009-11-08 18:27:35 UTC (rev 1510) +++ cpp-commons/trunk/src/commons/sockets.h 2009-11-09 04:18:43 UTC (rev 1511) @@ -3,6 +3,7 @@ #ifdef WIN32 #include <winsock2.h> +#include <ws2tcpip.h> #else #include <arpa/inet.h> #include <netdb.h> @@ -24,7 +25,7 @@ #ifdef WIN32 typedef SOCKET socket_t; - int inet_aton(const char *cp, struct in_addr *inp) { + inline int inet_aton(const char *cp, struct in_addr *inp) { uint32_t a = inet_addr(cp); if (a == INADDR_NONE) return 0; inp->S_un.S_addr = a; @@ -148,7 +149,7 @@ return a; } - void close_socket(socket_t s) { + inline void close_socket(socket_t s) { #ifdef WIN32 closesocket(s); #else @@ -219,35 +220,55 @@ return c.release(); } +#if 0 #if defined(WIN32) && defined(UNICODE) #define getnameinfo GetNameInfoW #define getaddrinfo GetAddrInfoW #define addrinfo ADDRINFOW #define freeaddrinfo FreeAddrInfoW #endif +#endif +#if 0 /** - * T is a string or wstring. + * Resolve a sockaddr's IP address to its hostname. */ - template<typename T> - sockaddr_in - addr2name(const sockaddr_in sa) + inline string + sockaddr2hostname(const sockaddr_in &sa) { - enum { sz = 1024 }; - wchar_t buf[sz]; + char hostbuf[NI_MAXHOST]; check0x(getnameinfo(reinterpret_cast<const sockaddr*>(&sa), sizeof sa, - buf, sz, // output hostname + hostbuf, NI_MAXHOST, // output hostname nullptr, 0, // service 0)); // flags - return sa; + return string(buf); } /** + * Resolve an IP address to its hostname. + */ + inline string + ipaddr2hostname(const in_addr &ip) + { + sockaddr_in sa = { AF_INET, 0, ip }; + return sockaddr2hostname(sa); + } + + /** + * Convert an IP addr to a string. + */ + inline string + ipaddr2str(const in_addr &ip) + { + inet_ntop(); + } + + /** * Get IPv4 address for hostname. T is a string or wstring. */ template<typename T> in_addr - name2addr(const T *name) + name2ipaddr(const T *name) { addrinfo *ai, hints = {0}; in_addr addr; @@ -263,7 +284,16 @@ freeaddrinfo(ai); return addr; } +#endif + /** Get the IPv4 address as an int in network byte order. */ + inline uint32_t ipaddr2nl(const in_addr &a) + { return IFWIN32(a.S_un.S_addr, a.s_addr); } + + /** Get the IPv4 address as an int in host byte order. */ + inline uint32_t ipaddr2hl(const in_addr &a) + { return ntohl(ipaddr2nl(a)); } + } #endif Modified: cpp-commons/trunk/src/commons/streams.h =================================================================== --- cpp-commons/trunk/src/commons/streams.h 2009-11-08 18:27:35 UTC (rev 1510) +++ cpp-commons/trunk/src/commons/streams.h 2009-11-09 04:18:43 UTC (rev 1511) @@ -1,24 +1,76 @@ #ifndef COMMONS_STREAMS_H #define COMMONS_STREAMS_H +#include <iomanip> +#include <limits> #include <ostream> +#include <string> #include <vector> -namespace commons { +#include <boost/foreach.hpp> +#include <boost/io/ios_state.hpp> +#include <commons/strings.h> + +namespace commons { namespace formatters { + using namespace std; + using boost::io::ios_flags_saver; - // Pretty-prints a vector of ostreamables. - template <typename T> - ostream& operator<<(ostream& out, const vector<T> &v) { - out << "["; - if (!v.empty()) { - for (typename vector<T>::size_type i = 0; i < v.size() - 1; i++) - out << v[i] << ", "; - out << v.back(); + /** + * Pretty-prints a vector of ostreamables. + */ + template<typename T> + ostream &operator<<(ostream &o, const vector<T> &v) + { + bool first = true; + o << "["; + BOOST_FOREACH (const T &x, v) { + o << (first ? "" : ", ") << x; + first = false; + } + return o << "]"; + } + + /** + * Allow wstrings to be printed to ostreams. + */ + inline ostream &operator<<(ostream &o, const wstring &s) + { return o << to_string(s); } + + /** + * Allow strings to be printed to wostreams. + */ + inline wostream &operator<<(wostream &o, const string &s) + { return o << to_wstring(s); } + + /** + * Wrapper around integral types that enables pretty printing as hex numbers. + */ + template<typename T> + class hexfmt_t + { + public: + hexfmt_t(T x) : x_(x) {} + friend wostream &operator<<(wostream &o, hexfmt_t x) { + ios_flags_saver s(o); + return o << setfill('0') << setw(2 * sizeof(T)) << hex << x.x_; } - return out << "]"; + friend ostream &operator<<(ostream &o, hexfmt_t x) { + ios_flags_saver s(o); + return o << setfill('0') << setw(2 * sizeof(T)) << hex << x.x_; + } + private: + T x_; + }; + + /** + * Convenience constructor wrapper for hexfmt_t. + */ + template<typename T> hexfmt_t<T> hexfmt(T x) { + return hexfmt_t<T>(x); } -} +} } + #endif Modified: cpp-commons/trunk/src/commons/strings.h =================================================================== --- cpp-commons/trunk/src/commons/strings.h 2009-11-08 18:27:35 UTC (rev 1510) +++ cpp-commons/trunk/src/commons/strings.h 2009-11-09 04:18:43 UTC (rev 1511) @@ -3,9 +3,16 @@ #ifndef COMMONS_STRINGS_H #define COMMONS_STRINGS_H +#include <Poco/UnicodeConverter.h> + +#ifndef __cplusplus #include <strings.h> +#else +#include <cstring> +#endif #include <commons/check.h> +#include <commons/nullptr.h> namespace commons { @@ -42,44 +49,10 @@ struct eqstr { bool operator()(const char* s1, const char* s2) const - { - return strcmp(s1, s2) == 0; - } + { return strcmp(s1, s2) == 0; } }; /** - * Look for a substring, but without null-termination conventions. - * - * TODO: remove or fix - */ - inline char * - unsafe_strstr(char *p, const char *, const char *lim) - { - if (lim == 0) { - while (true) { - for (; !(*p == '\0' && *(p+1) == '\0'); p++) {} - return p; - } - } else { - check(p < lim); - while (true) { - for (; !(*p == '\0' && *(p+1) == '\0') && p < lim; p++) {} - if (p == lim) return NULL; - return p; - } - } - } - - /** - * Look for a substring, but without null-termination conventions. - */ - inline const char* - unsafe_strstr(const char *p, const char *q, const char *lim) - { - return unsafe_strstr(const_cast<char*>(p), q, lim); - } - - /** * "Touch" the entire memory region. Useful for ensuring that some piece of * memory is "warmed up." Visits each character. Note that this might be * optimized out if the caller doesn't meaningfully use the (mostly @@ -133,6 +106,115 @@ // return NULL; // } + /** + * Convert UTF-16 to UTF-8. + */ + inline string to_utf8(const wstring &w) { + string s; + Poco::UnicodeConverter::toUTF8(w, s); + return s; + } + + /** + * Convert UTF-8 to UTF-16. + */ + inline wstring to_utf16(const string &s) { + wstring w; + Poco::UnicodeConverter::toUTF16(s, w); + return w; + } + + /** + * Throw-away stream for easily building strings. + * + * \code + * throw msg_exception(tmpstream() << "error " << errcode() << endl); + * \endcode + */ + class tmpstream : public ostringstream { + public: + operator string() const { return str(); } + operator const char *() const { return str().c_str(); } + + template<typename T> + tmpstream &operator <<(const T &x) { + *static_cast<ostringstream*>(this) << x; + return *this; + } + }; + } +#ifdef WIN32 + +#include <windows.h> +#include <string> + +namespace commons { namespace win { + + using std::string; + using std::wstring; + + // TODO return unique_ptr + + /** + * Transcode to system default ANSI code page using WideCharToMultiByte. + */ + inline char* + to_chars(const wchar_t *w) + { + char *s; + int wlen = ::wcslen(w); + int slen = ::WideCharToMultiByte(CP_ACP, 0, w, wlen, 0, 0, nullptr, nullptr); + if (slen > 0) { + s = new char[slen + 1]; + ::WideCharToMultiByte(CP_ACP, 0, w, wlen, s, slen, nullptr, nullptr); + s[slen] = 0; + } + + return s; + } + + /** + * Transcode to system default ANSI code page using WideCharToMultiByte. + */ + inline string + to_string(const wstring &w) + { + char *p = to_chars(w.c_str()); + string s(p); + delete[] p; + return s; + } + + + /** + * Transcode from system default ANSI code page using MultiByteToWideChar. + */ + inline wchar_t * + to_wchars(const char *s) + { + int len = ::strlen(s); + wchar_t *w = new wchar_t[len + 1]; + ::MultiByteToWideChar(CP_ACP, 0, s, len, w, len + 1); + return w; + } + + + /** + * Transcode from system default ANSI code page using MultiByteToWideChar. + */ + inline wstring + to_wstring(const string &s) + { + wchar_t *p = to_wchars(s.c_str()); + wstring w(p); + delete[] p; + return w; + } + +} } + #endif + +#endif Modified: cpp-commons/trunk/src/commons/unique_ptr.h =================================================================== --- cpp-commons/trunk/src/commons/unique_ptr.h 2009-11-08 18:27:35 UTC (rev 1510) +++ cpp-commons/trunk/src/commons/unique_ptr.h 2009-11-09 04:18:43 UTC (rev 1511) @@ -35,6 +35,10 @@ #ifndef _UNIQUE_PTR_H #define _UNIQUE_PTR_H 1 +#include <commons/cxx0x.h> + +#ifdef COMMONS_CXX0X + #ifndef __GXX_EXPERIMENTAL_CXX0X__ # include <c++0x_warning.h> #endif @@ -456,4 +460,6 @@ _GLIBCXX_END_NAMESPACE +#endif // COMMONS_CXX0X + #endif /* _UNIQUE_PTR_H */ Property changes on: cpp-commons/trunk/src/commons/win.h ___________________________________________________________________ Deleted: svn:executable - * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-08 18:27:50
|
Revision: 1510 http://assorted.svn.sourceforge.net/assorted/?rev=1510&view=rev Author: yangzhang Date: 2009-11-08 18:27:35 +0000 (Sun, 08 Nov 2009) Log Message: ----------- added inet_nltoa, inet_hltoa Modified Paths: -------------- python-commons/trunk/src/commons/networking.py Modified: python-commons/trunk/src/commons/networking.py =================================================================== --- python-commons/trunk/src/commons/networking.py 2009-11-08 06:02:27 UTC (rev 1509) +++ python-commons/trunk/src/commons/networking.py 2009-11-08 18:27:35 UTC (rev 1510) @@ -5,11 +5,11 @@ Networking tools. """ -import os, sys +import os, socket, struct, sys from time import * from contextlib import contextmanager -class NoMacAddrError( Exception ): pass +class no_mac_addr_exception( Exception ): pass def get_mac_addr(): """ @@ -36,7 +36,7 @@ mac = line.split()[4] break if mac is None: - raise NoMacAddrError + raise no_mac_addr_exception return mac def retry_exp_backoff(initial_backoff, multiplier, func): @@ -67,8 +67,14 @@ @contextmanager def logout(x): - """ - A context manager for finally calling the C{logout()} method of an object. - """ + "A context manager for calling the C{logout()} method of an object." try: yield x finally: x.logout() + +def inet_nltoa(x): + "Convert an IPv4 address from an int in network byte order to a string." + return socket.inet_ntoa(struct.pack('>L', x)) + +def inet_hltoa(x): + "Convert an IPv4 address from an int in host byte order to a string." + return socket.inet_ntoa(struct.pack('L', x)) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-08 06:02:46
|
Revision: 1509 http://assorted.svn.sourceforge.net/assorted/?rev=1509&view=rev Author: yangzhang Date: 2009-11-08 06:02:27 +0000 (Sun, 08 Nov 2009) Log Message: ----------- added gitit config Added Paths: ----------- configs/trunk/src/gitit/ configs/trunk/src/gitit/config configs/trunk/src/gitit/custom.css Added: configs/trunk/src/gitit/config =================================================================== --- configs/trunk/src/gitit/config (rev 0) +++ configs/trunk/src/gitit/config 2009-11-08 06:02:27 UTC (rev 1509) @@ -0,0 +1,212 @@ +# gitit wiki configuration file + +port: 5001 +# sets the port on which the web server will run. + +repository-type: Git +# specifies the type of repository used for wiki content. +# Options are Git and Darcs. + +repository-path: wikidata +# specifies the path of the repository directory. If it does not +# exist, gitit will create it on startup. + +authentication-method: form +# 'form' means that users will be logged in and registered +# using forms in the gitit web interface. 'http' means +# that gitit will assume that HTTP authentication is in +# place and take the logged in username from the "Authorization" +# field of the HTTP request header (in addition, +# the login/logout and registration links will be +# suppressed). 'generic' means that gitit will assume that +# some form of authentication is in place that directly +# sets REMOTE_USER to the name of the authenticated user +# (e.g. mod_auth_cas on apache). + +user-file: gitit-users +# specifies the path of the file containing user login information. +# If it does not exist, gitit will create it (with an empty user list). +# This file is not used if 'http' is selected for authentication-method. + +static-dir: static +# specifies the path of the static directory (containing javascript, +# css, and images). If it does not exist, gitit will create it +# and populate it with required scripts, stylesheets, and images. + +default-page-type: Markdown +# specifies the type of markup used to interpret pages in the wiki. +# Possible values are Markdown, RST, LaTeX, HTML, Markdown+LHS, RST+LHS, +# and LaTeX+LHS. (The +LHS variants treat the input as +# literate Haskell. See pandoc's documentation for more details.) If +# Markdown is selected, pandoc's syntax extensions (for footnotes, +# delimited code blocks, etc.) will be enabled. Note that pandoc's +# reStructuredText parser is not complete, so some pages may not be +# rendered correctly if RST is selected. The same goes for LaTeX and +# HTML. + +math: jsMath +# specifies how LaTeX math is to be displayed. Possible values +# are MathML, raw, and jsMath. If mathml is selected, gitit will +# convert LaTeX math to MathML and link in a script, MathMLinHTML.js, +# that allows the MathML to be seen in Gecko browsers, IE + +# mathplayer, and Opera. In other browsers you may get a jumble +# of characters. If raw is selected, the LaTeX math will be displayed +# as raw LaTeX math. If jsMath is selected, gitit will link to +# the script /js/jsMath/easy/load.js, and will assume that jsMath +# has been installed into the js/jsMath directory. This is the most +# portable solution. + +show-lhs-bird-tracks: no +# specifies whether to show Haskell code blocks in "bird style", +# with "> " at the beginning of each line. + +templates-dir: templates +# specifies the path of the directory containing page templates. +# If it does not exist, gitit will create it with default templates. +# Users may wish to edit the templates to customize the appearance of +# their wiki. The template files are HStringTemplate templates. +# Variables to be interpolated appear between $'s. Literal $'s must be +# backslash-escaped. + +log-file: gitit.log +# specifies the path of gitit's log file. If it does not exist, +# gitit will create it. The log is in Apache combined log format. + +log-level: WARNING +# determines how much information is logged. +# Possible values (from most to least verbose) are DEBUG, INFO, +# NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY. + +front-page: Front Page +# specifies which wiki page is to be used as the wiki's front page. +# Gitit creates a default front page on startup, if one does not exist +# already. + +no-delete: Front Page, Help +# specifies pages that cannot be deleted through the web interface. +# (They can still be deleted directly using git or darcs.) +# A comma-separated list of page names. Leave blank to allow +# every page to be deleted. + +no-edit: Help +# specifies pages that cannot be edited through the web interface. +# Leave blank to allow every page to be edited. + +default-summary: +# specifies text to be used in the change description if the author +# leaves the "description" field blank. If default-summary is blank +# (the default), the author will be required to fill in the description +# field. + +table-of-contents: yes +# specifies whether to print a tables of contents (with links to +# sections) on each wiki page. + +plugins: +# specifies a list of plugins to load. Plugins may be specified +# either by their path or by their module name. If the plugin name +# starts with Gitit.Plugin., gitit will assume that the plugin is +# an installed module and will not try to find a source file. +# Examples: +# plugins: plugins/DotPlugin.hs, CapitalizeEmphasisPlugin.hs +# plugins: plugins/DotPlugin +# plugins: Gitit.Plugin.InterwikiLinks + +use-cache: no +# specifies whether to cache rendered pages. Note that if use-feed +# is selected, feeds will be cached regardless of the value of use-cache. + +cache-dir: cache +# directory where rendered pages will be cached + +max-upload-size: 100K +# specifies an upper limit on the size (in bytes) of files uploaded +# through the wiki's web interface. + +debug-mode: no +# if "yes", causes debug information to be logged while gitit is running. + +compress-responses: yes +# specifies whether HTTP responses should be compressed. + +mime-types-file: /etc/mime.types +# specifies the path of a file containing mime type mappings. +# Each line of the file should contain two fields, separated by +# whitespace. The first field is the mime type, the second is a +# file extension. For example: +# video/x-ms-wmx wmx +# If the file is not found, some simple defaults will be used. + +use-recaptcha: no +# if "yes", causes gitit to use the reCAPTCHA service +# (http://recaptcha.net) to prevent bots from creating accounts. + +recaptcha-private-key: +recaptcha-public-key: +# specifies the public and private keys for the reCAPTCHA service. +# To get these, you need to create an account at http://recaptcha.net. + +access-question: +access-question-answers: +# specifies a question that users must answer when they attempt to create +# an account, along with a comma-separated list of acceptable answers. +# This can be used to institute a rudimentary password for signing up as +# a user on the wiki, or as an alternative to reCAPTCHA. +# Example: +# access-question: What is the code given to you by Ms. X? +# access-question-answers: RED DOG, red dog + +mail-command: sendmail %s +# specifies the command to use to send notification emails. +# '%s' will be replaced by the destination email address. +# The body of the message will be read from stdin. +# If this field is left blank, password reset will not be offered. + +reset-password-message: + > From: nobody@$hostname$ + > To: $useremail$ + > Subject: Wiki password reset + > + > Dear $username$: + > + > To reset your password, please follow the link below: + > http://$hostname$:$port$$resetlink$ + > + > Yours sincerely, + > The Wiki Master + +# gives the text of the message that will be sent to the user should she +# want to reset her password, or change other registration info. +# The lines must be indented, and must begin with '>'. The initial +# spaces and '> ' will be stripped off. $username$ will be replaced +# by the user's username, $useremail$ by her email address, +# $hostname$ by the hostname on which the wiki is running (as +# returned by the hostname system call), $port$ by the port on +# which the wiki is running, and $resetlink$ by the +# relative path of a reset link derived from the user's existing +# hashed password. If your gitit wiki is being proxied to a location +# other than the root path of $port$, you should change the link to +# reflect this: for example, to +# http://$hostname$/path/to/wiki$resetlink$ or +# http://gitit.$hostname$$resetlink$ + +use-feed: yes +# specifies whether an ATOM feed should be enabled (for the site and for +# individual pages) + +base-url: +# the base URL of the wiki, to be used in constructing feed IDs. +# If this field is left blank, gitit will get the base URL from the +# request header 'Host'. For most users, this should be fine, but +# if you are proxying a gitit instance to a subdirectory URL, you will +# want to set this manually. + +wiki-title: Yang's Wiki +# the title of the wiki, used in feeds. + +feed-days: 30 +# number of days to be included in feeds. + +feed-refresh-time: 60 +# number of minutes to cache feeds before refreshing + Added: configs/trunk/src/gitit/custom.css =================================================================== --- configs/trunk/src/gitit/custom.css (rev 0) +++ configs/trunk/src/gitit/custom.css 2009-11-08 06:02:27 UTC (rev 1509) @@ -0,0 +1,9 @@ +@import url("screen.css"); /* default gitit screen styles */ +@import url("hk-pyg.css"); /* for syntax highlighting */ + +/* Put your custom style modifications here: */ + +#content li p { margin-bottom: 0; } +#content li ul { margin-bottom: 0; margin-top: 0; } +#content table td { border: 1px dotted silver; } +#content table th { border: 1px dotted silver; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-08 01:15:58
|
Revision: 1508 http://assorted.svn.sourceforge.net/assorted/?rev=1508&view=rev Author: yangzhang Date: 2009-11-08 01:15:51 +0000 (Sun, 08 Nov 2009) Log Message: ----------- added IFWIN32; dos2unix Modified Paths: -------------- cpp-commons/trunk/src/commons/win.h Modified: cpp-commons/trunk/src/commons/win.h =================================================================== --- cpp-commons/trunk/src/commons/win.h 2009-11-07 08:13:45 UTC (rev 1507) +++ cpp-commons/trunk/src/commons/win.h 2009-11-08 01:15:51 UTC (rev 1508) @@ -1,24 +1,30 @@ -#ifndef COMMONS_WIN_H -#define COMMONS_WIN_H - -#ifdef WIN32 -# define NONWIN(x) -# define __attribute__(x) -#include <boost/cstdint.hpp> -using boost::int8_t; -using boost::int16_t; -using boost::int32_t; -using boost::int64_t; -using boost::uint8_t; -using boost::uint16_t; -using boost::uint32_t; -using boost::uint64_t; -typedef HANDLE fd_t; -int close(fd_t fd) { return CloseHandle(fd) ? 0 : -1; } -void bzero(void *s, size_t n) { memset(s, 0, n); } -#else -# define NONWIN(x) x -typedef int fd_t; -#endif - -#endif +#ifndef COMMONS_WIN_H +#define COMMONS_WIN_H + +#ifdef WIN32 +# define NONWIN(x) +# define __attribute__(x) +#include <boost/cstdint.hpp> +using boost::int8_t; +using boost::int16_t; +using boost::int32_t; +using boost::int64_t; +using boost::uint8_t; +using boost::uint16_t; +using boost::uint32_t; +using boost::uint64_t; +typedef HANDLE fd_t; +inline int close(fd_t fd) { return CloseHandle(fd) ? 0 : -1; } +inline void bzero(void *s, size_t n) { memset(s, 0, n); } +#else +# define NONWIN(x) x +typedef int fd_t; +#endif + +#ifdef WIN32 +#define IFWIN32(a, b) a +#else +#define IFWIN32(a, b) b +#endif + +#endif This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-07 08:14:04
|
Revision: 1507 http://assorted.svn.sourceforge.net/assorted/?rev=1507&view=rev Author: yangzhang Date: 2009-11-07 08:13:45 +0000 (Sat, 07 Nov 2009) Log Message: ----------- simplified noncopyable demo Modified Paths: -------------- sandbox/trunk/src/cc/noncopyable.cc Modified: sandbox/trunk/src/cc/noncopyable.cc =================================================================== --- sandbox/trunk/src/cc/noncopyable.cc 2009-11-07 07:19:02 UTC (rev 1506) +++ sandbox/trunk/src/cc/noncopyable.cc 2009-11-07 08:13:45 UTC (rev 1507) @@ -1,4 +1,4 @@ -// $ g++ -Wall -g3 -o noncopyable noncopyable.cc -Wextra -Wconversion -Wpointer-arith -Wcast-qual -Wcast-align -Wwrite-strings -Winit-self -Wno-unused-parameter -Wparentheses -Wmissing-format-attribute -Wfloat-equal -Winline -Woverloaded-virtual -Wsign-promo -Wc++0x-compat -Wsynth -Wall -Werror -Wextra -Weffc++ -Wstrict-null-sentinel -Wno-old-style-cast -Woverloaded-virtual -Wsign-promo -Wformat=2 -Winit-self -Wswitch-enum -Wunused -Wstrict-overflow -Wfloat-equal -Wundef -Wunsafe-loop-optimizations -Wpointer-arith -Wcast-qual -Wcast-align -Wwrite-strings -Wconversion -Wlogical-op -Wno-aggregate-return -Wno-missing-declarations -Wno-missing-field-initializers -Wmissing-noreturn -Wmissing-format-attribute -Wpacked -Wredundant-decls -Wunreachable-code -Winline -Winvalid-pch -Wlong-long -Wvolatile-register-var -Wstack-protector +// $ g++ -Werror -Weffc++ -g3 -o noncopyable noncopyable.cc // cc1plus: warnings being treated as errors // noncopyable.cc:3: error: base class âass boost::noncopyable_::noncopyableâas a non-virtual destructor @@ -6,4 +6,4 @@ using namespace boost; class C : noncopyable { }; -int main() { return 0; } +int main() { C c; return 0; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-07 07:19:17
|
Revision: 1506 http://assorted.svn.sourceforge.net/assorted/?rev=1506&view=rev Author: yangzhang Date: 2009-11-07 07:19:02 +0000 (Sat, 07 Nov 2009) Log Message: ----------- swiped a tiny LLVM Lisp impl from the intarweb Added Paths: ----------- sandbox/trunk/src/cc/llvm_lisp.cc Added: sandbox/trunk/src/cc/llvm_lisp.cc =================================================================== --- sandbox/trunk/src/cc/llvm_lisp.cc (rev 0) +++ sandbox/trunk/src/cc/llvm_lisp.cc 2009-11-07 07:19:02 UTC (rev 1506) @@ -0,0 +1,530 @@ +// From <http://paste.lisp.org/display/74068>. + +/* A Trivial LLVM LISP + * Copyright (C) 2008-2009 David Robillard <da...@dr...> + * + * Parts from the Kaleidoscope tutorial <http://llvm.org/docs/tutorial/> + * by Chris Lattner and Erick Tryzelaar + * + * 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 3 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, see <http://www.gnu.org/licenses/>. + */ + +#include <iostream> +#include <list> +#include <map> +#include <stack> +#include <string> +#include <vector> +#include "llvm/Analysis/Verifier.h" +#include "llvm/DerivedTypes.h" +#include "llvm/ExecutionEngine/ExecutionEngine.h" +#include "llvm/Module.h" +#include "llvm/ModuleProvider.h" +#include "llvm/PassManager.h" +#include "llvm/Support/IRBuilder.h" +#include "llvm/Target/TargetData.h" +#include "llvm/Transforms/Scalar.h" + +using namespace llvm; +using namespace std; + + +/*************************************************************************** + * S-Expression Lexer - Read text and output nested lists of strings * + ***************************************************************************/ + +struct SExp { + SExp() : type(LIST) {} + SExp(const std::list<SExp>& l) : type(LIST), list(l) {} + SExp(const std::string& s) : type(ATOM), atom(s) {} + enum { ATOM, LIST } type; + std::string atom; + std::list<SExp> list; +}; + +struct SyntaxError : public std::exception { + SyntaxError(const char* m) : msg(m) {} + const char* what() const throw() { return msg; } + const char* msg; +}; + +static SExp +readExpression(std::istream& in) +{ + stack<SExp> stk; + string tok; + +#define APPEND_TOK() \ + if (stk.empty()) return tok; else stk.top().list.push_back(SExp(tok)) + + while (char ch = in.get()) { + switch (ch) { + case EOF: + return SExp(); + case ' ': case '\t': case '\n': + if (tok == "") + continue; + else + APPEND_TOK(); + tok = ""; + break; + case '"': + do { tok.push_back(ch); } while ((ch = in.get()) != '"'); + tok.push_back('"'); + APPEND_TOK(); + tok = ""; + break; + case '(': + stk.push(SExp()); + break; + case ')': + switch (stk.size()) { + case 0: + throw SyntaxError("Missing '('"); + break; + case 1: + if (tok != "") stk.top().list.push_back(SExp(tok)); + return stk.top(); + default: + if (tok != "") stk.top().list.push_back(SExp(tok)); + SExp l = stk.top(); + stk.pop(); + stk.top().list.push_back(l); + } + tok = ""; + break; + default: + tok.push_back(ch); + } + } + + switch (stk.size()) { + case 0: return tok; break; + case 1: return stk.top(); break; + default: throw SyntaxError("Missing ')'"); + } +} + + + +/*************************************************************************** + * Abstract Syntax Tree * + ***************************************************************************/ + +struct CEnv; ///< Compile Time Environment + +/// Base class for all AST nodes. +struct AST { + virtual ~AST() {} + virtual Value* Codegen(CEnv& cenv) = 0; + virtual bool evaluatable() const { return true; } +}; + +/// Numeric literals, e.g. "1.0". +struct ASTNumber : public AST { + ASTNumber(double val) : _val(val) {} + virtual Value* Codegen(CEnv& cenv); +private: + double _val; +}; + +/// Variable reference (i.e. symbol), e.g. "a". +struct ASTVariable : public AST { + ASTVariable(const string& name) : _name(name) {} + virtual Value* Codegen(CEnv& cenv); +private: + string _name; +}; + +/// Function call, e.g. "(func arg1 arg2)". +struct ASTCall : public AST { + ASTCall(const string& f, vector<AST*>& a) : _func(f), _args(a) {} + virtual Value* Codegen(CEnv& cenv); +private: + string _func; + vector<AST*> _args; +}; + +/// Conditional (special form "if"), e.g. "(if cond thenexp elseexp)". +struct ASTIf : public AST { + ASTIf(AST* c, AST* t, AST* e) : _cond(c), _then(t), _else(e) {} + virtual Value* Codegen(CEnv& cenv); +private: + AST* _cond; + AST* _then; + AST* _else; +}; + +/// Function prototype +struct ASTPrototype : public AST { + ASTPrototype(bool foreign, const string& n, const vector<string>& a) + : _foreign(foreign), _name(n), _args(a) {} + virtual bool evaluatable() const { return false; } + Value* Codegen(CEnv& cenv) { return Funcgen(cenv); } + Function* Funcgen(CEnv& cenv); +private: + bool _foreign; + string _name; + vector<string> _args; +}; + +/// Function definition +struct ASTFunction : public AST { + ASTFunction(ASTPrototype* p, AST* b) : _proto(p), _body(b) {} + virtual bool evaluatable() const { return false; } + Value* Codegen(CEnv& cenv) { return Funcgen(cenv); } + Function* Funcgen(CEnv& cenv); +private: + ASTPrototype* _proto; + AST* _body; +}; + + + +/*************************************************************************** + * Parser - Transform S-Expressions into AST nodes * + ***************************************************************************/ + +static const std::string& head(const SExp& exp) +{ + static const std::string empty = ""; + if (exp.type == SExp::LIST + && !exp.list.empty() + && exp.list.front().type == SExp::ATOM) + return exp.list.front().atom; + else + return empty; +} + +static AST* parseExpression(const SExp& exp); + +/// identifierexpr ::= identifier +static AST* parseIdentifierExpr(const SExp& exp) +{ + assert(exp.type == SExp::ATOM); + return new ASTVariable(exp.atom); +} + +/// numberexpr ::= number +static AST* parseNumberExpr(const SExp& exp) +{ + assert(exp.type == SExp::ATOM); + return new ASTNumber(strtod(exp.atom.c_str(), NULL)); +} + +/// ifexpr ::= ("if" expression expression expression) +static AST* parseIfExpr(const SExp& exp) +{ + assert(head(exp) == "if"); + list<SExp>::const_iterator i = exp.list.begin(); + ++i; + + AST* cond = parseExpression(*i++); + AST* then = parseExpression(*i++); + AST* otherwise = parseExpression(*i++); + + return new ASTIf(cond, then, otherwise); +} + +/// callexpr ::= (expression [...]) +static AST* parseCallExpr(const SExp& exp) +{ + assert(head(exp) != ""); + list<SExp>::const_iterator i = exp.list.begin(); + const string& name = i->atom; + + vector<AST*> params; + for (++i; i != exp.list.end(); ++i) + params.push_back(parseExpression(*i)); + + return new ASTCall(name, params); +} + +/// prototype ::= (name [arg*]) +static ASTPrototype* ParsePrototype(bool foreign, const SExp& exp) +{ + assert(head(exp) != ""); + list<SExp>::const_iterator i = exp.list.begin(); + const string& name = i->atom; + + vector<string> args; + for (++i; i != exp.list.end(); ++i) + if (i->type == SExp::ATOM) + args.push_back(i->atom); + else + throw SyntaxError("Expected parameter name, found list"); + + return new ASTPrototype(foreign, name, args); +} + +/// definition ::= ("def" prototype expression) +static ASTFunction* parseDefinition(const SExp& exp) +{ + assert(head(exp) == "def"); + list<SExp>::const_iterator i = exp.list.begin(); + ++i; + + ASTPrototype* proto = ParsePrototype(false, *i++); + AST* body = parseExpression(*i++); + + return new ASTFunction(proto, body); +} + +/// foreign ::= ("foreign" prototype expression) +static ASTPrototype* parseForeign(const SExp& exp) +{ + assert(head(exp) == "foreign"); + list<SExp>::const_iterator i = exp.list.begin(); + ++i; + + return ParsePrototype(true, *i++); +} + +static AST* parseExpression(const SExp& exp) +{ + if (exp.type == SExp::LIST) { + const string& form = head(exp); + if (form == "if") { + return parseIfExpr(exp); + } else if (form == "def") { + return parseDefinition(exp); + } else if (form == "foreign") { + return parseForeign(exp); + } else { + return parseCallExpr(exp); + } + } else if (isalpha(exp.atom[0])) { + return parseIdentifierExpr(exp); + } else if (isdigit(exp.atom[0])) { + return parseNumberExpr(exp); + } else { + throw SyntaxError("Illegal atom"); + } +} + + +/*************************************************************************** + * Code Generation * + ***************************************************************************/ + +/// Compile-time environment +struct CEnv { + CEnv(Module* m, const TargetData* target) + : module(m), provider(module), fpm(&provider) + { + // Set up the optimizer pipeline. + // Register info about how the target lays out data structures. + fpm.add(new TargetData(*target)); + // Do simple "peephole" and bit-twiddline optimizations. + fpm.add(createInstructionCombiningPass()); + // Reassociate expressions. + fpm.add(createReassociatePass()); + // Eliminate Common SubExpressions. + fpm.add(createGVNPass()); + // Simplify control flow graph (delete unreachable blocks, etc). + fpm.add(createCFGSimplificationPass()); + } + IRBuilder<> builder; + Module* module; + ExistingModuleProvider provider; + FunctionPassManager fpm; + map<string, Value*> env; +}; + +Value* ASTNumber::Codegen(CEnv& cenv) +{ + return ConstantFP::get(APFloat(_val)); +} + +Value* ASTVariable::Codegen(CEnv& cenv) +{ + map<string, Value*>::const_iterator v = cenv.env.find(_name); + if (v == cenv.env.end()) throw SyntaxError("Undefined identifier"); + return v->second; +} + +Value* ASTCall::Codegen(CEnv& cenv) +{ + // Look up the name in the global module table. + Function* f = cenv.module->getFunction(_func); + if (f == 0) throw SyntaxError("Undefined function"); + if (f->arg_size() != _args.size()) throw SyntaxError("Illegal arguments"); + + vector<Value*> args; + for (size_t i = 0, e = _args.size(); i != e; ++i) + args.push_back(_args[i]->Codegen(cenv)); + + return cenv.builder.CreateCall(f, args.begin(), args.end(), "calltmp"); +} + +Value* ASTIf::Codegen(CEnv& cenv) +{ + Value* condV = _cond->Codegen(cenv); + + // Convert condition to a bool by comparing equal to 0.0. + condV = cenv.builder.CreateFCmpONE( + condV, ConstantFP::get(APFloat(0.0)), "ifcond"); + + Function* parent = cenv.builder.GetInsertBlock()->getParent(); + + // Create blocks for the then and else cases. + // Insert the 'then' block at the end of the function. + BasicBlock* thenBB = BasicBlock::Create("then", parent); + BasicBlock* elseBB = BasicBlock::Create("else"); + BasicBlock* mergeBB = BasicBlock::Create("ifcont"); + + cenv.builder.CreateCondBr(condV, thenBB, elseBB); + + // Emit then value. + cenv.builder.SetInsertPoint(thenBB); + Value* thenV = _then->Codegen(cenv); + + cenv.builder.CreateBr(mergeBB); + // Codegen of 'Then' can change the current block, update thenBB + thenBB = cenv.builder.GetInsertBlock(); + + // Emit else block. + parent->getBasicBlockList().push_back(elseBB); + cenv.builder.SetInsertPoint(elseBB); + Value* elseV = _else->Codegen(cenv); + + cenv.builder.CreateBr(mergeBB); + // Codegen of 'Else' can change the current block, update elseBB + elseBB = cenv.builder.GetInsertBlock(); + + // Emit merge block. + parent->getBasicBlockList().push_back(mergeBB); + cenv.builder.SetInsertPoint(mergeBB); + PHINode* pn = cenv.builder.CreatePHI(Type::DoubleTy, "iftmp"); + + pn->addIncoming(thenV, thenBB); + pn->addIncoming(elseV, elseBB); + return pn; +} + +Function* ASTPrototype::Funcgen(CEnv& cenv) +{ + // Make the function type, e.g. double(double,double) + vector<const Type*> Doubles(_args.size(), Type::DoubleTy); + FunctionType* FT = FunctionType::get(Type::DoubleTy, Doubles, false); + + Function* f = Function::Create( + FT, Function::ExternalLinkage, _name, cenv.module); + + // If F conflicted, there was already something named 'Name'. + // If it has a body, don't allow redefinition. + if (f->getName() != _name) { + // Delete the one we just made and get the existing one. + f->eraseFromParent(); + f = cenv.module->getFunction(_name); + + // If F already has a body, reject this. + if (!f->empty()) throw SyntaxError("Function redefined"); + + // If F took a different number of args, reject. + if (f->arg_size() != _args.size()) + throw SyntaxError("Function redefined with mismatched arguments"); + } + + // Set names for all arguments. + size_t i = 0; + for (Function::arg_iterator a = f->arg_begin(); i != _args.size(); + ++a, ++i) { + a->setName(_args[i]); + + // Add arguments to variable symbol table. + cenv.env[_args[i]] = a; + } + + return f; +} + +Function* ASTFunction::Funcgen(CEnv& cenv) +{ + cenv.env.clear(); + + Function* f = _proto->Funcgen(cenv); + + // Create a new basic block to start insertion into. + BasicBlock* bb = BasicBlock::Create("entry", f); + cenv.builder.SetInsertPoint(bb); + + try { + Value* retVal = _body->Codegen(cenv); + cenv.builder.CreateRet(retVal); // Finish function + verifyFunction(*f); // Validate generated code + cenv.fpm.run(*f); // Optimize function + return f; + } catch (SyntaxError e) { + f->eraseFromParent(); // Error reading body, remove function + throw e; + } + + return 0; // Never reached +} + + +/*************************************************************************** + * REPL - Interactively compile, optimise, and execute code * + ***************************************************************************/ + +/// Read-Eval-Print-Loop +static void repl(CEnv& cenv, ExecutionEngine* engine) +{ + while (1) { + std::cout << "> "; + std::cout.flush(); + SExp exp = readExpression(std::cin); + + try { + AST* ast = parseExpression(exp); + if (ast->evaluatable()) { + ASTPrototype* proto = new ASTPrototype(false, "", vector<string>()); + ASTFunction* func = new ASTFunction(proto, ast); + Function* code = func->Funcgen(cenv); + void* fp = engine->getPointerToFunction(code); + double (*f)() = (double (*)())fp; + std::cout << f() << endl; + } else { + Value* code = ast->Codegen(cenv); + std::cout << "Generated code:" << endl; + code->dump(); + } + } catch (SyntaxError e) { + std::cerr << "Syntax error: " << e.what() << endl; + } + } +} + + +/*************************************************************************** + * Main driver code. + ***************************************************************************/ + +int +main() +{ + Module* module = new Module("interactive"); + ExecutionEngine* engine = ExecutionEngine::create(module); + + CEnv cenv(module, engine->getTargetData()); + + repl(cenv, engine); + + std::cout << "Generated code:" << endl; + module->dump(); + + return 0; +} + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-06 01:46:40
|
Revision: 1505 http://assorted.svn.sourceforge.net/assorted/?rev=1505&view=rev Author: yangzhang Date: 2009-11-06 01:46:27 +0000 (Fri, 06 Nov 2009) Log Message: ----------- discovered some old tests Added Paths: ----------- sandbox/trunk/src/cc/hodgepodge.cc Added: sandbox/trunk/src/cc/hodgepodge.cc =================================================================== --- sandbox/trunk/src/cc/hodgepodge.cc (rev 0) +++ sandbox/trunk/src/cc/hodgepodge.cc 2009-11-06 01:46:27 UTC (rev 1505) @@ -0,0 +1,125 @@ +/*************************************************************************** + * Copyright (C) 2007 by Yang Zhang * + * yaaang at gmail * + * * + * 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. * + ***************************************************************************/ + +// demos: +// - logical operators and/not/or +// - explores function pointers, their syntax, etc. +// - coroutine-based cooperative threading (cheap concurrency) +// - function, bind +// - pool + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <iostream> +#include <cstdlib> +#include <vector> +#include <queue> +#include <boost/bind.hpp> +#include <boost/function.hpp> +#include <boost/pool/object_pool.hpp> +#include <boost/coroutine/coroutine.hpp> + +#define null NULL +#define foreach BOOST_FOREACH + +using namespace std; +using namespace boost; +namespace coro = boost::coroutines; + +typedef coro::coroutine < void() > job_type; + +class scheduler { +public: + void add ( function < void ( job_type::self & ) > f ) { + job_type j ( f ); + q.push ( p.malloc() ); + } + + job_type& current() { + return *q.front(); + } + + void run () { + while ( !q.empty() ) { + current() ( nothrow ); + if ( current() ) q.push ( ¤t() ); + else p.free ( q.back() ); + q.pop(); + } + } + +private: + object_pool<job_type> p; + queue<job_type*> q; +}; + +scheduler global_scheduler; + +void printer ( job_type::self& self, std::string name, int iterations ) { + while ( iterations -- ) { + std::cout << name << " is running, " << iterations << " iterations left\n"; + self.yield(); + } + self.exit(); +} + +void print ( int i ) { cout << "aoeu" << endl; } + +void ffff() {} + +// AFAIK, there's no difference between specifying functions vs. functions pointers +void test_fptrs ( void f(), + int g ( int, int ), + int ( *h ) ( int, int ) ) { + function < void() > ff = f; + void ( *fff ) () = f; + // ERROR void fff () = f + // ERROR f = ff; + // ERROR fff = ff; + + fff = f; + f = fff; + // ERROR f = &fff; + // ERROR fff = &f; + + fff = &ffff; + f = &ffff; + fff = ffff; + f = ffff; + + function < int ( int, int ) > gg = g; + function < int ( int, int ) > hh = h; + int ( *hhh ) ( int, int ) = h; +} + +int main ( int argc, char *argv[] ) { + cout << "Hello, world! " << ( not true or true ) << endl; + + function < void() > f = bind ( print, 0 ); + f (); + + global_scheduler.add ( boost::bind ( printer, _1, "first", 10 ) ); + global_scheduler.add ( boost::bind ( printer, _1, "second", 5 ) ); + global_scheduler.add ( boost::bind ( printer, _1, "third", 3 ) ); + + return EXIT_SUCCESS; +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-06 01:43:35
|
Revision: 1504 http://assorted.svn.sourceforge.net/assorted/?rev=1504&view=rev Author: yangzhang Date: 2009-11-06 01:43:25 +0000 (Fri, 06 Nov 2009) Log Message: ----------- failed demo of boost spirit 2 Added Paths: ----------- sandbox/trunk/src/cc/boost_spirit.cc Added: sandbox/trunk/src/cc/boost_spirit.cc =================================================================== --- sandbox/trunk/src/cc/boost_spirit.cc (rev 0) +++ sandbox/trunk/src/cc/boost_spirit.cc 2009-11-06 01:43:25 UTC (rev 1504) @@ -0,0 +1,38 @@ +// failed attempt to get started boost spirit 2; the docs were not so good and +// out of sync with the code + +#include <boost/spirit/include/qi.hpp> +#include <iostream> +#include <string> +#include <vector> + +using namespace std; +using namespace boost; +using namespace boost::spirit; +//using namespace boost::spirit::ascii; +using namespace boost::spirit::qi; +using boost::spirit::ascii::space_p; +//using namespace boost::phoenix; + +struct pred { std::string src; std::string dst; int port; }; + +int main() { + vector<pred> preds; + pred p; +#if 0 + BOOST_FUSION_ADAPT_STRUCT(pred, + (string, src) + (string, dst) + (int, port)); +#endif + qi::rule<std::string::const_iterator, space_type> pred_p = +#if 0 + (+char_)[ref(p.src) = _1] >> ',' >> + (+char_)[ref(p.dst) = _1] >> ',' >> +#endif + int_[ref(p.port) = _1]; + //parse(string("2,4,6"), pred_p, space_p); + parse(string("6"), pred_p, space_p); + preds.push_back(p); + return 0; +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2009-11-06 01:43:27
|
Revision: 1503 http://assorted.svn.sourceforge.net/assorted/?rev=1503&view=rev Author: yangzhang Date: 2009-11-06 01:43:09 +0000 (Fri, 06 Nov 2009) Log Message: ----------- demo of c++0x lambda Added Paths: ----------- sandbox/trunk/src/cc/lambda.cc Added: sandbox/trunk/src/cc/lambda.cc =================================================================== --- sandbox/trunk/src/cc/lambda.cc (rev 0) +++ sandbox/trunk/src/cc/lambda.cc 2009-11-06 01:43:09 UTC (rev 1503) @@ -0,0 +1,11 @@ +#include <functional> +#include <iostream> +#include <thread> +using namespace std; +int main() { + function<void()> f = []{ cout << "hello" << endl; }; + thread t(f); + function<bool(int)> g = [&t](int x){ if (x == 0) t.join(); return true; }; + if (g(0)) cout << "world" << endl; + return 0; +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |