text:
<!DOCTYPE html>

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

    <link rel="icon" type="image/png" href="https://just2us.com/img/favicon-180.png" />
    <link rel="apple-touch-icon" href="https://just2us.com/img/favicon-192.png"/>

    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/clean-blog.min.css">
    <link rel="stylesheet" href="/css/syntax.css">

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic&display=swap' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&display=swap' rel='stylesheet' type='text/css'>

    <link type="application/atom+xml" rel="alternate" href="https://just2me.com/feed.xml" title="Just2me" />

<title>iCallQ, a copy of Hoiio | Just2me</title>
<meta name="generator" content="Jekyll v4.0.0" />
<meta property="og:title" content="iCallQ, a copy of Hoiio" />
<meta name="author" content="Junda Ong" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="iCallQ is a recent calling app developed by sgcoders, who probably develops software for LFI, a popular MLM (Multi-level Marketing) company in Singapore." />
<meta property="og:description" content="iCallQ is a recent calling app developed by sgcoders, who probably develops software for LFI, a popular MLM (Multi-level Marketing) company in Singapore." />
<link rel="canonical" href="https://just2me.com/2011/03/30/icallq-copy-of-hoiio/" />
<meta property="og:url" content="https://just2me.com/2011/03/30/icallq-copy-of-hoiio/" />
<meta property="og:site_name" content="Just2me" />
<meta property="og:image" content="https://just2me.com/img/jewel-fountain.jpeg" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2011-03-30T16:51:00+08:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:image" content="https://just2me.com/img/jewel-fountain.jpeg" />
<meta property="twitter:title" content="iCallQ, a copy of Hoiio" />
<meta name="twitter:site" content="@samwize" />
<meta name="twitter:creator" content="@Junda Ong" />
<meta property="fb:admins" content="704185456" />

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

            </button>
            Just2me

                  Stories

                  Apps

                  Quotes

                  About

iCallQ, a copy of Hoiio

                    Published on March 30, 2011

iCallQ is a recent calling app developed by sgcoders, who probably develops software for LFI, a popular MLM (Multi-level Marketing) company in Singapore.

The point that iCallQ is built around a MLM model makes it rather innovative. Applauds for that.

But what intrigues me most about iCallQ is how similar it is with Hoiio, where I was the iPhone developer.

Look at the comparison:

Similar, eh?

    TAGGED WITH

    app

                        How TIN PEI LING can turn the table around →

                        ← Review a scam from Joy's ElectroMart

                Please enable JavaScript to view the comments powered by Disqus.

Copyright © Junda Ong 1983-2021


text:
namespace Mgc {

// squared distance measurements

MAGICFM Real SqrDistance (const Line3& rkLine, const Rectangle3& rkRct,
    Real* pfLinP = NULL, Real* pfRctP0 = NULL, Real* pfRctP1 = NULL);

MAGICFM Real SqrDistance (const Ray3& rkRay, const Rectangle3& rkRct,
    Real* pfRayP = NULL, Real* pfRctP0 = NULL, Real* pfRctP1 = NULL);

MAGICFM Real SqrDistance (const Segment3& rkSeg, const Rectangle3& rkRct,
    Real* pfSegP = NULL, Real* pfRctP0 = NULL, Real* pfRctP1 = NULL);

// distance measurements

MAGICFM Real Distance (const Line3& rkLine, const Rectangle3& rkRct,
    Real* pfLinP = NULL, Real* pfRctP0 = NULL, Real* pfRctP1 = NULL);

MAGICFM Real Distance (const Ray3& rkRay, const Rectangle3& rkRct,
    Real* pfRayP = NULL, Real* pfRctP0 = NULL, Real* pfRctP1 = NULL);

MAGICFM Real Distance (const Segment3& rkSeg, const Rectangle3& rkRct,
    Real* pfSegP = NULL, Real* pfRctP0 = NULL, Real* pfRctP1 = NULL);

} // namespace Mgc

#endif

redpajama_set_name: RedPajamaGithub


text:
docker build -t cifar10-classification .
docker run -v `pwd`/../:/opt/ -t cifar10-classification cifar10_shallow_classifier.py


text:
package lila.common

import akka.actor._
import akka.event._

final class Bus(system: ActorSystem) extends Extension with EventBus {

  type Event = Bus.Event
  type Classifier = Symbol
  type Subscriber = ActorRef

  def publish(payload: Any, channel: Classifier) {
    publish(Bus.Event(payload, channel))
  }

  /**
   * Attempts to register the subscriber to the specified Classifier
   * @return true if successful and false if not (because it was already subscribed to that Classifier, or otherwise)
   */
  def subscribe(subscriber: Subscriber, to: Classifier): Boolean = {
    // log(s"subscribe $to $subscriber")
    bus.subscribe(subscriber, to)
  }

  def subscribe(subscriber: Subscriber, to: Classifier*): Boolean = {
    to foreach { subscribe(subscriber, _) }
    true
  }

  /**
   * Attempts to deregister the subscriber from the specified Classifier
   * @return true if successful and false if not (because it wasn't subscribed to that Classifier, or otherwise)
   */
  def unsubscribe(subscriber: Subscriber, from: Classifier): Boolean = {
    // log(s"[UN]subscribe $from $subscriber")
    bus.unsubscribe(subscriber, from)
  }

  /**
   * Attempts to deregister the subscriber from all Classifiers it may be subscribed to
   */
  def unsubscribe(subscriber: Subscriber) {
    // log(s"[UN]subscribe ALL $subscriber")
    bus unsubscribe subscriber
  }

  /**
   * Publishes the specified Event to this bus
   */
  def publish(event: Event) {
    // log(event.toString)
    bus publish event
  }

  private def log(msg: => String) {
    // loginfo(msg)
  }

  private val bus = new ActorEventBus with LookupClassification {

    type Event = Bus.Event
    type Classifier = Symbol

    override protected val mapSize = 2048

    def classify(event: Event): Symbol = event.channel

    def publish(event: Event, subscriber: ActorRef) = {
      subscriber ! event.payload
    }
  }
}

object Bus extends ExtensionId[Bus] with ExtensionIdProvider {

  case class Event(payload: Any, channel: Symbol)

  override def lookup = Bus

  override def createExtension(system: ExtendedActorSystem) = new Bus(system)
}


text:
namespace xls::noc {
namespace {

TEST(SimObjectsTest, BackToBackNetwork0) {
  // Build and assign simulation objects
  NetworkConfigProto proto;
  NetworkManager graph;
  NocParameters params;
  XLS_ASSERT_OK(BuildNetworkGraphLinear000(&proto, &graph, &params));

  // Create global routing table.
  DistributedRoutingTableBuilderForTrees route_builder;
  XLS_ASSERT_OK_AND_ASSIGN(DistributedRoutingTable routing_table,
                           route_builder.BuildNetworkRoutingTables(
                               graph.GetNetworkIds()[0], graph, params));

  // Build simulator objects.
  NocSimulator simulator;
  XLS_ASSERT_OK(simulator.Initialize(graph, params, routing_table,
                                     graph.GetNetworkIds()[0]));
  simulator.Dump();

  // Retrieve src and sink objects
  XLS_ASSERT_OK_AND_ASSIGN(
      NetworkComponentId send_port_0,
      FindNetworkComponentByName("SendPort0", graph, params));
  XLS_ASSERT_OK_AND_ASSIGN(
      NetworkComponentId recv_port_0,
      FindNetworkComponentByName("RecvPort0", graph, params));
  XLS_ASSERT_OK_AND_ASSIGN(
      NetworkComponentId router,
      FindNetworkComponentByName("RouterA", graph, params));

  XLS_ASSERT_OK_AND_ASSIGN(
      int64_t src_index_0,
      simulator.GetRoutingTable()->GetSourceIndices().GetNetworkComponentIndex(
          send_port_0));

  XLS_ASSERT_OK_AND_ASSIGN(
      int64_t dest_index_0,
      simulator.GetRoutingTable()->GetSinkIndices().GetNetworkComponentIndex(
          recv_port_0));

  // Send a packet and expect that the flits it turns into
  // arrive at the other end in-order.
  XLS_ASSERT_OK_AND_ASSIGN(DataPacket packet,
                           DataPacketBuilder()
                               .Valid(true)
                               .SourceIndex(src_index_0)
                               .DestinationIndex(dest_index_0)
                               .VirtualChannel(0)
                               .Data(UBits(0b1010'0110'1100'0011, 16))
                               .Build());

  DePacketizer depacketizer(16, 3, 128);

  XLS_ASSERT_OK(depacketizer.AcceptNewPacket(packet));
  XLS_ASSERT_OK_AND_ASSIGN(SimNetworkInterfaceSrc * sim_send_port_0,
                           simulator.GetSimNetworkInterfaceSrc(send_port_0));

  int64_t cycle_to_send = 0;
  while (!depacketizer.IsIdle()) {
    XLS_ASSERT_OK_AND_ASSIGN(DataFlit flit, depacketizer.ComputeNextFlit());
    TimedDataFlit timed_flit{cycle_to_send, flit};

    XLS_ASSERT_OK(sim_send_port_0->SendFlitAtTime(timed_flit));
    XLS_LOG(INFO) << ++cycle_to_send;
  }

  for (int64_t i = 0; i < 10; ++i) {
    XLS_ASSERT_OK(simulator.RunCycle());
  }

  XLS_ASSERT_OK_AND_ASSIGN(SimNetworkInterfaceSink * sim_recv_port_0,
                           simulator.GetSimNetworkInterfaceSink(recv_port_0));

  absl::Span<const TimedDataFlit> traffic_recv_port_0 =
      sim_recv_port_0->GetReceivedTraffic();

  EXPECT_EQ(traffic_recv_port_0.size(), 2);

  TimedDataFlit flit0 = traffic_recv_port_0[0];
  TimedDataFlit flit1 = traffic_recv_port_0[1];

  EXPECT_EQ(flit0.cycle, 5);
  EXPECT_EQ(flit0.flit.source_index, src_index_0);
  EXPECT_EQ(flit0.flit.destination_index, dest_index_0);
  EXPECT_EQ(flit0.flit.type, FlitType::kHead);
  EXPECT_EQ(flit0.flit.vc, 0);
  EXPECT_EQ(flit0.flit.data.Slice(0, flit0.flit.data_bit_count),
            UBits(0b0'0110'1100'0011, 13));
  EXPECT_THAT(flit0.metadata.timed_route_info.route,
              ::testing::ElementsAre(TimedRouteItem{send_port_0, 1},
                                     TimedRouteItem{router, 3},
                                     TimedRouteItem{recv_port_0, 5}));

  EXPECT_EQ(flit1.cycle, 6);
  EXPECT_EQ(flit1.flit.source_index, src_index_0);
  EXPECT_EQ(flit1.flit.destination_index, dest_index_0);
  EXPECT_EQ(flit1.flit.type, FlitType::kTail);
  EXPECT_EQ(flit1.flit.vc, 0);
  EXPECT_EQ(flit1.flit.data.Slice(0, flit1.flit.data_bit_count),
            UBits(0b101, 3));
  EXPECT_THAT(flit1.metadata.timed_route_info.route,
              ::testing::ElementsAre(TimedRouteItem{send_port_0, 2},
                                     TimedRouteItem{router, 4},
                                     TimedRouteItem{recv_port_0, 6}));
}

}  // namespace
}  // namespace xls::noc


text:
import { action } from "@ember/object";
import InputSelectComponent, {
  SelectArguments,
} from "../input-select/component";

export default class InputMultiSelectComponent extends InputSelectComponent<
  SelectArguments
> {
  type = "multi-select";

  @action
  multiSelectValueChanged(event: Event) {
    const element = <HTMLSelectElement>event.target;
    const values: string[] = [];

    if (!element) {
      this.setNewValue(values);
      return;
    }

    for (const option of element.options) {
      if (option.selected && option.value) {
        values.push(option.value);
      }
    }

    this.setNewValue(values);
  }
}


text:
'*******************************************************************************************'
'                                                                                '
' Download Free Evaluation Version From:     https://bytescout.com/download/web-installer   '
'                                                                                '
' Also available as Web API! Get free API Key https://app.pdf.co/signup                     '
'                                                                                '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                '
' https://www.bytescout.com                                                                 '
' https://www.pdf.co                                                                        '
'*******************************************************************************************'

Imports Bytescout.PDFExtractor

Class Program
	Friend Shared Sub Main(args As String())

		' Create Bytescout.PDFExtractor.TextExtractor instance
		Dim extractor As New TextExtractor()
		extractor.RegistrationName = "demo"
		extractor.RegistrationKey = "demo"

		' Load sample PDF document
		extractor.LoadDocumentFromFile(".\sample2.pdf")

		' Get page count
		Dim pageCount As Integer = extractor.GetPageCount()

		For i As Integer = 0 To pageCount - 1
			Dim fileName As String = "page" & i & ".txt"

			' Save extracted page text to file
			extractor.SavePageTextToFile(i, fileName)
		Next

		' Cleanup
		extractor.Dispose()

		' Open result file in default associated application (for demo purposes)
		System.Diagnostics.Process.Start(".\page1.txt")

	End Sub
End Class


text:
package org.hyperledger.indy.sdk.did;

import org.hyperledger.indy.sdk.IndyIntegrationTestWithSingleWallet;
import org.hyperledger.indy.sdk.wallet.WalletItemNotFoundException;
import org.junit.Test;

import java.util.concurrent.ExecutionException;

import static org.hamcrest.CoreMatchers.isA;
import static org.junit.Assert.assertEquals;

public class KeyForLocalDidTest extends IndyIntegrationTestWithSingleWallet {

	@Test
	public void testKeyForLocalDidWorksForMyDid() throws Exception {
		DidResults.CreateAndStoreMyDidResult result = Did.createAndStoreMyDid(wallet, "{}").get();
		String did = result.getDid();
		String key = result.getVerkey();

		String receivedKey = Did.keyForLocalDid(wallet, did).get();
		assertEquals(key, receivedKey);
	}

	@Test
	public void testKeyForDidWorksForNoKey() throws Exception {
		thrown.expect(ExecutionException.class);
		thrown.expectCause(isA(WalletItemNotFoundException.class));

		Did.keyForLocalDid(wallet, DID_MY2).get();
	}
}


text:
/*
** Declarations for the address list module.
*/

/*
** Data characteristics
**
**	Maximum lengths of the various data (includes space for the
**	terminating NUL byte), and maximum number of addresses.
*/
#define	NAME_LENGTH	30		/* longest name allowed */
#define	ADDR_LENGTH	100		/* longest address allowed */
#define	PHONE_LENGTH	11		/* longest phone # allowed */

#define	MAX_ADDRESSES	1000		/* # of addresses allowed */

/*
** Interface functions
**
**	Given a name, find the corresponding address.
*/
char const *
lookup_address( char const *name );

/*
**	Given a name, find the corresponding phone number.
*/
char const *
lookup_phone( char const *name );


text:
package org.knowm.xchange.examples.kucoin;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.kucoin.KucoinExchange;

public class KucoinExamplesUtils {

  public static Exchange getExchange() {

    ExchangeSpecification exSpec = new ExchangeSpecification(KucoinExchange.class);
    exSpec.setApiKey("your-api-key");
    exSpec.setSecretKey("your-secret-key");

    return ExchangeFactory.INSTANCE.createExchange(exSpec);
  }
}


text:
package li260.ihm.key;

import java.util.Set;

import li260.jeu.Jeu;
import li260.voiture.Commande;
import li260.voiture.VoitureException;

public class InputHandler {

	private Jeu game;
	// private SteeringWheel volant;

	public InputHandler(Jeu game) {
		super();
		this.game = game;
		// volant = new SteeringWheel();
	}

	public double keyAccel(char c) {
		if (c == 'z') {
			return 1;
		}
		if (c == 's') {
			return -1;
		}
		return 0;
	}

	public double keyTurn(char c) {
		if (c == 'q') {
			return 0.7;
		}
		if (c == 'd') {
			return -0.7;
		}
		return 0;
	}

	public boolean isValidKey(char c) {
		return (c == 'z' || c == 's' || c == 'q' || c == 'd');
	}

	public void process(Set<Character> pressedKey) throws VoitureException {
		double acc = 0;
		double turn = 0;
		for (Character c : pressedKey) {
			if (!isValidKey(c)) {
				continue;
			}
			acc += keyAccel(c);
			turn += keyTurn(c);
		}

		// Commande cmd = new Commande(acc, volant.getTurn());
		Commande cmd = new Commande(acc, turn);
		if (Math.abs(cmd.getTurn()) >= game.getVoiture()
				.getMaxTurnSansDerapage()) {
			cmd = new Commande(cmd.getAcc(), Math.signum(cmd.getTurn())
					* game.getVoiture().getMaxTurnSansDerapage());
		}
		game.getSimulation().playCommande(cmd);
	}

}


text:
package org.apache.directory.api.ldap.extras.extended.ads_impl.pwdModify;

import org.apache.directory.api.asn1.ber.AbstractContainer;

/**
 * A container for PasswordModifyRequest codec.
 *
 * @author Apache Directory Project
 */
public class PasswordModifyRequestContainer extends AbstractContainer
{
    /** PasswordModifyRequest decorator*/
    private PasswordModifyRequestDecorator passwordModifyRequest;

    /**
     * Creates a new PasswordModifyContainer object. We will store one
     * grammar, it's enough ...
     */
    public PasswordModifyRequestContainer()
    {
        super();
        grammar = PasswordModifyRequestGrammar.getInstance();
        setTransition( PasswordModifyRequestStatesEnum.START_STATE );
    }

    /**
     * @return Returns the PwdModifyRequest instance.
     */
    public PasswordModifyRequestDecorator getPwdModifyRequest()
    {
        return passwordModifyRequest;
    }

    /**
     * Set a PasswordModifyRequest Object into the container. It will be completed by
     * the ldapDecoder.
     *
     * @param passwordModifyRequestDecorator the PasswordModifyRequest to set.
     */
    public void setPasswordModifyRequest( PasswordModifyRequestDecorator passwordModifyRequestDecorator )
    {
        this.passwordModifyRequest = passwordModifyRequestDecorator;
    }

    /**
     * Clean the container for the next decoding.
     */
    public void clean()
    {
        super.clean();
        passwordModifyRequest = null;
    }
}


text:
A tool for tooting tweets from your favorite accounts

## Follow us at [@rubydev@octodon.social](https://octodon.social/@rubydev)

Currently, we are only following [@RubyInside](https://twitter.com/RubyInside),
[@rubyflow](https://twitter.com/rubyflow), and
[@DriftingRuby](https://twitter.com/DriftingRuby) from Twitter, but are open to
more useful Ruby Development News accounts! Open an issue to suggest new accounts!

## Steps to install

### 1. Clone the Repository

```
git clone https://github.com/jstumbaugh/tweet-to-toot
```

### 2. Create a Twitter app to get the access keys

Create a [twitter app](https://apps.twitter.com/app/new) and generate access
tokens. Store these in the `env.example` file.

### 3. Create a Mastodon Account to post the Tweets to

Store the instance URL, login email, and password in the `env.example` file.

### 4. Pick the Twitter Accounts to follow and post to Mastodon

Store these account handles in the `env.example` file.

```env
# Twitter handles in a comma separated list
TWITTER_HANDLES_TO_TOOT='RubyInside, rubyflow'
```

### Pro Tip: Add hashtags to tie all of your toots together

Store your hashtags to add in the `env.example` file. These will be appended to
the end of the tweets and posted to Mastodon.

```env
# Hashtags to be appended to the Toots
HASHTAGS='#RubyDevNews #TweetToToot'
```

### 5. Run the task to toot tweets

You can run the rake task

```
bundle exec rake
```

which will loop forever, or you can spin up a Docker image with:

```
make
```

which builds a docker image, starts it, and begins Tooting!

## Enjoy!


text:
CLOUDFRONT_DISTRIBUTION_ID=E372HNY0DNX3PN

all:
	@echo "Usage: make (deploy|analytics-report)"
	@exit 1

deploy:
	aws s3 sync --region=eu-west-1 $(shell nix-build blog --no-out-link) s3://wickstrom.tech --acl=public-read --profile wickstrom.tech --delete
	aws cloudfront create-invalidation --distribution-id $(CLOUDFRONT_DISTRIBUTION_ID) --paths '/*' --profile wickstrom.tech

###############################################################
# ANALYTICS
###############################################################

ANALYTICS_DIR=$(HOME)/opt/wickstrom-tech-analytics

.PHONY: analytics-report
analytics-report:
	@echo "Creating analytics report..."
	mkdir -p $(ANALYTICS_DIR)
	aws s3 sync s3://wickstrom-tech-access-logs/wickstrom.tech "$(ANALYTICS_DIR)"
	find $(ANALYTICS_DIR) -name '*.gz' | xargs zcat -f | grep -v feed.xml | goaccess --log-format=CLOUDFRONT --ignore-referer=wickstrom.tech --ignore-crawlers -o "$(ANALYTICS_DIR)"/report.html
	firefox "$(ANALYTICS_DIR)"/report.html


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "http://google-web-toolkit.googlecode.com/svn/trunk/distro-source/core/src/gwt-module.dtd">
<module>
	<source path="io/piotrjastrzebski/box2dinterpolation" />
</module>


text:
modules.define(
    'user-data-storage',
    ['inherit'],
    function (provide, inherit) {

    var UserDataStorage = inherit({
        __constructor: function () {
            var key = '__localStorageTest';
            try {
                localStorage.setItem(key, key);
                localStorage.removeItem(key);
                this._storage = localStorage;
            } catch(e) {
                this._storage = {};
            }
        },

        getValue: function (key) {
            var value = this._storage[key];
            return value === undefined ? undefined : JSON.parse(value);
        },

        setValue: function (key, value) {
            this._storage[key] = JSON.stringify(value);
        }
    });
    provide(UserDataStorage);
});


text:
package org.apache.logging.log4j.core.async.perftest;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.spi.LifeCycle;

import com.lmax.disruptor.collections.Histogram;

public class RunLogback implements IPerfTestRunner {
    final Logger LOGGER = (Logger) LoggerFactory.getLogger(getClass());

    @Override
    public void runThroughputTest(final int lines, final Histogram histogram) {
        final long s1 = System.nanoTime();
        final Logger logger = LOGGER;
        for (int j = 0; j < lines; j++) {
            logger.info(THROUGHPUT_MSG);
        }
        final long s2 = System.nanoTime();
        final long opsPerSec = (1000L * 1000L * 1000L * lines) / (s2 - s1);
        histogram.addObservation(opsPerSec);
    }

    @Override
    public void runLatencyTest(final int samples, final Histogram histogram,
            final long nanoTimeCost, final int threadCount) {
        final Logger logger = LOGGER;
        for (int i = 0; i < samples; i++) {
            final long s1 = System.nanoTime();
            logger.info(LATENCY_MSG);
            final long s2 = System.nanoTime();
            final long value = s2 - s1 - nanoTimeCost;
            if (value > 0) {
                histogram.addObservation(value);
            }
            // wait 1 microsec
            final long PAUSE_NANOS = 10000 * threadCount;
            final long pauseStart = System.nanoTime();
            while (PAUSE_NANOS > (System.nanoTime() - pauseStart)) {
                // busy spin
            }
        }
    }

    @Override
    public void shutdown() {
        ((LifeCycle) LoggerFactory.getILoggerFactory()).stop();
    }

    @Override
    public void log(final String msg) {
        LOGGER.info(msg);
    }
}


text:
package org.kuali.mobility.bus.dao.helper;

import java.io.IOException;

import org.springframework.core.io.Resource;

/**
 * Helper class to get a unit test compatible URL string from the classpath
 *
 * @author Kuali Mobility Team (mobility.collab@kuali.org)
 * @since 2.3.0
 */
public class URLHelper {

	/**
	 * A reference to a springyfied resource
	 */
	private Resource resource;

	/**
	 * Sets the resource
	 *
	 * @param resource
	 */
	public void setResource(Resource resource) {
		this.resource = resource;
	}

	/**
	 * Get a string representing the url to the resource
	 *
	 * @return
	 */
	public String getUrlPath() {
		try {
			return resource.getURL().toString();
		} catch (IOException e) {
			e.printStackTrace();
			return "ERROR";
		}
	}
}


text:
PILOTARIAK_HOME="${PROJECTS_HOME}/Pilotariak"

SESSION="pilotariak"

function tmux_pilotariak {
    tmux start-server
    tmux new-session -s $SESSION -n Pilotariak -d
    tmux new-window -n "Jo"
    tmux send-keys -t $SESSION "cd ${PILOTARIAK_HOME}/jo" C-m
    tmux new-window -n "Trinquet"
    tmux send-keys -t $SESSION "cd ${PILOTARIAK_HOME}/trinquet" C-m
    tmux new-window -n "Paleta"
    tmux send-keys -t $SESSION "cd ${PILOTARIAK_HOME}/paleta" C-m
    tmux new-window -n "Berriz"
    tmux send-keys -t $SESSION "cd ${PILOTARIAK_HOME}/berriz" C-m
    tmux attach-session -t $SESSION
}

tmux_pilotariak


text:
require 'qmail_log/analyze/helper'

module QmailLog
  class Analyzer
    class << self
      include QmailLog::Analyze::Helper

      def analyze log, data, qid_from_did, memory
        time     = Tai64.parse(log.split[0]).to_time.to_s
        content  = log.partition(' ')[-1]
        queue_id = queue_id(content, qid_from_did)

        case content
        when /(new)/
          memory[queue_id] = { time: {} }

        when /(info)/
          memory[queue_id].merge!( info(content) )

        when /(starting)/
          memory[queue_id].merge!( starting(content) )
          qid_from_did[ memory[queue_id][:delivery_id] ] = queue_id

        when /(delivery)/
          memory[queue_id].merge!( delivery(content) )

        when /end/
          memory[queue_id][:time][:end] = time
          data << memory[queue_id].merge!({ queue_id: queue_id })
        end

        memory[queue_id][:time][$1.to_sym] = time if $1
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="nonexistent"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="wrong1"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="wrong2"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="wrong3"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="wrong4"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="wrong5"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="wrong6"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="ok"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="simple_typo"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="my\u1234method"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="wrong7"
        android:text="Button" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="@string/ok"
        android:text="Button" />

</LinearLayout>


text:
<?php

class Bringit_RequestHeaderTest extends BringitTestCase
{
	public function testRequestHeader()
	{
		$header = new Bringit_Header_RequestHeader();

		$header->setHeaderValue('One', 'wrong');
		$header->setHeaderValue('One', 'I');

		$header->setHeaderValue('Two', 'also wrong');
		$header->addField(new Bringit_Header_HeaderField('Two', 'II'));

		$header->addField(new Bringit_Header_HeaderField('Three', 'III'));
		$header->remove('Three');

		$this->assertEqual($header->value('One'), 'I');
		$this->assertEqual($header->value('Two'), 'II');
		try
		{
			$header->value('Three');
			$this->fail('Bringit_Exception should be thrown');
		}
		catch (Bringit_Exception $e)
		{
			$this->pass('Bringit_Exception should be thrown');
		}

		$headers = $header->fields();
		$this->assertIsA($headers, 'array');
		$this->assertEqual(count($headers), 2);
	}

	public function testToString()
	{
		$header = new Bringit_Header_RequestHeader();
		$header['one'] = 'I';
		$header['two'] = 'II';

		$this->assertEqual(
			"$header",
			"One: I\r\nTwo: II\r\n\r\n"
		);
	}

	public function testRequestHeaderCountable()
	{
		$header = new Bringit_Header_RequestHeader();
		$this->assertEqual(count($header), 0);

		$header->setHeaderValue('One', 'wrong');
		$this->assertEqual(count($header), 1);

		$header->setHeaderValue('One', 'I');
		$this->assertEqual(count($header), 1);

		$header->setHeaderValue('Two', 'II');
		$this->assertEqual(count($header), 2);

		$header->remove('One');
		$this->assertEqual(count($header), 1);
	}

	public function testRequestHeaderArrayAccess()
	{
		$header = new Bringit_Header_RequestHeader();
		$header['One'] = 'wrong';
		$header['One'] = 'I';
		$header['Two'] = 'II';

		$header['Three'] = 'III';
		$this->assertTrue(isset($header['Three']));
		unset($header['Three']);
		$this->assertFalse(isset($header['Three']));

		$this->assertEqual(count($header), 2);
		$this->assertEqual($header['One'], 'I');
		$this->assertEqual($header['Two'], 'II');

		$count = 0;
		foreach ($header as $name => $value)
		{
			$count++;
			$this->assertTrue(in_array($name, array('One', 'Two')));
			$this->assertTrue(in_array($value, array('I', 'II')));
		}
		$this->assertEqual($count, 2);
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="assets/ico/favicon.png">

    <title>NewFirm - Corporate Bootstrap 3 Theme</title>

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

    <link href="assets/css/main.css" rel="stylesheet">
    <link href="assets/css/colors/color-3498db.css" rel="stylesheet">
    <link href="assets/css/animations.css" rel="stylesheet">
    <link href="assets/css/font-awesome.min.css" rel="stylesheet">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

          </button>
          NEWFIRM

              Home

Home - Main Version

Home - Agency Version

Home - Corporate Version

Home - Classic Version

Home - One Page Version

              Pages

Services

About

Team Member

FAQ

Our Offices

Pricing

Contact

404 Error Page

              Portfolio

Classic Portfolio

4 Columns Portfolio

Masonry Portfolio

Full Width Project

Project Split

Video Project

Project Slideshow

              Blog

Article List

Article List Variation

Blog Post

	<! ========== HEADERWRAP ====================================================================================================
	=============================================================================================================================>

NewFirm is a digital creative agency. We focus on design, consulting, and technology.

<button type="button" class="btn btn-cta btn-lg">LEARN MORE</button>

	<! ========== FEATURED ICONS ================================================================================================
	=============================================================================================================================>

Important Features

 Built with Bootstrap 3

Built for all levels of expertise, whether you need simple pages or complex ones, creating something incredible with NewFirm is an effortless and intuitive process.

 Retina Ready

We've taken great care to ensure that NewFirm is fully retina-ready. So it'll look good on any retina display. We use retina.js to ensure the best view.

 Responsive Design

NewFirm fits any device handsomely. We tested our theme in major devices and browsers. Check it out and test it before buy it on responsinator.com.

 Nice Animations

Good looking animations are an essential part of the new theme design trend. We add animations.css, a cool script to help you enhance your site with style.

	<! ========== PORTFOLIO SECTION =============================================================================================
	=============================================================================================================================>

Our Latest Work

APE -

RAIDERS -

VIKINGS -

YODA -

    			<button type="button" class="btn btn-theme btn-lg">VIEW OUR PORTFOLIO</button>

	<! ========== CALL TO ACTION 1 ==============================================================================================
	=============================================================================================================================>

The probability of success is difficult to estimate;
but if we never search, the chance of success is zero.

    				<button type="button" class="btn btn-cta btn-lg">SUCCESS</button>

<! --/cta01 -->

	<! ========== BLOG & TESTIMONIAL ============================================================================================
	=============================================================================================================================>

What Is Happening?

The Sky Is The Limit

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

 3 |  14 Nov.

Another Cool Stuff

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

 1 |  13 Oct.

There's more to design than meets the eye. It's when it meets the heart that design creates a meaningful, lasting connection with the audience. First, your brand has to matter to consumers. This is where your emotional connection begins.

We became the brand that we always wanted. They worked so hard to achieve our goals, that they seemed part of our own company.

 - David Wayne - BlackTie.co

	<! ========== BRANDS & CLIENTS ===============================================================================================
	=============================================================================================================================>

Brands & Clients

	<! ========== CALL TO ACTION BAR ===============================================================================================
	=============================================================================================================================>

Are You Ready For The Next Step?

	<! ========== FOOTER ========================================================================================================
	=============================================================================================================================>

Our Studio

						Some Ave. 987,

						Postal 64733

						London, UK.

						 +55 4893.8943

						 hello@yourdomain.com

<! --/col-lg-3 -->

Recent Tweets

Follow us @Alvrz_is

Latest Posts

						 A post with an image

						 Other post with a video

						 A full width post

						 We talk about something nice

						 Yet another single post

New Project

<! --/row -->


text:
#pragma once
#include <aws/accessanalyzer/AccessAnalyzer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace AccessAnalyzer
{
namespace Model
{
  enum class ValidatePolicyResourceType
  {
    NOT_SET,
    AWS_S3_Bucket,
    AWS_S3_AccessPoint,
    AWS_S3_MultiRegionAccessPoint,
    AWS_S3ObjectLambda_AccessPoint
  };

namespace ValidatePolicyResourceTypeMapper
{
AWS_ACCESSANALYZER_API ValidatePolicyResourceType GetValidatePolicyResourceTypeForName(const Aws::String& name);

AWS_ACCESSANALYZER_API Aws::String GetNameForValidatePolicyResourceType(ValidatePolicyResourceType value);
} // namespace ValidatePolicyResourceTypeMapper
} // namespace Model
} // namespace AccessAnalyzer
} // namespace Aws


text:
typedef BOOL (^NUIRenderOverrideBlock)(NUIRenderContainer *renderContainer);

//////////////////////////////////////////////////////
//////////////// DEFINED PROPERTIES //////////////////
//////////////////////////////////////////////////////

static NSString * const kHeight = @"height";
static NSString * const kWidth = @"width";

static NSString * const kVerticalAlign = @"vertical-align";

static NSString * const kBackgroundColor = @"background-color";
static NSString * const kBackgroundTintColor = @"background-tint-color";
static NSString * const kBackgroundColorHighlighted = @"background-color-highlighted";
static NSString * const kBackgroundColorSelected = @"background-color-selected";
static NSString * const kBackgroundColorSelectedHighlighted = @"background-color-selected-highlighted";
static NSString * const kBackgroundColorSelectedDisabled = @"background-color-selected-disabled";
static NSString * const kBackgroundColorDisabled = @"background-color-disabled";
static NSString * const kBackgroundColorTop = @"background-color-top";
static NSString * const kBackgroundColorTopSelected = @"background-color-top-selected";
static NSString * const kBackgroundColorBottom = @"background-color-bottom";
static NSString * const kBackgroundColorBottomSelected = @"background-color-bottom-selected";
static NSString * const kBackgroundRepeat = @"background-repeat";

static NSString * const kBackgroundImage = @"background-image";
static NSString * const kBackgroundImageTop = @"background-image-top";
static NSString * const kBackgroundImageTopLandscape = @"background-image-top-landscape";
static NSString * const kBackgroundImageBottom = @"background-image-bottom";
static NSString * const kBackgroundImageBottomLandscape = @"background-image-bottom-landscape";
static NSString * const kBackgroundImageHighlighted = @"background-image-highlighted";
static NSString * const kBackgroundImageSelected = @"background-image-selected";
static NSString * const kBackgroundImageSelectedHighlighted = @"background-image-selected-highlighted";
static NSString * const kBackgroundImageSelectedDisabled = @"background-image-selected-disabled";
static NSString * const kBackgroundImageDisabled = @"background-image-disabled";

static NSString * const kBarTintColor = @"bar-tint-color";

static NSString * const kBorderStyle = @"border-style";
static NSString * const kBorderColor = @"border-color";
static NSString * const kBorderWidth = @"border-width";

static NSString * const kContentInsets = @"content-insets";
static NSString * const kCornerRadius = @"corner-radius";

static NSString * const kDividerColor = @"divider-color";
static NSString * const kDividerImage = @"divider-image";

static NSString * const kExcludeViews = @"exclude-views";
static NSString * const kExcludeSubviews = @"exclude-subviews";

static NSString * const kFinishedImage = @"finished-image";
static NSString * const kFinishedImageSelected = @"finished-image-selected";

static NSString * const kFontColor = @"font-color";
static NSString * const kFontColorHighlighted = @"font-color-highlighted";
static NSString * const kFontColorSelected = @"font-color-selected";
static NSString * const kFontColorSelectedHighlighted = @"font-color-selected-highlighted";
static NSString * const kFontColorSelectedDisabled = @"font-color-selected-disabled";
static NSString * const kFontColorDisabled = @"font-color-disabled";
static NSString * const kFontName = @"font-name";
static NSString * const kFontSize = @"font-size";

static NSString * const kImage = @"image";
static NSString * const kImageHighlighted = @"image-highlighted";
static NSString * const kImageSelected = @"image-selected";
static NSString * const kImageSelectedHighlighted = @"image-selected-highlighted";
static NSString * const kImageSelectedDisabled = @"image-selected-disabled";
static NSString * const kImageDisabled = @"image-disabled";

static NSString * const kMinimumTrackTintColor = @"minimum-track-tint-color";
static NSString * const kMaximumTrackTintColor = @"maximum-track-tint-color";
static NSString * const kMinimumValueImage = @"minimum-value-image";
static NSString * const kMaximumValueImage = @"maximum-value-image";

static NSString * const kOffImage = @"off-image";
static NSString * const kOnImage = @"on-image";

static NSString * const kPadding = @"padding";
static NSString * const kProgressImage = @"progress-image";
static NSString * const kProgressTintColor = @"progress-tint-color";

static NSString * const kRowHeight = @"row-height";

static NSString * const kScopeBackgroundColor = @"scope-background-color";
static NSString * const kScopeBackgroundImage = @"scope-background-image";

static NSString * const kSelectedImage = @"selected-image";
static NSString * const kSelectedImageTintColor = @"selected-image-tint-color";

static NSString * const kSeparatorColor = @"separator-color";
static NSString * const kSeparatorStyle = @"separator-style";

static NSString * const kShadowColor = @"shadow-color";
static NSString * const kShadowImage = @"shadow-image";
static NSString * const kShadowImageTop = @"shadow-image-top";
static NSString * const kShadowImageBottom = @"shadow-image-bottom";
static NSString * const kShadowRadius = @"shadow-radius";
static NSString * const kShadowOffset = @"shadow-offset";
static NSString * const kShadowOpacity = @"shadow-opacity";

static NSString * const kTextAlign = @"text-align";
static NSString * const kTextAlpha = @"text-alpha";
static NSString * const kTextAutoFit = @"text-auto-fit";
static NSString * const kTextOffset = @"text-offset";
static NSString * const kTextShadowColor = @"text-shadow-color";
static NSString * const kTextShadowColorHighlighted = @"text-shadow-color-highlighted";
static NSString * const kTextShadowColorSelected = @"text-shadow-color-selected";
static NSString * const kTextShadowColorSelectedHighlighted = @"text-shadow-color-selected-highlighted";
static NSString * const kTextShadowColorSelectedDisabled = @"text-shadow-color-selected-disabled";
static NSString * const kTextShadowColorDisabled = @"text-shadow-color-disabled";
static NSString * const kTextShadowOffset = @"text-shadow-offset";
static NSString * const kTextTransform = @"text-transform";

static NSString * const kTintColor = @"tint-color";
static NSString * const kOnTintColor = @"on-tint-color";
static NSString * const kThumbTintColor = @"thumb-tint-color";
static NSString * const kThumbImage = @"thumb-image";

static NSString * const kTitleInsets = @"title-insets";
static NSString * const kTitleVerticalOffset = @"title-vertical-offset";

static NSString * const kTrackImage = @"track-image";
static NSString * const kTrackTintColor = @"track-tint-color";

//////////////////////////////////////////////////////

@interface NUISettings : NSObject

@property (nonatomic, copy) NSString *autoUpdatePath;
@property (nonatomic, strong) NSMutableDictionary *styles;
@property (nonatomic, copy) NSString *stylesheetName;
@property (nonatomic, strong) NSMutableArray *additionalStylesheetNames;
@property (nonatomic, strong) NSMutableArray *globalExclusions;
@property (nonatomic, copy) NSString *stylesheetOrientation;

+ (void)init;
+ (void)initWithStylesheet:(NSString*)name;
+ (void)appendStylesheet:(NSString*)name;
+ (void)loadStylesheetByPath:(NSString*)path;
+ (BOOL)reloadStylesheetsOnOrientationChange:(UIInterfaceOrientation)orientation;
+ (BOOL)autoUpdateIsEnabled;
+ (NSString*)autoUpdatePath;
+ (void)setAutoUpdatePath:(NSString*)path;
+ (BOOL)hasProperty:(NSString*)property withClass:(NSString*)className;
+ (BOOL)hasFontPropertiesWithClass:(NSString*)className;
+ (NSDictionary*)allPropertiesForClass:(NSString*)className;
+ (id)get:(NSString*)property withClass:(NSString*)className;
+ (BOOL)getBoolean:(NSString*)property withClass:(NSString*)className;
+ (float)getFloat:(NSString*)property withClass:(NSString*)className;
+ (CGSize)getSize:(NSString*)property withClass:(NSString*)className;
+ (UIOffset)getOffset:(NSString*)property withClass:(NSString*)className;
+ (UIEdgeInsets)getEdgeInsets:(NSString*)property withClass:(NSString*)className;
+ (UIRectEdge)getRectEdge:(NSString *)property withClass:(NSString *)className;
+ (UIRectCorner)getRectCorner:(NSString *)property withClass:(NSString *)className;
+ (UITextBorderStyle)getBorderStyle:(NSString*)property withClass:(NSString*)className;
+ (UITableViewCellSeparatorStyle)getSeparatorStyle:(NSString*)property withClass:(NSString*)className;
+ (UIFont*)getFontWithClass:(NSString*)className;
+ (UIFont*)getFontWithClass:(NSString*)className baseFont:(UIFont *)baseFont;
+ (UIColor*)getColor:(NSString*)property withClass:(NSString*)className;
+ (UIColor*)getColorFromImage:(NSString*)property withClass:(NSString*)className;
+ (UIImage*)getImage:(NSString*)property withClass:(NSString*)className;
+ (UIImage*)getImageFromColor:(NSString*)property withClass:(NSString*)className;
+ (kTextAlignment)getTextAlignment:(NSString*)property withClass:(NSString*)className;
+ (UIControlContentHorizontalAlignment)getControlContentHorizontalAlignment:(NSString*)property withClass:(NSString*)className;
+ (UIControlContentVerticalAlignment)getControlContentVerticalAlignment:(NSString*)property withClass:(NSString*)className;
+ (NSMutableArray*)getGlobalExclusions;
+ (void)setGlobalExclusions:(NSArray*)globalExclusions;

+ (NSString *)stylesheetOrientation;
+ (NSDictionary *)getAttributesFromSpecificClass:(NSString *)className;

+ (NSDictionary*)unrecognizedPropertiesForClass:(NSString*)className;
+ (void)alertObject:(id)object
          withClass:(NSString*)className
ofUnsupportedProperties:(NSDictionary*)properties
          withBlock:(NUIRenderOverrideBlock)block;
+ (void)checkUnsupportedPropertiesForObject:(NSObject*)object
                                  withClass:(NSString*)className;
+ (BOOL)applyProperties:(NSArray*)propertyNames
              withClass:(NSString*)className
               onObject:(NSObject*)object
               forState:(UIControlState)state
        appliedProperty:(id)appliedProperty;
+ (BOOL)applyProperty:(id)propertyName
            withClass:(NSString*)className
             onObject:(NSObject*)object
             forState:(UIControlState)state
      appliedProperty:(id)appliedProperty;

@end


text:
package com.yin.myproject.demo.jvm.chapter07;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Eason on 2017/1/5.
 */
public class ClassLoaderTest {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        ClassLoader myloader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream is = getClass().getResourceAsStream(fileName);
                    if (is == null) {
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0, b.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };

        Object obj = myloader.loadClass("com.yin.myproject.demo.jvm.chapter07.ClassLoaderTest").newInstance();
        System.out.println(obj.getClass());
        System.out.println(obj instanceof ClassLoaderTest);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Encyclop. Mycol. (Paris) 7: 51 (1935)

#### Original name
Galera pulchra Clem.

### Remarks
null


text:
local pairs = pairs
local type = type
local unpack = unpack
local select = select
local getfenv = getfenv
local tostring = tostring
local newproxy = newproxy
local getmetatable = getmetatable
local setmetatable = setmetatable
local getupvalue = debug and debug.getupvalue

local string = require "string"
local table = require "loop.table"
local oo = require "loop.base"

module("loop.debug.Matcher", oo.class)

__mode = "k"

isomorphic = true
environment = getfenv
upvalue = getupvalue

metakey = newproxy()
envkey = newproxy()

function error(self, message)
	local path = { "value" }
	for i = 2, #self do
		local key = self[i]
		if key == metakey then
			table.insert(path, 1, "getmetatable(")
			key = ")"
		elseif key == envkey then
			table.insert(path, 1, "getfenv(")
			key = ")"
		elseif type(key) == "string" then
			if key:match("^[%a_][%w_]*$") then
				key = "."..key
			else
				key = string.format("[%q]", key)
			end
		else
			key = string.format("[%s]", tostring(key))
		end
		path[#path+1] = key
	end
	return string.format("%s: %s", table.concat(path), message)
end

function matchtable(self, value, other)
	local matched, errmsg = true
	local keysmatched = {}
	self[value], self[other] = other, value
	for key, field in pairs(value) do
		local otherfield = other[key]
		if otherfield == nil then
			matched = false
			for otherkey, otherfield in pairs(other) do
				local matcher = setmetatable(table.copy(self), getmetatable(self))
				matcher.error = nil
				if
					matcher:match(key, otherkey) and
					matcher:match(field, otherfield)
				then
					table.copy(matcher, self)
					keysmatched[otherkey] = true
					matched = true
					break
				end
			end
			if not matched then
				self[#self+1] = key
				errmsg = self:error("no match found")
				self[#self] = nil
				break
			end
		else
			self[#self+1] = key
			matched, errmsg = self:match(field, otherfield)
			self[#self] = nil
			if matched then
				keysmatched[key] = true
			else
				break
			end
		end
	end
	if matched and self.isomorphic then
		for otherkey, otherfield in pairs(other) do
			if not keysmatched[otherkey] then
				self[#self+1] = otherkey
				matched, errmsg = false, self:error("missing")
				self[#self] = nil
				break
			end
		end
	end
	if not matched then self[value], self[other] = nil, nil end
	return matched, errmsg
end

local dump = string.dump
function matchfunction(self, func, other)
	local matched, errmsg = (dump(func) == dump(other))
	if matched then
		self[func], self[other] = other, func
		local upvalue = self.upvalue
		if upvalue then
			local name, value
			local up = 1
			repeat
				name, value = upvalue(func, up)
				if name then
					self[#self+1] = name
					matched, errmsg = self:match(value, select(2, upvalue(other, up)))
					self[#self] = nil
					if not matched then
						self[func], self[other] = nil, nil
						break
					end
					up = up + 1
				end
			until not name
		end
		local environment = self.environment
		if matched and environment then
			self[#self+1] = envkey
			matched, errmsg = self:match(environment(func), environment(other))
			self[#self] = nil
		end
	else
		errmsg = self:error "bytecodes not matched"
	end
	return matched, errmsg
end

function match(self, value, other)
	self[0] = self[0] or other
	self[1] = self[1] or value
	local matched, errmsg = false
	local kind = type(value)
	local matcher = self[kind]
	if matcher then
		local valuematch = self[value]
		local othermatch = self[other]
		matched = (valuematch == other and othermatch == value)
		if not matched then
			if valuematch == nil and othermatch == nil then
				if value == other then
					matched = true
				elseif kind == type(other) then
					matched, errmsg = matcher(self, value, other)
					matcher = self.metatable
					if matched and matcher then
						self[#self+1] = metakey
						matched, errmsg = matcher(self, getmetatable(value), getmetatable(other))
						self[#self] = nil
					end
				else
					errmsg = self:error "not matched"
				end
			else
				errmsg = self:error "wrong match"
			end
		end
	elseif value == other then
		matched = true
	else
		errmsg = self:error "not matched"
	end
	return matched, errmsg
end

_M["table"] = matchtable
_M["function"] = matchfunction
_M["metatable"] = match


text:
/*
 * HomePage
 *
 * This is the first thing users see of our App, at the '/' route
 *
 * NOTE: while this component should technically be a stateless functional
 * component (SFC), hot reloading does not currently support SFCs. If hot
 * reloading is not a necessity for you then you can refactor it and remove
 * the linting exception.
 */

import React from 'react';

import Page from './../shared/Page';
import Header from './../HomePage/Header';
import TattooPortfolio from './../HomePage/TattooPortfolio';
import About from './../HomePage/About';
import FeaturedProducts from './../HomePage/FeaturedProducts';

export function HomePage() {
  const images = [
    { path: 'https://s3.amazonaws.com/tattoo-images/1.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/2.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/3.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/4.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/5.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/6.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/7.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/8.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/9.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/10.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/11.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/12.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/13.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/14.jpg' },
    { path: 'https://s3.amazonaws.com/tattoo-images/15.jpg' },
  ];
  return (
    <Page>
      <Header />
      <TattooPortfolio images={images} />
      <About />
      <FeaturedProducts />
    </Page>
  );
}


text:
#!/bin/bash

# This script provides common script functions for the hacks
# Requires OS_ROOT to be set

readonly OS_BUILD_ENV_GOLANG="${OS_BUILD_ENV_GOLANG:-1.6}"
readonly OS_BUILD_ENV_IMAGE="${OS_BUILD_ENV_IMAGE:-openshift/origin-release:golang-${OS_BUILD_ENV_GOLANG}}"

readonly OS_OUTPUT_SUBPATH="${OS_OUTPUT_SUBPATH:-_output/local}"
readonly OS_OUTPUT="${OS_ROOT}/${OS_OUTPUT_SUBPATH}"
readonly OS_LOCAL_RELEASEPATH="${OS_OUTPUT}/releases"
readonly OS_OUTPUT_BINPATH="${OS_OUTPUT}/bin"
readonly OS_OUTPUT_PKGDIR="${OS_OUTPUT}/pkgdir"

readonly OS_GO_PACKAGE=github.com/openshift/origin

# Asks golang what it thinks the host platform is.  The go tool chain does some
# slightly different things when the target platform matches the host platform.
function os::build::host_platform() {
  echo "$(go env GOHOSTOS)/$(go env GOHOSTARCH)"
}
readonly -f os::build::host_platform

readonly OS_IMAGE_COMPILE_PLATFORMS=("$(os::build::host_platform)")

readonly OS_SDN_COMPILE_TARGETS_LINUX=(
  pkg/sdn/plugin/sdn-cni-plugin
  vendor/github.com/containernetworking/cni/plugins/ipam/host-local
  vendor/github.com/containernetworking/cni/plugins/main/loopback
)
readonly OS_IMAGE_COMPILE_TARGETS=(
  images/pod
  cmd/dockerregistry
  cmd/gitserver
  "${OS_SDN_COMPILE_TARGETS_LINUX[@]}"
)
readonly OS_IMAGE_COMPILE_GOFLAGS="-tags include_gcs"
readonly OS_SCRATCH_IMAGE_COMPILE_TARGETS=(
  examples/hello-openshift
  examples/deployment
)
readonly OS_IMAGE_COMPILE_BINARIES=("${OS_SCRATCH_IMAGE_COMPILE_TARGETS[@]##*/}" "${OS_IMAGE_COMPILE_TARGETS[@]##*/}")

OS_CROSS_COMPILE_PLATFORMS=(
  linux/amd64
  darwin/amd64
  windows/amd64
  linux/386
)
if [[ "$(os::build::host_platform)" == "linux/ppc64le" ]]; then
  OS_CROSS_COMPILE_PLATFORMS+=(
    "linux/ppc64le"
  )
fi

readonly OS_IMAGE_COMPILE_PLATFORMS

readonly OS_CROSS_COMPILE_TARGETS=(
  cmd/openshift
  cmd/oc
)
readonly OS_CROSS_COMPILE_BINARIES=("${OS_CROSS_COMPILE_TARGETS[@]##*/}")

readonly OS_ALL_TARGETS=(
  "${OS_CROSS_COMPILE_TARGETS[@]}"
)
readonly OS_ALL_BINARIES=("${OS_ALL_TARGETS[@]##*/}")

#If you update this list, be sure to get the images/origin/Dockerfile
readonly OPENSHIFT_BINARY_SYMLINKS=(
  openshift-router
  openshift-deploy
  openshift-recycle
  openshift-sti-build
  openshift-docker-build
  origin
  atomic-enterprise
  osc
  oadm
  osadm
  kubectl
  kubernetes
  kubelet
  kube-proxy
  kube-apiserver
  kube-controller-manager
  kube-scheduler
)
readonly OPENSHIFT_BINARY_COPY=(
  oadm
  kubelet
  kube-proxy
  kube-apiserver
  kube-controller-manager
  kube-scheduler
)
readonly OC_BINARY_COPY=(
  kubectl
)
readonly OS_BINARY_RELEASE_CLIENT_WINDOWS=(
  oc.exe
  README.md
  ./LICENSE
)
readonly OS_BINARY_RELEASE_CLIENT_MAC=(
  oc
  README.md
  ./LICENSE
)
readonly OS_BINARY_RELEASE_CLIENT_LINUX=(
  ./oc
  ./README.md
  ./LICENSE
)
readonly OS_BINARY_RELEASE_SERVER_LINUX=(
  './*'
)
readonly OS_BINARY_RELEASE_CLIENT_EXTRA=(
  ${OS_ROOT}/README.md
  ${OS_ROOT}/LICENSE
)

# os::build::binaries_from_targets take a list of build targets and return the
# full go package to be built
function os::build::binaries_from_targets() {
  local target
  for target; do
    echo "${OS_GO_PACKAGE}/${target}"
  done
}
readonly -f os::build::binaries_from_targets

# Create a user friendly version of host_platform for end users
function os::build::host_platform_friendly() {
  local platform=${1:-}
  if [[ -z "${platform}" ]]; then
    platform=$(os::build::host_platform)
  fi
  if [[ $platform == "windows/amd64" ]]; then
    echo "windows"
  elif [[ $platform == "darwin/amd64" ]]; then
    echo "mac"
  elif [[ $platform == "linux/386" ]]; then
    echo "linux-32bit"
  elif [[ $platform == "linux/amd64" ]]; then
    echo "linux-64bit"
  else
    echo "$(go env GOHOSTOS)-$(go env GOHOSTARCH)"
  fi
}
readonly -f os::build::host_platform_friendly

# os::build::setup_env will check that the `go` commands is available in
# ${PATH}. If not running on Travis, it will also check that the Go version is
# good enough for the Kubernetes build.
#
# Output Vars:
#   export GOPATH - A modified GOPATH to our created tree along with extra
#     stuff.
#   export GOBIN - This is actively unset if already set as we want binaries
#     placed in a predictable place.
function os::build::setup_env() {
  if [[ -z "$(which go)" ]]; then
    cat <<EOF

Can't find 'go' in PATH, please fix and retry.
See http://golang.org/doc/install for installation instructions.

EOF
    exit 2
  fi

  if [[ -z "$(which sha256sum)" ]]; then
    sha256sum() {
      return 0
    }
  fi

  # Travis continuous build uses a head go release that doesn't report
  # a version number, so we skip this check on Travis.  It's unnecessary
  # there anyway.
  if [[ "${TRAVIS:-}" != "true" ]]; then
    local go_version
    go_version=($(go version))
    if [[ "${go_version[2]}" < "go1.5" ]]; then
      cat <<EOF

Detected Go version: ${go_version[*]}.
Origin builds require Go version 1.6 or greater.

EOF
      exit 2
    fi
  fi
  # For any tools that expect this to be set (it is default in golang 1.6),
  # force vendor experiment.
  export GO15VENDOREXPERIMENT=1

  unset GOBIN

  # default to OS_OUTPUT_GOPATH if no GOPATH set
  if [[ -z "${GOPATH:-}" ]]; then
    export OS_OUTPUT_GOPATH=1
  fi

  # use the regular gopath for building
  if [[ -z "${OS_OUTPUT_GOPATH:-}" ]]; then
    export OS_TARGET_BIN=${GOPATH}/bin
    return
  fi

  # create a local GOPATH in _output
  GOPATH="${OS_OUTPUT}/go"
  OS_TARGET_BIN=${GOPATH}/bin
  local go_pkg_dir="${GOPATH}/src/${OS_GO_PACKAGE}"
  local go_pkg_basedir=$(dirname "${go_pkg_dir}")

  mkdir -p "${go_pkg_basedir}"
  rm -f "${go_pkg_dir}"

  # TODO: This symlink should be relative.
  ln -s "${OS_ROOT}" "${go_pkg_dir}"

  # lots of tools "just don't work" unless we're in the GOPATH
  cd "${go_pkg_dir}"

  # Append OS_EXTRA_GOPATH to the GOPATH if it is defined.
  if [[ -n ${OS_EXTRA_GOPATH:-} ]]; then
    GOPATH="${GOPATH}:${OS_EXTRA_GOPATH}"
    # TODO: needs to handle multiple directories
    OS_TARGET_BIN=${OS_EXTRA_GOPATH}/bin
  fi
  export GOPATH
  export OS_TARGET_BIN
}
readonly -f os::build::setup_env

# Build static binary targets.
#
# Input:
#   $@ - targets and go flags.  If no targets are set then all binaries targets
#     are built.
#   OS_BUILD_PLATFORMS - Incoming variable of targets to build for.  If unset
#     then just the host architecture is built.
function os::build::build_static_binaries() {
  CGO_ENABLED=0 os::build::build_binaries -installsuffix=cgo "$@"
}
readonly -f os::build::build_static_binaries

# Build binary targets specified
#
# Input:
#   $@ - targets and go flags.  If no targets are set then all binaries targets
#     are built.
#   OS_BUILD_PLATFORMS - Incoming variable of targets to build for.  If unset
#     then just the host architecture is built.
function os::build::build_binaries() {
  local -a binaries=( "$@" )
  # Create a sub-shell so that we don't pollute the outer environment
  ( os::build::internal::build_binaries "${binaries[@]+"${binaries[@]}"}" )
}

# Build binary targets specified. Should always be run in a sub-shell so we don't leak GOBIN
#
# Input:
#   $@ - targets and go flags.  If no targets are set then all binaries targets
#     are built.
#   OS_BUILD_PLATFORMS - Incoming variable of targets to build for.  If unset
#     then just the host architecture is built.
os::build::internal::build_binaries() {
    # Check for `go` binary and set ${GOPATH}.
    os::build::setup_env

    # Fetch the version.
    local version_ldflags
    version_ldflags=$(os::build::ldflags)

    # Use eval to preserve embedded quoted strings.
    local goflags
    eval "goflags=(${OS_GOFLAGS:-})"

    local arg
    for arg; do
      if [[ "${arg}" == -* ]]; then
        # Assume arguments starting with a dash are flags to pass to go.
        goflags+=("${arg}")
      fi
    done

    os::build::export_targets "$@"

    local -a nonstatics=()
    local -a tests=()
    for binary in "${binaries[@]}"; do
      if [[ "${binary}" =~ ".test"$ ]]; then
        tests+=($binary)
      else
        nonstatics+=($binary)
      fi
    done

    # Temporarily enable swap for the duration of the build until we move
    # to Go 1.7
    os::build::enable_swap
    trap "os::build::disable_swap" EXIT

    local host_platform=$(os::build::host_platform)
    local platform
    for platform in "${platforms[@]}"; do
      echo "++ Building go targets for ${platform}:" "${targets[@]}"
      mkdir -p "${OS_OUTPUT_BINPATH}/${platform}"

      # output directly to the desired location
      if [[ $platform == $host_platform ]]; then
        export GOBIN="${OS_OUTPUT_BINPATH}/${platform}"
      else
        unset GOBIN
      fi

      if [[ ${#nonstatics[@]} -gt 0 ]]; then
        # allow per-os/arch build flags like OS_GOFLAGS_LINUX_AMD64
        local platform_goflags_envvar=OS_GOFLAGS_$(echo ${platform} | tr '[:lower:]/' '[:upper:]_')
        local platform_goflags
        eval "platform_goflags=(${!platform_goflags_envvar:-})"

        GOOS=${platform%/*} GOARCH=${platform##*/} go install \
          -pkgdir "${OS_OUTPUT_PKGDIR}" \
          "${goflags[@]:+${goflags[@]}}" "${platform_goflags[@]:+${platform_goflags[@]}}" \
          -ldflags "${version_ldflags}" \
          "${nonstatics[@]}"

        # GOBIN is not supported on cross-compile in Go 1.5+ - move to the correct target
        if [[ $platform != $host_platform ]]; then
          local platform_src="/${platform//\//_}"
          mv "${OS_TARGET_BIN}/${platform_src}/"* "${OS_OUTPUT_BINPATH}/${platform}/"
        fi
      fi

      for test in "${tests[@]:+${tests[@]}}"; do
        local outfile="${OS_OUTPUT_BINPATH}/${platform}/$(basename ${test})"
        GOOS=${platform%/*} GOARCH=${platform##*/} go test \
          -pkgdir "${OS_OUTPUT_PKGDIR}" \
          -i -c -o "${outfile}" \
          "${goflags[@]:+${goflags[@]}}" \
          -ldflags "${version_ldflags}" \
          "$(dirname ${test})"
      done
    done
}
readonly -f os::build::build_binaries

# Generates the set of target packages, binaries, and platforms to build for.
# Accepts binaries via $@, and platforms via OS_BUILD_PLATFORMS, or defaults to
# the current platform.
function os::build::export_targets() {
  targets=()
  local arg
  for arg; do
    if [[ "${arg}" != -* ]]; then
      targets+=("${arg}")
    fi
  done

  if [[ ${#targets[@]} -eq 0 ]]; then
    echo "No targets to export!"
    exit 1
  fi

  binaries=($(os::build::binaries_from_targets "${targets[@]}"))

  platforms=("${OS_BUILD_PLATFORMS[@]:+${OS_BUILD_PLATFORMS[@]}}")
  if [[ ${#platforms[@]} -eq 0 ]]; then
    echo "No platforms to build for!"
    exit 1
  fi
}
readonly -f os::build::export_targets

# This will take $@ from $GOPATH/bin and copy them to the appropriate
# place in ${OS_OUTPUT_BINDIR}
#
# If OS_RELEASE_ARCHIVE is set, tar archives prefixed with OS_RELEASE_ARCHIVE for
# each of OS_BUILD_PLATFORMS are created.
#
# Ideally this wouldn't be necessary and we could just set GOBIN to
# OS_OUTPUT_BINDIR but that won't work in the face of cross compilation.  'go
# install' will place binaries that match the host platform directly in $GOBIN
# while placing cross compiled binaries into `platform_arch` subdirs.  This
# complicates pretty much everything else we do around packaging and such.
function os::build::place_bins() {
  (
    local host_platform
    host_platform=$(os::build::host_platform)

    echo "++ Placing binaries"

    if [[ "${OS_RELEASE_ARCHIVE-}" != "" ]]; then
      os::build::get_version_vars
      mkdir -p "${OS_LOCAL_RELEASEPATH}"
    fi

    os::build::export_targets "$@"
    for platform in "${platforms[@]}"; do
      # The substitution on platform_src below will replace all slashes with
      # underscores.  It'll transform darwin/amd64 -> darwin_amd64.
      local platform_src="/${platform//\//_}"

      # Skip this directory if the platform has no binaries.
      if [[ ! -d "${OS_OUTPUT_BINPATH}/${platform}" ]]; then
        continue
      fi

      # Create an array of binaries to release. Append .exe variants if the platform is windows.
      local -a binaries=()
      for binary in "${targets[@]}"; do
        binary=$(basename $binary)
        if [[ $platform == "windows/amd64" ]]; then
          binaries+=("${binary}.exe")
        else
          binaries+=("${binary}")
        fi
      done

      # If no release archive was requested, we're done.
      if [[ "${OS_RELEASE_ARCHIVE-}" == "" ]]; then
        continue
      fi

      # Create a temporary bin directory containing only the binaries marked for release.
      local release_binpath=$(mktemp -d openshift.release.${OS_RELEASE_ARCHIVE}.XXX)
      for binary in "${binaries[@]}"; do
        cp "${OS_OUTPUT_BINPATH}/${platform}/${binary}" "${release_binpath}/"
      done

      # Create binary copies where specified.
      local suffix=""
      if [[ $platform == "windows/amd64" ]]; then
        suffix=".exe"
      fi
      for linkname in "${OPENSHIFT_BINARY_COPY[@]}"; do
        local src="${release_binpath}/openshift${suffix}"
        if [[ -f "${src}" ]]; then
          ln "${release_binpath}/openshift${suffix}" "${release_binpath}/${linkname}${suffix}"
        fi
      done
      for linkname in "${OC_BINARY_COPY[@]}"; do
        local src="${release_binpath}/oc${suffix}"
        if [[ -f "${src}" ]]; then
          ln "${release_binpath}/oc${suffix}" "${release_binpath}/${linkname}${suffix}"
        fi
      done

      # Create the release archive.
      local platform_segment="${platform//\//-}"
      if [[ ${OS_RELEASE_ARCHIVE} == "openshift-origin" ]]; then
        for file in "${OS_BINARY_RELEASE_CLIENT_EXTRA[@]}"; do
          cp "${file}" "${release_binpath}/"
        done
        if [[ $platform == "windows/amd64" ]]; then
          platform="windows" OS_RELEASE_ARCHIVE="openshift-origin-client-tools" os::build::archive_zip "${OS_BINARY_RELEASE_CLIENT_WINDOWS[@]}"
        elif [[ $platform == "darwin/amd64" ]]; then
          platform="mac" OS_RELEASE_ARCHIVE="openshift-origin-client-tools" os::build::archive_zip "${OS_BINARY_RELEASE_CLIENT_MAC[@]}"
        elif [[ $platform == "linux/386" ]]; then
          platform="linux/32bit" OS_RELEASE_ARCHIVE="openshift-origin-client-tools" os::build::archive_tar "${OS_BINARY_RELEASE_CLIENT_LINUX[@]}"
        elif [[ $platform == "linux/amd64" ]]; then
          platform="linux/64bit" OS_RELEASE_ARCHIVE="openshift-origin-client-tools" os::build::archive_tar "${OS_BINARY_RELEASE_CLIENT_LINUX[@]}"
          platform="linux/64bit" OS_RELEASE_ARCHIVE="openshift-origin-server" os::build::archive_tar "${OS_BINARY_RELEASE_SERVER_LINUX[@]}"
        elif [[ $platform == "linux/ppc64le" ]]; then
          platform="linux/ppc64le" OS_RELEASE_ARCHIVE="openshift-origin-client-tools" os::build::archive_tar "${OS_BINARY_RELEASE_CLIENT_LINUX[@]}"
          platform="linux/ppc64le" OS_RELEASE_ARCHIVE="openshift-origin-server" os::build::archive_tar "${OS_BINARY_RELEASE_SERVER_LINUX[@]}"
        else
          echo "++ ERROR: No release type defined for $platform"
        fi
      else
        if [[ $platform == "linux/amd64" ]]; then
          platform="linux/64bit" os::build::archive_tar "./*"
        elif [[ $platform == "linux/ppc64le" ]]; then
          platform="linux/ppc64le" os::build::archive_tar "./*"
        else
          echo "++ ERROR: No release type defined for $platform"
        fi
      fi
      rm -rf "${release_binpath}"
    done
  )
}
readonly -f os::build::place_bins

function os::build::archive_name() {
  echo "${OS_RELEASE_ARCHIVE}-${OS_GIT_VERSION}-$1"
}
readonly -f os::build::archive_name

function os::build::archive_zip() {
  local platform_segment="${platform//\//-}"
  local default_name
  default_name="$( os::build::archive_name "${platform_segment}" ).zip"
  local archive_name="${archive_name:-$default_name}"
  echo "++ Creating ${archive_name}"
  for file in "$@"; do
    pushd "${release_binpath}" &> /dev/null
      sha256sum "${file}"
    popd &>/dev/null
    zip "${OS_LOCAL_RELEASEPATH}/${archive_name}" -qj "${release_binpath}/${file}"
  done
}
readonly -f os::build::archive_zip

function os::build::archive_tar() {
  local platform_segment="${platform//\//-}"
  local base_name
  base_name="$( os::build::archive_name "${platform_segment}" )"
  local default_name="${base_name}.tar.gz"
  local archive_name="${archive_name:-$default_name}"
  echo "++ Creating ${archive_name}"
  pushd "${release_binpath}" &> /dev/null
  find . -type f -exec sha256sum {} \;
  if [[ -n "$(which bsdtar)" ]]; then
    bsdtar -czf "${OS_LOCAL_RELEASEPATH}/${archive_name}" -s ",^\.,${base_name}," $@
  else
    tar -czf "${OS_LOCAL_RELEASEPATH}/${archive_name}" --transform="s,^\.,${base_name}," $@
  fi
  popd &>/dev/null
}
readonly -f os::build::archive_tar

# Checks if the filesystem on a partition that the provided path points to is
# supporting hard links.
#
# Input:
#  $1 - the path where the hardlinks support test will be done.
# Returns:
#  0 - if hardlinks are supported
#  non-zero - if hardlinks aren't supported
function os::build::is_hardlink_supported() {
  local path="$1"
  # Determine if FS supports hard links
  local temp_file=$(TMPDIR="${path}" mktemp)
  ln "${temp_file}" "${temp_file}.link" &> /dev/null && unlink "${temp_file}.link" || local supported=$?
  rm -f "${temp_file}"
  return ${supported:-0}
}
readonly -f os::build::is_hardlink_supported

# Extract a tar.gz compressed archive in a given directory. If the
# archive contains hardlinks and the underlying filesystem is not
# supporting hardlinks then the a hard dereference will be done.
#
# Input:
#   $1 - path to archive file
#   $2 - directory where the archive will be extracted
function os::build::extract_tar() {
  local archive_file="$1"
  local change_dir="$2"

  if [[ -z "${archive_file}" ]]; then
    return 0
  fi

  local tar_flags="--strip-components=1"

  # Unpack archive
  echo "++ Extracting $(basename ${archive_file})"
  if [[ "${archive_file}" == *.zip ]]; then
    unzip -o "${archive_file}" -d "${change_dir}"
    return 0
  fi
  if os::build::is_hardlink_supported "${change_dir}" ; then
    # Ensure that tar won't try to set an owner when extracting to an
    # nfs mount. Setting ownership on an nfs mount is likely to fail
    # even for root.
    local mount_type=$(df -P -T "${change_dir}" | tail -n +2 | awk '{print $2}')
    if [[ "${mount_type}" = "nfs" ]]; then
      tar_flags="${tar_flags} --no-same-owner"
    fi
    tar mxzf "${archive_file}" ${tar_flags} -C "${change_dir}"
  else
    local temp_dir=$(TMPDIR=/dev/shm/ mktemp -d)
    tar mxzf "${archive_file}" ${tar_flags} -C "${temp_dir}"
    pushd "${temp_dir}" &> /dev/null
    tar cO --hard-dereference * | tar xf - -C "${change_dir}"
    popd &>/dev/null
    rm -rf "${temp_dir}"
  fi
}
readonly -f os::build::extract_tar

# os::build::release_sha calculates a SHA256 checksum over the contents of the
# built release directory.
function os::build::release_sha() {
  pushd "${OS_LOCAL_RELEASEPATH}" &> /dev/null
  sha256sum * > CHECKSUM
  popd &> /dev/null
}
readonly -f os::build::release_sha

# os::build::make_openshift_binary_symlinks makes symlinks for the openshift
# binary in _output/local/bin/${platform}
function os::build::make_openshift_binary_symlinks() {
  platform=$(os::build::host_platform)
  if [[ -f "${OS_OUTPUT_BINPATH}/${platform}/openshift" ]]; then
    for linkname in "${OPENSHIFT_BINARY_SYMLINKS[@]}"; do
      ln -sf openshift "${OS_OUTPUT_BINPATH}/${platform}/${linkname}"
    done
  fi
}
readonly -f os::build::make_openshift_binary_symlinks

# os::build::detect_local_release_tars verifies there is only one primary and one
# image binaries release tar in OS_LOCAL_RELEASEPATH for the given platform specified by
# argument 1, exiting if more than one of either is found.
#
# If the tars are discovered, their full paths are exported to the following env vars:
#
#   OS_PRIMARY_RELEASE_TAR
#   OS_IMAGE_RELEASE_TAR
function os::build::detect_local_release_tars() {
  local platform="$1"

  if [[ ! -d "${OS_LOCAL_RELEASEPATH}" ]]; then
    echo "There are no release artifacts in ${OS_LOCAL_RELEASEPATH}"
    return 2
  fi
  if [[ ! -f "${OS_LOCAL_RELEASEPATH}/.commit" ]]; then
    echo "There is no release .commit identifier ${OS_LOCAL_RELEASEPATH}"
    return 2
  fi
  local primary=$(find ${OS_LOCAL_RELEASEPATH} -maxdepth 1 -type f -name openshift-origin-server-*-${platform}* \( -name *.tar.gz -or -name *.zip \))
  if [[ $(echo "${primary}" | wc -l) -ne 1 || -z "${primary}" ]]; then
    echo "There should be exactly one ${platform} server tar in $OS_LOCAL_RELEASEPATH"
    [[ -z "${WARN-}" ]] && return 2
  fi

  local client=$(find ${OS_LOCAL_RELEASEPATH} -maxdepth 1 -type f -name openshift-origin-client-tools-*-${platform}* \( -name *.tar.gz -or -name *.zip \))
  if [[ $(echo "${client}" | wc -l) -ne 1 || -z "${client}" ]]; then
    echo "There should be exactly one ${platform} client tar in $OS_LOCAL_RELEASEPATH"
    [[ -n "${WARN-}" ]] || return 2
  fi

  local image=$(find ${OS_LOCAL_RELEASEPATH} -maxdepth 1 -type f -name openshift-origin-image*-${platform}* \( -name *.tar.gz -or -name *.zip \))
  if [[ $(echo "${image}" | wc -l) -ne 1 || -z "${image}" ]]; then
    echo "There should be exactly one ${platform} image tar in $OS_LOCAL_RELEASEPATH"
    [[ -n "${WARN-}" ]] || return 2
  fi

  export OS_PRIMARY_RELEASE_TAR="${primary}"
  export OS_IMAGE_RELEASE_TAR="${image}"
  export OS_CLIENT_RELEASE_TAR="${client}"
  export OS_RELEASE_COMMIT="$(cat ${OS_LOCAL_RELEASEPATH}/.commit)"
}
readonly -f os::build::detect_local_release_tars

# os::build::get_version_vars loads the standard version variables as
# ENV vars
function os::build::get_version_vars() {
  if [[ -n ${OS_VERSION_FILE-} ]]; then
    source "${OS_VERSION_FILE}"
    return
  fi
  os::build::os_version_vars
  os::build::kube_version_vars
  os::build::etcd_version_vars
}
readonly -f os::build::get_version_vars

# os::build::os_version_vars looks up the current Git vars
function os::build::os_version_vars() {
  local git=(git --work-tree "${OS_ROOT}")

  if [[ -n ${OS_GIT_COMMIT-} ]] || OS_GIT_COMMIT=$("${git[@]}" rev-parse --short "HEAD^{commit}" 2>/dev/null); then
    if [[ -z ${OS_GIT_TREE_STATE-} ]]; then
      # Check if the tree is dirty.  default to dirty
      if git_status=$("${git[@]}" status --porcelain 2>/dev/null) && [[ -z ${git_status} ]]; then
        OS_GIT_TREE_STATE="clean"
      else
        OS_GIT_TREE_STATE="dirty"
      fi
    fi
    # Use git describe to find the version based on annotated tags.
    if [[ -n ${OS_GIT_VERSION-} ]] || OS_GIT_VERSION=$("${git[@]}" describe --long --tags --abbrev=7 "${OS_GIT_COMMIT}^{commit}" 2>/dev/null); then
      # Try to match the "git describe" output to a regex to try to extract
      # the "major" and "minor" versions and whether this is the exact tagged
      # version or whether the tree is between two tagged versions.
      if [[ "${OS_GIT_VERSION}" =~ ^v([0-9]+)\.([0-9]+)(\.[0-9]+)?([-].*)?$ ]]; then
        OS_GIT_MAJOR=${BASH_REMATCH[1]}
        OS_GIT_MINOR=${BASH_REMATCH[2]}
        if [[ -n "${BASH_REMATCH[4]}" ]]; then
          OS_GIT_MINOR+="+"
        fi
      fi

      # This translates the "git describe" to an actual semver.org
      # compatible semantic version that looks something like this:
      #   v1.1.0-alpha.0.6+84c76d1-345
      OS_GIT_VERSION=$(echo "${OS_GIT_VERSION}" | sed "s/-\([0-9]\{1,\}\)-g\([0-9a-f]\{7,40\}\)$/\+\2-\1/")
      # If this is an exact tag, remove the last segment.
      OS_GIT_VERSION=$(echo "${OS_GIT_VERSION}" | sed "s/-0$//")
      if [[ "${OS_GIT_TREE_STATE}" == "dirty" ]]; then
        # git describe --dirty only considers changes to existing files, but
        # that is problematic since new untracked .go files affect the build,
        # so use our idea of "dirty" from git status instead.
        OS_GIT_VERSION+="-dirty"
      fi
    fi
  fi
}
readonly -f os::build::os_version_vars

function os::build::etcd_version_vars() {
  ETCD_GIT_VERSION=$(go run "${OS_ROOT}/tools/godepversion/godepversion.go" "${OS_ROOT}/Godeps/Godeps.json" "github.com/coreos/etcd/etcdserver" "comment")
  ETCD_GIT_COMMIT=$(go run "${OS_ROOT}/tools/godepversion/godepversion.go" "${OS_ROOT}/Godeps/Godeps.json" "github.com/coreos/etcd/etcdserver")
}
readonly -f os::build::etcd_version_vars

# os::build::kube_version_vars returns the version of Kubernetes we have
# vendored.
function os::build::kube_version_vars() {
  KUBE_GIT_VERSION=$(go run "${OS_ROOT}/tools/godepversion/godepversion.go" "${OS_ROOT}/Godeps/Godeps.json" "k8s.io/kubernetes/pkg/api" "comment")
  KUBE_GIT_COMMIT=$(go run "${OS_ROOT}/tools/godepversion/godepversion.go" "${OS_ROOT}/Godeps/Godeps.json" "k8s.io/kubernetes/pkg/api")

  # This translates the "git describe" to an actual semver.org
  # compatible semantic version that looks something like this:
  #   v1.1.0-alpha.0.6+84c76d1142ea4d
  #
  # TODO: We continue calling this "git version" because so many
  # downstream consumers are expecting it there.
  KUBE_GIT_VERSION=$(echo "${KUBE_GIT_VERSION}" | sed "s/-\([0-9]\{1,\}\)-g\([0-9a-f]\{7,40\}\)$/\+\2/")

  # Try to match the "git describe" output to a regex to try to extract
  # the "major" and "minor" versions and whether this is the exact tagged
  # version or whether the tree is between two tagged versions.
  if [[ "${KUBE_GIT_VERSION}" =~ ^v([0-9]+)\.([0-9]+)(\.[0-9]+)?([-].*)?$ ]]; then
    KUBE_GIT_MAJOR=${BASH_REMATCH[1]}
    KUBE_GIT_MINOR=${BASH_REMATCH[2]}
    if [[ -n "${BASH_REMATCH[4]}" ]]; then
      KUBE_GIT_MINOR+="+"
    fi
  fi
}
readonly -f os::build::kube_version_vars

# Saves the environment flags to $1
function os::build::save_version_vars() {
  local version_file=${1-}
  [[ -n ${version_file} ]] || {
    echo "!!! Internal error.  No file specified in os::build::save_version_vars"
    return 1
  }

  cat <<EOF >"${version_file}"
OS_GIT_COMMIT='${OS_GIT_COMMIT-}'
OS_GIT_TREE_STATE='${OS_GIT_TREE_STATE-}'
OS_GIT_VERSION='${OS_GIT_VERSION-}'
OS_GIT_MAJOR='${OS_GIT_MAJOR-}'
OS_GIT_MINOR='${OS_GIT_MINOR-}'
KUBE_GIT_COMMIT='${KUBE_GIT_COMMIT-}'
KUBE_GIT_VERSION='${KUBE_GIT_VERSION-}'
ETCD_GIT_VERSION='${ETCD_GIT_VERSION-}'
ETCD_GIT_COMMIT='${ETCD_GIT_COMMIT-}'
EOF
}
readonly -f os::build::save_version_vars

# golang 1.5 wants `-X key=val`, but golang 1.4- REQUIRES `-X key val`
function os::build::ldflag() {
  local key=${1}
  local val=${2}

  GO_VERSION=($(go version))
  if [[ -n $(echo "${GO_VERSION[2]}" | grep -E 'go1.4') ]]; then
    echo "-X ${key} ${val}"
  else
    echo "-X ${key}=${val}"
  fi
}
readonly -f os::build::ldflag

# os::build::ldflags calculates the -ldflags argument for building OpenShift
function os::build::ldflags() {
  # Run this in a subshell to prevent settings/variables from leaking.
  set -o errexit
  set -o nounset
  set -o pipefail

  cd "${OS_ROOT}"

  os::build::get_version_vars

  local buildDate="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"

  declare -a ldflags=()

  ldflags+=($(os::build::ldflag "${OS_GO_PACKAGE}/pkg/version.majorFromGit" "${OS_GIT_MAJOR}"))
  ldflags+=($(os::build::ldflag "${OS_GO_PACKAGE}/pkg/version.minorFromGit" "${OS_GIT_MINOR}"))
  ldflags+=($(os::build::ldflag "${OS_GO_PACKAGE}/pkg/version.versionFromGit" "${OS_GIT_VERSION}"))
  ldflags+=($(os::build::ldflag "${OS_GO_PACKAGE}/pkg/version.commitFromGit" "${OS_GIT_COMMIT}"))
  ldflags+=($(os::build::ldflag "${OS_GO_PACKAGE}/pkg/version.buildDate" "${buildDate}"))
  ldflags+=($(os::build::ldflag "${OS_GO_PACKAGE}/vendor/k8s.io/kubernetes/pkg/version.gitCommit" "${KUBE_GIT_COMMIT}"))
  ldflags+=($(os::build::ldflag "${OS_GO_PACKAGE}/vendor/k8s.io/kubernetes/pkg/version.gitVersion" "${KUBE_GIT_VERSION}"))
  ldflags+=($(os::build::ldflag "${OS_GO_PACKAGE}/vendor/k8s.io/kubernetes/pkg/version.buildDate" "${buildDate}"))
  ldflags+=($(os::build::ldflag "${OS_GO_PACKAGE}/vendor/k8s.io/kubernetes/pkg/version.gitTreeState" "clean"))

  # The -ldflags parameter takes a single string, so join the output.
  echo "${ldflags[*]-}"
}
readonly -f os::build::ldflags

# os::build::enable_swap attempts to enable swap for the system if a) this is Linux and b)
# the amount of physical memory is less than 10GB. This is a stopgap until we have
# better control over memory use in Go 1.7+.
function os::build::enable_swap() {
  # if we aren't on linux or have more than 9GB of memory
  if [[ -n "${OS_BUILD_SWAP_DISABLE-}" || "$(go env GOHOSTOS)" != "linux" || "$( os::build::physmem_gb )" -gt 9 ]]; then
    return
  fi
  # if we don't have the swapon command available
  if ! swapon &>/dev/null; then
    return
  fi
  # if swap is already on
  if [[ "$( swapon --show --noheadings | wc -l )" -ne 0 ]]; then
    return
  fi
  echo "++ temporarily enabling swap space to assist in building in limited memory - use OS_BUILD_SWAP_DISABLE=1 to bypass"

  (
    set -e
    sudo cp /etc/fstab /origin-backupfstab
    sudo dd if=/dev/zero of=/origin-swapfile bs=1M count=${OS_BUILD_SWAP_SIZE:-2048}
    sudo chmod 600 /origin-swapfile
    sudo mkswap /origin-swapfile
    sudo swapon /origin-swapfile
    sudo /bin/sh -c 'echo "/origin-swapfile none swap defaults 0 0" >> /etc/fstab'
  ) &>/dev/null || true
}
readonly -f os::build::enable_swap

# os::build::disable_swap undoes the effects of os::build::enable_swap
function os::build::disable_swap() {
  # if we aren't on linux or have more than 9GB of memory
  if [[ -n "${OS_BUILD_SWAP_DISABLE-}" || "$(go env GOHOSTOS)" != "linux" ]]; then
    return
  fi
  # if we previously set up a swapfile
  if [[ ! -f /origin-swapfile ]]; then
    return
  fi
  (
    set +e
    sudo swapoff /origin-swapfile
    sudo cp /origin-backupfstab /etc/fstab
    sudo rm -f /origin-backupfstab /origin-swapfile
  ) || true
}
readonly -f os::build::disable_swap

# os::build::physmem_gb returns the approximate gigabytes of memory on the system
# This is copied verbatim from kube for the purposes of detecting how much available
# memory we have for building.
function os::build::physmem_gb() {
  local mem

  # Linux kernel version >=3.14, in kb
  if mem=$(grep MemAvailable /proc/meminfo | awk '{ print $2 }'); then
    echo $(( ${mem} / 1048576 ))
    return
  fi

  # Linux, in kb
  if mem=$(grep MemTotal /proc/meminfo | awk '{ print $2 }'); then
    echo $(( ${mem} / 1048576 ))
    return
  fi

  # OS X, in bytes. Note that get_physmem, as used, should only ever
  # run in a Linux container (because it's only used in the multiple
  # platform case, which is a Dockerized build), but this is provided
  # for completeness.
  if mem=$(sysctl -n hw.memsize 2>/dev/null); then
    echo $(( ${mem} / 1073741824 ))
    return
  fi

  # If we can't infer it, just give up and assume a low memory system
  echo 1
}
readonly -f os::build::physmem_gb

# os::build::require_clean_tree exits if the current Git tree is not clean.
function os::build::require_clean_tree() {
  if ! git diff-index --quiet HEAD -- || test $(git ls-files --exclude-standard --others | wc -l) != 0; then
    echo "You can't have any staged or dirty files in $(pwd) for this command."
    echo "Either commit them or unstage them to continue."
    exit 1
  fi
}
readonly -f os::build::require_clean_tree

# os::build::commit_range takes one or two arguments - if the first argument is an
# integer, it is assumed to be a pull request and the local origin/pr/# branch is
# used to determine the common range with the second argument. If the first argument
# is not an integer, it is assumed to be a Git commit range and output directly.
function os::build::commit_range() {
  local remote
  remote="${UPSTREAM_REMOTE:-origin}"
  if [[ "$1" =~ ^-?[0-9]+$ ]]; then
    local target
    target="$(git rev-parse ${remote}/pr/$1)"
    if [[ $? -ne 0 ]]; then
      echo "Branch does not exist, or you have not configured ${remote}/pr/* style branches from GitHub" 1>&2
      exit 1
    fi

    local base
    base="$(git merge-base ${target} $2)"
    if [[ $? -ne 0 ]]; then
      echo "Branch has no common commits with $2" 1>&2
      exit 1
    fi
    if [[ "${base}" == "${target}" ]]; then

      # DO NOT TRUST THIS CODE
      merged="$(git rev-list --reverse ${target}..$2 --ancestry-path | head -1)"
      if [[ -z "${merged}" ]]; then
        echo "Unable to find the commit that merged ${remote}/pr/$1" 1>&2
        exit 1
      fi
      #if [[ $? -ne 0 ]]; then
      #  echo "Unable to find the merge commit for $1: ${merged}" 1>&2
      #  exit 1
      #fi
      echo "++ pr/$1 appears to have merged at ${merged}" 1>&2
      leftparent="$(git rev-list --parents -n 1 ${merged} | cut -f2 -d ' ')"
      if [[ $? -ne 0 ]]; then
        echo "Unable to find the left-parent for the merge of for $1" 1>&2
        exit 1
      fi
      base="$(git merge-base ${target} ${leftparent})"
      if [[ $? -ne 0 ]]; then
        echo "Unable to find the common commit between ${leftparent} and $1" 1>&2
        exit 1
      fi
      echo "${base}..${target}"
      exit 0
      #echo "Branch has already been merged to upstream master, use explicit range instead" 1>&2
      #exit 1
    fi

    echo "${base}...${target}"
    exit 0
  fi

  echo "$1"
}
readonly -f os::build::commit_range

function os::build::gen-completions() {
  local dest="$1"
  local shell="$2"
  local skipprefix="${3:-}"

  # We do this in a tmpdir in case the dest has other non-autogenned files
  # We don't want to include them in the list of gen'd files
  local tmpdir="${OS_ROOT}/_tmp/gen_comp"
  mkdir -p "${tmpdir}"
  # generate the new files
  ${OS_OUTPUT_BINPATH}/${platform}/oc completion ${shell} > $tmpdir/oc
  ${OS_OUTPUT_BINPATH}/${platform}/openshift completion ${shell} > $tmpdir/openshift
  ${OS_OUTPUT_BINPATH}/${platform}/oadm completion ${shell} > $tmpdir/oadm
  # create the list of generated files
  ls "${tmpdir}" | LC_ALL=C sort > "${tmpdir}/.files_generated"

  # remove all old generated file from the destination
  while read file; do
    if [[ -e "${tmpdir}/${file}" && -n "${skipprefix}" ]]; then
      local original generated
      original=$(grep -v "^${skipprefix}" "${dest}/${file}") || :
      generated=$(grep -v "^${skipprefix}" "${tmpdir}/${file}") || :
      if [[ "${original}" == "${generated}" ]]; then
        # overwrite generated with original.
        mv "${dest}/${file}" "${tmpdir}/${file}"
      fi
    else
      rm "${dest}/${file}" || true
    fi
  done <"${dest}/.files_generated"

  # put the new generated file into the destination
  find "${tmpdir}" -exec rsync -pt {} "${dest}" \; >/dev/null
  #cleanup
  rm -rf "${tmpdir}"

  echo "Assets generated in ${dest}"
}
readonly -f os::build::gen-completions

function os::build::gen-man() {
  local cmd="$1"
  local dest="$2"
  local cmdName="$3"
  local filestore=".files_generated_$3"
  local skipprefix="${4:-}"

  # We do this in a tmpdir in case the dest has other non-autogenned files
  # We don't want to include them in the list of gen'd files
  local tmpdir="${OS_ROOT}/_tmp/gen_man"
  mkdir -p "${tmpdir}"
  # generate the new files
  ${cmd} "${tmpdir}" "${cmdName}"
  # create the list of generated files
  ls "${tmpdir}" | LC_ALL=C sort > "${tmpdir}/${filestore}"

  # remove all old generated file from the destination
  while read file; do
    if [[ -e "${tmpdir}/${file}" && -n "${skipprefix}" ]]; then
      local original generated
      original=$(grep -v "^${skipprefix}" "${dest}/${file}") || :
      generated=$(grep -v "^${skipprefix}" "${tmpdir}/${file}") || :
      if [[ "${original}" == "${generated}" ]]; then
        # overwrite generated with original.
        mv "${dest}/${file}" "${tmpdir}/${file}"
      fi
    else
      rm "${dest}/${file}" || true
    fi
  done <"${dest}/${filestore}"

  # put the new generated file into the destination
  find "${tmpdir}" -exec rsync -pt {} "${dest}" \; >/dev/null
  #cleanup
  rm -rf "${tmpdir}"

  echo "Assets generated in ${dest}"
}
readonly -f os::build::gen-man

function os::build::gen-docs() {
  local cmd="$1"
  local dest="$2"
  local skipprefix="${3:-}"

  # We do this in a tmpdir in case the dest has other non-autogenned files
  # We don't want to include them in the list of gen'd files
  local tmpdir="${OS_ROOT}/_tmp/gen_doc"
  mkdir -p "${tmpdir}"
  # generate the new files
  ${cmd} "${tmpdir}"
  # create the list of generated files
  ls "${tmpdir}" | LC_ALL=C sort > "${tmpdir}/.files_generated"

  # remove all old generated file from the destination
  while read file; do
    if [[ -e "${tmpdir}/${file}" && -n "${skipprefix}" ]]; then
      local original generated
      original=$(grep -v "^${skipprefix}" "${dest}/${file}") || :
      generated=$(grep -v "^${skipprefix}" "${tmpdir}/${file}") || :
      if [[ "${original}" == "${generated}" ]]; then
        # overwrite generated with original.
        mv "${dest}/${file}" "${tmpdir}/${file}"
      fi
    else
      rm "${dest}/${file}" || true
    fi
  done <"${dest}/.files_generated"

  # put the new generated file into the destination
  find "${tmpdir}" -exec rsync -pt {} "${dest}" \; >/dev/null
  #cleanup
  rm -rf "${tmpdir}"

  echo "Assets generated in ${dest}"
}
readonly -f os::build::gen-docs

function os::build::get-bin-output-path() {
  local os_root="${1:-}"

  if [[ -n "${os_root}" ]]; then
    os_root="${os_root}/"
  fi
  echo ${os_root}_output/local/bin/$(os::build::host_platform)
}
readonly -f os::build::get-bin-output-path

# os::build::find-binary locates a locally built binary for the current
# platform and returns the path to the binary.  The base path to search
# from will default to the current working directory but can be
# overridden via the optional second argument.
function os::build::find-binary() {
  local bin="$1"
  local os_root="${2:-}"

  local path=$( (ls -t $(os::build::get-bin-output-path "${os_root}")/${bin}) 2>/dev/null || true | head -1 )
  echo "$path"
}
readonly -f os::build::find-binary

# os::build::environment::create creates a docker container with the default variables.
# arguments are passed directly to the container, OS_BUILD_ENV_GOLANG, OS_BUILD_ENV_IMAGE,
# and OS_RELEASE_DOCKER_ARGS can be used to customize the container. The docker socket
# is mounted by default and the output of the command is the container id.
function os::build::environment::create() {
  set -o errexit
  local release_image="${OS_BUILD_ENV_IMAGE}"
  local additional_context="${OS_BUILD_ENV_DOCKER_ARGS:-}"
  if [[ "${OS_BUILD_ENV_USE_DOCKER:-y}" == "y" ]]; then
    additional_context+="--privileged -v /var/run/docker.sock:/var/run/docker.sock"

    if [[ "${OS_BUILD_ENV_LOCAL_DOCKER:-n}" == "y" ]]; then
      # if OS_BUILD_ENV_LOCAL_DOCKER==y, add the local OS_ROOT as the bind mount to the working dir
      # and set the running user to the current user
      local workingdir
      workingdir=$( os::build::environment::release::workingdir )
      additional_context+=" -v ${OS_ROOT}:${workingdir} -u $(id -u)"
    elif [[ -n "${OS_BUILD_ENV_REUSE_VOLUME:-}" ]]; then
      # if OS_BUILD_ENV_REUSE_VOLUME is set, create a docker volume to store the working output so
      # successive iterations can reuse shared code.
      local workingdir
      workingdir=$( os::build::environment::release::workingdir )
      name="$( echo "${OS_BUILD_ENV_REUSE_VOLUME}" | tr '[:upper:]' '[:lower:]' )"
      docker volume create --name "${name}" > /dev/null
      additional_context+=" -v ${name}:${workingdir}"
    fi
  fi

  local args
  if [[ $# -eq 0 ]]; then
    args=( "echo" "docker create ${additional_context} ${release_image}" )
  else
    args=( "$@" )
  fi

  # Create a new container to from the release environment
  docker create ${additional_context} "${release_image}" "${args[@]}"
}
readonly -f os::build::environment::create

# os::build::environment::release::workingdir calculates the working directory for the current
# release image.
function os::build::environment::release::workingdir() {
  set -o errexit
  # get working directory
  local container
  container="$(docker create "${release_image}")"
  local workingdir
  workingdir="$(docker inspect -f '{{ index . "Config" "WorkingDir" }}' "${container}")"
  docker rm "${container}" > /dev/null
  echo "${workingdir}"
}
readonly -f os::build::environment::release::workingdir

# os::build::environment::cleanup stops and removes the container named in the argument
# (unless OS_BUILD_ENV_LEAVE_CONTAINER is set, in which case it will only stop the container).
function os::build::environment::cleanup() {
  local container=$1
  docker stop --time=0 "${container}" > /dev/null || true
  if [[ -z "${OS_BUILD_ENV_LEAVE_CONTAINER:-}" ]]; then
    docker rm "${container}" > /dev/null
  fi
}
readonly -f os::build::environment::cleanup

# os::build::environment::start starts the container provided as the first argument
# using whatever content exists in the container already.
function os::build::environment::start() {
  local container=$1

  docker start "${container}" > /dev/null
  docker logs -f "${container}"

  local exitcode
  exitcode="$( docker inspect --type container -f '{{ .State.ExitCode }}' "${container}" )"

  # extract content from the image
  if [[ -n "${OS_BUILD_ENV_PRESERVE-}" ]]; then
    local workingdir
    workingdir="$(docker inspect -f '{{ index . "Config" "WorkingDir" }}' "${container}")"
    local oldIFS="${IFS}"
    IFS=:
    for path in ${OS_BUILD_ENV_PRESERVE}; do
      local parent=.
      if [[ "${path}" != "." ]]; then
        parent="$( dirname ${path} )"
        mkdir -p "${parent}"
      fi
      docker cp "${container}:${workingdir}/${path}" "${parent}"
    done
    IFS="${oldIFS}"
  fi
  return $exitcode
}
readonly -f os::build::environment::start

# os::build::environment::withsource starts the container provided as the first argument
# after copying in the contents of the current Git repository at HEAD (or, if specified,
# the ref specified in the second argument).
function os::build::environment::withsource() {
  local container=$1
  local commit=${2:-HEAD}

  if [[ -n "${OS_BUILD_ENV_LOCAL_DOCKER-}" ]]; then
    # running locally, no change necessary
    os::build::get_version_vars
    os::build::save_version_vars "${OS_ROOT}/os-version-defs"
  else
    local workingdir
    workingdir="$(docker inspect -f '{{ index . "Config" "WorkingDir" }}' "${container}")"
    if [[ -n "${OS_BUILD_ENV_REUSE_VOLUME-}" ]]; then
      local excluded=()
      local oldIFS="${IFS}"
      IFS=:
      for exclude in ${OS_BUILD_ENV_EXCLUDE:-_output}; do
        excluded+=("--exclude=${exclude}")
      done
      IFS="${oldIFS}"
      if which rsync &>/dev/null; then
        local name
        name="$( echo "${OS_BUILD_ENV_REUSE_VOLUME}" | tr '[:upper:]' '[:lower:]' )"
        if ! rsync -a --blocking-io ${excluded[@]} --omit-dir-times --numeric-ids -e "docker run --rm -i -v \"${name}:${workingdir}\" --entrypoint=/bin/bash \"${OS_BUILD_ENV_IMAGE}\" -c '\$@'" . remote:"${workingdir}"; then
          # fall back to a tar if rsync is not in container
          tar -cf - ${excluded[@]} . | docker cp - "${container}:${workingdir}"
        fi
      else
        tar -cf - ${excluded[@]} . | docker cp - "${container}:${workingdir}"
      fi
    else
      # Generate version definitions. Tree state is clean because we are pulling from git directly.
      OS_GIT_TREE_STATE=clean os::build::get_version_vars
      os::build::save_version_vars "/tmp/os-version-defs"

      tar -cf - -C /tmp/ os-version-defs | docker cp - "${container}:${workingdir}"
      git archive --format=tar "${commit}" | docker cp - "${container}:${workingdir}"
    fi
  fi

  os::build::environment::start "${container}"
}
readonly -f os::build::environment::withsource

# os::build::environment::run launches the container with the provided arguments and
# the current commit (defaults to HEAD). The container is automatically cleaned up.
function os::build::environment::run() {
  local commit="${OS_GIT_COMMIT:-HEAD}"
  local volume="${OS_BUILD_ENV_REUSE_VOLUME:-}"
  if [[ -z "${volume}" ]]; then
    volume="origin-build-$( git rev-parse "${commit}" )"
  fi

  local container
  container="$( OS_BUILD_ENV_REUSE_VOLUME=${volume} os::build::environment::create "$@" )"
  trap "os::build::environment::cleanup ${container}" EXIT

  os::build::environment::withsource "${container}" "${commit}"
}
readonly -f os::build::environment::run