Showing posts with label Interactive Digital Primary Education Development.. Show all posts
Showing posts with label Interactive Digital Primary Education Development.. Show all posts

Sunday, April 8, 2012

Save Space and Bunk Up! Bunk Beds in Real Rooms

Save Space and Bunk Up! Bunk Beds in Real Rooms:
"Use the height" is a frequent refrain we hear in reference to small spaces. This is especially useful if you have tall ceilings, and seems like an obvious enough suggestion. What is somewhat surprising in this roundup of bunk beds is how varied they are. These are not just your standard sibling bedroom fare.
More


Read More...

Best Kids Parties: First Fiesta My Party

Best Kids Parties: First Fiesta My Party:
Name: Olivia
Location: Buenos Aires, Argentina
For my daughter Olivia's first birthday I planned about two months ahead since I was going for something special and that reflected Olivia's amazing smile and all the joy she's brought into our lives. I wanted to do something playful and modern so "Olivia's First Fiesta" felt like the right theme. More


Read More...

Microsoft's Patch Tuesday will address exploits in Office 2010, IE9

Microsoft's Patch Tuesday will address exploits in Office 2010, IE9: Four of the six security bulletins Microsoft will release on next week's Patch Tuesday are rated "critical" and will address vulnerabilities in everything from Windows 7 and Office 2010 to the .NET framework and Internet Explorer 9.

Government IT strains under BYOD challenge

Government IT strains under BYOD challenge: IT executives with federal and state governments are struggling to sort out mobile strategies for smartphones and tablets that would be used by employees at work.

Getting New Value Out of Social Media

Getting New Value Out of Social Media: Beachbody CIO Steve Winshel wants more out of his company's social media offerings. How can he prove their worth?

Google now providing business analytics for Maps

Google now providing business analytics for Maps: If you've ever wondered if the Google Map of your business location you've posted on your website is actually effective, now you'll get to find out.

Speaking at Percona Live MySQL conference

Speaking at Percona Live MySQL conference:
Suitcase packed? Check!

Laptop? Check!

Presentation? Check!

I’m ready for my departure to San Francisco tomorrow morning!
I already mentioned before that I will be a speaker at the MySQL conference, but I think the session has moved since. It is now scheduled Thursday between 1:00 and 1:50 in ballrooom E. Be there if you want to know more about what Spil Games is doing!
I also determined what the most interesting talks are going to be for me and here are some of the highlights:

One to Many: The Story of Sharding at Box (Wed 1:00 – 1:50pm)

Sounds very interesting to see how different their story is from the one at Spil Games.
The Etsy Shard Architecture: Starts with S and Ends With Hard (Wed 2:00 – 2:50)

Same as above but then with the difference that, from the description, it seems they are implementing almost the same solution as we are. :D
Scripting MySQL with Lua and libdrizzle inside Nginx (Wed 3:30 – 16:20)

Very interesting thought of combining Nginx with Lua and a database connection through Libdrizzle. It seems you can easily implement lightweight services this way. So definitely a reccomended session!
Percona XtraDB Cluster: New HA solution (Thu 11:00 – 11:50)

Percona XtraDB Cluster came to me as a complete surprise earlier this year. I’ve been playing around with it a little bit and now that it has gone GA last week I’m even more anxious to attend this session. I think it could be a good candidate to become one of the building blocks for Spil Games in the future.
Common Schema: a framework for MySQL server administration (Thu 2:00 – 2:50)

I haven’t done much with Common Schema so far and it is already available on our platform so I think it would be a good idea to attend this session and get more practical insights.
So I’m off to SF in about 19 hours. If you are also attending the conference: see you there!

Tagged: MySQL Conference & Expo
PlanetMySQL Voting:
Vote UP /
Vote DOWN

Shinguz: MySQL and Galera Load Balancer (GLB)

Shinguz: MySQL and Galera Load Balancer (GLB):
When you install a Galera Cluster for MySQL for High Availability (HA) it is not enough to install the Database Cluster to achieve this goal. You also have to make the application aware of this HA functionality. This is typically done with some kind of load balancing mechanism between the database and the application.
We have several possibilities how to make such a load balancing possible:

  • We build such a load balancing mechanism directly into the application.

  • When we use Java or PHP we can use the fail-over functionality of the connectors (Connector/J, mysqlnd-ms).

  • If we cannot touch the application we can put a load balancing mechanism between the application and the database. This can be done with:




Building the Galera Load Balancer


As an example we look at the Galera Load Balancer (GLB). The documentation about it you can find in the README file.
It can be built as follows:
wget http://www.codership.com/files/glb/glb-0.7.4.tar.gz
tar xf glb-0.7.4.tar.gz
cd glb-0.7.4
./configure
make
make install


Starting the Galera Load Balancer


The Galera Load Balancer will be started as follows:
./glbd --daemon --threads 6 --control 127.0.0.1:4444 127.0.0.1:3306 \
192.168.56.101:3306:1 192.168.56.102:3306:1 192.168.56.103:3306:1
Incoming address: 127.0.0.1:3306 , control FIFO: /tmp/glbd.fifo
Control address: 127.0.0.1:4444
Number of threads: 6, source tracking: OFF, verbose: OFF, daemon: YES
Destinations: 3
0: 192.168.56.101:3306 , w: 1.000
1: 192.168.56.102:3306 , w: 1.000
2: 192.168.56.103:3306 , w: 1.000


Querying the Galera Load Balancer


It can be queried as follows:
echo getinfo | nc -q 1 127.0.0.1 4444
Router:
----------------------------------------------------
Address : weight usage conns
192.168.56.101:3306 : 1.000 0.667 2
192.168.56.102:3306 : 1.000 0.500 1
192.168.56.103:3306 : 1.000 0.500 1
----------------------------------------------------
Destinations: 3, total connections: 4

and
echo getstats | nc -q 1 127.0.0.1 4444
in: 37349 out: 52598 recv: 89947 / 1989 send: 89947 / 1768 conns: 225 / 4
poll: 1989 / 0 / 1989 elapsed: 76.59987


Draining nodes with Galera Load Balancer


Let's assume, we want to take out node 192.168.56.101 from the Load Balancer for maintenance purposes, this can be done as follows:
echo 192.168.56.101:3306:0 | nc -q 1 127.0.0.1 4444
echo getinfo | nc -q 1 127.0.0.1 4444
Router:
----------------------------------------------------
Address : weight usage conns
192.168.56.101:3306 : 0.000 1.000 0
192.168.56.102:3306 : 1.000 0.667 2
192.168.56.103:3306 : 1.000 0.667 2
----------------------------------------------------
Destinations: 3, total connections: 4


Removing and adding nodes from Galera Load Balancer


If you want to shrink or grow your database cluster, removing and adding nodes works as follows:
echo 192.168.56.103:3306:-1 | nc -q 1 127.0.0.1 4444

echo 192.168.56.103:3306:2 | nc -q 1 127.0.0.1 4444

And now have fun playing around with your Galera Load Balancer...

PlanetMySQL Voting:
Vote UP /
Vote DOWN

High Availability Deep Dive tutorial at PLMCE

High Availability Deep Dive tutorial at PLMCE:
(a slightly modify rebroadcast of Florian’s post)
If you are interested by High availability solution with MySQL, Florian Haas from and myself myself will be co-presenting next Tuesday a tutorial on the topic. It is never too late to register!
For the ones who are already registered, here’s advance information which you will find useful.
As our tutorial is going to be highly interactive, every attendee will have the opportunity to follow along with Florian and me as we walk you through several deployment scenarios for Pacemaker MySQL high availability. We’re coming with pre-installed virtual machine images for you to use.
Florian took care of the Libvirt/KVM (or Libvirt/Qemu) and VMware images for you while I has prepared virtual appliances for VirtualBox. The download links are here:
VirtualBox virtual appliances (tarball): http://ubuntuone.com/01mJtfGDc2QbxB9eaOqcWc

Libvirt and VMware images and configuration files (bzipped tarball): http://ubuntuone.com/3nikxumH483slq8rfP73iZ

If one of those links produces a 404 for you, then that means it isn’t fully synced yet, and you should just come back in an our or two. Those images are literally hot off the presses and just uploading.
Don’t worry about actually setting them up just yet; you’ll have time to do so at the start of the tutorial. Those of you who download ahead of time – it would be a wonderful move if you could copy your downloads onto a USB thumbdrive and share with co-attendees.
Our tutorial starts on Tuesday at 9:30 in Ballroom H; if you show up early then that will be no problem. At least one of us should be there by 8:45 at the latest. See you there!

PlanetMySQL Voting:
Vote UP /
Vote DOWN

Optimizing MySQL performance with accurate keys

Optimizing MySQL performance with accurate keys:
MySQL performance is largely defined by keys and how efficiently queries can use them. As you scale, at certain point it isn’t enough anymore to just have any indexes and still get a good performance in return. You have to really figure them out and allow your queries to do less work, as little work as possible.
The approach presented in this article can sometimes help designing such good, efficient indexes. As a consultant, I have to rely on it myself from time to time, having to optimize a query that works in a database I know nothing about.

Let’s assume there is an application, which collects user activity in various places. The application uses a poorly indexed database, so there are plenty of examples to choose from. Our example query performs a full table scan, which means it reads all rows from the table it uses. It is also among the most popular statements executed by application.
mysql> EXPLAIN SELECT * FROM `checkins` WHERE user_id = 1410 AND checkin_source = 3 AND checkin_type IN (3,5)\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: checkins
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 1039425
Extra: Using where

A full table scan is indicated by type field, which simply says ALL. Another relevant information is the estimation of how many rows the query will have to read. MySQL thinks it may be 1039425, but in reality, with InnoDB tables, this number is usually be a bit skewed. It should still give the idea of the magnitude of the effort even without the fine accuracy. It is clear that the query needs an index to become more efficient, but what index exactly?
It is typically expected from a key to offer high cardinality, or in other words, to contain many distinct values. It allows an index lookup to hit fewer, more relevant rows. Often even only by looking at a query, it may be easy to conclude, which columns have good cardinality and which don’t. The table from our example query holds information on users activity, so there will likely be a good mix of many different values in user_id column. But can there be equally many sources where user check-ins originate from? A reasonably good guess could be that the options are limited to a web page, a few named social networks, a mobile application and perhaps some more. In other words, not a lot.
This can always be verified:
mysql> SELECT COUNT(1) FROM `checkins` WHERE user_id = 1410;
+----------+
| COUNT(1) |
+----------+
| 6360 |
+----------+

mysql> SELECT COUNT(1) FROM `checkins` WHERE checkin_source = 3;
+----------+
| COUNT(1) |
+----------+
| 108623 |
+----------+

It becomes evident that user_id is a better candidate for indexing than checkin_source as it finds less rows. A query executing against a key on the former column would match only 6360 at first, while one executing against a key on the latter would have to start with 108623 rows. Why start? Because filtering happens in two stages. If MySQL has an index that can be applied, it uses it to find matches, but only using the columns that exist in both WHERE clause and in the index (with some limitations too). Every matching row is then read in full length and any remaining conditions are applied. Starting with one hundred thousand rather than six thousand something rows would push nearly twenty times more of them for post-filtering in the second step. Looking at a bigger picture, it is not just twenty times more work for CPU, but also possibility many more I/O requests.
A cross-check on cardinality could also be done:
mysql> SELECT COUNT(DISTINCT user_id) AS cardinality FROM `checkins`;
+-------------+
| cardinality |
+-------------+
| 26360 |
+-------------+

mysql> SELECT COUNT(DISTINCT checkin_source) AS cardinality FROM `checkins`;
+-------------+
| cardinality |
+-------------+
| 18 |
+-------------+

There are over twenty six thousand unique user values in this table, while only eighteen different check-in sources, so user_id column has much higher cardinality.
But is adding an index on user_id really the best of what can be done? A new key could be created on only one of the columns referenced in the WHERE clause. Or it could be created on a combination of these columns – it would be so called composite index.
Why not try examining the data even further? How many rows does the original query actually match?
mysql> SELECT COUNT(1) FROM `checkins` WHERE user_id = 1410 AND checkin_source = 3 AND checkin_type IN (3,5);
+----------+
| COUNT(1) |
+----------+
| 832 |
+----------+

That is even better than 6360 matched by the user alone. It means that using all three columns together can more significantly improve selectivity, i.e. reduce number of rows matched by a set of conditions. If this is somewhat consistent behavior, what can be verified through query statistics from MySQL slow log, the information can be used to improve the new index design. A composite key on (user_id, checkin_source, checkin_type) seems good candidate now, better than user_id alone, but now another question emerges… could it be shorter?
Indexes shouldn’t be needlessly long, because they use disk space and memory. They also require a lot of maintenance work from database to keep them up-to-date, so if something does not really, to a measurable extent, benefit MySQL performance elsewhere, should not be part of any index.
What if only two out of the three columns where used:
mysql> SELECT COUNT(1) FROM `checkins` WHERE user_id = 1410 AND checkin_source = 3;
+----------+
| COUNT(1) |
+----------+
| 869 |
+----------+

Thirty rows more is not going to turn into a measurable difference in most cases, so it should be okay to use a shorter index covering just (user_id, checking_source).

Conclusion

We considered four different keys for optimizing performance of the example query:

  1. (user_id)

  2. (checkin_status)

  3. (user_id, checkin_status, checkin_type)

  4. (user_id, checkin_status)


The last one offered the best factor of efficiency to cost being nine times more efficient than index number one and slightly less expensive than comparable index number three. Therefore we found the accurate index, which should help MySQL performance the most considering this particular query.

PlanetMySQL Voting:
Vote UP /
Vote DOWN

Announcing MariaDB 5.1.62 and 5.2.12

Announcing MariaDB 5.1.62 and 5.2.12:
We are pleased to announce the immediate availability of MariaDB 5.1.62 and MariaDB 5.2.12. Both of these stable (GA) releases incorporate MySQL 5.1.62 and several bug fixes.
Most importantly, MariaDB 5.1.62 and 5.2.12 include a fix for a bug that under certain rare circumstances allowed a user to connect with an invalid password. This is a serious security issue. We recommend upgrading from older versions as soon as possible.
Please see the What is MariaDB 5.1 page for an overview of MariaDB 5.1, and the What is MariaDB 5.2 page for an overview of MariaDB 5.2.
Sources, binaries, and package downloads are available from our network of MariaDB mirrors. Debian and Ubuntu packages are available from our mirrored apt repositories. We have a sources.list generator for creating sources.list entries.

PlanetMySQL Voting:
Vote UP /
Vote DOWN

MySQL DELETE Join example

MySQL DELETE Join example:
A very useful helper in your join toolbox can be a delete join. Even though it’s not a special join type but a join used within DELETE statements, it’s still worth mentioning. However, from time to time when I want to make use of delete joins  on my own, I somehow managed it to forgot the syntax and have to look it up somewhere. Therefor, here is a description as well as an example.
Take care: A delete join is a very powerful weapon. And with great power comes great responsibility! I recommend to develop the delete join on a development database. At least, make sure you have a working an recent backup before trying to delete things. A delete statement that uses joins makes it easy to shot yourself in the foot. And if you do, it probably blows away your hole leg.


DELETE join syntax


When you delete data in MySQL using DELETE statements you are able to define a condition which specifies which rows should be removed. Take a look at the following database model:
DELETE join




In our example the table files keeps track of filenames. Now, when a user wants to delete a file we first have to delete the file itself. Afterwards we can remove the record from our database. But since it could take a little while until we’re done and don’t want our users to wait, we are simply adding a record to the table delete_queue and wait for a background process to clean up. This isn’t a far fetched scenario, especially in the web environment.
Our background process could use the following statement that uses inner join to add the WHERE condition:
DELETE f FROM files f
INNER JOIN delete_queue USING (file_id)


You can add additional join clauses to your statement like in SELECT statements for example. Adding a WHERE-clause is possible as well:
DELETE f FROM files f
INNER JOIN delete_queue USING (file_id)
WHERE file_id > 100



More Information


For more information about MySQL joins please also see:



PlanetMySQL Voting:
Vote UP /
Vote DOWN

MySQL now has two user conferences (*)

MySQL now has two user conferences (*):
PC World has written a post with this title(*) about the upcoming MySQL Connect conference and references the Percona Live conference and an official Percona comment. As this is not syndicated in Planet MySQL I encourage you to read the full article.
This is the MySQL conference to get technical presentations by the many great Oracle/MySQL technical staff who will not be in attendance at Percona Live. There will also be a strong community presence in speaking at Oracle Connect in September. While Oracle was organizing a dedicated MySQL event in April for the community with all vendors including Percona to replace the conference dropped by long term partner O’Reilly (kudos for many years of great events), Percona decided to go at it without including Oracle, the owners and developers of MySQL. The statement quoted in the PC World article regarding “lack of momentum around the [annual community] event” is clearly inaccurate and not a true representation of actual events.
It is difficult to keep up with all the community events Oracle is now running including multiple OTN MySQL Developer days per month across the US and Europe. I will be speaking at the upcoming OTN NY event in April, the Rocky Mountain Training Day in May, and hopefully the MySQL Innovation day in June. Get the full list at Upcoming MySQL Events.
Indeed MySQL content and presentations have also been represented at Oracle Open World for a number of years. 2011 was a very large turnout and many MySQL presentations. As a senior consultant for MySQL Inc I manned a MySQL booth at OOW exhibition hall back in 2007, prior to both Sun and Oracle acquisitions.

PlanetMySQL Voting:
Vote UP /
Vote DOWN

Mastering MySQL Indexing

Mastering MySQL Indexing: Indexes are tricky things. In my experience, indexes are added whenever SQL queries are too slow. This makes sense. However, sometimes these indexes were added without being thought through enough (I am guilty of this). Sometimes they were thought through, but the table itself now has so many indexes that the optimizer doesn't know which one to choose from.

The overhead of indexes greatly effects tables that need to be written to or altered often (even indexes on NoSQL database greatly effect writes).

Over indexed tables inflate the database size dramatically which adds to people's concerns that the database becomes unwieldy.





Read more »



PlanetMySQL Voting:
Vote UP /
Vote DOWN

Tick-tock, tick-tock … 5 days to go until MySQL Week kicks off!

Tick-tock, tick-tock … 5 days to go until MySQL Week kicks off!:
Great speaker line up at SkySQL & MariaDB: Solutions Day for the MySQL Database and Percona Live MySQL Conference & Expo
If you haven’t yet registeredfor next week’sSkySQL & MariaDB: Solutions Day for the MySQL Database, do it today so you don’t miss any of these important discussions about MariaDB, MySQL & related technologies:


  • Opening keynote from Monty Widenius and David Axmark


  • SkySQL, MySQL, MariaDB & the Cloud, withUlf Sandberg, Kaj Arnö, and Ivan Zoratti of SkySQL


  • Automating master failover and non-stop master switch with MHA for MySQL, withYoshinori Matsunobu from Facebook


  • Creating Data Warehousing Schemas - Using a Real-World Example,with Sheeri K. Cabral of Mozilla Foundation


  • Migrating to ScaleDB - From A Single Database Instance To A Cluster Of Integrated Database And Storage Nodes On The Cloud, withMoshe Shadmon of ScaleDB


  • The “MySQL DBA in a box”: MONyog Tutorial & Use Cases, withRohit Nadhani of WebYog


  • Complex Multi-Master Solutions Made Easy with Tungsten, withRobert Hodges & Giuseppe Maxia of Continuent


  • De-Mystifying Columnar Databases, withJune Tong of InfiniDB


  • Introduction to Sphinx for MySQL/MariaDB Users,with Andrew Aksyonoff of Sphinx


  • Using MySQL as a NoSQL Datastore - New Features in MySQL Cluster 7.2 GA,with Johan Andersson of Severalnines


  • Special presentation by Dan Berry of Constant Contact


  • Surprise closing keynote


SkySQL & MariaDB: Solutions Day for the MySQL Database was created specifically for MySQL Database Administrators, Application Developers building solutions on MySQL, Development/Engineering Management and IT Architects.
Register Now!
And don’t miss other great discussions next week at Percona Live MySQL Conference & Expo led by representatives from SkySQL and our partners:
Tuesday, April 10

Wednesday, April 11

See you next week in Santa Clara!

PlanetMySQL Voting:
Vote UP /
Vote DOWN

Generalised entropy

Generalised entropy: Introduction
The entropy of a probability distribution can be seen as a measure of its uncertainty or a measure of the diversity of samples taken from it. Over the years I've talked lots about how probability theory gives rise to a monad. This suggests the possibility that maybe the notion of entropy can be generalised to monads other than probability. So here goes...

> {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, GeneralizedNewtypeDeriving #-}
> {-# LANGUAGE FunctionalDependencies, TypeSynonymInstances #-}

> import Control.Monad
> import Control.Monad.Writer hiding (lift)


Shannon entropy
I've talked in the past about how there is some trickiness with defining the probability monad in Haskell because a good implementation requires use of the Eq typeclass, and hence restricted monads. Restricted monads are possible through a bunch of methods, but this time I don't want them.

It's common to represent probability distributions on finite sets as lists of pairs where each pair (p, x) means x has a probability p. But I'm going to allow lists without the restriction that each x appears once and make my code work with these generalised distributions. When I compute the entropy, say, it will only be the usual entropy in the case that each x in the list is unique.

So here's our type and some instances for it:

> data P a = P [(a, Float)] deriving Show

> instance Functor P where
> fmap f (P xs) = P [(f a, p) | (a, p) <- xs]

> instance Monad P where
> return x = P [(x, 1)]
> P xss >>= f = P [(y, p*q) | (pxs, p) <- xss, let P ys = f pxs, (y, q) <- ys]

We can easily compute the expected value of a distribution, and its entropy, like this:

> expectation0 (P xs) = sum [x*p | (x, p) <- xs]
> entropy0 (P xs) = -sum [if p==0 then 0 else p*log p/log 2.0 | (_, p) <- xs]

An important property of entropy is known as the grouping property which can be illustrated through an example tree like this:




The entropy for the probability distribution of the final leaves is the sum of two components: (1) the entropy of the branch at the root of the tree and (2) the expected entropy of the subtrees. Here's some corresponding code. First simple bernoulli trials:

> bernoulli p a b = P [(a, p), (b, 1-p)]

Now the branch at the root of the tree:

> root = bernoulli 0.3 False True

We can compute the entropy for the distrbution on the leaves:

> test1 = entropy0 $ do
> x <- root
> if x
> then bernoulli 0.2 3 4
> else bernoulli 0.4 5 6

Or the sum of the root entropy and the expected subtree entropy:

> test2 = entropy0 root + (expectation0 $ do
> x <- root
> if x
> then return $ entropy0 (bernoulli 0.2 3 4)
> else return $ entropy0 (bernoulli 0.4 5 6))

You can confirm for yourself that test1 == test2.

We can rewrite that a little. We're drawing True or False from root only to decide which distribution to use at the next stage. But we may as will pick the distribution itself at random. So define:

> dist = bernoulli 0.3 (bernoulli 0.4 5 6) (bernoulli 0.2 3 4)

And now we expect the equality of test3 and test4:

> test3 = entropy0 $ do
> x <- dist
> x

> test4 = entropy0 dist + (expectation0 $ do
> x <- dist
> return $ entropy0 x)

There's a more elegant way of writing this. Define:

> left0 dist = entropy0 (join dist)
> right0 dist = entropy0 dist+expectation0 (fmap entropy0 dist)

Now we expect left0 dist and right0 dist to always be equal. We've almost generalised to something that makes sense in the context of monads other than probability.

The algebra of a monad
Here are a couple of important properties of expectation0:

1. expectation0 (return d) = d
2. expectation0 (join d) = expectation0 (fmap expectation d)

In English: the expectation of certainty is just the certain value, and the expectation of an expectation is just the expectation. But these rules are precisely the conditions that define an -algebra, where is a monad.

So let's define a type class:

> class Algebra m a | m -> a where
> expectation :: m a -> a

We'll assume that when m is a monad, any instance satisfies the two laws above. Here's the instance for probability:

> instance Algebra P Float where
> expectation (P xs) = sum [x*p | (x, p) <- xs]

In keeping with the notion that entropy measure diversity let's also define:

> class Diverse m r | m -> r where
> entropy :: m x -> r

with the instance:

> instance Diverse P Float where
> entropy (P xs) = -sum [if p==0 then 0 else p*log p/log 2.0 | (_, p) <- xs]

It's not clear what laws we need but for now we'll assume a generalised entropy satisfies left dist == right dist :

> left dist = entropy (join dist)
> right dist = entropy dist+expectation (fmap entropy dist)

We'll call that the generalised grouping law.

Binary trees
It's not hard to find other structures that satisfy these laws if we cheat and use alternative structures to represent probabilities. For example We can make Tree an instance by assuming Fork represents a 50/50 chance of going one way or another:

> data Tree a = Leaf a | Fork (Tree a) (Tree a) deriving Show

> instance Functor Tree where
> fmap f (Leaf a) = Leaf (f a)
> fmap f (Fork l r) = Fork (fmap f l) (fmap f r)

> instance Monad Tree where
> return x = Leaf x
> Leaf a >>= f = f a
> Fork l r >>= f = Fork (l >>= f) (r >>= f)

> instance Algebra Tree Float where
> expectation (Leaf a) = a
> expectation (Fork l r) = 0.5*expectation l+0.5*expectation r

> instance Diverse Tree Float where
> entropy (Leaf a) = 0
> entropy (Fork l r) = 1+0.5*entropy l+0.5*entropy r

Lists
We could make non-empty lists into an instance by assuming a uniform distribution on the list. But another way to measure the diversity is simply to count the elements. We subtract one so that [x] corresponds to diversity zero. This subtraction gives us a non-trivial instance:

> newtype L a = L [a] deriving (Show, Monad, Functor)

> instance Algebra L Int where
> expectation (L xs) = sum xs

> instance Diverse L Int where
> entropy (L xs) = length xs-1

Tsallis entropy
There are measures of diversity for probability distributions that are distinct from Shannon entropy. An example is Tsallis entropy. At this point I'd like a family of types parametrised by reals but Haskell doesn't support dependent types. So I'll just fix a real number q and we can define:

> q = 2.5

> data T a = T [(a, Float)] deriving Show

> instance Functor T where
> fmap f (T xs) = T [(f a, p) | (a, p) <- xs]

> instance Monad T where
> return x = T [(x, 1)]
> T xss >>= f = T [(y, p*q) | (pxs, p) <- xss, let T ys = f pxs, (y, q) <- ys]

> instance Algebra T Float where
> expectation (T xs) = sum [x*p**q | (x, p) <- xs]

> instance Diverse T Float where
> entropy (T xs) = (1-sum [p**q | (_, p) <- xs])/(q-1)

And again we find our generalised grouping rule for entropy holds.

Operads
This is all derived from Tom Leinster's post last year at the n-category cafe. As I talked about here there's a close relationship between monads and operads. Operads area a bit like container monads where the containers don't contain anything, but just have holes where contents could be placed. This makes operads a better place to work because you don't have the awkward issue I started with: having to disallow lists of value/probability pairs where the same value can appear more than once. Nonetheless, in (unrestricted) Haskell monads you don't have Eq available so you can't actually have definitions of return or >>= that can notice the equality of two elements. If such definitions were possible, the grouping law would no longer work as stated above.

Crossed homomorphisms
The generalised grouping law even makes sense for very different monads. For the Reader monad the law gives the definition of a crossed homomorphism. It's pretty weird seeing a notion from group cohomology emerge like this and I recommend skipping to the final section unless you care about this sort of thing. But if you do, this is related to research I did a long time ago. This is to test that the Schwarzian derivative really does give rise to a crossed homomorphism.

Firstly let me set up some automatic differentiation code:

> data D a = D { re::a, im::a } deriving (Show, Ord, Eq)

> instance Num a => Num (D a) where
> fromInteger n = D (fromInteger n) 0
> D a a'+D b b' = D (a+b) (a'+b')
> D a a'*D b b' = D (a*b) (a*b'+a'*b)
> D a a'-D b b' = D (a-b) (a'-b')

> instance Fractional a => Fractional (D a) where
> fromRational n = D (fromRational n) 0
> D a a'/D b b' = let q = 1/b in D (a*q) ((-a*b'+a'*b)*q*q)

> lift x = D x 0

> d f x = im (f (D x 1))

> raised f = re . f . lift
> raised2 = raised . raised
> raised3 = raised2 . raised

The Cn are the n-times (automatically) differentiable functions. Unfortunately the Endo defined in Data.Monoid acts the wrong way round from what I want so I need a Dual:

> type C1 = Dual (Endo (D Double))
> type C3 = Dual (Endo (D (D (D Double))))
> type C4 = Dual (Endo (D (D (D (D Double)))))

> instance Eq (Endo (D Double))
> instance Ord (Endo (D Double))

A silly Show instance that simply evaluates a function at a number I chose randomly: 1.234.

> instance Show (Endo (D Double)) where
> show (Endo f) = show (f 1.234)

> instance Num C1 where
> fromInteger n = Dual (Endo (\x -> fromInteger n))
> Dual (Endo f)+Dual (Endo g) = Dual (Endo (\x -> f x + g x))
> Dual (Endo f)-Dual (Endo g) = Dual (Endo (\x -> f x - g x))
> Dual (Endo f)*Dual (Endo g) = Dual (Endo (\x -> f x * g x))

> instance Fractional C1 where
> fromRational n = Dual (Endo (\x -> fromRational n))
> Dual (Endo f)/Dual (Endo g) = Dual (Endo (\x -> f x / g x))

> newtype Q a = Q (Writer C4 a) deriving (Monad, Functor)

We can give Q a a geometrical interpretation. The underlying type is a pair (a, C4). If we think of elements of C4 as charts charts on a piece of Riemann surface then for any , an element of (a, C4) represents a local piece of a section of the th tensor power of the canonical bundle. Ie. we can think of it as representing . I'll concentrate on the case which gives quadratic differentials. We can think of an element of ((a, C4), C4) as forms where we're composing two charts. We can collapse down to an ordinary chart by using the chain rule. Here's the code:

> instance Algebra Q C1 where
> expectation (Q ma) = let (Dual (Endo a), Dual (Endo f)) = runWriter ma
> in Dual (Endo (\x -> a (raised3 f x)*(raised2 (d f) x)^2))

Now we can define the Schwarzian derivative:

> schwarzian f x = let f0 = raised3 f x
> f1 = raised2 (d f) x
> f2 = raised (d $ d f) x
> f3 = (d $ d $ d f) x
> in f3/f1-1.5*(f2/f1)^2

And somwehat bizarrely, we now have a generalised entropy:

> instance Diverse Q C1 where
> entropy (Q ma) = let (_, Dual (Endo f)) = runWriter ma
> in Dual (Endo (\x -> schwarzian f x))

This is the construction that gives rise to the Virasoro algebra which plays such an important role in String Theory.

Some tests
And here's a bunch of tests. I'd have used QuickCheck but it won't install for me today...

> test :: (Algebra m t, Diverse m t, Num t, Functor m, Monad m) => m (m x) -> IO ()
> test x = do
> print (left x, right x)

> main = do
> test $ L [L [1, 2, 3], L [2, 3, 4], L [1], L [5], L [2, 7::Int]]
> test $ P [(P [(0, 0.5), (1, 0.5)], 0.5), (P [(2, 0.5), (3::Int, 0.5)], 0.5::Float)]
> test $ T [(T [(0, 0.5), (1, 0.5)], 0.5), (T [(2, 0.5), (3::Int, 0.5)], 0.5::Float)]
> test $ Leaf (Leaf 1 `Fork` Leaf 2) `Fork` Leaf (Leaf 3 `Fork` (Leaf 4 `Fork` Leaf 5))
> test $ (Q (writer
> (Q (writer (Dual (Endo (\x -> x)),
> Dual (Endo (\x -> x^2+1)))),
> Dual (Endo (\x -> (2+x)/(3+x*x))))) :: Q (Q C3))




Four Ways to Improve the Lead-to-Sales Handoff

Four Ways to Improve the Lead-to-Sales Handoff: Improving the lead-to-sales handoff at your company--and setting lead follow-up guidelines--can significantly boost ROI and help close Sales. Learn four invaluable handoff techniques you should be implementing. Read the full article at MarketingProfs


Want Real Business Results From Facebook? Run a Social Campaign

Want Real Business Results From Facebook? Run a Social Campaign: To get real business results from your social media efforts, you need to build a community, engage your audience, and create word-of-mouth. Learn how running a social campaign on Facebook can help you do just that. Read the full article at MarketingProfs

Panasonic unveils LUMIX GF5 camera

Panasonic unveils LUMIX GF5 camera:






Panasonic (http://www.panasonic.com/lumix) has announced a new digital interchangeable lens system camera, the LUMIX DMC-GF5. It will be available in black, white and red later this year in the following kit options:  a body with 14-42mm standard zoom lens will have a suggested retail price of $599; body with 14-42mm power zoom lens will have an SRP of $749.
read more