Archive for the Category » 程序设计 «

星期三, 04月 29th, 2009 | Author: Zealot

今天小试了一把nginx,用apt装上后开始配置,可对着中文wiki上的文档配置时总是超出预期,出现各种问题,突然想起查看一下版本,竟然是0.4,官方已经0.7了,faint

于是用apt卸掉,结果aptfaint了。。。:

$ sudo apt-get –purge remove nginx
Reading package lists… Done
Building dependency tree
Reading state information… Done
The following packages will be REMOVED:
nginx*
0 upgraded, 0 newly installed, 1 to remove and 116 not upgraded.
1 not fully installed or removed.
Need to get 0B of archives.
After unpacking 528kB disk space will be freed.
Do you want to continue [Y/n]?
(Reading database … 242827 files and directories currently installed.)
Removing nginx …
Stopping nginx: invoke-rc.d: initscript nginx, action “stop” failed.
dpkg: error processing nginx (–purge):
subprocess pre-removal script returned error exit status 1
Starting nginx: invoke-rc.d: initscript nginx, action “start” failed.
dpkg: error while cleaning up:
subprocess post-installation script returned error exit status 1
Errors were encountered while processing:
nginx

E: Sub-process /usr/bin/dpkg returned an error code (1)
上网搜了一把,好多都是说直接把相关文件删了,最后看到这个方法:“How to uninstall nginx with apt(
http://www.peterbe.com/plog/how-to-uninstall-nginx-with-apt)”,也就是在/etc/init.d/nginx 脚本的最前面加上exit 0,这样就强制return 0,解决了这个问题:E: “Sub-process /usr/bin/dpkg returned an error code (1)”

然后再apt-get –purge remove nginx,done

最后手动清了/var/lib/nginx/var/log/nginx

Category: linux, 程序设计  | Tags: , ,  | Leave a Comment
星期三, 04月 29th, 2009 | Author: Zealot

问题是在这http://lilacbbs.com/forum/d.php?bid=66&id=62395,想了半天想不明白

摘要就是 Fred z = Fred(3);时没有执行拷贝构造函数,查了标准手册才发现原来如此:会不会调用拷贝构造函数由具体编译器实现决定:

Standard C++98 12.8

15 Whenever a temporary class object is copied using a copy constructor, and this object and the copy have the

same cvunqualified

type, an implementation is permitted to treat the original and the copy as two different

ways of referring to the same object and not perform a copy at all, even if the class copy constructor or

destructor have side effects. For a function with a class return type, if the expression in the return statement

is the name of a local object, and the cvunqualified

type of the local object is the same as the function

return type, an implementation is permitted to omit creating the temporary object to hold the function return

value, even if the class copy constructor or destructor has side effects. In these cases, the object is

destroyed at the later of times when the original and the copy would have been destroyed without the optimization.

111) [Example:

class Thing {

public:

Thing();

~Thing();

Thing(const Thing&);

Thing operator=(const Thing&);

void fun();

};

Thing f() {

Thing t;

return t;

}

Thing t2 = f();

Here t does not need to be copied when returning from f. The return value of f may be constructed

directly into the object t2. ]

Category: C/C++, 程序设计  | Tags: , ,  | Leave a Comment
星期二, 04月 28th, 2009 | Author: Zealot

今天apt-get install vim-full的时候,出现了错误,详见后面。原因不清楚,估计是sun-java5-jre这个包相关的东西出了问题,彻底清除了试试:sudo apt-get –purge remove sun-java5-jre,然后重新装上。。
再来sudo apt-get install vim-full,OK。

Reading package lists…
Building dependency tree…
You might want to run `apt-get -f install’ to correct these:
The following packages have unmet dependencies:
sun-java5-jre: Depends: sun-java5-bin (= 1.5.0-14-1etch1) but it is not going to be installed or
ia32-sun-java5-bin (= 1.5.0-14-1etch1) but it is not installable
vim-full: Depends: vim-gui-common (= 1:7.0-122+1etch5) but it is not going to be installed
Depends: vim-common (= 1:7.0-122+1etch5) but 1:7.0-122+1etch3 is to be installed
Depends: vim-runtime (= 1:7.0-122+1etch5) but 1:7.0-122+1etch3 is to be installed
Depends: libart-2.0-2 (>= 2.3.16) but it is not going to be installed
Depends: libatk1.0-0 (>= 1.12.2) but it is not going to be installed
Depends: libbonobo2-0 (>= 2.13.0) but it is not going to be installed
Depends: libbonoboui2-0 (>= 2.5.4) but it is not going to be installed
Depends: libcairo2 (>= 1.2.4) but it is not going to be installed
Depends: libgconf2-4 (>= 2.13.5) but it is not going to be installed
Depends: libglib2.0-0 (>= 2.12.0) but it is not going to be installed
Depends: libgnome-keyring0 (>= 0.6.0) but it is not going to be installed
Depends: libgnome2-0 (>= 2.14.1) but it is not going to be installed
Depends: libgnomecanvas2-0 (>= 2.11.1) but it is not going to be installed
Depends: libgnomeui-0 (>= 2.13.0) but it is not going to be installed
Depends: libgnomevfs2-0 (>= 2.13.92) but it is not going to be installed
Depends: libgtk2.0-0 (>= 2.8.0) but it is not going to be installed
Depends: liborbit2 (>= 1:2.14.1) but it is not going to be installed
Depends: libpango1.0-0 (>= 1.14.8) but it is not going to be installed
Depends: libperl5.8 (>= 5.8.8) but it is not going to be installed
Depends: libruby1.8 (>= 1.8.5) but it is not going to be installed
Depends: libxcursor1 (> 1.1.2) but it is not going to be installed
Depends: libxfixes3 (>= 1:4.0.1) but it is not going to be installed
Depends: libxi6 but it is not going to be installed
Depends: libxinerama1 but it is not going to be installed
Depends: libxrandr2 but it is not going to be installed
Depends: libxrender1 but it is not going to be installed
Depends: tcl8.4 (>= 8.4.5) but it is not going to be installed

星期日, 04月 26th, 2009 | Author: Zealot

前不久需要解析一个json的接口,上json官网(http://www.json.org/json-zh.html)上找找C++parser。结果发现长长的list,支持各种语言的各种版本。上第一个官网看看(http://blog.beef.de/projects/tinyjson/),对tiny**的东西还是比较感兴趣的,比如tinyxml。。。

果然够tiny,下载下来一看发现只有一个.hpp文件就行了。接下来就开始ft了,按照官网上的sample调用了一下,编译都不过:

../include/tinyjson/tinyjson.hpp: In function ‘typename json::grammar<typename Iterator::value_type>::variant json::parse(const Iterator&, const Iterator&)’:

../include/tinyjson/tinyjson.hpp:549: error: expected `;’ before ’st’

../include/tinyjson/tinyjson.hpp:550: error: ’st’ was not declared in this scope

../include/tinyjson/tinyjson.hpp: In function ‘typename json::grammar<typename Iterator::value_type>::variant json::parse(const Iterator&, const Iterator&) [with Iterator = __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >]‘:

test.cpp:45: instantiated from here

../include/tinyjson/tinyjson.hpp:549: error: dependent-name ‘json::grammar<typename Iterator::value_type>::stack’ is parsed as a non-type, but instantiation yields a type

../include/tinyjson/tinyjson.hpp:549: note: say ‘typename json::grammar<typename Iterator::value_type>::stack’ if a type is meant

……

google了一下,相关资料真少,难道用c++解析json很发指么,最后硬着头皮在这个日文的bloghttp://d.hatena.ne.jp/S_Nakayama/20081207/1228592806)上找到了答案。修改记录如下:

549c549

< json::grammar< typename Iterator::value_type >::stack st;

> typename json::grammar< typename Iterator::value_type >::stack st;

565c565

< return json::grammar< typename Iterator::value_type >::variant(new boost::any());

> return typename json::grammar< typename Iterator::value_type >::variant(new boost::any());

相应的加上typename就行了。

最后,还想说一句,tinyjson官网的sample里遍历的方法也没编译过,最后改了一下遍历函数的参数,函数原型是void Traverse(json::grammar<char>::variant const v, const string& name, int level)。name表示上级节点名称,level表示当前内容的深度。虽然看着还是不爽,但好歹能工作了。

Category: C/C++, 程序设计  | Tags: , , , ,  | Leave a Comment
星期四, 10月 30th, 2008 | Author: Zealot

From : http://www.fire3.cn/2008/08/03/linux-howto-read-man-page.html

 
 

搜索和打印介绍不错:)

 
 

1 什么是man手册

 
 

首先,man是manual的简称,中文说法可以是手册。

 
 

在Linux世界中,许多新手请教某条命令的用法时, 好多不耐心的老手通常会用一条命令来回答这位无助的新手,而这条命令通常

就是man开头。无助的新手敲上这条命令一看究竟,在终端上顿时显示出来了一屏幕的英文,

老手的意思是,自己看看手册吗,可是看手册也是有学问的,无助的新手甚

至不知道怎么退出这条命令呢。下面我们就来讲解一下看man手册的学问。

2 从man手册中获取有用的信息

 
 

我们先以mkdir命令来解释读man手册的一些入门知识。

 
 

MKDIR(1) User Commands MKDIR(1)

 
 

NAME

mkdir – make directories

 
 

SYNOPSIS

mkdir [OPTION] DIRECTORY…

 
 

DESCRIPTION

Create the DIRECTORY(ies), if they do not already exist.

 
 

Mandatory arguments to long options are mandatory for short options too.

 
 

-m, –mode=MODE

set file mode (as in chmod), not a=rwx – umask

 
 

-p, –parents

no error if existing, make parent directories as needed

 
 

-v, –verbose

print a message for each created directory

 
 

-Z, –context=CTX

set the SELinux security context of each created directory to CTX

 
 

–help display this help and exit

 
 

–version

output version information and exit

 
 

AUTHOR

Written by David MacKenzie.

 
 

REPORTING BUGS

Report bugs to <bug-coreutils@gnu.org>.

 
 

COPYRIGHT

Copyright (C) 2008 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

 
 

This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.

 
 

SEE ALSO

 
 

mkdir(2)

 
 

The full documentation for mkdir is maintained as a Texinfo manual. If the info and mkdir programs are properly installed at your site, the com-

 
 

mand

 
 

info coreutils ‘mkdir invocation’

 
 

should give you access to the complete manual.

 
 

首先第一行 MKDIR(1),显然,MKDIR是命令的大写,那么为什么有个(1)呢,那是因为man手册页有如下的规定:

Section         名称         说明

l         本地文档         与本特定系统有关的

1         用户命令         可由任何人启动的

2         系统调用         即由内核提供的函数

3         例程         即库函数

4         设备         即/dev目录下的特殊文件

5         文件格式描述         例如/etc/passwd

6         游戏         不用解释啦

7         杂项         例如宏命令包、惯例等

8         系统管理员工具         只能由root启动

9         其他(Linux特定的)         用来存放内核例行程序的文档

n         新文档         可能要移到更适合的领域

o         老文档         可能会在一段期限内保留

 
 

MKDIR(1)表示该命令属于Section 1,为用户命令,类似的man

apt-get会看到APT-GET(8),表示apt-get命令为系统管理工具。

 
 

“NAME”部分是该命令的名字和简单的解释,显然,在命令行中要执行该命令要使用到它的名称。

 
 

“SNOPSIS”是摘要部分,简要解释该命令如何使用,比如mkdir的摘要:

mkdir [OPTION] DIRECTORY…,读到这里便需要讲解一下了:

 
 

“OPTIONS”左右有”["和"]“,表示这些参数并不必须,但是可以使用。对应的DIRECTORY两边没有”[]“,就是必须要加的参数了。

另外,它们后面都有”…” ,表示这些参数可以重复使用多次。至于OPTIONS具体怎么用,就要看DESCRIPTION部分了。下面举几个简单的例子,并配合例子解释:

用法         解释

mkdir tmp         创建 tmp 目录

mkdir –mode=a+w tmp         创建一个模式为”a+w”的tmp目录,–mode是长参数,用法是–mode=MODE,在DESCRIPTION里说明

mkdir -m a+w tmp         创建一个模式为”a+w”的tmp目录,-m 是短参数,不用加 = 号,效果等同 –mode=MODE

mkdir -mv a+w tmp         创建一个模式为”a+w”的tmp目录,同时显示信息,verbose模式,-mv可以一起用

mkdir -v -m a+w tmp         创建一个模式为”a+w”的tmp目录,同时显示信息,verbose模式,-v后面接一个空格再用-m

3 man手册页的操作

3.1 退出man

 
 

最简单,按下”q”键

3.2 查找

 
 

如果你知道要打开的手册页,在man命令打开的手册页中可以用

“/” 键进行正则表达式的搜索。

 
 

如果不知道所要打开的手册页名称,可以用 “man

-k”命令搜索相关的手册页,比如:

 
 

man -k postscript

 
 

会给出一堆关于”postscript”的相关命令页。

3.3 打印

 
 

最简单的办法,以mkdir为例:

 
 

man -t mkdir > mkdir_man.ps

 
 

可以直接打印ps,打算发给别人打印的话,转换成pdf也比较方便:

 
 

ps2pdf mkdir_man.ps mkdir_man.pdf

Category: linux  | Tags: , , , , ,  | Leave a Comment
星期一, 10月 13th, 2008 | Author: Zealot

features of Python

From: http://stackoverflow.com/questions/101268/hidden-features-of-python

  • Chaining comparison operators:

    >>> x = 5

    >>> 1 < x < 10

    True

    >>> x < 10 < x*10 < 100

    True

    >>> 10 > x <= 9

    True

    >>> 5 == x > 4

    True

    In case you’re thinking it’s doing, ‘1 < x’, which comes out as True, and then comparing ‘True < 10′, which is also True, then no, that’s really not what happens (see the last example.) It’s really translating into ‘1 < x and x < 10′, and ‘x < 10 and 10 < x * 10 and x*10 < 100′, but with less typing and each term is only evaluated once.

  • Readable regular expressions

    In Python you can split a regular expression over multiple lines, name your matches and insert comments.

    Example verbose syntax (from Dive into Python):

    >>> pattern = “”"

        ^                   # beginning of string

        M{0,4}              # thousands – 0 to 4 M’s

        (CM|CD|D?C{0,3})    # hundreds – 900 (CM), 400 (CD), 0-300 (0 to 3 C’s),

                            #            or 500-800 (D, followed by 0 to 3 C’s)

        (XC|XL|L?X{0,3})    # tens – 90 (XC), 40 (XL), 0-30 (0 to 3 X’s),

                            #        or 50-80 (L, followed by 0 to 3 X’s)

        (IX|IV|V?I{0,3})    # ones – 9 (IX), 4 (IV), 0-3 (0 to 3 I’s),

                            #        or 5-8 (V, followed by 0 to 3 I’s)

        $                   # end of string

        “”"

    >>> re.search(pattern, ‘M’, re.VERBOSE)

    Example naming matches (from Regular Expression HOWTO)

    >>> p = re.compile(r‘(?P<word>\b\w+\b)’)

    >>> m = p.search( ‘(((( Lots of punctuation )))’ )

    >>> m.group(‘word’)

    ‘Lots’

  • Decorators

    Decorators allow to wrap a function or method in another function that can add functionality, modify arguments or results, etc. You write decorators one line above the function definition, beginning with an “at” sign (@).

    Example shows a print_args decorator that prints function’s arguments before calling it:

    >>> def print_args(function):

    >>>     def wrapper(*args, **kwargs):

    >>>         print
    ‘Arguments:’, args, kwargs

    >>>         return
    function(*args, **kwargs)

    >>>     return wrapper

     
     

    >>> @print_args

    >>> def write(text):

    >>>     print text

     
     

    >>> write(‘foo’)

    Arguments: (‘foo’,) {}

    foo

  • iter() can take a callable argument

    For instance:

    def seek_next_line(f):

        for c in iter(lambda: f.read(1),‘\n’):

            pass

    The iter(callable, until_value) calls repetitively the callable and yields its result until the callable returns _until_value_.

  • Creating generators objects

    If you write

    x=(n for n in foo if bar(n))

    you can get out the generator and assign it to x. Now it means you can do

    for n in x:

    The advantage of this is that you don’t need intermediate storage, which you would need if you did

    x = [n for n in foo if bar(n)]

    In some cases this can lead to significant speed up.

  • Futures and the “With” Statement

    There’s a special module in Python called __future__. Some new language features end up in this module for testing, and to use them you have to explicitly import them from here. One such feature which is a favorite of mine is the “with” statement, which is currently present in __future__ in version 2.5, but will be part of the language in the soon-to-be-released 2.6 and 3.0 versions.

    The reason it is in __future__ is because it makes both with and as keywords, which could break existing code.

    I have used the “with” statement in 2.5 a lot because I think it’s a very useful construct, here is a quick demo:

    from __future__ import with_statement

     
     

    with open(‘foo.txt’, ‘w’) as f:

        f.write(‘hello!’)

    What’s happening here behind the scenes, is that the “with” statement calls the special __enter__ and__exit__ methods on the file object. Exception details are also passed to __exit__ if any exception was raised from the with statement body, allowing for exception handling to happen there.

    What this does for you in this particular case is that it guarantees that the file is closed when execution falls out of scope of the “with” statement’s body, regardless if that occurs naturally or whether an exception was thrown. It is basically a way of abstracting away common error-handling code.

    Other common use cases for this include locking with threads and database transactions.

    For more information on how to use this and how to implement your own “with” statement compatible objects read PEP 343

  • The step argument in slice operators. For example:

    a = [1,2,3,4,5]

    >>> a[::2]  # iterate over the whole list in 2-increments

    [1,3,5]

    The special case x[::-1] is a useful idiom for ‘x reversed’.

    >>> a[::-1]

    [5,4,3,2,1]

  • From 2.5 onwards dicts have a special method __missing__ that is invoked for missing items:

    >>> class
    MyDict(dict):

    …  def __missing__(self, key):

    …   self[key] = rv = []

    …   return rv


    >>> m = MyDict()

    >>> m["foo"].append(1)

    >>> m["foo"].append(2)

    >>> dict(m)

    {‘foo’: [1, 2]}

    There is also a dict subclass in collections called defaultdict that does pretty much the same but calls a function without arguments for not existing items:

    >>> from collections import defaultdict

    >>> m = defaultdict(list)

    >>> m["foo"].append(1)

    >>> m["foo"].append(2)

    >>> dict(m)

    {‘foo’: [1, 2]}

    I recommend converting such dicts to regular dicts before passing them to functions that don’t expect such subclasses. A lot of code uses d[a_key] and catches KeyErrors to check if an item exists which would add a new item to the dict.

  • Doctest: documentation and unit-testing at the same time.

    Example extracted fom python documentation:

    def factorial(n):

        “”"Return the factorial of n, an exact integer >= 0.

     
     

        If the result is small enough to fit in an int, return an int.

        Else return a long.

     
     

        >>> [factorial(n) for n in range(6)]

        [1, 1, 2, 6, 24, 120]

        >>> factorial(-1)

        Traceback (most recent call last):

            …

        ValueError: n must be >= 0

     
     

        Factorials of floats are OK, but the float must be an exact integer:

        “”"

     
     

        import math

        if
    not n >= 0:

            raise
    ValueError(“n must be >= 0″)

        if math.floor(n) != n:

            raise
    ValueError(“n must be exact integer”)

        if n+1 == n:  # catch a value like 1e300

            raise
    OverflowError(“n too large”)

        result = 1

        factor = 2

        while factor <= n:

            result *= factor

            factor += 1

        return result

     
     

    def _test():

        import doctest

        doctest.testmod()    

     
     

    if __name__ == “__main__”:

        _test()

  • Descriptors

    They’re the magic behind a whole bunch of core Python features.

    When you use dotted access to look up a member (eg, x.y), Python first looks for the member in the instance dictionary. If it’s not found, it looks for it in the class dictionary. If it finds it in the class dictionary, and the object implements the descriptor protocol, instead of just returning it, Python executes it. A descriptor is any class that implements the getset, or del methods.

    Here’s how you’d implement your own (read-only) version of property using descriptors:

    class
    Property(object):

        def __init__(self, fget):

            self.fget = fget

     
     

        def __get__(self, obj, type):

            if obj is
    None:

                return
    self

            return
    self.fget(obj)

    and you’d use it just like the built-in property():

    class
    MyClass(object):

        @Property

        def foo(self):

            return
    “Foo!”

    Descriptors are used in Python to implement properties, bound methods, static methods, class methods and slots, amongst other things. Understanding them makes it easy to see why a lot of things that previously looked like Python ‘quirks’ are the way they are.

    Raymond Hettinger has an excellent tutorial that does a much better job of describing them than I do.

  • Sending values into generator functions. For example having this function:

    def mygen():

      “”"Yield 5 until something else is passed back via send()”"”

      a = 5

      while
    True:

        f = yield(a) #yield a and possibly get f in return

        if f: a = f  #store the new value

    You can:

    >>> g = mygen()

    >>> g.next()

    5

    >>> g.next()

    5

    >>> g.send(7)  #we send this back to the generator

    7

    >>> g.next() #now it will yield 7 until we send something else

    7

  • One line Variable value swapping

    >>> a = 10

    >>> b = 5

    >>> a, b = b, a

     
     

    >>> print a

    5

    >>> print b

    10

    a will have the value of b and so on.

    This is a side effect of python packing and unpacking feature.

  • enumerate

    Wrap an iterable with enumerate and it will yield the item along with it’s index.

    For example:

    >>> a = ['a', 'b', 'c', 'd', 'e']

    >>> for index, item in enumerate(a): print index, item


    0 a

    1 b

    2 c

    3 d

    4 e

    >>>

  • Creating new types at runtime

    >>> NewType = type(“NewType”, (object,), {“x”: “hello”})

    >>> n = NewType()

    >>> n.x

    “hello”

    which is exactly the same as

    >>> class
    NewType(object):

    >>>     x = “hello”

    >>> n = NewType()

    >>> n.x

    “hello”

    Probably not the most useful thing, but nice to know.

    Edit: Fixed name of new type, should be NewType to be the exact same thing as with class statement.

     
     

    查看更多:http://stackoverflow.com/questions/101268/hidden-features-of-python

    这个页面里收集了很多python技巧

    Onenote不错,再试一下Onenote发帖,呵呵

     
     

Category: Python, linux  | Tags: , ,  | Leave a Comment
星期三, 10月 08th, 2008 | Author: Zealot

  • 获取Squid
  • 编译安装
  • 快速配置
  • 运行Squid
Category: linux  | Tags: , , ,  | Leave a Comment