many people have heard that you can't override a static method. this is true - you can't. however it is possible to write code like this:
class foo {
public static void method() {
system.out.println("in foo");
}
}
class bar extends foo {
public static void method() {
system.out.println("in bar");
}
}
this compiles and runs just fine. isn't it an example of a static method overriding another static method? the answer is no - it's an example of a static method hiding another static method. if you try to override a static method, the compiler doesn't actually stop you - it just doesn't do what you think it does.
so what's the difference?
briefly, when you override a method, you still get the benefits of run-time polymorphism, and when you hide, you don't. so what does that mean? take a look at this code:
class foo {
public static void classmethod() {
system.out.println("classmethod() in foo");
}
public void instancemethod() {
system.out.println("instancemethod() in foo");
}
}
class bar extends foo {
public static void classmethod() {
system.out.println("classmethod() in bar");
}
public void instancemethod() {
system.out.println("instancemethod() in bar");
}
}
class test {
public static void main(string[] args) {
foo f = new bar();
f.instancemethod();
f.classmethod();
}
}
if you run this, the output is
instancemethod() in bar classmethod() in foo
why do we get instancemethod from bar, but classmethod() from foo? aren't we using the same instance f to access both of these? yes we are - but since one is overriding and the other is hiding, we see different behavior.
since instancemethod() is (drum roll please...) an instance method, in which bar overrides the method from foo, at run time the jvm uses the actual class of the instance f to determine which method to run. although f was declared as a foo, the actual instance we created was a new bar(). so at runtime, the jvm finds that f is a bar instance, and so it calls instancemethod() in bar rather than the one in foo. that's how java normally works for instance methods.
with classmethod() though. since (ahem) it's a class method, the compiler and jvm don't expect to need an actual instance to invoke the method. and even if you provide one (which we did: the instance referred to by f) the jvm will never look at it. the compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. since f is declared as type foo, the compiler looks at f.classmethod() and decides it means foo.classmethod. it doesn't matter that the instance reffered to by f is actually a bar - for static methods, the compiler only uses the declared type of the reference. that's what we mean when we say a static method does not have run-time polymorphism.
because instance methods and class methods have this important difference in behavior, we use different terms - "overriding" for instance methods and "hiding" for class methods - to distinguish between the two cases. and when we say you can't override a static method, what that means is that even if you write code that looks like it's overriding a static method (like the first foo and bar at the top of this page) - it won't behave like an overridden method.
so what about accessing a static method using an instance?
it's possible in java to write something like:
f.classmethod();
where f is an instance of some class, and classmethod() is a class method (i.e. a static method) of that class. this is legal, but it's a bad idea because it creates confusion. the actual instance f is not really important here. only the declared type of f matters. that is, what class is f declared to be? since classmethod() is static, the class of f (as determined by the compiler at compile time) is all we need.
rather than writing:
f.classmethod();it would be better coding style to write either:
foo.classmethod();or
bar.classmethod();that way, it is crystal clear which class method you would like to call. it is also clear that the method you are calling is indeed a class method.
barring that, you could always come up with this monstrosity:
f.getclass().getmethod("classmethod", new class[]).invoke(null, new object[]);
but all this could be avoided by simply not trying to override your static (class) methods. :-)
why does the compiler sometimes talk about overriding static methods?
sometimes you will see error messages from the compiler that talk about overriding static methods. apparently, whoever writes these particular messages has not read the java language specification and does not know the difference between overriding and hiding. so they use incorrect and misleading terminology. just ignore it. the java language specification is very clear about the difference between overriding and hiding, even if the compiler messages are not. just pretend that the compiler said "hide" rather than "override"..
ref: http://www.coderanch.com/how-to/java/overridingvshiding
var id = settimeout(fn, delay);
– initiates a single timer which will call the specified function after the delay. the function returns a unique id with which the timer can be canceled at a later time.var id = setinterval(fn, delay);
– similar to settimeout
but continually calls the function (with a delay every time) until it is canceled.clearinterval(id);
, cleartimeout(id);
– accepts a timer id (returned by either of the aforementioned functions) and stops the timer callback from occurring.in order to understand how the timers work internally there’s one important concept that needs to be explored: timer delay is not guaranteed. since all javascript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there’s been an opening in the execution. this is best demonstrated with a diagram, like in the following:
there’s a lot of information in this figure to digest but understanding it completely will give you a better realization of how asynchronous javascript execution works. this diagram is one dimensional: vertically we have the (wall clock) time, in milliseconds. the blue boxes represent portions of javascript being executed. for example the first block of javascript executes for approximately 18ms, the mouse click block for approximately 11ms, and so on.
since javascript can only ever execute one piece of code at a time (due to its single-threaded nature) each of these blocks of code are “blocking” the progress of other asynchronous events. this means that when an asynchronous event occurs (like a mouse click, a timer firing, or an xmlhttprequest completing) it gets queued up to be executed later (how this queueing actually occurs surely varies from browser-to-browser, so consider this to be a simplification).
to start with, within the first block of javascript, two timers are initiated: a 10mssettimeout
and a 10ms setinterval
. due to where and when the timer was started it actually fires before we actually complete the first block of code. note, however, that it does not execute immediately (it is incapable of doing that, because of the threading). instead that delayed function is queued in order to be executed at the next available moment.
additionally, within this first javascript block we see a mouse click occur. the javascript callbacks associated with this asynchronous event (we never know when a user may perform an action, thus it’s consider to be asynchronous) are unable to be executed immediately thus, like the initial timer, it is queued to be executed later.
after the initial block of javascript finishes executing the browser immediately asks the question: what is waiting to be executed? in this case both a mouse click handler and a timer callback are waiting. the browser then picks one (the mouse click callback) and executes it immediately. the timer will wait until the next possible time, in order to execute.
note that while mouse click handler is executing the first interval callback executes. as with the timer its handler is queued for later execution. however, note that when the interval is fired again (when the timer handler is executing) this time that handler execution is dropped. if you were to queue up all interval callbacks when a large block of code is executing the result would be a bunch of intervals executing with no delay between them, upon completion. instead browsers tend to simply wait until no more interval handlers are queued (for the interval in question) before queuing more.
we can, in fact, see that this is the case when a third interval callback fires while the interval, itself, is executing. this shows us an important fact: intervals don’t care about what is currently executing, they will queue indiscriminately, even if it means that the time between callbacks will be sacrificed.
finally, after the second interval callback is finished executing, we can see that there’s nothing left for the javascript engine to execute. this means that the browser now waits for a new asynchronous event to occur. we get this at the 50ms mark when the interval fires again. this time, however, there is nothing blocking its execution, so it fires immediately.
let’s take a look at an example to better illustrate the differences betweensettimeout
and setinterval
.
these two pieces of code may appear to be functionally equivalent, at first glance, but they are not. notably the settimeout
code will always have at least a 10ms delay after the previous callback execution (it may end up being more, but never less) whereas the setinterval
will attempt to execute a callback every 10ms regardless of when the last callback was executed.
there’s a lot that we’ve learned here, let’s recap:
settimeout
and setinterval
are fundamentally different in how they execute asynchronous code.all of this is incredibly important knowledge to build off of. knowing how a javascript engine works, especially with the large number of asynchronous events that typically occur, makes for a great foundation when building an advanced piece of application code.
from:
但苹果电脑 mac os x 10.6.5 系统做出了一项意义重大的升级:支持 exfat 磁盘格式,格式化成 exfat 格式的 u 盘、移动硬盘在 windows pc 上和苹果电脑 mac os x 系统下均能读写,而且支持超过单个体积超过 4 gb 的大文件。
下面是将 u 盘、移动硬盘格式化成 exfat 格式的方法,以及 exfat、fat32、hfs+ 三种格式下同一块 u 盘的读写速度测试
点击苹果电脑屏幕右上角的放大镜按钮,sportlight 搜索“磁盘工具”,在磁盘工具侧边栏选择要格式化的 u 盘或移动硬盘分区,右侧选择“抹掉”标签,在格式下拉菜单里选择 exfat 即可。如上图所示。
windows 7 和 vista 默认就支持 exfat 格式,如果是 xp 系统,要下载 kb955704 补丁:
至于 exfat 格式的 u 盘的读写速度,下面是同一块 u 盘在同一台电脑(我的 macbook pro)上的读写速度测试,测试软件为 。
顺时针依次是 fat32、hfs+、exfat 格式下 u 盘读写速度测试结果,不太妙。所以:只把 u 盘和移动硬盘的一个分区(专门用于 pc、mac 之间交换文件)格式化成 exfat 就行了。
keep for ref: http://www.mac52ipod.cn/post/use-u-disk-hdd-on-windows-pc-and-mac-os-x-4gb-exfat.php
result
criteriabuilder critbuilder = entitymanager.getcriteriabuilder();
criteriaquerycritquery = criteriabuilder.createquery(long.class);
rootroot = critquery.from(foo.class);
critquery.select(root).distinct(true);
listresult = entitymanager.createquery(critquery).getresultlist();
– merriam-webster online dictionary, 2012
when brothers thomas and john knoll began designing and writing an image editing program in the late 1980s, they could not have imagined that they would be adding a word to the dictionary.
thomas knoll
john knoll
thomas knoll, a phd student in computer vision at the university of michigan, had written a program in 1987 to display and modify digital images. his brother john, working at the movie visual effects company industrial light & magic, found it useful for editing photos, but it wasn’t intended to be a product. thomas said, “we developed it originally for our own personal use…it was a lot a fun to do.”
gradually the program, called “display”, became more sophisticated. in the summer of 1988 they realized that it indeed could be a credible commercial product. they renamed it “photoshop” and began to search for a company to distribute it. about 200 copies of version 0.87 were bundled by slide scanner manufacturer barneyscan as “barneyscan xp”.
the fate of photoshop was sealed when adobe, encouraged by its art director russell brown, decided to buy a license to distribute an enhanced version of photoshop. the deal was finalized in april 1989, and version 1.0 started shipping early in 1990.
over the next ten years, more than 3 million copies of photoshop were sold.
that first version of photoshop was written primarily in pascal for the apple macintosh, with some machine language for the underlying motorola 68000 microprocessor where execution efficiency was important. it wasn’t the effort of a huge team. thomas said, “for version 1, i was the only engineer, and for version 2, we had two engineers.” while thomas worked on the base application program, john wrote many of the image-processing plug-ins.
with the permission of adobe systems inc., the computer history museum is pleased to make available, for non-commercial use, the source code to the 1990 version 1.0.1 of photoshop. all the code is here with the exception of the macapp applications library that was licensed from apple. there are 179 files in the zipped folder, comprising about 128,000 lines of mostly uncommented but well-structured code. by line count, about 75% of the code is in pascal, about 15% is in 68000 assembler language, and the rest is data of various sorts. to download the code you must agree to the terms of the license.
download
the 1990 version of the adobe photoshop user guide is at
and the 1990 adobe photoshop tutorial is at
software architect grady booch is the chief scientist for software engineering at ibm research almaden and a trustee of the computer history museum. he offers the following observations about the photoshop source code:
“opening the files that constituted the source code for photoshop 1.0, i felt a bit like howard carter as he first breached the tomb of king tutankhamen. what wonders awaited me?
i was not disappointed by what i found. indeed, it was a marvelous journey to open up the cunning machinery of an application i’d first used over 20 years ago.
architecturally, this is a very well-structured system. there’s a consistent separation of interface and abstraction, and the design decisions made to componentize those abstractions – with generally one major type for each combination of interface and implementation — were easy to follow.
the abstractions are quite mature. the consistent naming, the granularity of methods, the almost breathtaking simplicity of the implementations because each type was so well abstracted, all combine to make it easy to discern the texture of the system.
having the opportunity to examine photoshop’s current architecture, i believe i see fundamental structures that have persisted, though certainly in more evolved forms, in the modern implementation. tiles, filters, abstractions for virtual memory (to attend to images far larger than display buffers or main memory could normally handle) are all there in the first version. yet it had just over 100,000 lines of code, compared to well over 10 million in the current version! then and now, much of the code is related to input/output and the myriad of file formats that photoshop has to attend to.
there are only a few comments in the version 1.0 source code, most of which are associated with assembly language snippets. that said, the lack of comments is simply not an issue. this code is so literate, so easy to read, that comments might even have gotten in the way.
it is delightful to find historical vestiges of the time: code to attend to andy herzfield’s software for the thunderscan scanner, support of early targa raster graphics file types, and even a few passing references to barneyscan lie scattered about in the code. these are very small elements of the overall code base, but their appearance reminds me that no code is an island.
this is the kind of code i aspire to write.”
and this is the kind of code we all can learn from. software source code is the literature of computer scientists, and it deserves to be studied and appreciated. enjoy a view of photoshop from the inside.
the home screen, showing the available tools.
photoshop allowed you to select brush color as well as size and texture. (the first color mac was the macintosh ii in 1987.)
there were some sophisticated selection tools, and a good assortment of image filters. one important missing feature, which came with version 3 in 1994, was the ability to divide an image into multiple layers.
the preferences page allowed for some customization of the features.
there was a limited choice of fonts, font sizes, and font styles. the text was entered into this dialog box, then moved into the image.
*screen shots courtesy of creativebits, .
from: http://computerhistory.org/atchm/adobe-photoshop-source-code/
anders hejlsberg, a distinguished engineer at microsoft, led the team that designed the c# (pronounced c sharp) programming language. hejlsberg first vaulted onto the software world stage in the early eighties by creating a pascal compiler for ms-dos and cp/m. a very young company called borland soon hired hejlsberg and bought his compiler, which was thereafter marketed as turbo pascal. at borland, hejlsberg continued to develop turbo pascal and eventually led the team that designed turbo pascal's replacement: delphi. in 1996, after 13 years with borland, hejlsberg joined microsoft, where he initially worked as an architect of visual j and the windows foundation classes (wfc). subsequently, hejlsberg was chief designer of c# and a key participant in the creation of the .net framework. currently, anders hejlsberg leads the continued development of the c# programming language.
on july 30, 2003, bruce eckel, author of thinking in c and thinking in java, and bill venners, editor-in-chief of artima.com, met with anders hejlsberg in his office at microsoft in redmond, washington. in this interview, which will be published in multiple installments on artima.com and on an audio cd-rom to be released this fall by bruce eckel, anders hejlsberg discusses many design choices of the c# language and the .net framework.
bruce eckel: c# doesn't have checked exceptions. how did you decide whether or not to put checked exceptions into c#?
anders hejlsberg: i see two big issues with checked exceptions: scalability and versionability. i know you've written some about checked exceptions too, and you tend to agree with our line of thinking.
bruce eckel: i used to think that checked exceptions were really great.
anders hejlsberg: exactly. frankly, they look really great up front, and there's nothing wrong with the idea. i completely agree that checked exceptions are a wonderful feature. it's just that particular implementations can be problematic. by implementing checked exceptions the way it's done in java, for example, i think you just take one set of problems and trade them for another set of problems. in the end it's not clear to me that you actually make life any easier. you just make it different.
bruce eckel: was there a lot of disagreement in the c# design team about checked excpetions?
anders hejlsberg: no, i think there was fairly broad agreement in our design group.
c# is basically silent on the checked exceptions issue. once a better solution is known—and trust me we continue to think about it—we can go back and actually put something in place. i'm a strong believer that if you don't have anything right to say, or anything that moves the art forward, then you'd better just be completely silent and neutral, as opposed to trying to lay out a framework.
if you ask beginning programmers to write a calendar control, they often think to themselves, "oh, i'm going to write the world's best calendar control! it's going to be polymorphic with respect to the kind of calendar. it will have displayers, and mungers, and this, that, and the other." they need to ship a calendar application in two months. they put all this infrastructure into place in the control, and then spend two days writing a crappy calendar application on top of it. they'll think, "in the next version of the application, i'm going to do so much more."
once they start thinking about how they're actually going to implement all of these other concretizations of their abstract design, however, it turns out that their design is completely wrong. and now they've painted themself into a corner, and they have to throw the whole thing out. i have seen that over and over. i'm a strong believer in being minimalistic. unless you actually are going to solve the general problem, don't try and put in place a framework for solving a specific one, because you don't know what that framework should look like.
bruce eckel: the extreme programmers say, "do the simplest thing that could possibly work."
anders hejlsberg: yeah, well, einstein said that, "do the simplest thing possible, but no simpler." the concern i have about checked exceptions is the handcuffs they put on programmers. you see programmers picking up new apis that have all these throws clauses, and then you see how convoluted their code gets, and you realize the checked exceptions aren't helping them any. it is sort of these dictatorial api designers telling you how to do your exception handling. they should not be doing that.
bill venners: you mentioned scalability and versioning concerns with respect to checked exceptions. could you clarify what you mean by those two issues?
anders hejlsberg: let's start with versioning, because the issues are pretty easy to see there. let's say i create a method foo
that declares it throws exceptions a
, b
, and c
. in version two of foo
, i want to add a bunch of features, and now foo
might throw exception d
. it is a breaking change for me to add d
to the throws clause of that method, because existing caller of that method will almost certainly not handle that exception.
adding a new exception to a throws clause in a new version breaks client code. it's like adding a method to an interface. after you publish an interface, it is for all practical purposes immutable, because any implementation of it might have the methods that you want to add in the next version. so you've got to create a new interface instead. similarly with exceptions, you would either have to create a whole new method called foo2
that throws more exceptions, or you would have to catch exception d
in the new foo
, and transform the d
into an a
,b
, or c
.
bill venners: but aren't you breaking their code in that case anyway, even in a language without checked exceptions? if the new version of foo
is going to throw a new exception that clients should think about handling, isn't their code broken just by the fact that they didn't expect that exception when they wrote the code?
anders hejlsberg: no, because in a lot of cases, people don't care. they're not going to handle any of these exceptions. there's a bottom level exception handler around their message loop. that handler is just going to bring up a dialog that says what went wrong and continue. the programmers protect their code by writing try finally's everywhere, so they'll back out correctly if an exception occurs, but they're not actually interested in handling the exceptions.
the throws clause, at least the way it's implemented in java, doesn't necessarily force you to handle the exceptions, but if you don't handle them, it forces you to acknowledge precisely which exceptions might pass through. it requires you to either catch declared exceptions or put them in your own throws clause. to work around this requirement, people do ridiculous things. for example, they decorate every method with, "throws exception
." that just completely defeats the feature, and you just made the programmer write more gobbledy gunk. that doesn't help anybody.
bill venners: so you think the more common case is that callers don't explicitly handle exceptions in deference to a general catch clause further up the call stack?
anders hejlsberg: it is funny how people think that the important thing about exceptions is handling them. that is not the important thing about exceptions. in a well-written application there's a ratio of ten to one, in my opinion, of try finally to try catch. or in c#, using
statements, which are like try finally.
bill venners: what's in the finally?
anders hejlsberg: in the finally, you protect yourself against the exceptions, but you don't actually handle them. error handling you put somewhere else. surely in any kind of event-driven application like any kind of modern ui, you typically put an exception handler around your main message pump, and you just handle exceptions as they fall out that way. but you make sure you protect yourself all the way out by deallocating any resources you've grabbed, and so forth. you clean up after yourself, so you're always in a consistent state. you don't want a program where in 100 different places you handle exceptions and pop up error dialogs. what if you want to change the way you put up that dialog box? that's just terrible. the exception handling should be centralized, and you should just protect yourself as the exceptions propagate out to the handler.
anders hejlsberg: the scalability issue is somewhat related to the versionability issue. in the small, checked exceptions are very enticing. with a little example, you can show that you've actually checked that you caught the filenotfoundexception
, and isn't that great? well, that's fine when you're just calling one api. the trouble begins when you start building big systems where you're talking to four or five different subsystems. each subsystem throws four to ten exceptions. now, each time you walk up the ladder of aggregation, you have this exponential hierarchy below you of exceptions you have to deal with. you end up having to declare 40 exceptions that you might throw. and once you aggregate that with another subsystem you've got 80 exceptions in your throws clause. it just balloons out of control.
in the large, checked exceptions become such an irritation that people completely circumvent the feature. they either say, "throws exception
," everywhere; or—and i can't tell you how many times i've seen this—they say, "try, da da da da da, catch curly curly
." they think, "oh i'll come back and deal with these empty catch clauses later," and then of course they never do. in those situations, checked exceptions have actually degraded the quality of the system in the large.
and so, when you take all of these issues, to me it just seems more thinking is needed before we put some kind of checked exceptions mechanism in place for c#. but that said, there's certainly tremendous value in knowing what exceptions can get thrown, and having some sort of tool that checks. i don't think we can construct hard and fast rules down to, it is either a compiler error or not. but i think we can certainly do a lot with analysis tools that detect suspicious code, including uncaught exceptions, and points out those potential holes to you.
from: http://www.artima.com/intv/handcuffs.html
(1)命令配置
# ifconfig eth0 192.168.0.2 netmask 255.255.255.0 //ip地址、子网掩码
# route add default gw 192.168.0.1 dev eth0 //网关
# hostname centos //计算机名
(2)文件配置
<1>修改ip地址
修改对应网卡的ip地址的配置文件
# vi /etc/sysconfig/network-scripts/ifcfg-eth0
device=eth0 (描述网卡对应的设备别名,例如ifcfg-eth0的文件中它为eth0)
bootproto=static (设置网卡获得ip地址的方式,可能的选项为static,dhcp或bootp,分别对应静态指定的ip地址,通过dhcp协议获得的ip地址,通过bootp协议获得的ip地址)
broadcast=192.168.0.255 (对应的子网广播地址)
hwaddr=00:07:e9:05:e8:b4 (对应的网卡物理地址)
ipaddr=12.168.1.2 (如果设置网卡获得ip地址的方式为静态指定,此字段就指定了网卡对应的ip地址)
ipv6init=no (开启或关闭ipv6;关闭no,开启yes)
ipv6_autoconf=no (开启或关闭ipv6自动配置;关闭no,开启yes)
netmask=255.255.255.0 (网卡对应的网络掩码)
network=192.168.1.0 (网卡对应的网络地址)
onboot=yes (系统启动时是否设置此网络接口,设置为yes时,系统启动时激活此设备)
<2>修改网关
修改对应网卡的网关的配置文件
# vi /etc/sysconfig/network
networking=yes (表示系统是否使用网络,一般设置为yes。如果设为no,则不能使用网络,而且很多系统服务程序将无法启动)
hostname=centos (设置本机的主机名,这里设置的主机名要和/etc/hosts中设置的主机名对应)
gateway=192.168.1.1 (设置本机连接的网关的ip地址。例如,网关为10.0.0.2)
<3>修改dns
修改对应网卡的dns的配置文件
# vi /etc/resolv.conf
nameserver 202.101.224.68 (域名服务器)
nameserver 202.101.224.69 (域名服务器)
<4>重新启动网络配置
# service network restart
或
# /etc/init.d/network restart
2.软件源配置
国内速度较快的常用更新源如下:
http://mirrors.163.com/centos/ 163-网易
http://mirrors.ta139.com/centos/ 中国移动通信(山东移动)
http://centos.ustc.edu.cn/centos/ 中国科学技术大学
http://mirror.neu.edu.cn/centos/ 东北大学
编辑yum配置文件:
#vi /etc/yum.repos.d/centos-base.repo
[base]
name=centos-$releasever - base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
baseurl=http://mirrors.163.com/centos/$releasever/os/$basearch/
http://mirrors.ta139.com/centos/$releasever/os/$basearch/
http://centos.ustc.edu.cn/centos/$releasever/os/$basearch/
http://mirror.neu.edu.cn/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/rpm-gpg-key-centos-6
#released updates
[updates]
name=centos-$releasever - updates
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
baseurl=http://mirrors.163.com/centos/$releasever/updates/$basearch/
http://mirrors.ta139.com/centos/$releasever/updates/$basearch/
http://centos.ustc.edu.cn/centos/$releasever/updates/$basearch/
http://mirror.neu.edu.cn/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/rpm-gpg-key-centos-6
#additional packages that may be useful
[extras]
name=centos-$releasever - extras
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
#baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
baseurl=http://mirrors.163.com/centos/$releasever/extras/$basearch/
http://mirrors.ta139.com/centos/$releasever/extras/$basearch/
http://centos.ustc.edu.cn/centos/$releasever/extras/$basearch/
http://mirror.neu.edu.cn/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/rpm-gpg-key-centos-6
#additional packages that extend functionality of existing packages
[centosplus]
name=centos-$releasever - plus
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
baseurl=http://mirrors.163.com/centos/$releasever/centosplus/$basearch/
http://mirrors.ta139.com/centos/$releasever/centosplus/$basearch/
http://centos.ustc.edu.cn/centos/$releasever/centosplus/$basearch/
http://mirror.neu.edu.cn/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=http://mirror.centos.org/centos/rpm-gpg-key-centos-6
#contrib - packages by centos users
[contrib]
name=centos-$releasever - contrib
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=contrib
#baseurl=http://mirror.centos.org/centos/$releasever/contrib/$basearch/
baseurl=http://mirrors.163.com/centos/$releasever/contrib/$basearch/
http://mirrors.ta139.com/centos/$releasever/contrib/$basearch/
http://centos.ustc.edu.cn/centos/$releasever/contrib/$basearch/
http://mirror.neu.edu.cn/centos/$releasever/contrib/$basearch/
gpgcheck=1
enabled=0
gpgkey=http://mirror.centos.org/centos/rpm-gpg-key-centos-6
然后使用如下命令更新到最新系统:
#rpm –import /etc/pki/rpm-gpg-key*
#yum upgrade3.安装语言包
从安装盘进行安装,找到对应rpm包:
fonts-chinese-3.02-9.6.el5.noarch.rpm
fonts-iso8859-2-75dpi-1.0-17.1.noarch.rpm
可以通过yum进行安装,安装办法为:
#yum groupinstall
在 上面的命令中,
4.解压缩软件
#yum install unrar unzip p7zip-full
开启80、21、3306端口:
/sbin/iptables -i input -p tcp --dport 80 -j accept
/sbin/iptables -i input -p tcp --dport 3306 -j accept
/sbin/iptables -i input -p tcp --dport 21 -j accept
/etc/init.d/iptables save
service iptables restart
其实,刚刚看了以前写过的一篇文章。发现此文已经是多余的了。唉。既然写了。就写完整一点吧。
一般来说,我们不会使用linux自带的防火墙的。在idc机房,人家的防火墙是硬件。肯定比软件要强大得多。
可以使用如下方式对操作防火墙:
永久性关掉防火墙shell:
chkconfig --level 35 iptables off
通过如下命令查看防火墙是否关闭:
service iptables status
如果已经正确关闭,则会输出如下信息:
iptables:未运行防火墙。
如果,你的是英文版本,则可能提示信息不太一样。
如果没有输出类似防火墙关闭的信息,直接重启系统或者执行如下命令试一试:
service iptables stop
关掉防火墙之后,那么所有开启的端口都将会暴露给互联网所有人。那么,可能会导致别有用心的人针对你的系统漏洞做出一些破坏的事情。
除了这个还有一个东西是就selinux这个玩意儿。如果防火墙放开了端口也无法进行访问。说明这个玩意做了限制,大家将它关闭即可。
二、安装配置虚拟机系统
1) 打虚拟机。然后,选择虚拟机工具栏上的“新建”按钮。如图:
2)点击“新建”按钮后,弹出如下弹出框,我们在名称项里面输入:centos 6.3 mini。这个位置随便填写没有任何问题。如果,你填写的是windows xp的话,则类型会自动变成windows,版本自动会变成windows xp。当我们填写centos 6.3的时候,类型会自动变成linux,版本会变成 red hat。但是,我们安装的是64位的,所以,要修改red hat (64 bit)。
3)点击“下一步”,弹出内存分配的选项框。这个地方特别要注意,内存在768mb这个位置是一个分水岭。如果低于这个这个值,则安装的时候会进入字符安装模式。大于等于这个值会进入图形安装界面。刚开始我不太熟悉字符安装模式,一直在这里纠结了很久都不知道为什么。后面,百度搜索答案的时候,发现官方已经有说明。如图,我分配了1024mb的内存。图中的绿色的线代表是内存最佳的分配值,超过这个值,可能会造成系统内存不足的问题。
4)点击“下一步”保持默认的选项不变,如图:
5)点击“创建”,弹出选项框,保持默认不变。如图:
6)点击“下一步”,弹出虚拟硬盘空间分配的方式。一般保持默认不变。如图:
7)点击“下一步”,设置虚拟硬盘位置和大小。我将虚拟硬盘文件的位置放置在了g:\vboxs中,大小配置20gb。如图:
8)点击“创建”按钮,即完成了对虚拟机的创建。但是,此时只是把配置做好了。即下来的操作才是安装系统。此时,在vbox列表里面已经有了刚才创建的虚拟机。如图:
9)到此一步,我们的配置并没有结束。因为,很多机器现在的内存都已经4gb了。这会给32位的系统安装造成一些问题。所以,我们还需要来消除这些问题。右键选中,vbox列表中刚才创建的虚拟机,选择“设置”,选择“系统”,再选择“处理器(p)”,会看到一项:扩展特性。我们把它勾选上,让虚拟机支持4gb以上的内存。如图:
10)现在我们要把centos iso镜像文件加载到虚拟机中。在上图中的左侧中选择“储存”。然后根据下图中的操作进行:
11)虚拟机除了镜像还可以使用电脑的光驱进行安装。如图:
然后点击“确定”即可。
12)此时,我们再点击vbox工具样上的“启动”按钮。点击之前,必须先选中刚才我们创建的虚拟机。就会到达如下界面:
如果,你进入这个界面之前,弹出如下错误提示:
vt-x/amd-v 硬件加速器已被启动,但当前处于无效状态。您虚拟电脑内的操作系统将无法检测到64位的cpu,因此也将无法启动….
那么,你要确定你的cpu是支持64位的,可以按照如下方式进行解决:
1、请确认你的iso文件或dvd为64位的ios文件。
2、请确认你的cpu为64位的cpu。
3、请确认bios的virtualization是否为enabled。设置方法:进入bios—->advanced bios features—–>virtualization—->disabled(预设值)修改为enabled,储存(save),重启。有些bios设置方法与此并不相同,比如,有些笔记本virualization这个选项进去是将vt-x与amd-v两项设置分开的。所以,要将两个选项都要设置为enabled。
13)我们选择”install or upgrade an existsing system”,然后,敲击回车键往下安装。
14)接下来会的界面是让你检测要安装的系统介质是否完整有效。因为我是从正规渠道下载的系统iso,所以,基本上不会出现问题。所以,我选择了“skip”选项跳过介质检测。如图:
15)回车“skip”之后出现如下界面,选择点击“next”。
16)此时会出现一个选择当前系统语言的选项,我们肯定是选择简体中文了,选择之后点击下一步。如图:
17)此时会出现一个键盘语言的选择,我们肯定是选择“美国式英语”了。也就是保持默认选项,点击“下一步”即可。如图:
18)出现如下界面,保持默认即可,然后点击“下一步”继续往下安装。如图:
19)出现如下界面,点击“是,忽略所有数据”。因为,在virtualbox里面,所做的任何操作都不会影响到真实系统里面的数据。所以,放心大胆地选择此项吧。如图:
20)然后出现如下界面,要求我们为这台计算机取一个名字。很简单,我们按照要求填写即可。如图:
21)接下来的界面是让我们为电脑设置一个时区。我的选择如图所示:
22)即下来,会要求我们为默认的root系统账户设置一个密码。如图:
如果,你设置的密码过于简单。如:123456这样的密码,则系统会提示我们,密码强度不够安全。我们不管它,直接选择“无论如何都使用(u)” 即可。如图:
23)在接下来的界面中,我们选择“使用所有空间”的选项进行安装。如果,你想在电脑上装双系统,那么请不要选择此项。我们是用vittualbox完全不用担心硬盘会被格式化的问题。如图:
24)点击“下一步”会弹出如下提示框,我们选择“将修改写入硬盘”选择。
25)ok。一切完毕之后,就该执行安装过程了。我们能做的就是等待。当安装进度100%的时候,会提示我们重新引导系统。到时候记得点击即可。如图:
可选的类型说明如下:
desktop :基本的桌面系统,包括常用的桌面软件,如文档查看工具。
minimal desktop :基本的桌面系统,包含的软件更少。
minimal :基本的系统,不含有任何可选的软件包。
basic server :安装的基本系统的平台支持,不包含桌面。
database server :基本系统平台,加上mysql和postgresql数据库,无桌面。
web server :基本系统平台,加上php,web server,还有mysql和postgresql数据库的客户端,无桌面。
virtual host :基本系统加虚拟平台。
software development workstation :包含软件包较多,基本系统,虚拟化平台,桌面环境,开发工具。
到此关于virtualbox安装centos 6.3 最小化安装已经介绍完了。
- # locale -a
- # locale -a|grep en
■ 查看当前操作系统使用的语言
- # echo $lang
■ 设置系统locale语言为中文环境(永久生效)
# vi /etc/sysconfig/i18n
- lang="zh_cn.utf-8"
■ 设置系统locale语言为英文环境(永久生效)
- lang="en_us.utf-8"
■ 临时改变系统locale语言(退出本次登录立即失效)
- # export lang=zh_cn.utf-8
■ 安装中文字体
- # yum install fonts-chinese.noarch
■ 指定中文字体路径
# vi /etc/x11/fs/config
- catalogue = /usr/x11r6/lib/x11/fonts/misc:unscaled,
- /usr/x11r6/lib/x11/fonts/75dpi:unscaled,
- /usr/x11r6/lib/x11/fonts/100dpi:unscaled,
- /usr/x11r6/lib/x11/fonts/type1,
- /usr/share/fonts/default/type1,
- ,
- /usr/share/fonts/zh_cn/truetype,
- /usr/share/fonts/zh_tw/truetype
方法2
修改centos运行环境的默认语言环境变量值
[root@www ~]# vi /etc/profile
找到export语句,在语句前面加入
lang=”en_us.utf-8″
再在export后面追加lang
export path user logname mail hostname histsize inputrc lang
保存配置,修改centos语言完成。
shell>sudo /library/startupitems/mysqlcom/mysqlcom start
(enter your password, if necessary)
(press control-d or enter "exit" to exit the shell)
if you do not use the startup item, enter the following command sequence:
shell>cd /usr/local/mysql
shell>sudo ./bin/mysqld_safe
(enter your password, if necessary)
(press control-z)
shell>bg
(press control-d or enter "exit" to exit the shell)
you should be able to connect to the mysql server, for example, by running/usr/local/mysql/bin/mysql
.alias mysql=/usr/local/mysql/bin/mysql alias mysqladmin=/usr/local/mysql/bin/mysqladmin
sequel pro is a database management app for mysql databaseshttp://www.sequelpro.com/
linux lan card: find out full duplex / half speed or mode
q. how do i find out if my lan (nic) card working at full or halt duplex mode / speed under linux?
a. lan card or nic is use to send and receive data. technically, we use word duplex for this functionality. full duplex means you are able to send and receive data (files) simultaneously. in half duplex, you can either send or receive data at a time (i.e. you cannot send receive data (files) simultaneously). obviously, full duplex gives you best user experience. however, how can i find out whether i am using full duplex/half duplex speed/mode?
task: find full or half duplex speed
you can use dmesg command to find out your duplex mode:
# dmesg | grep -i duplex
output:
eth0: link up, 100mbps, full-duplex, lpa 0x45e1
ethtool command
uss ethtool to display or change ethernet card settings. to display duplex speed, enter:
# ethtool eth1
output:
settings for eth1:
supported ports: [ tp ]
supported link modes: 10baset/half 10baset/full
100baset/half 100baset/full
1000baset/full
supports auto-negotiation: yes
advertised link modes: 10baset/half 10baset/full
100baset/half 100baset/full
1000baset/full
advertised auto-negotiation: yes
speed: 10mb/s
duplex: full
port: twisted pair
phyad: 0
transceiver: internal
auto-negotiation: on
supports wake-on: umbg
wake-on: g
current message level: 0x00000007 (7)
link detected: yes
mii-tool command
you can also use mii-tool to find out your duplex mode. type following command at shell prompt:
# mii-tool
output:
eth0: negotiated 100basetx-fd flow-control, link ok
remember,
1. 100basetx-fd: 100mbps full duplex (fd)
2. 100basetx-hd: 100mbps half duplex (hd)
3. 10baset-fd: 10mbps full duplex (fd)
4. 10baset-hd: 10mbps half duplex (hd)
mii-tool utility checks or sets the status of a network interface media independent interface (mii) unit. most fast ethernet adapters use an mii to autonegotiate link speed and duplex setting. if you are using old card then this utility may not work (use dmesg command).
this utility is useful for forcing specific ethernet speed and duplex settings too, setup 100mbps full duplex speed under linux:
# mii-tool -f 100basetx-fd
setup 10mbps half duplex:
# mii-tool -f 10baset-hd
source:
http://www.cyberciti.biz/faq/howto-setup-linux-lan-card-find-out-full-duplex-half-speed-or-mode/
case sensitivity | |
|
i reproduced this prototype on alternativa3d engine. and here you can find it:
generally this port is bit different from emanuele’s version. i can’t find information about feature like skybox in alternativa3d, so this feature coded manually. another difference is camera behavior. emanuele binds camera to object and during rotations player object stand still and only camera fly around by its orbit. in alternativa3d version object rotates too, this allow us to face player object it to it’s current direction. camera is not binded to the object directly it is binded to object container and we can manipulate with player object in container, add animations, rotations etc. but both variants are good i think.
here is source code:
package { import alternativa.alternativa3d; import alternativa.engine3d.containers.*; import alternativa.engine3d.controllers.*; import alternativa.engine3d.core.camera3d; import alternativa.engine3d.core.clipping; import alternativa.engine3d.core.debug; import alternativa.engine3d.core.mipmapping; import alternativa.engine3d.core.mouseevent3d; import alternativa.engine3d.core.object3d; import alternativa.engine3d.core.object3dcontainer; import alternativa.engine3d.core.sorting; import alternativa.engine3d.core.view; import alternativa.engine3d.materials.fillmaterial; import alternativa.engine3d.materials.texturematerial; import alternativa.engine3d.objects.sprite3d; import alternativa.engine3d.primitives.box; import alternativa.engine3d.primitives.plane; import alternativa.engine3d.primitives.sphere; import flash.display.bitmapdata; import flash.display.blendmode; import flash.display.sprite; import flash.display.stagealign; import flash.display.stagequality; import flash.display.stagescalemode; import flash.events.event; import flash.events.keyboardevent; import flash.filters.glowfilter; import flash.geom.colortransform; import flash.geom.vector3d; import flash.sampler.newobjectsample; import flash.system.capabilities; import flash.ui.keyboard; [swf(backgroundcolor="#000000", framerate="100", width="640", height="480")] public class alternativa3dsokoban extends sprite { private const cubesize:number=10; //embeding textures images [embed(source="resource/cratetextureimg.jpg")] static private const cratetextureimg:class; [embed(source="resource/floortextureimg.png")] static private const floortextureimg:class; [embed(source="resource/cratetoptextureimg.jpg")] static private const cratetoptextureimg:class; [embed(source="resource/cratetopgoaltextureimg.jpg")] static private const cratetopgoaltextureimg:class; [embed(source="resource/walltextureimg.png")] static private const walltextureimg:class; [embed(source="resource/goaltextureimg.jpg")] static private const goaltextureimg:class; [embed(source="resource/playertextureimg.jpg")] static private const playertextureimg:class; [embed(source="resource/backbitmapimg.jpg")] static private const backtextureimg:class; [embed(source="resource/backbottombitmapimg.jpg")] static private const backbottomtextureimg:class; // sokobal demo level and player position private var levels:array=[[1,1,1,1,0,0,0,0],[1,0,0,1,1,1,1,1],[1,0,2,0,0,3,0,1],[1,0,3,0,0,2,4,1],[1,1,1,0,0,1,1,1],[0,0,1,1,1,1,0,0]]; private var playercol:uint; private var playerrow:uint; private var playerrotation:number=0; private var playerangle:number=0; private var playermovement:number=0; private var drow:int; private var dcol:int; // alternativa3d engine variables private var camera:camera3d; private var controller:simpleobjectcontroller; private var container:conflictcontainer; private var frame:sprite = new sprite(); public var player:sphere;// sphere primitive representing the player public var cplayer:simpleobjectcontroller; //controller for player object public var conplayer:object3dcontainer; //container for player private var movingcrate:box;// cube primitive representing the moving crate // textures private var cratetexture:texturematerial = new texturematerial(new cratetextureimg().bitmapdata); private var floortexture:texturematerial = new texturematerial(new floortextureimg().bitmapdata); private var cratetoptexture:texturematerial = new texturematerial(new cratetoptextureimg().bitmapdata); private var cratetopgoaltexture:texturematerial = new texturematerial(new cratetopgoaltextureimg().bitmapdata); private var walltexture:texturematerial = new texturematerial(new walltextureimg().bitmapdata); private var goaltexture:texturematerial = new texturematerial(new goaltextureimg().bitmapdata); private var playertexture:texturematerial = new texturematerial(new playertextureimg().bitmapdata); // skybox textures private var backtexture:texturematerial = new texturematerial(new backtextureimg().bitmapdata); private var backbottomtexture:texturematerial = new texturematerial(new backbottomtextureimg().bitmapdata); public function alternativa3dsokoban() { stage.scalemode = stagescalemode.no_scale; stage.align = stagealign.top_left; stage.quality = stagequality.best; // camera camera = new camera3d(); camera.view = new view(640, 480); addchild(camera.view); // camera controller controller = new simpleobjectcontroller(stage, camera, 200, 3); // root object container = new conflictcontainer(); container.resolvebyaabb = true; container.resolvebyoobb = true; //player controller conplayer = new object3dcontainer(); cplayer = new simpleobjectcontroller(stage, player, 3); //i am not shure about skybox in alternativa and will prepare it manually var backbottom:plane = new plane(200*cubesize/2,200*cubesize/2); backbottom.setmaterialtoallfaces(backbottomtexture); backbottom.x = 0; backbottom.y = -100*cubesize/2; backbottom.z = 0; backbottom.rotationx = 90*math.pi/180; container.addchild(backbottom); var backleft:plane = new plane(200*cubesize/2,200*cubesize/2); backleft.setmaterialtoallfaces(backtexture); backleft.x = 0; backleft.y = 0; backleft.z = 100*cubesize/2; container.addchild(backleft); var backright:plane = new plane(200*cubesize/2,200*cubesize/2); backright.setmaterialtoallfaces(backtexture); backright.x = 0; backright.y = 0; backright.z = -100*cubesize/2; container.addchild(backright); var backfront:plane = new plane(200*cubesize/2,200*cubesize/2); backfront.setmaterialtoallfaces(backtexture); backfront.x = -100*cubesize/2; backfront.y = 0; backfront.z = 0; backfront.rotationy = 90*math.pi/180; container.addchild(backfront); var backback:plane = new plane(200*cubesize/2,200*cubesize/2); backback.setmaterialtoallfaces(backtexture); backback.x = 100*cubesize/2; backback.y = 0; backback.z = 0; backback.rotationy = 90*math.pi/180; container.addchild(backback); // end skybox var box:box; /* [[1,1,1,1,0,0,0,0], [1,0,0,1,1,1,1,1], [1,0,2,0,0,3,0,1], [1,0,3,0,0,2,4,1], [1,1,1,0,0,1,1,1], [0,0,1,1,1,1,0,0]]; */ // level construction for (var i:uint=0; i<6; i ) { for (var j:uint=0; j<8; j ) { switch (levels[i][j]) { case 0 : box = new box(cubesize,cubesize/2,cubesize,1,1); box.setmaterialtoallfaces(floortexture); box.x = cubesize*j; box.y = 0; box.z = cubesize*i; container.addchild(box); break; case 1 : box = new box(cubesize,cubesize/2,cubesize,1); box.setmaterialtoallfaces(floortexture); box.x = cubesize*j; box.y = 0; box.z = cubesize*i; container.addchild(box); box = new box(cubesize,cubesize,cubesize,1); box.setmaterialtoallfaces(walltexture); box.x = cubesize*j; box.y = cubesize*3/4; box.z = cubesize*i; container.addchild(box); break; case 2 : box = new box(cubesize,cubesize/2,cubesize,1); box.setmaterialtoallfaces(goaltexture); box.x = cubesize*j; box.y = 0; box.z = cubesize*i; container.addchild(box); break; case 3 : box = new box(cubesize,cubesize/2,cubesize,1); box.setmaterialtoallfaces(floortexture); box.x = cubesize*j; box.y = 0; box.z = cubesize*i; container.addchild(box); box = new box(cubesize,cubesize,cubesize,1); box.name = "crate_" i "_" j; box.setmaterialtoallfaces(cratetexture); box.x = cubesize*j; box.y = cubesize*3/4; box.z = cubesize*i; box.rotationx -= 90*math.pi/180; // top of the crate box.faces[4].material=cratetoptexture; box.faces[5].material=cratetoptexture; container.addchild(box); break; case 4 : box = new box(cubesize,cubesize/2,cubesize,1); box.setmaterialtoallfaces(floortexture); box.x = cubesize*j; box.y = 0; box.z = cubesize*i; container.addchild(box); player = new sphere(cubesize/2,16,16,false,playertexture); conplayer.addchild(player); conplayer.visible = true; conplayer.x = cubesize*j; conplayer.y = cubesize*3/4; conplayer.z = cubesize*i; conplayer.rotationx -= 90*math.pi/180; container.addchild(conplayer); playercol=j; playerrow=i; break; } } } // adding camera container.addchild(camera); // view frame addchild(frame); onresize(); stage.addeventlistener(event.enter_frame, updateevent); stage.addeventlistener(keyboardevent.key_down, onkeydwn); stage.addeventlistener(event.resize, onresize); } private function onkeydwn(e:keyboardevent):void { if (playerrotation==0&&playermovement==0) { switch (e.keycode) { case keyboard.left : playerrotation= 9; playerangle =90; break; case keyboard.right : playerrotation=-9; playerangle-=90; break; case keyboard.up : movingcrate=null; playerangle=math.round(conplayer.rotationy*180/math.pi)60; if (playerangle<0) { playerangle =360; } // we have to determine the difference between current row and column // and the new row and column according to player heading switch (playerangle) { case 0 : drow=0; dcol=-1; break; case 90 : //drow=-1; drow=1; dcol=0; break; case 180 : drow=0; dcol=1; break; case 270 : //drow=1; drow=-1; dcol=0; break; } if (levels[playerrow drow][playercol dcol]==0||levels[playerrow drow][playercol dcol]==2) { // the player can move playermovement=-cubesize/10; } else { if (levels[playerrow drow][playercol dcol]==3||levels[playerrow drow][playercol dcol]==5) { if (levels[playerrow 2*drow][playercol 2*dcol]==0||levels[playerrow 2*drow][playercol 2*dcol]==2) { // the player can move and can push a crate movingcrate=container.getchildbyname("crate_" (playerrow drow) "_" (playercol dcol))as box; playermovement=-cubesize/10; } } } break; } } } public function updateevent(e:event):void { if (playerrotation) { conplayer.rotationy =playerrotation*math.pi/180; if (math.abs(math.round(conplayer.rotationy*180/math.pi))�==0) { playerrotation=0; } } if (playermovement) { switch (playerangle) { case 0 : conplayer.x = playermovement; player.rotationy -= 18*math.pi/180; break; case 90 : conplayer.z = -playermovement; player.rotationy -= 18*math.pi/180; break; case 180 : conplayer.x = -playermovement; player.rotationy -= 18*math.pi/180; break; case 270 : conplayer.z = playermovement; player.rotationy -= 18*math.pi/180; break; } if (movingcrate) { switch (playerangle) { case 0 : movingcrate.x = playermovement; break; case 90 : movingcrate.z = -playermovement; break; case 180 : movingcrate.x = -playermovement; break; case 270 : movingcrate.z = playermovement; break; } } // we need this to know if the player stopped on the destination tile if ((playerangle0==0&&(math.round(conplayer.x*10)/10)%cubesize==0)||(playerangle0!=0&&(math.round(conplayer.z*10)/10)%cubesize==0)) { playermovement=0; levels[playerrow drow][playercol dcol] =4; levels[playerrow][playercol]-=4; if (movingcrate) { levels[playerrow 2*drow][playercol 2*dcol] =3; if (levels[playerrow 2*drow][playercol 2*dcol]==5) { // changing materials on the fly movingcrate.setmaterialtoallfaces(cratetexture); // top of the crate on goal movingcrate.faces[4].material=cratetopgoaltexture; movingcrate.faces[5].material=cratetopgoaltexture; } else { //movingcrate.setmaterialtoallfaces(cratematerial); movingcrate.setmaterialtoallfaces(cratetexture); // top of the crate movingcrate.faces[4].material=cratetoptexture; movingcrate.faces[5].material=cratetoptexture; } levels[playerrow drow][playercol dcol]-=3; movingcrate.name="crate_" (playerrow 2*drow) "_" (playercol 2*dcol); } playercol =dcol; playerrow =drow; } } onenterframe(); } public function correct_camera_angles():void { //set camera position var r:number = 10*cubesize/3; var a:number = -conplayer.rotationy; var cx:number = conplayer.x math.cos(a)*r; var cz:number = conplayer.z math.sin(a)*r; var cy:number = conplayer.y r; controller.setobjectposxyz(cx,cy,cz); //look at player box controller.lookatxyz(conplayer.x,conplayer.y,conplayer.z); //correct camera angles var cproty:number; cproty=math.round(conplayer.rotationy*180/math.pi)60; if (cproty<0) { cproty =360; } if (cproty>180) { camera.rotationx = camera.rotationx (90*math.pi/180)*math.sin((cproty0)*math.pi/180); } camera.rotationy = camera.rotationy 90*math.pi/180-conplayer.rotationy; } public function onenterframe(e:event = null):void { controller.update(); correct_camera_angles(); cplayer.update(); camera.render(); } public function onresize(e:event = null):void { //here you can add border size for view var pd:number = 0; camera.view.width = stage.stagewidth - pd*2; camera.view.height = stage.stageheight - pd*2; camera.view.x = pd; camera.view.y = pd; frame.graphics.clear(); frame.graphics.beginfill(0x000000, 0); frame.graphics.drawrect(0, 0, stage.stagewidth, stage.stageheight); //frame.graphics.linestyle(0, 0x7f7f7f); frame.graphics.drawrect(pd, pd, camera.view.width, camera.view.height); frame.graphics.endfill(); } } }
here you can .
a vnc server is included in every edition of mac os x, including mac os x 10.6 –aka snow leopard. you can start the server through a hidden check box in the sharing preferences.
a vnc server lets you control your mac from another computer using the vncprotocol. with recent editions of mac os x, apple has moved to a more sophisticated method of screen sharing. however, a traditional vnc server is still included but is turned off by default.
starting the mac os x vnc serverlaunch the system preferences
select the sharing preferences icon
enable the screen sharing service
enable vnc and choose a password
your mac is now running a traditional vnc server. you can now connect to your mac using a vnc client running on another mac, windows, or linux computer.
note: the default vnc listening port is 5900
this list is not complete, and your input is appreciated.
concept/language construct | java 5.0 | actionscript 3.0 |
class library packaging | .jar | .swc |
inheritance | class employee extends person{…} | class employee extends person{…} |
variable declaration and initialization | string firstname=”john”; date shipdate=new date(); int i; int a, b=10; double salary; | var firstname:string=”john”; var shipdate:date=new date(); var i:int; var a:int, b:int=10; var salary:number; |
undeclared variables | n/a | it’s an equivalent to the wild card type notation *. if you declare a variable but do not specify its type, the * type will apply. a default value: undefined var myvar:*; |
variable scopes | block: declared within curly braces, member: declared on the class level no global variables | no block scope: the minimal scope is a function local: declared within a function member: declared on the class level if a variable is declared outside of any function or class definition, it has global scope. |
strings | immutable, store sequences of two-byte unicode characters | immutable, store sequences of two-byte unicode characters |
terminating statements with semicolons | a must | if you write one statement per line you can omit it. |
strict equality operator | n/a | === for strict non-equality use !== |
constant qualifier | the keyword final final int state=”ny”; | the keyword const const state:int =”ny”; |
type checking | static (checked at compile time) | dynamic (checked at run-time) and static (it’s so called ‘strict mode’, which is default in flex builder) |
type check operator | instanceof | is – checks data type, i.e. if (myvar is string){…} the is operator is a replacement of older instanceof |
the as operator | n/a | similar to is operator, but returns not boolean, but the result of expression: var orderid:string=”123”; var orderidn:number=orderid as number; trace(orderidn);//prints 123 |
primitives | byte, int, long, float, double,short, boolean, char | all primitives in actionscript areobjects. the following lines are equivalent; var age:int = 25; var age:int = new int(25); |
complex types | n/a | array, date, error, function, regexp, xml, and xmllist |
array declaration and instantiation | int quarterresults[]; quarterresults = int quarterresults[]={25,33,56,84}; | var quarterresults:array or var quarterresults:array=[]; var quarterresults:array= as3 also has associative arrays that uses named elements instead of numeric indexes (similar to hashtable). |
the top class in the inheritance tree | object | object |
casting syntax: cast the class object to person: | person p=(person) myobject; | var p:person= person(myobject); or var p:person= myobject as person; |
upcasting | class xyz extends abc{} abc myobj = new xyz(); | class xyz extends abc{} var myobj:abc=new xyz(); |
un-typed variable | n/a | var myobject:* var myobject: |
packages | package com.xyz; class myclass {…} | package com.xyz{ class myclass{…} } actionscript packages can include not only classes, but separate functions as well |
class access levels | public, private, protected if none is specified, classes have package access level | public, private, protected if none is specified, classes haveinternal access level (similar to package access level in java) |
custom access levels: namespaces | n/a | similar to xml namespaces. namespace abc; abc function mycalc(){} or abc::mycalc(){} use namespace abc ; |
console output | system.out.println(); | // in debug mode only trace(); |
imports | import com.abc.*; import com.abc.myclass; | import com.abc.*; import com.abc.myclass; packages must be imported even if the class names are fully qualified in the code. |
unordered key-value pairs | hashtable, map hashtable friends = new hashtable(); friends.put(“good”, friends.put(“best”, friends.put(“bad”, string bestfriend= friends.get(“best”); // bestfriend is bill | associative arrays allows referencing its elements by names instead of indexes. var friends:array=new array(); friends["best"]=”bill”; friends["bad"]=”masha”; var bestfriend:string= friends[“best”] friends.best=”alex”; another syntax: var car:object = {make:”toyota”, model:”camry”}; trace (car["make"], car.model); // output: toyota camry |
hoisting | n/a | compiler moves all variable declarations to the top of the function, so you can use a variable name even before it’s been explicitly declared in the code. |
instantiation objects from classes | customer cmr = new customer(); class cls = class.forname(“customer”); object myobj= cls.newinstance(); | var cmr:customer = new customer(); var cls:class = flash.util.getclassbyname(“customer”); |
private classes | private class myclass{…} | there is no private classes in as3. |
private constructors | supported. typical use: singleton classes. | not available. implementation of private constructors is postponed as they are not the part of the ecmascript standard yet. to create a singleton, use public static getinstance(), which sets a private flag instanceexists after the first instantiation. check this flag in the public constructor, and if instanceexists==true, throw an error. |
class and file names | a file can have multiple class declarations, but only one of them can be public, and the file must have the same name as this class. | a file can have multiple class declarations, but only one of them can be placed inside the package declaration, and the file must have the same name as this class. |
what can be placed in a package | classes and interfaces | classes, interfaces, variables, functions, namespaces, and executable statements. |
dynamic classes (define an object that can be altered at runtime by adding or changing properties and methods). | n/a | dynamic class person { var name:string; } //dynamically add a variable // and a function var p:person = new person(); p.name=”joe”; p.age=25; p.printme = function () { trace (p.name, p.age); } p.printme(); // joe 25 |
function closures | n/a. closure is a proposed addition to java 7. | mybutton.addeventlistener(“click”, mymethod); a closure is an object that represents a snapshot of a function with its lexical context (variable’s values, objects in the scope). a function closure can be passed as an argument and executed without being a part of any object |
abstract classes | supported | n/a |
function overriding | supported | supported. you must use the override qualifier |
function overloading | supported | not supported. |
interfaces | class a implements b{…} interfaces can contain method declarations and final variables. | class a implements b{…} interfaces can contain only function declarations. |
exception handling | keywords: try, catch, throw, finally, throws uncaught exceptions are propagated to the calling method. | keywords: try, catch, throw, finally a method does not have to declare exceptions. can throw not only error objects, but also numbers: throw 25.3; flash player terminates the script in case of uncaught exception. |
regular expressions | supported | supported |
mysql -u root -p# 2) update password for root (optional)
update mysql.user set password=password('newpasswordforroot') where user='root';
flush privileges;
# 4) grant all privileges for this user
grant all privileges on *.* to 'user1'@'localhost' identified by 'mypassword';
flush privileges;# 5) create a database with char set utf-8create database mydatabase character set utf8;
set character_set_client=utf8;
set character_set_connection=utf8;
set character_set_database=utf8;
set character_set_results=utf8;
set character_set_server=utf8;# 6) switch to a database
use mydatabase;
show tables;
# 7) sample jdbc connection urljdbc:mysql://localhost:3306/mydatabase?useunicode=true&characterencoding=utf-8&autoreconnect=true&failoverreadonly=false
what is shallow copy?
shallow copy is a bit-wise copy of an object. a new object is created that has an exact copy of the values in the original object. if any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
in this figure, the mainobject1 have fields "field1" of int type, and "containobject1" of containobject type. when you do a shallow copy of mainobject1, mainobject2 is created with "field3" containing the copied value of "field1" and still pointing to containobject1 itself. observe here and you will find that since field1 is of primitive type, the values of it are copied to field3 but containedobject1 is an object, so mainobject2 is still pointing to containobject1. so any changes made to containobject1 in mainobject1 will reflect in mainobject2.
now if this is shallow copy, lets see what's deep copy?
what is deep copy?
a deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. a deep copy occurs when an object is copied along with the objects to which it refers.
in this figure, the mainobject1 have fields "field1" of int type, and "containobject1" of containobject type. when you do a deep copy of mainobject1, mainobject2 is created with "field3" containing the copied value of "field1" and "containobject2" containing the copied value of containobject1.so any changes made to containobject1 in mainobject1 will not reflect in mainobject2.
well, here we are with what shallow copy and deep copy are and obviously the difference between them. now lets see how to implement them in java.
how to implement shallow copy in java?
here is an example of shallow copy implementation
how to implement deep copy in java?
here is an example of deep copy implementation. this is the same example of shallow copy implementation and hence i didnt write the subject and copytest classes as there is no change in them.
well, if you observe here in the "student" class, you will see only the change in the "clone()" method. since its a deep copy, you need to create an object of the cloned class. well if you have have references in the subject class, then you need to implement cloneable interface in subject class and override clone method in it and this goes on and on.
there is an alternative way for deep copy.
yes, there is. you can do deep copy through serialization. what does serialization do? it writes out the whole object graph into a persistant store and read it back when needed, which means you will get a copy of the whole object graph whne you read it back. this is exactly what you want when you deep copy an object. note, when you deep copy through serialization, you should make sure that all classes in the object's graph are serializable. let me explain you this alternative way with an example.
in this example, i have created a coloredcircle object, c1 and then serialized it (write it out to bytearrayoutputstream). then i deserialed the serialized object and saved it in c2. later i modified the original object, c1. then if you see the result, c1 is different from c2. c2 is deep copy of first version of c1. so its just a copy and not a reference. now any modifications to c1 wont affect c2, the deep copy of first version of c1.
well this approach has got its own limitations and issues:
as you cannot serialize a transient variable, using this approach you cannot copy the transient variables.
another issue is dealing with the case of a class whose object's instances within a virtual machine must be controlled. this is a special case of the singleton pattern, in which a class has only one object within a vm. as discussed above, when you serialize an object, you create a totally new object that will not be unique. to get around this default behavior you can use the readresolve() method to force the stream to return an appropriate object rather than the one that was serialized. in this particular case, the appropriate object is the same one that was serialized.
next one is the performance issue. creating a socket, serializing an object, passing it through the socket, and then deserializing it is slow compared to calling methods in existing objects. i say, there will be vast difference in the performance. if your code is performance critical, i suggest dont go for this approach. it takes almost 100 times more time to deep copy the object than the way you do by implementing clonable interface.
when to do shallow copy and deep copy?
its very simple that if the object has only primitive fields, then obviously you will go for shallow copy but if the object has references to other objects, then based on the requiement, shallow copy or deep copy should be chosen. what i mean here is, if the references are not modified anytime, then there is no point in going for deep copy. you can just opt shallow copy. but if the references are modified often, then you need to go for deep copy. again there is no hard and fast rule, it all depends on the requirement.
finally lets have a word about rarely used option - lazy copy
a lazy copy is a combination of both shallow copy and deep copy. when initially copying an object, a (fast) shallow copy is used. a counter is also used to track how many objects share the data. when the program wants to modify the original object, it can determine if the data is shared (by examining the counter) and can do a deep copy at that time if necessary.
lazy copy looks to the outside just as a deep copy but takes advantage of the speed of a shallow copy whenever possible. it can be used when the references in the original object are not modified often. the downside are rather high but constant base costs because of the counter. also, in certain situations, circular references can also cause problems.
str="hello world"
1) cut
where -cn-m tells the cut command to return columns n to m, inclusive. cut -cn-m
bash
, consider using cut
. ${str:offset}
${str:offset:length}
sub_str=${str:0:5}
output: hello
3) expr
expr substr string position length
sub_str=`expr substr $str 1 5`
output: hello
treeset | hashset | linkedhashset |
|
|
|
unique values | unique values | unique values |
it stores its elements in a red-black tree | it stores its elements in a hash table | is implemented as a hash table with a linked list running through it |
order : ascending order | undefined | insertion order |
performance : slow | better than linkedhashset | has fast adding to the start of the list, and fast deletion from the interior via iteration |
operations (add , remove and contains ) | operations (add, remove, contains and size) | operations (add, contains and remove) |
add, addall,ceiling,clear,clone,comparator,contains, descendingiterator,descendingset,first,floor, hashset,higher,isempty,iterator,last,lower,pollfirst, remove,size,subset,tailset | , , , , ,, , | , , , , ,, , |
from abstractset:, , | , , | , , |
, , , , | abstractcollection:, , , ,, | , , , ,, |
set:, , , ,, , | , , , ,, , , | , , , , ,, , , , ,, , , , |
定义 | 说明 |
%@ | objective-c object, printed as the string returned by descriptionwithlocale: if available, or description otherwise. also works with cftyperef objects, returning the result of the cfcopydescription function. |
%% | ‘%’ character |
%d, %d, %i | signed 32-bit integer (int) |
%u, %u | unsigned 32-bit integer (unsigned int) |
%hi | signed 16-bit integer (short) |
%hu | unsigned 16-bit integer (unsigned short) |
%qi | signed 64-bit integer (long long) |
%qu | unsigned 64-bit integer (unsigned long long) |
%x | unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and lowercase a–f |
%x | unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and uppercase a–f |
%qx | unsigned 64-bit integer (unsigned long long), printed in hexadecimal using the digits 0–9 and lowercase a–f |
%qx | unsigned 64-bit integer (unsigned long long), printed in hexadecimal using the digits 0–9 and uppercase a–f |
%o, %o | unsigned 32-bit integer (unsigned int), printed in octal |
%f | 64-bit floating-point number (double) |
%e | 64-bit floating-point number (double), printed in scientific notation using a lowercase e to introduce the exponent |
%e | 64-bit floating-point number (double), printed in scientific notation using an uppercase e to introduce the exponent |
%g | 64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise |
%g | 64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise |
%c | 8-bit unsigned character (unsigned char), printed by nslog() as an ascii character, or, if not an ascii character, in the octal format \\ddd or the unicode hexadecimal format \\udddd, where d is a digit |
%c | 16-bit unicode character (unichar), printed by nslog() as an ascii character, or, if not an ascii character, in the octal format \\ddd or the unicode hexadecimal format \\udddd, where d is a digit |
%s | null-terminated array of 8-bit unsigned characters. %s interprets its input in the system encoding rather than, for example, utf-8. |
%s | null-terminated array of 16-bit unicode characters |
%p | void pointer (void *), printed in hexadecimal with the digits 0–9 and lowercase a–f, with a leading 0x |
%l | length modifier specifying that a following a, a, e, e, f, f, g, or g conversion specifier applies to a long double argument |
%a | 64-bit floating-point number (double), printed in scientific notation with a leading 0x and one hexadecimal digit before the decimal point using a lowercase p to introduce the exponent |
%a | 64-bit floating-point number (double), printed in scientific notation with a leading 0x and one hexadecimal digit before the decimal point using a uppercase p to introduce the exponent |
%f | 64-bit floating-point number (double), printed in decimal notation |
%z | length modifier specifying that a following d, i, o, u, x, or x conversion specifier applies to a size_t or the corresponding signed integer type argument |
%t | length modifier specifying that a following d, i, o, u, x, or x conversion specifier applies to a ptrdiff_t or the corresponding unsigned integer type argument |
%j | length modifier specifying that a following d, i, o, u, x, or x conversion specifier applies to a intmax_t or uintmax_t argument |
mac os x uses several data types—nsinteger, nsuinteger,cgfloat, and cfindex—to provide a
consistent means of representing values in 32- and 64-bit environments. in a 32-bit environment,
nsinteger and nsuinteger are defined as int and unsigned int, respectively. in 64-bit environments,
nsinteger and nsuinteger are defined as long and unsigned long, respectively. to avoid the need to
use different printf-style type specifiers depending on the platform, you can use the specifiers shown
in table 2. note that in some cases you may have to cast the value.
类型 | 定义 | 建议 |
nsinteger | %ld or %lx | cast the value to long |
nsuinteger | %lu or %lx | cast the value to unsigned long |
cgfloat | %f or %g | %f works for floats and doubles when formatting; but see below warning when scanning |
cfindex | %ld or %lx | the same as nsinteger |
pointer | %p | %p adds 0x to the beginning of the output. if you don’t want that, use %lx and cast to long. |
long long | %lld or %llx | long long is 64-bit on both 32- and 64-bit platforms |
unsigned long long | %llu or %llx | unsigned long long is 64-bit on both 32- and 64-bit platforms |
the following example illustrates the use of %ld to format an nsinteger and the use of a cast.
1 2 | nsinteger i = 42; printf("%ld\n", (long)i); |
in addition to the considerations mentioned in table 2, there is one extra case with scanning:
you must distinguish the types for float and double. you should use %f for float, %lf for double.
if you need to use scanf (or a variant thereof) with cgfloat, switch to double instead, and copy the double to cgfloat.
1 2 3 4 | cgfloat imagewidth; double tmp; sscanf (str, "%lf", &tmp); imagewidth = tmp; |
it is important to remember that %lf does not represent cgfloat correctly on either 32- or 64-bit platforms.
this is unlike %ld, which works for long in all cases.
ce frumoasa e iubirea 爱情多美丽
fiecare clipa pictata-n roz, 每一分每一秒都涂成了玫瑰色
tre'sa recunosc,iti apartine... 我必须得承认,这属于你
si nici macar eu nu ma cunosc 我已无法认识自己
asa cum ma stii pe mine.. 只有你了解真正的我
ma tem uneori ca ai sa pleci 有时候我担心你将离去,
si nu vreau sa ma lasi fara tine...不要留下孤单的我
iar eu nu sunt eu...而我已不是我,
de fapt,fara tine,sunt nimeni...事实上,没有你,我也将无法存在
refren: ce frumoasa e iubirea ,爱情多美呀!
cand ma alinti cu zambetul tau curat! 当你用纯洁的微笑爱抚我时
ce frumoasa e iubirea 爱情多美呀
cand tot ce spui devine adevarat!当你说的话成真的那一刻
(bis)
ficare clipa trecuta-n alb 白日里度过的每一刻
a insemna ca tu esti departe 告诉你已走远
uneori ma intreb daca esti real 有时候我问自己你是否真的存在
sau inchipuit din printr-o carte! 也许你只是书中的虚幻
ma tem uneori ca ai sa pleci 有时担心你会离去
si nu vreau sa ma lasi fara tine... 不要留下孤单的我
iar eu nu sunt eu... 而我已不是我
de fapt,fara tine,sunt nimeni... 没有你,我也将不再存在
refren: ce frumoasa e iubirea 爱情多美呀
cand ma alinti cu zambetul tau curat! 当你用纯洁的微笑爱抚我时
ce frumoasa e iubirea 爱情多美呀
cand tot ce spui devine adevarat! 当你的话语成真时
(bis)
ma cuprinzi incet..ma stangi la piept 慢慢将我拥入怀中
imi spui ca nu..n-ai sa pleci prea curand... 对我说不。。。不要马上立开我
(bis)
refren: ce frumoasa e iubirea 爱情多美呀
cand ma alinti cu zambetul tau curat! 当你用纯洁的微笑爱抚我时
ce frumoasa e iubirea 爱情多美呀
cand tot ce spui devine adevarat! 当你的话语成真时
(bis)