Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials

7018 Articles
article-image-creating-web-templates-inkscape
Packt
04 Nov 2010
9 min read
Save for later

How to create web templates in Inkscape

Packt
04 Nov 2010
9 min read
Blogs and storefronts have some different elements when designing, however, they also have "pages" within them that use standard items, those that repeat over time. Blogs have posts that all have (at least): headings/titles content in the body options to comment Storefronts have some of the following: lists of items to purchase prices descriptions ratings/comments checkouts or shopping baskets And since these items are common on a number of the website pages, it can use templates for the design. You can create a site based on a template. Here are two quick examples based on each type of site. Designing for blogs Some common parts of many blog site are: the blog header or banner, a sidebar with recent posts (or archives), about section, recent posts, blog roll and/or links section, a main content section that will contain all of the blog posts, then links to their relevant comments, and a footer of the site. Of course you can get as fancy as you would like here, or as simple, but let's design a site based on these simple sections. Here's how it's done: Open Inkscape, and create a new document. From the file menu, select File, New, and Desktop_800x600. When open, create a new layer (Shift + Ctrl + N) and call it Basic Layout. Use the Rectangle Tool to draw rectangles for each of your layout areas in your blog design. For now, use different shades of gray for each area so you can easily distinguish between them at a glance. To change the fill color of a particular rectangle, left click the rectangle and choose a gray shade for the rectangle. Or drag the gray shade from the color palette onto the rectangle. Use sharp edged (not rounded) rectangles. If you need to change to sharp, click the Make Corners Sharp button in the Tool Controls Bar. Make sure your rectangle shapes do not have an outline or stroke. Use the Shift + Left click keypad shortcut to open the Stroke dialog and choose No Color (the icon with an X) to delete the stroke. Position the rectangles so there are no white spaces in-between them. From the main menu choose Object and then Align and Distribute. In the Remove Overlapssection, click the icon. This makes sure that the bounding boxes around each object don't over lap each other and place the objects tangent to each other. Use the Tool Controls Bar W (width): number fi eld to apply a setting of 800.0 px so the Header fills the entire width of the web page. Continue using the steps described to add rectangles for all areas shown below in the rough layout of the blog page we'll be creating. Once all of your areas are blocked out on the canvas, we'll need to convert the current rectangles into guides so we can use the guides when creating our web page layout graphics. We can easily keep the Basic Layout Export layer intact; we need to copy all of the rectangles in this layer. On the main menu, select Edit and then Select All (or use the keyboard shortcut keys Ctrl + A). Then select Edit and Duplicate (or use the keyboard shortcut Ctrl + D) to duplicate all of the elements in this layer. Now you are ready to convert these current shapes into guides. First, select all the rectangles in the top (duplicate) layout. Do this by clicking a rectangle and then holding the Shift key on your keypad. Then click/select the next rectangle. When you have all rectangles selected, from the main menu select Object and then Object to Guide. Your duplicate rectangles will be removed from the canvas and replaced with blue guides. To better see the guides, turn off the grid (from the main menu choose View and Grid) and hide the basic layout layer (click the eye icon). Create a new layer (Shift + Ctrl + N) called Background. Use the rectangle tool to draw a background that fills the entire canvas. Use the control bar, to set the width to 800 and the height to 600. Use the Color Palette to choose a fi ll color of white. In the Status bar, right-click the Stroke setting and select Remove Stroke. Create a new layer (Shift + Ctrl + N) called Header. Click the Create and Edit tool and enter the header title as shown in the following screenshot. Remember to use the control bar to adjust the font type and size. Then, still using the Create and Edit tool, type the sub-title as shown below and, again use the control bar to adjust the font type and size. Create a new layer (Shift + Ctrl + N) called Navigation. Now we need to import the icons that we have created. From the main menu, select File and then Import. Select the SVG file for the icon and then place it on the canvas. Repeat this until you have all five icons on the canvas. Use the rectangle tool to draw the horizontal bars below the title and then below the navigation icons. Use the Color Palette to choose a fill color for the rectangles. For our example, we're using a turquoise color. Select both rectangles, and then in the Status bar, right-click the Stroke setting and select Remove Stroke. With the rectangles still selected open the Align and Distribute dialog (Shift + Ctrl + A) and click the Center on Vertical Axis button. Select all of the icons and then open the Align and Distribute dialog (Shift + Ctrl + A) and click the Distribute Centers Equidistantly Horizontally button. Next we will create the sidebar content. Most of this will be the links to help with navigating to previous posts or static content—content that doesn't change. Create a new layer (Shift + Ctrl + N) called Sidebar. Import a photograph (File and then Import). Place it on the upper left side of the page. Use your guides to place it appropriately on the page. Select the Create and Edit tool, and drag it across your canvas in the area you want to add a block of text to create a textbox. Then start typing placeholder text for an author bio. Use the control bar to adjust font styles and sizes. Again use the guides for left alignment placement. Continue to use the Create and Edit to create any Headings and other text content on the left sidebar. Note that Inkscape does not support bullets or numbers. So any "bullets" will need to be created manually with dashes (-) or importing graphics. Your blog web page should look similar to the following screenshot: Now it is time to create the look of the content portion of the site—where the blog posts will appear. Create a new layer (Shift + Ctrl + N) called Blog Post. Just like with the sidebar text, use the Create and Edit text tool to create text and use the control bar to adjust fonts and sizes. Start with a heading. Then with the Create and Edit text tool selected, drag it across the screen to create a textbox. Add in dummy text or write some placeholder blog post. Again, use the control bar to adjust font and size of the text. Select the heading and the blog post text and align it within your guides. Or use the Align and Distribute dialog (Shift + Ctrl + A) to align items on the page correctly. Now it is time to create the comment, permalink and share this link text. Create a new layer (Shift + Ctrl + N) called Blog Post Footer. Again select the Create and Edit text tool, and type: comment | 0 comments | permalink | share this post. Use the control bar to adjust font and size as needed. Then use the color palette to change the text to red. If desired, use the rectangle tool to draw the horizontal bars to show a break between blog posts. Use the color palette to choose a fill color for the rectangles. For our example, we're using turquoise color. You can save the file, or add additional post examples. Use Steps 37 – 44 to do a second blog post. Your page should now look something like the following example: There will likely also be a sub-page of this content that will show an individual blog post. We can design that page, based on how we want it to look here. Finally, for this page, let's add blog footer with some copyright information to see a completed blog design. Create a new layer (Shift + Ctrl + N) called Footer. Select the horizontal bar under the navigation icon. From the main menu select Edit and then Duplicate. Select the duplicate rectangle and use the guides to place it at the footer area of your web page. Select the Create and Edit text tool and type a copyright attribution statement. In the following example we entered: © 2010 Jane Somebody | All rights reserved. Select both the rectangle in the footer and the copyright text and open the Align and Distribute dialog (Shift + Ctrl + A). Click the Center on Vertical Axis button to center the footer content. As stated in Step 46, there will also likely be a "sub-page" used in a blog to show each individual post as it's unique web address (if you want to link to the one blog post instead of the dynamic stream posts). Here's what this page would look like: As you can see, it looks very much like the main blog page, just without any posts before it, or after it. And in this case, we display the comments on this post directly instead of just making it a link. To modify the existing web page file to match the previous image, you would: Open the existing file in Inkscape. From the main menu select File and then Save a Copy. Give this a new file name. Delete any sample blog posts below the first one. Use the Create and Edit text tool to create the comments, headings, and text. Re-align all text appropriately with guides and the Align and Distribute dialog (Shift + Ctrl + A). Save the file again to save your work.
Read more
  • 0
  • 0
  • 6178

article-image-web-design-principles-inkscape
Packt
04 Nov 2010
8 min read
Save for later

Web Design Principles in Inkscape

Packt
04 Nov 2010
8 min read
Blogs contain entries or posts that can be anything from commentary of life events, videos and pictures to anything else that can be 'posted' online. Blog posts are in reverse-chronological order and allow readers to provide comments and sometime ratings. Sometimes a blog is the entire website, or a blog can be a subset of the entire site. Another critical element of a blog is comments. Readers expect to be able to leave comments about the posts and sometimes rate the content. Thus, the posts themselves and the way they are displayed on a site are important, as it is the main content portion of the site. Clever designs allow for the common elements around the posts to stay the same and consistent, while allowing posts to be updated (and aggregated) frequently. Small business storefronts, or any site that sells a commodity, often has an area that allows you to search through its products and then purchase them through a "shopping cart". These storefronts then need a well designed area to be able to view products, get the specifications, and then add the products to a cart to checkout. It is a process that would be repeated often and used whenever a product is purchased. Web design principles for blogs and storefronts As with general web design there are some guidelines that can help you create effective, clean, and inspired blog and storefront designs. The web design basics should also be taken into account: proximity, alignment, repetition, and contrast—but also here are a few other pointers. Keeping it simple For blogs, there are more widgets and plugins you can add into your blog than you have space for—and more than is ever really needed. Be particular and choosy. Use only those that make sense for the type of reader you want to attract. Otherwise it becomes visual clutter. Choose sidebar features wisely and keep it to a bare minimum. Some basics are: a picture or more information about yourself, how to contact you (if you like), links to other similar blogs links to some of your past posts (favorites, archives, most mentioned), and links to any other websites you contribute to and/or own. When designing storefronts or any websites where your end goal is to have someone purchase an item—don't distract a user from their main goal of purchasing an item. If you add in sidebars with too much distraction, you'll lose the ever-dwindling window of opportunity for a purchase. Keep the important items front and center: a shopping cart, account information, check out. Identifiable You have about a five second window to attract and keep a reader on your website. So, use those seconds wisely and give your viewers everything they need to know about you and your blog or store within that first five seconds. How can you do this? Use your header wisely. A graphical title, tagline that is prominent and expressive can do it all, and quickly. This should be placed in the "header" location of your web design. When blogging this is critical, since most blogs are text-based, most viewers won't take the time to read but a few sentences unless you entice them to stay on your site and read along for a while. For any storefront, if you keep your company name, and a graphical representation of what they might find in your online store, then you too will encourage a casual browser to "click around" and see what else you have for them to browse. This also increases your chances at making a purchase. Making your site navigationally easy Everyone hates a website where they can't figure out "where to go next". So make your links and navigation very easy to find. Top or sidebar locations are the most obvious and natural locations for these, and probably the best locations for any of the key places you want any visitor to your site to see. You can also incorporate other forms of navigation like breadcrumb trails, tree menus, and submenus. Breadcrumbs are visual navigational elements. They show the "trail" of where you are in the site, and how you arrived at your current location. Most often breadcrumb trails are near the top of the web page. An example of breadcrumb trails is seen in the following screenshot from the online Inkscape Manual http://tavmjong.free.fr/INKSCAPE/MANUAL/html/index.php: An example of a tree menu is as follows: Tree menus are a bit more complicated. They show the main level web pages and then, when clicked, expand to show the next "tier" of pages. Each level can continue to expand if needed. As seen in the tree menu, main level pages can expand to submenus. This could also be done in a drop down in any horizontal-based navigation as well, like the example shown below: No matter what navigational elements used, the key is to keep them simple and identifiable throughout your web page design and obvious that a user can use these links to get where they need to be on your website. Feeds and social networking links More and more people today are taking advantage of RSS feeds. What are RSS feeds? RSS (Really Simple Syndication) feeds are a way to continually broadcast (or publish) your blog entries. These feeds are in a standardized XML format and pull the metadata tags you assigned when publishing your blog post and display them in "readers" for others to automatically receive. Feed readers allow subscribers (those who want to favor your site), to receive updates as soon as you post any new information, in this case, every time you would release a new blog post. When using an RSS reader, the user needs to enter you blog's feed URL to complete a subscription. Then, the RSS reader checks these subscribed feeds' URLs regularly for new updates and then alerts them when new podcasts are available. So, how do you create an RSS feed for your blog? For a website with hosting where you have your blog as part of an entire site, you can create RSS feeds by using a simple RSS feed provider, such as FeedBurner (www.feedburner.com). These services are free, and once you provide a link to your blog, they do the rest automatically for you. You'll have to set up an account, and then make a note of the blog RSS feed URL (it typically ends in XML). Then on your website, you can offer a link to subscribe to your blog feed. When using a blogging service, there are usually ways to automatically set up RSS feeds to your blog entries. In fact, most blog software has two types of RSS feeds links built in. These can be found in the <head> element of the HTML. There are also many orange 'RSS' buttons that can be easily set up and used within the design itself. Explore your blogging service provider site and set up to determine how best to set up RSS feeds. Either way you set up a feed, make sure you display the RSS feed link prominently. Put it in the sidebar, under each blog post, up near the titles. And give it a distinct link title like: Subscribe to my blog or RSS feed or something similar. RSS feeds are most commonly used for blogs, but as a storefront or online merchandiser, you might set up you own blog announcement area where you would want to announce new products or features of your online store. This would be an easy way for your shoppers to stay tuned to your latest offerings. An alternative to RSS feeds are Atom feeds. Atom stands for Atom Syndication Format which is an XML language used for web feeds. This differs from RSS feeds that focus on post updates; web feeds focus on allowing software programs to check for updates on an entire website. The site owner can use a content management system or other special software that publishes a feed of all the new content that then can be used by a feed reader, another program, or fed into other content management systems. Making checkout easy Design the checkout process of your online store to be as easy as entering brief information and clicking a few buttons. Ideally you need to have the shopping cart, checkout, continue shopping, and my account access available from any page within the site. Then, any potential purchase could also be made from any page on the site as well. Work with the programmers of the shopping cart to create the most effi cient checkout process possible. Give them design options that can allow for the fewest number of screens, but that captures the critical information from the purchaser. Summary In this article we learnt about designing for blogs and online merchant stores. We walked through simple designs for each, defining common elements for each website type and even some sub-level pages to help keep the designs consistent. In the next article, Creating Web templates in Inkscape, we will look at how to create templates so that you can create the design and each part of the web page faster. Further resources on this subject: Logos in Inkscape [Article] Creating Web templates in Inkscape [Article]
Read more
  • 0
  • 0
  • 23191

article-image-using-osgi-bundle-repository-osgi-and-apache-felix-30
Packt
03 Nov 2010
5 min read
Save for later

Using the OSGi Bundle Repository in OSGi and Apache Felix 3.0

Packt
03 Nov 2010
5 min read
OSGi and Apache Felix 3.0 Beginner's Guide Introduction The OSGi Bundle Repository (OBR) is a draft specification from the OSGi alliance for a service that would allow getting access to a set of remote bundle repositories. Each remote repository, potentially a front for a federation of repositories, provides a list of bundles available for download, along with some additional information related to them. The access to the OBR repository can be through a defined API to a remote service or as a direct connection to an XML repository file. The bundles declared in an OBR repository can then be downloaded and installed to an OSGi framework like Felix. We will go through this install process a bit later. The OSGi specification for OBRs is currently in the draft state, which means that it may change before it is released. The following diagram shows the elements related to the OBR, in the context of the OSGi framework: The OBR bundle exposes a service that is registered with the framework. This interface can be used by other components on the framework to inspect repositories, download bundles, and install them. The Gogo command bundle also registers commands that interact with the OBR service to achieve the same purpose. Later in this article, we will cover those commands. API-based interaction with the service is not covered, as it is beyond the scope of this article. The OBR service currently implements remote XML repositories only. However, the Repository interface defined by the OBR service can be implemented for other potential types of repositories as well as for a direct API integration. There are a few OSGi repositories out there, here are some examples: Apache Felix: http://felix.apache.org/obr/releases.xml Apache Sling: http://sling.apache.org/obr/sling.xml Paremus: http://sigil.codecauldron.org/spring-external.obr and http://sigil.codecauldron.org/spring-release.obr Those may be of use later, as a source for the dependencies of your project. The repository XML Descriptor We already have an OBR repository available to us, our releases repository. Typically, you'll rarely need to look into the repository XML file. However, it's a good validation step when investigating issues with the deploy/install process. Let's inspect some of its contents: <repository lastmodified='20100905070524.031'> Not included above in the automatically created repository file is the optional repository name attribute. The repository contains a list of resources that it makes available for download. Here, we're inspecting the entry for the bundle com.packt.felix.bookshelf-inventory-api: <resource id='com.packtpub.felix.bookshelf-inventory-api/1.4.0' symbolicname='com.packtpub.felix.bookshelf-inventory-api' presentationname='Bookshelf Inventory API' uri='file:/C:/projects/felixbook/releases/com/packtpub/felix/ com.packtpub.felix.bookshelf-inventory-api/1.4.0/com.packtpub.felix. bookshelf-inventory-api-1.4.0.jar' version='1.4.0'> <description> Defines the API for the Bookshelf inventory.</description> <size>7781</size> <category id='sample'/> <capability name='bundle'> <p n='symbolicname' v='com.packtpub.felix.bookshelf-inventory-api'/> <p n='presentationname' v='Bookshelf Inventory API'/> <p n='version' t='version' v='1.4.0'/> <p n='manifestversion' v='2'/> </capability> <capability name='package'> <p n='package' v='com.packtpub.felix.bookshelf.inventory.api'/> <p n='version' t='version' v='0.0.0'/> </capability> <require name='package' filter= '(&amp;(package=com.packtpub.felix.bookshelf.inventory.api))' extend='false' multiple='false' optional='false'> Import package com.packtpub.felix.bookshelf.inventory.api </require> </resource> Notice that the bundle location (attribute uri), which points to where the bundle can be downloaded, relative to the base repository location. The presentationname is used when listing the bundles and the uri is used to get the bundle when a request to install it is issued. Inside the main resource entry tag are further bundle characteristics, a description of its capabilities, its requirements, and so on. Although the same information is included in the bundle manifest, it is also included in the repository XML for quick access during validation of the environment, before the actual bundle is downloaded. For example, the package capability elements describe the packages that this bundle exports: <capability name="package"> <p n="package" v="com.packtpub.felix.bookshelf.inventory.api"/> <p n="version" t="version" v="0.0.0"/> </capability> The require elements describe the bundle requirements from the target platform: <require extend="false" filter="(&amp;(package=com.packtpub.felix.bookshelf.inventory. api)(version&gt;=0.0.0))" multiple="false" name="package" optional="false"> Import package com.packtpub.felix.bookshelf.inventory.api </require> </resource> <!-- ... –-> </repository> The preceding excerpts respectively correspond to the Export-Package and Import-Package manifest headers. Each bundle may have more than one entry in the repository XML: an entry for every deployed version. Updating the OBR repository The Felix Maven Bundle Plugin attaches to the deploy phase to automate the bundle deployment and the update of the repository.xml file. Using the OBR scope commands The Gogo Command bundle registers a set of commands for the interaction with the OBR service. Those commands allow registering repositories, listing their bundles, and requesting their download and installation. Let's look at those commands in detail.
Read more
  • 0
  • 0
  • 3782

article-image-logos-inkscape
Packt
03 Nov 2010
6 min read
Save for later

Logos in Inkscape

Packt
03 Nov 2010
6 min read
  Inkscape 0.48 Essentials for Web Designers Use the fascinating Inkscape graphics editor to create attractive layout designs, images, and icons for your website The first book on the newly released Inkscape version 0.48, with an exclusive focus on web design Comprehensive coverage of all aspects of Inkscape required for web design Incorporate eye-catching designs, patterns, and other visual elements to spice up your web pages Learn how to create your own Inkscape templates in addition to using the built-in ones Written in a simple illustrative manner, which will appeal to web designers and experienced Inkscape users alike        Here's an example of a web page with a logo as a major design element: Logos as the cornerstone of the design Logos are the graphical representation or emblem for a company or organization—sometimes even individuals use them to promote instant recognition. They can be a graphic (a combination of symbols or icons), a combination of graphics and text, or graphical forms of text. Why are they important in web design? Since most companies want to be recognized by their logo alone—the logo is the critical piece of the design. It needs prominent placement to work flawlessly with the design. Best practices for creating logos There are a lot of guidelines and principles to the best logo designs. And they start with some simple ideas that have been reworked and discussed intensely since the start of the Internet. But it never hurts to review the best practices. You want your company logos to be: Simple: That's right, you want to keep them clean, simple, neat, and intensely easy to recreate. If you nail this attribute, the others listed below will be easy to achieve. Memorable: Think of all the great company logos. You remember them in your mind's eye very easily right? That's because they are unique and in essence simple. These two attributes together make some of the best company logos today. Timeless: These logos will last many years. This not only saves the company or individual money, but it also increases the memorability of the logo and brand of the company. Versatile: Any logo that can be used in print (color and black and white), digital media, television, any size, letterhead, billboards, and small iconic statements along the bottom of web pages or promotional materials—is a successful logo. You never know where a logo might be placed, especially on the web. You want something that can be used in a prominent location on the company web site itself, but also something that works in a small thumbnail space for social media or cell phone applications. Appropriate: We want the logo to be appropriate for the company it is representing. The right colors, images, and more will go along way in giving the company credibility immediately upon first glance by any consumer or potential client. It can also prove to be a great indication of the services one can expect from the company itself. Seems easy enough right? It is, after some practice and some processes are in place. It never hurts to have a loose process to work with clients to determine their needs and wants in a logo. Some may already have a logo and want to keep parts of the design and revamp others while other clients might be so new they haven't ever had a logo before. As a start, here's a brief process for working with clients and discussing logos. Information gathering There's no better place to start than to open the floor for discussion. Here's just the start of what you can ask or gather from your client in an initial information gathering meeting: Does the client already have a logo? If yes, do they intend to keep that logo to use in the web design? Again if yes, get the source files. Hopefully they are in vector graphic format so they are scalable and usable right away in the web design. Are they interested in a logo redesign? This can be beneficial if they are rebranding themselves as a business or having a 'grand re-opening' of some sort. It can breathe life into a stale business and sometimes garner some new interest. If yes, is it a complete (open to anything) redesign? Or are there certain elements that need to stay? Sometimes color is important, or a certain font or even a certain graphical element needs to stay within the logo. Listen and take notes; it is important to work with the client to try to fulfill their needs as much as possible. If the client is open to a complete redesign, brainstorm a bit with them about their needs and wants. Colors, fonts, graphical ideas. Don't be afraid to bring out some paper and pencils and start sketching some ideas. Sometimes it can be most productive to work through some rough ideas this way to get a feel for what the client likes most and not. Consider it a working session. Try to understand where the client wants to use this logo most prominently. Keeping that in mind you will design something that is versatile and could be used in most mediums; you still want to know where they plan to use it the most. That way, you can tailor the logo as much as possible for that space—especially if you can use more color. What are the primary goals of the company? What is their mission statement? Does the client already have brand guidelines to consider? Creating initial designs After the initial informational session it is your turn to start designing. Take the paper and pencil sketches (if you had any) from the initial meeting and expand on them. In fact, spend a bit more time with your team and flesh out a few more of those ideas in a true brainstorming session. It can be beneficial to start this way first before jumping on to the computer and getting caught in details like typeface and effects. Once you have some solid ideas, bring it over to the computer and start designing. Focus on only three of your best ideas. That way you bring only your best to the client to review and discuss. Much like with the web design process, the logo design process takes a very similar route. You bring design mock ups to your client to review, give feedback, redesign, and then you go back and design some more—all until you get approvals. And then you—being an Inkscape expert—can build and then export the logo in any number of vector formats for use in almost any medium.
Read more
  • 0
  • 0
  • 3193

article-image-graphical-capabilities-r
Packt
29 Oct 2010
8 min read
Save for later

Graphical Capabilities of R

Packt
29 Oct 2010
8 min read
Statistical Analysis with R Take control of your data and produce superior statistical analysis with R. An easy introduction for people who are new to R, with plenty of strong examples for you to work through This book will take you on a journey to learn R as the strategist for an ancient Chinese kingdom! A step by step guide to understand R, its benefits, and how to use it to maximize the impact of your data analysis A practical guide to conduct and communicate your data analysis with R in the most effective manner           Read more about this book       (For more resources on R, see here.) Time for action — creating a line chart The ever popular line chart, or line graph, depicts relationships as continuous series of connected data points. Line charts are particularly useful for visualizing specific values and trends over time. Just as a line chart is an extension of a scatterplot in the non-digital realm, a line chart is created using an extended form of the plot(...) function in R. Let us explore how to extend the plot(...) function to create line charts in R: Use the type argument within the plot(...) function to create a line chart that depicts a single relationship between two variables: > #create a line chart that depicts the durations of past fire attacks> #get the data to be used in the chart> lineFireDurationDataX <- c(1:30)> lineFireDurationDataY <- subsetFire$DurationInDays> #customize the chart> lineFireDurationMain <- "Duration of Past Fire Attacks"> lineFireDurationLabX <- "Battle Number"> lineFireDurationLabY <- "Duration in Days"> #use the type argument to connect the data points with a line> lineFireDurationType <- "o"> #use plot(...) to create and display the line chart> plot(x = lineFireDurationDataX, y = lineFireDurationDataY,main = lineFireDurationMain, xlab = lineFireDurationLabX,ylab = lineFireDurationLabY, type = lineFireDurationType) Your chart will be displayed in the graphic window, as follows: What just happened? We expanded our use of the plot(...) function to generate a line chart and encountered a new data notation in the process. Let us review these features. type In the plot(...) function, the type argument determines what kind of line, if any, should be used to connect a chart's data points. The type argument receives one of several character values, all of which are listed as follows: p: only points are plotted; this is the default value when type is undefined l: only lines are drawn, without any points o: both lines and points are drawn, with the lines overlapping the points b: both lines and points are drawn, with the lines broken where they intersect with points c: only lines are drawn, but they are broken where points would occur s: only the lines are drawn in step formation; the initial step begins at zero S: (uppercase) only the lines are drawn in step formation; the final step tails off at the last point h: vertical lines are drawn to represent each point n: no points nor lines are drawn Our chart, which represented the duration of past fire attacks, featured a line that overlapped the plotted points. First, we defined our desired line type in an R variable: > lineFireDurationType <- "o" Then the type argument was placed within our plot(...) function to generate the line chart: > plot(lineFireDurationDataX, lineFireDurationDataY,main = lineFireDurationMain, xlab = lineFireDurationLabX,ylab = lineFireDurationLabY,type = lineFireDurationType) Number-colon-number notation You may have noticed that we specified a vector for the x-axis data in our plot(...) function. > lineFireDurationDataX <- c(1:30) This vector used number-colon-number notation. Essentially, this notation has the effect of enumerating a range of values that lie between the number that precedes the colon and the number that follows it. To do so, it adds one to the beginning value until it reaches a final value that is equal to or less than the number that comes after the colon. For example, the code > 14:21 would yield eight whole numbers, beginning with 14 and ending with 21, as follows: [1] 14 15 16 17 18 19 20 21 Furthermore, the code > 14.2:21 would yield seven values, beginning with 14.2 and ending with 20.2, as follows: [1] 14.2 15.2 16.2 17.2 18.2 19.2 20.2 Number-colon-number notation is a useful way to enumerate a series of values without having to type each one individually. It can be used in any circumstance where a series of values is acceptable input into an R function. Number-colon-number notation can also enumerate values from high to low. For instance, 21:14 would yield a list of values beginning with 21 and ending with 14. Since we do not have exact dates or other identifying information for our 30 past battles, we simply enumerated the numbers 1 through 30 on the x-axis. This had the effect of assigning a generic identification number to each of our past battles, which in turn allowed us to plot the duration of each battle on the y axis. Pop quiz Which of the following is the type argument capable of? Drawing a line to connect or replace the points on a scatterplot. Drawing vertical or step lines. Drawing no points or lines. All of the above. What would the following line of code yield in the R console? > 1:50 A sequence of 50 whole numbers, in order from 1 to 50. A sequence of 50 whole numbers, in order from 50 to 1. A sequence of 50 random numbers, in order from 1 to 50. A sequence of 50 random numbers, in order from 50 to 1. Time for action — creating a box plot A useful way to convey a collection of summary statistics in a dataset is through the use of a box plot. This type of graph depicts a dataset's minimum and maximum, as well as its lower, median, and upper quartiles in a single diagram. Let us look at how box plots are created in R: Use the boxplot(...) function to create a box plot. > #create a box plot that depicts the number of soldiers required to launch a fire attack> #get the data to be used in the plot> boxplotFireShuSoldiersData <- subsetFire$ShuSoldiers> #customize the plot> boxPlotFireShuSoldiersLabelMain <- "Number of Soldiers Required to Launch a Fire Attack"> boxPlotFireShuSoldiersLabelX <- "Fire Attack Method"> boxPlotFireShuSoldiersLabelY <- "Number of Soldiers"> #use boxplot(...) to create and display the box plot> boxplot(x = boxplotFireShuSoldiersData,main = boxPlotFireShuSoldiersLabelMain,xlab = boxPlotFireShuSoldiersLabelX,ylab = boxPlotFireShuSoldiersLabelY) Your plot will be displayed in the graphic window, as shown in the following: Use the boxplot(...) function to create a box plot that compares multiple datasets. > #create a box plot that compares the number of soldiers required across the battle methods> #get the data formula to be used in the plot> boxplotAllMethodsShuSoldiersData <- battleHistory$ShuSoldiers ~ battleHistory$Method> #customize the plot> boxPlotAllMethodsShuSoldiersLabelMain <- "Number of Soldiers Required by Battle Method"> boxPlotAllMethodsShuSoldiersLabelX <- "Battle Method"> boxPlotAllMethodsShuSoldiersLabelY <- "Number of Soldiers"> #use boxplot(...) to create and display the box plot> boxplot(formula = boxplotAllMethodsShuSoldiersData,main = boxPlotAllMethodsShuSoldiersLabelMain,xlab = boxPlotAllMethodsShuSoldiersLabelX,ylab = boxPlotAllMethodsShuSoldiersLabelY) Your plot will be displayed in the graphic window, as shown in the following: What just happened? We just created two box plots using R's boxplot(...) function, one with a single box and one with multiple boxes. boxplot(...) We started by generating a single box plot that was composed of a dataset, main title, and x and y labels. The basic format for a single box plot is as follows: boxplot(x = dataset) The x argument contains the data to be plotted. Technically, only x is required to create a box plot, although you will often include additional arguments. Our boxplot(...) function used the main, xlab, and ylab arguments to display text on the plot, as shown: > boxplot(x = boxplotFireShuSoldiersData,main = boxPlotFireShuSoldiersLabelMain,xlab = boxPlotFireShuSoldiersLabelX,ylab = boxPlotFireShuSoldiersLabelY) Next, we created a multiple box plot that compared the number of Shu soldiers deployed by each battle method. The main, xlab, and ylab arguments remained from our single box plot, however our multiple box plot used the formula argument instead of x. Here, a formula allows us to break a dataset down into separate groups, thus yielding multiple boxes. The basic format for a multiple box plot is as follows: boxplot(formula = dataset ~ group) In our case, we took our entire Shu soldier dataset (battleHistory$ShuSoldiers) and separated it by battle method (battleHistory$Method): > boxplotAllMethodsShuSoldiersData <- battleHistory$ShuSoldiers ~ battleHistory$Method Once incorporated into the boxplot(...) function, this formula resulted in a plot that contained four distinct boxes—ambush, fire, head to head, and surround: > boxplot(formula = boxplotAllMethodsShuSoldiersData,main = boxPlotAllMethodsShuSoldiersLabelMain,xlab = boxPlotAllMethodsShuSoldiersLabelX,ylab = boxPlotAllMethodsShuSoldiersLabelY) Pop quiz Which of the following best describes the result of the following code? > boxplot(x = a) A single box plot of the a dataset. A single box plot of the x dataset. A multiple box plot of the a dataset that is grouped by x. A multiple box plot of the x dataset that is grouped by a. Which of the following best describes the result of the following code? > boxplot(formula = a ~ b) A single box plot of the a dataset. A single box plot of the b dataset. A multiple box plot of the a dataset that is grouped by b. A multiple box plot of the b dataset that is grouped by a.
Read more
  • 0
  • 0
  • 3325

article-image-microsoft-dynamics-nav-os-integration
Packt
29 Oct 2010
7 min read
Save for later

Microsoft Dynamics NAV: OS Integration

Packt
29 Oct 2010
7 min read
Microsoft Dynamics NAV 2009 Programming Cookbook Build better business applications with NAV Write NAV programs to do everything from finding data in a table to integration with an instant messenger client Develop your own .NET code to perform tasks that NAV cannot handle on its own Work with SQL Server to create better integration between NAV and other systems Learn to use the new features of the NAV 2009 Role Tailored Client Easy-to-read recipes with detailed explanations and images Maximize your learning with short tutorials that tell you exactly what you need to know without all of the fluff If you have programmed with Windows or used a Windows-based operating system for any length of time you will see that it is really an all-encompassing OS, at least for our needs. Unlike with other types of software development, we don't need to interact with device drivers or create three dimensional graphics for our users. Most of what we need to do involves integrating with the file system; that is searching for files or folders and running external applications. Occasionally, we may need to go a little deeper. There may be instances where we need to check the user's environment, query the registry, or check for specific administrator permissions. These can all be performed within NAV, although many require a little outside help from a built-in or custom automation control. As Windows is such a large piece of software, it already contains ways for us to do these things. As a result, the recipes in this article are not very lengthy or complicated, but that does not make them any less useful. They explore the basics of what you can do with the OS and it is up to you to decide when and how to make the best use of them. It is important to note that many of these recipes will require additional coding to make them work with the RoleTailored client. This is because the code is actually executing on a server, not your own computer as it does with the Classic client. Using HYPERLINK to open external files Many times you may need to open files external to the NAV program. NAV has a built-in function that interacts with the file system to open the file with the appropriate application. How to do it... Create a new codeunit from Object Designer. Add the following global variable: NameTypeSelectionInteger Add the following code to the OnRun trigger: Selection := STRMENU('Image,Website'); IF Selection = 1 THEN HYPERLINK('C:UsersPublic PicturesSample PicturesPenguins.jpg') ELSE HYPERLINK('HTTP://www.mibuso.com'); Save and close the codeunit. How it works... When you run the codeunit you will be presented with a simple selection menu that asks you to choose between an image and a website. Depending on your choice we will use the HYPERLINK command to load a specific file. This command takes in a single string which points to a location and loads that pointer using the default program on the current machine. If you choose Image then the Penguins image that ships with Microsoft Windows 7 will load in the default program you have set to open pictures, usually Windows Photo Viewer. If you choose Website then the Mibuso website will open in your default internet browser, typically Internet Explorer. There's more... With the RoleTailored client, it is best to use HYPERLINK with shared drives and folders. This is because the actual HYPERLINK command is running on the NAV service tier, not on the local computer or client. It has no idea about the user's system. This example is for the Classic client (thus the link to a file on the C: drive), but changing the parameter to a shared file on your network should work just fine. See also Using SHELL to run external applications Browsing for a file Checking file and folder access permissions Working with environment variables Environment variables are a set of named values that can affect the way processes and applications run on a computer. NAV has a built-in function to reference these variables and lets you change the way it functions. How to do it... Create a new codeunit from Object Designer. Add the following code to the OnRun trigger: MESSAGE(' OS: %1Temp: %2WinDir: %3', ENVIRON('OS'), ENVIRON('TEMP'), ENVIRON('WINDIR')); Save and close the codeunit. How it works... The ENVIRON function takes in a single string and returns a string. Our codeunit uses the ENVIRON function to return three common environment variables: the name of the operating system, the path to the temporary folder for the current user, and the path to the Windows installation directory. In Windows 7, in order to see all of the options available to the ENVIRON command, simply right-click on My Computer and go to Properties. Click on Advanced system settings, the Advanced tab, and then on the Environment Variables button. You will find them in the System variables section of the window. There's more... This recipe is not compatible with the RoleTailored client. The code running on the NAV service tier does not know anything about the client operating system. There is, however, a way around this. We need a way to force code to be executed on the client-side instead of the server-side. ENVIRON for the RoleTailored client We can force our code to execute on the client-side by creating an Automation. Start by creating a new project in Visual Studio with the following code: using System.Management; using System.Runtime.InteropServices; namespace RemoteSystemInfo { [ClassInterface(ClassInterfaceType.AutoDual)] [ProgId("RemoteSystemInfo")] [ComVisible(true)] public class RemoteSystemInfo { public string GetSysInfo(string domain, string machine, string username, string password, string variable) { ManagementObjectSearcher query = null; ManagementObjectCollection queryCollection = null; ConnectionOptions opt = new ConnectionOptions(); opt.Impersonation = ImpersonationLevel.Impersonate; opt.EnablePrivileges = true; opt.Username = username; opt.Password = password;    try { ManagementPath p = new ManagementPath(@"" + machine + @"rootcimv2"); ManagementScope msc = new ManagementScope(p, opt); SelectQuery q = new SelectQuery("Win32_Environment"); query = new ManagementObjectSearcher(msc, q, null); queryCollection = query.Get();     foreach (ManagementBaseObject envVar in queryCollection) { if (envVar["Name"].ToString() == variable) { return envVar["VariableValue"].ToString(); } } } catch (ManagementException e) { throw new ManagementException("Management Exception: " + e.Message); } catch (System.UnauthorizedAccessException e) { throw new ManagementException("Access Exception: " + e.Message); } return ""; } } } When using the Automation in your NAV objects you must do the following: CREATE(MyAutomation, FALSE, TRUE); The third parameter tells the system to create the instance of the Automation on the client (TRUE) and not the server (FALSE). As the code executes on the client machine it can query the environment variables and easily return the correct result. Just pass the appropriate values to the GetSysInfo function. See also Using SHELL Using SHELL to run external applications Just as external files can be opened from within NAV, so can external programs. This recipe will show you how to launch one of such applications. How to do it... Create a new codeunit from Object Designer. Add the following code to the OnRun trigger: SHELL(ENVIRON('WINDIR') + 'notepad.exe'); Save and close the codeunit. How it works... The SHELL command takes in a required string parameter representing the application to launch. There is an optional second parameter that will be passed as an argument to the application to be launched (not used here). This argument could represent a file to open or other flags incorporated into the program. See also Querying the registry  
Read more
  • 0
  • 0
  • 2499
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-organizing-clarifying-and-communicating-r-data-analyses
Packt
29 Oct 2010
8 min read
Save for later

Organizing, Clarifying and Communicating the R Data Analyses

Packt
29 Oct 2010
8 min read
  Statistical Analysis with R Take control of your data and produce superior statistical analysis with R. An easy introduction for people who are new to R, with plenty of strong examples for you to work through This book will take you on a journey to learn R as the strategist for an ancient Chinese kingdom! A step by step guide to understand R, its benefits, and how to use it to maximize the impact of your data analysis A practical guide to conduct and communicate your data analysis with R in the most effective manner           Read more about this book       (For more resources on R, see here.) Retracing and refining a complete analysis For demonstration purposes, it will be assumed that a fire attack was chosen as the optimal battle strategy. Throughout this segment, we will retrace the steps that lead us to this decision. Meanwhile, we will make sure to organize and clarify our analyses so they can be easily communicated to others. Suppose we determined our fire attack will take place 225 miles away in Anding, which houses 10,000 Wei soldiers. We will deploy 2,500 soldiers for a period of 7 days and assume that they are able to successfully execute the plans. Let us return to the beginning to develop this strategy with R in a clear and concise manner. Time for action – first steps To begin our analysis, we must first launch R and set our working directory: Launch R. The R console will be displayed. Set your R working directory using the setwd(dir) function. The following code is a hypothetical example. Your working directory should be a relevant location on your own computer. > #set the R working directory using setwd(dir)> setwd("/Users/johnmquick/rBeginnersGuide/") Verify that your working directory has been set to the proper location using the getwd() command : > #verify the location of your working directory> getwd()[1] "/Users/johnmquick/rBeginnersGuide/" What just happened? We prepared R to begin our analysis by launching the soft ware and setting our working directory. At this point, you should be very comfortable completing these steps. Time for action – data setup Next, we need to import our battle data into R and isolate the portion pertaining to past fire attacks: Copy the battleHistory.csv file into your R working directory. This file contains data from 120 previous battles between the Shu and Wei forces. Read the contents of battleHistory.csv into an R variable named battleHistory using the read.table(...) command: > #read the contents of battleHistory.csv into an R variable> #battleHistory contains data from 120 previous battlesbetween the Shu and Wei forces> battleHistory <- read.table("battleHistory.csv", TRUE, ",") Create a subset using the subset(data, ...) function and save it to a new variable named subsetFire: > #use the subset(data, ...) function to create a subset ofthe battleHistory dataset that contains data only from battlesin which the fire attack strategy was employed> subsetFire <- subset(battleHistory, battleHistory$Method =="fire") Verify the contents of the new subset. Note that the console should return 30 rows, all of which contain fire in the Method column: > #display the fire attack data subset> subsetFire What just happened? We imported our dataset and then created a subset containing our fire attack data. However, we used a slightly different function, called read.table(...), to import our external data into R. read.table(...) U p to this point, we have always used the read.csv() function to import data into R. However, you should know that there are oft en many ways to accomplish the same objectives in R. For instance, read.table(...) is a generic data import function that can handle a variety of file types. While it accepts several arguments, the following three are required to properly import a CSV file, like the one containing our battle history data: file: t he name of the file to be imported, along with its extension, in quotes header: whether or not the file contains column headings; TRUE for yes, FALSE (default) for no sep: t he character used to separate values in the file, in quotes Using these arguments, we were able to import the data in our battleHistory.csv into R. Since our file contained headings, we used a value of TRUE for the header argument and because it is a comma-separated values file, we used "," for our sep argument: > battleHistory <- read.table("battleHistory.csv", TRUE, ",") This is just one example of how a different technique can be used to achieve a similar outcome in R. We will continue to explore new methods in our upcoming activities. Pop quiz Suppose you wanted to import the following dataset, named newData into R. Which of the following read.table(...) functions would be best to use? 4,55,96,12 read.table("newData", FALSE, ",") read.table("newData", TRUE, ",") read.table("newData.csv", FALSE, ",") read.table("newData.csv", TRUE, ",") Time for action – data exploration To begin our analysis, we will examine the summary statistics and correlations of our data. These will give us an overview of the data and inform our subsequent analyses: Generate a summary of the fire attack subset using summary(object): > #generate a summary of the fire subset> summaryFire <- summary(subsetFire)> #display the summary> summaryFire Before calculating correlations, we will have to convert our nonnumeric data from the Method, SuccessfullyExecuted, and Result columns into numeric form. Re code the Method column using as.numeric(data): > #represent categorical data numerically usingas.numeric(data)> #recode the Method column into Fire = 1> numericMethodFire <- as.numeric(subsetFire$Method) - 1 Recode the SuccessfullyExecuted column using as.numeric(data): > #recode the SuccessfullyExecuted column into N = 0 and Y = 1> numericExecutionFire <-as.numeric(subsetFire$SuccessfullyExecuted) - 1 Recode the Result column using as.numeric(data): > #recode the Result column into Defeat = 0 and Victory = 1> numericResultFire <- as.numeric(subsetFire$Result) - 1 With the Method, SuccessfullyExecuted, and Result columns coded into numeric form, let us now add them back into our fire dataset. Save the data in our recoded variables back into the original dataset: > #save the data in the numeric Method, SuccessfullyExecuted,and Result columns back into the fire attack dataset> subsetFire$Method <- numericMethodFire> subsetFire$SuccessfullyExecuted <- numericExecutionFire> subsetFire$Result <- numericResultFire Display the numeric version of the fire attack subset. Notice that all of the columns now contain numeric data; it will look like the following: Having replaced our original text values in the SuccessfullyExecuted and Result columns with numeric data, we can now calculate all of the correlations in the dataset using the cor(data) function: > #use cor(data) to calculate all of the correlations in thefire attack dataset> cor(subsetFire) Note that the error message and NA values in our correlation output result from the fact that our Method column contains only a single value. This is irrelevant to our analysis and can be ignored. What just happened? Initially, we calculated summary statistics for our fire attack dataset using the summary(object) function. From this information, we can derive the following useful insights about our past battles: The rating of the Shu army's performance in fire attacks has ranged from 10 to 100, with a mean of 45 Fire attack plans have been successfully executed 10 out of 30 times (33%) Fire attacks have resulted in victory 8 out of 30 times (27%) Successfully executed fire attacks have resulted in victory 8 out of 10 times (80%), while unsuccessful attacks have never resulted in victory The number of Shu soldiers engaged in fire attacks has ranged from 100 to 10,000 with a mean of 2,052 The number of Wei soldiers engaged in fire attacks has ranged from 1,500 to 50,000 with a mean of 12,333 The duration of fire attacks has ranged from 1 to 14 days with a mean of 7 Next, we recoded the text values in our dataset's Method, SuccessfullyExecuted, and Result columns into numeric form. Aft er adding the data from these variables back into our our original dataset, we were able to calculate all of its correlations. This allowed us to learn even more about our past battle data: The performance rating of a fire attack has been highly correlated with successful execution of the battle plans (0.92) and the battle's result (0.90), but not strongly correlated with the other variables. The execution of a fire attack has been moderately negatively correlated with the duration of the attack, such that a longer attack leads to a lesser chance of success (-0.46). The numbers of Shu and Wei soldiers engaged are highly correlated with each other (0.74), but not strongly correlated with the other variables. The insights gleaned from our summary statistics and correlations put us in a prime position to begin developing our regression model. Pop quiz Which of the following is a benefit of adding a text variable back into its original dataset aft er it has been recoded into numeric form? Calculation functions can be executed on the recoded variable. Calculation functions can be executed on the other variables in the dataset. Calculation functions can be executed on the entire dataset. There is no benefit.
Read more
  • 0
  • 0
  • 3229

article-image-aspnet-site-performance-reducing-page-load-time
Packt
28 Oct 2010
10 min read
Save for later

ASP.Net Site Performance: Reducing Page Load Time

Packt
28 Oct 2010
10 min read
The JavaScript code for a page falls into two groups—code required to render the page, and code required to handle user interface events, such as button clicks. The code to render the page is used to make the page look better , and to attach event handlers to for example, buttons. Although the rendering code needs to be loaded and executed in conjunction with the page itself, the user interface code can be loaded later, in response to a user interface event, such as a button click. That reduces the amount of code to be loaded, and therefore the time rendering of the page is blocked. It also reduces your bandwidth costs, because the user interface code is loaded only when it's actually needed. On the other hand, it does require separating the user interface code from the rendering code. You then need to invoke code that potentially hasn't loaded yet, tell the visitor that the code is loading, and finally invoke the code after it has loaded. Let's see how to make this all happen. Separating user interface code from render code Depending on how your JavaScript code is structured, this could be your biggest challenge in implementing on-demand loading. Make sure the time you're likely to spend on this and the subsequent testing and debugging is worth the performance improvement you're likely to gain. A very handy tool that identifies which code is used while loading the page is Page Speed, an add-on for Firefox. Besides identifying code that doesn't need to be loaded upfront, it reports many speed-related issues on your web page. Information on Page Speed is available at http://code.google.com/speed/page-speed/. OnDemandLoader library Assuming your user interface code is separated from your render code, it is time to look at implementing actual on-demand loading. To keep it simple, we'll use OnDemandLoader, a simple low-footprint object. You'll find it in the downloaded code bundle in the folder OnDemandLoad in the file OnDemandLoader.js. OnDemandLoader has the following features: It allows you to specify the script, in which it is defined, for each event-handler function. It allows you to specify that a particular script depends on some other script; for example Button1Code.js depends on library code in UILibrary1.js. A script file can depend on multiple other script files, and those script files can in turn be dependent on yet other script files. It exposes function runf, which takes the name of a function, arguments to call it with, and the this pointer to use while it's being executed. If the function is already defined, runf calls it right away. Otherwise, it loads all the necessary script files and then calls the function. It exposes the function loadScript, which loads a given script file and all the script files it depends on. Function runf uses this function to load script files. While script files are being loaded in response to a user interface event, a "Loading..." box appears on top of the affected control. That way, the visitor knows that the page is working to execute their action. If a script file has already been loaded or if it is already loading, it won't be loaded again. If the visitor does the same action repeatedly while the associated code is loading, such as clicking the same button, that event is handled only once. If the visitor clicks a second button or takes some other action while the code for the first button is still loading, both events are handled. A drawback of OnDemandLoader is that it always loads all the required scripts in parallel. If one script automatically executes a function that is defined in another script , there will be a JavaScript error if the other script hasn't loaded yet. However, if your library script files only define functions and other objects, OnDemandLoader will work well. Initializing OnDemandLoader OnDemandLoading.aspx in folder OnDemandLoad in the downloaded code bundle is a worked-out example of a page using on-demand loading. It delays the loading of JavaScript files by five seconds, to simulate slowly loading files. Only OnDemandLoader.js loads at normal speed. If you open OnDemandLoading.aspx, you'll find that it defines two arrays—the script map array and the script dependencies array. These are needed to construct the loader object that will take care of the on-demand loading. The script map array shows the script file, in which it is defined, for each function: var scriptMap = [ { fname: 'btn1a_click', src: 'js/Button1Code.js' }, { fname: 'btn1b_click', src: 'js/Button1Code.js' }, { fname: 'btn2_click', src: 'js/Button2Code.js' } ]; Here, functions btn1a_click and btn1b_click live in script file js/Button1Code. js, while function btn2_click lives in script file js/Button2Code.js. The second array defines which other script files it needs to run for each script file: var scriptDependencies = [ { src: '/js/Button1Code.js', testSymbol: 'btn1a_click', dependentOn: ['/js/UILibrary1.js', '/js/UILibrary2.js'] }, { src: '/js/Button2Code.js', testSymbol: 'btn2_click', dependentOn: ['/js/UILibrary2.js'] }, { src: '/js/UILibrary2.js', testSymbol: 'uifunction2', dependentOn: [] }, { src: '/js/UILibrary1.js', testSymbol: 'uifunction1', dependentOn: ['/js/UILibrary2.js'] } ]; This says that Button1Code.js depends on UILibrary1.js and UILibrary2.js. Further, Button2Code.js depends on UILibrary2.js. Further, UILibrary1.js relies on UILibrary2.js, and UILibrary2.js doesn't require any other script files. The testSymbol field holds the name of a function defined in the script. Any function will do, as long as it is defined in the script. This way, the on-demand loader can determine whether a script has been loaded by testing whether that name has been defined. With these two pieces of information, we can construct the loader object: <script type="text/javascript" src="js/OnDemandLoader.js"> </script> var loader = new OnDemandLoader(scriptMap, scriptDependencies); Now that the loader object has been created, let's see how to invoke user interface handler functions before their code has been loaded. Invoking not-yet-loaded functions The point of on-demand loading is that the visitor is allowed to take an action for which the code hasn't been loaded yet. How do you invoke a function that hasn't been defined yet? Here, you'll see two approaches: Call a loader function and pass it the name of the function to load and execute Create a stub function with the same name as the function you want to execute, and have the stub load and execute the actual function Let's focus on the first approach first. The OnDemandLoader object exposes a loader function runf that takes the name of a function to call, the arguments to call it with, and the current this pointer: function runf(fname, thisObj) { // implementation } Wait a minute! This signature shows a function name parameter and the this pointer, but what about the arguments to call the function with? One of the amazing features of JavaScript is that can you pass as few or as many parameters as you want to a function, irrespective of the signature. Within each function, you can access all the parameters via the built-in arguments array. The signature is simply a convenience that allows you to name some of the arguments. This means that you can call runf as shown: loader.runf('myfunction', this, 'argument1', 'argument2'); If for example, your original HTML has a button as shown: <input id="btn1a" type="button" value="Button 1a" onclick="btn1a_click(this.value, 'more info')" /> To have btn1a_click loaded on demand, rewrite this to the following (file OnDemandLoading.aspx): <input id="btn1a" type="button" value="Button 1a" onclick="loader.runf('btn1a_click', this, this.value, 'more info')" /> If, in the original HTML, the click handler function was assigned to a button programmatically as shown: <input id="btn1b" type="button" value="Button 1b" /> <script type="text/javascript"> window.onload = function() { document.getElementById('btn1b').onclick = btn1b_click; } </script> Then, use an anonymous function that calls loader.runf with the function to execute: <input id="btn1b" type="button" value="Button 1b" /> <script type="text/javascript"> window.onload = function() { document.getElementById('btn1b').onclick = function() { loader.runf('btn1b_click', this); } } </script> This is where you can use the second approach—the stub function. Instead of changing the HTML of your controls, you can load a stub function upfront before the page renders (file OnDemandLoading.aspx): function btn1b_click() { loader.runf('btn1b_click', this); } When the visitor clicks the button, the stub function is executed. It then calls loader.runf to load and execute its namesake that does the actual work, overwriting the stub function in the process. This leaves behind one problem. The on-demand loader checks whether a function with the given name is already defined before initiating a script load. And a function with that same name already exists—the stub function itself.   The solution is based on the fact that functions in JavaScript are objects. And all JavaScript objects can have properties. You can tell the on-demand loader that a function is a stub by attaching the property "stub": btn1b_click.stub = true; To see all this functionality in action, run the OnDemandLoading.aspx page in folder OnDemandLoad in the downloaded code bundle. Click on one of the buttons on the page, and you'll see how the required code is loaded on demand. It's best to do this in Firefox with Firebug installed, so that you can see the script files getting loaded in a Waterfall chart. Preloading Now that you have on-demand loading working, there is one more issue to consider: trading off bandwidth against visitor wait time. Currently, when a visitor clicks a button and the code required to process the click hadn't been loaded, loading starts in response to the click. This can be a problem if loading the code takes too much time. An alternative is to initiate loading the user interface code after the page has been loaded, instead of when a user interface event happens. That way, the code may have already loaded by the time the visitor clicks the button; or at least it will already be partly loaded, so that the code finishes loading sooner. On the other hand, this means expending bandwidth on loading code that may never be used by the visitor. You can implement preloading with the loadScript function exposed by the OnDemandLoader object. As you saw earlier, this function loads a JavaScript file plus any files it depends on, without blocking rendering. Simply add calls to loadScript in the onload handler of the page, as shown (page PreLoad.aspx in folder OnDemandLoad in the downloaded code bundle): <script type="text/javascript"> window.onload = function() { document.getElementById('btn1b').onclick = btn1b_click; loader.loadScript('js/Button1Code.js'); loader.loadScript('js/Button2Code.js'); } </script> You could preload all your user interface code, or just the code you think is likely to be needed. Now that you've looked at the load on demand approach, it's time to consider the last approach—loading your code without blocking page rendering and without getting into stub functions or other complications inherent in on-demand loading.
Read more
  • 0
  • 0
  • 10031

article-image-aspnet-site-performance-improving-javascript-loading
Packt
28 Oct 2010
11 min read
Save for later

ASP.Net Site Performance: Improving JavaScript Loading

Packt
28 Oct 2010
11 min read
  ASP.NET Site Performance Secrets Simple and proven techniques to quickly speed up your ASP.NET website Speed up your ASP.NET website by identifying performance bottlenecks that hold back your site's performance and fixing them Tips and tricks for writing faster code and pinpointing those areas in the code that matter most, thus saving time and energy Drastically reduce page load times Configure and improve compression – the single most important way to improve your site's performance Written in a simple problem-solving manner – with a practical hands-on approach and just the right amount of theory you need to make sense of it all           Read more about this book       One approach to improving page performance is to shift functionality from the server to the browser. Instead of calculating a result or validating a form in C# on the server, you use JavaScript code on the browser. A drawback of this approach is that it involves physically moving code from the server to the browser. Because JavaScript is not compiled, it can be quite bulky. This can affect page load times, especially if you use large JavaScript libraries. You're effectively trading off increased page load times against faster response times after the page has loaded. In this article by Matt Perdeck, author of ASP.NET Site Performance Secret, you'll see how to reduce the impact on page load times by the need to load JavaScript files. It shows: How JavaScript files can block rendering of the page while they are being loaded and executed How to load JavaScript in parallel with other resources How to load JavaScript more quickly (For more resources on ASP.Net, see here.) Problem: JavaScript loading blocks page rendering JavaScript files are static files, just as images and CSS files. However, unlike images, when a JavaScript file is loaded or executed using a <script> tag, rendering of the page is suspended. This makes sense, because the page may contain script blocks after the <script> tag that are dependent on the JavaScript file. If loading of a JavaScript file didn't block page rendering, the other blocks could be executed before the file had loaded, leading to JavaScript errors. Confirming with a test site You can confirm that loading a JavaScript file blocks rendering of the page by running the website in the folder JavaScriptBlocksRendering in the downloaded code bundle. This site consists of a single page that loads a single script, script1.js. It also has a single image, chemistry.png, and a stylesheet style1.css. It uses an HTTP module that suspends the working thread for five seconds when a JavaScript file is loaded. Images and CSS files are delayed by about two seconds. When you load the page, you'll see that the page content appears after only about five seconds. Then after two seconds, the image appears, unless you use Firefox, which often loads images in parallel with the JavaScript. If you make a Waterfall chart, you can see how the image and stylesheet are loaded after the JavaScript file, instead of in parallel: To get the delays, run the test site on IIS 7 in integrated pipeline mode. Do not use the Cassini web server built into Visual Studio. If you find that there is no delay, clear the browser cache. If that doesn't work either, the files may be in kernel cache on the server—remove them by restarting IIS using Internet Information Services (IIS) Manager. To open IIS manager, click on Start | Control Panel, type "admin" in the search box, click on Administrative Tools, and then double-click on Internet Information Services (IIS) Manager. Integrated/Classic Pipeline Mode As in IIS 6, every website runs as part of an application pool in IIS 7. Each IIS 7 application pool can be switched between Integrated Pipeline Mode (the default) and Classic Pipeline Mode. In Integrated Pipeline Mode, the ASP.NET runtime is integrated with the core web server, so that the server can be managed for example, via web.config elements. In Classic Pipeline Mode, IIS 7 functions more like IIS 6, where ASP.NET runs within an ISAPI extension. Approaches to reduce the impact on load times Although it makes sense to suspend rendering the page while a <script> tag loads or executes JavaScript, it would still be good to minimize the time visitors have to wait for the page to appear, especially if there is a lot of JavaScript to load. Here are a few ways to do that: Start loading JavaScript after other components have started loading, such as images and CSS files. That way, the other components load in parallel with the JavaScript instead of after the JavaScript, and so are available sooner when page rendering resumes. Load JavaScript more quickly. Page rendering is still blocked, but for less time. Load JavaScript on demand. Only load the JavaScript upfront that you need to render the page. Load the JavaScript that handles button clicks, and so on, when you need it. Use specific techniques to prevent JavaScript loading from blocking rendering. This includes loading the JavaScript after the page has rendered, or in parallel with page rendering. These approaches can be combined or used on their own for the best tradeoff between development time and performance. Let's go through each approach. Approach: Start loading after other components This approach aims to render the page sooner by loading CSS stylesheets and images in parallel with the JavaScript rather than after the JavaScript. That way, when the JavaScript has finished loading, the CSS and images will have finished loading too and will be ready to use; or at least it will take less time for them to finish loading after the JavaScript has loaded. To load the CSS stylesheets and images in parallel with the JavaScript, you would start loading them before you start loading the JavaScript. In the case of CSS stylesheets that is easy—simply place their <link> tags before the <script> tags: <link rel="Stylesheet" type="text/css" href="css/style1.css" /><script type="text/javascript" src="js/script1.js"></script> Starting the loading of images is slightly trickier because images are normally loaded when the page body is evaluated, not as a part of the page head. In the test page you just saw with the image chemistry.png, you can use a bit of simple JavaScript to get the browser to start loading the image before it starts loading the JavaScript file. This is referred to as "image preloading" (page PreLoadWithJavaScript.aspx in the folder PreLoadImages in the downloaded code bundle): <script type="text/javascript"> var img1 = new Image(); img1.src = "images/chemistry.png";</script><link rel="Stylesheet" type="text/css" href="css/style1.css" /><script type="text/javascript" src="js/script1.js"></script> Run the page now and you'll get the following Waterfall chart: When the page is rendered after the JavaScript has loaded, the image and CSS files have already been loaded; so the image shows up right away. A second option is to use invisible image tags at the start of the page body that preload the images. You can make the image tags invisible by using the style display:none. You would have to move the <script> tags from the page head to the page body after the invisible image tags, as shown (page PreLoadWithCss.aspx in folder PreLoadImages in the downloaded code bundle): <body> <div style="display:none"> <img src="images/chemistry.png" /> </div> <script type="text/javascript" src="js/script1.js"></script> Although the examples we've seen so far preload only one image, chemistry.png, you could easily preload multiple images. When you do, it makes sense to preload the most important images first, so that they are most likely to appear right away when the page renders. The browser loads components, such as images, in the order in which they appear in the HTML, so you'd wind up with something similar to the following code: <script type="text/javascript"> var img1 = new Image(); img1.src = "images/important.png"; var img1 = new Image(); img2.src = "images/notsoimportant.png"; var img1 = new Image(); img3.src = "images/unimportant.png";</script> Approach: Loading JavaScript more quickly The second approach is to simply spend less time loading the same JavaScript, so that visitors spend less time waiting for the page to render. There are a number of ways to achieve just that: Techniques used with images, such as caching and parallel download Free Content Delivery Networks GZIP compression Minification Combining or breaking up JavaScript files Removing unused code Techniques used with images JavaScript files are static files, just like images and CSS files. This means that many techniques that apply to images apply to JavaScript files as well, including the use of cookie-free domains, caching, and boosting parallel loading. Free Content Delivery Networks Serving static files from a Content Delivery Network (CDN) can greatly reduce download times, by serving the files from a server that is close to the visitor. A CDN also saves you bandwidth because the files are no longer served from your own server. A number of companies now serve popular JavaScript libraries from their CDNs for free. Here are their details: Google AJAX Libraries API http://code.google.com/apis/ajaxlibs/ Serves a wide range of libraries including jQuery, jQuery UI, Prototype, Dojo, and Yahoo! User Interface Library (YUI) Microsoft Ajax Content Delivery Network http://www.asp.net/ajaxlibrary/cdn.ashx Serves libraries used by the ASP.NET and ASP.NET MVC frameworks including the jQuery library and the jQuery Validation plugin jQuery CDN http://docs.jquery.com/Downloading_jQuery Serves the jQuery library In ASP.NET 4.0 and later, you can get the ScriptManager control to load the ASP. NET AJAX script files from the Microsoft AJAX CDN instead of your web server, by setting the EnableCdn property to true: <asp:ScriptManager ID="ScriptManager1" EnableCdn="true" runat="server" /> One issue with loading libraries from a CDN is that it creates another point of failure—if the CDN goes down, your site is crippled. GZIP compression IIS has the ability to compress content sent to the browser, including JavaScript and CSS files. Compression can make a dramatic difference to a JavaScript file as it goes over the wire from the server to the browser. Take for example the production version of the jQuery library:   Uncompressed Compressed jQuery library 78 KB 26 KB   Compression for static files is enabled by default in IIS 7. This immediately benefits CSS files. It should also immediately benefit JavaScript files, but it doesn't because of a quirk in the default configuration of IIS 7. Not all static files benefit from compression; for example JPEG, PNG, and GIF files are already inherently compressed because of their format. To cater to this, the IIS 7 configuration file applicationHost.config contains a list of mime types that get compressed when static compression is enabled: <staticTypes> <add mimeType="text/*" enabled="true" /> <add mimeType="message/*" enabled="true" /> <add mimeType="application/javascript" enabled="true" /> <add mimeType="*/*" enabled="false" /></staticTypes> To allow IIS to figure out what mime type a particular file has, applicationHost.config also contains default mappings from file extensions to mime types, including this one: <staticContent lockAttributes="isDocFooterFileName"> ... <mimeMap fileExtension=".js" mimeType="application/x-javascript" /> ...</staticContent> If you look closely, you'll see that the .js extension is mapped by default to a mime type that isn't in the list of mime types to be compressed when static file compression is enabled. The easiest way to solve this is to modify your site's web.config, so that it maps the extension .js to mime type text/javascript. This matches text/* in the list of mime types to be compressed. So, IIS 7 will now compress JavaScript files with the extension .js (folder Minify in the downloaded code bundle): <system.webServer> <staticContent> <remove fileExtension=".js" /> <mimeMap fileExtension=".js" mimeType="text/javascript" /> </staticContent></system.webServer> Keep in mind that IIS 7 only applies static compression to files that are "frequently" requested. This means that the first time you request a file, it won't be compressed! Refresh the page a couple of times and compression will kick in.
Read more
  • 0
  • 0
  • 13093

article-image-customizing-graphics-and-creating-bar-chart-and-scatterplot-r
Packt
28 Oct 2010
4 min read
Save for later

Customizing Graphics and Creating a Bar Chart and Scatterplot in R

Packt
28 Oct 2010
4 min read
Statistical Analysis with R Take control of your data and produce superior statistical analysis with R. An easy introduction for people who are new to R, with plenty of strong examples for you to work through This book will take you on a journey to learn R as the strategist for an ancient Chinese kingdom! A step by step guide to understand R, its benefits, and how to use it to maximize the impact of your data analysis A practical guide to conduct and communicate your data analysis with R in the most effective manner       Charts, graphs, and plots in R R features several options for creating charts, graphs, and plots. In this article, we will explore the generation and customization of these visuals, as well as methods for saving and exporting them for use outside of R. The following visuals will be covered in this article: Bar graphs Scatterplots Line charts Box plots Histograms Pie charts Time for action — creating a bar chart A bar chart or bar graph is a common visual that uses rectangles to depict the values of different items. Bar graphs are especially useful when comparing data over time or between diverse groups. Let us create a bar chart in R: Open R and set your working directory: > #set the R working directory > #replace the sample location with one that is relevant to you > setwd("/Users/johnmquick/rBeginnersGuide/") Use the barplot(...) function to create a bar chart: > #create a bar chart that compares the mean durations of the battle methods > #calculate the mean duration of each battle method > meanDurationFire <- mean(subsetFire$DurationInDays) > meanDurationAmbush <- mean(subsetAmbush$DurationInDays) > meanDurationHeadToHead <- mean(subsetHeadToHead$DurationInDays) > meanDurationSurround <- mean(subsetSurround$DurationInDays) > #use a vector to define the chart's bar values > barAllMethodsDurationBars <- c(meanDurationFire, meanDurationAmbush, meanDurationHeadToHead, meanDurationSurround) > #use barplot(...) to create and display the bar chart > barplot(height = barAllMethodsDurationBars) Your chart will be displayed in the graphic window, similar to the following: What just happened? You created your first graphic in R. Let us examine the barplot(...) function that we used to generate our bar chart, along with the new R components that we encountered. barplot(...) We created a bar chart that compared the mean durations of battles between the different combat methods. As it turns out, there is only one required argument in the barplot(...) function. This height argument receives a series of values that specify the length of each bar. Therefore, the barplot(...) function, at its simplest, takes on the following form: barplot(height = heightValues) Accordingly, our bar chart function reflected this same format: > barplot(height = barAllMethodsDurationBars) Vectors We stored the heights of our chart's bars in a vector variable. In R, a vector is a series of data. R's c(...) function can be used to create a vector from one or more data points. For example, the numbers 1, 2, 3, 4, and 5 can be arranged into a vector like so: > #arrange the numbers 1, 2, 3, 4, and 5 into a vector > numberVector <- c(1, 2, 3, 4, 5) Similarly, text data can also be placed into vector form, so long as the values are contained within quotation marks: > #arrange the letters a, b, c, d, and e into a vector > textVector <- c("a", "b", "c", "d", "e") Our vector defined the values for our bars: > #use a vector to define the chart's bar values > barAllMethodsDurationBars <- c(meanDurationFire, meanDurationAmbush, meanDurationHeadToHead, meanDurationSurround) Many function arguments in R require vector input. Hence, it is very common to use and encounter the c(...) function when working in R. Graphic window When you executed your barplot(...) function in the R console, the graphic window opened to display it. The graphic window will have different names across different operating systems, but its purpose and function remain the same. For example, in Mac OS X, the graphic window is named Quartz. For the remainder of this article, all R graphics will be displayed without the graphics window frame, which will allow us to focus on the visuals themselves. Pop quiz When entering text into a vector using the c(...) function, what characters must surround each text value? Quotation marks Parenthesis Asterisks Percent signs   What is the purpose of the R graphic window? To debug graphics functions To execute graphics functions To edit graphics To display graphics
Read more
  • 0
  • 0
  • 17320
article-image-joomla-15-top-extensions-using-languages
Packt
28 Oct 2010
5 min read
Save for later

Joomla! 1.5 Top Extensions for Using Languages

Packt
28 Oct 2010
5 min read
  Joomla! 1.5 Top Extensions Cookbook Over 80 great recipes for taking control of Joomla! Extensions Set up and use the best extensions available for Joomla! Covers extensions for just about every use of Joomla! Packed with recipes to help you get the most of the Joomla! extensions Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible        Introduction One of the greatest features of Joomla! is that you can build a multilingual website. The Joomla! interface can be displayed in many languages. You can simply download the translation pack for the required language and install that to Joomla!. If you don't have a translation pack for your desired language, you can translate it by editing language files directly or by using the translation manager component. The translation manager component allows you to visually translate your site's interface into any language, right from the Joomla! administration area. After completing the translation, you can pack the translation and share it with others, so that they can install the translation in other Joomla! sites. Besides translating the Joomla! interface, you can translate a site's contents into your desired language. The GTranslate component allows you to translate your site's content into 55 languages using Google's translation service. Adding a language to your site Joomla! can build a multilingual site. A site interface can be in multiple languages, using different locales. In this recipe, you will learn how to add an additional language to a Joomla! site. Getting ready... Joomla! translations are available in major languages. First, decide which language you want to add to your site. For example, we want to add French to a Joomla! website. A French translation for Joomla! 1.5 is available to download at the Joomla! Extensions Directory, http://extensions.joomla.org/extensions/languages/translations-for-joomla. Download this extension from http://joomlacode.org/gf/project/french/frs/, and install it from the Extensions | Install/Uninstall screen. How to do it... After installation, follow the steps as shown: From the Joomla! administration panel, click on Extensions | Language Manager. This will show the Language Manager screen, listing the installed languages for the site: Note that the default language for the site is marked with a yellow star in the Default column. To make the newly-installed language, French (Fr), the default language for your site, select the language and click on the Default button in the toolbar. Preview the site's frontend and you will find the site's interface (not content) in French. For example, the Login Form module will look like the following screenshot: For changing the language of the administration panel, in the Language Manager screen click on Administrator, select a language from the list, and set that as the default language for the administrator backend. See also... Adding a translation will only show the Joomla! interfaces in that language. The content of the site is not translated or displayed in the selected language. Also note that we still don't have a mechanism to select our desired language. All of these things can be done using the Joom!Fish extension, which is discussed in the recipe Manually Translating Your Joomla! Site's Content into Your Desired Language. Translating language files for your site Joomla!'s translations are available in most major languages. However, you may like to change the translations and have your own translation in your desired language. In that case, Joomla! provides a mechanism to translate the Joomla! interface language. In this recipe, you will learn how to translate language files for your site from the administration backend. Getting ready... Translation Manager is a popular extension that can help you translate the site's language files right from the administration backend, without opening a text editor. Download this extension from http://joomlacode.org/gf/project/joomla_1_5_tr1/frs/ and install it from the Extensions | Install/Uninstall screen. How to do it... After installation, follow the steps as shown: From the Joomla! administration panel, click on Components | Translation Manager. This will show the Translation Manager screen, listing all of the installed languages for the site and the administration backend. < For changing any language translation, select that language, for example Site [en-GB] English(United Kingdom), and click on the View Files button. This will show the language files for that language. Now select a file, such as, com_banners, and click on the Edit button. This shows the string editing screen for the com_banners.ini file. Change the strings accordingly, and click on the Save button in the toolbar. For adding a new language, click on New in the Translation Manager screen. This will show the Create New Language screen: In the Language Details section, configure the following: Client: Select who will be the client for this translation—Administrator, Installation, or Site. If you want to translate for the administrator interface, select Administrator. We want to translate the site's frontend, therefore we select Site. Language ISO tag: Type the ISO tag for the language. For example, if we want to translate it into Bengali, type ISO code bn-BD. Name: Type language name, that is Bangla. Description: Type a short description for the translation. Legacy Name: Type the traditional name of the language, for example, bn for bn-BD. Language Locales: Type the locale code for the language. Windows Code page: Specify the code page for the language. The default is iso-8859-1. For the Bangla language it will be utf-8. PDF Font: Specify the font family to be used for displaying the PDF in that language. Right-to-Left: Specify Yes if the language is to be read from right to left (for example, Arabic). In the Author Details section, provide the translator's name (probably your name), e-mail address, website URL, version number for the translation, creation date, the copyright holder's name, and URL to the license document. When done, click on the Save button in the toolbar. This saves the language definition and you will see the language name on the Translation Manager screen:
Read more
  • 0
  • 0
  • 4925

article-image-manually-translating-your-joomla-sites-content-your-desired-language
Packt
28 Oct 2010
5 min read
Save for later

Manually Translating Your Joomla! Site's Content into Your Desired Language

Packt
28 Oct 2010
5 min read
Joomla! 1.5 Top Extensions Cookbook Over 80 great recipes for taking control of Joomla! Extensions Set up and use the best extensions available for Joomla! Covers extensions for just about every use of Joomla! Packed with recipes to help you get the most of the Joomla! extensions Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible        The reader would benefit from the previous article on Joomla! 1.5 Top Extensions for Using Languages. Getting ready... Joom!Fish is the most popular extension for building multilingual Joomla! websites. Download the latest version of Joom!Fish from http://joomlacode.org/gf/download/frsrelease/11315/45280/JoomFish2.0.4.zip, and install it from the Extensions | Install/Uninstall screen. It installs one component, two modules, and several plugins. How to do it... After installation, carry out the following steps: From the Joomla! administration panel, click on Components | Joom!Fish | Control Panel. This shows the Joom!Fish :: The multilingual Content Manager for Joomla! screen. Click on Language Configuration. This shows the Joom!Fish Language Manager screen, and lists all the installed languages. In the Active column, enable the checkboxes to activate the required languages. If you don't see an image for a language, type the image's URL in the Image filename field. Then click the icon displayed in the Config column. This shows the Joom!Fish Language Manager - Translate Configuration screen. In this screen, you can translate some common phrases, for example Offline Message, Site Name, Global Site Meta Description, Global Site Meta Keywords, a help site URL, mail settings, and so on. Type in the translations and click on the Save button in the toolbar. Now click on Translation, select Bengali in the Languages drop-down list, and select Categories in the Content elements drop-down list. This shows the translatable categories. Click on a category name and you should see the Translate screen, with the original text and a textbox to insert your translation. Type your translation in the Translate fields, enable the Published checkbox and then click on the Save button in the toolbar. Follow the same process for translating other categories. When finished translating all categories, select Contents in the Content elements drop-down list on the Translate screen. This shows the list of available articles for translation. Click an article title to translate. This shows the Translate screen with the original text and textboxes for translation. Type the translations in the Translation fields, enable the Published checkbox, and click on the Save button in the toolbar. Similarly, change types in the Content elements drop-down box and translate other content including Modules, Menus, Contacts, Banners, and so on. When finished translating, click on Extensions | Module Manager. This shows the Module Manager screen, listing the installed modules. From the list, click on the Language Selection module. This shows the Module: [Edit] screen: Select Yes in the Published field and select a module position from the Position drop-down list. From the Module Parameters section, in the Appearance of language selector drop-down list select how you want to display the language selection box. You can choose from Drop down of names, Drop down of names with current language flag, ul-list of names, ul-list of names with flag, ul-list of images, and Raw display of images. Preview the site's frontend and you should see the site in the default language, with the language selection box at the specified position. From the language selection module, click another case, in my case Bangla, to show the site content in that language. Visitors to your site can now switch to any active language through this language selection module. Note that the URL of the site now appends language code, for example, http://www.yourjoomlasite.com/index.php?lang=bn, where bn stands for the Bangla language. There's more... Note that in Joom!Fish, you can translate almost anything—articles, modules, menus, sections, categories, and so on. These translations are done through content elements. You can see any component or module by clicking on Components | Joom!Fish | Content Elements. You can download content elements for new extensions from http://extensions.joomla.org/extensions/extension-specific/joomfish-extensions and http://joomlacode.org/gf/project/joomfish/frs/. After downloading content elements, click on the Install button on Content Elements screen. This shows the Joom!Fish::Content Element Installer screen. Click on the Browse button, select the content element file, and then click on the Upload File & Install button. This installs the content and you can translate the content for that particular component or module. Summary This article covered: Manually translating your site's content into your desired language Further resources on this subject: Adding an Event Calendar to your Joomla! Site using JEvents Showing your Google calendar on your Joomla! site using GCalendar Joomla! 1.5 Top Extensions: Adding a Booking System for Events Joomla! 1.5 Top Extensions for Using Languages
Read more
  • 0
  • 0
  • 3524

article-image-managing-articles-using-k2-content-construction-kit
Packt
27 Oct 2010
8 min read
Save for later

Managing Articles Using the K2 Content Construction Kit

Packt
27 Oct 2010
8 min read
  Joomla! 1.5 Cookbook The reader would benefit from the previous article on Installation and Introduction of K2 Working with items AKA articles The power of K2 is in the idea of categorizing your data, thus making it easier to manage. This will be especially helpful as your site grows in content. Many sites are fully article-based and it is not uncommon to see a site with thousands of articles on it. In this section, we'll tackle some more category-specific recipes. You may have noticed by now that data does not show up as typical articles do in Joomla!. In other words, if you added an item, set it published and featured, it may not be displayed on your site because you have not set up a menu item to your K2 content. K2 will need to be added to your menu structure to display the items (articles) in K2. The first recipe will take into account a site that has been in operation for a while and has K2 added to it. Getting ready This section assumes you have installed K2 and have content on your site. How to do it... Make sure you have a full backup of the database and the files. Log in as the administrator. Open the K2 Dashboard. If you DID NOT import your content in, (see the first recipe), do so now. If you have ALREADY imported your content using the Import Joomla! Content button - DO NOT import again. You run the risk of duplicating all your content. Should this happen, you can go in and delete the duplicate items. This can be a time-consuming process. Open Article Manager | Content | Article Manager. Select all your articles from the Article Manager and unpublish. Open Menu Manager and find your Home menu.Now that we have unpublished content, we'll need to replace the traditional Joomla! content items with K2 content. Opening the Menu Manager and selecting the Home menu item will show this: As you can see under K2 there are several choices to display content on your site. I will choose Item | Item as my display mode. This will show my visitors content in article form. You can pick what works best for you. Now returning to the instructions: After choosing Menu Item Type - click Save. Open K2 Dashboard. Select Items.Here is a partial screenshot of the items in our sample site. As you can see, it now starts to take on a bit more traditional Joomla! look. I can choose featured articles, publish them, or note. Set the order they show up in, the category they belong to and more. When you import content, from Joomla!, the articles retain their identity from Section and Category configuration. For example, the Joomla! Community Portal listed in the preceding screenshot as belonging to the category Latest has a parent category of News. When you imported the content, sections became the new K2 top-level categories. All existing categories become subcategories of the new top level categories. As we added K2 to a working site with sections and category data already in place, I want to make sure they inherit from our master category. In our sample site, we see the following screen when we open the K2 categories from the K2 Dashboard: We instruct the new top-level categories to follow the master category as the model for the rest. The following instructions will show you how. Open K2 Dashboard. Click Categories. Open your imported top-level categories - for this site it's About Joomla! and News. Each of these has sub-categories. Click About Joomla! (or your equivalent). Change the Inherit parameter options from category to MASTER CATEGORY USE AS INHERIT ONLY. Make sure the Parent category stays set to –None--. Click Save.When done, it will look like this: Extra fields Did you notice the Associated "Extra Fields Group" is set to - None - ? You can change this parent category group to use an extra fields group and still keep the master category parameters. Each of the subcategories will inherit from the master category. By doing this, you can still control all the categories parameters simply by changing the master category. How it works... The category system as described here for K2 is a giant access-control system allowing you the flexibility to structure your site and data as you need. It also offers a means to control the 'look and feel' of the articles from a central place. When you import a Joomla! site into K2 you bring all the sections, content, articles, and other associated parts into it. Sections become new parent categories and the old categories become subcategories. This can be a bit confusing at first. One suggestion is to write out on paper what you want the site to look like, and then lay out your categories. You might find that the structure you had can be more user-friendly using K2 and you will want to change. This category system offers you nearly unlimited means to nest articles. In essence, a category can have unlimited categories under it. There is a limit to this in terms of management, but you get the idea. There's more... Using tags in K2 will give you the ability to improve your Search Engine Optimization or SEO on your site. Additionally, the use of tags will allow you to give your users the ability to follow the tags to other articles. In this section we'll review how to use Tags in K2. Tags are keywords or terms that are assigned to your content. This enables your visitors to quickly locate what they need by one word descriptions. Using Tags in K2 Tags can be created before an article is written or on the fly. I prefer on the fly as it will match the article. You can think of a tag almost as a dynamic index. Every time a tag is added to an article, it will show up in the K2 Tag Cloud module if you are using it. The more a single tag, such as Joomla!, is used in the content, the larger it appears in the K2 Cloud module. K2 Tag Clouds can benefit your search engine optimization and a navigational element. Here is an example of our K2 Tag Cloud: This is an image of our K2 Tag Cloud module. The more often a tag is added to an article, the larger it appears. Setting up your site for Tag Clouds K2 installs the K2 Tools module by default. The module has many functions, but for our purposes here, we'll use the Tag module. Log in to the Administrator Console of Joomla!. Click Extensions | Module Manager. Click New to create a new module. Find this for your new item: Once in there, give it a name and select its module location. On the right under Parameters, pull down the Select module functionality drop-down list as follows: Select Tag Cloud as shown in the preceding screenshot. Leave all the root categories set for none - this will enable K2 to pull in all the categories. Click Save. This particular module, has many functions and you can set up a new module to use any of the great tools built into it. Next you will want to add some tags to articles. As I said at the beginning of this article, you have two different ways to do this. You may add them to the article or you may add them to the Tag Manager. Let's quickly review the latter method. Open K2 Dashboard. Click Tags. You may see a list of tags there. If you wish to delete them, simply check the ones you want to remove and click Delete in the upper right-hand corner. Otherwise just leave them. Click New which will open the Details box. Fill in the tag; make sure it's published and click Save. This is an example of a filled out tag box (before save). Adding Tags on the fly This model allows you to tag the content as soon as you create it. If there are tags available, already such as those from the previous step, then you can add them. Open K2 Dashboard. Click Items. Select an item or click New to create an item. The field Tags will be blank, you can start to type in a field, such as K2 Content Creation Kit (as shown in the preceding screenshot). If it exists, then it will be available to be able to click and add. If there are no tags available, then simply type one in and click Return or add a comma. Here is an example item with tags. Here we have four tags, Security x, PHP x, Joomla x, K2 Content Creation Kit x. Any item (article) that has these tags will be easily found by both users and search bots. Let's see how our Tag Cloud looks now: You probably notice the changes, especially the addition of the new tag K2 Content Creation Kit. Clicking on that tag will yield two articles, and clicking on the Security tag yields three. Search engines can follow these links to better categorize your site. Users can get a sense of what is more important in terms of content from your site and it helps them navigate. Closing on this, I strongly suggest you spend time picking tags that are important on your site and is relevant to the purpose of it.
Read more
  • 0
  • 0
  • 3516
article-image-postgresql-9-reliable-controller-and-disk-setup
Packt
27 Oct 2010
10 min read
Save for later

PostgreSQL 9: Reliable Controller and Disk Setup

Packt
27 Oct 2010
10 min read
Accelerate your PostgreSQL system Learn the right techniques to obtain optimal PostgreSQL database performance, from initial design to routine maintenance Discover the techniques used to scale successful database installations Avoid the common pitfalls that can slow your system down Filled with advice about what you should be doing; how to build experimental databases to explore performance topics, and then move what you've learned into a production database environment Covers versions 8.1 through 9.0 PostgreSQL uses a Write-Ahead Log (WAL) to write data in a way that survives a database or hardware crash. This is similar to the log buffer or REDO log found in other databases. The database documentation covers the motivation and implementation of the WAL at http://www.postgresql.org/docs/current/ static/wal.html To quote from that introduction: WAL's central concept is that changes to data files (where tables and indexes reside) must be written only after those changes have been logged, that is, after log records describing the changes have been flushed to permanent storage. This procedure ensures that if your application has received a COMMIT for a transaction, that transaction is on permanent storage, and will not be lost even if there is a crash. This satisfies the durability portion of the ACID (atomicity, consistency, isolation, durability) expectations databases aim to satisfy. Write-back caches The CPUs and memory in your server are quite fast compared to its disk drives. Accordingly, making the rest of the system wait for the disks, particularly when things need to be written out, can drag overall performance down heavily. Systems that wait for the disks to complete their writes before moving into their next task are referred to as having a write-through cache. While the data may be stored temporarily in a memory cache, until it's made it all the way through to the physical disk, any write an application requested isn't considered complete. The normal solution to making that faster is to introduce a different type of write cache between the program doing the writing and disks. A write-back cache is one where data is copied into memory, and then control returns to the application that requested the write. Those writes are then handled asynchronously, at some future time dictated by the design of the write-back cache. It can take minutes before the data actually makes it to disk. When PostgreSQL writes information to the WAL, and sometimes when it writes to the regular database files too, that information must be "flushed to permanent storage" in order for the database's crash corruption defense mechanism to work. So what happens if you have a write-back cache that says the write is complete, but it really isn't? People call these lying drives, and the result can be very bad: If you have a system with a write-back cache, and a system crash causes the contents of that write-back cache to be lost, this can corrupt a PostgreSQL database stored on that drive and make it unusable. You can discover it takes expert intervention to even get the database to start again, and determining what data is damaged will be difficult. Consider the case where you have committed a transaction. Details of that new transaction might be spread across two data blocks on the drive. Now, imagine that one of those made it to disk before the system crashed, but the other didn't. You've now left the database in a corrupted state: one block refers to a transaction that doesn't exist where it's supposed to in the other block. Had at least all of the data blocks related to the WAL been written properly, the database WAL could correct this error after the crash. But the WAL protection only works if it can get honest information about whether information has been written to the disks properly or not, and the "lying" write-back caches do not report that. Sources of write-back caching Servers are filled with write caches you need to be aware of: Operating system write cache. This cache can easily be gigabytes in size. Typically you can flush data out of this cache by forcing a "sync" operation on the block that needs to be stored on disk. On POSIX systems (which includes all UNIX-like ones), this is done with the fsync or fdatasync calls. In some cases, it's possible to write directly in a sync mode, which is effectively a write followed by fsync. The postgresql.conf setting wal_sync_method controls which method is used, and it's possible to disable this altogether to optimize for speed instead of safety. Disk controller write cache. You'll find a write cache on most RAID controller cards, as well as inside external storage such as a SAN. Common sizes right now are 128 MB to 512 MB for cards, but gigabytes are common on a SAN. Typically controllers can be changed to operate in the completely writethrough mode, albeit slowly. But by default, you'll normally find them in write-back mode. Writes that can fit in the controller's cache are stored there, the operating system is told the write is completed, and the card writes the data out at some future time. To keep this write from being lost if power is interrupted, the card must be configured with a battery. That combination is referred to as a battery-backed write cache (BBC or BBWC). Disk drive write cache. All SATA and SAS disks have a write cache on them that on current hardware is 8 MB to 32 MB in size. This cache is always volatile: if power is lost, any data stored in there will be lost and they're always write-back caches if enabled. How can you make sure you're safe given all these write-back caches that might lose your data? There are a few basic precautions to take: Make sure whatever file system you're using properly implements fsync calls, or whatever similar mechanism is used, fully. Monitor your driver controller battery. Some controller cards will monitor their battery health, and automatically switch from write-back to writethough mode when there is no battery or it's not working properly. That's a helpful safety measure, but performance is going to drop hard when this happens. Disable any drive write caches. Most hardware RAID controllers will do this for you, preferring their own battery-backed caches instead. Disk controller monitoring When you have a RAID controller card with a battery-backed cache, you probably expect you'll need to monitor the card to determine when disks fail. But monitoring controller battery health is an equally critical aspect of maintaining a reliable database system when you're using this technology. If the battery fails and you're using it in write-back mode, your writes are not safe. Similarly, if your power fails, you should prefer shutting the database server down after a few minutes of power loss to trying to keep it going. Integrating in power monitoring via a UPS or similar mechanism should be part of your database server configuration, so that a short outage results in an orderly shutdown. Consider the purpose of the controller battery to protect yourself from really unexpected outages, like someone tripping over the power cord. Even if the manufacturer claims the controller battery will last through days of downtime, that's not a good reason to believe you'll actually be safe for an extended outage. You should consider the battery as something you'd prefer to only use for some number of minutes of protection. That may be the reality, particularly in a case where the battery is older and has lost much of its capacity, and some controller batteries don't start out with very much capacity. Be sure to run your own tests rather than blindly believing the manufacturer specifications: your data depends on it. Better RAID controllers will automatically disable write-back mode if their battery stops working normally. If performance suddenly drops on an older server, this is one potential cause. Also don't forget that every UPS has a battery that degrades over time as well. That's all the more reason to arrange an orderly shutdown of your server during a power outage, rather than optimistically presuming you can keep it running until power returns. Disabling drive write caches If your card doesn't disable all the drive write caches, or if you're using a software RAID approach, you'll need to turn the caches off yourself. The best way to do this is to see if it's possible to change the default write cache state using the utilities provided by the drive manufacturer. You should be able to do this through software as well. Here is a sample session from a Linux system checking the write cache, toggling it off, confirming that change took, and then toggling it on again: # hdparm -I /dev/sda | grep "Write cache" * Write cache # sudo hdparm -W 0 /dev/sda /dev/sda: setting drive write-caching to 0 (off) write-caching = 0 (off) # hdparm -I /dev/sda | grep "Write cache" Write cache # hdparm -W 1 /dev/sda /dev/sda: setting drive write-caching to 1 (on) write-caching = 1 (on) Only the -W 0 configuration is completely safe for database use. The PostgreSQL WAL documentation suggests similar commands to use for other operating systems. Performance impact of write-through caching If you don't have a battery-backed write cache, and therefore can't utilize some memory-based cache to accelerate fsync writes, commit performance on your database can be quite bad. The worst-case here is where you have a single client that is issuing a commit after every statement it executes. The reality of how a hard drive works means that individual writes happen once each time the drive spins around. Here are the measurements for the common drive speeds available right now, with computed maximum commit rate:     Rotation speed Rotation time (ms) Max commits/second 5400 11.1 90 7200 8.3 120 10000 6.0 166 15000 4.0 250 It's important to realize how limiting this can be: If you have a common 7200 rpm hard drive, no single client can commit more than 120 transactions/second in any situation where all that's available is a write-back cache. It doesn't matter how many disks you have in a RAID array, or how you configure your software. You must have hardware with a battery, enabling a non-volatile write-back cache, in order to safely exceed this limit. Some PostgreSQL installs use a RAID controller card just for this purpose, to provide a BBWC, in Just a Bunch of Disks (JBOD) mode—where no RAID is being done on the controller at all. Sometimes disks are used directly, and others layer software RAID on top, which can have some advantages compared to hardware RAID. If you have more than one client, you'll get more done per commit. It's normal to see >500 committed transactions per second if you have a larger number of clients all committing regularly, because each flushed disk write will include any queued up commit requests from other clients, too. The other common technique here is to batch commits into larger pieces, perhaps going 1000 records at a time rather than a single one, in order to reduce the average impact of commit latency. Another approach for accelerating systems that don't have a usable write cache is asynchronous commit. Summary In this article we saw how accidentally using volatile write-back caching in disk controllers and drives can easily introduce database corruption. Further resources on this subject: UNIX Monitoring Tool for PostgreSQL [Article] Server Configuration Tuning in PostgreSQL [Article] PostgreSQL 9: Balancing Hardware Spending [Article]
Read more
  • 0
  • 0
  • 2665

article-image-tips-and-tricks-joomla-multimedia
Packt
27 Oct 2010
7 min read
Save for later

Tips and Tricks for Joomla! Multimedia

Packt
27 Oct 2010
7 min read
  Joomla! 1.5 Multimedia Build media-rich Joomla! web sites by learning to embed and display Multimedia content Build a livelier Joomla! site by adding videos, audios, images and more to your web content Install, configure, and use popular Multimedia Extensions Make your web site collaborate with external resources such as Twitter, YouTube, Google, and Flickr with the help of Joomla! extensions Follow a step-by-step tutorial to create a feature-packed media-rich Joomla! site         Read more about this book       (For more resources on Joomla!, see here.) Using another folder name for images in Joomla! Tip: If you do decide to use another folder name for your media directory, it is important to leave the current /images directory on the server as this can often be used by other components.   Organizing your content Tip: The organization of your website media content is of utmost importance. Just like with your Joomla! Articles, the correct structure of your files can save you time and frustration down the line when you want to easily find an image or media file.   Creating a new directory using Joomla! Media Manager Tip: While creating a new directory using Joomla! Media Manager, a forward slash is already pre-populated, so you only need to enter the name of the directory and nothing else.   Uploading and downloading files Tip: FTP programs offer you the most flexibility in managing your website files, but it is important to take care when using FTP programs. By connecting to your directory structure on the web server, you are navigating amongst core Joomla! files. You can download a file in a similar manner, or you might need to double-click on the file to start downloading it.   Uploading a new file with Joomla! Media Manager Tip: To upload a new file, make sure you are residing in the correct remote directory for upload. Browse to a file on your computer and simply drag this file over into your web browser.   Location of the Joomla! Template CSS files Tip: The Joomla! Template CSS file is usually located in the following directory /templates/yourtemplate/css/template.css. If you are using a pre-built Joomla! Template, you may see multiple CSS files inside the CSS directory. It is important to note that the names of these CSS files may differ between Joomla! Templates, but the template.css file is the standard naming convention for the main CSS file.   Adding an image using the Joomla! Article Image button Tip: Images can be easily added to new and existing Joomla! Articles (and Modules) by using the Image button, which is an extended editor plugin that is configured to be turned on with new Joomla! installations.   Adjusting your Joomla! template images Tip: The images for a Joomla! Template are generally located in the <Your Joomla Home Folder>/templates/<yourtemplate>/images directory. If you would like to adjust certain images in your template, the easiest way to do this is by viewing the template in your site browser and then making the necessary adjustments to the images.   Audio in Joomla! Articles Tip: It is good practice to make a blank .html file and upload it to your new audio directory. This will help stop anyone from being able to directly view all of the files inside your new audio directory. If you cannot create a new .html file, copy an existing Joomla! .html file that resides in the images directory.   Backup of site database Tip: Before installing any third-party code into your Joomla! website, make sure you take a backup of your site database and file set before installing extensions.   Dealing with complex HTML code Tip: Make sure you don't have your WYSIWYG editor turned on in your Joomla! Articles when entering complex HTML code into your Joomla! Articles.   Joomla! Plugin tags Tip: It is worth noting that Joomla! Plugin tags work with and without the WYSIWYG editor turned on.   Video podcast for Joomla! Tip: Creating a video podcast for Joomla! will allow you to display and promote your site or products to many users. Due to the nature of a podcast, they do not even have to be on your website to view the video podcasts, if produced correctly.   Multimedia enhancements with Shadowbox Tip: Shadowbox is a multi-use media plugin for your Joomla! website, so it may be all that you need for your multimedia requirements. The extension can be downloaded at http://extensions.joomla.org by searching for "Shadow".   Inserting custom code into your Joomla! Articles Tip: When starting to insert custom code into your Joomla! Articles, it is important to turn off WYSIWYG editors for your user account. This is because these editors cannot always process the custom HTML code. If the code is not recognized by the editor when loading in the content, it will remove the code altogether. The editor settings can be adjusted in the Global Configuration, or on a user basis via the User Manager.   Extension titles in Joomla! Extension Directory (JED) listings Tip: Due to lengthy URLs and the possibility that Joomla! Extension Directory (JED) listings could change at any time, search terms for the following extensions have been included, rather than direct links to the extensions. Performing a search on the JED for the related terms will help you find these extensions easily. The letters after the extension titles denote the following: M = Module C = Component P = Plugin L = Language T = Template   Publishing your Twitter tweets in your Joomla! site Tip: The JTweet extension is a module that publishes your Twitter tweets in your Joomla! site. The jTweet module now requires the JB Library plugin in order to work. The JB Library plugin loads the jQuery library automatically into the head of your template. The jQuery library is required for the jTweet module.   Mobilebot for Joomla 1.5 Tip: Mobilebot 1.0 for Joomla! 1.5.x can detect visitors using mobile devices and change the Joomla! Template automatically.   If you install an extension and do not use it, then remove it. Tip: Besides keeping your Joomla! site organized and uncluttered, it is best to remove code/files/folders from your server that are not being used. Leaving older code lying around can create security vulnerabilities.   Keep Joomla! up-to-date. Tip: Joomla! releases are made available for a reason and it is important to stay up-to-date with the software. With a well-structured design to the framework, there are now very few reasons to go near the core codework. Upgrading is usually an easy process, compared to some other web platforms. Remember to take a backup of your site files before performing any upgrade work, and to take regular backups whenever you can.   Content parameters Tip: The Article Manager in Joomla! contains a "Global Parameter" setting that sets the default options for your Joomla! Articles. You can override these within each article, but it is good practice to set these globally first, so you don't have to go back and adjust them later on.   HTTP status errors Tip: Joomla! uses the /templates/system/error.php file to handle several HTTP status errors, including "403 Forbidden", "404 Not Found", and "500 Internal Server" errors.   Uninstalling Extensions for Joomla! 1.5 Tip: Extensions for Joomla! 1.5 can be uninstalled easily by clicking on the Manage menu item on the Extension Manager page.   Summary In this article we highlighted some of the tips and tricks which can be of great use while working with Joomla! Multimedia. Further resources on this subject: Joomla! 1.5 Top Extensions Cookbook [Book] Joomla! Social Networking with JomSocial [Book] Joomla! 1.5 JavaScript jQuery [Book]
Read more
  • 0
  • 0
  • 1954
Modal Close icon
Modal Close icon