首页 文章 精选 留言 我的

精选列表

搜索[笔记],共9151篇文章
优秀的个人博客,低调大师

Android Bitmap和Canvas学习笔记

位图是我们开发中最常用的资源,毕竟一个漂亮的界面对用户是最有吸引力的。 1. 从资源中获取位图 可以使用BitmapDrawable或者BitmapFactory来获取资源中的位图。 当然,首先需要获取资源: Resources res=getResources(); 使用BitmapDrawable获取位图 使用BitmapDrawable (InputStream is)构造一个BitmapDrawable; 使用BitmapDrawable类的getBitmap()获取得到位图; // 读取InputStream并得到位图 InputStream is=res.openRawResource(R.drawable.pic180); BitmapDrawable bmpDraw=new BitmapDrawable(is); Bitmap bmp=bmpDraw.getBitmap(); 或者采用下面的方式: BitmapDrawable bmpDraw=(BitmapDrawable)res.getDrawable(R.drawable.pic180); Bitmap bmp=bmpDraw.getBitmap(); 使用BitmapFactory获取位图 (Creates Bitmap objects from various sources, including files, streams, and byte-arrays.) 使用BitmapFactory类decodeStream(InputStream is)解码位图资源,获取位图。 Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic180); BitmapFactory的所有函数都是static,这个辅助类可以通过资源ID、路径、文件、数据流等方式来获取位图。 以上方法在编程的时候可以自由选择,在Android SDK中说明可以支持的图片格式如下:png (preferred), jpg (acceptable), gif (discouraged),和bmp(Android SDK Support Media Format)。 2. 获取位图的信息 要获取位图信息,比如位图大小、像素、density、透明度、颜色格式等,获取得到Bitmap就迎刃而解了,这些信息在Bitmap的手册中,这里只是辅助说明以下2点: 在Bitmap中对RGB颜色格式使用Bitmap.Config定义,仅包括ALPHA_8、ARGB_4444、ARGB_8888、RGB_565,缺少了一些其他的,比如说RGB_555,在开发中可能需要注意这个小问题; Bitmap还提供了compress()接口来压缩图片,不过AndroidSAK只支持PNG、JPG格式的压缩;其他格式的需要Android开发人员自己补充了。 3. 显示位图 显示位图可以使用核心类Canvas,通过Canvas类的drawBirmap()显示位图,或者借助于BitmapDrawable来将Bitmap绘制到Canvas。当然,也可以通过BitmapDrawable将位图显示到View中。 转换为BitmapDrawable对象显示位图 // 获取位图 Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic180); // 转换为BitmapDrawable对象 BitmapDrawable bmpDraw=newBitmapDrawable(bmp); // 显示位图 ImageView iv2 = (ImageView)findViewById(R.id.ImageView02); iv2.setImageDrawable(bmpDraw); 使用Canvas类显示位图 这儿采用一个继承自View的子类Panel,在子类的OnDraw中显示 public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new Panel(this)); } class Panel extends View{ public Panel(Context context) { super(context); } public void onDraw(Canvas canvas){ Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180); canvas.drawColor(Color.BLACK); canvas.drawBitmap(bmp, 10, 10, null); } } } 4. 位图缩放 (1)将一个位图按照需求重画一遍,画后的位图就是我们需要的了,与位图的显示几乎一样:drawBitmap(Bitmapbitmap,Rectsrc,Rectdst,Paintpaint)。 (2)在原有位图的基础上,缩放原位图,创建一个新的位图:CreateBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter) (3)借助Canvas的scale(float sx, float sy) (Preconcat the current matrix with the specified scale.),不过要注意此时整个画布都缩放了。 (4)借助Matrix: Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180); Matrix matrix=new Matrix(); matrix.postScale(0.2f, 0.2f); Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(), bmp.getHeight(),matrix,true); canvas.drawColor(Color.BLACK); canvas.drawBitmap(dstbmp, 10, 10, null); 5. 位图旋转 同样,位图的旋转也可以借助Matrix或者Canvas来实现。 Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180); Matrix matrix=new Matrix(); matrix.postScale(0.8f, 0.8f); matrix.postRotate(45); Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(), bmp.getHeight(),matrix,true); canvas.drawColor(Color.BLACK); canvas.drawBitmap(dstbmp, 10, 10, null); 旋转效果: 6.图片水印的生成方法 生成水印的过程。其实分为三个环节:第一,载入原始图片;第二,载入水印图片;第三,保存新的图片。 /** * create thebitmapfrom a byte array * * @param src thebitmapobject you want proecss * @param watermark the water mark above the src * @return return abitmapobject ,if paramter's length is 0,return null */ privateBitmap createBitmap( Bitmap src, Bitmap watermark ) { String tag ="createBitmap"; Log.d( tag,"create a newbitmap"); if( src ==null) { returnnull; } intw = src.getWidth(); inth = src.getHeight(); intww = watermark.getWidth(); intwh = watermark.getHeight(); //create the new blankbitmap Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 );//创建一个新的和SRC长度宽度一样的位图 Canvas cv =newCanvas( newb ); //draw src into cv.drawBitmap( src,0,0,null);//在 0,0坐标开始画入src //draw watermark into cv.drawBitmap( watermark, w - ww +5, h - wh +5,null);//在src的右下角画入水印 //save all clip cv.save( Canvas.ALL_SAVE_FLAG );//保存 //store cv.restore();//存储 returnnewb; } 7.Canvas的save和restore onDraw方法会传入一个Canvas对象,它是你用来绘制控件视觉界面的画布。 在onDraw方法里,我们经常会看到调用save和restore方法,它们到底是干什么用的呢? save:用来保存Canvas的状态。save之后,可以调用Canvas的平移、放缩、旋转、错切、裁剪等操作。 restore:用来恢复Canvas之前保存的状态。防止save后对Canvas执行的操作对后续的绘制有影响。 save和restore要配对使用(restore可以比save少,但不能多),如果restore调用次数比save多,会引发Error。save和restore之间,往往夹杂的是对Canvas的特殊操作。 例如:我们先想在画布上绘制一个右向的三角箭头,当然,我们可以直接绘制,另外,我们也可以先把画布旋转90°,画一个向上的箭头,然后再旋转回来(这种旋转操作对于画圆周上的标记非常有用)。然后,我们想在右下角有个20像素的圆,那么,onDraw中的核心代码是: int px = getMeasuredWidth(); int py = getMeasuredWidth(); // Draw background canvas.drawRect(0, 0, px, py, backgroundPaint); canvas.save(); canvas.rotate(90, px/2, py/2); // Draw up arrow canvas.drawLine(px / 2, 0, 0, py / 2, linePaint); canvas.drawLine(px / 2, 0, px, py / 2, linePaint); canvas.drawLine(px / 2, 0, px / 2, py, linePaint); canvas.restore(); // Draw circle canvas.drawCircle(px - 10, py - 10, 10, linePaint); 效果如图1所示: 如果我们不调用save和restore会是什么样子呢?如图2所示: 从这两个图中,我们就能看到圆圈位置的明显差异。不进行Canvas的save和restore操作的话,所有的图像都是在画布旋转90°后的画布上绘制的。当执行完onDraw方法,系统自动将画布恢复回来。save和restore操作执行的时机不同,就能造成绘制的图形不同。 本文转自feisky博客园博客,原文链接:http://www.cnblogs.com/feisky/archive/2010/01/10/1643460.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Hadoop- The Definitive Guide 笔记二

TheApache Hadoop projectdevelops open-source software for reliable, scalable, distributed computing, including:Hadoop Core, our flagship sub-project, provides a distributed filesystem (HDFS) and support for the MapReduce distributed computing metaphor. HBasebuilds on Hadoop Core to provide a scalable, distributed database. Pigis a high-level data-flow language and execution framework for parallel computation. It is built on top of Hadoop Core. ZooKeeperis a highly available and reliable coordination system. Distributed applications use ZooKeeper to store and mediate updates for critical shared state. Hiveis a data warehouse infrastructure built on Hadoop Core that provides data summarization, adhoc querying and analysis of datasets. Pig Pig raises thelevel of abstractionfor processing large datasets. With MapReduce, there is a map function and there is a reduce function, and working out how to fit your data processing into this pattern, which often requires multiple MapReduce stages, can be a challenge. Pig is made up of two pieces: The language used to express data flows, calledPig Latin. The execution environment to run Pig Latin programs. There are currently two environments:local executionin a single JVM anddistributed executionon a Hadoop cluster. A Pig Latin program is made up of a series of operations, or transformations, that are applied to the input data to produce output. Taken as a whole, the operations describe adata flow, which the Pig execution environment translates into an executable representation and then runs.Under the covers, Pig turns the transformations into a series of MapReduce jobs, but as a programmer you are mostly unaware of this, which allows you to focus on the data rather than the nature of the execution. Pig is a scripting language for exploring large datasets. One criticism of MapReduce is that the development cycle is very long. Writing the mappers and reducers, compiling and packaging the code, submitting the job(s) and retrieving the results is a timeconsuming business, and even with Streaming, which removes the compile and package step, the experience is still involved.Pig’s sweet spot is its ability to process terabytes of data simply by issuing a half-dozen lines of Pig Latin from the console. 总结一下,Pig是什么,为什么需要这个project,那就要先从MapReduce模型的不足说起 实际使用MapReduce模型时,你首先会碰到的一个问题就是建模问题,给定一个复杂的数据分析问题,怎么样把它抽象,转化成一系列的MapReduce过程,这个往往是比较困难的,是有些技术含量的 在分析抽象成了一系列MapReduce过程,你还要用Java去实现他们,事实证明用Java去实现还是很麻烦的 那么有没有一种Framework,能够让用户仅仅focus在怎样处理data的data flow上,而把这些底层的MapReduce和Java给屏蔽掉,好,Pig粉墨登场了,这个是Yahoo捐给Apache的一个项目,也是模仿google的一个项目开发的。 Pig包含了Pig Latin,一种脚本语言,专门用于描述data flow,看底下的一个例子。 An Example Let’s look at a simple example by writing the program to calculate the maximum recorded temperature by year for the weather dataset in Pig Latin. The complete program is only a few lines long: -- max_temp.pig: Finds the maximum temperature by year records = LOAD ''input/ncdc/micro-tab/sample.txt'' AS (year:chararray, temperature:int, quality:int); filtered_records = FILTER records BY temperature != 9999 AND (quality == 0 OR quality == 1 OR quality == 4 OR quality == 5 OR quality == 9); grouped_records = GROUP filtered_records BY year; max_temp = FOREACH grouped_records GENERATE group, MAX(filtered_records.temperature); DUMP max_temp; 好,这样一段简单的代码就完成了前面也介绍过的,年最高温度的问题,可以和前面用java写的对比一下,你就再也不会想用java写code了 具体什么意思,下面分别解释, Grunt是Pig的命令行程序 grunt> records = LOAD ''input/ncdc/micro-tab/sample.txt'' >> AS (year:chararray, temperature:int, quality:int); For simplicity, the program assumes that the input is tab-delimited text, with each line having just year, temperature, and quality fields. Load这个文件,Load会默认文件中的每行包含一些由Tab隔开的field,每个field是什么意思,即元数据在AS里面指定 grunt> DUMP records; (1950,0,1) (1950,22,1) (1950,-11,1) (1949,111,1) (1949,78,1)grunt> DESCRIBE records; records: {year: chararray,temperature: int,quality: int} 这步你读过去就知道什么意思了grunt> filtered_records = FILTER records BY temperature != 9999 AND >> (quality == 0 OR quality == 1 OR quality == 4 OR quality == 5 OR quality == 9); grunt> DUMP filtered_records; (1950,0,1) (1950,22,1) (1950,-11,1) (1949,111,1) (1949,78,1) The third statement uses the GROUP function to group the records relation by the year field.grunt> grouped_records = GROUP filtered_records BY year; grunt> DUMP grouped_records; (1949,{(1949,111,1),(1949,78,1)}) (1950,{(1950,0,1),(1950,22,1),(1950,-11,1)}) grunt>max_temp = FOREACH grouped_records GENERATE group, MAX(filtered_records.temperature); grunt> DUMP max_temp; (1949,111) (1950,22) 想知道Pig怎么样parse这些脚本语言的,看看下面这段话 As a Pig Latin program is executed, each statement is parsed in turn. If there are syntax errors, or other (semantic) problems such as undefined aliases, the interpreter will halt and display an error message. The interpreter builds alogical planfor every relational operation, which forms the core of a Pig Latin program. The logical plan for the statement is added to the logical plan for the program so far, then the interpreter moves on to the next statement. It’s important to note that no data processing takes place while the logical plan of the program is being constructed. When the Pig Latin interpreter sees the first line containing the LOAD statement, it confirms that it is syntactically and semantically correct, and adds it to the logical plan, but it does not load the data from the file (or even check whether the file exists). Similarly, Pig validates the GROUP and FOREACH ... GENERATE statements, and adds them to the logical plan without executing them. The trigger for Pig to start processing is the DUMP statement (a STORE statement also triggers processing). At that point, the logical plan is compiled into aphysical planand executed. The type of physical plan that Pig prepares depends on the execution environment. For local execution, Pig will create a physical plan that runs in a single local JVM, whereas for execution on Hadoop, Pig compiles the logical plan into a series of MapReduce jobs. You can see the logical and physical plans created by Pig using theEXPLAINcommand on a relation (EXPLAIN max_temp; for example). In MapReduce mode, EXPLAIN will also show the MapReduce plan, which shows how the physical operators are grouped into MapReduce jobs. This is a good way to find out how many MapReduce jobs Pig will run for your query. 总结,Pig在Parse脚本的时候,不是一句一句执行的,而是一条一条去check正确性,都放到Logic Plan里面,再把Logic Plan转化为Physical Plan去执行,这里脚本是local还是distributed执行对于用户透明的,只在转化为Physical Plan的时候,系统做了不同的处理。 那么如果你想知道Pig将你的脚本转化为怎样的MapReduce过程,你可以通过Explain命令去查看, 这个很有意思。 下面列出了Pig Latin的关系操作,从这儿你大概可以看出Pig可以对数据做怎么样的操作Pig Latin relational operatorsCategory Operator Description Loading and storingLOAD Loads data from the filesystem or other storage into a relation STORE Saves a relation to the filesystem or other storage DUMP Prints a relation to the console FilteringFILTER Removes unwanted rows from a relation DISTINCT Removes duplicate rows from a relation FOREACH ... GENERATE Adds or removes fields from a relation STREAM Transforms a relation using an external program Grouping and joiningJOIN Joins two or more relations COGROUP Groups the data in two or more relations GROUP Groups the data in a single relation CROSS Creates the cross product of two or more relations SortingORDER Sorts a relation by one or more fields LIMIT Limits the size of a relation to a maximum number of tuples Combining and splittingUNION Combines two or more relations into one SPLIT Splits a relation into two or more relations HBase HBase is adistributed column-oriented databasebuilton top of HDFS. HBase is the Hadoop application to use when you requirereal-time read/write random-accessto very large datasets. 给出一个HBase的Usecase The canonical HBase use case is thewebtable, a table of crawled web pages and their attributes (such as language and MIME type) keyed by the web page URL. The webtable is large with row counts that run into the billions. Batch analytic and parsing MapReduce jobs are continuously run against the webtable deriving statistics and adding new columns of MIME type and parsed text content for later indexing by a search engine. Concurrently, the table is randomly accessed by crawlers running at various rates updating random rows while random web pages are served in real time as users click on a website’s cached-page feature. Concepts Whirlwind Tour of theData Model Applications store data intolabeled tables. Tables are made of rows and columns. Table cells—the intersection of row and column coordinates—areversioned. By default, their version is a timestamp auto-assigned by HBase at the time of cell insertion. A cell’s content is an uninterpreted array of bytes. Table row keys are alsobyte arrays, so theoretically anything can serve as a row key from strings to binary representations of longs or even serialized data structures.Table rows are sorted by row key, the table’s primary key. Row columns are grouped intocolumn families. All column family members have a common prefix, so, for example, the columns temperature:air and temperature: dew_point are both members of the temperature column family, whereas station:identifier belongs to the station family.The column family prefix must be composed of printable characters. The qualifying tail can be made of any arbitrary bytes. A table’s column families must be specified up front as part of the table schema definition, butnew column family members can be added on demand. Physically,all column family members are stored togetheron the filesystem. So, though earlier we described HBase as a column-oriented store, it would be more accurate if it were described as acolumn-family-oriented store. In synopsis, HBase tables are like those in an RDBMS, onlycells are versioned,rows are sorted, andcolumns can be added on the flyby the client as long as the column family they belong to preexists. 总结,从抽象上你可以理解为Hbase也是采用Table的结构,不同于严谨的关系表,它design的目的就是可扩展性,所以你不用定义每个 column的类型(都是byte arrays),column的个数也是可以每行都不一样的,不会象关系表为稀疏表占用大量的空间,所以他就是一种可扩展的比关系表更灵活的一种表结构。 可是你有没有想过,这种表结构为什么那么灵活,答案就是其实Table只是你想象出来的,它本身并不是什么真正的表结构,尽管Google称为BigTable. 参考:http://jimbojw.com/wiki/index.php?title=Understanding_Hbase_and_BigTable Fortunately,Google''s BigTable Paperclearly explains what BigTable actually is. Here is the first sentence of the "Data Model" section: A Bigtable is asparse,distributed,persistent multidimensional sorted map. The BigTable paper continues, explaining that: The map is indexed by arow key, column key, and a timestamp; each value in the map is anuninterpreted array of bytes. 是的,它只是sorted map by row key,对于它前面那些定语还是比较好理解的,可以参考原文。 Regions Tables are automaticallypartitioned horizontally by HBase into regions. Each region comprises a subset of a table’s rows. A region is defined by its first row, inclusive, and last row, exclusive, plus a randomly generated region identifier. HBase会自动为大表分region,这个对用户是透明的。Implementation Just as HDFS and MapReduce are built of clients, slaves and a coordinating master—namenode and datanodes in HDFS and jobtracker and tasktrackers in MapReduce—so is HBase characterized with anHBase master nodeorchestratinga cluster of one or more regionserver slaves. The HBase master is responsible for bootstrapping a virgin install, for assigning regions to registered regionservers, and for recovering regionserver failures. The master node is lightly loaded. The regionservers carry zero or more regions and field client read/write requests. They also manage region splits informing the HBase master about the new daughter regions for it to manage the offlining of parent region and assignment of the replacement daughters. HBase depends on ZooKeeper and by default it manages a ZooKeeper instance as the authority on cluster state. HBase Versus RDBMS HBase and other column-oriented databases are often compared to more traditional and popular relational databases or RDBMSs. As described previously, HBase is a distributed, column-oriented data storage system. It picks up where Hadoop left off by providing random reads and writes on top of HDFS. Strictly speaking, anRDBMSis a database thatfollows Codd’s 12 Rules. Typical RDBMSs arefixed-schema,row-orienteddatabases withACID propertiesand a sophisticated SQL query engine. The emphasis is onstrong consistency,referential integrity,abstraction from the physical layer, andcomplex queriesthrough the SQL language. You can easily create secondary indexes, perform complex inner and outer joins, count, sum, sort, group, and page your data across a number of tables, rows, and columns. For a majority of small- to medium-volume applications, there is no substitute for the ease of use, flexibility, maturity, and powerful feature set of available open source RDBMS solutions like MySQL and PostgreSQL. However, if you need to scale up in terms of dataset size, read/write concurrency, or both, you’ll soon find that the conveniences of an RDBMS come at an enormous performance penalty and make distribution inherently difficult. The scaling of an RDBMS usually involvesbreaking Codd’s rules, loosening ACID restrictions, forgetting conventional DBA wisdom, and on the way losing most of the desirable properties that made relational databases so convenient in the first place. Countless applications, businesses, and websites have successfully achieved scalable, fault-tolerant, and distributed data systems built on top of RDBMSs and are likely using many of the previous strategies. But what you end up with is something that isno longer a true RDBMS, sacrificing features and conveniences for compromises and complexities. HBase Enter HBase, which has the following characteristics:No real indexes Rows are stored sequentially, as are the columns within each row. Therefore, no issues with index bloat, and insert performance is independent of table size.Automatic partitioning As your tables grow, they will automatically be split into regions and distributed across all available nodes.Scale linearly and automatically with new nodes Add a node, point it to the existing cluster, and run the regionserver. Regions will automatically rebalance and load will spread evenly.Commodity hardware Clusters are built on1,000–1,000–5,000 nodes rather than $50,000 nodes. RDBMS are hungry I/O, which is the most costly type of hardware.Fault tolerance Lots of nodes means each is relatively insignificant. No need to worry about individual node downtime.Batch processing MapReduce integration allows fully parallel, distributed jobs against your data with locality awareness. If you stay up at night worrying about your database (uptime, scale, or speed), then you should seriously consider making a jump from the RDBMS world to HBase. 总结,关系数据库什么都好,成熟稳定,严谨,但就是没有办法处理large scale data, 现在有很多正对关系数据库的large scale 的优化的solution,不过那些都破坏了其本源的那些准则和属性,这样使得它很多优点无法体现。 所以面对Large Scale data,来试试HBase吧,上面列出了那么多优点,还犹豫什么^_^ 同类型的NoSql数据库 here are other projects competing for the same position in the stack, in particular Facebook''sCassandraand LinkedIn''sProject Voldemort ZooKeeper 分布式环境中大多数服务是允许部分失败,也允许数据不一致,但有些最基础的服务是需要高可靠性,高一致性的,这些服务是其他分布式服务运转的基础,比如naming service、分布式lock等,这些分布式的基础服务有以下要求: 高可用性 高一致性 高性能 对 于这种有些挑战CAP原则的服务该如何设计,是一个挑战,也是一个不错的研究课题,Apache的ZooKeeper也许给了我们一个不错的答案。 ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,它暴露了一个简单的原语集,分布式应用程序可以基于它实现同步服务,配置维护和命 名服务等。(http://blog.csdn.net/cutesource/archive/2010/08/18/5822459.aspx) 对于Hadoop,它的namenode或jobtracker就是一种重要的基础的node,必须要保证他们的高可用性,这就可以用 zookeeper来维护他们。对于Hbase也是这样的,依赖zookeeper来协调MasterServer,和RegionServer。 那么ZooKeeper的工作原理是什么了 ZooKeeper is a highly available, high-performance coordination service. Data Model ZooKeeper maintains ahierarchical tree of nodescalledznodes. A znode stores data and has an associated ACL. ZooKeeper is designed for coordination (which typically uses small data files), not high-volume data storage, so there is a limit of 1 MB on the amount of data that may be stored in any znode. ZooKeeper是用来存放一些coordination信息的,这些信息一般比较小,在zookeeper中是以一种hierarchical tree的形式来存放,这些具体的信息就store在tree node中,称为znode。 Data access is atomic.所有读写操作都是原子的 Znodes are referenced by paths, which in ZooKeeper are represented as slash-delimited Unicode character strings, like filesystem paths in Unix. 比如/zoo/duck, /zoo/cow Ephemeral znodes Znodes can be one of two types:ephemeral or persistent. A znode’s type is set at creation time and may not be changed later. An ephemeral znode is deleted by ZooKeeper when the creating client’s session ends. Ephemeral znodes are ideal for building applications that needs to know when certain distributed resources are available. 这边znode是有一种叫零时znode,这种当client session结束时会自动delete,后面讲到的lock service就会用到 Sequence numbers Asequential znodeis given a sequence number by ZooKeeper as a part of its name. If a znode is created with the sequential flag set, then the value of a monotonically increasing counter (maintained by the parent znode) is appended to its name. Sequence numbers can be used toimpose a global ordering on eventsin a distributed system, and may be used by the client to infer the ordering. 后面讲到的lock service,you will learn how to use sequential znodes to build a shared lock Watches Watches allow clients to get notifications when a znode changes in some way. Watches are set by operations on the ZooKeeper service, and are triggered by other operations on the service. There is an example in “A Configuration Service” demonstrating how to use watches to update configuration across a cluster. Watch就是可以在znode对某种操作加上trigger,如exist,change,当这种操作发生时,watch就会发notification给client Operations Operation Description create Creates a znode (the parent znode must already exist) delete Deletes a znode (the znode may not have any children) exists Tests whether a znode exists and retrieves its metadata getACL, setACL Gets/sets the ACL for a znode getChildren Gets a list of the children of a znode getData, setData Gets/sets the data associated with a znode sync Synchronizes a client’s view of a znode with ZooKeeper 这儿列出对znode的操作 Implementation The ZooKeeper service can run in two modes. Instandalonemode, there is a single ZooKeeper server, which is useful for testing due to its simplicity (it can even be embedded in unit tests), but provides no guarantees of high-availability or resilience. In production, ZooKeeper runs inreplicatedmode, on a cluster of machines called anensemble. ZooKeeper achieves high-availability through replication, and can provide a service as long as a majority of the machines in the ensemble are up. 前面说了,Zookeeper通过hierarchical tree来保存信息,但是standalone模式,其实没有实用价值的,单点局限,一个挂了就挂了。所以只有replicated模式才是high- availability的,只要cluster中majority servers是正常的,那么Zookeeper服务就是可用的 但是有个问题, 你在多台server,及ensemble上保存data,怎样保证所有server上数据的一致性,即Consistency,他是用了如下的方法 ZooKeeper uses a protocol calledZabthat runs in two phases, which may be repeated indefinitely: Phase 1:Leader election The machines in an ensemble go through a process of electing a distinguished member, called theleader. The other machines are termedfollowers. This phase is finished once a majority (or quorum) of followers have synchronized their state with the leader. Phase 2:Atomic broadcastAll write requests are forwarded to the leader, which broadcasts the update to the followers.When a majority have persisted the change, the leader commits the update, and the client gets a response saying the update succeeded. The protocol for achieving consensus is designed to be atomic, so a change either succeeds or fails. It resembles two-phase commit. If the leader fails, the remaining machines hold another leader election and continue as before with the new leader. If the old leader later recovers, it then starts as a follower. Does ZooKeeper Use Paxos? No. ZooKeeper’s Zab protocol is not the same as the well-known Paxos algorithm Google’sChubbyLock Service , which shares similar goals with ZooKeeper, is based on Paxos. 但是可用认为Zookeeper是对Paxos的优化实现,对于Paxos的相关资料如下 Paxos Made Simple【翻译】http://blog.csdn.net/sparkliang/archive/2010/07/16/5740882.aspx Paxos在大型系统中常见的应用场景 http://timyang.net/distributed/paxos-scenarios/ Consistency The terms “leader” and “follower” for the machines in an ensemble are apt, for they make the point that a follower may lag the leader by a number of updates. This is a consequence of the fact that only a majority and not all of the ensemble needs to have persisted a change before it is committed. follower对数据的更新肯定会lag于leader,而leader当majority的follower persisted achange的时候就会commit Every update made to the znode tree is given aglobally unique identifier, called azxid(which stands for “ZooKeeper transaction ID”). Updates are ordered, so if zxid z1 is less than z2, then z1 happened before z2, according to ZooKeeper, which is the single authority on ordering in the distributed system. 只是为什么所有的更新都要发给leader,需要一个globlly id来保证update的时序性 The followingguarantees for data consistency flowfrom ZooKeeper’s design:Sequential consistency Updates from any particular client are applied in the order that they are sent.Atomicity Updates either succeed or fail. This means that if an update fails, no client will ever see it. Single system image A client will see the same view of the system regardless of the server it connects to.Durability Once an update has succeeded, it will persist and will not be undone. This means updates will survive server failures. 每个znode的更新都是先更新persist设备,即硬盘,再更新memory Timeliness The lag in any client’s view of the system is bounded, so it will not be out of date by more than some multiple of tens of seconds. This means that rather than allow a client to see data that is very stale, a server will shut down, forcing the client to switch to a more up-to-date server. 下面举两个利用zookeeper的例子吧 A Configuration Service One of the most basic services that a distributed application needs is a configuration service so that common pieces of configuration information can be shared by machines in a cluster. At the simplest level, ZooKeeper can act as a highly available store for configuration, allowing application participants to retrieve or update configuration files. Using ZooKeeper watches, it is possible to create an active configuration service, where interested clients are notified of changes in configuration. A Lock Service A distributed lock is a mechanism for providing mutual exclusion between a collection of processes. At any one time, only a single process may hold the lock. Distributed locks can be used for leader election in a large distributed system, where the leader is the process that holds the lock at any point in time. 这儿的leader election,不同于zookeeper的leader election, 这儿讲的是一种通用的算法。 The pseudocode for lock acquisition is as follows: 1. Create anephemeral sequential znodenamed lock- under the lock znode and remember its actual path name (the return value of the create operation). 2. Get the children of the lock znode and set a watch. 3. If the path name of the znode created in 1 has the lowest number of the children returned in 2, then the lock has been acquired. Exit. 4. Wait for the notification from the watch set in 2 and go to step 2. The idea is simple: first designate a lock znode, typically describing the entity being locked on, say /leader; then clients that want to acquire the lock create sequential ephemeral znodes as children of the lock znode. At any point in time, the client with the lowest sequence number holds the lock. 其实过程是这样的 当一个client需要aquire lock的时候,和zookeeper建立session,并创建一个ephemeral sequential znode,所以产生的znodename是按照这个client aquire时的情况递增的,比如前面已有client 产生过lock-1,这时候你去aquire就会产生lock-2 znode lock-number最小的那个znode所对应的client得到这个lock,当它用完这个lock,需要释放lock时,这需要断开这个 client session,因为创建的是ephemeral znode,所以当session断开的时候,znode会自动删除。 It will be notified that it has the lock by creating a watch that fires when znodes go away. 你可用看到, client设置的watch只能触发一次,所以当有个znode被删除的时候,会给所有的client发notification,client收到后 check删除的是不是前一个znode,如果是那么就得到了lock,如果不是还要继续设置watch,就是上面第4步 这个的触发模式,当client很多时,会比较低效,一下要发出大量的notification,而其中只有一条是有用的,所以应该优化成watch 某一个znode被删除的情况。 Server Monitor Imagine a group of servers that provide some service to clients. 必须保持一个group membership list用于用户查询那些server可用,并当server fail的时候将他从list里面删除,server recover后自动加到list中。 The membership list clearly cannot be stored on a single node in the network, as the failure of that node would mean the failure of the whole system (we would like the list to be highly available). Suppose for a moment that we had a robust way of storing the list. We would still have the problem of how to remove a server from the list if it failed. Some process needs to be responsible for removing failed servers, but note that it can’t be the servers themselves, since they are no longer running! 你看这个问题还是比较麻烦的, 首先不能存在单点,不然单点fail了,整个service都挂了, 那就是要存在多台服务器上,保持replica,那么多台服务器上的data consistency就是一个很大的问题。就算这个问题解决了, 我们怎么样监控这个server,并动态的把fail的从list中删除,我们可用单独的进程去做这事,但如果这个进程所在的server崩溃了,怎么 办,好,是不是已经头大了 OK,Zookeeper可以比较好的解决这个问题, 只是我的理解,书中没说 对于每个服务器,当它启动时,自动建立一个client和zookeeper建立session,并创建一个ephemeral znode,client会不断的发送heartbeat保持这个session 这样当所有server都启动时, 他们在zookeeper上都有一个代表自己的znode, 而zookeeper的这个hierarchical tree就构成了这个服务group membership list,那么zookeeper是replica的,不用担心单点问题 当某个服务器crash,那么它建立的client的session会结束,那么它创建的那个znode,会被自动删除,因为是ephemeral的znode 这样就不需要单独的进程去监控server情况,并特意把fail的server从list中删除 同样当server recover的时候,会再次自动的创建client 建立session,也不需要其他进程干涉 这样用户只要通过查询zookeeper就可用知道那些server是可用的了 艾,牛啊,这个zookeeper真是很不容易理解。。。 Hive 为什么需要Hive When we started using Hadoop, we very quickly became impressed by its scalability and availability. However, we were worried about widespread adoption, primarily because of the complexity involved in writing MapReduce programs in Java (as well as the cost of training users to write them). We were aware that a lot of engineers and analysts in the company understood SQL as a tool to query and analyze data and that a lot of them were proficient in a number of scripting languages like PHP and Python. As a result, it was imperative for us to develop software that couldbridge this gapbetween thelanguages that the users were proficientin and the languages required toprogram Hadoop. Hadoop在scalability和availability方面非常的好,但是对于用Java来编写Map Reduce程序比较麻烦也比较困难。大多数程序员对SQL,和类似PHP,Python的脚本语言比较熟悉,所以如果我们能够直接用SQL-like语 言来对HDFS中存放的海量数据进行查询和处理就会非常方便,那么Hive就可以提供这样的功能。 Hive产生的动机和Pig比较相似,都是为了开发一套基于Hadoop的统一编程接口,来降低开发和使用Map Reduce的门槛,他们的之间的是有一定的overlap的。不过Pig使用Pig latin脚本语言,而Hive使用SQL-like语言,Pig Latin is procedural, where SQL is declarative. 所以他们使用的usecase还是有所不同的,Pig Latin更适合用来描述这个Data flow的处理过程,而Hive适合用于对海量数据进行查询访问 http://developer.yahoo.com/blogs/hadoop/posts/2010/08/pig_and_hive_at_yahoo/ 对于两者的区别参看上面的这个链接,说的比较清楚 Let me begin with a little background on processing and using large data. Data processing often splits into three separate tasks: data collection, data preparation, and data presentation. Thedata preparationphase is often known as ETL (Extract Transform Load) or thedata factory. Thedata presentationphase is usually referred to as thedata warehouse. Pig(combined with a workflow system such as Oozie) is best suited for thedata factory, andHivefor thedata warehouse. Hive是什么 Hive is adata warehouse infrastructurebuilt on top of Hadoop and serves as the predominant tool that is used to query the data stored in Hadoop at Facebook. A system that couldmodel data as tablesandpartitionsand that could also provide aSQL-like languagefor query and analysis. Also essential was the ability to plug in customized MapReduce programs written in the programming language of the user’s choice into the query. 这儿说Hive是数据仓库,model data as tables,partitions,自然会想到Hive和Hbase有什么不同 http://stackoverflow.com/questions/24179/how-does-hive-compare-to-hbase Hive is an analytics tool. Just like pig, it was designed for ad hoc batch processing of potentially enourmous amounts of data by leveraging map reduce. Think terrabytes. Imagine trying to do that in a relational database... HBase is a column based key value store based on BigTable. You can''t do queries per say, though you can run map reduce jobs over HBase. It''s primary use case is fetching rows by key, or scanning ranges of rows. A major feature is being able to have data locality when scanning across ranges of row keys for a ''family'' of columns. 从上面这段可以看出,Hbase和Hive其实问题域是不一样的,Hbase主要是为Hadoop提供low latency的随机访问能力,而Hive是为Hadoop提供一套SQL-like的分析和查询工具,Hive并不能保证low latency。 Hive is based on Hadoop which is a batch processing system. Accordingly, this system does not andcannot promise low latencies on queries. For Hive queries response times for even the smallest jobs can be of the order of 5-10 minutes and for larger jobs this may even run into hours. From one perspective, Hive consists of five main components: a SQL-like grammar and parser, a query planner, a query execution engine, a metadata repository, and a columnar storage layout. Its primary focus is data warehouse-style analytical workloads, so low latency retrieval of values by key is not necessary. Data organization Data is organized consistently across all datasets and is stored compressed, partitioned, and sorted:Compression Almost all datasets are stored as sequence files using gzip codec. Older datasets are recompressed to use the bzip codec that gives substantially more compression than gzip. Bzip is slower than gzip, but older data is accessed much less frequently and this performance hit is well worth the savings in terms of disk space.Partitioning Most datasets are partitioned by date. Going forward, we are also going to be partitioning data on multiple attributes (for example, country and date).Sorting Each partition within a table is often sorted (and hash-partitioned) by unique ID (if one is present). 本文章摘自博客园,原文发布日期:2011-07-04

优秀的个人博客,低调大师

Android 动画使用的笔记整理

//=================【frame animation 帧动画】=============================== Frame动画是一系列图片按照一定的顺序展示的过程,和放电影的机制很相似,我们称为逐帧动画。 Frame动画可以被定义在XML文件中,也可以完全编码实现。(animation-list,标签内容没有提示,就手动添加) 《studio 中 需要在drawable里边创建 frame动画的文件。animation-list》 实现方法两种: 1)xml中的实现方法 在/res下的anim或drawable目录中(/res/[anim |drawable]/filename.xml), 文件名可以作为资源ID在代码中引用; 1、[xml文件的语法] <?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot=["true" | "false"] > <item android:drawable="@[package:]drawable/drawable_resource_name" android:duration="integer" /> </animation-list> <item>元素代表一帧动画,android:drawable指定此帧动画所对应的图片资源,android:druation代表此帧持续的时间,整数,单位为毫秒。 Android:onshot如果定义为true的话,此动画只会执行一次,如果为false则一直循环。 2、图片放于drawable目录 ImageView image = (ImageView) findViewById(R.id.frame_image); image.setBackgroundResource(R.anim.frame); //将动画资源文件设置为ImageView的背景 //or xml.布局中,android:background="@anim/mywifi_animation" / //获取ImageView背景,此时已被编译成AnimationDrawable AnimationDrawable anim = (AnimationDrawable) image.getBackground(); anim.start(); //开始动画 在onCreate中调用AnimationDrawable的start方法时,窗口Window对象还没有完全初始化, AnimationDrawable不能完全追加到窗口Window对象中,那么该怎么办呢? 我们需要把这段代码放在onWindowFocusChanged方法中,当Activity展示给用户时,onWindowFocusChanged方法就会被调用,我们正是在这个时候实现我们的动画效果。 当然,onWindowFocusChanged是在onCreate之后被调用的,如图: public void stopFrame(View view) { if (anim.isRunning()) { //如果正在运行,就停止 anim.stop(); } } 2)Java代码实现的帧动画 public void runFrame(View view) { //完全编码实现的动画效果 AnimationDrawable anim = new AnimationDrawable(); for (int i = 1; i <= 4; i++) { //根据资源名称和目录获取R.java中对应的资源ID int id = getResources().getIdentifier("f" + i, "drawable", getPackageName()); //根据资源ID获取到Drawable对象 Drawable drawable = getResources().getDrawable(id); //将此帧添加到AnimationDrawable中 anim.addFrame(drawable, 300); } anim.setOneShot(false); //重复的次数 image.setBackgroundDrawable(anim); //将动画设置为ImageView背景 anim.start(); //开始动画 } //===========【Tween Animation:(补间动画)】================= 补间动画就是我们只需指定开始、结束的“关键帧“,而变化中的其他帧由系统来计算,不必自己一帧帧的去定义。 四种子类:AlphaAnimation(透明度动画)、ScaleAnimation(缩放动画)、TranslateAnimation(位移动画)、RotateAnimation(旋转度动画)。 /* 1.动画时间 duration 2.是否循环 3.开始位置坐标 4. 动画属性 ,由快到慢 etc */ AnimationSet animationSet = new AnimationSet(true); AlphaAnimation:淡入淡出动画 // 动画1:透明度变化: 1.0 fully opaque 完全不透明;0.0 fully transparent 完全透明 AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0); alphaAnimation.setDuration(2000);// 持续时间 animationSet.addAnimation(alphaAnimation); imageView.startAnimation(animationSet); TranslateAnimation:位移动画 // 平移动画设置 TranslateAnimation translateAnimation = new TranslateAnimation(0, 150, 0, 0); // new TranslateAnimation( // Animation.RELATIVE_TO_SELF, 10f, Animation.RELATIVE_TO_SELF, 50.0f, // Animation.RELATIVE_TO_SELF, 10f, Animation.RELATIVE_TO_SELF, 50.0f); translateAnimation.setDuration(2000); translateAnimation.setInterpolator(new AccelerateInterpolator()); /** * TranslateAnimation * @setFillAfter的设置如果为true,则动画执行完之后效果定格在执行完之后的状态 * @setFillBefore的设置如果为true,则动画执行完之后效果定格在执行完之前的状态 * @setStartOffset设置的是一个long类型的值,是指动画延迟多少毫秒之后执行 * @setRepeatCount定义的是动画重复几次执行 */ translateAnimation.setRepeatCount(3); translateAnimation.setStartOffset(2000); animationSet.setFillAfter(false); animationSet.setFillBefore(true); animationSet.addAnimation(translateAnimation); imageView.startAnimation(animationSet); ScaleAnimation:缩放动画 // 前四个参数,x、y方向上从什么倍数缩放到什么倍数,后面四个参数是相对在什么位 // 置进行缩放。跟平移差不多一个意思 ScaleAnimation scaleAnimation = new ScaleAnimation(1, 0.1f, 1, 0.1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); scaleAnimation.setDuration(2000); animationSet.addAnimation(scaleAnimation); imageView.startAnimation(scaleAnimation); RotateAnimation:旋转动画 // 后面的四个参数定义的是旋转的圆心位置 RotateAnimation rotateAnimation = new RotateAnimation(0, -359, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotateAnimation.setDuration(2000); rotateAnimation.setInterpolator(new LinearInterpolator());//恒定变化 rotateAnimation.setRepeatCount(-1); animationSet.addAnimation(rotateAnimation); imageView.startAnimation(animationSet); 以上是java的实现: //--------------------------------------------------------------- 以下是xml的实现补间动画的方法tween //res/anim 文件夹建立 *.xml动画的文件, 格式如下 <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="false" android:fillBefore="true"> <alpha android:duration="2000" android:fromAlpha="1.0" android:toAlpha="0" /> <!-- 透明度控制动画效果 alpha 浮点型值: fromAlpha 属性为动画起始时透明度 toAlpha 属性为动画结束时透明度 说明: 0.0表示完全透明 1.0表示完全不透明 以上值取0.0-1.0之间的float数据类型的数字 长整型值: duration 属性为动画持续时间 说明: 时间以毫秒为单位 --> <translate android:duration="1000" android:fromXDelta="-50%p" android:toXDelta="0" /> <!-- translate 位置转移动画效果 整型值: fromXDelta 属性为动画起始时 X坐标上的位置 toXDelta 属性为动画结束时 X坐标上的位置 fromYDelta 属性为动画起始时 Y坐标上的位置 toYDelta 属性为动画结束时 Y坐标上的位置 注意: 不管是100%还是100%p,都应该是以控件所在的位置为起始点开始 没有指定fromXType toXType fromYType toYType 时候,默认是以自己为相对参照物 android:toXDelta="100%",表示自身的100%,也就是从View自己的位置开始。 android:toXDelta="80%p",表示父层View的80%,是以它父层View为参照的。 长整型值: duration 属性为动画持续时间 说明: 时间以毫秒为单位 --> <rotate android:duration="3000" android:fromDegrees="0" android:interpolator="@android:anim/accelerate_decelerate_interpolator" android:pivotX="50%" android:pivotY="50%" android:toDegrees="+1080" /> <!-- rotate 旋转动画效果 浮点数型值: fromDegrees 属性为动画起始时物件的角度 toDegrees 属性为动画结束时物件旋转的角度 可以大于360度 说明: 当角度为负数――表示逆时针旋转 当角度为正数――表示顺时针旋转 (负数from――to正数:顺时针旋转) (负数from――to负数:逆时针旋转) (正数from――to正数:顺时针旋转) (正数from――to负数:逆时针旋转) pivotX 属性为动画相对于物件的X坐标的开始位置 pivotY 属性为动画相对于物件的Y坐标的开始位置 说明: 都是以物件所在的位置起始点 以上两个属性值 从0%-100%中取值 50%:物件的X或Y方向坐标上物件长度的一半的距离 50%p为物件在X或Y方向坐标上屏幕的一半的距离 长整型值: duration 属性为动画持续时间 说明: 时间以毫秒为单位 --> <scale android:duration="5000" android:fromXScale="0.0" android:fromYScale="0.0" android:interpolator="@android:anim/accelerate_decelerate_interpolator" android:pivotX="50%" android:pivotY="50%" android:toXScale="4.0" android:toYScale="4.0" /> <!-- 尺寸伸缩动画效果 scale android:fillAfter="true" 动画停留在最后一帧。只在<set />里面在有作用 属性:interpolator 指定一个动画的插入器 使用android.res.anim中的资源时候发现有三种动画插入器 accelerate_decelerate_interpolator 加速-减速 动画插入器 accelerate_interpolator 加速-动画插入器 decelerate_interpolator 减速- 动画插入器 其他的属于特定的动画效果 浮点型值: fromXScale 属性为动画起始时 X坐标上的伸缩尺寸 toXScale 属性为动画结束时 X坐标上的伸缩尺寸 fromYScale 属性为动画起始时Y坐标上的伸缩尺寸 toYScale 属性为动画结束时Y坐标上的伸缩尺寸 说明: 以上四种属性值 0.0表示收缩到没有 1.0表示正常无伸缩 值小于1.0表示收缩 值大于1.0表示放大 pivotX 属性为动画相对于物件的X坐标的开始位置 pivotY 属性为动画相对于物件的Y坐标的开始位置 说明: 都是以物件所在的位置起始点 以上两个属性值 从0%-100%中取值 50%:物件的X或Y方向坐标上物件长度的一半的距离 50%p为物件在X或Y方向坐标上屏幕的一半的距离 长整型值: duration 属性为动画持续时间 说明: 时间以毫秒为单位 布尔型值: fillBefore是指动画结束时画面停留在第一帧, fillAfter是指动画结束是画面停留在最后一帧。 最关键的问题是,这2个参数不能在</alpha>,</scale>,</translate>,</rotate>中设置,这是没有用的,必须 在动画xml文件的</set>节点中设置 fillAfter 属性 当设置为true ,该动画转化在动画结束后被应用 startOffset, 动画多次执行的间隔时间,如果只执行一次,执行前会暂停这段时间, 单位毫秒 duration,一次动画效果消耗的时间,单位毫秒, 值越小动画速度越快 repeatCount,动画重复的计数,动画将会执行该值+1次 repeatMode,动画重复的模式,reverse为反向,当第偶次执行时,动画方向会相反。 restart为重新执行,方向不变 --> </set> //载入xml动画 //Animation animation = AnimationUtils.loadAnimation(ActivityMain.this, R.anim.name); AnimationSet set = (AnimationSet) AnimationUtils.loadAnimation(this, R.anim.tweentest); // 载入XML文件成Animation对象 view.startAnimation(animation); //动画的监听方法 int i = 0; for (Animation a : set.getAnimations()) { Log.e(TAG, " a = " + i++); if (i == 1) a.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { Log.e(TAG, " start "); } @Override public void onAnimationRepeat(Animation animation) { Log.e(TAG, " repeat "); } @Override public void onAnimationEnd(Animation animation) { Log.e(TAG, " end "); } }); } Activity 入场动画 Intent intent = new Intent(Activity01.this,Activity02.class); startActivity(intent); //1.启动的Activity02的动画;2.当前退出的Activity01的动画 overridePendingTransition(R.anim.myint,R.anim.alpha); //===========【Property Animation:(属性动画)】================= Android 3.0中才引进 :直接更改我们对象的属性 (1)ValueAnimator:包含Property Animation动画的所有核心功能,如动画时间,开始、结束属性值,相应时间属性值计算方法等。应用ValueAnimator有两个步骤 1计算属性值。 2根据属性值执行相应的动作,如改变对象的某一属性。 我们的主是第二步,需要实现ValueAnimator.onUpdateListener接口,这个接口只有一个函数onAnimationUpdate(),将要改变View对象属性的事情在该接口中do。 animation.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { //do your work } }); (2)ObjectAnimator:继承自ValueAnimator,要指定一个对象及该对象的一个属性,当属性值计算完成时自动设置为该对象的相应属性,即完成了Property Animation的全部两步操作。实际应用中一般都会用ObjectAnimator来改变某一对象的某一属性,但用ObjectAnimator有一定的限制,要想使用ObjectAnimator,应该满足以下条件: 1.对象应该有一个setter函数:set(驼峰命名法) 2如下面的例子,像ofFloat之类的工场方法,第一个参数为对象名,第二个为属性名,后面的参数为可变参数,如果values…参数只设置了一个值的话,那么会假定为目的值,属性值的变化范围为当前值到目的值,为了获得当前值,该对象要有相应属性的getter方法:get 3如果有getter方法,其应返回值类型应与相应的setter方法的参数类型一致。 ObjectAnimator oa=ObjectAnimator.ofFloat(tv, alpha, 0f, 1f); oa.setDuration(3000); oa.start(); 如果不满足上面的条件,我们只能乖乖的使用ValueAnimator来创建动画。 (3)Animator.AnimatorListener:可以为Animator设置动画监听,需要重写下面四个方法。 onAnimationStart() onAnimationEnd() onAnimationRepeat() onAnimationCancel() 三种动画的优缺点: (1)Frame Animation(帧动画)主要用于播放一帧帧准备好的图片,类似GIF图片,优点是使用简单方便、缺点是需要事先准备好每一帧图片; (2)Tween Animation(补间动画)仅需定义开始与结束的关键帧,而变化的中间帧由系统补上,优点是不用准备每一帧,缺点是只改变了对象绘制,而没有改变View本身属性。因此如果改变了按钮的位置,还是需要点击原来按钮所在位置才有效。 (3)Property Animation(属性动画)是3.0后推出的动画,优点是使用简单、降低实现的复杂度、直接更改对象的属性、几乎可适用于任何对象而仅非View类,缺点是需要3.0以上的API支持,限制较大!但是目前国外有个开源库,可以提供低版本支持! 三种动画的demo下载地址: Frame动画简单的应用演示 http://download.csdn.net/detail/flyingsir_zw/9541211 Activity入场动画合集 积 分:1437上传资源:44下载资源:98总 排 名:第9346名上传权限:100MB

优秀的个人博客,低调大师

Machine Learning学习笔记(1)Introduction

1、机器学习可以做什么? 搜索引擎、垃圾邮件过滤、人脸识别等等,不仅用于人工智能领域,生物、医疗、机械等很多领域都有应用。 2、机器学习的定义 A computer program is said to learn from experience E with respect to some task T and some performance measure P,if its performance on T,as measured by P,improves with experience E.—-Tom Mitchell 3、监督学习(Supervised Learning) 举个例子:房价预测中,我们可以根据不同的模型预测房价。监督学习又叫回归问题,应该说回归属于监督的一种,意指要预测一个连续值的输出,比如房价预测、肿瘤预测。 4、无监督学习(Unsupervised Learning) 在监督学习的数据集中,比如肿瘤预测,我们可以知道数据集的肿瘤是良性的或者是恶性的,然而在无监督学习的数据集中是没有这种标签的,无监督学习可以把数据集自动分成两种不同的数据簇,所以叫做簇类算法。无监督学习应用很广,比如搜索引擎把同一类的信息归纳到一个组、计算机集群、市场细分、社交网络分析、天文数据分析。 5、鸡尾酒宴会问题 宴会上很多人,都在聊天,声音此起彼伏,所以存在这样一种可能:同一时间两个人同时在说话,我们放两个麦克风在房间里。 麦克风1距离人物1近一点,麦克风2距离人物2近一点,但是麦克风都可以搜到两个人声音的重叠,这是在计算机语音识别领域的一个问题,当前语音识别技术已经可以以较高精度识别一个人所讲的话,但是当说话的人数为两人或者多人时,语音识别率就会极大的降低,这一难题被称为鸡尾酒会问题。 6、学习准备 安装并熟悉Octave编程环境。

优秀的个人博客,低调大师

Hadoop学习笔记(三):Hive简介

定义 Hive是一个构建在Hadoop上的数据仓库框架。可以将结构化的数据文件映射为一张数据库表,并提供完整的sql查询功能,可以将sql语句转换为MapReduce任务进行运行。 其优点是学习成本低,可以通过类SQL语句快速实现简单的MapReduce统计,不必开发专门的MapReduce应用,十分适合数据仓库的统计分析。(来自百度百科~~) metastore metastore是Hive元数据的集中存放地,metastore包括两部分:服务和后台数据的存储。默认情况下,元数据存储在Derby数据库实例中。由于是本地数据库且不支持并发访问,故多作为练手使用。还一种使用其他数据库的方式称为“Local metastore”,支持并发访问,但metestore服务仍然和hive服务运行在同一个进程中,故称之为本地metastore。还有第三种方式:“Remote metastore”,metastore无武器和hive服务运行在不同的进程内,可以提供更好的可管理性和安全性。(怎么配Local metastore和Remte metastore先不搞了,先拿默认方式练手为主~) 和传统数据库的比较 最本质的一点,hive依赖于hdfs和MapReduce! 在传统数据库里,表的模式是在数据加载时强制确定的(写时模式,schema on write),而hive对数据的验证却在查询时进行(读时模式,schema on read);读时模式有利于数据加载,基本上就是纯粹的复制粘贴,且更加灵活,可以以各种不同模式来分析数据。写时模式有利于提升查询性能,因为可以建索引,压缩数据等。 hive不支持更新,事务和索引。(暂时不支持吧,将来谁也说不准~)hive是用来以MR的方式操作HDFS数据的,在这种环境下,全表扫描(full-table scan)是常态操作,而表更新则是通过吧数据变换后放入新表实现。事务方面hive并没有对表的并发访问做什么处理,需要应用程序端自己在应用层实现。(比如类似spring事务) HiveQL 不完全支持SQL-92标准,支持数值型,布尔型,字符串类型等原子类型;数组,映射,结构等复杂类型。 TINYINT,SMALLINT,INT,BUGINT分别对应于java中的byte,short,int,long。 FLOAT,DOUBLE直接对应float,double(废话~) STRING对应于string,而没有其他数据库中的 varchar,varchar2,char等类型。hive的STRING类似于其他数据库中的VARCHAR,但是不能声明最长字符数,理论上STRING最长为2G。 数据类型转换: 任何类型都可以隐式转换为一个范围更广的类型,所有整数类型,float,string(这个有点奇怪)都可以隐式转换为double,tinyint,smallint,int都可以隐式转换为float,double最大,不能隐式转换为任何类型。 可以使用cast执行显式转换,如果转换失败则返回空值null。 复杂类型: Hive有3中复杂类型:ARRAY,MAP和STRUCT;ARRAY,MAP和java中的类似;struct是一种记录类型,封装了一个命名的字段集合。复杂数据类型允许任意层次的嵌套。 操作: “||” 不是字符串连接操作符,而是 “或”操作符,concat函数用来作为连接操作 表: Hive表格逻辑上由存储的数据和描述表格中数据形式的相关元数据组成。数据存放在hdfs中,元数据(metastore)存放在关系数据库中。 Hive中的表分为托管表(managed table)和外部表(external table)两种。托管表是默认情况,托管表会将数据移入Hive的仓库目录(warehouse directory);外部表则直接到外部目录访问数据。 相应的,如果是托管表,LOAD操作将会复制数据到仓库目录,DROP操作将会删除表数据和表的元数据,而外部表则需要在CREATE操作时指定外部数据路径,在DROP操作时,只删除元数据而不碰外部数据。外部表使用EXTERNAL关键字创建。 普遍的用法是把存放在hdfs中的初始数据集用作外部表使,用Hive转换后的数据存入托管表;反过来——外部表可以用作将托管表中的数据导出到HDFS以供其他应用程序使用。 分区和桶 分区的好处是对于同一分区内的数据进行查询的时候将会非常高效,比如按年份分区,查某一年的数据只需要到这个分区中检索就行了。分区是在创建表的时候用 PARTITIONED BY 子句定义的。 CREATE TABLE LOGS(ts BEGINT,line STRING) PARTITIONED BY (dt STRING,country STRING); 在LOAD数据的时候则需要指定分区值: LOAD DATA LOCAL INPUT 'input/hive/partitions/file1' INTO TABLE logs PARTITION (dt='2001-1-1',country='GB'); 在文件系统中,分区只是表目录下嵌套的子目录。如按分区检索数据其实就是按文件系统目录检索数据了。 SHOW PARTITIONS logs; 命令会返回当前表中所有分区信息。PARTITIONED BY 子句中的列是表中正式的列,称为分区列。但是数据文件并不包含这些列,因为在目录中包含了。可以像普通列一样使用分区列(partition column)。 select ts,dt,line from logs where country='GB' 桶可以获得更高的查询处理效率;桶可以使取样操作更高效。使用CLUSTERED BY 子句来制定划分桶所用的列和要划分的桶的个数。 create table bucketed_records(year int,temperature STRING,quality STRING,station STRING) clustered by (year) sorted by (year ASC) into 4 buckets; insert overwrite table bucketed_records select * from records; 桶对应于MR的输出文件分区:一个作业产生的桶(输出文件)和reduce任务个数相同。由于我本地只有一个伪分布环境,只能一个reduce,所以只得到一个桶,一个桶~ 桶文件中包含在这个桶中的记录信息,划分桶的规则是:Hive对值进行哈希并将结果除以桶的个数取余数,这样任何一个桶里都会有一个随机的用户集合。 TABLESAMPLE 子句对表进行取样,这个子句会将查询限定在表的一部分桶内,而不是使用整个表: select * from bucketed_records tablesample(bucket 1 out of 4 on year); 存储格式 Hive从两个维度对表的存储进行管理:“行格式”(row format)和“文件格式”(file format)。行格式指行和一行中的字段如何存储,行格式由SerDe定义(Serializer-Deserializer) 默认格式为分割的文本,每行存储一个数据行。 二进制存储格式:顺序文件和RCFile Hadoop的顺序文件格式是一种针对顺序和记录的通用二进制格式。在Hive中,可以在CREATE TABLE 中通过声明STORED AS SEQUENCEFILE来使用顺序文件。使用顺序文件一个主要的优点是支持可分割的压缩(splittable)。顺序文件时面相行的,这意味着同一行中的字段作为一个顺序文件记录存储在一起。 RCFile按列记录文件,RCFile把表分成行分片(row split),在每一个分片中先存所有行的第一列,再存第二列,以此类推。通过声明STRED AS RCFILE来使用RCFile存储格式。 面向行的存储格式对于那些只访问表中一小部分行的查询比较有效;面相列的存储格式适合同事处理一列中很多列的情况。 导入数据 CREATE TABLE ... AS SELECT INSERT OVERWRITE TABLE LOAD DATA 三种格式,load data 和 insert overwrite table 上面都有示例了,ctas练手一个吧,还有插入partition的示例,多表插入 create table test_records(year int,temperature STRING,quality STRING,station STRING) as select * from records; insert overwrite table target partition (dt='xxx') select col1,col2 from source; insert overwrite table target partition (dt) select col1,col2,dt from source; from souce insert overwrite table table1 select col1,col2 insert voerwrite table tablw2 select col3,col4 ...; CTAS操作是原子的,如果SELECT查询由于某种原因失败,是不会创建新表的。表的操作 该语句可以将更新元数据并且将表目录移动到新名称所对应的目录下: alter table source rename to target; 添加一个新列: alter table target add columns (col3 string); drop表就跟其他sql一致了, 如果是外部表,则只删除元数据,外部数据不会受到影响。查询数据 排序和聚集: Hive的Order By子句对数据进行排序,但是Order By是通过只用一个Reducer来做到这一点的。对于大规模的数据集,效率非常低下。 在很多情况下,并不需要结果是全局排序。此时,可以使用Hive的非标准的扩展SORT BY。 SORT BY:为每个reducer产生一个排序文件; DISTRIBUTE BY X:确保X列相同的数据在同一个reduce分区中; select year,temperature from records distribute by year sort by temperature desc; 内连接: Hive 不支持 where sales.id=things.id 这样的连接操作! select * from sales.*,things.* from sales join things on (sales.id = things.id); 三种外连接:(左外,右外,全外) select * from sales.*.things.* from sales left outer jion things on (sales.id=things.id); select * from sales.*.things.* from sales right outer jion things on (sales.id=things.id); select * from sales.*.things.* from sales full outer jion things on (sales.id=things.id); 半连接: Hive不支持IN操作,但是可以使用left semi join 达到相同的效果:(sales表不能再select 后面出现,感觉类似exist了) select * from things left semi join sales on (sales.id=things.id); 指定map连接: 如果有一个连接表小到足以放入内存,Hive就可以把较小的表放入每个mapper的内存来执行连接操作。在Hive中需要使用注释来指定map连接: select /*+ MAPJOIN(things) */ sales.*,things.* from sales join things on (sales.id=things.id); 子查询: Hive只支持子查询出现在From子句中 select col1,col2 from (select * from records where ... ) a 视图:貌似和其他数据库中视图没啥区别,只是保存元数据,而不执行查询,不物化数据。 使用外部脚本: 使用Hadoop Streaming,TRANSFORM,MAP,REDUCE子句可以在Hive中调用外部脚本 ADD FILE /test.py; SELECT TRANSFORM(COL1,COL2,COL3) FROM TABLE USING 'test.py' AS COL1,COL2; --TRANSFORM(COL1,COL2,COL3) 表示查询本身将把col1,col2,col3作为以制表符分割的行的形式流式传递给脚本test.py FROM ( FROM table MAP col1,col2,col3 USING 'testmap.py' AS col1,col2) map_output REDUCE col1,col2 USING 'testreduce.py' AS col1,col2; 用户自定义函数(user-defined function,UDF) Hive有三种UDF:普通UDF,用户定义聚集函数UDAF,用户定义表生成函数UDTF。 UDF用户操作单个数据行,产生一个数据行作为输出,就像普通函数返回一个返回值; UDAF接受多个输入数据行,产生一个输出数据行,聚集函数好像都如此; UDTF作用于单个数据行,产生多个数据行(一个表)作为输出。 (不想写了~ 这几个鸟函数决定使用到了再来研究了!!!)OVER

优秀的个人博客,低调大师

云计算读书笔记(五)

Hadoop:Google云计算的开源实现 Hadoop是Apache开源组织的一个分布式计算机框架,可以在大量廉价的硬件设备组成的集群上运行应用程序,为应用程序提供一组稳定可靠的接口,旨在构建一个具有高可靠性和良好扩展性的分布式系统。 Hadoop的核心是HDFS,MapReduce和HBase,它们分别对应Google的云计算GFS,MapReduce和Bigtable。 Hadoop主要由以下几个子项目组成: 1)Hadoop Common:原来的Hadoop Core,这是整个Hadoop项目的核心 2)Avro:Hadoop的RPC方案 3)Vhukwa:一个用来管理大型分布式系统的数据采集系统 4)HBase:支持结构化数据存储的分布式数据库,是Bigtable的开源实现 5)HDFS:提供高呑吐量的分布式文件系统,是GFS的开源实现 6)Hive:提供数据摘要和查询功能键的数据仓库 7)MapReduce:大型数据的分布式处理模型 8)Pig:是在MapReduce上构建的一种高级的数据流语言 9)ZooKeeper:用于解决分布式系统中的一致性问题,是Chubby的开源实现 除了开源以外,hadoop还有很多优点: 1)可扩展 2)经济 3)可靠 4)高效 分布式文件系统HDFS 设计前提和目标: 1)处理硬件错误并快速自动恢复 2)流式的数据访问,应用程序以流式读为主,做批量处理,更注重数据访问的高吞吐量 3)超大规模数据集,支持大文件存储,一个单一的HDFS实例能够支撑数以千万计的文件,并且能在一个集群里扩展到数百个节点 4)简单一致性模型,应用程序一般对文件实行一次性写,多次读的访问模式 5)移动计算比移动数据更简单 6)异构软硬件平台间的可移植性 体系结构: HDFS是一个主从结构的体系,HDFS集群有一个NameNode和很多个DataNode组成的。 NameNode管理文件系统的元数据,DataNode存储实际的数据。客户端联系NameNode以获取文件的元数据,而真正的文件I/O操作是直接和DataNode进行交互的。 HDFS的数据都是一次写入多次读取,典型的块大小是64MB 客户端从NameNode获得组成文件的数据块的位置列表,也就是知道数据块被存储在哪些DataNode上,然后客户端直接从DataNode上读取文件,NameNode不参与文件的传输 NameNode使用事件日志记录HDFS元数据的变化,使用映像文件存储文件系统的命名空间 保障可靠性措施: 1)冗余备份 2)副本存放 3)心跳检测,每个DataNode定期接受心跳包和块报告,收到心跳包说明该DataNode工作正常 4)安全模式,在系统启动时会进入一个安全模式,此时不会出现数据块的写操作 5)数据完整性检测,在HDFS文件创建时,计算每个数据块和校验和,并将校验和作为一个单独的隐藏文件保存在命名空间下。客户端获取文件时会做对应的校验检查,如果不同则客户端认为数据块有损坏,将从其它的DataNode获取数据块的副本 6)空间回收,当文件被删除时,会先被移到/trash目录里,只要还在这个目录里就可以很快恢复,目录的清空时间是可配置的 7)元数据磁盘失效,映像文件和事务日志是HDFS的核心数据结构 8)快照,快照支持某个时间的数据复制,当HDFS数据损坏时,可以回滚到过去一个已知正确的时间点。 提升性能的措施: 1)副本选择 2)负载均衡 3)客户端缓存 4)流水线复制 访问接口: 可以通过Java API,也可以使用C语言封装的API 1)org.apache.hadoop.conf:定义了系统参数的配置文件处理API 2)org.apache.hadoop.dfs:Hadoop分布式文件系统(HDFS)模块的实现 3)org.apache.hadoop.fs:定义了抽象的文件系统API 4)org.apache.hadoop.io:定义了通用的I/O API,用于针对网络,数据库,文件等数据对象做读/写操作 5)org.apache.hadoop.ipc:用于网络服务端和客户端的工具,封装了网络异步I/O的基础模块 6)org.apache.hadoop.mapred:Hadoop分布式计算系统(MapReduce)模块的实现 7)org.apache.hadoop.metrics:定义了用于性能统计信息的API,主要用于mapred和dfs模块 8)org.apache.hadoop.record:定义了针对记录的I/O API类及一个记录描述语言的翻译器 9)org.apache.hadoop.tools:定义了一些通用的工具 10)org.apache.hadoop.util:定义了一些公用的API 分布式数据处理MapReduce MapReduce是一种分布式的计算机模型,也是Hadoop的核心 逻辑模型: 将运行在大规模集群上的并行计算过程抽象为两个函数:Map和Reduce,也就是映射和化简 简单说MapReduce就是任务的分解与结果的汇总,Map把任务分解为多个任务,Reduce把分解后的结果汇总起来,得到最终结果 实现机制: 1,分布式并行计算,MapReduce框架由JobTracker和TaskTracker这两类服务调度的。JobTracker是主控服务,只有一个,负责调度和管理TaskTracker 2,本地计算 3,任务粒度,有利于数据的本地性,一个小数据集启动一个Map服务,M个Map任务可以在N台计算机上并行运行,用户可以指定Reduce任务的数量 4,Combine 5,分区,经过连接后可以把产生的中间结果按key的范围划分为R份 6,读取中间结果 7,任务管道 分布式数据化数据表HBase HBase数据库是基于hadoop的项目,是针对Google的Bigtable的开源实现,它与Google的Bigtable相似 逻辑模型: 用户在表格里存储一系列的数据行,每行包含一个可排序的关键字,一个可选的时间戳及一些可能有数据的列 Hadoop的安装 可以使用虚拟机进行模拟,如果机器上没有安装SSH,安装SSH 配置安装JDK,详细步骤网上很多不一一操作了 到apache的hadoop网站上下载hadoop-0.20.2.tar.gz 使用ftp传到相应的服务器上,如果是虚拟机可以到共享文件夹下选择 复制到linux下的usr目录 tar -zxvf hadoop-0.20.2.tar.gz 解压后使用vi找到conf/hadoop-env.sh文件 打开 # The java implementation to use. Required. # export JAVA_HOME=/usr/lib/j2sdk1.5-sun export JAVA_HOME=/opt/jdk1.6.0_27 # Extra Java CLASSPATH elements. Optional. # export HADOOP_CLASSPATH= 安装步骤: hadoop有三种运行模式:单机模式,伪分布式模式和完全分布式模式。 在调试阶段使用单机模式 查看并且运行示例 bin/hadoop jar hadoop-0.20.2-examples.jar wordcount input output cat output/* 查看到的结果如下: [root@LinuxServer hadoop-0.20.2]# cat output/* hadoop 1 hello 2 world 1

优秀的个人博客,低调大师

云计算读书笔记(三)

Amazon云计算AWS 亚马逊的云是业界比较领先的云,主要包括弹性计算云EC2,简单存储服务S3,简单数据库服务Simple DB,简单队列服务SQS,弹性MapReduce服务,内容推送服务CloudFront,电子商务服务DevPay和FPS等。 基础存储架构:Dynamo Dynamo以简单的键值存储,不支持复杂的查询 架构的主要技术 1,数据均衡分布的问题 1)一致性哈希算法 (1)平衡性 (2)单调性 (3)分散性 (4)负载 2)采用的改进算法,引入虚拟结点的概念 3)数据备份 2,数据冲突问题 主要考虑三个因素:可靠性,可用性和一致性 3,容错机制 1)临时故障容错机制 2)永久性故障处理机制 4,成员资格及错误检测 弹性计算云EC2 是Amazon云计算环境的基本平台 主要特性: 1)灵活性 2)低成本 3)安全性 4)易用性 5)容错性 EC2的关键技术: 1)弹性块存储 2)地理区域和可用区域 3)EC2的通信机制 4)弹性负载均衡 5)监控服务 6)自动缩放 7)服务管理控制台 简单存储服务S3 s3是amazon推出的简单存储服务 s3是架构在Dynamo之上的 s3存储涉及的几个基本概念: 1)对象 是基本的存储单元,主要由两部分组成:数据和元数据 2)键 键是对象的唯一标识符 3)桶 桶是一个用来存储对象的容器 4)基本操作 基本操作包括:Get,Put,List,Delete和Head 简单队列服务SQS SQS是Amazon为了解决其云平台之间不同组件的通信而专门设计开发的。 SQS由三个基本部分组成:系统组件,队列和消息 简单数据库服务 Simple DB主要用于存储结构化的数据,并为这些数据提供基本的查找,删除等数据库功能 重要概念: 1)用户账户 2)域 3)条目 4)属性 5)值 关系数据库服务RDS RDS是一种云中的MySQL数据库系统,它采用集群的方式将MySQL移植到云中 内容推送服务CloudFront CloudFront实际上就是一个基于Amazon云计算平台实现的内容分发网络。通过Amazon部署在世界各地的边缘节点,用户可以快速,高效的由CloudFront提供服务的网站进行访问 云内容推送: 1,对象 2,源服务器 3,分发 4,别名指向 5,边缘节点位置 6,有效期 其它Amazon云计算服务 1)快速应用部署Elatic Beanstalk和服务模板CloudFormation 2)云中的DNS服务Router53 3)虚拟私有云VPC 4)简单通知服务SNS和简单邮件服务SES 5)弹性MapReduce服务 6)电子商务服务DevPay,FPS和Simple Pay 7)Amazon执行网络服务 8)土耳其机器人

优秀的个人博客,低调大师

云计算读书笔记(二)

google云计算原理与应用 google云计算服务包括:google文件系统GFS,分布式计算编程模形MapReduce,分布式锁服务Chubby,分布式结构化数据表Bigtable,分布式存储系统Megastore以及分布式监控系统Dapper等。 GFS提供了海量数据的存储和访问能力。 GFS 系统架构: 分为三类角色,client(客户端),Master(主服务器)和Chunk Server(数据块服务器) 1,使用的是中心服务器模块,可以任意添加chunk server. 2,不实现缓存,这是从必要性和可行性两方面考虑。 必要性:客户端大部分是流式读写,不存在大量的重复读写。 可行性:如何维护缓存与实际数据之间一致性是一个极其复杂的问题。加之网络等不确定因素,一致性问题尤为复杂。而且数据量非常大,以当前的内存容量根本无法缓存。 而对于存储在GFS的Master中的数据实现了缓存。 3,在用户状态下实现,正常的文件系统是操作系统的重要组成部分,在内核态实现文件系统可以更好的和操作系统本身结合。 但GFS却选择在用户态下实现,主要基于以下考虑: 1)在用户态下直接利用操作系统提供的POSIX编程接口就可以扩展存取数据,无需了解内部的实现接口。 2)POSIX接口提供的功能更为丰富不受内核编程的限制 3)在用户态下有多种调试工具 4)用户态下,Master和Chunk Server都以进程的方式运行,单个进程不会影响整个操作系统 5)在用户态下,GFS和操作系统运行在不同的空间,两者的耦合性降低,方便GFS自身的扩展和升级 4,只提供专有的接口 容错机制: 1,Master容错 1)命名空间也就是整个文件系统的目录结构 2)Chunk与文件名的映射表 3)Chunk副本的位置信息,每一个Chunk默认有三个副本 2,Chunk Server容错 GFS采用副本的方式实现Chunk Server的容错,默认每个副本存储3个 GFS划分的每一个Chunk的默认大小是64MB 系统管理技术: 1)大规模的集群安装 2)故障检测 3)节点动态加入 4)节能 分存式数据处理MapReduce MapReduce就是“映射”和“化简”的概念和主要思想。 比如查询一个大型文本中各个单词出现的次数,经过Map处理后,形成一批中间结果<单词,出现次数>,而Reduce函数处理中间结果,将相同单词出现的次数累加,得到每个单词出现的次数。 分存式锁服务 Chubby是Google设计的提供粗粒度服务的一个文件系统,它是基于松耦合的分布式系统。 通过使用Chubby的锁服务,用户可以确保数据操作过程中的一致性。 1,Paxos算法 paxos是一种基于消息传送的一致性算法,用于解决分布式中的一致性问题 如何解决分布式中的一致性问题呢,最简单的就是设置一个结点,所有操作都经过这个结点,这样就能保证唯一性的问题。 但是这样缺点也是显而易见的,就是如果结点失效就会出现混乱,所以需要在系统中设置多个这样的结点。 Paxos算法分成三个类型:proposers、acceptors和learners,其中Proposers提出决议,acceptors批准决议,learners获取并使用已经通过的决议。 2,Chubby系统设计 Chubby的设计目标主要有以下几个: 1)高可用性和高可靠性 2)高扩展性 3)支持粗粒度的建议性锁服务 4)服务信息的直接存储 5)支持通报机制 6)支持缓存机制 分存式结构化数据表Bigtable Bigtable是Google基于GFS和Chubby的分布式存储系统。 Bigtable在很多方面跟数据库类似。 数据模型: Bigtable是一个分布式的多维映射表,表中数据通过一个行关键字,一个列关键字以及一个时间戳进行索引。Bigtable对存储在其中的数据不做任何解析,一律看成是字符串。 1)行 可以是任意的字符串,但是大小不能超过64K,排序是根据行关键字进行排序的,推荐使用的是字典序 2)列 有列族的概念,族名:限定词(family:qualifier),族名必须有意义,限定词可以任意选定,同族被压缩存储在一起 族同时也是Bigtable中访问控制的基本单元,也就是说访问权限是在族这一级别上进行的 3)时间戳 默认是64位整数 目前提供两种设置,一种是保留最近N个不同的版本,另一种就是保留限定时间内的所有不同版本 系统架构: Bigtable主要由三部分组成:客户端程序库(Client Library)、一个主服务器(Master Server)和多个子表服务器(Table Server) 客户端访问Bigtable服务时,首先利用函数库执行open操作打开一个锁,锁打开后客户端就可以跟子表服务器进行通信了。 主服务器的作用: 1)新子表分配 2)子表服务器状态监控 3)子服务器之间的负载均衡 子表服务器: 1)SSTable中的数据被划分成一个个的块(Block),每个块的大小是可以设置的,一般为64KB,在SSTable的结尾有一个索引(Index),在SSTable打开时这个索引会被加载进内存,所以查找的速度会非常快。 每个子表都是由多个SSTable和日志组成 2)子表地址,在Bigtable系统的内部采用的是一种类似B+树的三层查询体系 先查根子表,然后找到元数据子表,最后找到对应的用户表 3)子表的数据存储及读写操作 性能优化 1)局部性群组 2)压缩 3)布隆过滤器 分存式存储系统Megastore Megastore:关系型数据库和NoSQL的完美结合 设计目标: 1)针对可用性:引入了Paxos算法 2)针对扩展性:采用数据分区将每个分区存放在NoSQL中 megastore的数据模型 通过类似SQL的方式进行查询,有一套对应的查询语言。 Megastore的核心技术-复制 1)复制的日志 2)数据读取 (1)本地查询 (2)发现位置 (3)追赶 (4)验证 (5)查询数据 3)数据写入 (1)接受leader (2)准备 (3)接受 (4)失效 (5)生效 分存式系统的监控基础框架Dapper 分布式监控系统 基本设计目标: 1)低开销 2)对应用层透明 3)可扩展性

优秀的个人博客,低调大师

云计算读书笔记(一)

云计算的概念 云计算是一种商业计算模型,它将计算任务分布在大量计算机构成的资源池上,使用户能够按需获取计算力、存储空间和信息服务。 云的核心理念就是资源池。 为什么叫云? 因为云一般都比较大,规模可以动态伸缩,而且边界是模糊的,云在空中飘忽不定,无法确定它的具体位置,但是它确实存在于某处,所以叫作云。 形象的比喻 单台发电机转向电厂发电。 云的特点 (1)超大规模 (2)虚拟化,云可以支持任何用户任何终端。 (3)高可靠性,多个副本容错 (4)通用性,一片云可以支撑不同的应用 (5)高可伸缩性 (6)按需服务,定义好的资源池所有资源在池中取 (7)极其廉价,可以使用低成本的节点构成云,从而组成数据中心管理的成本大大降低 云的类型 IAAS 基础设施即服务 PAAS 平台即服务,提供应用程序的运行环境,如google的app engine SAAS 软件即服务 云的现状 Amazon的EC2,提供存储服务,按月收费 Google提供包括地图,gmail,docs等服务,并且发布多个论文公开其三大法宝:GFS、MapReduce和BigTable IBM的“蓝云”计算平台 微软推出Windows Azure操作系统,充分体现“云+端”的战略 云的实现机制 技术上分为四层:物理资源层,资源池层,管理中间件层和SOA构建层。 网格计算 分为三类:计算网格,信息网格和知识网格。 网格即将一定范围内分布的异构资源集成为有机的整体,提供资源共享和协同工作服务的平台,均可以认为是网格。 跟云的最重要区别是网格可能是多个组织的异步资源,云是同一组织的同构资源。 两者相辅相成,从某种意义上来说云是网格的一种变体。 云与3G 3G的三个标准制式:CDMA2000,WCDMA,TD-SCDMA。3G代表高速数据传输的能力能够提供2Mbps以上的带宽。 云与物联网 物联网即“物物相连的网络”,物联网通过大量分散的射频识别(RFID),传感器,GPS,激光扫描器等小型设备,将感知的信息,通过互联网传输到指定的处理设施上进行智能化处理。 物联网根据实质的用途可归结为三种基本应用模式:对象的智能标签,环境监控和对象跟踪。 驱动力方面: 1)需求驱动 2)技术驱动 3)政策驱动 云与移动互联网 互联网的“云”与“端”之间形成的平滑的对接,中间的“管”就是浏览器。 云与三网融合 三网就是指:广播电视网,电信网和互联网,其中互联网是核心。

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码