text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="robots" content="noindex">

    <title>Manasvi Somaiya</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/agency.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Raleway:600' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    <link rel='stylesheet' type='text/css' href='https://fonts.googleapis.com/css?family=Josefin+Sans' />
    <link rel='stylesheet' type='text/css' href='https://fonts.googleapis.com/css?family=Amaranth'/>
    <link href='https://fonts.googleapis.com/css?family=Libre+Baskerville:400,600|Poppins:400,500,700' rel='stylesheet' type='text/css'/>

    <link href='img/favicon.jpg' rel='icon'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Manasvi Somaiya

                        Portfolio

                        About

I design thoughtful, beautiful and easy-to-use experiences.

                See My Work

Portfolio

Modernizing a Cloud Management Application

Redesigning VMware's cloud operations and management application with a goal to enhance usability and accelerate time to value.

                    READ MORE

Evolving alerts & troubleshooting

Using data and empathy to uncover user needs and evolve designs for datacenter alerting and troubleshooting.

                    READ MORE

Building a better capacity planning experience

Using research, personas and workflows to drive design decisions to build a better capacity planning experience.

                    READ MORE

Designing a simulation service

Simulating and visualizing the impact of server failures.

                    READ MORE

Launching a recovery to the cloud service

End to end designs for a SaaS based cloud recovery planning service.

                    READ MORE

About

I'm a Product Designer based in San Francisco with over 5 years of work experience.

I'm an avid dreamer who enjoys solving problems and making a positive impact through design. I believe that telling your user's story and building empathy are key to understanding the problem to be solved.

I currently work at  VMware as a  Sr. Product Designer.  I recently won an award for my paper,  'Using Storytelling to Promote Customer Experience' at VMware's annual R&D conference. In addition, I also hold  two patents  for my work around visualizing error information.

In my free time I like planning trips to places I haven't seen, playing board games, doing 1000 piece puzzles, dabbling in water color painting and searching for the next best cup of coffee.

Modernizing a Cloud Management Application

Lead Product Designer

SUMMARY

BACKGROUND

VMware's cloud operations solution provides analytics and insights to help administrators manage their datacenters efficiently.

USERS

Our target users are cloud administrators who ensure that business applications and services are always up and running.

THE GOAL

Give the product a complete refresh, improve the overall usability and optimize the key workflows.

ROLE

Lead Product Designer

I worked alongside 2 designers and 1 researcher

PROCESS

We spent many months working with a large engineering team spread across different countries. We collaborated closely with product managers and tech leads.

                                            The process included:

Discovery

Planning

Ideation

Design

User Testing & Validation

Implementation

DISCOVERY

1. Usability Evaluation of Existing Product

We went through the most common workflows and tasks in the product and identified areas for improvement. A few of the areas we identified included:

Improve context, by grouping similar items and actions together

Make navigation intuitive, to eliminate guesswork

Use of progressive disclosure, to expose information and actions at a second level

The Initial State

2. Gathering Business Requirements

We worked closely alongside product managers to understand the requirements from the business and market perspective.

3. User Research

Before starting this project, we conducted a  usability benchmarking study  to collect data about the current ease of use of the product. This data was very helpful during the redesign, it helped provide us targeted goals to work towards. It established a starting point to compare against our design iterations.

Targeted Goals from Research

Improve wayfinding and need for context switching.

Refine information architecture for a clear happy path.

PLANNING

1. Defining our target persona

In previous projects, we had already spent time defining the target personas for this product. We used our personas to help define how we saw our users using the product in particular flows.

2. Defining Workflows

Before starting to work on designs, we mapped out the current workflows in the product today. We also listed tasks and subtasks.

3. Creating a phased plan

I created a design plan to help set expectations of the tasks we would accomplish through the means of phases. This helped prioritize the UX work to be done.

IDEATION

1. Redesigning the information architecture

To understand areas of improvement, I started by documenting the existing information architecture of the product and then evaluated the different categories and groupings for each of the items.

2. Early designs and concepts

I started by redesigning the overall navigation. In my design explorations I played around with making the primary navigation in the header as opposed to the side panel. I also designed ideas to move dashboard navigation to the side panel and replace the current tab structure.

3. Initial User Research

Method: Card Sorting Study

Goal: Understand our user's mental model of information presented in the product

We conducted this session with 9 customers. We asked them to organize the product functionalities (cards) into different groups and assign categories to them. As an end result, we were able to gather data to drive and back our design proposals.

DESIGN

1. Redesigning the Navigation Model

 We changed the primary navigation to the header and saved the left side menu for secondary navigation. This eliminated the need for having a sliding panel or quick links. Our intention with this change was to give users a clear understanding of where they were in the product.

2. Organizing Dashboards

 We used the side panel to expose the dashboard list to allow for scalability in number of open dashboards.

3. Contextual Alerts

 We used the means of a right-hand drawer mechanism to show detailed information when a user clicks on an alert.

4. Prototype

 We used  Invision  to create prototypes of our designs and used this as a means to collaborate with and share our work with engineering and product management teams.

5. User Research

We validated our designs through research and collected feedback on the proposed changes to the navigation and workflows.

"It's much cleaner and the information is much easier to digest because the text is a lot more consolidated."

"This list very clearly indicates what we are seeing here and ability to switch between available dashboards."

6. Before & After Screens

7. Final Product

8. Product Demo

USER TESTING & VALIDATION

We validated our designs through 1-1 user studies and used the feedback to iterate through the design cycle. Once the implementation had begun, we ran tech preview sessions to get user feedback with a working build of the application. We conducted user tests with 7 customers. On the whole, we received a lot of positive feedback and saw a high completion rate of tasks and received high scores for ease of use.

IMPLEMENTATION

1. Fit & Finish

Since we were redesigning the entire product, we worked very closely with the UI team to ensure that the design specs met the implementation. We set up a process for us to track UX bugs and ensure they were being fixed.

2. Bug Bash

To ensure that the transition of the redesign was smooth, I hosted an internal bug bash session with other teams and stakeholders. We divided up the workflows and filed bugs on the implementation.

THE IMPACT

The redesign of vRealize Operations Manager was one of the major updates in the release and received a lot of positive responses.

1. Usability was a Key Selling Point

2. Release Received Positive Results

"I LOVE THE NEW vROPS 6.6 INTERFACE. I'm a fan of well-created, thought-out user interfaces"

"The new HTML5 interface is absolutely awesome - a vast improvement on previous versions. The layout is far simpler to navigate and makes a lot more sense"

"The new Getting Started Dashboard list is VERY useful (thank you VMware!)"

"Not going to lie, the sole reason for our upgrade was the UI"

"Our main motivation for upgrading was to take advantage of the newest dashboards and HTML5 UI which are really sleek and very easy to navigate!"

"The latest release provides a much needed update in the UI along with some very slick dashboards. It features an all new HTML5 interface which provides and easier and more consistent experience when navigating."

LEARNINGS

1. You can't argue with data

Having research data to back our early evaluations and assumptions really helped us communicate our designs better with other stakeholders. It also helped ensure that our designs matched our customer's mental models.

2. Building trust is a process

The product release scaled horizontally across a vast number of people and teams, many of whom were the original architects of the product. Taking the time to understand each other's point of view really helped build a two-way trust which was essential in building the product.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Launching a Recovery to the Cloud Service

Lead Product Designer

SUMMARY

BACKGROUND

VMware was looking to launch a new SAAS based application to allow users to back-up and recover their applications in the cloud

USERS

Our target users are cloud administrators

THE GOAL

Design a new application for customers that are transitioning to using services on the cloud

ROLE

Lead Product Designer

PROCESS

                                            The process included:

Discovery

Ideation

Design

User Testing & Validation

Implementation

DISCOVERY

1. Understanding the domain

To be able to effectively design for a new service it was important for me to start by understanding the domain. To achieve that, I did the following:

Attend webinars on the topic

Read through documentation

Watch live demos

Talk to subject matter experts

Tinker with similar products / tools

2. Competitive Analysis

I studied competitor products to understand their offering not only in terms of the functionality they presented but also from the perspective of the experience they provided to their users.

I used Pinterest boards as a way to organize my findings.

IDEATION

1. Use Cases & Workflows

I started the ideation phase by documenting the use cases and end to end flows that a user would go through while using the product. This included workflows needed by the new functionality as well as set up and configuration flows.

2. Advocating for the user

In the initial phases of ideation, the engineering team was working on making key decisions that impacted how the service would be made available. These decisions directly affected the workflows. I created comparative flows to help be the voice of the user and advocate for the best experience.

DESIGN ITERATIONS

1. Defining the information architecture

I began the design cycle by outlining the high level flows and information architecture. Starting with the big picture helped identify potential pain points early on.

For example, while doing this I realized that to configure the product, the users need networking information at hand. I accommodated for this while designing the workflow.

2. Wireframes

I created wireframes and sketches to get early feedback. I iterated over the wireframes based on the feedback.

Low fidelity Wireframes

3. Final Designs

USER TESTING & VALIDATION

User Studies x 4 Rounds

I conducted 4 rounds of user studies to validate the wireframes at each step. The feedback I collected directly impacted the design decisions I was making and helped improve the overall design.

Goal: Get feedback on key workflows in the product

Type of sessions: 1 Concept validation, 3 Usability testing

Format: 1-1 user interviews

Session Length: 60 mins

Outcomes:

Overall received positive feedback

Identified usability issues

Understood user needs for new functionality

Fixed terminology issues

"I think reminder (of the next steps) would be beneficial. I think if you highlight the potential next options, it will be very helpful"

"As a user I would expect to see the recovery plan I need to run first in the list. If I had my wishes, the user should be able to order plans."

IMPLEMENTATION

Collaborating with Engineering teams

I supported the engineering team through implementation. We used the UX prototype as a way to share up to date designs and communicate expected interactions. The engineering team was located across different continents so we set up a regular cadence of sharing updates.

60 minutes, 2 times a week

I also reviewed the implementation to ensure that it matched the design specifications.

LEARNINGS

Get feedback early and often.

Design for the 80% use case. Push back on optimizing the user experience around edge cases.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Designing a Simulation Service

Product Designer

SUMMARY

BACKGROUND

Our users love and rely on our existing technology, it helps ensure that their services are always up and running. The 'behind the curtain' magic depends on the customers having the right amount of capacity in case of failures.

USERS

Our target users are infrastructure administrators.

THE GOAL

Design a service to help simulate consequences of server failures.

ROLE

Product Designer

PROCESS

                                            The process included:

Discovery

Use Case Definition

Design

Validation

DISCOVERY

Gathering Requirements

This project was brought to the UX team by tech leads. Unlike most other projects, this one did not have any product managers or formal requirements. I had to spend the first few meetings with the tech leads trying to understand and gather more information on the problem and the desired outcomes.

USE CASE DEFINITION

1. Define the Use Cases

To make sure that we were telling the right user story, the design process started by validating initial workflows and use cases internally with subject matter experts.

To define the problem being solved, I outlined the scenario, potential triggers and proposed workflow.

2. Define the Workflow

To expand on the workflow, I illustrated the steps a user would take to run this simulation. This illustration helped ensure that there was a common understanding between stakeholders.

DESIGN

1. Sketches & Wireframes

I started by creating initial wireframes and sketches to get early feedback. I iterated over wireframes based on the feedback.

ITERATION 1

ITERATION 2

2. Final Designs

You can access the service HERE.

The service was launched as a VMware Fling and was received with commendation at VMworld.

USER TESTING & VALIDATION

Showcase at VMworld

We used VMworld as a platform to showcase the demo and get user feedback at our yearly conference.

LEARNINGS

It was a really good experience working closely with tech leads and subject matter experts. Since there were no product managers on this project, I had to learn to translate the mathematical magic into something simple.

Defining a detailed workflow early on helped ensure there was a common understanding between all the stakeholders.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Building a Better Capacity Planning Experience

Lead Product Designer

SUMMARY

BACKGROUND

VMware's cloud operations solution provides analytics and insights to help administrators manage their datacenters efficiently.  One of the core capabilities of the product is capacity planning.

USERS

Our target users are capacity planners that plan for the growth of the business and ensure that there is no shortage of resources.

THE GOAL

Design capacity planning workflows in the product.

ROLE

Lead Product Designer

I worked alongside 2 designers and 1 researcher in this project.

PROCESS

                                            The process included:

Discovery

User Research

Ideation

Design Sprints

User Testing & Validation

DISCOVERY

1. Buy a Feature Exercise

As we worked towards planning features, we teamed up with the product management team to run a prioritization exercise with 30 customers.

To make this exercise interactive, we handed out $120 VMware dollars to each customer and displayed different feature sets with a price tag. We asked the customers to shop for features they wanted.

One of the top voted features was capacity planning. We used this opportunity to hear customer stories and understand their underlying needs from the tool.

2. Understanding User Needs

To better understand the customer needs, we mapped out their current workflows and tasks.

We identified areas where we could add value and proposed new workflows.

USER RESEARCH

1. Customer Site Visits

We spoke to 66 customers across 18 companies to understand their workflows, needs and aspirations from the product. We also gathered early feedback on workflows and low fidelity wireframes.

2. Customer Trip Summary

To summarize the takeaways from our trip we highlighted the following areas:

Customer Profile

Challenges in doing capacity planning today

Use cases for capacity planning

Needs & Aspirations

Ideation

1. Defining the Persona

Our target persona is a capacity planner who is responsible of ensuring that his company has sufficient resources to run their business smoothly.

2. Creating Storyboards

As designers, we want to share our work by telling the customer story. We use storyboards by means of illustrating the user context, need and workflows that happen both inside and outside of using the product. This helps align teams and build empathy for our customer.

DESIGN SPRINTS

We focused on designing in 2 week sprints.

Day 1-2: The first 2 days were spent defining the problem, gathering requirements, identifying pain points and designing a proposed workflow.

Day 3 -7: Brainstorming. Collaborating. White-boarding. Speed Sketching.

Day 8-10: We reviewed designs and got feedback from stakeholders and customers. We also shared our work and findings with the broader teams. This included back-end and front-end engineering teams, product management teams across different locations.

1. Ideation through Speed Sketching

We used speed sketching as a mechanism to iterate through ideas.

For each problem, we spent:

10 minutes discussing the problem

10 minutes sketching ideas

10 minutes reviewing ideas

Once reached a consensus we moved to creating wireframes and getting internal feedback (PM & Eng.).

2. Mock-ups

We had 3 iteration cycles on the designs based on feedback we received both internally and through customers.

Unfortunately, I can't share screenshots of my work as yet.

USER TESTING & VALIDATION

1. Storyboards to Build Context

We used storyboards to give our customers more context about the problems we were trying to solve.

We also used them as conversation starters to learn more about whether the stories matched their real world experiences.

2. Feedback Sessions

We conducted sessions for 4 days at the VMworld conference to showcase our latest work and get feedback.  Apart from participating in the discussion we also handed out printed surveys and mockups that customers could leave feedback on. We had some great participation and results from the sessions.

Session Format: Group Session

Time: 90mins

VMworld Design Studio

3. Feedback Synthesis

We synthesized the feedback and used the data to inform design changes.

LEARNINGS

Visiting the customers in person helped us see their usage of the product and eventually helped us advocate for their needs in an informed manner.

Research helped validate our assumptions before we started designing.

User stories and workflows helped build alignment among stakeholders.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Evolving Alerts & Troubleshooting

Product Designer

SUMMARY

BACKGROUND

VMware's cloud operations management solution allows users to get insights and analytics about their infrastructure. When something is amiss, they need ways to be alerted and be able to remediate the issues.

USERS

Our target users are cloud administrators that need to triage tickets by troubleshooting issues on a daily basis.

THE GOAL

Create a new vision for alerts and troubleshooting.

ROLE

Product Designer

I worked alongside 2 designers and 1 researcher in this project. We also worked alongside a design consulting firm during the discovery and research phase.

PROCESS

                                            The process included:

Discovery

User Research

Ideation

Design Framework

User Testing & Validation

DISCOVERY

1. Desirable Outcomes Exercise

We worked alongside a design consulting firm to run a kick-off activity to get teams aligned. We asked the stakeholders to pick the top 3 desired outcomes for this project. The top outcomes from this exercise were:

Build Empathy for our users

Help users Reduce Resource Wastage

Give users Ease of Mind

"The language of our product needs to be accessible."

- Tech Lead

"We can help customers worry less, trust more."

- Product Manager

2. The Love/Break-up Letter Exercise

This was a design thinking activity to help stakeholders communicate what they envisioned the product to be. Instead of directly asking people what they like or dislike, this method gives insight into their perceptions by eliciting feelings of admiration, appreciation, frustration or aversion based on real life experiences. Each person was given a letter to fill out.

what they like

what they dislike

what they want

This was a great way to better understand individual perspectives and tones which is often hard to come across through group conversations.

3. Outcomes

The kick-off activities helped us focus on some high level themes and objectives for the service

(1) Reduce Noise

                                            Prioritize highest impact outages first

(2) Evidence

                                            Help customers with data to prove innocence

(3) Diagnose Issues Faster

                                            Be able to see all relevant information at once

(4) Efficiency

                                            Help customers be efficient

"When everything is red, nothing is red."

"I only need one notification, not 10,000."

"Admin should be able to say it's not my system, but it's this..."

USER RESEARCH

1. Customer Site Visits

We conduced on-site user research to better understand the following:

Team Structure and Communication

Current Troubleshooting Workflow

Challenges

Needs and Aspirations

We visited 21 customers across 5 companies

2. Synthesis Workshop

We used a quadrant method to explore similarities and differences between different types of users.

We observed that distinct groups were emerging. We further delved into understanding the differences between the groups.

IDEATION

1. Building Personas

 Through the synthesis workshop, we started uncovering patterns and seeing similarities between different user groups. We used a 2x2 plot diagram method to explore similarities and differences between the users.

We used the data from the exercise to create a draft of the personas. We identified two main user groups and outlined user themes.

2. Personas

DESIGN FRAMEWORK

1. Defining User Context

Our personas were mainly based on larger enterprise customers but we also wanted to make sure that we understood smaller businesses. We did so by detailing user context and noting areas where we expected them to be different. A few of them included:

Goals, Passions, Struggles

Stress level, Emotional triggers

Experience

Device diversity

Responsibility (business vs. personal)

Measure success

2. Defining User Tasks

The next step of the process was to list all the tasks a user needs to accomplish during and before receiving an issue to fix.

Solve problems (reactive)

Prevent problems (proactive)

Monitor (performance, progress, resource)

Track/Delegate/Assign tasks

Collaborate

Tune/Customize

3. Collaborating with Stakeholders

We collaborated closely with the product and engineering teams during the ideation phase.

4. Defining Workflows

We outlined the high level workflows which served as a reference to the big picture and the main problems we were trying to solve. We reviewed the flows with other teams before designing the interactions.

5. Wireframes

6. Final Screens

USER TESTING & VALIDATION

1. Storyboards to build context

We created storyboards to give our customers more context about the problems we were trying to solve.

We used storyboards to validate workflows and understand if the stories matched our user's real world experiences.

In between stories, we included questions to engage customers in conversations.

"Ethan got off easy, we have noisy neighbor problems but very uncooperative noisy neighbors"

Is this scenario valid?

"Yes, almost exactly, kind of scary"

2. Feedback Sessions

VMworld Design Studio

We conducted sessions for 4 days at the VMworld 2016 conference to showcase our latest work and get feedback. The session lasted 90 mins and covered 2 main workflows we were looking to get feedback on.

3. Feedback Synthesis & Takeaways

Very positive feedback towards the workflows we showed.

Identified 13 areas of improvements to be addressed in future releases.

Continued to see differences between commercial and enterprise customers.

LEARNINGS

What worked well

A common set of personas helped bring alignment amongst all the stakeholders.

Design framework exercises helped us dive deeper into the personas to understand the nuances between enterprise and commercial customers.

What could be better

More upfront UX research on feature requests before we start to design.

                                <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>


text:
module Invoiced
  class TaxRule < Object
    include Invoiced::Operations::List
    include Invoiced::Operations::Create
    include Invoiced::Operations::Update
    include Invoiced::Operations::Delete

    OBJECT_NAME = 'tax_rule'
  end
end

redpajama_set_name: RedPajamaGithub


text:
package tiered

import (
	"testing"
	"time"

	clientmodel "github.com/prometheus/client_golang/model"

	"github.com/prometheus/prometheus/utility/test"
)

func testBuilder(t test.Tester) {
	type atTime struct {
		fingerprint string
		time        clientmodel.Timestamp
	}

	type atInterval struct {
		fingerprint string
		from        clientmodel.Timestamp
		through     clientmodel.Timestamp
		interval    time.Duration
	}

	type atRange struct {
		fingerprint string
		from        clientmodel.Timestamp
		through     clientmodel.Timestamp
	}

	type in struct {
		atTimes     []atTime
		atIntervals []atInterval
		atRanges    []atRange
	}

	type out []struct {
		fingerprint string
		operations  ops
	}

	var scenarios = []struct {
		in  in
		out out
	}{
		// Ensure that the fingerprint is sorted in proper order.
		{
			in: in{
				atTimes: []atTime{
					{
						fingerprint: "0000000000000001111-a-4-a",
						time:        clientmodel.TimestampFromUnix(100),
					},
					{
						fingerprint: "0000000000000000000-a-4-a",
						time:        clientmodel.TimestampFromUnix(100),
					},
				},
			},
			out: out{
				{
					fingerprint: "00000000000000000000-a-4-a",
				},
				{
					fingerprint: "00000000000000001111-a-4-a",
				},
			},
		},
		// // Ensure that the fingerprint-timestamp pairs are sorted in proper order.
		{
			in: in{
				atTimes: []atTime{
					{
						fingerprint: "1111-a-4-a",
						time:        clientmodel.TimestampFromUnix(100),
					},
					{
						fingerprint: "1111-a-4-a",
						time:        clientmodel.TimestampFromUnix(200),
					},
					{
						fingerprint: "0-a-4-a",
						time:        clientmodel.TimestampFromUnix(100),
					},
					{
						fingerprint: "0-a-4-a",
						time:        clientmodel.TimestampFromUnix(0),
					},
				},
			},
			out: out{
				{
					fingerprint: "00000000000000000000-a-4-a",
				},
				{
					fingerprint: "00000000000000000000-a-4-a",
				},
				{
					fingerprint: "00000000000000001111-a-4-a",
				},
				{
					fingerprint: "00000000000000001111-a-4-a",
				},
			},
		},
		// Ensure grouping of operations
		{
			in: in{
				atTimes: []atTime{
					{
						fingerprint: "1111-a-4-a",
						time:        clientmodel.TimestampFromUnix(100),
					},
				},
				atRanges: []atRange{
					{
						fingerprint: "1111-a-4-a",
						from:        clientmodel.TimestampFromUnix(100),
						through:     clientmodel.TimestampFromUnix(1000),
					},
					{
						fingerprint: "1111-a-4-a",
						from:        clientmodel.TimestampFromUnix(100),
						through:     clientmodel.TimestampFromUnix(9000),
					},
				},
			},
			out: out{
				{
					fingerprint: "00000000000000001111-a-4-a",
				},
				{
					fingerprint: "00000000000000001111-a-4-a",
				},
				{
					fingerprint: "00000000000000001111-a-4-a",
				},
			},
		},
	}

	for i, scenario := range scenarios {
		builder := &viewRequestBuilder{}

		for _, atTime := range scenario.in.atTimes {
			fingerprint := &clientmodel.Fingerprint{}
			fingerprint.LoadFromString(atTime.fingerprint)
			builder.GetMetricAtTime(fingerprint, atTime.time)
		}

		for _, atInterval := range scenario.in.atIntervals {
			fingerprint := &clientmodel.Fingerprint{}
			fingerprint.LoadFromString(atInterval.fingerprint)
			builder.GetMetricAtInterval(fingerprint, atInterval.from, atInterval.through, atInterval.interval)
		}

		for _, atRange := range scenario.in.atRanges {
			fingerprint := &clientmodel.Fingerprint{}
			fingerprint.LoadFromString(atRange.fingerprint)
			builder.GetMetricRange(fingerprint, atRange.from, atRange.through)
		}

		for j, job := range scenario.out {
			got := builder.PopOp()
			if got.Fingerprint().String() != job.fingerprint {
				t.Errorf("%d.%d. expected fingerprint %s, got %s", i, j, job.fingerprint, got.Fingerprint())
			}
		}
		if builder.HasOp() {
			t.Error("Expected builder to have no scan jobs left.")
		}
	}
}

func TestBuilder(t *testing.T) {
	testBuilder(t)
}

func BenchmarkBuilder(b *testing.B) {
	for i := 0; i < b.N; i++ {
		testBuilder(b)
	}
}


text:
The intent of this project is to use the Pager Duty API to create a test alert and then follow up the alert with a check to see if any team member has acknowledged the alert with in a given time frame so that teams can verify that the on call procedures in place are working properly.

#Guidelines for contributing

Please read the [guidelines for contributing](GUIDELINES_FOR_CONTRIBUTING.md) to make sure you and others have an amazing experience when giving back to OSS.


text:
package io.fullstack.firestack.auth;

import android.util.Log;

import java.util.Map;

import android.net.Uri;
import android.support.annotation.NonNull;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReactContext;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GetTokenResult;
import com.google.firebase.auth.GoogleAuthProvider;

import io.fullstack.firestack.Utils;

@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public class FirestackAuth extends ReactContextBaseJavaModule {
  private final int NO_CURRENT_USER = 100;
  private final int ERROR_FETCHING_TOKEN = 101;
  private final int ERROR_SENDING_VERIFICATION_EMAIL = 102;

  private static final String TAG = "FirestackAuth";

  // private Context context;
  private ReactContext mReactContext;
  private FirebaseAuth mAuth;
  private FirebaseAuth.AuthStateListener mAuthListener;

  public FirestackAuth(ReactApplicationContext reactContext) {
    super(reactContext);
    mReactContext = reactContext;
    mAuth = FirebaseAuth.getInstance();

   Log.d(TAG, "New FirestackAuth instance");
  }

  @Override
  public String getName() {
    return TAG;
  }

  /**
   * Returns a no user error.
   *
   * @param callback JS callback
   */
  private void callbackNoUser(Callback callback, Boolean isError) {
    WritableMap err = Arguments.createMap();
    err.putInt("errorCode", NO_CURRENT_USER);
    err.putString("errorMessage", "No current user");

    if (isError) {
      callback.invoke(err);
    } else {
      callback.invoke(null, null);
    }
  }

  @ReactMethod
  public void listenForAuth() {
    if (mAuthListener == null) {
      mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
          FirebaseUser user = firebaseAuth.getCurrentUser();
          WritableMap msgMap = Arguments.createMap();
          msgMap.putString("eventName", "listenForAuth");

          if (user != null) {
            // TODO move to helper
            WritableMap userMap = getUserMap(user);
            msgMap.putBoolean("authenticated", true);
            msgMap.putMap("user", userMap);

            Utils.sendEvent(mReactContext, "listenForAuth", msgMap);
          } else {
            msgMap.putBoolean("authenticated", false);
            Utils.sendEvent(mReactContext, "listenForAuth", msgMap);
          }
        }
      };
      mAuth.addAuthStateListener(mAuthListener);
    }
  }

  @ReactMethod
  public void unlistenForAuth(final Callback callback) {
    if (mAuthListener != null) {
      mAuth.removeAuthStateListener(mAuthListener);

      // TODO move to helper
      WritableMap resp = Arguments.createMap();
      resp.putString("status", "complete");

      callback.invoke(null, resp);
    }
  }

  @ReactMethod
  public void createUserWithEmail(final String email, final String password, final Callback callback) {
    mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
            try {
              if (task.isSuccessful()) {
                userCallback(task.getResult().getUser(), callback);
              } else {
                userErrorCallback(task, callback);
              }
            } catch (Exception ex) {
              userExceptionCallback(ex, callback);
            }
          }
        });
  }

  @ReactMethod
  public void signInWithEmail(final String email, final String password, final Callback callback) {

    mAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
            try {
              if (task.isSuccessful()) {
                userCallback(task.getResult().getUser(), callback);
              } else {
                userErrorCallback(task, callback);
              }
            } catch (Exception ex) {
              userExceptionCallback(ex, callback);
            }
          }
        });
  }

  @ReactMethod
  public void signInWithProvider(final String provider, final String authToken, final String authSecret, final Callback callback) {
    if (provider.equals("facebook")) {
      this.facebookLogin(authToken, callback);
    } else if (provider.equals("google")) {
      this.googleLogin(authToken, callback);
    } else
      // TODO
      Utils.todoNote(TAG, "signInWithProvider", callback);
  }

  @ReactMethod
  public void signInAnonymously(final Callback callback) {
    Log.d(TAG, "signInAnonymously:called:");
    mAuth.signInAnonymously()
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
            Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful());

            try {
              if (task.isSuccessful()) {
                userCallback(task.getResult().getUser(), callback);
              } else {
                userErrorCallback(task, callback);
              }
            } catch (Exception ex) {
              userExceptionCallback(ex, callback);
            }
          }
        });
  }

  @ReactMethod
  public void signInWithCustomToken(final String customToken, final Callback callback) {
    mAuth.signInWithCustomToken(customToken)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
            Log.d(TAG, "signInWithCustomToken:onComplete:" + task.isSuccessful());
            try {
              if (task.isSuccessful()) {
                userCallback(task.getResult().getUser(), callback);
              } else {
                userErrorCallback(task, callback);
              }
            } catch (Exception ex) {
              userExceptionCallback(ex, callback);
            }
          }
        });
  }

  @ReactMethod
  public void reauthenticateWithCredentialForProvider(final String provider, final String authToken, final String authSecret, final Callback callback) {
    // TODO:
    Utils.todoNote(TAG, "reauthenticateWithCredentialForProvider", callback);
    // AuthCredential credential;
    // Log.d(TAG, "reauthenticateWithCredentialForProvider called with: " + provider);
  }

  @ReactMethod
  public void updateUserEmail(final String email, final Callback callback) {
    FirebaseUser user = mAuth.getCurrentUser();

    if (user != null) {
      user
          .updateEmail(email)
          .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
              try {
                if (task.isSuccessful()) {
                  Log.d(TAG, "User email address updated");
                  userCallback(mAuth.getCurrentUser(), callback);
                } else {
                  userErrorCallback(task, callback);
                }
              } catch (Exception ex) {
                userExceptionCallback(ex, callback);
              }
            }
          });
    } else {
      callbackNoUser(callback, true);
    }
  }

  @ReactMethod
  public void updateUserPassword(final String newPassword, final Callback callback) {
    FirebaseUser user = mAuth.getCurrentUser();

    if (user != null) {
      user.updatePassword(newPassword)
          .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
              try {
                if (task.isSuccessful()) {
                  Log.d(TAG, "User password updated");
                  userCallback(mAuth.getCurrentUser(), callback);
                } else {
                  userErrorCallback(task, callback);
                }
              } catch (Exception ex) {
                userExceptionCallback(ex, callback);
              }
            }
          });
    } else {
      callbackNoUser(callback, true);
    }
  }

  @ReactMethod
  public void sendPasswordResetWithEmail(final String email, final Callback callback) {
    mAuth.sendPasswordResetEmail(email)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
          @Override
          public void onComplete(@NonNull Task<Void> task) {
            try {
              if (task.isSuccessful()) {
                WritableMap resp = Arguments.createMap();
                resp.putString("status", "complete");
                callback.invoke(null, resp);
              } else {
                callback.invoke(task.getException().toString());
              }
            } catch (Exception ex) {
              userExceptionCallback(ex, callback);
            }
          }
        });
  }

  @ReactMethod
  public void deleteUser(final Callback callback) {
    FirebaseUser user = mAuth.getCurrentUser();
    if (user != null) {
      user.delete()
          .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
              try {
                if (task.isSuccessful()) {
                  Log.d(TAG, "User account deleted");
                  WritableMap resp = Arguments.createMap();
                  resp.putString("status", "complete");
                  resp.putString("msg", "User account deleted");
                  callback.invoke(null, resp);
                } else {
                  userErrorCallback(task, callback);
                }
              } catch (Exception ex) {
                userExceptionCallback(ex, callback);
              }
            }
          });
    } else {
      callbackNoUser(callback, true);
    }
  }

  @ReactMethod
  public void sendEmailVerification(final Callback callback) {
    FirebaseUser user = mAuth.getCurrentUser();

    if (user != null) {
      user.sendEmailVerification()
          .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
              try {
                if (task.isSuccessful()) {
                  WritableMap resp = Arguments.createMap();
                  resp.putString("status", "complete");
                  resp.putString("msg", "User verification email sent");
                  callback.invoke(null, resp);
                } else {
                  WritableMap err = Arguments.createMap();
                  err.putInt("errorCode", ERROR_SENDING_VERIFICATION_EMAIL);
                  err.putString("errorMessage", task.getException().getMessage());
                  callback.invoke(err);
                }
              } catch (Exception ex) {
                userExceptionCallback(ex, callback);
              }
            }
          });
    } else {
      callbackNoUser(callback, true);
    }
  }

  @ReactMethod
  public void getToken(final Callback callback) {
    FirebaseUser user = mAuth.getCurrentUser();

    if (user != null) {
      user.getToken(true)
          .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
            @Override
            public void onComplete(@NonNull Task<GetTokenResult> task) {
              try {
                if (task.isSuccessful()) {
                  String token = task.getResult().getToken();
                  WritableMap resp = Arguments.createMap();
                  resp.putString("status", "complete");
                  resp.putString("token", token);
                  callback.invoke(null, resp);
                } else {
                  WritableMap err = Arguments.createMap();
                  err.putInt("errorCode", ERROR_FETCHING_TOKEN);
                  err.putString("errorMessage", task.getException().getMessage());
                  callback.invoke(err);
                }
              } catch (Exception ex) {
                userExceptionCallback(ex, callback);
              }
            }
          });
    } else {
      callbackNoUser(callback, true);
    }
  }

  @ReactMethod
  public void updateUserProfile(ReadableMap props, final Callback callback) {
    FirebaseUser user = mAuth.getCurrentUser();

    if (user != null) {
      UserProfileChangeRequest.Builder profileBuilder = new UserProfileChangeRequest.Builder();

      Map<String, Object> m = Utils.recursivelyDeconstructReadableMap(props);

      if (m.containsKey("displayName")) {
        String displayName = (String) m.get("displayName");
        profileBuilder.setDisplayName(displayName);
      }

      if (m.containsKey("photoUri")) {
        String photoUriStr = (String) m.get("photoUri");
        Uri uri = Uri.parse(photoUriStr);
        profileBuilder.setPhotoUri(uri);
      }

      UserProfileChangeRequest profileUpdates = profileBuilder.build();

      user.updateProfile(profileUpdates)
          .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
              try {
                if (task.isSuccessful()) {
                  Log.d(TAG, "User profile updated");
                  userCallback(mAuth.getCurrentUser(), callback);
                } else {
                  userErrorCallback(task, callback);
                }
              } catch (Exception ex) {
                userExceptionCallback(ex, callback);
              }
            }
          });
    } else {
      callbackNoUser(callback, true);
    }
  }

  @ReactMethod
  public void signOut(final Callback callback) {
    mAuth.signOut();

    WritableMap resp = Arguments.createMap();
    resp.putString("status", "complete");
    resp.putString("msg", "User signed out");
    callback.invoke(null, resp);
  }

  @ReactMethod
  public void getCurrentUser(final Callback callback) {
    FirebaseUser user = mAuth.getCurrentUser();
    if (user == null) {
      callbackNoUser(callback, false);
    } else {
      Log.d("USRC", user.getUid());
      userCallback(user, callback);
    }
  }

  // TODO: Check these things
  @ReactMethod
  public void googleLogin(String IdToken, final Callback callback) {
    AuthCredential credential = GoogleAuthProvider.getCredential(IdToken, null);
    mAuth.signInWithCredential(credential)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
            try {
              if (task.isSuccessful()) {
                userCallback(task.getResult().getUser(), callback);
              } else {
                userErrorCallback(task, callback);
              }
            } catch (Exception ex) {
              userExceptionCallback(ex, callback);
            }
          }
        });
  }

  @ReactMethod
  public void facebookLogin(String Token, final Callback callback) {
    AuthCredential credential = FacebookAuthProvider.getCredential(Token);
    mAuth.signInWithCredential(credential)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
            try {
              if (task.isSuccessful()) {
                userCallback(task.getResult().getUser(), callback);
              } else {
                userErrorCallback(task, callback);
              }
            } catch (Exception ex) {
              userExceptionCallback(ex, callback);
            }
          }
        });
  }

  // Internal helpers
  private void userCallback(final FirebaseUser user, final Callback callback) {
    if (user != null) {
      user.getToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
        @Override
        public void onComplete(@NonNull Task<GetTokenResult> task) {
          try {
            if (task.isSuccessful()) {
              WritableMap userMap = getUserMap(user);
              userMap.putString("token", task.getResult().getToken());
              callback.invoke(null, userMap);
            } else {
              userErrorCallback(task, callback);
            }
          } catch (Exception ex) {
            userExceptionCallback(ex, callback);
          }
        }
      });
    } else {
      callbackNoUser(callback, true);
    }
  }

  private void userErrorCallback(Task task, final Callback onFail) {
    WritableMap error = Arguments.createMap();
    error.putInt("errorCode", task.getException().hashCode());
    error.putString("errorMessage", task.getException().getMessage());
    error.putString("allErrorMessage", task.getException().toString());

    onFail.invoke(error);
  }

  private void userExceptionCallback(Exception ex, final Callback onFail) {
    WritableMap error = Arguments.createMap();
    error.putInt("errorCode", ex.hashCode());
    error.putString("errorMessage", ex.getMessage());
    error.putString("allErrorMessage", ex.toString());

    onFail.invoke(error);
  }

  private WritableMap getUserMap(FirebaseUser user) {
    WritableMap userMap = Arguments.createMap();
    if (user != null) {
      final String email = user.getEmail();
      final String uid = user.getUid();
      final String provider = user.getProviderId();
      final String name = user.getDisplayName();
      final Boolean verified = user.isEmailVerified();
      final Uri photoUrl = user.getPhotoUrl();

      userMap.putString("email", email);
      userMap.putString("uid", uid);
      userMap.putString("providerId", provider);
      userMap.putBoolean("emailVerified", verified);

      if (name != null) {
        userMap.putString("name", name);
      }

      if (photoUrl != null) {
        userMap.putString("photoURL", photoUrl.toString());
      }
    } else {
      userMap.putString("msg", "no user");
    }

    return userMap;
  }
}


text:
package com.intellij.openapi.editor.impl.view;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.BitUtil;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.Rectangle2D;

/**
 * GlyphVector-based text fragment. Used for non-Latin text or when ligatures are enabled
 */
class ComplexTextFragment extends TextFragment {
  private static final Logger LOG = Logger.getInstance(ComplexTextFragment.class);
  private static final double CLIP_MARGIN = 1e4;

  @NotNull
  private final GlyphVector myGlyphVector;

  ComplexTextFragment(@NotNull char[] lineChars, int start, int end, boolean isRtl,
                      @NotNull Font font, @NotNull FontRenderContext fontRenderContext) {
    super(end - start);
    assert start >= 0;
    assert end <= lineChars.length;
    assert start < end;
    myGlyphVector = FontLayoutService.getInstance().layoutGlyphVector(font, fontRenderContext, lineChars, start, end, isRtl);
    int numChars = end - start;
    int numGlyphs = myGlyphVector.getNumGlyphs();
    float totalWidth = (float)myGlyphVector.getGlyphPosition(numGlyphs).getX();
    myCharPositions[numChars - 1] = totalWidth;
    int lastCharIndex = -1;
    float lastX = isRtl ? totalWidth : 0;
    float prevX = lastX;
    // Here we determine coordinates for boundaries between characters.
    // They will be used to place caret, last boundary coordinate is also defining the width of text fragment.
    //
    // We expect these positions to be ordered, so that when caret moves through text characters in some direction, corresponding text
    // offsets change monotonously (within the same-directionality fragment).
    //
    // Special case that we must account for is a ligature, when several adjacent characters are represented as a single glyph.
    // In a glyph vector this glyph is associated with the first character,
    // other characters either don't have an associated glyph, or they are associated with empty glyphs.
    // (in RTL case real glyph will be associated with first logical character, i.e. last visual character)
    for (int i = 0; i < numGlyphs; i++) {
      int visualGlyphIndex = isRtl ? numGlyphs - 1 - i : i;
      int charIndex = myGlyphVector.getGlyphCharIndex(visualGlyphIndex);
      if (charIndex > lastCharIndex) {
        Rectangle2D bounds = myGlyphVector.getGlyphLogicalBounds(visualGlyphIndex).getBounds2D();
        if (!bounds.isEmpty()) {
          if (charIndex > lastCharIndex + 1) {
            for (int j = Math.max(0, lastCharIndex); j < charIndex; j++) {
              setCharPosition(j, prevX + (lastX - prevX) * (j - lastCharIndex + 1) / (charIndex - lastCharIndex), isRtl, numChars);
            }
          }
          float newX = isRtl ? Math.min(lastX, (float)bounds.getMinX()) : Math.max(lastX, (float)bounds.getMaxX());
          newX = Math.max(0, Math.min(totalWidth, newX));
          setCharPosition(charIndex, newX, isRtl, numChars);
          prevX = lastX;
          lastX = newX;
          lastCharIndex = charIndex;
        }
      }
    }
    if (lastCharIndex < numChars - 1) {
      for (int j = Math.max(0, lastCharIndex); j < numChars - 1; j++) {
        setCharPosition(j, prevX + (lastX - prevX) * (j - lastCharIndex + 1) / (numChars - lastCharIndex), isRtl, numChars);
      }
    }
  }

  private void setCharPosition(int logicalCharIndex, float x, boolean isRtl, int numChars) {
    int charPosition = isRtl ? numChars - logicalCharIndex - 2 : logicalCharIndex;
    if (charPosition >= 0 && charPosition < numChars - 1) {
      myCharPositions[charPosition] = x;
    }
  }

  boolean isRtl() {
    return BitUtil.isSet(myGlyphVector.getLayoutFlags(), GlyphVector.FLAG_RUN_RTL);
  }

  // Drawing a portion of glyph vector using clipping might be not very effective
  // (we still pass all glyphs to the rendering code, and filtering by clipping might occur late in the processing,
  // on OS X larger number of glyphs passed for processing is known to slow down rendering significantly).
  // So we try to merge drawing of adjacent glyph vector fragments, if possible.
  private static ComplexTextFragment lastFragment;
  private static int lastStartColumn;
  private static int lastEndColumn;
  private static Color lastColor;
  private static float lastStartX;
  private static float lastEndX;
  private static float lastY;

  @SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod")
  @Override
  public void draw(Graphics2D g, float x, float y, int startColumn, int endColumn) {
    assert startColumn >= 0;
    assert endColumn <= myCharPositions.length;
    assert startColumn < endColumn;

    Color color = g.getColor();
    assert color != null;
    float newX = x - getX(startColumn) + getX(endColumn);
    if (lastFragment == this && lastEndColumn == startColumn && lastEndX == x && lastY == y && color.equals(lastColor)) {
      lastEndColumn = endColumn;
      lastEndX = newX;
      return;
    }

    flushDrawingCache(g);
    lastFragment = this;
    lastStartColumn = startColumn;
    lastEndColumn = endColumn;
    lastColor = color;
    lastStartX = x;
    lastEndX = newX;
    lastY = y;
  }

  private void doDraw(Graphics2D g, float x, float y, int startColumn, int endColumn) {
    updateStats(endColumn - startColumn, myCharPositions.length);
    if (startColumn == 0 && endColumn == myCharPositions.length) {
      g.drawGlyphVector(myGlyphVector, x, y);
    }
    else {
      Shape savedClip = g.getClip();
      float startX = x - getX(startColumn);
      // We define clip region here assuming that glyphs do not extend further than CLIP_MARGIN pixels from baseline
      // vertically (both up and down) and horizontally (from the region defined by glyph vector's total advance)
      double xMin = x - (startColumn == 0 ? CLIP_MARGIN : 0);
      double xMax = startX + getX(endColumn) + (endColumn == myCharPositions.length ? CLIP_MARGIN : 0);
      double yMin = y - CLIP_MARGIN;
      double yMax = y + CLIP_MARGIN;
      g.clip(new Rectangle2D.Double(xMin, yMin, xMax - xMin, yMax - yMin));
      g.drawGlyphVector(myGlyphVector, startX, y);
      g.setClip(savedClip);
    }
  }

  public static void flushDrawingCache(Graphics2D g) {
    if (lastFragment != null) {
      g.setColor(lastColor);
      lastFragment.doDraw(g, lastStartX, lastY, lastStartColumn, lastEndColumn);
      lastFragment = null;
    }
  }

  private static long ourDrawingCount;
  private static long ourCharsProcessed;
  private static long ourGlyphsProcessed;

  private static void updateStats(int charCount, int glyphCount) {
    if (!LOG.isDebugEnabled()) return;
    ourCharsProcessed += charCount;
    ourGlyphsProcessed += glyphCount;
    if (++ourDrawingCount == 10000) {
      LOG.debug("Text rendering stats: " + ourCharsProcessed + " chars, " + ourGlyphsProcessed + " glyps, ratio - " +
                ((float) ourGlyphsProcessed) / ourCharsProcessed);
      ourDrawingCount = 0;
      ourCharsProcessed = 0;
      ourGlyphsProcessed = 0;
    }
  }
}


text:
<?php
namespace Lead\Net\Http;

use Lead\Set\Set;
use Lead\Net\Headers;

/**
 * Support Multipart message with HTTP headers as well as single part message.
 */
class MixedPart extends \Lead\Net\MixedPart
{
    /**
     * The constructor
     *
     * @param array $config The config array.
     */
    public function __construct($config = [])
    {
        $config += [
            'headers' => null
        ];
        $config['headers'] = is_object($config['headers']) ?  $config['headers'] : new Headers([
            'data'      => $config['headers'],
            'length'    => 0,
            'maxLength' => 2998
        ]);
        parent::__construct($config);
    }

}


text:
from ducktape.services.service import Service
from ducktape.tests.test import Test
from ducktape.mark import parametrize
from ducktape.mark import matrix

from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.services.kafka import KafkaService
from kafkatest.services.performance import ProducerPerformanceService, EndToEndLatencyService, ConsumerPerformanceService

TOPIC_REP_ONE = "topic-replication-factor-one"
TOPIC_REP_THREE = "topic-replication-factor-three"
DEFAULT_RECORD_SIZE = 100  # bytes

class Benchmark(Test):
    """A benchmark of Kafka producer/consumer performance. This replicates the test
    run here:
    https://engineering.linkedin.com/kafka/benchmarking-apache-kafka-2-million-writes-second-three-cheap-machines
    """
    def __init__(self, test_context):
        super(Benchmark, self).__init__(test_context)
        self.num_zk = 1
        self.num_brokers = 3
        self.topics = {
            TOPIC_REP_ONE: {'partitions': 6, 'replication-factor': 1},
            TOPIC_REP_THREE: {'partitions': 6, 'replication-factor': 3}
        }

        self.zk = ZookeeperService(test_context, self.num_zk)

        self.msgs_large = 10000000
        self.batch_size = 8*1024
        self.buffer_memory = 64*1024*1024
        self.msg_sizes = [10, 100, 1000, 10000, 100000]
        self.target_data_size = 128*1024*1024
        self.target_data_size_gb = self.target_data_size/float(1024*1024*1024)

    def setUp(self):
        self.zk.start()

    def start_kafka(self, security_protocol, interbroker_security_protocol):
        self.kafka = KafkaService(
            self.test_context, self.num_brokers,
            self.zk, security_protocol=security_protocol,
            interbroker_security_protocol=interbroker_security_protocol, topics=self.topics)
        self.kafka.start()

    @parametrize(acks=1, topic=TOPIC_REP_ONE)
    @parametrize(acks=1, topic=TOPIC_REP_THREE)
    @parametrize(acks=-1, topic=TOPIC_REP_THREE)
    @parametrize(acks=1, topic=TOPIC_REP_THREE, num_producers=3)
    @matrix(acks=[1], topic=[TOPIC_REP_THREE], message_size=[10, 100, 1000, 10000, 100000], security_protocol=['PLAINTEXT', 'SSL'])
    def test_producer_throughput(self, acks, topic, num_producers=1, message_size=DEFAULT_RECORD_SIZE, security_protocol='PLAINTEXT'):
        """
        Setup: 1 node zk + 3 node kafka cluster
        Produce ~128MB worth of messages to a topic with 6 partitions. Required acks, topic replication factor,
        security protocol and message size are varied depending on arguments injected into this test.

        Collect and return aggregate throughput statistics after all messages have been acknowledged.
        (This runs ProducerPerformance.java under the hood)
        """
        self.start_kafka(security_protocol, security_protocol)
        # Always generate the same total amount of data
        nrecords = int(self.target_data_size / message_size)

        self.producer = ProducerPerformanceService(
            self.test_context, num_producers, self.kafka, topic=topic,
            num_records=nrecords, record_size=message_size,  throughput=-1,
            settings={
                'acks': acks,
                'batch.size': self.batch_size,
                'buffer.memory': self.buffer_memory})
        self.producer.run()
        return compute_aggregate_throughput(self.producer)

    @parametrize(security_protocol='SSL', interbroker_security_protocol='PLAINTEXT')
    @matrix(security_protocol=['PLAINTEXT', 'SSL'])
    def test_long_term_producer_throughput(self, security_protocol, interbroker_security_protocol=None):
        """
        Setup: 1 node zk + 3 node kafka cluster
        Produce 10e6 100 byte messages to a topic with 6 partitions, replication-factor 3, and acks=1.

        Collect and return aggregate throughput statistics after all messages have been acknowledged.

        (This runs ProducerPerformance.java under the hood)
        """
        if interbroker_security_protocol is None:
            interbroker_security_protocol = security_protocol
        self.start_kafka(security_protocol, interbroker_security_protocol)
        self.producer = ProducerPerformanceService(
            self.test_context, 1, self.kafka,
            topic=TOPIC_REP_THREE, num_records=self.msgs_large, record_size=DEFAULT_RECORD_SIZE,
            throughput=-1, settings={'acks': 1, 'batch.size': self.batch_size, 'buffer.memory': self.buffer_memory},
            intermediate_stats=True
        )
        self.producer.run()

        summary = ["Throughput over long run, data > memory:"]
        data = {}
        # FIXME we should be generating a graph too
        # Try to break it into 5 blocks, but fall back to a smaller number if
        # there aren't even 5 elements
        block_size = max(len(self.producer.stats[0]) / 5, 1)
        nblocks = len(self.producer.stats[0]) / block_size

        for i in range(nblocks):
            subset = self.producer.stats[0][i*block_size:min((i+1)*block_size, len(self.producer.stats[0]))]
            if len(subset) == 0:
                summary.append(" Time block %d: (empty)" % i)
                data[i] = None
            else:
                records_per_sec = sum([stat['records_per_sec'] for stat in subset])/float(len(subset))
                mb_per_sec = sum([stat['mbps'] for stat in subset])/float(len(subset))

                summary.append(" Time block %d: %f rec/sec (%f MB/s)" % (i, records_per_sec, mb_per_sec))
                data[i] = throughput(records_per_sec, mb_per_sec)

        self.logger.info("\n".join(summary))
        return data

    @parametrize(security_protocol='SSL', interbroker_security_protocol='PLAINTEXT')
    @matrix(security_protocol=['PLAINTEXT', 'SSL', 'SASL_PLAINTEXT', 'SASL_SSL'])
    def test_end_to_end_latency(self, security_protocol, interbroker_security_protocol=None):
        """
        Setup: 1 node zk + 3 node kafka cluster
        Produce (acks = 1) and consume 10e3 messages to a topic with 6 partitions and replication-factor 3,
        measuring the latency between production and consumption of each message.

        Return aggregate latency statistics.

        (Under the hood, this simply runs EndToEndLatency.scala)
        """
        if interbroker_security_protocol is None:
            interbroker_security_protocol = security_protocol
        self.start_kafka(security_protocol, interbroker_security_protocol)
        self.logger.info("BENCHMARK: End to end latency")
        self.perf = EndToEndLatencyService(
            self.test_context, 1, self.kafka,
            topic=TOPIC_REP_THREE, num_records=10000
        )
        self.perf.run()
        return latency(self.perf.results[0]['latency_50th_ms'],  self.perf.results[0]['latency_99th_ms'], self.perf.results[0]['latency_999th_ms'])

    @parametrize(security_protocol='PLAINTEXT', new_consumer=False)
    @parametrize(security_protocol='SSL', interbroker_security_protocol='PLAINTEXT')
    @matrix(security_protocol=['PLAINTEXT', 'SSL'])
    def test_producer_and_consumer(self, security_protocol, interbroker_security_protocol=None, new_consumer=True):
        """
        Setup: 1 node zk + 3 node kafka cluster
        Concurrently produce and consume 10e6 messages with a single producer and a single consumer,
        using new consumer if new_consumer == True

        Return aggregate throughput statistics for both producer and consumer.

        (Under the hood, this runs ProducerPerformance.java, and ConsumerPerformance.scala)
        """
        if interbroker_security_protocol is None:
            interbroker_security_protocol = security_protocol
        self.start_kafka(security_protocol, interbroker_security_protocol)
        num_records = 10 * 1000 * 1000  # 10e6

        self.producer = ProducerPerformanceService(
            self.test_context, 1, self.kafka,
            topic=TOPIC_REP_THREE,
            num_records=num_records, record_size=DEFAULT_RECORD_SIZE, throughput=-1,
            settings={'acks': 1, 'batch.size': self.batch_size, 'buffer.memory': self.buffer_memory}
        )
        self.consumer = ConsumerPerformanceService(
            self.test_context, 1, self.kafka, topic=TOPIC_REP_THREE, new_consumer=new_consumer, messages=num_records)
        Service.run_parallel(self.producer, self.consumer)

        data = {
            "producer": compute_aggregate_throughput(self.producer),
            "consumer": compute_aggregate_throughput(self.consumer)
        }
        summary = [
            "Producer + consumer:",
            str(data)]
        self.logger.info("\n".join(summary))
        return data

    @parametrize(security_protocol='PLAINTEXT', new_consumer=False)
    @parametrize(security_protocol='SSL', interbroker_security_protocol='PLAINTEXT')
    @matrix(security_protocol=['PLAINTEXT', 'SSL'])
    def test_consumer_throughput(self, security_protocol, interbroker_security_protocol=None, new_consumer=True, num_consumers=1):
        """
        Consume 10e6 100-byte messages with 1 or more consumers from a topic with 6 partitions
        (using new consumer iff new_consumer == True), and report throughput.
        """
        if interbroker_security_protocol is None:
            interbroker_security_protocol = security_protocol
        self.start_kafka(security_protocol, interbroker_security_protocol)
        num_records = 10 * 1000 * 1000  # 10e6

        # seed kafka w/messages
        self.producer = ProducerPerformanceService(
            self.test_context, 1, self.kafka,
            topic=TOPIC_REP_THREE,
            num_records=num_records, record_size=DEFAULT_RECORD_SIZE, throughput=-1,
            settings={'acks': 1, 'batch.size': self.batch_size, 'buffer.memory': self.buffer_memory}
        )
        self.producer.run()

        # consume
        self.consumer = ConsumerPerformanceService(
            self.test_context, num_consumers, self.kafka,
            topic=TOPIC_REP_THREE, new_consumer=new_consumer, messages=num_records)
        self.consumer.group = "test-consumer-group"
        self.consumer.run()
        return compute_aggregate_throughput(self.consumer)

def throughput(records_per_sec, mb_per_sec):
    """Helper method to ensure uniform representation of throughput data"""
    return {
        "records_per_sec": records_per_sec,
        "mb_per_sec": mb_per_sec
    }

def latency(latency_50th_ms, latency_99th_ms, latency_999th_ms):
    """Helper method to ensure uniform representation of latency data"""
    return {
        "latency_50th_ms": latency_50th_ms,
        "latency_99th_ms": latency_99th_ms,
        "latency_999th_ms": latency_999th_ms
    }

def compute_aggregate_throughput(perf):
    """Helper method for computing throughput after running a performance service."""
    aggregate_rate = sum([r['records_per_sec'] for r in perf.results])
    aggregate_mbps = sum([r['mbps'] for r in perf.results])

    return throughput(aggregate_rate, aggregate_mbps)


text:
var assert = require('assert'),
	should = require('should');
	Incidents = require('../lib/incidents.js')();

describe ('incidents test', function() {

	describe ('get incidents', function() {

		it ('should return a collection of incidents with time to resolve', function(done) {
			var limit = 1;
			var offset = 0;
			Incidents.getIncidents('PJXJWYN','2015-01-01','2015-01-15', limit,offset, function(error,response){
				console.log('callback response = ' + JSON.stringify(response));
				assert(response.incidents.should.be.instanceof(Array));
				assert.equal(1, response.incidents.length);
				assert(response.mean_ttr != null);
				done();
			});
		});
	});
});


text:
package com.twitter.zipkin.hadoop

import org.specs.Specification
import com.twitter.zipkin.gen
import com.twitter.scalding._
import gen.AnnotationType
import scala.collection.JavaConverters._
import collection.mutable.HashMap
import java.nio.ByteBuffer
import sources.{PreprocessedSpanSource, PrepNoNamesSpanSource, Util}

/**
 * Tests that MemcacheRequest finds, per service and memcache request type, the number
 * of memcache requests
 */

class MemcacheRequestSpec extends Specification with TupleConversions {

  noDetailedDiffs()

  implicit val dateRange = DateRange(RichDate(123), RichDate(321))

  val endpoint = new gen.Endpoint(123, 666, "service")
  val endpoint1 = new gen.Endpoint(123, 666, "service1")
  val endpoint2 = new gen.Endpoint(123, 666, "service2")
  val span = new gen.SpanServiceName(12345, "methodcall", 666,
    List(new gen.Annotation(1000, "cs").setHost(endpoint), new gen.Annotation(2000, "sr").setHost(endpoint)).asJava,
    List[gen.BinaryAnnotation]().asJava, "service")
  val span1 = new gen.Span(12345, "methodcall", 666,
    List(new gen.Annotation(1000, "cs").setHost(endpoint1), new gen.Annotation(4000, "cr").setHost(endpoint1)).asJava,
    List(new gen.BinaryAnnotation("memcached.keys", ByteBuffer.allocate(4).putInt(0, 10), AnnotationType.BOOL)).asJava)
  val span2 = new gen.SpanServiceName(12346, "methodcall", 666,
    List(new gen.Annotation(1000, "cs").setHost(endpoint), new gen.Annotation(2000, "sr").setHost(endpoint)).asJava,
    List[gen.BinaryAnnotation]().asJava, "service")
  val span3 = new gen.Span(123456, "methodcall", 666,
    List(new gen.Annotation(1000, "cs").setHost(endpoint1), new gen.Annotation(4000, "cr").setHost(endpoint1)).asJava,
    List(new gen.BinaryAnnotation("memcached.keys", ByteBuffer.allocate(4).putInt(0, 10), AnnotationType.BOOL)).asJava)
  val span4 = new gen.Span(123456, "methodcall", 666,
    List(new gen.Annotation(1000, "cs").setHost(endpoint1), new gen.Annotation(4000, "cr").setHost(endpoint1)).asJava,
    List(new gen.BinaryAnnotation("foobar", ByteBuffer.allocate(4).putInt(0, 10), AnnotationType.BOOL)).asJava)

  "MemcacheRequest" should {
    "find spans with memcache requests and their service names and labels" in {
      JobTest("com.twitter.zipkin.hadoop.MemcacheRequest").
        arg("input", "inputFile").
        arg("output", "outputFile").
        arg("date", "2012-01-01T01:00").
        source(PrepNoNamesSpanSource(), Util.repeatSpan(span1, 10, 100, 0) ++ Util.repeatSpan(span3, 2, 200, 300) ++ Util.repeatSpan(span3, 0, 1000, 500) ++ Util.repeatSpan(span4, 2, 1000, 11) ).
        source(PreprocessedSpanSource(), Util.repeatSpan(span, 12, 0, 20) ++ Util.repeatSpan(span2, 2, 300, 400) ++ Util.repeatSpan(span2, 0, 500, 100000)).
        sink[(String, Long)](Tsv("outputFile")) {
        val counts = new HashMap[String, Long]()
        counts("service") = 0
        counts("service1") = 0
        outputBuffer => outputBuffer foreach { e =>
          counts(e._1) += e._2
            println(e)
        }
        counts("service") mustEqual 2
        counts("service1") mustEqual 0
      }.run.finish
    }
  }
}


text:
<!-- From: file:/Users/gmarques/Documents/workspaces/inSPorteGitHub/InsPorte_android/CardsUILib/AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.fima.cardsui">

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>

</manifest>


text:
package com.clearlyspam23.GLE.GUI.util;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager2;

public class AspectRatioLayout implements LayoutManager2 {

	private Component component;

	@Override
	public void addLayoutComponent(String arg0, Component arg1) {
		component = arg1;
	}

	@Override
	public void layoutContainer(Container target) {
		if(component==null)
			return;
		Insets insets = target.getInsets();
		double top = insets.top;
		double bottom = target.getHeight() - insets.bottom;
		double left = insets.left;
		double right = target.getWidth() - insets.right;
		Dimension pref = component.getPreferredSize();
		double ratioPref = pref.getWidth()/pref.getHeight();
		double ratioCurr = (right-left)/(bottom-top);
		int width = 0;
		int height = 0;
		if(ratioCurr>ratioPref){
			//this means that y is the smaller dimension, expand as far as we can vertically
			height = (int) Math.round(bottom-top);
			width = (int) Math.round(height*ratioPref);
		}
		else {
			//this means that x is the smaller dimension, expand as far as we can horizontally
			width = (int) Math.round(right-left);
			height = (int) Math.round(width*pref.getHeight()/pref.getWidth());
		}
		component.setBounds((int)((right-left)/2-width/2), (int)((bottom-top)/2-height/2), width, height);
	}

	@Override
	public Dimension minimumLayoutSize(Container arg0) {
		if(component!=null)
			return component.getMinimumSize();
		return new Dimension();
	}

	@Override
	public Dimension preferredLayoutSize(Container arg0) {
		if(component!=null)
			return component.getPreferredSize();
		return new Dimension();
	}

	@Override
	public void removeLayoutComponent(Component arg0) {
		if(arg0==component)
			component = null;

	}

	@Override
	public void addLayoutComponent(Component arg0, Object arg1) {
		component = arg0;
	}

	@Override
	public float getLayoutAlignmentX(Container arg0) {
		return 0.5f;
	}

	@Override
	public float getLayoutAlignmentY(Container arg0) {
		return 0.5f;
	}

	@Override
	public void invalidateLayout(Container arg0) {

	}

	@Override
	public Dimension maximumLayoutSize(Container arg0) {
		return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
	}

}


text:
'use strict';

var utils = module.exports,
    rules = [],
    logger = { ok: function () {}, error: function () {} };

// Handling rules
//////////////////

function isValidExtendedRule(rule) {
    return ( typeof rule       === 'object' &&
             typeof rule.url   === 'string' &&
             ( typeof rule.delay === 'number' ||
               typeof rule.delay === 'string' ) &&
             typeof rule.rewrite === 'string'
           );
}

function isValidSimpleRule(rule) {
    return ( typeof rule       === 'object' &&
             typeof rule.url   === 'string' &&
             typeof rule.delay === 'number'
           );
}

utils.registerRule = function (rule) {

    if (!isValidSimpleRule(rule) && !isValidExtendedRule(rule)) {
        return false;
    }

    rules.push({ url     : new RegExp(rule.url)
               , delay   : rule.delay
               , rewrite : rule.rewrite
               });

    return '"' + rule.url + '" by: ' + rule.delay + ' ms' +
            (typeof rule.rewrite === 'undefined' ?
                 ''
               : ' to: ' + rule.rewrite
            );
};

utils.defaultRule = { url     : '^/delay/([0-9]+)/(.*)$'
                    , delay   : '$1'
                    , rewrite : '/$2'
                    };

/* These functions aid in testing this module */
utils.getRules = function () {
    return rules;
};

utils.clearRules = function () {
    rules = [];
};

/* Set up the logging */
utils.setLogger = function (externalLogger) {
    logger = externalLogger;
};

/* This is the snippet which is used as the middleware in the external
 * Gruntfile functions aid in testing this module.
 */
function logAndProxy(url, delay, next) {
    return function () {
        logger.ok('Proxying to "' + url + '" after ' + delay + ' ms.');
        next();
    };
}

utils.delayRequest = function (req, res, next) {
    var proxied = false;
    for (var ii = 0; ii < rules.length; ii++) {
        if (rules[ii].url.test(req.url)) {
            // If there was a match, then schedule progress after the delay

            var rule      = rules[ii],
                isInError = false;

            var delay = rule.delay, destUrl = req.url;

            if (typeof rule.rewrite === 'string') {
                destUrl = destUrl.replace(rule.url, rule.rewrite);

                // This is an extended rule which requires re-writing
                if (typeof rule.delay === 'string') {
                    delay = parseInt(req.url.replace(rule.url, rule.delay));

                    if (isNaN(delay)) {
                        logger.error
                            ( 'Could not parse the delay "' + rule.delay
                            + '" from URL: "' + req.url + '"'
                            );
                        isInError = true;
                    }
                } // Else the delay was a fixed number
            }

            if (!isInError) {

                req.url = destUrl;
                logger.ok
                   ( 'Will proxy to "'
                   + req.url
                   + '" after '
                   + delay
                   + ' ms.'
                   );

                setTimeout(logAndProxy(req.url, delay, next), delay);
                proxied = true;
            }

            // Do no proxy the same call twice.
            // Proxy after the first rule match rule match.
            break;
        }
    }

    // If there was no match, continue immediately
    if (!proxied) {
        next();
    }
};


text:
See the `plain-js` branch to see a version of the app written in vanilla JavaScript :)

Also, check out a working [demo on GitHub pages](https://www.ccampo.me/NBodyJS/)

## Background

In an n-body gravity simulator, the magnitude of the force `F[i]` acting on each body `i`, in a system of `n` bodies, is determined by Newton's law of universal gravitation,

    F[i] = Sum(G  * (m[i] * m[j]) / r[i, j]^2), where j = 1....n and j != i

where `G` is the gravitational constant, `m[i]` is the mass of body `i`, `m[j]` is the mass of body `j`, and `r[i, j]` is the distance from `i` to `j`.  Of course, force is a vector quantity, so the force vector with magnitude `F[i]` is just a unit vector in the direction from `i` to `j`, scaled by `F[i]`.

In the case of gravity simulations, the forces due to gravity get exceedingly large as bodies get closer to each other (due to the 1/r2 nature of the gravitational force), and hence bodies tend to rapidly accelerate and zoom off when they seemingly "collide". To compensate for this, a softening length `R^2` has been applied in the gravity calculation to prevent bodies from zipping off into the abyss when they get near each-other.  Also, `G` has been set to 1 for simplicity in NBodyJS.

To compute the positions and velocities of all of the bodies, NBodyJS utilizes the [**Velocity Verlet**](http://en.wikipedia.org/wiki/Verlet_integration#Velocity_Verlet) method of numerical integration.  Verlet integration is a second-order method, which offers more stability than simpler, first order solutions such as [Euler's method](http://en.wikipedia.org/wiki/Euler_method), yet at no significant additional computational cost.

For the algorithm to work, first you need to specify the initial conditions of the simulation; namely the initial positions and velocities of all the bodies at some start time `t`.  Then, the Velocity Verlet algorithm consists of the following steps:

1. Calculate the acceleration `a(t)` of each body due to gravity (or whatever force(s) you want) at time `t`, using Newton's laws.
2. Calculate the positon `x(t + dt)` of each body at time `t + dt` (where `dt` is a small time step), using the approximation `x(t + dt) = x(t) + v(t)*dt + a(t) * dt^2 / 2`.
3. Calculate the acceleration `a(t + dt)`, again using Newton's laws and the forces in play.
4. Calculate the velocity `v(t + dt)` using the approximation `v(t + dt) = v(t) + (a(t) + a(t + dt)) * dt / 2`

This algorithm is executed every time you take a time step, `dt`.  Since every body exerts a force on every other body, computing the accelerations is done in O(N2) time.  There are quicker, yet similarily accurate algorithms out there, so feel free to implement your own version if you feel like experimenting!  Also note that this method can be used to integrate Newton's laws for nearly any force(s), not just gravity!

NBodyJS utilizes the HTML5 canvas element for display, and [`kotlin-js`](https://kotlinlang.org/docs/tutorials/javascript/kotlin-to-javascript/kotlin-to-javascript.html) to transpile Kotlin to Javascript.

You can view NBodyJS in action on [GitHub Pages](http://ccampo133.github.io/NBodyJS)!

For more information on N-body simulations in general, see [Scholarpedia](http://www.scholarpedia.org/article/N-body_simulations_(gravitational)).

## Controls

* Click and fling to add new particles.
* Hold-click and use the scroll wheel (or up/down arrows) to increase/decrease mass (and radius).
* Press 't' to toggle trails, 'p' to pause, 'c' to clear, and 'r' reset to the initial conditions.

## Development

### To Build

For *nix/OS X:

    ./gradlew build

For Windows:

    gradlew.bat build

### To Run

First build (see above), and then to run the application, open `build/web/index.html`.

## License
This code is released under [The BSD License](https://github.com/ccampo133/NBodyJS/blob/gh-pages/LICENSE.txt).

Copyright © 2017 Christopher J. Campo. All Rights Reserved.


text:
package io.encoded.jersik.java.codegen

import java.io.File
import java.io.FileWriter

import scala.io.Source

import io.encoded.jersik.schema.SchemaParser

object JavaCodeGenerator {

  def generateModule(schemaFile: File, targetDir: File, generateClient: Boolean = true, generateServer: Boolean = false): Unit = {
    val source = Source.fromFile(schemaFile).mkString("")
    val parseResult = SchemaParser.parseModule(source)
    if (!parseResult.successful)
      throw new RuntimeException("Could not parse "+ schemaFile +": "+ parseResult)
    val module = parseResult.get
    val moduleDir = new File(targetDir, module.name.replace('.', File.separatorChar))
    moduleDir.mkdirs()
    for (enum <- module.enums) {
      val enumFile = new File(moduleDir, enum.name +".java")
      val enumCode = new JavaEnum(module.name, enum).toCode
      writeFile(enumFile, enumCode)
    }
    for (struct <- module.structs) {
      val structFile = new File(moduleDir, struct.name +".java")
      val structCode = new JavaStruct(module.name, struct).toCode
      writeFile(structFile, structCode)
      val structCodecFile = new File(moduleDir, struct.name +"Codec.java")
      val structCodecCode = new JavaStructCodec(module, struct).toCode
      writeFile(structCodecFile, structCodecCode)
    }
    for (service <- module.services) {
      val serviceFile = new File(moduleDir, service.name +".java")
      val serviceCode = new JavaService(module.name, service).toCode
      writeFile(serviceFile, serviceCode)
      if (generateServer) {
        val operationMapFile = new File(moduleDir, service.name +"OperationMap.java")
        val operationMapCode = new JavaServiceOperationMap(module.name, service).toCode
        writeFile(operationMapFile, operationMapCode)
      }
      if (generateClient) {
        val clientFile = new File(moduleDir, service.name +"Client.java")
        val clientCode = new JavaServiceClient(module.name, service).toCode
        writeFile(clientFile, clientCode)
      }
    }
  }

  private def writeFile(file: File, body: String) = {
    val writer = new FileWriter(file)
    writer.write(body)
    writer.close()
  }

}


text:
package com.hazelcast.jca.examples;

import javax.ejb.ApplicationException;

@ApplicationException(rollback = true)
public class CustomRuntimeException extends RuntimeException {
    public CustomRuntimeException(String s) {
        super(s);
    }
}


text:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

#ifndef __PROCESS_ADDRESS_HPP__
#define __PROCESS_ADDRESS_HPP__

#include <stdint.h>
#ifndef __WINDOWS__
#include <unistd.h>
#endif // __WINDOWS__

#ifndef __WINDOWS__
#include <arpa/inet.h>
#endif // __WINDOWS__

#include <glog/logging.h>

#ifndef __WINDOWS__
#include <sys/un.h>
#endif // __WINDOWS__

#include <ostream>

#include <boost/functional/hash.hpp>

#include <stout/abort.hpp>
#include <stout/check.hpp>
#include <stout/ip.hpp>
#include <stout/net.hpp>
#include <stout/stringify.hpp>
#include <stout/unreachable.hpp>

namespace process {
namespace network {

namespace inet {
class Address;
} // namespace inet {

#ifndef __WINDOWS__
namespace unix {
class Address;
} // namespace unix {
#endif // __WINDOWS__

// Represents a network "address", subsuming the `struct addrinfo` and
// `struct sockaddr` that typically is used to encapsulate an address.
//
// TODO(jieyu): Move this class to stout.
class Address
{
public:
  enum class Family {
    INET,
#ifndef __WINDOWS__
    UNIX
#endif // __WINDOWS__
  };

  static Try<Address> create(const sockaddr_storage& storage)
  {
    switch (storage.ss_family) {
      case AF_INET:
#ifndef __WINDOWS__
      case AF_UNIX:
#endif // __WINDOWS__
        return Address(storage);
      default:
        return Error("Unsupported family: " + stringify(storage.ss_family));
    }
  }

  Family family() const
  {
    switch (sockaddr.storage.ss_family) {
      case AF_INET:
        return Family::INET;
#ifndef __WINDOWS__
      case AF_UNIX:
        return Family::UNIX;
#endif // __WINDOWS__
      default:
        ABORT("Unexpected family: " + stringify(sockaddr.storage.ss_family));
    }
  }

  // Returns the storage size depending on the family of this address.
  size_t size() const
  {
    switch (family()) {
      case Family::INET:
        return sizeof(sockaddr_in);
#ifndef __WINDOWS__
      case Family::UNIX:
        return sizeof(sockaddr_un);
#endif // __WINDOWS__
    }
    UNREACHABLE();
  }

  operator sockaddr_storage() const
  {
    return sockaddr.storage;
  }

private:
  friend class inet::Address;
#ifndef __WINDOWS__
  friend class unix::Address;
#endif // __WINDOWS__

  template <typename AddressType>
  friend Try<AddressType> convert(Try<Address>&& address);
  friend std::ostream& operator<<(std::ostream& stream, const Address& address);

  Address(const sockaddr_storage& storage)
  {
    sockaddr.storage = storage;
  }

  union {
    sockaddr_storage storage;
    sockaddr_in in;
#ifndef __WINDOWS__
    sockaddr_un un;
#endif // __WINDOWS__
  } sockaddr;
};

// Helper for converting between Address and other types.
template <typename AddressType>
Try<AddressType> convert(Try<Address>&& address);

template <>
inline Try<Address> convert(Try<Address>&& address)
{
  return address;
}

namespace inet {

class Address
{
public:
  Address(const net::IP& _ip, uint16_t _port)
    : ip(_ip), port(_port) {}

  Address(const sockaddr_in& in)
    : Address(net::IP(in.sin_addr), ntohs(in.sin_port)) {}

  static Address LOOPBACK_ANY() { return Address(net::IP(INADDR_LOOPBACK), 0); }

  static Address ANY_ANY() { return Address(net::IP(INADDR_ANY), 0); }

  /**
   * Returns the hostname of this address's IP.
   *
   * @returns the hostname of this address's IP.
   */
  // TODO(jmlvanre): Consider making this return a Future in order to
  // deal with slow name resolution.
  Try<std::string> hostname() const
  {
    const Try<std::string> hostname = ip == net::IP(INADDR_ANY)
      ? net::hostname()
      : net::getHostname(ip);

    if (hostname.isError()) {
      return Error(hostname.error());
    }

    return hostname.get();
  }

  bool operator<(const Address& that) const
  {
    if (ip == that.ip) {
      return port < that.port;
    } else {
      return ip < that.ip;
    }
  }

  bool operator>(const Address& that) const
  {
    if (ip == that.ip) {
      return port > that.port;
    } else {
      return ip > that.ip;
    }
  }

  bool operator==(const Address& that) const
  {
    return (ip == that.ip && port == that.port);
  }

  bool operator!=(const Address& that) const
  {
    return !(*this == that);
  }

  bool operator==(const network::Address& that) const;

  operator network::Address() const
  {
    union {
      sockaddr_storage storage;
      sockaddr_in in;
    } sockaddr;
    memset(&sockaddr.storage, 0, sizeof(sockaddr_storage));
    sockaddr.in.sin_family = AF_INET;
    sockaddr.in.sin_addr = ip.in().get();
    sockaddr.in.sin_port = htons(port);
    return network::Address(sockaddr.storage);
  }

  // TODO(benh): Use a sockaddr_in here like we do for unix::Address.
  net::IP ip;
  uint16_t port;
};

inline std::ostream& operator<<(std::ostream& stream, const Address& address)
{
  stream << address.ip << ":" << address.port;
  return stream;
}

} // namespace inet {

template <>
inline Try<inet::Address> convert(Try<Address>&& address)
{
  if (address.isError()) {
    return Error(address.error());
  }

  if (address->family() == Address::Family::INET) {
    return inet::Address(address->sockaddr.in);
  }

  return Error("Unexpected address family");
}

namespace inet {

inline bool Address::operator==(const network::Address& that) const
{
  Try<Address> address = convert<Address>(that);
  if (address.isError()) {
    return false;
  }
  return *this == address.get();
}

} // namespace inet {

#ifndef __WINDOWS__
namespace unix {

class Address
{
public:
  static Try<Address> create(const std::string& path)
  {
    sockaddr_un un;

    const size_t PATH_LENGTH = sizeof(un.sun_path);

    if (path.length() >= PATH_LENGTH) {
      return Error("Path too long, must be less than " +
                   stringify(PATH_LENGTH) + " bytes");
    }

    un.sun_family = AF_UNIX;
    memcpy(un.sun_path, path.c_str(), path.length() + 1);

    return Address(un);
  }

  Address(const sockaddr_un& un)
    : sockaddr() // Zero initialize.
  {
    sockaddr.un = un;
  }

  std::string path() const
  {
    if (sockaddr.un.sun_path[0] == '\0') {
      return '\0' + std::string(sockaddr.un.sun_path + 1);
    }

    return std::string(sockaddr.un.sun_path);
  }

  operator network::Address() const
  {
    return network::Address(sockaddr.storage);
  }

private:
  friend std::ostream& operator<<(
      std::ostream& stream,
      const Address& address);

  union {
    sockaddr_storage storage;
    sockaddr_un un;
  } sockaddr;
};

inline std::ostream& operator<<(
    std::ostream& stream,
    const Address& address)
{
  std::string path = address.path();
  if (!path.empty() && path[0] == '\0') {
    path[0] = '@';
  }
  return stream << path;
}

} // namespace unix {

template <>
inline Try<unix::Address> convert(Try<Address>&& address)
{
  if (address.isError()) {
    return Error(address.error());
  }

  if (address->family() == Address::Family::UNIX) {
    return unix::Address(address->sockaddr.un);
  }

  return Error("Unexpected address family");
}
#endif // __WINDOWS__

inline std::ostream& operator<<(std::ostream& stream, const Address& address)
{
  switch (address.family()) {
    case Address::Family::INET:
      return stream << inet::Address(address.sockaddr.in);
#ifndef __WINDOWS__
    case Address::Family::UNIX:
      return stream << unix::Address(address.sockaddr.un);
#endif // __WINDOWS__
  }

  UNREACHABLE();
}

} // namespace network {
} // namespace process {

namespace std {

template <>
struct hash<process::network::inet::Address>
{
  typedef size_t result_type;

  typedef process::network::inet::Address argument_type;

  result_type operator()(const argument_type& address) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, std::hash<net::IP>()(address.ip));
    boost::hash_combine(seed, address.port);
    return seed;
  }
};

} // namespace std {

#endif // __PROCESS_ADDRESS_HPP__


text:
@implementation NSException (DefaultExceptions)

+ (NSException *)notImplementedException {
    return [NSException exceptionWithName:@"NotYetImplemented" reason:@"Code lacks implementation" userInfo:nil];
}

+ (NSException *)abstractMethodNotOverridenException{
    return [NSException exceptionWithName:@"NotOverridenException" reason:@"The method must be overriden" userInfo:nil];
}

+ (NSException *)wrongInitException {
    return [NSException exceptionWithName:@"WrongInit" reason:@"Please use a different init" userInfo:nil];
}

+ (NSException *)exceptionWithDescription:(NSString*)description {
    return [NSException exceptionWithName:@"H2F Exception" reason:description userInfo:nil];
}

@end


text:
<?php
/**
 * ChatRoomBan Collection
 *
 * @package    Collection
 * @author     Romain Laneuville <romain.laneuville@hotmail.fr>
 */

namespace classes\entitiesCollection;

use \abstracts\Collection as Collection;

/**
 * A collection of ChatRoomBan entity that extends the Collection pattern
 */
class ChatRoomBanCollection extends Collection
{
    /*=====================================
    =            Magic methods            =
    =====================================*/

    /**
     * constructor
     */
    public function __construct()
    {
    }

    /*-----  End of Magic methods  ------*/
}


text:
// We only need to import the modules necessary for initial render
import CoreLayout from '../layouts/CoreLayout/CoreLayout'
import Welcome from './Welcome'
import LocationsView from './Locations'
import Dashboard from './Dashboard'
import Community from './Community'
import Network from './Network'
import Settings from './Settings'
import Speeds from './Speeds'
import WiFiInsight from './WiFiInsight'
import ConnectedDevices from './ConnectedDevices'
import RouterConditions from './RouterConditions'
import SettingsPost from './SettingsPost'
import SettingsDiagnostics from './SettingsDiagnostics'
import SettingsContactUs from './SettingsContactUs'

/*  Note: Instead of using JSX, we recommend using react-router
    PlainRoute objects to build route definitions.   */

export const createRoutes = (store) => ({
  path: '/',
  component: CoreLayout,
  indexRoute: Welcome(store),
  childRoutes: [
    LocationsView(store),
    Dashboard(store),
    Community(store),
    Network(store),
    Settings(store),
    Speeds(store),
    WiFiInsight(store),
    ConnectedDevices(store),
    RouterConditions(store),
    SettingsPost(store),
    SettingsDiagnostics(store),
    SettingsContactUs(store)
  ]
})

/*  Note: childRoutes can be chunked or otherwise loaded programmatically
    using getChildRoutes with the following signature:

    getChildRoutes (location, cb) {
      require.ensure([], (require) => {
        cb(null, [
          // Remove imports!
          require('./Counter').default(store)
        ])
      })
    }

    However, this is not necessary for code-splitting! It simply provides
    an API for async route definitions. Your code splitting should occur
    inside the route `getComponent` function, since it is only invoked
    when the route exists and matches.
*/

export default createRoutes


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit61477b56b4cba5925ba0dee7168cde59::getLoader();