text:
"""Represent a deployment of MongoDB servers."""

from random import sample
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple

from bson.min_key import MinKey
from bson.objectid import ObjectId
from pymongo import common
from pymongo.errors import ConfigurationError
from pymongo.read_preferences import ReadPreference, _AggWritePref, _ServerMode
from pymongo.server_description import ServerDescription
from pymongo.server_selectors import Selection
from pymongo.server_type import SERVER_TYPE
from pymongo.typings import _Address

# Enumeration for various kinds of MongoDB cluster topologies.
class _TopologyType(NamedTuple):
    Single: int
    ReplicaSetNoPrimary: int
    ReplicaSetWithPrimary: int
    Sharded: int
    Unknown: int
    LoadBalanced: int

TOPOLOGY_TYPE = _TopologyType(*range(6))

# Topologies compatible with SRV record polling.
SRV_POLLING_TOPOLOGIES: Tuple[int, int] = (TOPOLOGY_TYPE.Unknown, TOPOLOGY_TYPE.Sharded)

_ServerSelector = Callable[[List[ServerDescription]], List[ServerDescription]]

class TopologyDescription(object):
    def __init__(
        self,
        topology_type: int,
        server_descriptions: Dict[_Address, ServerDescription],
        replica_set_name: Optional[str],
        max_set_version: Optional[int],
        max_election_id: Optional[ObjectId],
        topology_settings: Any,
    ) -> None:
        """Representation of a deployment of MongoDB servers.

        :Parameters:
          - `topology_type`: initial type
          - `server_descriptions`: dict of (address, ServerDescription) for
            all seeds
          - `replica_set_name`: replica set name or None
          - `max_set_version`: greatest setVersion seen from a primary, or None
          - `max_election_id`: greatest electionId seen from a primary, or None
          - `topology_settings`: a TopologySettings
        """
        self._topology_type = topology_type
        self._replica_set_name = replica_set_name
        self._server_descriptions = server_descriptions
        self._max_set_version = max_set_version
        self._max_election_id = max_election_id

        # The heartbeat_frequency is used in staleness estimates.
        self._topology_settings = topology_settings

        # Is PyMongo compatible with all servers' wire protocols?
        self._incompatible_err = None
        if self._topology_type != TOPOLOGY_TYPE.LoadBalanced:
            self._init_incompatible_err()

        # Server Discovery And Monitoring Spec: Whenever a client updates the
        # TopologyDescription from an hello response, it MUST set
        # TopologyDescription.logicalSessionTimeoutMinutes to the smallest
        # logicalSessionTimeoutMinutes value among ServerDescriptions of all
        # data-bearing server types. If any have a null
        # logicalSessionTimeoutMinutes, then
        # TopologyDescription.logicalSessionTimeoutMinutes MUST be set to null.
        readable_servers = self.readable_servers
        if not readable_servers:
            self._ls_timeout_minutes = None
        elif any(s.logical_session_timeout_minutes is None for s in readable_servers):
            self._ls_timeout_minutes = None
        else:
            self._ls_timeout_minutes = min(  # type: ignore[type-var]
                s.logical_session_timeout_minutes for s in readable_servers
            )

    def _init_incompatible_err(self):
        """Internal compatibility check for non-load balanced topologies."""
        for s in self._server_descriptions.values():
            if not s.is_server_type_known:
                continue

            # s.min/max_wire_version is the server's wire protocol.
            # MIN/MAX_SUPPORTED_WIRE_VERSION is what PyMongo supports.
            server_too_new = (
                # Server too new.
                s.min_wire_version is not None
                and s.min_wire_version > common.MAX_SUPPORTED_WIRE_VERSION
            )

            server_too_old = (
                # Server too old.
                s.max_wire_version is not None
                and s.max_wire_version < common.MIN_SUPPORTED_WIRE_VERSION
            )

            if server_too_new:
                self._incompatible_err = (
                    "Server at %s:%d requires wire version %d, but this "  # type: ignore
                    "version of PyMongo only supports up to %d."
                    % (
                        s.address[0],
                        s.address[1] or 0,
                        s.min_wire_version,
                        common.MAX_SUPPORTED_WIRE_VERSION,
                    )
                )

            elif server_too_old:
                self._incompatible_err = (
                    "Server at %s:%d reports wire version %d, but this "  # type: ignore
                    "version of PyMongo requires at least %d (MongoDB %s)."
                    % (
                        s.address[0],
                        s.address[1] or 0,
                        s.max_wire_version,
                        common.MIN_SUPPORTED_WIRE_VERSION,
                        common.MIN_SUPPORTED_SERVER_VERSION,
                    )
                )

                break

    def check_compatible(self) -> None:
        """Raise ConfigurationError if any server is incompatible.

        A server is incompatible if its wire protocol version range does not
        overlap with PyMongo's.
        """
        if self._incompatible_err:
            raise ConfigurationError(self._incompatible_err)

    def has_server(self, address: _Address) -> bool:
        return address in self._server_descriptions

    def reset_server(self, address: _Address) -> "TopologyDescription":
        """A copy of this description, with one server marked Unknown."""
        unknown_sd = self._server_descriptions[address].to_unknown()
        return updated_topology_description(self, unknown_sd)

    def reset(self) -> "TopologyDescription":
        """A copy of this description, with all servers marked Unknown."""
        if self._topology_type == TOPOLOGY_TYPE.ReplicaSetWithPrimary:
            topology_type = TOPOLOGY_TYPE.ReplicaSetNoPrimary
        else:
            topology_type = self._topology_type

        # The default ServerDescription's type is Unknown.
        sds = dict((address, ServerDescription(address)) for address in self._server_descriptions)

        return TopologyDescription(
            topology_type,
            sds,
            self._replica_set_name,
            self._max_set_version,
            self._max_election_id,
            self._topology_settings,
        )

    def server_descriptions(self) -> Dict[_Address, ServerDescription]:
        """Dict of (address,
        :class:`~pymongo.server_description.ServerDescription`)."""
        return self._server_descriptions.copy()

    @property
    def topology_type(self) -> int:
        """The type of this topology."""
        return self._topology_type

    @property
    def topology_type_name(self) -> str:
        """The topology type as a human readable string.

        .. versionadded:: 3.4
        """
        return TOPOLOGY_TYPE._fields[self._topology_type]

    @property
    def replica_set_name(self) -> Optional[str]:
        """The replica set name."""
        return self._replica_set_name

    @property
    def max_set_version(self) -> Optional[int]:
        """Greatest setVersion seen from a primary, or None."""
        return self._max_set_version

    @property
    def max_election_id(self) -> Optional[ObjectId]:
        """Greatest electionId seen from a primary, or None."""
        return self._max_election_id

    @property
    def logical_session_timeout_minutes(self) -> Optional[int]:
        """Minimum logical session timeout, or None."""
        return self._ls_timeout_minutes

    @property
    def known_servers(self) -> List[ServerDescription]:
        """List of Servers of types besides Unknown."""
        return [s for s in self._server_descriptions.values() if s.is_server_type_known]

    @property
    def has_known_servers(self) -> bool:
        """Whether there are any Servers of types besides Unknown."""
        return any(s for s in self._server_descriptions.values() if s.is_server_type_known)

    @property
    def readable_servers(self) -> List[ServerDescription]:
        """List of readable Servers."""
        return [s for s in self._server_descriptions.values() if s.is_readable]

    @property
    def common_wire_version(self) -> Optional[int]:
        """Minimum of all servers' max wire versions, or None."""
        servers = self.known_servers
        if servers:
            return min(s.max_wire_version for s in self.known_servers)

        return None

    @property
    def heartbeat_frequency(self) -> int:
        return self._topology_settings.heartbeat_frequency

    @property
    def srv_max_hosts(self) -> int:
        return self._topology_settings._srv_max_hosts

    def _apply_local_threshold(self, selection):
        if not selection:
            return []
        # Round trip time in seconds.
        fastest = min(s.round_trip_time for s in selection.server_descriptions)
        threshold = self._topology_settings.local_threshold_ms / 1000.0
        return [
            s for s in selection.server_descriptions if (s.round_trip_time - fastest) <= threshold
        ]

    def apply_selector(
        self,
        selector: Any,
        address: Optional[_Address] = None,
        custom_selector: Optional[_ServerSelector] = None,
    ) -> List[ServerDescription]:
        """List of servers matching the provided selector(s).

        :Parameters:
          - `selector`: a callable that takes a Selection as input and returns
            a Selection as output. For example, an instance of a read
            preference from :mod:`~pymongo.read_preferences`.
          - `address` (optional): A server address to select.
          - `custom_selector` (optional): A callable that augments server
            selection rules. Accepts a list of
            :class:`~pymongo.server_description.ServerDescription` objects and
            return a list of server descriptions that should be considered
            suitable for the desired operation.

        .. versionadded:: 3.4
        """
        if getattr(selector, "min_wire_version", 0):
            common_wv = self.common_wire_version
            if common_wv and common_wv < selector.min_wire_version:
                raise ConfigurationError(
                    "%s requires min wire version %d, but topology's min"
                    " wire version is %d" % (selector, selector.min_wire_version, common_wv)
                )

        if isinstance(selector, _AggWritePref):
            selector.selection_hook(self)

        if self.topology_type == TOPOLOGY_TYPE.Unknown:
            return []
        elif self.topology_type in (TOPOLOGY_TYPE.Single, TOPOLOGY_TYPE.LoadBalanced):
            # Ignore selectors for standalone and load balancer mode.
            return self.known_servers
        if address:
            # Ignore selectors when explicit address is requested.
            description = self.server_descriptions().get(address)
            return [description] if description else []

        selection = Selection.from_topology_description(self)
        # Ignore read preference for sharded clusters.
        if self.topology_type != TOPOLOGY_TYPE.Sharded:
            selection = selector(selection)

        # Apply custom selector followed by localThresholdMS.
        if custom_selector is not None and selection:
            selection = selection.with_server_descriptions(
                custom_selector(selection.server_descriptions)
            )
        return self._apply_local_threshold(selection)

    def has_readable_server(self, read_preference: _ServerMode = ReadPreference.PRIMARY) -> bool:
        """Does this topology have any readable servers available matching the
        given read preference?

        :Parameters:
          - `read_preference`: an instance of a read preference from
            :mod:`~pymongo.read_preferences`. Defaults to
            :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.

        .. note:: When connected directly to a single server this method
          always returns ``True``.

        .. versionadded:: 3.4
        """
        common.validate_read_preference("read_preference", read_preference)
        return any(self.apply_selector(read_preference))

    def has_writable_server(self) -> bool:
        """Does this topology have a writable server available?

        .. note:: When connected directly to a single server this method
          always returns ``True``.

        .. versionadded:: 3.4
        """
        return self.has_readable_server(ReadPreference.PRIMARY)

    def __repr__(self):
        # Sort the servers by address.
        servers = sorted(self._server_descriptions.values(), key=lambda sd: sd.address)
        return "<%s id: %s, topology_type: %s, servers: %r>" % (
            self.__class__.__name__,
            self._topology_settings._topology_id,
            self.topology_type_name,
            servers,
        )

# If topology type is Unknown and we receive a hello response, what should
# the new topology type be?
_SERVER_TYPE_TO_TOPOLOGY_TYPE = {
    SERVER_TYPE.Mongos: TOPOLOGY_TYPE.Sharded,
    SERVER_TYPE.RSPrimary: TOPOLOGY_TYPE.ReplicaSetWithPrimary,
    SERVER_TYPE.RSSecondary: TOPOLOGY_TYPE.ReplicaSetNoPrimary,
    SERVER_TYPE.RSArbiter: TOPOLOGY_TYPE.ReplicaSetNoPrimary,
    SERVER_TYPE.RSOther: TOPOLOGY_TYPE.ReplicaSetNoPrimary,
    # Note: SERVER_TYPE.LoadBalancer and Unknown are intentionally left out.
}

def updated_topology_description(
    topology_description: TopologyDescription, server_description: ServerDescription
) -> "TopologyDescription":
    """Return an updated copy of a TopologyDescription.

    :Parameters:
      - `topology_description`: the current TopologyDescription
      - `server_description`: a new ServerDescription that resulted from
        a hello call

    Called after attempting (successfully or not) to call hello on the
    server at server_description.address. Does not modify topology_description.
    """
    address = server_description.address

    # These values will be updated, if necessary, to form the new
    # TopologyDescription.
    topology_type = topology_description.topology_type
    set_name = topology_description.replica_set_name
    max_set_version = topology_description.max_set_version
    max_election_id = topology_description.max_election_id
    server_type = server_description.server_type

    # Don't mutate the original dict of server descriptions; copy it.
    sds = topology_description.server_descriptions()

    # Replace this server's description with the new one.
    sds[address] = server_description

    if topology_type == TOPOLOGY_TYPE.Single:
        # Set server type to Unknown if replica set name does not match.
        if set_name is not None and set_name != server_description.replica_set_name:
            error = ConfigurationError(
                "client is configured to connect to a replica set named "
                "'%s' but this node belongs to a set named '%s'"
                % (set_name, server_description.replica_set_name)
            )
            sds[address] = server_description.to_unknown(error=error)
        # Single type never changes.
        return TopologyDescription(
            TOPOLOGY_TYPE.Single,
            sds,
            set_name,
            max_set_version,
            max_election_id,
            topology_description._topology_settings,
        )

    if topology_type == TOPOLOGY_TYPE.Unknown:
        if server_type in (SERVER_TYPE.Standalone, SERVER_TYPE.LoadBalancer):
            if len(topology_description._topology_settings.seeds) == 1:
                topology_type = TOPOLOGY_TYPE.Single
            else:
                # Remove standalone from Topology when given multiple seeds.
                sds.pop(address)
        elif server_type not in (SERVER_TYPE.Unknown, SERVER_TYPE.RSGhost):
            topology_type = _SERVER_TYPE_TO_TOPOLOGY_TYPE[server_type]

    if topology_type == TOPOLOGY_TYPE.Sharded:
        if server_type not in (SERVER_TYPE.Mongos, SERVER_TYPE.Unknown):
            sds.pop(address)

    elif topology_type == TOPOLOGY_TYPE.ReplicaSetNoPrimary:
        if server_type in (SERVER_TYPE.Standalone, SERVER_TYPE.Mongos):
            sds.pop(address)

        elif server_type == SERVER_TYPE.RSPrimary:
            (topology_type, set_name, max_set_version, max_election_id) = _update_rs_from_primary(
                sds, set_name, server_description, max_set_version, max_election_id
            )

        elif server_type in (SERVER_TYPE.RSSecondary, SERVER_TYPE.RSArbiter, SERVER_TYPE.RSOther):
            topology_type, set_name = _update_rs_no_primary_from_member(
                sds, set_name, server_description
            )

    elif topology_type == TOPOLOGY_TYPE.ReplicaSetWithPrimary:
        if server_type in (SERVER_TYPE.Standalone, SERVER_TYPE.Mongos):
            sds.pop(address)
            topology_type = _check_has_primary(sds)

        elif server_type == SERVER_TYPE.RSPrimary:
            (topology_type, set_name, max_set_version, max_election_id) = _update_rs_from_primary(
                sds, set_name, server_description, max_set_version, max_election_id
            )

        elif server_type in (SERVER_TYPE.RSSecondary, SERVER_TYPE.RSArbiter, SERVER_TYPE.RSOther):
            topology_type = _update_rs_with_primary_from_member(sds, set_name, server_description)

        else:
            # Server type is Unknown or RSGhost: did we just lose the primary?
            topology_type = _check_has_primary(sds)

    # Return updated copy.
    return TopologyDescription(
        topology_type,
        sds,
        set_name,
        max_set_version,
        max_election_id,
        topology_description._topology_settings,
    )

def _updated_topology_description_srv_polling(topology_description, seedlist):
    """Return an updated copy of a TopologyDescription.

    :Parameters:
      - `topology_description`: the current TopologyDescription
      - `seedlist`: a list of new seeds new ServerDescription that resulted from
        a hello call
    """
    assert topology_description.topology_type in SRV_POLLING_TOPOLOGIES
    # Create a copy of the server descriptions.
    sds = topology_description.server_descriptions()

    # If seeds haven't changed, don't do anything.
    if set(sds.keys()) == set(seedlist):
        return topology_description

    # Remove SDs corresponding to servers no longer part of the SRV record.
    for address in list(sds.keys()):
        if address not in seedlist:
            sds.pop(address)

    if topology_description.srv_max_hosts != 0:
        new_hosts = set(seedlist) - set(sds.keys())
        n_to_add = topology_description.srv_max_hosts - len(sds)
        if n_to_add > 0:
            seedlist = sample(sorted(new_hosts), min(n_to_add, len(new_hosts)))
        else:
            seedlist = []
    # Add SDs corresponding to servers recently added to the SRV record.
    for address in seedlist:
        if address not in sds:
            sds[address] = ServerDescription(address)
    return TopologyDescription(
        topology_description.topology_type,
        sds,
        topology_description.replica_set_name,
        topology_description.max_set_version,
        topology_description.max_election_id,
        topology_description._topology_settings,
    )

def _update_rs_from_primary(
    sds, replica_set_name, server_description, max_set_version, max_election_id
):
    """Update topology description from a primary's hello response.

    Pass in a dict of ServerDescriptions, current replica set name, the
    ServerDescription we are processing, and the TopologyDescription's
    max_set_version and max_election_id if any.

    Returns (new topology type, new replica_set_name, new max_set_version,
    new max_election_id).
    """
    if replica_set_name is None:
        replica_set_name = server_description.replica_set_name

    elif replica_set_name != server_description.replica_set_name:
        # We found a primary but it doesn't have the replica_set_name
        # provided by the user.
        sds.pop(server_description.address)
        return _check_has_primary(sds), replica_set_name, max_set_version, max_election_id

    if server_description.max_wire_version is None or server_description.max_wire_version < 17:
        new_election_tuple = server_description.set_version, server_description.election_id
        max_election_tuple = max_set_version, max_election_id
        if None not in new_election_tuple:
            if None not in max_election_tuple and new_election_tuple < max_election_tuple:
                # Stale primary, set to type Unknown.
                sds[server_description.address] = server_description.to_unknown()
                return _check_has_primary(sds), replica_set_name, max_set_version, max_election_id
            max_election_id = server_description.election_id

        if server_description.set_version is not None and (
            max_set_version is None or server_description.set_version > max_set_version
        ):
            max_set_version = server_description.set_version
    else:
        new_election_tuple = server_description.election_id, server_description.set_version
        max_election_tuple = max_election_id, max_set_version
        new_election_safe = tuple(MinKey() if i is None else i for i in new_election_tuple)
        max_election_safe = tuple(MinKey() if i is None else i for i in max_election_tuple)
        if new_election_safe < max_election_safe:
            # Stale primary, set to type Unknown.
            sds[server_description.address] = server_description.to_unknown()
            return _check_has_primary(sds), replica_set_name, max_set_version, max_election_id
        else:
            max_election_id = server_description.election_id
            max_set_version = server_description.set_version

    # We've heard from the primary. Is it the same primary as before?
    for server in sds.values():
        if (
            server.server_type is SERVER_TYPE.RSPrimary
            and server.address != server_description.address
        ):

            # Reset old primary's type to Unknown.
            sds[server.address] = server.to_unknown()

            # There can be only one prior primary.
            break

    # Discover new hosts from this primary's response.
    for new_address in server_description.all_hosts:
        if new_address not in sds:
            sds[new_address] = ServerDescription(new_address)

    # Remove hosts not in the response.
    for addr in set(sds) - server_description.all_hosts:
        sds.pop(addr)

    # If the host list differs from the seed list, we may not have a primary
    # after all.
    return (_check_has_primary(sds), replica_set_name, max_set_version, max_election_id)

def _update_rs_with_primary_from_member(sds, replica_set_name, server_description):
    """RS with known primary. Process a response from a non-primary.

    Pass in a dict of ServerDescriptions, current replica set name, and the
    ServerDescription we are processing.

    Returns new topology type.
    """
    assert replica_set_name is not None

    if replica_set_name != server_description.replica_set_name:
        sds.pop(server_description.address)
    elif server_description.me and server_description.address != server_description.me:
        sds.pop(server_description.address)

    # Had this member been the primary?
    return _check_has_primary(sds)

def _update_rs_no_primary_from_member(sds, replica_set_name, server_description):
    """RS without known primary. Update from a non-primary's response.

    Pass in a dict of ServerDescriptions, current replica set name, and the
    ServerDescription we are processing.

    Returns (new topology type, new replica_set_name).
    """
    topology_type = TOPOLOGY_TYPE.ReplicaSetNoPrimary
    if replica_set_name is None:
        replica_set_name = server_description.replica_set_name

    elif replica_set_name != server_description.replica_set_name:
        sds.pop(server_description.address)
        return topology_type, replica_set_name

    # This isn't the primary's response, so don't remove any servers
    # it doesn't report. Only add new servers.
    for address in server_description.all_hosts:
        if address not in sds:
            sds[address] = ServerDescription(address)

    if server_description.me and server_description.address != server_description.me:
        sds.pop(server_description.address)

    return topology_type, replica_set_name

def _check_has_primary(sds):
    """Current topology type is ReplicaSetWithPrimary. Is primary still known?

    Pass in a dict of ServerDescriptions.

    Returns new topology type.
    """
    for s in sds.values():
        if s.server_type == SERVER_TYPE.RSPrimary:
            return TOPOLOGY_TYPE.ReplicaSetWithPrimary
    else:
        return TOPOLOGY_TYPE.ReplicaSetNoPrimary


text:
Passes arguments directly to the resource compiler command line without translation.

```lua
resoptions { "options" }
```

### Parameters ###

`options` is a list of resource compiler flags and options, specific to a particular compiler.

### Applies To ###

Project configurations.

### Availability ###

Premake 4.0 or later.

### Examples ###

Use `pkg-config` style configuration when building on Linux with GCC. Build options are always compiler specific and should be targeted to a particular toolset.

```lua
filter { "system:linux", "action:gmake" }
  resoptions { "`wx-config --cxxflags`", "-ansi", "-pedantic" }
```

redpajama_set_name: RedPajamaGithub


text:
#include <aws/gamelift/model/ResourceCreationLimitPolicy.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace GameLift
{
namespace Model
{

ResourceCreationLimitPolicy::ResourceCreationLimitPolicy() :
    m_newGameSessionsPerCreator(0),
    m_newGameSessionsPerCreatorHasBeenSet(false),
    m_policyPeriodInMinutes(0),
    m_policyPeriodInMinutesHasBeenSet(false)
{
}

ResourceCreationLimitPolicy::ResourceCreationLimitPolicy(const JsonValue& jsonValue) :
    m_newGameSessionsPerCreator(0),
    m_newGameSessionsPerCreatorHasBeenSet(false),
    m_policyPeriodInMinutes(0),
    m_policyPeriodInMinutesHasBeenSet(false)
{
  *this = jsonValue;
}

ResourceCreationLimitPolicy& ResourceCreationLimitPolicy::operator =(const JsonValue& jsonValue)
{
  if(jsonValue.ValueExists("NewGameSessionsPerCreator"))
  {
    m_newGameSessionsPerCreator = jsonValue.GetInteger("NewGameSessionsPerCreator");

    m_newGameSessionsPerCreatorHasBeenSet = true;
  }

  if(jsonValue.ValueExists("PolicyPeriodInMinutes"))
  {
    m_policyPeriodInMinutes = jsonValue.GetInteger("PolicyPeriodInMinutes");

    m_policyPeriodInMinutesHasBeenSet = true;
  }

  return *this;
}

JsonValue ResourceCreationLimitPolicy::Jsonize() const
{
  JsonValue payload;

  if(m_newGameSessionsPerCreatorHasBeenSet)
  {
   payload.WithInteger("NewGameSessionsPerCreator", m_newGameSessionsPerCreator);

  }

  if(m_policyPeriodInMinutesHasBeenSet)
  {
   payload.WithInteger("PolicyPeriodInMinutes", m_policyPeriodInMinutes);

  }

  return payload;
}

} // namespace Model
} // namespace GameLift
} // namespace Aws


text:
Nuno Job on Rewrite
===

I received a very nice email from [Nuno Job](http://github.com/dscape). Here it is with a few minor edits:

> Hi,
>
> I was watching your lecture ([video on infoq](http://www.infoq.com/presentations/braithwaite-rewrite-ruby), [slides and comments](http://github.com/raganwald/presentation_decks/tree/master/rubyfringe "rubyfringe at master from raganwald's presentation_decks — GitHub")) and quite enjoyed it.
>
> In one of your last slides you where doing advanced recursion on a tree and wanted to share this book with you: [Program Design by Calculation](http://www.di.uminho.pt/~jno/ps/pdbc_fm.pdf "PDF Download").
>
> It's mostly [Haskell](http://www.haskell.org/ "Haskell - HaskellWiki") but the recursion over trees is quite something else and I think your work might benefit from it.
>
> [Here's a little sample of code](http://github.com/dscape/pointfreeexprsimplication/tree/master/ExpTree.hs "ExpTree.hs at master from dscape's pointfreeexprsimplication — GitHub") written with this kind of generic fold mechanisms for a tree (in this case a pointfree exp tree).
>
> Best,
> Nuno

---

My recent work:

![](http://i.minus.com/iL337yTdgFj7.png)[![JavaScript Allongé](http://i.minus.com/iW2E1A8M5UWe6.jpeg)](http://leanpub.com/javascript-allonge "JavaScript Allongé")![](http://i.minus.com/iL337yTdgFj7.png)[![CoffeeScript Ristretto](http://i.minus.com/iMmGxzIZkHSLD.jpeg)](http://leanpub.com/coffeescript-ristretto "CoffeeScript Ristretto")![](http://i.minus.com/iL337yTdgFj7.png)[![Kestrels, Quirky Birds, and Hopeless Egocentricity](http://i.minus.com/ibw1f1ARQ4bhi1.jpeg)](http://leanpub.com/combinators "Kestrels, Quirky Birds, and Hopeless Egocentricity")

* [JavaScript Allongé](http://leanpub.com/javascript-allonge), [CoffeeScript Ristretto](http://leanpub.com/coffeescript-ristretto), and my [other books](http://leanpub.com/u/raganwald).
* [allong.es](http://allong.es), practical function combinators and decorators for JavaScript.
* [Method Combinators](https://github.com/raganwald/method-combinators), a CoffeeScript/JavaScript library for writing method decorators, simply and easily.
* [jQuery Combinators](http://github.com/raganwald/jquery-combinators), what else? A jQuery plugin for writing your own fluent, jQuery-like code.

---

(Spot a bug or a spelling mistake? This is a Github repo, fork it and send me a pull request!)

[Reg Braithwaite](http://braythwayt.com) | [@raganwald](http://twitter.com/raganwald)


text:
package io.cyberstock.tcdop.model;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by beolnix on 12/07/15.
 */
public enum DropletSize {
    M512MB(20, "512MB"),
    M1GB(30, "1GB"),
    M2GB(40, "2GB"),
    M4GB(60, "4GB"),
    M8GB(80, "8GB"),
    M16GB(160, "16GB"),
    M32GB(320, "32GB"),
    M64GB(640, "64GB");

    private Integer diskSize;
    private String slug;

    private DropletSize(Integer diskSize, String slug) {
        this.diskSize = diskSize;
        this.slug = slug;
    }

    public boolean isLessOrEqualThen(DropletSize that) {
        return this.diskSize <= that.diskSize;
    }

    public static DropletSize resolveBySlug(String slug) {
        if (StringUtils.isEmpty(slug)) {
            throw new IllegalArgumentException("slug must not be null");
        }

        for (DropletSize size : DropletSize.values()) {
            if (size.getSlug().equals(slug)) {
                return size;
            }
        }

        throw new IllegalArgumentException("unknown slug: " + slug);
    }

    public static DropletSize resolveByDiskSize(Integer diskSize) {
        if (diskSize == null) {
            throw new IllegalArgumentException("diskSize must not be null");
        }

        for (DropletSize size : DropletSize.values()) {
            if (size.getDiskSize() >= diskSize) {
                return size;
            }
        }
        return null;
    }

    public Integer getDiskSize() {
        return diskSize;
    }

    public String getSlug() {
        return slug;
    }

}


text:
package nl.ebpi.yaidom.integrationtest

import java.io.InputStream

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

import nl.ebpi.yaidom.convert.ScalaXmlConversions.convertElem
import nl.ebpi.yaidom.convert.ScalaXmlConversions.convertToElem
import nl.ebpi.yaidom.simple.Document
import nl.ebpi.yaidom.parse.AbstractDocumentParser
import nl.ebpi.yaidom.parse.DocumentParser
import nl.ebpi.yaidom.parse.DocumentParserUsingSax
import nl.ebpi.yaidom.resolved

/**
 * See AbstractOtherNamespaceTest.
 *
 * Acknowledgments: This test uses the examples in http://www.datypic.com/books/defxmlschema/chapter03.html, that are also used
 * in the excellent book Definitive XML Schema.
 *
 * @author Chris de Vreeze
 */
@RunWith(classOf[JUnitRunner])
class OtherNamespaceTestUsingSaxParserAndRoundTripping extends AbstractOtherNamespaceTest {

  val documentParser: DocumentParser = new AbstractDocumentParser {

    private val wrappedDocumentParser: DocumentParser = DocumentParserUsingSax.newInstance

    override def parse(inputStream: InputStream): Document = {
      val doc = wrappedDocumentParser.parse(inputStream)

      val result = doc.withDocumentElement(convertToElem(convertElem(doc.documentElement)))

      require(
        resolved.Elem(doc.documentElement) == resolved.Elem(result.documentElement),
        "Data loss during roundtripping")

      result
    }
  }

  val documentParserForXml11: DocumentParser = new AbstractDocumentParser {

    private val wrappedDocumentParser: DocumentParser = DocumentParserUsingSax.newInstance

    override def parse(inputStream: InputStream): Document = {
      val doc = wrappedDocumentParser.parse(inputStream)

      val result = doc.withDocumentElement(convertToElem(convertElem(doc.documentElement)))

      require(
        resolved.Elem(doc.documentElement) == resolved.Elem(result.documentElement),
        "Data loss during roundtripping")

      result
    }
  }
}


text:
var mod = angular.module('restaurant', ['ngResource', 'ngRoute']);

mod.factory('Restaurant', ['$resource',
    function($resource) {
      return $resource('/api/restaurants/restaurants/:slug', {}, {
        query: {
            method: 'GET',
            isArray: true,
        }
      });
    }
  ]);

mod.factory('Rating', ['$resource',
   function($resource) {
       return $resource('/api/restaurants/ratings/:id', {}, {
           'create': {
               method: 'POST',
           }
       });
   }

]);

mod.controller('SearchCtrl', ['$scope', '$http', '$location', function($scope, $http, $location){

    $scope.getRestaurants = function(val) {
        return $http.get('/api/restaurants/restaurantsearch', {
              params: {
              name: val
            }
        }).then(function(response){
            // maybe we can send the full array of json items then pull the name property out in the template
            return response.data;
            /*
            return response.data.map(function(item){
                return item.name;
            });*/
        });
    };
    $scope.onSelect = function($item, $model, $label) {
        $location.path("/restaurant/"+$item.slug)
        console.log($item);
    }

}]);


text:
/**
 *
 */
package com.github.phantomthief.thrift.client.utils;

import static com.google.common.cache.CacheBuilder.newBuilder;
import static com.google.common.collect.EvictingQueue.create;
import static java.lang.Boolean.TRUE;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static org.slf4j.LoggerFactory.getLogger;

import java.util.Set;
import java.util.concurrent.ExecutionException;

import org.slf4j.Logger;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.EvictingQueue;

/**
 *

 * FailoverCheckingStrategy class.
 *

 *
 * @author w.vela
 * @version $Id: $Id
 */
public class FailoverCheckingStrategy<T> {

    private static final int DEFAULT_FAIL_COUNT = 10;
    private static final long DEFAULT_FAIL_DURATION = MINUTES.toMillis(1);
    private static final long DEFAULT_RECOVERY_DURATION = MINUTES.toMillis(3);
    private final Logger logger = getLogger(getClass());
    private final long failDuration;

    private final Cache<T, Boolean> failedList;

    private final LoadingCache<T, EvictingQueue<Long>> failCountMap;

    /**
     *

     * Constructor for FailoverCheckingStrategy.
     *

     */
    public FailoverCheckingStrategy() {
        this(DEFAULT_FAIL_COUNT, DEFAULT_FAIL_DURATION, DEFAULT_RECOVERY_DURATION);
    }

    /**
     *

     * Constructor for FailoverCheckingStrategy.
     *

     *
     * @param failDuration a long.
     * @param recoveryDuration a long.
     */
    public FailoverCheckingStrategy(int failCount, long failDuration, long recoveryDuration) {
        this.failDuration = failDuration;
        this.failedList = newBuilder().weakKeys().expireAfterWrite(recoveryDuration, MILLISECONDS)
                .build();
        this.failCountMap = newBuilder().weakKeys().build(
                new CacheLoader<T, EvictingQueue<Long>>() {

                    @Override
                    public EvictingQueue<Long> load(T key) throws Exception {
                        return create(failCount);
                    }
                });
    }

    /**
     *

     * getFailed.
     *

     *
     * @return a {@link java.util.Set} object.
     */
    public Set<T> getFailed() {
        return failedList.asMap().keySet();
    }

    /**
     *

     * fail.
     *

     *
     * @param object a T object.
     */
    public void fail(T object) {
        logger.trace("server {} failed.", object);
        boolean addToFail = false;
        try {
            EvictingQueue<Long> evictingQueue = failCountMap.get(object);
            synchronized (evictingQueue) {
                evictingQueue.add(System.currentTimeMillis());
                if (evictingQueue.remainingCapacity() == 0
                        && evictingQueue.element() >= System.currentTimeMillis() - failDuration) {
                    addToFail = true;
                }
            }
        } catch (ExecutionException e) {
            logger.error("Ops.", e);
        }
        if (addToFail) {
            failedList.put(object, TRUE);
            logger.trace("server {} failed. add to fail list.", object);
        }
    }
}


text:
<?php
namespace SubscriptionHost\Form\Factory;

use Zend\ServiceManager\ServiceLocatorInterface;
use SubscriptionHost\Form\SubscriptionHostForm;

class SubscriptionHostFormFactory
{

    /**
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return \SubscriptionHost\Form\SubscriptionHostForm
     */
    public function __invoke(ServiceLocatorInterface $serviceLocator)
    {
        $hostService = $serviceLocator->get('Host\Service\HostServiceInterface');

        return new SubscriptionHostForm($hostService);
    }
}


text:
'use strict';

/*!
 * snakeskin.github.io
 * https://github.com/SnakeskinTpl/snakeskin.github.io
 *
 * Released under the MIT license
 * https://github.com/SnakeskinTpl/snakeskin.github.io/blob/master/LICENSE
 */

$(() => {
	const
		doc = $(document),
		contents = $('nav.b-contents'),
		headerHeight = $('header.b-header').innerHeight(),
		arrows = $('.b-articles__nav-cont');

	doc.on('scroll', () => {
		if (doc.scrollTop() >= headerHeight) {
			contents.addClass('b-contents_full_true');
			arrows.addClass('b-articles__nav-cont_full_true');

		} else {
			contents.removeClass('b-contents_full_true');
			arrows.removeClass('b-articles__nav-cont_full_true');
		}
	});
});


text:
function circleArea(r) {

    let radius = Math.PI * r * r;

    console.log(radius);
    console.log(Math.round(radius * 100) / 100);
}

circleArea(5);


text:
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN

class bulk_write::impl {
   public:
    impl(mongoc_bulk_operation_t* op) : operation_t(op) {
    }

    ~impl() {
        libmongoc::bulk_operation_destroy(operation_t);
    }

    mongoc_bulk_operation_t* operation_t;
};

MONGOCXX_INLINE_NAMESPACE_END
}  // namespace mongocxx

#include <mongocxx/config/private/postlude.hpp>


text:
require 'fileutils'

class SessionService
  def self.get_current
    path = DATA_PATH + SESSION_FILE

    File.open path, 'r' do |file|
      @id = file.readline.gsub("\n", '')
      @total = file.readline.gsub("\n", '').to_i

    end

    {id: @id, total: @total}
  end

  def self.exist?
    File.exist?(DATA_PATH + SESSION_FILE)
  end

  def self.start
    time = Time.new.strftime '%Y%m%d%H%M%S'
    path = DATA_PATH + SESSION_FILE
    File.open path, 'w' do |file|
      file.write time
      file.write "\n"
      file.write 0
    end

    Dir.mkdir DATA_PATH + time
  end

  def self.update order_total
    session = SessionService.get_current
    session[:total] = session[:total] + order_total

    File.open(DATA_PATH + SESSION_FILE, 'wb') { |f| f.write "#{session[:id]}\n#{session[:total]}" }
  end

  def self.close
    current_session = SessionService.get_current[:id]
    source_path = DATA_PATH + SESSION_FILE
    target_path = DATA_PATH + current_session + '/session.ekz'
    session = File.open(source_path, 'rb') { |f| f.read }

    time = Time.new.strftime '%Y%m%d%H%M%S'
    File.open(target_path, 'w+') { |f| f.write session+"\n"+time }

    #Удаление старой сессии
    File.delete source_path
  end
end


text:
var Trello = require("trello");
var key = process.env.TRELLO_APP_KEY, token = process.env.TRELLO_USER_TOKEN;
var async = require('async');
var _ = require('lodash');
var slug = require('slug');
var marked = require('marked');
marked.setOptions({
    gfm: true,
    tables: true,
    breaks: true
}); // TODO further parser customizations as per trello-markdown ? headings with no space broken...

var markedp = require('marked');

var trello = new Trello(key, token);

// var api = {};
// api.uri = "https://api.trello.com/1";
// Trello.get('/sessions/socket', success, error);

// var io = require('socket.io-client')
// var socket = io.connect(api.uri + '/sessions/socket?key=' + key + '&token=' + token, {reconnect: true});
// console.log('io:', io, socket);
// Add a connect listener
// socket.on('connect', function(socket) {
    // console.log('Connected!', socket);
// });

// socket.on('connect_error', function(err){
    // console.log('connect_error on socket:', err);
// })

// this is our return object
var router = require('express').Router();

// we store an array of slug url / name combos for building a simple one-level deep navigation
var nav = [];

// generic route handler
function handler(req, res) {
    // for now we just do render statics
    // "this" is used to create a bound route definition object, as parsed from Trello API.
    // console.log("handler:", this.name, this.slug, this.cards.length);
    res.render("trello-list", {
        content: this.cards,
        title: this.name,
        nav: nav,
        path: this.slug
    });
}

// addroute:
// once we have a handler bound to a route definition, we wire it up to our router on the path
function addroute(path, hdlr) {
    // console.log("ADDROUTE:", path);
    router.get(path, hdlr);
}

// iterate all our configured routes, adding using above methods
function addroutes(cfg, sitename) {

    _.each(cfg, function (routedef, listid) {
        // add the bound route handler for each board list
        var path = "/" + routedef.slug;
        addroute(path, handler.bind(routedef));
        // add relevant info to the nav object
        nav.push({url: path, text: routedef.name});
    });
    // add an index page! TODO maybe look for a special list name to use here OR use an option
    addroute('/', handler.bind({name: sitename, cards: [], slug: '/'}))
}
// end router stuff

// our export function so we can get some options.
module.exports = function(options){
    // specify a board via passed option, will default to first board if not set or if not found
    var boardName = options.boardName || "";
    var boardId = options.boardId; // overrides board name
    // console.log('trello logged in:', trello);
    // new options:
    // rootList: 'listid' // specify a list name or list id to use as the root URL of the router

    // use labels to change rendering styles
    var boardLabelData;

    // local async helper method...
    var fetchCards = function(listid, done) {
        // default to all actions for a list get all cards
        trello.getCardsForList(listid, 'all', done);
    }

    // prepare our promise - will collate card content onto the express router
    var routeP = new Promise(function(resolve, reject) {
        var routeObj = {}; // route and content meta
        // do a bunch of stuff in order on the Trello API
        async.waterfall([
                // get my boards
                function(next) {
                    // console.log('get boards:', boardId, boardName);
                    if (boardId) {
                        next(null, boardId);
                    } else {
                        trello.getBoards("me", next);
                    }

                },
                // find the named or first board
                function(boards, next) {
                    if (typeof boards === 'string') return next(null, {id: boards});
                    var boardNames = _.map(boards, 'name');
                    // console.log('found board names:', boardNames);
                    var board = _.find(boards, ['name', boardName]);
                    if (!board) {
                        board = boards[0];
                        boardName = board.name;
                    }
                    console.log('found board:', board);  // has labelNames
                    next(null, board);
                },
                // use labels for modifying templates.
                function(board, next) {
                    trello.getLabelsForBoard(board.id, function(err, labels){
                        if (err) return next(err);
                        boardLabelData = labels; // simpler
                        next(null, board);
                    })
                },
                // get lists on the board
                function(board, next) {
                    // need to get list names + ids at the very least.
                    // console.log('get lists on:', board);
                    trello.getListsOnBoard(board.id, next);
                },
                // start getting all the cards on the board, by list
                // TODO could optimize this by just getting all cards on the board, since we sort them out by list id anyway
                function(lists, next) {
                    // console.log('lists on the board:', lists);
                    // now we have enough info to start building our router definition
                    var names = _.map(lists, 'name');
                    // console.log('list names:', names);
                    // prepare the base of our route metadata here...
                    var slugs = _.map(names, (name) => {
                        return {slug: slug(name), name: name, cards: [], sitename: boardName}
                    });
                    var ids = _.map(lists, 'id');
                    routeObj = _.zipObject(ids, slugs);
                    // console.log(names, slugs, ids);
                    // start an async for each list
                    var listFetchers = lists.map((list) => {
                        return fetchCards.bind(this, list.id);
                    });
                    async.parallel(listFetchers, next);
                },
                // sort cards to their correct page by list, plucking the data we want for our pages
                function(listsOfCards, next) {
                    // populates router definition with cards

                    // console.log('routes so far:', routeObj);
                    _.flatten(listsOfCards).forEach((card) => {
                        // simplify card model just have name and desc for now - TODO attachments
                        // console.log('route a card stack:', card);
                        if (routeObj[card.idList]) {
                            // markdown parser here
                            // console.log(card.desc);
                            var cardFormatted = {
                                name: card.name,
                                desc: marked(card.desc),
                                actions: card.actions,
                                labels: card.idLabels
                            }

                            // console.log('actions:', card.actions);
                            var attachments = _.filter(card.actions, (action) => {
                                // console.log(action.type);
                                if (action.data.attachment) { // = 'addAttachmentToCard') {
                                    // console.log(action.data.attachment);
                                    return true;
                                }

                            });
                            var comments = _.reduce(card.actions, function(memo, action) {
                                if (action.type === "commentCard") {
                                    // console.log('comment:', action.data.text);
                                    // weird newline artifacts - some strangeness in the trello-markdown
                                    memo.push(marked(action.data.text).replace('\n', ''));

                                }
                                return memo;
                            }, []);
                            // tag labels for view rendering
                            var labels = _.reduce(card.labels, function(memo, labelId){
                                // console.log('label reduce:', boardLabelData, labelId);
                                memo.push('label-' + labelId.name + labelId.color);
                                return memo;
                            }, []);
                            // console.log('labels:', labels);
                            cardFormatted.labels = labels;
                            cardFormatted.attachments = attachments;
                            cardFormatted.comments = comments;
                            // console.log('attachments:', attachments);
                            routeObj[card.idList].cards.push(cardFormatted);
                            /*
                            attachment:
                             { previewUrl2x: 'https://trello-attachments.s3.amazonaws.com/561d2b01473eb47fd8739c48/1200x800/bd081c51b4ec6d24e4f490f0819ff1c0/winterwalk_cropped.jpg',
                               previewUrl: 'https://trello-attachments.s3.amazonaws.com/561d2b01473eb47fd8739c48/600x400/b2481541b9790103e920516075675062/winterwalk_cropped.jpg',
                               url: 'https://trello-attachments.s3.amazonaws.com/561d2b01473eb47fd8739c48/2000x1333/c4674d17f598c49cb0435147daa72de3/winterwalk_cropped.jpg',
                               name: 'winterwalk_cropped.jpg',
                               id: '56c7625f4600a34c913aa25f' } }
                            */
                        }
                    });
                    // TODO filter actions for attachments, resolve URLs of image mime types
                    next(null, routeObj);
                },
                // add all routes to the router
                function(routeData, next) {
                    addroutes(routeObj, boardName);
                    next(null, router);
                }
            ], function(err, router){
            // main async waterfall is done
            // console.log('done all api calls ok:', err, router);
            // resolve / reject our promise. Changed to return an object so we can confirm that the router matches the trello board data
            if (!err) resolve({router: router, data: routeObj});
            reject(err);
        })
    });

    // promise is returned from the module.exports function.
    return routeP;
}


text:
@import PAYJP;

@interface UIViewController (Alert)

- (void)showToken:(PAYToken *)token;
- (void)showError:(NSError *)error;
- (NSString *)displayToken:(PAYToken *)token;

@end


text:
package org.keycloak.subsystem.wf8.extension;

import org.jboss.as.controller.Extension;
import org.jboss.as.controller.ExtensionContext;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ResourceDefinition;
import org.jboss.as.controller.SubsystemRegistration;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.as.controller.parsing.ExtensionParsingContext;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.keycloak.subsystem.wf8.logging.KeycloakLogger;

import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;

/**
 * Main Extension class for the subsystem.
 *
 * @author Stan Silvert ssilvert@redhat.com (C) 2013 Red Hat Inc.
 */
public class KeycloakExtension implements Extension {

    public static final String SUBSYSTEM_NAME = "keycloak";
    public static final String NAMESPACE = "urn:jboss:domain:keycloak:1.1";
    private static final KeycloakSubsystemParser PARSER = new KeycloakSubsystemParser();
    static final PathElement PATH_SUBSYSTEM = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
    private static final String RESOURCE_NAME = KeycloakExtension.class.getPackage().getName() + ".LocalDescriptions";
    private static final int MANAGEMENT_API_MAJOR_VERSION = 1;
    private static final int MANAGEMENT_API_MINOR_VERSION = 0;
    private static final int MANAGEMENT_API_MICRO_VERSION = 0;
    static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
    private static final ResourceDefinition KEYCLOAK_SUBSYSTEM_RESOURCE = new KeycloakSubsystemDefinition();
    static final RealmDefinition REALM_DEFINITION = new RealmDefinition();
    static final SecureDeploymentDefinition SECURE_DEPLOYMENT_DEFINITION = new SecureDeploymentDefinition();
    static final CredentialDefinition CREDENTIAL_DEFINITION = new CredentialDefinition();

    public static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {
        StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);
        for (String kp : keyPrefix) {
            prefix.append('.').append(kp);
        }
        return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, KeycloakExtension.class.getClassLoader(), true, false);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void initializeParsers(final ExtensionParsingContext context) {
        context.setSubsystemXmlMapping(SUBSYSTEM_NAME, KeycloakExtension.NAMESPACE, PARSER);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void initialize(final ExtensionContext context) {
        KeycloakLogger.ROOT_LOGGER.debug("Activating Keycloak Extension");
        final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, MANAGEMENT_API_MAJOR_VERSION, MANAGEMENT_API_MINOR_VERSION, MANAGEMENT_API_MICRO_VERSION);

        ManagementResourceRegistration registration = subsystem.registerSubsystemModel(KEYCLOAK_SUBSYSTEM_RESOURCE);
        registration.registerSubModel(REALM_DEFINITION);
        ManagementResourceRegistration secureDeploymentRegistration = registration.registerSubModel(SECURE_DEPLOYMENT_DEFINITION);
        secureDeploymentRegistration.registerSubModel(CREDENTIAL_DEFINITION);

        subsystem.registerXMLElementWriter(PARSER);
    }
}


text:
package org.terasology.reflection.copy;

/**
 * A strategy for copying an object/type.
 * This may be returning the object unchanged for immutable or otherwise safe to share types.
 * Copy strategies are deep-copies - contents should also be copied where appropriate.
 *
 * @author Immortius
 */
public interface CopyStrategy<T> {

    /**
     * @param value The value to copy
     * @return A safe to use copy of the given value.
     */
    T copy(T value);

}


text:
using SimplePersistence.Model;

namespace SimplePersistence.Example.Models.Logging
{
    public class Log : EntityWithCreatedMeta<long>
    {
        public virtual Level Level { get; set; }

        public virtual string Logger { get; set; }

        public virtual string Message { get; set; }

        public virtual string Exception { get; set; }

        public virtual Application Application { get; set; }

        public virtual string Thread { get; set; }

        public virtual string MachineName { get; set; }

        public virtual string AssemblyVersion { get; set; }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>CUDNN Frontend API: Member List</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>

<link href="../../navtree.css" rel="stylesheet" type="text/css"/>

<link href="../../search/search.css" rel="stylesheet" type="text/css"/>

<link href="../../doxygen.css" rel="stylesheet" type="text/css" />

CUDNN Frontend API
    8.3.0

cudnn_frontend::TensorBuilder_v8 Member List

This is the complete list of members for cudnn_frontend::TensorBuilder_v8, including all inherited members.

build()	cudnn_frontend::TensorBuilder_v8	inline

m_tensor	cudnn_frontend::TensorBuilder_v8	private

operator=(TensorBuilder_v8 const &)=delete	cudnn_frontend::TensorBuilder_v8

setAlignment(int64_t alignment_) -> TensorBuilder_v8 &	cudnn_frontend::TensorBuilder_v8	inline

setByValue(bool isByValue_=true) -> TensorBuilder_v8 &	cudnn_frontend::TensorBuilder_v8	inline

setDataType(cudnnDataType_t data_type_) -> TensorBuilder_v8 &	cudnn_frontend::TensorBuilder_v8	inline

setDim(int64_t ndim, int64_t const *dim) -> TensorBuilder_v8 &	cudnn_frontend::TensorBuilder_v8	inline

setId(int64_t id_) -> TensorBuilder_v8 &	cudnn_frontend::TensorBuilder_v8	inline

setStrides(int64_t ndim, int64_t const *strides) -> TensorBuilder_v8 &	cudnn_frontend::TensorBuilder_v8	inline

setVectorCountAndDimension(int64_t vectorCount_, int64_t vectorDimension_) -> TensorBuilder_v8 &	cudnn_frontend::TensorBuilder_v8	inline

setVirtual(bool virtual_=true) -> TensorBuilder_v8 &	cudnn_frontend::TensorBuilder_v8	inline

TensorBuilder_v8()=default	cudnn_frontend::TensorBuilder_v8	explicit

TensorBuilder_v8(TensorBuilder_v8 &&)=delete	cudnn_frontend::TensorBuilder_v8

TensorBuilder_v8(TensorBuilder_v8 const &)=delete	cudnn_frontend::TensorBuilder_v8

~TensorBuilder_v8()=default	cudnn_frontend::TensorBuilder_v8

Generated by

     1.8.13


text:
class Foo {
  constructor(set, readonly) {}
  constructor(set: any, readonly: boolean) {}
}


text:
module Spec
  module Support
    module Helpers
      # Returns the path with options[:version] prefixed if options[:using] is :path.
      # Returns normal path otherwise.
      def versioned_path(**options)
        case options[:using]
        when :path
          File.join('/', options[:prefix] || '', options[:version], options[:path])
        when :param
          File.join('/', options[:prefix] || '', options[:path])
        when :header
          File.join('/', options[:prefix] || '', options[:path])
        when :accept_version_header
          File.join('/', options[:prefix] || '', options[:path])
        else
          raise ArgumentError.new("unknown versioning strategy: #{options[:using]}")
        end
      end

      def versioned_headers(**options)
        case options[:using]
        when :path
          {}  # no-op
        when :param
          {}  # no-op
        when :header
          {
            'HTTP_ACCEPT' => [
              "application/vnd.#{options[:vendor]}-#{options[:version]}",
              options[:format]
            ].compact.join('+')
          }
        when :accept_version_header
          {
            'HTTP_ACCEPT_VERSION' => options[:version].to_s
          }
        else
          raise ArgumentError.new("unknown versioning strategy: #{options[:using]}")
        end
      end

      def versioned_get(path, version_name, **version_options)
        path = versioned_path(**version_options.merge(version: version_name, path: path))
        headers = versioned_headers(**version_options.merge(version: version_name))
        params = {}
        params = { version_options[:parameter] => version_name } if version_options[:using] == :param
        get path, params, headers
      end
    end
  end
end


text:
package org.apache.camel.processor.resequencer;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class TestComparatorTest extends Assert {

    private TestComparator c;

    private TestObject e1;
    private TestObject e2;
    private TestObject e3;

    @Before
    public void setUp() {
        c = new TestComparator();
        e1 = new TestObject(3);
        e2 = new TestObject(4);
        e3 = new TestObject(7);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testPredecessor() {
        assertTrue(c.predecessor(e1, e2));
        assertFalse(c.predecessor(e2, e1));
        assertFalse(c.predecessor(e1, e3));
        assertFalse(c.predecessor(e3, e1));
        assertFalse(c.predecessor(e3, e3));
    }

    @Test
    public void testSuccessor() {
        assertTrue(c.successor(e2, e1));
        assertFalse(c.successor(e1, e2));
        assertFalse(c.successor(e3, e1));
        assertFalse(c.successor(e1, e3));
        assertFalse(c.successor(e3, e3));
    }

    @Test
    public void testCompare() {
        assertTrue(c.compare(e1, e2) < 0);
        assertTrue(c.compare(e2, e1) > 0);
        assertTrue(c.compare(e1, e3) < 0);
        assertTrue(c.compare(e3, e1) > 0);
        assertTrue(c.compare(e3, e3) == 0);
    }

}


text:
from __future__ import unicode_literals

import datetime
from django.db import migrations, models
from django.utils.timezone import utc

class Migration(migrations.Migration):

    dependencies = [
        ('projects', '0005_auto_20160526_0749'),
    ]

    operations = [
        migrations.RenameField(
            model_name='membership',
            old_name='date_involved',
            new_name='date_first_involved',
        ),
        migrations.AddField(
            model_name='membership',
            name='date_updated',
            field=models.DateTimeField(auto_now=True, default=datetime.datetime(2016, 5, 26, 20, 54, 2, 621345, tzinfo=utc)),
            preserve_default=False,
        ),
    ]


text:
package org.codehaus.mojo.buildhelper;

import java.util.ArrayList;
import java.util.List;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

/**
 * Sets a property by applying a regex replacement rule to a supplied value. This is similar to regex-property goal with
 * support for multiple regex settings using RegexPropertyConfig
 *
 * @since 1.9
 */
@Mojo( name = "regex-properties", defaultPhase = LifecyclePhase.VALIDATE, threadSafe = true )
public class RegexPropertiesMojo
    extends AbstractRegexPropertyMojo
{
    /**
     * List of RegexPropertyConfig to apply the regex
     */
    @Parameter( required = false )
    private List<RegexPropertySetting> regexPropertySettings = new ArrayList<RegexPropertySetting>();

    public void execute()
        throws MojoExecutionException, MojoFailureException
    {

        for ( RegexPropertySetting setting : regexPropertySettings )
        {
            this.execute( setting );
        }
    }

}


text:
package org.talend.dataprep.dataset.store.content;

public interface DataSetContentLimit {

    DataSetContentStore get(DataSetContentStore store);

    boolean limitContentSize();

    Long getLimit();

}


text:
using ::testing::_;
using ::testing::Invoke;
using ::testing::NotNull;
using ::testing::Return;

namespace media {

MockDemuxer::MockDemuxer() {}

MockDemuxer::~MockDemuxer() {}

MockDemuxerStream::MockDemuxerStream(DemuxerStream::Type type)
    : type_(type), liveness_(LIVENESS_UNKNOWN) {
}

MockDemuxerStream::~MockDemuxerStream() {}

DemuxerStream::Type MockDemuxerStream::type() const {
  return type_;
}

DemuxerStream::Liveness MockDemuxerStream::liveness() const {
  return liveness_;
}

AudioDecoderConfig MockDemuxerStream::audio_decoder_config() {
  DCHECK_EQ(type_, DemuxerStream::AUDIO);
  return audio_decoder_config_;
}

VideoDecoderConfig MockDemuxerStream::video_decoder_config() {
  DCHECK_EQ(type_, DemuxerStream::VIDEO);
  return video_decoder_config_;
}

void MockDemuxerStream::set_audio_decoder_config(
    const AudioDecoderConfig& config) {
  DCHECK_EQ(type_, DemuxerStream::AUDIO);
  audio_decoder_config_ = config;
}

void MockDemuxerStream::set_video_decoder_config(
    const VideoDecoderConfig& config) {
  DCHECK_EQ(type_, DemuxerStream::VIDEO);
  video_decoder_config_ = config;
}

void MockDemuxerStream::set_liveness(DemuxerStream::Liveness liveness) {
  liveness_ = liveness;
}

VideoRotation MockDemuxerStream::video_rotation() {
  return VIDEO_ROTATION_0;
}

std::string MockVideoDecoder::GetDisplayName() const {
  return "MockVideoDecoder";
}

MockVideoDecoder::MockVideoDecoder() {
  EXPECT_CALL(*this, HasAlpha()).WillRepeatedly(Return(false));
}

std::string MockAudioDecoder::GetDisplayName() const {
  return "MockAudioDecoder";
}

MockVideoDecoder::~MockVideoDecoder() {}

MockAudioDecoder::MockAudioDecoder() {}

MockAudioDecoder::~MockAudioDecoder() {}

MockVideoRenderer::MockVideoRenderer() {}

MockVideoRenderer::~MockVideoRenderer() {}

MockAudioRenderer::MockAudioRenderer() {}

MockAudioRenderer::~MockAudioRenderer() {}

MockRenderer::MockRenderer() {}

MockRenderer::~MockRenderer() {}

MockTimeSource::MockTimeSource() {}

MockTimeSource::~MockTimeSource() {}

MockTextTrack::MockTextTrack() {}

MockTextTrack::~MockTextTrack() {}

MockDecryptor::MockDecryptor() {}

MockDecryptor::~MockDecryptor() {}

}  // namespace media


text:
package org.jbb.system.web.logging.data;

import org.jbb.system.api.logging.model.AppLogger;
import org.jbb.system.api.logging.model.LogAppender;
import org.jbb.system.api.logging.model.LogLevel;

import java.util.List;
import java.util.stream.Collectors;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
public class LoggerRow {
    private String name;
    private String level;
    private String addivity;
    private List<String> appenders;

    public LoggerRow(String name, LogLevel level, boolean addivity, List<LogAppender> appenders) {
        this.name = name;
        this.level = level.toString().toLowerCase();
        if (AppLogger.ROOT_LOGGER_NAME.equalsIgnoreCase(name)) {
            this.addivity = "N/A";
        } else {
            this.addivity = Boolean.toString(addivity);
        }
        this.appenders = appenders.stream()
                .map(LogAppender::getName)
                .collect(Collectors.toList());
    }
}


text:
from __future__ import print_function
import boto3
import json
import uuid
from decimal import *

# Monkey patch Decimal's default Context to allow
# inexact and rounded representation of floats
from boto3.dynamodb.types import DYNAMODB_CONTEXT
# Inhibit Inexact Exceptions
DYNAMODB_CONTEXT.traps[Inexact] = 0

# Inhibit Rounded Exceptions
DYNAMODB_CONTEXT.traps[Rounded] = 0

def lambda_handler(event, context):
    dynamo = boto3.resource('dynamodb').Table('senseware')

    # When testing thorugh the lambda UI the packet is the event but when testing through the Api Gateway the packet
    # is wrapped in an additional request metadata dictionary
    try:
        packet = json.loads(event['body'])
    except KeyError:
        packet = event

    for record in packet['data']:
        for key in ['value', 'raw']:
            if record[key] != "" and record[key] != None:
                # DynamoDb wants decimals, not floats
                record[key] = Decimal(record[key])
            else:
                del record[key]

        for key in ['pkt', 'ts']:
            if record[key] == "" or record[key] == None:
                del record[key]

        # Add the streams meta data to every record (optional)
        for key in ['sn', 'site', 'location', 'mod', 'sid', 'type', 'cid', 'name', 'unit']:
            if packet[key] != "" and packet[key] != None:
                # DynamoDb wants decimals, not floats
                record[key] = packet[key]

        # Give this record an ID
        record['partition'] = str(uuid.uuid4())

        # Put it into the database
        dynamo.put_item(
            TableName='senseware',
            Item=record
        )

    # Return a Success Message
    return {
      "statusCode": 200,
      "body": ""
    }


text:
Vue.component('clear-playlist-modal', {
  data() {
    return {
      opened: false
    };
  },
  methods: {
    open() {
      this.opened = true;
    },
    close() {
      this.opened = false;
    },
    onSubmit() {
      this.clearPlaylist();
      this.close();
    },
    ...mapActions(['clearPlaylist'])
  },

  template: `

Confirmation

        <button class="delete" @click="close"></button>

Do you really want to clear the playlist?

If you click the clear button, all of tracks in the playlist will be removed.

        Clear
        Cancel

  `
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.quartz.core.QuartzSchedulerThread (Quartz Enterprise Job Scheduler 2.2.0 API)
</TITLE>

<META NAME="date" CONTENT="2013-06-29">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.quartz.core.QuartzSchedulerThread

Packages that use QuartzSchedulerThread

org.quartz.core
Contains the core classes and interfaces for the Quartz job scheduler.

Uses of QuartzSchedulerThread in org.quartz.core

Fields in org.quartz.core declared as QuartzSchedulerThread

protected  QuartzSchedulerThread
SchedulerSignalerImpl.schedThread

Constructors in org.quartz.core with parameters of type QuartzSchedulerThread

SchedulerSignalerImpl(QuartzScheduler sched,
                      QuartzSchedulerThread schedThread)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright 2001-2013, Terracotta, Inc.


text:
#include "mbedtls/md2.h"
#include "mbedtls/md4.h"
#include "mbedtls/md5.h"
#include "mbedtls/sha1.h"
#include "mbedtls/sha256.h"
#include "mbedtls/sha512.h"

#if defined(MBEDTLS_MD2_ALT) && defined(MBEDTLS_MD2_C)

/**
 * \brief          MD2 context setup
 *
 * \deprecated     Superseded by mbedtls_md2_starts_ret() in 2.7.0
 *
 * \param ctx      context to be initialized
 *
 * \warning        MD2 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_md2_starts( mbedtls_md2_context *ctx )
{
    mbedtls_md2_starts_ret( ctx );
}

/**
 * \brief          MD2 process buffer
 *
 * \deprecated     Superseded by mbedtls_md2_update_ret() in 2.7.0
 *
 * \param ctx      MD2 context
 * \param input    buffer holding the data
 * \param ilen     length of the input data
 *
 * \warning        MD2 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_md2_update( mbedtls_md2_context *ctx,
                         const unsigned char *input,
                         size_t ilen )
{
    mbedtls_md2_update_ret( ctx, input, ilen );
}

/**
 * \brief          MD2 final digest
 *
 * \deprecated     Superseded by mbedtls_md2_finish_ret() in 2.7.0
 *
 * \param ctx      MD2 context
 * \param output   MD2 checksum result
 *
 * \warning        MD2 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_md2_finish( mbedtls_md2_context *ctx,
                         unsigned char output[16] )
{
    mbedtls_md2_finish_ret( ctx, output );
}

#endif /* defined(MBEDTLS_MD2_ALT) */

#if defined(MBEDTLS_MD4_ALT) && defined(MBEDTLS_MD4_C)

/**
 * \brief          MD4 context setup
 *
 * \deprecated     Superseded by mbedtls_md4_starts_ret() in 2.7.0
 *
 * \param ctx      context to be initialized
 *
 * \warning        MD4 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_md4_starts( mbedtls_md4_context *ctx )
{
    mbedtls_md4_starts_ret( ctx );
}

/**
 * \brief          MD4 process buffer
 *
 * \deprecated     Superseded by mbedtls_md4_update_ret() in 2.7.0
 *
 * \param ctx      MD4 context
 * \param input    buffer holding the data
 * \param ilen     length of the input data
 *
 * \warning        MD4 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_md4_update( mbedtls_md4_context *ctx,
                         const unsigned char *input,
                         size_t ilen )
{
    mbedtls_md4_update_ret( ctx, input, ilen );
}

/**
 * \brief          MD4 final digest
 *
 * \deprecated     Superseded by mbedtls_md4_finish_ret() in 2.7.0
 *
 * \param ctx      MD4 context
 * \param output   MD4 checksum result
 *
 * \warning        MD4 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_md4_finish( mbedtls_md4_context *ctx,
                         unsigned char output[16] )
{
    mbedtls_md4_finish_ret( ctx, output );
}

#endif /* defined(MBEDTLS_MD4_ALT) */

#if defined(MBEDTLS_MD5_ALT) && defined(MBEDTLS_MD5_C)

/**
 * \brief          MD5 context setup
 *
 * \deprecated     Superseded by mbedtls_md5_starts_ret() in 2.7.0
 *
 * \param ctx      context to be initialized
 *
 * \warning        MD5 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_md5_starts( mbedtls_md5_context *ctx )
{
    mbedtls_md5_starts_ret( ctx );
}

/**
 * \brief          MD5 process buffer
 *
 * \deprecated     Superseded by mbedtls_md5_update_ret() in 2.7.0
 *
 * \param ctx      MD5 context
 * \param input    buffer holding the data
 * \param ilen     length of the input data
 *
 * \warning        MD5 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_md5_update( mbedtls_md5_context *ctx,
                         const unsigned char *input,
                         size_t ilen )
{
    mbedtls_md5_update_ret( ctx, input, ilen );
}

/**
 * \brief          MD5 final digest
 *
 * \deprecated     Superseded by mbedtls_md5_finish_ret() in 2.7.0
 *
 * \param ctx      MD5 context
 * \param output   MD5 checksum result
 *
 * \warning        MD5 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_md5_finish( mbedtls_md5_context *ctx,
                         unsigned char output[16] )
{
    mbedtls_md5_finish_ret( ctx, output );
}

#endif /* defined(MBEDTLS_MD5_ALT) */

#if defined(MBEDTLS_SHA1_ALT) && defined(MBEDTLS_SHA1_C)

/**
 * \brief          SHA-1 context setup
 *
 * \deprecated     Superseded by mbedtls_sha1_starts_ret() in 2.7.0
 *
 * \param ctx      The SHA-1 context to be initialized.
 *
 * \warning        SHA-1 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_sha1_starts( mbedtls_sha1_context *ctx )
{
    mbedtls_sha1_starts_ret( ctx );
}

/**
 * \brief          SHA-1 process buffer
 *
 * \deprecated     Superseded by mbedtls_sha1_update_ret() in 2.7.0
 *
 * \param ctx      The SHA-1 context.
 * \param input    The buffer holding the input data.
 * \param ilen     The length of the input data.
 *
 * \warning        SHA-1 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_sha1_update( mbedtls_sha1_context *ctx,
                          const unsigned char *input,
                          size_t ilen )
{
    mbedtls_sha1_update_ret( ctx, input, ilen );
}

/**
 * \brief          SHA-1 final digest
 *
 * \deprecated     Superseded by mbedtls_sha1_finish_ret() in 2.7.0
 *
 * \param ctx      The SHA-1 context.
 * \param output   The SHA-1 checksum result.
 *
 * \warning        SHA-1 is considered a weak message digest and its use
 *                 constitutes a security risk. We recommend considering
 *                 stronger message digests instead.
 *
 */
void mbedtls_sha1_finish( mbedtls_sha1_context *ctx,
                          unsigned char output[20] )
{
    mbedtls_sha1_finish_ret( ctx, output );
}

#endif /* defined(MBEDTLS_SHA1_ALT) */

#if defined(MBEDTLS_SHA256_ALT) && defined(MBEDTLS_SHA256_C)

/**
 * \brief          This function starts a SHA-256 checksum calculation.
 *
 * \deprecated     Superseded by mbedtls_sha256_starts_ret() in 2.7.0.
 *
 * \param ctx      The SHA-256 context to initialize.
 * \param is224    Determines which function to use.
 *

0: Use SHA-256.

 *
1: Use SHA-224.

 */
void mbedtls_sha256_starts( mbedtls_sha256_context *ctx,
                            int is224 )
{
    mbedtls_sha256_starts_ret( ctx, is224 );
}

/**
 * \brief          This function feeds an input buffer into an ongoing
 *                 SHA-256 checksum calculation.
 *
 * \deprecated     Superseded by mbedtls_sha256_update_ret() in 2.7.0.
 *
 * \param ctx      The SHA-256 context to initialize.
 * \param input    The buffer holding the data.
 * \param ilen     The length of the input data.
 */
void mbedtls_sha256_update( mbedtls_sha256_context *ctx,
                            const unsigned char *input,
                            size_t ilen )
{
    mbedtls_sha256_update_ret( ctx, input, ilen );
}

/**
 * \brief          This function finishes the SHA-256 operation, and writes
 *                 the result to the output buffer.
 *
 * \deprecated     Superseded by mbedtls_sha256_finish_ret() in 2.7.0.
 *
 * \param ctx      The SHA-256 context.
 * \param output   The SHA-224or SHA-256 checksum result.
 */
void mbedtls_sha256_finish( mbedtls_sha256_context *ctx,
                            unsigned char output[32] )
{
    mbedtls_sha256_finish_ret( ctx, output );
}

#endif /* defined(MBEDTLS_SHA256_ALT) */

#if defined(MBEDTLS_SHA512_ALT) && defined(MBEDTLS_SHA512_C)

/**
 * \brief          This function starts a SHA-384 or SHA-512 checksum
 *                 calculation.
 *
 * \deprecated     Superseded by mbedtls_sha512_starts_ret() in 2.7.0
 *
 * \param ctx      The SHA-512 context to initialize.
 * \param is384    Determines which function to use.
 *

0: Use SHA-512.

 *
1: Use SHA-384.

 */
void mbedtls_sha512_starts( mbedtls_sha512_context *ctx,
                            int is384 )
{
    mbedtls_sha512_starts_ret( ctx, is384 );
}

/**
 * \brief          This function feeds an input buffer into an ongoing
 *                 SHA-512 checksum calculation.
 *
 * \deprecated     Superseded by mbedtls_sha512_update_ret() in 2.7.0
 *
 * \param ctx      The SHA-512 context.
 * \param input    The buffer holding the data.
 * \param ilen     The length of the input data.
 */
void mbedtls_sha512_update( mbedtls_sha512_context *ctx,
                            const unsigned char *input,
                            size_t ilen )
{
    mbedtls_sha512_update_ret( ctx, input, ilen );
}

/**
 * \brief          This function finishes the SHA-512 operation, and writes
 *                 the result to the output buffer.
 *
 * \deprecated     Superseded by mbedtls_sha512_finish_ret() in 2.7.0
 *
 * \param ctx      The SHA-512 context.
 * \param output   The SHA-384 or SHA-512 checksum result.
 */
void mbedtls_sha512_finish( mbedtls_sha512_context *ctx,
                            unsigned char output[64] )
{
    mbedtls_sha512_finish_ret( ctx, output );
}

#endif /* defined(MBEDTLS_SHA512_ALT) */


text:
#if !defined(_SEGMENT_H_)
#define _SEGMENT_H_

#include <SegmentLdr.h>

namespace Executor
{
extern bool ROMlib_exit;

struct finderinfo
{
    GUEST_STRUCT;
    GUEST<INTEGER> message;
    GUEST<INTEGER> count;
    GUEST<AppFile[1]> files;
};

extern void InitAppFiles(const std::vector<std::string>&);
extern void empty_timer_queues();

extern void C_LoadSeg(INTEGER segno);

static_assert(sizeof(finderinfo) == 268);
}
#endif /* !_SEGMENT_H_ */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Z. Mykol. 65(1): 34 (1999)

#### Original name
Moravecia hvaleri Benkert & Kristiansen

### Remarks
null


text:
import React, {Component} from 'react';

export default class Gimme extends Component {
    render() {
        return (

{this.props.title}

        );
    }
}


text:
<?php
namespace Blog\V1\Rest\User;

use Zend\Paginator\Paginator;

class UserCollection extends Paginator
{
}


text:
package solar.dimensions.api.plugin;

public class PluginParser {

}


text:
from abc import ABC, abstractmethod
from typing import Any, Callable, Optional, Dict, Tuple, Set

from .utils import Interfaces

class Node(ABC):
	"""Abstract interface implemented by every Pabiana Node.

	A Pabiana Node is a type of networking software that can provide different types of Interfaces.
	Other Nodes can connect to these Interfaces.

	Attributes:
		name: Unique name of the Node.
		interfaces: IP addresses, ports and optionally host IPs for every Nodes interfaces are stored here.
		time: Internal time of the Node.
	"""
	def __init__(self, name: str, interfaces: Interfaces):
		self.name = name  # type: str
		self.interfaces = interfaces  # type: Interfaces
		self.time = 1  # type: int

	def rslv(self, interface: str, name: str=None) -> Tuple[str, int, Optional[str]]:
		"""Return the IP address, port and optionally host IP for one of this Nodes interfaces."""
		if name is None:
			name = self.name
		key = '{}-{}'.format(name, interface)
		host = self.interfaces[key].get('host', None)
		return self.interfaces[key]['ip'], self.interfaces[key]['port'], host

	@abstractmethod
	def run(self):
		"""Starts the Node. Runs in an infinite loop."""
		pass

	@abstractmethod
	def stop(self):
		"""Stops the Node safely."""
		pass

class Area(Node):
	"""Abstract interface implemented by every Pabiana Area.

	A Pabiana Area is a special type of Node.
	It can provide one Receiver and multiple Subscriber Interfaces.
	Other Areas could call remote Triggers on and Publish messages to these Interfaces.
	It can process Triggers and messages. It includes time synch mechanisms.

	Attributes:
		context: Central store of the Areas non-volatile state.
	"""
	def __init__(self, name: str, interfaces: Interfaces):
		super().__init__(name, interfaces)
		self.context = {}  # type: dict

	@abstractmethod
	def publish(self, message: dict, slot: str=None):
		"""Publishes a message on the optionally given Slot."""
		pass

	@abstractmethod
	def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}):
		"""Calls the specified Trigger of another Area with the optionally given parameters.

		Args:
			target: The name of the target Area.
			trigger: The name of the Trigger.
			parameters: The parameters of the function call.
		"""
		pass

	@abstractmethod
	def scheduling(self, func: Callable) -> Callable:
		"""Registers this function as scheduler (only one). Intended to be used as decorator."""
		pass

	# ------------- Trigger processing functions -------------

	@abstractmethod
	def register(self, func: Callable) -> Callable:
		"""Registers the function as remote Trigger. Intended to be used as decorator."""
		pass

	@abstractmethod
	def comply(self, trigger: str, parameters: Dict[str, Any]={}):  # TODO: args/kwargs?
		"""Registers a request to call the Trigger function with the given parameters during the next round.

		This method should be induced by Areas higher in the hierarchy, to influence this Areas procedures.
		A certain trigger will only be called once in a single round.
		The parameters of the most recent request will be used.
		This method should not be called from within the Area.
		Autoloop requests are given preference.

		Args:
			trigger: The name of the trigger.
			parameters: The parameters of the function call.
		"""
		pass

	@abstractmethod
	def autoloop(self, trigger: str, parameters: Dict[str, Any]={}):  # TODO: args/kwargs?
		"""Registers a request to call the Trigger function with the given parameters during the next round.

		A certain trigger will only be called once in a single round.
		The parameters of the most recent request will be used.
		This method is intended to be called from within the Area.

		Args:
			trigger: The name of the trigger.
			parameters: The parameters of the function call.
		"""
		pass

	# ------------- Message processing functions -------------

	@abstractmethod
	def alteration(self, func: Callable=None, source: str=None, slot: str=None) -> Callable:
		"""Registers the function to be called in the next round after a optionally specified Subscriber message has arrived.

		Intended to be used as decorator.
		Only one function can be registered for a certain source/slot combination.

		Args:
			func: The function to be called.
			source: The optional name of the Area that sent the message.
			slot: The optional Slot from which the message was sent. A source must be given.
		"""
		pass

	@abstractmethod
	def process(self, source: str, message: dict, slot: str=None):
		"""Processes the given message. A message should originate from an Area lower in the hierarchy.

		This method should be induced by Areas lower in the hierarchy, to send their results.
		Data processing should be done by alteration functions.
		This method should not be called from within the Area.

		Args:
			source: The name of the Area that sent the message.
			message: The message to be processed.
			slot: The optional Slot from which the message was sent.
		"""
		pass

	@abstractmethod
	def alter(self, source: str=None, slot: str=None):
		"""Requests an alteration function to be called in the next round, even if no Subscriber message has arrived.

		A certain function will only be called once in a single round.
		This method is intended to be called from within the Area.

		Args:
			source: The source value the desired function was registered with.
			slot: The slot value the desired function was registered with.
		"""
		pass

	# ------------- Clock processing functions -------------

	@abstractmethod
	def activity(self, func: Callable) -> Callable:
		"""Registers the function to be called if there occurred input during this round.

		Only one function can be set.
		This method is intended to be used as a decorator.
		"""
		pass

	@abstractmethod
	def pulse(self, func: Callable) -> Callable:
		"""Registers the function to be called at the end of every round.

		Only one function can be set.
		This method is intended to be used as a decorator.
		"""
		pass

	@abstractmethod
	def proceed(self):
		"""Initiates the next round of this Areas procedures. Requested functions will be called.

		This method should not be called from within the Area.
		"""
		pass


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
MenuItemCompat.OnActionExpandListener
</TITLE>

<META NAME="date" CONTENT="2013-08-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

android.support.v4.view

Interface MenuItemCompat.OnActionExpandListener

Enclosing class:
MenuItemCompat

public static interface MenuItemCompat.OnActionExpandListener

Interface definition for a callback to be invoked when a menu item marked with MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW is expanded or collapsed.

See Also:
#expandActionView(android.view.MenuItem),
#collapseActionView(android.view.MenuItem),
#setShowAsAction(android.view.MenuItem, int)

Method Summary

 boolean
onMenuItemActionCollapse(MenuItem item)

          Called when a menu item with MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
 is collapsed.

 boolean
onMenuItemActionExpand(MenuItem item)

          Called when a menu item with MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
 is expanded.

Method Detail

onMenuItemActionExpand

boolean onMenuItemActionExpand(MenuItem item)

Called when a menu item with MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
 is expanded.

Parameters:
item - Item that was expanded

Returns:
true if the item should expand, false if expansion should be suppressed.

onMenuItemActionCollapse

boolean onMenuItemActionCollapse(MenuItem item)

Called when a menu item with MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
 is collapsed.

Parameters:
item - Item that was collapsed

Returns:
true if the item should collapse, false if collapsing should be suppressed.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
DISK=my.disk
MOUNTDIR=tmpdisk

# If no arg supplied, setup disk
if [ $# -eq 0 ]
then

  # Remove disk if exists
  rm -f $DISK
  # Preallocate space to a 4GB file
  truncate -s 128M $DISK
  # Create FAT32 filesystem on "my.disk"
  mkfs.fat $DISK

  # Create mountdir and mount
  mkdir -p $MOUNTDIR
  sudo mount -o rw $DISK $MOUNTDIR/
  # Copy banana.txt onto disk
  sudo cp banana.txt $MOUNTDIR/
  # Create deep nested directory and copy banana.txt into dir
  sudo mkdir -p $MOUNTDIR/dir1/dir2/dir3/dir4/dir5/dir6
  sudo cp banana.txt $MOUNTDIR/dir1/dir2/dir3/dir4/dir5/dir6/
  sync # Mui Importante
  sudo umount $MOUNTDIR/
  rmdir $MOUNTDIR

# If "clean" is supplied, clean up
elif [ $1 = "clean" ]
then
  echo "> Cleaning up FAT32 TEST DISK: $DISK"
  rm -f $DISK
fi


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/serwis_nowy.iml" filepath="$PROJECT_DIR$/.idea/serwis_nowy.iml" />
    </modules>
  </component>
</project>


text:
-A INPUT -p tcp -m tcp --dport smtp -m state --state NEW,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --sport auth -m state --state ESTABLISHED -j ACCEPT

#
# POP3S (995) - Hosting a secure POP3 server for remote clients
# IMAPS (993) - Hosting a Secure IMAP server for remote clients
#
-A INPUT -p tcp --sport 1024: -m multiport --dports 995,993 -j ACCEPT

#
# IMAP (143) - Retrieving Mail as an IMAP client
# IMAPS (993) - Retrieving Mail as an Secure IMAP client
# POP3S (995) - Retrieving Mail as a POP3S client
# IMAPS (1194) - Another port for retrieving mail as secure IMAP client
#
-A INPUT -p tcp -m state --state ESTABLISHED,RELATED -m multiport --sports 143,993,995,1194 -m tcp --dport 1024: -j ACCEPT

# End iptables.3.m


text:
import {RecipeActions} from 'app/home/body/process/recipe/opticalMosaic/opticalMosaicRecipe'
import {Subject, map, takeUntil} from 'rxjs'
import {compose} from 'compose'
import {msg} from 'translate'
import {withRecipe} from 'app/home/body/process/recipeContext'
import MapStatus from 'widget/mapStatus'
import React from 'react'
import api from 'api'

const mapRecipeToProps = recipe => ({recipe})

class AutoSelectScenes extends React.Component {
    constructor(props) {
        super(props)
        const {recipe, asyncActionBuilder} = props
        this.recipeActions = RecipeActions(recipe.id)
        this.request$ = new Subject()
        this.request$.subscribe(() => {
            this.recipeActions.setAutoSelectScenesState('RUNNING').dispatch()
            asyncActionBuilder('AUTO_SELECT_SCENES',
                this.autoSelectScenes$())
                .onComplete(() => this.recipeActions.setAutoSelectScenesState(null))
                .dispatch()
        }
        )
    }

    autoSelectScenes$() {
        const recipe = this.props.recipe
        return api.gee.autoSelectScenes$({
            sceneAreaIds: recipe.ui.sceneAreas.map(sceneArea => sceneArea.id),
            sources: recipe.model.sources,
            dates: recipe.model.dates,
            sceneSelectionOptions: recipe.model.sceneSelectionOptions,
            sceneCount: recipe.ui.autoSelectScenes,
            cloudCoverTarget: 0.001
        }).pipe(
            map(scenes =>
                this.recipeActions.setSelectedScenes(scenes)
            ),
            takeUntil(this.request$)
        )
    }

    render() {
        const {action} = this.props
        return (
            <div>
                {action('AUTO_SELECT_SCENES').dispatching
                    ? <MapStatus message={msg('process.mosaic.panel.autoSelectScenes.selecting')}/>
                    : null}
            </div>
        )
    }

    componentDidUpdate() {
        if (this.props.recipe.ui.autoSelectScenesState === 'SUBMITTED')
            this.request$.next()
    }

    componentWillUnmount() {
        this.request$.unsubscribe()
    }
}

export default compose(
    AutoSelectScenes,
    withRecipe(mapRecipeToProps)
)


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>kml</artifactId>
	<packaging>pom</packaging>
	<name>OGC KML</name>
	<parent>
		<groupId>org.jvnet.ogc</groupId>
		<artifactId>ogc-schemas-project</artifactId>
		<version>2.5.1-SNAPSHOT</version>
	</parent>
	<modules>
		<module>2.2.0</module>
	</modules>
	<build>
		<defaultGoal>install</defaultGoal>
	</build>
</project>


text:
package main

import (
    "encoding/json"
    "io/ioutil"
    "log"
    "github.com/MrSaints/gobeaver"
)

func DumpUndergraduate() {
    //courses := gobeaver.GetAllCourses()
    courses := gobeaver.GetCourses("Undergraduate")
    log.Printf("Total courses: %d", len(courses))
    courses.GetProperties()

    json_courses, json_error := json.Marshal(courses)
    if json_error != nil {
        log.Fatal(json_error)
    }

    file_error := ioutil.WriteFile("courses_dump.json", json_courses, 0644)
    if file_error != nil {
        panic(file_error)
    }

    log.Print("Complete!")
}

func main() {
    //EC599 := gobeaver.GetCourse("EC599")
    //log.Print(EC599)

    DumpUndergraduate()
}


text:
package org.axonframework.saga.annotation;

import org.axonframework.saga.AssociationValue;
import org.junit.*;

import java.util.Iterator;

import static org.junit.Assert.*;

/**
 * @author Allard Buijze
 */
public class AssociationValuesImplTest {

    private AssociationValuesImpl testSubject;
    private AssociationValue associationValue;

    @Before
    public void setUp() throws Exception {
        testSubject = new AssociationValuesImpl();
        associationValue = new AssociationValue("key", "value");
    }

    @Test
    public void testAddAssociationValue() throws Exception {
        testSubject.add(associationValue);

        assertEquals(1, testSubject.addedAssociations().size());
        assertTrue(testSubject.removedAssociations().isEmpty());
    }

    @Test
    public void testAddAssociationValue_AddedTwice() throws Exception {
        testSubject.add(associationValue);
        testSubject.commit();
        testSubject.add(associationValue);
        assertTrue(testSubject.addedAssociations().isEmpty());
        assertTrue(testSubject.removedAssociations().isEmpty());
    }

    @Test
    public void testRemoveAssociationValue() {
        assertTrue(testSubject.add(associationValue));
        testSubject.commit();
        assertTrue(testSubject.remove(associationValue));
        assertTrue(testSubject.addedAssociations().isEmpty());
        assertEquals(1, testSubject.removedAssociations().size());
    }

    @Test
    public void testRemoveAssociationValue_NotInContainer() {
        testSubject.remove(associationValue);
        assertTrue(testSubject.addedAssociations().isEmpty());
        assertTrue(testSubject.removedAssociations().isEmpty());
    }

    @Test
    public void testAddAndRemoveEntry() {
        testSubject.add(associationValue);
        testSubject.remove(associationValue);

        assertTrue(testSubject.addedAssociations().isEmpty());
        assertTrue(testSubject.removedAssociations().isEmpty());
    }

    @Test
    public void testContains() {
        assertFalse(testSubject.contains(associationValue));
        testSubject.add(associationValue);
        assertTrue(testSubject.contains(associationValue));
        assertTrue(testSubject.contains(new AssociationValue("key", "value")));
        testSubject.remove(associationValue);
        assertFalse(testSubject.contains(associationValue));
    }

    @Test
    public void testAsSet() {
        testSubject.add(associationValue);
        int t = 0;
        for (AssociationValue actual : testSubject.asSet()) {
            assertSame(associationValue, actual);
            t++;
        }
        assertEquals(1, t);
    }

    @Test
    public void testIterator() {
        testSubject.add(associationValue);
        Iterator<AssociationValue> iterator = testSubject.iterator();
        assertSame(associationValue, iterator.next());
        assertFalse(iterator.hasNext());
    }
}