text:
package igpp.servlet;

//import java.io.*;
import java.io.PrintStream;
import java.io.PrintWriter;

import javax.xml.transform.stream.StreamResult;

import javax.servlet.jsp.JspWriter;

/**
 * Implements the JspWriter interface for a PrintStream.
 * Allows directing the output of a servlet to the display (System.out)
 * Useful in the main() method of an executable class.
 *
 * @author Todd King
 * @version 1.00 2006
 */
public class MultiPrinter extends JspWriter
{
	PrintStream outStream = null;
	PrintWriter outWriter = null;

	/**
	 * Command line interface.
	 *
	 * @param args   command-line arguments.
	 **/
	static public void main(String[] args)
	{
		MultiPrinter me = new MultiPrinter();
		System.out.println( me.getClass().getName() );
		me.close();
	}

	/**
	 * Create an instance of a MultiPrinter.
	 **/
	public MultiPrinter()
	{
		super(1024, true);
		setOut(System.out);
	}

	/**
	 * Create an instance of a MultiPrinter configured to output to a {@link PrintStream}.
	 *
	 * @param out  a pre-opened {@link PrintStream} like System.out.
	 **/
	public MultiPrinter(PrintStream out)
	{
		super(1024, true);
		setOut(out);
	}

	/**
	 * Create an instance of a MultiPrinter configured to output to a {@link PrintWriter}.
	 *
	 * @param out  a pre-opened {@link PrintWriter} like "out" in a JSP servlet.
	 **/
	public MultiPrinter(PrintWriter out)
	{
		super(1024, true);
		setOut(out);
	}

	/**
	 * Set the output to match another {@link MultiPrinter}.
	 *
	 * @param out  a pre-configured {@link MultiPrinter}.
	 **/
	public void setOut(MultiPrinter out)
	{
		this.outStream = out.outStream;
		this.outWriter = out.outWriter;
	}

	/**
	 * Set the output to a pre-opened {@link PrintWriter}.
	 *
	 * @param out  a pre-opened {@link PrintWriter} like "out" in a JSP servlet.
	 **/
	public void setOut(PrintWriter out)
	{
		this.outStream = null;
		this.outWriter = out;
	}

	/**
	 * Set the output to a pre-opened {@link PrintStream}.
	 *
	 * @param out  a pre-opened {@link PrintStream} like System.out.
	 **/
	public void setOut(PrintStream out)
	{
		this.outStream = out;
		this.outWriter = null;
	}

	/**
	 * Get a {@link StreamResult} for the current output stream.
	 *
	 * @return  a {@link StreamResult} prepared with the current output stream. Returns null if no output stream is set.
	 **/
	public StreamResult getStreamResult()
	{
		if(this.outStream != null) return new StreamResult(this.outStream);
		if(this.outWriter != null) return new StreamResult(this.outWriter);

		return null;
	}

	public int getRemaining()
	{
		return 0;
	}

	/**
	 * Close the currently set output method.
	 **/
	public void close()
	{
		if(outStream != null) outStream.close();
		if(outWriter != null) outWriter.close();
	}

	/**
	 * Flush the currently set output method.
	 **/
	public void flush()
	{
		if(outStream != null) outStream.flush();
		if(outWriter != null) outWriter.flush();
	}

	/**
	 * Clear intermeadiate buffers in the currently set output method.
	 **/
	public void clearBuffer()
	{
	}

	/**
	 * Clear the currently set output method.
	 **/
	public void clear()
	{
	}

	/**
	 * Output a new line sequence.
	 **/
	public void newLine()
	{
		if(outStream != null) outStream.println();
		if(outWriter != null) outWriter.println();
	}

	/**
	 * Output a new line sequence.
	 **/
	public void println()
	{
		if(outStream != null) outStream.println();
		if(outWriter != null) outWriter.println();
	}

	/**
	 * Print an Object and then terminate the line with a new line sequence.
	 *
	 * @param o the object to be printed.
	 **/
	public void println(Object o)
	{
		if(outStream != null) outStream.println(o);
		if(outWriter != null) outWriter.println(o);
	}

	/**
	 * Print a String and then terminate the line with a new line secquence.
	 *
	 * @param s the {@link String} to be printed.
	 **/
	public void println(String s)
	{
		if(outStream != null) outStream.println(s);
		if(outWriter != null) outWriter.println(s);
	}

	/**
	 * Print a long and then terminate the line with a new line secquence.
	 *
	 * @param l the long to be printed.
	 **/
	public void println(long l)
	{
		if(outStream != null) outStream.println(l);
		if(outWriter != null) outWriter.println(l);
	}

	/**
	 * Print a float and then terminate the line with a new line secquence.
	 *
	 * @param f the float to be printed.
	 **/
	public void println(float f)
	{
		if(outStream != null) outStream.println(f);
		if(outWriter != null) outWriter.println(f);
	}

	/**
	 * Print a double and then terminate the line with a new line secquence.
	 *
	 * @param d the double to be printed.
	 **/
	public void println(double d)
	{
		if(outStream != null) outStream.println(d);
		if(outWriter != null) outWriter.println(d);
	}

	/**
	 * Print an int and then terminate the line with a new line secquence.
	 *
	 * @param i the int to be printed.
	 **/
	public void println(int i)
	{
		if(outStream != null) outStream.println(i);
		if(outWriter != null) outWriter.println(i);
	}

	/**
	 * Print a character sequence and then terminate the line with a new line secquence.
	 *
	 * @param c the sequence of char to be printed.
	 **/
	public void println(char[] c)
	{
		if(outStream != null) outStream.println(c);
		if(outWriter != null) outWriter.println(c);
	}

	/**
	 * Print a char and then terminate the line with a new line secquence.
	 *
	 * @param c the char to be printed.
	 **/
	public void println(char c)
	{
		if(outStream != null) outStream.println(c);
		if(outWriter != null) outWriter.println(c);
	}

	/**
	 * Print a boolean and then terminate the line with a new line secquence.
	 *
	 * @param b the boolean to be printed.
	 **/
	public void println(boolean b)
	{
		if(outStream != null) outStream.println(b);
		if(outWriter != null) outWriter.println(b);
	}

	/**
	 * Print an object.
	 *
	 * @param o the {@link Object} to be printed.
	 **/
	public void print(Object o)
	{
		if(outStream != null) outStream.print(o);
		if(outWriter != null) outWriter.print(o);
	}

	/**
	 * Print a String.
	 *
	 * @param s the {@link String} to be printed.
	 **/
	public void print(String s)
	{
		if(outStream != null) outStream.print(s);
		if(outWriter != null) outWriter.print(s);
	}

	/**
	 * Print an long integer.
	 *
	 * @param l the long to be printed.
	 **/
	public void print(long l)
	{
		if(outStream != null) outStream.print(l);
		if(outWriter != null) outWriter.print(l);
	}

	/**
	 * Print a float.
	 *
	 * @param f the float to be printed.
	 **/
	public void print(float f)
	{
		if(outStream != null) outStream.print(f);
		if(outWriter != null) outWriter.print(f);
	}

	/**
	 * Print a double.
	 *
	 * @param d the double to be printed.
	 **/
	public void print(double d)
	{
		if(outStream != null) outStream.print(d);
		if(outWriter != null) outWriter.print(d);
	}

	/**
	 * Print an int.
	 *
	 * @param i the int to be printed.
	 **/
	public void print(int i)
	{
		if(outStream != null) outStream.print(i);
		if(outWriter != null) outWriter.print(i);
	}

	/**
	 * Print an array of char.
	 *
	 * @param c the sequence of char to be printed.
	 **/
	public void print(char[] c)
	{
		if(outStream != null) outStream.print(c);
		if(outWriter != null) outWriter.print(c);
	}

	/**
	 * Print an char.
	 *
	 * @param c the char to be printed.
	 **/
	public void print(char c)
	{
		if(outStream != null) outStream.print(c);
		if(outWriter != null) outWriter.print(c);
	}

	/**
	 * Print a boolean.
	 *
	 * @param b the boolean to be printed.
	 **/
	public void print(boolean b)
	{
		if(outStream != null) outStream.print(b);
		if(outWriter != null) outWriter.print(b);
	}

	/**
	 * Write a {@link String} to the output stream.
	 *
	 * @param s the {@link String} to write.
	 **/
	public void write(String s)
	{
		if(outStream != null) outStream.print(s);
		if(outWriter != null) outWriter.write(s);
	}

	/**
	 * Write len char from the specified char array starting at offset off to this stream.
	 *
	 * @param c the char array.
	 * @param off the offset into the c to start writing.
	 * @param len the number of char to write starting at off.
	 **/
	public void write(char[] c, int off, int len)
	{
		String	buffer = new String(c, off, len);
		if(outStream != null) outStream.print(buffer);
		if(outWriter != null) outWriter.print(buffer);
	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <!-- Favicon -->
  <link href="<?php echo base_url('assets/favicon.png'); ?>" type="image/x-icon" rel="shortcut icon">

  <!-- TITLE -->
  <!-- /.END TITLE -->

  <!-- Bootstrap 3.3.6 -->
  <link rel="stylesheet" href="<?php echo base_url(); ?>assets/belakang/frameworks/bootstrap/css/bootstrap.min.css">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="<?php echo base_url(); ?>assets/belakang/fonts/font-awesome/css/font-awesome.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="<?php echo base_url(); ?>assets/belakang/fonts/ionicons/css/ionicons.min.css">
  <!-- jvectormap -->
  <link rel="stylesheet" href="<?php echo base_url(); ?>assets/belakang/plugins/jvectormap/jquery-jvectormap-1.2.2.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="<?php echo base_url(); ?>assets/belakang/frameworks/dist/css/AdminLTE.min.css">
  <!-- AdminLTE Skins. Choose a skin from the css/skins
       folder instead of downloading all of them to reduce the load. -->
  <link rel="stylesheet" href="<?php echo base_url(); ?>assets/belakang/frameworks/dist/css/skins/_all-skins.min.css">

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->

</head>

<!-- ADD THE CLASS fixed TO GET A FIXED HEADER AND SIDEBAR LAYOUT -->
<!-- the fixed layout is not compatible with sidebar-mini -->
<body class="hold-transition skin-blue fixed sidebar-mini">

  <!-- Site wrapper -->
  <div class="wrapper">

redpajama_set_name: RedPajamaGithub


text:
import os
import unittest

from telemetry.core import browser_finder
from telemetry.page import page_runner
from telemetry.page import page as page_module
from telemetry.page import page_benchmark_results
from telemetry.page import page_set
from telemetry.test import options_for_unittests

class PageBenchmarkUnitTestBase(unittest.TestCase):
  """unittest.TestCase-derived class to help in the construction of unit tests
  for a benchmark."""

  def CreatePageSetFromFileInUnittestDataDir(self, test_filename):
    return self.CreatePageSet('file:///' + os.path.join(
        '..', '..', 'unittest_data', test_filename))

  def CreatePageSet(self, test_filename):
    base_dir = os.path.dirname(__file__)
    ps = page_set.PageSet(file_path=os.path.join(base_dir, 'foo.json'))
    page = page_module.Page(test_filename, ps, base_dir=base_dir)
    setattr(page, 'smoothness', {'action': 'scroll'})
    ps.pages.append(page)
    return ps

  def RunBenchmark(self, benchmark, ps, options=None):
    """Runs a benchmark against a pageset, returning the rows its outputs."""
    if options is None:
      options = options_for_unittests.GetCopy()
    assert options
    temp_parser = options.CreateParser()
    benchmark.AddCommandLineOptions(temp_parser)
    defaults = temp_parser.get_default_values()
    for k, v in defaults.__dict__.items():
      if hasattr(options, k):
        continue
      setattr(options, k, v)

    benchmark.CustomizeBrowserOptions(options)
    possible_browser = browser_finder.FindBrowser(options)

    results = page_benchmark_results.PageBenchmarkResults()
    with page_runner.PageRunner(ps) as runner:
      runner.Run(options, possible_browser, benchmark, results)
    return results


text:
<!DOCTYPE html>

	<meta name="generator" content="Hugo 0.50" />
    <base href="https://muskegonrisers.com/">
    <title>Muskegon Riser -- Muskegon Risers</title>
    <meta charset="utf-8">
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

<meta name="description" content="Muskegon Riser">
<meta name="keywords" content="pro soccer, muskegon, soccer club, soccer, grand haven, whitehall, NPSL, PDL, watch muskegon" />
<meta name="author" content="Sleeping Bear Design - SleepingBearDesign.com">

<meta property="og:title" content="Muskegon Risers" />
<meta property="og:site_name" content="Muskegon Risers">
<meta property="og:type" content="website" />
<meta property="og:url" content="https://muskegonrisers.com/" />
<meta property="og:description" content="Muskegon Risers SC strives to represent the spirit of our area's people in past, present and future tense." />
<meta property="og:image" content="https://muskegonrisers.com/assets/img/social/facebook.jpg" />

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@RisersSC"/>
<meta name="twitter:image" content="https://muskegonrisers.com/assets/img/social/twitter.jpg">
<meta name="twitter:title" content="Muskegon Risers">
<meta name="twitter:description" content="Muskegon Risers SC strives to represent the spirit of our area's people in past, present and future tense.">

<meta name="application-name" content="Muskegon Riser"/>
<meta name="msapplication-TileColor" content="#ffffff"/>
<meta name="msapplication-TileImage" content="ico/ms-icon-144x144.png">
<meta name="msapplication-square70x70logo" content="ico/ms-icon-70x70.png"/>
<meta name="msapplication-square150x150logo" content="ico/ms-icon-150x150.png"/>
<meta name="msapplication-square310x310logo" content="ico/ms-icon-310x310.png"/>

<link rel="apple-touch-icon" sizes="57x57" href="ico/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="ico/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="ico/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="ico/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="ico/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="ico/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="ico/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="ico/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="ico/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="ico/android-icon-192x192.png">
<link rel="shortcut icon" type="image/png" sizes="32x32" href="ico/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="ico/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="ico/favicon-16x16.png">
<meta name="theme-color" content="#ffffff">

    <link href="bootstrap3/css/bootstrap.min.css" rel="stylesheet" />
    <link href="assets/css/gsdk.css" rel="stylesheet"/>
    <link href="assets/css/demo.css" rel="stylesheet" />

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Grand+Hotel|Open+Sans:400,300' rel='stylesheet' type='text/css'>
    <link href="assets/css/pe-icon-7-stroke.css" rel="stylesheet" />

    <link id="snipcart-theme" type="text/css" href="https://cdn.snipcart.com/themes/base/snipcart.min.css" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/snipcart.css">

    <meta name="google-site-verification" content="FGOvBqPlJa4NNhTN58o7Izde6oJ6Gx8Lk2au7QKWY08" />

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

      </button>

Home

 About

 Store

 Staff

 Schedule

 Roster

 Blog

 Contact

 ()
 Cart

            <video autoplay loop class="fillWidth">
                <source src="assets/video/mp4/Beach-Ball.mp4" type="video/mp4" />Your browser does not support the video tag. I suggest you upgrade your browser.
                <source src="assets/video/webm/Beach-Ball.webm" type="video/webm" />Your browser does not support the video tag. I suggest you upgrade your browser.
            </video>

Our Purpose

Muskegon Risers SC was founded to help facilitate positive social and economic change along the Muskegon Lakeshore through the game of soccer. A Riser is someone who understands our community's potential and who pushes themselves and others to realize that potential. Our 'Risers' name was inspired by the 'Muskegon, Together Rising' sculpture that stands in the heart of downtown Muskegon. Risers are not limited to an era, industry or ethnicity. Muskegon Risers SC strives to represent the spirit of our area's people in past, present and future tense.

Store

Jersey Tank Top

               With true style, this tank is extremely smooth and soft.

                $30.00

Tube Socks

               Maximum comfort and style simultaneously!

                $25.00

Baby Short Sleeve One-Piece

               Designed for maximum comfort!

                $30.00

                    View All Products

Share Us!

                     <button class="btn btn-round btn-fill btn-social btn-facebook" onclick="FB.ui({method: 'share', href: 'https:\/\/muskegonrisers.com\/',}, function(response){});">
                          Share
                     </button>

                          Tweet

                          Share

                          Pin it

Staff

Ben Ritsema

Head Coach (Men's Arena)

 Muskegon, MI

Ben Ritsema

Experience

Ben Ritsema has led the Muskegon Risers men's arena soccer team since 2015. During this time, the Risers have experienced exponential growth and are currently competing in the Major Arena Soccer League II.

Stu Collins

Head Coach (Men's Outdoor)

 Muskegon, MI

Stu Collins

Experience

Stuart Collins is a former standout and National Champion at Davenport University and has logged the most minutes as a player in Muskegon Risers history. Collins also served as team captain for the Risers from May of 2016 through 2019.

Jon Romkema, AT, ATC

Athletic Trainer

 Muskegon, MI

 Mercy Health

Jon Romkema, AT, ATC

Experience

Jon has 28 years of Athletic Training experience and serves as the Manager of Sports Medicine at Mercy Health. He is responsible for coordinating Athletic Training services for the Risers.

Marcus Schillaci, AT, ATC, CSCS

Athletic Trainer

 Muskegon, MI

 Mercy Health

Marcus Schillaci, AT, ATC, CSCS

Experience

Marcus serves as Manager of Rehab and Athletic Performance. A longtime soccer player and Muskegon native, his training expertise will prepare the Risers for the season as he coordinates all training sessions for the team through the PEAK Training Academy.

Mark Peterman, PT, DPT

Physical Therapist

 Muskegon, MI

Mark Peterman, PT, DPT

Experience

Dr. Mark Peterman is the official Team Physical Therapist for Muskegon Risers SC. A life-long soccer player and fan, Dr. Peterman graduated from Western Michigan Christian to pursue a career in physical therapy.

Dr. Mike Morea

Chiropractor

 Muskegon, MI

 MoreaChiro.com

Dr. Mike Morea

Experience

Dr. Mike Morea graduated with a degree in biology from Michigan State University and graduated from Chiropractic School at Life University in Georgia earning top honors, Summa Cum Laude.

Kody Harrell

Partnership Manager

 Muskegon, MI

Kody Harrell

Experience

Kody Harrell started as a marketing intern with the Muskegon Risers in 2014 and has developed into his current position as the team's Partnership Manager. Harrell graduated with a degree in business management from Grand Valley State University in 2016.

Upcoming Games

                    View Entire Schedule

                        Riser Review

Get the latest news about MKG!

                        View All Stories

                                     Read More

Blog

Riser Review

Corporate Partners

Reach Out

Feel free to get in touch with questions, concerns, or volunteer opportunities and we'll get back to you as soon as possible. If you feel inclined, please sign up for our newsletter below and receive the latest updates and possible volunteer opportunities.

                    <form id="contact-form" class="contact-form" action="#">

                                Your name
                                <input id="nameid" class="form-control" placeholder="Name" type="text" name="name" required>

                                Your email
                                <input id="emailid" class="form-control" placeholder="Email" type="email" name="_replyto" required>

                            Your message
                            <textarea id="textareaid" class="form-control" rows="4" placeholder="Tell us your thoughts and feelings..." name="message" required></textarea>

                                <button class="btn btn-round btn-default btn-lg" id="sendButton" name="send" data-toggle="morphing" type="submit" data-rotation-color="green">Send Message</button>

                        <input type="hidden" name="_subject" value="Contact from Muskegon Risers!" />
                        <input class="hidden" type="text" name="_gotcha" style="display:none" />
                    </form>

                <form action="//muskegonrisers.us9.list-manage.com/subscribe/post?u=fcf121a2d5e4c66d5ee168321&id=b4bd2ebb16" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

                                  <input type="email" name="EMAIL" value="" class="form-control" placeholder="Enter your email..." id="mce-EMAIL">

<input type="text" name="b_fcf121a2d5e4c66d5ee168321_b4bd2ebb16" tabindex="-1" value="">

                             <input type="submit" value="Subscribe Now!" name="subscribe" id="mc-embedded-subscribe" class="btn btn-default btn-fill btn-round">

                 </form>

Home

Blog

            © 2018 Muskegon Risers Soccer Club. All Rights Reserved, made with  by Sleeping Bear Design


text:
#pragma once

#include <gtest/gtest.h>

#include <jni.h>

class LibnativehelperTest : public ::testing::Test {
  protected:
    virtual void SetUp() override;
    virtual void TearDown() override;

    JNIEnv* mEnv;
};


text:
/**
 * This module defines the Title view which generates title for the workflow page
 */
define(['lib/jquery', '../core', './core'], function($, Ambrose, View) {
  var Title = View.Title = function(workflow, container) {
    return new View.Title.fn.init(workflow, container);
  };

  Title.fn = Title.prototype = {
    /**
     * Constructor.
     *
     * @param workflow the Workflow instance to bind to.
     * @param container the DOM element in which to render the view.
     */
    init: function(workflow, container) {
      container = $(container);
      var info = Ambrose.parseHRavenWorkflow(workflow);
      console.log(info);
      if (!$.isEmptyObject(info)) {
        $('
').appendTo(container).text(info.id).css('margin-bottom', '0px');
        $('').appendTo(container)
          .html("user " + info.user + " on cluster " + info.cluster + "");
      } else {
        container.remove();
      }
    },
  };

  // bind prototype to ctor
  Title.fn.init.prototype = Title.fn;
  return Title;
});


text:
package org.apache.hadoop.hbase.master;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.coprocessor.*;
import org.apache.hadoop.hbase.ipc.CoprocessorProtocol;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;

import java.io.IOException;

/**
 * Provides the coprocessor framework and environment for master oriented
 * operations.  {@link HMaster} interacts with the loaded coprocessors
 * through this class.
 */
public class MasterCoprocessorHost
    extends CoprocessorHost<MasterCoprocessorHost.MasterEnvironment> {

  private static final Log LOG = LogFactory.getLog(MasterCoprocessorHost.class);

  /**
   * Coprocessor environment extension providing access to master related
   * services.
   */
  static class MasterEnvironment extends CoprocessorHost.Environment
      implements MasterCoprocessorEnvironment {
    private MasterServices masterServices;

    public MasterEnvironment(final Class<?> implClass, final Coprocessor impl,
        final int priority, final int seq, final Configuration conf,
        final MasterServices services) {
      super(impl, priority, seq, conf);
      this.masterServices = services;
    }

    public MasterServices getMasterServices() {
      return masterServices;
    }
  }

  private MasterServices masterServices;

  MasterCoprocessorHost(final MasterServices services, final Configuration conf) {
    this.conf = conf;
    this.masterServices = services;
    loadSystemCoprocessors(conf, MASTER_COPROCESSOR_CONF_KEY);
  }

  @Override
  public MasterEnvironment createEnvironment(final Class<?> implClass,
      final Coprocessor instance, final int priority, final int seq,
      final Configuration conf) {
    for (Class c : implClass.getInterfaces()) {
      if (CoprocessorProtocol.class.isAssignableFrom(c)) {
        masterServices.registerProtocol(c, (CoprocessorProtocol)instance);
        break;
      }
    }
    return new MasterEnvironment(implClass, instance, priority, seq, conf,
        masterServices);
  }

  @Override
  protected void abortServer(final CoprocessorEnvironment env, final Throwable e) {
    abortServer("master", masterServices, env, e);
  }

  /* Implementation of hooks for invoking MasterObservers */
  void preCreateTable(HTableDescriptor htd, HRegionInfo[] regions)
    throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preCreateTable(ctx, htd, regions);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void postCreateTable(HTableDescriptor htd, HRegionInfo[] regions)
    throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
            ((MasterObserver)env.getInstance()).postCreateTable(ctx, htd, regions);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void preDeleteTable(byte[] tableName) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preDeleteTable(ctx, tableName);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void postDeleteTable(byte[] tableName) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postDeleteTable(ctx, tableName);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void preModifyTable(final byte[] tableName, HTableDescriptor htd)
      throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preModifyTable(ctx, tableName,
              htd);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void postModifyTable(final byte[] tableName, HTableDescriptor htd)
      throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postModifyTable(ctx, tableName,
              htd);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  boolean preAddColumn(byte [] tableName, HColumnDescriptor column)
      throws IOException {
    boolean bypass = false;
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preAddColumn(ctx, tableName, column);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  void postAddColumn(byte [] tableName, HColumnDescriptor column)
      throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postAddColumn(ctx, tableName,
              column);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  boolean preModifyColumn(byte [] tableName, HColumnDescriptor descriptor)
      throws IOException {
    boolean bypass = false;
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preModifyColumn(
            ctx, tableName, descriptor);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  void postModifyColumn(byte [] tableName, HColumnDescriptor descriptor)
      throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postModifyColumn(
              ctx, tableName, descriptor);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  boolean preDeleteColumn(final byte [] tableName, final byte [] c)
      throws IOException {
    boolean bypass = false;
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preDeleteColumn(ctx, tableName, c);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  void postDeleteColumn(final byte [] tableName, final byte [] c)
      throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postDeleteColumn(ctx, tableName,
              c);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void preEnableTable(final byte [] tableName) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preEnableTable(ctx, tableName);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void postEnableTable(final byte [] tableName) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postEnableTable(ctx, tableName);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void preDisableTable(final byte [] tableName) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preDisableTable(ctx, tableName);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void postDisableTable(final byte [] tableName) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postDisableTable(ctx, tableName);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  boolean preMove(final HRegionInfo region, final ServerName srcServer, final ServerName destServer)
      throws IOException {
    boolean bypass = false;
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preMove(
              ctx, region, srcServer, destServer);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  void postMove(final HRegionInfo region, final ServerName srcServer, final ServerName destServer)
      throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postMove(
              ctx, region, srcServer, destServer);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  boolean preAssign(final HRegionInfo regionInfo) throws IOException {
    boolean bypass = false;
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver) env.getInstance()).preAssign(ctx, regionInfo);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  void postAssign(final HRegionInfo regionInfo) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postAssign(ctx, regionInfo);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  boolean preUnassign(final HRegionInfo regionInfo, final boolean force)
      throws IOException {
    boolean bypass = false;
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preUnassign(
              ctx, regionInfo, force);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  void postUnassign(final HRegionInfo regionInfo, final boolean force)
      throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postUnassign(
              ctx, regionInfo, force);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  boolean preBalance() throws IOException {
    boolean bypass = false;
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preBalance(ctx);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        bypass |= ctx.shouldBypass();
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return bypass;
  }

  void postBalance() throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postBalance(ctx);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  boolean preBalanceSwitch(final boolean b) throws IOException {
    boolean balance = b;
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          balance = ((MasterObserver)env.getInstance()).preBalanceSwitch(
              ctx, balance);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
    return balance;
  }

  void postBalanceSwitch(final boolean oldValue, final boolean newValue)
      throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postBalanceSwitch(
              ctx, oldValue, newValue);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void preShutdown() throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preShutdown(ctx);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void preStopMaster() throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preStopMaster(ctx);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  void postStartMaster() throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postStartMaster(ctx);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  public void preSnapshot(final SnapshotDescription snapshot,
      final HTableDescriptor hTableDescriptor) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preSnapshot(ctx, snapshot, hTableDescriptor);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  public void postSnapshot(final SnapshotDescription snapshot,
      final HTableDescriptor hTableDescriptor) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postSnapshot(ctx, snapshot, hTableDescriptor);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  public void preCloneSnapshot(final SnapshotDescription snapshot,
      final HTableDescriptor hTableDescriptor) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preCloneSnapshot(ctx, snapshot, hTableDescriptor);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  public void postCloneSnapshot(final SnapshotDescription snapshot,
      final HTableDescriptor hTableDescriptor) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postCloneSnapshot(ctx, snapshot, hTableDescriptor);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  public void preRestoreSnapshot(final SnapshotDescription snapshot,
      final HTableDescriptor hTableDescriptor) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preRestoreSnapshot(ctx, snapshot, hTableDescriptor);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  public void postRestoreSnapshot(final SnapshotDescription snapshot,
      final HTableDescriptor hTableDescriptor) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postRestoreSnapshot(ctx, snapshot, hTableDescriptor);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  public void preDeleteSnapshot(final SnapshotDescription snapshot) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).preDeleteSnapshot(ctx, snapshot);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }

  public void postDeleteSnapshot(final SnapshotDescription snapshot) throws IOException {
    ObserverContext<MasterCoprocessorEnvironment> ctx = null;
    for (MasterEnvironment env: coprocessors) {
      if (env.getInstance() instanceof MasterObserver) {
        ctx = ObserverContext.createAndPrepare(env, ctx);
        try {
          ((MasterObserver)env.getInstance()).postDeleteSnapshot(ctx, snapshot);
        } catch (Throwable e) {
          handleCoprocessorThrowable(env, e);
        }
        if (ctx.shouldComplete()) {
          break;
        }
      }
    }
  }
}


text:
<script>
    // Capture window.window and window.opener: once this context is navigated, these properties
    // always return null.
    var w = window;
    var o = opener;
    opener.accessFrame = function()
    {
        function normalizeURL(url)
        {
            return url.substring(url.lastIndexOf("LayoutTests"));
        }

        try {
            o.log("document.URL: " + normalizeURL(document.URL));
            o.log("window.document.URL: " + normalizeURL(w.document.URL));
            o.log("name: " + name);
            o.log("window.name: " + w.name);
        } catch (e) {
            o.log("An exception was thrown: " + e.message);
        }
    }

    window.location = "notify-opener-done.html";
</script>


text:
import React, { ReactNode, ReactElement } from "react";
import { storiesOf } from "@storybook/react";
import { RowStack, ColumnStack, Fit, Fill, Fixed } from "../Components/ItemsStack/ItemsStack";

function Outline(props: { children: ReactNode }): ReactElement {
    const { children } = props;
    return (
        <div
            style={{
                padding: "5px 3px",
                height: "100%",
                border: "1px solid #333",
                boxSizing: "border-box",
            }}
        >
            {children}
        </div>
    );
}

storiesOf("ItemsStack", module)
    .add("RowStack", () => (
        <RowStack block gap={2}>
            <Fit>
                <Outline>Fit Item</Outline>
            </Fit>
            <Fill>
                <Outline>Fill Item</Outline>
            </Fill>
            <Fixed width={70}>
                <Outline>
                    Item with fixed width and long, long word "Eyjafjallajökull"
                </Outline>
            </Fixed>
        </RowStack>
    ))
    .add("ColumnStack", () => (
        <ColumnStack block stretch gap={2} style={{ height: "300px" }}>
            <Fit>
                <Outline>Fit Item</Outline>
            </Fit>
            <Fill>
                <Outline>Fill Item (when parent have fixed height)</Outline>
            </Fill>
            <Fit>
                <Outline>Fit Item</Outline>
            </Fit>
        </ColumnStack>
    ));


text:
declare const cssClasses: {
    HELPER_TEXT_PERSISTENT: string;
    HELPER_TEXT_VALIDATION_MSG: string;
    ROOT: string;
};
declare const strings: {
    ARIA_HIDDEN: string;
    ROLE: string;
    ROOT_SELECTOR: string;
};
export { strings, cssClasses };


text:
"""
from multiworld.core.serializable import Serializable
from typing import Dict, List, Tuple
import cv2
import gym
from gym import spaces
import numpy as np
import time
from datetime import datetime

try:
    from juggler.libraries import robot_client
except:
    print("Failed to import juggler")

from weakly_supervised_control.envs.env_util import normalize_image, unormalize_image, concat_images

JOINT_POS_SPACE = np.array((2.97, 2.09, 2.97, 2.09, 2.97, 2.09, 3.05))
JOINT_VEL_SPACE = np.array((1.48, 1.48, 1.75, 1.31, 2.27, 2.36, 2.36))

# Franka settings
INIT_QUATERNION = np.array((0, 1, 0, 0))  # For Kuka, use (0, 0, 1, 0).
MIN_POS = np.array((0.355, -0.135, 0.248))#0.257845))
MAX_POS = np.array((0.545, 0.105, 0.257845))
MAX_VEL_ACTION = np.array((0.12, 0.12, 0.01))
MAX_VEL_PER_COMMAND = 0.04
COLLISION_DIST_THRESHOLD = 1e-2

def get_image_from_camera(camera) -> np.ndarray:
    """Reads an image from the camera."""
    assert camera is not None
    while True:
        try:
            _, image = camera.read()
            if len(image) > 0:
                break
        except:
            print(image)
    return image

class HardwareRobotEnv(gym.Env, Serializable):
    def __init__(self,
                 camera_ids: List[int] = [2, 0],
                 frequency: int = 2,
                 reset_blocks_freq: int = 5,
                 stack_images: bool = True):
        self.quick_init(locals())
        self.client = robot_client.make_robot_client_from_commandline()
        self.client.send_command(
            robot_client.RobotCommandBuilder().enable_motion())

        self.reset_blocks_freq = reset_blocks_freq
        self.stack_images = stack_images
        self.last_pos = np.zeros(3)
        self.timestep = 1. / frequency
        self.num_resets = 0

        # Initialize cameras.
        self.cameras = []
        if camera_ids:
            for camera_id in camera_ids:
                camera = cv2.VideoCapture(camera_id)
                assert camera is not None, camera_id
                self.cameras.append(camera)

        if self.stack_images:
            image_obs_shape = (48, 48, 3 * len(self.cameras))
        else:
            image_obs_shape = (len(self.cameras), 48, 48, 3)

        self.observation_space = spaces.Dict({
            'joint_pos': spaces.Box(
                low=-JOINT_POS_SPACE, high=JOINT_POS_SPACE
            ),
            'joint_vel': spaces.Box(
                low=-JOINT_VEL_SPACE, high=JOINT_VEL_SPACE,
            ),
            'end_effector_pos': spaces.Box(
                low=MIN_POS, high=MAX_POS,
            ),
            'end_effector_quaternion': spaces.Box(
                low=-1, high=1, shape=(4,), dtype=float
            ),
            'image_observation': spaces.Box(
                low=0, high=255, shape=image_obs_shape, dtype=int),
        })
        self.action_space = spaces.Box(
            low=-1, high=1, shape=(3,), dtype=float)

        command = robot_client.RobotCommandBuilder()
        command.set_part('arm').set_blocking().joint_position_move(
            (0, 0, 0, -np.pi / 2, 0, np.pi / 2, 0))
        self.client.send_command(command)

        # command = robot_client.RobotCommandBuilder()
        # command.set_part('gripper').gripper_move(0.02, 1.0)
        # self.client.send_command(command)

        self.reset()

    def _get_arm_pos(self):
        state = self.client.get_state()

        joint_pos = np.asarray(state.part_states[
            'arm'].joint_position_sensed.data)
        joint_vel = np.asarray(state.part_states[
            'arm'].joint_velocity_sensed.data)

        t = state.part_states['arm'].pose_sensed.translation
        end_effector_pos = np.asarray([t.x, t.y, t.z])

        t = state.part_states['arm'].pose_sensed.rotation
        end_effector_quaternion = np.asarray([t.w, t.x, t.y, t.z])

        return joint_pos, joint_vel, end_effector_pos, end_effector_quaternion

    def get_image(self, width: int = 48, height: int = 48) -> np.ndarray:
        """Returns a list of images."""
        images = []
        for camera in self.cameras:
            if camera is None:
                print("Warning: Camera is not set")
                image = np.zeros((width, height, 3))
            else:
                image = get_image_from_camera(camera)
                image = cv2.resize(image, (width, height))
            images.append(image)
        images = np.array(images)

        if self.stack_images:
            # Images should be of shape (num_images, w, h, 3).
            assert len(images.shape) == 4, images.shape
            assert images.shape[-1] == 3, images.shape
            # Reshape to (w, h, 3 * num_images).
            images = np.concatenate(images, axis=2)
        return images

    def render(self, width: int = 500, height: int = 500) -> None:
        if not self.cameras:
            return
        images = self.get_image(width, height)  # Do not resize
        images = concat_images(images)
        cv2.imshow('image', images)
        cv2.waitKey(1)

    def _get_obs(self):
        # Get arm pos
        joint_pos, joint_vel, end_effector_pos, end_effector_quaternion = self._get_arm_pos()
        obs = {
            'joint_pos': joint_pos,
            'joint_vel': joint_vel,
            'end_effector_pos': end_effector_pos,
            'end_effector_quaternion': end_effector_quaternion,
        }

        # Get image
        if self.cameras:
            images = self.get_image()
            obs['image_observation'] = images

        return obs

    def _move_arm_fast(self, pos: np.ndarray):
        command = robot_client.RobotCommandBuilder()
        command.set_part('arm').set_blocking(
        ).cartesian_position_move(pos, INIT_QUATERNION)
        self.client.send_command(command)

    def _move_arm(self, xyz: np.ndarray, max_vel_per_command: float = None, blocking: bool = False):
        if max_vel_per_command is None:
            max_vel_per_command = MAX_VEL_PER_COMMAND
        xyz = np.clip(xyz, MIN_POS, MAX_POS)

        _, _, self.last_pos, _ = self._get_arm_pos()
        vel = xyz - self.last_pos
        num_commands = max(
            int(np.ceil(np.max(np.abs(vel)) / max_vel_per_command)), 1)
        vel_per_command = vel / num_commands
        #print(f'xyz: {xyz}, vel: {vel}, num_commands: {num_commands}, vel_per_command: {vel_per_command}')

        command = robot_client.RobotCommandBuilder()
        for i in range(num_commands):
            pos = self.last_pos + vel_per_command
            pos = np.clip(pos, MIN_POS, MAX_POS)

            if blocking:
                command.set_part('arm').set_blocking(
                ).cartesian_position_move(pos, INIT_QUATERNION)
                self.client.send_command(command)
            else:
                command.set_part('arm').cartesian_position_move(
                    pos, INIT_QUATERNION)
                self.client.send_command(command)
                time.sleep(self.timestep)

            _, _, self.last_pos, _ = self._get_arm_pos()

            # Check for collision.
            pos_diff = np.linalg.norm(self.last_pos - pos)
            if pos_diff > COLLISION_DIST_THRESHOLD:
                #print(f"Collision detected (actual: {self.last_pos}, expected: {pos}, diff: {pos_diff}). Clipping action after {i+1}/{num_commands} commands.")
                break

    def step(self, action: np.ndarray):
        assert action.shape == (3,), action.shape
        action = action * MAX_VEL_ACTION
        assert np.all(action <= MAX_VEL_ACTION), action

        # Execute action
        self._move_arm(self.last_pos + action)

        obs = self._get_obs()
        return obs, 0, False, {}

    def _reset_arm(self):
        """Resets arm position to initial position."""
        command = robot_client.RobotCommandBuilder()
        init_pos = np.array(0.5 * (MIN_POS + MAX_POS))
        command.set_part('arm').set_blocking().cartesian_position_move(
            init_pos, INIT_QUATERNION)
        self.client.send_command(command)

        # Update last position.
        self.last_pos = init_pos.copy()

    def _reset_blocks(self):
        """Sweeps arm around the bin to randomize block positions."""
        center_pos_low = np.array(0.5 * (MIN_POS + MAX_POS))
        center_pos_low[2] = MIN_POS[2]

        center_pos_high = np.array(0.5 * (MIN_POS + MAX_POS))
        center_pos_high[2] = MAX_POS[2] + 0.05

        x_min = MIN_POS[0]
        x_max = MAX_POS[0]
        y_min = MIN_POS[1]
        y_max = MAX_POS[1]
        z_min = MIN_POS[2]
        z_max = MAX_POS[2] + 0.05
        slow_vel = 0.05
        fast_vel = 0.1
        delta_y = (y_max - y_min) / 2
        delta_x = (x_max - x_min) / 2

        # Move arm along the edges of the bin, pushing blocks to the center.
        #   1    2
        #   4    3
        command = robot_client.RobotCommandBuilder()
        print("Moving arm from 1 to 2...")
        i = 0
        y = y_min + delta_y * i
        while y < y_max:
            command.set_part('arm').set_blocking().cartesian_position_move(
                np.array([x_min, y, z_max]), INIT_QUATERNION)
            self.client.send_command(command)

            self._move_arm(np.array([x_min, y, z_min]),
                           slow_vel, blocking=True)
            self._move_arm(center_pos_low + [-0.05, 0, 0], fast_vel, blocking=True)

            # command.set_part('arm').set_blocking().cartesian_position_move(
            #     center_pos_high, INIT_QUATERNION)
            # self.client.send_command(command)
            i += 1
            y = y_min + delta_y * i

        print("Moving arm from 2 to 3...")
        i = 0
        x = x_min + delta_x * i
        while x < x_max:
            command.set_part('arm').set_blocking().cartesian_position_move(
                np.array([x, y_max, z_max]), INIT_QUATERNION)
            self.client.send_command(command)

            self._move_arm(np.array([x, y_max, z_min]),
                           slow_vel, blocking=True)
            self._move_arm(center_pos_low + [0, 0.05, 0], fast_vel, blocking=True)

            # command.set_part('arm').set_blocking().cartesian_position_move(
            #     center_pos_high, INIT_QUATERNION)
            # self.client.send_command(command)
            i += 1
            x = x_min + delta_x * i

        print("Moving arm from 3 to 4...")
        i = 0
        y = y_max - delta_y * i
        while y > y_min:
            command.set_part('arm').set_blocking().cartesian_position_move(
                np.array([x_max, y, z_max]), INIT_QUATERNION)
            self.client.send_command(command)

            self._move_arm(np.array([x_max, y, z_min]),
                           slow_vel, blocking=True)
            self._move_arm(center_pos_low + [0.05, 0, 0], fast_vel, blocking=True)

            # command.set_part('arm').set_blocking().cartesian_position_move(
            #     center_pos_high, INIT_QUATERNION)
            # self.client.send_command(command)
            i += 1
            y = y_max - delta_y * i

        print("Moving arm from 4 to 1...")
        i = 0
        x = x_max - delta_x * i
        while x > x_min:
            command.set_part('arm').set_blocking().cartesian_position_move(
                np.array([x, y_min, z_max]), INIT_QUATERNION)
            self.client.send_command(command)

            self._move_arm(np.array([x, y_min, z_min]),
                           slow_vel, blocking=True)
            self._move_arm(center_pos_low + [-0.05, 0, 0], fast_vel, blocking=True)

            # command.set_part('arm').set_blocking().cartesian_position_move(
            #     center_pos_high, INIT_QUATERNION)
            # self.client.send_command(command)
            i += 1
            x = x_min - delta_x * i

        command.set_part('arm').set_blocking().cartesian_position_move(
            np.array([x_min, y_min, z_max]), INIT_QUATERNION)
        self.client.send_command(command)

        self._move_arm(np.array([x_min, y_min, z_min]),
                       slow_vel, blocking=True)
        self._move_arm(center_pos_low, fast_vel, blocking=True)

        # command.set_part('arm').set_blocking().cartesian_position_move(
        #     center_pos_high, INIT_QUATERNION)
        # self.client.send_command(command)

        # self._move_arm(np.array([x_min, y_min, z_min]),
        #                fast_vel, blocking=True)
        # self._move_arm(np.array([x_min, y_max, z_min]),
        #                fast_vel, blocking=True)
        # self._move_arm(np.array([x_max, y_max, z_min]),
        #                fast_vel, blocking=True)
        # self._move_arm(np.array([x_max, y_min, z_min]),
        #                fast_vel, blocking=True)
        # self._move_arm(np.array([x_min, y_min, z_min]),
        #                fast_vel, blocking=True)
        # self._move_arm(np.array([x_min, y_max, z_min]),
        #                fast_vel, blocking=True)

        # Move arm back to reset position
        print("Reset pos")
        init_pos = np.array(0.5 * (MIN_POS + MAX_POS))
        self._move_arm(init_pos, fast_vel, blocking=True)

        # Update last position.
        self.last_pos = init_pos.copy()

    def reset(self):
        if (self.num_resets == 0 or (self.reset_blocks_freq is not None and self.num_resets % self.reset_blocks_freq == 0)):
            print("Resetting blocks...")
            self._reset_blocks()
            print("Finished resetting blocks.")
        else:
            self._reset_arm()
        self.num_resets += 1

        obs = self._get_obs()
        return obs

    def set_goal(self, goal: Dict[str, np.ndarray]):
        pass

    def set_to_goal(self, goal: Dict[str, np.ndarray]):
        pass

    def compute_rewards(self, actions: np.ndarray, obs: np.ndarray):
        return np.zeros(actions.shape[0])

    def get_diagnostics(self, paths, **kwargs):
        return {}

if __name__ == '__main__':
    EXIT_KEY = 'q'
    save_freq = 1
    num_steps_per_key_input = 10000

    env = HardwareRobotEnv(frequency=2, camera_ids=[0, 2], stack_images=False)
    env.reset()

    t = 0
    observations = []
    key_input = None
    while key_input != EXIT_KEY:
        for _ in range(num_steps_per_key_input * save_freq):
            # Take one env step.
            action = env.action_space.sample()
            obs, rew, done, info = env.step(action)

            if t % save_freq == 0:
                #print(f't: {t}')
                # print(obs)
                env.render()
                observations.append(obs)

            t += 1

        key_input = input("Enter q to exit, or any other key to continue.")

    observations = np.stack(observations)
    output_npz = 'output/robot_observations-' + \
        datetime.now().strftime("%Y-%m-%d-%H:%M:%S") + '.npz'
    with open(output_npz, 'wb') as f:
        np.savez(f, observations=observations)
    print(f"Saved to {output_npz}")


text:
package ru.r2cloud.jradio.blocks;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import ru.r2cloud.jradio.ArrayByteInput;

public class HardToSoftTest {

	@Test
	public void testSuccess() throws Exception {
		ArrayByteInput input = new ArrayByteInput(new int[] { 0b1010_0011, 0b0101_1111 });
		HardToSoft block = new HardToSoft(input);
		assertEquals(Byte.MAX_VALUE, block.readByte());
		assertEquals(Byte.MIN_VALUE, block.readByte());
		assertEquals(Byte.MAX_VALUE, block.readByte());
		assertEquals(Byte.MIN_VALUE, block.readByte());
		assertEquals(Byte.MIN_VALUE, block.readByte());
		assertEquals(Byte.MIN_VALUE, block.readByte());
		assertEquals(Byte.MAX_VALUE, block.readByte());
		assertEquals(Byte.MAX_VALUE, block.readByte());

		assertEquals(Byte.MIN_VALUE, block.readByte());
		assertEquals(Byte.MAX_VALUE, block.readByte());
		assertEquals(Byte.MIN_VALUE, block.readByte());
		assertEquals(Byte.MAX_VALUE, block.readByte());
		assertEquals(Byte.MAX_VALUE, block.readByte());
		assertEquals(Byte.MAX_VALUE, block.readByte());
		assertEquals(Byte.MAX_VALUE, block.readByte());
		assertEquals(Byte.MAX_VALUE, block.readByte());
		block.close();
	}

}


text:
"""Utility functions for running the lab tests.

"""

import logging
import os
import subprocess
import shutil
import sys

import runner_constants as const
import util

CHANGE_RESOLUTION_PATH = os.path.join(const.TEST_PATH, 'lab',
                                      'ChangeResolution','Debug',
                                      'changeresolution.exe')

def EnsureWindowsScreenResolution(width, height, bpp):
  """Performs all steps needed to configure system for testing on Windows.

  Args:
    width: new screen resolution width
    height: new screen resolution height
    bpp: new screen resolution bytes per pixel
  Returns:
    True on success.
  """
  if not os.path.exists(CHANGE_RESOLUTION_PATH):
    return False
  command = 'call "%s" %d %d %d' % (CHANGE_RESOLUTION_PATH, width, height, bpp)

  our_process = subprocess.Popen(command,
                                 shell=True,
                                 stdout=None,
                                 stderr=None,
                                 universal_newlines=True)

  our_process.wait()

  return our_process.returncode == 0

def AddPythonPath(path):
  """Add path to PYTHONPATH in environment."""
  try:
    os.environ['PYTHONPATH'] = path + os.pathsep + os.environ['PYTHONPATH']
  except KeyError:
    os.environ['PYTHONPATH'] = path

  # Need to put at front of sys.path so python will try to import modules from
  # path before locations further down the sys.path.
  sys.path = [path] + sys.path

def InstallO3DPlugin():
  """Installs O3D plugin."""

  logging.info('Installing plugin...')
  if util.IsWindows():
    installer_path = os.path.join(const.PRODUCT_DIR_PATH, 'o3d.msi')

    if not os.path.exists(installer_path):
      logging.error('Installer path not found, %s' % installer_path)
      return False

    install_command = 'msiexec.exe /i "%s"' % installer_path
    if util.RunStr(install_command) != 0:
      return False

  elif util.IsMac():
    dmg_path = os.path.join(const.PRODUCT_DIR_PATH, 'o3d.dmg')
    mnt = util.MountDiskImage(dmg_path)
    if mnt is None:
      return False
    (device, volumes_path) = mnt

    installer_path = os.path.join(volumes_path, 'O3D.mpkg')

    if not os.path.exists(installer_path):
      logging.error('Installer path not found, %s' % installer_path)
      util.UnmountDiskImage(device)
      return False

    admin_password = 'g00gl3'
    install_command = ('echo %s | sudo -S /usr/sbin/installer -pkg '
                       '"%s" -target /' % (admin_password, installer_path))

    ret_code = util.RunStr(install_command)
    util.UnmountDiskImage(device)
    if ret_code != 0:
      return False

  else:
    plugin_path = os.path.join(const.PRODUCT_DIR_PATH, 'libnpo3dautoplugin.so')
    plugin_dst_dir = os.path.expanduser('~/.mozilla/plugins')
    try:
      os.makedirs(plugin_dst_dir)
    except os.error:
      pass

    plugin_dst = os.path.join(plugin_dst_dir, 'libnpo3dautoplugin.so')
    shutil.copyfile(plugin_path, plugin_dst)
    return True

  return True

def UninstallO3DPlugin():
  """Uninstalls O3D.

  Returns:
    True, if O3D is no longer installed."""

  if util.IsWindows():
    installer_path = os.path.join(const.PRODUCT_DIR_PATH, 'o3d.msi')
    os.system('msiexec.exe /x "%s" /q' % installer_path)

  # Forcibly remove plugins.
  for path in const.INSTALL_PATHS:
    if os.path.exists(path):
      if util.IsWindows():
        os.remove(path)
      else:
        os.system('echo g00gl3 | sudo -S rm -rf "%s"' % path)

  return not DoesAnO3DPluginExist()

def DoesAnO3DPluginExist():
  for path in const.INSTALL_PATHS:
    if os.path.exists(path):
      return True
  return False


text:
Article 1386-3
----
Est un produit tout bien meuble, même s'il est incorporé dans un immeuble, y
compris les produits du sol, de l'élevage, de la chasse et de la pêche.
L'électricité est considérée comme un produit.


text:
appengine-endpoints-tictactoe-android
=====================================

This application implements a simple client for a Tic Tac Toe game using
Google Cloud Endpoints, App Engine, Java, and Android.

**NOTE:** This sample was written with a Java backend in mind. As a result,
the generated code will differ slightly than that for the [Python Tic Tac
Toe sample][8]. For the most part this will be immaterial to the sample,
but there are a few key differences:
- The generated schema names in the discovery document are different in Python
  than in Java, even though the hold the same data. This will cause the generated
  classes corresponding to the schema to have different names.
- Python supports enums and uses `'WHEN'` and `'TEXT'` for the `order` field in
  queries, while Java simply uses `"1"` and `"2"`, respectively.
- The Python backend stores the current user for authenticated requests, but does
  not return the user in the score insert response or score list response.

## Products
- [App Engine][1]
- [Android][2]

## Language
- [Java][3]

## APIs
- [Google Cloud Endpoints][4]

## Setup Instructions
1. Import the project into Eclipse.
1. Make sure the following files are added to a `libs` directory in your
   project (they come from the google-api-java-client and are not bundled with
   this sample):
    - google-api-client-1.13.2-beta.jar
    - google-api-client-android-1.13.2-beta.jar
    - google-http-client-1.13.1-beta.jar
    - google-http-client-android-1.13.1-beta.jar
    - google-http-client-gson-1.13.1-beta.jar
    - google-oauth-client-1.13.1-beta.jar
    - gson-2.1.jar
    - guava-jdk5-13.0.jar
    - jsr305-1.3.9.jar
   Later versions of these libraries may work, but it's not guaranteed.
1. Make sure you've added [Google Play Services][5] to your development
   environment.
1. Update the value of `DEFAULT_ROOT_URL` in
   `src/com/appspot/api/services/tictactoe/Tictactoe.java` to point to the
   location where you are hosting a Tic Tac Toe backend (based off of the [Java
   backend example][6]).
1. Update the value of `AUDIENCE` in
   `src/com/google/devrel/samples/ttt/ClientCredentials.java`, replacing the
   string "your_web_client_id" with the web application client ID you
   registered in the [APIs Console][7].
1. Run the application.

[1]: https://developers.google.com/appengine
[2]: http://developer.android.com/index.html
[3]: http://java.com/en/
[4]: https://developers.google.com/appengine/docs/java/endpoints/
[5]: https://developer.android.com/google/play-services/setup.html
[6]: https://github.com/GoogleCloudPlatform/appengine-endpoints-tictactoe-java
[7]: https://code.google.com/apis/console
[8]:  https://github.com/GoogleCloudPlatform/appengine-endpoints-tictactoe-python


text:
"""Testing control functionality"""

import unittest

from control.repository import Repository

class RepositoryTest(unittest.TestCase):
    """Tests Repository creation"""

    def test_creation(self):
        """Ensure that minimal options produce a correct Repository object"""
        repository = Repository('ubuntu')
        self.assertTrue(repository.repo == 'ubuntu:latest')
        self.assertTrue(repository.image == 'ubuntu')
        self.assertTrue(repository.get_pull_image_name() == 'ubuntu')
        self.assertTrue(repository.tag == 'latest')
        self.assertTrue(repository.domain is None)
        self.assertTrue(repository.port is None)
        self.assertTrue(repository.registry is None)

    def test_tagging(self):
        """Make sure that tagging an image produces the correct result"""
        repository = Repository('ubuntu', '14.04')
        self.assertTrue(repository.repo == 'ubuntu:14.04')
        self.assertTrue(repository.image == 'ubuntu')
        self.assertTrue(repository.get_pull_image_name() == 'ubuntu')
        self.assertTrue(repository.tag == '14.04')
        self.assertTrue(repository.domain is None)
        self.assertTrue(repository.port is None)
        self.assertTrue(repository.registry is None)

    def test_registry(self):
        """Test a registry running on port 443"""
        repository = Repository('ubuntu', '14.04', 'docker.petrode.com')
        self.assertTrue(repository.repo == 'docker.petrode.com/ubuntu:14.04')
        self.assertTrue(repository.image == 'ubuntu')
        self.assertTrue(repository.get_pull_image_name() == 'docker.petrode.com/ubuntu')
        self.assertTrue(repository.tag == '14.04')
        self.assertTrue(repository.domain == 'docker.petrode.com')
        self.assertTrue(repository.port is None)
        self.assertTrue(repository.registry == 'docker.petrode.com')

    def test_registry_and_port(self):
        """Test a registry running on port 443"""
        repository = Repository('ubuntu', '14.04', 'docker.petrode.com', '5002')
        self.assertTrue(repository.repo == 'docker.petrode.com:5002/ubuntu:14.04')
        self.assertTrue(repository.image == 'ubuntu')
        self.assertTrue(repository.get_pull_image_name() == 'docker.petrode.com:5002/ubuntu')
        self.assertTrue(repository.tag == '14.04')
        self.assertTrue(repository.domain == 'docker.petrode.com')
        self.assertTrue(repository.port == '5002')
        self.assertTrue(repository.registry == 'docker.petrode.com:5002')

class MatcherTest(unittest.TestCase):
    """Test the matcher function that it correctly creates Repositories"""

    def test_matching_only_latest_image(self):
        """Create a repo based on just an image name"""
        repository = Repository.match('ubuntu')
        self.assertTrue(repository.image == 'ubuntu')
        self.assertTrue(repository.tag == 'latest')
        self.assertTrue(repository.domain is None)
        self.assertTrue(repository.port is None)

    def test_matching_image(self):
        """Create a repo based on an image name with a tag"""
        repository = Repository.match('ubuntu:14.04')
        self.assertTrue(repository.image == 'ubuntu')
        self.assertTrue(repository.tag == '14.04')
        self.assertTrue(repository.domain is None)
        self.assertTrue(repository.port is None)

    def test_matching_image_with_domain(self):
        """Create a repo based on an image from a registry"""
        repository = Repository.match('docker.petrode.com/ubuntu:14.04')
        self.assertTrue(repository.image == 'ubuntu')
        self.assertTrue(repository.tag == '14.04')
        self.assertTrue(repository.domain == 'docker.petrode.com')
        self.assertTrue(repository.port is None)

    def test_match_repo_with_registry(self):
        """Create a repo based on an image from a registry running on not 443"""
        repository = Repository.match('docker.petrode.com:5002/ubuntu:14.04')
        self.assertTrue(repository.image == 'ubuntu')
        self.assertTrue(repository.tag == '14.04')
        self.assertTrue(repository.domain == 'docker.petrode.com')
        self.assertTrue(repository.port == '5002')

def suite():
    """Group TestCases together so all the tests run"""
    testsuite = unittest.TestSuite()
    testsuite.addTest(unittest.makeSuite(RepositoryTest))
    testsuite.addTest(unittest.makeSuite(MatcherTest))
    return testsuite

if __name__ == '__main__':
    unittest.TextTestRunner().run(suite())