Thursday, April 7, 2016

Breaking the SQL Barrier Google BigQuery User Defined Functions

Posted by, Thomas Park, Senior Software Engineer, Google BigQuery

Many types of computations can be difficult or impossible to express in SQL. Loops, complex conditionals, and non-trivial string parsing or transformations are all common examples. What can you do when you need to perform these operations but your data lives in a SQL-based Big data tool? Is it possible to retain the convenience and speed of keeping your data in a single system, when portions of your logic are a poor fit for SQL?

Google BigQuery is a fully managed, petabyte-scale data analytics service that uses SQL as its query interface. As part of our latest BigQuery release, we are announcing support for executing user-defined functions (UDFs) over your BigQuery data. This gives you the ability to combine the convenience and accessibility of SQL with the option to use a familiar programming language, JavaScript, when SQL isn’t the right tool for the job.

How does it work?

BigQuery UDFs are similar to map functions in MapReduce. They take one row of input and produce zero or more rows of output, potentially with a different schema.

Below is a simple example that performs URL decoding. Although BigQuery provides a number of built-in functions, it does not have a built-in for decoding URL-encoded strings. However, this functionality is available in JavaScript, so we can extend BigQuery with a simple User-Defined Function to decode this type of data:



function decodeHelper(s) {
try {
return decodeURI(s);
} catch (ex) {
return s;
}
}

// The UDF.
function urlDecode(r, emit) {
emit({title: decodeHelper(r.title),
requests: r.num_requests});
}

BigQuery UDFs are functions with two formal parameters. The first parameter is a variable to which each input row will be bound. The second parameter is an “emitter” function. Each time the emitter is invoked with a JavaScript object, that object will be returned as a row to the query.

In the above example, urlDecode is the UDF that will be invoked from BigQuery. It calls a helper function decodeHelper that uses JavaScript’s built-in decodeURI function to transform URL-encoded data into UTF-8.

Note the use of try / catch in decodeHelper. Data is sometimes dirty! If we encounter an error decoding a particular string for any reason, the helper returns the original, un-decoded string.

To make this function visible to BigQuery, it is necessary to include a registration call in your code that describes the function, including its input columns and output schema, and a name that you’ll use to reference the function in your SQL:



bigquery.defineFunction(
urlDecode, // Name used to call the function from SQL.

[title, num_requests], // Input column names.

// JSON representation of output schema.
[{name: title, type: string},
{name: requests, type: integer}],

urlDecode // The UDF reference.
);

The UDF can then be invoked by the name “urlDecode” in the SQL query, with a source table or subquery as an argument. The following query looks for the most-visited French Wikipedia articles from April 2015 that contain a cédille character (ç) in the title:



SELECT requests, title
FROM
urlDecode(
SELECT
title, sum(requests) AS num_requests
FROM
[fh-bigquery:wikipedia.pagecounts_201504]
WHERE language = fr
GROUP EACH BY title
)
WHERE title LIKE %ç%
ORDER BY requests DESC
LIMIT 100

This query processes data from a 5.6 billion row / 380 Gb dataset and generally runs in less than two minutes. The cost? About $1.37, at the time of this writing.

To use a UDF in a query, it must be described via UserDefinedFunctionResource elements in your JobConfiguration request. UserDefinedFunctionResource elements can either contain inline JavaScript code or pointers to code files stored in Google Cloud Storage.

Under the hood

JavaScript UDFs are executed on instances of Google V8 running on Google servers. Your code runs close to your data in order to minimize added latency.

You don’t have to worry about provisioning hardware or managing pipelines to deal with data import / export. BigQuery automatically scales with the size of the data being queried in order to provide good query performance.

In addition, you only pay for what you use - there is no need to forecast usage or pre-purchase resources.

Developing your function

Interested in developing your JavaScript UDF without running up your BigQuery bill? Here is a simple browser-based widget that allows you to test and debug UDFs.

Note that not all JavaScript functionality supported in the browser is available in BigQuery. For example, anything related to the browser DOM is unsupported, including Window and Document objects, and any functions that require them, such as atob() / btoa().

Tips and tricks

Pre-filter input

In our URL-decoding example, we are passing a subquery as the input to urlDecode rather than the full table. Why?

There are about 5.6 billion rows in [fh-bigquery:wikipedia.pagecounts_201504]. However, one of the query predicates will filter the input data down to the rows where language is “fr” (French) - this is about 262 million rows. If we ran the UDF over the entire table and did the language and cédille filtering in a single WHERE clause, that would cause the JavaScript framework to process over 21 times more rows than it would with the filtered subquery. This equates to a lot of CPU cycles wasted doing unnecessary data conversion and marshalling.

If your input can easily be filtered down before invoking a UDF by using native SQL predicates, doing so will usually lead to a faster (and potentially cheaper) query.

Avoid persistent mutable state

You must not store and access mutable state across UDF execution for different rows. The following contrived example illustrates this error:



// myCode.js
var numRows = 0;

function dontDoThis(r, emit) {
emit(rowCount: ++numRows);
}

// The query.
SELECT max(rowCount) FROM dontDoThis(myTable);

This is a problem because BigQuery will shard your query across multiple nodes, each of which has independent V8 instances and will therefore accumulate separate values for numRows.

Expand select *

You cannot execute SELECT * FROM urlDecode(...) at this time; you must explicitly list the columns being selected from the UDF: select requests, title from urlDecode(...)

For more information about BigQuery User-Defined Functions, see the full feature documentation.

Read More..

Wednesday, April 6, 2016

How to Fix a random reboots on the HTC One M8


Some time ago I described a method to format the /data partition on the HTC One (M7) - How to: Fix a corrupted DATA partition on the HTC One. This method is suitable for more HTC devices (all with EXT4 support) and with the mkfs.ext4 tool you can format system and cache partitions as well. All you need to know is the proper /dev/block/mmcblk0pXY number of the partition you want to format.

However, formatting the partition always means that your data will be gone. On the HTC One M8 I noticed a problem, most likely caused by the wp_mod.ko module (module to disable system R/W protection). When the module is loaded too late and anything ever gets changed before the module is loaded the file-structure of the /data partition might (and probably will) get corrupted. As a result your device will reboot each time youll try to make and change on the /system partition (even if mounted as RW). So removing, copying, moving, re-naming or editing any file on a system partition will result with the following message in the kernel log (last_kmsg.txt):


Formatting the /data partition is not the best idea for some and its not needed in most cases.

Repair Process
  1. Download this mini-sdk package and extract it to c:mini-sdk
  2. Download this fsck.ext4 binary and put it into c:mini-sdk
  3. Connect your device to the PC
  4. Boot your device in recovery mode
  5. Open a command prompt on the PC (cmd.exe), type and confirm each command with ENTER:
  6. cd /d c:mini-sdk
  7. adb push fsck.ext4 /tmp
  8. adb shell
  9. chmod 777 /tmp/fsck.ext4
  10. /tmp/fsck.ext4 -fn /dev/block/mmcblk0p47

This will fix your /data partition and you should see the following output (numbers in the last line will be different in each case):

e2fsck 1.42.9 (28-Dec-2013)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/block/mmcblk0p47: 19050/712704 files (2.7% non-contiguous), 2320338/2850816 blocks


Your /data partition is now fixed and you should no longer experience random reboots problem on your device (assuming that the corrupted /data partition was the source of the problem). Keep in mind that the fsck.ext4 -fn command can be used to check other EXT4 partitions on any device that has EXT4 file-system structure. All you need to know is the partition name or block number.


Do you have any questions or comments? Feel free to share! Also, if you like this article, please use media sharing buttons (Twitter, G+, Facebook) below this post!


For latest news follow Android Revolution HD on popular social platforms:

Read More..

Tuesday, April 5, 2016

Google for Education hits the road


(Cross-posted on the Google for Education Blog.)

Remember back in 2008 when the Google for Education team road-tripped across the US, visiting universities using Google Apps for Education? We hardly do, either, which is why we were itching to get back out on the road. This time in the UK. And we brought along a pop-up classroom instead of a bio-fuel bus.

In four weeks, we visited seven schools in England, Wales and Scotland that are doing inspiring and creative things with education technology. We wanted to hear more about how Google for Education tools are helping them to transform their approach to teaching and learning, and we wanted to provide an opportunity for other educators nearby to hear and learn from them, too.
Our pop-up classroom at Wigan UTC


And we werent disappointed. We heard from Cramlington Learning Village in Newcastle, where Physical Education students have become more engaged by doing their own real-time personalized fitness tracking with Google Sheets on their Chromebooks. That’s what we call healthy competition!

Students of GSCE Physics were getting a last-minute helping hand with their study thanks to revision videos created by the science department hosted on Youtube at The Streetly Academy in Birmingham. “What’s great about them is that we’re used to their style of teaching and their voices – and our teachers know how we learn best,” says Jack Webb, a student of The Streetly Academy.

City Heights E-Act Academy in London also gave media teachers some great ideas, by showing us how their students utilized Google Drive when creating their BBC School Report and giving us a demonstration of their HTML writing abilities.
Students at City Heights E-Act Academy showed off their HTML writing capabilities






We also loved how inquisitive students at the Horsforth Campus of Leeds City College used Google Draw to document and track changes to nearby wetland areas over time, based on their hypothesis about how a nearby motorway is affecting the surrounding ecosystem.
Students at Preston Lodge High School working collaboratively in our pop-up classroom


We toured the world’s first controlled-environment agricultural facility using a Vertical High Density Growing system in an educational institution at Wigan UTC. There, budding food technicians can get hands-on with technology that can help to combat current and future food production issues, working together to track production levels collaboratively with Google Sheets.

In East Lothian, the pipe band at Preston Lodge High School treated us to a roof-lifting performance to start the morning!
The Preston Lodge High School Pipe Band warming up






We heard lots of teacher tips along the way, but our favourite was from Assistant Headteacher David Beesley, who uses boomerang for Gmail to set his emails to send at times he knows his staff are at their desks.
Asst. Headteacher David Beesley sharing his favourite Gmail tips










Students at St. Julians showed us their favourite apps on Google Play
One day Google for Education might pop up—or roll into—a town near you, but in the meantime you can check out a video of our pop-up classroom being built, captured by the impressive media students at St. Julian’s in Newport, Wales.
Read More..

Monday, April 4, 2016

Narvik Kommune brings social services to the Arctic with Google Apps for Work



Editors note: Today we hear from Per Jakobsen, head of IT operations and development at Narvik Kommune, a Norwegian municipality 343 kilometres north of the Arctic circle. Read how Google Apps for Work is being used at Narvik Kommune to make life simpler for staff, so that they can spend less time doing paperwork and more time managing healthcare, childcare, schools, transport and housing services for the people that depend on them.

Norwegians value the human touch in social services. We call this “warm hands,” and we know nothing can replace it. But as a municipality, we need cool efficiency to make sure that our carers, teachers and medics are in the right place at the right time for 20,000 citizens across more than 2,000km².
Photo by Pål Jakobsen

Every day, Narvik Kommune coordinates 1,600 employees across 58 locations — but our old email system was holding us back from doing our best work. An obsolete user interface made it difficult to navigate, spam was a chronic problem, and we depended on expensive consultants for maintenance. Buying 750 Google Apps for Work accounts hasn’t just resolved these issues at a reasonable and predictable price; it’s made Narvik Kommune more efficient, more reliable and more mobile. We worked with Avalon Solutions, a Google Apps Premier Partner in the Nordics, who contributed to the successful migration.

We’ve gained several hours each week now that we use stable and secure Google servers, instead of wasting time servicing a spam filter and antivirus software and troubleshooting email instability. And the minimal training necessary to use Google Apps tools means departments throughout Narvik Kommune are discovering creative and productive ways to use them — all on their own:

  • Working together under tight deadlines in Sheets: Our economy team uses Sheets instead of Excel, so they can update documents simultaneously during hectic periods and avoid the delays and confusion caused by multiple copies when union representatives and others are involved in compiling records.
  • Collecting and sharing information across teams with Sites: HR uses Sites to reach out more effectively through the organisation when collecting and presenting information on large internal procedures.
  • Staying on top of meetings with Calendar: All teams use Calendar on our smartphones to organise meetings (and receive SMS notifications before they start).
  • Digital discussion notes on Docs: All teams use Docs to take notes during discussions, which keeps everyone better aligned and saves time and cost on printing.
  • Building budgets on Drive: Our councilman and managers across the administration used Drive to compile our last annual budget, saving time on a joint task that we would previously handle with fileshare documents that could only be opened and edited by one person at a time.

Most importantly, Google Apps for Work keeps our internal data secure. We have the added peace of mind knowing that our information is protected on one of the most secure infrastructures in the world.

With the flexibility of Google Apps tools, we can prepare for a smooth relocation while the Narvik town hall shuts down for two years of renovation and our core team spreads across three locations instead of one. We’ll use Hangouts on five Chromeboxes to meet and collaborate face-to-face, so we don’t lose that important personal interaction among teams.

We’ve been so impressed by the power of Google Apps, that we’ve extended the advantages of Google Apps tools to local students. We implemented Google Apps for Education accounts for each of the 2,000 pupils at our nine primary and lower secondary schools, and we’re trialling Chromebooks and Classroom. Digitizing public services with Google hasn’t just brought us national attention — it has freed up resources to invest in our future.
Read More..

Saturday, April 2, 2016

Official Google Blog Supercharging Android Google to Acquire Motorola Mobility

Official Google Blog: Supercharging Android: Google to Acquire Motorola Mobility
Read More..

Google brings educators startups and researchers together in North Carolina



(Cross-posted on the Google for Education Blog.)

Editors note: Were going across the U.S. to shine light on the great things schools are doing with technology at the statewide level, with North Carolina up first. North Carolina is a strong Google partner. From the rollout of broadband infrastructure to the adoption of Google for Education, Google for Work and Google Cloud Platform in schools, nonprofits, labs and startups, Google technology is helping to liberate learning, empower employees and give researchers tools that can help solve real world problems.

North Carolina’s Research Triangle has a rich tradition of fostering quality education, research and entrepreneurship – prime areas for investment and innovation. In fact, Google is now laying thousands of miles of state-of-the-art fiber optic cable that will expand internet connectivity in the area. In the spirit of building next-generation technologies, the Google Cloud Platform and Google for Education teams hosted an inaugural Innovate with Google event at the University of North Carolina’s Kenan-Flagler Business School in Chapel Hill.

Startups, researchers and educators come together to innovate 

The event brought together more than 200 educators, startup executives, life science researchers and others who are innovating with Google. They’re building new teaching models, services and scientific advancements designed to improve lives.

Attendees heard from Jonathan Rochelle, Google’s director of Product Management, who discussed innovation used by billions of people. He gave the example of his own XL2Web startup that became Google Sheets and Expeditions, which allows teachers to take students on virtual field trips.

A panel of educators, students and entrepreneurs shared stories of creating change with technology. Brittany Wenger, Duke University student and Google 2012 Science Fair winner, shared her experience of teaching herself how to code and building a platform powered by Google App Engine that predicts breast cancer with 99 percent accuracy. Dr. Valerie Truesdale of Charlotte-Mecklenburg Schools talked about the district’s Chromebook program (83,000 devices across 168 schools), which began with researching what age group most needed the devices. Sarah Noell of North Carolina State University discussed how faculty and students are working together to design engaging lessons that inspire creativity.

Learning, building and scaling 

Attendees chose from breakout sessions in genomics, startups and education. In the education track, teachers and school administrators shared how they’re rethinking traditional teaching and learning methods with help from Google Apps for Education and Chromebooks. Teachers also got hands-on with tackling current educational challenges with a 10X Design Thinking workshop. Jamel Mims of the Urban Arts partnership led a challenge on how to align pedagogy with art and culture to engage students. He shared his approach of teaching history through rapping. Ellie Gamache of American Underground led a group on how to foster community between local schools, universities and startups to drive innovation and embrace diversity.
Attendees worked in small groups with tools like pipe cleaners, popsicle sticks, construction paper and Play Doh to brainstorm ideas to solve different educational challenges.








The genomics breakout sessions appealed to attendees whose work with big data uses the very same cloud computing platform that powers the Google backbone and services like Search, Maps and Google Genomics. The non-profit organization Autism Speaks, for example, discussed how they’re sequencing 10,000 whole genomes and building the world’s largest private collection of autism-related DNA samples. They shared how they already uploaded nearly 100 terabytes of data from more than 1,300 genomes onto Google Cloud Storage and how they make this genomic data available to researchers for free via the Google Cloud Platform, searchable through BigQuery.

The future looks bright for students, teachers, scientists and entrepreneurs in North Carolina. From research on Autism to creating new companies to enabling students to collaborate on projects remotely, Google tools are providing the building blocks people need to turn their big thoughts into reality and build a better tomorrow.

We’ve heard great stories from many of you about how you’re using technology to do amazing things in your schools, so were going across the U.S. to see for ourselves! North Carolina was the first state we visited. Check out the map below to see where we’ll head next. We’d love to hear what’s happening in your state, so please share your story on Twitter or Google+ and tag us (@GoogleEdu) or include the #GoogleEdu hashtag.


Read More..

Friday, April 1, 2016

Google Search Easter egg for Star Wars A Long Time Ago in a Galaxy Far Far Away


Search "A Long Time Ago in a Galaxy Far Far Away" in Google.


Read More..