text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;

namespace Microsoft.Azure.Management.ApiManagement
{
    /// <summary>
    /// Operations for managing Authorization Servers.
    /// </summary>
    public partial interface IAuthorizationServersOperations
    {
        /// <summary>
        /// Creates new authorization server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// The name of the Api Management service.
        /// </param>
        /// <param name='authsid'>
        /// Identifier of the authorization server.
        /// </param>
        /// <param name='parameters'>
        /// Create or update parameters.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        Task<AzureOperationResponse> CreateAsync(string resourceGroupName, string serviceName, string authsid, AuthorizationServerCreateOrUpdateParameters parameters, CancellationToken cancellationToken);

        /// <summary>
        /// Deletes specific auuthorization server instance.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// The name of the Api Management service.
        /// </param>
        /// <param name='authsid'>
        /// Identifier of the authorization server.
        /// </param>
        /// <param name='etag'>
        /// ETag.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string authsid, string etag, CancellationToken cancellationToken);

        /// <summary>
        /// Gets specific authorizations server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// The name of the Api Management service.
        /// </param>
        /// <param name='authsid'>
        /// Identifier of the authorization server.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Get Authorizations server operation response details.
        /// </returns>
        Task<AuthorizationServerGetResponse> GetAsync(string resourceGroupName, string serviceName, string authsid, CancellationToken cancellationToken);

        /// <summary>
        /// List all authorization servers.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// The name of the Api Management service.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List Authorization Servers operation response details.
        /// </returns>
        Task<AuthorizationServerListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken);

        /// <summary>
        /// List all authorization servers.
        /// </summary>
        /// <param name='nextLink'>
        /// NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// List Authorization Servers operation response details.
        /// </returns>
        Task<AuthorizationServerListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken);

        /// <summary>
        /// Patches existing authorization server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// The name of the Api Management service.
        /// </param>
        /// <param name='authsid'>
        /// Identifier of the authorization server.
        /// </param>
        /// <param name='parameters'>
        /// Patch parameters.
        /// </param>
        /// <param name='etag'>
        /// ETag.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        Task<AzureOperationResponse> PatchAsync(string resourceGroupName, string serviceName, string authsid, PatchParameters parameters, string etag, CancellationToken cancellationToken);

        /// <summary>
        /// Updates existing authorization server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group.
        /// </param>
        /// <param name='serviceName'>
        /// The name of the Api Management service.
        /// </param>
        /// <param name='authsid'>
        /// Identifier of the authorization server.
        /// </param>
        /// <param name='parameters'>
        /// Create or update parameters.
        /// </param>
        /// <param name='etag'>
        /// ETag.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        Task<AzureOperationResponse> UpdateAsync(string resourceGroupName, string serviceName, string authsid, AuthorizationServerCreateOrUpdateParameters parameters, string etag, CancellationToken cancellationToken);
    }
}


text:
ALTER TABLE {$NAMESPACE}_phame.phame_blog
  ADD status VARCHAR(32) NOT NULL COLLATE {$COLLATE_TEXT};

redpajama_set_name: RedPajamaGithub


text:
<?php

class UserHistoryModel extends CI_Model
{
    public function insert(
        $idUser,
        $currentXpPoints,
        $newXpPoints,
        $evalXpPoints,
        $currentRankId,
        $newRankId,
        $commitId
    ) {
        return
            $this->db->insert('ivvll_user_history',
                [
                    'IdUser' => $idUser,
                    'CurrentXpPoints' => $currentXpPoints,
                    'NewXpPoints' => $newXpPoints,
                    'EvalXpPoints' => $evalXpPoints,
                    'CurrentRankId' => $currentRankId,
                    'NewRankId' => $newRankId,
                    'CommitId' => $commitId
                ]);
    }

    public function getUserHistory($userId, $startDate = null, $endDate = null, $order = 'ASC')
    {
        if (!is_null($startDate)) {
            $this->db->where('EvalTime >=', $startDate);
        }
        if (!is_null($startDate)) {
            $this->db->where('EvalTime <', $endDate);
        }

        if (!is_null($order)) {
            $this->db->order_by('EvalTime', 'ASC');
        }

        return $this->db
            ->from('ivvll_user_history')
            ->where('IdUser', $userId)
            ->get()
            ->result_array();
    }
}


text:
"""Helper class to test ssh-related code."""

from ganeti import constants
from ganeti import pathutils
from ganeti import errors

from collections import namedtuple

class FakeSshFileManager(object):
  """Class which 'fakes' the lowest layer of SSH key manipulation.

  There are various operations which touch the nodes' SSH keys and their
  respective key files (authorized_keys and ganeti_pub_keys). Those are
  tedious to test as file operations have to be mocked on different levels
  (direct access to the authorized_keys and ganeti_pub_keys) of the master
  node, indirect access to those files of the non-master nodes (via the
  ssh_update tool). In order to make unit tests of those operations more
  readable and managable, we introduce this class, which mocks all
  direct and indirect access to SSH key files on all nodes. This way,
  the state of this FakeSshFileManager represents the state of a cluster's
  nodes' SSH key files in a consise and easily accessible way.

  """
  def __init__(self):
    # Dictionary mapping node name to node properties. The properties
    # are a named tuple of (node_uuid, ssh_key, is_potential_master_candidate,
    # is_master_candidate, is_master).
    self._all_node_data = {}
    # Dictionary emulating the authorized keys files of all nodes. The
    # indices of the dictionary are the node names, the values are sets
    # of keys (strings).
    self._authorized_keys = {}
    # Dictionary emulating the public keys file of all nodes. The indices
    # of the dictionary are the node names where the public key file is
    # 'located' (if it wasn't faked). The values of the dictionary are
    # dictionaries itself. Each of those dictionaries is indexed by the
    # node UUIDs mapping to a list of public keys.
    self._public_keys = {} # dict of dicts
    # Node name of the master node
    self._master_node_name = None
    # Dictionary mapping nodes by name to number of retries where 'RunCommand'
    # succeeds. For example if set to '3', RunCommand will fail two times when
    # called for this node before it succeeds in the 3rd retry.
    self._max_retries = {}
    # Dictionary mapping nodes by name to number of retries which
    # 'RunCommand' has already carried out.
    self._retries = {}

    self._AssertTypePublicKeys()
    self._AssertTypeAuthorizedKeys()

  _NodeInfo = namedtuple(
      "NodeInfo",
      ["uuid",
       "key",
       "is_potential_master_candidate",
       "is_master_candidate",
       "is_master"])

  def _SetMasterNodeName(self):
    self._master_node_name = [name for name, node_info
                              in self._all_node_data.items()
                              if node_info.is_master][0]

  def GetMasterNodeName(self):
    return self._master_node_name

  def _CreateNodeDict(self, num_nodes, num_pot_mcs, num_mcs):
    """Creates a dictionary of all nodes and their properties."""

    self._all_node_data = {}
    for i in range(num_nodes):
      name = "node_name_%i" % i
      uuid = "node_uuid_%i" % i
      key = "key%s" % i
      self._public_keys[name] = {}
      self._authorized_keys[name] = set()

      pot_mc = i < num_pot_mcs
      mc = i < num_mcs
      master = i == num_mcs / 2

      self._all_node_data[name] = self._NodeInfo(uuid, key, pot_mc, mc, master)

    self._AssertTypePublicKeys()
    self._AssertTypeAuthorizedKeys()

  def _FillPublicKeyOfOneNode(self, receiving_node_name):
    node_info = self._all_node_data[receiving_node_name]
    # Nodes which are not potential master candidates receive no keys
    if not node_info.is_potential_master_candidate:
      return
    for node_info in self._all_node_data.values():
      if node_info.is_potential_master_candidate:
        self._public_keys[receiving_node_name][node_info.uuid] = [node_info.key]

  def _FillAuthorizedKeyOfOneNode(self, receiving_node_name):
    for node_name, node_info in self._all_node_data.items():
      if node_info.is_master_candidate \
          or node_name == receiving_node_name:
        self._authorized_keys[receiving_node_name].add(node_info.key)

  def InitAllNodes(self, num_nodes, num_pot_mcs, num_mcs):
    """Initializes the entire state of the cluster wrt SSH keys.

    @type num_nodes: int
    @param num_nodes: number of nodes in the cluster
    @type num_pot_mcs: int
    @param num_pot_mcs: number of potential master candidates in the cluster
    @type num_mcs: in
    @param num_mcs: number of master candidates in the cluster.

    """
    self._public_keys = {}
    self._authorized_keys = {}
    self._CreateNodeDict(num_nodes, num_pot_mcs, num_mcs)
    for node in self._all_node_data.keys():
      self._FillPublicKeyOfOneNode(node)
      self._FillAuthorizedKeyOfOneNode(node)
    self._SetMasterNodeName()
    self._AssertTypePublicKeys()
    self._AssertTypeAuthorizedKeys()

  def SetMaxRetries(self, node_name, retries):
    """Set the number of unsuccessful retries of 'RunCommand' per node.

    @type node_name: string
    @param node_name: name of the node
    @type retries: integer
    @param retries: number of unsuccessful retries

    """
    self._max_retries[node_name] = retries

  def GetSshPortMap(self, port):
    """Creates a SSH port map with all nodes mapped to the given port.

    @type port: int
    @param port: SSH port number for all nodes

    """
    port_map = {}
    for node in self._all_node_data.keys():
      port_map[node] = port
    return port_map

  def GetAllNodeNames(self):
    """Returns all node names of the cluster.

    @rtype: list of str
    @returns: list of all node names
    """
    return self._all_node_data.keys()

  def GetAllPotentialMasterCandidateNodeNames(self):
    return [name for name, node_info
            in self._all_node_data.items()
            if node_info.is_potential_master_candidate]

  def GetAllMasterCandidateUuids(self):
    return [node_info.uuid for node_info
            in self._all_node_data.values() if node_info.is_master_candidate]

  def GetAllPurePotentialMasterCandidates(self):
    """Get the potential master candidates which are not master candidates.

    @rtype: list of tuples (string, C{_NodeInfo})
    @returns: list of tuples of node name and node information of nodes
              which are potential master candidates but not master
              candidates
    """
    return [(name, node_info) for name, node_info
            in self._all_node_data.items()
            if node_info.is_potential_master_candidate and
            not node_info.is_master_candidate]

  def GetAllMasterCandidates(self):
    """Get all master candidate nodes.

    @rtype: list of tuples (string, C{_NodeInfo})
    @returns: list of tuples of node name and node information of master
              candidate nodes.
    """
    return [(name, node_info) for name, node_info
            in self._all_node_data.items() if node_info.is_master_candidate]

  def GetAllNormalNodes(self):
    """Get all normal nodes.

    Normal nodes are nodes that are neither master, master candidate nor
    potential master candidate.

    @rtype: list of tuples (string, C{_NodeInfo})
    @returns: list of tuples of node name and node information of normal
              nodes
    """
    return [(name, node_info) for name, node_info
            in self._all_node_data.items() if not node_info.is_master_candidate
            and not node_info.is_potential_master_candidate]

  def GetAllNodesDiverse(self):
    """This returns all nodes in a diverse order.

    This will return all nodes, but makes sure that they are ordered so that
    the list will contain in a round-robin fashion, a master candidate,
    a potential master candidate, a normal node, then again a master
    candidate, etc.

    @rtype: list of tuples (string, C{_NodeInfo})
    @returns: list of tuples of node name and node information

    """
    master_candidates = self.GetAllMasterCandidates()
    potential_master_candidates = self.GetAllPurePotentialMasterCandidates()
    normal_nodes = self.GetAllNormalNodes()

    mixed_list = []

    i = 0

    assert (len(self._all_node_data) == len(master_candidates)
            + len(potential_master_candidates) + len(normal_nodes))

    while len(mixed_list) < len(self._all_node_data):
      if i % 3 == 0:
        if master_candidates:
          mixed_list.append(master_candidates[0])
          master_candidates = master_candidates[1:]
      elif i % 3 == 1:
        if potential_master_candidates:
          mixed_list.append(potential_master_candidates[0])
          potential_master_candidates = potential_master_candidates[1:]
      else:  # i % 3 == 2
        if normal_nodes:
          mixed_list.append(normal_nodes[0])
          normal_nodes = normal_nodes[1:]
      i += 1

    return mixed_list

  def GetPublicKeysOfNode(self, node):
    """Returns the public keys that are stored on the given node.

    @rtype: dict of str to list of str
    @returns: a mapping of node names to a list of public keys

    """
    return self._public_keys[node]

  def GetAuthorizedKeysOfNode(self, node):
    """Returns the authorized keys of the given node.

    @rtype: list of str
    @returns: a list of authorized keys that are stored on that node

    """
    return self._authorized_keys[node]

  def SetOrAddNode(self, name, uuid, key, pot_mc, mc, master):
    """Adds a new node to the state of the file manager.

    This is necessary when testing to add new nodes to the cluster. Otherwise
    this new node's state would not be evaluated properly with the assertion
    functions.

    @type name: string
    @param name: name of the new node
    @type uuid: string
    @param uuid: UUID of the new node
    @type key: string
    @param key: SSH key of the new node
    @type pot_mc: boolean
    @param pot_mc: whether the new node is a potential master candidate
    @type mc: boolean
    @param mc: whether the new node is a master candidate
    @type master: boolean
    @param master: whether the new node is the master

    """
    self._all_node_data[name] = self._NodeInfo(uuid, key, pot_mc, mc, master)
    if name not in self._authorized_keys:
      self._authorized_keys[name] = set()
    if mc:
      self._authorized_keys[name].add(key)
    if name not in self._public_keys:
      self._public_keys[name] = {}
    self._AssertTypePublicKeys()
    self._AssertTypeAuthorizedKeys()

  def NodeHasPublicKey(self, file_node_name, key_node_uuid, key):
    """Checks whether a node has another node's public key.

    @type file_node_name: string
    @param file_node_name: name of the node whose public key file is inspected
    @type key_node_uuid: string
    @param key_node_uuid: UUID of the node whose key is checked for
    @rtype: boolean
    @return: True if the key_node's UUID is found with the machting key 'key'

    """
    for (node_uuid, pub_keys) in self._public_keys[file_node_name].items():
      if key in pub_keys and key_node_uuid == node_uuid:
        return True
    return False

  def NodeHasAuthorizedKey(self, file_node_name, key):
    """Checks whether a node has a particular key in its authorized_keys file.

    @type file_node_name: string
    @param file_node_name: name of the node whose authorized_key file is
      inspected
    @type key: string
    @param key: key which is expected to be found in the node's authorized_key
      file
    @rtype: boolean
    @return: True if the key is found in the node's authorized_key file

    """
    return key in self._authorized_keys[file_node_name]

  def AssertNodeSetOnlyHasAuthorizedKey(self, node_set, query_node_key):
    """Check if nodes in the given set only have a particular authorized key.

    @type node_set: list of strings
    @param node_set: list of nodes who are supposed to have the key
    @type query_node_key: string
    @param query_node_key: key which is looked for

    """
    assert isinstance(node_set, list)
    for node_name in self._all_node_data.keys():
      if node_name in node_set:
        if not self.NodeHasAuthorizedKey(node_name, query_node_key):
          raise Exception("Node '%s' does not have authorized key '%s'."
                          % (node_name, query_node_key))
      else:
        if self.NodeHasAuthorizedKey(node_name, query_node_key):
          raise Exception("Node '%s' has authorized key '%s' although it"
                          " should not." % (node_name, query_node_key))

  def AssertAllNodesHaveAuthorizedKey(self, key):
    """Check if all nodes have a particular key in their auth. keys file.

    @type key: string
    @param key: key exptected to be present in all node's authorized_keys file
    @raise Exception: if a node does not have the authorized key.

    """
    self.AssertNodeSetOnlyHasAuthorizedKey(self._all_node_data.keys(), key)

  def AssertNoNodeHasAuthorizedKey(self, key):
    """Check if none of the nodes has a particular key in their auth. keys file.

    @type key: string
    @param key: key exptected to be present in all node's authorized_keys file
    @raise Exception: if a node *does* have the authorized key.

    """
    self.AssertNodeSetOnlyHasAuthorizedKey([], key)

  def AssertNodeSetOnlyHasPublicKey(self, node_set, query_node_uuid,
                                    query_node_key):
    """Check if nodes in the given set only have a particular public key.

    @type node_set: list of strings
    @param node_set: list of nodes who are supposed to have the key
    @type query_node_uuid: string
    @param query_node_uuid: uuid of the node whose key is looked for
    @type query_node_key: string
    @param query_node_key: key which is looked for

    """
    for node_name in self._all_node_data.keys():
      if node_name in node_set:
        if not self.NodeHasPublicKey(node_name, query_node_uuid,
                                     query_node_key):
          raise Exception("Node '%s' does not have public key '%s' of node"
                          " '%s'." % (node_name, query_node_key,
                                      query_node_uuid))
      else:
        if self.NodeHasPublicKey(node_name, query_node_uuid, query_node_key):
          raise Exception("Node '%s' has public key '%s' of node"
                          " '%s' although it should not."
                          % (node_name, query_node_key, query_node_uuid))

  def AssertNoNodeHasPublicKey(self, uuid, key):
    """Check if none of the nodes have the given public key in their file.

    @type uuid: string
    @param uuid: UUID of the node whose key is looked for
    @raise Exception: if a node *does* have the public key.

    """
    self.AssertNodeSetOnlyHasPublicKey([], uuid, key)

  def AssertPotentialMasterCandidatesOnlyHavePublicKey(self, query_node_name):
    """Checks if the node's key is on all potential master candidates only.

    This ensures that the node's key is in all public key files of all
    potential master candidates, and it also checks whether the key is
    *not* in all other nodes's key files.

    @param query_node_name: name of the node whose key is expected to be
                            in the public key file of all potential master
                            candidates
    @type query_node_name: string
    @raise Exception: when a potential master candidate does not have
                      the public key or a normal node *does* have a public key.

    """
    query_node_uuid, query_node_key, _, _, _ = \
        self._all_node_data[query_node_name]
    potential_master_candidates = self.GetAllPotentialMasterCandidateNodeNames()
    self.AssertNodeSetOnlyHasPublicKey(
        potential_master_candidates, query_node_uuid, query_node_key)

  def _AssertTypePublicKeys(self):
    """Asserts that the public key dictionary has the right types.

    This is helpful as an invariant that shall not be violated during the
    tests due to type errors.

    """
    assert isinstance(self._public_keys, dict)
    for node_file, pub_keys in self._public_keys.items():
      assert isinstance(node_file, str)
      assert isinstance(pub_keys, dict)
      for node_key, keys in pub_keys.items():
        assert isinstance(node_key, str)
        assert isinstance(keys, list)
        for key in keys:
          assert isinstance(key, str)

  def _AssertTypeAuthorizedKeys(self):
    """Asserts that the authorized keys dictionary has the right types.

    This is useful to check as an invariant that is not supposed to be violated
    during the tests.

    """
    assert isinstance(self._authorized_keys, dict)
    for node_file, auth_keys in self._authorized_keys.items():
      assert isinstance(node_file, str)
      assert isinstance(auth_keys, set)
      for key in auth_keys:
        assert isinstance(key, str)

  # Disabling a pylint warning about unused parameters. Those need
  # to be here to properly mock the real methods.
  # pylint: disable=W0613
  def RunCommand(self, cluster_name, node, base_cmd, port, data,
                 debug=False, verbose=False, use_cluster_key=False,
                 ask_key=False, strict_host_check=False,
                 ensure_version=False):
    """This emulates ssh.RunSshCmdWithStdin calling ssh_update.

    While in real SSH operations, ssh.RunSshCmdWithStdin is called
    with the command ssh_update to manipulate a remote node's SSH
    key files (authorized_keys and ganeti_pub_key) file, this method
    emulates the operation by manipulating only its internal dictionaries
    of SSH keys. No actual key files of any node is touched.

    """
    if node in self._max_retries:
      if node not in self._retries:
        self._retries[node] = 0
      self._retries[node] += 1
      if self._retries[node] < self._max_retries[node]:
        raise errors.OpExecError("(Fake) SSH connection to node '%s' failed."
                                 % node)

    assert base_cmd == pathutils.SSH_UPDATE

    if constants.SSHS_SSH_AUTHORIZED_KEYS in data:
      instructions_auth = data[constants.SSHS_SSH_AUTHORIZED_KEYS]
      self._HandleAuthorizedKeys(instructions_auth, node)
    if constants.SSHS_SSH_PUBLIC_KEYS in data:
      instructions_pub = data[constants.SSHS_SSH_PUBLIC_KEYS]
      self._HandlePublicKeys(instructions_pub, node)
  # pylint: enable=W0613

  def _EnsureAuthKeyFile(self, file_node_name):
    if file_node_name not in self._authorized_keys:
      self._authorized_keys[file_node_name] = set()
    self._AssertTypePublicKeys()
    self._AssertTypeAuthorizedKeys()

  def _AddAuthorizedKeys(self, file_node_name, ssh_keys):
    """Mocks adding the given keys to the authorized_keys file."""
    assert isinstance(ssh_keys, list)
    self._EnsureAuthKeyFile(file_node_name)
    for key in ssh_keys:
      self._authorized_keys[file_node_name].add(key)
    self._AssertTypePublicKeys()
    self._AssertTypeAuthorizedKeys()

  def _RemoveAuthorizedKeys(self, file_node_name, keys):
    """Mocks removing the keys from authorized_keys on the given node.

    @param keys: list of ssh keys
    @type keys: list of strings

    """
    self._EnsureAuthKeyFile(file_node_name)
    self._authorized_keys[file_node_name] = \
        set([k for k in self._authorized_keys[file_node_name] if k not in keys])
    self._AssertTypeAuthorizedKeys()

  def _HandleAuthorizedKeys(self, instructions, node):
    (action, authorized_keys) = instructions
    ssh_key_sets = authorized_keys.values()
    if action == constants.SSHS_ADD:
      for ssh_keys in ssh_key_sets:
        self._AddAuthorizedKeys(node, ssh_keys)
    elif action == constants.SSHS_REMOVE:
      for ssh_keys in ssh_key_sets:
        self._RemoveAuthorizedKeys(node, ssh_keys)
    else:
      raise Exception("Unsupported action: %s" % action)
    self._AssertTypeAuthorizedKeys()

  def _EnsurePublicKeyFile(self, file_node_name):
    if file_node_name not in self._public_keys:
      self._public_keys[file_node_name] = {}
    self._AssertTypePublicKeys()

  def _ClearPublicKeys(self, file_node_name):
    self._public_keys[file_node_name] = {}
    self._AssertTypePublicKeys()

  def _OverridePublicKeys(self, ssh_keys, file_node_name):
    assert isinstance(ssh_keys, dict)
    self._ClearPublicKeys(file_node_name)
    for key_node_uuid, node_keys in ssh_keys.items():
      assert isinstance(node_keys, list)
      if key_node_uuid in self._public_keys[file_node_name]:
        raise Exception("Duplicate node in ssh_update data.")
      self._public_keys[file_node_name][key_node_uuid] = node_keys
    self._AssertTypePublicKeys()

  def _ReplaceOrAddPublicKeys(self, public_keys, file_node_name):
    assert isinstance(public_keys, dict)
    self._EnsurePublicKeyFile(file_node_name)
    for key_node_uuid, keys in public_keys.items():
      assert isinstance(keys, list)
      self._public_keys[file_node_name][key_node_uuid] = keys
    self._AssertTypePublicKeys()

  def _RemovePublicKeys(self, public_keys, file_node_name):
    assert isinstance(public_keys, dict)
    self._EnsurePublicKeyFile(file_node_name)
    for key_node_uuid, _ in public_keys.items():
      if key_node_uuid in self._public_keys[file_node_name]:
        self._public_keys[file_node_name][key_node_uuid] = []
    self._AssertTypePublicKeys()

  def _HandlePublicKeys(self, instructions, node):
    (action, public_keys) = instructions
    if action == constants.SSHS_OVERRIDE:
      self._OverridePublicKeys(public_keys, node)
    elif action == constants.SSHS_ADD:
      self._ReplaceOrAddPublicKeys(public_keys, node)
    elif action == constants.SSHS_REPLACE_OR_ADD:
      self._ReplaceOrAddPublicKeys(public_keys, node)
    elif action == constants.SSHS_REMOVE:
      self._RemovePublicKeys(public_keys, node)
    elif action == constants.SSHS_CLEAR:
      self._ClearPublicKeys(node)
    else:
      raise Exception("Unsupported action: %s." % action)
    self._AssertTypePublicKeys()

  # pylint: disable=W0613
  def AddAuthorizedKeys(self, file_obj, keys):
    """Emulates ssh.AddAuthorizedKeys on the master node.

    Instead of actually mainpulating the authorized_keys file, this method
    keeps the state of the file in a dictionary in memory.

    @see: C{ssh.AddAuthorizedKeys}

    """
    assert isinstance(keys, list)
    assert self._master_node_name
    self._AddAuthorizedKeys(self._master_node_name, keys)
    self._AssertTypeAuthorizedKeys()

  def RemoveAuthorizedKeys(self, file_name, keys):
    """Emulates ssh.RemoveAuthorizeKeys on the master node.

    Instead of actually mainpulating the authorized_keys file, this method
    keeps the state of the file in a dictionary in memory.

    @see: C{ssh.RemoveAuthorizedKeys}

    """
    assert isinstance(keys, list)
    assert self._master_node_name
    self._RemoveAuthorizedKeys(self._master_node_name, keys)
    self._AssertTypeAuthorizedKeys()

  def AddPublicKey(self, new_uuid, new_key, **kwargs):
    """Emulates ssh.AddPublicKey on the master node.

    Instead of actually mainpulating the authorized_keys file, this method
    keeps the state of the file in a dictionary in memory.

    @see: C{ssh.AddPublicKey}

    """
    assert self._master_node_name
    assert isinstance(new_key, str)
    key_dict = {new_uuid: [new_key]}
    self._ReplaceOrAddPublicKeys(key_dict, self._master_node_name)
    self._AssertTypePublicKeys()

  def RemovePublicKey(self, target_uuid, **kwargs):
    """Emulates ssh.RemovePublicKey on the master node.

    Instead of actually mainpulating the authorized_keys file, this method
    keeps the state of the file in a dictionary in memory.

    @see: {ssh.RemovePublicKey}

    """
    assert self._master_node_name
    key_dict = {target_uuid: []}
    self._RemovePublicKeys(key_dict, self._master_node_name)
    self._AssertTypePublicKeys()

  def QueryPubKeyFile(self, target_uuids, **kwargs):
    """Emulates ssh.QueryPubKeyFile on the master node.

    Instead of actually mainpulating the authorized_keys file, this method
    keeps the state of the file in a dictionary in memory.

    @see: C{ssh.QueryPubKey}

    """
    assert self._master_node_name
    all_keys = target_uuids is None
    if all_keys:
      return self._public_keys[self._master_node_name]

    if isinstance(target_uuids, str):
      target_uuids = [target_uuids]
    result_dict = {}
    for key_node_uuid, keys in \
        self._public_keys[self._master_node_name].items():
      if key_node_uuid in target_uuids:
        result_dict[key_node_uuid] = keys
    self._AssertTypePublicKeys()
    return result_dict

  def ReplaceNameByUuid(self, node_uuid, node_name, **kwargs):
    """Emulates ssh.ReplaceNameByUuid on the master node.

    Instead of actually mainpulating the authorized_keys file, this method
    keeps the state of the file in a dictionary in memory.

    @see: C{ssh.ReplacenameByUuid}

    """
    assert isinstance(node_uuid, str)
    assert isinstance(node_name, str)
    assert self._master_node_name
    if node_name in self._public_keys[self._master_node_name]:
      self._public_keys[self._master_node_name][node_uuid] = \
        self._public_keys[self._master_node_name][node_name][:]
      del self._public_keys[self._master_node_name][node_name]
    self._AssertTypePublicKeys()
  # pylint: enable=W0613


text:
<?php
declare(strict_types=1);

namespace AppBundle\Form;

use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class CommentFormType extends BaseFormType
{
    protected $formClass = CommentData::class;

    public function buildForm(FormBuilderInterface $builder, array $options) :void
    {
        $builder
            ->add('name', TextType::class)
            ->add('message', TextType::class)
        ;

    }
}


text:
#ifndef __ALUX_GARBAGE_OBJECT_HPP__
#define __ALUX_GARBAGE_OBJECT_HPP__

#include <ansa/linked-list>

namespace Alux {

class GarbageCollector;

class GarbageObject {
public:
  /**
   * Add this object to the garbage collector.
   * @ambicritical
   */
  void ThrowAway();

  /**
   * Deallocate this object on the spot.
   * @noncritical
   */
  virtual void Dealloc() = 0;

protected:
  GarbageObject(GarbageCollector &);
  virtual ~GarbageObject();

  friend class GarbageCollector;
  ansa::LinkedList<GarbageObject>::Link garbageLink;

private:
  GarbageCollector & collector;
};

}

#endif


text:
import unittest
import week1

class TestWeek1(unittest.TestCase):

    def test_add_works(self):
        self.assertEqual(4, week1.add(2, 2))

    def test_adding_without_numbers_causes_error(self):
        self.assertRaises(TypeError, week1.add, 2, '2')

    def test_sub_works(self):
        self.assertEquals(4, week1.sub(8, 5))

    def test_mul_works(self):
        self.assertEquals(20, week1.mul(4, 5))

    def test_div_works(self):
        self.assertEquals(10, week1.div(100, 10))

if __name__ == '__main__':
    unittest.main()


text:
package monix.reactive.consumers

import cats.laws._
import cats.laws.discipline._
import cats.effect.IO
import monix.execution.exceptions.DummyException
import monix.reactive.{ BaseTestSuite, Consumer, Observable }
import scala.util.Failure

object MapEvalConsumerSuite extends BaseTestSuite {
  test("consumer.mapEval equivalence with task.map") { implicit s =>
    check1 { (obs: Observable[Int]) =>
      val consumer = Consumer.foldLeft[Long, Int](0L)(_ + _)
      val t1 = obs.consumeWith(consumer.mapEval(x => IO(x + 100)))
      val t2 = obs.consumeWith(consumer).map(_ + 100)
      t1 <-> t2
    }
  }

  test("consumer.mapEval streams error") { implicit s =>
    check2 { (obs: Observable[Int], ex: Throwable) =>
      val withError = obs.endWithError(ex)
      val consumer = Consumer.foldLeft[Long, Int](0L)(_ + _)

      val t1 = withError.consumeWith(consumer.mapEval(x => IO(x + 100)))
      val t2 = withError.consumeWith(consumer).map(_ + 100)
      t1 <-> t2
    }
  }

  test("consumer.mapEval handles task errors") { implicit s =>
    val ex = DummyException("dummy")
    val f = Observable(1)
      .consumeWith(Consumer.head[Int].mapEval(_ => IO.raiseError(ex)))
      .runToFuture

    s.tick()
    assertEquals(f.value, Some(Failure(ex)))
  }

  test("consumer.mapEval protects against user code") { implicit s =>
    val ex = DummyException("dummy")
    val f = Observable(1)
      .consumeWith(Consumer.head[Int].mapEval(_ => (throw ex): IO[Int]))
      .runToFuture

    s.tick()
    assertEquals(f.value, Some(Failure(ex)))
  }

  test("consumer.mapEval(sync) equivalence with task.map") { implicit s =>
    check1 { (obs: Observable[Int]) =>
      val consumer = Consumer.foldLeft[Long, Int](0L)(_ + _)
      val t1 = obs.consumeWith(consumer.mapEval(x => IO(x + 100)))
      val t2 = obs.consumeWith(consumer).map(_ + 100)
      t1 <-> t2
    }
  }

  test("consumer.mapEval(sync) streams error") { implicit s =>
    check2 { (obs: Observable[Int], ex: Throwable) =>
      val withError = obs.endWithError(ex)
      val consumer = Consumer.foldLeft[Long, Int](0L)(_ + _)

      val t1 = withError.consumeWith(consumer.mapEval(x => IO(x + 100)))
      val t2 = withError.consumeWith(consumer).map(_ + 100)
      t1 <-> t2
    }
  }

  test("consumer.mapEval(sync) protects against user code") { implicit s =>
    val ex = DummyException("dummy")
    val f = Observable(1)
      .consumeWith(Consumer.head[Int].mapEval(_ => IO(throw ex)))
      .runToFuture

    s.tick()
    assertEquals(f.value, Some(Failure(ex)))
  }
}


text:
folderPath=""
blockSize="m"
blockSizeFriendly="MB"
warnThresh=""
critThresh=""

# Get the flags!
while getopts "f:b:w:c:" opt
	do
		case $opt in
			f ) folderPath=$OPTARG;;
			b ) blockSize=$OPTARG;;
			w ) warnThresh=$OPTARG;;
			c ) critThresh=$OPTARG;;
		esac
done

if [ "$folderPath" == "" ]
then
	printf "ERROR - You must provide a file path with -f!\n"
	exit 2
fi

if [ "$warnThresh" == "" ]
then
	printf "ERROR - You must provide a warning threshold with -w!\n"
	exit 2
fi

if [ "$critThresh" == "" ]
then
	printf "ERROR - You must provide a critical threshold with -c!\n"
	exit 2
fi

if [ "$blockSize" == "k" ]
then
	blockSizeFriendly="KB"
fi

if [ "$blockSize" == "g" ]
then
	blockSizeFriendly="GB"
fi

folderSize=`du -s$blockSize $folderPath | grep -E -o "[0-9]+"`

if [ "$folderSize" -ge "$critThresh" ]
then
	printf "CRITICAL - folder is $folderSize $blockSizeFriendly in size | folderSize=$folderSize;$warnThresh;$critThresh;\n"
	exit 2
elif [ "$folderSize" -ge "$warnThresh" ]
then
	printf "WARNING - folder is $folderSize $blockSizeFriendly in size | folderSize=$folderSize;$warnThresh;$critThresh;\n"
	exit 1
fi

printf "OK - folder is $folderSize $blockSizeFriendly in size | folderSize=$folderSize;$warnThresh;$critThresh;\n"
exit 0


text:
+++
#disabled = true
weight = 10
title = "Welcome To Rich Valley Harvest!"
subtitle = "It's nice to meet you"
button = "Tell me more"
lastmod = "2016-11-22"
date = "2016-11-22"

# Background image is located at 'static/img/header-bg.jpg'.
# To change replace the specified image.
+++


text:
<?php

namespace Kily\Delivery;

use Kily\Delivery\Base\Component;

class CalculatorResponse extends Component
{
    public $service;
    public $cost;
    public $period;

    public function getAttributes()
    {
        return array(
            'service' => $this->service,
            'cost' => $this->cost,
            'period' => $this->period,
        );
    }
}


text:
package org.globalnames.resolver.model.db

import java.util.UUID

import slick.jdbc.PostgresProfile.api._
import slick.lifted.ProvenShape

case class VernacularString(id: UUID, name: String)

class VernacularStrings(tag: Tag) extends Table[VernacularString](tag, "vernacular_strings") {
  def id: Rep[UUID] = column[UUID]("id", O.PrimaryKey)

  def name: Rep[String] = column[String]("name")

  def * : ProvenShape[VernacularString] =
    (id, name) <> (VernacularString.tupled, VernacularString.unapply)
}


text:
package com.hazelcast.spi.merge;

import com.hazelcast.spi.annotation.Beta;

/**
 * Represents a read-only view of a data structure key/value-pair for the merging process after a split-brain.
 *
 * @param <K> the type of the key
 * @param <V> the type of the value
 * @since 3.10
 */
@Beta
public interface MergingEntry<K, V> extends MergingValue<V> {

    /**
     * Returns the merging key in the in-memory format of the backing data structure.
     *
     * @return the merging key
     */
    K getKey();

    /**
     * Returns the deserialized merging key.
     *
     * @param <DK> the type of the deserialized key
     * @return the deserialized merging key
     */
    <DK> DK getDeserializedKey();
}


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  Infrastructure Systems, Services, and Climate Change: Integrated Impacts and Response Strategies for the Boston Metropolitan Area|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2017-01-26" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Project Research Results

Final Report

2002 Progress Report

2001 Progress Report

2000 Progress Report

                      47 publications for this project

                        3 journal articles for this project

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      Infrastructure Systems, Services, and Climate Change: Integrated Impacts and Response Strategies for the Boston Metropolitan Area

    EPA Grant Number: R827450

    Title: Infrastructure Systems, Services, and Climate Change: Integrated Impacts and Response Strategies for the Boston Metropolitan Area

    Investigators:
     Kirshen, Paul
        ,  Ruth, Matthias

        Current Investigators:

             Kirshen, Paul
            ,
             Anderson, William
            ,
             Chapra, Steve
            ,
             Chudyk, Wayne
            ,
             Edgers, Lewis
            ,
             Gute, David
            ,
             Lakshmanan, T. R.
            ,
             Ruth, Matthias
            ,
             Sanayei, Masoud
            ,
             Vogel, Richard

      Institution:

      Tufts University

     ,

    Boston University

    Current Institution:

          Tufts University

         ,

        Boston University
         ,

        University of Maryland

    	EPA Project Officer:

           Smith, Bernice

      Project Period:
      September 14, 1999 through
        September 13, 2003
          (Extended to March 12, 2004)

        Project Amount:

          $899,985

      RFA:
      Integrated Assessment of the Consequences of Climate Change (1999)

        		RFA Text |
          Recipients Lists

      Research Category:

          Ecological Indicators/Assessment/Restoration
          ,
          Global Climate Change
          ,
          Water
          ,
          Ecosystems
          ,
          Climate Change

Description:

The services provided by infrastructure systems include flood control, water
supply, drainage, waste water management, solid and hazardous waste management,
energy, transportation, providing constructed facilities for residential,
commercial, and industrial activities, communication, and recreation. The
infrastructure industry is one of the largest contributors to US Gross Domestic
Product. The real value of infrastructure, however, is that the socioeconomic
and environmental services it provides are essential; without them, the US
economy could not function and many human and environmental systems would
collapse. This is particularly the case in metropolitan areas.

Even though infrastructure systems and services (ISS) are designed according
to socioeconomic and environmental conditions that are very sensitive to climate
(for examples; energy and water demands, wind and water loads) and have
interrelated impacts upon each other, there have been no major integrated
assessments of the impacts of climate change on metropolitan ISS in the US.
Several researchers have shown that the possible economic damages to ISS because
of climate change are the same as or larger than damages to agriculture.
Infrastructure systems last considerably longer than decades (some a century or
more) and provide the footprint and direction for future ISS and related future
socioeconomic activities and environmental quality. Hence it is important that
decision-makers understand the short- and long-term consequences of climate
change on ISS. This includes both local and regional decision-makers because
they make most infrastructure-related decisions and state and national
decision-makers because they provide policy guidance.

The objectives of the proposed research include:

Documentation and analysis of the state of present infrastructure systems
and the socioeconomic and environmental services provided by them in the Boston
Metropolitan Area (BMA, includes the major cities of Boston and Cambridge and 99
other municipalities within approximately 20 miles of Boston - land use varies
from urban to farms and open space) using various indicators to indicate their
contribution to the quality of life in the region.

Determination of the integrated direct and indirect impacts of climate
change, socioeconomic, and technology scenarios on the future evolution of ISS
and the regional quality of life over time.

Identification and importance of policies and short- and long-term research
needs for the provision of infrastructure services that will meet stakeholder
needs over time given the uncertainties of climate and other changes.

Collaboration with the Metropolitan Area Planning Council (MAPC), our local
partner, to ensure that stakeholders are involved, their concerns are addressed,
and the project results are effectively communicated to them and the public at
large and to begin to engage stakeholders in the process of preparing for
potential climate change.

Approach:

The approach includes:
Work with stakeholders and experts to understand the multiple driving forces behind ISS in the BMA and the vertical and horizontal interrelationships of ISS demands and impacts.
Build a dynamic analytical modeling tool that incorporates this understanding and uses indicators to: (1) organize data; (2) model socioeconomic and environmental dynamics and interrelated impacts of ISS; and (3) aid in communication of project results.
Work with stakeholders to execute the model with climate change, socioeconomic, and technology scenarios to achieve the research objectives.
Communicate with the help of the MAPC to stakeholders and the general public throughout the project.

Expected Results:

The research will improve the risk management of the impacts on infrastructure from future uncertain climate, socioeconomic, environmental, and technology changes by showing possible impacts and driving forces behind those impacts and their sensitivities, working with stakeholders to develop short- and long-term resilient policies and programs to mitigate and adapt to impacts, and empowering stakeholders and the general public with the results.

Publications and Presentations:

        Publications have been submitted on this project: View all 47 publications for this project

Journal Articles:

          Journal Articles have been submitted on this project: View all 3 journal articles for this project

Supplemental Keywords:

      global warming, Massachusetts, adaptation, suburbs, humid, developed world., RFA, Scientific Discipline, Air, Geographic Area, Hydrology, climate change, State, Environmental Monitoring, Ecological Risk Assessment, Social Science, infrastructure systems, integrated assessments, water resources, policy making, flood control, energy generation, Boston Metropolitan Area, socioeconomic indicators, Massachusetts (MA), climate models, global warming, human activity, Boston, climate variability, Global Climate Change

Progress and Final Reports:

                2000 Progress Report

                2001 Progress Report

                2002 Progress Report

                Final Report

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Thursday, January 26, 2017


text:
package models.daos.slick

import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.daos.DelegableAuthInfoDAO
import com.mohiva.play.silhouette.impl.providers.PasswordInfo
import play.api.db.slick._
import scala.concurrent.Future
import models.daos.slick.DBTableDefinitions._
import play.api.db.slick.Config.driver.simple._

/**
 * The DAO to store the password information.
 */
class PasswordInfoDAOSlick extends DelegableAuthInfoDAO[PasswordInfo] {

  import play.api.Play.current

  /**
   * Saves the password info.
   *
   * @param loginInfo The login info for which the auth info should be saved.
   * @param authInfo The password info to save.
   * @return The saved password info or None if the password info couldn't be saved.
   */
  def save(loginInfo: LoginInfo, authInfo: PasswordInfo): Future[PasswordInfo] = {
    /*
    data += (loginInfo -> authInfo)
    Future.successful(authInfo)
    */
    Future.successful {
      DB withSession {implicit session =>
        val infoId = slickLoginInfos.filter(
          x => x.providerID === loginInfo.providerID && x.providerKey === loginInfo.providerKey
        ).first.id.get
        slickPasswordInfos insert DBPasswordInfo(authInfo.hasher, authInfo.password, authInfo.salt, infoId)
        authInfo
      }
    }
  }

  /**
   * Finds the password info which is linked with the specified login info.
   *
   * @param loginInfo The linked login info.
   * @return The retrieved password info or None if no password info could be retrieved for the given login info.
   */
  def find(loginInfo: LoginInfo): Future[Option[PasswordInfo]] = {
    Future.successful {
      DB withSession { implicit session =>
        slickLoginInfos.filter(info => info.providerID === loginInfo.providerID && info.providerKey === loginInfo.providerKey).firstOption match {
          case Some(info) =>
            val passwordInfo = slickPasswordInfos.filter(_.loginInfoId === info.id).first
            Some(PasswordInfo(passwordInfo.hasher, passwordInfo.password, passwordInfo.salt))
          case None => None
        }
      }
    }
  }
}


text:
package com.graphics.world.util;

import java.util.ArrayList;

/**
 * An edge of a graph. Note these edges are directed
 *
 * @author Craig Ferris
 *
 */
public class Edge
{
	private Vertex						source;
	private Vertex						destination;
	private ArrayList<EnemyMovement>	enemyMovement;

	private int							weight;

	/**
	 * Creates a new edge between the source and destination Vertexs
	 *
	 * @param source
	 *            The source Vertex
	 * @param destination
	 *            The destination Vertex
	 * @param weight
	 *            The weight of taveling over this edge
	 */
	public Edge(Vertex source, Vertex destination, int weight)
	{
		if (source == null)
		{
			throw new NullPointerException("Can't have an edge that has no source");
		}
		if (destination == null)
		{
			throw new NullPointerException("Can't have an edge that has no destination");
		}
		this.source = source;
		this.destination = destination;
		this.weight = weight;
		enemyMovement = new ArrayList<EnemyMovement>();
	}

	/**
	 * Returns the source Vertex of the edge
	 *
	 * @return Returns the source Vertex of the edge
	 */
	public Vertex getSource()
	{
		return source;
	}

	/**
	 * Returns the destination Vertex of the edge
	 *
	 * @return Returns the destination Vertex of the edge
	 */
	public Vertex getDestination()
	{
		return destination;
	}

	/**
	 * Returns the weight of the edge
	 *
	 * @return Returns the weight of the edge
	 */
	public int getWeight()
	{
		return weight;
	}

	/**
	 * Overrides the tostring method in object
	 */
	public String toString()
	{
		return "[Edge Source: " + source + " Destination: " + destination + " Weight: " + weight + "]";
	}

	/**
	 * Returns the possible enemy movements
	 *
	 * @return Returns the possible enemy movements
	 */
	public ArrayList<EnemyMovement> getEnemyMovement()
	{
		return enemyMovement;
	}

	/**
	 * Adds enemy movements
	 *
	 * @param enemyTypeID
	 *            The type of enemy
	 * @param method
	 *            The method to move
	 */
	public void addEnemyMovementMethod(int enemyTypeID, MovementMethod method)
	{
		enemyMovement.add(new EnemyMovement(enemyTypeID, method));
	}
}


text:
<?php

namespace spec\Http\Discovery\Helper;

use Http\Discovery\Strategy\DiscoveryStrategy;

/**
 * This is a discovery helper used in tests
 *
 * @author Tobias Nyholm <tobias.nyholm@gmail.com>
 */
class DiscoveryHelper implements DiscoveryStrategy
{
    private static $classes = [];

    /**
     * @param string $type
     * @param array $classes
     *
     * @return $this
     */
    public static function setClasses($type, array $classes)
    {
        self::$classes[$type] = $classes;
    }

    /**
     * Clear all classes.
     */
    public static function clearClasses()
    {
        self::$classes = [];
    }

    /**
     * {@inheritdoc}
     */
    public static function getCandidates($type)
    {
        if (isset(static::$classes[$type])) {
            return static::$classes[$type];
        }

        return [];
    }
}


text:
package com.pubnub.api;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;

public class StateTest {
    Pubnub pubnub;
    String channel;
    String group;

    String random;

    @Before
    public void setUp() throws InterruptedException {
        random = UUID.randomUUID().toString().substring(0, 8);

        pubnub = new Pubnub("demo", "demo");
        pubnub.setCacheBusting(false);

        group = "jtest-" + random;
        channel = "ch1" + random;
    }

    @Test
    public void testStateForChannel()
            throws InterruptedException, PubnubException, JSONException {

        JSONObject state = new JSONObject();
        state.put("nickname", "jtester");
        state.put("status", "online");
        state.put("age", 32);

        final CountDownLatch latch1 = new CountDownLatch(1);
        final CountDownLatch latch2 = new CountDownLatch(1);
        final CountDownLatch latch3 = new CountDownLatch(1);

        final TestHelper.SimpleCallback cb1 = new TestHelper.SubscribeCallback(latch1);
        final TestHelper.SimpleCallback cb2 = new TestHelper.SimpleCallback(latch2);
        final TestHelper.SimpleCallback cb3 = new TestHelper.SimpleCallback(latch3);

        pubnub.setHeartbeat(6);
        pubnub.subscribe(channel, cb1);
        latch1.await(10, TimeUnit.SECONDS);

        pubnub.setState(channel, pubnub.getUUID(), state, cb2);
        latch2.await(10, TimeUnit.SECONDS);

        pubnub.getState(channel, pubnub.getUUID(), cb3);
        latch3.await(10, TimeUnit.SECONDS);

        JSONObject result = (JSONObject) cb3.getResponse();

        assertEquals(state.getString("nickname"), result.getString("nickname"));
        assertEquals(state.getString("status"), result.getString("status"));
        assertEquals(state.getInt("age"), result.getInt("age"));
    }

    @Test
    public void testStateForChannelGroup()
            throws InterruptedException, PubnubException, JSONException {

        JSONObject state = new JSONObject();
        state.put("nickname", "jtester");
        state.put("status", "online");
        state.put("age", 32);

        final CountDownLatch latch1 = new CountDownLatch(1);
        final CountDownLatch latch3 = new CountDownLatch(1);
        final CountDownLatch latch4 = new CountDownLatch(1);

        final TestHelper.SimpleCallback cb1 = new TestHelper.SimpleCallback(latch1);
        final TestHelper.SimpleCallback cb3 = new TestHelper.SimpleCallback(latch3);
        final TestHelper.SimpleCallback cb4 = new TestHelper.SimpleCallback(latch4);

        pubnub.setHeartbeat(6);

        pubnub.channelGroupAddChannel(group, channel, cb1);
        latch1.await(10, TimeUnit.SECONDS);

        pubnub.channelGroupSetState(group, pubnub.getUUID(), state, cb3);
        latch3.await(10, TimeUnit.SECONDS);

        pubnub.getState(channel, pubnub.getUUID(), cb4);
        latch4.await(10, TimeUnit.SECONDS);

        JSONObject result = (JSONObject) cb4.getResponse();

        assertEquals(state.getString("nickname"), result.getString("nickname"));
        assertEquals(state.getString("status"), result.getString("status"));
        assertEquals(state.getInt("age"), result.getInt("age"));
    }
}


text:
/*global define*/
define(
	function () {
		var lang = navigator.language || navigator.userLanguage || 'en-us';
		var intlIsSupported = !! window.Intl;

		function dateToStr ( date ) {
			return date.toISOString();
		}

		function timestampToDate ( str ) {
			return new Date( parseInt( str, 10 ) );
		}

		function dateTimeToLocalStr ( date ) {
			if (
				intlIsSupported &&
				Intl.DateTimeFormat.supportedLocalesOf( [ lang ] ).length &&
				date.toLocaleDateString &&
				date.toLocaleTimeString
			) {
				return date.toLocaleDateString( lang ) + ' ' + date.toLocaleTimeString( lang );
			} else {
				return dateToLocalStr( date ) + ' ' + timeToLocalStr( date );
			}
		}

		function dateToLocalStr ( date ) {
			if (
				intlIsSupported &&
				Intl.DateTimeFormat.supportedLocalesOf( [ lang ] ).length &&
				date.toLocaleDateString
			) {
				return date.toLocaleDateString( lang );
			} else {
				if ( navigator.language.toLowerCase() === 'en-us' ) {
					return ( date.getMonth() + 1 ) + '/' + date.getDate() + '/' + date.getFullYear();
				} else {
					return ( date.getDate() + '.' + date.getMonth() + 1 ) + '.' + date.getFullYear();
				}
			}
		}

		function timeToLocalStr ( date ) {
			if (
				intlIsSupported &&
				Intl.DateTimeFormat.supportedLocalesOf( [ lang ] ).length &&
				date.toLocaleTimeString
			) {
				return date.toLocaleTimeString( lang );
			} else {
				var hours = date.getHours();
				var minutes = date.getMinutes();

				if ( hours < 10 ) {	hours = '0' + hours; }
				if ( minutes < 10 ) { minutes = '0' + minutes; }

				if ( navigator.language.toLowerCase().indexOf( 'en' ) >= 0 ) {
					var amPm = 'AM';

					if ( hours > 12 ) {
						hours -= 12;
						amPm = 'PM';
					}

					return hours + ':' + minutes + ' ' + amPm;

				} else {
					return hours + ':' + minutes;
				}
			}
		}

		return {
			dateToStr: dateToStr,
			dateToLocalStr: dateToLocalStr,
			timeToLocalStr: timeToLocalStr,
			dateTimeToLocalStr: dateTimeToLocalStr,
			timestampToDate: timestampToDate
		};
	}
);


text:
package net.sf.anpr.rcp.filesystem;

import java.awt.Component;
import java.awt.Insets;
import java.awt.Point;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;

public class AutoScroll {
	Component comp;
	Insets insets;
	Insets scrollUnits;

	public AutoScroll(Component comp, Insets insets) {
		this(comp, insets, insets);
	}

	public AutoScroll(Component comp, Insets insets, Insets scrollUnits) {
		this.comp = comp;
		this.insets = insets;
		this.scrollUnits = scrollUnits;
	}

	public void autoscroll(Point cursorLoc) {
		JViewport viewport = getViewport();
		if (viewport == null)
			return;
		Point viewPos = viewport.getViewPosition();
		int viewHeight = viewport.getExtentSize().height;
		int viewWidth = viewport.getExtentSize().width;

		if (cursorLoc.y - viewPos.y < this.insets.top)
			viewport.setViewPosition(new Point(viewPos.x, Math.max(viewPos.y
					- this.scrollUnits.top, 0)));
		else if (viewPos.y + viewHeight - cursorLoc.y < this.insets.bottom)
			viewport.setViewPosition(new Point(viewPos.x, Math.min(viewPos.y
					+ this.scrollUnits.bottom, this.comp.getHeight()
					- viewHeight)));
		else if (cursorLoc.x - viewPos.x < this.insets.left)
			viewport.setViewPosition(new Point(Math.max(viewPos.x
					- this.scrollUnits.left, 0), viewPos.y));
		else if (viewPos.x + viewWidth - cursorLoc.x < this.insets.right)
			viewport.setViewPosition(new Point(
					Math.min(viewPos.x + this.scrollUnits.right,
							this.comp.getWidth() - viewWidth), viewPos.y));
	}

	JViewport getViewport() {
		return (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class,
				this.comp);
	}
}


text:
Ecurueil Virtuel's HeadBundle
=====================

`HeadBundle`

Installation
============

License
=======

This bundle is under MIT license


text:
<GridLayout>
    <fresco:FrescoDrawee xmlns:fresco="nativescript-fresco"
                        verticalAlignment="center"
                        placeholderImageUri="res://ns_logo"
                        aspectRatio="1.49"
                        decodeWidth="665"
                        decodeHeight="500"
                        imageUri="https://raw.githubusercontent.com/NativeScript/nativescript-fresco/master/examples-data/dessert1.jpg"/>
</GridLayout>


text:
'use strict';

import type {
  ConcreteFragment,
  ConcreteBatch,
  ConcreteRoot,
} from 'RelayConcreteNode';

/**
 * Utilities (custom matchers etc) for Relay "static" tests.
 */
const RelayModernTestUtils = {
  matchers: {
    toBeDeeplyFrozen(actual) {
      const {isCollection, forEach} = require('iterall');
      const forEachObject = require('forEachObject');

      function check(value) {
        expect(Object.isFrozen(value)).toBe(true);
        if (isCollection(value)) {
          forEach(value, check);
        } else if (typeof value === 'object' && value !== null) {
          forEachObject(value, check);
        }
      }
      check(actual);
      return {
        pass: true,
      };
    },

    toFailInvariant(actual, expected) {
      expect(actual).toThrowError(expected);
      return {
        pass: true,
      };
    },

    toWarn(actual, expected) {
      const negative = this.isNot;

      function formatItem(item) {
        return item instanceof RegExp ? item.toString() : JSON.stringify(item);
      }

      function formatArray(array) {
        return '[' + array.map(formatItem).join(', ') + ']';
      }

      function formatExpected(args) {
        return formatArray([false].concat(args));
      }

      function formatActual(calls) {
        if (calls.length) {
          return calls
            .map(args => {
              return formatArray([!!args[0]].concat(args.slice(1)));
            })
            .join(', ');
        } else {
          return '[]';
        }
      }

      const warning = require('warning');
      if (!warning.mock) {
        throw new Error("toWarn(): Requires `jest.mock('warning')`.");
      }

      const callsCount = warning.mock.calls.length;
      actual();
      const calls = warning.mock.calls.slice(callsCount);

      // Simple case: no explicit expectation.
      if (!expected) {
        const warned = calls.filter(args => !args[0]).length;
        return {
          pass: !!warned,
          message:
            `Expected ${negative ? 'not ' : ''}to warn but ` +
            '`warning` received the following calls: ' +
            `${formatActual(calls)}.`,
        };
      }

      // Custom case: explicit expectation.
      if (!Array.isArray(expected)) {
        expected = [expected];
      }
      const call = calls.find(args => {
        return (
          args.length === expected.length + 1 &&
          args.every((arg, index) => {
            if (!index) {
              return !arg;
            }
            const other = expected[index - 1];
            return other instanceof RegExp ? other.test(arg) : arg === other;
          })
        );
      });

      return {
        pass: !!call,
        message:
          `Expected ${negative ? 'not ' : ''}to warn: ` +
          `${formatExpected(expected)} but ` +
          '`warning` received the following calls: ' +
          `${formatActual(calls)}.`,
      };
    },

    toThrowTypeError(fn) {
      let pass = false;
      try {
        fn();
      } catch (e) {
        pass = e instanceof TypeError;
      }
      return {
        pass,
        message: 'Expected function to throw a TypeError.',
      };
    },
  },

  /**
   * Parses GraphQL text, applies the selected transforms only (or none if
   * transforms is not specified), and returns a mapping of definition name to
   * its basic generated representation.
   */
  generateWithTransforms(
    text: string,
    transforms?: ?Array<{
      transform: (context: GraphQLCompilerContext) => GraphQLCompilerContext,
    }>,
  ): {[key: string]: ConcreteRoot | ConcreteFragment} {
    const RelayCodeGenerator = require('RelayCodeGenerator');
    // eslint-disable-next-line no-shadow
    const GraphQLCompilerContext = require('GraphQLCompilerContext');
    const RelayParser = require('RelayParser');
    const RelayTestSchema = require('RelayTestSchema');

    const ast = RelayParser.parse(RelayTestSchema, text);
    let context = new GraphQLCompilerContext(RelayTestSchema);
    context = ast.reduce((ctx, node) => ctx.add(node), context);
    context = (transforms || [])
      .reduce((ctx, {transform}) => transform(ctx), context);
    const documentMap = {};
    context.documents().forEach(node => {
      documentMap[node.name] = RelayCodeGenerator.generate(node);
    });
    return documentMap;
  },

  /**
   * Compiles the given GraphQL text using the standard set of transforms (as
   * defined in RelayCompiler) and returns a mapping of definition name to
   * its full runtime representation (roots are wrapped in a ConcreteBatch).
   */
  generateAndCompile(
    text: string,
    schema?: ?GraphQLSchema,
  ): {[key: string]: ConcreteBatch | ConcreteFragment} {
    const {transformASTSchema} = require('ASTConvert');
    const {generate} = require('RelayCodeGenerator');
    const RelayCompiler = require('RelayCompiler');
    const GraphQLCompilerContext = require('GraphQLCompilerContext');
    const RelayIRTransforms = require('RelayIRTransforms');
    const RelayTestSchema = require('RelayTestSchema');
    const parseGraphQLText = require('parseGraphQLText');

    schema = schema || RelayTestSchema;
    const relaySchema = transformASTSchema(
      schema,
      RelayIRTransforms.schemaExtensions,
    );
    const compiler = new RelayCompiler(
      schema,
      new GraphQLCompilerContext(relaySchema),
      RelayIRTransforms,
      generate,
    );

    compiler.addDefinitions(parseGraphQLText(relaySchema, text).definitions);
    const documentMap = {};
    compiler.compile().forEach(node => {
      documentMap[node.name] = node;
    });
    return documentMap;
  },
};

module.exports = RelayModernTestUtils;


text:
Ext.define('MCLM.view.draw.DrawToolBarController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.drawToolBar',

    // Eh necessario uma camada para ter onde desenhar!
    addDrawableLayer : function() {
    	var addDrawableLayer = Ext.getCmp("addDrawableLayer");
    	if ( !addDrawableLayer ) {
    		addDrawableLayer = Ext.create('MCLM.view.draw.AddDrawableLayerDialog');
    	}
    	addDrawableLayer.show();
    },

    // Desenha uma linha na camada
    drawLine : function() {
    	var drawToolBar = Ext.getCmp("drawToolBar");
    	if ( !drawToolBar ) {
    		drawToolBar = Ext.create('MCLM.view.draw.DrawToolBarWindow');
    	}
    	drawToolBar.show();
    },

    // Fecha a janela de adicionar nova camada desenhavel
    closeAddDrawableLayer : function() {
    	Ext.getCmp("addDrawableLayer").close();
    },

    // Cria (pergunta) uma nova camada desenhavel
    submitAddDrawableLayer : function() {
    	var feicaoNome = Ext.getCmp("feicaoNome").getValue();
    	var feicaoDescricao = Ext.getCmp("feicaoDescricao").getValue();
    	var idEstilo = Ext.getCmp("idFeicaoStyle").getValue();
    	var feicaoDestinoId = Ext.getCmp("feicaoDestino").getValue();
    	var feicaoDestino = Ext.getCmp("feicaoDestino").getRawValue();

    	this.closeAddDrawableLayer();
    	var me = this;

    	if( !feicaoNome || !feicaoDescricao  ) {
			Ext.Msg.alert('Operação Inválida', 'É necessário fornecer um nome e uma descrição para a camada de desenho.' );
			return true;
    	}

    	if ( MCLM.DrawHelper.dirty ) {

    		Ext.Msg.confirm('Atenção', 'Existe uma camada sendo utilizada e que não foi salva. Deseja apagar seu conteúdo?', function(e) {
    			if( e == 'no' ) {
    				return true;
    			} else {
    	    		me.addNewDrawableLayer(feicaoNome, feicaoDescricao, idEstilo, feicaoDestinoId, feicaoDestino);
    	    	}
    		});

    	} else {
    		me.addNewDrawableLayer(feicaoNome, feicaoDescricao, idEstilo, feicaoDestinoId, feicaoDestino);
    	}

    },

    // Efetivamente cria uma nova camada desenhavel
    addNewDrawableLayer : function(feicaoNome, feicaoDescricao, idEstilo, feicaoDestinoId, feicaoDestino) {
    	Ext.getCmp('drawLineBtn').enable();
    	Ext.getCmp('drawBoxBtn').enable();
    	Ext.getCmp('drawPolygonBtn').enable();
    	Ext.getCmp('drawPointBtn').enable();
    	Ext.getCmp('drawSquareBtn').enable();
    	Ext.getCmp('drawCircleBtn').enable();
    	Ext.getCmp('saveDrawableBtn').enable();

    	MCLM.DrawHelper.init(feicaoNome, feicaoDescricao, idEstilo, feicaoDestinoId,feicaoDestino);

    	var styleCombo = Ext.getCmp("idFeicaoStyle");
    	var estiloNome = styleCombo.getRawValue();

    	var record = styleCombo.getStore().findRecord('idFeatureStyle', idEstilo);

    	MCLM.DrawHelper.updateStyle( record.data );

		Ext.getCmp("drawToolBar").update( "Nome: " + feicaoNome +
				"
Destino: " + feicaoDestino +
				"
Estilo: " + estiloNome + "
Descrição: "+feicaoDescricao  );
    },

    // Desenha uma linha
    drawLine : function() {
    	MCLM.DrawHelper.setDrawType('LineString');
    },

    drawBox : function() {
    	MCLM.DrawHelper.setDrawType('Box');
    },

    drawPolygon : function() {
    	MCLM.DrawHelper.setDrawType('Polygon');
    },

    drawPoint : function() {
    	MCLM.DrawHelper.setDrawType('Point');
    },

    drawSquare : function() {
    	MCLM.DrawHelper.setDrawType('Square');
    },

    drawCircle : function() {
    	MCLM.DrawHelper.setDrawType('Circle');
    },

    saveDrawableLayer : function() {
    	var me = this;
    	var data = MCLM.DrawHelper.getAsJson();
    	var style = MCLM.DrawHelper.styleData;
    	var idFeatureStyle = style.idFeatureStyle;

    	var obj = JSON.parse( data );

    	if ( !obj.features[0] ) {
    		Ext.Msg.alert('Erro','Não existem dados a serem salvos. Desenhe ao menos um objeto nesta Feição.' );
    		return true;
    	}

    	console.log("Nota: Continuar a criação de areas de interesse pela feicao.");
    	console.log("MCLM.view.draw.DrawToolBarController : saveDrawableLayer");

    	switch ( obj.features[0].properties.feicaoDestinoId ) {
	  	  case 'AN.A':
	  		  Ext.Msg.alert('Erro','Não implementado ainda.' );
	  		  //anWindow.setTitle( "Áreas Agrícolas" );
	  		  //Ext.getCmp("cat_code").setValue( "AGR" );
	  	      break;
	  	  case 'AN.E':
	  		  Ext.Msg.alert('Erro','Não implementado ainda.' );
	  		  //anWindow.setTitle( "Áreas de Endemias" );
	  		  //Ext.getCmp("cat_code").setValue( "END" );
	  	      break;
	  	  case 'AN.I':
	  		  Ext.Msg.alert('Erro','Não implementado ainda.' );
	  		  //anWindow.setTitle( "Áreas de Interesse" );
	  		  //Ext.getCmp("cat_code").setValue( "INT" );
	    	  break;
	  	  case 'AN.IB':
	  		  Ext.Msg.alert('Erro','Não implementado ainda.' );
	  		  //anWindow.setTitle( "Áreas de Insumos Biocombustíveis" );
	  		  //Ext.getCmp("cat_code").setValue( "BIO" );
	  		  break;
	  	  case 'AN.PP':
	  		  Ext.Msg.alert('Erro','Não implementado ainda.' );
	  		  //anWindow.setTitle( "Áreas de Produção Pecuária" );
	  		  //Ext.getCmp("cat_code").setValue( "PEC" );
	  		  break;
	  	  case 'OC':
	  		  Ext.Msg.alert('Erro','Não implementado ainda.' );
	  		  break;
	  	  case 'CE':
		  		Ext.Ajax.request({
				       url: 'newFeicao',
				       params: {
				           'data': data,
				           'idFeatureStyle' : idFeatureStyle
				       },
				       success: function(response, opts) {
				    	   var respObj = Ext.decode( response.responseText );

				    	   if( respObj.success ) {

				    		   // A feicao foi gravada no banco. Cria um no para ela na arvore do cenario
				    		   var layerAlias = respObj.layerAlias;
				    		   var serialId = "FE" + MCLM.Functions.guid().substring(1, 8);
				    		   var trabalhoTree = Ext.getCmp('trabalhoTree');
				    		   var root = trabalhoTree.getRootNode();
				    		   var idLayer = respObj.idLayer;
				    		   var newFeicao = respObj.feicao;

				    		   // **************************************************
			                	var layerTree = Ext.getCmp('layerTree');
					    		var rootMaintree = layerTree.getRootNode();
					    		var feicaoRootNode = null;

					    		rootMaintree.cascadeBy( function(n) {
					    			if ( n.get('layerType') == 'CRN' ) {
					    				feicaoRootNode = n;
					    			}
					    		});

					    		if ( feicaoRootNode.get('expanded')  ) {
							  		var layerTreeStore = Ext.getStore('store.layerTree');
							  		layerTreeStore.load( { node: feicaoRootNode } );
					    		}
				    		   // **************************************************

				    		   var newId = 0;
				    		   root.cascadeBy( function(n) {
				    			   console.log( n );
				    			   var temp = n.get('id');
				    			   if ( temp > newId ) newId = temp;
				    		   });
				    		   newId++;

				    		   newNode =  root.appendChild({
				    			   'id' : newId,
				    			   'text' : obj.features[0].properties.feicaoNome,
				    			   'layerAlias' : layerAlias,
				    			   'layerName' : obj.features[0].properties.feicaoNome,
				    			   'layerType' : 'FEI',
				    			   'description' : obj.features[0].properties.feicaoDescricao,
				    			   'readOnly' : false,
				    			   'checked' : false,
				    			   'selected' : false,
				    			   'institute' : obj.features[0].properties.feicaoTipo,
				    			   'indexOrder' : 0,
				    			   'iconCls' : 'fei-icon',
				    			   'leaf' : true,
				    			   'idNodeParent' : 0,
				    			   'serialId' : serialId,
				    			   'idNodeData' : idLayer,
				    			   'feicao' : newFeicao
				    		   });

				    		   // Torna a aba de cenario ativa, caso nao esteja
				    		   var painelEsquerdo = Ext.getCmp("painelesquerdo");
				    		   var tabTrabalho = Ext.getCmp("abaTrabalho");
				    		   painelEsquerdo.setActiveTab(tabTrabalho);

				    		   Ext.Msg.alert('Sucesso','Feição gravada com sucesso.');
				    	   } else {
					    	   Ext.Msg.alert('Erro','Erro ao gravar Feição: ' + respObj.msg );
				    	   }
				       },
				       failure: function(response, opts) {
				    	   var respObj = Ext.decode( response.responseText );
				    	   Ext.Msg.alert('Erro','Erro ao gravar Feição: ' + respObj.msg );
				       }
				});

	  		  break;
	  	  case 'NE':
	  		  //
	  		  break;
	  	  default:
	  	      //
	  	      break;
	  	}

    	Ext.getCmp("drawToolBar").close();

    	/*

    	var anWindow = Ext.getCmp("anWindow");
    	if ( !anWindow ) {
    		anWindow = Ext.create('MCLM.view.apolo.feicoes.AreasNotaveisWindow');
    	}
    	anWindow.show();

    	Ext.getCmp("anData").setValue( data );
    	Ext.getCmp("mappolycolor").setValue( obj.properties.feicaoEstilo.polygonFillColor );
    	Ext.get('mappolycolorBox').setStyle('background-color', obj.properties.feicaoEstilo.polygonFillColor );

    	*/
    }

});


text:
package info.archinnov.achilles.internals.codegen.dsl.select;

import static info.archinnov.achilles.internals.parser.TypeUtils.*;
import static info.archinnov.achilles.internals.utils.NamingHelper.upperCaseFirst;
import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.lang.model.element.Modifier;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;

import info.archinnov.achilles.internals.codegen.dsl.AbstractDSLCodeGen;
import info.archinnov.achilles.internals.codegen.dsl.BaseSingleColumnRestriction;
import info.archinnov.achilles.internals.codegen.dsl.MultiColumnsSliceRestrictionCodeGen;
import info.archinnov.achilles.internals.codegen.meta.EntityMetaCodeGen.EntityMetaSignature;
import info.archinnov.achilles.internals.metamodel.columns.ColumnType;
import info.archinnov.achilles.internals.parser.context.GlobalParsingContext;

public abstract class SelectWhereDSLCodeGen extends AbstractDSLCodeGen
        implements BaseSingleColumnRestriction, MultiColumnsSliceRestrictionCodeGen {

    public abstract void augmentSelectEndClass(TypeSpec.Builder selectEndClassBuilder, ClassSignatureInfo lastSignature);

    public abstract List<TypeSpec> generateExtraWhereClasses(GlobalParsingContext context,
                                                             EntityMetaSignature signature,
                                                             List<FieldSignatureInfo> partitionKeys,
                                                             List<FieldSignatureInfo> clusteringCols);

    public abstract void augmentRelationClassForWhereClause(TypeSpec.Builder relationClassBuilder,
                                                            FieldSignatureInfo fieldSignatureInfo,
                                                            ClassSignatureInfo nextSignature,
                                                            ReturnType returnType);

//    public abstract void augmentClusteringWhereClass(TypeSpec.Builder clusteringClassBuilder,
//                                                     String rootClassName,
//                                                     List<ClassSignatureInfo> classesSignature,
//                                                     ClassSignatureInfo lastSignature);

    public List<TypeSpec> buildWhereClasses(GlobalParsingContext context, EntityMetaSignature signature) {
        SelectWhereDSLCodeGen selectWhereDSLCodeGen = context.selectWhereDSLCodeGen();

        final List<FieldSignatureInfo> partitionKeys = getPartitionKeysSignatureInfo(signature.fieldMetaSignatures);
        final List<FieldSignatureInfo> clusteringCols = getClusteringColsSignatureInfo(signature.fieldMetaSignatures);

        final ClassSignatureParams classSignatureParams = ClassSignatureParams.of(SELECT_DSL_SUFFIX,
                WHERE_DSL_SUFFIX, END_DSL_SUFFIX,
                ABSTRACT_SELECT_WHERE_PARTITION, ABSTRACT_SELECT_WHERE);

        final ClassSignatureParams typedMapClassSignatureParams = ClassSignatureParams.of(SELECT_DSL_SUFFIX,
                WHERE_TYPED_MAP_DSL_SUFFIX, END_TYPED_MAP_DSL_SUFFIX,
                ABSTRACT_SELECT_WHERE_PARTITION_TYPED_MAP, ABSTRACT_SELECT_WHERE_TYPED_MAP);

        final List<TypeSpec> partitionKeysWhereClasses = buildWhereClassesInternal(signature, selectWhereDSLCodeGen, partitionKeys, clusteringCols,
                classSignatureParams);
        final List<TypeSpec> partitionKeysWhereTypedMapClasses = buildWhereClassesInternal(signature, selectWhereDSLCodeGen, partitionKeys, clusteringCols,
                typedMapClassSignatureParams);
        partitionKeysWhereClasses.addAll(partitionKeysWhereTypedMapClasses);

        partitionKeysWhereClasses.addAll(generateExtraWhereClasses(context, signature, partitionKeys, clusteringCols));

        return partitionKeysWhereClasses;
    }

    public List<TypeSpec> buildWhereClassesInternal(EntityMetaSignature signature, SelectWhereDSLCodeGen selectWhereDSLCodeGen,
                                                    List<FieldSignatureInfo> partitionKeys, List<FieldSignatureInfo> clusteringCols,
                                                    ClassSignatureParams classSignatureParams) {

        final List<ClassSignatureInfo> classesSignature = selectWhereDSLCodeGen.buildClassesSignatureForWhereClause(signature, classSignatureParams,
                partitionKeys, clusteringCols, WhereClauseFor.NORMAL);

        final Optional<ClassSignatureInfo> firstClusteringClassSignature = classesSignature.stream()
                .filter(x -> x.columnType == ColumnType.CLUSTERING)
                .findFirst();

        final ClassSignatureInfo lastSignature = classesSignature.get(classesSignature.size() - 1);

        final List<TypeSpec> partitionKeysWhereClasses = buildWhereClassesForPartitionKeys(signature.selectClassName(), true, lastSignature, classesSignature);
        final List<TypeSpec> clusteringColsWhereClasses = buildWhereClassesForClusteringColumns(signature, firstClusteringClassSignature, classesSignature, lastSignature);

        final TypeSpec selectEndClass = buildSelectEndClass(signature, lastSignature, firstClusteringClassSignature);

        partitionKeysWhereClasses.addAll(clusteringColsWhereClasses);
        partitionKeysWhereClasses.add(selectEndClass);
        return partitionKeysWhereClasses;
    }

    public TypeSpec buildSelectEndClass(EntityMetaSignature signature, ClassSignatureInfo lastSignature, Optional<ClassSignatureInfo> firstClusteringClassSignature) {

        final TypeSpec.Builder builder = TypeSpec.classBuilder(lastSignature.className)
                .superclass(lastSignature.superType)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addMethod(buildWhereConstructorWithOptions(SELECT_DOT_WHERE))
                .addMethod(buildGetEntityClass(signature))
                .addMethod(buildGetMetaInternal(signature.entityRawClass))
                .addMethod(buildGetRte())
                .addMethod(buildGetOptions())
                .addMethod(buildGetBoundValuesInternal())
                .addMethod(buildGetEncodedBoundValuesInternal())
                .addMethod(buildLimit(lastSignature))
                .addMethod(buildGetThis(lastSignature.returnClassType));

        augmentSelectEndClass(builder, lastSignature);

        maybeBuildOrderingBy(lastSignature, firstClusteringClassSignature.map(x -> x.fieldSignatureInfo), builder);

        return builder.build();
    }

    public void maybeBuildOrderingBy(ClassSignatureInfo lastSignature, Optional<FieldSignatureInfo> fieldSignatureInfoOptional, TypeSpec.Builder builder) {
        if (fieldSignatureInfoOptional.isPresent()) {
            final FieldSignatureInfo fieldSignatureInfo = fieldSignatureInfoOptional.get();
            final MethodSpec orderByAsc = MethodSpec
                    .methodBuilder("orderBy" + upperCaseFirst(fieldSignatureInfo.fieldName) + "Ascending")
                    .addJavadoc("Generate a SELECT ... FROM ... WHERE ... ORDER BY $L ASC", fieldSignatureInfo.cqlColumn)
                    .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                    .returns(lastSignature.returnClassType)
                    .addStatement("where.orderBy($T.asc($S))", QUERY_BUILDER, fieldSignatureInfo.cqlColumn)
                    .addStatement("return this")
                    .build();

            final MethodSpec orderByDesc = MethodSpec
                    .methodBuilder("orderBy" + upperCaseFirst(fieldSignatureInfo.fieldName) + "Descending")
                    .addJavadoc("Generate a SELECT ... FROM ... WHERE ... ORDER BY $L DESC", fieldSignatureInfo.cqlColumn)
                    .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                    .returns(lastSignature.returnClassType)
                    .addStatement("where.orderBy($T.desc($S))", QUERY_BUILDER, fieldSignatureInfo.cqlColumn)
                    .addStatement("return this")
                    .build();

            builder.addMethod(orderByAsc).addMethod(orderByDesc);
        }
    }

    public MethodSpec buildLimit(ClassSignatureInfo lastSignature) {
        return MethodSpec.methodBuilder("limit")
                .addJavadoc("Generate a SELECT ... FROM ... WHERE ... LIMIT :limit")
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addParameter(TypeName.INT.box(), "limit", Modifier.FINAL)
                .returns(lastSignature.returnClassType)
                .addStatement("where.limit($T.bindMarker($S))", QUERY_BUILDER, "lim")
                .addStatement("boundValues.add($N)", "limit")
                .addStatement("encodedValues.add($N)", "limit")
                .addStatement("return this")
                .build();
    }

    public List<TypeSpec> buildWhereClassesForPartitionKeys(String rootClassName,
                                                            boolean buildTokenFunction,
                                                            ClassSignatureInfo lastSignature,
                                                            List<ClassSignatureInfo> classesSignature) {
        final ColumnType columnType = classesSignature.get(0).columnType;
        if (columnType == ColumnType.CLUSTERING || columnType == null) {
            return new ArrayList<>();
        } else {
            final ClassSignatureInfo classSignature = classesSignature.remove(0);
            final TypeSpec.Builder builder = buildSelectWhereForPartitionKey(rootClassName, classSignature, classesSignature.get(0));
            final TypeSpec typeSpec;
            if (buildTokenFunction) {
                final List<String> partitionKeyColumns = new ArrayList<>(classesSignature
                        .stream()
                        .filter(x -> x.columnType == ColumnType.PARTITION)
                        .map(x -> x.fieldSignatureInfo.quotedCqlColumn)
                        .collect(toList()));
                partitionKeyColumns.add(0, classSignature.fieldSignatureInfo.quotedCqlColumn);
                typeSpec = augmentWithTokenValueRelationClass(rootClassName, builder, lastSignature, classSignature, partitionKeyColumns);
            } else {
                typeSpec = builder.build();
            }

            final List<TypeSpec> typeSpecs = buildWhereClassesForPartitionKeys(rootClassName, false, lastSignature, classesSignature);
            typeSpecs.add(0, typeSpec);
            return typeSpecs;
        }
    }

    public TypeSpec augmentWithTokenValueRelationClass(String rootClassName,
                                                       TypeSpec.Builder builder,
                                                       ClassSignatureInfo nextClassSignatureForTokenFunction,
                                                       ClassSignatureInfo classSignature,
                                                       List<String> partitionKeyColumns) {

        TypeName relationClassTypeName = ClassName.get(DSL_PACKAGE, rootClassName
                + "." + classSignature.className
                + "." + DSL_TOKEN);

        final TypeSpec tokenClass = TypeSpec.classBuilder(DSL_TOKEN)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addMethod(buildTokenValueRelation(EQ, nextClassSignatureForTokenFunction.returnClassType, partitionKeyColumns, ReturnType.NEW))
                .addMethod(buildTokenValueRelation(GT, nextClassSignatureForTokenFunction.returnClassType, partitionKeyColumns, ReturnType.NEW))
                .addMethod(buildTokenValueRelation(GTE, nextClassSignatureForTokenFunction.returnClassType, partitionKeyColumns, ReturnType.NEW))
                .addMethod(buildTokenValueRelation(LT, nextClassSignatureForTokenFunction.returnClassType, partitionKeyColumns, ReturnType.NEW))
                .addMethod(buildTokenValueRelation(LTE, nextClassSignatureForTokenFunction.returnClassType, partitionKeyColumns, ReturnType.NEW))
                .addMethod(buildDoubleTokenValueRelation(GT, LT, nextClassSignatureForTokenFunction.returnClassType, partitionKeyColumns, ReturnType.NEW))
                .addMethod(buildDoubleTokenValueRelation(GT, LTE, nextClassSignatureForTokenFunction.returnClassType, partitionKeyColumns, ReturnType.NEW))
                .addMethod(buildDoubleTokenValueRelation(GTE, LT, nextClassSignatureForTokenFunction.returnClassType, partitionKeyColumns, ReturnType.NEW))
                .addMethod(buildDoubleTokenValueRelation(GTE, LTE, nextClassSignatureForTokenFunction.returnClassType, partitionKeyColumns, ReturnType.NEW))
                .build();

        final String methodName = partitionKeyColumns.stream().collect(Collectors.joining("_", "tokenValueOf_", "")).replaceAll("\"", "");

        return builder
                .addType(tokenClass)
                .addMethod(buildRelationMethod(methodName,relationClassTypeName))
                .build();

    }

    public TypeSpec.Builder buildSelectWhereForPartitionKey(String rootClassName,
                                                    ClassSignatureInfo classSignature,
                                                    ClassSignatureInfo nextSignature) {

        FieldSignatureInfo partitionInfo = classSignature.fieldSignatureInfo;

        TypeName relationClassTypeName = ClassName.get(DSL_PACKAGE, rootClassName
                + "." + classSignature.className
                + "." + DSL_RELATION);

        final TypeSpec.Builder relationClassBuilder = TypeSpec.classBuilder(DSL_RELATION)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addMethod(buildColumnRelation(EQ, nextSignature.returnClassType, partitionInfo, ReturnType.NEW))
                .addMethod(buildColumnInVarargs(nextSignature.returnClassType, partitionInfo, ReturnType.NEW));

        augmentRelationClassForWhereClause(relationClassBuilder, partitionInfo, nextSignature, ReturnType.NEW);

        return TypeSpec.classBuilder(classSignature.className)
                .superclass(classSignature.superType)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addMethod(buildWhereConstructorWithOptions(SELECT_DOT_WHERE))
                .addType(relationClassBuilder.build())
                .addMethod(buildRelationMethod(partitionInfo.fieldName, relationClassTypeName));
    }

    public List<TypeSpec> buildWhereClassesForClusteringColumns(EntityMetaSignature signature,
                                                                Optional<ClassSignatureInfo> firstClusteringClassSignature,
                                                                List<ClassSignatureInfo> classesSignature,
                                                                ClassSignatureInfo lastSignature) {
        if (classesSignature.get(0).columnType == null) {
            return new ArrayList<>();
        } else {
            final List<ClassSignatureInfo> copyClassesSignature = new ArrayList<>(classesSignature);
            classesSignature.remove(0);
            final TypeSpec currentType = buildSelectWhereForClusteringColumn(signature, firstClusteringClassSignature, copyClassesSignature, lastSignature).build();
            final List<TypeSpec> typeSpecs = buildWhereClassesForClusteringColumns(signature, firstClusteringClassSignature, classesSignature, lastSignature);
            typeSpecs.add(0, currentType);
            return typeSpecs;
        }
    }

    public TypeSpec.Builder buildSelectWhereForClusteringColumn(EntityMetaSignature signature,
                                                        Optional<ClassSignatureInfo> firstClusteringClassSignature,
                                                        List<ClassSignatureInfo> classesSignature,
                                                        ClassSignatureInfo lastSignature) {

        final String rootClassName = signature.selectClassName();
        final ClassSignatureInfo classSignature = classesSignature.get(0);
        final ClassSignatureInfo nextSignature = classesSignature.get(1);
        final FieldSignatureInfo clusteringColumnInfo = classSignature.fieldSignatureInfo;
        final TypeName relationClassTypeName = ClassName.get(DSL_PACKAGE, rootClassName
                + "." + classSignature.className
                + "." + DSL_RELATION);

        final TypeSpec.Builder builder = TypeSpec.classBuilder(classSignature.className)
                .superclass(classSignature.superType)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addMethod(buildWhereConstructorWithOptions(SELECT_DOT_WHERE))
                .addMethod(buildGetThis(classSignature.returnClassType))
                .addMethod(buildGetMetaInternal(signature.entityRawClass))
                .addMethod(buildGetEntityClass(signature))
                .addMethod(buildGetRte())
                .addMethod(buildGetOptions())
                .addMethod(buildGetBoundValuesInternal())
                .addMethod(buildGetEncodedBoundValuesInternal())
                .addMethod(buildLimit(classSignature));

//        augmentClusteringWhereClass(builder, rootClassName, classesSignature, lastSignature);

        TypeSpec.Builder relationClassBuilder = TypeSpec.classBuilder(DSL_RELATION)
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addMethod(buildColumnRelation(EQ, nextSignature.returnClassType, clusteringColumnInfo, ReturnType.NEW));

        addSingleColumnSliceRestrictions(relationClassBuilder, clusteringColumnInfo, nextSignature, lastSignature, ReturnType.NEW);

        augmentRelationClassForWhereClause(relationClassBuilder, clusteringColumnInfo, nextSignature, ReturnType.NEW);

        builder.addType(relationClassBuilder.build());
        builder.addMethod(buildRelationMethod(clusteringColumnInfo.fieldName, relationClassTypeName));

        String parentClassName = signature.selectClassName() + "." + classesSignature.get(0).className;

        final List<ClassSignatureInfo> classesSignatureCopy = new ArrayList<>(classesSignature);
        classesSignatureCopy.remove(lastSignature);

        addMultipleColumnsSliceRestrictions(builder, parentClassName,
                classesSignatureCopy.stream().map(x -> x.fieldSignatureInfo).collect(toList()),
                lastSignature, ReturnType.NEW);

        maybeBuildOrderingBy(classSignature, firstClusteringClassSignature.map(x -> x.fieldSignatureInfo), builder);

        return builder;
    }
}


text:
module Fog
  module Compute
    class Cloudstack

      class Real
        # configures a netscaler load balancer device
        #
        # {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.3/root_admin/configureNetscalerLoadBalancer.html]
        def configure_netscaler_load_balancer(lbdeviceid, options={})
          options.merge!(
            'command' => 'configureNetscalerLoadBalancer',
            'lbdeviceid' => lbdeviceid
          )
          request(options)
        end
      end

    end
  end
end


text:
<?php

namespace App\Modules\Partners\Http\Controllers;

use App\Modules\Partners\PartnerCat;
use BackController;
use Hover;
use ModelHandlerTrait;

class AdminPartnerCatsController extends BackController
{

    use ModelHandlerTrait;

    protected $icon = 'money-bill-alt';

    public function __construct()
    {
        $this->modelClass = PartnerCat::class;

        parent::__construct();
    }

    public function index()
    {
        $this->indexPage([
            'tableHead' => [
                trans('app.id')     => 'id',
                trans('app.title')  => 'title'
            ],
            'tableRow' => function(PartnerCat $partnerCat)
            {
                Hover::modelAttributes($partnerCat, ['creator', 'updated_at']);

                return [
                    $partnerCat->id,
                    raw(Hover::pull(), $partnerCat->title),
                ];
            }
        ]);
    }
}