text:
package db

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/lxc/lxd/lxd/db/cluster"
	"github.com/lxc/lxd/lxd/db/query"
	"github.com/lxc/lxd/shared/version"
	"github.com/pkg/errors"
)

// NodeInfo holds information about a single LXD instance in a cluster.
type NodeInfo struct {
	ID            int64     // Stable node identifier
	Name          string    // User-assigned name of the node
	Address       string    // Network address of the node
	Description   string    // Node description (optional)
	Schema        int       // Schema version of the LXD code running the node
	APIExtensions int       // Number of API extensions of the LXD code running on the node
	Heartbeat     time.Time // Timestamp of the last heartbeat
}

// IsOffline returns true if the last successful heartbeat time of the node is
// older than the given threshold.
func (n NodeInfo) IsOffline(threshold time.Duration) bool {
	return nodeIsOffline(threshold, n.Heartbeat)
}

// Version returns the node's version, composed by its schema level and
// number of extensions.
func (n NodeInfo) Version() [2]int {
	return [2]int{n.Schema, n.APIExtensions}
}

// NodeByAddress returns the node with the given network address.
func (c *ClusterTx) NodeByAddress(address string) (NodeInfo, error) {
	null := NodeInfo{}
	nodes, err := c.nodes(false /* not pending */, "address=?", address)
	if err != nil {
		return null, err
	}
	switch len(nodes) {
	case 0:
		return null, ErrNoSuchObject
	case 1:
		return nodes[0], nil
	default:
		return null, fmt.Errorf("more than one node matches")
	}
}

// NodePendingByAddress returns the pending node with the given network address.
func (c *ClusterTx) NodePendingByAddress(address string) (NodeInfo, error) {
	null := NodeInfo{}
	nodes, err := c.nodes(true /*pending */, "address=?", address)
	if err != nil {
		return null, err
	}
	switch len(nodes) {
	case 0:
		return null, ErrNoSuchObject
	case 1:
		return nodes[0], nil
	default:
		return null, fmt.Errorf("more than one node matches")
	}
}

// NodeByName returns the node with the given name.
func (c *ClusterTx) NodeByName(name string) (NodeInfo, error) {
	null := NodeInfo{}
	nodes, err := c.nodes(false /* not pending */, "name=?", name)
	if err != nil {
		return null, err
	}
	switch len(nodes) {
	case 0:
		return null, ErrNoSuchObject
	case 1:
		return nodes[0], nil
	default:
		return null, fmt.Errorf("more than one node matches")
	}
}

// NodeName returns the name of the node this method is invoked on.
func (c *ClusterTx) NodeName() (string, error) {
	stmt := "SELECT name FROM nodes WHERE id=?"
	names, err := query.SelectStrings(c.tx, stmt, c.nodeID)
	if err != nil {
		return "", err
	}
	switch len(names) {
	case 0:
		return "", nil
	case 1:
		return names[0], nil
	default:
		return "", fmt.Errorf("inconsistency: non-unique node ID")
	}
}

// NodeAddress returns the address of the node this method is invoked on.
func (c *ClusterTx) NodeAddress() (string, error) {
	stmt := "SELECT address FROM nodes WHERE id=?"
	addresses, err := query.SelectStrings(c.tx, stmt, c.nodeID)
	if err != nil {
		return "", err
	}
	switch len(addresses) {
	case 0:
		return "", nil
	case 1:
		return addresses[0], nil
	default:
		return "", fmt.Errorf("inconsistency: non-unique node ID")
	}
}

// Nodes returns all LXD nodes part of the cluster.
//
// If this LXD instance is not clustered, a list with a single node whose
// address is 0.0.0.0 is returned.
func (c *ClusterTx) Nodes() ([]NodeInfo, error) {
	return c.nodes(false /* not pending */, "")
}

// NodesCount returns the number of nodes in the LXD cluster.
//
// Since there's always at least one node row, even when not-clustered, the
// return value is greater than zero
func (c *ClusterTx) NodesCount() (int, error) {
	count, err := query.Count(c.tx, "nodes", "")
	if err != nil {
		return 0, errors.Wrap(err, "failed to count existing nodes")
	}
	return count, nil
}

// NodeRename changes the name of an existing node.
//
// Return an error if a node with the same name already exists.
func (c *ClusterTx) NodeRename(old, new string) error {
	count, err := query.Count(c.tx, "nodes", "name=?", new)
	if err != nil {
		return errors.Wrap(err, "failed to check existing nodes")
	}
	if count != 0 {
		return ErrAlreadyDefined
	}
	stmt := `UPDATE nodes SET name=? WHERE name=?`
	result, err := c.tx.Exec(stmt, new, old)
	if err != nil {
		return errors.Wrap(err, "failed to update node name")
	}
	n, err := result.RowsAffected()
	if err != nil {
		return errors.Wrap(err, "failed to get rows count")
	}
	if n != 1 {
		return fmt.Errorf("expected to update one row, not %d", n)
	}
	return nil
}

// Nodes returns all LXD nodes part of the cluster.
func (c *ClusterTx) nodes(pending bool, where string, args ...interface{}) ([]NodeInfo, error) {
	nodes := []NodeInfo{}
	dest := func(i int) []interface{} {
		nodes = append(nodes, NodeInfo{})
		return []interface{}{
			&nodes[i].ID,
			&nodes[i].Name,
			&nodes[i].Address,
			&nodes[i].Description,
			&nodes[i].Schema,
			&nodes[i].APIExtensions,
			&nodes[i].Heartbeat,
		}
	}
	if pending {
		args = append([]interface{}{1}, args...)
	} else {
		args = append([]interface{}{0}, args...)
	}
	stmt := `
SELECT id, name, address, description, schema, api_extensions, heartbeat FROM nodes WHERE pending=? `
	if where != "" {
		stmt += fmt.Sprintf("AND %s ", where)
	}
	stmt += "ORDER BY id"
	err := query.SelectObjects(c.tx, dest, stmt, args...)
	if err != nil {
		return nil, errors.Wrap(err, "failed to fecth nodes")
	}
	return nodes, nil
}

// NodeAdd adds a node to the current list of LXD nodes that are part of the
// cluster. It returns the ID of the newly inserted row.
func (c *ClusterTx) NodeAdd(name string, address string) (int64, error) {
	columns := []string{"name", "address", "schema", "api_extensions"}
	values := []interface{}{name, address, cluster.SchemaVersion, version.APIExtensionsCount()}
	return query.UpsertObject(c.tx, "nodes", columns, values)
}

// NodePending toggles the pending flag for the node. A node is pending when
// it's been accepted in the cluster, but has not yet actually joined it.
func (c *ClusterTx) NodePending(id int64, pending bool) error {
	value := 0
	if pending {
		value = 1
	}
	result, err := c.tx.Exec("UPDATE nodes SET pending=? WHERE id=?", value, id)
	if err != nil {
		return err
	}
	n, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if n != 1 {
		return fmt.Errorf("query updated %d rows instead of 1", n)
	}
	return nil
}

// NodeUpdate updates the name an address of a node.
func (c *ClusterTx) NodeUpdate(id int64, name string, address string) error {
	result, err := c.tx.Exec("UPDATE nodes SET name=?, address=? WHERE id=?", name, address, id)
	if err != nil {
		return err
	}
	n, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if n != 1 {
		return fmt.Errorf("query updated %d rows instead of 1", n)
	}
	return nil
}

// NodeRemove removes the node with the given id.
func (c *ClusterTx) NodeRemove(id int64) error {
	result, err := c.tx.Exec("DELETE FROM nodes WHERE id=?", id)
	if err != nil {
		return err
	}
	n, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if n != 1 {
		return fmt.Errorf("query deleted %d rows instead of 1", n)
	}
	return nil
}

// NodeHeartbeat updates the heartbeat column of the node with the given address.
func (c *ClusterTx) NodeHeartbeat(address string, heartbeat time.Time) error {
	stmt := "UPDATE nodes SET heartbeat=? WHERE address=?"
	result, err := c.tx.Exec(stmt, heartbeat, address)
	if err != nil {
		return err
	}
	n, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if n != 1 {
		return fmt.Errorf("expected to update one row and not %d", n)
	}
	return nil
}

// NodeIsEmpty returns an empty string if the node with the given ID has no
// containers or images associated with it. Otherwise, it returns a message
// say what's left.
func (c *ClusterTx) NodeIsEmpty(id int64) (string, error) {
	// Check if the node has any containers.
	containers, err := query.SelectStrings(c.tx, "SELECT name FROM containers WHERE node_id=?", id)
	if err != nil {
		return "", errors.Wrapf(err, "failed to get containers for node %d", id)
	}
	if len(containers) > 0 {
		message := fmt.Sprintf(
			"node still has the following containers: %s", strings.Join(containers, ", "))
		return message, nil
	}

	// Check if the node has any images available only in.
	images := []struct {
		fingerprint string
		nodeID      int64
	}{}
	dest := func(i int) []interface{} {
		images = append(images, struct {
			fingerprint string
			nodeID      int64
		}{})
		return []interface{}{&images[i].fingerprint, &images[i].nodeID}

	}
	err = query.SelectObjects(c.tx, dest, `
SELECT fingerprint, node_id FROM images JOIN images_nodes ON images.id=images_nodes.image_id`)
	if err != nil {
		return "", errors.Wrapf(err, "failed to get image list for node %d", id)
	}
	index := map[string][]int64{} // Map fingerprints to IDs of nodes
	for _, image := range images {
		index[image.fingerprint] = append(index[image.fingerprint], image.nodeID)
	}

	fingerprints := []string{}
	for fingerprint, ids := range index {
		if len(ids) > 1 {
			continue
		}
		if ids[0] == id {
			fingerprints = append(fingerprints, fingerprint)
		}
	}

	if len(fingerprints) > 0 {
		message := fmt.Sprintf(
			"node still has the following images: %s", strings.Join(fingerprints, ", "))
		return message, nil
	}

	return "", nil
}

// NodeClear removes any container or image associated with this node.
func (c *ClusterTx) NodeClear(id int64) error {
	_, err := c.tx.Exec("DELETE FROM containers WHERE node_id=?", id)
	if err != nil {
		return err
	}

	// Get the IDs of the images this node is hosting.
	ids, err := query.SelectIntegers(c.tx, "SELECT image_id FROM images_nodes WHERE node_id=?", id)
	if err != nil {
		return err
	}

	// Delete the association
	_, err = c.tx.Exec("DELETE FROM images_nodes WHERE node_id=?", id)
	if err != nil {
		return err
	}

	// Delete the image as well if this was the only node with it.
	for _, id := range ids {
		count, err := query.Count(c.tx, "images_nodes", "image_id=?", id)
		if err != nil {
			return err
		}
		if count > 0 {
			continue
		}
		_, err = c.tx.Exec("DELETE FROM images WHERE id=?", id)
		if err != nil {
			return err
		}
	}

	return nil
}

// NodeOfflineThreshold returns the amount of time that needs to elapse after
// which a series of unsuccessful heartbeat will make the node be considered
// offline.
func (c *ClusterTx) NodeOfflineThreshold() (time.Duration, error) {
	threshold := time.Duration(DefaultOfflineThreshold) * time.Second
	values, err := query.SelectStrings(
		c.tx, "SELECT value FROM config WHERE key='cluster.offline_threshold'")
	if err != nil {
		return -1, err
	}
	if len(values) > 0 {
		seconds, err := strconv.Atoi(values[0])
		if err != nil {
			return -1, err
		}
		threshold = time.Duration(seconds) * time.Second
	}
	return threshold, nil
}

// NodeWithLeastContainers returns the name of the non-offline node with
// with the least number of containers.
func (c *ClusterTx) NodeWithLeastContainers() (string, error) {
	threshold, err := c.NodeOfflineThreshold()
	if err != nil {
		return "", errors.Wrap(err, "failed to get offline threshold")
	}
	nodes, err := c.Nodes()
	if err != nil {
		return "", errors.Wrap(err, "failed to get current nodes")
	}

	name := ""
	containers := -1
	for _, node := range nodes {
		if node.IsOffline(threshold) {
			continue
		}
		count, err := query.Count(c.tx, "containers", "node_id=?", node.ID)
		if err != nil {
			return "", errors.Wrap(err, "failed to get containers count")
		}
		if containers == -1 || count < containers {
			containers = count
			name = node.Name
		}
	}
	return name, nil
}

func nodeIsOffline(threshold time.Duration, heartbeat time.Time) bool {
	return heartbeat.Before(time.Now().Add(-threshold))
}

// DefaultOfflineThreshold is the default value for the
// cluster.offline_threshold configuration key, expressed in seconds.
const DefaultOfflineThreshold = 20


text:
using System.Linq;

namespace WelderCalculator.Model
{
    public class BaseMaterial : Material
    {
        public string Number { get; set; }

        public BaseMaterial() : base()
        {
            Number = string.Empty;
        }
        public override void CreateBasicListOfElements()
        {
            Elements.Add(new Element(Category.OfElement.C));
            Elements.Add(new Element(Category.OfElement.Si));
            Elements.Add(new Element(Category.OfElement.Mn));
            Elements.Add(new Element(Category.OfElement.P));
            Elements.Add(new Element(Category.OfElement.S));
            Elements.Add(new Element(Category.OfElement.Cr));
            Elements.Add(new Element(Category.OfElement.Ni));
            Elements.Add(new Element(Category.OfElement.Mo));
            Elements.Add(new Element(Category.OfElement.N));
            Elements.Add(new Element(Category.OfElement.Cu));
            Elements.Add(new Element(Category.OfElement.Nb));
            Elements.Add(new Element(Category.OfElement.Ti));
            Elements.Add(new Element(Category.OfElement.V));
            Elements.Add(new Element(Category.OfElement.Al));
        }

        public override bool Equals(Material material)
        {
            var newTypeMaterial = material as BaseMaterial;

            if (this.Name != newTypeMaterial.Name)
                return false;
            if (this.Number != newTypeMaterial.Number)
                return false;
            if (this.Elements.Count != newTypeMaterial.Elements.Count)
                return false;

            foreach (var thatElement in newTypeMaterial.Elements)
            {
                var thisElement = this.Elements.First(x => x.Name == thatElement.Name);
                if (thisElement.Min != thatElement.Min || thisElement.Max != thatElement.Max || thisElement.RealValue != thatElement.RealValue)
                    return false;
            }

            return true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.wso2.developerstudio.eclipse.gmf.esb.impl;

import org.eclipse.emf.ecore.EClass;

import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
import org.wso2.developerstudio.eclipse.gmf.esb.PropertyGroupMediatorInputConnector;

/**
 *
 * An implementation of the model object 'Property Group Mediator Input Connector'.
 *
 *
 * @generated
 */
public class PropertyGroupMediatorInputConnectorImpl extends InputConnectorImpl implements PropertyGroupMediatorInputConnector {
	/**
     *
	 *
     * @generated
     */
	protected PropertyGroupMediatorInputConnectorImpl() {
        super();
    }

	/**
     *
	 *
     * @generated
     */
	@Override
	protected EClass eStaticClass() {
        return EsbPackage.Literals.PROPERTY_GROUP_MEDIATOR_INPUT_CONNECTOR;
    }
} //PropertyGroupMediatorInputConnectorImpl


text:
gomock_example
==============

```sh
go install code.google.com/p/gomock/gomock
go install code.google.com/p/gomock/mockgen
mkdir mock_gomock_example
mockgen github.com/daimatz/gomock_example/twitter_bot TwitterService > mock_gomock_example/a.go
cd twitter_bot
go test
```


text:
@interface LLNavigationViewControllerTests : XCTestCase

@end

@implementation LLNavigationViewControllerTests

- (void)setUp
{
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown
{
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testExample
{
    XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__);
}

@end


text:
using System;
using System.Threading.Tasks;
using ZendeskApi_v2.Models.Tickets;

namespace ZendeskTicketExporter.Core
{
    public class TicketRetriever : ITicketRetriever
    {
        private readonly IWait _wait;
        private readonly Func<DateTime> _utcNowProvider;
        private readonly IZendeskApi _zendeskApi;

        private DateTime? _lastBatchRetrivedAt;

        public TicketRetriever(IWait wait, IZendeskApi zendeskApi, Func<DateTime> utcNowProvider = null)
        {
            _wait = wait;
            _zendeskApi = zendeskApi;
            _utcNowProvider = utcNowProvider ?? (() => DateTime.UtcNow);
        }

        public async Task<TicketExportResponse> GetBatchAsync(long? marker)
        {
            if (_lastBatchRetrivedAt.HasValue)
            {
                var nextAllowedRequest = _lastBatchRetrivedAt.Value.Add(
                    Configuration.ZendeskRequiredCooloffBetweenIncrementalTicketExportResults);

                await _wait.UntilAsync(nextAllowedRequest);
            }

            var ticketsBatch = await _zendeskApi.IncrementalTicketExport(marker);

            _lastBatchRetrivedAt = _utcNowProvider();

            return ticketsBatch;
        }
    }
}


text:
import test from 'ava';
import {RuleTester} from 'eslint';
import rule from '../rules/preferred-alias';

import {code} from './helpers';

const ruleTester = new RuleTester({
  env: {
    es6: true
  },
  parserOptions: {
    sourceType: 'module'
  }
});

test('Invalid configurations', t => {
  t.throws(() => {
    ruleTester.run('preferred-alias', rule, {
      valid: [],
      invalid: [
        {
          code: code('foo'),
          options: [{overrides: ['propEq', 'pathEq']}],
          errors: []
        }
      ]
    });
  }, 'Error while loading rule \'preferred-alias\': `override` contains `propEq` and `pathEq` that target `matchesProperty`');

  t.throws(() => {
    ruleTester.run('preferred-alias', rule, {
      invalid: [],
      valid: [
        {
          code: code('foo'),
          options: [{overrides: ['matchesProperty', 'propEq']}],
          errors: [{message: 'ok'}]
        }
      ]
    });
  }, 'Error while loading rule \'preferred-alias\': `override` contains `matchesProperty` and `propEq` that target `matchesProperty`');
});


text:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
  <input type="hidden" name="cmd" value="_s-xclick">
  <input type="hidden" name="hosted_button_id" value="FG73LWYQMT63S">
  <input type="image" src="https://www.paypalobjects.com/es_XC/MX/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal, la forma más segura y rápida de pagar en línea.">
  <img alt="" border="0" src="https://www.paypalobjects.com/es_XC/i/scr/pixel.gif" width="1" height="1">
</form>


text:
import Marionette from 'backbone.marionette';
import React from 'react';
import ReactDOM from 'react-dom';

const defaultModelEvents = 'change';
const defaultCollectionEvents = 'add remove reset';

function defaultGetProps({model, collection, state = {}} = {}) {
  if (model) {
    Object.assign(state, model.toJSON());
  }

  if (collection) {
    Object.assign(state, {items: collection.toJSON()});
  }

  return state;
}

function extractNewState(options = {}) {
  const {
    getProps = defaultGetProps,
    props
  } = options;

  const newState = {
    ...getProps(options),
    ...props
  };

  return newState;
}

function viewCallback(...args) {
  this.options.dispatch(...args);
}

// Override the default remove function in order not to erase the
// Marionette.View from the DOM when updating the the React Component

function unobtrusiveRemove() {
  this.$el.off();
  this.stopListening();
  return this;
}

const ReactBridge = {

  /**
   * function to wrap a React Component in a Marionette View
   *
   * @param {React Component} Component, the react component which will be rendered inside the Marionette View
   * @param {Object} options, configuration for the React Component
   */

  viewFromComponent(Component, options = {}) {
    const ReactMarionetteView = Marionette.View.extend({

      initialize() {

        // +-----+--------------------+
        // | Mn  | Lifecycle Events   |
        // +-----+--------------------+
        // | v1  | ['show close']     |
        // +-----+--------------------+
        // | v2  | ['show destroy']   |
        // +-----+--------------------+
        // | v3  | ['render destroy'] |
        // +-----+--------------------+

        this.listenTo(this, 'show render', this._onShowRender);
        this.listenTo(this, 'close destroy', this._onCloseDestroy);
      },

      template() {},

      _onShowRender() {
        if (this._reactInternalInstance) {
          return false;
        }

        // Create and render a container component wrapping the given component
        class Container extends React.Component {

          constructor() {
            super();
            this.state = extractNewState(options);
            this.updateComponentState = this.updateComponentState.bind(this);
          }

          componentDidMount() {
            const {
              model,
              collections,
              observe = {}
            } = options;

            this.initListener(model, observe.model || defaultModelEvents);
            this.initListener(collections, observe.collection || defaultCollectionEvents);
          }

          componentWillUnmount() {
            this.destroyListener(options.model);
            this.destroyListener(options.collection);
          }

          initListener(entity, events) {
            if (!entity) {
              return;
            }

            if (events instanceof Array) {
              events = events.join(' ');
            }

            entity.on(events, this.updateComponentState);
          }

          updateComponentState() {
            const newState = extractNewState(options);
            this.setState(newState);
          }

          destroyListener(entity) {
            if (!entity) {
              return;
            }

            entity.off();
          }

          render() {
            if (React.isValidElement(Component)) {
              return React.cloneElement(Component, this.state);
            }

            return <Component {...this.state} />;
          }

        }

        ReactDOM.render(<Container ref={el => (this._reactInternalInstance = el)} />, this.el);
      },

      _onCloseDestroy() {
        this.stopListening(this, 'show render close destroy');
        ReactDOM.unmountComponentAtNode(this.el);
        delete this._reactInternalInstance;
      }

    });

    return new ReactMarionetteView(options);
  },

  /**
   * function to wrap a Marionette View in a React Component
   *
   * @param {Marionette View} MarionetteView, the view which will be wrapped inside the React Component
   * @param {Object} options, configuration for the Marionette View
   */

  componentFromView(MarionetteView, options) {
    return class extends React.Component {

      componentDidMount() {
        const parentElem = this._reactInternalFiber
          ? this._reactInternalFiber.child.stateNode
          : ReactDOM.findDOMNode(this._reactInternalInstance._instance);

        if (MarionetteView instanceof Marionette.View) {
          MarionetteView.setElement(parentElem);
          this._marionetteView = MarionetteView;
          Object.assign(this._marionetteView.options, options);
        } else {
          this._marionetteView = new MarionetteView({
            el: parentElem,
            ...options
          });
        }

        this._marionetteView.remove = unobtrusiveRemove;
        this.mapEventsToActions(options);
        this._marionetteView.render();
      }

      shouldComponentUpdate() {
        return false;
      }

      componentWillUnmount() {
        // Unregister listeners for the user defined marionette events
        Object.keys(options.eventsToActions).forEach(event => {
          this._marionetteView.stopListening(this._marionetteView, event);
        });

        this._marionetteView.destroy && this._marionetteView.destroy();
        this._marionetteView.close && this._marionetteView.close();
      }

      createTemplate(view, opts) {
        let tagName = view instanceof Marionette.View
          ? view.tagName
          : view.prototype.tagName;

        let className = view instanceof Marionette.View
          ? view.className
          : view.prototype.className;

        if (opts.tagName) {
          tagName = opts.tagName;
        }

        if (opts.className) {
          className = opts.className;
        }

        return React.createElement(tagName, {className}, null);
      }

      delegate(methodName, ...args) {
        // Check if method exists
        if (!this._marionetteView[methodName]) {
          return;
        }

        // Pass the arguments to marionette method
        return this._marionetteView[methodName](...args);
      }

      mapEventsToActions(opts) {
        const {
          eventsToActions,
          dispatch
        } = opts;

        if (!eventsToActions instanceof Object || !Object.keys(eventsToActions).length) {
          return;
        }

        if (!dispatch || !dispatch instanceof Function) {
          console.error('The `dispatch` function is not defined.');
          return;
        }

        Object.keys(eventsToActions).forEach(event => {
          const action = eventsToActions[event];

          this._marionetteView.listenTo(this._marionetteView, event, (...args) => {
            const myAction = typeof action === 'function' ? action(...args) : action;
            viewCallback.apply(this._marionetteView, [myAction, ...args]);
          });
        });

        return this._marionetteView;
      }

      render() {
        return this.createTemplate(MarionetteView, options);
      }

    }
  }
};

export default ReactBridge;


text: {% include icon-github.svg %}


text:
'use strict';
module.exports = {
  up: function(queryInterface, Sequelize) {
    return queryInterface.createTable('Books', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      author: {
        type: Sequelize.STRING
      },
      copies: {
        type: Sequelize.INTEGER
      },
      price: {
        type: Sequelize.INTEGER
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: function(queryInterface, Sequelize) {
    return queryInterface.dropTable('Books');
  }
};


text:
package org.apache.camel.maven.generator.openapi;

import java.io.File;
import java.io.FileOutputStream;

import io.apicurio.datamodels.openapi.models.OasDocument;
import org.apache.camel.CamelContext;
import org.apache.camel.generator.openapi.DestinationGenerator;
import org.apache.camel.generator.openapi.RestDslGenerator;
import org.apache.camel.generator.openapi.RestDslXmlGenerator;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.util.ObjectHelper;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;

@Mojo(name = "generate-xml", inheritByDefault = false, defaultPhase = LifecyclePhase.GENERATE_SOURCES,
    requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true)
public class GenerateXmlMojo extends AbstractGenerateMojo {

    @Parameter(defaultValue = "false")
    private boolean blueprint;

    @Parameter(defaultValue = "camel-rest.xml", required = true)
    private String fileName;

    @Parameter(defaultValue = "${project.build.directory}/generated-sources/restdsl-openapi", required = true)
    private String outputDirectory;

    @Override
    public void execute() throws MojoExecutionException {
        if (skip) {
            return;
        }

        OasDocument openapi = null;
        try {
            openapi = readOpenApiDoc(specificationUri);
        } catch (Exception e1) {
            throw new MojoExecutionException("can't load open api doc from " + specificationUri, e1);
        }

        if (openapi == null) {
            throw new MojoExecutionException("Unable to generate REST DSL OpenApi sources from specification: "
                + specificationUri + ", make sure that the specification is available at the given URI");
        }

        final RestDslXmlGenerator generator = RestDslGenerator.toXml(openapi);

        if (blueprint) {
            generator.withBlueprint();
        }

        if (ObjectHelper.isNotEmpty(filterOperation)) {
            generator.withOperationFilter(filterOperation);
        }

        if (ObjectHelper.isNotEmpty(destinationGenerator)) {
            final DestinationGenerator destinationGeneratorObject = createDestinationGenerator();

            generator.withDestinationGenerator(destinationGeneratorObject);
        }

        if (restConfiguration) {
            String comp = detectRestComponentFromClasspath();
            if (comp != null) {
                getLog().info("Detected Camel Rest component from classpath: " + comp);
                generator.withRestComponent(comp);
            } else {
                comp = "servlet";

                // is it spring boot?
                String aid = "camel-servlet";
                if (detectSpringBootFromClasspath()) {
                    aid = "camel-servlet-starter";
                }

                String dep = "\n\t\t<dependency>"
                    + "\n\t\t\t<groupId>org.apache.camel</groupId>"
                    + "\n\t\t\t<artifactId>" + aid + "</artifactId>";
                final String ver = detectCamelVersionFromClasspath();
                if (ver != null) {
                    dep += "\n\t\t\t<version>" + ver + "</version>";
                }
                dep += "\n\t\t</dependency>\n";

                getLog().info("Cannot detect Rest component from classpath. Will use servlet as Rest component.");
                getLog().info("Add the following dependency in the Maven pom.xml file:\n" + dep + "\n");

                generator.withRestComponent(comp);
            }
        }

        try {
            final CamelContext camel = new DefaultCamelContext();
            final String xml = generator.generate(camel);

            // ensure output folder is created
            new File(outputDirectory).mkdirs();
            final File out = new File(outputDirectory, fileName);

            try (FileOutputStream fos = new FileOutputStream(out)) {
                fos.write(xml.getBytes());
            }
        } catch (final Exception e) {
            throw new MojoExecutionException(
                "Unable to generate REST DSL OpenApi sources from specification: " + specificationUri, e);
        }
    }

}


text:
<!DOCTYPE html>

Sample Map


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>JOGL Applet3 Graph UI-Scene Demo 01 (NApplet)</title>

JOGL Applet3 Graph UI-Scene Demo 01

<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
      width="640" height="480">
   <param name="code" value="com.jogamp.newt.util.applet.JOGLNewtApplet3Run">
   <param name="archive" value="jar/gluegen-rt.jar,
                                jar/joal.jar,
                                jar/jogl-all-noawt.jar,
                                jar/jogl-test.jar">
   <param name="gl_event_listener_class" value="com.jogamp.opengl.test.junit.graph.demos.GPUUISceneGLListener0A">
   <param name="gl_profile" value="GL2ES2">
   <param name="gl_swap_interval" value="1">
   <param name="gl_alpha" value="4">
   <param name="gl_multisamplebuffer" value="4">
   <param name="gl_debug" value="false">
   <param name="gl_trace" value="false">
   <comment>
     <embed code="com.jogamp.newt.util.applet.JOGLNewtApplet3Run"
          width="640" height="480"
          type="application/x-java-applet;version=1.6"
          pluginspage="http://java.sun.com/javase/downloads/ea.jsp"
          archive="jar/gluegen-rt.jar,
                   jar/joal.jar,
                   jar/jogl-all-noawt.jar,
                   jar/jogl-test.jar"
          gl_event_listener_class="com.jogamp.opengl.test.junit.graph.demos.GPUUISceneGLListener0A"
          gl_profile="GL2ES2"
          gl_swap_interval="1"
          gl_alpha="4"
          gl_multisamplebuffer="4"
          gl_debug="false"
          gl_trace="false">
        <noembed>Sorry, no Java support detected.</noembed>
     </embed>
   </comment>
</object>

Graph UI-Scene Demo Keys:

 none - use mouse

JOGL NEWT JNLP Applet Runner Special Keys:

 d - toggle decoration

 f - toggle fullscreen

 r - in/out browser window

 a - on/off always-on-top

 c - change mouse pointer

 i - invisible mouse pointer

 w - warp mouse pointer to center


text:
import ast, operator

def Subscript(node):
    def get(getter, value):
        return getter(value)

    return get, [node.slice, node.value]

def Index(node):
    return operator.itemgetter, [node.value]

NONE = ast.NameConstant(value=None)

def Slice(node):
    def slicer(start, stop, step):
        s = slice(start, stop, step)
        return lambda x: x[s]

    return slicer, [node.lower or NONE, node.upper or NONE, node.step or NONE]


text:
package org.innovateuk.ifs.application.domain;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.innovateuk.ifs.organisation.domain.OrganisationAddress;

import javax.persistence.*;

/**
 * Entity to link an organisation_address with an application.
 */
@Entity
public class ApplicationOrganisationAddress {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private OrganisationAddress organisationAddress;

    @ManyToOne(fetch = FetchType.LAZY)
    private Application application;

    //for orm
    ApplicationOrganisationAddress() {}

    public ApplicationOrganisationAddress(OrganisationAddress organisationAddress, Application application) {
        this.organisationAddress = organisationAddress;
        this.application = application;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public OrganisationAddress getOrganisationAddress() {
        return organisationAddress;
    }

    public void setOrganisationAddress(OrganisationAddress organisationAddress) {
        this.organisationAddress = organisationAddress;
    }

    public Application getApplication() {
        return application;
    }

    public void setApplication(Application application) {
        this.application = application;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        ApplicationOrganisationAddress that = (ApplicationOrganisationAddress) o;

        return new EqualsBuilder()
                .append(id, that.id)
                .append(organisationAddress, that.organisationAddress)
                .append(application, that.application)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(id)
                .append(organisationAddress)
                .append(application)
                .toHashCode();
    }
}


text:
name: sticky footer, fluid height
slug: sticky-footer-fluid
summary: Ensure that your *fluid-height* footer stays down at the bottom of the viewport, no matter what.
type: mixin only
categories:
  - layout
args:
  - variable: $wrapper
    default: "\".wrapper\""
    comment: A CSS selector for the page-wrapper element. *Wrap your selector in quotes.*
  - variable: $footer
    default: "\".scut-sticky\""
    comment: A CSS selector for the footer. Wrap this selector in quotes, too.
references:
  - description: "\"Sticky CSS Footers: The Flexible Way\""
    url: "http://pixelsvsbytes.com/blog/2011/09/sticky-css-footers-the-flexible-way/"
---

To implement this mixin you'll need the following **a full-page wrapper element, with the footer inside of it.** That's it.

The footer is the wrapper's child, like so:

<body>
  <div class="wrapper">
    <!-- your page's content -->
    <footer class="scut-sticky">
      <!-- your footer's content -->
    </footer>
  </div>
</body>

Then your footer should stick to the bottom of the page, regardless of the height of the content above it *or its own height*. (If you have a fixed-height footer, you could try [`scut-sticky-footer-fixed`](sticky-footer-fixed.html)).

**This mixin should not be invoked within a declaration block — i.e. don't nest it.** The mixin needs to add rules for a number of elements — `html`, `body`, the wrapper, and the footer — so it can't be restricted to the context of a different selector.

Since an example of this utility requires its own `<html>` and `<body>` elements, **[this example is relegated to Codepen](http://codepen.io/davidtheclark/pen/qvngp)**.


text:
In RedHat or CentOS System:

```
yum install tetex
```

## Usage

Run latex on tex file to produce some output:

```
latex doc.tex
bibtex doc.aux
latex doc.tex
latex doc.tex
```

View the output file (.dvi) with xdvi:

```
xdvi doc.dvi &
```

To produce a PDF of this you simply run pdflatex instead of latex:

```
pdflatex doc.tex
```

View the output file (.pdf) with evince:

```
evince doc.pdf &
```

## Reference

[The Latex Project]

[The Latex Project]: https://www.latex-project.org


text:
package org.gdl2.expression;

public enum Constant {
    E("e", "A mathematical constant that is the base of the natural logarithm");
    private String name;
    private String description;

    Constant(String name, String description) {
        this.name = name;
        this.description = description;
    }

    @Override
    public String toString() {
        return this.name;
    }

    public String description() {
        return this.description;
    }
}


text:
require 'net/http'
require 'time'

module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    module Integrations #:nodoc:
      module PrzelewyDwaCztery
        class Notification < ActiveMerchant::Billing::Integrations::Notification

          #przelewy24 nie wysylaja zadnego statusu. dla niepopranej odpowiedzi nie ma zadnego requesta
          def status
            params['p24_statement'].present?
          end

          # Id of this transaction (przelewy24 number)
          def transaction_id
            params['p24_order_id']
          end

          # the money amount we received in X.2 decimal.
          def gross
            params['p24_amount']
          end

          def complete?
            params['p24_statement'].present?
          end

          def currency
            params['p24_currency']
          end

          def order_id
            params['p24_session_id']
          end

          def key=(value)
            @options[:key] = value
          end

          def test?
            # params['t_id'].match('.*-TST\d+') ? true : false
          end

          PAYMENT_HOOK_FIELDS = [
              :p24_merchant_id,
              :p24_pos_id,
              :p24_session_id,
              :p24_amount,
              :p24_currency,
              :p24_order_id,
              :p24_method,
              :p24_statement,
              :p24_sign
          ]

          PAYMENT_HOOK_SIGNATURE_FIELDS = [
              :p24_session_id,
              :p24_merchant_id,
              :p24_amount,
              :p24_currency
          ]

          VERIFY_HOOK_SIGNATURE_FIELDS = [
              :p24_session_id,
              :p24_order_id,
              :p24_amount,
              :p24_currency
          ]

          # Provide access to raw fields
          PAYMENT_HOOK_FIELDS.each do |key|
            define_method(key.to_s) do
              params[key.to_s]
            end
          end

          def generate_signature_string
            PAYMENT_HOOK_SIGNATURE_FIELDS.map { |key| params[key.to_s] } * "|" + "|#{@options[:key]}"
          end

          def generate_signature_verify
            VERIFY_HOOK_SIGNATURE_FIELDS.map { |key| params[key.to_s] } * "|" + "|#{@options[:key]}"
          end

          def generate_signature(verify = false)
            Digest::MD5.hexdigest(verify ? generate_signature_verify : generate_signature_string)
          end

          def acknowledge(authcode = nil)
            generate_signature.to_s == md5.to_s
          end
        end
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace SimpleWeather.Utils
{
    public class DateTimeUtils
    {
        public static TimeSpan MaxTimeOfDay()
        {
            return new TimeSpan(0, 23, 59, 59, 999);
        }

        public static DateTime GetClosestWeekday(DayOfWeek day)
        {
            var today = new DateTime(DateTime.Today.Ticks, DateTimeKind.Utc);

            var nextWeekday = GetNextWeekday(today, day);
            var prevWeekday = GetPrevWeekday(today, day);

            if ((nextWeekday - today) < (today - prevWeekday))
                return nextWeekday;
            else
                return prevWeekday;
        }

        // Functionality thanks to: https://stackoverflow.com/questions/6346119/datetime-get-next-tuesday
        public static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
        {
            // The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
            int daysToAdd = ((int)day - (int)start.DayOfWeek + 7) % 7;
            return start.AddDays(daysToAdd);
        }

        public static DateTime GetPrevWeekday(DateTime start, DayOfWeek day)
        {
            // The (... - 7) % 7 ensures we end up with a value in the range [0, 6]
            int daysToRemove = -(((int)start.DayOfWeek - (int)day + 7) % 7);
            return start.AddDays(daysToRemove);
        }
    }
}


text:
package org.apache.camel.catalog;

import java.lang.management.ManagementFactory;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;

/**
 * MBean exporter to register the {@link CamelCatalog} in JMX.
 */
public class CamelCatalogMBeanExporter {

    public static final String MBEAN_NAME = "org.apache.camel.catalog:type=catalog,name=catalog";

    private CamelCatalog catalog;
    private ObjectName objectName;
    private MBeanServer mBeanServer;

    /**
     * Initializes and exports the {@link CamelCatalog} in JMX using the domain name,
     * which can be obtained using {@link #getObjectName()}.
     *
     * @throws Exception
     */
    public void init() throws Exception {
        catalog = new DefaultCamelCatalog();

        if (objectName == null) {
            objectName = getObjectName();
        }

        if (mBeanServer == null) {
            mBeanServer = ManagementFactory.getPlatformMBeanServer();
        }

        if (mBeanServer != null) {
            try {
                // notice some mbean servers may register using a changed object name
                ObjectInstance oi = mBeanServer.registerMBean(catalog, objectName);
                if (oi != null && oi.getObjectName() != null) {
                    objectName = oi.getObjectName();
                }
            } catch (InstanceAlreadyExistsException iaee) {
                // Try to remove and re-register
                mBeanServer.unregisterMBean(objectName);
                mBeanServer.registerMBean(catalog, objectName);
            }
        }
    }

    /**
     * Destroyes and unregisteres the {@link CamelCatalog} from JMX.
     *
     * @throws Exception is thrown if error during unregistration
     */
    public void destroy() throws Exception {
        if (mBeanServer != null) {
            if (objectName != null) {
                mBeanServer.unregisterMBean(objectName);
            }
        }
    }

    protected ObjectName getObjectName() throws Exception {
        return new ObjectName(MBEAN_NAME);
    }

}


text:
package test.dataprovider;

import org.testng.Assert;
import org.testng.annotations.Test;

public class StaticDataProviderSampleTest {

  @Test(dataProvider = "static", dataProviderClass = StaticProvider.class)
  public void verifyStatic(String s) {
    Assert.assertEquals(s, "Cedric");
  }
}


text:
package com.github.nyrkovalex.migrate.me;

import com.github.nyrkovalex.seed.Db;
import com.github.nyrkovalex.seed.Io;
import com.github.nyrkovalex.seed.Sys;
import java.time.Instant;

public class Database {

	private final static Io.Fs FS = Io.fs();
	private final static Sys.Clock CLOCK = Sys.clock();

	public static Executor executor(Db.Runner runner) {
		return new DbExecutor(FS, runner, CLOCK);
	}

	public interface Executed {
		Instant on();
		String fileName();
	}

	public interface Executor {
		Executed execute(String fileName) throws Err;
	}

	public static class Err extends RuntimeException {
		Err(Throwable cause) {
			super(cause);
		}
	}
}

class DbExecuted implements Database.Executed {

	private final Instant on;
	private final String fileName;

	DbExecuted(String fileName, Instant on) {
		this.on = on;
		this.fileName = fileName;
	}

	@Override
	public Instant on() {
		return on;
	}

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

	@Override
	public String toString() {
		return String.format("Executed %s on %s", fileName(), on());
	}
}

class DbExecutor implements Database.Executor {

	private final Db.Runner runner;
	private final Io.Fs fs;
	private final Sys.Clock clock;

	DbExecutor(Io.Fs fs, Db.Runner conn, Sys.Clock clock) {
		this.fs = fs;
		this.runner = conn;
		this.clock = clock;
	}

	@Override
	public Database.Executed execute(String fileName) throws Database.Err {
		try {
			String sql = fs.file(fileName).string();
			runner.run(sql);
			return new DbExecuted(fileName, clock.now());
		} catch (Db.Err | Io.Err err) {
			throw new Database.Err(err);
		}
	}
}


text:
import { FairArticlesPaginationContainer } from "Apps/Fair/Routes/FairArticles"
import { setupTestWrapper } from "DevTools/setupTestWrapper"
import { graphql } from "react-relay"

jest.unmock("react-relay")

const { getWrapper } = setupTestWrapper({
  Component: FairArticlesPaginationContainer,
  query: graphql`
    query FairArticles_test_Query($id: String!, $page: Int!)
      @relay_test_operation {
      fair(id: $id) {
        ...FairArticles_fair @arguments(page: $page)
      }
    }
  `,
})

describe("FairArticles", () => {
  it("renders the articles", () => {
    const wrapper = getWrapper({
      Article: () => ({
        thumbnailTitle: "Example Article",
        byline: "Example Author",
      }),
    })

    const html = wrapper.html()

    expect(html).toContain("Example Article")
    expect(html).toContain("Example Author")
  })

  it("renders an empty state when there are no articles", () => {
    const wrapper = getWrapper({
      Fair: () => ({
        articlesConnection: {
          totalCount: 0,
          edges: [],
        },
      }),
    })

    const html = wrapper.html()

    expect(html).not.toContain("Example Article")
    expect(html).not.toContain("Example Author")
    expect(html).toContain("There aren't any articles at this time.")
  })
})


text:
SHELL = /bin/sh

## Configuration Directory Variables
prefix := /usr/local
exec_prefix := $(prefix)
sysconfdir := $(prefix)/etc
includedir := $(prefix)/include
libdir := $(exec_prefix)/lib
bindir := $(exec_prefix)/bin

MAKEFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CURRENT_DIR := $(patsubst %/,%,$(dir $(MAKEFILE_PATH)))
BUILD_DIR := $(CURRENT_DIR)/build
CONFIG_DIR := $(sysconfdir)/guest-client/heartbeat
PACKAGE_DIR := $(BUILD_DIR)/package
PACKAGE_ROOT_DIR := $(PACKAGE_DIR)/rootdir

.PHONY: all build sample clean distclean package

all: build

build:
	mkdir -p --mode 755 $(BUILD_DIR)
	@(cd src; make --no-print-directory build \
	sysconfdir=$(sysconfdir) BUILD_DIR=$(BUILD_DIR))

sample:
	@:

clean:
	@-(cd src; make --no-print-directory clean BUILD_DIR=$(BUILD_DIR))

distclean: clean

package:
	@(mkdir -p --mode 755 $(PACKAGE_DIR))
	@(echo "Packaging guest-client.init in $(PACKAGE_DIR)")
	@(cp $(CURRENT_DIR)/scripts/guest-client.init $(PACKAGE_DIR)/guest-client.init)
	@(chmod 755  $(PACKAGE_DIR)/guest-client.init)
	@(echo "Packaging guest-client.service in $(PACKAGE_DIR)")
	@(cp $(CURRENT_DIR)/scripts/guest-client.service $(PACKAGE_DIR)/guest-client.service)
	@(chmod 644  $(PACKAGE_DIR)/guest-client.service)
	@(echo "Packaging guest-client.systemd in $(PACKAGE_DIR)")
	@(cp $(CURRENT_DIR)/scripts/guest-client.systemd $(PACKAGE_DIR)/guest-client.systemd)
	@(mkdir -p --mode 755 $(PACKAGE_ROOT_DIR)/$(CONFIG_DIR))
	@(echo "Packaging guest_heartbeat.conf in $(PACKAGE_ROOT_DIR)/$(CONFIG_DIR)")
	@(cp $(CURRENT_DIR)/scripts/guest_heartbeat.conf $(PACKAGE_ROOT_DIR)/$(CONFIG_DIR)/guest_heartbeat.conf)
	@(echo "Packaging sample_event_handling_script in $(PACKAGE_ROOT_DIR)/$(CONFIG_DIR)")
	@(cp $(CURRENT_DIR)/scripts/sample_event_handling_script $(PACKAGE_ROOT_DIR)/$(CONFIG_DIR)/sample_event_handling_script)
	@(echo "Packaging sample_health_check_script in $(PACKAGE_ROOT_DIR)/$(CONFIG_DIR)")
	@(cp $(CURRENT_DIR)/scripts/sample_health_check_script $(PACKAGE_ROOT_DIR)/$(CONFIG_DIR)/sample_health_check_script)
	@-(cd src; make --no-print-directory package BUILD_DIR=$(BUILD_DIR) \
	PACKAGE_DIR=$(PACKAGE_DIR) prefix=$(prefix) exec_prefix=$(exec_prefix) \
	sysconfdir=$(sysconfdir) includedir=$(includedir) libdir=$(libdir) \
	bindir=$(bindir))


text:
/**
 * Onshape REST API
 * The Onshape REST API consumed by all clients.
 *
 * OpenAPI spec version: 1.93
 * Contact: api-support@onshape.zendesk.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

import { BTIdAndConfiguration } from './bTIdAndConfiguration';

export class BTUpdateVersionThumbnailParams {
    'versionIds'?: Array<BTIdAndConfiguration>;
    'forceUpdate'?: boolean;

    static discriminator: string | undefined = undefined;

    static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
        {
            "name": "versionIds",
            "baseName": "versionIds",
            "type": "Array<BTIdAndConfiguration>"
        },
        {
            "name": "forceUpdate",
            "baseName": "forceUpdate",
            "type": "boolean"
        }    ];

    static getAttributeTypeMap() {
        return BTUpdateVersionThumbnailParams.attributeTypeMap;
    }
}


text:
docsection: guides
layout: doc_subpage
slug: component-libs
title: Component libraries
description: How to implement component libraries for use with Typescene
pageintro: |
  The following guides describe common tasks related to creating component libraries.
---

### In development

_This section is not completed yet._


text:
/*
 * The IEEE hereby grants a general, royalty-free license to copy, distribute,
 * display and make derivative works from this material, for all purposes,
 * provided that any use of the material contains the following
 * attribution: "Reprinted with permission from IEEE 1516.1(TM)-2010".
 * Should you require additional information, contact the Manager, Standards
 * Intellectual Property, IEEE Standards Association (stds-ipr@ieee.org).
 */

//File: ObjectClassHandleFactory.java

package hla.rti1516e;

import hla.rti1516e.exceptions.CouldNotDecode;
import hla.rti1516e.exceptions.FederateNotExecutionMember;
import hla.rti1516e.exceptions.NotConnected;
import hla.rti1516e.exceptions.RTIinternalError;

import java.io.Serializable;

/**
 * The factory is used only (outside RTI) to create ObjectClassHandle
 * received as an attribute value or parameter value.
 */

public interface ObjectClassHandleFactory extends Serializable {
   ObjectClassHandle decode(byte[] buffer, int offset)
      throws CouldNotDecode, FederateNotExecutionMember, NotConnected, RTIinternalError;
}


text:
<?php

define("FUTURE_LOCK", "FUTURE_LOCK");

/**
 * A task intended to be performed asynchronously. Should be subclassed for particular tasks.
 */
abstract class FutureTask {

    const QUEUE = "FUTURE_TASK_REQUESTS";

    private $asyncId;
    private $connConfig;
    private $cookies;
    private $enqueueTime;

    function __construct() {
        $this->asyncId = uniqid();
        $this->requestId = isset($_SERVER['HTTP_X_REQUEST_ID']) ? $_SERVER['HTTP_X_REQUEST_ID'] : null;
        $this->connConfig = WorkbenchContext::get()->getConnConfig();
        $this->cookies = $_COOKIE;
    }

    /**
     * Convenience method that
     * enqueues for async processing if Redis is available;
     * otherwise performs sync processing.
     * Either way, callers should `echo` the return value back to the page.
     *
     * @return string
     */
    public function enqueueOrPerform() {
        if (hasRedis()) {
            $future = $this->enqueue();
            return $future->ajax();
        } else {
            return $this->perform();
        }
    }

    /**
     * Enqueue for async processing.
     * A FutureResult is returned immediately while processing continues asynchronously in the background.
     *
     * @return FutureResult
     * @throws WorkbenchHandledException
     */
    public function enqueue() {
        if (WorkbenchConfig::get()->isConfigured("blockFutureTaskEnqueue")) {
            throw new WorkbenchHandledException("Tasks are currently not being accepted. Try again in a few moments.");
        }

        $this->enqueueTime = time();
        WorkbenchContext::get()->getPartnerConnection()->getServerTimestamp();                                                                // check user has active session before going into async land
        redis()->setex(FUTURE_LOCK . $this->asyncId, WorkbenchConfig::get()->value('asyncTimeoutSeconds'), crypto_serialize(session_id()));   // set an expiring lock on this async id so GC doesn't get it
        $payload = crypto_serialize($this);
        redis()->rpush(self::QUEUE, $payload);                                                                                // place actual job on the queue
        workbenchLog(LOG_INFO, "FutureTaskEnqueue", array(
            "async_id" =>  $this->asyncId,
            "source" => get_class($this),
            "measure.async.enqueue.size" => strlen($payload). "byte"));
        return new FutureResult($this->asyncId);
    }

    /**
     * Subclasses should override for whatever they need to perform.
     * This can be called for sync processing of task
     *
     * @abstract
     * @return mixed
     */
    abstract function perform();

    /**
     * Executes the task within the user's config and context.
     * The result or any thrown exception is redeemed to a FutureResult with the same async id.
     * Only to be called by CLI. Will error if called from a web process.
     */
    function execute() {
        verifyCallingFromCLI();

        $execStartTime = time();
        $future = new FutureResult($this->asyncId);
        try {
            WorkbenchConfig::destroy(); // destroy the WorkbenchConfig, if one happens to exist
            $_SERVER['HTTP_X_REQUEST_ID'] = $this->requestId; // reestablish the original requestId for logging
            $_COOKIE = $this->cookies;  // reestablish the user's cookies so they'll be picked up by new WorkbenchConfig, if required
            WorkbenchContext::establish($this->connConfig);
            WorkbenchContext::get()->agreeToTerms();

            workbenchLog(LOG_INFO, "FutureTaskExecuteStart", array(
                "async_id" =>  $this->asyncId,
                "source" => get_class($this),
                "measure.async.queue_time" => ($execStartTime - $this->enqueueTime) . "sec"));

            $future->redeem($this->perform());
        } catch (Exception $e) {
            $future->redeem($e);
        }

        workbenchLog(LOG_INFO, "FutureTaskExecuteEnd", array(
            "async_id" =>  $this->asyncId,
            "source" => get_class($this),
            "measure.async.exec_time" => (time() - $execStartTime) . "sec"));

        WorkbenchContext::get()->release();
        WorkbenchConfig::destroy();
        $_COOKIE = array();
    }

    /**
     * Dequeues the next task for processing. Blocks until $timeout is reached.
     * Only to be called by CLI. Will error if called from a web process.
     *
     * @static
     * @return FutureTask
     */
    public static function dequeue($timeout) {
        verifyCallingFromCLI();

        $blpop = redis()->blpop(self::QUEUE, $timeout);
        if (isset($blpop[1])) {
            $task = crypto_unserialize($blpop[1]);

            if (!redis()->exists(FUTURE_LOCK . $task->asyncId)) {
                workbenchLog(LOG_INFO, "FutureTaskGC", array(
                    "async_id" =>  $task->asyncId,
                    "request_id" =>  $task->requestId, // explicitly log here because not available in context yet
                    "source" => get_class($task),
                    "measure.async.gc.task" => 1 . "task"));
                throw new TimeoutException();
            }

            return $task;
        }

        throw new TimeoutException();
    }
}

/**
 * The promise of the result of a FutureTask.
 * This is returned immediately by FutureTask::enqueue()
 * as a handle for the caller to get the actual result once it has been redeemed.
 */
class FutureResult {

    const RESULT = "FUTURE_RESULT";

    private $asyncId;
    private $result;

    function __construct($asyncId) {
        $this->asyncId = $asyncId;
    }

    /**
     * Get the FutureResult associated with an asyncId.
     * Users can only get FutureResults of FutureTasks they previously enqueued.
     *
     * @static
     * @param $asyncId
     * @return FutureResult
     */
    public static function fromId($asyncId) {
        // check lock is there and is for this session
        $sid = crypto_unserialize(redis()->get(FUTURE_LOCK . $asyncId));
        if ($sid == null || $sid !== session_id()) {
            throw new UnknownAsyncIdException();
        }

        return new FutureResult($asyncId);
    }

    /**
     * Redeems the result (or exception) after async processing has completed.
     *
     * @param $result
     */
    function redeem($result) {
        verifyCallingFromCLI();
        $this->result = $result;
        redis()->rpush(self::RESULT . $this->asyncId, crypto_serialize($this->result));
    }

    /**
     * Gets the actual result when available.
     * If timeout is reached before actual result is redeemed, a TimeoutException will be thrown.
     * If the actual result is an Exception, that Exception will be thrown.
     *
     * @param $timeout
     * @return mixed
     * @throws TimeoutException
     * @throws
     */
    public function get($timeout) {
        $blpop = redis()->blpop(self::RESULT . $this->asyncId, $timeout);

        if (isset($blpop[1])) {
            $this->result = crypto_unserialize($blpop[1]);
        } else {
            throw new TimeoutException();
        }

        redis()->del(FUTURE_LOCK . $this->asyncId); // remove lock

        if ($this->result instanceof Exception) {
            throw $this->result;
        }

        return $this->result;
    }

    /**
     * Returns HTML and JavaScript snippet that can be rendered to the page
     * to call get() on this FutureResult until actual result redeemed.
     *
     * @return string
     */
    public function ajax() {
        ob_start();
        require "future_ajax.js.php";
        futureAjax($this->asyncId);
        $ajax = ob_get_contents();
        ob_end_clean();
        return $ajax;
    }

}

class TimeoutException extends Exception {}
class UnknownAsyncIdException extends Exception {}
?>


text:
package com.google.cloud.hadoop.testing;

import com.google.cloud.hadoop.util.EntriesCredentialConfiguration;
import com.google.cloud.hadoop.util.EntriesCredentialConfiguration.Entries;

import java.util.HashMap;
import java.util.Map;

/**
 * Utility methods for creating configuration objects for use in testing.
 */
public class EntriesCredentialConfigurationUtil {
  public static void addTestConfigurationSettings(Entries configuration) {
    configuration.set(EntriesCredentialConfiguration.BASE_KEY_PREFIX
        + EntriesCredentialConfiguration.ENABLE_SERVICE_ACCOUNTS_SUFFIX,
            "false");

    configuration.set(EntriesCredentialConfiguration.BASE_KEY_PREFIX
        + EntriesCredentialConfiguration.ENABLE_NULL_CREDENTIAL_SUFFIX, "true");
  }

  public static Entries getTestConfiguration() {
    Entries configuration = new TestEntries();
    addTestConfigurationSettings(configuration);
    return configuration;
  }

  /**
   * A class to hold Entries for EntriesCredentialConfiguration for testing.
   */
  public static class TestEntries implements Entries {
    private Map<String, Object> map = new HashMap<String, Object>();

    public void set(String key, String value) {
      map.put(key, value);
    }

    public String get(String key) {
      Object v = map.get(key);
      return (v == null) ? null : v.toString();
    }

    public void setBoolean(String key, boolean value) {
      Boolean b = Boolean.valueOf(value);
      map.put(key, b);
    }
  }
}


text:
package com.hazelcast.internal.metrics.impl;

import com.hazelcast.internal.metrics.Gauge;
import com.hazelcast.internal.metrics.MetricDescriptor;
import com.hazelcast.internal.metrics.MetricTarget;
import com.hazelcast.internal.metrics.ProbeUnit;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

import static java.util.Objects.requireNonNull;

/**
 * Default implementation of {@link MetricDescriptor} and
 * {@link MetricDescriptor}.
 */
@SuppressWarnings("checkstyle:MethodCount")
public final class MetricDescriptorImpl implements MetricDescriptor {
    private static final int INITIAL_TAG_CAPACITY = 4;
    private static final double GROW_FACTOR = 1.2D;
    private static final int INITIAL_STRING_CAPACITY = 64;

    private final LookupView lookupView = new LookupView();

    private Supplier<MetricDescriptorImpl> supplier;
    private String[] tags;
    private int tagPtr;
    private String prefix;
    private String metric;
    private String discriminator;
    private String discriminatorValue;
    private ProbeUnit unit;
    private Collection<MetricTarget> excludedTargets = MetricTarget.NONE_OF;

    public MetricDescriptorImpl(Supplier<MetricDescriptorImpl> supplier) {
        this.supplier = requireNonNull(supplier);

        tags = new String[INITIAL_TAG_CAPACITY * 2];
    }

    @Override
    @Nonnull
    public MetricDescriptorImpl withTag(String tag, String value) {
        ensureCapacity(tagPtr);

        tags[tagPtr] = requireNonNull(tag);
        tags[tagPtr + 1] = requireNonNull(value);
        tagPtr += 2;
        return this;
    }

    @Nullable
    @Override
    public String tagValue(String tag) {
        Objects.requireNonNull(tag);
        for (int i = 0; i < tagPtr; i += 2) {
            String tagStored = tags[i];
            String tagValue = tags[i + 1];
            if (tag.equals(tagStored)) {
                return tagValue;
            }
        }
        return null;
    }

    @Override
    @Nonnull
    public MetricDescriptorImpl withPrefix(String prefix) {
        this.prefix = prefix;
        return this;
    }

    @Override
    @Nonnull
    public MetricDescriptorImpl withMetric(String metric) {
        this.metric = metric;
        return this;
    }

    @Override
    @Nonnull
    public MetricDescriptorImpl withDiscriminator(String discriminatorTag, String discriminatorValue) {
        this.discriminator = discriminatorTag;
        this.discriminatorValue = discriminatorValue;
        return this;
    }

    @Override
    @Nonnull
    public MetricDescriptorImpl withUnit(ProbeUnit unit) {
        this.unit = unit;
        return this;
    }

    @Override
    @Nonnull
    public MetricDescriptorImpl copy() {
        MetricDescriptorImpl copy = supplier.get();
        copy.prefix = prefix;
        copy.metric = metric;
        copy.discriminator = discriminator;
        copy.discriminatorValue = discriminatorValue;
        copy.unit = unit;
        copy.excludedTargets = excludedTargets;
        copy.ensureCapacity(tagCount() << 1);
        readTags(copy::withTag);

        return copy;
    }

    @Override
    @Nonnull
    public MetricDescriptorImpl copy(MetricDescriptor descriptor) {
        reset();

        this.prefix = descriptor.prefix();
        this.metric = descriptor.metric();
        this.discriminator = descriptor.discriminator();
        this.discriminatorValue = descriptor.discriminatorValue();
        this.unit = descriptor.unit();
        this.excludedTargets = descriptor.excludedTargets();
        this.ensureCapacity(descriptor.tagCount() << 1);
        descriptor.readTags(this::withTag);

        return this;
    }

    @Nullable
    @Override
    public String prefix() {
        return prefix;
    }

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

    @Nullable
    @Override
    public String discriminator() {
        return discriminator;
    }

    @Nullable
    @Override
    public String discriminatorValue() {
        return discriminatorValue;
    }

    @Nullable
    @Override
    public ProbeUnit unit() {
        return unit;
    }

    @Override
    public int tagCount() {
        return tagPtr >> 1;
    }

    @Override
    public void readTags(BiConsumer<String, String> tagReader) {
        for (int i = 0; i < tagPtr; i += 2) {
            String tag = tags[i];
            String tagValue = tags[i + 1];
            tagReader.accept(tag, tagValue);
        }
    }

    @Override
    public String tag(int index) {
        index = index << 1;
        if (index < 0 || index >= tagPtr) {
            throw new IndexOutOfBoundsException();
        }

        return tags[index];
    }

    @Override
    public String tagValue(int index) {
        index = (index << 1) + 1;
        if (index < 0 || index >= tagPtr) {
            throw new IndexOutOfBoundsException();
        }

        return tags[index];
    }

    @Override
    @Nonnull
    public String metricString() {
        return buildMetricString(false);
    }

    private String buildMetricString(boolean includeExcludedTargets) {
        StringBuilder sb = new StringBuilder(INITIAL_STRING_CAPACITY).append('[');

        if (discriminatorValue != null) {
            sb.append(discriminator).append('=').append(discriminatorValue).append(',');
        }

        if (unit != null) {
            sb.append("unit=").append(unit.name().toLowerCase()).append(',');
        }

        if (metric != null) {
            sb.append("metric=");
            if (prefix != null) {
                sb.append(prefix).append('.');
            }
            sb.append(metric);
            sb.append(',');
        }

        for (int i = 0; i < tagPtr; i += 2) {
            String tag = tags[i];
            String tagValue = tags[i + 1];
            sb.append(tag).append('=').append(tagValue).append(',');
        }

        if (includeExcludedTargets) {
            sb.append("excludedTargets={");
            if (excludedTargets.isEmpty()) {
                sb.append('}');
            } else {
                for (MetricTarget target : excludedTargets) {
                    sb.append(target.name()).append(',');
                }
                sb.setCharAt(sb.length() - 1, '}');
            }
            sb.append(',');
        }

        if (sb.length() > 1) {
            sb.setCharAt(sb.length() - 1, ']');
        } else {
            sb.append(']');
        }

        return sb.toString();
    }

    @Nonnull
    @Override
    public Collection<MetricTarget> excludedTargets() {
        return excludedTargets;
    }

    @Override
    public boolean isTargetExcluded(MetricTarget target) {
        return excludedTargets.contains(target);
    }

    @Override
    public boolean isTargetIncluded(MetricTarget target) {
        return !isTargetExcluded(target);
    }

    @Override
    @Nonnull
    public MetricDescriptorImpl withExcludedTarget(MetricTarget target) {
        excludedTargets = MetricTarget.asSetWith(excludedTargets, target);
        return this;
    }

    @Override
    @Nonnull
    public MetricDescriptorImpl withIncludedTarget(MetricTarget target) {
        excludedTargets = MetricTarget.asSetWithout(excludedTargets, target);
        return this;
    }

    @Nonnull
    @Override
    public MetricDescriptorImpl withExcludedTargets(Collection<MetricTarget> excludedTargets) {
        this.excludedTargets = excludedTargets;
        return this;
    }

    LookupView lookupView() {
        return lookupView;
    }

    private void ensureCapacity(int tagPtr) {
        if (tagPtr < tags.length) {
            return;
        }

        int newCapacity = (int) Math.max(tagPtr, Math.ceil(tags.length * GROW_FACTOR));
        if (newCapacity % 2 != 0) {
            newCapacity++;
        }
        String[] newTags = new String[newCapacity];
        System.arraycopy(tags, 0, newTags, 0, tags.length);
        tags = newTags;
    }

    @Override
    @SuppressWarnings({"checkstyle:NPathComplexity", "checkstyle:CyclomaticComplexity"})
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        MetricDescriptorImpl that = (MetricDescriptorImpl) o;

        if (tagPtr != that.tagPtr) {
            return false;
        }
        if (unit != that.unit) {
            return false;
        }
        if (!Objects.equals(prefix, that.prefix)) {
            return false;
        }
        if (!Objects.equals(metric, that.metric)) {
            return false;
        }
        if (!Objects.equals(discriminatorValue, that.discriminatorValue)) {
            return false;
        }
        if (!Objects.equals(this.discriminator, that.discriminator)) {
            return false;
        }
        if (!Objects.equals(this.excludedTargets, that.excludedTargets)) {
            return false;
        }

        // since we already checked that the two descriptors have the same number
        // of tags, we can safely compare them from only one side but we need
        // to compare pairs. The order of tags doesn't matter.
        outer:
        for (int i = 0; i < tagPtr; i += 2) {
            String thisTag = tags[i];
            String thisTagValue = tags[i + 1];
            for (int j = 0; j < that.tagPtr; j += 2) {
                String thatTag = that.tags[j];
                String thatTagValue = that.tags[j + 1];
                if (thisTag.equals(thatTag) && thisTagValue.equals(thatTagValue)) {
                    continue outer;
                }
            }
            // no match
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int result = 0;
        for (int i = 0; i < tagPtr; i += 2) {
            String tag = tags[i];
            String tagValue = tags[i + 1];
            result += tag.hashCode() + 31 * tagValue.hashCode();
        }

        result = 31 * result + tagPtr;
        result = 31 * result + (prefix != null ? prefix.hashCode() : 0);
        result = 31 * result + (metric != null ? metric.hashCode() : 0);
        result = 31 * result + (discriminator != null ? discriminator.hashCode() : 0);
        result = 31 * result + (discriminatorValue != null ? discriminatorValue.hashCode() : 0);
        result = 31 * result + (unit != null ? unit.hashCode() : 0);
        result = 31 * result + excludedTargets.hashCode();

        return result;
    }

    @Override
    @Nonnull
    public MetricDescriptor reset() {
        prefix = null;
        metric = null;
        unit = null;
        tagPtr = 0;
        discriminator = null;
        discriminatorValue = null;
        Arrays.fill(tags, null);

        return this;
    }

    /**
     * Sets the supplier to the given one. Used by
     * {@link PoolingMetricDescriptorSupplier#close()} to ensure no leaking
     * is possible.
     *
     * @param supplier The supplier to set.
     */
    void setSupplier(Supplier<MetricDescriptorImpl> supplier) {
        this.supplier = requireNonNull(supplier);
    }

    @Override
    public String toString() {
        return buildMetricString(true);
    }

    /**
     * Reduced view of the {@link MetricDescriptorImpl}. Used for looking
     * up {@link Gauge}s.
     */
    public class LookupView {

        public MetricDescriptorImpl descriptor() {
            return MetricDescriptorImpl.this;
        }

        private String prefix() {
            return prefix;
        }

        private String metricName() {
            return metric;
        }

        private String discriminatorValue() {
            return discriminatorValue;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            LookupView that = (LookupView) o;

            if (!Objects.equals(prefix, that.prefix())) {
                return false;
            }
            if (!Objects.equals(metric, that.metricName())) {
                return false;
            }
            return Objects.equals(discriminatorValue, that.discriminatorValue());
        }

        @Override
        public int hashCode() {
            int result = prefix != null ? prefix.hashCode() : 0;
            result = 31 * result + (metric != null ? metric.hashCode() : 0);
            result = 31 * result + (discriminatorValue != null ? discriminatorValue.hashCode() : 0);
            result = 31 * result + (discriminatorValue != null ? discriminatorValue.hashCode() : 0);
            return result;
        }

        @Override
        public String toString() {
            return metricName();
        }
    }
}


text:
This is a bot to preserve the B1G logos for the Reddit [/r/place](https://www.reddit.com/r/place/) event of 2017 April Fools Day.

[Here's the current image.](https://raw.githubusercontent.com/sargunster/reddit-placebot/master/images/target.bmp)

The map currently contains Purdue, Illinois, and Minnesota. Feel free to PR for other B1G schools.

## Installation

You need to have [NodeJS installed](https://nodejs.org)

```
git clone https://github.com/sargunster/reddit-placebot
cd reddit-placebot
npm install
```

## Configuration

Change `users.example.json` to `users.json` and add your username and password
of your account and all your throwaways.

Skip to "Usage" if you're just trying to preserve the B1G schools.

## The target.bmp file

[The target is already configured with a few logos.](https://raw.githubusercontent.com/sargunster/reddit-placebot/master/images/target.bmp)
If you want to modify the target, follow the below instructions.

The target file must meet the following requirements:

  - Format: BMP
  - Dimensions: 1000x1000
  - Compression: NONE! Should weight about 3mb, 4 bytes per color
  - Colors: exactly the same colors used in the board
  - Transparency: Color `#ff00ffff` is considered transparent (a bright purple color), and will be ignored by the bots

You can check the colors on `colors.js`, but is easier to
import `board.example.bmp` to your image editor, and use the eyedropper tool
from there. You can use that image as a template and go from there too, covering
parts that you don't use in `#ff00ffff`

With an advanced image editor is recommended to have the board in a separate
layer so you actually know what you're modifying.

## Target Drawing

The bot downloads the board each time it's time to draw, so it only changes
the necessary pixels that don't match the target.

### Remote (for multiple people)

You can configure the target to be downloaded from a remote image by
settin on `config.js`:

- `autoupdateRemoteTarget: true`
- `REMOTE_TARGET_URL: "http://example.com/remote_target.bmp"`

The image will be downloaded before paining and saved to `target.bmp`.

### Local (just for your own bots)

Just use the file `target.bmp` and set `autoupdateRemoteTarget: false` on `config.js`.

## Bundle up changes

If you want to wait until multiple users are available to paint and do the
changes all at the same time, change the config:

- *bundleAccounts*: <Number 1-Infinity>

## Usage

```
  npm run start
```

It'll keep keep drawing forever and if it can't draw anymore it's gonna
wait until something breaks and fix it.

## Testing

LOL

You can `npm run watch`, but that's about it.

## Similar Projects

Thanks to [trosh/rplace](https://github.com/trosh/rplace) to figure out how to actually read the bitmap from the server. I just ported that to Node.

## License

The Reddit Placebot is released under the [MIT License](http://www.opensource.org/licenses/MIT).


text:
<?php

include_once 'common.php';

$room = filter_input(INPUT_GET, 'room', FILTER_VALIDATE_REGEXP, array('options' => array('default' => '', 'regexp' => "/\w+/")));
$lastId = filter_input(INPUT_GET, 'lastId', FILTER_VALIDATE_INT, array('options' => array('default' => 0)));

taab_echo_backend($lastId, $room);
?>


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.Request;
import com.amazonaws.services.ec2.model.transform.CreateNetworkInterfaceRequestMarshaller;

/**
 * Container for the parameters to the {@link com.amazonaws.services.ec2.AmazonEC2#createNetworkInterface(CreateNetworkInterfaceRequest) CreateNetworkInterface operation}.
 *

 * Creates a network interface in the specified subnet.
 *

 *

 * For more information about network interfaces, see
 *  Elastic Network Interfaces
 * in the Amazon Elastic Compute Cloud User Guide .
 *

 *
 * @see com.amazonaws.services.ec2.AmazonEC2#createNetworkInterface(CreateNetworkInterfaceRequest)
 */
public class CreateNetworkInterfaceRequest extends AmazonWebServiceRequest implements Serializable, Cloneable, DryRunSupportedRequest<CreateNetworkInterfaceRequest> {

    /**
     * The ID of the subnet to associate with the network interface.
     */
    private String subnetId;

    /**
     * A description for the network interface.
     */
    private String description;

    /**
     * The primary private IP address of the network interface. If you don't
     * specify an IP address, Amazon EC2 selects one for you from the subnet
     * range. If you specify an IP address, you cannot indicate any IP
     * addresses specified in privateIpAddresses as primary
     * (only one IP address can be designated as primary).
     */
    private String privateIpAddress;

    /**
     * The IDs of one or more security groups.
     */
    private com.amazonaws.internal.ListWithAutoConstructFlag<String> groups;

    /**
     * One or more private IP addresses.
     */
    private com.amazonaws.internal.ListWithAutoConstructFlag<PrivateIpAddressSpecification> privateIpAddresses;

    /**
     * The number of secondary private IP addresses to assign to a network
     * interface. When you specify a number of secondary IP addresses, Amazon
     * EC2 selects these IP addresses within the subnet range. You can't
     * specify this option and specify more than one private IP address using
     * privateIpAddresses.
The number of IP addresses you can
     * assign to a network interface varies by instance type. For more
     * information, see Private
     * IP Addresses Per ENI Per Instance Type in the Amazon Elastic
     * Compute Cloud User Guide.
     */
    private Integer secondaryPrivateIpAddressCount;

    /**
     * The ID of the subnet to associate with the network interface.
     *
     * @return The ID of the subnet to associate with the network interface.
     */
    public String getSubnetId() {
        return subnetId;
    }

    /**
     * The ID of the subnet to associate with the network interface.
     *
     * @param subnetId The ID of the subnet to associate with the network interface.
     */
    public void setSubnetId(String subnetId) {
        this.subnetId = subnetId;
    }

    /**
     * The ID of the subnet to associate with the network interface.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param subnetId The ID of the subnet to associate with the network interface.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateNetworkInterfaceRequest withSubnetId(String subnetId) {
        this.subnetId = subnetId;
        return this;
    }

    /**
     * A description for the network interface.
     *
     * @return A description for the network interface.
     */
    public String getDescription() {
        return description;
    }

    /**
     * A description for the network interface.
     *
     * @param description A description for the network interface.
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * A description for the network interface.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param description A description for the network interface.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateNetworkInterfaceRequest withDescription(String description) {
        this.description = description;
        return this;
    }

    /**
     * The primary private IP address of the network interface. If you don't
     * specify an IP address, Amazon EC2 selects one for you from the subnet
     * range. If you specify an IP address, you cannot indicate any IP
     * addresses specified in privateIpAddresses as primary
     * (only one IP address can be designated as primary).
     *
     * @return The primary private IP address of the network interface. If you don't
     *         specify an IP address, Amazon EC2 selects one for you from the subnet
     *         range. If you specify an IP address, you cannot indicate any IP
     *         addresses specified in privateIpAddresses as primary
     *         (only one IP address can be designated as primary).
     */
    public String getPrivateIpAddress() {
        return privateIpAddress;
    }

    /**
     * The primary private IP address of the network interface. If you don't
     * specify an IP address, Amazon EC2 selects one for you from the subnet
     * range. If you specify an IP address, you cannot indicate any IP
     * addresses specified in privateIpAddresses as primary
     * (only one IP address can be designated as primary).
     *
     * @param privateIpAddress The primary private IP address of the network interface. If you don't
     *         specify an IP address, Amazon EC2 selects one for you from the subnet
     *         range. If you specify an IP address, you cannot indicate any IP
     *         addresses specified in privateIpAddresses as primary
     *         (only one IP address can be designated as primary).
     */
    public void setPrivateIpAddress(String privateIpAddress) {
        this.privateIpAddress = privateIpAddress;
    }

    /**
     * The primary private IP address of the network interface. If you don't
     * specify an IP address, Amazon EC2 selects one for you from the subnet
     * range. If you specify an IP address, you cannot indicate any IP
     * addresses specified in privateIpAddresses as primary
     * (only one IP address can be designated as primary).
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param privateIpAddress The primary private IP address of the network interface. If you don't
     *         specify an IP address, Amazon EC2 selects one for you from the subnet
     *         range. If you specify an IP address, you cannot indicate any IP
     *         addresses specified in privateIpAddresses as primary
     *         (only one IP address can be designated as primary).
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateNetworkInterfaceRequest withPrivateIpAddress(String privateIpAddress) {
        this.privateIpAddress = privateIpAddress;
        return this;
    }

    /**
     * The IDs of one or more security groups.
     *
     * @return The IDs of one or more security groups.
     */
    public java.util.List<String> getGroups() {
        if (groups == null) {
              groups = new com.amazonaws.internal.ListWithAutoConstructFlag<String>();
              groups.setAutoConstruct(true);
        }
        return groups;
    }

    /**
     * The IDs of one or more security groups.
     *
     * @param groups The IDs of one or more security groups.
     */
    public void setGroups(java.util.Collection<String> groups) {
        if (groups == null) {
            this.groups = null;
            return;
        }
        com.amazonaws.internal.ListWithAutoConstructFlag<String> groupsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(groups.size());
        groupsCopy.addAll(groups);
        this.groups = groupsCopy;
    }

    /**
     * The IDs of one or more security groups.
     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setGroups(java.util.Collection)} or {@link
     * #withGroups(java.util.Collection)} if you want to override the
     * existing values.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param groups The IDs of one or more security groups.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateNetworkInterfaceRequest withGroups(String... groups) {
        if (getGroups() == null) setGroups(new java.util.ArrayList<String>(groups.length));
        for (String value : groups) {
            getGroups().add(value);
        }
        return this;
    }

    /**
     * The IDs of one or more security groups.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param groups The IDs of one or more security groups.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateNetworkInterfaceRequest withGroups(java.util.Collection<String> groups) {
        if (groups == null) {
            this.groups = null;
        } else {
            com.amazonaws.internal.ListWithAutoConstructFlag<String> groupsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<String>(groups.size());
            groupsCopy.addAll(groups);
            this.groups = groupsCopy;
        }

        return this;
    }

    /**
     * One or more private IP addresses.
     *
     * @return One or more private IP addresses.
     */
    public java.util.List<PrivateIpAddressSpecification> getPrivateIpAddresses() {
        if (privateIpAddresses == null) {
              privateIpAddresses = new com.amazonaws.internal.ListWithAutoConstructFlag<PrivateIpAddressSpecification>();
              privateIpAddresses.setAutoConstruct(true);
        }
        return privateIpAddresses;
    }

    /**
     * One or more private IP addresses.
     *
     * @param privateIpAddresses One or more private IP addresses.
     */
    public void setPrivateIpAddresses(java.util.Collection<PrivateIpAddressSpecification> privateIpAddresses) {
        if (privateIpAddresses == null) {
            this.privateIpAddresses = null;
            return;
        }
        com.amazonaws.internal.ListWithAutoConstructFlag<PrivateIpAddressSpecification> privateIpAddressesCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<PrivateIpAddressSpecification>(privateIpAddresses.size());
        privateIpAddressesCopy.addAll(privateIpAddresses);
        this.privateIpAddresses = privateIpAddressesCopy;
    }

    /**
     * One or more private IP addresses.
     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setPrivateIpAddresses(java.util.Collection)} or
     * {@link #withPrivateIpAddresses(java.util.Collection)} if you want to
     * override the existing values.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param privateIpAddresses One or more private IP addresses.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateNetworkInterfaceRequest withPrivateIpAddresses(PrivateIpAddressSpecification... privateIpAddresses) {
        if (getPrivateIpAddresses() == null) setPrivateIpAddresses(new java.util.ArrayList<PrivateIpAddressSpecification>(privateIpAddresses.length));
        for (PrivateIpAddressSpecification value : privateIpAddresses) {
            getPrivateIpAddresses().add(value);
        }
        return this;
    }

    /**
     * One or more private IP addresses.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param privateIpAddresses One or more private IP addresses.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateNetworkInterfaceRequest withPrivateIpAddresses(java.util.Collection<PrivateIpAddressSpecification> privateIpAddresses) {
        if (privateIpAddresses == null) {
            this.privateIpAddresses = null;
        } else {
            com.amazonaws.internal.ListWithAutoConstructFlag<PrivateIpAddressSpecification> privateIpAddressesCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<PrivateIpAddressSpecification>(privateIpAddresses.size());
            privateIpAddressesCopy.addAll(privateIpAddresses);
            this.privateIpAddresses = privateIpAddressesCopy;
        }

        return this;
    }

    /**
     * The number of secondary private IP addresses to assign to a network
     * interface. When you specify a number of secondary IP addresses, Amazon
     * EC2 selects these IP addresses within the subnet range. You can't
     * specify this option and specify more than one private IP address using
     * privateIpAddresses.
The number of IP addresses you can
     * assign to a network interface varies by instance type. For more
     * information, see Private
     * IP Addresses Per ENI Per Instance Type in the Amazon Elastic
     * Compute Cloud User Guide.
     *
     * @return The number of secondary private IP addresses to assign to a network
     *         interface. When you specify a number of secondary IP addresses, Amazon
     *         EC2 selects these IP addresses within the subnet range. You can't
     *         specify this option and specify more than one private IP address using
     *         privateIpAddresses.
The number of IP addresses you can
     *         assign to a network interface varies by instance type. For more
     *         information, see Private
     *         IP Addresses Per ENI Per Instance Type in the Amazon Elastic
     *         Compute Cloud User Guide.
     */
    public Integer getSecondaryPrivateIpAddressCount() {
        return secondaryPrivateIpAddressCount;
    }

    /**
     * The number of secondary private IP addresses to assign to a network
     * interface. When you specify a number of secondary IP addresses, Amazon
     * EC2 selects these IP addresses within the subnet range. You can't
     * specify this option and specify more than one private IP address using
     * privateIpAddresses.
The number of IP addresses you can
     * assign to a network interface varies by instance type. For more
     * information, see Private
     * IP Addresses Per ENI Per Instance Type in the Amazon Elastic
     * Compute Cloud User Guide.
     *
     * @param secondaryPrivateIpAddressCount The number of secondary private IP addresses to assign to a network
     *         interface. When you specify a number of secondary IP addresses, Amazon
     *         EC2 selects these IP addresses within the subnet range. You can't
     *         specify this option and specify more than one private IP address using
     *         privateIpAddresses.
The number of IP addresses you can
     *         assign to a network interface varies by instance type. For more
     *         information, see Private
     *         IP Addresses Per ENI Per Instance Type in the Amazon Elastic
     *         Compute Cloud User Guide.
     */
    public void setSecondaryPrivateIpAddressCount(Integer secondaryPrivateIpAddressCount) {
        this.secondaryPrivateIpAddressCount = secondaryPrivateIpAddressCount;
    }

    /**
     * The number of secondary private IP addresses to assign to a network
     * interface. When you specify a number of secondary IP addresses, Amazon
     * EC2 selects these IP addresses within the subnet range. You can't
     * specify this option and specify more than one private IP address using
     * privateIpAddresses.
The number of IP addresses you can
     * assign to a network interface varies by instance type. For more
     * information, see Private
     * IP Addresses Per ENI Per Instance Type in the Amazon Elastic
     * Compute Cloud User Guide.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param secondaryPrivateIpAddressCount The number of secondary private IP addresses to assign to a network
     *         interface. When you specify a number of secondary IP addresses, Amazon
     *         EC2 selects these IP addresses within the subnet range. You can't
     *         specify this option and specify more than one private IP address using
     *         privateIpAddresses.
The number of IP addresses you can
     *         assign to a network interface varies by instance type. For more
     *         information, see Private
     *         IP Addresses Per ENI Per Instance Type in the Amazon Elastic
     *         Compute Cloud User Guide.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public CreateNetworkInterfaceRequest withSecondaryPrivateIpAddressCount(Integer secondaryPrivateIpAddressCount) {
        this.secondaryPrivateIpAddressCount = secondaryPrivateIpAddressCount;
        return this;
    }

    /**
     * This method is intended for internal use only.
     * Returns the marshaled request configured with additional parameters to
     * enable operation dry-run.
     */
    @Override
    public Request<CreateNetworkInterfaceRequest> getDryRunRequest() {
        Request<CreateNetworkInterfaceRequest> request = new CreateNetworkInterfaceRequestMarshaller().marshall(this);
        request.addParameter("DryRun", Boolean.toString(true));
        return request;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getSubnetId() != null) sb.append("SubnetId: " + getSubnetId() + ",");
        if (getDescription() != null) sb.append("Description: " + getDescription() + ",");
        if (getPrivateIpAddress() != null) sb.append("PrivateIpAddress: " + getPrivateIpAddress() + ",");
        if (getGroups() != null) sb.append("Groups: " + getGroups() + ",");
        if (getPrivateIpAddresses() != null) sb.append("PrivateIpAddresses: " + getPrivateIpAddresses() + ",");
        if (getSecondaryPrivateIpAddressCount() != null) sb.append("SecondaryPrivateIpAddressCount: " + getSecondaryPrivateIpAddressCount() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getSubnetId() == null) ? 0 : getSubnetId().hashCode());
        hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
        hashCode = prime * hashCode + ((getPrivateIpAddress() == null) ? 0 : getPrivateIpAddress().hashCode());
        hashCode = prime * hashCode + ((getGroups() == null) ? 0 : getGroups().hashCode());
        hashCode = prime * hashCode + ((getPrivateIpAddresses() == null) ? 0 : getPrivateIpAddresses().hashCode());
        hashCode = prime * hashCode + ((getSecondaryPrivateIpAddressCount() == null) ? 0 : getSecondaryPrivateIpAddressCount().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof CreateNetworkInterfaceRequest == false) return false;
        CreateNetworkInterfaceRequest other = (CreateNetworkInterfaceRequest)obj;

        if (other.getSubnetId() == null ^ this.getSubnetId() == null) return false;
        if (other.getSubnetId() != null && other.getSubnetId().equals(this.getSubnetId()) == false) return false;
        if (other.getDescription() == null ^ this.getDescription() == null) return false;
        if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false;
        if (other.getPrivateIpAddress() == null ^ this.getPrivateIpAddress() == null) return false;
        if (other.getPrivateIpAddress() != null && other.getPrivateIpAddress().equals(this.getPrivateIpAddress()) == false) return false;
        if (other.getGroups() == null ^ this.getGroups() == null) return false;
        if (other.getGroups() != null && other.getGroups().equals(this.getGroups()) == false) return false;
        if (other.getPrivateIpAddresses() == null ^ this.getPrivateIpAddresses() == null) return false;
        if (other.getPrivateIpAddresses() != null && other.getPrivateIpAddresses().equals(this.getPrivateIpAddresses()) == false) return false;
        if (other.getSecondaryPrivateIpAddressCount() == null ^ this.getSecondaryPrivateIpAddressCount() == null) return false;
        if (other.getSecondaryPrivateIpAddressCount() != null && other.getSecondaryPrivateIpAddressCount().equals(this.getSecondaryPrivateIpAddressCount()) == false) return false;
        return true;
    }

    @Override
    public CreateNetworkInterfaceRequest clone() {

            return (CreateNetworkInterfaceRequest) super.clone();
    }

}