Wednesday, March 24, 2010

Static variable inside a function

int nonestatic_var_Test(void)
{
int number_of_times=0;

for(int y=0; y<10; y++)
{
number_of_times++;
}

return number_of_times;

}


int static_var_Test(void)
{
static int static_number_of_times = 0;

for(int y=0; y<10; y++)
{
static_number_of_times++;
}

return static_number_of_times;

}


int main()
{

int i;
int func_invoke_times;

for(i=0;i<10;i++)
func_invoke_times=static_var_Test();

printf("static_func_invoke_times is %d\n",func_invoke_times);

for(i=0;i<10;i++)
func_invoke_times=static_var_Test();
printf("static_func_invoke_times is %d\n",func_invoke_times);

for(i=0;i<10;i++)
func_invoke_times=nonestatic_var_Test();

printf("nonstatic_func_invoke_times is %d\n",func_invoke_times);

for(i=0;i<10;i++)
func_invoke_times=nonestatic_var_Test();
printf("nonstatic_func_invoke_times is %d\n",func_invoke_times);

}





result:

static_func_invoke_timers is 100
static_func_invoke_timers is 200
nonstatic_func_invoke_timers is 10
nonstatic_func_invoke_timers is 10

Tuesday, November 17, 2009

FW: How to copy arrays and objects in Javascript

from: http://my.opera.com/GreyWyvern/blog/show.dml/1725165

How to copy arrays and objects in Javascript

Friday, 8. February 2008, 01:29:48

object, tip, clone, copy, array, javascript
There are a few things that trip people up with regards to Javascript. One is the fact that assigning a boolean or string to a variable makes a copy of that value, while assigning an array or an object to a variable makes a reference to the value. The trouble this causes can range from befuddlement - when two variables you assume are separate are in fact references to the same value - to frustration when you realize there is no native way to tell the Javascript engine to pass a value rather than a reference.

In PHP, for example, all assignments make copies unless you explicitly tell the engine to pass a reference using the =& operator. If only it were so simple in Javascript.

I'm pretty much reinventing the wheel with this post since this issue has been solved before, but the reason I'm writing it is because up until recently I had always been designing custom functions to copy objects of types I designed myself. Very efficient on a per-case basis, but not very reusable. There had to be a way to make such a thing work for any and all arrays and objects. So I searched the interwebs and was enlightened.

Firstly, arrays. Surprisingly, arrays are easy to copy because a couple of native Array object methods actually return a copy of the array. The easiest to use is the slice() method:

var foo = [1, 2, 3];
var bar = foo;
bar[1] = 5;
alert(foo[1]);
// alerts 5

var foo = [1, 2, 3];
var bar = foo.slice(0);
bar[1] = 5;
alert(foo[1]);
// alerts 2


The slice(0) method means, return a slice of the array from element 0 to the end. In other words, the entire array. Voila, a copy of the array. The only caveat to remember here is that this method works if the array contains only simple data types, like numbers, strings and booleans. If the array contains objects or other arrays (a multi-dimensional array), then those contained "objects" will be copied by reference, retaining a connection with the source array. In such a case you will need to copy the array as a full-fledged object.

Objects are trickier because there is no native method which returns a copy of the object. So instead we add one ourselves using a prototype method:

Object.prototype.clone = function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i == 'clone') continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
} else newObj[i] = this[i]
} return newObj;
};


Notice the recursion going on; isn't it divine? :smile: The clone() method steps through the properties of any object one by one. If the property is itself an object or array, it calls the clone() method on that object too. If the property is anything else, it just takes the value of the property. Then the result received is assigned to a property of the same name in a new object.

Finally, after we're done stepping through all properties, return the new object which is a copy of - not a reference to - the old object. A call to the clone method is as simple as this:

var foo = {a: 1, b: 2, c: 3};
var bar = foo;
bar.b = 5;
alert(foo.b);
// alerts 5

var foo = {a: 1, b: 2, c: 3};
var bar = foo.clone();
bar.b = 5;
alert(foo.b);
// alerts 2

Monday, November 2, 2009

Forms' element samples (checkbox,radio,select,option)

[HTML>
[HEAD>
[TITLE>Checkbox Inspector[/TITLE>
[SCRIPT LANGUAGE="JavaScript">
function inspectBox() {
if (document.forms[0].checkThis.checked) {
alert("The box is checked.")
} else {
alert("The box is not checked at the moment.")
}
}


function inspectRadio() {
for (var i = 0; i [ document.forms[0].sex.length; i++) {
if (document.forms[0].sex[i].checked) {
break
}
}
alert("You chose " + document.forms[0].sex[i].value + ".")
}


function verifySong(entry) {
var song = entry.value
alert("Checking whether " + song + " is a Beatles tune...")
}


function showCarSelected() {
var list = document.forms[0].carSelect
alert("SelectIndex="+list.selectedIndex+" Value="+list.options[list.selectedIndex].value+" "+list.options[list.selectedIndex].text+" Car is selected.");
}


function checkAll(field)
{
for (i = 0; i [ field.length; i++)
field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i [ field.length; i++)
field[i].checked = false ;
}

[/SCRIPT>
[/HEAD>
[BODY>
[FORM>
[INPUT TYPE='checkbox' NAME='checkThis' onClick='javascript:inspectBox()'>Check here[BR>

[input type="radio" name="sex" value="male" onClick='javascript:inspectRadio()' > Male
[br />
[input type="radio" name="sex" value="female" onClick='javascript:inspectRadio()'> Female
[br>

[INPUT TYPE="text" NAME="song" VALUE = "Eleanor Rigby" onChange="verifySong(this)">[P>


[select name="carSelect" onChange="showCarSelected()" >
[option value="0" >Volvo[/option>
[option value="1" >Saab[/option>
[option >Mercedes[/option>
[option selected >Audi[/option>
[/select>


[/FORM>

[form name="myform" action="checkboxes.asp" method="post">

[b>Your Favorite Scripts & Languages[/b>[br>
[input type="checkbox" name="list" value="1">Java[br>
[input type="checkbox" name="list" value="2">Javascript[br>
[input type="checkbox" name="list" value="3">Active Server Pages[br>
[input type="checkbox" name="list" value="4">HTML[br>
[input type="checkbox" name="list" value="5">SQL[br>

[input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.myform.list)">
[input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.myform.list)">
[br>
[/FORM>
[/BODY>
[/HTML>

Thursday, October 22, 2009

转:PHP网站开发方案(开发新人必读)

PHP网站开发方案(开发新人必读)
发布时间:2009-9-18 11:30  作者: php.cn  信息来源: PHPchina  发表评论
一、开发成员

a)项目主管
b)页面美工
c)页面开发
d)服务端程序开发
e)系统与数据管理
f)测试与版本控制

二、 网站组开发简明流程


三、 开发工具与环境

a)服务器配置
i. WEB服务器: FreeBSD6.1+Apache2.0+PHP5.0,SVN版本控制服务(仅测试机)。
ii.数据库服务器: WIN2003 server+SQL server 2000+MySQL5.0,CLUSTERED SERVER 集群服务,邮件服务器。
iii. 100M/1000M交换机
b) 开发工具
i. 前台: Macromedia flash 8.0、Macromedia Dreamweaver 8.0、Adobe photoshop CS
ii. 后台: Zend Studio 5.2、SQL Server Enterprise Manager、PhpMyAdmin

四、 技术规则

a) 浏览器兼容策略: 兼容IE5.0以上版本,同时兼容FireFOX2.0以上浏览器。
b) 搜索引擎优化: 着重针对baidu、Google、Yahoo搜索优化,制作清晰明确的网站地图。
c) 字符编码规则:中文网站一率采用GB2312字符标准。[目前我统一使用UTF-8编码包括了数据库的文件内容的编码统一]
d) 文件与文件夹命名: 为兼容win32与unix系统,一率采用小写字母命名。
(统一全站的文件夹与文件的命名都使用小写的形式处理。这样不会出现问题了!)
e) 公共文件命名规则:
i. 默认首页: index.htm、index.html、index.php
ii. 主CSS文件: style.css
iii. 主JS文件: main.js
iv. 主程序配置文件:config.php
f) 公共文件目录统一命名
i. 图片目录: /images 或者 /pic
ii. CSS样式目录: /css
iii. JS脚本程序目录:/js
iv.模板文件目录:/tpl
v. 类或者组件目录:/class 或者 /lib
g) 页面脚本规范: 统一采用JavaScript
h)代码中的类、函数、变量名:统一使用近似英文单词命名,如:DefaultClass 或者 default_class
i) 代码注释规则:所有程序中的函数或者过程必须加确切的注释。
j) 数据库相关规则
i. 数据表与字段命名规则: 全部小写字母命名,并归类命名前缀,如:用户表组,user_passport、user_info、user_service….
ii. 日期类型字段: 统一使用unix时间戳,char(12)
iii. 主关键字命名: 所有表必须建立以id命名的主键。
k) 模板组件规则:统一使用兼容版本的Smarty,统一缓存目录,便于Unix下权限控制。
(设置全部的可写文件统一放入到一个目录下面去做成缓存目录用)
l) 数据库虚拟层: 统一使用Adodb 或 Pdo,SQL语句要兼容现有主流数据库规则。
m)工厂模式开发规则: 以comm.php为中心开发或继承组件类,统一控制文件调用IO与类的实例化。
n) 面向对象开发规则: 所有函数必须以类 ---> 过程的方式存在。
(学会封装代码成类的形式出现)
o) SQL封装规则: 所有SQL语句及数据库查询必须存在于过程中。

p) URL转向规则: 为优化搜索引擎,尽量使用Apache的mod_rewrite模块来美化URL,如:http://www.yourname.com/action.php?id=123转化为:http://www.yourname.com/action/id/123或者http://www.yourname.com/action/id_123.html


五、 网站安全与维护策略

a) 服务器与数据库安全:
i. 建立完善的病毒防御机制,安装防火墙,关闭服务器上任何不必要的端口以及服务。
ii. 统一管理用户权限,定期跟踪用户及系统事件,定期查看系统日志。
b) 容灾与备份机制:
i. 建立数据库集群,至少保持一台服务器同步数据,确保意外发生时数据库系统可自动转移到正常的服务器稳定运行。
ii. 定期备份文件及数据,通过各种方式保存数据与文件。
c) 程序安全策略:
i. SQL注入防范:坚决过滤不可预见的非法字符,严格做好数据库查询、更新的SQL语句检验。
ii. 不使用来路不明的第三方源码,不轻易将未知代码拷贝到服务器。

TAG: 新人 网站开发 PHP php 方案

Tuesday, October 20, 2009

Convert binary file to ASCII file

/************************************************/
/* Convert binary file to ASCII file */
/************************************************/


#include < D:/VC6Green/VC98/Include/math.h>
#include < D:/VC6Green/VC98/Include/stdio.h>
#include < D:/VC6Green/VC98/Include/string.h>



void __ConvertBinFile_To_ASCIIFile(void *ptrInRd, void *ptrOutWr)
{
unsigned char lcByteIn,i;
FILE *ptrRd,*ptrWr;

ptrRd=(FILE *)(ptrInRd);
ptrWr=(FILE *)(ptrOutWr);


i=0;

fprintf(ptrWr, " ");

while (1)
{
lcByteIn = fgetc(ptrRd);
if(feof(ptrRd)!=0)
break;
printf("%02X ",lcByteIn); /* O/P the character to the screen */
fprintf(ptrWr, "%02X ",lcByteIn);
i++;
if (i==16)
{
printf("\n");
fprintf(ptrWr, "\n ");
i=0;
}
}

fclose(ptrRd); /* Close the file. */
fclose(ptrWr); /* Close the file. */

printf("\n");
printf("////////////Done Bin To ASCII conversion //////////// \n");

}




main()
{
FILE *fileRdPtr, *fileWrtPtr;

/* Open Binary file for output. */
fileWrtPtr = fopen("Result.txt","w");
fileRdPtr = fopen("BinaryFile2Convert.bin", "rb");

if(fileRdPtr==NULL)
{
printf("Could not find input binary file: BinaryFile2Convert.bin \n");
return 0;
}

printf("Pls make sure binary input file is using file name: 'BinaryFile2Convert.bin'. Output file is: 'Result.txt'\n");


__ConvertBinFile_To_ASCIIFile(fileRdPtr,fileWrtPtr);

return 0;


}

Tuesday, October 6, 2009

java socket comms

/**
* SimpleSocketClient.java
*
* Created on October 2, 2002, 5:34 PM
*/

import java.awt.*;
import java.net.*; //contains socket class
import java.io.*; //The java.io package provides input and output classes that we will use to extract the data from the response

import java.applet.Applet;


/**
*
* @author Stephen Potts
*/
public class AppletSocketClient // extends Applet

{
Socket socket1;
int portNumber = 20000;
String str = "";


ObjectInputStream ois;

InputStream istream;
OutputStream ostream;

byte[] theByteArray;

/** Creates a new instance of AppletSocketClient */
public AppletSocketClient()
{



try
{


// socket1 = new Socket(InetAddress.getLocalHost(), portNumber);

socket1 = new Socket("192.168.0.201", portNumber);

// socket1 = new Socket("192.168.0.201", portNumber,"192.168.0.1", 8000);

System.out.println("--Debug: build socket ");

istream=socket1.getInputStream();

// ois = new ObjectInputStream(istream);

System.out.println("--Debug: build input stream ");

ostream=socket1.getOutputStream();

// ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream());

System.out.println("--Debug: build output stream ");

str = "initialize";

System.out.println("--Debug: about to send string "+str);

theByteArray=str.getBytes();

ostream.write(theByteArray);

// oos.writeObject(str);

// System.out.println("--Debug: out string"+str);;
//
// str = (String) ois.readObject();
//
// System.out.println("--Debug: input string"+str);
//
// oos.writeObject("bye");



// while ((str = (String) ois.readObject()) == null);

// while ((str = (String) ois.readObject()) != null)
// {
// System.out.println(str);
// oos.writeObject("bye");
//
// if (str.equals("bye bye"))
// break;
// }

System.out.println("--Debug:ois close, oos close, socket close");

// ois.close();
// oos.close();
socket1.close();

} catch (Exception e)
{
System.out.println("Exception " + e);
}
}

public void paint(Graphics g)
{
g.drawString("Hello, Applet", 10, 10);
}


public static void main(String args[])
{
System.out.println("--Debug: main start ");

AppletSocketClient lsp = new AppletSocketClient();
}

}



++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

/*
* LoopingSocketServer.java
*
* Created on October 2, 2002, 5:24 PM
*/

import java.net.*;
import java.io.*;

/**
*
* @author Stephen Potts
*/
public class AppSocketServer
{
ServerSocket servSocket;
Socket fromClientSocket;
int cTosPortNumber = 20000;
String str;


/** Creates a new instance of LoopingSocketServer */
public AppSocketServer()
{
// Create ServerSocket to listen for connections
try
{
servSocket = new ServerSocket(cTosPortNumber);

// Wait for client to connnect, then get Socket
System.out.println("ServerSocket created");
System.out.println("Waiting for a connection on " + cTosPortNumber);

fromClientSocket = servSocket.accept();
System.out.println("fromClientSocket accepted");

// Use ObjectOutputStream to send String to the client
ObjectOutputStream oos =
new ObjectOutputStream(fromClientSocket.getOutputStream());

//Use ObjectInputStream to get String from client
ObjectInputStream ois =
new ObjectInputStream(fromClientSocket.getInputStream());


while ((str = (String) ois.readObject()) != null)
{
System.out.println("The message from client is *** " + str);

if (str.equals("bye"))
{
oos.writeObject("bye bye");
break;
}
else
{
str = "Server returns " + str;
oos.writeObject(str);
}

}
oos.close();

// Close Sockets
fromClientSocket.close();
} catch (Exception e)
{
System.out.println("Exception " + e);
}
}

public static void main(String args[])
{
AppSocketServer lss = new AppSocketServer();
}


}

Tuesday, September 1, 2009

MiMe header from HTTP Server

// Sample MiMe Header:
// HTTP/1.1·200·OK(CR)(LF)
// Date:·Wed,·02·Sep·2009·04:51:49·GMT(CR)(LF)
// Server:·Apache/2.0.52·(Red·Hat)(CR)(LF)
// Last-Modified:·Mon,·15·Nov·2004·18:23:08·GMT(CR)(LF)
// ETag:·"179c2-1ca39-21dc1b00"(CR)(LF)
// Accept-Ranges:·bytes(CR)(LF)
// Content-Length:·117305(CR)(LF)
// Connection:·close(CR)(LF)
// Content-Type:·application/x-rpm(CR)(LF)
// (CR)(LF)
//
// Faked MiMe Header:
// HTTP/1.1·200·OK0D0A
// Server:·CableTrackerIChip0D0A
// Accept-Ranges:·bytes0D0A
// Content-Length:·xxxx0D0A
// Connection:·close0D0A
// Content-Type:·application/octet-stream0D0A
// 0D0A

//

// HTTP/1.1·200·OK
// Server:·CableTrackerIChip
// Accept-Ranges:·bytes
// Content-Length:·xxxx
// Connection:·close
// Content-Type:·application/octet-stream