text:
package org.locationtech.geowave.analytic.mapreduce.clustering.runner;

import java.util.Arrays;
import java.util.Collection;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.locationtech.geowave.analytic.IndependentJobRunner;
import org.locationtech.geowave.analytic.PropertyManagement;
import org.locationtech.geowave.analytic.mapreduce.GeoWaveAnalyticJobRunner;
import org.locationtech.geowave.analytic.mapreduce.GeoWaveInputFormatConfiguration;
import org.locationtech.geowave.analytic.mapreduce.MapReduceJobRunner;
import org.locationtech.geowave.analytic.mapreduce.SequenceFileOutputFormatConfiguration;
import org.locationtech.geowave.analytic.mapreduce.clustering.InputToOutputKeyReducer;
import org.locationtech.geowave.analytic.param.CentroidParameters;
import org.locationtech.geowave.analytic.param.MapReduceParameters;
import org.locationtech.geowave.analytic.param.OutputParameters;
import org.locationtech.geowave.analytic.param.ParameterEnum;
import org.locationtech.geowave.core.geotime.index.SpatialDimensionalityTypeProvider;
import org.locationtech.geowave.core.geotime.index.SpatialOptions;
import org.locationtech.geowave.mapreduce.input.GeoWaveInputKey;
import org.locationtech.geowave.mapreduce.output.GeoWaveOutputKey;

/**
 * Run a map reduce job to extract a population of data from GeoWave (Accumulo), remove duplicates,
 * and output a SimpleFeature with the ID and the extracted geometry from each of the GeoWave data
 * item.
 */
public class GeoWaveInputLoadJobRunner extends GeoWaveAnalyticJobRunner implements
    MapReduceJobRunner,
    IndependentJobRunner {
  public GeoWaveInputLoadJobRunner() {
    // defaults
    super.setInputFormatConfiguration(new GeoWaveInputFormatConfiguration());
    super.setOutputFormatConfiguration(new SequenceFileOutputFormatConfiguration());
  }

  @Override
  public void configure(final Job job) throws Exception {

    job.setMapperClass(Mapper.class);
    job.setReducerClass(InputToOutputKeyReducer.class);
    job.setMapOutputKeyClass(GeoWaveInputKey.class);
    job.setMapOutputValueClass(ObjectWritable.class);
    job.setOutputKeyClass(GeoWaveOutputKey.class);
    job.setOutputValueClass(Object.class);
    job.setSpeculativeExecution(false);

    job.setJobName("GeoWave Input to Output");
    job.setReduceSpeculativeExecution(false);
  }

  @Override
  public Class<?> getScope() {
    return InputToOutputKeyReducer.class;
  }

  @Override
  public int run(final Configuration config, final PropertyManagement runTimeProperties)
      throws Exception {
    final String indexId =
        checkIndex(
            runTimeProperties,
            OutputParameters.Output.INDEX_ID,
            runTimeProperties.getPropertyAsString(
                CentroidParameters.Centroid.INDEX_NAME,
                SpatialDimensionalityTypeProvider.createIndexFromOptions(
                    new SpatialOptions()).getName()));
    OutputParameters.Output.INDEX_ID.getHelper().setValue(config, getScope(), indexId);

    addDataAdapter(
        config,
        getAdapter(
            runTimeProperties,
            OutputParameters.Output.DATA_TYPE_ID,
            OutputParameters.Output.DATA_NAMESPACE_URI));
    runTimeProperties.setConfig(
        new ParameterEnum[] {
            OutputParameters.Output.DATA_TYPE_ID,
            OutputParameters.Output.DATA_NAMESPACE_URI,
            OutputParameters.Output.INDEX_ID},
        config,
        getScope());
    // HP Fortify "Command Injection" false positive
    // What Fortify considers "externally-influenced input"
    // comes only from users with OS-level access anyway
    return super.run(config, runTimeProperties);
  }

  @Override
  public Collection<ParameterEnum<?>> getParameters() {
    final Collection<ParameterEnum<?>> params = super.getParameters();
    params.addAll(
        Arrays.asList(
            new OutputParameters.Output[] {
                OutputParameters.Output.INDEX_ID,
                OutputParameters.Output.DATA_TYPE_ID,
                OutputParameters.Output.DATA_NAMESPACE_URI}));
    params.addAll(MapReduceParameters.getParameters());
    return params;
  }

  @Override
  protected String getJobName() {
    return "Input Load";
  }
}


text:
/** @file SkylineBinPack.cpp
	@author Jukka Jylänki

	@brief Implements different bin packer algorithms that use the SKYLINE data structure.

	This work is released to Public Domain, do whatever you want with it.
*/

#include <cassert>
#include <limits.h>
#include "templates.h"

#include "SkylineBinPack.h"

using namespace std;

SkylineBinPack::SkylineBinPack()
:binWidth(0),
binHeight(0)
{
}

SkylineBinPack::SkylineBinPack(int width, int height, bool useWasteMap)
{
	Init(width, height, useWasteMap);
}

void SkylineBinPack::Init(int width, int height, bool useWasteMap_)
{
	binWidth = width;
	binHeight = height;

	useWasteMap = useWasteMap_;

#ifdef _DEBUG
	disjointRects.Clear();
#endif

	usedSurfaceArea = 0;
	skyLine.Clear();
	SkylineNode node;
	node.x = 0;
	node.y = 0;
	node.width = binWidth;
	skyLine.Push(node);

	if (useWasteMap)
	{
		wasteMap.Init(width, height);
		wasteMap.GetFreeRectangles().Clear();
	}
}

void SkylineBinPack::Insert(TArray<RectSize> &rects, TArray<Rect> &dst)
{
	dst.Clear();

	while(rects.Size() > 0)
	{
		Rect bestNode;
		int bestScore1 = INT_MAX;
		int bestScore2 = INT_MAX;
		int bestSkylineIndex = -1;
		int bestRectIndex = -1;
		for(unsigned i = 0; i < rects.Size(); ++i)
		{
			Rect newNode;
			int score1;
			int score2;
			int index;
			newNode = FindPositionForNewNodeMinWaste(rects[i].width, rects[i].height, score2, score1, index);
#ifdef _DEBUG
			assert(disjointRects.Disjoint(newNode));
#endif
			if (newNode.height != 0)
			{
				if (score1 < bestScore1 || (score1 == bestScore1 && score2 < bestScore2))
				{
					bestNode = newNode;
					bestScore1 = score1;
					bestScore2 = score2;
					bestSkylineIndex = index;
					bestRectIndex = i;
				}
			}
		}

		if (bestRectIndex == -1)
			return;

		// Perform the actual packing.
#ifdef _DEBUG
		assert(disjointRects.Disjoint(bestNode));
		disjointRects.Add(bestNode);
#endif
		AddSkylineLevel(bestSkylineIndex, bestNode);
		usedSurfaceArea += rects[bestRectIndex].width * rects[bestRectIndex].height;
		rects.Delete(bestRectIndex);
		dst.Push(bestNode);
	}
}

Rect SkylineBinPack::Insert(int width, int height)
{
	// First try to pack this rectangle into the waste map, if it fits.
	Rect node = wasteMap.Insert(width, height, true, GuillotineBinPack::RectBestShortSideFit,
		GuillotineBinPack::SplitMaximizeArea);
#ifdef _DEBUG
	assert(disjointRects.Disjoint(node));
#endif

	if (node.height != 0)
	{
		Rect newNode;
		newNode.x = node.x;
		newNode.y = node.y;
		newNode.width = node.width;
		newNode.height = node.height;
		usedSurfaceArea += width * height;
#ifdef _DEBUG
		assert(disjointRects.Disjoint(newNode));
		disjointRects.Add(newNode);
#endif
		return newNode;
	}

	return InsertBottomLeft(width, height);
}

bool SkylineBinPack::RectangleFits(int skylineNodeIndex, int width, int height, int &y) const
{
	int x = skyLine[skylineNodeIndex].x;
	if (x + width > binWidth)
		return false;
	int widthLeft = width;
	int i = skylineNodeIndex;
	y = skyLine[skylineNodeIndex].y;
	while(widthLeft > 0)
	{
		y = MAX(y, skyLine[i].y);
		if (y + height > binHeight)
			return false;
		widthLeft -= skyLine[i].width;
		++i;
		assert(i < (int)skyLine.Size() || widthLeft <= 0);
	}
	return true;
}

int SkylineBinPack::ComputeWastedArea(int skylineNodeIndex, int width, int height, int y) const
{
	int wastedArea = 0;
	const int rectLeft = skyLine[skylineNodeIndex].x;
	const int rectRight = rectLeft + width;
	for(; skylineNodeIndex < (int)skyLine.Size() && skyLine[skylineNodeIndex].x < rectRight; ++skylineNodeIndex)
	{
		if (skyLine[skylineNodeIndex].x >= rectRight || skyLine[skylineNodeIndex].x + skyLine[skylineNodeIndex].width <= rectLeft)
			break;

		int leftSide = skyLine[skylineNodeIndex].x;
		int rightSide = MIN(rectRight, leftSide + skyLine[skylineNodeIndex].width);
		assert(y >= skyLine[skylineNodeIndex].y);
		wastedArea += (rightSide - leftSide) * (y - skyLine[skylineNodeIndex].y);
	}
	return wastedArea;
}

bool SkylineBinPack::RectangleFits(int skylineNodeIndex, int width, int height, int &y, int &wastedArea) const
{
	bool fits = RectangleFits(skylineNodeIndex, width, height, y);
	if (fits)
		wastedArea = ComputeWastedArea(skylineNodeIndex, width, height, y);

	return fits;
}

void SkylineBinPack::AddWasteMapArea(int skylineNodeIndex, int width, int height, int y)
{
	int wastedArea = 0;
	const int rectLeft = skyLine[skylineNodeIndex].x;
	const int rectRight = rectLeft + width;
	for(; skylineNodeIndex < (int)skyLine.Size() && skyLine[skylineNodeIndex].x < rectRight; ++skylineNodeIndex)
	{
		if (skyLine[skylineNodeIndex].x >= rectRight || skyLine[skylineNodeIndex].x + skyLine[skylineNodeIndex].width <= rectLeft)
			break;

		int leftSide = skyLine[skylineNodeIndex].x;
		int rightSide = MIN(rectRight, leftSide + skyLine[skylineNodeIndex].width);
		assert(y >= skyLine[skylineNodeIndex].y);

		Rect waste;
		waste.x = leftSide;
		waste.y = skyLine[skylineNodeIndex].y;
		waste.width = rightSide - leftSide;
		waste.height = y - skyLine[skylineNodeIndex].y;

#ifdef _DEBUG
		assert(disjointRects.Disjoint(waste));
#endif
		wasteMap.GetFreeRectangles().Push(waste);
	}
}

void SkylineBinPack::AddWaste(const Rect &waste)
{
	wasteMap.GetFreeRectangles().Push(waste);
#ifdef _DEBUG
	disjointRects.Del(waste);
	wasteMap.DelDisjoint(waste);
#endif
}

void SkylineBinPack::AddSkylineLevel(int skylineNodeIndex, const Rect &rect)
{
	// First track all wasted areas and mark them into the waste map if we're using one.
	if (useWasteMap)
		AddWasteMapArea(skylineNodeIndex, rect.width, rect.height, rect.y);

	SkylineNode newNode;
	newNode.x = rect.x;
	newNode.y = rect.y + rect.height;
	newNode.width = rect.width;
	skyLine.Insert(skylineNodeIndex, newNode);

	assert(newNode.x + newNode.width <= binWidth);
	assert(newNode.y <= binHeight);

	for(unsigned i = skylineNodeIndex+1; i < skyLine.Size(); ++i)
	{
		assert(skyLine[i-1].x <= skyLine[i].x);

		if (skyLine[i].x < skyLine[i-1].x + skyLine[i-1].width)
		{
			int shrink = skyLine[i-1].x + skyLine[i-1].width - skyLine[i].x;

			skyLine[i].x += shrink;
			skyLine[i].width -= shrink;

			if (skyLine[i].width <= 0)
			{
				skyLine.Delete(i);
				--i;
			}
			else
				break;
		}
		else
			break;
	}
	MergeSkylines();
}

void SkylineBinPack::MergeSkylines()
{
	for(unsigned i = 0; i < skyLine.Size()-1; ++i)
		if (skyLine[i].y == skyLine[i+1].y)
		{
			skyLine[i].width += skyLine[i+1].width;
			skyLine.Delete(i+1);
			--i;
		}
}

Rect SkylineBinPack::InsertBottomLeft(int width, int height)
{
	int bestHeight;
	int bestWidth;
	int bestIndex;
	Rect newNode = FindPositionForNewNodeBottomLeft(width, height, bestHeight, bestWidth, bestIndex);

	if (bestIndex != -1)
	{
#ifdef _DEBUG
		assert(disjointRects.Disjoint(newNode));
#endif
		// Perform the actual packing.
		AddSkylineLevel(bestIndex, newNode);

		usedSurfaceArea += width * height;
#ifdef _DEBUG
		disjointRects.Add(newNode);
#endif
	}
	else
		memset(&newNode, 0, sizeof(Rect));

	return newNode;
}

Rect SkylineBinPack::FindPositionForNewNodeBottomLeft(int width, int height, int &bestHeight, int &bestWidth, int &bestIndex) const
{
	bestHeight = INT_MAX;
	bestIndex = -1;
	// Used to break ties if there are nodes at the same level. Then pick the narrowest one.
	bestWidth = INT_MAX;
	Rect newNode = { 0, 0, 0, 0 };
	for(unsigned i = 0; i < skyLine.Size(); ++i)
	{
		int y;
		if (RectangleFits(i, width, height, y))
		{
			if (y + height < bestHeight || (y + height == bestHeight && skyLine[i].width < bestWidth))
			{
				bestHeight = y + height;
				bestIndex = i;
				bestWidth = skyLine[i].width;
				newNode.x = skyLine[i].x;
				newNode.y = y;
				newNode.width = width;
				newNode.height = height;
#ifdef _DEBUG
				assert(disjointRects.Disjoint(newNode));
#endif
			}
		}
/*		if (RectangleFits(i, height, width, y))
		{
			if (y + width < bestHeight || (y + width == bestHeight && skyLine[i].width < bestWidth))
			{
				bestHeight = y + width;
				bestIndex = i;
				bestWidth = skyLine[i].width;
				newNode.x = skyLine[i].x;
				newNode.y = y;
				newNode.width = height;
				newNode.height = width;
				assert(disjointRects.Disjoint(newNode));
			}
		}
*/	}

	return newNode;
}

Rect SkylineBinPack::InsertMinWaste(int width, int height)
{
	int bestHeight;
	int bestWastedArea;
	int bestIndex;
	Rect newNode = FindPositionForNewNodeMinWaste(width, height, bestHeight, bestWastedArea, bestIndex);

	if (bestIndex != -1)
	{
#ifdef _DEBUG
		assert(disjointRects.Disjoint(newNode));
#endif
		// Perform the actual packing.
		AddSkylineLevel(bestIndex, newNode);

		usedSurfaceArea += width * height;
#ifdef _DEBUG
		disjointRects.Add(newNode);
#endif
	}
	else
		memset(&newNode, 0, sizeof(newNode));

	return newNode;
}

Rect SkylineBinPack::FindPositionForNewNodeMinWaste(int width, int height, int &bestHeight, int &bestWastedArea, int &bestIndex) const
{
	bestHeight = INT_MAX;
	bestWastedArea = INT_MAX;
	bestIndex = -1;
	Rect newNode;
	memset(&newNode, 0, sizeof(newNode));
	for(unsigned i = 0; i < skyLine.Size(); ++i)
	{
		int y;
		int wastedArea;

		if (RectangleFits(i, width, height, y, wastedArea))
		{
			if (wastedArea < bestWastedArea || (wastedArea == bestWastedArea && y + height < bestHeight))
			{
				bestHeight = y + height;
				bestWastedArea = wastedArea;
				bestIndex = i;
				newNode.x = skyLine[i].x;
				newNode.y = y;
				newNode.width = width;
				newNode.height = height;
#ifdef _DEBUG
				assert(disjointRects.Disjoint(newNode));
#endif
			}
		}
/*		if (RectangleFits(i, height, width, y, wastedArea))
		{
			if (wastedArea < bestWastedArea || (wastedArea == bestWastedArea && y + width < bestHeight))
			{
				bestHeight = y + width;
				bestWastedArea = wastedArea;
				bestIndex = i;
				newNode.x = skyLine[i].x;
				newNode.y = y;
				newNode.width = height;
				newNode.height = width;
				assert(disjointRects.Disjoint(newNode));
			}
		}*/
	}

	return newNode;
}

/// Computes the ratio of used surface area.
float SkylineBinPack::Occupancy() const
{
	return (float)usedSurfaceArea / (binWidth * binHeight);
}

redpajama_set_name: RedPajamaGithub


text:
package org.motechproject.security.repository;

import org.joda.time.DateTime;
import org.motechproject.commons.api.Range;
import org.motechproject.commons.date.util.DateUtil;
import org.motechproject.security.domain.PasswordRecovery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Locale;

/**
 * Implementation of DAO interface that utilizes a MDS back-end for storage.
 * Class responsible for handling PasswordRecoveries.
 */
@Repository
public class AllPasswordRecoveries {
    private PasswordRecoveriesDataService dataService;

    /**
     * Returns all expired PasswordRecoveries
     *
     * @return list that contains recoveries
     */
    @Transactional
    public List<PasswordRecovery> getExpired() {
        Range<DateTime> range = new Range<>(new DateTime(0), DateUtil.now());
        return dataService.findByExpirationDate(range);
    }

    /**
     * Returns all PasswordRecoveries
     *
     * @return list that contains recoveries
     */
    @Transactional
    public List<PasswordRecovery> allRecoveries() {
        return dataService.retrieveAll();
    }

    /**
     * Gets PasswordRecovery for user with given name
     *
     * @param username name of user
     * @return recovery for given name or null in case when username is a null
     */
    @Transactional
    public PasswordRecovery findForUser(String username) {
        return null == username ? null : dataService.findForUser(username);
    }

    /**
     * Gets PasswordRecovery for given token
     *
     * @param token for recovery
     * @return recovery for given token or null in case when token is a null
     */
    @Transactional
    public PasswordRecovery findForToken(String token) {
        return null == token ? null : dataService.findForToken(token);
    }

    /**
     * Creates PasswordRecovery for given informations and return it
     *
     * @param username for recovery
     * @param email for recovery
     * @param token for recovery
     * @param expirationDate for recovery
     * @param locale for recovery
     * @return recovery with given informations
     */
    @Transactional
    public PasswordRecovery createRecovery(String username, String email, String token, DateTime expirationDate, Locale locale) {
        PasswordRecovery oldRecovery = findForUser(username);

        if (oldRecovery != null) {
            remove(oldRecovery);
        }

        PasswordRecovery recovery = new PasswordRecovery();
        recovery.setUsername(username);
        recovery.setEmail(email);
        recovery.setToken(token);
        recovery.setExpirationDate(expirationDate);
        recovery.setLocale(locale);

        add(recovery);

        return recovery;
    }

    /**
     * Updates given PasswordRecovery
     *
     * @param passwordRecovery to be updated
     */
    @Transactional
    public void update(PasswordRecovery passwordRecovery) {
        dataService.update(passwordRecovery);
    }

    /**
     * Adds given PasswordRecovery provided tha one doesn't exist yet for the user
     *
     * @param passwordRecovery to be added
     */
    @Transactional
    public void add(PasswordRecovery passwordRecovery) {
        if (findForUser(passwordRecovery.getUsername()) == null) {
            dataService.create(passwordRecovery);
        }
    }

    /**
     * Deletes given PasswordRecovery
     *
     * @param passwordRecovery to be removed
     */
    @Transactional
    public void remove(PasswordRecovery passwordRecovery) {
        dataService.delete(passwordRecovery);
    }

    @Autowired
    public void setDataService(PasswordRecoveriesDataService dataService) {
        this.dataService = dataService;
    }
}


text:
package com.webtrends.service

import com.webtrends.harness.service.Service
import com.webtrends.harness.service.messages.Ready

class ${service-name} extends Service {

  /**
   * This function should be implemented by any service that wants to add
   * any commands to make available for use
   */
  override def addCommands = {
    addCommand(${service-name}Command.CommandName, classOf[${service-name}Command])
  }

  /**
   * This is the receive expression for your service. Apply any logic you wish
   * to handle specific messages
   */
  override def serviceReceive = ({
    // TODO: Add additional message handlers here
    case Ready(meta) =>
      log.info("I received a Ready message from the outside world")
  }: Receive) orElse super.serviceReceive
}


text:
export interface BottomNavigationActionClasses {
    /** Styles applied to the root element. */
    root: string;
    /** State class applied to the root element if selected. */
    selected: string;
    /** State class applied to the root element if `showLabel={false}` and not selected. */
    iconOnly: string;
    /** Styles applied to the label's span element. */
    label: string;
}
export declare type BottomNavigationActionClassKey = keyof BottomNavigationActionClasses;
export declare function getBottomNavigationActionUtilityClass(slot: string): string;
declare const bottomNavigationActionClasses: BottomNavigationActionClasses;
export default bottomNavigationActionClasses;


text:
package org.apache.log4j;

import static org.junit.Assert.assertTrue;

import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.Test;

/**
 * Tests {@link LogManager}.
 */
public class LogManagerTest {

    private static final String SIMPLE_NAME = LogManagerTest.class.getSimpleName();

    List<String> getCurrentLoggerNames() {
        return Collections.list((Enumeration<Logger>) LogManager.getCurrentLoggers()).stream().map(Logger::getName).collect(Collectors.toList());
    }

    @Test
    public void testGetCurrentLoggers() {
        Logger.getLogger(SIMPLE_NAME);
        Logger.getLogger(SIMPLE_NAME + ".foo");
        Logger.getLogger(SIMPLE_NAME + ".foo.bar");
        final List<String> names = getCurrentLoggerNames();
        assertTrue(names.contains(SIMPLE_NAME));
        assertTrue(names.contains(SIMPLE_NAME + ".foo"));
        assertTrue(names.contains(SIMPLE_NAME + ".foo.bar"));
    }
}


text:
import { describe } from 'mocha';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import React from 'react';

import moment from 'moment';
import { setup, assertRenderSuccess, assertRenderFailure, TestUtilError } from './util';
import { momentObj } from '../../src/index';
import { messages } from '../../src/core';

const successIdKey = '#success';
class MomentObj extends React.Component {
  render() {
    return (

required: {typeof this.props.requiredObjectNamedPredicate}

required: {typeof this.props.requiredObjectAnonPredicate}

    );
  }
}

setup();

describe('predicates', () => {

  describe('isRequired', () => {

    describe('<MomentObj moment={moment} />', () => {
      before(() => {
        MomentObj.propTypes = {
          requiredObjectNamedPredicate : momentObj.withPredicate(
            function namedPredicate(momentPropValue) {
              return true;
            }
          ).isRequired,
          requiredObjectAnonPredicate : momentObj.withPredicate(() => true).isRequired,
        };
      });

      it('renders without error', () => {
        const props = {
          requiredObjectNamedPredicate: moment(),
          requiredObjectAnonPredicate: moment(),
        };
        assertRenderSuccess(() => shallow(<MomentObj {...props} />), successIdKey);
      });
    });

    describe('<MomentObj moment={moment} />', () => {
      let predicateName = null;

      before(() => {
        function namedPredicate(momentPropValue) {
          return false;
        }
        predicateName = namedPredicate.name;
        MomentObj.propTypes = {
          requiredObjectNamedPredicate : momentObj.withPredicate(namedPredicate).isRequired,
        };
      });

      it('named predicated fails', () => {
        const props = { requiredObjectNamedPredicate: moment() };
        assertRenderFailure(() => shallow(<MomentObj {...props} />), (ex) => {
          expect(predicateName).to.not.be.null;
          expect(ex).to.be.an.instanceOf(TestUtilError);
          expect(ex.message).to.contain(messages.predicateFailureCore);
          expect(ex.message).to.contain(predicateName);
        });
      });
    });

    describe('<MomentObj moment={moment} />', () => {
      before(() => {
        MomentObj.propTypes = {
          requiredObjectAnonPredicate : momentObj.withPredicate(() => false).isRequired,
        };
      });

      it('anonymous predicated fails', () => {
        const props = { requiredObjectAnonPredicate: moment() };
        assertRenderFailure(() => shallow(<MomentObj {...props} />), (ex) => {
          expect(ex).to.be.an.instanceOf(TestUtilError);
          expect(ex.message).to.contain(messages.predicateFailureCore);
          expect(ex.message).to.contain(messages.anonymousMessage);
        });
      });
    });

    describe('basePropValidation', () => {

      before(() => {
        MomentObj.propTypes = {
          requiredObjectAnonPredicate : momentObj.withPredicate(() => true).isRequired,
        };
      });

      describe('<MomentObj />', () => {
        it('Throws required message', () => {
          assertRenderFailure(() => shallow(<MomentObj />), (ex) => {
            expect(ex).to.be.an.instanceOf(TestUtilError);
            expect(ex.message).to.contain(messages.requiredCore);
          });
        });
      });

      describe('<MomentObj moment={null} />', () => {
        it('Throws required message', () => {
          const props = { requiredObjectAnonPredicate: null };
          assertRenderFailure(() => shallow(<MomentObj {...props} />), (ex) => {
            expect(ex).to.be.an.instanceOf(TestUtilError);
            expect(ex.message).to.contain(messages.requiredCore);
          });
        });
      });

      // TODO: [Issue 26] passing when it shouldn't in Enzyme. Uncomment when fixed
      // describe('<MomentObj moment={undefined} />', () => {
      //   it('Throws required message', () => {
      //     const props = { requiredObjectAnonPredicate: undefined };
      //     assertRenderFailure(() => mount(<MomentObj {...props} />), (ex) => {
      //       expect(ex).to.be.an.instanceOf(TestUtilError);
      //       expect(ex.message).to.contain(messages.requiredCore);
      //     });
      //   });
      // });
    });

  });

  describe('optional', () => {

    describe('<MomentObj moment={moment} />', () => {
      before(() => {
        MomentObj.propTypes = {
          optionalObjectNamedPredicate : momentObj.withPredicate(
            function namedPredicate(momentPropValue) {
              return true;
            }
          ),
          optionalObjectAnonPredicate : momentObj.withPredicate(() => true),
        };
      });

      it('renders without error', () => {
        const props = {
          optionalObjectNamedPredicate: moment(),
          optionalObjectAnonPredicate: moment(),
        };
        assertRenderSuccess(() => shallow(<MomentObj {...props} />), successIdKey);
      });
    });

    describe('<MomentObj moment={moment} />', () => {
      let predicateName = null;

      before(() => {
        function namedPredicate(momentPropValue) {
          return false;
        }
        predicateName = namedPredicate.name;
        MomentObj.propTypes = {
          optionalObjectNamedPredicate : momentObj.withPredicate(namedPredicate),
        };
      });

      it('named predicated fails', () => {
        const props = { optionalObjectNamedPredicate: moment() };
        assertRenderFailure(() => shallow(<MomentObj {...props} />), (ex) => {
          expect(predicateName).to.not.be.null;
          expect(ex).to.be.an.instanceOf(TestUtilError);
          expect(ex.message).to.contain(messages.predicateFailureCore);
          expect(ex.message).to.contain(predicateName);
        });
      });
    });

    describe('<MomentObj moment={moment} />', () => {
      before(() => {
        MomentObj.propTypes = {
          optionalObjectAnonPredicate : momentObj.withPredicate(() => false),
        };
      });

      it('anonymous predicated fails', () => {
        const props = { optionalObjectAnonPredicate: moment() };
        assertRenderFailure(() => shallow(<MomentObj {...props} />), (ex) => {
          expect(ex).to.be.an.instanceOf(TestUtilError);
          expect(ex.message).to.contain(messages.predicateFailureCore);
          expect(ex.message).to.contain(messages.anonymousMessage);
        });
      });
    });

    describe('basePropValidation', () => {

      before(() => {
        MomentObj.propTypes = {
          optionalObjectAnonPredicate : momentObj.withPredicate(() => true),
        };
      });

      describe('<MomentObj />', () => {
        it('Throws required message', () => {
          assertRenderSuccess(() => shallow(<MomentObj />), successIdKey);
        });
      });

      describe('<MomentObj moment={null} />', () => {
        it('Throws required message', () => {
          const props = { optionalObjectAnonPredicate: null };
          assertRenderSuccess(() => shallow(<MomentObj {...props} />), successIdKey);
        });
      });

      // TODO: [Issue 26] passing when it shouldn't in Enzyme. Uncomment when fixed
      // describe('<MomentObj moment={undefined} />', () => {
      //   it('Throws required message', () => {
      //     const props = { optionalObjectAnonPredicate: undefined };
      //     assertRenderSuccess(() => shallow(<MomentObj {...props} />), successIdKey);
      //   });
      // });
    });

  });

});


text:
layout: default
---

Introduction

        I'm a software developer with data analysis skills who hails from a humanities and legal background. I feel this amalgamation of skills makes me an interesting and capable developer.
        I'm interested in backend web development, data analysis, machine learning, and data visualization.
        I am currently looking for exciting opportunities in the Research Triangle Area of North Carolina. Please feel free to download my resume and contact me for any comments and questions.

Portfolio

        The four projects below highlight my skill at programming in Python, creating web applications, building REST APIs, and performing data analysis.

Bringing Buzzwords Home

        Bringing Buzzwords Home is a three person data visualization project created by myself, Jonathan Kross, and David Conley while we were students at The Iron Yard.
        We extracted, transformed, and loaded (ETL) data from disparate sources into relational database, fed visualizations via dynamically created JSON, and created NVD3 visualizations from that JSON. You may view the code for this project on GitHub.

        Tools used include: Git, Django, Django Rest Framework, Postgresql, D3, NVD3 and deployment via Heroku

Computer Programming Language Predictor

        The Computer Programming Language Predictor is python script that utilizes machine learning to predict the programming language (out of a set of 15) of any given program.

        Tools used include: Git, Scikit-Learn, and Jupyter Notebook

Analysis of the American Time Use Survey

        Analysis of the American Time Use Survey (ATUS) is a Jupyter Notebook and python module that do exploratory data analysis of parts of the ATUS.

Monte Carlo Simulation of the Monty Hall Problem

        monty_hall.py is a python script that executes a Monte Carlo simulation to prove the "switch strategy" to the Monty Hall Problem.


text:
{% extends "home/index.html" %}
{%  load staticfiles %}

{% block content %}

    <link rel='stylesheet' href="{% static "Fullcalendar/js/Fullcalendar/fullcalendar.css" %}" />
 <script src="{% static "Fullcalendar/js/lib/jquery.min.js" %}"></script>
    <script src="{% static "Fullcalendar/js/lib/moment.min.js" %}"></script>
    <script src="{% static "Fullcalendar/js/Fullcalendar/fullcalendar.js" %}" ></script>
<script>

    $(document).ready(function() {

    // page is now ready, initialize the calendar...
        var date1 = new Date();
        var d = date1.getDate();
        var m = date1.getMonth();
        var y = date1.getFullYear();

        function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

    $('#calendar').fullCalendar({
        // put your options and callbacks here
        editable: true,
    weekMode: 'liquid',
    url:'#',
         timeFormat: "hh:mm",
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay',
                },
                allDaySlot: false,
                firstDay: 0,
                weekMode: 'liquid',
{#                slotMinutes: 15,#}
{#                defaultEventMinutes: 30,#}
{#                minTime: 8,#}
{#                maxTime: 20,#}
                editable: true,
                dayClick: function(date, allDay, jsEvent, view) {
                    if (allDay) {
                        $('#calendar').fullCalendar('gotoDate', date)
                        $('#calendar').fullCalendar('changeView', 'agendaDay')
                    }
                },
                eventClick: function(event, jsEvent, view) {
                    if (view.name == 'month') {
                        $('#calendar').fullCalendar('gotoDate', event.start)
                        $('#calendar').fullCalendar('changeView', 'agendaDay')
                    }

                },

/*
            events: [
                {
                    title: 'Test1',
                    start: new Date(y, m, 1, 9, 00),
                    end: new Date(y, m, 1, 10, 00),
                    allDay: false
                },
                {
                    title: 'Test2',
                    start: new Date(y, m, 2, 16, 00),
                    allDay: false
                }

            ]*/
        events: {{ Events|safe }}
{#        eventColor:getRandomColor()#}

    })

});

</script>
<div id='calendar'>
calendar
</div>

{% endblock %}


text:
package com.xsolla.android.sdkexampleapp;

import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.filters.LargeTest;
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static androidx.test.espresso.Espresso.closeSoftKeyboard;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.Espresso.pressBack;
import static androidx.test.espresso.action.ViewActions.clearText;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.scrollTo;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.isRoot;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static com.xsolla.android.sdkexampleapp.util.Waiter.waitId;

@RunWith(AndroidJUnit4ClassRunner.class)
@LargeTest
public class MainTest {

    @Rule
    public ActivityScenarioRule<MainActivity> activityScenarioRule = new ActivityScenarioRule<>(MainActivity.class);

    @Test
    public void testTokenWithZip(){
        onView(withId(R.id.edToken))
                .check(matches(isDisplayed()))
                .perform(clearText())
                .perform(typeText("4sp0zq2oLg9zNUNqnSuJMJCDKOwioi5u"));

        closeSoftKeyboard();
        onView(withId(R.id.buttonCreate))
                .check(matches(isDisplayed()))
                .perform(click());

        onView(isRoot()).perform(waitId(R.id.tvCardNumber, Sampling.SECONDS_10));

        onView(withId(R.id.edCardNumber))
                .check(matches(isDisplayed()))
                .perform(typeText("4111111111111111"));
        onView(withId(R.id.edMonth))
                .check(matches(isDisplayed()))
                .perform(typeText("12"));
        onView(withId(R.id.edYear))
                .check(matches(isDisplayed()))
                .perform(typeText("40"));
        onView(withId(R.id.edCvv))
                .check(matches(isDisplayed()))
                .perform(typeText("123"));
        onView(withId(R.id.edZipCode))
                .check(matches(isDisplayed()))
                .perform(typeText("1234"));

        closeSoftKeyboard();

        onView(withId(R.id.btnPay))
                .perform(scrollTo())
                .check(matches(isDisplayed()))
                .perform(click());

        onView(isRoot()).perform(waitId(R.id.tvProductName, Sampling.SECONDS_10));

        onView(withId(R.id.btnComplete))
                .perform(scrollTo())
                .check(matches(isDisplayed()))
                .perform(click());
    }

    // TODO set suitable token
    @Test
    public void testSimpleToken(){
        onView(withId(R.id.edToken))
                .check(matches(isDisplayed()))
                .perform(clearText())
                .perform(typeText("4sp0KfihTJpf7lxCEKMCJm75JtYPPOCu"));

        closeSoftKeyboard();
        onView(withId(R.id.buttonCreate))
                .check(matches(isDisplayed()))
                .perform(click());

        onView(isRoot()).perform(waitId(R.id.tvCardNumber, Sampling.SECONDS_10));

        onView(withId(R.id.edCardNumber))
                .check(matches(isDisplayed()))
                .perform(typeText("4111111111111111"));
        onView(withId(R.id.edMonth))
                .check(matches(isDisplayed()))
                .perform(typeText("12"));
        onView(withId(R.id.edYear))
                .check(matches(isDisplayed()))
                .perform(typeText("40"));
        onView(withId(R.id.edCvv))
                .check(matches(isDisplayed()))
                .perform(typeText("123"));

        closeSoftKeyboard();

        onView(withId(R.id.btnPay))
                .perform(scrollTo())
                .check(matches(isDisplayed()))
                .perform(click());

        onView(isRoot()).perform(waitId(R.id.tvProductName, Sampling.SECONDS_10));

        onView(withId(R.id.btnComplete))
                .perform(scrollTo())
                .check(matches(isDisplayed()))
                .perform(click());
    }

    // TODO set suitable token and fix test
    @Test
    public void testTokenWithCardHolder(){
        onView(withId(R.id.edToken))
                .check(matches(isDisplayed()))
                .perform(clearText())
                .perform(typeText("yeenj6Z9hH4elpB42Hpsm1vRGhcVCTyH"));

        closeSoftKeyboard();
        onView(withId(R.id.buttonCreate))
                .check(matches(isDisplayed()))
                .perform(click());

        onView(isRoot()).perform(waitId(R.id.tvDescription, Sampling.SECONDS_10));

        onView(withId(R.id.edCardNumber))
                .check(matches(isDisplayed()))
                .perform(typeText("4111111111111111"));
        onView(withId(R.id.edYear))
                .check(matches(isDisplayed()))
                .perform(typeText("20"));
        onView(withId(R.id.edMonth))
                .check(matches(isDisplayed()))
                .perform(typeText("12"));
        onView(withId(R.id.edCardHolder))
                .check(matches(isDisplayed()))
                .perform(typeText("Ivan"));
        onView(withId(R.id.edCvv))
                .check(matches(isDisplayed()))
                .perform(typeText("123"));
        onView(withId(R.id.btnPay))
                .perform(scrollTo())
                .check(matches(isDisplayed()))
                .perform(click());

        onView(isRoot()).perform(waitId(R.id.tvProductName, Sampling.SECONDS_10));

        onView(withId(R.id.btnComplete))
                .perform(scrollTo())
                .check(matches(isDisplayed()))
                .perform(click());
    }

    // TODO set suitable token and fix test
    @Test
    public void testSimpleTokenInvalidCardInfo(){
        onView(withId(R.id.edToken))
                .check(matches(isDisplayed()))
                .perform(clearText())
                .perform(typeText("sBVfYM208VSA6GiBj108Y1UKJlJ3Lv6F"));

        closeSoftKeyboard();
        onView(withId(R.id.buttonCreate))
                .check(matches(isDisplayed()))
                .perform(click());

        onView(isRoot()).perform(waitId(R.id.tvDescription, Sampling.SECONDS_10));

        onView(withId(R.id.edCardNumber))
                .check(matches(isDisplayed()))
                .perform(typeText("4111111111111111"));
        onView(withId(R.id.edYear))
                .check(matches(isDisplayed()))
                .perform(typeText("20"));
        onView(withId(R.id.edMonth))
                .check(matches(isDisplayed()))
                .perform(typeText("12"));
        onView(withId(R.id.edCvv))
                .check(matches(isDisplayed()))
                .perform(typeText("123"));
        onView(withId(R.id.btnPay))
                .perform(scrollTo())
                .check(matches(isDisplayed()))
                .perform(click());

        onView(isRoot()).perform(waitId(R.id.tvError, Sampling.SECONDS_10));

        onView(withId(R.id.tvError))
                .perform(scrollTo())
                .check(matches(isDisplayed()));

        pressBack();
    }

}


text:
using gax = Google.Api.Gax;
using gcav = Google.Cloud.ArtifactRegistry.V1;
using sys = System;

namespace Google.Cloud.ArtifactRegistry.V1
{
    /// Resource name for the <c>DockerImage</c> resource.
    public sealed partial class DockerImageName : gax::IResourceName, sys::IEquatable<DockerImageName>
    {
        /// The possible contents of <see cref="DockerImageName"/>.
        public enum ResourceNameType
        {
            /// An unparsed resource name.
            Unparsed = 0,

            ///
            /// A resource name with pattern
            /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>.
            ///
            ProjectLocationRepositoryDockerImage = 1,
        }

        private static gax::PathTemplate s_projectLocationRepositoryDockerImage = new gax::PathTemplate("projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}");

        /// Creates a <see cref="DockerImageName"/> containing an unparsed resource name.
        /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
        /// <returns>
        /// A new instance of <see cref="DockerImageName"/> containing the provided
        /// <paramref name="unparsedResourceName"/>.
        /// </returns>
        public static DockerImageName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
            new DockerImageName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));

        ///
        /// Creates a <see cref="DockerImageName"/> with the pattern
        /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>.
        ///
        /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="dockerImageId">The <c>DockerImage</c> ID. Must not be <c>null</c> or empty.</param>
        /// <returns>A new instance of <see cref="DockerImageName"/> constructed from the provided ids.</returns>
        public static DockerImageName FromProjectLocationRepositoryDockerImage(string projectId, string locationId, string repositoryId, string dockerImageId) =>
            new DockerImageName(ResourceNameType.ProjectLocationRepositoryDockerImage, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)), dockerImageId: gax::GaxPreconditions.CheckNotNullOrEmpty(dockerImageId, nameof(dockerImageId)));

        ///
        /// Formats the IDs into the string representation of this <see cref="DockerImageName"/> with pattern
        /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>.
        ///
        /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="dockerImageId">The <c>DockerImage</c> ID. Must not be <c>null</c> or empty.</param>
        /// <returns>
        /// The string representation of this <see cref="DockerImageName"/> with pattern
        /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>.
        /// </returns>
        public static string Format(string projectId, string locationId, string repositoryId, string dockerImageId) =>
            FormatProjectLocationRepositoryDockerImage(projectId, locationId, repositoryId, dockerImageId);

        ///
        /// Formats the IDs into the string representation of this <see cref="DockerImageName"/> with pattern
        /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>.
        ///
        /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="dockerImageId">The <c>DockerImage</c> ID. Must not be <c>null</c> or empty.</param>
        /// <returns>
        /// The string representation of this <see cref="DockerImageName"/> with pattern
        /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>.
        /// </returns>
        public static string FormatProjectLocationRepositoryDockerImage(string projectId, string locationId, string repositoryId, string dockerImageId) =>
            s_projectLocationRepositoryDockerImage.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)), gax::GaxPreconditions.CheckNotNullOrEmpty(dockerImageId, nameof(dockerImageId)));

        /// Parses the given resource name string into a new <see cref="DockerImageName"/> instance.
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet">
        /// <item>
        /// <description>
        /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>
        /// </description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="dockerImageName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <returns>The parsed <see cref="DockerImageName"/> if successful.</returns>
        public static DockerImageName Parse(string dockerImageName) => Parse(dockerImageName, false);

        ///
        /// Parses the given resource name string into a new <see cref="DockerImageName"/> instance; optionally allowing
        /// an unparseable resource name.
        ///
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet">
        /// <item>
        /// <description>
        /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>
        /// </description>
        /// </item>
        /// </list>
        /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
        /// </remarks>
        /// <param name="dockerImageName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <param name="allowUnparsed">
        /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
        /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
        /// specified.
        /// </param>
        /// <returns>The parsed <see cref="DockerImageName"/> if successful.</returns>
        public static DockerImageName Parse(string dockerImageName, bool allowUnparsed) =>
            TryParse(dockerImageName, allowUnparsed, out DockerImageName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");

        ///
        /// Tries to parse the given resource name string into a new <see cref="DockerImageName"/> instance.
        ///
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet">
        /// <item>
        /// <description>
        /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>
        /// </description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="dockerImageName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <param name="result">
        /// When this method returns, the parsed <see cref="DockerImageName"/>, or <c>null</c> if parsing failed.
        /// </param>
        /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
        public static bool TryParse(string dockerImageName, out DockerImageName result) =>
            TryParse(dockerImageName, false, out result);

        ///
        /// Tries to parse the given resource name string into a new <see cref="DockerImageName"/> instance; optionally
        /// allowing an unparseable resource name.
        ///
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet">
        /// <item>
        /// <description>
        /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>
        /// </description>
        /// </item>
        /// </list>
        /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
        /// </remarks>
        /// <param name="dockerImageName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <param name="allowUnparsed">
        /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
        /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
        /// specified.
        /// </param>
        /// <param name="result">
        /// When this method returns, the parsed <see cref="DockerImageName"/>, or <c>null</c> if parsing failed.
        /// </param>
        /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
        public static bool TryParse(string dockerImageName, bool allowUnparsed, out DockerImageName result)
        {
            gax::GaxPreconditions.CheckNotNull(dockerImageName, nameof(dockerImageName));
            gax::TemplatedResourceName resourceName;
            if (s_projectLocationRepositoryDockerImage.TryParseName(dockerImageName, out resourceName))
            {
                result = FromProjectLocationRepositoryDockerImage(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
                return true;
            }
            if (allowUnparsed)
            {
                if (gax::UnparsedResourceName.TryParse(dockerImageName, out gax::UnparsedResourceName unparsedResourceName))
                {
                    result = FromUnparsed(unparsedResourceName);
                    return true;
                }
            }
            result = null;
            return false;
        }

        private DockerImageName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string dockerImageId = null, string locationId = null, string projectId = null, string repositoryId = null)
        {
            Type = type;
            UnparsedResource = unparsedResourceName;
            DockerImageId = dockerImageId;
            LocationId = locationId;
            ProjectId = projectId;
            RepositoryId = repositoryId;
        }

        ///
        /// Constructs a new instance of a <see cref="DockerImageName"/> class from the component parts of pattern
        /// <c>projects/{project}/locations/{location}/repositories/{repository}/dockerImages/{docker_image}</c>
        ///
        /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="dockerImageId">The <c>DockerImage</c> ID. Must not be <c>null</c> or empty.</param>
        public DockerImageName(string projectId, string locationId, string repositoryId, string dockerImageId) : this(ResourceNameType.ProjectLocationRepositoryDockerImage, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)), dockerImageId: gax::GaxPreconditions.CheckNotNullOrEmpty(dockerImageId, nameof(dockerImageId)))
        {
        }

        /// The <see cref="ResourceNameType"/> of the contained resource name.
        public ResourceNameType Type { get; }

        ///
        /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
        /// unparsed resource name.
        ///
        public gax::UnparsedResourceName UnparsedResource { get; }

        ///
        /// The <c>DockerImage</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
        ///
        public string DockerImageId { get; }

        ///
        /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
        ///
        public string LocationId { get; }

        ///
        /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
        ///
        public string ProjectId { get; }

        ///
        /// The <c>Repository</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
        ///
        public string RepositoryId { get; }

        /// Whether this instance contains a resource name with a known pattern.
        public bool IsKnownPattern => Type != ResourceNameType.Unparsed;

        /// The string representation of the resource name.
        /// <returns>The string representation of the resource name.</returns>
        public override string ToString()
        {
            switch (Type)
            {
                case ResourceNameType.Unparsed: return UnparsedResource.ToString();
                case ResourceNameType.ProjectLocationRepositoryDockerImage: return s_projectLocationRepositoryDockerImage.Expand(ProjectId, LocationId, RepositoryId, DockerImageId);
                default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
            }
        }

        /// Returns a hash code for this resource name.
        public override int GetHashCode() => ToString().GetHashCode();

        /// <inheritdoc/>
        public override bool Equals(object obj) => Equals(obj as DockerImageName);

        /// <inheritdoc/>
        public bool Equals(DockerImageName other) => ToString() == other?.ToString();

        /// <inheritdoc/>
        public static bool operator ==(DockerImageName a, DockerImageName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);

        /// <inheritdoc/>
        public static bool operator !=(DockerImageName a, DockerImageName b) => !(a == b);
    }

    public partial class DockerImage
    {
        ///
        /// <see cref="gcav::DockerImageName"/>-typed view over the <see cref="Name"/> resource name property.
        ///
        public gcav::DockerImageName DockerImageName
        {
            get => string.IsNullOrEmpty(Name) ? null : gcav::DockerImageName.Parse(Name, allowUnparsed: true);
            set => Name = value?.ToString() ?? "";
        }
    }

    public partial class GetDockerImageRequest
    {
        ///
        /// <see cref="gcav::DockerImageName"/>-typed view over the <see cref="Name"/> resource name property.
        ///
        public gcav::DockerImageName DockerImageName
        {
            get => string.IsNullOrEmpty(Name) ? null : gcav::DockerImageName.Parse(Name, allowUnparsed: true);
            set => Name = value?.ToString() ?? "";
        }
    }
}


text:
class CreateParlors < ActiveRecord::Migration[5.0]
  def change
    create_table :parlors do |t|
      t.string :name
      t.string :street_address
      t.string :city
      t.string :state
      t.integer :zip_code
      t.boolean :chain
      t.timestamps
    end
  end
end


text:
package org.apache.storm.redis.state;

import com.google.common.base.Optional;
import org.apache.storm.state.DefaultStateSerializer;
import org.apache.storm.redis.common.container.JedisCommandsInstanceContainer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import redis.clients.jedis.BinaryClient;
import redis.clients.jedis.JedisCommands;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.SortingParams;
import redis.clients.jedis.Tuple;

import java.util.HashMap;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.*;

/**
 * Unit tests for {@link RedisKeyValueState}
 */
public class RedisKeyValueStateTest {
    JedisCommandsInstanceContainer mockContainer;
    JedisCommands mockCommands;
    RedisKeyValueState<String, String> keyValueState;

    @Before
    public void setUp() {
        final Map<String, Map<String, String>> mockMap = new HashMap<>();
        mockContainer = Mockito.mock(JedisCommandsInstanceContainer.class);
        mockCommands = Mockito.mock(JedisCommands.class);
        Mockito.when(mockContainer.getInstance()).thenReturn(mockCommands);
        ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class);
        ArgumentCaptor<String> stringArgumentCaptor2 = ArgumentCaptor.forClass(String.class);
        ArgumentCaptor<Map> mapArgumentCaptor = ArgumentCaptor.forClass(Map.class);

        Mockito.when(mockCommands.exists(Mockito.anyString()))
                .thenAnswer(new Answer<Boolean>() {
                    @Override
                    public Boolean answer(InvocationOnMock invocation) throws Throwable {
                        Object[] args = invocation.getArguments();
                        return mockMap.containsKey(args[0]);
                    }
                });

        Mockito.when(mockCommands.hmset(Mockito.anyString(), Mockito.anyMap()))
                .thenAnswer(new Answer<String>() {
                    @Override
                    public String answer(InvocationOnMock invocation) throws Throwable {
                        Object[] args = invocation.getArguments();
                        return hmset(mockMap, (String) args[0], (Map) args[1]);
                    }
                });

        Mockito.when(mockCommands.del(Mockito.anyString()))
                .thenAnswer(new Answer<Long>() {
                    @Override
                    public Long answer(InvocationOnMock invocation) throws Throwable {
                        Object[] args = invocation.getArguments();
                        return del(mockMap, (String) args[0]);
                    }
                });

        Mockito.when(mockCommands.hget(Mockito.anyString(), Mockito.anyString()))
                .thenAnswer(new Answer<String>() {
                    @Override
                    public String answer(InvocationOnMock invocation) throws Throwable {
                        Object[] args = invocation.getArguments();
                        return hget(mockMap, (String) args[0], (String) args[1]);
                    }
                });

        Mockito.when(mockCommands.hdel(Mockito.anyString(), Mockito.<String>anyVararg()))
                .thenAnswer(new Answer<Long>() {
                    @Override
                    public Long answer(InvocationOnMock invocation) throws Throwable {
                        Object[] args = invocation.getArguments();
                        int argsSize = args.length;
                        String[] fields = Arrays.asList(args).subList(1, argsSize).toArray(new String[argsSize - 1]);
                        return hdel(mockMap, (String) args[0], fields);
                    }
                });

        keyValueState = new RedisKeyValueState<String, String>("test", mockContainer, new DefaultStateSerializer<String>(),
                                                               new DefaultStateSerializer<String>());
    }

    @Test
    public void testPutAndGet() throws Exception {
        keyValueState.put("a", "1");
        keyValueState.put("b", "2");
        assertEquals("1", keyValueState.get("a"));
        assertEquals("2", keyValueState.get("b"));
        assertEquals(null, keyValueState.get("c"));
    }

    @Test
    public void testPutAndDelete() throws Exception {
        keyValueState.put("a", "1");
        keyValueState.put("b", "2");
        assertEquals("1", keyValueState.get("a"));
        assertEquals("2", keyValueState.get("b"));
        assertEquals(null, keyValueState.get("c"));
        assertEquals("1", keyValueState.delete("a"));
        assertEquals(null, keyValueState.get("a"));
        assertEquals("2", keyValueState.get("b"));
        assertEquals(null, keyValueState.get("c"));
    }

    @Test
    public void testPrepareCommitRollback() throws Exception {
        keyValueState.put("a", "1");
        keyValueState.put("b", "2");
        keyValueState.prepareCommit(1);
        keyValueState.put("c", "3");
        assertArrayEquals(new String[]{"1", "2", "3"}, getValues());
        keyValueState.rollback();
        assertArrayEquals(new String[]{null, null, null}, getValues());
        keyValueState.put("a", "1");
        keyValueState.put("b", "2");
        keyValueState.prepareCommit(1);
        keyValueState.commit(1);
        keyValueState.put("c", "3");
        assertArrayEquals(new String[]{"1", "2", "3"}, getValues());
        keyValueState.rollback();
        assertArrayEquals(new String[]{"1", "2", null}, getValues());
        keyValueState.put("c", "3");
        assertEquals("2", keyValueState.delete("b"));
        assertEquals("3", keyValueState.delete("c"));
        assertArrayEquals(new String[]{"1", null, null}, getValues());
        keyValueState.prepareCommit(2);
        assertArrayEquals(new String[]{"1", null, null}, getValues());
        keyValueState.commit(2);
        assertArrayEquals(new String[]{"1", null, null}, getValues());
        keyValueState.put("b", "2");
        keyValueState.prepareCommit(3);
        keyValueState.put("c", "3");
        assertArrayEquals(new String[]{"1", "2", "3"}, getValues());
        keyValueState.rollback();
        assertArrayEquals(new String[]{"1", null, null}, getValues());
    }

    private String[] getValues() {
        return new String[]{
                keyValueState.get("a"),
                keyValueState.get("b"),
                keyValueState.get("c")
        };
    }

    private String hmset(Map<String, Map<String, String>> mockMap, String key, Map value) {
        Map<String, String> currentValue = mockMap.get(key);
        if (currentValue == null) {
            currentValue = new HashMap<>();
        }
        currentValue.putAll(value);
        mockMap.put(key, currentValue);
        return "";
    }

    private Long del(Map<String, Map<String, String>> mockMap, String key) {
        if (mockMap.remove(key) == null)
            return 0L;
        else
            return 1L;
    }

    private String hget(Map<String, Map<String, String>> mockMap, String namespace, String key) {
        if (mockMap.containsKey(namespace)) {
            return mockMap.get(namespace).get(key);
        }
        return null;
    }

    private Long hdel(Map<String, Map<String, String>> mockMap, String namespace, String ... keys) {
        Long count = 0L;
        for (String key: keys) {
            if (mockMap.get(namespace).remove(key) != null) count++;
        }
        return count;
    }

}


text:
<?php

namespace Jhu\RestDocConverter\Converter;

/**
 *
 */
interface ConverterInterface
{
    /**
     * Convert a given specification to a list of conversions
     * containing the requests and their possible responses.
     *
     * @param  mixed    $filepath   Filepath to specification
     *
     * @return array                A list of Jhu\RestDocConverter\Conversion\ConversionInterface
     */
    public function convert($filepath);
}


text:
package edu.harvard.hul.ois.fits.consolidation;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;

import org.apache.log4j.Logger;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import edu.harvard.hul.ois.fits.Fits;
import edu.harvard.hul.ois.fits.FitsOutput;
import edu.harvard.hul.ois.fits.exceptions.FitsConfigurationException;
import edu.harvard.hul.ois.fits.identity.ExternalIdentifier;
import edu.harvard.hul.ois.fits.identity.ToolIdentity;
import edu.harvard.hul.ois.fits.identity.FitsIdentity;
import edu.harvard.hul.ois.fits.identity.FormatVersion;
import edu.harvard.hul.ois.fits.tools.Tool;
import edu.harvard.hul.ois.fits.tools.ToolInfo;
import edu.harvard.hul.ois.fits.tools.ToolOutput;
import edu.harvard.hul.ois.fits.tools.utils.XmlUtils;

public class OISConsolidator implements ToolOutputConsolidator {

    private static Namespace xsiNS = Namespace.getNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");

    private Logger logger = Logger.getLogger(this.getClass());

	private boolean reportConflicts;
	private boolean displayToolOutput;
	private Document formatTree;

	private final static int CONFLICT = 0;
	private final static int SINGLE_RESULT = 1;
	private final static int ALL_AGREE = 2;

	static private final String REAL_NUMBER = "^[-+]?\\d+(\\.\\d+)?$";

	static private final List<String> repeatableElements =  new ArrayList<String>(Arrays.asList("linebreak"));  ;

	private final static Namespace fitsNS = Namespace.getNamespace(Fits.XML_NAMESPACE);

	public OISConsolidator() throws FitsConfigurationException {

		reportConflicts = Fits.config.getBoolean("output.report-conflicts",true);
		displayToolOutput = Fits.config.getBoolean("output.display-tool-output",false);
		SAXBuilder saxBuilder = new SAXBuilder();
		try {
			formatTree = saxBuilder.build(Fits.FITS_XML+"fits_format_tree.xml");
		} catch (Exception e) {
			throw new FitsConfigurationException("",e);
		}
		//fitsNS = Namespace.getNamespace(Fits.XML_NAMESPACE);
	}

	private Element findAnElement(List<ToolOutput> results, String xpath_query, boolean useChildren) {
		for(ToolOutput result : results) {
			Document dom = result.getFitsXml();
			try {
				//only look at non null dom structures
				if(dom != null) {
					XPath xpath = XPath.newInstance(xpath_query);
					xpath.addNamespace("fits",Fits.XML_NAMESPACE);
					Element e = (Element)xpath.selectSingleNode(dom);
					if(e != null && e.getChildren().size() > 0) {
						if(useChildren) {
							e = (Element)e.getChildren().get(0);
						}
						List children = e.getChildren();
						if(children.size()>0) {
							Element child = (Element)children.get(0);
							return child;
						}
					}
				}
			} catch (JDOMException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * Removes null and unknown output from ToolOutput results
	 * @param results
	 * @return
	 */
	private List<ToolOutput> cullResults(List<ToolOutput> results) {
		List<ToolOutput> newResults = new ArrayList<ToolOutput>();
		for(ToolOutput result : results) {
			if(result != null) {
				Tool t = result.getTool();
				//if the tool can't identify files, or if it can and all identities are good
				if(!t.canIdentify() || (t.canIdentify() && allIdentitiesAreGood(result))) {
					newResults.add(result);
				}
				else {
					logger.debug("tossing " + t.getName() + " identification because of invalid identification");
				}
			}
		}
		return newResults;
	}

	/**
	 * Skips null identities and returns the first tools unknown Identities that are found
	 * @param results
	 * @return
	 */
	private List<FitsIdentity> getFirstUnknownIdentity(List<ToolOutput> results) {
		List<FitsIdentity> identities = new ArrayList<FitsIdentity>();
		for(ToolOutput result : results) {
			//if result is null skip it
			if(result == null) {
				continue;
			}
			List<ToolIdentity> toolIdentities = result.getFileIdentity();
			if(result.getTool().canIdentify() && toolIdentities != null && toolIdentities.size() > 0) {
				for(ToolIdentity fileIdent : toolIdentities) {
					identities.add(new FitsIdentity(fileIdent));
				}
				break;
			}
		}
		return identities;
	}

	/**
	 * Skips null identities and returns the first tools unknown Identities that are found
	 * @param results
	 * @return
	 */
	private List<FitsIdentity> getFirstPartialIdentity(List<ToolOutput> results) {
		List<FitsIdentity> identities = new ArrayList<FitsIdentity>();
		for(ToolOutput result : results) {
			//if result is null skip it
			if(result == null) {
				continue;
			}
			List<ToolIdentity> toolIdentities = result.getFileIdentity();
			if(result.getTool().canIdentify() && toolIdentities != null && toolIdentities.size() > 0) {
				if(isPartialIdentity(toolIdentities)) {
					for(ToolIdentity fileIdent : toolIdentities) {
						identities.add(new FitsIdentity(fileIdent));
					}
					break;
				}

			}
		}
		return identities;
	}

	private boolean allIdentitiesAreGood(ToolOutput result) {
		List<ToolIdentity> identities = result.getFileIdentity();
		if(identities.size() == 0) {
			return false;
		}
		Tool t = result.getTool();
		for(ToolIdentity ident : identities) {
			if(t.isIdentityKnown(ident)) {
				continue;
			}
			else {
				return false;
			}
		}
		return true;
	}

	private List<Element> mergeXmlesults(List<ToolOutput> results, Element element) {
		//holder for consolidated elements
		List<Element> consolidatedElements = new ArrayList<Element>();
		//Get the element from each ToolOutput result
		List<Element> fitsElements = new ArrayList<Element>();
		for(ToolOutput result : results) {
			Document dom = result.getFitsXml();
			//if dom is null there is nothing to merge
			if(dom == null) {
				continue;
			}
			ToolInfo toolInfo = result.getTool().getToolInfo();
			try {
				XPath xpath = XPath.newInstance("//fits:"+element.getName());
				xpath.addNamespace("fits",Fits.XML_NAMESPACE);
				Element e = (Element)xpath.selectSingleNode(dom);
				if(e != null) {
					e.setAttribute("toolname",toolInfo.getName());
					e.setAttribute("toolversion",toolInfo.getVersion());
					fitsElements.add(e);
					e.getParent().removeContent(e);
				}
			}
			catch(JDOMException e) {
				e.printStackTrace();
			}
		}

		//remove any unknown values
		fitsElements = removeUnknowns(fitsElements);
		//if there are no elements after removing unknowns just return null
		if(fitsElements.size() == 0) {
			return fitsElements;
		}
		int equalityResult = testEquality(fitsElements);
		if(equalityResult == ALL_AGREE) {
			//since all tools agreed, or all conflicts could be resolved
			//return the element without the identifying tool name and version
			Element e = fitsElements.get(0);
			//Commented out so tool name and version are always displayed
			//e.removeAttribute("toolname");
			//e.removeAttribute("toolversion");
			consolidatedElements.add(e);
		}
		else if(equalityResult == SINGLE_RESULT) {
			Element e = fitsElements.get(0);
			e.setAttribute("status","SINGLE_RESULT");
			consolidatedElements.add(e);
		}
		//if configured to report conflicts return all values in fitsElements
		else if(equalityResult == CONFLICT && reportConflicts && !isRepeatableElement(fitsElements)) {
			for(Element e : fitsElements) {
				e.setAttribute("status","CONFLICT");
			}
			//to flatten any matches into single results
			consolidatedElements = consolidateFitsElements(fitsElements);
		}
		else {
			//pick first value using preferred tool list
			Element e = fitsElements.get(0);
			consolidatedElements.add(e);
		}
		return consolidatedElements;
	}

	private boolean isRepeatableElement(List<Element> fitsElements) {
		String name = fitsElements.get(0).getName();
		if(repeatableElements.contains(name)) {
			return true;
		}
		else {
			return false;
		}
	}

	private List<Element> consolidateFitsElements(List<Element> fitsElements) {
		List<Element> conElements = new ArrayList<Element>();
		for(Element e : fitsElements) {
			ListIterator<Element> iter = conElements.listIterator();
			boolean anyMatches = false;
			while ( iter.hasNext() ) {
				//compare e with conElement
				Element conElement = iter.next();
				if(conElement.getText().equalsIgnoreCase(e.getText())) {
					//elements match so don't add it
					anyMatches = true;
					break;
				}
			}
			if(!anyMatches) {
				iter.add(e);
			}
		}
		return conElements;
	}

	private synchronized List<Element> removeUnknowns(List<Element> fitsElements) {
		ListIterator<Element> iter = fitsElements.listIterator();
		while ( iter.hasNext() ) {
			Element e = iter.next();
			if(e == null || e.getValue() == null || e.getText().length() == 0) {
				//remove the element from the list
				iter.remove();
				//fitsElements.remove(e);
			}
		}
		return fitsElements;
	}

	private int testEquality(List<Element> fitsElements) {
		if(fitsElements.size() == 1) {
			return SINGLE_RESULT;
		}
		Element e = fitsElements.get(0);
		String eText = e.getText();
		for(int i=1;i<fitsElements.size();i++) {
			Element ee = fitsElements.get(i);
			//if both match as strings
			if(eText.equalsIgnoreCase(ee.getText())) {
				continue;
			}
			//else check as digits
			else if(eText.matches(REAL_NUMBER) && ee.getText().matches(REAL_NUMBER)) {
				Double e_d = Double.parseDouble(eText);
				Double ee_d =  Double.parseDouble(ee.getText());
				if(e_d.compareTo(ee_d) == 0) {
					continue;
				}
				else {
					return CONFLICT;
				}
			}
			else {
				return CONFLICT;
			}
		}
		return ALL_AGREE;
	}

	private boolean parentContainsChild(Element parent, String childName) {
		List<Element> children = parent.getChildren();
		for(Element e : children) {
			if(e.getName().equalsIgnoreCase(childName)) {
				return true;
			}
		}
		return false;
	}

	private List<ToolIdentity> getAllIdentities(List<ToolOutput> results) {
		List<ToolIdentity> identities = new ArrayList<ToolIdentity>();
		for(ToolOutput result : results) {
			if(result.getTool().canIdentify()) {
				List<ToolIdentity> identList = result.getFileIdentity();
				for(ToolIdentity ident : identList) {
					identities.add(ident);
				}
			}
		}
		return identities;
	}

	private boolean identitiesMatch(ToolIdentity a, FitsIdentity b) {
		//if format and mimetype match
		if(a.getFormat().equalsIgnoreCase(b.getFormat())
				&& a.getMime().equalsIgnoreCase(b.getMimetype())) {
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * merge from a to b
	 * @return
	 */
	private void mergeExternalIdentifiers(ToolIdentity a, FitsIdentity b) {
		//add external identifiers to consolidated element from the new item, checking for duplicates
		for(ExternalIdentifier xIdent : a.getExternalIds()) {
			if(!b.hasExternalIdentifier(xIdent)) {
				b.addExternalID(xIdent);
			}
		}
	}

	private void mergeFormatVersions(ToolIdentity a, FitsIdentity b) {
		FormatVersion v = a.getFormatVersion();
		if(v != null && v.getValue() != null && !b.hasFormatVersion(v)) {
			b.addFormatVersion(v);
		}
	}

	private List<FitsIdentity> consolidateIdentities(List<ToolIdentity> identities) {
		List<FitsIdentity> consolidatedIdentities = new ArrayList<FitsIdentity>();
		for(ToolIdentity ident : identities) {
			ListIterator<FitsIdentity> iter = consolidatedIdentities.listIterator();
			boolean anyMatches = false;
			boolean formatTreeMatch = false;
			while ( iter.hasNext() ) {
				//compare ident with conIdent
				FitsIdentity identitySection = (FitsIdentity)iter.next();
				if(identitiesMatch(ident,identitySection)) {
					//Add external identifiers from ident to the existing item
					mergeExternalIdentifiers(ident,identitySection);
					//add format versions from ident to the existing item
					mergeFormatVersions(ident,identitySection);
					//add reporting tools from ident to the existing item
					identitySection.addReportingTool(ident.getToolInfo());
					//we found a match
					anyMatches = true;
					break;
				}
				//if identities don't match check format tree for specific/generic formats
				else {
					int matchCondition = checkFormatTree(ident,identitySection);
					if(matchCondition == -1) {
						logger.debug(ident.getFormat() + " is more specific than " + identitySection.getFormat() + " tossing out " + identitySection.getToolName());
						//ident is more specific.  Most specific identity should always
						// be first element in list
						// overwrite the formate with more specific format
						identitySection.setFormat(ident.getFormat());
						// overwrite the formate with more specific mimetype
						identitySection.setMimetype((ident.getMime()));
						//Add external identifiers from ident to the existing item
						mergeExternalIdentifiers(ident,identitySection);
						//add format versions from ident to the existing item
						mergeFormatVersions(ident,identitySection);
						//add reporting tools from ident to the existing item
						identitySection.addReportingTool(ident.getToolInfo());
						//FitsIdentity newSection = new FitsIdentity(ident);
						//add new section
						//backup on one position
						//iter.previous();
						//add the new item
						//iter.add(newSection);
						//skip head to next item
						//iter.next();
						//delete
						//iter.remove();
						//indicate we found a match
						anyMatches = true;
						break;
					}
					// existing format is more specific
					else if(matchCondition == 1) {
						logger.debug(identitySection.getFormat() + " is more specific than " + ident.getFormat() + " tossing out " + ident.getToolInfo().getName());
						formatTreeMatch = true;
						//do nothing, keep going and add to consolidated identities if no other matches
					}
					//formats are not specific or generic version of one another
					else {
						//leave anyMatches as false so ident is added to consolidated identities
					}
				}
			}
			//if there were no matches to existing consolidated identities add it
			if(!anyMatches && !formatTreeMatch) {
				iter.add(new FitsIdentity(ident));
			}
		}
		return consolidatedIdentities;
	}

	/**
	 * Returns 1 if a  is more specific than b.  Returns -1 if b is more specific than a.
	 * If neither is more specific then 0 is returned.
	 * @param a
	 * @param b
	 * @return
	 */
	private int checkFormatTree(ToolIdentity a, FitsIdentity b) {

		//if formats are equal then just return
		if(a.getFormat().equals(b.getFormat())) {
			return 0;
		}

		//check if a is more specific than b
		Attribute a_attr = new Attribute("format",a.getFormat());
		Attribute b_attr = new Attribute("format",b.getFormat());

		Element root = formatTree.getRootElement();
		Element a_element = XmlUtils.getChildWithAttribute(root,a_attr);
		Element b_element = XmlUtils.getChildWithAttribute(root,b_attr);

		if(a_element != null && b_element != null) {
			//if a contains b's attribute, so b is more specific
			if(XmlUtils.getChildWithAttribute(a_element,b_attr) != null) {
				return 1;
			}
			//if b contains a's attribute, so a is more specific
			else if(XmlUtils.getChildWithAttribute(b_element,a_attr) != null) {
				return -1;
			}
			else {
				return 0;
			}
		}
		return 0;
	}

	private void filterToolOutput(FitsIdentity section, List<ToolOutput> results) {
		ListIterator<ToolOutput> iter = results.listIterator();
		while ( iter.hasNext() ) {
			ToolOutput result = iter.next();
			//if the identity section doesn't contain the results from the tool remove it
			if(!section.hasOutputFromTool(result.getTool().getToolInfo())) {
				iter.remove();
			}
		}
	}

	/* (non-Javadoc)
	 * @see edu.harvard.hul.ois.fits.DataConsolidator#processResults(java.util.List)
	 */
	public FitsOutput processResults(List<ToolOutput> results) {
		//Remove any null results, or results from tools that have the capability to identify files,
		// but couldn't identify the file.
		List<ToolOutput> culledResults = cullResults(results);

		//start building the FITS xml document
		Document mergedDoc = new Document();
		Element fits = new Element("fits",fitsNS);

		fits.addNamespaceDeclaration(xsiNS);
		fits.setAttribute(new Attribute("schemaLocation",Fits.XML_NAMESPACE+" "+Fits.externalOutputSchema, xsiNS));

		fits.setAttribute("version", Fits.VERSION);
		DateFormat dateFormat = new SimpleDateFormat();
		Date date = new Date();
		fits.setAttribute("timestamp",dateFormat.format(date));

		Element identificationsection = new Element("identification",fitsNS);
		fits.addContent(identificationsection);
		mergedDoc.addContent(fits);

		String curSec;
		String curSecName;

		//check identities
			//one "identity" per unique combination of format and mimetype
		List<ToolIdentity> identities = getAllIdentities(culledResults);
		List<FitsIdentity> identitySections = new ArrayList<FitsIdentity>();
		boolean unknownStatus = false;
		boolean partialStatus = false;
		//If there are no known identities in the culled results
		if(identities.size() == 0) {
			//try to find a partial identity match in the original results
			identitySections = getFirstPartialIdentity(results);
			if(identitySections.size() == 0)  {
				//get the first default unknown identity from original results
				unknownStatus = true;
				identitySections = getFirstUnknownIdentity(results);
			}
			else {
				partialStatus = true;
			}

		}
		else {
			//else merge the known identities
			identitySections = consolidateIdentities(identities);
		}

		for(FitsIdentity identSection : identitySections) {
			Element identElement = new Element("identity",fitsNS);
			Attribute identFormatAttr = new Attribute("format",identSection.getFormat());
			Attribute identMimeAttr = new Attribute("mimetype",identSection.getMimetype());
			Attribute fitsToolName = new Attribute("toolname",identSection.getToolName());
			Attribute fitsToolVersion = new Attribute("toolversion",identSection.getToolVersion());

			//set format and mimetype attributes
			identElement.setAttribute(identFormatAttr);
			identElement.setAttribute(identMimeAttr);
			identElement.setAttribute(fitsToolName);
			identElement.setAttribute(fitsToolVersion);

			//add reporting tools
			for(ToolInfo info : identSection.getReportingTools()) {
				Element tool = new Element("tool",fitsNS);
				tool.setAttribute("toolname", info.getName());
				tool.setAttribute("toolversion", info.getVersion());
				identElement.addContent(tool);
			}
			 // tools agree
			 boolean toolsAgree = (identitySections.size() == 1 && identSection.getReportingTools().size() > 1);

			//add format version

			List<FormatVersion> formatVersions = identSection.getFormatVersions();
			String formatStatus = null;
			if(formatVersions.size() > 1) {
				formatStatus = "CONFLICT";
			}

			//only add if there is a version number to report
			if(formatVersions.size() > 0) {
				for(FormatVersion version : formatVersions) {
					Element identVersion = new Element("version",fitsNS);
					identVersion.setAttribute("toolname",version.getToolInfo().getName());
					identVersion.setAttribute("toolversion",version.getToolInfo().getVersion());
					if(formatStatus != null) {
						identVersion.setAttribute("status",formatStatus);
					}
					identVersion.setText(version.getValue());
					identElement.addContent(identVersion);
				}
			}

			for(ExternalIdentifier xId : identSection.getExternalIdentifiers()) {
				Element externalID = new Element("externalIdentifier",fitsNS);
				ToolInfo xIdInfo = xId.getToolInfo();
				externalID.setAttribute("toolname",xIdInfo.getName());
				externalID.setAttribute("toolversion",xIdInfo.getVersion());
				externalID.setAttribute("type",xId.getName());
				externalID.setText(xId.getValue());
				identElement.addContent(externalID);
			}
			//set the status of the section
			String status = "";
			if(identitySections.size() > 1 && reportConflicts) {
				status = "CONFLICT";
			}
			else if((identitySections.size() == 1 && (!unknownStatus && !partialStatus && !toolsAgree)) || !reportConflicts) {
				status="SINGLE_RESULT";
			}
			else if(identitySections.size() == 1 && partialStatus) {
				status = "PARTIAL";
			}
			else if (!toolsAgree) {
				status = "UNKNOWN";
			}

			 if (status != "")
				 {
						identificationsection.setAttribute("status",status);
				 }

			identificationsection.addContent(identElement);

			//if conflicts are being reported continue, else break after 1 iteration
			if(reportConflicts) {
				continue;
			}
			else {
				break;
			}
		}

		//check fileinfo, do normal xml comparison.  Use all non-culled tool output
		curSec = "/fits:fits/fits:fileinfo";
		//curSec = "/fits/fileinfo";
		curSecName = "fileinfo";
		Element s = new Element(curSecName,fitsNS);
		fits.addContent(s);
		Element e = null;
		while((e = findAnElement(culledResults,curSec,false)) != null) {
			List<Element> fitsElements = mergeXmlesults(culledResults, e);
			for(Element fitsElement : fitsElements) {
				s.addContent(fitsElement);
			}
		}

		//Only use the output from tools that were able to identify
		// the file and are in the first identity section
		if(identitySections.size() > 0) {
			filterToolOutput(identitySections.get(0),culledResults);
		}

		//check filestatus, do normal xml comparison
		curSec = "/fits:fits/fits:filestatus";
		//curSec = "/fits/filestatus";
		curSecName = "filestatus";
		s = new Element(curSecName,fitsNS);
		fits.addContent(s);
		e = null;
		while((e = findAnElement(culledResults,curSec,false)) != null) {
			List<Element> fitsElements = mergeXmlesults(culledResults, e);
			for(Element fitsElement : fitsElements) {
				s.addContent(fitsElement);
			}
		}

		//check metadata/child
			//if child.getParent() !exist in mergedDoc, then create and add these elements to it.
			//  else, add to existing section in mergedDoc
			//then do normal xml comparison
		curSec = "/fits:fits/fits:metadata";
		//curSec = "/fits/metadata";
		curSecName = "metadata";
		s = new Element(curSecName,fitsNS);
		fits.addContent(s);
		e = null;
		while((e = findAnElement(culledResults,curSec,true)) != null) {
			Element eParent = e.getParentElement();
			Element metadataType = null;
			if(!parentContainsChild(s,eParent.getName())) {
				metadataType = new Element(eParent.getName(),fitsNS);
				s.addContent(metadataType);
			}
			else {
				metadataType = s.getChild(eParent.getName(),fitsNS);
			}
			List<Element> fitsElements = mergeXmlesults(culledResults, e);
			for(Element fitsElement : fitsElements) {
				metadataType.addContent(fitsElement);
			}
		}

		//Consolidate results from each tool
		// Check for identical and unknown values for each field
		// Check format tree for specific/generic formats
		// if conflicts exist && configured to report multiple values in conflict
			//report both values
		// else
			// pick value using preferred tool list ordering

		//while non empty results exist - check for elements in //identity, //info and //metadata (method for this)
		//Start with first result that is not empty (method for this to grab any element from these sections)
			//pull out an element
				//  /fits/summary/identity
				//  /fits/summary/info
				//  /fits/summary/metadata
			//look up and pull that element out of other results
			//do comparison
				//Identical?
				//unknown values?
				//consult tree?
				//configured to report multiple conflicting values?
					//use preferred ordering of tools
			//add result or results if configured to report multiples when conflict exists
			//to mergedDoc

			//continue with next element until result is empty
			//continue with all results until all are empty.

		if(displayToolOutput) {
			Element toolOutput = new Element("toolOutput",fitsNS);
			for(ToolOutput output : results) {
				if(output != null) {
					Element tool = new Element("tool",fitsNS);
					tool.setAttribute("name",output.getTool().getToolInfo().getName());
					tool.setAttribute("version",output.getTool().getToolInfo().getVersion());
					Document doc = output.getToolOutput();
					if(doc != null) {
						Element root = (Element)doc.getRootElement().detach();
						tool.addContent(root);
						toolOutput.addContent(tool);
						}
				}
			}
			fits.addContent(toolOutput);
		}

		FitsOutput result = new FitsOutput(mergedDoc);
		return result;
	}

	private boolean isPartialIdentity(List<ToolIdentity> identities) {
		ToolIdentity identity = identities.get(0);
		if(identity != null) {
			String mime = identity.getMime();
			String format = identity.getFormat();

			boolean validMime = (mime != null && mime.length()>0);
			boolean validFormat = (format != null && format.length()>0);

			if((validMime && validFormat) ||
					(validMime && !validFormat) ||
					(validFormat && !validMime)) {
				if((mime.equals("application/octet-stream")
						&& !format.equals("Unknown Binary"))
						||
						(format.equals("Unknown Binary")
						&& !mime.equals("application/octet-stream"))) {
					return true;
				}
			}
		}
		return false;
	}

}


text:
package android.widget;

import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.ArrowKeyMovementMethod;
import android.text.method.MovementMethod;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

/*
 * This is supposed to be a *very* thin veneer over TextView.
 * Do not make any changes here that do anything that a TextView
 * with a key listener and a movement method wouldn't do!
 */

/**
 * EditText is a thin veneer over TextView that configures itself
 * to be editable.
 *
 *
See the Text Fields
 * guide.

 *

 * XML attributes
 *

 * See {@link android.R.styleable#EditText EditText Attributes},
 * {@link android.R.styleable#TextView TextView Attributes},
 * {@link android.R.styleable#View View Attributes}
 */
public class EditText extends TextView {
    public EditText(Context context) {
        this(context, null);
    }

    public EditText(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.editTextStyle);
    }

    public EditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected boolean getDefaultEditable() {
        return true;
    }

    @Override
    protected MovementMethod getDefaultMovementMethod() {
        return ArrowKeyMovementMethod.getInstance();
    }

    @Override
    public Editable getText() {
        return (Editable) super.getText();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, BufferType.EDITABLE);
    }

    /**
     * Convenience for {@link Selection#setSelection(Spannable, int, int)}.
     */
    public void setSelection(int start, int stop) {
        Selection.setSelection(getText(), start, stop);
    }

    /**
     * Convenience for {@link Selection#setSelection(Spannable, int)}.
     */
    public void setSelection(int index) {
        Selection.setSelection(getText(), index);
    }

    /**
     * Convenience for {@link Selection#selectAll}.
     */
    public void selectAll() {
        Selection.selectAll(getText());
    }

    /**
     * Convenience for {@link Selection#extendSelection}.
     */
    public void extendSelection(int index) {
        Selection.extendSelection(getText(), index);
    }

    @Override
    public void setEllipsize(TextUtils.TruncateAt ellipsis) {
        if (ellipsis == TextUtils.TruncateAt.MARQUEE) {
            throw new IllegalArgumentException("EditText cannot use the ellipsize mode "
                    + "TextUtils.TruncateAt.MARQUEE");
        }
        super.setEllipsize(ellipsis);
    }

    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        super.onInitializeAccessibilityEvent(event);
        event.setClassName(EditText.class.getName());
    }

    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        info.setClassName(EditText.class.getName());
    }
}


text:
using System.Collections.Immutable;
using System.Text.RegularExpressions;

using Microsoft.Recognizers.Text.Number;

namespace Microsoft.Recognizers.Text.DateTime
{
    public interface IDateTimePeriodParserConfiguration : IOptionsConfiguration
    {
        IDateTimeExtractor DateExtractor { get; }

        IDateTimeExtractor TimeExtractor { get; }

        IDateTimeExtractor DateTimeExtractor { get; }

        IDateTimeExtractor TimePeriodExtractor { get; }

        IDateTimeExtractor DurationExtractor { get; }

        IExtractor CardinalExtractor { get; }

        IParser NumberParser { get; }

        IDateTimeParser DateParser { get; }

        IDateTimeParser TimeParser { get; }

        IDateTimeParser DateTimeParser { get; }

        IDateTimeParser TimePeriodParser { get; }

        IDateTimeParser DurationParser { get; }

        Regex PureNumberFromToRegex { get; }

        Regex PureNumberBetweenAndRegex { get; }

        Regex SpecificTimeOfDayRegex { get; }

        Regex TimeOfDayRegex { get; }

        Regex PastRegex { get; }

        Regex FutureRegex { get; }

        Regex NumberCombinedWithUnitRegex { get; }

        Regex UnitRegex { get; }

        Regex PeriodTimeOfDayWithDateRegex { get; }

        Regex RelativeTimeUnitRegex { get; }

        Regex RestOfDateTimeRegex { get; }

        IImmutableDictionary<string, string> UnitMap { get; }

        IImmutableDictionary<string, int> Numbers { get; }

        bool GetMatchedTimeRange(string text, out string timeStr, out int beginHour, out int endHour, out int endMin);

        int GetSwiftPrefix(string text);
    }
}


text:
var Offshore = require('../../../lib/offshore'),
    assert = require('assert');

describe('Collection Query', function() {

  describe('.create()', function() {

    describe('with nested model values', function() {
      var query;

      before(function(done) {

        var offshore = new Offshore();
        var Model = Offshore.Collection.extend({
          identity: 'user',
          connection: 'foo',
          attributes: {
            name: {
              type: 'string',
              defaultsTo: 'Foo Bar'
            },
            nestedModel: {
              model: 'nested'
            }
          }
        });
        var Nested = Offshore.Collection.extend({
          identity: 'nested',
          connection: 'foo',
          attributes: {
            name: 'string'
          }
        });

        offshore.loadCollection(Model);
        offshore.loadCollection(Nested);

        // Fixture Adapter Def
        var _id = 1;
        var findValues = [];

        var adapterDef = {
          create: function(con, col, values, cb) {
            values.id = _id;
            findValues.push(values);
            _id++;
            return cb(null, values);
          },
          find: function(con, col, criteria, cb) {
            cb(null, findValues[_id - 1]);
          }
        };

        var connections = {
          'foo': {
            adapter: 'foobar'
          }
        };

        offshore.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) {
          if(err) return done(err);
          query = colls.collections.user;
          done();
        });
      });

      it('should reduce the nested object down to a foreign key', function(done) {
        query.create({ name: 'foo', nestedModel: { name: 'joe' }}, function(err, status) {
          assert(!err);
          assert(status.nestedModel);
          assert(status.nestedModel === 1);
          done();
        });
      });
    });

    describe('with nested collection values', function() {
      var query, updatedModels = [], findValues = [];

      before(function(done) {

        var offshore = new Offshore();
        var Model = Offshore.Collection.extend({
          identity: 'user',
          connection: 'foo',
          attributes: {
            name: {
              type: 'string',
              defaultsTo: 'Foo Bar'
            },
            nestedModels: {
              collection: 'nested',
              via: 'model'
            }
          }
        });
        var Nested = Offshore.Collection.extend({
          identity: 'nested',
          connection: 'foo',
          attributes: {
            name: 'string',
            model: {
              model: 'user'
            }
          }
        });

        offshore.loadCollection(Model);
        offshore.loadCollection(Nested);

        var _id = 1;
        var adapterDef = {
          create: function(con, col, values, cb) {
            values.id = _id;
            findValues.push(values);
            _id++;
            return cb(null, values);
          },
          find: function(con, col, criteria, cb) {
            cb(null, findValues[_id - 1]);
          },
          update: function(con, col, criteria, values, cb) {
            updatedModels.push(criteria.where);
            return cb(null, [values]);
          }
        };

        var connections = {
          'foo': {
            adapter: 'foobar'
          }
        };

        offshore.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) {
          if(err) return done(err);
          query = colls.collections.user;
          done();
        });
      });

      it('should attempt to update each nested model', function(done) {

        var nestedModels = [
          { name: 'joe', model: 2 },
          { name: 'moe', model: 3 },
          { name: 'flow', model: 4 }
        ];

        query.create({ id: 5, name: 'foo', nestedModels: nestedModels }, function(err, status) {
          assert(!err);
          assert(status.nestedModels.length === 0);
          assert(findValues.length === 4);
          done();
        });
      });
    });

  });
});


text:
/**
 * User metadata store config classes.
 */
package com.netflix.metacat.metadata.store.configs;


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('service-legend', 'Integration | Component | service legend', {
  integration: true
});

test('it renders', function(assert) {
  this.render(hbs`{{service-legend}}`);
  assert.equal(this.$('.service-legend__entry').length, 14);
});


text:
require "rails_helper"

RSpec.describe Item, :type => :feature do
  it "without any arguments" do
    expect(subject).to be_invalid
  end
end