assorted-commits Mailing List for Assorted projects (Page 67)
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...> - 2008-01-20 06:31:42
|
Revision: 252 http://assorted.svn.sourceforge.net/assorted/?rev=252&view=rev Author: yangzhang Date: 2008-01-19 22:31:46 -0800 (Sat, 19 Jan 2008) Log Message: ----------- adding haskell commons code Added Paths: ----------- haskell-commons/trunk/src/Commons/ haskell-commons/trunk/src/Commons/Concurrent.hs haskell-commons/trunk/src/Commons/Control.hs haskell-commons/trunk/src/Commons/Exception.hs haskell-commons/trunk/src/Commons/Io.hs haskell-commons/trunk/src/Commons/Posix.hs haskell-commons/trunk/src/Commons/Text.hs Added: haskell-commons/trunk/src/Commons/Concurrent.hs =================================================================== --- haskell-commons/trunk/src/Commons/Concurrent.hs (rev 0) +++ haskell-commons/trunk/src/Commons/Concurrent.hs 2008-01-20 06:31:46 UTC (rev 252) @@ -0,0 +1,75 @@ +module Commons.Concurrent where + +import Control.Concurrent +import Control.Concurrent.MVar +import Control.Exception +import Control.Monad +import Data.Maybe +import Data.Typeable + +tryReadMVar v = do + x <- tryTakeMVar v + case x of + Just x -> putMVar v x + Nothing -> return () + return x + +-- TODO extend this to allow interruptibles to specify exactly which +-- exceptions they tolerate + +-- This is designed for only one interrupt to ever happen; there is +-- currently no mechanism to clear interrupts. This is also designed +-- for only one client thread. + +newInterruptible :: (Typeable e) => + Bool -> IO ((forall a. IO a -> IO a), (e -> IO ())) +newInterruptible saveInterrupts = do + -- omnipotent lock + lock <- newMVar () + -- any ThreadId currently running and is interruptible + tid <- newEmptyMVar + -- any pending interrupt + pending <- newEmptyMVar + + let acquire = takeMVar lock + release = putMVar lock () + withLock f = bracket acquire (const release) (const f) + + let + -- the interruptible first puts tid, then takes pending + interruptible f = do + myTid <- myThreadId + acquire + intr <- tryReadMVar pending + case intr of + Nothing -> do + -- Let interruptors know who to throw to. + putMVar tid myTid + + -- We're clear to proceed; we'll get async exceptions for + -- interrupts. + release + res <- f + + -- If an async exception is on its way, then we'll + -- (thankfully, due to async exception semantics) receive + -- it while blocked either on acquire or on takeMVar. + withLock $ do + takeMVar tid + return res + + Just ex -> do + -- There's an interrupt just waiting for us; raise the + -- exception. + release + throwDyn ex + + -- The interrupter first puts pending, then takes tid. + interrupt ex = withLock $ do + when saveInterrupts $ putMVar pending ex + current <- tryTakeMVar tid + case current of + Just tid -> throwDynTo tid ex + Nothing -> return () + + return (interruptible, interrupt) \ No newline at end of file Added: haskell-commons/trunk/src/Commons/Control.hs =================================================================== --- haskell-commons/trunk/src/Commons/Control.hs (rev 0) +++ haskell-commons/trunk/src/Commons/Control.hs 2008-01-20 06:31:46 UTC (rev 252) @@ -0,0 +1,13 @@ +module Commons.Control where + +import Control.Monad + +while :: Bool -> IO a -> IO () +while cond body = + when cond (body `seq` while cond body) + +loop :: IO a -> IO () +loop = while True + +discard :: (Monad m) => m a -> m () +discard f = f >> return () \ No newline at end of file Added: haskell-commons/trunk/src/Commons/Exception.hs =================================================================== --- haskell-commons/trunk/src/Commons/Exception.hs (rev 0) +++ haskell-commons/trunk/src/Commons/Exception.hs 2008-01-20 06:31:46 UTC (rev 252) @@ -0,0 +1,8 @@ +module Commons.Exception where + +import Control.Exception + +-- avoid monomorphism restriction +handleDyn body handler = catchDyn handler body + +f `or` handler = f `Prelude.catch` handler \ No newline at end of file Added: haskell-commons/trunk/src/Commons/Io.hs =================================================================== --- haskell-commons/trunk/src/Commons/Io.hs (rev 0) +++ haskell-commons/trunk/src/Commons/Io.hs 2008-01-20 06:31:46 UTC (rev 252) @@ -0,0 +1,24 @@ +module Commons.Io where + +import Data.List +import System.IO + +-- TODO available in 6.8 +{- +withFile path mode f = do + h <- openFile path mode + res <- f h + hClose h + return res +-} + +unhidden = filter (not . ("." `isPrefixOf`)) + +strict f = do + xs <- f + length xs `seq` return xs + +hGetContents' = strict . hGetContents + +readFileOrNil path = readFile path `catch` const (return "") +readFileOrNil' = strict . readFileOrNil \ No newline at end of file Added: haskell-commons/trunk/src/Commons/Posix.hs =================================================================== --- haskell-commons/trunk/src/Commons/Posix.hs (rev 0) +++ haskell-commons/trunk/src/Commons/Posix.hs 2008-01-20 06:31:46 UTC (rev 252) @@ -0,0 +1,12 @@ +module Commons.Posix where + +import Data.List +import System.Posix.Files + +mergeModes = foldl' unionFileModes nullFileMode + +executeMode = mergeModes [ownerExecuteMode, groupExecuteMode, otherExecuteMode] + +chmod mode path = do + origMode <- fmap fileMode $ getFileStatus path + setFileMode path $ origMode `unionFileModes` mode Added: haskell-commons/trunk/src/Commons/Text.hs =================================================================== --- haskell-commons/trunk/src/Commons/Text.hs (rev 0) +++ haskell-commons/trunk/src/Commons/Text.hs 2008-01-20 06:31:46 UTC (rev 252) @@ -0,0 +1,9 @@ +module Commons.Text where + +import Control.Arrow + +indent n = lines >>> map (replicate n ' ' ++) >>> unlines + +--grep pat = lines >>> filter (contains pat) >>> unlines +-- +--fgrep_v = filter (contains " \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-20 06:30:08
|
Revision: 251 http://assorted.svn.sourceforge.net/assorted/?rev=251&view=rev Author: yangzhang Date: 2008-01-19 22:30:08 -0800 (Sat, 19 Jan 2008) Log Message: ----------- - very dissatisfied with the dark theme! changed the default back to plain - fixed some xhtml validation errors Modified Paths: -------------- personal-site/trunk/Makefile personal-site/trunk/src/dark.css personal-site/trunk/src/index.txt Modified: personal-site/trunk/Makefile =================================================================== --- personal-site/trunk/Makefile 2008-01-20 06:25:59 UTC (rev 250) +++ personal-site/trunk/Makefile 2008-01-20 06:30:08 UTC (rev 251) @@ -13,7 +13,7 @@ cpp -P -CC -traditional-cpp $^ $@ $(INDEX): $(DARK) - ln -sf dark.html $(INDEX) + ln -sf plain.html $(INDEX) $(PLAIN): src/index.txt src/header.html out pandoc -s -S --tab-stop=2 -H src/header.html src/index.txt \ Modified: personal-site/trunk/src/dark.css =================================================================== --- personal-site/trunk/src/dark.css 2008-01-20 06:25:59 UTC (rev 250) +++ personal-site/trunk/src/dark.css 2008-01-20 06:30:08 UTC (rev 251) @@ -3,7 +3,7 @@ * (http://arcsin.se/). */ -#define DIM_GOLD #B8860B +#define DIM_GOLD #805D08 /* #B8860B */ #define BRIGHT_GOLD #DAA520 #define DIM_BLUE #87BEEB Modified: personal-site/trunk/src/index.txt =================================================================== --- personal-site/trunk/src/index.txt 2008-01-20 06:25:59 UTC (rev 250) +++ personal-site/trunk/src/index.txt 2008-01-20 06:30:08 UTC (rev 251) @@ -118,7 +118,7 @@ <!-- Extreme Tracking --> <div id="eXTReMe"><a href="http://extremetracking.com/open?login=yzzororg"> -<img src="http://t1.extreme-dm.com/i.gif" style="border: 0;" id="extremeimg" +<img src="http://t1.extreme-dm.com/i.gif" style="border: 0;" height="38" width="41" id="EXim" alt="eXTReMe Tracker" /></a> <script type="text/javascript"><!-- var EXlogin='yzzororg' // Login @@ -134,8 +134,8 @@ </script><noscript><div id="neXTReMe"><img height="1" width="1" alt="" src="http://e0.extreme-dm.com/s9.g?login=yzzororg&j=n&jv=n" /> </div></noscript></div> -<script> -var img = document.getElementById("extremeimg"); +<script type="text/javascript"> +var img = document.getElementById("EXim"); img.width=1; img.height=1; </script> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-20 06:25:53
|
Revision: 250 http://assorted.svn.sourceforge.net/assorted/?rev=250&view=rev Author: yangzhang Date: 2008-01-19 22:25:59 -0800 (Sat, 19 Jan 2008) Log Message: ----------- removed is_environ_set Modified Paths: -------------- python-commons/trunk/src/commons/environ.py Modified: python-commons/trunk/src/commons/environ.py =================================================================== --- python-commons/trunk/src/commons/environ.py 2008-01-20 06:25:53 UTC (rev 249) +++ python-commons/trunk/src/commons/environ.py 2008-01-20 06:25:59 UTC (rev 250) @@ -7,22 +7,6 @@ import os -def is_environ_set( name ): - """ - Tests if an environment variable is set and non-empty. - - @param name: The environment variable's name. - @type name: str - - @return: True if the environment variable is set and non-empty; - false otherwise. - @rtype: bool - """ - try: - return os.environ[ name ] != '' - except KeyError: - return False - def get_environs( *names ): """ Get the value from a prioritized ordering of environment This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-20 06:25:48
|
Revision: 249 http://assorted.svn.sourceforge.net/assorted/?rev=249&view=rev Author: yangzhang Date: 2008-01-19 22:25:53 -0800 (Sat, 19 Jan 2008) Log Message: ----------- fixed missing import Modified Paths: -------------- python-commons/trunk/src/commons/seqs.py Modified: python-commons/trunk/src/commons/seqs.py =================================================================== --- python-commons/trunk/src/commons/seqs.py 2008-01-20 06:25:30 UTC (rev 248) +++ python-commons/trunk/src/commons/seqs.py 2008-01-20 06:25:53 UTC (rev 249) @@ -1,7 +1,7 @@ # -*- mode: python; tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4; -*- # vim:ft=python:et:sw=4:ts=4 -from __future__ import with_statement +from __future__ import ( absolute_import, with_statement ) from cStringIO import StringIO from cPickle import * @@ -9,6 +9,7 @@ from contextlib import closing from itertools import ( chain, count, ifilterfalse, islice, izip, tee ) +from .log import warning """ Sequences, streams, and generators. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-20 06:25:26
|
Revision: 248 http://assorted.svn.sourceforge.net/assorted/?rev=248&view=rev Author: yangzhang Date: 2008-01-19 22:25:30 -0800 (Sat, 19 Jan 2008) Log Message: ----------- added better profiling facility, made consistent with multithreaded facility; removed is_environ_set Modified Paths: -------------- python-commons/trunk/src/commons/startup.py Modified: python-commons/trunk/src/commons/startup.py =================================================================== --- python-commons/trunk/src/commons/startup.py 2008-01-20 00:27:16 UTC (rev 247) +++ python-commons/trunk/src/commons/startup.py 2008-01-20 06:25:30 UTC (rev 248) @@ -7,9 +7,10 @@ from __future__ import absolute_import from .log import ( critical, debug, config_logging ) -from .environ import ( is_environ_set, get_environs ) +from .environ import ( get_environs ) from .interp import interp from sys import _current_frames +from threading import currentThread import os, sys class UnsetError( Exception ): pass @@ -145,21 +146,26 @@ runner = ( ( lambda main, args: main( args ) ) if runner is None else runner ) main = frame.f_globals[ 'main' ] if main is None else main - do_debug = is_environ_set( 'PYDBG' ) - do_profile = is_environ_set( 'PYPROF' ) + do_debug = os.environ.get( 'PYDBG', '' ) != '' + do_profile = os.environ.get( 'PYPROF', '' ) != '' if do_debug: import pdb signal(SIGINT, lambda *args: pdb.set_trace()) status = pdb.runcall( runner, main, sys.argv ) elif do_profile: - import cProfile as profile - container = {} - output_path = os.environ[ 'PYPROF' ] - profile.runctx( - 'container[ "status" ] = runner( main, sys.argv )', - globals(), locals(), filename = output_path ) - status = container[ 'status' ] + from cProfile import runctx + container = [] + try: + outpath = os.environ[ 'PYPROF' ] % \ + currentThread().getName() + except: + error( 'bad PYPROF:', os.environ[ 'PYPROF' ] ) + status = runner( main, sys.argv ) + else: + runctx( 'container[0] = runner( main, sys.argv )', + globals(), locals(), filename = outpath ) + status = container[0] else: status = runner( main, sys.argv ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-20 00:27:12
|
Revision: 247 http://assorted.svn.sourceforge.net/assorted/?rev=247&view=rev Author: yangzhang Date: 2008-01-19 16:27:16 -0800 (Sat, 19 Jan 2008) Log Message: ----------- bitfields Added Paths: ----------- sandbox/trunk/src/c/bitfields.c Added: sandbox/trunk/src/c/bitfields.c =================================================================== --- sandbox/trunk/src/c/bitfields.c (rev 0) +++ sandbox/trunk/src/c/bitfields.c 2008-01-20 00:27:16 UTC (rev 247) @@ -0,0 +1,19 @@ +#include <stdio.h> +struct s { + // This just means that it is 1 bit wide. It's not standard C (where + // bitfields are used only on ints). Seen in JOSMP. Some source on the + // Internet (forgot where) mentioned that although these may save space, they + // may end up generating a surprising amount of code (depending on the + // alignment details). + unsigned char c : 1; +}; +int main() { + // These are the only two valid values. + struct s s = { 1 }; + struct s t = { 0 }; + // This wouldn't work. + // struct s u = { 2 }; + printf("%d %d\n", s.c, t.c); + return 0; +} +// vim:et:sw=2:ts=2 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-20 00:23:49
|
Revision: 246 http://assorted.svn.sourceforge.net/assorted/?rev=246&view=rev Author: yangzhang Date: 2008-01-19 16:23:46 -0800 (Sat, 19 Jan 2008) Log Message: ----------- left out some old files on laptop Added Paths: ----------- problems/topcoder/BinaryCode/BinaryCode.cs problems/topcoder/Lottery/Lottery.cs problems/topcoder/PenLift/PenLift.jnt Added: problems/topcoder/BinaryCode/BinaryCode.cs =================================================================== --- problems/topcoder/BinaryCode/BinaryCode.cs (rev 0) +++ problems/topcoder/BinaryCode/BinaryCode.cs 2008-01-20 00:23:46 UTC (rev 246) @@ -0,0 +1,129 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; + +public class BinaryCode { + public string[] decode(string message) { + //List<int> xs = new List<int>(); + //foreach(char c in message) xs.Add(c - '0'); + //List<string> ss = new List<string>(); + //for (int i = 0; i < 2; i++) { + // List<int> ys = new List<int>(); + // ys.Add(i); + // for (int j = 1; j < xs.Count; j++) + // ys.Add(xs[j - 1] - ys[j - 1] - (j > 1 ? ys[j - 2] : 0)); + // string s = ""; + // foreach (int j in ys) s += j; + // bool bad = false; + // foreach (int j in ys) if (j != 0 && j != 1) bad = true; + // { + // int j = xs.Count; + // if (xs[j - 1] - ys[j - 1] - (j > 1 ? ys[j - 2] : 0) != 0) bad = true; + // } + // if (bad) s = "NONE"; + // ss.Add(s); + //} + //return ss.ToArray(); + + string m = message; + string[] ss = new string[2]; + for (int i = 0; i < 2; i++) { + string s = "" + i; + for (int j = 1; j < m.Length; j++) + s += (m[j - 1] - s[j - 1] - (j > 1 ? s[j - 2] : '0') + '0'); + bool bad = false; + for (int j = 0; j < m.Length; j++) + if (s[j] != '0' && s[j] != '1') bad = true; + if (s[s.Length - 1] + (s.Length > 1 ? s[s.Length - 2] : '0') != '0' + m[m.Length - 1]) bad = true; + if (bad) s = "NONE"; + ss[i] = s; + } + return ss; + } + + + + + + + public void pp<T>(T x) { Console.WriteLine(x); } + + + + + + + + + // BEGIN CUT HERE + public static void Main(string[] args) { + eq(0,(new BinaryCode()).decode("123210122"),new string[] { "011100011", "NONE" }); + eq(1,(new BinaryCode()).decode("11"),new string[] { "01", "10" }); + eq(2,(new BinaryCode()).decode("22111"),new string[] { "NONE", "11001" }); + eq(3,(new BinaryCode()).decode("123210120"),new string[] { "NONE", "NONE" }); + eq(4,(new BinaryCode()).decode("3"),new string[] { "NONE", "NONE" }); + eq(5,(new BinaryCode()).decode("12221112222221112221111111112221111"),new string[] { "01101001101101001101001001001101001", "10110010110110010110010010010110010" }); + Console.WriteLine("done!"); + Console.Read(); + } + private static void eq( int n, object have, object need) { + if( eq( have, need ) ) { + Console.WriteLine( "Case "+n+" passed." ); + } else { + Console.Write( "Case "+n+" failed: expected " ); + print( need ); + Console.Write( ", received " ); + print( have ); + Console.WriteLine(); + } + } + private static void eq( int n, Array have, Array need) { + if( have == null || have.Length != need.Length ) { + Console.WriteLine("Case "+n+" failed: returned "+have.Length+" elements; expected "+need.Length+" elements."); + print( have ); + print( need ); + return; + } + for( int i= 0; i < have.Length; i++ ) { + if( ! eq( have.GetValue(i), need.GetValue(i) ) ) { + Console.WriteLine( "Case "+n+" failed. Expected and returned array differ in position "+i ); + print( have ); + print( need ); + return; + } + } + Console.WriteLine("Case "+n+" passed."); + } + private static bool eq( object a, object b ) { + if ( a is double && b is double ) { + return Math.Abs((double)a-(double)b) < 1E-9; + } else { + return a!=null && b!=null && a.Equals(b); + } + } + private static void print( object a ) { + if ( a is string ) { + Console.Write("\"{0}\"", a); + } else if ( a is long ) { + Console.Write("{0}L", a); + } else { + Console.Write(a); + } + } + private static void print( Array a ) { + if ( a == null) { + Console.WriteLine("<NULL>"); + } + Console.Write('{'); + for ( int i= 0; i < a.Length; i++ ) { + print( a.GetValue(i) ); + if( i != a.Length-1 ) { + Console.Write(", "); + } + } + Console.WriteLine( '}' ); + } + // END CUT HERE +} Added: problems/topcoder/Lottery/Lottery.cs =================================================================== --- problems/topcoder/Lottery/Lottery.cs (rev 0) +++ problems/topcoder/Lottery/Lottery.cs 2008-01-20 00:23:46 UTC (rev 246) @@ -0,0 +1,131 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; + +using P = System.Collections.Generic.KeyValuePair<double, string>; + +public class Lottery { + public string[] sortByOdds(string[] rules) { + List<P> list = new List<P>(); + foreach(string rule in rules) { + string[] parts = rule.Split(':'); + string name = parts[0]; + parts = parts[1].Trim().Split(); + int choi = int.Parse(parts[0]); + int blan = int.Parse(parts[1]); + bool sort = (parts[2] == "T"); + bool uniq = (parts[3] == "T"); + double z = 999; + if (!sort && !uniq) z = Math.Pow(choi, blan); + if (!sort && uniq) z = fact(choi) / fact(choi - blan); + if (sort && !uniq) z = fact(choi+blan-1) / fact(choi-1) / fact(blan); + if (sort && uniq) z = fact(choi) / fact(choi - blan) / fact(blan); + //pp(name + " " + choi + " " + blan + " " + " " + sort + " " + uniq + " " + z); + list.Add(new P(z, name)); + } + list.Sort(delegate(P x, P y) { return x.Key.CompareTo(y.Key) != 0 ? x.Key.CompareTo(y.Key) : x.Value.CompareTo(y.Value); }); + List<String> ys = new List<String>(); + foreach (P p in list) ys.Add(p.Value); + return ys.ToArray(); + } + double fact(int x) { + double y = 1; + for (int i = 0; i < x; i++) { + y *= i+1; + } + return y; + } + + + + + + + public void pp<T>(T x) { Console.WriteLine(x); } + + + + + + + + + // BEGIN CUT HERE + public static void Main(string[] args) { + eq(0,(new Lottery()).sortByOdds(new string[] {"PICK ANY TWO: 10 2 F F" + ,"PICK TWO IN ORDER: 10 2 T F" + ,"PICK TWO DIFFERENT: 10 2 F T" + ,"PICK TWO LIMITED: 10 2 T T"}),new string[] { "PICK TWO LIMITED", "PICK TWO IN ORDER", "PICK TWO DIFFERENT", "PICK ANY TWO" }); + eq(1,(new Lottery()).sortByOdds(new string[] {"INDIGO: 93 8 T F", + "ORANGE: 29 8 F T", + "VIOLET: 76 6 F F", + "BLUE: 100 8 T T", + "RED: 99 8 T T", + "GREEN: 78 6 F T", + "YELLOW: 75 6 F F"} + ),new string[] { "RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "INDIGO", "VIOLET" }); + eq(2,(new Lottery()).sortByOdds(new string[] {}),new string[] { }); + Console.WriteLine("done!"); + Console.Read(); + } + private static void eq( int n, object have, object need) { + if( eq( have, need ) ) { + Console.WriteLine( "Case "+n+" passed." ); + } else { + Console.Write( "Case "+n+" failed: expected " ); + print( need ); + Console.Write( ", received " ); + print( have ); + Console.WriteLine(); + } + } + private static void eq( int n, Array have, Array need) { + if( have == null || have.Length != need.Length ) { + Console.WriteLine("Case "+n+" failed: returned "+have.Length+" elements; expected "+need.Length+" elements."); + print( have ); + print( need ); + return; + } + for( int i= 0; i < have.Length; i++ ) { + if( ! eq( have.GetValue(i), need.GetValue(i) ) ) { + Console.WriteLine( "Case "+n+" failed. Expected and returned array differ in position "+i ); + print( have ); + print( need ); + return; + } + } + Console.WriteLine("Case "+n+" passed."); + } + private static bool eq( object a, object b ) { + if ( a is double && b is double ) { + return Math.Abs((double)a-(double)b) < 1E-9; + } else { + return a!=null && b!=null && a.Equals(b); + } + } + private static void print( object a ) { + if ( a is string ) { + Console.Write("\"{0}\"", a); + } else if ( a is long ) { + Console.Write("{0}L", a); + } else { + Console.Write(a); + } + } + private static void print( Array a ) { + if ( a == null) { + Console.WriteLine("<NULL>"); + } + Console.Write('{'); + for ( int i= 0; i < a.Length; i++ ) { + print( a.GetValue(i) ); + if( i != a.Length-1 ) { + Console.Write(", "); + } + } + Console.WriteLine( '}' ); + } + // END CUT HERE +} Added: problems/topcoder/PenLift/PenLift.jnt =================================================================== (Binary files differ) Property changes on: problems/topcoder/PenLift/PenLift.jnt ___________________________________________________________________ Name: svn:mime-type + application/octet-stream This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-20 00:23:14
|
Revision: 245 http://assorted.svn.sourceforge.net/assorted/?rev=245&view=rev Author: yangzhang Date: 2008-01-19 16:23:20 -0800 (Sat, 19 Jan 2008) Log Message: ----------- - this commit: darcs configuration added to installer - messed up previous commit - updated .vimrc - tweaked subversion, ssh configs Modified Paths: -------------- configs/trunk/setup-yang.bash Modified: configs/trunk/setup-yang.bash =================================================================== --- configs/trunk/setup-yang.bash 2008-01-20 00:21:21 UTC (rev 244) +++ configs/trunk/setup-yang.bash 2008-01-20 00:23:20 UTC (rev 245) @@ -15,6 +15,7 @@ install .screenrc screenrc install .pythonrc.py pythonrc.py install .valgrindrc valgrindrc +install .darcs/ darcs/boring install .subversion/ subversion/config install .Xdefaults Xdefaults install .synergy.conf synergy.conf This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-20 00:21:21
|
Revision: 244 http://assorted.svn.sourceforge.net/assorted/?rev=244&view=rev Author: yangzhang Date: 2008-01-19 16:21:21 -0800 (Sat, 19 Jan 2008) Log Message: ----------- added darcs configuration Modified Paths: -------------- configs/trunk/src/ssh/config configs/trunk/src/subversion/config configs/trunk/src/vim/plugin/_yang.vim Added Paths: ----------- configs/trunk/src/darcs/ configs/trunk/src/darcs/boring Added: configs/trunk/src/darcs/boring =================================================================== --- configs/trunk/src/darcs/boring (rev 0) +++ configs/trunk/src/darcs/boring 2008-01-20 00:21:21 UTC (rev 244) @@ -0,0 +1,2 @@ +^_whizzy_.*_tex$ +\.aux$ Modified: configs/trunk/src/ssh/config =================================================================== --- configs/trunk/src/ssh/config 2008-01-20 00:17:56 UTC (rev 243) +++ configs/trunk/src/ssh/config 2008-01-20 00:21:21 UTC (rev 244) @@ -5,6 +5,10 @@ # StrictHostKeyChecking no +Host pdos + HostName pdos.csail.mit.edu + User yang + Host sn HostName sn002.datapository.net User yang Modified: configs/trunk/src/subversion/config =================================================================== --- configs/trunk/src/subversion/config 2008-01-20 00:17:56 UTC (rev 243) +++ configs/trunk/src/subversion/config 2008-01-20 00:21:21 UTC (rev 244) @@ -67,7 +67,7 @@ [miscellany] ### Set global-ignores to a set of whitespace-delimited globs ### which Subversion will ignore in its 'status' output. -global-ignores = *.aux *.aux *.elc *.ml[io] *.hi .*.sw? *.class *.pyc *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store +global-ignores = tags cscope.* *.aux *.aux *.elc *.ml[io] *.hi .*.sw? *.class *.pyc *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store ### Set log-encoding to the default encoding for log messages # log-encoding = latin1 ### Set use-commit-times to make checkout/update/switch/revert Modified: configs/trunk/src/vim/plugin/_yang.vim =================================================================== --- configs/trunk/src/vim/plugin/_yang.vim 2008-01-20 00:17:56 UTC (rev 243) +++ configs/trunk/src/vim/plugin/_yang.vim 2008-01-20 00:21:21 UTC (rev 244) @@ -1,3 +1,5 @@ +" crawl http://eigenstate.org/vim/vimrc + " UNSORTED " command! DiffOff :call CleanDiffOptions() " @@ -25,6 +27,9 @@ + + + imap ^D <ESC>`[ @@ -40,14 +45,6 @@ " OPTIONS --------------------------------------------------------------------- -"hi Normal guifg=black guibg=#aaccaa " highlight -"hi Normal guifg=black guibg=#ccddcc " highlight -" colorscheme -colo desert -" syntax -sy enable -set modeline -set ws " disable reports "set report=99999 set display=lastline @@ -74,20 +71,9 @@ set gfn=Bitstream\ Vera\ Sans\ Mono\ 12 endif -" switchbuf -set swb=useopen " TODO find out what's still causing t_vb to be set " TODO upgrade to vim 7 set visualbell t_vb= -" enable bottom horizontal scrollbar -set go+=b -" ruler -set ru -set list -" equalalways -set noea -" hlsearch -set hls highlight WhitespaceEOL ctermbg=red guibg=red " red trailing spaces "match WhitespaceEOL /\s\+$/ " whitespace @@ -96,63 +82,51 @@ else set listchars=tab:>-,trail:- endif -" C indent -"set cindent -set winaltkeys=menu -" winminheight -set wmh=0 -" noexpandtab -set noet -" tabstop -set ts=4 -" shiftwidth -set sw=4 -" smartindent -set si -" showmatch -set sm -" mouse -set mouse=a if $TERM =~ '^screen' && exists("+ttymouse") && &ttymouse == '' - set ttymouse=xterm + set ttymouse=xterm endif -" hidden -set hid -" incremental searching -set incsearch -" backspace -set bs=indent,eol,start -" winaltkeys -set wak=no -" cmdheight -"set ch=2 -" highlight strings in C comments -let c_comment_strings=1 -" whichwrap -set ww+=<,>,[,],h,l -" linebreak -set lbr -" number -"set nu -" laststatus -set ls=2 -" statusline +let c_comment_strings=1 " highlight strings in C comments " see plugin/cream-statusline.vim hi User1 guibg=#000000 guifg=#aaaaaa hi User2 guibg=#000000 gui=bold hi User3 guibg=#000000 guifg=LightBlue gui=bold hi User4 guibg=#000000 guifg=LightBlue gui=bold hi LineNr guibg=grey30 -set cindent -set cino+=(0 -set updatetime=500 -set fo+=n -set fo-=l -set ai -set nowrap +colorscheme desert +syntax enable +" set number " number lines +set autoindent +set backspace=indent,eol,start +set cinoptions+=(0 " TODO ??? +set expandtab +set formatoptions+=n " TODO ??? +set formatoptions-=l " TODO ??? +set guioptions+=b " enable bottom horizontal scrollbar +set hidden " TODO ??? +set hlsearch +set incsearch +set laststatus=2 " TODO ??? +set linebreak " do break lines +set list +set modeline " TODO ??? +set mouse=a +set noequalalways " TODO ??? +set nowrap +set ruler " TODO ??? +set shiftwidth=2 +set showmatch +set smartindent " TODO ??? +set switchbuf=useopen " TODO ??? +set tabstop=2 +set updatetime=500 +set whichwrap+=<,>,[,],h,l " wrap on these letters +set winaltkeys=menu +set winaltkeys=no +set wrapscan " TODO ??? + " AUTOCOMMANDS ---------------------------------------------------------------- " makes this enable plugins and indentation based on file types filetype plugin on @@ -168,30 +142,13 @@ au BufWritePost *.bin if &bin | %!xxd au BufWritePost *.bin set nomod | endif augroup END -" autocmd Project -au BufEnter .vimprojects setlocal et -" autocmd sources -au BufEnter sources setf make | setlocal et -" autocmd DIRS -au BufEnter DIRS setf make | setlocal et -" autocmd NesC -au BufEnter *.nc setf nc | setlocal et | setlocal sw=2 | setlocal ts=8 " Java/Eclim "au BufEnter *.java iunmap <tab> "au BufEnter *.java setlocal cot+=longest | inoremap <buffer> . .<c-x><c-u> | inoremap <buffer> <c-j> <c-x><c-u> | nnoremap <silent> <buffer> <tab> :call eclim#util#FillTemplate("${", "}")<cr> | nnoremap <silent> <buffer> <leader>i :JavaImport<cr> | nnoremap <silent> <buffer> <leader>d :JavaDocSearch -x declarations<cr> | nnoremap <silent> <buffer> <cr> :JavaSearchContext<cr> " autocmd Mapserver map files au BufNewFile,BufRead *.map setf map -" autocmd SLF -au BufEnter *.slf setf tcl | setlocal ts=8 -" autocmd TCL -au BufEnter *.tcl setlocal ts=8 -" autocmd Lisp -au BufEnter *.lisp setlocal et -" autocmd C, C++ -au BufEnter *.c setlocal cindent -au BufEnter *.cc setlocal cindent -au BufEnter *.cpp setlocal cindent -au BufEnter *.cxx setlocal cindent +" temporaries +autocmd BufEnter *.{c,cc,cpp,cxx,h} setlocal cindent expandtab softtabstop=4 shiftwidth=4 tabstop=8 " autocmd GDB au BufEnter *.gdb set ft=gdb " autocmd hxx, cxx @@ -201,10 +158,10 @@ " \ exe "normal g`\"" | " \ endif -" GNU style indentation -augroup CXX - autocmd BufRead *.cxx setlocal cinoptions={.5s,:.5s,+.5s,t0,g0,^-2,e-2,n-2,p2s,(0,=.5s formatoptions=croql cindent shiftwidth=4 tabstop=8 -augroup END +" GNU style indentation TODO +" augroup CXX +" autocmd BufRead *.cxx setlocal cinoptions={.5s,:.5s,+.5s,t0,g0,^-2,e-2,n-2,p2s,(0,=.5s formatoptions=croql cindent shiftwidth=4 tabstop=8 +" augroup END @@ -395,3 +352,29 @@ ""au BufRead *.hs compiler ghci " hugs ""au BufRead *.lhs compiler ghci " hugs filetype plugin indent on + +function ProjectDir() + let dir = expand('%') + if (dir =~ "^$") + let dir = getcwd() + endif + while isdirectory(dir) && + \ dir !~ '^/*$' && + \glob(dir . "/configure*") =~ "^$" + let dir = fnamemodify(dir, ":h") + endwhile + if glob(dir . "/configure*") =~ "^$" + let dir = getcwd() + endif + return dir +endfunction + +" ctags handling +let tag_path = ProjectDir() . "/tags" +let &tags = &tags . "," . tag_path +autocmd BufWritePost * + \ if exists("b:is_source") && b:is_source | + \ silent! exe "!ctags -f ".tag_path." -a ".expand("%") | + \ endif + +" vim:et:sw=2:ts=2 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-20 00:17:57
|
Revision: 243 http://assorted.svn.sourceforge.net/assorted/?rev=243&view=rev Author: yangzhang Date: 2008-01-19 16:17:56 -0800 (Sat, 19 Jan 2008) Log Message: ----------- signed Modified Paths: -------------- sandbox/trunk/src/c/signed.c Modified: sandbox/trunk/src/c/signed.c =================================================================== --- sandbox/trunk/src/c/signed.c 2008-01-20 00:17:21 UTC (rev 242) +++ sandbox/trunk/src/c/signed.c 2008-01-20 00:17:56 UTC (rev 243) @@ -1,8 +1,22 @@ -// vim:et:sw=2:ts=2 +#include <inttypes.h> #include <stdio.h> + int main() { - size_t len = 0; - int i; - for (i = 0; i < len; i++) printf("hello\n"); + { + size_t len = 0; + int i; + // nothing is printed + for (i = 0; i < len; i++) printf("hello\n"); + } + + { + int i = 1; + uint32_t j = 1; + if (!(i || j)) printf("i || j == 0\n"); + else printf("i || j != 0\n"); // this is printed + } + return 0; } + +// vim:et:sw=2:ts=2 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-20 00:17:25
|
Revision: 242 http://assorted.svn.sourceforge.net/assorted/?rev=242&view=rev Author: yangzhang Date: 2008-01-19 16:17:21 -0800 (Sat, 19 Jan 2008) Log Message: ----------- tweaks Modified Paths: -------------- wallpaper-tools/trunk/src/next-wallpaper.bash wallpaper-tools/trunk/src/remove-wallpaper.bash Modified: wallpaper-tools/trunk/src/next-wallpaper.bash =================================================================== --- wallpaper-tools/trunk/src/next-wallpaper.bash 2008-01-19 00:14:37 UTC (rev 241) +++ wallpaper-tools/trunk/src/next-wallpaper.bash 2008-01-20 00:17:21 UTC (rev 242) @@ -1,6 +1,6 @@ #!/usr/bin/env bash -: ${WALLPAPER_DIR:="$HOME/cache/wallpaper"} +: ${WALLPAPER_DIR:="$HOME/shared/cache/wallpaper"} : ${WALLPAPER_LOG:=/tmp/next-wallpaper.log} find "$WALLPAPER_DIR" | Modified: wallpaper-tools/trunk/src/remove-wallpaper.bash =================================================================== --- wallpaper-tools/trunk/src/remove-wallpaper.bash 2008-01-19 00:14:37 UTC (rev 241) +++ wallpaper-tools/trunk/src/remove-wallpaper.bash 2008-01-20 00:17:21 UTC (rev 242) @@ -1,10 +1,13 @@ #!/usr/bin/env bash -: ${WALLPAPER_REMOVE_LOG:="$HOME/Desktop/removed-wallpapers.log"} +set -o errexit +set -o nounset +log="$1" + gconftool -g /desktop/gnome/background/picture_filename | xargs readlink -f | -tee -a "$WALLPAPER_REMOVE_LOG" | +tee -a "$log" | xargs -I_ mv _ ~/.Trash next-wallpaper This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-19 00:14:47
|
Revision: 241 http://assorted.svn.sourceforge.net/assorted/?rev=241&view=rev Author: yangzhang Date: 2008-01-18 16:14:37 -0800 (Fri, 18 Jan 2008) Log Message: ----------- multithreaded profiling Added Paths: ----------- sandbox/trunk/src/py/profile-threads/ sandbox/trunk/src/py/profile-threads/profmt.py Added: sandbox/trunk/src/py/profile-threads/profmt.py =================================================================== --- sandbox/trunk/src/py/profile-threads/profmt.py (rev 0) +++ sandbox/trunk/src/py/profile-threads/profmt.py 2008-01-19 00:14:37 UTC (rev 241) @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +# Multithreaded profiling with cProfile: a bit of a hassle, but it seems to +# work. (Googling revealed very little information juxtaposing cProfile with +# threads or with threading.setprofile.) + +from cProfile import * +from time import * +from threading import * + +def profile_thread(f, *args): + runctx('f(*args)', locals(), globals(), filename = 'profmt-%s.pstats' % currentThread().getName()) + +def worker(i): + for i in range(2): + sleep(1) + print i + +def main(): + for i in range(5): + Thread(target=profile_thread, args=(worker, i,)).start() + +runctx('main()', locals(), globals(), filename='profmt.pstats') Property changes on: sandbox/trunk/src/py/profile-threads/profmt.py ___________________________________________________________________ Name: svn:executable + * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-18 22:28:59
|
Revision: 240 http://assorted.svn.sourceforge.net/assorted/?rev=240&view=rev Author: yangzhang Date: 2008-01-18 14:28:57 -0800 (Fri, 18 Jan 2008) Log Message: ----------- - added result to condvar.wait - fixed tag() - flexible pickler - fixed read_pickle - touchups Modified Paths: -------------- python-afx/trunk/src/afx/pubsub.py Modified: python-afx/trunk/src/afx/pubsub.py =================================================================== --- python-afx/trunk/src/afx/pubsub.py 2008-01-18 09:01:43 UTC (rev 239) +++ python-afx/trunk/src/afx/pubsub.py 2008-01-18 22:28:57 UTC (rev 240) @@ -8,9 +8,9 @@ from cStringIO import StringIO from itertools import chain from struct import unpack -from cPickle import dumps, load +from cPickle import load from commons.log import warning -from commons.seqs import streamlen, safe_pickle +from commons.seqs import streamlen, safe_pickler import af stop = 'stop' @@ -53,10 +53,11 @@ self.waiters = [] self.token = token @af.task - def wait( self ): + def wait( self, result = None ): c = af.channel( 1 ) self.waiters.append( c ) yield c.get() + yield af.result( result ) def notify_one( self ): if len( self.waiters ) > 0: res = self.waiters.pop().try_put( self.token ) @@ -261,42 +262,56 @@ @af.task def tag( task, attach ): result = yield task - yield ( attach, result ) + yield af.result( ( attach, result ) ) -@af.task -def write_pickle( socket, obj ): - yield socket.write( safe_pickle( obj ) ) +class cell( object ): + """ + Holds a single value, and replaces it on each put. + Puts are also non-yielding. + """ + def __init__( self ): + self.q = af.channel( 1 ) + def put( self, x ): + deplete( self.q ) + res = self.q.try_put( x ) + assert res + @af.task + def get( self ): + yield af.result( ( yield self.q.get() ) ) @af.task -def read_pickle( socket, init = '', length_thresh = 100000 ): - with closing( StringIO() ) as stream: +def read_pickle( read, init = '', length_thresh = 100000 ): + with closing( StringIO() ) as sio: obj = None # return this if we hit eof (not enough bytes read) + sio.write( init ) @af.task def read_until(target): - remain = target - streamlen(stream) + remain = target - streamlen(sio) if remain > 0: - chunk = yield socket.read( remain ) + chunk = yield read( remain ) # append to end - stream.seek(0,2) - stream.write( chunk ) - yield af.result( stream.tell() >= target ) + sio.seek(0,2) + sio.write( chunk ) + offset = streamlen(sio) + sio.seek(0) + yield af.result( offset >= target ) if ( yield read_until(4) ): - stream.seek(0) - lengthstr = stream.read(4) + lengthstr = sio.read(4) (length,) = unpack('i4', lengthstr) - if length_thresh is not None and length > length_thresh or length <= 0: + if length_thresh is not None and length > length_thresh or \ + length <= 0: warning( 'read_pickle', 'got length', length, - 'streamlen', streamlen(stream), + 'streamlen', streamlen(sio), 'first bytes %x %x %x %x' % tuple(map(ord,lengthstr)) ) if ( yield read_until(length + 4) ): # start reading from right after header - stream.seek(4) - obj = load( stream ) + sio.seek(4) + obj = load(sio) - yield af.result( ( obj, stream.read() ) ) + yield af.result( ( obj, sio.read() ) ) #### stream.write( init ) #### while True: @@ -309,33 +324,22 @@ #### else: #### yield af.result( ( obj, stream.read() ) ) -class cell( object ): - """ - Holds a single value, and replaces it on each put. - Puts are also non-yielding. - """ - def __init__( self ): - self.q = af.channel( 1 ) - def put( self, x ): - deplete( self.q ) - res = self.q.try_put( x ) - assert res - @af.task - def get( self ): - yield af.result( ( yield self.q.get() ) ) - class socket_unpickler( object ): """ Pickle objects directly to a socket stream. """ + def __init__( self, s ): self.s = s self.buffer = '' + @af.task def read( self ): - obj, self.buffer = yield read_pickle( self.s, self.buffer ) + obj, self.buffer = yield read_pickle( self.s.read, self.buffer ) yield af.result( obj ) + + class socket_line_reader( object ): """ A line-reading interface to socket streams. @@ -343,6 +347,7 @@ def __init__( self, s ): self.s = s self.buffer = [] + @af.task def read_line( self ): """ @@ -362,6 +367,7 @@ yield af.result( line ) else: self.buffer.append( chunk[ start : ] ) + @af.task def read_some_lines( self ): """ @@ -381,15 +387,17 @@ else: self.buffer.append( chunk ) + + @af.task def get_traceback(): - import sys - try: raise Exception() - except: yield af.result( sys.exc_info()[2] ) + import sys + try: raise Exception() + except: yield af.result( sys.exc_info()[2] ) @af.task def get_tb_string(): - import traceback - tb = yield get_traceback() - yield af.result( '\n'.join( traceback.format_tb( tb ) ) ) + import traceback + tb = yield get_traceback() + yield af.result( '\n'.join( traceback.format_tb( tb ) ) ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-18 09:01:45
|
Revision: 239 http://assorted.svn.sourceforge.net/assorted/?rev=239&view=rev Author: yangzhang Date: 2008-01-18 01:01:43 -0800 (Fri, 18 Jan 2008) Log Message: ----------- updated pickling tools to allow/default to more efficient protocols Modified Paths: -------------- python-commons/trunk/src/commons/seqs.py Modified: python-commons/trunk/src/commons/seqs.py =================================================================== --- python-commons/trunk/src/commons/seqs.py 2008-01-18 06:56:08 UTC (rev 238) +++ python-commons/trunk/src/commons/seqs.py 2008-01-18 09:01:43 UTC (rev 239) @@ -18,7 +18,7 @@ default_chunk_size = 8192 -def read_pickle( read ): +def read_pickle( read, init = '', length_thresh = 100000 ): """ Given a reader function L{read}, reads in pickled objects from it. I am a generator which yields unpickled objects. I assume that the pickling @@ -33,26 +33,36 @@ the EOF that were not consumed by unpickling. @rtype: (object, str) """ - with closing( StringIO() ) as stream: + with closing( StringIO() ) as sio: obj = None # return this if we hit eof (not enough bytes read) + sio.write( init ) def read_until( target ): - remain = target - streamlen( stream ) + remain = target - streamlen( sio ) if remain > 0: chunk = read( remain ) # append to end - stream.seek(0,2) - stream.write( chunk ) - return stream.tell() >= target + sio.seek(0,2) + sio.write( chunk ) + offset = streamlen( sio ) + sio.seek(0) + return offset >= target if read_until(4): - stream.seek(0) - (length,) = unpack('i4', stream.read(4)) + lengthstr = sio.read(4) + (length,) = unpack('i4', lengthstr) + if length_thresh is not None and length > length_thresh or \ + length <= 0: + warning( 'read_pickle', + 'got length', length, + 'streamlen', streamlen(sio), + 'first bytes %x %x %x %x' % tuple(map(ord,lengthstr)) ) if read_until(length+4): - stream.seek(4) - obj = load(stream) + # start reading from right after header + sio.seek(4) + obj = load(sio) - return ( obj, stream.read() ) + return ( obj, sio.read() ) def read_pickles( read ): """ @@ -60,16 +70,23 @@ """ while True: pair = ( obj, rem ) = read_pickle( read ) - if obj is None: - break + if obj is None: break yield pair -def safe_pickle( obj ): - """ - Pickle L{obj} but prepends the serialized length in bytes. - """ - msg = dumps(obj) - return pack('i4',len(msg)) + msg +class safe_pickler( object ): + def __init__( self, protocol = HIGHEST_PROTOCOL ): + self.sio = StringIO() + self.pickler = Pickler( self.sio, protocol ) + def dumps( self, obj ): + """ + Pickle L{obj} but prepends the serialized length in bytes. + """ + self.pickler.clear_memo() + self.sio.seek(0) + self.pickler.dump(obj) + self.sio.truncate() + msg = self.sio.getvalue() + return pack('i4', self.sio.tell()) + msg def write_pickle( obj, write ): """ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-18 06:56:17
|
Revision: 238 http://assorted.svn.sourceforge.net/assorted/?rev=238&view=rev Author: yangzhang Date: 2008-01-17 22:56:08 -0800 (Thu, 17 Jan 2008) Log Message: ----------- small cleanup, reintroduced tag Modified Paths: -------------- python-afx/trunk/src/afx/pubsub.py Modified: python-afx/trunk/src/afx/pubsub.py =================================================================== --- python-afx/trunk/src/afx/pubsub.py 2008-01-18 06:55:22 UTC (rev 237) +++ python-afx/trunk/src/afx/pubsub.py 2008-01-18 06:56:08 UTC (rev 238) @@ -1,5 +1,5 @@ # -*- mode: python; tab-width: 2; indent-tabs-mode: nil; py-indent-offset: 2; -*- -# vim:et:sw=2:ts=2 +# vim:et:sw=4:ts=4 # TODO rename something to 'skip channels' (a la ch paper) @@ -70,7 +70,7 @@ """ A bool on which threads can wait for notifications about changes in state. """ - def __init__( self, value = False, result = None ): + def __init__( self, value = False ): self.onset = condvar() self.onreset = condvar() self.value = value @@ -253,15 +253,17 @@ return isinstance( proc, af.task ) # XXX this won't work with exceptions +# XXX huh? what do i mean by the above? #@af.task #def tagged_any( tasks* ): -# @af.task -# def tag( task, index ): -# result = yield task() -# yield ( index, result ) # yield any( tag( task, index ) for index, task in enumerate( tasks ) ) @af.task +def tag( task, attach ): + result = yield task + yield ( attach, result ) + +@af.task def write_pickle( socket, obj ): yield socket.write( safe_pickle( obj ) ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-18 06:55:21
|
Revision: 237 http://assorted.svn.sourceforge.net/assorted/?rev=237&view=rev Author: yangzhang Date: 2008-01-17 22:55:22 -0800 (Thu, 17 Jan 2008) Log Message: ----------- added bidict Modified Paths: -------------- python-commons/trunk/src/commons/structs.py Modified: python-commons/trunk/src/commons/structs.py =================================================================== --- python-commons/trunk/src/commons/structs.py 2008-01-18 06:55:09 UTC (rev 236) +++ python-commons/trunk/src/commons/structs.py 2008-01-18 06:55:22 UTC (rev 237) @@ -1,5 +1,5 @@ # -*- mode: python; tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4; -*- -# vim:ft=python:et:sw=4:ts=4 +# vim:ft=python:et:sw=2:ts=2 """ Data structures: Heaps, lists, queues, and Python hacks. @@ -7,6 +7,30 @@ import copy, heapq, itertools, sys +class bidict( object ): + """Bi-directional dictionary; assumes 1:1 mappings.""" + def __init__( self ): self.a2b = {}; self.b2a = {} + def add( self, a, b ): self.a2b[a] = b; self.b2a[b] = a + def get_a( self, a ): return self.a2b[a] + def get_b( self, b ): return self.b2a[b] + def get_a_default( self, a, d = None ): return self.a2b.get(a,d) + def get_b_default( self, b, d = None ): return self.b2a.get(b,d) + def contains_a( self, a ): return a in self.a2b + def contains_b( self, b ): return b in self.b2a + def __len__( self ): return len( self.a2b ) + def items( self ): return self.a2b.iteritems() + def as( self ): return self.a2b.keys() + def bs( self ): return self.b2a.keys() + def clear( self ): self.a2b.clear(); self.b2a.clear() + def remove_a( self, a ): + b = self.a2b.pop(a) + del self.b2a[b] + return b + def remove_b( self, b ): + a = self.b2a.pop(b) + del self.a2b[a] + return a + class idict( dict ): """Case-insensitive string-keyed dictionary.""" def __getitem__( self, k ): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-18 06:55:04
|
Revision: 236 http://assorted.svn.sourceforge.net/assorted/?rev=236&view=rev Author: yangzhang Date: 2008-01-17 22:55:09 -0800 (Thu, 17 Jan 2008) Log Message: ----------- added read_pickles, touched up doc Modified Paths: -------------- python-commons/trunk/src/commons/seqs.py Modified: python-commons/trunk/src/commons/seqs.py =================================================================== --- python-commons/trunk/src/commons/seqs.py 2008-01-17 23:57:23 UTC (rev 235) +++ python-commons/trunk/src/commons/seqs.py 2008-01-18 06:55:09 UTC (rev 236) @@ -27,6 +27,11 @@ @param read: The reader function that reads from a stream. It should take a single argument, the number of bytes to consume. @type read: function + + @return: A tuple whose first element is the deserialized object or None if + EOF was encountered, and whose second element is the remainder bytes until + the EOF that were not consumed by unpickling. + @rtype: (object, str) """ with closing( StringIO() ) as stream: obj = None # return this if we hit eof (not enough bytes read) @@ -49,6 +54,16 @@ return ( obj, stream.read() ) +def read_pickles( read ): + """ + Reads all the consecutively pickled objects from the L{read} function. + """ + while True: + pair = ( obj, rem ) = read_pickle( read ) + if obj is None: + break + yield pair + def safe_pickle( obj ): """ Pickle L{obj} but prepends the serialized length in bytes. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-17 23:57:19
|
Revision: 235 http://assorted.svn.sourceforge.net/assorted/?rev=235&view=rev Author: yangzhang Date: 2008-01-17 15:57:23 -0800 (Thu, 17 Jan 2008) Log Message: ----------- fixed accidental wiping out of read-file in persistent disk double buffer Modified Paths: -------------- python-commons/trunk/src/commons/files.py Modified: python-commons/trunk/src/commons/files.py =================================================================== --- python-commons/trunk/src/commons/files.py 2008-01-17 23:41:52 UTC (rev 234) +++ python-commons/trunk/src/commons/files.py 2008-01-17 23:57:23 UTC (rev 235) @@ -86,18 +86,18 @@ writing, and a facility for swapping the two roles is provided. """ def __init__( self, path_base, do_persist = True ): - self.paths = [ path_base + '.0', path_base + '.1' ] + self.paths = map( path, [ path_base + '.0', path_base + '.1' ] ) self.do_persist = do_persist self.switch_status = path( path_base + '.switched' ) if not do_persist or not self.switch_status.exists(): self.w, self.r = 0, 1 # default else: self.w, self.r = 1, 0 - # initialize empty reader file - with file( self.paths[ self.r ], 'w' ): pass self.reload_files() def reload_files( self ): self.writer = file( self.paths[ self.w ], 'w' ) + if not self.paths[ self.r ].exists(): + self.paths[ self.r ].touch() self.reader = file( self.paths[ self.r ] ) def switch( self ): self.close() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-17 23:41:58
|
Revision: 234 http://assorted.svn.sourceforge.net/assorted/?rev=234&view=rev Author: yangzhang Date: 2008-01-17 15:41:52 -0800 (Thu, 17 Jan 2008) Log Message: ----------- moved safe_pickle to commons; added packet length sanity checking Modified Paths: -------------- python-afx/trunk/src/afx/pubsub.py Modified: python-afx/trunk/src/afx/pubsub.py =================================================================== --- python-afx/trunk/src/afx/pubsub.py 2008-01-17 23:15:04 UTC (rev 233) +++ python-afx/trunk/src/afx/pubsub.py 2008-01-17 23:41:52 UTC (rev 234) @@ -7,9 +7,10 @@ from contextlib import closing from cStringIO import StringIO from itertools import chain -from struct import pack, unpack +from struct import unpack from cPickle import dumps, load -from commons.seqs import streamlen +from commons.log import warning +from commons.seqs import streamlen, safe_pickle import af stop = 'stop' @@ -264,14 +265,9 @@ def write_pickle( socket, obj ): yield socket.write( safe_pickle( obj ) ) -def safe_pickle( obj ): - msg = dumps(obj) - return pack('i4',len(msg)) + msg - @af.task -def read_pickle( socket, init = '' ): +def read_pickle( socket, init = '', length_thresh = 100000 ): with closing( StringIO() ) as stream: - failed = False obj = None # return this if we hit eof (not enough bytes read) @af.task @@ -286,7 +282,13 @@ if ( yield read_until(4) ): stream.seek(0) - (length,) = unpack('i4',stream.read(4)) + lengthstr = stream.read(4) + (length,) = unpack('i4', lengthstr) + if length_thresh is not None and length > length_thresh or length <= 0: + warning( 'read_pickle', + 'got length', length, + 'streamlen', streamlen(stream), + 'first bytes %x %x %x %x' % tuple(map(ord,lengthstr)) ) if ( yield read_until(length + 4) ): # start reading from right after header stream.seek(4) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-17 23:15:13
|
Revision: 233 http://assorted.svn.sourceforge.net/assorted/?rev=233&view=rev Author: yangzhang Date: 2008-01-17 15:15:04 -0800 (Thu, 17 Jan 2008) Log Message: ----------- added multi-threaded stack dumps to sigquit handler Modified Paths: -------------- python-commons/trunk/src/commons/startup.py Modified: python-commons/trunk/src/commons/startup.py =================================================================== --- python-commons/trunk/src/commons/startup.py 2008-01-17 23:13:45 UTC (rev 232) +++ python-commons/trunk/src/commons/startup.py 2008-01-17 23:15:04 UTC (rev 233) @@ -9,6 +9,7 @@ from .log import ( critical, debug, config_logging ) from .environ import ( is_environ_set, get_environs ) from .interp import interp +from sys import _current_frames import os, sys class UnsetError( Exception ): pass @@ -101,12 +102,15 @@ from traceback import print_stack from cStringIO import StringIO s = StringIO() - print_stack(file = s) - print s.getvalue() + for tid, frame in _current_frames().iteritems(): + print >> s, 'thread', tid + print_stack(f = frame, file = s) + output = s.getvalue() + print output sys.stdout.flush() - print >> sys.stderr, s.getvalue() + print >> sys.stderr, output sys.stderr.flush() - critical( '', s.getvalue() ) + critical( '', output ) def run_main( main = None, do_force = False, runner = None, use_sigquit_handler = False ): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-17 23:14:09
|
Revision: 232 http://assorted.svn.sourceforge.net/assorted/?rev=232&view=rev Author: yangzhang Date: 2008-01-17 15:13:45 -0800 (Thu, 17 Jan 2008) Log Message: ----------- added persistence to disk double buffers Modified Paths: -------------- python-commons/trunk/src/commons/files.py Modified: python-commons/trunk/src/commons/files.py =================================================================== --- python-commons/trunk/src/commons/files.py 2008-01-17 23:11:45 UTC (rev 231) +++ python-commons/trunk/src/commons/files.py 2008-01-17 23:13:45 UTC (rev 232) @@ -15,6 +15,8 @@ import os, re, tempfile +from path import path + def soft_makedirs( path ): """ Emulate C{mkdir -p} (doesn't complain if it already exists). @@ -83,9 +85,14 @@ A simple disk double-buffer. One file is for reading, the other is for writing, and a facility for swapping the two roles is provided. """ - def __init__( self, path ): - self.paths = [ path + '.0', path + '.1' ] - self.w, self.r = 0, 1 + def __init__( self, path_base, do_persist = True ): + self.paths = [ path_base + '.0', path_base + '.1' ] + self.do_persist = do_persist + self.switch_status = path( path_base + '.switched' ) + if not do_persist or not self.switch_status.exists(): + self.w, self.r = 0, 1 # default + else: + self.w, self.r = 1, 0 # initialize empty reader file with file( self.paths[ self.r ], 'w' ): pass self.reload_files() @@ -93,8 +100,11 @@ self.writer = file( self.paths[ self.w ], 'w' ) self.reader = file( self.paths[ self.r ] ) def switch( self ): + self.close() + if self.do_persist: + if self.w == 0: self.switch_status.touch() + else: self.switch_status.remove() self.r, self.w = self.w, self.r - self.close() self.reload_files() def write( self, x ): self.writer.write( x ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-17 23:12:12
|
Revision: 231 http://assorted.svn.sourceforge.net/assorted/?rev=231&view=rev Author: yangzhang Date: 2008-01-17 15:11:45 -0800 (Thu, 17 Jan 2008) Log Message: ----------- added tests (barely) Added Paths: ----------- python-commons/trunk/src/test/ python-commons/trunk/src/test/startup/ python-commons/trunk/src/test/startup/main.py python-commons/trunk/src/test/startup/real_main.py Added: python-commons/trunk/src/test/startup/main.py =================================================================== --- python-commons/trunk/src/test/startup/main.py (rev 0) +++ python-commons/trunk/src/test/startup/main.py 2008-01-17 23:11:45 UTC (rev 231) @@ -0,0 +1,3 @@ +from commons.startup import run_main +def main( argv ): print 'should not see this' +run_main() Added: python-commons/trunk/src/test/startup/real_main.py =================================================================== --- python-commons/trunk/src/test/startup/real_main.py (rev 0) +++ python-commons/trunk/src/test/startup/real_main.py 2008-01-17 23:11:45 UTC (rev 231) @@ -0,0 +1,2 @@ +import main +print 'hello world' This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-14 04:01:40
|
Revision: 230 http://assorted.svn.sourceforge.net/assorted/?rev=230&view=rev Author: yangzhang Date: 2008-01-13 20:01:39 -0800 (Sun, 13 Jan 2008) Log Message: ----------- Added Paths: ----------- sandbox/trunk/src/java/AnonClassFields.java sandbox/trunk/src/java/MinaUdpExample.java Added: sandbox/trunk/src/java/AnonClassFields.java =================================================================== --- sandbox/trunk/src/java/AnonClassFields.java (rev 0) +++ sandbox/trunk/src/java/AnonClassFields.java 2008-01-14 04:01:39 UTC (rev 230) @@ -0,0 +1,16 @@ +/** + * Demonstrates that we can use fields, but public fields won't do us much good + * since the static type containing such a public field doesn't exist. + */ +public class AnonClassFields { + public static void main(String[] args) { + Runnable r = new Runnable() { + private int x; + public int y; + public void run() { + System.out.println(x); + } + }.run(); + } +} +// vim:et:sw=2:ts=2 Added: sandbox/trunk/src/java/MinaUdpExample.java =================================================================== --- sandbox/trunk/src/java/MinaUdpExample.java (rev 0) +++ sandbox/trunk/src/java/MinaUdpExample.java 2008-01-14 04:01:39 UTC (rev 230) @@ -0,0 +1,61 @@ +import java.net.InetSocketAddress; +import java.util.ArrayList; + +import org.apache.mina.common.IdleStatus; +import org.apache.mina.common.IoHandlerAdapter; +import org.apache.mina.common.IoServiceConfig; +import org.apache.mina.common.IoSession; +import org.apache.mina.filter.LoggingFilter; +import org.apache.mina.filter.codec.ProtocolCodecFilter; +import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; +import org.apache.mina.transport.socket.nio.DatagramAcceptor; +import org.apache.mina.transport.socket.nio.DatagramAcceptorConfig; +import org.apache.mina.transport.socket.nio.DatagramConnector; + +public class MinaUdpExample { + + private static final int PORT = 9123; + + public static void main(String[] args) throws Exception { + final IoServiceConfig cfg = new DatagramAcceptorConfig(); + cfg.getFilterChain().addLast("logger", new LoggingFilter()); + cfg.getFilterChain().addLast("codec", + new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); + + new DatagramAcceptor().bind(new InetSocketAddress(PORT), + new TimeServerHandler(), cfg); + System.out.println("server started"); + + new DatagramConnector().connect( + new InetSocketAddress("localhost", PORT), + new TimeClientHandler(), cfg); + System.out.println("client started"); + } + + public static class TimeClientHandler extends IoHandlerAdapter { + @Override + public void sessionCreated(IoSession session) throws Exception { + session.write(new ArrayList<String>()); + } + } + + public static class TimeServerHandler extends IoHandlerAdapter { + public void exceptionCaught(IoSession session, Throwable t) + throws Exception { + t.printStackTrace(); + session.close(); + } + + @Override + public void messageReceived(IoSession session, Object msg) + throws Exception { + System.out.println("server got " + msg); + } + + @Override + public void sessionCreated(IoSession session) throws Exception { + System.out.println("server session created"); + session.setIdleTime(IdleStatus.BOTH_IDLE, 10); + } + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-13 02:30:19
|
Revision: 229 http://assorted.svn.sourceforge.net/assorted/?rev=229&view=rev Author: yangzhang Date: 2008-01-12 18:30:22 -0800 (Sat, 12 Jan 2008) Log Message: ----------- added wall_clock Modified Paths: -------------- python-commons/trunk/src/commons/misc.py Modified: python-commons/trunk/src/commons/misc.py =================================================================== --- python-commons/trunk/src/commons/misc.py 2008-01-13 02:30:11 UTC (rev 228) +++ python-commons/trunk/src/commons/misc.py 2008-01-13 02:30:22 UTC (rev 229) @@ -1,6 +1,9 @@ # -*- mode: python; tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4; -*- # vim:ft=python:et:sw=4:ts=4 +from contextlib import * +from time import * + """ Miscellanea. """ @@ -21,3 +24,25 @@ for i in xrange( count ): yield j j <<= 1 + +@contextmanager +def wall_clock(output): + """ + A simple timer for code sections. + + @param output: The resulting time is put into index 0 of L{output}. + @type output: index-writeable + + Example: + + t = [0] + with wall_clock(t): + sleep(1) + print "the sleep operation took %d seconds" % t[0] + """ + start = time() + try: + yield + finally: + end = time() + output[0] = end - start This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <yan...@us...> - 2008-01-13 02:30:18
|
Revision: 228 http://assorted.svn.sourceforge.net/assorted/?rev=228&view=rev Author: yangzhang Date: 2008-01-12 18:30:11 -0800 (Sat, 12 Jan 2008) Log Message: ----------- added disk double buffer Modified Paths: -------------- python-commons/trunk/src/commons/files.py Modified: python-commons/trunk/src/commons/files.py =================================================================== --- python-commons/trunk/src/commons/files.py 2008-01-13 02:29:58 UTC (rev 227) +++ python-commons/trunk/src/commons/files.py 2008-01-13 02:30:11 UTC (rev 228) @@ -11,6 +11,8 @@ from L{invalid_filename_chars}. """ +from __future__ import with_statement + import os, re, tempfile def soft_makedirs( path ): @@ -76,3 +78,28 @@ pattern = invalid_filename_chars_regex return re.sub( pattern, '_', filename ) +class disk_double_buffer( object ): + """ + A simple disk double-buffer. One file is for reading, the other is for + writing, and a facility for swapping the two roles is provided. + """ + def __init__( self, path ): + self.paths = [ path + '.0', path + '.1' ] + self.w, self.r = 0, 1 + # initialize empty reader file + with file( self.paths[ self.r ], 'w' ): pass + self.reload_files() + def reload_files( self ): + self.writer = file( self.paths[ self.w ], 'w' ) + self.reader = file( self.paths[ self.r ] ) + def switch( self ): + self.r, self.w = self.w, self.r + self.close() + self.reload_files() + def write( self, x ): + self.writer.write( x ) + def read( self, len = 8192 ): + return self.reader.read( len ) + def close( self ): + self.reader.close() + self.writer.close() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |