Showing posts with label google. Show all posts
Showing posts with label google. Show all posts

Sunday, November 07, 2010

Making a Table of Contents for Sites with Google Apps Script

At work I was building a document using Google Sites. While building them, the section headings were given their own numbers, like so:

Introduction
Part 1: Apples
  Introduction
  1.1: Fuji
  1.2: Macintosh
  1.3: Cameo
  Summary
Part 2: Pears
  Introduction
  2.1: Bosc
  2.2:D'Anjou
  2.3:Warden
  Summary

Yes, of course there's already a gadget you can use to create a table of contents for your page (Menu > Insert > Table of Contents). It's a rather nice gadget, but because I've intentionally numbered some sections and not others, there's a mental mismatch.

As you see, the Table of Contents generator gave section numbers to everything, so depending where you look, 2.2 is either Fuji apples or Bosc pears.

I didn't want to remove the section headings, and there was no real way to remove them via the Table of Contents gadget.

If you're not familiar with Google Apps Script, it's as you think: a scripting engine for Google properties. It's particularly powerful for scripting spreadsheets, and. as of October 22, you can process Google Sites with Google Apps Script.

Before going any farther, let me show you what I generated with Google Apps Script:

I'm no HTML Picasso, but it's not bad. Not bad at all. The links work, thanks to Google Sites automatically injecting <a name> tags with every <h[1-6]> tag.

The code

Let me share the code with you. First, here's how it's invoked:

function run() {
  createToc(
    'https://sites.google.com/site/sitename/source-page',
    'https://sites.google.com/site/sitename/destination-page');
}



Yes, so you can specify a page from which to read and generate a second page with the table-of-contents included. (Side note: This actually gives me lots of ideas about workflow -- envision if the source URL was a private site where drafts were written, you could use Google Apps Script as a way to push from a staging area to production.)

OK, the code. It's mostly processing XML and generating HTML.

// I do not warrant this code in any way.
// If you break something important, don't come crying to me.
// Actually, check your Sites revision history first.
// Then go cry.

// Load content from fromUrl. Find the table of contents, and stick it in the document
// Save at toUrl.
function createToc(fromUrl, toUrl) {
  var page = SitesApp.getPageByUrl(fromUrl);
  var content = page.getHtmlContent();
  var doc = Xml.parse(content, true);
  var root = doc.getElement();
  var toc=[];
  parse(toc, root);

  var prefixDiv = "<div id='kberg-toc'>";
  var postfixHtml = "</div><div id='kberg-toc-coda'/>";
  var codaDiv = "<div id='kberg-toc-coda'/>";

  var html = prefixDiv + tocToHtml(toc) + postfixHtml;

  var index = content.indexOf(prefixDiv);

  var newContent;
  if (index == -1) {
    var x = "<div dir='ltr'>";
    index = content.indexOf("<div dir='ltr'>") + x.length;
    Logger.log("3: " + index);
    var outdex = index;
    newContent = content.substr(0, index) + html + content.substr(outdex);
  } else {
    var outdex = content.indexOf(codaDiv);
    newContent = content.substr(0, index) + html + content.substr(outdex + codaDiv.length);
  }
  var newpage = SitesApp.getPageByUrl(toUrl);
  newpage.setHtmlContent(newContent);
}

// Recurse through the XML, finding <h[1-5]> tags.
function parse(toc, element) {
  var name = element.getName().getLocalName().toUpperCase();
  if (name == "H1" || name == "H2" || name == "H3" || name == "H4" || name == "H5") {
    var level = parseInt(name.substring(1));
    var anchorChildren = element.getElements("a");
    var anchorText = (anchorChildren.length > 0)
        ? anchorChildren[0].getAttribute("name").getValue() : "";
    
    var item = {
      level : level,
      anchor : anchorText,
      description : element.getText() };
    toc.push(item);
  } else {
    for each (var child in element.getElements()) {
      parse(toc, child);
    }
  }
}
     
// Convert the table of contents entries into HTML.
function tocToHtml(toc) {
  var html =
      "<div style='width: 250px; background-color: #e8e8e8;'>\n"
      + "<br/><b>Contents</b><br/><br/>\n"
  for each (var entry in toc) {
    var html2 = indent(entry["level"]) + "<a href='#" + entry["anchor"] + "'>" +
        entry["description"] + "</a><br/>\n";
    html = html + html2;
  }
  html = html + "<br/></div>";
  return html;
}

// Given an indentation level, return (2 * (level - 1)) non-breaking spaces.
function indent(level) {
  var x = "";
  for (var i = 0; i < level - 1; i++) {
    x = x + "&nbsp;&nbsp;";
  }
  return x;
}
​


Final Thoughts

The remaining issue is triggering this script. Google Apps Script does have an event notification mechanism (e.g. run this script when the spreadsheet opens) but right now, Google Sites only has a time-based trigger (e.g. run this script every n minutes/hours.) To be honest, if an onSave trigger was written, would createToc(url, url), which would save the TOC to itself, trigger another onSave event? No big deal, if it results in a no-change, I could tweak the code accordingly.

But the lack of an onSave trigger makes this just slightly usable for me. Having this run every two minutes is too frequent for when the site isn't updated. I don't know the plans for the Google Apps Script team and/or the Google Sites team, but this is a good use case for onSave.

I wonder how hard it would be to hide the default TOC renderers' section numbers with clever CSS, or just write my own Google Gadget...

Friday, March 19, 2010

Learn about how Google uses Eclipse

Hey EclipseCon attendees,

If you're interested in how Googlers use Eclipse to develop some of the products you use, come to our talk on Tuesday, 4:15PM:
Eclipse in the Enterprise: Lessons from Google 
Providing Eclipse tools to thousands of engineers at Google is a satisfying job, but it's not always easy. In the last two years supporting Eclipse at Google has gone from casual support by enthusiasts in their spare time to a dedicated team mandated to make engineers' lives better. We will talk about the plug-ins we've written and processes we've established to provide features, enterprise deployment and support, and even share some of the pitfalls discovered along the way. 
And then, come to the Eclipse In The Enterprise BoF on Tuesday at 7:15PM for an opportunity to discuss how Eclipse is used at your organization!
Hey, you! Yes, you -- don't you work for that big company? Are you supporting hundreds, maybe thousands of your Eclipse-using colleagues? Are upgrades and environmental consistency your problem, too? Are you constantly struggling with fitting your company's build system to the IDE and Eclipse builders? Is your source code base so large that you're continually fooling Eclipse into thinking it's smaller?

Then come meet your peeps at the "Eclipse in the Enterprise" BoF. Let's share war stories and ideas. Impress everyone with your clever solutions and work-arounds! We're all facing the same issues, so come, let's talk.

Thursday, March 11, 2010

Google, thanks for your dog policy.

I want to take a moment and thank my employer, Google.

See, Google has a policy that permits its employees to bring their dogs to work. Now whether you can bring your dog to your office depends on many factors: whether your building allows dogs, whether your teammates tolerate dogs, whether your dog is well behaved, healthy, and so on. In fact, the possibility of bringing a dog to work made it easier to decide that, yes, we could get one. (Note: it was not part of my plan to rely on bringing a dog to Google, it just helped with the decision. You can't predict a rescue dog's personality.)

And then we got Maggie, whom I like to call "the world's best starter dog." Superbly well behaved with only a penchant for barking at strangers a little more frequently and loudly than I'd prefer, taking her to work quickly became one of the very best parts of my job. In the morning we would walk the 2 miles to work, with a couple of walks in the afternoon, and play-time at 5PM, on the dot. She made people in the office happy. She made me happy.

And then we moved to New Jersey.

Dogs are allowed in the Google New York office. But, they're not allowed on the train, at least, not without a crate, and we never managed to successfully crate-train Maggie. That means the only choice is to drive her into New York City. Since my wife works from home most days, there's just a natural predisposition to leave her home. Unfortunately this means she gets much less socialization than she did in California.

I once brought Maggie the NYC office, on Bring Your Dog To Work Day. It didn't go well. Traffic jams dominated the trip in. Maggie was perpetually frightened. Frightened by the highway, the tunnel, the loud, twitchy freight elevator, the noise around my desk, the open cubicle area. She couldn't relax and neither could I. Taking her on a walk was out of the question. No, instead we left for home at 2PM, both of us stressed and sorry, and relieved to be getting out of there.

But this week my wife is away, so I decided to try again. Would things be different?

You bet.

I brought her in on Tuesday. Maggie still hates the freight elevators, but she's hating them less with every ride. The traffic still sucks but I'm beginning to assemble a plan that might help me beat it. My office mates were very happy to have her there. Maggie wasn't afraid of the office, she got lots of much needed human attention and socialization. We found an abandoned part of the office floor, a perfect place to throw a ball. We even managed to go on a walk in the afternoon, complete with a poop! I didn't get a lot of work done, but I brought her in yet again today, and managed to do a solid day's work. Just like when we would hang out at the Santa Monica office.

The traffic, the higher travel cost, the restricted walking, it was all worthwhile.

All of this is to say: Tuesday was my happiest day at work since moving back east. Thank you, Google.

Maggie and me, chilling on the carpet.

Tuesday, March 02, 2010

Advice On Running an Engineering Reading Group

This is an edited version of an internal document I wrote for other engineers at Google about leading an engineering reading group. While much of it meanders into standard tips for managing meetings, they bear mentioning.

Feedback is appreciated!

Advice On Running an Engineering Reading Group

1. Thank you!

First, leading a reading group provides value to you, your colleagues and your company. It's more work than just showing up, and comes with frustration, particularly when attendance is low or someone dominates the conversation. So, thank you.

2. Selecting the book

As the leader, you get to choose the book. If anyone challenges you, ask them to talk to me. It's hard for anyone else to be enthusiastic about the material if you aren't either. Your own self-interest is the best way to generate excitement, ensure you will complete the book and provide ideas. Also, your interests are a fine gauge for other people's interests.

If this is your first reading group, start with an easier book (such as Head First Design Patterns), or one with a reading group guide (such as Joshua Kerievsky's Design Patterns reading group guide.) The harder a book is to understand, the larger number of people will read less, and eventually fall behind and drop out of the group. If anyone complains that the book is too simple, invite them to champion the next book.

By the way, you don't have to be the topic master. Personally, I select books that require the social pressure of leadership for me to finish. When I realized I forgot most design patterns, I led a group in design patterns. Months later, I got stuck half-way through Java Concurrency in Practice, so it became the next reading group book. Both led to successful and engaging reading groups.

3. Do not let the community choose the book.

This was a hard-earned lesson. When you let the community choose the book, you run the risk of the book's most ardent supports disappearing. Leader gets to choose, no question.

4. Purchasing books

Any approval for buying books is probably something you need to discuss with your manager or director. If you have a director willing to take the cost, or perhaps company approval to purchase en masse, great. But while buying individual books can be a logistic hassle, it brings up an important issue:

5. Participants should purchase the books themselves.

After leading several of these groups, I've learned that people who express interest but wait for someone else to get them a book are the ones who tend to be passive participants, or show up for no more than two sessions. Putting participants through a purchasing a hurdle has the benefit of self-selecting the most interested participants.

You might ignore this advice and provide material for attendees. If you want to start with a larger group, or if the reading group is new, then perhaps it's more appropriate to set a welcoming tone. And to be fair, some people for whom I purchased books became the best participants. But take note who sticks around.

6. Set and communicate your expectations.

Make sure you know what kind of reading group you want, and communicate your expectations up-front. Three areas where expectation management can matter:
  • Reading requirements: If people are required to complete reading assignments, those that have not will have difficulty following the conversation. This is okay if you can accept a smaller number of dedicated participants. Or, you can spend the meeting time reviewing the material as if it was not read by the majority. You may wind up with more passive participants, but you may also get more questions.
  • Computers during the meeting: I've never enforced a no-computer policy, but sometimes wished I had. People will keep their focus on a laptop or mobile phone for the entire session. Are they paying attention? Are they encouraging other participants to disconnect? This is a tricky one which comes with existing social pressure. (Update: See the addendum below about actually implementing this.)
  • Tardiness: When you've only got 60 minutes a week to discuss a book and most people show up ten minutes late, you're group's value drops 15%. Communicate the expectation up front, and consider demonstrating it by starting the conversation with whomever is in the room.
Whatever you decide, remember: nobody has to attend, so you'll do better being polite than a draconian jerk.

7. Be Prepared

My wife taught me a lesson from her law school days : you can't always be the smartest person in the room, but you can always be the most prepared. This applies to leaders in particular. Read and understand the content. Come to sessions with conversation openers. The most engaged Java Concurrency in Practice session we had was one where I brought in sample code; a broken task pipeline, and fixed it in front of everyone.

There's another reason to be prepared: to master the material! Isn't that why you chose to lead a reading group, instead of waiting to participate?

8. Set the tone, and then share the leadership role.

Being a book's champion or the reading group leader does not make you responsible for generating interesting content from week to week, and in fact it's better to ask other participants to take the role of leading the group for single sessions. This is most valuable after a reliable leader spends two to three weeks setting the group's tone.

9. Encourage quiet people to participate or even lead for a week.

Part of the leader's job is to draw all participants into the discussion. Keep a few loud people from dominating the conversation. Draw out quieter people, preferably with open-ended solicitations of opinions or observations. Avoid  pop-quiz challenges; the goal is to expose a broad range of views, not intimidate shy people.

When you can get a quiet person to lead the discussion for one meeting, now that's a win.

10. Manage how far you drift off-topic.

Drifting off-topic can distract the group from more relevant material, but it can also provide the most interesting content. Conversations about concurrency can lead to conversations about testing which eventually take you to complaints about the build system. That's okay. Keep your eye on the clock, use your judgment, and don't be afraid to cut conversations off after a while. Remember to do it with kindness.

11. Always ask for feedback.

Ask the other participants how you're doing. Ask why they aren't speaking up. Ask how improve the sessions. Mostly you'll hear what a great job you're doing. Thanks! Now ask someone else. You're about to spend several weeks with everyone: keep an active two-way conversation channel.

That reminds me: ask drop-outs why they left. People tend to feel bad about leaving. I've had drop-outs hide from me after they leave. Go find out what happened. They might have useful feedback, they might even return for the next book.

12. Mistakes are good!

People already respect you for dedicating your time to take charge. Don't worry when you make mistakes your first time. You'll learn so much that leading the second book will be a cinch in comparison.

Addenda September 25, 2012:

Addendum regarding the no-laptop policy

 My most recent group had a no-laptop policy. We set it up before the first meeting by general consensus, and it worked really well. It allowed us to stay focused, and also, to have the authority to ask new visitors to close theirs, as well as their phones, by association.

Gauging Comprehension

Here's a useful tip: a good opening question is to find out how well people comprehended a chapter. (This also applies to individual sections within a chapter.) The way to gauge interest is to ask everyone to demonstrate their comprehension as a range, not unlike a volume meter. If the participant understands the content fully, the arm and hand point straight up. If the participant didn't understand it at all, the arm is parallel to the floor. From there, people can use the range in between 0 and 90 degrees to demonstrate comprehension. Then as the leader you can get a quick sense of the room, not just from the positions of their hands, but of the looks on their faces. Find someone whose hand is in the middle and ask the person to go into detail about their experience.


Thursday, August 27, 2009

Live from Eclipse Day at the Googleplex

The day finally came: Eclipse Day at the Googleplex, 2009. This event was hosted by the Google Open Source Program Office, and really, they did a great job. Seriously big thanks to Chris, Leslie, Cat and Ellen, who put together a fantastic program. Except for the forks. (Note to self: Even if Eclipse Day lunch has no forks, I must no longer try stealing forks from a Google cafeteria. You'll get caught and questioned by the cafeteria manager.)

But also I have to thank Ian Skerrett and Lynn of the Eclipse Foundation for putting so much together on their side of the event. Ian is actually sitting right next to me: we're listening to one of the final talks "Google Plugin for Eclipse: Not Just for Newbies Anymore" given by my Google colleague, Miguel Méndez. Miguel just demonstrated how the Google Plugin for Eclipse deals with launch configurations. I'm drooling.

My teammate, Terry Parker, and I gave the keynote presentation, titled "Eclipse in the Enterprise: Lessons from Google" which was a glimpse into what it takes to support all the people at Google who build applications with Eclipse:
Providing Eclipse tools to thousands of engineers at Google is a satisfying job, but it's not always easy. In the last two years Eclipse has gone from being a tool supported by enthusiasts in their spare time to one supported by a team mandated to make engineers' lives better. We will talk about the plug-ins we've written and processes we've established to provide features, enterprise deployment and support, and even share some of the pitfalls discovered along the way.
I wasn't sure how the talk would be received, but it sure seems to have gone over well. Slides are coming shortly, as is, I hope, a YouTube video.

Along those same lines, Joep Rottinghuis from eBay talked about Deploying Successful Enterprise Tools, and it was serendipitous since he managed to touch on all the facets of enterprise tool support that we omitted from our talk: support, documentation and training.

The best part, though, was how people from both eBay and Cisco told us that they were happy to see us talking about the scalability issues we've seen; they have the same problems!

All of this underscores what I have thought since last year's EclipseCon: next year I'd like to see an Enterprise Tools BoF.

Ooh, gotta go: now Miguel is talking about adding special JSNI formatting in editors. Swoon!

Tuesday, June 09, 2009

Registration is open for Eclipse Day at the Googleplex

We've been working hard behind the scenes, but now I'm happy to report that registration is now open for Eclipse Day at the Googleplex 2009! This is a collaboration between the Google Open Source Office and the Eclipse Foundation.

Last year's Eclipse Day [videos] was a great success, and I'm happy that we're doing it again this year. Additionally, this year, my colleague Terry Parker, and I, are giving the keynote, titled Features, Deployment and Support in the Enterprise: Lessons from Google where we'll talk a bit about some of the things we've learned providing developer tools to a large base of smart users who love their tools.

It's free to attend, so register now.

Sunday, September 14, 2008

An observation about facial tagging

I am happy to see that the Picasa team launched their new facial tagging feature. I've had the pleasure of playing with it/testing it/providing feedback before its release and am glad to see it released to the world. While it was internal, I did not dedicate my time to seriously tagging photos. Consider: when something is in an internal testing phase, there's always an outside chance that the engineers might have to clear out historical data. Now that it's public, I've tagged thousands of faces.

I discovered something interesting from tagging this many faces. Let me give you some background: the facial tagging feature does two things very well: it can identify faces in a photograph, and it can identify when the same face appears in multiple locations. In other words, it can easily tell you when several photos contain the same person. What it can't do is tell you who those people are -- that's something you have to do. It may know that these are all the same person but only you know that's Chris's Mom.



So here's the thing. While looking at a nonstop stream of faces that represent my entire social graph, I all too often could not name face. Twice so far I failed to recall the name of colleagues I see every day. Often I see faces that I can only seem to tag as "Ellen's baby" or "Chris's Mom." You can get away with that sometimes but you can't get away with it when it's "your coworker who you mostly remember because of the great socks she wears."

This is unsettling. And it's also a good way to test my recall ability. You typically see faces in conjunction with other related faces. With Picasa, facial tagging lacks the context of related faces, and clusters of faces do not appear next to their related faces, so I find myself going from coworkers husband to niece's friend to next door neighbor. In this case, my brain cannot leverage its ability to cache related concepts up front.

Incidentally, what is Chris' mother's name?

Friday, April 04, 2008

Testing on the Toilet

I'm a big fan of Google's internal series called Testing on the Toilet, in which we post Software Testing hints in the bathroom stalls. It's sometimes difficult to effectively write something that fits the TOtT style: it has to be informative, succinct, and comprehensible, to be blunt, readers are only there for a minute or two while they do their business. So most of the articles have to be short and useful. That said, I wrote a small article last year and it made the rounds through the company reading rooms. It took a surprising amount of work to write that small article, requiring several revisions, lots of feedback, and I practiced removing two words where just one would do.

Early in 2007, Google started its public testing blog, and today I see that the article I wrote, "Time is Random" is on there. It's not mind-blowing, but it fits nicely on a single sheet of paper, and applies to areas well beyond keeping time. Dependency injection need not have a framework, sometimes you just need to add a parameter.

Given the nature of the work I do at Google, it's rare that anything I do is seen by the general public, so I just wanted to toot my horn.