text:
"""
# Meta-info

Author: Nelson Brochado

Created: 01/08/2015

Updated: 28/09/2017

# Description

## Red-black tree property

1. Every node is either red or black.

2. The root is black.

3. Every NIL or leaf node is black.

4. If a node is red, then both its children are black, which also means that
there cannot be two red nodes in a row.

5. For every node x, each path from x to its descendant leaves has the same
number of black nodes.

## Lemma

The height h(x) of a red-black tree with n internal nodes is at most

    2 * log₂(n + 1),

that is,

    h(x) <= 2 * log₂(n + 1),

which is equivalent to

    h(x) / 2 <= log₂(n + 1),

which is equivalent to

    n >= 2^(h(x) / 2) - 1.

To possibly better understand the previous statements, we can perform the
reversed reasoning:

    n >= 2^(h(x) / 2) - 1 ⇔

    n + 1 >= 2^(h(x) / 2)

Now, we log both parts:

    log₂(n + 1) >= log₂(2^(h(x) / 2)) ⇔

    log₂(n + 1) >= h(x) / 2 * log₂(2) ⇔

    log₂(n + 1) >= h(x) / 2 * 1 ⇔

    2 * log₂(n + 1) >= h(x)

### Proof

We want to prove (by induction) that, for all x, size(x) >= 2^bh(x) - 1.

1. Base case: x is a leaf, so size(x) = 0 and bh(x) = 0.

2. Induction hypothesis: consider y₁, y₂, and x such that

    parent(y₁) = parent(y₂) = x,

and assume () that

    size(y₁) >= 2^bh(y₁) - 1, and
    size(y₂) >= 2^bh(y₂) - 1.

We want to prove: size(x) >= 2^bh(x) - 1.

1.3. Induction step

size(x) = size(y₁) + size(y₂) + 1 >= (2^bh(y₁) - 1) + (2^bh(y₂) - 1) + 1

Since

        +---------------------------------+
        | bh(y),      if color(y) = red   |
bh(x) = |                                 |
        | bh(y) + 1,  if color(y) = black |
        +---------------------------------+

size(x) >= (2^(bh(x) - 1) - 1) + (2^(bh(x) - 1) - 1) + 1 = (2^bh(x) - 1).

Since every red node has black children, in every path from x to a leaf
node, at least half the nodes are black, thus

    bh(x) >= h(x) / 2.

So: n = size(x) >= 2^(h(x) / 2) - 1.

Therefore: h(x) <= 2 * log₂(n + 1).

## Red-black tree operations

A red-black tree works as a binary-search tree for search, insert, etc, so the
complexity of those operations is T(n) = O(h), that is T(n) = O(log₂(n)), which
is also the worst case complexity.

# References

- https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
- Slides by prof. A. Carzaniga
- Chapter 13 of Introduction to Algorithms (3rd ed.) by CLRS
"""

import math

from ands.ds.BST import BST, _BSTNode, is_bst

__all__ = ["RBT", "is_rbt"]

RED = "RED"
BLACK = "BLACK"

class _RBTNode(_BSTNode):
    """Class to represent a node of a RBT."""

    def __init__(self, key, color=BLACK, parent=None, left=None, right=None):
        _BSTNode.__init__(self, key, parent, left, right)
        self.color = color

class RBT(BST):
    """Red-black tree, which is a self-balancing binary-search tree.

    Since it's self-balancing operations such as inserting, searching or
    deletion all take O(log₂(n))."""

    def __init__(self):
        BST.__init__(self)

    def insert(self, key: object) -> None:
        """Inserts key into this RBT.

        This operation is similar to the insert operation of a classical BST,
        but, in this case, the red-black tree property must be maintained, so
        additional work is needed.

        There are several cases of inserting into a RBT to handle:

        1. key is the root node.

        2. key.parent is BLACK.

        3. key.parent and the uncle of key are RED.

        The uncle of key will be the left child of key.parent.parent, if
        key.parent is the right child of key.parent.parent, otherwise the uncle
        will be the right child of key.parent.parent.

        4. key.parent is RED, but key.uncle is BLACK (or None).

        key.grandparent exists because key.parent is RED.

            4.1. key is added to the right of a left child of key.parent.parent
            (grandparent).

            4.2. or key is added to the left of a right child of
            key.parent.parent.

            4.3. key is added to the left of a left child of key.parent.parent.

            4.4. or key is added to the right of a right child of
            key.parent.parent.

        _fix_insertion handles these cases in the same order as above.

        Time complexity: O(log₂(n))."""
        assert is_rbt(self)

        if key is None:
            raise ValueError("key cannot be None")

        key_node = _RBTNode(key)

        c = self._root  # Current node.
        p = None  # Current node's parent.

        while c is not None:
            p = c
            if key_node.key < c.key:
                c = c.left
            else:  # key.key >= c.key
                c = c.right

        key_node.parent = p

        # while loop was not executed even once.
        # Case 1: node is inserted as root.
        if p is None:
            self._root = key_node
        elif p.key > key_node.key:
            p.left = key_node
        else:  # p.key < key.key
            p.right = key_node

        key_node.color = RED
        self._n += 1
        self._fix_insertion(key_node)

        assert is_rbt(self)

    def _fix_insertion(self, u: _RBTNode) -> None:
        # u is the root and we color it BLACK.
        if u.parent is None:
            u.color = BLACK

        elif u.parent.color == BLACK:
            return

        elif (u.parent.color == RED and
              (u.uncle is not None and u.uncle.color == RED)):
            u.parent.color = BLACK
            u.uncle.color = BLACK
            u.grandparent.color = RED
            self._fix_insertion(u.grandparent)

        elif (u.parent.color == RED and
              (u.uncle is None or u.uncle.color == BLACK)):

            # u is added as a right child to a node that is the left child.
            if u.parent.is_left_child() and u.is_right_child():

                # left_rotation does not violate the property: all paths from
                # any given node to its leaf nodes contain the same number of
                # black nodes.
                self._left_rotate(u.parent)

                # With the previous _left_rotate call, u.parent has become the
                # left child of u, or, u bas become the parent of what before
                # was u.parent.
                #
                # We can pass to case 5, where we have 2 red nodes in a row,
                # specifically, u.parent and u, which are both left children of
                # their parents.

                self._fix_insertion(u.left)

            # u is added as a left child to a node that is the right child.
            elif u.parent.is_right_child() and u.is_left_child():
                self._right_rotate(u.parent)
                self._fix_insertion(u.right)

            # u is added as a left child to a node that is the left child.
            elif u.parent.is_left_child() and u.is_left_child():
                # Note: grandparent is known to be black, since its former child
                # could not have been RED without violating property 4.
                self._right_rotate(u.grandparent)
                u.parent.color = BLACK
                u.parent.right.color = RED

            # u is added as a right child to a node that is the right child.
            elif u.parent.is_right_child() and u.is_right_child():
                self._left_rotate(u.grandparent)
                u.parent.color = BLACK
                u.parent.left.color = RED

            else:
                assert False

    def _left_rotate(self, u: _RBTNode) -> _RBTNode:
        """Left rotates the subtree rooted at node u.

        Returns the node which is at the previous position of u, that is it
        returns the parent of u.

        Time complexity: O(1)."""
        assert u.has_right_child()

        u.right.parent = u.parent

        # Only the root has a None parent.
        if not u.has_parent():
            self._root = u.right

        # Checking if u is a left or a right child, in order to set the new left
        # or right child respectively of its parent.
        elif u.is_left_child():
            u.parent.left = u.right
        else:
            u.parent.right = u.right

        u.parent = u.right

        # The new right child of u becomes what is the left child of its
        # previous right child.
        u.right = u.parent.left

        # Set u to be the parent of its new right child.
        if u.has_right_child():
            u.right.parent = u

        # Set u to be the new left child of its new parent.
        u.parent.left = u
        return u.parent

    def _right_rotate(self, u: _RBTNode) -> _RBTNode:
        """Right rotates the subtree rooted at node u.

        Time complexity: O(1)."""
        assert u.has_left_child()

        u.left.parent = u.parent

        if not u.has_parent():
            self._root = u.left
        elif u.is_left_child():
            u.parent.left = u.left
        else:
            u.parent.right = u.left

        u.parent = u.left
        u.left = u.parent.right

        if u.has_left_child():
            u.left.parent = u

        u.parent.right = u
        return u.parent

    def delete(self, key: object) -> None:
        """Delete key from this RBT object.

        Time complexity: O(log₂(n))."""
        assert is_rbt(self)

        # A few checks of the inputs given.
        if key is None:
            raise ValueError("key cannot be None")

        key_node = self._search_key_iteratively(key, self._root)
        if key_node is None:
            raise LookupError("key not in this BST")

        # If key has 2 non-leaf children, then replace key with its successor.
        # Note: we exchange also the colors of key and its successor.
        if key_node.has_left_child() and key_node.has_right_child():
            s = self._successor(key_node)
            self._switch(key_node, s)
            key_node.color, s.color = s.color, key_node.color

        # At least one of the children must be None. Particularly, if key was
        # exchanged with its successor, key now should not have a left child.
        assert not key_node.has_left_child() or not key_node.has_right_child()

        # At this point key has at most 1 child.
        # Keep in mind this when reading the next cases!

        # If key is a red node and it has a child, we simply replace it with its
        # child c, which must be black by property 4.

        # This can only occur when key has 2 leaf children, because if key had a
        # black non-leaf child on one side, but just a leaf child on the other
        # side, then the count of black nodes on both sides would be different,
        # thus the tree would violate property 5.
        if key_node.color == RED:

            # A few checks while in alpha stage.
            assert (not key_node.has_left_child() and
                    not key_node.has_right_child())
            assert key_node != self._root

            if key_node.is_left_child():
                key_node.parent.left = None
            else:
                key_node.parent.right = None

        else:  # key.color == BLACK

            # One of the children of key is red.

            # Simply removing key could break properties 4, i.e., both children
            # of every red node are black, because key.parent could be red, and
            # 5, i.e. all paths from any given node to its leaf nodes contain
            # the same number of black nodes), but if we repaint c (the child)
            # BLACK, both of these properties are preserved.

            if key_node.has_left_child() and key_node.left.color == RED:
                if self._root != key_node:
                    if key_node.is_left_child():
                        key_node.parent.left = key_node.left
                    else:
                        key_node.parent.right = key_node.left

                key_node.left.parent = key_node.parent
                key_node.left.color = BLACK

                if self._root == key_node:
                    self._root = key_node.left

            elif key_node.has_right_child() and key_node.right.color == RED:
                if self._root != key_node:
                    if key_node.is_left_child():
                        key_node.parent.left = key_node.right
                    else:
                        key_node.parent.right = key_node.right

                key_node.right.parent = key_node.parent
                key_node.right.color = BLACK

                if self._root == key_node:
                    self._root = key_node.right
            else:
                # This the complex case: both key and c (the child) are BLACK.

                # This can only occur when deleting a black node which has 2
                # leaf children, because if the black node key had a black
                # non-leaf child on one side but just a leaf child on the other
                # side, then the count of black nodes on both sides would be
                # different, thus the tree would have been an invalid red–black
                # tree by violation of property 5.
                assert (not key_node.has_left_child() and
                        not key_node.has_right_child())

                # 6 cases
                if self._root != key_node:

                    assert key_node.sibling is not None

                    # Note: key.sibling cannot be None, because otherwise the
                    # subtree containing it would have fewer black nodes than
                    # the subtree containing key.
                    #
                    # Specifically, the subtree containing key would have a
                    # black height of 2, whereas the one containing the sibling
                    # would have a black height of 1.
                    self._delete_case_1(key_node)

                    # We begin by replacing key with its child c.
                    # Note: both children of key are leaf children.
                    if key_node.is_left_child():
                        key_node.parent.left = None
                    else:
                        key_node.parent.right = None

                else:
                    self._root = None

        self._n -= 1

        assert is_rbt(self)

    def _delete_case_1(self, u: _RBTNode) -> None:
        # This check is necessary because this function is also called from the
        # _delete_case_3 function.
        if u.parent is not None:
            self._delete_case_2(u)

    def _delete_case_2(self, u: _RBTNode) -> None:
        if u.sibling.color == RED:

            assert u.parent.color == BLACK

            u.sibling.color = BLACK
            u.parent.color = RED

            if u.is_left_child():
                self._left_rotate(u.parent)
            else:
                self._right_rotate(u.parent)

            assert u.sibling.color == BLACK

        self._delete_case_3(u)

    def _delete_case_3(self, u: _RBTNode) -> None:
        # Not sure if the children of u.sibling can be None.
        if (u.parent.color == BLACK and u.sibling.color == BLACK and
                ((u.sibling.left and u.sibling.left.color == BLACK) or
                 not u.sibling.left) and
                ((u.sibling.right and u.sibling.right.color == BLACK) or
                 not u.sibling.right)):

            u.sibling.color = RED
            self._delete_case_1(u.parent)
        else:
            self._delete_case_4(u)

    def _delete_case_4(self, u: _RBTNode) -> None:
        # Not sure if the children of u.sibling can be None.
        if (u.parent.color == RED and u.sibling.color == BLACK and
                ((u.sibling.left and u.sibling.left.color == BLACK) or
                 not u.sibling.left) and
                ((u.sibling.right and u.sibling.right.color == BLACK) or
                 not u.sibling.right)):

            u.sibling.color = RED
            u.parent.color = BLACK
        else:
            self._delete_case_5(u)

    def _delete_case_5(self, u: _RBTNode) -> None:
        assert u.sibling is not None

        if u.sibling.color == BLACK:
            if (u.is_left_child() and
                    (not u.sibling.right or u.sibling.right.color == BLACK) and
                    u.sibling.left.color == RED):

                u.sibling.color = RED
                u.sibling.left.color = BLACK
                self._right_rotate(u.sibling)

            elif (u.is_right_child() and
                  (not u.sibling.left or u.sibling.left.color == BLACK) and
                  u.sibling.right.color == RED):

                u.sibling.color = RED
                u.sibling.right.color = BLACK
                self._left_rotate(u.sibling)

        self._delete_case_6(u)

    def _delete_case_6(self, u: _RBTNode) -> None:
        assert u.sibling is not None

        u.sibling.color, u.parent.color = u.parent.color, u.sibling.color

        if u.is_left_child():
            assert u.sibling.right
            u.sibling.right.color = BLACK
            self._left_rotate(u.parent)
        else:
            assert u.sibling.left
            u.sibling.left.color = BLACK
            self._right_rotate(u.parent)

    def remove_max(self) -> None:
        """Removes the greatest element from self.

        Time complexity: O(log₂(n))."""
        assert is_rbt(self)
        if self._root is not None:
            m = self.maximum()
            assert m is not None
            self.delete(m)
            assert is_rbt(self)

    def remove_min(self) -> None:
        """Removes the smallest element from self.

        Time complexity: O(log₂(n))."""
        assert is_rbt(self)
        if self._root is not None:
            m = self.minimum()
            assert m is not None
            self.delete(m)
            assert is_rbt(self)

def black_height(n: _RBTNode) -> int:
    """Returns the black-height of the node n."""
    if n is None:
        return 1

    if not isinstance(n, _RBTNode):
        raise TypeError("n must be an instance of _RBTNode")

    left_bh = black_height(n.left)
    right_bh = black_height(n.right)

    if left_bh != right_bh:
        return -1
    else:
        return left_bh + (1 if n.color == BLACK else 0)

def upper_bound_height(t: RBT) -> bool:
    """Returns true if the height of the red-black tre t is bounded above by
    log₂(n + 1)."""
    return t.height() <= 2 * math.log2(t.size + 1)

def is_rbt(t: RBT) -> bool:
    """Returns true if t is a valid RBT object, false otherwise."""

    def are_all_red_or_black(t: RBT) -> bool:
        """Returns true if all colors are either RED or BLACK."""

        def h(n: _RBTNode) -> bool:
            if n is not None:
                if n.color != BLACK and n.color != RED:
                    return False
                return h(n.right) and h(n.left)
            return True

        return h(t._root)

    def is_root_black(t: RBT) -> bool:
        """Returns true if the root is BLACK (or it is None), false
        otherwise."""
        if t._root is not None:
            return t._root.color == BLACK
        return True

    def has_not_consecutive_red_nodes(t: RBT) -> bool:
        def h(n: _RBTNode) -> bool:
            if n is not None:
                if (n.parent is not None and n.color == RED and
                        n.parent.color == RED):
                    return False
                if n.parent is None and n.color == RED:
                    return False
                return h(n.left) and h(n.right)
            return True

        return h(t._root)

    def all_paths_have_same_black_height(t: RBT) -> bool:
        return black_height(t._root) != -1

    def are_all_rbt_nodes(t: RBT) -> bool:
        def h(n: _RBTNode) -> bool:
            if n is not None:
                if not isinstance(n, _RBTNode):
                    return False
                return h(n.left) and h(n.right)
            return True

        return h(t._root)

    if not is_bst(t):
        return False

    if not isinstance(t, RBT):
        return False

    if not are_all_rbt_nodes(t):
        return False

    if not upper_bound_height(t):
        return False

    return (are_all_red_or_black(t) and
            is_root_black(t) and
            has_not_consecutive_red_nodes(t) and
            all_paths_have_same_black_height(t))


text:
package com.google.common.jimfs;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * Immutable representation of a file name. Used both for the name components of paths and as the
 * keys for directory entries.
 *
 *
A name has both a display string (used in the {@code toString()} form of a {@code Path} as
 * well as for {@code Path} equality and sort ordering) and a canonical string, which is used for
 * determining equality of the name during file lookup.
 *
 *
Note: all factory methods return a constant name instance when given the original string "."
 * or "..", ensuring that those names can be accessed statically elsewhere in the code while still
 * being equal to any names created for those values, regardless of normalization settings.
 *
 * @author Colin Decker
 */
final class Name {

  /** The empty name. */
  static final Name EMPTY = new Name("", "");

  /** The name to use for a link from a directory to itself. */
  public static final Name SELF = new Name(".", ".");

  /** The name to use for a link from a directory to its parent directory. */
  public static final Name PARENT = new Name("..", "..");

  /** Creates a new name with no normalization done on the given string. */
  @VisibleForTesting
  static Name simple(String name) {
    switch (name) {
      case ".":
        return SELF;
      case "..":
        return PARENT;
      default:
        return new Name(name, name);
    }
  }

  /**
   * Creates a name with the given display representation and the given canonical representation.
   */
  public static Name create(String display, String canonical) {
    return new Name(display, canonical);
  }

  private final String display;
  private final String canonical;

  private Name(String display, String canonical) {
    this.display = checkNotNull(display);
    this.canonical = checkNotNull(canonical);
  }

  @Override
  public boolean equals(@NullableDecl Object obj) {
    if (obj instanceof Name) {
      Name other = (Name) obj;
      return canonical.equals(other.canonical);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Util.smearHash(canonical.hashCode());
  }

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

  /** Returns an ordering that orders names by their display representation. */
  public static Ordering<Name> displayOrdering() {
    return DISPLAY_ORDERING;
  }

  /** Returns an ordering that orders names by their canonical representation. */
  public static Ordering<Name> canonicalOrdering() {
    return CANONICAL_ORDERING;
  }

  private static final Ordering<Name> DISPLAY_ORDERING =
      Ordering.natural()
          .onResultOf(
              new Function<Name, String>() {
                @Override
                public String apply(Name name) {
                  return name.display;
                }
              });

  private static final Ordering<Name> CANONICAL_ORDERING =
      Ordering.natural()
          .onResultOf(
              new Function<Name, String>() {
                @Override
                public String apply(Name name) {
                  return name.canonical;
                }
              });
}

redpajama_set_name: RedPajamaGithub


text:
package com.cineplex.action;

import javax.annotation.Resource;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;

import com.cineplex.entity.Member;
import com.cineplex.service.ManagerService;
import com.cineplex.service.MemberService;
import com.cineplex.service.WaiterService;
import com.opensymphony.xwork2.ActionContext;

/**
 * he action of login
 * @author Andy 1993sj19993@gmail.com
 * @date 2015年1月25日 下午7:52:03
 *
 */

@Controller
public class LoginAction extends BaseAction {
	private static final Logger LOGGER = LogManager
			.getLogger(LoginAction.class);

	private static final long serialVersionUID = 1L;

	public final static String MEMBER_SUCCESS = "member";
	public final static String MANAGER_SUCCESS = "manager";
	public final static String WAITER_SUCCESS = "waiter";

	public final static String ACCOUNT_TYPE_MEMBER = "member";
	public final static String ACCOUNT_TYPE_MANAGER = "manager";
	public final static String ACCOUNT_TYPE_WAITER = "waiter";

	@Resource
	private MemberService memberService;
	@Resource
	private ManagerService managerService;
	@Resource
	private WaiterService waiterService;

	private String account;
	private String password;

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 *
	* login for all users
	* @return
	* String
	* @throws
	 */
	public String login() {
		LOGGER.info("user info:" + account + "," + password);
		// HttpServletRequest session = ServletActionContext.getRequest();
		ActionContext context = ActionContext.getContext();

		// check if it is a member
		Member member = memberService.login(account, password);
		if (member != null) {
			LOGGER.info("member id:" + member.getId());
			context.getSession().put("id", member.getId());
			context.getSession().put("account", account);
			context.getSession().put("account_type", ACCOUNT_TYPE_MEMBER);
			return MEMBER_SUCCESS;
		}

		// check if it is manager
		boolean isManager = managerService.login(account, password);
		if (isManager) {
			context.getSession().put("account", account);
			context.getSession().put("account_type", ACCOUNT_TYPE_MANAGER);
			return MANAGER_SUCCESS;
		}

		// check if it is waiter
		boolean isWaiter = waiterService.login(account, password);
		if (isWaiter) {
			context.getSession().put("account", account);
			context.getSession().put("account_type", ACCOUNT_TYPE_WAITER);
			return WAITER_SUCCESS;
		}

		return ERROR;
	}

	/**
	 * log out for all users
	*
	* @return
	* String
	* @throws
	 */
	public String logOut() {

		return SUCCESS;
	}

	/**
	 *
	* login again, using when there is some error
	* @return
	* String
	* @throws
	 */
	public String reLogin() {
		session().remove("account_type");
		if (session().get("id") != null) {
			session().remove("id");
		}
		return SUCCESS;
	}

	/**
	 *
	* recover from an error
	* @return
	* String
	* @throws
	 */
	public String errorBack() {
		return (String) session().get("account_type");
	}
}


text:
package rapid

import (
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"

	"github.com/Kiricon/Rapid/templating"
)

// Connection - struct for handling http request and write
type Connection struct {
	R      *http.Request
	W      http.ResponseWriter
	Params map[string]string
	JSON   interface{}
	server *Server
}

// Send - Return plain text string back to http request
func (c *Connection) Send(message string) {
	fmt.Fprintf(c.W, message)
}

// View - Render HTML view without templating
func (c *Connection) View(path string) {
	c.Render(path, nil)
}

// Render - Render HTML view with templating
// Templating uses standard library templating
func (c *Connection) Render(path string, object interface{}) {

	if c.server.viewPrefix != "" {
		path = c.server.viewPrefix + "/" + path
	}
	fileString := templating.AddPartial(path)
	t, _ := template.New("blah").Parse(fileString)
	c.W.Header().Set("Content-Type", "text/html; charset=utf-8")
	t.Execute(c.W, object)
}

// Redirect - Redirect a request to another rest end point
func (c *Connection) Redirect(path string) {
	http.Redirect(c.W, c.R, path, 301)
}

// NotFound - Return 404 message to user
func (c *Connection) NotFound() {
	if c.server.notFoundPage != "" {
		http.ServeFile(c.W, c.R, c.server.notFoundPage)
	} else {
		c.W.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(c.W, c.server.notFoundMessage)
	}
}

// SendJSON - Send json string back to client
func (c *Connection) SendJSON(object interface{}) {
	obj := &object
	j, err := json.Marshal(obj)
	if err != nil {
		fmt.Println(err)
		return
	}
	c.W.Header().Set("Content-Type", "application/json")
	c.Send(string(j))
}


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  before_create :assign_role
  def assign_role
    if User.count == 0
      self.role = "admin"
    else
      self.role = "guest"
    end
  end

end


text:
using namespace std;

// Function prototypes. Both functions use reference variables
// as parameters.
void doubleNum(int &);
void getNum(int &);

int main()
{
   int value;

   // Get a number and store it in value.
   getNum(value);

   // Double the number stored in value.
   doubleNum(value);

   // Display the resulting number.
   cout << "That value doubled is " << value << endl;
   return 0;
}

//*************************************************************
// Definition of getNum.                                      *
// The parameter userNum is a reference variable. The user is *
// asked to enter a number, which is stored in userNum.       *
//*************************************************************

void getNum(int &userNum)
{
   cout << "Enter a number: ";
   cin >> userNum;
}

//**********************************************************
// Definition of doubleNum.                                *
// The parameter refVar is a reference variable. The value *
// in refVar is doubled.                                   *
//**********************************************************

void doubleNum (int &refVar)
{
   refVar *= 2;
}


text:
/* global $, APP, YT, interfaceConfig, onPlayerReady, onPlayerStateChange,
onPlayerError */

const logger = require('jitsi-meet-logger').getLogger(__filename);

import UIUtil from '../util/UIUtil';
import UIEvents from '../../../service/UI/UIEvents';

import VideoLayout from '../videolayout/VideoLayout';
import LargeContainer from '../videolayout/LargeContainer';
import Filmstrip from '../videolayout/Filmstrip';

import {
    createSharedVideoEvent as createEvent,
    sendAnalytics
} from '../../../react/features/analytics';
import {
    participantJoined,
    participantLeft,
    pinParticipant
} from '../../../react/features/base/participants';
import {
    dockToolbox,
    getToolboxHeight,
    showToolbox
} from '../../../react/features/toolbox';

export const SHARED_VIDEO_CONTAINER_TYPE = 'sharedvideo';

/**
 * Example shared video link.
 * @type {string}
 */
const defaultSharedVideoLink = 'https://www.youtube.com/watch?v=xNXN7CZk8X0';
const updateInterval = 5000; // milliseconds

/**
 * The dialog for user input (video link).
 * @type {null}
 */
let dialog = null;

/**
 * Manager of shared video.
 */
export default class SharedVideoManager {
    /**
     *
     */
    constructor(emitter) {
        this.emitter = emitter;
        this.isSharedVideoShown = false;
        this.isPlayerAPILoaded = false;
        this.mutedWithUserInteraction = false;
    }

    /**
     * Indicates if the player volume is currently on. This will return true if
     * we have an available player, which is currently in a PLAYING state,
     * which isn't muted and has it's volume greater than 0.
     *
     * @returns {boolean} indicating if the volume of the shared video is
     * currently on.
     */
    isSharedVideoVolumeOn() {
        return this.player
                && this.player.getPlayerState() === YT.PlayerState.PLAYING
                && !this.player.isMuted()
                && this.player.getVolume() > 0;
    }

    /**
     * Indicates if the local user is the owner of the shared video.
     * @returns {*|boolean}
     */
    isSharedVideoOwner() {
        return this.from && APP.conference.isLocalId(this.from);
    }

    /**
     * Starts shared video by asking user for url, or if its already working
     * asks whether the user wants to stop sharing the video.
     */
    toggleSharedVideo() {
        if (dialog) {
            return;
        }

        if (!this.isSharedVideoShown) {
            requestVideoLink().then(
                    url => {
                        this.emitter.emit(
                            UIEvents.UPDATE_SHARED_VIDEO, url, 'start');
                        sendAnalytics(createEvent('started'));
                    },
                    err => {
                        logger.log('SHARED VIDEO CANCELED', err);
                        sendAnalytics(createEvent('canceled'));
                    }
            );

            return;
        }

        if (APP.conference.isLocalId(this.from)) {
            showStopVideoPropmpt().then(
                () => {
                    // make sure we stop updates for playing before we send stop
                    // if we stop it after receiving self presence, we can end
                    // up sending stop playing, and on the other end it will not
                    // stop
                    if (this.intervalId) {
                        clearInterval(this.intervalId);
                        this.intervalId = null;
                    }
                    this.emitter.emit(
                        UIEvents.UPDATE_SHARED_VIDEO, this.url, 'stop');
                    sendAnalytics(createEvent('stopped'));
                },
                () => {}); // eslint-disable-line no-empty-function
        } else {
            APP.UI.messageHandler.showWarning({
                descriptionKey: 'dialog.alreadySharedVideoMsg',
                titleKey: 'dialog.alreadySharedVideoTitle'
            });
            sendAnalytics(createEvent('already.shared'));
        }
    }

    /**
     * Shows the player component and starts the process that will be sending
     * updates, if we are the one shared the video.
     *
     * @param id the id of the sender of the command
     * @param url the video url
     * @param attributes
     */
    onSharedVideoStart(id, url, attributes) {
        if (this.isSharedVideoShown) {
            return;
        }

        this.isSharedVideoShown = true;

        // the video url
        this.url = url;

        // the owner of the video
        this.from = id;

        this.mutedWithUserInteraction = APP.conference.isLocalAudioMuted();

        // listen for local audio mute events
        this.localAudioMutedListener = this.onLocalAudioMuted.bind(this);
        this.emitter.on(UIEvents.AUDIO_MUTED, this.localAudioMutedListener);

        // This code loads the IFrame Player API code asynchronously.
        const tag = document.createElement('script');

        tag.src = 'https://www.youtube.com/iframe_api';
        const firstScriptTag = document.getElementsByTagName('script')[0];

        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        // sometimes we receive errors like player not defined
        // or player.pauseVideo is not a function
        // we need to operate with player after start playing
        // self.player will be defined once it start playing
        // and will process any initial attributes if any
        this.initialAttributes = attributes;

        const self = this;

        if (self.isPlayerAPILoaded) {
            window.onYouTubeIframeAPIReady();
        } else {
            window.onYouTubeIframeAPIReady = function() {
                self.isPlayerAPILoaded = true;
                const showControls
                    = APP.conference.isLocalId(self.from) ? 1 : 0;
                const p = new YT.Player('sharedVideoIFrame', {
                    height: '100%',
                    width: '100%',
                    videoId: self.url,
                    playerVars: {
                        'origin': location.origin,
                        'fs': '0',
                        'autoplay': 0,
                        'controls': showControls,
                        'rel': 0
                    },
                    events: {
                        'onReady': onPlayerReady,
                        'onStateChange': onPlayerStateChange,
                        'onError': onPlayerError
                    }
                });

                // add listener for volume changes
                p.addEventListener(
                    'onVolumeChange', 'onVolumeChange');

                if (APP.conference.isLocalId(self.from)) {
                // adds progress listener that will be firing events
                // while we are paused and we change the progress of the
                // video (seeking forward or backward on the video)
                    p.addEventListener(
                        'onVideoProgress', 'onVideoProgress');
                }
            };
        }

        /**
         * Indicates that a change in state has occurred for the shared video.
         * @param event the event notifying us of the change
         */
        window.onPlayerStateChange = function(event) {
            // eslint-disable-next-line eqeqeq
            if (event.data == YT.PlayerState.PLAYING) {
                self.player = event.target;

                if (self.initialAttributes) {
                    // If a network update has occurred already now is the
                    // time to process it.
                    self.processVideoUpdate(
                        self.player,
                        self.initialAttributes);

                    self.initialAttributes = null;
                }
                self.smartAudioMute();
                // eslint-disable-next-line eqeqeq
            } else if (event.data == YT.PlayerState.PAUSED) {
                self.smartAudioUnmute();
                sendAnalytics(createEvent('paused'));
            }
            // eslint-disable-next-line eqeqeq
            self.fireSharedVideoEvent(event.data == YT.PlayerState.PAUSED);
        };

        /**
         * Track player progress while paused.
         * @param event
         */
        window.onVideoProgress = function(event) {
            const state = event.target.getPlayerState();

            // eslint-disable-next-line eqeqeq
            if (state == YT.PlayerState.PAUSED) {
                self.fireSharedVideoEvent(true);
            }
        };

        /**
         * Gets notified for volume state changed.
         * @param event
         */
        window.onVolumeChange = function(event) {
            self.fireSharedVideoEvent();

            // let's check, if player is not muted lets mute locally
            if (event.data.volume > 0 && !event.data.muted) {
                self.smartAudioMute();
            } else if (event.data.volume <= 0 || event.data.muted) {
                self.smartAudioUnmute();
            }
            sendAnalytics(createEvent(
                'volume.changed',
                {
                    volume: event.data.volume,
                    muted: event.data.muted
                }));
        };

        window.onPlayerReady = function(event) {
            const player = event.target;

            // do not relay on autoplay as it is not sending all of the events
            // in onPlayerStateChange

            player.playVideo();

            const iframe = player.getIframe();

            // eslint-disable-next-line no-use-before-define
            self.sharedVideo = new SharedVideoContainer(
                { url,
                    iframe,
                    player });

            // prevents pausing participants not sharing the video
            // to pause the video
            if (!APP.conference.isLocalId(self.from)) {
                $('#sharedVideo').css('pointer-events', 'none');
            }

            VideoLayout.addLargeVideoContainer(
                SHARED_VIDEO_CONTAINER_TYPE, self.sharedVideo);

            APP.store.dispatch(participantJoined({

                // FIXME The cat is out of the bag already or rather _room is
                // not private because it is used in multiple other places
                // already such as AbstractPageReloadOverlay.
                conference: APP.conference._room,
                id: self.url,
                isFakeParticipant: true,
                name: 'YouTube'
            }));

            APP.store.dispatch(pinParticipant(self.url));

            // If we are sending the command and we are starting the player
            // we need to continuously send the player current time position
            if (APP.conference.isLocalId(self.from)) {
                self.intervalId = setInterval(
                    self.fireSharedVideoEvent.bind(self),
                    updateInterval);
            }
        };

        window.onPlayerError = function(event) {
            logger.error('Error in the player:', event.data);

            // store the error player, so we can remove it
            self.errorInPlayer = event.target;
        };
    }

    /**
     * Process attributes, whether player needs to be paused or seek.
     * @param player the player to operate over
     * @param attributes the attributes with the player state we want
     */
    processVideoUpdate(player, attributes) {
        if (!attributes) {
            return;
        }

        // eslint-disable-next-line eqeqeq
        if (attributes.state == 'playing') {

            const isPlayerPaused
                = this.player.getPlayerState() === YT.PlayerState.PAUSED;

            // If our player is currently paused force the seek.
            this.processTime(player, attributes, isPlayerPaused);

            // Process mute.
            const isAttrMuted = attributes.muted === 'true';

            if (player.isMuted() !== isAttrMuted) {
                this.smartPlayerMute(isAttrMuted, true);
            }

            // Process volume
            if (!isAttrMuted
                && attributes.volume !== undefined
                // eslint-disable-next-line eqeqeq
                && player.getVolume() != attributes.volume) {

                player.setVolume(attributes.volume);
                logger.info(`Player change of volume:${attributes.volume}`);
            }

            if (isPlayerPaused) {
                player.playVideo();
            }
            // eslint-disable-next-line eqeqeq
        } else if (attributes.state == 'pause') {
            // if its not paused, pause it
            player.pauseVideo();

            this.processTime(player, attributes, true);
        }
    }

    /**
     * Check for time in attributes and if needed seek in current player
     * @param player the player to operate over
     * @param attributes the attributes with the player state we want
     * @param forceSeek whether seek should be forced
     */
    processTime(player, attributes, forceSeek) {
        if (forceSeek) {
            logger.info('Player seekTo:', attributes.time);
            player.seekTo(attributes.time);

            return;
        }

        // check received time and current time
        const currentPosition = player.getCurrentTime();
        const diff = Math.abs(attributes.time - currentPosition);

        // if we drift more than the interval for checking
        // sync, the interval is in milliseconds
        if (diff > updateInterval / 1000) {
            logger.info('Player seekTo:', attributes.time,
                ' current time is:', currentPosition, ' diff:', diff);
            player.seekTo(attributes.time);
        }
    }

    /**
     * Checks current state of the player and fire an event with the values.
     */
    fireSharedVideoEvent(sendPauseEvent) {
        // ignore update checks if we are not the owner of the video
        // or there is still no player defined or we are stopped
        // (in a process of stopping)
        if (!APP.conference.isLocalId(this.from) || !this.player
            || !this.isSharedVideoShown) {
            return;
        }

        const state = this.player.getPlayerState();

        // if its paused and haven't been pause - send paused

        if (state === YT.PlayerState.PAUSED && sendPauseEvent) {
            this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
                this.url, 'pause', this.player.getCurrentTime());
        } else if (state === YT.PlayerState.PLAYING) {
            // if its playing and it was paused - send update with time
            // if its playing and was playing just send update with time
            this.emitter.emit(UIEvents.UPDATE_SHARED_VIDEO,
                this.url, 'playing',
                this.player.getCurrentTime(),
                this.player.isMuted(),
                this.player.getVolume());
        }
    }

    /**
     * Updates video, if it's not playing and needs starting or if it's playing
     * and needs to be paused.
     * @param id the id of the sender of the command
     * @param url the video url
     * @param attributes
     */
    onSharedVideoUpdate(id, url, attributes) {
        // if we are sending the event ignore
        if (APP.conference.isLocalId(this.from)) {
            return;
        }

        if (!this.isSharedVideoShown) {
            this.onSharedVideoStart(id, url, attributes);

            return;
        }

        // eslint-disable-next-line no-negated-condition
        if (!this.player) {
            this.initialAttributes = attributes;
        } else {
            this.processVideoUpdate(this.player, attributes);
        }
    }

    /**
     * Stop shared video if it is currently showed. If the user started the
     * shared video is the one in the id (called when user
     * left and we want to remove video if the user sharing it left).
     * @param id the id of the sender of the command
     */
    onSharedVideoStop(id, attributes) {
        if (!this.isSharedVideoShown) {
            return;
        }

        if (this.from !== id) {
            return;
        }

        if (!this.player) {
            // if there is no error in the player till now,
            // store the initial attributes
            if (!this.errorInPlayer) {
                this.initialAttributes = attributes;

                return;
            }
        }

        this.emitter.removeListener(UIEvents.AUDIO_MUTED,
            this.localAudioMutedListener);
        this.localAudioMutedListener = null;

        APP.store.dispatch(participantLeft(this.url, APP.conference._room));

        VideoLayout.showLargeVideoContainer(SHARED_VIDEO_CONTAINER_TYPE, false)
            .then(() => {
                VideoLayout.removeLargeVideoContainer(
                    SHARED_VIDEO_CONTAINER_TYPE);

                if (this.player) {
                    this.player.destroy();
                    this.player = null;
                } else if (this.errorInPlayer) {
                    // if there is an error in player, remove that instance
                    this.errorInPlayer.destroy();
                    this.errorInPlayer = null;
                }
                this.smartAudioUnmute();

                // revert to original behavior (prevents pausing
                // for participants not sharing the video to pause it)
                $('#sharedVideo').css('pointer-events', 'auto');

                this.emitter.emit(
                    UIEvents.UPDATE_SHARED_VIDEO, null, 'removed');
            });

        this.url = null;
        this.isSharedVideoShown = false;
        this.initialAttributes = null;
    }

    /**
     * Receives events for local audio mute/unmute by local user.
     * @param muted boolena whether it is muted or not.
     * @param {boolean} indicates if this mute was a result of user interaction,
     * i.e. pressing the mute button or it was programatically triggerred
     */
    onLocalAudioMuted(muted, userInteraction) {
        if (!this.player) {
            return;
        }

        if (muted) {
            this.mutedWithUserInteraction = userInteraction;
        } else if (this.player.getPlayerState() !== YT.PlayerState.PAUSED) {
            this.smartPlayerMute(true, false);

            // Check if we need to update other participants
            this.fireSharedVideoEvent();
        }
    }

    /**
     * Mutes / unmutes the player.
     * @param mute true to mute the shared video, false - otherwise.
     * @param {boolean} Indicates if this mute is a consequence of a network
     * video update or is called locally.
     */
    smartPlayerMute(mute, isVideoUpdate) {
        if (!this.player.isMuted() && mute) {
            this.player.mute();

            if (isVideoUpdate) {
                this.smartAudioUnmute();
            }
        } else if (this.player.isMuted() && !mute) {
            this.player.unMute();
            if (isVideoUpdate) {
                this.smartAudioMute();
            }
        }
    }

    /**
     * Smart mike unmute. If the mike is currently muted and it wasn't muted
     * by the user via the mike button and the volume of the shared video is on
     * we're unmuting the mike automatically.
     */
    smartAudioUnmute() {
        if (APP.conference.isLocalAudioMuted()
            && !this.mutedWithUserInteraction
            && !this.isSharedVideoVolumeOn()) {
            sendAnalytics(createEvent('audio.unmuted'));
            logger.log('Shared video: audio unmuted');
            this.emitter.emit(UIEvents.AUDIO_MUTED, false, false);
        }
    }

    /**
     * Smart mike mute. If the mike isn't currently muted and the shared video
     * volume is on we mute the mike.
     */
    smartAudioMute() {
        if (!APP.conference.isLocalAudioMuted()
            && this.isSharedVideoVolumeOn()) {
            sendAnalytics(createEvent('audio.muted'));
            logger.log('Shared video: audio muted');
            this.emitter.emit(UIEvents.AUDIO_MUTED, true, false);
        }
    }
}

/**
 * Container for shared video iframe.
 */
class SharedVideoContainer extends LargeContainer {
    /**
     *
     */
    constructor({ url, iframe, player }) {
        super();

        this.$iframe = $(iframe);
        this.url = url;
        this.player = player;
    }

    /**
     *
     */
    show() {
        const self = this;

        return new Promise(resolve => {
            this.$iframe.fadeIn(300, () => {
                self.bodyBackground = document.body.style.background;
                document.body.style.background = 'black';
                this.$iframe.css({ opacity: 1 });
                APP.store.dispatch(dockToolbox(true));
                resolve();
            });
        });
    }

    /**
     *
     */
    hide() {
        const self = this;

        APP.store.dispatch(dockToolbox(false));

        return new Promise(resolve => {
            this.$iframe.fadeOut(300, () => {
                document.body.style.background = self.bodyBackground;
                this.$iframe.css({ opacity: 0 });
                resolve();
            });
        });
    }

    /**
     *
     */
    onHoverIn() {
        APP.store.dispatch(showToolbox());
    }

    /**
     *
     */
    get id() {
        return this.url;
    }

    /**
     *
     */
    resize(containerWidth, containerHeight) {
        let height, width;

        if (interfaceConfig.VERTICAL_FILMSTRIP) {
            height = containerHeight - getToolboxHeight();
            width = containerWidth - Filmstrip.getVerticalFilmstripWidth();
        } else {
            height = containerHeight - Filmstrip.getFilmstripHeight();
            width = containerWidth;
        }

        this.$iframe.width(width).height(height);
    }

    /**
     * @return {boolean} do not switch on dominant speaker event if on stage.
     */
    stayOnStage() {
        return false;
    }
}

/**
 * Checks if given string is youtube url.
 * @param {string} url string to check.
 * @returns {boolean}
 */
function getYoutubeLink(url) {
    const p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;// eslint-disable-line max-len

    return url.match(p) ? RegExp.$1 : false;
}

/**
 * Ask user if he want to close shared video.
 */
function showStopVideoPropmpt() {
    return new Promise((resolve, reject) => {
        const submitFunction = function(e, v) {
            if (v) {
                resolve();
            } else {
                reject();
            }
        };

        const closeFunction = function() {
            dialog = null;
        };

        dialog = APP.UI.messageHandler.openTwoButtonDialog({
            titleKey: 'dialog.removeSharedVideoTitle',
            msgKey: 'dialog.removeSharedVideoMsg',
            leftButtonKey: 'dialog.Remove',
            submitFunction,
            closeFunction
        });
    });
}

/**
 * Ask user for shared video url to share with others.
 * Dialog validates client input to allow only youtube urls.
 */
function requestVideoLink() {
    const i18n = APP.translation;
    const cancelButton = i18n.generateTranslationHTML('dialog.Cancel');
    const shareButton = i18n.generateTranslationHTML('dialog.Share');
    const backButton = i18n.generateTranslationHTML('dialog.Back');
    const linkError
        = i18n.generateTranslationHTML('dialog.shareVideoLinkError');

    return new Promise((resolve, reject) => {
        dialog = APP.UI.messageHandler.openDialogWithStates({
            state0: {
                titleKey: 'dialog.shareVideoTitle',
                html: `
                    <input name='sharedVideoUrl' type='text'
                           class='input-control'
                           data-i18n='[placeholder]defaultLink'
                           autofocus>`,
                persistent: false,
                buttons: [
                    { title: cancelButton,
                        value: false },
                    { title: shareButton,
                        value: true }
                ],
                focus: ':input:first',
                defaultButton: 1,
                submit(e, v, m, f) { // eslint-disable-line max-params
                    e.preventDefault();
                    if (!v) {
                        reject('cancelled');
                        dialog.close();

                        return;
                    }

                    const sharedVideoUrl = f.sharedVideoUrl;

                    if (!sharedVideoUrl) {
                        return;
                    }

                    const urlValue
                        = encodeURI(UIUtil.escapeHtml(sharedVideoUrl));
                    const yVideoId = getYoutubeLink(urlValue);

                    if (!yVideoId) {
                        dialog.goToState('state1');

                        return false;
                    }

                    resolve(yVideoId);
                    dialog.close();
                }
            },

            state1: {
                titleKey: 'dialog.shareVideoTitle',
                html: linkError,
                persistent: false,
                buttons: [
                    { title: cancelButton,
                        value: false },
                    { title: backButton,
                        value: true }
                ],
                focus: ':input:first',
                defaultButton: 1,
                submit(e, v) {
                    e.preventDefault();
                    if (v === 0) {
                        reject();
                        dialog.close();
                    } else {
                        dialog.goToState('state0');
                    }
                }
            }
        }, {
            close() {
                dialog = null;
            }
        }, {
            url: defaultSharedVideoLink
        });
    });
}


text:
#include "Multistdafx.h"
#include <Siglune/SigDirect3D.h>
#include <EliVertexBuffer.h>

CVertexBuffer::CVertexBuffer() :
	m_Num(-1),
	m_Type(VX_INVALID),
	m_ObjectID(0)
{ ; }

BOOL CVertexBuffer::Create(DWORD num, VERTEX_TYPE type) {
	Release();

	GLenum res;

	glGenBuffers(1, &m_ObjectID);
	SIG_ERRORRETURNBOOL(res,"Failed@glGenBuffers");

	glBindBuffer(GL_ARRAY_BUFFER, m_ObjectID);
	SIG_ERRORRETURNBOOL(res,"Failed@glBindBuffer");

	glBufferData(GL_ARRAY_BUFFER, num * VERTEX_SIZE[type], NULL, GL_STATIC_DRAW);
	SIG_ERRORRETURNBOOL(res,"Failed@glBufferData");

	glBindBuffer(GL_ARRAY_BUFFER, 0);

	m_Type = type;

	return TRUE;
}

BOOL CVertexBuffer::SetData(void* pData, DWORD num) {
	GLenum res;

	glBindBuffer(GL_ARRAY_BUFFER, m_ObjectID);
	SIG_ERRORRETURNBOOL(res,"Failed@glBindBuffer");

	glBufferSubData(GL_ARRAY_BUFFER, 0, num * VERTEX_SIZE[m_Type], pData);
	SIG_ERRORRETURNBOOL(res,"Failed@glBufferSubData");

	glBindBuffer(GL_ARRAY_BUFFER, 0);

	m_Num = num;

	return TRUE;
}

void CVertexBuffer::Release() {
	if(m_ObjectID != 0)
		glDeleteBuffers(1,&m_ObjectID);

	GLenum hr;

	if(SUCCEEDED(hr))
		m_ObjectID = 0;
}

void CVertexBuffer::SetStream(int num) {
	GLenum res;

	glBindBuffer(GL_ARRAY_BUFFER, m_ObjectID);
	SIG_ERRORCHECK(res,"Failed@glBindBuffer");

	GLuint totalsize = 0;
	GLuint index = 0;

	for(ATTRIB_TYPE* a = _FIXED_VERTEX_FORMAT_[m_Type];*a != SH_ATR_TERMINATE ;a++) {
		glEnableVertexAttribArray(index);
		SIG_ERRORCHECK(res,"Failed@glEnableVertexAttribArray");
		// index, num, type, normalized, datalen, bufp
		glVertexAttribPointer(index, ShaderAttributeRef[*a].size_count, GL_FLOAT, GL_FALSE, VERTEX_SIZE[m_Type], (void*)totalsize);
		SIG_ERRORCHECK(res,"Failed@glVertexAttribPointer");
#ifdef _DALK_DEBUG_BUILD_
		string Name = ShaderAttributeRef[*a].name;
		_DEBUGPRINTF("index = %d count = %d total = %d offset = %d ", *a, ShaderAttributeRef[*a].size_count, VERTEX_SIZE[m_Type], totalsize);
#endif
		totalsize += ShaderAttributeRef[*a].size_count * sizeof(float);
		index++;
	}

}


text:
namespace blink {

class ComputedStyle;
class CSSProperty;

struct OptionalStyleColor {
 public:
  OptionalStyleColor(std::nullptr_t) : is_null_(true) {}
  OptionalStyleColor(const StyleColor& style_color)
      : is_null_(false), style_color_(style_color) {}
  OptionalStyleColor(const Color& color)
      : is_null_(false), style_color_(color) {}

  bool IsNull() const { return is_null_; }
  const StyleColor& Access() const {
    DCHECK(!is_null_);
    return style_color_;
  }
  bool operator==(const OptionalStyleColor& other) const {
    return is_null_ == other.is_null_ && style_color_ == other.style_color_;
  }

 private:
  bool is_null_;
  StyleColor style_color_;
};

class ColorPropertyFunctions {
 public:
  static OptionalStyleColor GetInitialColor(const CSSProperty&,
                                            const ComputedStyle& initial_style);
  static OptionalStyleColor GetUnvisitedColor(const CSSProperty&,
                                              const ComputedStyle&);
  static OptionalStyleColor GetVisitedColor(const CSSProperty&,
                                            const ComputedStyle&);
  static void SetUnvisitedColor(const CSSProperty&,
                                ComputedStyle&,
                                const Color&);
  static void SetVisitedColor(const CSSProperty&, ComputedStyle&, const Color&);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_COLOR_PROPERTY_FUNCTIONS_H_


text:
module Emails
  module Issues
    def new_issue_email(recipient_id, issue_id)
      @issue = Issue.find(issue_id)
      @project = @issue.project
      @target_url = project_issue_url(@project, @issue)
      mail(from: sender(@issue.author_id),
           to: recipient(recipient_id),
           subject: subject("#{@issue.title} (##{@issue.iid})"))
    end

    def reassigned_issue_email(recipient_id, issue_id, previous_assignee_id, updated_by_user_id)
      @issue = Issue.find(issue_id)
      @previous_assignee = User.find_by(id: previous_assignee_id) if previous_assignee_id
      @project = @issue.project
      @target_url = project_issue_url(@project, @issue)
      mail(from: sender(updated_by_user_id),
           to: recipient(recipient_id),
           subject: subject("#{@issue.title} (##{@issue.iid})"))
    end

    def closed_issue_email(recipient_id, issue_id, updated_by_user_id)
      @issue = Issue.find issue_id
      @project = @issue.project
      @updated_by = User.find updated_by_user_id
      @target_url = project_issue_url(@project, @issue)
      mail(from: sender(updated_by_user_id),
           to: recipient(recipient_id),
           subject: subject("#{@issue.title} (##{@issue.iid})"))
    end

    def issue_status_changed_email(recipient_id, issue_id, status, updated_by_user_id)
      @issue = Issue.find issue_id
      @issue_status = status
      @project = @issue.project
      @updated_by = User.find updated_by_user_id
      @target_url = project_issue_url(@project, @issue)
      mail(from: sender(updated_by_user_id),
           to: recipient(recipient_id),
           subject: subject("#{@issue.title} (##{@issue.iid})"))
    end
  end
end


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Card'
        db.create_table(u'cards_card', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
            ('todo', self.gf('django.db.models.fields.CharField')(max_length=254)),
            ('time_added', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('time_due', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
        ))
        db.send_create_signal(u'cards', ['Card'])

        # Adding model 'Recur'
        db.create_table(u'cards_recur', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('todo', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['cards.Card'])),
            ('freq', self.gf('django.db.models.fields.PositiveIntegerField')()),
        ))
        db.send_create_signal(u'cards', ['Recur'])

    def backwards(self, orm):
        # Deleting model 'Card'
        db.delete_table(u'cards_card')

        # Deleting model 'Recur'
        db.delete_table(u'cards_recur')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'cards.card': {
            'Meta': {'object_name': 'Card'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'time_added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'time_due': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'todo': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
        },
        u'cards.recur': {
            'Meta': {'object_name': 'Recur'},
            'freq': ('django.db.models.fields.PositiveIntegerField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'todo': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['cards.Card']"})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        }
    }

    complete_apps = ['cards']


text:
package com.thoughtworks.go.agent.launcher;

import java.util.List;

import com.thoughtworks.go.agent.testhelper.FakeBootstrapperServer;
import com.thoughtworks.go.mothers.ServerUrlGeneratorMother;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

@RunWith(FakeBootstrapperServer.class)
public class ServerCallTest {
    @Test
    public void shouldBeAbleToReadTheResponseBody() throws Exception {
        GetMethod getMethod = new GetMethod(DownloadableFile.AGENT.url(ServerUrlGeneratorMother.generatorFor("localhost", 9090)));
        ServerCall.ServerResponseWrapper response = ServerCall.invoke(getMethod);
        List list = IOUtils.readLines(response.body);
        assertThat(list.isEmpty(), is(false));
    }

    @Test
    public void shouldThrowSpecifiCExceptionIncaseOf404() throws Exception {
        GetMethod getMethod = new GetMethod("http://localhost:9090/go/not-found");
        try {
            ServerCall.invoke(getMethod);
        } catch (Exception ex) {
            assertThat(ex.getMessage().contains(
                    "This agent might be incompatible with your Go Server."
                            + "Please fix the version mismatch between Go Server and Go Agent."), is(true));
        }

    }
}


text:
#include "settings_test.h"
#include "settings/settings_fcb.h"

#ifdef TEST_LONG
#define TESTS_S3_FCB_ITERATIONS 4096
#else
#define TESTS_S3_FCB_ITERATIONS 100
#endif

void test_config_save_3_fcb(void)
{
	int rc;
	struct settings_fcb cf;
	int i;

	config_wipe_srcs();
	config_wipe_fcb(fcb_sectors, ARRAY_SIZE(fcb_sectors));

	cf.cf_fcb.f_magic = CONFIG_SETTINGS_FCB_MAGIC;
	cf.cf_fcb.f_sectors = fcb_sectors;
	cf.cf_fcb.f_sector_cnt = 4;

	rc = settings_fcb_src(&cf);
	zassert_true(rc == 0, "can't register FCB as configuration source");

	rc = settings_fcb_dst(&cf);
	zassert_true(rc == 0,
		     "can't register FCB as configuration destination");

	for (i = 0; i < TESTS_S3_FCB_ITERATIONS; i++) {
		val32 = i;

		rc = settings_save();
		zassert_true(rc == 0, "fcb write error");

		val32 = 0U;

		rc = settings_load();
		zassert_true(rc == 0, "fcb read error");
		zassert_true(val32 == i, "bad value read");
	}
}


text:
import socket
import binascii

from escea.message import (
    FanBoostOffRequest,
    FanBoostOnRequest,
    FlameEffectOffRequest,
    FlameEffectOnRequest,
    PowerOffRequest,
    PowerOnRequest,
    Response,
    SearchForFiresRequest,
    SetTempRequest,
    StatusRequest,
    StatusResponse,
)

from escea.error import (ConnectionTimeout, UnexpectedResponse)

def fires(timeout=1):
    # Create a socket to send/recv on
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.bind(('0.0.0.0', Fire.UDP_PORT))
    fires = []
    try:
        message = SearchForFiresRequest()
        sock.sendto(message.payload(), ('<broadcast>', Fire.UDP_PORT))
        # Each recv should have the full timeout period to complete
        sock.settimeout(timeout)
        while True:
            # Get some packets from the network
            data, (address, _) = sock.recvfrom(1024)
            response = Response(data)
            # Confirm it's an I_AM_A_FIRE response
            try:
                message.assert_code(response.get(1))
                fires.append(Fire(address, response.serial(), response.pin()))
            except UnexpectedResponse:
                pass
    except socket.timeout:
        # This will always happen, a timeout occurs when we no longer hear from any fires
        # This is the required flow to break out of the `while True:` statement above.
        pass
    finally:
        # Always close the socket
        sock.close()

    return fires

class Fire(object):
    UDP_PORT = 3300

    def __init__(self, ip, serial='', pin=''):
        super(Fire, self).__init__()
        self._ip = ip
        self._serial = serial
        self._pin = pin

    def send(self, message):
        # Create a socket to send/recv on
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind(('0.0.0.0', Fire.UDP_PORT))
        data = ''
        try:
            # All socket calls within a try block
            sock.sendto(message.payload(), (self._ip, Fire.UDP_PORT))
            sock.settimeout(2)
            data, _ = sock.recvfrom(1024)
        except socket.timeout:
            raise ConnectionTimeout
        finally:
            # Always close the socket
            sock.close()

        response = Response(data)
        message.assert_code(response.get(1))
        return response

    def status(self):
        return StatusResponse(self.send(StatusRequest()))

    def set_temp(self, target):
        self.send(SetTempRequest(target))

    def power_on(self):
        self.send(PowerOnRequest())

    def power_off(self):
        self.send(PowerOffRequest())

    def flame_effect_on(self):
        self.send(FlameEffectOnRequest())

    def flame_effect_off(self):
        self.send(FlameEffectOffRequest())

    def fan_boost_on(self):
        self.send(FanBoostOnRequest())

    def fan_boost_off(self):
        self.send(FanBoostOffRequest())

    def pin(self):
        return self._pin

    def serial(self):
        return self._serial


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddUserstamps extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('channels', function ($table) {
            $table->unsignedInteger('created_by')
                ->nullable()->default(null)->after('created_at');
            $table->unsignedInteger('updated_by')
                ->nullable()->default(null)->after('updated_at');
            $table->unsignedInteger('deleted_by')
                ->nullable()->default(null)->after('deleted_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('channels', function ($table) {
            $table->dropColumn('created_by');
            $table->dropColumn('updated_by');
            $table->dropColumn('deleted_by');

        });
    }
}


text:
<?php
namespace TYPO3\Flow\Tests\Functional\Security\Fixtures\Controller;

use TYPO3\Flow\Annotations as Flow;

/**
 * A controller for functional testing
 */
class RestrictedController extends \TYPO3\Flow\Mvc\Controller\ActionController
{
    /**
     * This action is not restricted in a policy, everybody can access it
     *
     * @return string
     */
    public function publicAction()
    {
        return 'public';
    }

    /**
     * This action is restricted to accounts with the role Customer by a policy in
     * the Flow package's Testing context configuration.
     *
     * @return string
     */
    public function customerAction()
    {
        return 'customer';
    }

    /**
     * This action is restricted to accounts with the role Administrator by a policy in
     * the Flow package's Testing context configuration.
     *
     * @return string
     */
    public function adminAction()
    {
        return 'admin';
    }

    /**
     * @param string $argument1
     * @param string $argument2
     * @return string
     */
    public function argumentsAction($argument1, $argument2 = 'default')
    {
        return sprintf('argument1: %s, argument2: %s', $argument1, $argument2);
    }
}


text:
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Orders.Fees;
using System;
using System.Collections.Generic;
using System.Linq;

namespace QuantConnect.Algorithm.CSharp.Alphas
{
    /// <summary>
    /// A number of companies publicly trade two different classes of shares
    /// in US equity markets. If both assets trade with reasonable volume, then
    /// the underlying driving forces of each should be similar or the same. Given
    /// this, we can create a relatively dollar-netural long/short portfolio using
    /// the dual share classes. Theoretically, any deviation of this portfolio from
    /// its mean-value should be corrected, and so the motivating idea is based on
    /// mean-reversion. Using a Simple Moving Average indicator, we can
    /// compare the value of this portfolio against its SMA and generate insights
    /// to buy the under-valued symbol and sell the over-valued symbol.
    ///
    /// This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open sourced so the community and client funds can see an example of an alpha.
    /// </summary>
    public class ShareClassMeanReversionAlpha : QCAlgorithm
    {
        public override void Initialize()
        {
            SetStartDate(2019, 1, 1);
            SetCash(100000);

            // Set zero transaction fees
            SetSecurityInitializer(security => security.FeeModel = new ConstantFeeModel(0));

            SetWarmUp(20);

            // Setup Universe settings and tickers to be used
            var symbols = new[] { "VIA", "VIAB" }
                .Select(x => QuantConnect.Symbol.Create(x, SecurityType.Equity, Market.USA));

            // Set requested data resolution
            UniverseSettings.Resolution = Resolution.Minute;
            SetUniverseSelection(new ManualUniverseSelectionModel(symbols));

            // Use ShareClassMeanReversionAlphaModel to establish insights
            SetAlpha(new ShareClassMeanReversionAlphaModel(symbols));

            // Equally weigh securities in portfolio, based on insights
            SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());

            // Set Immediate Execution Model
            SetExecution(new ImmediateExecutionModel());

            // Set Null Risk Management Model
            SetRiskManagement(new NullRiskManagementModel());
        }

        private class ShareClassMeanReversionAlphaModel : AlphaModel
        {
            private const double _insightMagnitude = 0.001;
            private readonly Symbol _longSymbol;
            private readonly Symbol _shortSymbol;
            private readonly TimeSpan _insightPeriod;
            private readonly SimpleMovingAverage _sma;
            private readonly RollingWindow<decimal> _positionWindow;
            private decimal _alpha;
            private decimal _beta;
            private bool _invested;

            public ShareClassMeanReversionAlphaModel(
                IEnumerable<Symbol> symbols,
                Resolution resolution = Resolution.Minute)
            {
                if (symbols.Count() != 2)
                {
                    throw new ArgumentException("ShareClassMeanReversionAlphaModel: symbols parameter must contain 2 elements");
                }
                _longSymbol = symbols.ToArray()[0];
                _shortSymbol = symbols.ToArray()[1];
                _insightPeriod = resolution.ToTimeSpan().Multiply(5);
                _sma = new SimpleMovingAverage(2);
                _positionWindow = new RollingWindow<decimal>(2);
            }

            public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
            {
                // Check to see if either ticker will return a NoneBar, and skip the data slice if so
                if (data.Bars.Count < 2)
                {
                    return Enumerable.Empty<Insight>();
                }

                // If Alpha and Beta haven't been calculated yet, then do so
                if (_alpha == 0 || _beta == 0)
                {
                    CalculateAlphaBeta(algorithm);
                }

                // Update indicator and Rolling Window for each data slice passed into Update() method
                if (!UpdateIndicators(data))
                {
                    return Enumerable.Empty<Insight>();
                }

                // Check to see if the portfolio is invested. If no, then perform value comparisons and emit insights accordingly
                if (!_invested)
                {
                    //Reset invested boolean
                    _invested = true;

                    if (_positionWindow[0] > _sma)
                    {
                        return Insight.Group(new[]
                        {
                            Insight.Price(_longSymbol, _insightPeriod, InsightDirection.Down, _insightMagnitude),
                            Insight.Price(_shortSymbol, _insightPeriod, InsightDirection.Up, _insightMagnitude),
                        });
                    }
                    else
                    {
                        return Insight.Group(new[]
                    {
                            Insight.Price(_longSymbol, _insightPeriod, InsightDirection.Up, _insightMagnitude),
                            Insight.Price(_shortSymbol, _insightPeriod, InsightDirection.Down, _insightMagnitude),
                        });
                    }
                }
                // If the portfolio is invested and crossed back over the SMA, then emit flat insights
                else if (_invested && CrossedMean())
                {
                    _invested = false;
                }

                return Enumerable.Empty<Insight>();
            }

            /// <summary>
            /// Calculate Alpha and Beta, the initial number of shares for each security needed to achieve a 50/50 weighting
            /// </summary>
            /// <param name="algorithm"></param>
            private void CalculateAlphaBeta(QCAlgorithm algorithm)
            {
                _alpha = algorithm.CalculateOrderQuantity(_longSymbol, 0.5);
                _beta = algorithm.CalculateOrderQuantity(_shortSymbol, 0.5);
                algorithm.Log($"{algorithm.Time} :: Alpha: {_alpha} Beta: {_beta}");
            }

            /// <summary>
            /// Calculate position value and update the SMA indicator and Rolling Window
            /// </summary>
            private bool UpdateIndicators(Slice data)
            {
                var positionValue = (_alpha * data[_longSymbol].Close) - (_beta * data[_shortSymbol].Close);
                _sma.Update(data[_longSymbol].EndTime, positionValue);
                _positionWindow.Add(positionValue);
                return _sma.IsReady && _positionWindow.IsReady;
            }

            /// <summary>
            /// Check to see if the position value has crossed the SMA and then return a boolean value
            /// </summary>
            /// <returns></returns>
            private bool CrossedMean()
            {
                return (_positionWindow[0] >= _sma && _positionWindow[1] < _sma)
                    || (_positionWindow[1] >= _sma && _positionWindow[0] < _sma);
            }
        }
    }
}


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

namespace Uzu
{
	/// <summary>
	/// A 'fixed size' list implementation.
	/// Maintains the the current size of the list for easy adding,
	/// but does not expand if the maximum capacity is exceeded.
	/// </summary>
	public class FixedList<T>
	{
		/// <summary>
		/// Constructor that allows initializing of buffer capacity.
		/// </summary>
		public FixedList (int capacity)
		{
			_buffer = new T[capacity];
		}

		/// <summary>
		/// Gets the number of current elements.
		/// </summary>
		public int Count {
			get { return _size; }
		}

		/// <summary>
		/// Gets the maximum capacity of the current buffer.
		/// This is different Count, which stores the number of items currently stored.
		/// </summary>
		public int Capacity {
			get {
				return _buffer.Length;
			}
		}

		/// <summary>
		/// For 'foreach' functionality.
		/// </summary>
		public IEnumerator<T> GetEnumerator ()
		{
			for (int i = 0; i < _size; ++i) {
				yield return _buffer[i];
			}
		}

		/// <summary>
		/// Indexing into the list.
		/// </summary>
		public T this [int i] {
			get { return _buffer [i]; }
			set { _buffer [i] = value; }
		}

		/// <summary>
		/// Clear the array by resetting its size to zero. Note that the memory is not actually released.
		/// </summary>
		public void Clear ()
		{
			_size = 0;
		}

		/// <summary>
		/// Add the specified item to the end of the list.
		/// </summary>
		public void Add (T item)
		{
			_buffer [_size++] = item;
		}

		/// <summary>
		/// Insert an item at the specified index, pushing the entries back.
		/// </summary>
		public void Insert (int index, T item)
		{
			for (int i = _size; i > index; --i) {
				_buffer [i] = _buffer [i - 1];
			}
			_buffer [index] = item;
			++_size;
		}

		/// <summary>
		/// Returns 'true' if the specified item is within the list.
		/// </summary>
		public bool Contains (T item)
		{
			for (int i = 0; i < _size; ++i) {
				if (_buffer [i].Equals (item)) {
					return true;
				}
			}
			return false;
		}

		/// <summary>
		/// Finds the index of the specified item.
		/// Returns the Count of the list if not found.
		/// </summary>
		public int FindIndex (T item)
		{
			for (int i = 0; i < _size; ++i) {
				if (_buffer [i].Equals (item)) {
					return i;
				}
			}
			return Count;
		}

		/// <summary>
		/// Remove the specified item from the list.
		/// Note that RemoveAt() is faster and is advisable if you already know the index.
		/// </summary>
		public bool Remove (T item)
		{
			EqualityComparer<T> comp = EqualityComparer<T>.Default;

			for (int i = 0; i < _size; ++i) {
				if (comp.Equals (_buffer [i], item)) {
					--_size;
					_buffer [i] = default(T);
					for (int b = i; b < _size; ++b) {
						_buffer [b] = _buffer [b + 1];
					}
					return true;
				}
			}
			return false;
		}

		/// <summary>
		/// Remove an item at the specified index.
		/// </summary>
		public void RemoveAt (int index)
		{
			if (index < _size) {
				--_size;
				_buffer [index] = default(T);
				for (int b = index; b < _size; ++b) {
					_buffer [b] = _buffer [b + 1];
				}
			}
		}

		/// <summary>
		/// Mimic List's ToArray() functionality, except that in this case the list is resized to match the current size.
		/// </summary>
		public T[] ToArray ()
		{
			return _buffer;
		}

		#region Implementation.
		private T[] _buffer;
		private int _size = 0;
		#endregion
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="4dp"
    card_view:cardCornerRadius="4dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="12dp"
        android:paddingLeft="12dp"
        android:paddingRight="12dp">

        <ImageView
            android:id="@+id/tweet_user_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="8dp"
            android:layout_marginEnd="8dp"
            android:src="@mipmap/ic_launcher"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tweet_user_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:maxLines="2"
                android:textStyle="bold"
                tools:text="droidmed"/>

            <TextView
                android:id="@+id/tweet_message"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:text="title"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:orientation="horizontal">
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="r"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="t"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="f"/>
            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>


text:
package org.apache.beam.runners.dataflow.options;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.beam.runners.dataflow.DataflowRunner;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
import org.apache.beam.sdk.extensions.gcp.options.GcsOptions;
import org.apache.beam.sdk.io.FileSystems;
import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryOptions;
import org.apache.beam.sdk.io.gcp.pubsub.PubsubOptions;
import org.apache.beam.sdk.options.ApplicationNameOptions;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.DefaultValueFactory;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.Hidden;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.StreamingOptions;
import org.apache.beam.sdk.options.Validation;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Options that can be used to configure the {@link DataflowRunner}. */
@Description("Options that configure the Dataflow pipeline.")
public interface DataflowPipelineOptions
    extends PipelineOptions,
        GcpOptions,
        ApplicationNameOptions,
        DataflowPipelineDebugOptions,
        DataflowPipelineWorkerPoolOptions,
        BigQueryOptions,
        GcsOptions,
        StreamingOptions,
        CloudDebuggerOptions,
        DataflowWorkerLoggingOptions,
        DataflowProfilingOptions,
        PubsubOptions {

  @Description(
      "Project id. Required when running a Dataflow in the cloud. "
          + "See https://cloud.google.com/storage/docs/projects for further details.")
  @Override
  @Validation.Required
  @Default.InstanceFactory(DefaultProjectFactory.class)
  String getProject();

  @Override
  void setProject(String value);

  /**
   * GCS path for staging local files, e.g. gs://bucket/object
   *
   *
Must be a valid Cloud Storage URL, beginning with the prefix "gs://"
   *
   *
If {@link #getStagingLocation()} is not set, it will default to {@link
   * GcpOptions#getGcpTempLocation()}. {@link GcpOptions#getGcpTempLocation()} must be a valid GCS
   * path.
   */
  @Description(
      "GCS path for staging local files, e.g. \"gs://bucket/object\". "
          + "Must be a valid Cloud Storage URL, beginning with the prefix \"gs://\". "
          + "If stagingLocation is unset, defaults to gcpTempLocation with \"/staging\" suffix.")
  @Default.InstanceFactory(StagingLocationFactory.class)
  String getStagingLocation();

  void setStagingLocation(String value);

  /** Whether to update the currently running pipeline with the same name as this one. */
  @Description(
      "If set, replace the existing pipeline with the name specified by --jobName with "
          + "this pipeline, preserving state.")
  boolean isUpdate();

  void setUpdate(boolean value);

  /** If set, the snapshot from which the job should be created. */
  @Hidden
  @Experimental
  @Description("If set, the snapshot from which the job should be created.")
  String getCreateFromSnapshot();

  void setCreateFromSnapshot(String value);

  /** Where the runner should generate a template file. Must either be local or Cloud Storage. */
  @Description(
      "Where the runner should generate a template file. "
          + "Must either be local or Cloud Storage.")
  String getTemplateLocation();

  void setTemplateLocation(String value);

  /** Run the job as a specific service account, instead of the default GCE robot. */
  @Hidden
  @Experimental
  @Description("Run the job as a specific service account, instead of the default GCE robot.")
  String getServiceAccount();

  void setServiceAccount(String value);

  /**
   * The Google Compute Engine region for
   * creating Dataflow jobs.
   */
  @Hidden
  @Experimental
  @Description(
      "The Google Compute Engine region for creating Dataflow jobs. See "
          + "https://cloud.google.com/compute/docs/regions-zones/regions-zones for a list of valid "
          + "options. Currently defaults to us-central1, but future releases of Beam will "
          + "require the user to set the region explicitly.")
  @Default.InstanceFactory(DefaultGcpRegionFactory.class)
  String getRegion();

  void setRegion(String region);

  /** Labels that will be applied to the billing records for this job. */
  @Description("Labels that will be applied to the billing records for this job.")
  Map<String, String> getLabels();

  void setLabels(Map<String, String> labels);

  /** The URL of the staged portable pipeline. */
  @Description("The URL of the staged portable pipeline")
  String getPipelineUrl();

  void setPipelineUrl(String urlString);

  @Description("The customized dataflow worker jar")
  String getDataflowWorkerJar();

  void setDataflowWorkerJar(String dataflowWorkerJar);

  /** Set of available Flexible Resource Scheduling goals. */
  enum FlexResourceSchedulingGoal {
    /** No goal specified. */
    UNSPECIFIED,

    /** Optimize for lower execution time. */
    SPEED_OPTIMIZED,

    /** Optimize for lower cost. */
    COST_OPTIMIZED,
  }

  /** This option controls Flexible Resource Scheduling mode. */
  @Description("Controls the Flexible Resource Scheduling mode.")
  @Default.Enum("UNSPECIFIED")
  FlexResourceSchedulingGoal getFlexRSGoal();

  void setFlexRSGoal(FlexResourceSchedulingGoal goal);

  /** Returns a default staging location under {@link GcpOptions#getGcpTempLocation}. */
  class StagingLocationFactory implements DefaultValueFactory<String> {
    private static final Logger LOG = LoggerFactory.getLogger(StagingLocationFactory.class);

    @Override
    public String create(PipelineOptions options) {
      GcsOptions gcsOptions = options.as(GcsOptions.class);
      LOG.info("No stagingLocation provided, falling back to gcpTempLocation");
      String gcpTempLocation;
      try {
        gcpTempLocation = gcsOptions.getGcpTempLocation();
      } catch (Exception e) {
        throw new IllegalArgumentException(
            "Error constructing default value for stagingLocation: failed to retrieve gcpTempLocation. "
                + "Either stagingLocation must be set explicitly or a valid value must be provided"
                + "for gcpTempLocation.",
            e);
      }
      try {
        gcsOptions.getPathValidator().validateOutputFilePrefixSupported(gcpTempLocation);
      } catch (Exception e) {
        throw new IllegalArgumentException(
            String.format(
                "Error constructing default value for stagingLocation: gcpTempLocation is not"
                    + " a valid GCS path, %s. ",
                gcpTempLocation),
            e);
      }
      return FileSystems.matchNewResource(gcpTempLocation, true /* isDirectory */)
          .resolve("staging", StandardResolveOptions.RESOLVE_DIRECTORY)
          .toString();
    }
  }

  /**
   * Factory for a default value for Google Cloud region according to
   * https://cloud.google.com/compute/docs/gcloud-compute/#default-properties. If no other default
   * can be found, returns "us-central1".
   */
  class DefaultGcpRegionFactory implements DefaultValueFactory<String> {
    private static final Logger LOG = LoggerFactory.getLogger(DefaultGcpRegionFactory.class);

    @Override
    public String create(PipelineOptions options) {
      String environmentRegion = getRegionFromEnvironment();
      if (!Strings.isNullOrEmpty(environmentRegion)) {
        LOG.info("Using default GCP region {} from $CLOUDSDK_COMPUTE_REGION", environmentRegion);
        return environmentRegion;
      }
      try {
        String gcloudRegion = getRegionFromGcloudCli();
        if (!gcloudRegion.isEmpty()) {
          LOG.info("Using default GCP region {} from gcloud CLI", gcloudRegion);
          return gcloudRegion;
        }
      } catch (Exception e) {
        // Ignore.
        LOG.debug("Unable to get gcloud compute region", e);
      }
      LOG.warn(
          "Region will default to us-central1. Future releases of Beam will "
              + "require the user to set the region explicitly. "
              + "https://cloud.google.com/compute/docs/regions-zones/regions-zones");
      return "us-central1";
    }

    @VisibleForTesting
    static String getRegionFromEnvironment() {
      return System.getenv("CLOUDSDK_COMPUTE_REGION");
    }

    @VisibleForTesting
    static String getRegionFromGcloudCli() throws IOException, InterruptedException {
      ProcessBuilder pb =
          new ProcessBuilder(Arrays.asList("gcloud", "config", "get-value", "compute/region"));
      Process process = pb.start();
      try (BufferedReader reader =
              new BufferedReader(
                  new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
          BufferedReader errorReader =
              new BufferedReader(
                  new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) {
        if (process.waitFor(2, TimeUnit.SECONDS) && process.exitValue() == 0) {
          return reader.lines().collect(Collectors.joining());
        } else {
          String stderr = errorReader.lines().collect(Collectors.joining("\n"));
          throw new RuntimeException(
              String.format(
                  "gcloud exited with exit value %d. Stderr:%n%s", process.exitValue(), stderr));
        }
      }
    }
  }
}


text:
import React from 'react'
import PropTypes from 'prop-types'

import analytics from 'src/analytics'

/**
 * Wraps standard <a> to track outgoing link on `click`.
 */
class OutLink extends React.PureComponent<any> {
    static propTypes = { to: PropTypes.string.isRequired }

    trackLinkClick = () =>
        analytics.trackEvent({
            category: 'Global',
            action: 'visitExternalLink',
            value: this.props.to,
        })

    render() {
        const { to, ...props } = this.props
        return (
            <a
                target="_blank"
                onClick={this.trackLinkClick}
                href={to}
                {...props}
            />
        )
    }
}

export default OutLink


text:
package gui.menuItems;

import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URI;

import javax.swing.JMenuItem;

public class AboutMenuItem extends JMenuItem implements ActionListener {

	private static final long serialVersionUID = -4588441455796244750L;

	private URI uri;

	public AboutMenuItem() {

		String url = "https://github.com/Dacaspex/Fractal#fractal";
		uri = URI.create(url);

		setText("About");
		addActionListener(this);

	}

	@Override
	public void actionPerformed(ActionEvent arg0) {

		try {

			Desktop.getDesktop().browse(uri);

		} catch (IOException e) {

			e.printStackTrace();

		}

	}

}