Tuesday, October 13, 2009
elb-create-lb
Friday, September 18, 2009
windows batch file to convert videos to mp3
@echo off
setlocal
set filename=%~n1
set filepath=%~df1
set dirname=%~dp1
set dumpfile=%dirname%\audiodump.wav
set outfile=%dirname%\%filename%.mp3
mplayer -ao pcm:fast -af volnorm -vo null -vc null "%filepath%" -dumpfile "%dumpfile%"
lame -h "%dumpfile%" -o "%outfile%"
del "%dumpfile%"
pause
endlocal
and drag and drop the movie to the batch file
Saturday, August 22, 2009
clojure tab completion on windows
windows sucks because it does.
so, clji.bat:
@echo off
setlocal
set CLOJURE_HOME=%~dp0\clojure
set CLASS_PATH=%CLOJURE_HOME%\jline-0.9.94.jar;%CLOJURE_HOME%\clojure.jar;%CLOJURE_HOME%\clojure-contrib.jar
java -Djline.words="%CLOJURE_HOME%\all_names.txt" -cp "%CLASS_PATH%" jline.ConsoleRunner clojure.main %*
endlocal
clj.bat:
@echo off
setlocal
set CLOJURE_HOME=%~dp0\clojure
set CLASS_PATH=%CLOJURE_HOME%\jline-0.9.94.jar;%CLOJURE_HOME%\clojure.jar;%CLOJURE_HOME%\clojure-contrib.jar
IF (%1)==() (
java -Djline.words="%CLOJURE_HOME%\all_names.txt" -cp "%CLASS_PATH%" jline.ConsoleRunner clojure.main
) ELSE (
java -Djline.words="%CLOJURE_HOME%\all_names.txt" -cp "%CLASS_PATH%" clojure.main %1 -- %*
)
endlocal
clji.bat always starts repl. clj.bat starts repl when no argument is passed. otherwise, it runs the first argument (should be .clj script).
it expects there's clojure/
directory at the same level of the batch files.
the directory should have some jar files (clojure.jar, clojure-contrib.jar, jline..)
and also clojure/
contains allnames.txt that is generated by allnames.clj:
(def all-names (concat (map (fn [p] (keys (ns-publics (find-ns p))))
'(clojure.core clojure.set clojure.xml clojure.zip))))
(println (apply str
(interleave (reduce concat all-names)
(repeat "\n"))))
to run it:
$ clj all_names.clj > all_names.txt
now, modified ConsoleRunner.java (from http://jline.sf.net) that'll actually use all_names.txt:
/*
* Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*/
package jline;
import java.io.*;
import java.util.*;
/**
* <p>
* A pass-through application that sets the system input stream to a
* {@link ConsoleReader} and invokes the specified main method.
* </p>
* @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a>
*/
public class ConsoleRunner {
public static final String HISTORY = "jline.history";
public static final String WORDS = "jline.words";
public static String[] getWords(String wordsFile) {
List result = new ArrayList();
try {
BufferedReader input = new BufferedReader(
new FileReader(wordsFile)
);
try {
String line = null;
while (null != (line = input.readLine())) {
result.add(line);
}
} finally {
input.close();
}
} catch (FileNotFoundException err) {
err.printStackTrace();
} catch (IOException err) {
err.printStackTrace();
}
String[] array = new String[result.size()];
result.toArray(array);
return array;
}
public static void main(final String[] args) throws Exception {
String historyFileName = null;
List argList = new ArrayList(Arrays.asList(args));
if (argList.size() == 0) {
usage();
return;
}
historyFileName = System.getProperty(ConsoleRunner.HISTORY, null);
// invoke the main() method
String mainClass = (String) argList.remove(0);
// setup the inpout stream
ConsoleReader reader = new ConsoleReader();
if (historyFileName != null) {
reader.setHistory(new History (new File
(System.getProperty("user.home"),
".jline-" + mainClass
+ "." + historyFileName + ".history")));
} else {
reader.setHistory(new History(new File
(System.getProperty("user.home"),
".jline-" + mainClass + ".history")));
}
String wordsFileName = System.getProperty(WORDS, null);
if (null != wordsFileName) {
//List list = new ArrayList();
//list.add(new SimpleCompletor(getWords(wordsFileName)));
//list.add(new FileNameCompletor());
//list.add(new NullCompletor());
Completor completor =
new MultiCompletor(new Completor[] {
new SimpleCompletor(getWords(wordsFileName))
, new FileNameCompletor()
});
reader.addCompletor(
new ArgumentCompletor(new Completor[] {
completor
, completor
}, new SExpr())
);
} else {
}
String completors = System.getProperty
(ConsoleRunner.class.getName() + ".completors", "");
List completorList = new ArrayList();
for (StringTokenizer tok = new StringTokenizer(completors, ",");
tok.hasMoreTokens();) {
completorList.add
((Completor) Class.forName(tok.nextToken()).newInstance());
}
if (completorList.size() > 0) {
reader.addCompletor(new ArgumentCompletor(completorList));
}
//reader.setCompletionHandler(new CandidateListCompletionHandler());
ConsoleReaderInputStream.setIn(reader);
try {
Class.forName(mainClass).
getMethod("main", new Class[] { String[].class }).
invoke(null, new Object[] { argList.toArray(new String[0]) });
} finally {
// just in case this main method is called from another program
ConsoleReaderInputStream.restoreIn();
}
}
private static void usage() {
System.out.println("Usage: \n java " + "[-Djline.history='name'] "
+ "[-Djline.words=<path to words file for autocompletion>] "
+ ConsoleRunner.class.getName()
+ " <target class name> [args]"
+ "\n\nThe -Djline.history option will avoid history"
+ "\nmangling when running ConsoleRunner on the same application."
+ "\n\nargs will be passed directly to the target class name.");
}
}
class SExpr
extends ArgumentCompletor.AbstractArgumentDelimiter {
public boolean isDelimiterChar(String buffer, int pos) {
String c = buffer.substring(pos, pos+1);
return c.matches("[^\\w-*<>=?]");
}
}
if -Djline.words=path/to/file/that/has/word/list
is passed, it'll use that
file to do tab completion.
it's quick and dirty. i don't get how jline works.
somehow, i had to pass completor (new MultiCompletor(...)) twice to ArgumentCompletor so that
tab completion works into middle of line.
Also, SExpr is argument delimiter that considers things other than [\w-*<>=?]
a delimiter.
so, run mvn package to build jline jar. then put jline jar file under clojure/
.
then clj.bat and clji.bat would work.
i always spend time to set up development environment then lose interest :P
Saturday, May 30, 2009
edl2srt.py
tried make subtitle using mplayer. thankfully, mplayer has -edlfile option. so, using that, I can cue when subtitle should change.
given the following:
subtitle.txt
hello!
how are you?
bye
I can play mplayer -edlfile subtitle.edl movie.avi
. and as I play the movie, I press i to cue for new subtitle text from subtitle.txt. Then,
python edl2srt.py subtitle.edl -t subtitle.txt > movie.srt
mplayer movie.avi -sub movie.srt
will play movie.avi with subtitle.
You can get comma separated cue seconds (seconds when i was pressed):
python edl2srt.py subtitle.edl
EDL to srt script is here: It needs optfunc module.
#!/usr/bin/python
# LICENSE: public domain.
"""converts edl file to srt.
EDL (Edit Decision List) file: http://www.mplayerhq.hu/DOCS/HTML/en/edl.html
SRT file: http://forum.doom9.org/archive/index.php/t-73953.html
requires optfunc found at: http://github.com/simonw/optfunc/tree/master"""
def split_float(f):
i = int(f)
return i, f - i
def split_float_str(fstr):
l = fstr.split('.')
return l[0], l[1]
def sec_to_hour_min_sec(seconds):
m,sec = divmod(seconds, 60)
hour,min = divmod(m, 60)
return (hour,min,sec)
def timestamp(seconds):
f = float(seconds)
i,frac = split_float(f)
hour,min,sec = sec_to_hour_min_sec(i)
return (hour, min, sec, int(frac*100))
def to_timestamp(seconds, format="%(hour)s:%(min)s:%(sec)s,%(millisec)s"):
hour,min,sec,millisec = timestamp(seconds)
return format % {"hour":hour, "min":min, "sec":sec, "millisec":millisec}
class ED(object):
"edit decision"
def __init__(self, sec_from=0.0, sec_to=0.0, flag=0):
self.sec_from = float(sec_from)
self.sec_to = float(sec_to)
self.flag = int(flag)
def to_tuple(self):
return (self.sec_from, self.sec_to, self.flag)
def to_pair(self):
return (self.sec_from, self.sec_to)
class EDL(object):
def __init__(self, filename=None):
self.edl = self.read_edl(filename) if filename else []
def read_edl(self, filename):
f = open(filename, "r")
l = []
for line in f:
x = line.split()
l.append(ED(x[0], x[1], x[2]))
return l
def seconds(self):
l = []
for ed in self.edl:
l.extend([ed.sec_from, ed.sec_to])
return l
def second_pairs(self):
l = []
for x in self.edl:
l.append(x.to_pair())
return l
class Text(object):
def __init__(self, filename=None):
self.text = self.read_text(filename) if filename else []
def __len__(self):
return len(self.text)
def __getitem__(self, key):
return self.text[key]
def __str__(self):
return '\n'.join(self.text)
def read_text(self, filename):
f = open(filename, "r")
l = []
for line in f:
x = line.strip()
if x:
l.append(x)
f.close()
return l
class Subtitle(object):
def __init__(self, index=0, time_from=0, time_to=0, text=""):
self.index = index
self.time_from = to_timestamp(time_from)
self.time_to = to_timestamp(time_to)
self.text = text
def __str__(self):
return """%u
%s --> %s
%s""" % (self.index, self.time_from, self.time_to, self.text)
def insert_end(seconds, limit=3.0, gap=0.001):
def delta(x,y):
d = y - x
return limit if d > limit else d
return [(x, x + delta(x,y) - gap) for x,y in zip(seconds, seconds[1:])]
def make_srt(edl, text):
index = 1
sec_pairs = insert_end(edl.seconds())
srt = []
for i,(sec_from,sec_to) in enumerate(sec_pairs):
t = text[i] if len(text) > i else None
srt.append(Subtitle(i+1, sec_from, sec_to, t))
return srt
def edl2srt(edlname, txtname=None):
"""Usage: %prog edlfile [-t textfile]
edlfile specification is at:
http://www.mplayerhq.hu/DOCS/HTML/en/edl.html
textfile should contain subtitles delimited by new line.
Example
mplayer a.avi -edlfile a.edl
during movie play, press i to insert a cue to change subtitle
defined in a.txt
%prog a.edl -t a.txt > a.srt
mplayer a.avi -sub a.srt"""
edl = EDL(edlname)
if txtname is None:
print(','.join([str(x) for x in edl.seconds()]))
else:
txt = Text(txtname)
print '\n\n'.join([str(x) for x in make_srt(edl, txt)])
if __name__ == "__main__":
import optfunc
optfunc.run(edl2srt)
tried make subtitle using mplayer.
thankfully, mplayer has -edlfile option.
so, using that, I can cue when subtitle should change.
given the following:
subtitle.txt
hello!
how are you?
bye
I can play `mplayer -edlfile subtitle.edl movie.avi` . and as I play the movie,
I press **i** to cue for new subtitle text from subtitle.txt.
Then,
python edl2srt.py subtitle.edl -t subtitle.txt > movie.srt
mplayer movie.avi -sub movie.srt
will play movie.avi with subtitle.
You can get comma separated cue seconds (seconds when **i** was pressed):
python edl2srt.py subtitle.edl
EDL to srt script is here:
It needs optfunc module.
#!/usr/bin/python
# LICENSE: public domain.
"""converts edl file to srt.
EDL (Edit Decision List) file: http://www.mplayerhq.hu/DOCS/HTML/en/edl.html
SRT file: http://forum.doom9.org/archive/index.php/t-73953.html
requires optfunc found at: http://github.com/simonw/optfunc/tree/master"""
def split_float(f):
i = int(f)
return i, f - i
def split_float_str(fstr):
l = fstr.split('.')
return l[0], l[1]
def sec_to_hour_min_sec(seconds):
m,sec = divmod(seconds, 60)
hour,min = divmod(m, 60)
return (hour,min,sec)
def timestamp(seconds):
f = float(seconds)
i,frac = split_float(f)
hour,min,sec = sec_to_hour_min_sec(i)
return (hour, min, sec, int(frac*100))
def to_timestamp(seconds, format="%(hour)s:%(min)s:%(sec)s,%(millisec)s"):
hour,min,sec,millisec = timestamp(seconds)
return format % {"hour":hour, "min":min, "sec":sec, "millisec":millisec}
class ED(object):
"edit decision"
def __init__(self, sec_from=0.0, sec_to=0.0, flag=0):
self.sec_from = float(sec_from)
self.sec_to = float(sec_to)
self.flag = int(flag)
def to_tuple(self):
return (self.sec_from, self.sec_to, self.flag)
def to_pair(self):
return (self.sec_from, self.sec_to)
class EDL(object):
def __init__(self, filename=None):
self.edl = self.read_edl(filename) if filename else []
def read_edl(self, filename):
f = open(filename, "r")
l = []
for line in f:
x = line.split()
l.append(ED(x[0], x[1], x[2]))
return l
def seconds(self):
l = []
for ed in self.edl:
l.extend([ed.sec_from, ed.sec_to])
return l
def second_pairs(self):
l = []
for x in self.edl:
l.append(x.to_pair())
return l
class Text(object):
def __init__(self, filename=None):
self.text = self.read_text(filename) if filename else []
def __len__(self):
return len(self.text)
def __getitem__(self, key):
return self.text[key]
def __str__(self):
return '\n'.join(self.text)
def read_text(self, filename):
f = open(filename, "r")
l = []
for line in f:
x = line.strip()
if x:
l.append(x)
f.close()
return l
class Subtitle(object):
def __init__(self, index=0, time_from=0, time_to=0, text=""):
self.index = index
self.time_from = to_timestamp(time_from)
self.time_to = to_timestamp(time_to)
self.text = text
def __str__(self):
return """%u
%s --> %s
%s""" % (self.index, self.time_from, self.time_to, self.text)
def insert_end(seconds, limit=3.0, gap=0.001):
def delta(x,y):
d = y - x
return limit if d > limit else d
return [(x, x + delta(x,y) - gap) for x,y in zip(seconds, seconds[1:])]
def make_srt(edl, text):
index = 1
sec_pairs = insert_end(edl.seconds())
srt = []
for i,(sec_from,sec_to) in enumerate(sec_pairs):
t = text[i] if len(text) > i else None
srt.append(Subtitle(i+1, sec_from, sec_to, t))
return srt
def edl2srt(edlname, txtname=None):
"""Usage: %prog edlfile [-t textfile]
edlfile specification is at:
http://www.mplayerhq.hu/DOCS/HTML/en/edl.html
textfile should contain subtitles delimited by new line.
Example
mplayer a.avi -edlfile a.edl
during movie play, press i to insert a cue to change subtitle
defined in a.txt
%prog a.edl -t a.txt > a.srt
mplayer a.avi -sub a.srt"""
edl = EDL(edlname)
if txtname is None:
print(','.join([str(x) for x in edl.seconds()]))
else:
txt = Text(txtname)
print '\n\n'.join([str(x) for x in make_srt(edl, txt)])
if __name__ == "__main__":
import optfunc
optfunc.run(edl2srt)
Wednesday, May 6, 2009
fundep
FunctionalDependencies example:
> {-# LANGUAGE GeneralizedNewtypeDeriving
> , FunctionalDependencies
> , MultiParamTypeClasses #-}
> module Test where
> import Control.Monad.State
> import Control.Monad.Identity
> class (Monad m) => MonadFoo a m | m -> a where
> -- class (Monad m) => MonadFoo a m where
> -- save :: m [a]
> save :: m ()
save has type (MonadFoo a m) => m () . And, although Foo (see below) is an instance of MonadFoo Char, GHC complains that there is No instance for (MonadFoo a Foo) arising from a use of 'save', if functional dependencies isn't used (see commented out code above).
One way to get around is to make save :: m [a] and explicitly annotate each usage of save with :: Foo String (see commented out code of action).
But, using functional dependencies, one can say that m uniquely identifies a. So, GHC will instantiate a with Char on Foo's save, since Foo is an instance of MonadFoo Char.
> restore :: m [a]
> push :: a -> m ()
> newtype FooT m a = FooT {
> runFooT :: (StateT (String, Int) m) a
> } deriving (Monad, Functor, MonadState (String, Int))
> instance (Monad m) => MonadFoo Char (FooT m) where
> save = do
> (current, _) <- get
> put (current, 0)
> -- return current
> restore = do
> (current, n) <- get
> put (drop n current, 0)
> return $ take n current
> push x = do
> (current, n) <- get
> put (x : current, n + 1)
> newtype Foo a = Foo {
> runFoo :: FooT Identity a
> } deriving (Monad, Functor
> , MonadState (String, Int), MonadFoo Char)
> action :: Foo String
> action = do
> push 'a'
> save
> -- save :: Foo String
> push 'b'
> push 'c'
> restore
> test = runIdentity $ runStateT (runFooT (runFoo action)) ("", 0)
FunctionalDependencies example:
> {-# LANGUAGE GeneralizedNewtypeDeriving
> , FunctionalDependencies
> , MultiParamTypeClasses #-}
> module Test where
> import Control.Monad.State
> import Control.Monad.Identity
> class (Monad m) => MonadFoo a m | m -> a where
> -- class (Monad m) => MonadFoo a m where
> -- save :: m [a]
> save :: m ()
save has type (MonadFoo a m) => m () .
And, although Foo (see below) is an instance of MonadFoo Char,
GHC complains that there is No instance for (MonadFoo a Foo)
arising from a use of 'save', if functional dependencies isn't used
(see commented out code above).
One way to get around is to make save :: m [a] and explicitly annotate
each usage of save with :: Foo String (see commented out code of action).
But, using functional dependencies, one can say that m uniquely identifies a.
So, GHC will instantiate a with Char on Foo's save,
since Foo is an instance of MonadFoo Char.
> restore :: m [a]
> push :: a -> m ()
> newtype FooT m a = FooT {
> runFooT :: (StateT (String, Int) m) a
> } deriving (Monad, Functor, MonadState (String, Int))
> instance (Monad m) => MonadFoo Char (FooT m) where
> save = do
> (current, _) <- get
> put (current, 0)
> -- return current
> restore = do
> (current, n) <- get
> put (drop n current, 0)
> return $ take n current
> push x = do
> (current, n) <- get
> put (x : current, n + 1)
> newtype Foo a = Foo {
> runFoo :: FooT Identity a
> } deriving (Monad, Functor
> , MonadState (String, Int), MonadFoo Char)
> action :: Foo String
> action = do
> push 'a'
> save
> -- save :: Foo String
> push 'b'
> push 'c'
> restore
> test = runIdentity $ runStateT (runFooT (runFoo action)) ("", 0)
Friday, April 17, 2009
/*
: doub dup + ;
: quad doub doub ;
: swap ( a b -- b a ) ;
: dup ( a -- a a ) ;
: pop ( a -- ) ;
: + ( int int -- int ) ;
int doub(int a)
{
return a + a;
}
int quad(int a)
{
return doub(doub(a));
}
*/
#include <iostream>
#include <vector>
#include <string>
struct Object
{
};
typedef Object* ObjectPtr;
struct Int : public Object
{
int val;
};
typedef Int* IntPtr;
#define DEREF_Int(x) (*static_cast<IntPtr>(x))
std::ostream& operator<<(std::ostream& os, Int const& i)
{
os<<i.val;
return os;
}
struct String : public Object
{
std::string val;
};
typedef String* StringPtr;
#define DEREF_String(x) (*static_cast<StringPtr>(x))
std::ostream& operator<<(std::ostream& os, String const& i)
{
os<<i.val;
return os;
}
int main()
{
std::vector<ObjectPtr> vec;
Int i;
i.val = 42;
vec.push_back(&i);
String s;
s.val = "hello world!";
vec.push_back(&s);
std::cout<<DEREF_Int(vec[0])<<std::endl
<<DEREF_String(vec[1])<<std::endl;
return 0;
}
Tuesday, March 31, 2009
Friday, March 27, 2009
ATS WHEEEEEEEEEEE
ATS looks cool.
So... to link things that use math functions, you use -lm
.
To compile http://www.ats-lang.org/TUTORIAL/contents/basics.dats, you should do the same because it uses sqrt
math function.
atscc basics.dats -lm
And I am writing ats.vim
" Vim syntax file
" Language: ats
if version < 600
syntax clear
elseif exists("b:current_syntax")
finish
endif
:runtime! syntax/c.vim
:unlet b:current_syntax
syn case match
" Keywords
syn keyword atsKeyword implement begin end staload
syn keyword atsKeyword prefix postfix infix infixl infixr op nonfix
syn keyword atsKeyword val and fun fn lam fix rec
syn keyword atsKeyword if then else let in where
syn keyword atsKeyword symintr overload with
syn keyword atsKeyword typedef datatype sortdef
syn keyword atsKeyword case of
syn keyword atsSorts bool char int prop type view viewtype
syn keyword atsTypes string float double
" Comments
syn match atsLineComment /\/\/.*$/
syn region atsFileComment start=/\/\/\/\// end=/\%$/
syn region atsMLComment start=/(\*/ end=/\*)/ contains=atsMLComment
syn region atsCComment start=/\/\*/ end=/\*\//
" Literals
syn keyword atsBoolean true false
if version >= 508 || !exists("did_c_syn_inits")
if version < 508
let did_c_syn_inits = 1
command -nargs=+ HiLink hi link <args>
else
command -nargs=+ HiLink hi def link <args>
endif
HiLink atsLineComment Comment
HiLink atsFileComment Comment
HiLink atsMLComment Comment
HiLink atsCComment Comment
HiLink atsKeyword Keyword
HiLink atsSorts Type
HiLink atsTypes Type
delcommand HiLink
endif
let b:current_syntax = "ats"
Things to look at:
- http://github.com/doublec/cf/tree/master
- above is from this
- http://www.call-with-current-continuation.org/fp/
Speaking of concatenative language, I was trying to do something like this: http://www.bluishcoder.co.nz/xyjs/xylistener.html, which is from this post. Lol I just copied it over and tried to do something... http://wekeywiki.googlepages.com/ascl-listener.html. But I gave up on it.. Anyways, it's another TODO thing :(
Wednesday, December 10, 2008
v8 not build on x86_64
Stupid Google, why would your v8 not build on 64bit system?
scons mode=release library=shared prefix=/usr wordsize=64 || return 1
g++ -o obj/release/third_party/jscre/pcre_compile.os -c -march=x86-64 -mtune=generic -O2 -pipe -ansi -w -O3 -fomit-frame-pointer -m32 -fno-rtti -fno-exceptions -ansi -w -O3 -fomit-frame-pointer -m32 -fPIC -DENABLE_LOGGING_AND_PROFILING -DSUPPORT_UTF8 -DNO_RECURSE -DSUPPORT_UCP
Look at that dreadful -m32 ...
Monday, December 8, 2008
back to archlinux
so, pacman -Syu then
pacman -Sf zsh #for http://www.archlinux.org/news/421/
rm /usr/lib/klibc/include/asm #for http://www.archlinux.org/news/411/
Then,
Section "ServerFlags" Option "AllowEmptyInput" "false" EndSectionfor http://www.archlinux.org/news/424/