Search This Blog

Tuesday, November 8, 2011

Box-shadow, one of CSS3′s best new features

Box-shadow, one of CSS3′s best new features


box-shadow property allows designers to easily implement multiple drop shadows (outer or inner) on box elements, specifying values for color, size, blur and offset.
Browser support is growing of late with Mozilla (Firefox), Webkit (Safari/Chrome/Konqueror), Opera and the IE9 Platform Preview all offering a decent implementation of the spec, although Mozilla and Webkit still require their respective -moz- and -webkit- prefixes (note Mozilla Firefox 4.0+ no longer requires the -moz- prefix).
Here’s a basic example:
Firefox, Safari/Chrome, Opera and IE9 users should see a grey fading shadow under this box.
In theory, the code for this is straightforward:
#example1 {
box-shadow: 10px 10px 5px #888;
}
But for the moment, as with many other ‘experimental’ CSS3 properties, you’ll need to use the following prefixes to support Mozilla and Webkit:
#example1 {
-moz-box-shadow: 10px 10px 5px #888;
-webkit-box-shadow: 10px 10px 5px #888;
box-shadow: 10px 10px 5px #888;
}

How it Works

The box-shadow property can accept a comma-serparated list of shadows, each defined by 2-4 length values (specifying in order the horizontal offset, vertical offset, optional blur distance and optional spread distance of the shadow), an optional color value and an optional ‘inset‘ keyword (to create an inner shadow, rather than the default outer shadow).
The Syntax:
box-shadow: none | <shadow> [ , <shadow> ]*

<shadow> = inset? && [ <length>{2,4} && <color>? ]
Examples:
box-shadow: 10px 10px;
box-shadow: 10px 10px 5px #888;
box-shadow: inset 2px 2px 2px 2px black;
box-shadow: 10px 10px #888, -10px -10px #f4f4f4, 0px 0px 5px 5px #cc6600;
Let’s first look at how to create a basic outer shadow, before going on to look at the inset keyword, layering multiple shadows and how to spice up your shadows with RGBa colors(?).

Creating a basic drop shadow

By default, shadows are drawn on the outside of elements. According to the specification;
An outer box-shadow casts a shadow as if the border-box of the element were opaque. The shadow is drawn outside the border edge only: it is clipped inside theborder-box of the element.
The first step is to define the shape of the shadow by specifying 2-4 length values.
The first value defines the horizontal offset of the shadow, with a positive value offseting the shadow to the right of the element, and a negative value to the left.
The second value defines the vertifical offset of the shadow, with a positive value offsetting the shadow from the bottom of the element, and a negative value from the top.
If supplied, an optional third value defines the blur distance of the shadow. Only positive values are allowed, and the larger the value, the more the shadow’s edge is blurred. The specification does not include an exact algorithm for how the blur distance should be calculated, however it does elaborate as follows:
…for a long, straight shadow edge, this should create a color transition the length of the blur distance that is perpendicular to and centered on the shadow’s edge, and that ranges from the full shadow color at the radius endpoint inside the shadow to fully transparent at the endpoint outside it.
An optional fourth value can be supplied to define the spread distance of the shadow. A positive value will cause the shadow shape to expand in all directions, while a negative value will cause the shadow shape to contract. The specification goes into much greater detail on how the shadow shape is calculated as follows:
If a spread distance is defined, the shadow is expanded outward or contracted inward by an operation equivalent to applying twice the absolute value of the spread value to a blur operation as defined below and thresholding the result such that for a positive spread distance all non-transparent pixels are given the full shadow color and for a negative spread distance all non-opaque pixels are made transparent. The UA may approximate this operation by taking an outward outset of the specified amount normal to the original shadow perimeter. Alternatively the UA may approximate the transformed shadow perimeter shape by outsetting (insetting, for inner shadows) the shadow’s straight edges by the spread distance and increasing (decreasing, for inner shadows) and flooring at zero the corner radii by the same amount. (The UA may even combine these methods, using one method for outer shadows and another for inner ones.) For corners with a zero border-radius, however, the corner must remain sharp—the operation is equivalent to scaling the shadow shape. In any case, the effective width and height of the shadow shape is floored at zero. (A zero-sized shadow shape would cause an outer shadow to disappear, and an inner shadow to cover the entire padding-box.)
The diagram below (taken from the W3C Backgrounds and Borders Candidate Recommendation) offers a good example of the effects of spread and blur on the shadow:
Spread Radius and Blur Radius diagram
An optional color value can also be supplied, directly after the 2-4 length values, to define the shadow’s color. If not supplied, a UA-chosen default should be applied, however, whilst in Firefox/Opera/IE9 the default color is black, in Safari/Chrome (webkit) no shadow is visible unless a color is specified.
Here are a few examples of shadows with differing offsets, spread and blur.
Examples:
A
B
C
D
E
F

Example A shows a shadow offset to the left and top by 5px:
#Example_A {
-moz-box-shadow: -5px -5px #888;
-webkit-box-shadow: -5px -5px #888;
box-shadow: -5px -5px #888;
}
Example B shows the same shadow with a blur distance of 5px:
#Example_B {
-moz-box-shadow: -5px -5px 5px #888;
-webkit-box-shadow: -5px -5px 5px #888;
box-shadow: -5px -5px 5px #888;
}
Example C shows the same shadow with a spread distance of 5px:
#Example_C {
-moz-box-shadow: -5px -5px 0 5px #888;
-webkit-box-shadow: -5px -5px 0 5px#888;
box-shadow: -5px -5px 0 5px #888;
}
Example D shows the same shadow with both a blur distance of 5px and a spread distance of 5px:
#Example_D {
-moz-box-shadow: -5px -5px 5px 5px #888;
-webkit-box-shadow: -5px -5px 5px 5px#888;
box-shadow: -5px -5px 5px 5px #888;
}
Example E shows a shadow with no offset and a blur distance of 5px:
#Example_E {
-moz-box-shadow: 0 0 5px #888;
-webkit-box-shadow: 0 0 5px#888;
box-shadow: 0 0 5px #888;
}
Example F shows a shadow with no offset and both a blur distance of 5px and a spread distance of 5px:
#Example_F {
-moz-box-shadow: 0 0 5px 5px #888;
-webkit-box-shadow: 0 0 5px 5px#888;
box-shadow: 0 0 5px 5px #888;
}

Creating an inner shadow with the ‘inset’ keyword

An optional ‘inset‘ keyword can be supplied, preceding the length and color values. If present, this keyword causes the shadow to be drawn inside the element. According to the specification:
An inner box-shadow casts a shadow as if everything outside the padding edge were opaque. The inner shadow is drawn inside the padding edge only: it is clipped outside the padding box of the element.
Here are the same examples as above, this time with the ‘inset‘ keyword present.
Examples:
G
H
I
J
K
L

Example G shows an inner shadow offset to the left and top by 5px:
#Example_G {
-moz-box-shadow: inset -5px -5px #888;
-webkit-box-shadow: inset -5px -5px #888;
box-shadow: inset -5px -5px #888;
}
Example H shows the same inner shadow with a blur distance of 5px:
#Example_H {
-moz-box-shadow: inset -5px -5px 5px #888;
-webkit-box-shadow: inset -5px -5px 5px #888;
box-shadow: inset -5px -5px 5px #888;
}
Example I shows the same inner shadow with a spread distance of 5px:
#Example_I {
-moz-box-shadow: inset -5px -5px 0 5px #888;
-webkit-box-shadow: inset -5px -5px 0 5px#888;
box-shadow: inset -5px -5px 0 5px #888;
}
Example J shows the same inner shadow with both a blur distance of 5px and a spread distance of 5px:
#Example_J {
-moz-box-shadow: inset -5px -5px 5px 5px #888;
-webkit-box-shadow: inset -5px -5px 5px 5px#888;
box-shadow: inset -5px -5px 5px 5px #888;
}
Example K shows an inner shadow with no offset and a blur distance of 5px:
#Example_K {
-moz-box-shadow: inset 0 0 5px #888;
-webkit-box-shadow: inset 0 0 5px#888;
box-shadow: inner 0 0 5px #888;
}
Example L shows an inner shadow with no offset and both a blur distance of 5px and a spread distance of 5px:
#Example_L {
-moz-box-shadow: inset 0 0 5px 5px #888;
-webkit-box-shadow: inset 0 0 5px 5px#888;
box-shadow: inset 0 0 5px 5px #888;
}

Layering multiple shadows

The box-shadow property allows elements to have multiple shadows, specified by a comma seperated list. When more than one shadow is specified, the shadows are layered front to back, as in the following example.
Example:
M
Example M shows five shadows specified in the following order; firstly a black shadow with a spread distance of px and a blur distance of px, secondly a lime shadow offset to the top right, thirdly a red shadow offset to the bottom right with a blur distance applied, fourthly a yellow shadow offset to the bottom left, and lastly a blue shadow offset to the top left with a blur distance applied:
#Example_M {
-moz-box-shadow: 0 0 10px 5px black, 40px -30px lime, 40px 30px 50px red, -40px 30px yellow, -40px -30px 50px blue;
-webkit-box-shadow: 0 0 10px 5px black, 40px -30px lime, 40px 30px 50px red, -40px 30px yellow, -40px -30px 50px blue;
box-shadow: 0 0 10px 5px black, 40px -30px lime, 40px 30px 50px red, -40px 30px yellow, -40px -30px 50px blue;
}

Spicing up shadows with RGBa color & border-radius

The box-shadow property can be further enhanced using CSS3 RGBa colors to create shadows with differing levels of opacity, as demonstrated by the examples below.
Examples:
N
O
P

Example N shows a black shadow, specified using standard RGB color, offset to the right and bottom by 5px:
#Example_N {
-moz-box-shadow: 5px 5px rgb(0,0,0);
-webkit-box-shadow: 5px 5px rgb(0,0,0);
box-shadow: 5px 5px rgb(0,0,0);
}
Example O shows the same shadow, this time with the color black specified using RGBa color with an opacity of 70%:
#Example_O {
-moz-box-shadow: 5px 5px rgba(0,0,0,0.7);
-webkit-box-shadow: 5px 5px rgba(0,0,0,0.7);
box-shadow: 5px 5px rgba(0,0,0,0.7);
}
Example P shows the same shadow, this time with the color black specified using RGBa color with an opacity of 50%:
#Example_P {
-moz-box-shadow: 5px 5px rgba(0,0,0,0.5);
-webkit-box-shadow: 5px 5px rgba(0,0,0,0.5);
box-shadow: 5px 5px rgba(0,0,0,0.5);
}

The box-shadow property can also be applied to elements with rounded corners, created using theborder-radius property, in which case the shadow will follow the curve specified by the border-radius property (note: although IE9 seems to struggle with this).
Examples:
Q
R

Example Q shows a shadow offset to the bottom and right by 5px, with a border-radius of 5px applied to each corner:
#Example_Q {
-moz-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: 5px 5px black;
-webkit-box-shadow: 5px 5px black;
box-shadow: 5px 5px black;
}
Example R shows the same shadow with a blur distance of 5px:
#Example_R {
-moz-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: 5px 5px 5px black;
-webkit-box-shadow: 5px 5px 5px black;
box-shadow: 5px 5px 5px black;
}

Browser Support

The box-shadow property has not caught on as quickly as some of its peers (such as the border-radius property) and the property was removed from the CSS3 Backgrounds and Borders specification when it reached Candidate Recommendation earlier this year, pending further development, however the property has been reintroduced in the latest version of the specification and browser support has been growing steadily of late.

Thursday, November 3, 2011

R Language Quick Tips

Built-in Functions

Almost everything in R is done through functions. Here I'm only refering to numeric and character functions that are commonly used in creating or recoding variables.

NUMERIC FUNCTIONS

FunctionDescription
abs(x)absolute value
sqrt(x)square root
ceiling(x)ceiling(3.475) is 4
floor(x)floor(3.475) is 3
trunc(x)trunc(5.99) is 5
round(x, digits=n)round(3.475, digits=2) is 3.48
signif(x, digits=n)signif(3.475, digits=2) is 3.5
cos(x), sin(x), tan(x)also acos(x), cosh(x), acosh(x), etc.
log(x)natural logarithm
log10(x)common logarithm
exp(x)e^x

CHARACTER FUNCTIONS

FunctionDescription
substr(x, start=n1, stop=n2)Extract or replace substrings in a character vector.
x <- "abcdef"
substr(x, 2, 4) is "bcd"
substr(x, 2, 4) <- "22222" is "a222ef"
grep(pattern, x , ignore.case=FALSE, fixed=FALSE)Search for pattern in x. If fixed =FALSE then pattern is aregular expression. If fixed=TRUE then pattern is a text string. Returns matching indices.
grep("A", c("b","A","c"), fixed=TRUE) returns 2
sub(pattern,replacement, x, ignore.case =FALSE, fixed=FALSE)Find pattern in x and replace with replacement text. If fixed=FALSE then pattern is a regular expression.If fixed = T then pattern is a text string.
sub("\\s",".","Hello There") returns "Hello.There"
strsplit(x, split)Split the elements of character vector x at split.
strsplit("abc", "") returns 3 element vector "a","b","c"
paste(..., sep="")Concatenate strings after using sep string to seperate them.
paste("x",1:3,sep="") returns c("x1","x2" "x3")
paste("x",1:3,sep="M") returns c("xM1","xM2" "xM3")
paste("Today is", date())
toupper(x)Uppercase
tolower(x)Lowercase

STATISTICAL PROBABILITY FUNCTIONS

The following table describes functions related to probaility distributions. For random number generators below, you can use set.seed(1234) or some other integer to create reproducible pseudo-random numbers.
FunctionDescription
dnorm(x)normal density function (by default m=0 sd=1)
# plot standard normal curve
x <- pretty(c(-3,3), 30)
y <- dnorm(x)
plot(x, y, type='l', xlab="Normal Deviate", ylab="Density", yaxs="i")
pnorm(q)cumulative normal probability for q
(area under the normal curve to the right of q)
pnorm(1.96) is 0.975
qnorm(p)normal quantile.
value at the p percentile of normal distribution
qnorm(.9) is 1.28 # 90th percentile
rnorm(n, m=0,sd=1)n random normal deviates with mean m
and standard deviation sd.
#50 random normal variates with mean=50, sd=10
x <- rnorm(50, m=50, sd=10)
dbinom(x, size, prob)
pbinom(
q, size, prob)
qbinom(
p, size, prob)
rbinom(
n, size, prob)
binomial distribution where size is the sample size
and prob is the probability of a heads (pi)
# prob of 0 to 5 heads of fair coin out of 10 flips
dbinom(0:5, 10, .5)
# prob of 5 or less heads of fair coin out of 10 flips
pbinom(5, 10, .5)
dpois(x, lamda)
ppois(
q, lamda)
qpois(
p, lamda)
rpois(
n, lamda)
poisson distribution with m=std=lamda
#probability of 0,1, or 2 events with lamda=4
dpois(0:2, 4)
# probability of at least 3 events with lamda=4
1- ppois(2,4)
dunif(x, min=0, max=1)
punif(
q, min=0, max=1)
qunif(
p, min=0, max=1)
runif(
n, min=0, max=1)
uniform distribution, follows the same pattern
as the normal distribution above.
#10 uniform random variates
x <- runif(10)

OTHER STATISTICAL FUNCTIONS

Other useful statistical functions are provided in the following table. Each has the option na.rm to strip missing values before calculations. Otherwise the presence of missing values will lead to a missing result. Object can be a numeric vector or dataframe.
FunctionDescription
mean(x, trim=0,
na.rm=
FALSE)
mean of object x
# trimmed mean, removing any missing values and
# 5 percent of highest and lowest scores
mx <- mean(x,trim=.05,na.rm=TRUE)
sd(x)standard deviation of object(x). also look at var(x) for variance and mad(x) for median absolute deviation.
median(x)median
quantile(x,probs)quantiles where x is the numeric vector whose quantiles are desired and probs is a numeric vector with probabilities in [0,1].
# 30th and 84th percentiles of x
y <- quantile(x, c(.3,.84))
range(x)range
sum(x)sum
diff(x, lag=1)lagged differences, with lag indicating which lag to use
min(x)minimum
max(x)maximum
scale(x, center=TRUE, scale=TRUE)column center or standardize a matrix.

OTHER USEFUL FUNCTIONS

FunctionDescription
seq(from , to, by)generate a sequence
indices <- seq(1,10,2)
#indices is c(1, 3, 5, 7, 9)
rep(x, ntimes)repeat x n times
y <- rep(1:3, 2)
# y is c(1, 2, 3, 1, 2, 3)
cut(x, n)divide continuous variable in factor with n levels
y <- cut(x, 5)
Note that while the examples on this page apply functions to individual variables, many can be applied to vectors and matrices as well.

Thursday, October 13, 2011

RApache Configuration

In the last post we installed Rapache, but didn't get to configuring it.  Let's now create the "rapache.conf" file and some "Hello World" examples to check that Rapache works.

Configuration

As was the case for PHP and Python, we create a file in the "/etc/httpd/conf.d" directory with configuration information.  We will name this "rapache.conf" and start out with the following text:


LoadModule R_module /etc/httpd/modules/mod_R.so

ROutputErrors

<Location /RApacheInfo>
  SetHandler r-info
</Location>

<Directory /var/www/html/rscripts>
  SetHandler r-script
  RHandler sys.source
</Directory>

<Directory /var/www/html/brew>
  SetHandler r-script
  RHandler brew::brew
</Directory>



The "LibModule" statement tells Apache to load the "mod_R.so" shared library and associate it with the "R_module" set of directives.

The "ROutputErrors" statement indicates that R errors should be displayed in the brower.

The "Location" statement creates a location "RApacheInfo" that displays information about the running rapache module. We can test that rapache has loaded and is running correctly by browsing to the link:


http://localhost/RApacheInfo


The first "Directory" statement indicates that all files in the "rscripts" subdirectory will be processed by the "sys.source()" function. This will execute the file as an R script.

The second "Directory" statement indicates that all files in the "brew" subdirectory will be processed by the "brew" function that is in the "brew" package. This function takes a file containing a mix of HTML and R code, executes the R code, and places the results within the HTML that is returned. This is analogous to the mixture of HTML and code in PHP and PSP.

Hello World: R Script

We can test the "R Script" handling with some simple code that generates HTML. This code also uses the "setContentType" function to indicate that the result should be treated as HTML, and finishes with the "DONE" statement indicating the script has finished without error.


setContentType("text/html")
cat("<HTML><BODY><H1>")
cat("Hello from R!")
cat("</H1></BODY></HTML>")
DONE



If we save this to the file "test.R" in "/var/www/html/rscripts" we will see "Hello from R!" displayed in the Header 1 font when we browse to:


http://localhost/rscripts/test.R


Hello World: Brew

Instead of writing out all of the HTML directly with "cat()" commands, we can create an "rhtml" file containing a mix of R and HTML. This then gets processed by the "brew" function to create the HTML response.

As an example, we create the file "test.rhtml" in "/var/www/html/brew" containing:


<HTML>
<BODY>
<H1>
<% cat("Hello from Brew!") %>
</H1>
</BODY>
</HTML>



Browsing to "http://localhost/brew/test.rhtml" will display "Hello from Brew!" in the Header 1 font.

Beyond Hello

Rapache provides rich capabilities for accessing all of the information in the HTTP request from within R, and for setting information as part of the HTTP response.

It also provides ways to pass information other than HTML back as the response, and can even support the uploading of files to the server as part of the client's request.

This is discussed on the Rapache manual and displayed by the examples available from the Rapache web site.

Installing R Language

    * R built for use as a shared library
    * rapache to connect R with Apache
    * The "brew" package for processing HTML files with embedded R code
    * Other packages we want to be available from R

Installing Dependencies

In order for Apache to load R, the R application needs to be built as a shared library.  As we are building R from the source, it's convenient to make sure we have installed other C libraries commonly needed by R first.

Recall that in the CentOS machine we configured there is a user "r-user" with password "r-passwd".  The system password is "r-lamp".  Start up CentOS and log in as "r-user".

Open a terminal and use the "su" command to gain administrative rights.  Then use "yum" to install the following packages:



yum install gcc-gfortran
yum install gcc-c++
yum install readline-devel
yum install libpng-devel libX11-devel libXt-devel
yum install texinfo-tex
yum install tetex-dvips
yum install docbook-utils-pdf
yum install cairo-devel
yum install java-1.6.0-openjdk-devel
yum install libxml2-devel


It isn't strictly required to install all of these.  For example, the "openjdk" libraries are only needed if the "rJava" package is going to be used.  However, it's much easier to install them all now than to rebuild R later when the desire to use "rJava" occurs.

Installing R

The first step is to retrieve the source "tar.gz" file from CRAN.  The source for the latest release is available from the main page of the CRAN web site, such as:

http://cran.r-project.org/src/base/R-2/R-2.10.1.tar.gz

Use Firefox to download this file, and move it to the home directory for "r-user".

At this point we need to follow the R installation instructions carefully.  Two important points:

    * In order for the files to be readable by others, we need to set the appropriate default permissions for newly created files.  For example, set "umask 022".
    * When configuring the R build, include the flag "--enable-R-shlib".

The following commands will unpack the files and build R 2.10.1, which is the most recent version when this was written:



umask 022
tar xf R-2.10.1.tar.gz
cd R-2.10.1
./configure --enable-R-shlib
make


For a quick check on whether R built correctly:



make check


When you are happy with the build, install R with:



make install


Installing R Packages

We will go ahead and install various packages that are likely to be of use with web applications.  It is likely that you will want to disallow installation of packages by R scripts run from Apache for security reasons, so the required packages would be installed in advance.

To install the packages, first use "cd" to change back to the home directory of "r-user" then start R with "R".  Package installation will possibly fail if you start "R" from within the directory where we were running the "make" command.

Use the "install.packages()" function to install the packages, such as:



install.packages(c("brew", "XML", "rjson", "RMySQL", "RJDBC", "rJava","Cairo", "Hmisc"))


The only package that's required for use with "rapache" is "brew".

Installing Rapache

The procedure for downloading, building, and installing Rapache is similar to that for R.  The main detail is you need to include "--with-apache2-apxs=/usr/sbin/apxs" when doing the configuration.

Download the "tar.gz" from the rapache web site:

http://rapache.net/files/rapache-1.1.9.tar.gz

Move the file to the home directory for "r-user" and run the following commands:



tar xf rapache-1.1.9.tar.gz
cd rapache-1.1.0
./configure --with-apache2-apxs=/usr/sbin/apxs
make install


Rapache is now installed.

Configuring Apache

The next step is configuring Apache HTTPD to load the R module.

Create a file "rapache.conf" in "/etc/httpd/conf.d" with this basic configuration information:



LoadModule R_module /etc/httpd/modules/mod_R.so

ROutputErrors

<Location /RApacheInfo>
  SetHandler r-info
</Location>


LoadModule tells Apache to load rapache.  ROutputErrors tells it to direct error messages from the R engine to the browser rather than just putting them in a log file.  SetHandler maps the "RApacheInfo" location to an action returning information about the rapache configuration.

To test this out, browse to "http://localhost/RApacheInfo".  Information about rapache should be displayed.

At this point we have rapache working, but Apache is not yet configured to process "R" or "RHTML" files.  That configuration and example test scripts will be covered in a later post.  If you are anxious to get that configuration in place, see the rapache manual for details.

Monday, April 11, 2011

Generating and using Schema files :: Schema management and migrations :: Core Console Applications :: The Manual :: 1.2 Collection

Generating and using Schema files

A generated schema file allows you to easily transport a database agnostic schema. You can generate a schema file of your database using:
$ cake schema generate
This will generate a schema.php file in you app/config/sql directory.
The schema shell will only process tables for which there are models defined. To force the schema shell to process all the tables, you must add the -f option in the command line.

To later rebuild the database schema from your previously made schema.php file run:
$ cake schema run create
This will drop and create the tables based on the contents of the schema.php.
Schema files can also be used to generate sql dump files. To generate a sql file containing the CREATE TABLE statements, run:

$ cake schema dump filename.sql

Where filename.sql is the desired filename for the sql dump. If you omit filename.sql the sql dump will be output to the console but not written to a file.