2009年6月17日

目的:
        即为img2py的用处,img2py是将图像转为以py文件存储的程序,简化了程序过程中读文件的处理。

开发环境:eclipse+pydev插件

步骤:
1,在 eclipse工程中增加个含有main函数的模块,用来处理图片到py,代码如下:
'''
Created on 2009-6-16
@author: fengxuanshuo

This is a way to save the startup time when running img2py on lots of
files...

'''
import sys
from wx.tools import img2py

command_lines = [
                 "-a -F -n book   pictures/right_menu/222.png   ../main/images.py",
                 "-a -F -n boo   pictures/right_menu/111.png   ../main/images.py",
                 "-a -F -n ook_red   pictures/right_menu/000.png   ../main/images.py",
                 ]

if __name__ == '__main__':
    for line in command_lines:
        args = line.split()
        img2py.main(args)

其中command_lines为命令行执行内容,程序需要的图片都可以处理,而且目标文件可以有多个,名字自己取。

2,执行新增加的模块,就会发现 main目录多了个images.py文件。

3,更新eclipse pydev工程:pydev插件并没有常用的那个add file to project选项,不过有pydev->source format python files.

4,然后再原工程里面就可以用图片py文件了(可能有些版本,在生成py文件的时候不会加import相关库的语句,需要手动添加)

5,images.py 在wxpython demo 中的用法
定义全局变量 images: images =None
在app里面声明全局的images : globel images
import imgaes as i
images = i

其他py文件类似,这么做的好处在demo的注释里面说了,不罗嗦了,over

后记:wxpython demo的构架不错的,值得纯python大型项目学习
http://www.vspecial.org/thread-554-1-1.html


发表于 2009-06-17 00:43 lostpencil 阅读(188) | 评论 (0)编辑 收藏

2008年11月29日

什么是 Python 语言

Python 语言是一种计算机编程语言,作用类似于 c/c++/java/perl/VB/Delphi 等等计算机编程语言,据有非常清晰易读的语法特点,并且是一种高级面向对象的语言,用途非常广泛,并且可以进行扩展。Python 可以运行在 Windows,Linux,FreeBSD,Solaris等等几乎所有的电脑中,也可以运行在手机中,支持 Java 和 .Net 技术。 Python(派森)语言是一种面向对象的用途非常广泛的编程语言,具有非常清晰的语法特点,适用于多种操作系统,可以在Windows和Unix这样的系统中运行。目前在国际上非常流行,正在得到越来越多的应用。Python可以完成许多任务,功能非常强大。Python核心网站是: http://www.python.org/ ,其中你可以找到很多资料。如果您第一次使用 Python, 可以下载一个试试。

Python 语言使用方便,不需要进行复杂的编译,用途非常广泛,可以进行各种软件的开发,比如: 网站,图形界面(GUI), 网络编程,数据库编程,图形图像处理,科学计算,手机编程等等。

使用 Python 最多的应该是 Google 公司了,就是人们到处都可以看到的 Google 搜索引擎。微软公司也已经开始提供Python语言的软件了。 全球著名的手机厂商 Nokia 公司早已经开始提供基于Python语言的手机开发软件了。另外,还有很多游戏是用Python开发的。另外一个比较有名的就是 Zope 公司了。

目前,Python已经有成百上千的公共资源可以供你调用。

“Python”这个英文单词的发音似“派森”,因此中文可以称之为派森。

举个小例子:

Toggle line numbers
   1 # -*- coding: utf-8 -*-
   2 # 这里是注释
   3 import string # 引用模块
   4 
   5 class abc: # 定义类
   6     def my(self): # 定义方法
   7         hi = '你好,世界'
   8         return hi
   9 
  10 def hello(int): # 定义函数或子程序
  11     """说明"""
  12     if int < 0:   # 判断
  13         res = '请输入整数'
  14     else:
  15         my_class = abc()
  16         res = my_class.my()
  17     return res
  18 
  19 print hello(2) # 调用函数 hello

下载和安装

  • 请到 Python.org下载, 当前最新的版本是 2.4.2

基础教程

Python语言是一种非常容易学习的语言,具有非常清晰的语法结构。因此,在非常短的时间内,就可以编写出实用的程序。最好先看看Python自带的文档。然后,可以再参考以下内容:

Zope 专题

Zope 是一种用途广泛的Web应用服务器软件,主要是基于Python开发的,有很多软件是构建在Zope基础上的,比如:Plone 等等。它的主页是 www.zope.org

面向对象编程

Python语言是一种有面向对象的语言,因此不仅适合于小型项目的开发, 还适合大中型项目的开发。

数据库

Python 在数据库方面也很优秀,可以和多种数据库进行连接,进行数据处理,从商业型的数据库到开放源码的数据库都提供支持。例如: Oracle, Ms SQL Server等等。有多种接口可以与数据库进行连接,至少包括ODBC。有许多公司采用着以Python为核心的架构。因此,掌握了Python使你可以充分利用面向对象的特点,在数据库处理方面如虎添翼。

Windows编程

Python 不仅可以在Unix类型的操作系统上应用,同样可以在Windows系统里有很好的表现。通过添加 PythonWin 模块,就可以通过 COM形式调用和建立各种资源,包括调用注册表、ActiveX控件以及各种COM等工作,最常见的例子就是通过程序对Office文档进行处理,自动生成文档和图表。

通过Python,你还可以利用py2exe模块生成exe应用程序。还有许多其他的日常维护和管理工作也可以交给 Python来做,从而减少维护的工作量。利用Python,你还可以开发出象VB,VC,Delphi那样的GUI程序,但却可以在多个平台上执行。这在许多方面并不逊色于Java。

多媒体

利用Python,你可以处理图象、声音、视频、动画等,从而为你的程序添加亮丽的光彩。动态图表的生成、统计分析图表都可以通过Python来完成。另外,还有OpenGL。利用PyOpenGL模块,你可以非常迅速的编写出三维场景。

  • Alice : 一个用Python和Java开发的动画编辑器。
  • VPython : 三维场景设计
  • PyOpenGl
  • PIL图像库 : 图像分析与处理模块
  • PyMol :开放源代码的分子模型系统,至少可以用于医学新药物的探索。精彩

高性能计算

Python可以广泛的在高性能计算领域发挥独特的角色,这包括科学计算领域、网格(Grid)计算领域等等。有许多模块可以帮助你在计算巨型数组、矢量分析、神经网络等方面高效率完成工作。尤其是在教育科研方面,可以发挥出独特的优势。

网络编程

Python可以非常方便的完成网络编程的工作,提供了众多的解决方案和模块,可以非常方便的定制出自己的服务器软件,无论是c/s,还是b/s模式,都有很好的解决方法。

XML

Python对XML的支持同样非常强大,有多个扩展模块可以帮助你建立、分析和处理XML,对于将来的发展趋势而言,这是非常重要的。Python支持PRC,SOAP等等。

图形界面(GUI)

Python可以非常方便的实现GUI编程,通过PyGTK,wxPython, PyQT等等模块,你就可以根据需要编写出强大的跨平台的用户界面程序。免费推荐使用PyGTK或wxPython。

关于如何用Python进行GUI开发,还可以参考 onlamp.com 的 这个页面

开发环境与编辑器

Python程序的开发工具比较多,目前主要的工具既有IDLE,PythonWin这样的免费工具, 也有一些商业性的工具。通过这些工具 ,可以让你更为快速的完成工作。

  • 集成开发环境(IDE): 列表
    • IDLE:这是Python里边自带的,基本上可以满足一般开发需要。
    • Eric3 : 非常专业的的IDE
    • SPE : 一个不错的编辑软件
    • PythonWin:这是基于Windows平台的编辑开发环境,基本上可以满足一般开发需要。下载
  • 代码编辑器:
    • LEO :完全由Python编写的程序代码编写辅助工具,可运行在多种操作系统中,支持独特的程序代码管理方式。
    • Vim :相当专业的代码编辑器,可运行在多种操作系统中,支持Python扩展。
    • Emacs:Unix系统中常用的工具。
    • SciTE:简单易用的代码编辑器,支持unicode编辑等等多种功能。
    • Quanta: 主要用于编辑网页等等

嵌入和扩展

Python 可以嵌入到其它应用程序中,也可以通过C/C++编写扩展模块,从而可以提高程序的运行速度或者完成只有通过C/C++才能完成的工作。现在Python 已经可以和C#相结合,并且结合到Visual Studio里边,实现微软的.Net思想。如果你会C语言,再学习Python,这将是一个非常棒的一种选择。以下是几个比较常用的扩展工具

如果你掌握了Python,想在Java里应用它,你可以采用Jython。Jython是采用Java语言实现的Python。这样,你只要按照 Python的语法,就可以调用Java的各种类库,快速的编写出基于Java的程序。也就是通过Jython,编写Java程序。这样就可以更为快速的实现Java的功能。另外,Oreilly已经出版了Jython方面的专著《Jython Essentials》,发展迅速。Python在面向对象方面和Java是相通的。神奇的Python!!

另外,你可以参考:

游戏编程

Python在很早的时候就是一种游戏编程的辅助工具。在《星球大战》中扮演了重要的角色。目前,通过Python完全可以编写出非常棒的游戏程序。另外,你可以到 pygame.org下载一些例子看看,确实可以让你感觉一新。

"Python plays a key role in our production pipeline. Without it a project the size of Star Wars: Episode II would have been very difficult to pull off. From crowd rendering to batch processing to compositing, Python binds all things together," said Tommy Burnette, Senior Technical Director, Industrial Light & Magic.

中文编程与文字处理

最新的 2.4 版本加强了对中文的支持,建议大家下载最新的版本。

另外,Glace对Python2.1.1进行了深入的改造,形成了一种中蟒语言,实现了可以用中文编程,详细请见: 中蟒

Python 对文字的处理功能强大,支持 unicode 和 正则表达式。下面是一些小工具,可以帮助用来排版:

  • Docutils :方便编写标准的文档
  • Epydoc :生成代码类文档
  • txt2tags :用纯文本帮助编写多种格式的文档, 和 Docutils 类似。
  • AsciiDoc

相关书籍:

手机移动

Python 也可以在手机中运行,目前,Nokia已经开始提供 Series 60 系统中的Python,通过它就可以调用手机中的各种功能啦!

成功案例与应用

目前,Python已经成功的实现企业级应用,在全球,已经有很多公司采用Python进行企业级软件的开发和应用,比如:ERP和CRM这样的应用。同时,通过Python技术,成功的实现了许多政务应用。 最有名的可能就要算 Google 啦。请查看以下一些网址:

"Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we're looking for more people with skills in this language." said Peter Norvig, director of search quality at Google, Inc.

书籍文档

目前,已经出版了多种中文书籍,不妨找一本看看。比如:

  • 《Python 核心编程》
  • 《Python 编程金典》

综合应用

以下是一些进行综合应用的软件:

  • PyMol :开放源代码的分子模型系统,至少可以用于医学新药物的探索。精彩!
  • Chandler : Lotus Notes的开发者进行的新的协同交流系统。
  • Plone :基于Zope开发的网站框架,轻松建立易于维护和管理的网站交流系统。
  • MailMan : 元老级别的邮件列表交流软件。
  • BitTorrent : BT 超强的下载工具
  • EarthClock : 挺好看的钟表
  • GNU Enterprise: 企业ERP
  • TinyERP: 小型的ERP系统

精选链接

英文:

中文:

发表于 2008-11-29 07:50 lostpencil 阅读(1378) | 评论 (0)编辑 收藏

2008年11月14日

== 基于本地的Python应用程序 ==


=== 写在之前 ===
{{{
这篇所说的是关于建立python调用Flash的本地应用,不同于Adobe的Apollo。

没有用到浏览器嵌入flash网页的方法,直接在pythonwin或者wxpython建立的窗口中插入Flash ocx。

因为是操作Activex控件的方式因此大概只适用于windows平台。抱歉我并未在其它平台上试过这种方法,不过linux中应该也有类似的技术。}}}

=== Flash ocx介绍 ===
{{{
Flash ocx实际上是一种COM组件开发模型(Microsoft Component Object Model),它原先是从Windows 3.x中的OLE发展过来的。现在又被改名叫做Activex。Activex是COM的一种,一般是指带有UI界面的COM。

Flash ocx的本名是叫Shockwave Flash Object,是一个Activex控件。Activex控件文件名的后缀是ocx。

原先的Shockwave包括了很多东西。被Adobe收购的MicroMedia公司的另一个产品Director的web应用就叫shockwave,它集合了视频流、Flash、shockwave 3D于一身。

对于Director我还是挺有感情的,只不过Director到了8.5以后的版本就基本不再发展了,我也渐渐不用它了。(听说Adobe收购MicroMedia以后,还会推出Director 11)}}}


=== Flash ocx与外界通迅的方法 ===

==== 调用ocx标准COM接口IDispatch ====

这种方法最简单,也比较通用。

它又叫COM对象的自动化接口。使用自动化,对象就可以提供一个简单的自动化接口,这样脚本语言作者只需掌握IDispatch和几个COM应用程序接口就可以了。

pythonwin的作者 Mark Hammond 的一本书(Python Programming on Win32)就讲到了怎样用python直接操作COM对象(操作的函义包括使用和发布)。如果想深入细节的话,可以参考这本书。

Python 程序使用 win32com.client.Dispatch() 方法来创建 COM objects。
如创建一个 Flash COM object.

{{{#!python
>>> import win32com.client
>>> fl = win32com.client.Dispatch("ShockwaveFlash.ShockwaveFlash.9") #Flash 9 的ProgID是ShockwaveFlash.ShockwaveFlash.9,有很多工具可以查到机器内部注册的COM组件信息
}}}
这样就得到了Flash COM object,你可以让它LoadMovie,让它Play,但是你暂时还看不到它,你得传给它一个窗口,这样它才能显示在窗口。
所幸wxpython帮我们封装了这一切,你只需要调用wx.lib.flashwin.FlashWindow类就行了。

例:
{{{#!python
import wx
from wx.lib.flashwin import FlashWindow

class CGui(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, 101, "map", size = (800, 600), style = wx.FRAME_SHAPED)
self.flash = FlashWindow(self, style=wx.SUNKEN_BORDER, size = (800, 600)) #用wx.lib.flashwin.FlashWindow创建窗口
self.flash.LoadMovie(0, 'C:\\drop_shadow_dog.swf') #播放"C:\\drop_shadow_dog.swf"的Flash影片
self.flash.SetSize((800, 600));

def getText(self):
returnValue = self.flash.GetVariable('FlashValue') #从Flash端
return returnValue

def setText(self, text):
self.flash.SetVariable("PythonValue", text) #传给Flash变量

}}}
这些传递变量在Flash AS端都处于_root层级下。

这儿有个例子
http://www.sephiroth.it/weblog/archives/2004/05
/wxpython_and_flash_first_test.php
{{{#!python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx, sys, os
import string, codecsfrom wx.lib.flashwin
import FlashWindow
from wx.lib.flashwin import EVT_FSCommand
#----------------------------------------
class TestPanel(wx.Panel):
def __init__(self, parent, base, swf):
wx.Panel.__init__(self, parent, -1)
self.base = base
sizer = wx.BoxSizer(wx.VERTICAL)
self.flash = FlashWindow(self, style=wx.SUNKEN_BORDER)
dlg = wx.MessageDialog(self, "This will work only under Windows!","Warning!",wx.OK | wx.ICON_INFORMATION)
dlg.Center()
dlg.ShowModal()
wx.BeginBusyCursor()
try:
self.flash.LoadMovie(0, swf)
except:
wx.MessageDialog(self, "could not load the swf file","Error",wx.OK | wx.ICON_ERROR).ShowModal()
sys.exit(2)
wx.EndBusyCursor()
self.flash.Stop()
self.flash.SetSize((self.flash.GetSize()[0],self.flash.GetSize()[1]))
# sizer
sizer.Add(self.flash, 1, wx.EXPAND)
self.SetSizer(sizer)
self.SetAutoLayout(True)
sizer.Fit(self)
sizer.SetSizeHints(self)
self.SetFlashOptions()
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
self.Bind(EVT_FSCommand, self.CallMethod) ##将Flash ocx的消息事件绑定到CallMethod函数上。

def SetFlashOptions(self):
self.flash.menu = False
self.flash._set_FlashVars("data=Server started on " + sys.platform)
self.flash.Play()

def OnDestroy(self, evt):
if self.flash:
self.flash.Cleanup()
self.flash = None

# Called from Flash FSCommand
def CallMethod(self, evt):
try:
arguments = string.split(evt.args,"###")
filename = arguments[0]
body = arguments[1]
if filename == "" or body == "":
wx.MessageDialog(self, "Please check data inserted", "An Error occurred", wx.OK | wx.ICON_INFORMATION).ShowModal()
else:
dlg = wx.FileDialog(self, "Save as..." , os.getcwd(), filename, "*.*", wx.SAVE | wx.OVERWRITE_PROMPT )
if dlg.ShowModal() == wx.ID_OK:
try:
f = codecs.open(os.path.normpath(dlg.GetPath()), "w", "utf-8", "ignore")
f.write(codecs.utf_8_decode(codecs.BOM_UTF8)[0])
f.write(body)
f.close()
self.flash._set_FlashVars("data=Succesfully saved text file")
except:
wx.MessageDialog(self, "%s %s %s" % sys.exc_info(), "An Error occurred", wx.OK | wx.ICON_ERROR).ShowModal()
self.flash._set_FlashVars("data=%s %s %s" % sys.exc_info())
except:
wx.MessageDialog(self, "Please check data inserted","An Error occurred",wx.OK | wx.ICON_INFORMATION).ShowModal()
self.flash._set_FlashVars("data=%s %s %s" % sys.exc_info())

#-------------------------------------------
if __name__ == '__main__':
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "ActiveX -- Flash", size=(640, 480), style=wx.DEFAULT_FRAME_STYLE )
base = os.path.normpath(os.path.abspath(os.path.dirname(sys.argv[0])))
swf = os.path.normpath(os.path.join(base, "movie.swf"))
self.tp = TestPanel(self, base, swf)
app = wx.PySimpleApp()
frame = TestFrame()
frame.Center()
frame.Show(True)
app.MainLoop()
}}}

Flash端很简单,两句话就搞定了。
{{{
on (click) {
fscommand("saveFile", this._parent.fnome.text + "###" + this._parent.ftesto.text)
}}}}

这里用到了Flash的fscommand。

在Flash端点击了以后,它就会发送一个fscommand消息事件。

python端接收到了以后,由CallMethod处理。

==== 使用Flash ExternalInterface ====

ExternalInterface 类是一个子系统,通过它可以轻松地实现从 ActionScript 和 Flash Player 到 HTML 页中的 JavaScript 或任何包含 Flash Player 实例的台式机应用程序的通信。
ExternalInterface 可以提供以下功能:
{{{
■ 可以调用注册过的 python 函数。 从python端也可以调用注册过的Flash ActionScript函数。
■ 可以传递任意数量的、具有任意名称的参数;而不是仅限于传递一个命令和一个字符串参数。
■ 可以传递各种数据类型(例如 Boolean 、Number 和 String);不再仅限于 String 参数。
■ 可以接收调用值,该值将立即返回到 ActionScript(作为进行的调用的返回值)。}}}

Flash利用ExternalInterface与Python之间的通信使用特定的XML格式对函数调用和值进行编码。Flash端自动处理XML格式,Python则需要将接收到的XML数据解析和发送前打包成XML格式。

使用ExternalInterface与Python进行通信时,Flash以特定的XML格式向应用程序发送消息(函数调用和返回值),并要求来自Python的函数调用和返回值使用相同的 XML格式。

下面的 XML 片断说明了一个 XML 格式的函数调用示例:

{{{


... (individual argument values)

}}}

通过XML格式,ExternalInterface与Python之间可以传递多种类型的参数,包括Python的list和dic类型。

我们可以建立一个数据转换类来专门将翻译Python与Flash之间的通迅。

{{{#!python
class EIDataSerializer:
__xmlData=None
def __packNumber(self,p,x):
p.appendChild(self.__xmlData.createElement('number')).appendChild(self.__xmlData.createTextNode(str(x)))
return
def __packString(self,p,x):
p.appendChild(self.__xmlData.createElement('string')).appendChild(self.__xmlData.createTextNode(x))
return
def __packNone(self,p):
p.appendChild(self.__xmlData.createElement('null'))
return
def __packBool(self,p,x):
if x:
p.appendChild(self.__xmlData.createElement('true'))
else:
p.appendChild(self.__xmlData.createElement('false'))
return
def __packDict(self,p,x):
p=p.appendChild(self.__xmlData.createElement('object'))
for k,v in x.items():
n=p.appendChild(self.__xmlData.createElement('property'))
n.setAttribute('id',str(k))
self.__packData(n,v)
return
def __packList(self,p,x):
p=p.appendChild(self.__xmlData.createElement('array'))
i=0
for v in x:
n=p.appendChild(self.__xmlData.createElement('property'))
n.setAttribute('id',str(i))
self.__packData(n,v)
i+=1
return
def __packData(self,p,x): ##将Python的类型打包成XML
t=type(x)
if t in (int,long,float):
self.__packNumber(p,x)
elif t in (str,unicode):
self.__packString(p,x)
elif x==None:
self.__packNone(p)
elif t==bool:
self.__packBool(p,x)
elif t in (list,tuple):
self.__packList(p,x)
elif t==dict:
self.__packDict(p,x)
return
def __unpackNumber(self,p):
try:
return int(p.firstChild.nodeValue)
except ValueError:
try:
return float(p.firstChild.nodeValue)
except ValueError:
return None
def __unpackString(self,p):
return p.firstChild.nodeValue
def __unpackTrue(self):
return True
def __unpackFalse(self):
return False
def __unpackNull(self):
return None
def __unpackUndefined(self):
return None
def __unpackObject(self,p):
d={}
for n in p.childNodes:
d[n.getAttribute('id')]=self.__unpackData(n.firstChild)
return d
def __unpackArray(self,p):
a=[]
for n in p.childNodes:
a.append(self.__unpackData(n.firstChild))
return a
def __unpackData(self,p): ##将Flash传过来的XML解析成Python类型数值
t=p.nodeName
if t=='number':
return self.__unpackNumber(p)
elif t=='string':
return self.__unpackString(p)
elif t=='true':
return self.__unpackTrue()
elif t=='false':
return self.__unpackFalse()
elif t=='null':
return self.__unpackNull()
elif t=='undefined':
return self.__unpackUndefined()
elif t=='object':
return self.__unpackObject(p)
elif t=='array':
return self.__unpackArray(p)
def serializeReturn(self,v):
self.__xmlData=minidom.Document()
p=self.__xmlData
self.__packData(p,v)
return self.__xmlData.toxml()
def serializeCall(self,name,args):
self.__xmlData=minidom.Document()
p=self.__xmlData.appendChild(self.__xmlData.createElement('invoke'))
p.setAttribute('name',name)
p.setAttribute('returntype','xml')
p=p.appendChild(self.__xmlData.createElement('arguments'))
for v in args:
self.__packData(p,v)
s=self.__xmlData.documentElement.toxml()
return s
def deserializeReturn(self,s):
self.__xmlData=minidom.parseString(s)
p=self.__xmlData.documentElement
return self.__unpackData(p)
def deserializeCall(self,s):
self.__xmlData=minidom.parseString(s)
p=self.__xmlData.documentElement#invoke
name=p.getAttribute('name')
args=[]
p=p.firstChild#arguments
for n in p.childNodes:
args.append(self.__unpackData(n))
return (name,args)}}}


===== 从Python调用Flash函数 =====

从Python端调用Flash端函数实际上是Python调用Shockwave Flash ActiveX控件的CallFunction()方法,通过ExternalInterface从Flash调用ActionScript函数。

以下示范了从Python调用Flash函数的用法:

Python端:

{{{#!python
def CallFlash(name,args): ## name是Flash ActionScript的函数名,args是传给Flash ActionScript的参数
ds = EIDataSerializer()
s = ds.serializeCall(name,args) ## 将传递的内容打包成XML
s = flashWnd.ocx.CallFunction(s) ## 调用Shockwave Flash ActiveX控件的CallFunction()方法
s = s.encode('utf-8') ## 从ActionScript返回的任何值都被编码为XML格式字符串,并作为CallFunction()调用的返回值发送回来。
return ds.deserializeReturn(s) ## 返回值解包}}}


Flash端:

要从Python调用ActionScript函数,必须向ExternalInterface类注册函数,然后再用Shockwave Flash ActiveX控件的CallFunction()方法调用它。

Python只能调用ExternalInterface类注册函数中的ActionScript代码,而不能调用任何其它ActionScript代码。

向ExternalInterface类注册ActionScript函数的方法,如下所示:

{{{
function callMe(name:String):String
{
return "busy signal";
}
ExternalInterface.addCallback("myFunction", callMe);}}}

ExternalInterface.addCallback()方法采用两个参数。第一个参数为 String 类型的函数名,这是告诉Python端调用的函数名。第二个参数为Flash端实际ActionScript函数。

由于这些名称是截然不同的,因此可以指定将由Python使用的函数名与实际的ActionScript函数具有不同的名称。这在函数名未知的情况下特别有用,例如:指定了匿名函数或需要在运行时确定要调用的函数。

===== 从Flash调用Python函数 =====

从Flash调用Python函数实际上是Shockwave Flash ActiveX控件发送了一个控件消息FlashCall,并附带包含有关函数调用信息的XML 格式的字符串。Python将其解析成函数名和参数,并调用相应函数。

我们继续从消息流程上解析这个过程,首先Flash端示例:

{{{
public function sendMessage(message:String):void
{
ExternalInterface.call("newMessage", message); //调用了Python端的newMessage的方法,message是newMessage方法的参数
}}}}

Python端示例:

先建立一个供Flash调用的函数

{{{#!python
def newMessage(self, message):
print message
return message}}}

建立一个函数字典库

{{{#!python
def RegisterCallback(self,name,callback): ##将需要调用的函数注册
if callable(callback):
self.__callbackReg[name]=callback ##和Flash类似,name是Flash端调用的函数名。callback为Python端实际函数。
return True
else:
return False}}}

{{{#!python
self.RegisterCallback("newMessage", newMessage) ##将其注册到__callbackReg中}}}

最后接收Flash消息,处理函数调用

{{{#!python
def OnFlashCall(self, receiveString): ##注册的Activex消息处理函数
receiveString = receiveString.encode('utf-8') ##从Flash控件消息接收的XML字符串
name,args = self.__szr.deserializeCall(receiveString) ##解析成Python函数名和参数
r = self.__callbackReg[name](*args) ##函数字典中注册的函数名
ds = EIDataSerializer()
s = ds.serializeReturn(r) ##返回值打包成XML
self.SetReturnValue(s)
return}}}

这样就可在Flash端调用Python函数了。



以上方法在pythonwin和wxPython中均可使用。

发表于 2008-11-14 16:45 lostpencil 阅读(1593) | 评论 (5)编辑 收藏

2008年10月18日

目前国内的聊天机器人大多都只是做了一个自然语言结构分析,然后就在此基础上做了场景记录。这2方面的努力结果最终产生了一个庞大的数据库,于是表现出来机器人的智能面不够灵活,而且速度很慢。

目前我发现人类的语言交流并不完全是的知识,信息的交流,策略占了很大比重,智能机器人语言方面的改善感觉应该加入策略的因素。

这里可以简单加入情绪因素进去,然后就是根据情绪来分类策略,这将直接导致数据库横向发展,查询效率提高很多。

而且很多策略是可以完全通过自然语言结构分析来确定句子的答复的,策略丰富化,机器人将更加智能。

目前我这方面针对朋友开发的一个机器人做了改进以后,运行速度大约提高了40%左右,至于语言效果由于策略的规划和实现还不完善,不如以前,但是大多数情况差别不大。

因为一些商业因素,就不继续说了,呵呵

发表于 2008-10-18 00:32 lostpencil 阅读(1481) | 评论 (2)编辑 收藏

2008年9月28日

一个偶尔的机会接触到了MDP,马尔可夫决策过程,突然发现多年的困惑有点头绪了,分享一段东西。

以下东西摘自某博士论文部分(若有版权问题请及时告知):

以哲学观点来看,人类来到世间至少有三件事要做:认识世界;改造世界;享受世界。

在这其中,学习类问题对应认识世界,而决策类问题便是和改造世界紧密相关的。决策问题伴随着人们的日常生活,大至公司乃至国家的战略性决定,小至个人利益相关的一些选择。‘决策’又区别于简单的‘决定’以及‘选择’。它通常涉及的是一个过程,其最终对应的行动的执行一般是多步的。在每一步,都要去做一个选择。不同的选择,不同的行动,导致不同的结果,进而也意味着不同的收益。决策不能孤立的进行,若不考虑现在与将来的联系,很难在整个过程中获得最好的收益,就如同在一次长跑比赛中,我们不能在起点就用尽全力冲刺一样。事实上,决策问题与人们的社会生活的联系是如此密切,可以说,一切社会实践活动都离不开决策,甚至,从辨证的观点看,若是把主观世界也当作客观世界的一部份,那么学习本身也是一个改造世界的过程,其过程也一样讲究策略,我们改造就是自己罢了。

对于智能体而言,当其面对客观世界中存在的一个待解决的问题时,首先,他的学习能力使其在主观世界中获得了对该问题的一个抽象的描述,对应为问题的模型,这其中通常包括:

¨        问题所有可能的状态,

¨        问题发展过程的演变规律,

¨        智能体在过程中可以做出的选择,

¨        智能体所期望的结果等。

事实上,这就是MDP模型的基本构成部分,

而所谓的智能体进行决策,也就是指智能体在此模型的基础上,基于问题过程的规律进行规划,利用智能体可行的选择参与改变过程,使其朝自身期望的结果发展,最终解决问题。总的来说,决策基于问题的模型再结合规划的方法两部分完成。在人工智能领域,马尔可夫决策过程是用来建模规划问题的一个基本理论模型。以其为基础,进一步发展出一系列更具一般性的决策模型,如部分可观察马尔可夫决策过程,分布式马尔可夫决策过程,部分可观察的随机博弈及半马尔可夫决策过程等等。

 

决策总是与一个过程相联系的(当然,从广义上来看,过程可以只有一步)。智能体要在过程中做出合适的选择,将过程的发展引入对自身有利的方向,必然需要了解描述过程发展变化的知识。相对于穷举所有变化,如果某些知识,不止一次可被用来推断过程发展,即为规律。主体更需要就是这种精简的知识。

马尔可夫过程正是具有一类普遍共性的过程。这类共性既是马尔可夫性,也称无后效性。由俄罗斯数学家马尔可夫于1907提出。所谓无后效性,指的是这样一种性质:某阶段的状态一旦确定,则此后过程的演变不再受此前各状态的影响。也就是说,未来与过去无关,当前的状态是此前历史的一个完整总结,此前的历史只能通过当前的状态去影响过程未来的演变。具体地说,如果一个问题被划分各个阶段之后,阶段 I 中的状态只能通过状态转移方程去影响阶段 I+1 中的状态的得来,与其他状态没有关系,特别是与未发生的状态没有关系,这就是无后效性。从更本质的的角度来理论,可以认为马尔可夫性来源于对因果性和时间的连续性以及单向性的认可。

马尔可夫性用来描述过程的规律类似数学中使用递推公式描述数列一样,并且特点是递推式只用到了前面一项。做为区别,比如著名的斐波拉契(Fibonacci)数列,11235……的递推公式F(n)=F(n-1)+F(n-2)就用到了前面的两项。假设我们构造一个过程,逐次去读取数列中的每一项,任何一个时刻的状态便是读取到的数字。那么,斐波拉契数列对应的便不是一个马尔可夫过程。描述规律的方式很多,把握“当前的状态是此前历史的一个完整总结”这一要点后,很多过程可以被转化描述为马尔可夫过程。当然,前提是,可以做到当前状态完整总结历史这点。但事实上完美总是相对而言的,从后面不确定性的讨论也可以看到。从这个角度来说,马尔可夫过程是一个很实用的理论。在马尔可夫过程上做决策的好处显而易见,我们可以忽略历史的影响,也无需再去不断的保存历史信息,一切规划都只要从当前状态出发即可。它所蕴含的思想是将智能体有限的规划能力引导至更有价值的方向。

马尔可夫决策过程与马尔可夫过程的本质区别就是多了主体即决策者的介入。下面将依次简单介绍马尔可夫决策过程(Markov Decision Processes, MDP),部分可观察马尔可夫决策过程(Partially Observable Markov Decision Processes, POMDP),分布式部分马尔可夫决策过程(Decentralized-POMDP, DEC-POMDP),部分可观察的随机博弈(Partially Observable Stochastic Games, POSG)及半马尔可夫决策过程(Semi-MDP)之间的区别与联系。

50年代R.贝尔曼研究动态规划时和L.S.沙普利研究随机对策时已出现马尔可夫决策过程的基本思想。R.A.霍华德(1960)D.布莱克韦尔(1962)等人的研究工作奠定了马尔可夫决策过程的理论基础。1965年,布莱克韦尔关于一般状态空间的研究和E.B.丁金关于非时齐(非时间平稳性)的研究,推动了这一理论的发展。1960年以来,马尔可夫决策过程理论得到迅速发展,应用领域不断扩大。凡是以马尔可夫过程作为数学模型的问题,只要能引入决策和效用结构,均可应用这种理论。

在人工智能领域中,对决策类问题的求解过程也可以称为规划。经典规划一般基于确定式的环境模式,如搜索算法A*等。这类方法在现实应用中有很大的局限性。面对现实中的规划问题,主体对环境特性的把握常常是不完整的,正是由于这种知识的缺失,造成了不确定性。马尔可夫决策模型则可以处理这类问题。利用下图信息集合划分的方式,可以更清晰的理解不确定性,以及马尔可夫决策过程(MDP)与下面将提到部分可观察马尔可夫决策过程(POMDP)的区别。

针对某个决策问题,从信息或者知识的角度我们区分出如下所示3个依次为包含关系的集合:


1.1 决策问题中的信息划分


A
集合:为客观存在的影响过程的全部信息,是整个客观世界的世界状态中与问题所对应过程相关的因素。

B集合:为影响智能体主观决策的信息,进一步解释,是智能体主观上知道存在,并能够把握运用的一些信息。因为对于某些因素,即便智能体知道应该与过程相关,但无法把握运用,这些信息也不会影响智能体决策。比如,一般都认为掷硬币,正反面的概率各50%。事实上,风力,掷硬币的具体操作方式,抛出轨迹,用力情况,地面情况等都会影响过程结果,而这些因素通常无法把握运用,即使考虑进来,也难以改变决策。因此,这类智能体知道存在却无法把握利用的信息,及主观上根本不知道其存在而客观上却影响过程的因素,构成了B集合与A集合的差别。同时,也正是这些差别,造成了不确定性的存在。从另一个角度,只要B不是空集,基于应用的需求,就存在进行决策的意义。但对不确定性仍需进行刻画,于是便引入了统计意义上概率。

C集合:为智能体总是能观察到的信息。现实中很多决策过程,对于B集合中的信息,智能体有时观察不到。比如踢足球,自己身后球员的位置是会影响决策的,但却可能会观察不到。

根据定义内容,首先有前提A>=B>=C,进而可以对问题做下面的分类:

1> A=B=C时是一个确定性问题。

2> A>=B=C时是一个MDP问题。

3> A>=B>C时是一个POMDP问题。

MDP本身既可以处理确定性问题,也可处理不确定性问题。而POMDPMDP模型上进行了一定扩展,引入了对观察不确定性的处理。从一定意义上也可以认为,MDPPOMDP的一种极端的情况,即决策相关信息全部可观察。

MDPPOMDP模型中都认为决策的智能体只有一个,并把其它一切因素都归于客观环境。这些因素一部分是确定性的知识;另一部分则是已归入统计概率的不确定性,认为在当前条件下,从处理问题的实际情况出发,不适合再进行探究,只作概率推理。当一个过程中,有多个智能体同时决策合作来解决一个问题时,上述模型是否适用的关键因素即其他智能体的策略是否已知。策略是决策的结果,指出在过程某个状态要采用哪个行动。如果认为其他智能体策略已知,无论是确定性的策略亦或含概率表示的不确定性策略,那么其他智能体一样可以归入环境,仍可使用MDPPOMDP模型处理。否则,其它智能体会采用何种策略也是需要纳入考虑的,在生成智能体自身决策的同时,也要生成其他智能体的决策,这是其客观过程本身的模型决定的。分布式马尔可夫决策过程(DEC-MDP)及分布式部分可观察马尔可夫决策过程(DEC-POMDP)可以处理这类多智能体合作问题。

在现实应用中,多智能体间除了合作也可能存在对抗,这类问题可以归为博弈。其中本质的区别即智能体间收益评价的不同。合作类问题,各个智能体有相同的收益评价,或者说有共同的目标;而博弈类问题,各个智能体收益评价存在区别,甚至完全对立。部分可观察的随机博弈(POSG)便是进一步扩展的一个决策模型,可以处理这类带有不确定性的博弈问题。

半马尔可夫过程又可以称为非时齐马尔可夫过程,这是相对于一般的时齐马尔可夫过程而言的。所谓时齐是指过程的每两个相邻状态点间的时间间隔是一致的,对应决策过程则是每步行动的执行时间是定长的。非时齐则是描述了一类更一般的情况,对应决策过程中行动的执行时间并不固定,甚至是时间上的一个概率分布。

我的收获:早些年研究的东西,基本思路是有一定的科学理论依据的,只是出发点有了问题,所以难逃计算量的恐怖。就像目前的彩票研究者一样,最终的常理的结论是预知性不明朗,靠运气吧。现在想想其实换一个研究层面去研究,然后按原来的方法计算,很多层面的东西还是相当有可能的。感谢数学,感谢马尔可夫。

发表于 2008-09-28 01:19 lostpencil 阅读(1387) | 评论 (1)编辑 收藏

2008年9月24日

我的电脑系统是XP, C盘是ntfs格式的,然后D盘是fat32格式的,这样DOS窗口里面怎么也cd 不进D盘去。
有没有什么办法,不重装系统或者格式化D盘,就可以轻松的CD D:\进去啊
因为之前D盘装了很多东西,格式化了太麻烦了

修改:
2008-09-25 08:13 by OneZ
进入D盘,只要在CMD窗口下输入D:,就可以了。前面不需要CD。

发表于 2008-09-24 23:27 lostpencil 阅读(1671) | 评论 (6)编辑 收藏

起因:通过MingW和qt-win-opensource-4.4.2-mingw.exe在windows下安装QT开源版的情况,在运行QT-demos时候会发现mediaplayer那个程序launch不起来,原因是本身那个程序就没有编译成可执行文件。然后自己找到那个模块后,qmake ,make,结果发现老有错误“Cannot find -lphonon”. 网上一搜同样的问题很多,答案比较少,超级复杂,还是有点乱说的成份在。包括那些英文网站上也没有有效的解决方案。

关于phonon:
Phonon是一个跨平台多媒体编程开发平台,可使具有不同编程经验的编程人员更便捷地将多媒体功能移植到他们的应用程序中去。
Phonon起初由KDE团队开发,是发布的KDE 4.0的一个组成部分。目前,奇趣科技将Phonon进行了扩展,使其可用于如Windows和 Mac OS X在内的所有主流桌面操作系统上。此外,奇趣科技已将该源程序代码编入KDE的源代码库中,并将其采用LGPL授权。
编程人员利用Phonon,可以更方便地将多媒体回放功能运用到C++应用程序中,很多操作程序仅利用极少的几个代码便可以实现。Phonon的源代码,包括仅在UNIX 和Linux平台上使用的、基于Xine的单一后端。而奇趣科技为Linux的GStreamer创建了其它的后端实施工具,同时为Windows和Mac OS X操作系统也创建了新的后端工具。
奇趣科技把Phonon纳入公司发布的Qt 4.4之中,目前该版本已在2008年第一季度末正式发布。

办法:会出现这个问题可能是qt-win-opensource-4.4.2-mingw.exe制作者的疏忽,把Phonon模块以及相关的程序没有编译到,
解决办法其实很简单,不要受那些答案的误导,只要在src下面找到phonon文件夹,然后编译下就好了。
这样会生成2个文件,一个是lib下面的libphonon4.a, 还有一个是bin下的 phonon4.dll, 也可以直接网上下到这2个文件,copy过去也能用。

注:仅验证了MingW + qt-win-opensource-4.4.2-mingw.exe的情况, 其他办法安装的有没有问题不清楚,Phonon是QT4以后才有的,要是用老版本是很难有办法用的。

发表于 2008-09-24 11:12 lostpencil 阅读(2437) | 评论 (5)编辑 收藏

2008年8月24日

什么是robots.txt文件? 搜索引擎通过一种程序robot(又称spider),自动访问互联网上的网页并获取网页信息。您可以在您的网站中创建一个纯文本文件robots.txt,在这个文件中声明该网站中不想被robot访问的部分,这样,该网站的部分或全部内容就可以不被搜索引擎收录了,或者指定搜索引擎只收录指定的内容。

robots.txt文件放在哪里? 
robots.txt文件应该放在网站根目录下。举例来说,当robots访问一个网站(比如http://www.abc.com)时,首先会检查该网站中是否存在http://www.abc.com/robots.txt这个文件,如果机器人找到这个文件,它就会根据这个文件的内容,来确定它访问权限的范围。
网站 url 相应的 robots.txt的 url 
http://www.w3.org/ http://www.w3.org/robots.txt 
http://www.w3.org:80/ http://www.w3.org:80/robots.txt 
http://www.w3.org:1234/ http: ... 234/robots.txt 
http://w3.org/ http://w3.org/robots.txt 

robots.txt文件的格式 
"robots.txt"文件包含一条或更多的记录,这些记录通过空行分开(以cr,cr/nl, or nl作为结束符),每一条记录的格式如下所示:
":"。

在该文件中可以使用#进行注解,具体使用方法和unix中的惯例一样。该文件中的记录通常以一行或多行user-agent开始,后面加上若干disallow行,详细情况如下:

user-agent:
  该项的值用于描述搜索引擎robot的名字,在"robots.txt"文件中,如果有多条user-agent记录说明有多个robot会受到该协议的限制,对该文件来说,至少要有一条user-agent记录。如果该项的值设为*,则该协议对任何机器人均有效,在"robots.txt"文件中,"user-agent:*"这样的记录只能有一条。

disallow:
  该项的值用于描述不希望被访问到的一个url,这个url可以是一条完整的路径,也可以是部分的,任何以disallow开头的url均不会被robot访问到。例如"disallow:/help"对/help.html 和/help/index.html都不允许搜索引擎访问,而"disallow:/help/"则允许robot访问/help.html,而不能访问/help/index.html。任何一条disallow记录为空,说明该网站的所有部分都允许被访问,在"/robots.txt"文件中,至少要有一条disallow记录。如果"/robots.txt"是一个空文件,则对于所有的搜索引擎robot,该网站都是开放的。


robots.txt文件用法举例 例1. 禁止所有搜索引擎访问网站的任何部分 
下载该robots.txt文件 user-agent: * 
disallow: / 
例2. 允许所有的robot访问 (或者也可以建一个空文件 "/robots.txt" file) user-agent: *
disallow: 
例3. 禁止某个搜索引擎的访问 user-agent: badbot
disallow: / 
例4. 允许某个搜索引擎的访问 user-agent: baiduspider
disallow: 

user-agent: *
disallow: / 
例5.一个简单例子
  在这个例子中,该网站有三个目录对搜索引擎的访问做了限制,即搜索引擎不会访问这三个目录。
  需要注意的是对每一个目录必须分开声明,而不要写成 "disallow: /cgi-bin/ /tmp/"。
  user-agent:后的*具有特殊的含义,代表"any robot",所以在该文件中不能有"disallow: /tmp/*" or "disallow:*.gif"这样的记录出现. user-agent: *
disallow: /cgi-bin/
disallow: /tmp/
disallow: /~joe/ 

发表于 2008-08-24 16:20 lostpencil 阅读(1953) | 评论 (2)编辑 收藏

2008年8月1日

1. Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife ?
2. You're given an array containing both positive and negative integers and required to find the sub-array with the largest sum (O(N) a la KBL). Write a routine in C for the above.
3. Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like. [ I ended up giving about 4 or 5 different solutions for this, each supposedly better than the others ].
4. Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all. [ This one had me stuck for quite some time and I first gave a solution that did have floating point computations
5. Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal. [ I gave the obvious solution of taking % 10 and / 10, which gives us the decimal value in reverse order. This requires an array since we need to print it out in the correct order. The interviewer wasn't too pleased and asked me to give a solution which didn't need the array
6. Give a one-line C expression to test whether a number is a power of 2. [No loops allowed - it's a simple test.
7. Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.
8. How many points are there on the globe where by walking one mile south, one mile east and one mile north you reach the place where you started.
9. Give a very good method to count the number of ones in a "n" (e.g. 32) bit number.
ANS. Given below are simple solutions, find a solution that does it in log (n) steps.
Iterativefunction iterativecount (unsigned int n)beginint count=0;while (n)begincount += n & 0x1 ;n >>= 1;endreturn count;endSparse Countfunction sparsecount (unsigned int n)beginint count=0;while (n)begincount++;n &= (n-1);endreturn count ;end
10. What are the different ways to implement a condition where the value of x can be either a 0 or a 1. Apparently the if then else solution has a jump when
written out in assembly. if (x == 0) y=a else y=b There is a logical, arithmetic and a data structure solution to the above problem.
11. Reverse a linked list.
12. Insert in a sorted list
13. In a X's and 0's game (i.e. TIC TAC TOE) if you write a program for this give a fast way to generate the moves by the computer. I mean this should be the fastest way possible.
The answer is that you need to store all possible configurations of the board and the move that is associated with that. Then it boils down to just accessing the right element and getting the corresponding move for it. Do some analysis and do some more optimization in storage since otherwise it becomes infeasible to get the required storage in a DOS machine.
14. I was given two lines of assembly code which found the absolute value of a number stored in two's complement form. I had to recognize what the code was doing. Pretty simple if you know some assembly and some fundaes on number representation.
15. Give a fast way to multiply a number by 7.
16. How would go about finding out where to find a book in a library. (You don't know how exactly the books are organized beforehand).
17. Linked list manipulation.
18. Tradeoff between time spent in testing a product and getting into the market first.
19. What to test for given that there isn't enough time to test everything you want to.
20. First some definitions for this problem: a) An ASCII character is one byte long and the most significant bit in the byte is always '0'. b) A Kanji character is two bytes long. The only characteristic of a Kanji character is that in its first byte the most significant bit is '1'.
Now you are given an array of a characters (both ASCII and Kanji) and, an index into the array. The index points to the start of some character. Now you need to write a function to do a backspace (i.e. delete the character before the given index).
21. Delete an element from a doubly linked list.
22. Write a function to find the depth of a binary tree.
23. Given two strings S1 and S2. Delete from S2 all those characters which occur in S1 also and finally create a clean S2 with the relevant characters deleted.
24. Assuming that locks are the only reason due to which deadlocks can occur in a system. What would be a foolproof method of avoiding deadlocks in the system.
25. Reverse a linked list.
Ans: Possible answers -
iterative loop
curr->next = prev;
prev = curr;
curr = next;
next = curr->next
endloop
recursive reverse(ptr)
if (ptr->next == NULL)
return ptr;
temp = reverse(ptr->next);
temp->next = ptr;
return ptr;
end
26. Write a small lexical analyzer - interviewer gave tokens. expressions like "a*b" etc.
27. Besides communication cost, what is the other source of inefficiency in RPC? (answer : context switches, excessive buffer copying). How can you optimize the communication? (ans : communicate through shared memory on same machine, bypassing the kernel _ A Univ. of Wash. thesis)
28. Write a routine that prints out a 2-D array in spiral order!
29. How is the readers-writers problem solved? - using semaphores/ada .. etc.
30. Ways of optimizing symbol table storage in compilers.
31. A walk-through through the symbol table functions, lookup() implementation etc. - The interviewer was on the Microsoft C team.
32. A version of the "There are three persons X Y Z, one of which always lies".. etc..
33. There are 3 ants at 3 corners of a triangle, they randomly start moving towards another corner.. what is the probability that they don't collide.
34. Write an efficient algorithm and C code to shuffle a pack of cards.. this one was a feedback process until we came up with one with no extra storage.
35. The if (x == 0) y = 0 etc..
36. Some more bitwise optimization at assembly level
37. Some general questions on Lex, Yacc etc.
38. Given an array t[100] which contains numbers between 1..99. Return the duplicated value. Try both O(n) and O(n-square).
39. Given an array of characters. How would you reverse it. ? How would you reverse it without using indexing in the array.
40. Given a sequence of characters. How will you convert the lower case characters to upper case characters. ( Try using bit vector - solutions given in the C lib -typec.h)
41. Fundamentals of RPC.
42. Given a linked list which is sorted. How will u insert in sorted way.
43. Given a linked list How will you reverse it.
44. Give a good data structure for having n queues ( n not fixed) in a finite memory segment. You can have some data-structure separate for each queue. Try to use at least 90% of the memory space.
45. Do a breadth first traversal of a tree.
46. Write code for reversing a linked list.
47. Write, efficient code for extracting unique elements from a sorted list of array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9).
48. Given an array of integers, find the contiguous sub-array with the largest sum.
ANS. Can be done in O(n) time and O(1) extra space. Scan array from 1 to n. Remember the best sub-array seen so far and the best sub-array ending in i.
49. Given an array of length N containing integers between 1 and N, determine if it contains any duplicates.
ANS.
50. Sort an array of size n containing integers between 1 and K, given a temporary scratch integer array of size K.
ANS. Compute cumulative counts of integers in the auxiliary array. Now scan the original array, rotating cycles! [Can someone word this more nicely?
51. An array of size k contains integers between 1 and n. You are given an additional scratch array of size n. Compress the original array by removing duplicates in it. What if k << n?
ANS. Can be done in O(k) time i.e. without initializing the auxiliary array!
52. An array of integers. The sum of the array is known not to overflow an integer. Compute the sum. What if we know that integers are in 2's complement form?
ANS. If numbers are in 2's complement, an ordinary looking loop like for(i=total=0;i< n;total+=array[i++]); will do. No need to check for overflows!
53. An array of characters. Reverse the order of words in it.
ANS. Write a routine to reverse a character array. Now call it for the given array and for each word in it.
* 54. An array of integers of size n. Generate a random permutation of the array, given a function rand_n() that returns an integer between 1 and n, both inclusive, with equal probability. What is the expected time of your algorithm?
ANS. "Expected time" should ring a bell. To compute a random permutation, use the standard algorithm of scanning array from n downto 1, swapping i-th element with a uniformly random element <= i-th. To compute a uniformly random integer between 1 and k (k < n), call rand_n() repeatedly until it returns a value in the desired range.
55. An array of pointers to (very long) strings. Find pointers to the (lexicographically) smallest and largest strings.
ANS. Scan array in pairs. Remember largest-so-far and smallest-so-far.
Compare the larger of the two strings in the current pair with largest-so-far to update it. And the smaller of the current pair with the smallest-so-far to update it. For a total of <= 3n/2 strcmp() calls. That's also the lower bound.
56. Write a program to remove duplicates from a sorted array.
ANS. int remove_duplicates(int * p, int size)
{
int current, insert = 1;
for (current=1; current < size; current++)
if (p[current] != p[insert-1])
{
p[insert] = p[current];
current++;
insert++;
} else
current++;
return insert;
}
57. C++ ( what is virtual function ? what happens if an error occurs in constructor or destructor. Discussion on error handling, templates, unique features of C++. What is different in C++, ( compare with unix).
58. Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list).
59. Given 3 lines of assembly code : find it is doing. IT was to find absolute value.
60. If you are on a boat and you throw out a suitcase, Will the level of water increase.
61. Print an integer using only putchar. Try doing it without using extra storage.
62. Write C code for (a) deleting an element from a linked list (b) traversing a linked list
63. What are various problems unique to distributed databases
64. Declare a void pointer ANS. void *ptr;
65. Make the pointer aligned to a 4 byte boundary in a efficient manner ANS. Assign the pointer to a long number and the number with 11...1100 add 4 to the number
66. What is a far pointer (in DOS)
67. What is a balanced tree
68. Given a linked list with the following property node2 is left child of node1, if node2 < node1 else, it is the right child.
O P
|
|
O A
|
|
O B
|
|
O C
How do you convert the above linked list to the form without disturbing the property. Write C code for that.
O P
|
|
O B
/ \
/ \
/ \
O ? O ?
determine where do A and C go
69. Describe the file system layout in the UNIX OS
ANS. describe boot block, super block, inodes and data layout
70. In UNIX, are the files allocated contiguous blocks of data
ANS. no, they might be fragmented
How is the fragmented data kept track of
ANS. Describe the direct blocks and indirect blocks in UNIX file system
71. Write an efficient C code for 'tr' program. 'tr' has two command line arguments. They both are strings of same length. tr reads an input file, replaces each character in the first string with the corresponding character in the second string. eg. 'tr abc xyz' replaces all 'a's by 'x's, 'b's by 'y's and so on. ANS.
a) have an array of length 26.
put 'x' in array element corr to 'a'
put 'y' in array element corr to 'b'
put 'z' in array element corr to 'c'
put 'd' in array element corr to 'd'
put 'e' in array element corr to 'e'
and so on.
the code
while (!eof)
{
c = getc();
putc(array[c - 'a']);
}
72. what is disk interleaving
73. why is disk interleaving adopted
74. given a new disk, how do you determine which interleaving is the best a) give 1000 read operations with each kind of interleaving determine the best interleaving from the statistics
75. draw the graph with performance on one axis and 'n' on another, where 'n' in the 'n' in n-way disk interleaving. (a tricky question, should be answered carefully)
76. I was a c++ code and was asked to find out the bug in that. The bug was that he declared an object locally in a function and tried to return the pointer to that object. Since the object is local to the function, it no more exists after returning from the function. The pointer, therefore, is invalid outside.
77. A real life problem - A square picture is cut into 16 squares and they are
shuffled. Write a program to rearrange the 16 squares to get the original big square.
78.
int *a;
char *c;
*(a) = 20;
*c = *a;
printf("%c",*c);
what is the output?
79. Write a program to find whether a given m/c is big-endian or little-endian!
80. What is a volatile variable?
81. What is the scope of a static function in C ?
82. What is the difference between "malloc" and "calloc"?
83. struct n { int data; struct n* next}node;
node *c,*t;
c->data = 10;
t->next = null;
*c = *t;
what is the effect of the last statement?
84. If you're familiar with the ? operator x ? y : z
you want to implement that in a function: int cond(int x, int y, int z); using only ~, !, ^, &, +, |, <<, >> no if statements, or loops or anything else, just those operators, and the function should correctly return y or z based on the value of x. You may use constants, but only 8 bit constants. You can cast all you want. You're not supposed to use extra variables, but in the end, it won't really matter, using vars just makes things cleaner. You should be able to reduce your solution to a single line in the end though that requires no extra vars.
85. You have an abstract computer, so just forget everything you know about computers, this one only does what I'm about to tell you it does. You can use as many variables as you need, there are no negative numbers, all numbers are integers. You do not know the size of the integers, they could be infinitely large, so you can't count on truncating at any point. There are NO comparisons allowed, no if statements or anything like that. There are only four operations you can do on a variable.
1) You can set a variable to 0.
2) You can set a variable = another variable.
3) You can increment a variable (only by 1), and it's a post increment.
4) You can loop. So, if you were to say loop(v1) and v1 = 10, your loop would execute 10 times, but the value in v1 wouldn't change so the first line in the loop can change value of v1 without changing the number of times you loop.
You need to do 3 things.
1) Write a function that decrements by 1.
2) Write a function that subtracts one variable from another.
3) Write a function that divides one variable by another.
4) See if you can implement all 3 using at most 4 variables. Meaning, you're not making function calls now, you're making macros. And at most you can have 4 variables. The restriction really only applies to divide, the other 2 are easy to do with 4 vars or less. Division on the other hand is dependent on the other 2 functions, so, if subtract requires 3 variables, then divide only has 1 variable left unchanged after a call to subtract. Basically, just make your function calls to decrement and subtract so you pass your vars in by reference, and you can't declare any new variables in a function, what you pass in is all it gets.
* 86. Under what circumstances can one delete an element from a singly linked list in constant time?
ANS. If the list is circular and there are no references to the nodes in the list from anywhere else! Just copy the contents of the next node and delete the next node. If the list is not circular, we can delete any but the last node using this idea. In that case, mark the last node as dummy!
* 87. Given a singly linked list, determine whether it contains a loop or not.
ANS. (a) Start reversing the list. If you reach the head, gotcha! there is a loop!
But this changes the list. So, reverse the list again.
(b) Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. If the latter overtakes the former at any time, there is a loop!
p1 = p2 = head;
do {
p1 = p1->next;
p2 = p2->next->next;
} while (p1 != p2);
88. Given a singly linked list, print out its contents in reverse order. Can you do it without using any extra space?
ANS. Start reversing the list. Do this again, printing the contents.
89. Given a binary tree with nodes, print out the values in pre-order/in-order/post-order without using any extra space.
90. Reverse a singly linked list recursively. The function prototype is node * reverse (node *) ;
ANS.
node * reverse (node * n)
{
node * m ;
if (! (n && n -> next))
return n ;
m = reverse (n -> next) ;
n -> next -> next = n ;
n -> next = NULL ;
return m ;
}
91. Given a singly linked list, find the middle of the list.
HINT. Use the single and double pointer jumping. Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. When the double reaches the end, the single is in the middle. This is not asymptotically faster but seems to take less steps than going through the list twice.
92. Reverse the bits of an unsigned integer.
ANS.
#define reverse(x) \
(x=x>>16|(0x0000ffff&x)<<16, \
x=(0xff00ff00&x)>>8|(0x00ff00ff&x)<<8, \
x=(0xf0f0f0f0&x)>>4|(0x0f0f0f0f&x)<<4, \
x=(0xcccccccc&x)>>2|(0x33333333&x)<<2, \
x=(0xaaaaaaaa&x)>>1|(0x55555555&x)<<1)
* 93. Compute the number of ones in an unsigned integer.
ANS.
#define count_ones(x) \
(x=(0xaaaaaaaa&x)>>1+(0x55555555&x), \
x=(0xcccccccc&x)>>2+(0x33333333&x), \
x=(0xf0f0f0f0&x)>>4+(0x0f0f0f0f&x), \
x=(0xff00ff00&x)>>8+(0x00ff00ff&x), \
x=x>>16+(0x0000ffff&x))
94. Compute the discrete log of an unsigned integer.
ANS.
#define discrete_log(h) \
(h=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16), \
h=(0xaaaaaaaa&h)>>1+(0x55555555&h), \
h=(0xcccccccc&h)>>2+(0x33333333&h), \
h=(0xf0f0f0f0&h)>>4+(0x0f0f0f0f&h), \
h=(0xff00ff00&h)>>8+(0x00ff00ff&h), \
h=(h>>16)+(0x0000ffff&h))
If I understand it right, log2(2) =1, log2(3)=1, log2(4)=2..... But this macro does not work out log2(0) which does not exist! How do you think it should be handled?
* 95. How do we test most simply if an unsigned integer is a power of two?
ANS. #define power_of_two(x) \ ((x)&&(~(x&(x-1))))
96. Set the highest significant bit of an unsigned integer to zero.
ANS. (from Denis Zabavchik) Set the highest significant bit of an unsigned integer to zero
#define zero_most_significant(h) \
(h&=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16))
97. Let f(k) = y where k is the y-th number in the increasing sequence of non-negative integers with the same number of ones in its binary representation as y, e.g. f(0) = 1, f(1) = 1, f(2) = 2, f(3) = 1, f(4) = 3, f(5) = 2, f(6)
= 3 and so on. Given k >= 0, compute f(k).
98. A character set has 1 and 2 byte characters. One byte characters have 0 as the first bit. You just keep accumulating the characters in a buffer. Suppose at some point the user types a backspace, how can you remove the character efficiently. (Note: You cant store the last character typed because the user can type in arbitrarily many backspaces)
99. What is the simples way to check if the sum of two unsigned integers has resulted in an overflow.
100. How do you represent an n-ary tree? Write a program to print the nodes of such a tree in breadth first order.
101. Write the 'tr' program of UNIX. Invoked as
tr -str1 -str2. It reads stdin and prints it out to stdout, replacing every occurance of str1[i] with str2[i].
e.g. tr -abc -xyz
to be and not to be <- input
to ye xnd not to ye <- output

发表于 2008-08-01 15:59 lostpencil 阅读(3241) | 评论 (5)编辑 收藏

2008年7月3日

起因:Python django web框架只能解析UTF-8的中文模板,于是我就建了html文件,用记事本打开,另存为UTF-8的形式。结果奇怪的问题就出现了,css文件布局网页的时候老是达不到预期的效果。

CSS也不太熟悉,一直以为是CSS理解错了,确认没有错后,还是没有改观,察看动态生成的网页的源码,也没有任何问题。打算放弃的时候,侥幸的保存了源码,然后用editplus打开,发现html文件开头多了一个问号(用微软的所有工具打开都没有这个问号)。

最近时间不多,就不罗嗦了:
类似WINDOWS自带的记事本等软件,在保存一个以UTF-8编码的文件时,会在文件开始的地方插入三个不可见的字符(0xEF 0xBB 0xBF,即BOM)。它是一串隐藏的字符,用于让记事本等编辑器识别这个文件是否以UTF-8编码。对于一般的文件,这样并不会产生什么麻烦。但对于Python或者PHP来说,BOM就是一个问题了。他们都不会忽略BOM, 然后在html文件的开头就多了那几个字符,editplus解析不了就显示成问号了,然后网页就不符合规范了,CSS的布局就有了问题,然后我就痛苦了。

我的解决办法:
最开始是自己写了个小程序把那串东西去掉了,后来发现原来UltraEdit支持无BOM的形式的保存........

真后悔最开始懒了,没有直接装linux服务器。

发表于 2008-07-03 08:13 lostpencil 阅读(1867) | 评论 (2)编辑 收藏

2008年5月6日

目的: 工作需要,从一个.P12或者pfx文件里面取得证书的内容,因为有个接口需要一个这样的证书字符串.

于是我这么写了:
 //取得服务器证书
 X509 *cert2;
 EVP_PKEY *pkey2=NULL;
 STACK_OF(X509) *server = NULL;
 BIO * in2 = BIO_new_file("server.pfx","rb");
 PKCS12 *p122 = d2i_PKCS12_bio(in2,NULL);
 PKCS12_parse(p122, "123456", &pkey2, &cert2, &server);
 *servercertLen = i2d_X509(cert2,&servercert);
 本来打算把servercert 和servercertLen作为证书字符串的衡量标准,传给那个接口,结果呢,TMD死活就是不对,servercert就是没有我要的东西.

反反复复的debug,找不到哪里出了问题,前面都是对的,就是到了最后一步servercert里面的东西就不对了,openssl的文档也被读烂了,啥也没说,有点想砸了电脑自杀了.

最后我就想啊想啊,因为知道openssl里面好多函数都是用宏实现的,是不是在i2d_X509里面改变了servercert的指向呢,虽然觉得比较荒唐,但是杨老师在他的COM系列文章里面讲过:有些看似不和规范和习惯的用法,在方方面面都有着运用的.

报着试试的态度在程序后面加了这么句:
servercert = servercert -*servercertLen;

结果TMD真的就好了,但是已经过了20个小时了.

罗嗦半天,要说的其实就是一句话: i2d_X509会改变第2个参数的指针,增加了一个证书内容的长度.

注:TMD是"甜蜜的"意思,不是说脏话,:)

发表于 2008-05-06 22:52 lostpencil 阅读(2261) | 评论 (2)编辑 收藏

2007年10月15日

起因:上研究生的表弟突然问我“你觉得你的付出和收获成正比吗?”

仔细想想,常常的郁闷也是因为心里不平衡吧。最后为了充过来人,我的回答是:
貌一看肯定是完全不成,但是仔细想想还是收获大于付出了
人和人竞争不光是100分的,你多付出的得到的是100分以外的东西
在100分以内,我们的3倍付出可能是1%的收获或者是0收获,拿你们考试来说也就是80分和81分的区别,但是有朝一日竞争需要考虑100分以外的东西了,你的优势就很明显了。
感觉工作也是,也许拼命了也不会涨工资或者得到肯定,但是总有一天还是会有回报的。毕竟工作一放松,整个人也就难紧张起来了。

发表于 2007-10-15 17:55 lostpencil 阅读(3591) | 评论 (5)编辑 收藏

2007年9月15日

起因:目前可以看到的所有介绍django的资料都是太详细,需要很久才能有一个整体的印象,本文意图是从整体上简单说下django的结构,方便学习者早点上手。

django是一个MVC(Model View Controller)模式的web开发框架。不过在这里它对应于MVC变成了MTV(Model Template View), Model主要是和数据库的表对应的,通过访问Model可以很容易的操作数据库;Template是不完全的html页面,它支持继承扩展等功能;View是一个控制器,也就是网站每个模块的逻辑部分。

一般网站的django结构(我一般画的图比较烂就不画图了):
主目录,都是创建工程时自动生成的一些东西,它包括如下东西:
  __init__.py   作用同于python模块内的init
  manage.py    一个脚本的接口,通过调用它对整个系统管理,增加一个模块,或者是手动更新数据库等等
  settings.py     在这里进行系统相关的设置
  urls.py           在这里用正则表达式的方式,将URL和View进行匹配。
一个关于结构的例子:比如你有一个简单的网站,有3个部分,一个是主页,一个是登陆,还有一个是产品。你首先创建一个主的project,然后可以在里面创建mainpage,login, product三个模块,通过主目录下面的urls.py将每个模块和相应的URL匹配。在每个模块下面会有自己的model和view.至于Template,你可以放在任何位置,只要在setting.py中指定好路径就可以了。

Model介绍
django通过Model文件直接帮定数据库的表,然后提供一系列的api对相应的Model对象操作,这样避免的自己写SQL语句,如果你不是数据库专家,它内部生成的SQL语句效率一般都比你写的高。 一个简单的例子:比如你想在数据库中建立一张表,你只需要在相应模块的models.py文件中加入,
from django.db import models

class xxxx(models.Model):
    name = models.CharField(maxlength=30)
    address = models.CharField(maxlength=50)
然后执行下脚本,就搞定了,然后你就可以通过这个class对象对数据库进行操作。

Template介绍
template实际就是一个html文件,但是不是一个完全合法html文件,它相当于c++里面的模板类,通过给他不同的参数,然后他就解析成不同的html文件,而且它也支持继承。一个Template B继承另一个Template A简单的说就是,B是A的扩展,可以在B中对A中的“block”处丰富化。template文件内的变量通过{{ xxx}}的方式定义,你只要在view.py中调用相应的函数给xxx指定值,就能得到一个完整的html文件。template也可以有逻辑控制,它通过{%  xxx  %}来定义,常见的逻辑控制都可以写在xxx的位置处。
{% for item in todo_list %}
    <p>{{ forloop.counter }}: {{ item }}</p>
{% endfor %}
(继承的例子比较占篇幅就不写了,反正到处都可以找到)

View介绍
view的作用就是接受一个request然后,对request进行处理,返回一个html页面或者是一个URL跳转等,主要就是根据网页的作用来编写逻辑处理了。一个例子:
from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)
一个打印当前时间的小view.py文件,当然这里你想干什么都可以的,只要没有人K你,:)

其他说明
前面说的只是django的一个大体结构,实际上每个部分都有一些高级运用,还有一些Middleware (功能已经很全面了),Caching (提高效率的好帮手)等
。django的口号是,一个星期就能搞定一个大中型网站(个人感觉熟练的话肯定没有问题),如果想进一步了解的话上www.djangoproject.com和www.djangobook.com,国内目前也有一些人翻译了一些资料可以参考。
学习前提:了解网站的原理+了解python的基础知识。




发表于 2007-09-15 12:28 lostpencil 阅读(3148) | 评论 (2)编辑 收藏

2007年9月13日

起因:辞职到处奔波了几个月,服务器也挂了不短的时间,加上驱动问题笔记本装linux比较麻烦,总之是一直没有linux用,很是不方便。

解决方案:
step 1: 让DOS窗口支持常用的linux命令。
这里首选的当然是cygwin了,这类的东西不大,官网上都能下载,一般也就是名字后面+.org搞定。装好后在环境变量的path里面加入bin的路径,就可以轻松的在DOS窗口使用大多数常用的命令了,要是感觉DOS不爽,也可以直接敲bash启动bash,和linux的差别就更小了,当然你可能无法使用vi/vim等一些小工具,自己去淘了,然后加进去都可以用。

step 2: GCC组件的安装
可能我们不太习惯VS系列的产品,当然我觉得他们做的非常成功的,费用是一个问题,还有就是不熟的话大多数情况扮演了杀鸡的牛刀的角色。图简便的话就是MinGW算了,网速不行的话就自己下包一个个的整了,在线安装会比较慢,而且出问题也不好分析解决。这里不推荐dev-c++了,一个不太美观和科学的UI层严重影响了它的使用(个人看法)。

step 3: IDE的安装
IDE虽然不常用了,但是有时候还是需要的,感觉几年前除了VS,在windows下也没有什么太好的选择,前面说过dev-C++也不怎么欣赏,现在那就eclipse吧,总的来说eclipse的设计和实用性还是相当到位的,目前也运用的越来越广,特别是java社群。当然它目前已经不在是一个简单的java的开发工具了,比如你想支持c/C++只要去当一个CDT,解压后将插件和特性的东西加到eclipse下对应的目录就可以了。eclipse主页也有直接打包好的东西可以用,当然它的运行需要jdk的支持,你也需要配置一些环境变量,都很简单的,网上文章比较多。顺便说一下其实eclipse插件开发是一件很有意思,也比较高效的事情,这玩艺应该很有前途吧。

现在我的windows就一个开发人员的日常使用来说已经和linux没有什么区别了,不过没有少折腾,大的方面也就这么几块吧,呵呵

发表于 2007-09-13 00:55 lostpencil 阅读(3260) | 评论 (6)编辑 收藏

2007年8月30日

题目:数据库里面有一个表如下
a(int) | b(int)
      1|       2
      3|       4
      5|       6
..................
希望根据该表生成一个新表如下
c(int)






......
要求:
1数据量很大,对效率要求比较高,希望用批处理的方式搞定
2对空间没有要求,允许创建中间表甚至是物理表

解答:
1 取出a列,加一个id列,生成中间表c1,id列为1开头步长为2的整数,也就是1 3 5 7......

2 同样取出b列,加一个id列,生成中间表c2, 2开头步长是2的整数,也就是2 4 6 8......

3 合并c1,c2为c

点评:没有太大的新意,软件开发灵感很重要吧

发表于 2007-08-30 04:38 lostpencil 阅读(3982) | 评论 (4)编辑 收藏

题目:有一个数组里面里面的元素是0和非0的整数字混排,希望进行排序后所有的0放在数组前端,所有非0数字顺序不变放在数组后端.(主要考思维吧)
要求:
1,不能增加新的缓存(也就是不能用另外的数组或者字符串等结构来存储中间结果).
2,只能用一次单循环.


分析:1,因为上述两个要求,则只能在循环到每个元素的时候就把它放到正确的位置.
   2,对于结果数组来说,有效的是非0数和其顺序,0没有意义.
   3,按照常规思维来做其实不是很好想,虽然感觉答案就在眼前但是始终不好确定,特别是在面试这种相对有点压力的情况下(考官眼巴巴的望着你,根本就不好意思想很久),换另外一个题“非0数放前面,0放后面”就简单的多了。
算法:判断当次循环的数,非0的话就移动到非零数个数的位置,然后将这个数赋0,0就不用管了。
解答:假设数组arr[length],定义一个变量a,记录当前循环所遇见的非0数的个数,
a=0;
for(i=0;i<length;i++){
  if(0!=arr[i]){
           arr[a] = arr[i];
           arr[i] = 0;
            ++a;
  }
}
这样比较简单的思维就搞定了,非0放后面的话无非就是数组的反序循环了.
点评:感觉题目难就难在很难想到要反序循环数组,紧张的情况下思维也没有这么明了,容易按常规乱试,感觉就快出来了,但是始终有点不对。
(我当时是急发汗了)

发表于 2007-08-30 04:09 lostpencil 阅读(6869) | 评论 (28)编辑 收藏