text:
using base::ASCIIToUTF16;
using base::TimeTicks;
using content::InterstitialPage;
using content::InterstitialPageDelegate;
using content::NavigationController;
using content::NavigationEntry;

namespace {

void LaunchDateAndTimeSettings() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
// The code for each OS is completely separate, in order to avoid bugs like
// https://crbug.com/430877 .
#if defined(OS_ANDROID)
  chrome::android::OpenDateAndTimeSettings();

#elif defined(OS_CHROMEOS)
  std::string sub_page =
      std::string(chrome::kSearchSubPage) + "#" +
      l10n_util::GetStringUTF8(IDS_OPTIONS_SETTINGS_SECTION_TITLE_DATETIME);
  chrome::ShowSettingsSubPageForProfile(ProfileManager::GetActiveUserProfile(),
                                        sub_page);

#elif defined(OS_IOS)
  // iOS does not have a way to launch the date and time settings.
  NOTREACHED();

#elif defined(OS_LINUX)
  struct ClockCommand {
    const char* pathname;
    const char* argument;
  };
  static const ClockCommand kClockCommands[] = {
      // Unity
      {"/usr/bin/unity-control-center", "datetime"},
      // GNOME
      //
      // NOTE: On old Ubuntu, naming control panels doesn't work, so it
      // opens the overview. This will have to be good enough.
      {"/usr/bin/gnome-control-center", "datetime"},
      {"/usr/local/bin/gnome-control-center", "datetime"},
      {"/opt/bin/gnome-control-center", "datetime"},
      // KDE
      {"/usr/bin/kcmshell4", "clock"},
      {"/usr/local/bin/kcmshell4", "clock"},
      {"/opt/bin/kcmshell4", "clock"},
  };

  base::CommandLine command(base::FilePath(""));
  for (const ClockCommand& cmd : kClockCommands) {
    base::FilePath pathname(cmd.pathname);
    if (base::PathExists(pathname)) {
      command.SetProgram(pathname);
      command.AppendArg(cmd.argument);
      break;
    }
  }
  if (command.GetProgram().empty()) {
    // Alas, there is nothing we can do.
    return;
  }

  base::LaunchOptions options;
  options.wait = false;
  options.allow_new_privs = true;
  base::LaunchProcess(command, options);

#elif defined(OS_MACOSX)
  base::CommandLine command(base::FilePath("/usr/bin/open"));
  command.AppendArg("/System/Library/PreferencePanes/DateAndTime.prefPane");

  base::LaunchOptions options;
  options.wait = false;
  base::LaunchProcess(command, options);

#elif defined(OS_WIN)
  base::FilePath path;
  PathService::Get(base::DIR_SYSTEM, &path);
  static const base::char16 kControlPanelExe[] = L"control.exe";
  path = path.Append(base::string16(kControlPanelExe));
  base::CommandLine command(path);
  command.AppendArg(std::string("/name"));
  command.AppendArg(std::string("Microsoft.DateAndTime"));

  base::LaunchOptions options;
  options.wait = false;
  base::LaunchProcess(command, options);

#else
  NOTREACHED();

#endif
  // Don't add code here! (See the comment at the beginning of the function.)
}

}  // namespace

// static
InterstitialPageDelegate::TypeID BadClockBlockingPage::kTypeForTesting =
    &BadClockBlockingPage::kTypeForTesting;

// Note that we always create a navigation entry with SSL errors.
// No error happening loading a sub-resource triggers an interstitial so far.
// Creating an interstitial without showing (e.g. from chrome://interstitials)
// it leaks memory, so don't create it here.
BadClockBlockingPage::BadClockBlockingPage(
    content::WebContents* web_contents,
    int cert_error,
    const net::SSLInfo& ssl_info,
    const GURL& request_url,
    const base::Time& time_triggered,
    const base::Callback<void(bool)>& callback)
    : SecurityInterstitialPage(web_contents, request_url),
      callback_(callback),
      cert_error_(cert_error),
      ssl_info_(ssl_info),
      time_triggered_(time_triggered) {}

bool BadClockBlockingPage::ShouldCreateNewNavigation() const {
  return true;
}

InterstitialPageDelegate::TypeID BadClockBlockingPage::GetTypeForTesting()
    const {
  return BadClockBlockingPage::kTypeForTesting;
}

BadClockBlockingPage::~BadClockBlockingPage() {
  if (!callback_.is_null()) {
    // Deny when the page is closed.
    NotifyDenyCertificate();
  }
}

void BadClockBlockingPage::PopulateInterstitialStrings(
    base::DictionaryValue* load_time_data) {
  CHECK(load_time_data);
  base::string16 url(GetFormattedHostName());

  // Values that are currently still shared with the SSL interstitial.
  load_time_data->SetString("type", "SSL");
  load_time_data->SetString("errorCode", net::ErrorToString(cert_error_));
  load_time_data->SetString(
      "openDetails", l10n_util::GetStringUTF16(IDS_SSL_V2_OPEN_DETAILS_BUTTON));
  load_time_data->SetString(
      "closeDetails",
      l10n_util::GetStringUTF16(IDS_SSL_V2_CLOSE_DETAILS_BUTTON));

  // Strings for the bad clock warning specifically.
  load_time_data->SetBoolean("bad_clock", true);
  load_time_data->SetBoolean("overridable", false);
#if defined(OS_IOS)
  load_time_data->SetBoolean("hide_primary_button", true);
#else
  load_time_data->SetBoolean("hide_primary_button", false);
#endif

  int heading_string =
      SSLErrorClassification::IsUserClockInTheFuture(time_triggered_)
          ? IDS_SSL_V2_CLOCK_AHEAD_HEADING
          : IDS_SSL_V2_CLOCK_BEHIND_HEADING;

  load_time_data->SetString("tabTitle",
                            l10n_util::GetStringUTF16(IDS_SSL_V2_CLOCK_TITLE));
  load_time_data->SetString("heading",
                            l10n_util::GetStringUTF16(heading_string));
  load_time_data->SetString(
      "primaryParagraph",
      l10n_util::GetStringFUTF16(
          IDS_SSL_V2_CLOCK_PRIMARY_PARAGRAPH, url,
          base::TimeFormatFriendlyDateAndTime(time_triggered_)));

  load_time_data->SetString(
      "primaryButtonText",
      l10n_util::GetStringUTF16(IDS_SSL_V2_CLOCK_UPDATE_DATE_AND_TIME));
  load_time_data->SetString(
      "explanationParagraph",
      l10n_util::GetStringUTF16(IDS_SSL_V2_CLOCK_EXPLANATION));

  // The interstitial template expects this string, but we're not using it.
  load_time_data->SetString("finalParagraph", std::string());

  // Set debugging information at the bottom of the warning.
  load_time_data->SetString("subject",
                            ssl_info_.cert->subject().GetDisplayName());
  load_time_data->SetString("issuer",
                            ssl_info_.cert->issuer().GetDisplayName());
  load_time_data->SetString(
      "expirationDate",
      base::TimeFormatShortDate(ssl_info_.cert->valid_expiry()));
  load_time_data->SetString("currentDate",
                            base::TimeFormatShortDate(time_triggered_));
  std::vector<std::string> encoded_chain;
  ssl_info_.cert->GetPEMEncodedChain(&encoded_chain);
  load_time_data->SetString(
      "pem", base::JoinString(encoded_chain, base::StringPiece()));
}

void BadClockBlockingPage::OverrideEntry(NavigationEntry* entry) {
  int cert_id = content::CertStore::GetInstance()->StoreCert(
      ssl_info_.cert.get(), web_contents()->GetRenderProcessHost()->GetID());
  DCHECK(cert_id);

  entry->GetSSL().security_style =
      content::SECURITY_STYLE_AUTHENTICATION_BROKEN;
  entry->GetSSL().cert_id = cert_id;
  entry->GetSSL().cert_status = ssl_info_.cert_status;
  entry->GetSSL().security_bits = ssl_info_.security_bits;
}

// This handles the commands sent from the interstitial JavaScript.
// DO NOT reorder or change this logic without also changing the JavaScript!
void BadClockBlockingPage::CommandReceived(const std::string& command) {
  if (command == "\"pageLoadComplete\"") {
    // content::WaitForRenderFrameReady sends this message when the page
    // load completes. Ignore it.
    return;
  }

  int cmd = 0;
  bool retval = base::StringToInt(command, &cmd);
  DCHECK(retval);
  switch (cmd) {
    case CMD_DONT_PROCEED:
      interstitial_page()->DontProceed();
      break;
    case CMD_DO_REPORT:
      SetReportingPreference(true);
      break;
    case CMD_DONT_REPORT:
      SetReportingPreference(false);
      break;
    case CMD_SHOW_MORE_SECTION:
      break;
    case CMD_OPEN_DATE_SETTINGS:
      content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE,
                                       base::Bind(&LaunchDateAndTimeSettings));
      break;
    case CMD_OPEN_REPORTING_PRIVACY:
      OpenExtendedReportingPrivacyPolicy();
      break;
    case CMD_PROCEED:
    case CMD_OPEN_HELP_CENTER:
    case CMD_RELOAD:
    case CMD_OPEN_DIAGNOSTIC:
      // Not supported for the bad clock interstitial.
      NOTREACHED() << "Unexpected command: " << command;
  }
}

void BadClockBlockingPage::OverrideRendererPrefs(
    content::RendererPreferences* prefs) {
  Profile* profile =
      Profile::FromBrowserContext(web_contents()->GetBrowserContext());
  renderer_preferences_util::UpdateFromSystemSettings(prefs, profile,
                                                      web_contents());
}

void BadClockBlockingPage::OnDontProceed() {
  NotifyDenyCertificate();
}

void BadClockBlockingPage::NotifyDenyCertificate() {
  // It's possible that callback_ may not exist if the user clicks "Proceed"
  // followed by pressing the back button before the interstitial is hidden.
  // In that case the certificate will still be treated as allowed.
  if (callback_.is_null())
    return;

  base::ResetAndReturn(&callback_).Run(false);
}


text:
require 'json'

# pry is not required but nice to have
begin
  require 'pry'
rescue LoadError
end

#
#
# Workaround log spam in older versions of ChefDK.
#
# https://github.com/berkshelf/berkshelf/pull/1668/
# https://github.com/intridea/hashie/issues/394
#
begin
  require 'hashie'
  require 'hashie/logger'
  Hashie.logger = Logger.new(nil)
rescue LoadError
end

require 'chef'
require 'chef-vault'
require 'ohai'
require 'ridley'
Ridley::Logging.logger.level = Logger.const_get 'ERROR'

module BACH

  #
  # Methods to get data about a BACH cluster
  #
  module ClusterData

    #
    # Methods which only run on machines with Chef credentials
    # or on the Chef Server
    #
    module ChefNode

      def chef_environment
        ridley.environment.find(chef_environment_name)
      end

      #
      # Returns the password for the 'ubuntu' account in plaintext.
      # The method name comes from the confusing name of the data bag item.
      #
      def cobbler_root_password
        # Among other things, Ridley will set up Chef::Config for ChefVault.
        unless ridley.data_bag.find('os/cobbler_keys')
          raise('No os/cobbler_keys data bag item found. ' \
                'Is this cluster using chef-vault?')
        end

        ChefVault::Item.load('os', 'cobbler')['root-password']
      end

      def refresh_vault_keys(entry = nil)
        reindex_and_wait(entry) if entry

        #
        # Vault data bags can be identified by distinctively named data
        # bag items ending in "_keys".
        #
        # Here we build a list of all the vaults by looking for "_keys"
        # and ignoring any data bags that contain no vault-items.
        #
        vault_list = ridley.data_bag.all.map do |db|
          vault_items = db.item.all.map do |dbi|
            dbi.chef_id.gsub(/_keys$/, '') if dbi.chef_id.end_with?('_keys')
          end.compact

          { db.name => vault_items } if vault_items.any?
        end.compact.reduce({}, :merge)

        vault_list.each do |vault, item_list|
          item_list.each do |item|
            begin
              vv = ChefVault::Item.load(vault, item)
              vv.refresh
              vv.save
              puts "Refreshed chef-vault item #{vault}/#{item}"
            rescue
              $stderr.puts "Failed to refresh chef-vault item #{vault}/#{item}!"
            end
          end
        end
      end

      def reindex_chef_server
        cc = Mixlib::ShellOut.new('sudo', 'chef-server-ctl', 'reindex')
        result = cc.run_command
        cc.error!
        result
      end

      def reindex_and_wait(entry)
        180.times do |i|
          if ridley.search(:node, "name:#{entry[:fqdn]}").any?
            puts "Found #{entry[:fqdn]} in search index"
            return
          else
            if i % 60 == 0
              puts "Waiting for #{entry[:fqdn]} to appear in Chef index..."
            # the #times method counts up, not down, so i == 179 on the 180th
            # iteration.
            elsif i == 179
              raise "Did not find indexed node for #{entry[:fqdn]} " \
                "after #{timeout} secs! Reindex by hand or wait again.\n" \
                'WARNING: Reindex is a dangerous cluster operation. Refer '\
                'to runbooks for details.'
            end
            sleep 1
          end
        end

        raise "Did not find #{entry[:fqdn]} in Chef index after 180 seconds!"
      end

      def ridley
        @ridley ||= Dir.chdir(repo_dir) { Ridley.from_chef_config }
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.matsemann.simulation;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.backends.lwjgl.LwjglCanvas;
import com.matsemann.ea.ipc.Task;
import com.matsemann.ea.reference.ReferenceManager;
import com.matsemann.ea.reference.SolutionReducer;
import org.moeaframework.core.NondominatedPopulation;
import org.moeaframework.core.Solution;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.text.NumberFormat;
import java.util.Arrays;

/**
 * Should only be used for showing Wheel solutions
 */
public class SimulationViewer extends JFrame {

    NondominatedPopulation population, reducedPopulation, referenceSet, reducedReferenceSet;

    JPanel mainPanel, buttonsPanel;
    JTextField toReduceField;
    JTable objectivesTable;
    JScrollPane tableScroll;
    LwjglCanvas lwjglCanvas;

    int toReduce = 20;
    SolutionReducer reducer = new SolutionReducer();
    ObjectivesModel objectivesModel;
    private final WheelRenderer wheelRenderer;

    public SimulationViewer(NondominatedPopulation population, NondominatedPopulation referenceSet) {
        this.population = population;
        this.referenceSet = referenceSet;

        JButton populationButton = new JButton("Population");
        populationButton.addActionListener(e -> updateTable("pop"));

        JButton reducedPopulationButton = new JButton("Reduced pop");
        reducedPopulationButton.addActionListener(e -> updateTable("reducedpop"));

        JButton referenceButton = new JButton("Reference set");
        referenceButton.addActionListener(e -> updateTable("ref"));

        JButton reducedReferenceButton = new JButton("Reduced ref");
        reducedReferenceButton.addActionListener(e -> updateTable("reducedref"));

        toReduceField = new JTextField(toReduce + "");
        toReduceField.setPreferredSize(new Dimension(50, toReduceField.getPreferredSize().height));

        mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBorder(BorderFactory.createEtchedBorder(Color.ORANGE, Color.CYAN));
        GridBagConstraints c = new GridBagConstraints();

        buttonsPanel = new JPanel();
        buttonsPanel.add(populationButton);
        buttonsPanel.add(reducedPopulationButton);
        buttonsPanel.add(referenceButton);
        buttonsPanel.add(reducedReferenceButton);
        buttonsPanel.add(toReduceField);

        String[] columnNames = {"Nr", "Dst", "rotZ", "rot", "spokes"};

        objectivesModel = new ObjectivesModel();
        objectivesModel.setColumnNames(columnNames);
        objectivesTable = new JTable(objectivesModel);
        objectivesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        objectivesTable.setAutoCreateRowSorter(true);
        objectivesTable.setDefaultRenderer(Double.class, new DoubleCellRenderer());

        objectivesTable.getSelectionModel().addListSelectionListener(x -> {
            int selectedRow = objectivesTable.getSelectedRow();

            if (selectedRow >= 0)  {
                int solutionSelected = objectivesTable.convertRowIndexToModel(selectedRow);
                showSolution(solutionSelected);
            }
        });

        tableScroll = new JScrollPane(objectivesTable);

        LwjglApplicationConfiguration configuration = new LwjglApplicationConfiguration();
        configuration.width = 1200;
        configuration.height = 1000;
        configuration.samples = 4;
//        configuration.forceExit = false;

        wheelRenderer = new WheelRenderer();
        lwjglCanvas = new LwjglCanvas(wheelRenderer, configuration);
        lwjglCanvas.getCanvas().setPreferredSize(new Dimension(configuration.width, configuration.height));

        mainPanel.add(buttonsPanel, c);

        c.gridy = 1;
        c.weighty = 1;
        c.fill = GridBagConstraints.BOTH;
        mainPanel.add(tableScroll, c);

        c.gridy = 0;
        c.gridx = 1;
        c.weightx = 1;
        c.weighty = 1;
        c.gridheight = 2;
        c.fill = GridBagConstraints.BOTH;
        mainPanel.add(lwjglCanvas.getCanvas(), c);

        if (this.population != null) {
            updateTable("pop");
        } else {
            updateTable("ref");
        }

        getContentPane().add(mainPanel);
        setVisible(true);
        pack();
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    @Override
    public void dispose() {
//        wheelRenderer.dispose();
//        lwjglCanvas.stop();
//        lwjglCanvas.postRunnable(() -> {
//            wheelRenderer.dispose();
//            lwjglCanvas.stop();
//        });
//        Gdx.app.postRunnable(lwjglCanvas::stop);
//        SwingUtilities.invokeLater(lwjglCanvas::stop);

//        lwjglCanvas.postRunnable(() -> {
//            LwjglCanvas.lwjglCanvas.listener.pause();
//            LwjglCanvas.lwjglCanvas.listener.dispose();
//        });
        lwjglCanvas.stop();
        super.dispose();
    }

    private void showSolution(int solutionSelected) {
        Solution solution = objectivesModel.getByIndex(solutionSelected);
        Task task = (Task) solution.getAttribute("task");
        if (task != null) {
            wheelRenderer.setAngles(task.angles);
        }
    }

    private void updateTable(String toShow) {
        int reduced = Integer.parseInt(toReduceField.getText());

        if (toShow.equals("pop")) {
            addDataToTable(population);
        } else if (toShow.equals("reducedpop")) {
            if (reducedPopulation == null || toReduce != reduced) {
                reducedPopulation = reducer.reduce(population, reduced);
            }
            addDataToTable(reducedPopulation);
        } else if (toShow.equals("ref")) {
            addDataToTable(referenceSet);
        } else if (toShow.equals("reducedref")) {
            if (reducedReferenceSet == null || toReduce != reduced) {
                reducedReferenceSet = reducer.reduce(referenceSet, reduced);
            }
            addDataToTable(reducedReferenceSet);
        }

        toReduce = reduced;
    }

    private void addDataToTable(NondominatedPopulation population) {
        objectivesModel.setSolutions(population);
    }

    public class ObjectivesModel extends AbstractTableModel {

        private NondominatedPopulation population;
        private String[] columnNames;

        public void setColumnNames(String[] columnNames) {
            this.columnNames = columnNames;
            fireTableStructureChanged();
        }

        public void setSolutions(NondominatedPopulation population) {
            this.population = population;
            fireTableDataChanged();
        }

        public Solution getByIndex(int i) {
            return population.get(i);
        }

        @Override
        public int getRowCount() {
            return population != null ? population.size() : 0;
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (columnIndex == 0) {
                return (double) rowIndex;
            }

            int obj = columnIndex - 1;

            if (obj >= population.get(rowIndex).getNumberOfObjectives()) {
                return -1.0;
            }

            return population.get(rowIndex).getObjective(obj);
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return Double.class;
        }

    }

    public class DoubleCellRenderer extends DefaultTableCellRenderer {

        NumberFormat format;

        public DoubleCellRenderer() {
            super();
            format = NumberFormat.getInstance();
            format.setMinimumFractionDigits(0);
            format.setMaximumFractionDigits(15);
        }

        @Override
        protected void setValue(Object value) {
            double v = (double) value;
            String format1 = format.format(v);
            setText(format1);
        }
    }

    public static void main(String[] args) {
        NondominatedPopulation dtlz2_2 = new ReferenceManager("test").getReferenceSet();

        SwingUtilities.invokeLater(() -> new SimulationViewer(dtlz2_2, null));
    }
}


text:
package ecs

import (
	"database/sql"
	"errors"
	"fmt"
	"io"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/client"
	"github.com/aws/aws-sdk-go/service/ecs"
	"github.com/remind101/empire/pkg/arn"
	. "github.com/remind101/empire/pkg/bytesize"
	"github.com/remind101/empire/pkg/ecsutil"
	"github.com/remind101/empire/scheduler"
	"github.com/remind101/empire/scheduler/ecs/lb"
	"golang.org/x/net/context"
)

// For HTTP/HTTPS/TCP services, we allocate an ELB and map it's instance port to
// the container port. This is the port that processes within the container
// should bind to. Tihs value is also exposed to the container through the PORT
// environment variable.
const ContainerPort = 8080

var DefaultDelimiter = "-"

type lbManager interface {
	lb.Manager
	RemoveCNAMEs(context.Context, map[string]string) error
}

// Scheduler is an implementation of the ServiceManager interface that
// is backed by Amazon ECS.
type Scheduler struct {
	cluster          string
	serviceRole      string
	ecs              *ecsutil.Client
	logConfiguration *ecs.LogConfiguration
	lb               lbManager
}

// Config holds configuration for generating a new ECS backed Scheduler
// implementation.
type Config struct {
	// The ECS cluster to create services and task definitions in.
	Cluster string

	// The IAM role to use for ECS services with ELBs attached.
	ServiceRole string

	// VPC controls what subnets to attach to ELBs that are created.
	VPC string

	// The hosted zone id to create internal DNS records in
	ZoneID string

	// The ID of the security group to assign to internal load balancers.
	InternalSecurityGroupID string

	// The ID of the security group to assign to external load balancers.
	ExternalSecurityGroupID string

	// The Subnet IDs to assign when creating internal load balancers.
	InternalSubnetIDs []string

	// The Subnet IDs to assign when creating external load balancers.
	ExternalSubnetIDs []string

	// AWS configuration.
	AWS client.ConfigProvider

	// Log configuraton for ECS tasks
	LogConfiguration *ecs.LogConfiguration
}

func newScheduler(config Config) *Scheduler {
	c := ecsutil.NewClient(config.AWS)

	return &Scheduler{
		cluster:          config.Cluster,
		serviceRole:      config.ServiceRole,
		ecs:              c,
		logConfiguration: config.LogConfiguration,
	}
}

// NewScheduler returns a new Scheduler implementation that:
//
// * Creates services with ECS.
func NewScheduler(config Config) (*Scheduler, error) {
	return newScheduler(config), nil
}

// NewLoadBalancedScheduler returns a new Scheduler instance that:
//
// * Creates services with ECS.
// * Creates internal or external ELBs for ECS services.
// * Creates a CNAME record in route53 under the internal TLD.
// * Allocates ports from the ports table.
func NewLoadBalancedScheduler(db *sql.DB, config Config) (*Scheduler, error) {
	lb, err := newLBManager(db, config)
	if err != nil {
		return nil, err
	}

	s := newScheduler(config)
	s.lb = lb
	return s, nil
}

func newLBManager(db *sql.DB, config Config) (lbManager, error) {
	if err := validateLoadBalancedConfig(config); err != nil {
		return nil, err
	}

	// Create the ELB Manager
	elb := lb.NewELBManager(config.AWS)
	elb.Ports = lb.NewDBPortAllocator(db)
	elb.InternalSecurityGroupID = config.InternalSecurityGroupID
	elb.ExternalSecurityGroupID = config.ExternalSecurityGroupID
	elb.InternalSubnetIDs = config.InternalSubnetIDs
	elb.ExternalSubnetIDs = config.ExternalSubnetIDs

	// Compose the LB Manager
	var lbm lb.Manager = elb

	n := lb.NewRoute53Nameserver(config.AWS)
	n.ZoneID = config.ZoneID

	lbm = lb.WithLogging(lbm)

	return lb.WithCNAME(lbm, n), nil
}

func validateLoadBalancedConfig(c Config) error {
	r := func(n string) error {
		return errors.New(fmt.Sprintf("%s is required", n))
	}

	if c.Cluster == "" {
		return r("Cluster")
	}
	if c.ServiceRole == "" {
		return r("ServiceRole")
	}
	if c.ZoneID == "" {
		return r("ZoneID")
	}
	if c.InternalSecurityGroupID == "" {
		return r("InternalSecurityGroupID")
	}
	if c.ExternalSecurityGroupID == "" {
		return r("ExternalSecurityGroupID")
	}
	if len(c.InternalSubnetIDs) == 0 {
		return r("InternalSubnetIDs")
	}
	if len(c.ExternalSubnetIDs) == 0 {
		return r("ExternalSubnetIDs")
	}

	return nil
}

// This is purely used to migrate to the new CloudFormation scheduler. Simply
// deletes the existing CNAME record for the app, so that the CloudFormation
// stack can create it.
func (m *Scheduler) RemoveCNAMEs(ctx context.Context, appID string) error {
	tags := map[string]string{
		"AppID": appID,
	}

	return m.lb.RemoveCNAMEs(ctx, tags)
}

// Submit will create an ECS service for each individual process in the App. New
// task definitions will be created based on the information with each process.
//
// If the app was previously submitted with different process than what are
// provided, any process types that don't exist in the new release will be
// removed from ECS. For example, if you previously submitted an app with a
// `web` and `worker` process, then submit an app with the `web` process, the
// ECS service for the old `worker` process will be removed.
func (m *Scheduler) Submit(ctx context.Context, app *scheduler.App, ss scheduler.StatusStream) error {
	processes, err := m.Processes(ctx, app.ID)
	if err != nil {
		return err
	}

	for _, p := range app.Processes {
		if err := m.CreateProcess(ctx, app, p); err != nil {
			return err
		}
	}

	toRemove := diffProcessTypes(processes, app.Processes)
	for _, p := range toRemove {
		if err := m.RemoveProcess(ctx, app.ID, p); err != nil {
			return err
		}
	}
	return nil
}

// Restart restarts all of the processes for the app.
func (m *Scheduler) Restart(ctx context.Context, app *scheduler.App, ss scheduler.StatusStream) error {
	return m.Submit(ctx, app, ss)
}

// Remove removes all of the AWS resources for this app.
func (m *Scheduler) Remove(ctx context.Context, appID string) error {
	return m.RemoveWithOptions(ctx, appID, RemoveOptions{})
}

// RemoveOptions are options that can be passed to RemoveWithOptions.
type RemoveOptions struct {
	// If set to true, DNS records will not be removed.
	NoDNS bool
}

// RemoveWithOptions removes the application.
func (m *Scheduler) RemoveWithOptions(ctx context.Context, appID string, opts RemoveOptions) error {
	processes, err := m.Processes(ctx, appID)
	if err != nil {
		return err
	}

	for t, _ := range processTypes(processes) {
		if err := m.RemoveProcess(ctx, appID, t); err != nil {
			return err
		}
	}

	return m.removeLoadBalancers(ctx, appID, opts.NoDNS)
}

// Instances returns all instances that are currently running, pending or
// draining.
func (m *Scheduler) Instances(ctx context.Context, appID string) ([]*scheduler.Instance, error) {
	var instances []*scheduler.Instance

	tasks, err := m.describeAppTasks(ctx, appID)
	if err != nil {
		return instances, err
	}

	taskDefinitions := make(map[string]*ecs.TaskDefinition)
	for _, t := range tasks {
		k := *t.TaskDefinitionArn

		if _, ok := taskDefinitions[k]; !ok {
			resp, err := m.ecs.DescribeTaskDefinition(ctx, &ecs.DescribeTaskDefinitionInput{
				TaskDefinition: t.TaskDefinitionArn,
			})
			if err != nil {
				return instances, err
			}
			taskDefinitions[k] = resp.TaskDefinition
		}
	}

	for _, t := range tasks {
		taskDefinition := taskDefinitions[*t.TaskDefinitionArn]

		id, err := arn.ResourceID(*t.TaskArn)
		if err != nil {
			return instances, err
		}

		p, err := taskDefinitionToProcess(taskDefinition)
		if err != nil {
			return instances, err
		}

		state := aws.StringValue(t.LastStatus)
		var updatedAt time.Time
		switch state {
		case "PENDING":
			updatedAt = *t.CreatedAt
		case "RUNNING":
			updatedAt = *t.StartedAt
		case "STOPPED":
			updatedAt = *t.StoppedAt
		}

		instances = append(instances, &scheduler.Instance{
			Process:   p,
			State:     state,
			ID:        id,
			UpdatedAt: updatedAt,
		})
	}

	return instances, nil
}

func (m *Scheduler) describeAppTasks(ctx context.Context, appID string) ([]*ecs.Task, error) {
	resp, err := m.ecs.ListAppTasks(ctx, appID, &ecs.ListTasksInput{
		Cluster: aws.String(m.cluster),
	})
	if err != nil {
		return nil, err
	}

	if len(resp.TaskArns) == 0 {
		return []*ecs.Task{}, nil
	}

	tasks, err := m.ecs.DescribeTasks(ctx, &ecs.DescribeTasksInput{
		Cluster: aws.String(m.cluster),
		Tasks:   resp.TaskArns,
	})
	return tasks.Tasks, err
}

func (m *Scheduler) Stop(ctx context.Context, instanceID string) error {
	_, err := m.ecs.StopTask(ctx, &ecs.StopTaskInput{
		Cluster: aws.String(m.cluster),
		Task:    aws.String(instanceID),
	})
	return err
}

// CreateProcess creates an ECS service for the process.
func (m *Scheduler) CreateProcess(ctx context.Context, app *scheduler.App, p *scheduler.Process) error {
	if p.Schedule != nil {
		return errors.New("%s: scheduled processes are not supported by this backend")
	}

	loadBalancer, err := m.loadBalancer(ctx, app, p)
	if err != nil {
		return err
	}

	if _, err := m.createTaskDefinition(ctx, app, p, loadBalancer); err != nil {
		return err
	}

	_, err = m.updateCreateService(ctx, app, p, loadBalancer)
	return err
}

func (m *Scheduler) Run(ctx context.Context, app *scheduler.App, process *scheduler.Process, in io.Reader, out io.Writer) error {
	if out != nil {
		return errors.New("running an attached process is not implemented by the ECS manager.")
	}

	td, err := m.createTaskDefinition(ctx, app, process, nil)
	if err != nil {
		return err
	}

	_, err = m.ecs.RunTask(ctx, &ecs.RunTaskInput{
		TaskDefinition: td.TaskDefinitionArn,
		Cluster:        aws.String(m.cluster),
		Count:          aws.Int64(1),
		StartedBy:      aws.String(app.ID),
	})
	return err
}

// createTaskDefinition creates a Task Definition in ECS for the service.
func (m *Scheduler) createTaskDefinition(ctx context.Context, app *scheduler.App, process *scheduler.Process, loadBalancer *lb.LoadBalancer) (*ecs.TaskDefinition, error) {
	taskDef, err := m.taskDefinitionInput(app, process, loadBalancer)
	if err != nil {
		return nil, err
	}

	resp, err := m.ecs.RegisterAppTaskDefinition(ctx, app.ID, taskDef)
	return resp.TaskDefinition, err
}

func (m *Scheduler) taskDefinitionInput(app *scheduler.App, p *scheduler.Process, loadBalancer *lb.LoadBalancer) (*ecs.RegisterTaskDefinitionInput, error) {
	// ecs.ContainerDefinition{Command} is expecting a []*string
	var command []*string
	for _, s := range p.Command {
		ss := s
		command = append(command, &ss)
	}

	var environment []*ecs.KeyValuePair
	for k, v := range scheduler.Env(app, p) {
		environment = append(environment, &ecs.KeyValuePair{
			Name:  aws.String(k),
			Value: aws.String(v),
		})
	}

	// If there's a load balancer attached, generate the port mappings and
	// expose the container port to the process via the PORT environment
	// variable.
	var ports []*ecs.PortMapping
	if loadBalancer != nil {
		ports = append(ports, &ecs.PortMapping{
			HostPort:      aws.Int64(loadBalancer.InstancePort),
			ContainerPort: aws.Int64(ContainerPort),
		})
		environment = append(environment, &ecs.KeyValuePair{
			Name:  aws.String("PORT"),
			Value: aws.String(fmt.Sprintf("%d", ContainerPort)),
		})
	}

	labels := make(map[string]*string)
	for k, v := range scheduler.Labels(app, p) {
		labels[k] = aws.String(v)
	}

	var ulimits []*ecs.Ulimit
	if p.Nproc != 0 {
		ulimits = []*ecs.Ulimit{
			&ecs.Ulimit{
				Name:      aws.String("nproc"),
				SoftLimit: aws.Int64(int64(p.Nproc)),
				HardLimit: aws.Int64(int64(p.Nproc)),
			},
		}
	}

	return &ecs.RegisterTaskDefinitionInput{
		Family: aws.String(p.Type),
		ContainerDefinitions: []*ecs.ContainerDefinition{
			&ecs.ContainerDefinition{
				Name:             aws.String(p.Type),
				Cpu:              aws.Int64(int64(p.CPUShares)),
				Command:          command,
				Image:            aws.String(p.Image.String()),
				Essential:        aws.Bool(true),
				Memory:           aws.Int64(int64(p.MemoryLimit / MB)),
				Environment:      environment,
				LogConfiguration: m.logConfiguration,
				PortMappings:     ports,
				DockerLabels:     labels,
				Ulimits:          ulimits,
			},
		},
	}, nil
}

// createService creates a Service in ECS for the service.
func (m *Scheduler) createService(ctx context.Context, app *scheduler.App, p *scheduler.Process, loadBalancer *lb.LoadBalancer) (*ecs.Service, error) {
	var role *string
	var loadBalancers []*ecs.LoadBalancer

	if loadBalancer != nil {
		loadBalancers = []*ecs.LoadBalancer{
			{
				ContainerName:    aws.String(p.Type),
				ContainerPort:    aws.Int64(ContainerPort),
				LoadBalancerName: aws.String(loadBalancer.Name),
			},
		}
		role = aws.String(m.serviceRole)
	}

	resp, err := m.ecs.CreateAppService(ctx, app.ID, &ecs.CreateServiceInput{
		Cluster:        aws.String(m.cluster),
		DesiredCount:   aws.Int64(int64(p.Instances)),
		ServiceName:    aws.String(p.Type),
		TaskDefinition: aws.String(p.Type),
		LoadBalancers:  loadBalancers,
		Role:           role,
	})
	return resp.Service, err
}

// updateService updates an existing Service in ECS.
func (m *Scheduler) updateService(ctx context.Context, app *scheduler.App, p *scheduler.Process) (*ecs.Service, error) {
	_, err := m.loadBalancer(ctx, app, p)
	if err != nil {
		return nil, err
	}

	resp, err := m.ecs.UpdateAppService(ctx, app.ID, &ecs.UpdateServiceInput{
		Cluster:        aws.String(m.cluster),
		DesiredCount:   aws.Int64(int64(p.Instances)),
		Service:        aws.String(p.Type),
		TaskDefinition: aws.String(p.Type),
	})

	// If the service does not exist, return nil.
	if noService(err) {
		return nil, nil
	}

	return resp.Service, err
}

// updateCreateService will perform an upsert for the service in ECS.
func (m *Scheduler) updateCreateService(ctx context.Context, app *scheduler.App, p *scheduler.Process, loadBalancer *lb.LoadBalancer) (*ecs.Service, error) {
	s, err := m.updateService(ctx, app, p)
	if err != nil {
		return nil, err
	}

	if s != nil {
		return s, nil
	}

	return m.createService(ctx, app, p, loadBalancer)
}

// loadBalancer creates (or updates) a a load balancer for the given process, if
// the process is exposed. It returns the name of the load balancer.
func (m *Scheduler) loadBalancer(ctx context.Context, app *scheduler.App, p *scheduler.Process) (*lb.LoadBalancer, error) {
	// No exposure, no load balancer.
	if p.Exposure == nil {
		return nil, nil
	}

	// Attempt to find an existing load balancer for this app.
	l, err := m.findLoadBalancer(ctx, app.ID, p.Type)
	if err != nil {
		return nil, err
	}

	// If the load balancer doesn't match the exposure that we
	// want, we'll return an error. Users should manually destroy
	// the app and re-create it with the proper exposure.
	if l != nil {
		var opts *lb.UpdateLoadBalancerOpts
		opts, err = updateOpts(p, l)
		if err != nil {
			return nil, err
		}

		if opts != nil {
			if err = m.lb.UpdateLoadBalancer(ctx, *opts); err != nil {
				return nil, err
			}
		}
	}

	// If this app doesn't have a load balancer yet, create one.
	if l == nil {
		tags := lbTags(app.ID, p.Type)

		// Add "App" tag so that a CNAME can be created.
		tags[lb.AppTag] = app.Name

		opts := lb.CreateLoadBalancerOpts{
			External: p.Exposure.External,
			Tags:     tags,
		}

		if e, ok := p.Exposure.Type.(*scheduler.HTTPSExposure); ok {
			opts.SSLCert = e.Cert
		}

		l, err = m.lb.CreateLoadBalancer(ctx, opts)
		if err != nil {
			return nil, err
		}
	}

	return l, nil
}

func (m *Scheduler) removeLoadBalancers(ctx context.Context, app string, noDNS bool) error {
	tags := map[string]string{
		"AppID": app,
	}

	lbs, err := m.lb.LoadBalancers(ctx, tags)
	if err != nil {
		return err
	}

	for _, l := range lbs {
		if noDNS {
			// Go around the CNAMEManager and destroy the load
			// balancer directly.
			if err := m.lb.(*lb.CNAMEManager).Manager.DestroyLoadBalancer(ctx, l); err != nil {
				return err
			}
		} else {
			if err := m.lb.DestroyLoadBalancer(ctx, l); err != nil {
				return err
			}
		}
	}

	return nil
}

// findLoadBalancer attempts to find an existing load balancer for the app.
func (m *Scheduler) findLoadBalancer(ctx context.Context, app string, process string) (*lb.LoadBalancer, error) {
	lbs, err := m.lb.LoadBalancers(ctx, lbTags(app, process))
	if err != nil || len(lbs) == 0 {
		return nil, err
	}

	return lbs[0], nil
}

func (m *Scheduler) Processes(ctx context.Context, appID string) ([]*scheduler.Process, error) {
	var processes []*scheduler.Process

	list, err := m.ecs.ListAppServices(ctx, appID, &ecs.ListServicesInput{
		Cluster: aws.String(m.cluster),
	})
	if err != nil {
		return processes, err
	}

	if len(list.ServiceArns) == 0 {
		return processes, nil
	}

	desc, err := m.ecs.DescribeServices(ctx, &ecs.DescribeServicesInput{
		Cluster:  aws.String(m.cluster),
		Services: list.ServiceArns,
	})
	if err != nil {
		return processes, err
	}

	for _, s := range desc.Services {
		resp, err := m.ecs.DescribeTaskDefinition(ctx, &ecs.DescribeTaskDefinitionInput{
			TaskDefinition: s.TaskDefinition,
		})
		if err != nil {
			return processes, err
		}

		p, err := taskDefinitionToProcess(resp.TaskDefinition)
		if err != nil {
			return processes, err
		}

		processes = append(processes, p)
	}

	return processes, nil
}

func (m *Scheduler) RemoveProcess(ctx context.Context, app string, process string) error {
	if err := m.scale(ctx, app, process, 0); noService(err) {
		return nil
	} else if err != nil {
		return err
	}

	_, err := m.ecs.DeleteAppService(ctx, app, &ecs.DeleteServiceInput{
		Cluster: aws.String(m.cluster),
		Service: aws.String(process),
	})
	if noService(err) {
		return nil
	}

	return err
}

// Scale scales an ECS service to the desired number of instances.
func (m *Scheduler) scale(ctx context.Context, app string, process string, instances uint) error {
	_, err := m.ecs.UpdateAppService(ctx, app, &ecs.UpdateServiceInput{
		Cluster:      aws.String(m.cluster),
		DesiredCount: aws.Int64(int64(instances)),
		Service:      aws.String(process),
	})
	return err
}

func noService(err error) bool {
	if err, ok := err.(awserr.Error); ok {
		if err.Message() == "Service was not ACTIVE." {
			return true
		}

		// Wat
		if err.Message() == "Could not find returned type com.amazon.madison.cmb#CMServiceNotActiveException in model" {
			return true
		}
		if err.Message() == "Could not find returned type com.amazon.madison.cmb#CMServiceNotFoundException in model" {
			return true
		}

		if err.Message() == "Service not found." {
			return true
		}
	}

	return false
}

// taskDefinitionToProcess takes an ECS Task Definition and converts it to a
// Process.
func taskDefinitionToProcess(td *ecs.TaskDefinition) (*scheduler.Process, error) {
	// If this task definition has no container definitions, then something
	// funky is up.
	if len(td.ContainerDefinitions) == 0 {
		return nil, errors.New("task definition had no container definitions")
	}

	container := td.ContainerDefinitions[0]

	var command []string
	for _, s := range container.Command {
		command = append(command, *s)
	}

	env := make(map[string]string)
	for _, kvp := range container.Environment {
		if kvp != nil {
			env[aws.StringValue(kvp.Name)] = aws.StringValue(kvp.Value)
		}
	}

	return &scheduler.Process{
		Type:        aws.StringValue(container.Name),
		Command:     command,
		Env:         env,
		CPUShares:   uint(*container.Cpu),
		MemoryLimit: uint(*container.Memory) * MB,
		Nproc:       uint(softLimit(container.Ulimits, "nproc")),
	}, nil
}

func softLimit(ulimits []*ecs.Ulimit, name string) int64 {
	if ulimits == nil {
		return 0
	}

	for _, u := range ulimits {
		if *u.Name == name {
			return *u.SoftLimit
		}
	}

	return 0
}

func diffProcessTypes(old, new []*scheduler.Process) []string {
	var types []string

	om := processTypes(old)
	nm := processTypes(new)

	for t, _ := range om {
		if _, ok := nm[t]; !ok {
			types = append(types, t)
		}
	}

	return types
}

func processTypes(processes []*scheduler.Process) map[string]struct{} {
	m := make(map[string]struct{})

	for _, p := range processes {
		m[p.Type] = struct{}{}
	}

	return m
}

// lbTags returns the tags that should be attached to the load balancer so that
// we can find it later.
func lbTags(app string, process string) map[string]string {
	return map[string]string{
		"AppID":       app,
		"ProcessType": process,
	}
}

// LoadBalancerExposureError is returned when the exposure of the process in the data store does not match the exposure of the ELB
type LoadBalancerExposureError struct {
	proc *scheduler.Process
	lb   *lb.LoadBalancer
}

func (e *LoadBalancerExposureError) Error() string {
	return fmt.Sprintf("Process %s is %s, but load balancer is %s. An update would require me to delete the load balancer.", e.proc.Type, external(e.proc.Exposure.External), external(e.lb.External))
}

type external bool

func (e external) String() string {
	if e {
		return "public"
	}

	return "private"
}

// canUpdate checks if the load balancer is suitable for the process.
func canUpdate(p *scheduler.Process, lb *lb.LoadBalancer) error {
	if p.Exposure.External && !lb.External {
		return &LoadBalancerExposureError{p, lb}
	}

	if !p.Exposure.External && lb.External {
		return &LoadBalancerExposureError{p, lb}
	}

	return nil
}

func updateOpts(p *scheduler.Process, b *lb.LoadBalancer) (*lb.UpdateLoadBalancerOpts, error) {
	// This load balancer can't be updated to make it work for the process.
	// Return an error.
	if err := canUpdate(p, b); err != nil {
		return nil, err
	}

	opts := lb.UpdateLoadBalancerOpts{
		Name: b.Name,
	}

	// Requires an update to the Cert.
	if e, ok := p.Exposure.Type.(*scheduler.HTTPSExposure); ok {
		if e.Cert != b.SSLCert {
			opts.SSLCert = &e.Cert
		}
	}

	// Load balancer doesn't require an update.
	if opts.SSLCert == nil {
		return nil, nil
	}

	return &opts, nil
}


text:
local base64 = require "util.encodings".base64.encode;
local sha1 = require "util.hashes".sha1;

local t_insert, t_sort, t_concat = table.insert, table.sort, table.concat;
local ipairs = ipairs;

local _ENV = nil;

local function calculate_hash(disco_info)
	local identities, features, extensions = {}, {}, {};
	for _, tag in ipairs(disco_info) do
		if tag.name == "identity" then
			t_insert(identities, (tag.attr.category or "").."\0"..(tag.attr.type or "").."\0"..(tag.attr["xml:lang"] or "").."\0"..(tag.attr.name or ""));
		elseif tag.name == "feature" then
			t_insert(features, tag.attr.var or "");
		elseif tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then
			local form = {};
			local FORM_TYPE;
			for _, field in ipairs(tag.tags) do
				if field.name == "field" and field.attr.var then
					local values = {};
					for _, val in ipairs(field.tags) do
						val = #val.tags == 0 and val:get_text();
						if val then t_insert(values, val); end
					end
					t_sort(values);
					if field.attr.var == "FORM_TYPE" then
						FORM_TYPE = values[1];
					elseif #values > 0 then
						t_insert(form, field.attr.var.."\0"..t_concat(values, "<"));
					else
						t_insert(form, field.attr.var);
					end
				end
			end
			t_sort(form);
			form = t_concat(form, "<");
			if FORM_TYPE then form = FORM_TYPE.."\0"..form; end
			t_insert(extensions, form);
		end
	end
	t_sort(identities);
	t_sort(features);
	t_sort(extensions);
	if #identities > 0 then identities = t_concat(identities, "<"):gsub("%z", "/").."<"; else identities = ""; end
	if #features > 0 then features = t_concat(features, "<").."<"; else features = ""; end
	if #extensions > 0 then extensions = t_concat(extensions, "<"):gsub("%z", "<").."<"; else extensions = ""; end
	local S = identities..features..extensions;
	local ver = base64(sha1(S));
	return ver, S;
end

return {
	calculate_hash = calculate_hash;
};


text:
import Redis = require('ioredis');
const redis = new Redis();

redis.set('foo', 'bar');
redis.get('foo', (err, result) => {
    console.log(result);
});

// Or using a promise if the last argument isn't a function
redis.get('foo').then((result: any) => {
    console.log(result);
});

// Arguments to commands are flattened, so the following are the same:
redis.sadd('set', 1, 3, 5, 7);
redis.sadd('set', [1, 3, 5, 7]);

// All arguments are passed directly to the redis server:
redis.set('key', '100');
redis.set('key', '100', 'XX');
redis.set('key', '100', 'PX', 10);
redis.set('key', '100', 'EX', 10, 'NX');
redis.set('key', '100', 'NX', 'EX', 10);
redis.set('key', '100', ['EX', 10, 'NX']);
redis.setBuffer('key', '100', 'NX', 'EX', 10);

redis.set('key', '100', (err, data) => {});
redis.set('key', '100', 'XX', (err, data) => {});
redis.set('key', '100', 'PX', 10, (err, data) => {});
redis.set('key', '100', 'EX', 10, 'NX', (err, data) => {});
redis.set('key', '100', ['EX', 10, 'NX'], (err, data) => {});
redis.setBuffer('key', '100', 'NX', 'EX', 10, (err, data) => {});

redis.exists('foo').then(result => result * 1);
redis.exists('foo', (err, data) => data * 1);

const listData = ['foo', 'bar', 'baz'];
listData.forEach(value => {
    redis.rpushBuffer('bufferlist', Buffer.from(value));
});
redis.lpopBuffer('bufferlist', (err, result) => {
    if (result.toString() !== listData[0]) {
        console.log(result.toString());
    }
});
redis.lrangeBuffer('bufferlist', 0, listData.length - 2, (err, results) => {
    results.forEach((value, index) => {
        if (value.toString() !== listData[index + 1]) {
            console.log(value.toString());
        }
    });
});

new Redis(); // Connect to 127.0.0.1:6379
new Redis(6380); // 127.0.0.1:6380
new Redis(6379, '192.168.1.1'); // 192.168.1.1:6379
new Redis('/tmp/redis.sock');
new Redis({
    port: 6379, // Redis port
    host: '127.0.0.1', // Redis host
    family: 4, // 4 (IPv4) or 6 (IPv6)
    password: 'auth',
    db: 0,
    retryStrategy() {
        return false;
    },
    showFriendlyErrorStack: true,
    tls: {
        servername: 'tlsservername',
    },
});

const pub = new Redis();
redis.subscribe('news', 'music', (err: any, count: any) => {
    // Now we are subscribed to both the 'news' and 'music' channels.
    // `count` represents the number of channels we are currently subscribed to.

    pub.publish('news', 'Hello world!');
    pub.publishBuffer('music', Buffer.from('Hello again!'));
});

redis.on('message', (channel: any, message: any) => {
    // Receive message Hello world! from channel news
    // Receive message Hello again! from channel music
    console.log('Receive message %s from channel %s', message, channel);
});

// There's also an event called 'messageBuffer', which is the same as 'message' except
// it returns buffers instead of strings.
redis.on('messageBuffer', (channel: any, message: any) => {
    // Both `channel` and `message` are buffers.
});

const pipeline = redis.pipeline();
pipeline.set('foo', 'bar');
pipeline.del('cc');
pipeline.hset('hash', 'foo', 4);
pipeline.hget('hash', 'foo');
pipeline.hsetBuffer('hash', 'fooBuffer', 4);
pipeline.hgetBuffer('hash', 'fooBuffer');
pipeline.exec((err, results) => {
    // `err` is always null, and `results` is an array of responses
    // corresponding to the sequence of queued commands.
    // Each response follows the format `[err, result]`.
});

// You can even chain the commands:
redis
    .pipeline()
    .set('foo', 'bar')
    .del('cc')
    .exec((err, results) => {});

// `exec` also returns a Promise:
const promise = redis.pipeline().set('foo', 'bar').get('foo').exec();
promise.then(result => {
    // result === [[null, 'OK'], [null, 'bar']]
});

redis
    .pipeline()
    .set('foo', 'bar')
    .get('foo', (err, result) => {
        // result === 'bar'
    })
    .exec((err, result) => {
        // result[1][1] === 'bar'
    });

redis
    .pipeline([
        ['set', 'foo', 'bar'],
        ['get', 'foo'],
    ])
    .exec(() => {
        /* ... */
    });

Redis.Command.setArgumentTransformer('set', args => {
    return args;
});

Redis.Command.setReplyTransformer('get', (result: any) => {
    return result;
});

// multi
redis
    .multi()
    .set('foo', 'bar')
    .set('foo', 'baz')
    .get('foo', (err, result) => {
        // result === 'QUEUED'
    })
    .exec((err, results) => {
        // results = [[null, 'OK'], [null, 'OK'], [null, 'baz']]
    });

redis
    .multi([
        ['set', 'foo', 'bar'],
        ['get', 'foo'],
    ])
    .exec((err, results) => {
        // results = [[null, 'OK'], [null, 'bar']]
    });

redis.Promise.onPossiblyUnhandledRejection(error => {});

const keys = ['foo', 'bar'];
redis.mget(...keys);

new Redis.Cluster(['localhost']);

new Redis.Cluster([6379]);

new Redis.Cluster([
    {
        host: 'localhost',
    },
]);

new Redis.Cluster([
    {
        port: 6379,
    },
]);

new Redis.Cluster([
    {
        host: 'localhost',
        port: 6379,
    },
]);

// ClusterRetryStrategy can return non-numbers to stop retrying
new Redis.Cluster([], {
    clusterRetryStrategy: (times: number) => null,
});

new Redis.Cluster([], {
    clusterRetryStrategy: (times: number) => 1,
});

redis.zaddBuffer('foo', 1, Buffer.from('bar')).then(() => {
    // sorted set 'foo' now has score 'foo1' containing barBuffer
});


text:
This project provides a demo of a very simple github dashboard. It consists of a web server written in Go that accesses Github's RESTFul API which is documented here:

	https://developer.github.com/v3/

This project was prepared as a simple proof of concept. The goal is to demonstrate the feasibility to automate access to Github repositories. It currently allows one to perform simple web based operations to create and delete repositories and to display the current list of repositories for a demo account:

	https://github.com/g-snoop

Many companies are considering or implementing automate access to github. Hopeful, overtime, we can develop this project to either serve as a useful reference on how to automate access to Github or even potentially evolve into a usably production strength free platform.

### Live Demo

You can access a live demo running on an AWS t2.micro server:

	 http://35.165.161.246/

### Installation

```
git clone https://github.com/MarkGisi/g-snoop.git
```

You will need the following despondencies:

```
	go get "github.com/google/go-github/github"
	go get "github.com/gorilla/mux"
	go get "golang.org/x/oauth2"
```

 Execute the build in the main directory:

```
go build
```

You may want to set the port to something other then 80 which is the default in the following config file:

```
g-snoop_config.json
```

Then let it rip:

```
./g-snoop
```

and you will see the follow:

```
Configuration:
-----------------------------------------------
github account   	=  g-snoop
github url      	=  https://github.com/g-snoop
token           	=  57651ab68ac4acd3fce820b6179dddcc19a6e74d
http port       	=  80
debug on          	=  true
verbose on        	= true
config  reload      =  true
running server on port: 80 ...

```

### Feedback & Contributing

You can contact me at mark_gisi@yahoo.com


text:
require_relative 'worker'

module DelayedJobCelluloid
  class Manager
    include Celluloid
    include Logger

    trap_exit :worker_died

    attr_reader :ready
    attr_reader :busy

    def initialize(options={}, worker_count)
      @options = options
      @worker_count = worker_count || 1
      @done_callback = nil

      @in_progress = {}
      @threads = {}
      @done = false
      @busy = []
      @ready = @worker_count.times.map do
        w = Worker.new_link(options, current_actor)
        w.proxy_id = w.object_id
        w
      end
    end

    def start
      @ready.each_with_index do |worker, index|
        worker.name = "delayed_job.#{index}"
        DelayedJobCelluloid.logger.info "Starting worker #{worker.name}"
        worker.async.start
      end
    end

    def stop(timeout)
      @done = true

      info "Shutting down #{@ready.size} idle workers"
      @ready.each do |worker|
        worker.terminate if worker.alive?
      end
      @ready.clear

      return after(0) { signal(:shutdown) } if @busy.empty?
      hard_shutdown_in timeout
    end

    def work(worker)
      @ready.delete(worker)
      @busy << worker
    end

    def worker_done(worker)
      @busy.delete(worker)
      if stopped?
        worker.terminate if worker.alive?
        signal(:shutdown) if @busy.empty?
      else
        @ready << worker if worker.alive?
      end
    end

    def worker_died(worker, reason)
      debug "#{worker.inspect} died because of #{reason}" unless reason.nil?
      @busy.delete(worker)
      unless stopped?
        worker = Worker.new_link(@options, current_actor)
        worker.name = "restarted"
        @ready << worker
        worker.async.start
      else
        signal(:shutdown) if @busy.empty?
      end
    end

    def stopped?
      @done
    end

    def real_thread(proxy_id, thr)
      @threads[proxy_id] = thr
    end

    def hard_shutdown_in(delay)
      info "Pausing up to #{delay} seconds to allow workers to finish..."

      after(delay) do
        # We've reached the timeout and we still have busy workers.
        # They must die but their messages shall live on.
        info "Still waiting for #{@busy.size} busy workers"

        debug "Terminating #{@busy.size} busy worker threads"
        @busy.each do |worker|
          if worker.alive? && t = @threads.delete(worker.object_id)
            t.raise Shutdown
          end
        end

        after(0) { signal(:shutdown) }
      end
    end

  end
end


text:
using System.Linq;
using System.Xml.Serialization;
using EmptyKeys.Strategy.Core;
using EmptyKeys.Strategy.Environment;
using EmptyKeys.Strategy.Units;

namespace EmptyKeys.Strategy.AI.Components.ActionsUnit
{
    /// <summary>
    /// Implements unit action for behavior. This action finds Planet for colonization.
    /// The result is stored in EnvironmentTarget of UnitBehaviorContext.
    /// </summary>
    /// <seealso cref="EmptyKeys.Strategy.AI.Components.BehaviorComponentBase" />
    public class FindPlanetToColonize : BehaviorComponentBase
    {
        /// <summary>
        /// Gets or sets the distance system utility coefficient.
        /// </summary>
        /// <value>
        /// The distance system utility coefficient.
        /// </value>
        [XmlAttribute]
        public float DistanceSystemUtilityCoefficient { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="FindPlanetToColonize"/> class.
        /// </summary>
        public FindPlanetToColonize()
            : base()
        {
        }

        /// <summary>
        /// Executes behavior with given context
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override BehaviorReturnCode Behave(IBehaviorContext context)
        {
            UnitBehaviorContext unitContext = context as UnitBehaviorContext;
            if (unitContext == null)
            {
                returnCode = BehaviorReturnCode.Failure;
                return returnCode;
            }

            BaseEnvironment envi = unitContext.Unit.Environment;
            if (envi == null)
            {
                returnCode = BehaviorReturnCode.Failure;
                return returnCode;
            }

            float maxPlanetUtility = float.MinValue;
            Planet selectedPlanet = null;
            var player = unitContext.Unit.Owner;
            foreach (var galaxyBodyKey in player.ExploredEnvironments)
            {
                HexElement elem = null;
                if (!player.GameSession.Galaxy.EnvironmentMap.TryGetValue(galaxyBodyKey, out elem))
                {
                    continue;
                }

                // TODO: rogue planets colonization
                StarSystem system = elem as StarSystem;
                if (system == null || system.NumberOfPlanets == 0 || !system.HasHighestInfluence(player))
                {
                    continue;
                }

                int systemDistance = HexMap.Distance(envi, system);
                if (envi is Galaxy)
                {
                    systemDistance = HexMap.Distance(unitContext.Unit, system);
                }

                foreach (var planet in system.Planets)
                {
                    if (planet == null || planet.Owner != null || !player.CanColonizePlanetType(planet.PlanetType))
                    {
                        continue;
                    }

                    var existingColonyShip = player.Units.FirstOrDefault(u => u.Item.UnitConfig.Actions.HasFlag(UnitActions.Colonize) &&
                                                                              u != unitContext.Unit &&
                                                                              u.BehaviorContext.EnvironmentTarget == planet);
                    if (existingColonyShip != null)
                    {
                        continue;
                    }

                    float planetUtility = GetPlanetUtility(player, planet);

                    planetUtility -= systemDistance * DistanceSystemUtilityCoefficient;

                    if (envi == system)
                    {
                        planetUtility -= HexMap.Distance(unitContext.Unit, planet);
                    }

                    var isHomePlanet = player.GameSession.Players.FirstOrDefault(p => p.HomePlanet == planet);
                    if (isHomePlanet != null)
                    {
                        selectedPlanet = planet;
                        break;
                    }

                    if (maxPlanetUtility > planetUtility)
                    {
                        continue;
                    }

                    maxPlanetUtility = planetUtility;
                    selectedPlanet = planet;
                }
            }

            if (selectedPlanet != null)
            {
                unitContext.EnvironmentTarget = selectedPlanet;
                returnCode = BehaviorReturnCode.Success;
                return returnCode;
            }

            returnCode = BehaviorReturnCode.Failure;
            return returnCode;
        }

        /// <summary>
        /// Gets the planet utility.
        /// </summary>
        /// <param name="player">The player.</param>
        /// <param name="planet">The planet.</param>
        /// <returns></returns>
        public static float GetPlanetUtility(Player player, Planet planet)
        {
            bool planetScanned = player.ScannedStarSystemBodies.Contains(planet.GlobalKey);
            float rareResourcesValue = 0;
            float planetUtility = 0;
            float planetPreference = player.Race.PlanetTypePreferences[(int)planet.PlanetType] / 100f;
            if (planetScanned)
            {
                foreach (var rareResource in planet.RareResources)
                {
                    rareResourcesValue += rareResource.Quantity;
                }

                rareResourcesValue = rareResourcesValue / 1000;
                planetUtility = (planet.AvailResources * planetPreference) / planet.Mass + planet.AvailEnergy / planet.Mass + rareResourcesValue + planet.MaxSlotsCount;
            }
            else
            {
                planetUtility = planet.MaxSlotsCount;
            }

            return planetUtility;
        }
    }
}


text:
namespace DallEX.io.API.MarketTools
{
    public interface IOrder
    {
        double PricePerCoin { get; }

        double AmountQuote { get; }
        double AmountBase { get; }
    }
}


text:
package denominator;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import dagger.ObjectGraph;
import denominator.mock.MockProvider;

import static org.assertj.core.api.Assertions.assertThat;

public class ProvidersTest {

  @Rule
  public final ExpectedException thrown = ExpectedException.none();

  @Test
  public void niceMessageWhenProviderNotFound() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("provider foo not in set of configured providers: [mock]");

    Providers.getByName("foo");
  }

  @Test
  public void illegalArgumentWhenMissingModule() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("NoModuleProvider should have a static inner class named Module");

    Providers.instantiateModule(new NoModuleProvider());
  }

  @Test
  public void illegalArgumentWhenModuleCtorHasArgs() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Module has a no-args constructor");

    Providers.instantiateModule(new WrongCtorModuleProvider());
  }

  @Test
  public void provideReturnsSameInstance() {
    FooProvider provider = new FooProvider();
    DNSApiManager
        mgr =
        ObjectGraph.create(Providers.provide(provider), new FooProvider.Module()).get(
            DNSApiManager.class);

    assertThat(mgr.provider()).isSameAs(provider);
  }

  @Test
  public void withUrlOverrides() {
    Provider provider = Providers.withUrl(new URLProvider(), "http://bar");
    assertThat(provider.url()).isEqualTo("http://bar");
  }

  @Test
  public void withUrlWhenProviderMissingStringCtor() {
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("FooProvider does not have a String parameter constructor");

    Providers.withUrl(new FooProvider(), "http://bar");
  }

  @Test
  public void anonymousProviderPermitted() {
    FooProvider provider = new FooProvider() {
      @Override
      public String name() {
        return "bar";
      }

      @Override
      public String url() {
        return "http://bar";
      }
    };
    DNSApiManager
        mgr =
        ObjectGraph.create(Providers.provide(provider), new FooProvider.Module()).get(
            DNSApiManager.class);
    assertThat(mgr.provider().name()).isEqualTo("bar");
    assertThat(provider.url()).isEqualTo("http://bar");
  }

  static class NoModuleProvider extends BasicProvider {

  }

  static class WrongCtorModuleProvider extends BasicProvider {

    @dagger.Module(injects = DNSApiManager.class, includes = MockProvider.Module.class, complete = false)
    static class Module {

      Module(String name) {
      }
    }
  }

  static class FooProvider extends BasicProvider {

    @dagger.Module(injects = DNSApiManager.class, includes = MockProvider.Module.class, complete = false)
    static class Module {

    }
  }

  static class URLProvider extends BasicProvider {

    private final String url;

    public URLProvider() {
      this(null);
    }

    public URLProvider(String url) {
      this.url = url == null || url.isEmpty() ? "http://foo" : url;
    }

    @Override
    public String url() {
      return url;
    }

    @dagger.Module(injects = DNSApiManager.class, includes = MockProvider.Module.class, complete = false)
    static class Module {

    }
  }
}


text:
package cherry.foundation.type.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistrar;
import org.springframework.format.FormatterRegistry;

import cherry.foundation.type.SecureBigDecimal;
import cherry.foundation.type.SecureBigInteger;
import cherry.foundation.type.SecureInteger;
import cherry.foundation.type.SecureLong;
import cherry.foundation.type.SecureString;

public class SecureTypeSqlConverterRegistrar implements FormatterRegistrar {

	@Override
	public void registerFormatters(FormatterRegistry registry) {
		registry.addConverter(new SecureStringConverter());
		registry.addConverter(new SecureIntegerConverter());
		registry.addConverter(new SecureLongConverter());
		registry.addConverter(new SecureBigIntegerConverter());
		registry.addConverter(new SecureBigDecimalConverter());
	}

	static class SecureStringConverter implements
			Converter<String, SecureString> {
		@Override
		public SecureString convert(String source) {
			return SecureString.cryptoValueOf(source);
		}
	}

	static class SecureIntegerConverter implements
			Converter<String, SecureInteger> {
		@Override
		public SecureInteger convert(String source) {
			return SecureInteger.cryptoValueOf(source);
		}
	}

	static class SecureLongConverter implements Converter<String, SecureLong> {
		@Override
		public SecureLong convert(String source) {
			return SecureLong.cryptoValueOf(source);
		}
	}

	static class SecureBigIntegerConverter implements
			Converter<String, SecureBigInteger> {
		@Override
		public SecureBigInteger convert(String source) {
			return SecureBigInteger.cryptoValueOf(source);
		}
	}

	static class SecureBigDecimalConverter implements
			Converter<String, SecureBigDecimal> {
		@Override
		public SecureBigDecimal convert(String source) {
			return SecureBigDecimal.cryptoValueOf(source);
		}
	}

}


text:
namespace blink {

CSSTransformComponent* CSSTransformComponent::fromCSSValue(const CSSValue& value)
{
    const CSSFunctionValue& functionValue = toCSSFunctionValue(value);
    switch (functionValue.functionType()) {
    case CSSValueMatrix:
    case CSSValueMatrix3d:
        return CSSMatrixTransformComponent::fromCSSValue(functionValue);
    case CSSValuePerspective:
        return CSSPerspective::fromCSSValue(functionValue);
    case CSSValueRotate:
    case CSSValueRotateX:
    case CSSValueRotateY:
    case CSSValueRotateZ:
    case CSSValueRotate3d:
        return CSSRotation::fromCSSValue(functionValue);
    case CSSValueScale:
    case CSSValueScaleX:
    case CSSValueScaleY:
    case CSSValueScaleZ:
    case CSSValueScale3d:
        return CSSScale::fromCSSValue(functionValue);
    case CSSValueSkew:
    case CSSValueSkewX:
    case CSSValueSkewY:
        return CSSSkew::fromCSSValue(functionValue);
    case CSSValueTranslate:
    case CSSValueTranslateX:
    case CSSValueTranslateY:
    case CSSValueTranslateZ:
    case CSSValueTranslate3d:
        return CSSTranslation::fromCSSValue(functionValue);
    default:
        return nullptr;
    }
}

} // namespace blink


text:
package org.radeox.test.macro;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.radeox.EngineManager;

public class ApiMacroTest extends MacroTestSupport
{
	public ApiMacroTest(String name)
	{
		super(name);
	}

	public static Test suite()
	{
		return new TestSuite(ApiMacroTest.class);
	}

	public void testApi()
	{
		String result = EngineManager.getInstance().render(
				"{api:java.lang.object}", context);
		assertEquals(
				"java.lang.object",
				result);
	}

	public void testRuby()
	{
		String result = EngineManager.getInstance().render("{api:String@Ruby}",
				context);
		assertEquals(
				"Ruby namespace is used",
				"String",
				result);
	}

}


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.6">
  <compounddef id="structboost_1_1geometry_1_1strategy_1_1within_1_1winding__check__touch_3_01_point_00_01_calculate9f52b8a0d2744ce64bb2f274fded74d" kind="struct" prot="public">
    <compoundname>boost::geometry::strategy::within::winding_check_touch< Point, CalculationType, cartesian_tag ></compoundname>
    <includes local="no">point_in_poly_winding.hpp</includes>
    <templateparamlist>
      <param>
        <type>typename Point</type>
      </param>
      <param>
        <type>typename CalculationType</type>
      </param>
    </templateparamlist>
      <sectiondef kind="public-type">
      <memberdef kind="typedef" id="structboost_1_1geometry_1_1strategy_1_1within_1_1winding__check__touch_3_01_point_00_01_calculate9f52b8a0d2744ce64bb2f274fded74d_1a62352d8bad4244d0d02d60752cad6ac9" prot="public" static="no">
        <type>CalculationType</type>
        <definition>typedef CalculationType boost::geometry::strategy::within::winding_check_touch< Point, CalculationType, cartesian_tag >::calc_t</definition>
        <argsstring></argsstring>
        <name>calc_t</name>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/ubuntu/boost/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp" line="221" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp" bodystart="221" bodyend="-1"/>
      </memberdef>
      </sectiondef>
      <sectiondef kind="public-static-func">
      <memberdef kind="function" id="structboost_1_1geometry_1_1strategy_1_1within_1_1winding__check__touch_3_01_point_00_01_calculate9f52b8a0d2744ce64bb2f274fded74d_1a9e6fabb63cd24ed36a81ccebb0b18d98" prot="public" static="yes" const="no" explicit="no" inline="yes" virt="non-virtual">
        <templateparamlist>
          <param>
            <type>typename PointOfSegment</type>
          </param>
          <param>
            <type>typename State</type>
          </param>
        </templateparamlist>
        <type>bool</type>
        <definition>static bool boost::geometry::strategy::within::winding_check_touch< Point, CalculationType, cartesian_tag >::apply</definition>
        <argsstring>(Point const &point, PointOfSegment const &seg1, PointOfSegment const &seg2, State &state, bool &eq1, bool &eq2)</argsstring>
        <name>apply</name>
        <param>
          <type>Point const &</type>
          <declname>point</declname>
        </param>
        <param>
          <type>PointOfSegment const &</type>
          <declname>seg1</declname>
        </param>
        <param>
          <type>PointOfSegment const &</type>
          <declname>seg2</declname>
        </param>
        <param>
          <type>State &</type>
          <declname>state</declname>
        </param>
        <param>
          <type>bool &</type>
          <declname>eq1</declname>
        </param>
        <param>
          <type>bool &</type>
          <declname>eq2</declname>
        </param>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/ubuntu/boost/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp" line="224" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp" bodystart="224" bodyend="252"/>
      </memberdef>
      </sectiondef>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <location file="/home/ubuntu/boost/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp" line="220" column="1" bodyfile="/home/ubuntu/boost/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp" bodystart="219" bodyend="253"/>
    <listofallmembers>
      <member refid="structboost_1_1geometry_1_1strategy_1_1within_1_1winding__check__touch_3_01_point_00_01_calculate9f52b8a0d2744ce64bb2f274fded74d_1a9e6fabb63cd24ed36a81ccebb0b18d98" prot="public" virt="non-virtual"><scope>boost::geometry::strategy::within::winding_check_touch< Point, CalculationType, cartesian_tag ></scope><name>apply</name></member>
      <member refid="structboost_1_1geometry_1_1strategy_1_1within_1_1winding__check__touch_3_01_point_00_01_calculate9f52b8a0d2744ce64bb2f274fded74d_1a62352d8bad4244d0d02d60752cad6ac9" prot="public" virt="non-virtual"><scope>boost::geometry::strategy::within::winding_check_touch< Point, CalculationType, cartesian_tag ></scope><name>calc_t</name></member>
    </listofallmembers>
  </compounddef>
</doxygen>


text:
import os
import time
import h5py
import torch
import torch.nn as nn
import torch.optim as optim
from device import device
import argparse
from doom_instance import *
from aac_lstm import BaseModelLSTM

def data_generator(args, screens, variables, labels, episodes):
    # remove short episodes
    episode_min_size = args.episode_size*args.skiprate
    episodes = episodes[episodes[:, 1]-episodes[:, 0] > episode_min_size]
    episodes_num = len(episodes)
    #
    batch_size = args.batch_size
    step_idx = episodes[:, 0].copy() + np.random.randint(args.skiprate, size=episodes_num)
    step_screens = np.ndarray(shape=(batch_size, *screens.shape[1:]), dtype=np.float32)
    step_variables = np.ndarray(shape=(batch_size, *variables.shape[1:]), dtype=np.float32)
    step_labels = np.ndarray(shape=(batch_size,), dtype=np.int)
    step_terminals = np.ones(shape=(batch_size, 1), dtype=np.float32)
    # select episodes for the initial batch
    batch_episodes = np.random.randint(episodes_num, size=batch_size)
    while True:
        for i in range(batch_size):
            idx = batch_episodes[i]
            step_screens[i, :] = screens[step_idx[idx]] / 127.5 - 1.0
            step_variables[i, :] = variables[step_idx[idx]] / 100
            step_labels[i] = labels[step_idx[idx]]
            step_idx[idx] += args.skiprate
            if step_idx[idx] > episodes[idx][1]:
                step_idx[idx] = episodes[idx][0] + np.random.randint(args.skiprate)
                step_terminals[i] = 0
                # reached terminal state, select a new episode
                batch_episodes[i] = np.random.randint(episodes_num)
            else:
                step_terminals[i] = 1

        yield torch.from_numpy(step_screens), \
              torch.from_numpy(step_variables), \
              torch.from_numpy(step_labels), \
              torch.from_numpy(step_terminals)

def train(args):

    data_file = h5py.File(args.h5_path, 'r')
    screens = data_file['screens']
    variables = data_file['variables']
    labels = data_file['action_labels']
    print('Dataset size =', len(screens))
    action_sets = data_file['action_sets'][:]
    episodes = data_file['episodes'][:]
    input_shape = screens[0].shape
    train_generator = data_generator(args, screens, variables, labels, episodes)

    model = BaseModelLSTM(input_shape[0], len(action_sets), variables.shape[1]).to(device)

    #source_model = torch.load('imitation_model_lstm_bn0.pth')
    #model.load_state_dict(source_model.state_dict())
    #del source_model

    criterion = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=5e-4)
    optimizer.zero_grad()
    running_loss = 0
    running_accuracy = 0
    batch_time = time.time()
    cp = 0

    for batch, (screens, variables, labels, terminals) in enumerate(train_generator):
        screens, variables, labels = screens.to(device), variables.to(device), labels.to(device)
        outputs = model(screens, variables)
        loss = criterion(outputs, labels)
        model.set_terminal(terminals)

        running_loss += loss.item()
        _, pred = outputs.max(1)
        accuracy = (pred == labels).float().mean()
        running_accuracy += accuracy

        if batch % args.episode_size == args.episode_size - 1:
            loss.backward()
            optimizer.step()
            model.reset()
            optimizer.zero_grad()

            running_loss /= args.episode_size
            running_accuracy /= args.episode_size

            print(
                '[{:d}] loss: {:.3f}, accuracy: {:.3f}, time: {:.6f}'.format(
                    batch + 1, running_loss, running_accuracy, time.time()-batch_time
                )
            )
            running_loss = 0
            running_accuracy = 0
            batch_time = time.time()

        if batch % args.checkpoint_rate == args.checkpoint_rate - 1:
            cp += 1
            torch.save(model, args.checkpoint_file)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Imitation Model Trainer')
    parser.add_argument('--batch_size', type=int, default=100, help='number of game instances running in parallel')
    parser.add_argument('--load', default=None, help='path to model file')
    parser.add_argument('--h5_path', default=os.path.expanduser('~') + '/test/datasets/vizdoom/cig_map01/flat.h5',
                        help='hd5 file path')

    parser.add_argument('--skiprate', type=int, default=4, help='number of skipped frames')
    parser.add_argument('--frame_num', type=int, default=1, help='number of frames per input')
    parser.add_argument('--checkpoint_file', default=None, help='check point file name')
    parser.add_argument('--checkpoint_rate', type=int, default=5000, help='number of batches per checkpoit')
    parser.add_argument('--episode_size', type=int, default=20, help='episode length')

    args = parser.parse_args()

    train(args)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 446 (1898)

#### Original name
Peziza subhirta Schwein.

### Remarks
null


text:
/**
 * @URL https://github.com/csetea/magpieJS
 * @license MIT
 */

/*

				item

				item auto

				item unit 1/4 offset 1/4

*/

// DONE
// [*] horizontal
// [*] offset
// [*] vertical
// TODO
// [?] end
//TODO align -> m-align? 'align' is already defined/reserved in dom

define([ 'magpie/log!magpie/dom/float/grid', 'module', 'magpie/util/config', 'magpie/dom/mediaQueries'//
         ,'css!./dom-grid'],
function(log, module, config, mediaQueries) {

	//@Polyfill
	if (!String.prototype.startsWith) {
		  Object.defineProperty(String.prototype, 'startsWith', {
		    enumerable: false,
		    configurable: false,
		    writable: false,
		    value: function(searchString, position) {
		      position = position || 0;
		      return this.lastIndexOf(searchString, position) === position;
		    }
		  });
		}

	/*jshint -W004 */
	var config = config(module, {
		ths : [ 5, 24 ]
	});
	// sort grid ths config
	config.ths = config.ths.sort(function(a, b) {
		return a.size - b.size;
	});
	var maxThs = config.ths[config.ths.length - 1];
	var thsMap = {};
	for (var i = 1; i <= maxThs; i++) {
		for ( var thsIndex in config.ths) {
			var ths = config.ths[thsIndex];
			if (ths % i === 0) {
				thsMap[i] = i;
			}
		}
	}

	var widthThsMap = {
			'100' : [ '1' ]
		};
	for ( var ths in thsMap) {
		for (var i = 1; i <= ths; i++) {
			var width = (i / ths * 100).toFixed(4) % 100;
			if (width === 0) {
				width = 100;
			}
			var listForWidth = widthThsMap[width];
			if (!listForWidth) {
				listForWidth = [];
				widthThsMap[width] = listForWidth;
			}
			listForWidth.push(i + '/' + ths);
		}
	}

	var widthThsList = [];
	for ( var width in widthThsMap) {
		widthThsList.push({
			width : width,
			thsList : widthThsMap[width]
		});
	}
	widthThsList = widthThsList.sort(function(a, b) {
		return a.width - b.width;
	});

	//
	// fill attribute ths map
	//
	var attributeNameSet = {};
	var attributes = [ 'unit','offset' ];
	// TODO push, poll and offset?
	// or push + offset
	// or push + poll
	// var attributes = [ 'unit', 'push', 'poll', 'offset' ];
	for (var i = 0; i < attributes.length; i++) {
		attributeNameSet[attributes[i]] = {};
	}
	var attributeScreenMap = {};
	mediaQueries.screens.each(function(screen) {
		for (var i = 0; i < attributes.length; i++) {
			attributeNameSet[attributes[i] + '-' + screen.name] = {};
			attributeScreenMap[attributes[i] + '-' + screen.name] = screen;
		}
	});

	//
	//
	for ( var width in widthThsMap) {
		var thsList = widthThsMap[width];
		for ( var unit in attributeNameSet) {
			for ( var thsIndex in thsList) {
				var ths = thsList[thsIndex];
				attributeNameSet[unit][ths] = ths;
			}
		}
	}

	//TODO common code base until this point with magpie/html5/widget/grid ???

	//
	// generate css
	//
	function cssPropertiesFor(attribute, percentageValue, isVertical) {
		if (/unit.*/.test(attribute)) {
			return '\n{' + //
			 			'flex-basis:' + percentageValue + ';' +//
			 		'}\n';
//			if (isVertical) {
//				return '\n{' //
//						+ 'height:' + percentageValue + ';'//
//						+ '}\n';
//			} else {
//				return '\n{' //
//				// + 'min-width:' + percentageValue + ';' //
//						+ 'width:' + percentageValue + ';' //
//						// + 'max-width:' + percentageValue + ';' //
////						 + 'flex:' + percentageValue + ';' // //for new
//						// browsers
//						// + 'height:' + percentageValue + ';'//
//						+ '}\n';
//			}
		} else if (/offset.*/.test(attribute)) {
			return '\n{' + //
// 				'margin-left:' + percentageValue + ';' +//
 				'margin-left:' + percentageValue + ';' +//
 			'}\n';
		} else if (/push.*/.test(attribute)) {
			// TODO
			// if(isVertical){
			// return '\n{' //
			// // + 'margin-top:' + percentageValue + ';' //
			// + '}\n';
			// }else{
			return '\n{' + //
			// + 'display: '
					// + 'top:' + percentageValue + ';' //

					// + 'margin-top:' + percentageValue + ';' //
					// + 'margin-left:' + percentageValue + ';' //
					 '}\n';
			// }
		} else if (/poll.*/.test(attribute)) {
			// TODO
			return '\n{' + //
					 '}\n';
		}
	}
	function cssSelectorListForThsList(attribute, thsList, isVertical) {
		var cssSelectorList = [];
		for ( var thsListIndex in thsList) {
			var ths = thsList[thsListIndex];

			var cssSelector = //
				'[m-grid]'+(isVertical ? '[vertical]' : '') + '>[' + attribute + '="' + ths + '"]';
			cssSelectorList.push(cssSelector);
		}
		return cssSelectorList;
	}

	var css = '/*Magpie magpie/dom/grid core*/';

	for ( var attribute in attributeNameSet) {
		var screen = attributeScreenMap[attribute];
		var cssForUnit = '\n';
		for ( var widthThsListIndex in widthThsList) {
			var widthThs = widthThsList[widthThsListIndex];
			var isVertical = false;
			var percentageValue = widthThs.width + "%";
			cssForUnit += cssSelectorListForThsList(attribute,
					widthThs.thsList, isVertical) + //
					cssPropertiesFor(attribute, percentageValue, isVertical);
			//TODO vertical support ???
//			isVertical = true;
//			cssForUnit += cssSelectorListForThsList(attribute,
//					widthThs.thsList, isVertical) + //
//					cssPropertiesFor(attribute, percentageValue, isVertical);
			log.trace(cssForUnit);

		}

		if (attribute.startsWith('unit')) {
			//FIXME maybe add '*' too as alternative shortened of 'auto'
			var cssSelector = '[m-grid]>[' + attribute + '="auto"]';
			css += cssSelector + //
							'\n{' + //
								'flex: 1 1 auto;' + //
							'}\n';
		}else if(attribute.startsWith('offset')) {
			//TODO
			var cssSelector = '[m-grid]>[' + attribute + '="auto"]';
			css += cssSelector + //
							'\n{' + //
								'margin-left: auto;' + //
							'}\n';
		}

		if (screen) {
			css += screen.createCssRuleString(cssForUnit);
		} else {
			css += cssForUnit;
		}
		css += '\n';
	}
	// log.trace(css);
	mediaQueries.addCssRule(css);
	if (log.isTrace){
		log.trace(css)
	}
}
);


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

    <ListPreference
        android:key="@string/pref_startScreen"
        android:title="@string/pref_startScreen_title"
        android:defaultValue="@string/books_value"
        android:entries="@array/pref_start_options"
        android:entryValues="@array/pref_start_values"
        />

</PreferenceScreen>


text:
package org.wso2.carbon.siddhi.editor.core.util.designview.beans.configs;

import org.wso2.carbon.siddhi.editor.core.util.designview.constants.NodeType;

import java.util.Objects;

/**
 * Represents a connection between two Siddhi app design view elements
 */
public class Edge {
    private String id;
    private String parentId;
    private NodeType parentType;
    private String childId;
    private NodeType childType;
    private boolean fromFaultStream;

    public Edge(String id, String parentId, NodeType parentType, String childId, NodeType childType) {
        this(id, parentId, parentType, childId, childType, false);
    }

    public Edge(String id, String parentId, NodeType parentType, String childId, NodeType childType,
                boolean fromFaultStream) {
        this.id = id;
        this.parentId = parentId;
        this.parentType = parentType;
        this.childId = childId;
        this.childType = childType;
        this.fromFaultStream = fromFaultStream;
    }

    public String getId() {
        return id;
    }

    public String getParentId() {
        return parentId;
    }

    public NodeType getParentType() {
        return parentType;
    }

    public String getChildId() {
        return childId;
    }

    public NodeType getChildType() {
        return childType;
    }

    public boolean isFromFaultStream() {
        return fromFaultStream;
    }

    public void setFromFaultStream(boolean fromFaultStream) {
        this.fromFaultStream = fromFaultStream;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Edge edge = (Edge) o;
        return Objects.equals(id, edge.id) && Objects.equals(fromFaultStream, edge.fromFaultStream);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var monad_1 = require("./monad");
/**
 * Class Maybe - return given value or produce null if take nothing or get nothing after execution of f(v).
 * @extends {Monad}
 */
var Maybe = /** @class */ (function (_super) {
    __extends(Maybe, _super);
    function Maybe() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Chains the operations on a monadic values.
     * @method bind
     * @param {MF<T, U>} f - transformation function for a monad.
     * @param {T} v - underlying value for a monad.
     * @return {Pr<U>} transformed by f() value v.
     */
    Maybe.prototype.bind = function (f, v) {
        if (v === null || v === undefined) {
            return this.nothing();
        }
        else {
            var vL = this.just(f, v);
            return (vL === null || vL === undefined) ? this.nothing() : vL;
        }
    };
    /**
     * Return nothing (null).
     * @method nothing
     * @return {null}
     */
    Maybe.prototype.nothing = function () {
        return null;
    };
    ;
    return Maybe;
}(monad_1.Monad));
exports.Maybe = Maybe;
//Copyright (c) 2017 Alex Tranchenko. All rights reserved.


text:
#pragma once
#include <aws/chime/Chime_EXPORTS.h>
#include <aws/chime/ChimeRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/chime/model/VoiceConnectorItem.h>
#include <utility>

namespace Aws
{
namespace Chime
{
namespace Model
{

  /**
   */
  class AWS_CHIME_API UpdateVoiceConnectorGroupRequest : public ChimeRequest
  {
  public:
    UpdateVoiceConnectorGroupRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateVoiceConnectorGroup"; }

    Aws::String SerializePayload() const override;

    /**
     *
The Amazon Chime Voice Connector group ID.

     */
    inline const Aws::String& GetVoiceConnectorGroupId() const{ return m_voiceConnectorGroupId; }

    /**
     *
The Amazon Chime Voice Connector group ID.

     */
    inline bool VoiceConnectorGroupIdHasBeenSet() const { return m_voiceConnectorGroupIdHasBeenSet; }

    /**
     *
The Amazon Chime Voice Connector group ID.

     */
    inline void SetVoiceConnectorGroupId(const Aws::String& value) { m_voiceConnectorGroupIdHasBeenSet = true; m_voiceConnectorGroupId = value; }

    /**
     *
The Amazon Chime Voice Connector group ID.

     */
    inline void SetVoiceConnectorGroupId(Aws::String&& value) { m_voiceConnectorGroupIdHasBeenSet = true; m_voiceConnectorGroupId = std::move(value); }

    /**
     *
The Amazon Chime Voice Connector group ID.

     */
    inline void SetVoiceConnectorGroupId(const char* value) { m_voiceConnectorGroupIdHasBeenSet = true; m_voiceConnectorGroupId.assign(value); }

    /**
     *
The Amazon Chime Voice Connector group ID.

     */
    inline UpdateVoiceConnectorGroupRequest& WithVoiceConnectorGroupId(const Aws::String& value) { SetVoiceConnectorGroupId(value); return *this;}

    /**
     *
The Amazon Chime Voice Connector group ID.

     */
    inline UpdateVoiceConnectorGroupRequest& WithVoiceConnectorGroupId(Aws::String&& value) { SetVoiceConnectorGroupId(std::move(value)); return *this;}

    /**
     *
The Amazon Chime Voice Connector group ID.

     */
    inline UpdateVoiceConnectorGroupRequest& WithVoiceConnectorGroupId(const char* value) { SetVoiceConnectorGroupId(value); return *this;}

    /**
     *
The name of the Amazon Chime Voice Connector group.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
The name of the Amazon Chime Voice Connector group.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
The name of the Amazon Chime Voice Connector group.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The name of the Amazon Chime Voice Connector group.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The name of the Amazon Chime Voice Connector group.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
The name of the Amazon Chime Voice Connector group.

     */
    inline UpdateVoiceConnectorGroupRequest& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
The name of the Amazon Chime Voice Connector group.

     */
    inline UpdateVoiceConnectorGroupRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The name of the Amazon Chime Voice Connector group.

     */
    inline UpdateVoiceConnectorGroupRequest& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
 The VoiceConnectorItems to associate with the group.

     */
    inline const Aws::Vector<VoiceConnectorItem>& GetVoiceConnectorItems() const{ return m_voiceConnectorItems; }

    /**
     *
 The VoiceConnectorItems to associate with the group.

     */
    inline bool VoiceConnectorItemsHasBeenSet() const { return m_voiceConnectorItemsHasBeenSet; }

    /**
     *
 The VoiceConnectorItems to associate with the group.

     */
    inline void SetVoiceConnectorItems(const Aws::Vector<VoiceConnectorItem>& value) { m_voiceConnectorItemsHasBeenSet = true; m_voiceConnectorItems = value; }

    /**
     *
 The VoiceConnectorItems to associate with the group.

     */
    inline void SetVoiceConnectorItems(Aws::Vector<VoiceConnectorItem>&& value) { m_voiceConnectorItemsHasBeenSet = true; m_voiceConnectorItems = std::move(value); }

    /**
     *
 The VoiceConnectorItems to associate with the group.

     */
    inline UpdateVoiceConnectorGroupRequest& WithVoiceConnectorItems(const Aws::Vector<VoiceConnectorItem>& value) { SetVoiceConnectorItems(value); return *this;}

    /**
     *
 The VoiceConnectorItems to associate with the group.

     */
    inline UpdateVoiceConnectorGroupRequest& WithVoiceConnectorItems(Aws::Vector<VoiceConnectorItem>&& value) { SetVoiceConnectorItems(std::move(value)); return *this;}

    /**
     *
 The VoiceConnectorItems to associate with the group.

     */
    inline UpdateVoiceConnectorGroupRequest& AddVoiceConnectorItems(const VoiceConnectorItem& value) { m_voiceConnectorItemsHasBeenSet = true; m_voiceConnectorItems.push_back(value); return *this; }

    /**
     *
 The VoiceConnectorItems to associate with the group.

     */
    inline UpdateVoiceConnectorGroupRequest& AddVoiceConnectorItems(VoiceConnectorItem&& value) { m_voiceConnectorItemsHasBeenSet = true; m_voiceConnectorItems.push_back(std::move(value)); return *this; }

  private:

    Aws::String m_voiceConnectorGroupId;
    bool m_voiceConnectorGroupIdHasBeenSet;

    Aws::String m_name;
    bool m_nameHasBeenSet;

    Aws::Vector<VoiceConnectorItem> m_voiceConnectorItems;
    bool m_voiceConnectorItemsHasBeenSet;
  };

} // namespace Model
} // namespace Chime
} // namespace Aws


text:
Welcome,

You've successfully generated this application. Click on the button above to dismiss this welcome message !

Learn more via the Book entity


text:
MKDIR=mkdir
CP=cp
CCADMIN=CCadmin

COVERAGE_FLAGS:=$(shell cd /tmp; echo 'int main(){}' | $(CXX) -x c++ -o /dev/null --coverage - > /dev/null 2>&1 && echo '--coverage')

# build
build: .build-post

.build-pre:
# Add your pre 'build' code here...

.build-post: .build-impl
# Add your post 'build' code here...

# clean
clean: .clean-post

.clean-pre:
# Add your pre 'clean' code here...
	rm -rf externals

.clean-post: .clean-impl
# Add your post 'clean' code here...

# clobber
clobber: .clobber-post

.clobber-pre:
# Add your pre 'clobber' code here...

.clobber-post: .clobber-impl
# Add your post 'clobber' code here...

# all
all: .all-post

.all-pre:
# Add your pre 'all' code here...

.all-post: .all-impl
# Add your post 'all' code here...

# build tests
build-tests: .build-tests-post

.build-tests-pre:
# Add your pre 'build-tests' code here...

.build-tests-post: .build-tests-impl
# Add your post 'build-tests' code here...

# run tests
test: .test-post

.test-pre: build-tests
# Add your pre 'test' code here...

.test-post: .test-impl
# Add your post 'test' code here...

# help
help: .help-post

.help-pre:
# Add your pre 'help' code here...

.help-post: .help-impl
# Add your post 'help' code here...

# include project implementation makefile
include nbproject/Makefile-impl.mk

# include project make variables
include nbproject/Makefile-variables.mk


text:
package org.apache.ode.jacob.vpu;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.apache.ode.jacob.Channel;
import org.apache.ode.jacob.soup.CommChannel;
import org.apache.ode.utils.CollectionUtils;

public class ChannelFactory {
	private static final Method METHOD_OBJECT_EQUALS;

	private static final Method METHOD_CHANNEL_EXPORT;

	static {
		try {
			METHOD_OBJECT_EQUALS = Object.class.getMethod("equals",
					new Class[] { Object.class });
		} catch (Exception e) {
			throw new AssertionError("No equals(Object) method on Object!");
		}

		try {
			METHOD_CHANNEL_EXPORT = Channel.class.getMethod("export",
					CollectionUtils.EMPTY_CLASS_ARRAY);
		} catch (Exception e) {
			throw new AssertionError("No export() method on Object!");
		}
	}

	public static Object getBackend(Channel channel) {
		ChannelInvocationHandler cih = (ChannelInvocationHandler) Proxy
				.getInvocationHandler(channel);
		return cih._backend;
	}

	public static Channel createChannel(CommChannel backend, Class type) {
		InvocationHandler h = new ChannelInvocationHandler(backend);
		Class[] ifaces = new Class[] { Channel.class, type };
		Object proxy = Proxy.newProxyInstance(Channel.class.getClassLoader(),
				ifaces, h);
		return (Channel) proxy;
	}

	public static final class ChannelInvocationHandler implements
			InvocationHandler {
		private CommChannel _backend;

		ChannelInvocationHandler(CommChannel backend) {
			_backend = backend;
		}

		public String toString() {
			return _backend.toString();
		}

		public boolean equals(Object other) {
			return ((ChannelInvocationHandler) other)._backend.equals(_backend);
		}

		public int hashCode() {
			return _backend.hashCode();
		}

		public Object invoke(Object proxy, Method method, Object[] args)
				throws Throwable {
			if (method.getDeclaringClass() == Object.class) {
				if (method.equals(METHOD_OBJECT_EQUALS)) {
					return Boolean.valueOf(this.equals(Proxy
							.getInvocationHandler(args[0])));
				}
				return method.invoke(this, args);
			}
			if (method.equals(METHOD_CHANNEL_EXPORT)) {
				return JacobVPU.activeJacobThread().exportChannel(
						(Channel) proxy);
			}
			return JacobVPU.activeJacobThread().message((Channel) proxy,
					method, args);
		}
	} // class ChannelInvocationHandler

}