text:
""" The access backend object base class """
import hashlib
import hmac
import time
from collections import defaultdict
from typing import Any, Dict, List, Optional, Set, Tuple

from passlib.apps import LazyCryptContext
from passlib.utils import sys_bits
from pyramid.security import (
    ALL_PERMISSIONS,
    Allow,
    Authenticated,
    Deny,
    Everyone,
    effective_principals,
)
from pyramid.settings import aslist

from pypicloud.util import get_environ_setting

# Roughly tuned using https://bitbucket.org/ecollins/passlib/raw/default/choose_rounds.py
# For 10ms. This differs from the passlib recommendation of 350ms due to the difference in use case
DEFAULT_ROUNDS = {
    "sha512_crypt__default_rounds": 20500,
    "sha256_crypt__default_rounds": 16000,
    "pbkdf2_sha512__default_rounds": 10500,
    "pbkdf2_sha256__default_rounds": 13000,
    "bcrypt__default_rounds": 7,
    "argon2__default_rounds": 1,
}
SCHEMES = [
    "sha512_crypt",
    "sha256_crypt",
    "pbkdf2_sha512",
    "pbkdf2_sha256",
    "bcrypt",
    "argon2",
]
if sys_bits < 64:
    SCHEMES.remove("sha512_crypt")
    SCHEMES.remove("pbkdf2_sha512")

def get_pwd_context(
    preferred_hash: Optional[str] = None, rounds: Optional[int] = None
) -> LazyCryptContext:
    """ Create a passlib context for hashing passwords """
    if preferred_hash is None or preferred_hash == "sha":
        preferred_hash = "sha256_crypt" if sys_bits < 64 else "sha512_crypt"
    if preferred_hash == "pbkdf2":
        preferred_hash = "pbkdf2_sha256" if sys_bits < 64 else "pbkdf2_sha512"

    if preferred_hash not in SCHEMES:
        raise Exception(
            "Password hash %r is not in the list of supported schemes" % preferred_hash
        )

    # Put the preferred hash at the beginning of the schemes list
    schemes = list(SCHEMES)
    schemes.remove(preferred_hash)
    schemes.insert(0, preferred_hash)

    # Override the default rounds of the preferred hash, if provided
    default_rounds = dict(DEFAULT_ROUNDS)
    if rounds is not None:
        default_rounds[preferred_hash + "__default_rounds"] = rounds

    return LazyCryptContext(schemes=schemes, default=schemes[0], **default_rounds)

def group_to_principal(group: str) -> str:
    """ Convert a group to its corresponding principal """
    if group in (Everyone, Authenticated) or group.startswith("group:"):
        return group
    elif group == "everyone":
        return Everyone
    elif group == "authenticated":
        return Authenticated
    else:
        return "group:" + group

def groups_to_principals(groups: List[str]) -> List[str]:
    """ Convert a list of groups to a list of principals """
    return [group_to_principal(g) for g in groups]

ONE_WEEK = 60 * 60 * 24 * 7

class IAccessBackend(object):

    """ Base class for retrieving user and package permission data """

    mutable = False
    ROOT_ACL = [
        (Allow, Authenticated, "login"),
        (Allow, "admin", ALL_PERMISSIONS),
        (Deny, Everyone, ALL_PERMISSIONS),
    ]

    def __init__(
        self,
        request=None,
        default_read=None,
        default_write=None,
        disallow_fallback=(),
        cache_update=None,
        pwd_context=None,
        token_expiration=ONE_WEEK,
        signing_key=None,
    ):
        self.request = request
        self.default_read = default_read
        self.default_write = default_write
        self.disallow_fallback = disallow_fallback
        self.cache_update = cache_update
        self.pwd_context = pwd_context
        self.token_expiration = token_expiration
        self.signing_key = signing_key

    @classmethod
    def configure(cls, settings) -> Dict[str, Any]:
        """ Configure the access backend with app settings """
        rounds = settings.get("auth.rounds")
        scheme = settings.get("auth.scheme")
        return {
            "default_read": aslist(
                settings.get("pypi.default_read", ["authenticated"])
            ),
            "default_write": aslist(settings.get("pypi.default_write", [])),
            "disallow_fallback": aslist(settings.get("pypi.disallow_fallback", [])),
            "cache_update": aslist(
                settings.get("pypi.cache_update", ["authenticated"])
            ),
            "pwd_context": get_pwd_context(scheme, rounds),
            "token_expiration": int(settings.get("auth.token_expire", ONE_WEEK)),
            "signing_key": get_environ_setting(settings, "auth.signing_key"),
        }

    @classmethod
    def postfork(cls, **kwargs):
        """ This method will be called after uWSGI forks """

    def allowed_permissions(self, package: str) -> Dict[str, Tuple[str, ...]]:
        """
        Get all allowed permissions for all principals on a package

        Returns
        -------
        perms : dict
            Mapping of principal to tuple of permissions

        """
        all_perms = {}
        for user, perms in self.user_permissions(package).items():
            all_perms["user:" + user] = tuple(perms)

        for group, perms in self.group_permissions(package).items():
            all_perms[group_to_principal(group)] = tuple(perms)

        # If there are no group or user specifications for the package, use the
        # default
        if not all_perms:
            for principal in groups_to_principals(self.default_read):
                all_perms[principal] = ("read",)
            for principal in groups_to_principals(self.default_write):
                if principal in all_perms:
                    all_perms[principal] += ("write",)
                else:
                    all_perms[principal] = ("write",)

        # add fallback permissions
        if package not in self.disallow_fallback:
            for principal in all_perms:
                all_perms[principal] += ("fallback",)
        return all_perms

    def get_acl(self, package: str) -> List[Tuple[str, str, str]]:
        """ Construct an ACL for a package """
        acl = []
        permissions = self.allowed_permissions(package)
        for principal, perms in permissions.items():
            for perm in perms:
                acl.append((Allow, principal, perm))
        return acl

    def has_permission(self, package: str, perm: str) -> bool:
        """ Check if this user has a permission for a package """
        current_userid = self.request.userid
        if current_userid is not None and self.is_admin(current_userid):
            return True

        perms = self.allowed_permissions(package)
        for principal in effective_principals(self.request):
            if perm in perms.get(principal, []):
                return True
        return False

    def user_principals(self, username: str) -> List[str]:
        """
        Get a list of principals for a user

        Parameters
        ----------
        username : str

        Returns
        -------
        principals : list

        """
        principals = ["user:" + username, Everyone, Authenticated]
        if self.is_admin(username):
            principals.append("admin")
        for group in self.groups(username):
            principals.append("group:" + group)
        return principals

    def in_group(self, username: str, group: str) -> bool:
        """
        Find out if a user is in a group

        Parameters
        ----------
        username : str
            Name of user. May be None for the anonymous user.
        group : str
            Name of the group. Supports 'everyone', 'authenticated', and
            'admin'.

        Returns
        -------
        member : bool

        """
        if group in ("everyone", Everyone):
            return True
        elif username is None:
            return False
        elif group in ("authenticated", Authenticated):
            return True
        elif group == "admin" and self.is_admin(username):
            return True
        else:
            return group in self.groups(username)

    def in_any_group(self, username: str, groups: List[str]) -> bool:
        """
        Find out if a user is in any of a set of groups

        Parameters
        ----------
        username : str
            Name of user. May be None for the anonymous user.
        groups : list
            list of group names. Supports 'everyone', 'authenticated', and
            'admin'.

        Returns
        -------
        member : bool

        """
        return any((self.in_group(username, group) for group in groups))

    def can_update_cache(self) -> bool:
        """
        Return True if the user has permissions to update the pypi cache
        """
        return self.in_any_group(self.request.userid, self.cache_update)

    def need_admin(self) -> bool:
        """
        Find out if there are any admin users

        This should only be overridden by mutable backends

        Returns
        -------
        need_admin : bool
            True if no admin user exists and the backend is mutable, False
            otherwise

        """
        return False

    def allow_register(self) -> bool:
        """
        Check if the backend allows registration

        This should only be overridden by mutable backends

        Returns
        -------
        allow : bool

        """
        return False

    def allow_register_token(self) -> bool:
        """
        Check if the backend allows registration via tokens

        This should only be overridden by mutable backends

        Returns
        -------
        allow : bool

        """
        return False

    def verify_user(self, username: str, password: str) -> bool:
        """
        Check the login credentials of a user

        For Mutable backends, pending users should fail to verify

        Parameters
        ----------
        username : str
        password : str

        Returns
        -------
        valid : bool
            True if user credentials are valid, false otherwise

        """
        stored_pw = self._get_password_hash(username)
        if self.mutable:
            # if a user is pending, user_data will be None
            user_data = self.user_data(username)
            if user_data is None:
                return False
        return bool(stored_pw and self.pwd_context.verify(password, stored_pw))

    def _get_password_hash(self, username: str) -> str:
        """ Get the stored password hash for a user """
        raise NotImplementedError

    def groups(self, username: Optional[str] = None) -> List[str]:
        """
        Get a list of all groups

        If a username is specified, get all groups that the user belongs to

        Parameters
        ----------
        username : str, optional

        Returns
        -------
        groups : list
            List of group names

        """
        raise NotImplementedError

    def group_members(self, group: str) -> List[str]:
        """
        Get a list of users that belong to a group

        Parameters
        ----------
        group : str

        Returns
        -------
        users : list
            List of user names

        """
        raise NotImplementedError

    def is_admin(self, username: str) -> bool:
        """
        Check if the user is an admin

        Parameters
        ----------
        username : str

        Returns
        -------
        is_admin : bool

        """
        raise NotImplementedError

    def group_permissions(self, package: str) -> Dict[str, List[str]]:
        """
        Get a mapping of all groups to their permissions on a package

        Parameters
        ----------
        package : str
            The name of a python package

        Returns
        -------
        permissions : dict
            mapping of group name to a list of permissions
            (which can contain 'read' and/or 'write')

        """
        raise NotImplementedError

    def user_permissions(self, package: str) -> Dict[str, List[str]]:
        """
        Get a mapping of all users to their permissions for a package

        Parameters
        ----------
        package : str
            The name of a python package

        Returns
        -------
        permissions : dict
            Mapping of username to a list of permissions (which can contain
            'read' and/or 'write')

        """
        raise NotImplementedError

    def user_package_permissions(self, username: str) -> List[Dict[str, List[str]]]:
        """
        Get a list of all packages that a user has permissions on

        Parameters
        ----------
        username : str

        Returns
        -------
        packages : list
            List of dicts. Each dict contains 'package' (str) and 'permissions'
            (list)

        """
        raise NotImplementedError

    def group_package_permissions(self, group: str) -> List[Dict[str, List[str]]]:
        """
        Get a list of all packages that a group has permissions on

        Parameters
        ----------
        group : str

        Returns
        -------
        packages : list
            List of dicts. Each dict contains 'package' (str) and 'permissions'
            (list)

        """
        raise NotImplementedError

    def user_data(self, username=None):
        """
        Get a list of all users or data for a single user

        For Mutable backends, this MUST exclude all pending users

        Returns
        -------
        users : list
            Each user is a dict with a 'username' str, and 'admin' bool
        user : dict
            If a username is passed in, instead return one user with the fields
            above plus a 'groups' list.

        """
        raise NotImplementedError

    def check_health(self) -> Tuple[bool, str]:
        """
        Check the health of the access backend

        Returns
        -------
        (healthy, status) : (bool, str)
            Tuple that describes the health status and provides an optional
            status message

        """
        return True, ""

    def dump(self) -> Dict[str, Any]:
        """
        Dump all of the access control data to a universal format

        Returns
        -------
        data : dict

        """
        from pypicloud import __version__

        data = {}  # type: Dict[str, Any]
        data["allow_register"] = self.allow_register()
        data["version"] = __version__

        groups = self.groups()
        users = self.user_data()
        for user in users:
            user["password"] = self._get_password_hash(user["username"])

        data["groups"] = {}
        packages = {
            "users": defaultdict(dict),
            "groups": defaultdict(dict),
        }  # type: Dict[str, Any]
        for group in groups:
            data["groups"][group] = self.group_members(group)
            perms = self.group_package_permissions(group)
            for perm in perms:
                package = perm["package"]
                packages["groups"][package][group] = perm["permissions"]

        for user in users:
            username = user["username"]
            perms = self.user_package_permissions(username)
            for perm in perms:
                package = perm["package"]
                packages["users"][package][username] = perm["permissions"]

        # Convert the defaultdict to a dict for easy serialization
        packages["users"] = dict(packages["users"])
        packages["groups"] = dict(packages["groups"])
        data["users"] = users
        data["packages"] = packages
        return data

    def load(self, data):
        """
        Idempotently load universal access control data.

        By default, this does nothing on immutable backends. Backends may
        override this method to provide an implementation.

        This method works by default on mutable backends with no override
        necessary.

        """
        raise TypeError(
            "Access backend '%s' is not mutable and has no "
            "'load' implementation" % self.__class__.__name__
        )

class IMutableAccessBackend(IAccessBackend):

    """
    Base class for access backends that can change user/group permissions

    """

    mutable = True

    def need_admin(self) -> bool:
        for user in self.user_data():
            if user["admin"]:
                return False
        return True

    def get_signup_token(self, username: str) -> str:
        """
        Create a signup token

        Parameters
        ----------
        username : str
            The username to be created when this token is consumed

        Returns
        -------
        token : str

        """
        msg, signature = self._hmac(username, time.time())
        return msg + ":" + signature

    def _hmac(self, username: str, timestamp: float) -> Tuple[str, str]:
        """ HMAC a username/expiration combo """
        if self.signing_key is None:
            raise RuntimeError("auth.signing_key is not set!")
        msg = "%s:%d" % (username, timestamp)
        return (
            msg,
            hmac.new(
                self.signing_key.encode("utf8"), msg.encode("utf8"), hashlib.sha256
            ).hexdigest(),
        )

    def validate_signup_token(self, token: str) -> Optional[str]:
        """
        Validate a signup token

        Parameters
        ----------
        token : str

        Returns
        -------
        username : str or None
            This will be None if the validation fails

        """
        if self.signing_key is None:
            return None
        pieces = token.split(":")
        signature = pieces.pop()
        username = pieces[0]
        issued = int(pieces[1])
        if issued + self.token_expiration < time.time():
            return None
        _, expected = self._hmac(username, issued)
        if hasattr(hmac, "compare_digest"):
            if not hmac.compare_digest(
                signature.encode("utf-8"), expected.encode("utf-8")
            ):
                return None
        else:
            if signature != expected:
                return None
        return username

    def allow_register(self):
        raise NotImplementedError

    def allow_register_token(self):
        return self.signing_key is not None

    def set_allow_register(self, allow: bool) -> None:
        """
        Allow or disallow user registration

        Parameters
        ----------
        allow : bool

        """
        raise NotImplementedError

    def register(self, username: str, password: str) -> None:
        """
        Register a new user

        The new user should be marked as pending admin approval

        Parameters
        ----------
        username : str
        password : str
            This should be the plaintext password

        """
        self._register(username, self.pwd_context.hash(password))

    def _register(self, username: str, password: str) -> None:
        """
        Register a new user

        The new user should be marked as pending admin approval

        Parameters
        ----------
        username : str
        password : str
            This will be the hash of the password

        """
        raise NotImplementedError

    def pending_users(self) -> List[str]:
        """
        Retrieve a list of all users pending admin approval

        Returns
        -------
        users : list
            List of usernames

        """
        raise NotImplementedError

    def approve_user(self, username: str) -> None:
        """
        Mark a user as approved by the admin

        Parameters
        ----------
        username : str

        """
        raise NotImplementedError

    def edit_user_password(self, username: str, password: str) -> None:
        """
        Change a user's password

        Parameters
        ----------
        username : str
        password : str

        """
        self._set_password_hash(username, self.pwd_context.hash(password))

    def _set_password_hash(self, username: str, password_hash: str) -> None:
        """
        Change a user's password

        Parameters
        ----------
        username : str
        password_hash : str
            The hashed password to store

        """
        raise NotImplementedError

    def delete_user(self, username: str) -> None:
        """
        Delete a user

        Parameters
        ----------
        username : str

        """
        raise NotImplementedError

    def set_user_admin(self, username: str, admin: bool) -> None:
        """
        Grant or revoke admin permissions for a user

        Parameters
        ----------
        username : str
        admin : bool
            If True, grant permissions. If False, revoke.

        """
        raise NotImplementedError

    def edit_user_group(self, username: str, group: str, add: bool) -> None:
        """
        Add or remove a user to/from a group

        Parameters
        ----------
        username : str
        group : str
        add : bool
            If True, add to group. If False, remove.

        """
        raise NotImplementedError

    def create_group(self, group: str) -> None:
        """
        Create a new group

        Parameters
        ----------
        group : str

        """
        raise NotImplementedError

    def delete_group(self, group: str) -> None:
        """
        Delete a group

        Parameters
        ----------
        group : str

        """
        raise NotImplementedError

    def edit_user_permission(
        self, package: str, username: str, perm: Set[str], add: bool
    ) -> None:
        """
        Grant or revoke a permission for a user on a package

        Parameters
        ----------
        package : str
        username : str
        perm : {'read', 'write'}
        add : bool
            If True, grant permissions. If False, revoke.

        """
        raise NotImplementedError

    def edit_group_permission(
        self, package: str, group: str, perm: Set[str], add: bool
    ) -> None:
        """
        Grant or revoke a permission for a group on a package

        Parameters
        ----------
        package : str
        group : str
        perm : {'read', 'write'}
        add : bool
            If True, grant permissions. If False, revoke.

        """
        raise NotImplementedError

    def dump(self):
        data = super(IMutableAccessBackend, self).dump()
        pending_users = []
        for username in self.pending_users():  # pylint: disable=E1101
            password = self._get_password_hash(username)
            pending_users.append({"username": username, "password": password})
        data["pending_users"] = pending_users
        return data

    def load(self, data):
        pending_users = set(self.pending_users())

        def user_exists(username):
            """ Helper function that checks if a user already exists """
            return username in pending_users or self.user_data(username) is not None

        for user in data["users"]:
            if not user_exists(user["username"]):
                self._register(user["username"], user["password"])
                self.approve_user(user["username"])
            self.set_user_admin(user["username"], user.get("admin", False))

        for group, members in data["groups"].items():
            if not self.group_members(group):
                self.create_group(group)
            current_members = self.group_members(group)
            add_members = set(members) - set(current_members)
            for member in add_members:
                self.edit_user_group(member, group, True)

        for user in data.get("pending_users", []):
            if not user_exists(user["username"]):
                self._register(user["username"], user["password"])

        for package, groups in data["packages"]["groups"].items():
            for group, permissions in groups.items():
                for perm in permissions:
                    self.edit_group_permission(package, group, perm, True)

        for package, users in data["packages"]["users"].items():
            for user, permissions in users.items():
                for perm in permissions:
                    self.edit_user_permission(package, user, perm, True)

        self.set_allow_register(data["allow_register"])


text:
#ifndef ARM_COMPUTE_NEPIXELWISEMULTIPLICATION_H
#define ARM_COMPUTE_NEPIXELWISEMULTIPLICATION_H

#include "arm_compute/core/Types.h"
#include "arm_compute/runtime/IFunction.h"

#include <memory>

namespace arm_compute
{
class ITensor;
class ITensorInfo;

/** Basic function to run @ref cpu::CpuMul */
class NEPixelWiseMultiplication : public IFunction
{
public:
    /** Default Constructor */
    NEPixelWiseMultiplication();
    /** Default Destructor */
    ~NEPixelWiseMultiplication();
    /** Prevent instances of this class from being copied (As this class contains pointers) */
    NEPixelWiseMultiplication(const NEPixelWiseMultiplication &) = delete;
    /** Default move constructor */
    NEPixelWiseMultiplication(NEPixelWiseMultiplication &&) = default;
    /** Prevent instances of this class from being copied (As this class contains pointers) */
    NEPixelWiseMultiplication &operator=(const NEPixelWiseMultiplication &) = delete;
    /** Default move assignment operator */
    NEPixelWiseMultiplication &operator=(NEPixelWiseMultiplication &&) = default;
    /** Initialise the kernel's inputs, output and convertion policy.
     *
     * Valid data layouts:
     * - All
     *
     * Valid data type configurations:
     * |src0           |src1           |dst            |
     * |:--------------|:--------------|:--------------|
     * |QASYMM8        |QASYMM8        |QASYMM8        |
     * |QASYMM8_SIGNED |QASYMM8_SIGNED |QASYMM8_SIGNED |
     * |QSYMM16        |QSYMM16        |QASYMM16       |
     * |QSYMM16        |QSYMM16        |S32            |
     * |U8             |U8             |U8             |
     * |U8             |U8             |S16            |
     * |U8             |S16            |S16            |
     * |S16            |U8             |S16            |
     * |S16            |S16            |S16            |
     * |F16            |F16            |F16            |
     * |F32            |S32            |F32            |
     *
     * @note For @p scale equal to 1/255 only round to nearest even (implemented as round half up) is supported.
     *       For all other scale values only round to zero (implemented as round towards minus infinity) is supported.
     *
     * @param[in, out] input1          An input tensor. Data types supported: U8/QASYMM8/QASYMM8_SIGNED/S16/S32/QSYMM16/F16/F32
     *                                 This input tensor is [in, out] because its TensorInfo might be modified inside the kernel in case of broadcasting of dimension 0.
     * @param[in, out] input2          An input tensor. Data types supported: U8, QASYMM8 (only if @p input1 is QASYMM8), QASYMM8_SIGNED (only if @p input1 is QASYMM8_SIGNED), S16, S32, QSYMM16 (only if @p input1 is QSYMM16), F16 (only if @p input1 is F16), F32 (only if @p input1 is F32).
     *                                 This input tensor is [in, out] because its TensorInfo might be modified inside the kernel in case of broadcasting of dimension 0.
     * @param[out]     output          Output tensor. Data types supported:
     *                                 - U8, only if both inputs are U8.
     *                                 - QASYMM8, only if both inputs are QASYMM8.
     *                                 - QASYMM8_SIGNED, only if @p input1 is QASYMM8_SIGNED.
     *                                 - S16.
     *                                 - QSYMM16, only if both inputs are QSYMM16.
     *                                 - S32, only if both inputs are S32 or both are QSYMM16.
     *                                 - F16, only if @p input1 is F16.
     *                                 - F32, only if both inputs are F32.
     * @param[in]      scale           Scale to apply after multiplication.
     *                                 Scale must be positive and its value must be either 1/255 or 1/2^n where n is between 0 and 15.
     *                                 If both @p input1, @p input2 and @p output are of datatype S32, scale cannot be 1/255
     * @param[in]      overflow_policy Overflow policy. ConvertPolicy cannot be WRAP if any of the inputs is of quantized datatype
     * @param[in]      rounding_policy Rounding policy.
     * @param[in]      act_info        (Optional) Activation layer information in case of a fused activation. Currently not supported.
     */
    void configure(const ITensor *input1, const ITensor *input2, ITensor *output, float scale, ConvertPolicy overflow_policy, RoundingPolicy rounding_policy,
                   const ActivationLayerInfo &act_info = ActivationLayerInfo());
    /** Static function to check if given info will lead to a valid configuration of @ref NEPixelWiseMultiplication
     *
     * @note For @p scale equal to 1/255 only round to nearest even (implemented as round half up) is supported.
     *       For all other scale values only round to zero (implemented as round towards minus infinity) is supported.
     *
     * @param[in] input1          An input tensor info. Data types supported: U8/QASYMM8/QASYMM8_SIGNED/S16/S32/QSYMM16/F16/F32
     * @param[in] input2          An input tensor info. Data types supported: U8, QASYMM8 (only if @p input1 is QASYMM8), QASYMM8_SIGNED (only if @p input1 is QASYMM8_SIGNED), S16, S32, QSYMM16 (only if both inputs are QSYMM16), F16 (only if @p input1 is F16), F32 (only if @p input1 is F32).
     * @param[in] output          Output tensor info. Data types supported:
     *                            - U8, only if both inputs are U8.
     *                            - QASYMM8, only if both inputs are QASYMM8.
     *                            - QASYMM8_SIGNED, only if @p input1 is QASYMM8_SIGNED.
     *                            - S16.
     *                            - QSYMM16, only if both inputs are QSYMM16.
     *                            - S32, only if both inputs are S32 or both are QSYMM16.
     *                            - F16, only if @p input1 is F16.
     *                            - F32, only if both inputs are F32.
     * @param[in] scale           Scale to apply after multiplication.
     *                            Scale must be positive and its value must be either 1/255 or 1/2^n where n is between 0 and 15.
     *                            If both @p input1, @p input2 and @p output are of datatype S32, scale cannot be 1/255
     * @param[in] overflow_policy Overflow policy. ConvertPolicy cannot be WRAP if any of the inputs is of quantized datatype
     * @param[in] rounding_policy Rounding policy.
     * @param[in] act_info        (Optional) Activation layer information in case of a fused activation. Currently not supported.
     *
     * @return a status
     */
    static Status validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output, float scale, ConvertPolicy overflow_policy, RoundingPolicy rounding_policy,
                           const ActivationLayerInfo &act_info = ActivationLayerInfo());

    // Inherited methods overridden:
    void run() override;

private:
    struct Impl;
    std::unique_ptr<Impl> _impl;
};

/** Basic function to run @ref cpu::CpuComplexMul. */
class NEComplexPixelWiseMultiplication : public IFunction
{
public:
    /** Default Constructor */
    NEComplexPixelWiseMultiplication();
    /** Default Destructor */
    ~NEComplexPixelWiseMultiplication();
    /** Prevent instances of this class from being copied (As this class contains pointers) */
    NEComplexPixelWiseMultiplication(const NEComplexPixelWiseMultiplication &) = delete;
    /** Default move constructor */
    NEComplexPixelWiseMultiplication(NEComplexPixelWiseMultiplication &&) = default;
    /** Prevent instances of this class from being copied (As this class contains pointers) */
    NEComplexPixelWiseMultiplication &operator=(const NEComplexPixelWiseMultiplication &) = delete;
    /** Default move assignment operator */
    NEComplexPixelWiseMultiplication &operator=(NEComplexPixelWiseMultiplication &&) = default;
    /** Initialise the kernel's inputs, output.
     *
     * @param[in, out] input1   An input tensor. Data types supported: F32. Number of channels supported: 2 (complex tensor).
     *                          The input tensor is [in, out] because its TensorInfo might be modified inside the kernel in case of broadcasting of dimension 0.
     * @param[in, out] input2   An input tensor. Data types supported: same as @p input1. Number of channels supported: same as @p input1.
     *                          The input tensor is [in, out] because its TensorInfo might be modified inside the kernel in case of broadcasting of dimension 0.
     * @param[out]     output   The output tensor. Data types supported: same as @p input1. Number of channels: same as @p input1.
     * @param[in]      act_info (Optional) Activation layer information in case of a fused activation. Currently not supported.
     */
    void configure(ITensor *input1, ITensor *input2, ITensor *output, const ActivationLayerInfo &act_info = ActivationLayerInfo());
    /** Static function to check if given info will lead to a valid configuration of @ref NEComplexPixelWiseMultiplication
     *
     * @param[in] input1   An input tensor info. Data types supported: F32. Number of channels supported: 2 (complex tensor).
     * @param[in] input2   An input tensor info. Data types supported: same as @p input1. Number of channels supported: same as @p input1.
     * @param[in] output   The output tensor info. Data types supported: same as @p input1. Number of channels supported: same as @p input1.
     * @param[in] act_info (Optional) Activation layer information in case of a fused activation. Currently not supported.
     */
    static Status validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output, const ActivationLayerInfo &act_info = ActivationLayerInfo());

    // Inherited methods overridden:
    void run() override;

private:
    struct Impl;
    std::unique_ptr<Impl> _impl;
};
} // namespace arm_compute
#endif /*ARM_COMPUTE_NEPIXELWISEMULTIPLICATION_H */

redpajama_set_name: RedPajamaGithub


text:
class CreateListings < ActiveRecord::Migration
  def change
    create_table :listings, id: false do |t|
      t.integer :order, null: false, default: 0
      t.belongs_to :playlist, foreign_key: true
      t.belongs_to :song, foreign_key: true

      t.timestamps null: false
    end
    add_index :listings, [:playlist_id, :song_id], unique: true
  end
end


text:
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;

SET search_path = public, pg_catalog;

SET default_tablespace = '';

SET default_with_oids = false;

--
-- Name: metrics_04; Type: TABLE; Schema: public; Owner: root; Tablespace:
--

CREATE TABLE metrics_04 (
    id bigint,
    "timestamp" timestamp without time zone,
    capture_interval integer,
    resource_id bigint,
    resource_type character varying(255),
    cpu_usage_rate_average double precision,
    cpu_usagemhz_rate_average double precision,
    mem_usage_absolute_average double precision,
    disk_usage_rate_average double precision,
    net_usage_rate_average double precision,
    sys_uptime_absolute_latest double precision,
    created_on timestamp without time zone,
    derived_cpu_available double precision,
    derived_memory_available double precision,
    derived_memory_used double precision,
    derived_cpu_reserved double precision,
    derived_memory_reserved double precision,
    derived_vm_count_on integer,
    derived_host_count_on integer,
    derived_vm_count_off integer,
    derived_host_count_off integer,
    derived_storage_total double precision,
    derived_storage_free double precision,
    capture_interval_name character varying(255),
    assoc_ids text,
    cpu_ready_delta_summation double precision,
    cpu_system_delta_summation double precision,
    cpu_wait_delta_summation double precision,
    resource_name character varying(255),
    cpu_used_delta_summation double precision,
    tag_names text,
    parent_host_id bigint,
    parent_ems_cluster_id bigint,
    parent_storage_id bigint,
    parent_ems_id bigint,
    derived_storage_vm_count_registered double precision,
    derived_storage_vm_count_unregistered double precision,
    derived_storage_vm_count_unmanaged double precision,
    derived_storage_used_registered double precision,
    derived_storage_used_unregistered double precision,
    derived_storage_used_unmanaged double precision,
    derived_storage_snapshot_registered double precision,
    derived_storage_snapshot_unregistered double precision,
    derived_storage_snapshot_unmanaged double precision,
    derived_storage_mem_registered double precision,
    derived_storage_mem_unregistered double precision,
    derived_storage_mem_unmanaged double precision,
    derived_storage_disk_registered double precision,
    derived_storage_disk_unregistered double precision,
    derived_storage_disk_unmanaged double precision,
    derived_storage_vm_count_managed double precision,
    derived_storage_used_managed double precision,
    derived_storage_snapshot_managed double precision,
    derived_storage_mem_managed double precision,
    derived_storage_disk_managed double precision,
    min_max text,
    intervals_in_rollup integer,
    mem_vmmemctl_absolute_average double precision,
    mem_vmmemctltarget_absolute_average double precision,
    mem_swapin_absolute_average double precision,
    mem_swapout_absolute_average double precision,
    mem_swapped_absolute_average double precision,
    mem_swaptarget_absolute_average double precision,
    derived_vm_used_disk_storage double precision,
    derived_vm_allocated_disk_storage double precision,
    derived_vm_numvcpus double precision,
    disk_devicelatency_absolute_average double precision,
    disk_kernellatency_absolute_average double precision,
    disk_queuelatency_absolute_average double precision,
    time_profile_id bigint,
    CONSTRAINT metrics_04_inheritance_check CHECK ((((capture_interval_name)::text = 'realtime'::text) AND (date_part('hour'::text, "timestamp") = (4)::double precision)))
)
INHERITS (metrics);

ALTER TABLE metrics_04 OWNER TO root;

--
-- Name: metrics_04_id_seq; Type: SEQUENCE; Schema: public; Owner: root
--

CREATE SEQUENCE metrics_04_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

ALTER TABLE metrics_04_id_seq OWNER TO root;

--
-- Name: metrics_04_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: root
--

ALTER SEQUENCE metrics_04_id_seq OWNED BY metrics_04.id;

--
-- Name: id; Type: DEFAULT; Schema: public; Owner: root
--

ALTER TABLE ONLY metrics_04 ALTER COLUMN id SET DEFAULT nextval('metrics_04_id_seq'::regclass);

--
-- Name: metrics_04_pkey; Type: CONSTRAINT; Schema: public; Owner: root; Tablespace:
--

ALTER TABLE ONLY metrics_04
    ADD CONSTRAINT metrics_04_pkey PRIMARY KEY (id);

--
-- Name: index_metrics_04_on_resource_and_ts; Type: INDEX; Schema: public; Owner: root; Tablespace:
--

CREATE INDEX index_metrics_04_on_resource_and_ts ON metrics_04 USING btree (resource_id, resource_type, capture_interval_name, "timestamp");

--
-- Name: index_metrics_04_on_ts_and_capture_interval_name; Type: INDEX; Schema: public; Owner: root; Tablespace:
--

CREATE INDEX index_metrics_04_on_ts_and_capture_interval_name ON metrics_04 USING btree ("timestamp", capture_interval_name, resource_id, resource_type);

--
-- PostgreSQL database dump complete
--


text:
module Spree
  class Gateway
    class BraintreeVzeroBase
      class Utils
        attr_reader :order, :customer, :gateway

        def initialize(gateway, order)
          @order = order
          begin
            @customer = gateway.provider::Customer.find(order.user.id) if order.user
          rescue
          end
          @gateway = gateway
        end

        def get_address(address_type)
          if order.user && (address = order.user.send("#{address_type}_address"))
            braintree_address = BraintreeVzeroBase::Address.new(gateway.provider, order)
            vaulted_duplicate = Spree::Address.vaulted_duplicates(address).first

            if vaulted_duplicate && braintree_address.find(vaulted_duplicate.braintree_id)
              { "#{address_type}_address_id" => vaulted_duplicate.braintree_id }
            else
              { address_type => address_data(address_type, order.user) }
            end
          else
            { address_type => address_data(address_type, order) }
          end
        end

        def get_customer
          if @customer
            { customer_id: @customer.id }
          else
            { customer: (payment_in_vault[:store_shipping_address_in_vault] && order.user) ? customer_data(order.user) : {} }
          end
        end

        def order_data(identifier, amount)
          identifier.merge(
            amount: amount,
            order_id: order.number,
            line_items: collect_line_items,
            shipping_amount: order_shipping
          )
        end

        def address_data(address_type, target)
          address = target.send("#{address_type}_address")
          country = address.country

          {
            company: address.company,
            country_code_alpha2: country.iso,
            country_code_alpha3: country.iso3,
            country_code_numeric: country.numcode,
            country_name: country.name,
            first_name: address.first_name,
            last_name: address.last_name,
            locality: address.city,
            postal_code: address.zipcode,
            region: address.state.try(:abbr),
            street_address: address.address1,
            extended_address: address.address2
          }
        end

        def customer_data(user)
          address_data('billing', user).slice(:first_name, :last_name, :company, :phone).merge!(id: user.id, email: user.email)
        end

        def customer_payment_methods(payment_method_type)
          payment_methods = @customer.try(:payment_methods) || []

          if payment_method_type.eql?('custom')
            payment_methods.select { |pm| pm.is_a?(Braintree::CreditCard) }
          elsif payment_method_type.eql?('paypal')
            payment_methods.select { |pm| pm.is_a?(Braintree::PayPalAccount) }
          else
            payment_methods
          end
        end

        def payment_in_vault(data = {})
          store_ship_address = data['shipping_address_id'].blank?

          case gateway.preferred_store_payments_in_vault.to_s
          when 'store_only_on_success'
            { store_in_vault_on_success: true, store_shipping_address_in_vault: store_ship_address }
          when 'store_all'
            { store_in_vault: true, store_shipping_address_in_vault: store_ship_address }
          else
            { store_in_vault: false }
          end
        end

        def map_payment_status(braintree_status)
          case braintree_status
          when 'authorized', 'settlement_pending'
            'pending'
          when 'voided'
            'void'
          when 'settled', 'submitted_for_settlement', 'settling'
            'completed'
          else
            'failed'
          end
        end

        private

        PAYPAL_MAX_LINEITEMS = 249

        # Because of strange PayPal behaviour with accepting discounts
        # the only solution to add needed discount (if it exist) to
        # create a virtual Line Item with discount amount and with 'credit'
        # and name it as 'discount' to be reflected in PayPal email to customer
        #
        def collect_line_items # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
          items =
            @order
            .line_items
            .reject { |li| li.price.zero? || li.quantity.zero? }
            .map do |li|
            {
              name: li.name.truncate(127, omission: ''),
              kind: 'debit',
              quantity: li.quantity.to_s,
              unit_amount: li.price.to_s,
              unit_of_measure: 'unit',
              product_code: li.sku,
              total_amount: (li.price * li.quantity).to_s,
              tax_amount: li.additional_tax_total.to_s
            }
          end.
            take(PAYPAL_MAX_LINEITEMS - 1)
          total = @order.adjustment_total.abs
          return items if total.zero?

          items.append({
                         name: 'discount',
                         kind: 'credit',
                         quantity: '1',
                         unit_amount: total.to_s,
                         total_amount: total.to_s
                       })
        end

        def order_shipping
          @order.shipment_total.to_s
        end
      end
    end
  end
end


text:
let request = require("superagent");
let utils = require("ethereumjs-util");

module.exports = {

    //TODO support other networks
    checkIfContractIsVerified : (contractAddress, cb) =>
    {
        let etherScanApi = "http://api.etherscan.io/api?module=contract&action=getabi&address=";
        request.get(etherScanApi + contractAddress, (error, data) =>
        {
            if(error)
            {
                cb(error, null);
            }
            else
            {
                cb(null, data);
            }
        });
    },

    extractAbiFunctions : (abi) =>
    {
        let arrayOfFunctionObjects = [];
        for(let i = 0; i < abi.length; i++)
        {
            if(abi[i].type == "function")
            {
                // console.log("here is each function from abi: " + JSON.stringify(abi[i]));
                arrayOfFunctionObjects.push(abi[i]);
            }
        }
        return arrayOfFunctionObjects;
    },

    getContractFunctionNamesAndParams : (abiFunctions) =>
    {
        let nameAndParamObj = {};
        let functionNameFields = [];
        let functionParamFields = [];
        let readOnlyParamInputs = [];
        //for each function
        for(let abiFunc of abiFunctions)
        {
            let functionName = abiFunc.name;
            let functionParams = [];
            //for each specific function parameters
            for(let input of abiFunc.inputs)
            {
                functionParams.push(input);
            }
            //create jade elements for each function with name and param
            functionNameFields.push(functionName);
            functionParamFields.push(functionParams);

            //if there are no params then set the input to readonly
            if(functionParams.length == 0)
            {
                readOnlyParamInputs.push(true);
            }
            else
            {
                readOnlyParamInputs.push(false);
                //add ability to attach ether to transaction
                if(JSON.stringify(abiFunc).includes('"payable":true'))
                {
                    functionParams.push({
                        "name":"Optional_Ether_Amount",
                        "type":"uint256"
                    });
                }
            }
        }
        nameAndParamObj.names = functionNameFields;
        nameAndParamObj.params = functionParamFields;
        nameAndParamObj.readOnly = readOnlyParamInputs;

        return nameAndParamObj;
    },

    executeContractFunction : (contract, txObj, cb) =>
    {
        let etherValue = 0;
        if(txObj.isPayable)
        {
            //last element is ether value
            etherValue = parseInt(txObj.filledOutParams[txObj.filledOutParams.length - 1]);
            txObj.filledOutParams.pop();
        }
        contract[txObj.functionCalled](...txObj.filledOutParams, { value: etherValue }, (err, data) =>
        {
            if(err) throw err;
            cb(data)
        });
    },

    checkAddressValidity : (web3, address) =>
    {
        return web3.isAddress(address);
    },

    signMessage : (web3, account, message, cb) =>
    {
        try
        {
            web3.eth.sign(account, message, (err, data) => {
                cb(err, data);
            });
        }
        catch(e)
        {
            console.log("signing error: " + e);
        }
    },

    verify: (web3, message, signature, cb) =>
    {
        try
        {
            message = web3.sha3(message);
            const {v, r, s} = utils.fromRpcSig(signature);
            let m = utils.toBuffer(message);
            let pub = utils.ecrecover(m, v, r, s);
            let adr = '0x' + utils.pubToAddress(pub).toString('hex');
            cb(adr);
        }
        catch(e)
        {
            console.log("verify error: " + e);
        }
    },

    redirectToEtherscan : (web3, address) =>
    {
        web3.version.getNetwork((err, networkId) => {
            if (networkId == 3) window.location.href = "https://ropsten.etherscan.io/address/" + address;
            else if (networkId == 4) window.location.href = "https://rinkeby.etherscan.io/address/" + address;
            else if (networkId == 42) window.location.href = "https://kovan.etherscan.io/address/" + address;
            else window.location.href = "https://etherscan.io/address/" + address;
        });
    },

    getNetworkName : (web3, cb) =>
    {
        web3.version.getNetwork((err, networkId) =>
        {
            if(networkId == 3) cb("Ropsten");
            else if (networkId == 4) cb("Rinkeby");
            else if (networkId == 42) cb("Kovan");
            else cb("Mainnet");
        });
    },

    getName : (contract, cb) =>
    {
        try
        {
            contract.name.call((err, name) =>
            {
                if(err) cb(err, null);
                else cb(null, name);
            })
        }
        catch(e)
        {
            cb(e, null);
            console.log("no name defined: " + e);
        }

    },

    parseABIToJSON: (abi) =>
    {
        try
        {
            if(typeof abi == 'object')
            {
                return abi;
            }
            else
            {
                return JSON.parse(abi);
            }
        }
        catch(exception)
        {
            console.log("JSON parsing issue: " + exception);
            return {};
        }
    },

    parseABIToString: (abi) =>
    {
        try
        {
            if(typeof abi == 'string')
            {
                return abi;
            }
            else
            {
                return JSON.stringify(abi);
            }
        }
        catch(exception)
        {
            console.log("JSON parsing issue: " + exception);
            return "";
        }
    }

};


text:
(function(){

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

            window.dadosTeste = JSON.parse(this.responseText);

            //Operações de testes no banco;

            // testeInsert();
            // testeRetrieve();
            testeRemove();

        }
    };
    xhttp.open("GET", "./dados.json");
    xhttp.send();

})();

function insert(){

    let tempoInicial = performance.now();;

    let db = new PouchDB('db');

    db.put({
        _id: 'dados',
        nome: dadosTeste
    }).then(function (response) {
        let tempoFinal = performance.now();;
        console.log((tempoFinal - tempoInicial));
    }).catch(function (err) {
        console.log("erro");
    });

}

function retrieve(){
    let tempoInicial = performance.now();;
    let db = new PouchDB('db');

    db.get('dados').then(function(doc) {
        let tempoFinal = performance.now();;
        console.log((tempoFinal - tempoInicial));
    });
}

function remove(){

    let tempoInicial = performance.now();;
    let db = new PouchDB('db');

    db.get('dados').then(function(doc) {
        return db.remove(doc);
    }).then(function (result) {
        let tempoFinal = performance.now();;
        console.log((tempoFinal - tempoInicial));
    }).catch(function (err) {
        console.log(err);
    });
}

// -----------------------------------------------------------

function testeInsert(){

    let db = new PouchDB('db');

    db.get('dados').then(function(doc) {
        return db.remove(doc);
    }).then(function (result) {
        insert();
    }).catch(function (err) {
        console.log(err);
    });

}

function testeRetrieve(){
    retrieve();
}

function testeRemove(){

    let db = new PouchDB('db');

    db.put({
        _id: 'dados',
        nome: dadosTeste
    }).then(function (response) {
        remove();
    }).catch(function (err) {
        console.log(err);
    });
}


text:
/**
 * LoginException.java
 *
 * Project: projecth
 *
 * @author mobileman
 * @date 14.1.2011
 * @version 1.0
 *
 * (c) 2010 MobileMan GmbH
 */

package com.mobileman.projecth.business.exception;

/**
 * Represents errors in user's registration logic
 *
 * @author mobileman
 *
 */
public class UserRegistrationException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Reason of an exception
	 *
	 * @author mobileman
	 *
	 */
	public enum Reason {

		/**
		 * Given email already exists
		 */
		EMAIL_ALREADY_EXISTS;
	}

	private final Reason reason;

	/**
	 * @param reason
	 */
	public UserRegistrationException(Reason reason) {
		super();
		this.reason = reason;
	}

	/**
	 * @return reason
	 */
	public Reason getReason() {
		return this.reason;
	}
}


text:
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'app-header',
  styles: [
    require('./app-header.scss')
  ],
  template: `

FireDAX

Sign out

  `
})

export class AppHeader {
  @Input() authenticated: boolean;
  @Output() signOut: EventEmitter<any> = new EventEmitter(false);
}


text:
var fs = require('fs')
var path = require('path')
var mkdirp = require('mkdirp')
var broccoli = require('broccoli')
var Transform = require('broccoli-transform')

module.exports = Concat

Concat.prototype = Object.create(Transform.prototype)
Concat.prototype.constructor = Concat
function Concat(inputTree, options) {
  if (!(this instanceof Concat)) return new Concat(inputTree, options)
  this.inputTree = inputTree
  for (var key in options) {
    if (options.hasOwnProperty(key)) {
      this[key] = options[key]
    }
  }

  this.cache = {}
}

Concat.prototype.DEFAULT_SEPARATOR = '\n'

Concat.prototype.transform = function (srcDir, destDir) {
  var self = this
  var modulesAdded = {}
  var output = []

  // When we are done compiling, we replace this.cache with newCache, so that
  // unused cache entries are garbage-collected
  var newCache = {}

  var inputFiles = broccoli.helpers.multiGlob(this.inputFiles, {cwd: srcDir})
  for (i = 0; i < inputFiles.length; i++) {
    addFile(inputFiles[i])
  }

  broccoli.helpers.assertAbsolutePaths([this.outputFile])
  mkdirp.sync(path.join(destDir, path.dirname(this.outputFile)))
  fs.writeFileSync(path.join(destDir, this.outputFile), output.join(self.separator || self.DEFAULT_SEPARATOR))

  self.cache = newCache

  function addFile (filePath) {
    // This function is just slow enough that we benefit from caching
    var statsHash = broccoli.helpers.hashStats(fs.statSync(srcDir + '/' + filePath), filePath)
    var cacheObject = self.cache[statsHash]
    if (cacheObject == null) { // cache miss
      var fileContents = fs.readFileSync(srcDir + '/' + filePath, { encoding: 'utf8' })
      cacheObject = {
        output: fileContents
      }
    }
    newCache[statsHash] = cacheObject
    output.push(cacheObject.output)
  }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.

namespace mshtml
{
    using System;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;

    [ComImport, Guid("3050F33B-98B5-11CF-BB82-00AA00BDCE0B"), TypeLibType((short)0x1040)]
    public interface IHTMLCurrentStyle4
    {
        [DispId(-2147412899)]
        string msInterpolationMode { [return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc((short)20), DispId(-2147412899)] get; }
        [DispId(-2147412898)]
        object maxHeight { [return: MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc((short)20), DispId(-2147412898)] get; }
        [DispId(-2147412897)]
        object minWidth { [return: MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc((short)20), DispId(-2147412897)] get; }
        [DispId(-2147412896)]
        object maxWidth { [return: MarshalAs(UnmanagedType.Struct)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), TypeLibFunc((short)20), DispId(-2147412896)] get; }
    }
}


text:
//
//  Me_WeiBoTableViewController.m
//  微博项目
//
//  Created by tarena26 on 16/5/16.
//  Copyright © 2016年 tarena. All rights reserved.
//

#import "Me_WeiBoTableViewController.h"

@interface Me_WeiBoTableViewController ()

//每个新设置的静态表要进行关联
@property (strong, nonatomic) IBOutlet UITableViewCell *meCell;

@property (strong, nonatomic) IBOutlet UITableViewCell *commentCell;

@property (strong, nonatomic) IBOutlet UITableViewCell *praiseCell;

@property (strong, nonatomic) IBOutlet UITableViewCell *moreTitleCell;

@property (strong, nonatomic) IBOutlet UITableViewCell *smallMessageCell;

@end

@implementation Me_WeiBoTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

//假如分三组
    //第二组是动态的话 开始以五个来算
    //先尝试小界面实现
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//几个分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 3;
}

//每个分区多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 3;

        case 1:
            return 5;
        default:
            return 1;

    }

}

//每行长什么样

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    switch (indexPath.section) {
        case 0:
            if (indexPath.row == 0) {
                return self.meCell;
            }
            else if (indexPath.row == 1){
                return self.commentCell;
            }
            else if (indexPath.row == 2){
                return self.praiseCell;
            }

        case 1:
           // UITableViewCell *cell = self.moreTitleCell;//好像多态的不能采用自定义的那种 也就是说动态的cell是一个套路 不能采用自定义的方式复用

           // return [[UITableViewCell alloc] init];

        {

            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

            if (!cell) {

                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];

            }

            cell.textLabel.text = [NSString stringWithFormat:@"想看看能不能显示%ld",indexPath.row];

            cell.detailTextLabel.text = [NSString stringWithFormat:@"实际行数是%ld",indexPath.row];
            cell.imageView.image = [UIImage imageNamed:@"common_icon_membership_level1"];

            //这几行主要是做时间戳

            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(cell.bounds.size.width - 50, (cell.bounds.size.height - 20)/2, 50, 20)];
            label.text = [NSString stringWithFormat:@"%ld 11:11",indexPath.row];

            [cell.contentView addSubview:label];

            return cell;

        }

        default:
            return self.smallMessageCell;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 60;
}

//后面是考虑点中了某行会发生什么

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];

    // Pass the selected object to the new view controller.

    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.github.nukc.stateview">

    <application />

</manifest>


text:
<?php

/** */
namespace CoreTest\Queue\Exception;

use PHPUnit\Framework\TestCase;

use Core\Queue\Exception\AbstractJobException;
use Core\Queue\Exception\RecoverableJobException;
use CoreTestUtils\TestCase\TestInheritanceTrait;

/**
 * Tests for \Core\Queue\Exception\RecoverableJobException
 *
 * @covers \Core\Queue\Exception\RecoverableJobException
 * @author Mathias Gelhausen <gelhausen@cross-solution.de>
 *
 */
class RecoverableJobExceptionTest extends TestCase
{
    use TestInheritanceTrait;

    private $target = RecoverableJobException::class;

    private $inheritance = [ AbstractJobException::class ];
}


text:
package edu.ucsc.twitter;

import edu.ucsc.cli.util.Strings;
import java.util.NoSuchElementException;

/**
* A Person's gender.
*
* @author hsanchez@cs.ucsc.edu (Huascar A. Sanchez)
*/
public enum Gender {
  MALE,
  FEMALE;

  public static boolean isFemale(Gender other){
    return FEMALE.isSame(other);
  }

  public static boolean isMale(Gender other){
    return !isFemale(other);
  }

  public boolean isSame(Gender other){
    return this == other;
  }

  public static Gender from(String name){
    for(Gender each : values()){
      if(Strings.same(name, each.toString().toLowerCase())){
        return each;
      }
    }

    throw new NoSuchElementException();
  }
}


text:
import { takeLatest, call, put, select, take, cancel } from 'redux-saga/effects';
import { LOCATION_CHANGE } from 'react-router-redux';

import request from 'utils/request';
import { appUrl } from 'utils/constants';
import { makeSelectToken, makeSelectUserId } from 'containers/App/selectors';
import { unselectBook } from 'containers/App/actions';
import { WISHLIST_BOOKS_REQUEST, REMOVE_REQUEST_REQUEST } from './constants';
import { wishlistBooksSuccess, wishlistBooksError, removeRequestSuccess, removeRequestError } from './actions';

export function* wishlistBooksSaga(action) {
  const token = yield select(makeSelectToken());
  const userId = yield select(makeSelectUserId());
  const activePage = action.payload.activePage ? action.payload.activePage : 0;
  const requestUrl = `${appUrl}/api/wishlist?token=${token}&&userId=${userId}&&activePage=${activePage}`;
  try {
    const response = yield call(request, requestUrl);
    if (response.success) {
      yield put(wishlistBooksSuccess({ books: response.books, numPages: response.numPages }));
    } else {
      yield put(wishlistBooksError({ error: response.error }));
    }
  } catch (error) {
    yield put(wishlistBooksError({ error: error.response }));
  }
}

export function* wishlistBooksWatcher() {
  const watcher = yield takeLatest(WISHLIST_BOOKS_REQUEST, wishlistBooksSaga);

  yield take(LOCATION_CHANGE);
  yield cancel(watcher);
}

export function* removeRequestSaga(action) {
  const token = yield select(makeSelectToken());
  const userId = yield select(makeSelectUserId());
  try {
    const removedRequest = yield call(request, `${appUrl}/api/removeRequest`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ token, userId, bookId: action.payload.bookId }),
    });
    if (removedRequest.success) {
      yield put(unselectBook());  // Closes the modal
      yield put(removeRequestSuccess({ bookId: action.payload.bookId }));
    } else {
      yield put(removeRequestError({ error: removedRequest.error }));
    }
  } catch (error) {
    yield put(removeRequestError({ error: error.response }));
  }
}

export function* removeRequestWatcher() {
  const watcher = yield takeLatest(REMOVE_REQUEST_REQUEST, removeRequestSaga);

  yield take(LOCATION_CHANGE);
  yield cancel(watcher);
}

// All sagas to be loaded
export default [
  wishlistBooksWatcher,
  removeRequestWatcher,
];


text:
package org.commonjava.indy.core.change;

import org.commonjava.indy.audit.ChangeSummary;
import org.commonjava.indy.change.event.ArtifactStoreDeletePostEvent;
import org.commonjava.indy.change.event.ArtifactStoreDeletePreEvent;
import org.commonjava.indy.data.IndyDataException;
import org.commonjava.indy.data.StoreDataManager;
import org.commonjava.indy.model.core.ArtifactStore;
import org.commonjava.indy.model.core.Group;
import org.commonjava.indy.model.core.StoreKey;
import org.commonjava.maven.galley.event.EventMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.event.Observes;
import javax.inject.Inject;
import java.util.Set;

@javax.enterprise.context.ApplicationScoped
public class GroupConsistencyListener
{

    public static final String GROUP_CONSISTENCY_ORIGIN = "group-consistency";

    private final Logger logger = LoggerFactory.getLogger( getClass() );

    @Inject
    private StoreDataManager storeDataManager;

    private void processChanged( final ArtifactStore store )
    {
        final StoreKey key = store.getKey();
        try
        {
            final Set<Group> groups = storeDataManager.query().getGroupsContaining( key );
            logger.trace( "For repo: {}, containing groups are: {}", key, groups );
            for ( final Group group : groups )
            {
                logger.debug( "Removing {} from membership of group: {}", key, group.getKey() );

                Group g = group.copyOf();
                g.removeConstituent( key );
                storeDataManager.storeArtifactStore( g, new ChangeSummary( ChangeSummary.SYSTEM_USER,
                                                                           "Auto-update groups containing: " + key
                                                                                + " (to maintain consistency)" ),
                                                     false, false,
                                                     new EventMetadata().set( StoreDataManager.EVENT_ORIGIN,
                                                                              GROUP_CONSISTENCY_ORIGIN ) );
            }
        }
        catch ( final IndyDataException e )
        {
            logger.error( String.format( "Failed to remove group constituent listings for: %s. Error: %s", key,
                                         e.getMessage() ), e );
        }
    }

    public void storeDeleted( @Observes final ArtifactStoreDeletePostEvent event )
    {
        logger.trace( "Processing proxy-manager store deletion: {}", event.getStores() );
        for ( final ArtifactStore store : event )
        {
            logger.trace( "Processing deletion of: {}", store.getKey() );
            processChanged( store );
        }
    }

}


text:
namespace DetailPrinter
{
    public class StartUp
    {
        public static void Main()
        {
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:state_enabled="false"
    android:drawable="@drawable/custom_button_selected" />
<item
    android:state_pressed="true"
    android:state_enabled="true"
    android:drawable="@drawable/custom_button_selected" />
<item
    android:state_focused="true"
    android:state_enabled="true"
    android:drawable="@drawable/custom_button_selected" />
<item
    android:state_enabled="true"
    android:drawable="@drawable/custom_button_normal" />
</selector>


text:
ngNews is simple [Electron](http://electron.atom.io/)/[Angular2](https://angular.io/)  (also using [TypeScript](http://www.typescriptlang.org/)) desktop-application for demonstrating how to fetch JSON-data from server using http.get (in this example we are using news-site called [High.fi](http://high.fi/) to get our news-data) and showing it in very minimalistic view. Clicking links will open them in system default browser.

![ngNews mainview](https://github.com/MikPak/ngNews/blob/master/mainview.png "ngNews mainview")

## Install

Clone this repo and execute in your favourite shell:

* `npm install` to install dependencies
* `npm run build` to build
* `npm run watch` to build and watch for changes
* `npm run electron` to run the app

You may execute `npm run watch` in one shell window and `npm run electron` in another in order to watch for changes in code and easily re-run the app.

## Author
[Mikko Pakkanen](http://mikkopakkanen.com)


text:
begin; require 'rubygems'; rescue LoadError; end

require "appscript"
include Appscript

def make_message(addresses, subject, content, show_window=false)
	# Make an outgoing message in Mail.
	# 	addresses : list of unicode -- a list of email addresses
	# 	subject : unicode -- the message subject
	# 	content : unicode -- the message content
	# 	show_window : Boolean -- show message window in Mail
	# Result : reference -- reference to the new outgoing message
	mail = app('Mail')
	msg = mail.make(
			:new => :outgoing_message,
			:with_properties => {:visible => show_window})
	addresses.each do |an_address|
		msg.to_recipients.end.make(
				:new => :recipient,
				:with_properties => {:address => an_address})
	end
	msg.subject.set(subject)
	msg.content.set(content)
	return msg
end

# test
p make_message(['joe@foo.com', 'jane@bar.net'], 'Hello World', 'Some body text.', true)


text:
package org.wickedsource.logviewer.parser;

import java.text.ParseException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.wickedsource.logviewer.parser.descriptor.CustomFieldDescriptor;
import org.wickedsource.logviewer.parser.descriptor.LineDescriptor;
import org.wickedsource.logviewer.parser.event.LineNotParsedEvent;
import org.wickedsource.logviewer.parser.event.LineNotParsedEvent.Reason;
import org.wickedsource.logviewer.parser.event.LineSuccessfullyParsedEvent;
import org.wickedsource.logviewer.parser.listener.ParseEventListener;
import org.wickedsource.logviewer.parser.model.LogEntry;

/**
 * This strategy parses a "normal" line of a log file, i.e. a line that fits the
 * pattern as described by a {@link LineDescriptor}, without caring about the
 * context of the log line.
 *
 * @author Tom
 */
public class SimpleParseStrategy implements ParseStrategy {

	private final LineDescriptor descriptor;

	private Pattern pattern;

	public SimpleParseStrategy(LineDescriptor descriptor) {
		this.descriptor = descriptor;
		pattern = Pattern.compile(descriptor.getLineRegex());
	}

	public void parseLine(ParseWindow window, ParseEventListener listener) {
		LogEntry logEntry = parseLineSynchronous(window, listener);
		if (logEntry != null) {
			listener.handleEvent(new LineSuccessfullyParsedEvent(window.getFocusLineNumber(), logEntry));
		}
	}

	public LineDescriptor getDescriptor() {
		return descriptor;
	}

	protected LogEntry parseLineSynchronous(ParseWindow window, ParseEventListener listener) {
		Matcher matcher = pattern.matcher(window.getFocusLine());

		int lineNumber = window.getFocusLineNumber();

		if (!matcher.matches()) {
			listener.handleEvent(new LineNotParsedEvent(lineNumber, Reason.LINE_REGEX_DOES_NOT_MATCH));
			return null;
		}

		LogEntry entry = new LogEntry();
		entry.setLineNumber(lineNumber);

		Date timestamp = parseTimestampField(matcher, descriptor);
		if (timestamp == null) {
			listener.handleEvent(new LineNotParsedEvent(lineNumber, Reason.DATE_PATTERN_DOES_NOT_MATCH));
			return null;
		} else {
			entry.setTimestamp(timestamp);
		}

		String severity = parseSeverityField(matcher, descriptor);
		if (severity == null) {
			listener.handleEvent(new LineNotParsedEvent(lineNumber, Reason.SEVERITY_FIELD_MISSING));
			return null;
		} else {
			entry.setSeverity(severity);
		}

		String logger = parseLoggerField(matcher, descriptor);
		if (logger == null) {
			listener.handleEvent(new LineNotParsedEvent(lineNumber, Reason.LOGGER_FIELD_MISSING));
			return null;
		} else {
			entry.setLogger(logger);
		}

		String message = parseMessageField(matcher, descriptor);
		if (message == null) {
			listener.handleEvent(new LineNotParsedEvent(lineNumber, Reason.MESSAGE_FIELD_MISSING));
			return null;
		} else {
			entry.setMessage(message);
		}

		for (CustomFieldDescriptor fieldDescriptor : descriptor.getCustomFieldDescriptors()) {
			String field = parseCustomField(matcher, fieldDescriptor);
			if (field == null) {
				listener.handleEvent(new LineNotParsedEvent(lineNumber, Reason.CUSTOM_FIELD_MISSING));
				return null;
			} else {
				entry.setCustomField(fieldDescriptor.getKey(), field);
			}
		}

		return entry;
	}

	private String parseLoggerField(Matcher matcher, LineDescriptor descriptor2) {
		String logger = matcher.group(descriptor.getLoggerGroup());
		return logger;
	}

	private Date parseTimestampField(Matcher matcher, LineDescriptor descriptor) {
		try {
			String dateString = matcher.group(descriptor.getDateGroup());
			Date date = descriptor.getDateFormat().parse(dateString);
			return date;
		} catch (ParseException e) {
			return null;
		}
	}

	private String parseSeverityField(Matcher matcher, LineDescriptor descriptor) {
		String severity = matcher.group(descriptor.getSeverityGroup());
		return severity;
	}

	private String parseMessageField(Matcher matcher, LineDescriptor descriptor) {
		String message = matcher.group(descriptor.getMessageGroup());
		return message;
	}

	private String parseCustomField(Matcher matcher, CustomFieldDescriptor fieldDescriptor) {
		String field = matcher.group(fieldDescriptor.getFieldGroup());
		return field;
	}

	@Override
	public boolean hasSolutionFor(ParseWindow window) {
		return matches(window.getFocusLine());
	}

	protected boolean matches(String line) {
		Matcher matcher = pattern.matcher(line);
		return matcher.matches();
	}

}


text:
<?php

namespace Core\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Duvidas
 *
 * @ORM\Table(name="duvidas", indexes={@ORM\Index(name="fk_duvidas_servicos1_idx", columns={"fk_id_servico"})})
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="Core\Repository\DuvidasRepository")
 *
 */
class Duvidas
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id_duvida", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idDuvida;

    /**
     * @var string
     *
     * @ORM\Column(name="pergunta", type="string", length=400, nullable=true)
     */
    private $pergunta;

    /**
     * @var string
     *
     * @ORM\Column(name="resposta", type="text", nullable=true)
     */
    private $resposta;

    /**
     * @var string
     *
     * @ORM\Column(name="status", type="string",  length=10, nullable=true)
     */
    private $status;

    /**
     * @var \Core\Entity\Servicos
     *
     * @ORM\ManyToOne(targetEntity="Core\Entity\Servicos")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="fk_id_servico", referencedColumnName="id_servico")
     * })
     */
    private $fkServico;

    /**
     * Get idDuvida
     *
     * @return integer
     */
    public function getIdDuvida()
    {
        return $this->idDuvida;
    }

    /**
     * Set fkServico
     *
     * @param \Core\Entity\Servicos $fkServico
     * @return Duvidas
     */
    public function setFkServico(\Core\Entity\Servicos $fkServico = null)
    {
        $this->fkServico = $fkServico;

        return $this;
    }

    /**
     * Get fkServico
     *
     * @return \Core\Entity\Servicos
     */
    public function getFkServico()
    {
        return $this->fkServico;
    }

    /**
     * Set pergunta
     *
     * @param string $pergunta
     * @return Duvidas
     */
    public function setPergunta($pergunta)
    {
        $this->pergunta = $pergunta;

        return $this;
    }

    /**
     * Get pergunta
     *
     * @return string
     */
    public function getPergunta()
    {
        return $this->pergunta;
    }

    /**
     * Set resposta
     *
     * @param string $resposta
     * @return Duvidas
     */
    public function setResposta($resposta)
    {
        $this->resposta = $resposta;

        return $this;
    }

    /**
     * Get resposta
     *
     * @return string
     */
    public function getResposta()
    {
        return $this->resposta;
    }

    /**
     * Set status
     *
     * @param string $status
     * @return Duvidas
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return string
     */
    public function getStatus()
    {
        return $this->status;
    }
}


text:
<?php $this->load->view('/templates/header')?>

				Name
				Quantity
				Price
				Description
				Action

<?php
		$total = 0;
		foreach($order as $item){
			// var_dump($item);
		$total += $item['price'];
?>

				<?=$item['title']?>
				<?=$item['quantity']?>
				<?=$item['price']?>
				<?=$item['description']?>
				<a href="/orders/delete/<?=$item['order_id']?>"><button class = "btn btn-danger">REMOVE</button>

<?php }?>

Total:  <?=$total?>

<?php
	if(!empty($this->session->flashdata('errors'))){
?>

		  <?= $this->session->flashdata('errors') ?>

<?php
	}
?>

		<form action = '/orders/insert_address' method = 'post'>

Shipping Address

			<fieldset>
				Address:
				<input type = 'text' class = 'form-control' name = 'shipping_address'>

				City:
				<input type = 'text' class = 'form-control' name = 'shipping_city'>

				State:
				<input type = 'text' class = 'form-control' name = 'shipping_state'>

				Zip:
				<input type = 'number' class = 'form-control' name = 'shipping_zip'>

			</fieldset>

			Same
	      <input name = 'check' type="checkbox" class="switch-input" onclick = 'same_info(this.form)'>

Billing Information

			<fieldset>
				Address:
				<input type = 'text' class = 'form-control' name = 'billing_address'>

				City:
				<input type = 'text' class = 'form-control' name = 'billing_city'>

				State:
				<input type = 'text' class = 'form-control' name = 'billing_state'>

				Zip:
				<input type = 'number' class = 'form-control' name = 'billing_zip'>

			</fieldset>

			<?php $this->load->view('/orders/_payment_card') ?>
		</form>

<?php $this->load->view('/templates/footer') ?>


text:
require 'rubygems'
require 'simplecov'
require "codeclimate-test-reporter"
CodeClimate::TestReporter.start

SimpleCov.start do
    add_filter 'spec/'
end

Dir[File.join(File.dirname(__FILE__), "support/**/*.rb")].each {|f| require f }

RSpec.configure do |config|
end


text:
class Toy
  include Mongoid::Document

  embedded_in :crate

  field :name
end


text:
'use strict';

var Schema = require('../schema');

module.exports = new Schema({
  include: [
    require('./minimal')
  ],
  implicit: [
    require('../type/null'),
    require('../type/bool'),
    require('../type/int'),
    require('../type/float'),
    require('../type/timestamp'),
    require('../type/merge')
  ],
  explicit: [
    require('../type/binary'),
    require('../type/omap'),
    require('../type/pairs'),
    require('../type/set')
  ]
});


text:
module AddProviderToUser

  extend self

  def perform(user:, auth_hash:)
    user.providers.create(
      uid: auth_hash.uid,
      name: auth_hash.provider
    )
  end

end


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

<title>com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper (AWS SDK for Android - 2.2.1)</title>
<meta name="date" content="2015-04-21">
<link rel="stylesheet" type="text/css" href="../../../../../JavaDoc.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper

     Primary classes for interacting with the DynamoDB Object Mapper mobile connector for easily storing Java objects in the cloud.

See: Description

Interface Summary

Interface
Description

ArgumentMarshaller

Interface to make it possible to cache the expensive type determination
 behavior.

ArgumentMarshaller.BinaryAttributeMarshaller

ArgumentMarshaller.BinarySetAttributeMarshaller

ArgumentMarshaller.BooleanAttributeMarshaller

ArgumentMarshaller.ListAttributeMarshaller

ArgumentMarshaller.MapAttributeMarshaller

ArgumentMarshaller.NumberAttributeMarshaller

ArgumentMarshaller.NumberSetAttributeMarshaller

ArgumentMarshaller.StringAttributeMarshaller

ArgumentMarshaller.StringSetAttributeMarshaller

ArgumentUnmarshaller

Unmarshaller interface to make it possible to cache the expensive
 type-determination behavior necessary when turning a service result back into
 an object.

AttributeTransformer

A hook allowing a custom transform/untransform of the raw attribute values
 immediately before writing them into DynamoDB and immediately after reading
 them out of DynamoDB, but with extra context about the model class not
 available at the raw AmazonDymnamoDB level.

AttributeTransformer.Parameters<T>

Parameters for the transform and untransform methods, so
 we don't have to break the interface in order to add additional
 parameters.

ConversionSchema

A strategy for mapping between Java types and DynamoDB types.

DynamoDBMapperConfig.ObjectTableNameResolver

Interface for a strategy used to determine the table name of an object
 based on it's class.

DynamoDBMapperConfig.TableNameResolver

Interface for a strategy used to determine the table name of an object
 based on it's class.

DynamoDBMarshaller<T>

Marshaller interface for storing complex types in DynamoDB as Strings.

ItemConverter

The concrete realization of a strategy for converting between Java objects
 and DynamoDB AttributeValues.

Class Summary

Class
Description

AttributeTransformerChain

A virtual AttributeTransformer that transforms and untransforms
 attributes by running them through a cascading series of child
 AttributeTransformer instances.

ConversionSchema.Dependencies

Dependency injection for the ItemConverters that this
 ConversionSchema generates.

ConversionSchemas

Pre-defined strategies for mapping between Java types and DynamoDB types.

DynamoDBDeleteExpression

Enables adding options to a delete operation.

DynamoDBMapper

Object mapper for domain-object interaction with DynamoDB.

DynamoDBMapper.FailedBatch

The return type of batchWrite, batchDelete and batchSave.

DynamoDBMapperConfig

Immutable configuration object for service call behavior.

DynamoDBMapperConfig.Builder

A fluent builder for DynamoDBMapperConfig objects.

DynamoDBMapperConfig.DefaultTableNameResolver

Default implementation of DynamoDBMapperConfig.TableNameResolver that mimics the
 behavior of DynamoDBMapper before the addition of
 DynamoDBMapperConfig.TableNameResolver.

DynamoDBMapperConfig.TableNameOverride

Allows overriding the table name declared on a domain class by the
 DynamoDBTable annotation.

DynamoDBMapperFieldModel

DynamoDBQueryExpression<T>

A query expression.

DynamoDBSaveExpression

Enables adding options to a save operation.

DynamoDBScanExpression

Options for filtering results from a scan operation.

JsonMarshaller<T>

Simple JSON marshaller that uses Gson mapper.

KeyPair

PaginatedList<T>

Unmodifiable list supporting paginated result sets from Amazon DynamoDB.

PaginatedParallelScanList<T>

Implementation of the List interface that represents the results from a
 parallel scan in AWS DynamoDB.

PaginatedQueryList<T>

Implementation of the List interface that represents the results from a query
 in AWS DynamoDB.

PaginatedScanList<T>

Implementation of the List interface that represents the results from a scan
 in AWS DynamoDB.

ParallelScanTask

QueryResultPage<T>

Container for a page of query results

S3ClientCache

A smart Map for AmazonS3Client objects.

S3Link

An S3 Link that works with DynamoDBMapper.

ScanResultPage<T>

Container for a page of scan results.

Enum Summary

Enum
Description

DynamoDBMapperConfig.ConsistentReads

Enumeration of consistent read behavior.

DynamoDBMapperConfig.PaginationLoadingStrategy

Enumeration of pagination loading strategy.

DynamoDBMapperConfig.SaveBehavior

Enumeration of behaviors for the save operation.

DynamoDBMapperFieldModel.DynamoDBAttributeType

Exception Summary

Exception
Description

DynamoDBMappingException

Generic exception for problems occuring when mapping DynamoDB items to Java
 objects or vice versa.

Annotation Types Summary

Annotation Type
Description

DynamoDBAttribute

Interface for marking a class property as an attribute in a DynamoDB table.

DynamoDBAutoGeneratedKey

Annotation for marking a hash key or range key property in a class to
 auto-generate this key.

DynamoDBDocument

An annotation that marks a class which can be serialized to a DynamoDB
 document or sub-document.

DynamoDBHashKey

Annotation for marking a property as the hash key for a modeled class.

DynamoDBIgnore

Annotation for marking a class property as non-modeled.

DynamoDBIndexHashKey

Annotation for marking a property in a class as the attribute to be used as
 the hash key for one or more global secondary indexes on a DynamoDB table.

DynamoDBIndexRangeKey

Annotation for marking a property in a class as the attribute to be used as
 range key for one or more local secondary indexes on a DynamoDB table.

DynamoDBMarshalling

Annotation to mark a property as using a custom marshaller.

DynamoDBNativeBoolean

An annotation that marks a boolean or Boolean attribute of a
 modeled class which should be serialized as a DynamoDB BOOL.

DynamoDBRangeKey

Annotation for marking a property in a class as the range key for a DynamoDB
 table.

DynamoDBTable

Annotation to mark a class as a DynamoDB table.

DynamoDBVersionAttribute

Annotation for marking a property as an optimistic locking version attribute.

Package com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper Description

     Primary classes for interacting with the DynamoDB Object Mapper mobile connector for easily storing Java objects in the cloud.

Overview

Package

Class

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

                Copyright © 2010 Amazon Web Services, Inc. All Rights Reserved.


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

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListSchedulingPoliciesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * A list of scheduling policies that match the request.
     *

     */
    private java.util.List<SchedulingPolicyListingDetail> schedulingPolicies;
    /**
     *

     * The nextToken value to include in a future ListSchedulingPolicies request. When the
     * results of a ListSchedulingPolicies request exceed maxResults, this value can be used
     * to retrieve the next page of results. This value is null when there are no more results to return.
     *

     */
    private String nextToken;

    /**
     *

     * A list of scheduling policies that match the request.
     *

     *
     * @return A list of scheduling policies that match the request.
     */

    public java.util.List<SchedulingPolicyListingDetail> getSchedulingPolicies() {
        return schedulingPolicies;
    }

    /**
     *

     * A list of scheduling policies that match the request.
     *

     *
     * @param schedulingPolicies
     *        A list of scheduling policies that match the request.
     */

    public void setSchedulingPolicies(java.util.Collection<SchedulingPolicyListingDetail> schedulingPolicies) {
        if (schedulingPolicies == null) {
            this.schedulingPolicies = null;
            return;
        }

        this.schedulingPolicies = new java.util.ArrayList<SchedulingPolicyListingDetail>(schedulingPolicies);
    }

    /**
     *

     * A list of scheduling policies that match the request.
     *

     *

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

     *
     * @param schedulingPolicies
     *        A list of scheduling policies that match the request.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListSchedulingPoliciesResult withSchedulingPolicies(SchedulingPolicyListingDetail... schedulingPolicies) {
        if (this.schedulingPolicies == null) {
            setSchedulingPolicies(new java.util.ArrayList<SchedulingPolicyListingDetail>(schedulingPolicies.length));
        }
        for (SchedulingPolicyListingDetail ele : schedulingPolicies) {
            this.schedulingPolicies.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of scheduling policies that match the request.
     *

     *
     * @param schedulingPolicies
     *        A list of scheduling policies that match the request.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListSchedulingPoliciesResult withSchedulingPolicies(java.util.Collection<SchedulingPolicyListingDetail> schedulingPolicies) {
        setSchedulingPolicies(schedulingPolicies);
        return this;
    }

    /**
     *

     * The nextToken value to include in a future ListSchedulingPolicies request. When the
     * results of a ListSchedulingPolicies request exceed maxResults, this value can be used
     * to retrieve the next page of results. This value is null when there are no more results to return.
     *

     *
     * @param nextToken
     *        The nextToken value to include in a future ListSchedulingPolicies request. When
     *        the results of a ListSchedulingPolicies request exceed maxResults, this value
     *        can be used to retrieve the next page of results. This value is null when there are no more
     *        results to return.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The nextToken value to include in a future ListSchedulingPolicies request. When the
     * results of a ListSchedulingPolicies request exceed maxResults, this value can be used
     * to retrieve the next page of results. This value is null when there are no more results to return.
     *

     *
     * @return The nextToken value to include in a future ListSchedulingPolicies request. When
     *         the results of a ListSchedulingPolicies request exceed maxResults, this value
     *         can be used to retrieve the next page of results. This value is null when there are no more
     *         results to return.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The nextToken value to include in a future ListSchedulingPolicies request. When the
     * results of a ListSchedulingPolicies request exceed maxResults, this value can be used
     * to retrieve the next page of results. This value is null when there are no more results to return.
     *

     *
     * @param nextToken
     *        The nextToken value to include in a future ListSchedulingPolicies request. When
     *        the results of a ListSchedulingPolicies request exceed maxResults, this value
     *        can be used to retrieve the next page of results. This value is null when there are no more
     *        results to return.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListSchedulingPoliciesResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getSchedulingPolicies() != null)
            sb.append("SchedulingPolicies: ").append(getSchedulingPolicies()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof ListSchedulingPoliciesResult == false)
            return false;
        ListSchedulingPoliciesResult other = (ListSchedulingPoliciesResult) obj;
        if (other.getSchedulingPolicies() == null ^ this.getSchedulingPolicies() == null)
            return false;
        if (other.getSchedulingPolicies() != null && other.getSchedulingPolicies().equals(this.getSchedulingPolicies()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getSchedulingPolicies() == null) ? 0 : getSchedulingPolicies().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public ListSchedulingPoliciesResult clone() {
        try {
            return (ListSchedulingPoliciesResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}