text:
"""Workflow Logic the Assignment service."""

import copy
import uuid

import six
from six.moves import urllib

from keystone.common import controller
from keystone.common import dependency
from keystone import config
from keystone import exception
from keystone.openstack.common.gettextutils import _
from keystone.openstack.common import log

CONF = config.CONF
LOG = log.getLogger(__name__)

@dependency.requires('assignment_api', 'identity_api', 'token_api')
class Tenant(controller.V2Controller):

    @controller.v2_deprecated
    def get_all_projects(self, context, **kw):
        """Gets a list of all tenants for an admin user."""
        if 'name' in context['query_string']:
            return self.get_project_by_name(
                context, context['query_string'].get('name'))

        self.assert_admin(context)
        tenant_refs = self.assignment_api.list_projects_in_domain(
            CONF.identity.default_domain_id)
        for tenant_ref in tenant_refs:
            tenant_ref = self.filter_domain_id(tenant_ref)
        params = {
            'limit': context['query_string'].get('limit'),
            'marker': context['query_string'].get('marker'),
        }
        return self._format_project_list(tenant_refs, **params)

    @controller.v2_deprecated
    def get_projects_for_token(self, context, **kw):
        """Get valid tenants for token based on token used to authenticate.

        Pulls the token from the context, validates it and gets the valid
        tenants for the user in the token.

        Doesn't care about token scopedness.

        """
        try:
            token_ref = self.token_api.get_token(context['token_id'])
        except exception.NotFound as e:
            LOG.warning(_('Authentication failed: %s'), e)
            raise exception.Unauthorized(e)

        user_ref = token_ref['user']
        tenant_refs = (
            self.assignment_api.list_projects_for_user(user_ref['id']))
        tenant_refs = [self.filter_domain_id(ref) for ref in tenant_refs
                       if ref['domain_id'] == CONF.identity.default_domain_id]
        params = {
            'limit': context['query_string'].get('limit'),
            'marker': context['query_string'].get('marker'),
        }
        return self._format_project_list(tenant_refs, **params)

    @controller.v2_deprecated
    def get_project(self, context, tenant_id):
        # TODO(termie): this stuff should probably be moved to middleware
        self.assert_admin(context)
        ref = self.assignment_api.get_project(tenant_id)
        return {'tenant': self.filter_domain_id(ref)}

    @controller.v2_deprecated
    def get_project_by_name(self, context, tenant_name):
        self.assert_admin(context)
        ref = self.assignment_api.get_project_by_name(
            tenant_name, CONF.identity.default_domain_id)
        return {'tenant': self.filter_domain_id(ref)}

    # CRUD Extension
    @controller.v2_deprecated
    def create_project(self, context, tenant):
        tenant_ref = self._normalize_dict(tenant)

        if 'name' not in tenant_ref or not tenant_ref['name']:
            msg = _('Name field is required and cannot be empty')
            raise exception.ValidationError(message=msg)

        self.assert_admin(context)
        tenant_ref['id'] = tenant_ref.get('id', uuid.uuid4().hex)
        tenant = self.assignment_api.create_project(
            tenant_ref['id'],
            self._normalize_domain_id(context, tenant_ref))
        return {'tenant': self.filter_domain_id(tenant)}

    @controller.v2_deprecated
    def update_project(self, context, tenant_id, tenant):
        self.assert_admin(context)
        # Remove domain_id if specified - a v2 api caller should not
        # be specifying that
        clean_tenant = tenant.copy()
        clean_tenant.pop('domain_id', None)

        tenant_ref = self.assignment_api.update_project(
            tenant_id, clean_tenant)
        return {'tenant': tenant_ref}

    @controller.v2_deprecated
    def delete_project(self, context, tenant_id):
        self.assert_admin(context)
        self.assignment_api.delete_project(tenant_id)

    @controller.v2_deprecated
    def get_project_users(self, context, tenant_id, **kw):
        self.assert_admin(context)
        user_refs = []
        user_ids = self.assignment_api.list_user_ids_for_project(tenant_id)
        for user_id in user_ids:
            try:
                user_ref = self.identity_api.get_user(user_id)
            except exception.UserNotFound:
                # Log that user is missing and continue on.
                message = _("User %(user_id)s in project %(project_id)s "
                            "doesn't exist.")
                LOG.debug(message,
                          {'user_id': user_id, 'project_id': tenant_id})
            else:
                user_refs.append(self.v3_to_v2_user(user_ref))
        return {'users': user_refs}

    def _format_project_list(self, tenant_refs, **kwargs):
        marker = kwargs.get('marker')
        first_index = 0
        if marker is not None:
            for (marker_index, tenant) in enumerate(tenant_refs):
                if tenant['id'] == marker:
                    # we start pagination after the marker
                    first_index = marker_index + 1
                    break
            else:
                msg = _('Marker could not be found')
                raise exception.ValidationError(message=msg)

        limit = kwargs.get('limit')
        last_index = None
        if limit is not None:
            try:
                limit = int(limit)
                if limit < 0:
                    raise AssertionError()
            except (ValueError, AssertionError):
                msg = _('Invalid limit value')
                raise exception.ValidationError(message=msg)
            last_index = first_index + limit

        tenant_refs = tenant_refs[first_index:last_index]

        for x in tenant_refs:
            if 'enabled' not in x:
                x['enabled'] = True
        o = {'tenants': tenant_refs,
             'tenants_links': []}
        return o

@dependency.requires('assignment_api')
class Role(controller.V2Controller):

    # COMPAT(essex-3)
    @controller.v2_deprecated
    def get_user_roles(self, context, user_id, tenant_id=None):
        """Get the roles for a user and tenant pair.

        Since we're trying to ignore the idea of user-only roles we're
        not implementing them in hopes that the idea will die off.

        """
        self.assert_admin(context)
        if tenant_id is None:
            raise exception.NotImplemented(message='User roles not supported: '
                                                   'tenant ID required')

        roles = self.assignment_api.get_roles_for_user_and_project(
            user_id, tenant_id)
        return {'roles': [self.assignment_api.get_role(x)
                          for x in roles]}

    # CRUD extension
    @controller.v2_deprecated
    def get_role(self, context, role_id):
        self.assert_admin(context)
        return {'role': self.assignment_api.get_role(role_id)}

    @controller.v2_deprecated
    def create_role(self, context, role):
        role = self._normalize_dict(role)
        self.assert_admin(context)

        if 'name' not in role or not role['name']:
            msg = _('Name field is required and cannot be empty')
            raise exception.ValidationError(message=msg)

        role_id = uuid.uuid4().hex
        role['id'] = role_id
        role_ref = self.assignment_api.create_role(role_id, role)
        return {'role': role_ref}

    @controller.v2_deprecated
    def delete_role(self, context, role_id):
        self.assert_admin(context)
        self.assignment_api.delete_role(role_id)

    @controller.v2_deprecated
    def get_roles(self, context):
        self.assert_admin(context)
        return {'roles': self.assignment_api.list_roles()}

    @controller.v2_deprecated
    def add_role_to_user(self, context, user_id, role_id, tenant_id=None):
        """Add a role to a user and tenant pair.

        Since we're trying to ignore the idea of user-only roles we're
        not implementing them in hopes that the idea will die off.

        """
        self.assert_admin(context)
        if tenant_id is None:
            raise exception.NotImplemented(message='User roles not supported: '
                                                   'tenant_id required')

        self.assignment_api.add_role_to_user_and_project(
            user_id, tenant_id, role_id)

        role_ref = self.assignment_api.get_role(role_id)
        return {'role': role_ref}

    @controller.v2_deprecated
    def remove_role_from_user(self, context, user_id, role_id, tenant_id=None):
        """Remove a role from a user and tenant pair.

        Since we're trying to ignore the idea of user-only roles we're
        not implementing them in hopes that the idea will die off.

        """
        self.assert_admin(context)
        if tenant_id is None:
            raise exception.NotImplemented(message='User roles not supported: '
                                                   'tenant_id required')

        # This still has the weird legacy semantics that adding a role to
        # a user also adds them to a tenant, so we must follow up on that
        self.assignment_api.remove_role_from_user_and_project(
            user_id, tenant_id, role_id)

    # COMPAT(diablo): CRUD extension
    @controller.v2_deprecated
    def get_role_refs(self, context, user_id):
        """Ultimate hack to get around having to make role_refs first-class.

        This will basically iterate over the various roles the user has in
        all tenants the user is a member of and create fake role_refs where
        the id encodes the user-tenant-role information so we can look
        up the appropriate data when we need to delete them.

        """
        self.assert_admin(context)
        tenants = self.assignment_api.list_projects_for_user(user_id)
        o = []
        for tenant in tenants:
            # As a v2 call, we should limit the response to those projects in
            # the default domain.
            if tenant['domain_id'] != CONF.identity.default_domain_id:
                continue
            role_ids = self.assignment_api.get_roles_for_user_and_project(
                user_id, tenant['id'])
            for role_id in role_ids:
                ref = {'roleId': role_id,
                       'tenantId': tenant['id'],
                       'userId': user_id}
                ref['id'] = urllib.parse.urlencode(ref)
                o.append(ref)
        return {'roles': o}

    # COMPAT(diablo): CRUD extension
    @controller.v2_deprecated
    def create_role_ref(self, context, user_id, role):
        """This is actually used for adding a user to a tenant.

        In the legacy data model adding a user to a tenant required setting
        a role.

        """
        self.assert_admin(context)
        # TODO(termie): for now we're ignoring the actual role
        tenant_id = role.get('tenantId')
        role_id = role.get('roleId')
        self.assignment_api.add_role_to_user_and_project(
            user_id, tenant_id, role_id)

        role_ref = self.assignment_api.get_role(role_id)
        return {'role': role_ref}

    # COMPAT(diablo): CRUD extension
    @controller.v2_deprecated
    def delete_role_ref(self, context, user_id, role_ref_id):
        """This is actually used for deleting a user from a tenant.

        In the legacy data model removing a user from a tenant required
        deleting a role.

        To emulate this, we encode the tenant and role in the role_ref_id,
        and if this happens to be the last role for the user-tenant pair,
        we remove the user from the tenant.

        """
        self.assert_admin(context)
        # TODO(termie): for now we're ignoring the actual role
        role_ref_ref = urllib.parse.parse_qs(role_ref_id)
        tenant_id = role_ref_ref.get('tenantId')[0]
        role_id = role_ref_ref.get('roleId')[0]
        self.assignment_api.remove_role_from_user_and_project(
            user_id, tenant_id, role_id)

@dependency.requires('assignment_api')
class DomainV3(controller.V3Controller):
    collection_name = 'domains'
    member_name = 'domain'

    def __init__(self):
        super(DomainV3, self).__init__()
        self.get_member_from_driver = self.assignment_api.get_domain

    @controller.protected()
    def create_domain(self, context, domain):
        self._require_attribute(domain, 'name')

        ref = self._assign_unique_id(self._normalize_dict(domain))
        ref = self.assignment_api.create_domain(ref['id'], ref)
        return DomainV3.wrap_member(context, ref)

    @controller.filterprotected('enabled', 'name')
    def list_domains(self, context, filters):
        hints = DomainV3.build_driver_hints(context, filters)
        refs = self.assignment_api.list_domains(hints=hints)
        return DomainV3.wrap_collection(context, refs, hints=hints)

    @controller.protected()
    def get_domain(self, context, domain_id):
        ref = self.assignment_api.get_domain(domain_id)
        return DomainV3.wrap_member(context, ref)

    @controller.protected()
    def update_domain(self, context, domain_id, domain):
	print("controller.py: domain=", domain)
        self._require_matching_id(domain_id, domain)
        ref = self.assignment_api.update_domain(domain_id, domain)
        return DomainV3.wrap_member(context, ref)

    @controller.protected()
    def delete_domain(self, context, domain_id):
        return self.assignment_api.delete_domain(domain_id)

@dependency.requires('assignment_api')
class SidV3(controller.V3Controller):
    collection_name = 'sids'
    member_name = 'sid'

    def __init__(self):
        super(SidV3, self).__init__()

    @controller.protected()
    def create_sid(self, context, sid ):
	#print("controller.py: sid=", sid)
        self._require_attribute(sid, 'name')
        ref = self._assign_unique_id(self._normalize_dict(sid))
        sid_ref = self.assignment_api.create_domain(ref['id'], ref)

	sidinfo = {}
        sid_id = sid_ref['id']
        sidinfo['id'] = sid_id
	sidinfo['members'] = sid['members']
        sidinfo_ref = self.assignment_api.create_sidinfo(sidinfo)

	# create a default sip
        project={"name": "defaultsip", "domain_id": sid_id}
	default_sip_name="default_sip_"+sid['name']
	#print("default_sip_name=", default_sip_name)
	default_sip_id="default_sip_"+sid_id
	#print("default_sip_id=", default_sip_id)
 	sip_ref={"name": default_sip_name, "domain_id": sid_id, "id": default_sip_id}
        defaultsip_ref = self.assignment_api.create_project(sip_ref['id'], sip_ref)

        return SidV3.wrap_member(context, sid_ref)

    @controller.protected()
    def get_sidinfo(self, context, sid_id):
        ref = self.assignment_api.get_sidinfo(sid_id)
	print("controller.py: get_sidinfo: ref=", ref)
        return SidV3.wrap_member(context, ref)

#    @controller.protected()
#    def delete_sidinfo(self, context, sid_id):
#        return self.assignment_api.delete_sidinfo(sid_id)

    @controller.protected()
    def delete_sid(self, context, sid_id):
	domain={"enabled": False}
        self._require_matching_id(sid_id, domain)
        self.assignment_api.update_domain(sid_id, domain)

	self.assignment_api.delete_domain(sid_id)
        self.assignment_api.delete_sidinfo(sid_id)
	return

@dependency.requires('assignment_api')
class ProjectV3(controller.V3Controller):
    collection_name = 'projects'
    member_name = 'project'

    def __init__(self):
        super(ProjectV3, self).__init__()
        self.get_member_from_driver = self.assignment_api.get_project

    @controller.protected()
    def create_project(self, context, project):
        self._require_attribute(project, 'name')

        ref = self._assign_unique_id(self._normalize_dict(project))
        ref = self._normalize_domain_id(context, ref)
        ref = self.assignment_api.create_project(ref['id'], ref)
        return ProjectV3.wrap_member(context, ref)

    @controller.filterprotected('domain_id', 'enabled', 'name')
    def list_projects(self, context, filters):
	#print("controller.py: filters=", filters)
        hints = ProjectV3.build_driver_hints(context, filters)
	#print("controller.py: hints=", hints)
        refs = self.assignment_api.list_projects(hints=hints)
        return ProjectV3.wrap_collection(context, refs, hints=hints)

    @controller.filterprotected('enabled', 'name')
    def list_user_projects(self, context, filters, user_id):
        hints = ProjectV3.build_driver_hints(context, filters)
        refs = self.assignment_api.list_projects_for_user(user_id,
                                                          hints=hints)
        return ProjectV3.wrap_collection(context, refs, hints=hints)

    @controller.protected()
    def get_project(self, context, project_id):
        ref = self.assignment_api.get_project(project_id)
        return ProjectV3.wrap_member(context, ref)

    @controller.protected()
    def update_project(self, context, project_id, project):
        self._require_matching_id(project_id, project)
        self._require_matching_domain_id(
            project_id, project, self.assignment_api.get_project)
        ref = self.assignment_api.update_project(project_id, project)
        return ProjectV3.wrap_member(context, ref)

    @controller.protected()
    def delete_project(self, context, project_id):
        return self.assignment_api.delete_project(project_id)

@dependency.requires('assignment_api', 'identity_api')
class RoleV3(controller.V3Controller):
    collection_name = 'roles'
    member_name = 'role'

    def __init__(self):
        super(RoleV3, self).__init__()
        self.get_member_from_driver = self.assignment_api.get_role

    @controller.protected()
    def create_role(self, context, role):
        self._require_attribute(role, 'name')

        ref = self._assign_unique_id(self._normalize_dict(role))
        ref = self.assignment_api.create_role(ref['id'], ref)
        return RoleV3.wrap_member(context, ref)

    @controller.filterprotected('name')
    def list_roles(self, context, filters):
        hints = RoleV3.build_driver_hints(context, filters)
        refs = self.assignment_api.list_roles(
            hints=hints)
        return RoleV3.wrap_collection(context, refs, hints=hints)

    @controller.protected()
    def get_role(self, context, role_id):
        ref = self.assignment_api.get_role(role_id)
        return RoleV3.wrap_member(context, ref)

    @controller.protected()
    def update_role(self, context, role_id, role):
        self._require_matching_id(role_id, role)

        ref = self.assignment_api.update_role(role_id, role)
        return RoleV3.wrap_member(context, ref)

    @controller.protected()
    def delete_role(self, context, role_id):
        self.assignment_api.delete_role(role_id)

    def _require_domain_xor_project(self, domain_id, project_id):
        if (domain_id and project_id) or (not domain_id and not project_id):
            msg = _('Specify a domain or project, not both')
            raise exception.ValidationError(msg)

    def _require_user_xor_group(self, user_id, group_id):
        if (user_id and group_id) or (not user_id and not group_id):
            msg = _('Specify a user or group, not both')
            raise exception.ValidationError(msg)

    def _check_if_inherited(self, context):
        return (CONF.os_inherit.enabled and
                context['path'].startswith('/OS-INHERIT') and
                context['path'].endswith('/inherited_to_projects'))

    def _check_grant_protection(self, context, protection, attr=None, role_id=None,
                                user_id=None, group_id=None,
                                domain_id=None, project_id=None):
        """Check protection for role grant APIs.

        The policy rule might want to inspect attributes of any of the entities
        involved in the grant.  So we get these and pass them to the
        check_protection() handler in the controller.

        """
	print("protection:", protection)
        ref = {}
        if role_id:
            ref['role'] = self.assignment_api.get_role(role_id)
        if user_id:
            ref['user'] = self.identity_api.get_user(user_id)
        else:
            ref['group'] = self.identity_api.get_group(group_id)

        if domain_id:
            ref['domain'] = self.assignment_api.get_domain(domain_id)
        else:
            ref['project'] = self.assignment_api.get_project(project_id)

        self.check_protection(context, protection, ref)

    @controller.protected(callback=_check_grant_protection)
    def create_grant(self, context, role_id, user_id=None,
                     group_id=None, domain_id=None, project_id=None):
        """Grants a role to a user or group on either a domain or project."""
        self._require_domain_xor_project(domain_id, project_id)
        self._require_user_xor_group(user_id, group_id)

	ref_sid = None
	if domain_id != None:
	    ref_sid = self.assignment_api.get_sidinfo(domain_id)
	    if ref_sid is not None:
		#self.create_sid_grant(context, role_id, user_id, group_id, domain_id, project_id)
		return
	    else:
        	self.assignment_api.create_grant(
            	    role_id, user_id, group_id, domain_id, project_id,
            	    self._check_if_inherited(context))

	if project_id != None:
            ref_project = self.assignment_api.get_project(project_id)
            project_domain_id = ref_project['domain_id']
	    print("project_domain_id=", project_domain_id)
            ref_sid = self.assignment_api.get_sidinfo(project_domain_id)
            if ref_sid is not None:
		print("assignment/controller.py: ref_sid[sid_id]=", ref_sid['sid_id'])
		#self.create_sid_grant(context, role_id, user_id, group_id, domain_id, project_id)
		return
	    else:
        	self.assignment_api.create_grant(
            	    role_id, user_id, group_id, domain_id, project_id,
            	    self._check_if_inherited(context))

    @controller.protected(callback=_check_grant_protection)
    def create_sid_grant(self, context, role_id, user_id=None, group_id=None, domain_id=None, project_id=None):
        """Grants a role to a user on  a sid ."""
	# get auth info from context
 	auth_ref = context['environment']['KEYSTONE_AUTH_CONTEXT']
	#print("-------------------------------------------------------")
	#print("auth_ref=")
	#print(auth_ref)

	user_home_domain_id = auth_ref['user.domain_id']

        self._require_domain_xor_project(domain_id, project_id)
        self._require_user_xor_group(user_id, group_id)

        if domain_id != None:
            ref_sid = self.assignment_api.get_sidinfo(domain_id)
            if ref_sid is None:
                raise exception.SidNotFound(sid_id=domain_id)
            members = ref_sid['members']

        if project_id != None:
            ref_sip = self.assignment_api.get_project(project_id)
            sid_id = ref_sip['domain_id']
            ref_sid = self.assignment_api.get_sidinfo(sid_id)
            if ref_sid is None:
                raise exception.SidNotFound(sid_id=sid_id)
            members = ref_sid['members']

        if user_id != None:
            ref_user=self.identity_api.get_user(user_id, domain_scope=None)
            if ref_user is None:
                raise exception.UserNotFound(user_id=user_id)
            user_domain_id = ref_user['domain_id']

        # check if user_domain_id is in sid member domains
        if user_domain_id not in members:
            raise exception.MemberDomainNotFound(domain_id=user_domain_id)

        # check if user_domain_id is the same as user_home_domain_id
        if user_domain_id != user_home_domain_id:
            raise exception.MemberDomainNotFound(domain_id=user_domain_id)

        self.assignment_api.create_grant(
            role_id, user_id, group_id, domain_id, project_id,
            self._check_if_inherited(context))

#    @controller.protected(callback=_check_grant_protection)
#    def create_sid_grant(self, context, role_id, user_id=None, group_id=None, domain_id=None, project_id=None):
#        """Grants a role to a user on  a sid ."""
#        self._require_domain_xor_project(domain_id, project_id)
#        self._require_user_xor_group(user_id, group_id)
#
#	if domain_id != None:
#	    ref_sid = self.assignment_api.get_sidinfo(domain_id)
#	    if ref_sid is None:
#                raise exception.SidNotFound(sid_id=domain_id)
#            members = ref_sid['members']
#
#        if project_id != None:
#            ref_sip = self.assignment_api.get_project(project_id)
#            sid_id = ref_sip['domain_id']
#            ref_sid = self.assignment_api.get_sidinfo(sid_id)
#            if ref_sid is None:
#                raise exception.SidNotFound(sid_id=sid_id)
#            members = ref_sid['members']
#
#	if user_id != None:
#            ref_user=self.identity_api.get_user(user_id, domain_scope=None)
#            if ref_user is None:
#                raise exception.UserNotFound(user_id=user_id)
#            user_domain_id = ref_user['domain_id']
#
        # check if user_domain_id is in sid member domains
#        if user_domain_id not in members:
#            raise exception.MemberDomainNotFound(domain_id=user_domain_id)
#
#        self.assignment_api.create_grant(
#            role_id, user_id, group_id, domain_id, project_id,
#            self._check_if_inherited(context))

#    @controller.protected(callback=_check_grant_protection)
#    def create_grant(self, context, role_id, user_id=None,
#                     group_id=None, domain_id=None, project_id=None):
#        """Grants a role to a user or group on either a domain or project."""
#        self._require_domain_xor_project(domain_id, project_id)
#        self._require_user_xor_group(user_id, group_id)
#
#        self.assignment_api.create_grant(
#            role_id, user_id, group_id, domain_id, project_id,
#            self._check_if_inherited(context))

    @controller.protected(callback=_check_grant_protection)
    def list_grants(self, context, user_id=None,
                    group_id=None, domain_id=None, project_id=None):
        """Lists roles granted to user/group on either a domain or project."""
        self._require_domain_xor_project(domain_id, project_id)
        self._require_user_xor_group(user_id, group_id)

        refs = self.assignment_api.list_grants(
            user_id, group_id, domain_id, project_id,
            self._check_if_inherited(context))
        return RoleV3.wrap_collection(context, refs)

    @controller.protected(callback=_check_grant_protection)
    def check_grant(self, context, role_id, user_id=None,
                    group_id=None, domain_id=None, project_id=None):
        """Checks if a role has been granted on either a domain or project."""
        self._require_domain_xor_project(domain_id, project_id)
        self._require_user_xor_group(user_id, group_id)

        self.assignment_api.get_grant(
            role_id, user_id, group_id, domain_id, project_id,
            self._check_if_inherited(context))

    @controller.protected(callback=_check_grant_protection)
    def revoke_grant(self, context, role_id, user_id=None,
                     group_id=None, domain_id=None, project_id=None):
        """Revokes a role from user/group on either a domain or project."""
        self._require_domain_xor_project(domain_id, project_id)
        self._require_user_xor_group(user_id, group_id)

        self.assignment_api.delete_grant(
            role_id, user_id, group_id, domain_id, project_id,
            self._check_if_inherited(context))

@dependency.requires('assignment_api', 'identity_api')
class RoleAssignmentV3(controller.V3Controller):

    # TODO(henry-nash): The current implementation does not provide a full
    # first class entity for role-assignment. There is no role_assignment_id
    # and only the list_role_assignment call is supported. Further, since it
    # is not a first class entity, the links for the individual entities
    # reference the individual role grant APIs.

    collection_name = 'role_assignments'
    member_name = 'role_assignment'

    @classmethod
    def wrap_member(cls, context, ref):
        # NOTE(henry-nash): Since we are not yet a true collection, we override
        # the wrapper as have already included the links in the entities
        pass

    def _format_entity(self, context, entity):
        """Format an assignment entity for API response.

        The driver layer returns entities as dicts containing the ids of the
        actor (e.g. user or group), target (e.g. domain or project) and role.
        If it is an inherited role, then this is also indicated. Examples:

        {'user_id': user_id,
         'project_id': domain_id,
         'role_id': role_id}

        or, for an inherited role:

        {'user_id': user_id,
         'domain_id': domain_id,
         'role_id': role_id,
         'inherited_to_projects': true}

        This function maps this into the format to be returned via the API,
        e.g. for the second example above:

        {
            'user': {
                {'id': user_id}
            },
            'scope': {
                'domain': {
                    {'id': domain_id}
                },
                'OS-INHERIT:inherited_to': 'projects
            },
            'role': {
                {'id': role_id}
            },
            'links': {
                'assignment': '/domains/domain_id/users/user_id/roles/'
                              'role_id/inherited_to_projects'
            }
        }

        """

        formatted_entity = {}
        suffix = ""
        if 'user_id' in entity:
            formatted_entity['user'] = {'id': entity['user_id']}
            actor_link = 'users/%s' % entity['user_id']
        if 'group_id' in entity:
            formatted_entity['group'] = {'id': entity['group_id']}
            actor_link = 'groups/%s' % entity['group_id']
        if 'role_id' in entity:
            formatted_entity['role'] = {'id': entity['role_id']}
        if 'project_id' in entity:
            formatted_entity['scope'] = (
                {'project': {'id': entity['project_id']}})
            target_link = '/projects/%s' % entity['project_id']
        if 'domain_id' in entity:
            formatted_entity['scope'] = (
                {'domain': {'id': entity['domain_id']}})
            if 'inherited_to_projects' in entity:
                formatted_entity['scope']['OS-INHERIT:inherited_to'] = (
                    'projects')
                target_link = '/OS-INHERIT/domains/%s' % entity['domain_id']
                suffix = '/inherited_to_projects'
            else:
                target_link = '/domains/%s' % entity['domain_id']
        formatted_entity.setdefault('links', {})

        path = '%(target)s/%(actor)s/roles/%(role)s%(suffix)s' % {
            'target': target_link,
            'actor': actor_link,
            'role': entity['role_id'],
            'suffix': suffix}
        formatted_entity['links']['assignment'] = self.base_url(context, path)

        return formatted_entity

    def _expand_indirect_assignments(self, context, refs):
        """Processes entity list into all-direct assignments.

        For any group role assignments in the list, create a role assignment
        entity for each member of that group, and then remove the group
        assignment entity itself from the list.

        If the OS-INHERIT extension is enabled, then honor any inherited
        roles on the domain by creating the equivalent on all projects
        owned by the domain.

        For any new entity created by virtue of group membership, add in an
        additional link to that membership.

        """
        def _get_group_members(ref):
            """Get a list of group members.

            Get the list of group members.  If this fails with
            GroupNotFound, then log this as a warning, but allow
            overall processing to continue.

            """
            try:
                members = self.identity_api.list_users_in_group(
                    ref['group']['id'])
            except exception.GroupNotFound:
                members = []
                # The group is missing, which should not happen since
                # group deletion should remove any related assignments, so
                # log a warning
                if 'domain' in ref:
                    target = 'Domain: %s' % ref['domain'].get('domain_id')
                elif 'project' in ref:
                    target = 'Project: %s' % ref['project'].get('project_id')
                else:
                    # Should always be a domain or project, but since to get
                    # here things have gone astray, let's be cautious.
                    target = 'Unknown'
                LOG.warning(
                    _('Group %(group)s not found for role-assignment - '
                      '%(target)s with Role: %(role)s'), {
                          'group': ref['group_id'], 'target': target,
                          'role': ref.get('role_id')})
            return members

        def _build_user_assignment_equivalent_of_group(
                user, group_id, template):
            """Create a user assignment equivalent to the group one.

            The template has had the 'group' entity removed, so
            substitute a 'user' one. The 'assignment' link stays as it is,
            referring to the group assignment that led to this role.
            A 'membership' link is added that refers to this particular
            user's membership of this group.

            """
            user_entry = copy.deepcopy(template)
            user_entry['user'] = {'id': user['id']}
            user_entry['links']['membership'] = (
                self.base_url(context, '/groups/%s/users/%s' %
                              (group_id, user['id'])))
            return user_entry

        def _build_project_equivalent_of_user_domain_role(
                project_id, domain_id, template):
            """Create a user project assignment equivalent to the domain one.

            The template has had the 'domain' entity removed, so
            substitute a 'project' one, modifying the 'assignment' link
            to match.

            """
            project_entry = copy.deepcopy(template)
            project_entry['scope']['project'] = {'id': project_id}
            project_entry['links']['assignment'] = (
                self.base_url(
                    context,
                    '/OS-INHERIT/domains/%s/users/%s/roles/%s'
                    '/inherited_to_projects' % (
                        domain_id, project_entry['user']['id'],
                        project_entry['role']['id'])))
            return project_entry

        def _build_project_equivalent_of_group_domain_role(
                user_id, group_id, project_id, domain_id, template):
            """Create a user project equivalent to the domain group one.

            The template has had the 'domain' and 'group' entities removed, so
            substitute a 'user-project' one, modifying the 'assignment' link
            to match.

            """
            project_entry = copy.deepcopy(template)
            project_entry['user'] = {'id': user_id}
            project_entry['scope']['project'] = {'id': project_id}
            project_entry['links']['assignment'] = (
                self.base_url(context,
                              '/OS-INHERIT/domains/%s/groups/%s/roles/%s'
                              '/inherited_to_projects' % (
                                  domain_id, group_id,
                                  project_entry['role']['id'])))
            project_entry['links']['membership'] = (
                self.base_url(context, '/groups/%s/users/%s' %
                              (group_id, user_id)))
            return project_entry

        # Scan the list of entities for any assignments that need to be
        # expanded.
        #
        # If the OS-INERIT extension is enabled, the refs lists may
        # contain roles to be inherited from domain to project, so expand
        # these as well into project equivalents
        #
        # For any regular group entries, expand these into user entries based
        # on membership of that group.
        #
        # Due to the potentially large expansions, rather than modify the
        # list we are enumerating, we build a new one as we go.
        #

        new_refs = []
        for r in refs:
            if 'OS-INHERIT:inherited_to' in r['scope']:
                # It's an inherited domain role - so get the list of projects
                # owned by this domain. A domain scope is guaranteed since we
                # checked this when we built the refs list
                project_ids = (
                    [x['id'] for x in
                        self.assignment_api.list_projects_in_domain(
                            r['scope']['domain']['id'])])
                base_entry = copy.deepcopy(r)
                domain_id = base_entry['scope']['domain']['id']
                base_entry['scope'].pop('domain')
                # For each project, create an equivalent role assignment
                for p in project_ids:
                    # If it's a group assignment, then create equivalent user
                    # roles based on membership of the group
                    if 'group' in base_entry:
                        members = _get_group_members(base_entry)
                        sub_entry = copy.deepcopy(base_entry)
                        group_id = sub_entry['group']['id']
                        sub_entry.pop('group')
                        for m in members:
                            new_entry = (
                                _build_project_equivalent_of_group_domain_role(
                                    m['id'], group_id, p,
                                    domain_id, sub_entry))
                            new_refs.append(new_entry)
                    else:
                        new_entry = (
                            _build_project_equivalent_of_user_domain_role(
                                p, domain_id, base_entry))
                        new_refs.append(new_entry)
            elif 'group' in r:
                # It's a non-inherited group role assignment, so get the list
                # of members.
                members = _get_group_members(r)

                # Now replace that group role assignment entry with an
                # equivalent user role assignment for each of the group members
                base_entry = copy.deepcopy(r)
                group_id = base_entry['group']['id']
                base_entry.pop('group')
                for m in members:
                    user_entry = _build_user_assignment_equivalent_of_group(
                        m, group_id, base_entry)
                    new_refs.append(user_entry)
            else:
                new_refs.append(r)

        return new_refs

    def _query_filter_is_true(self, filter_value):
        """Determine if bool query param is 'True'.

        We treat this the same way as we do for policy
        enforcement:

        {bool_param}=0 is treated as False

        Any other value is considered to be equivalent to
        True, including the absence of a value

        """

        if (isinstance(filter_value, six.string_types) and
                filter_value == '0'):
            val = False
        else:
            val = True
        return val

    def _filter_inherited(self, entry):
        if ('inherited_to_projects' in entry and
                not CONF.os_inherit.enabled):
                    return False
        else:
            return True

    @controller.filterprotected('group.id', 'role.id',
                                'scope.domain.id', 'scope.project.id',
                                'scope.OS-INHERIT:inherited_to', 'user.id')
    def list_role_assignments(self, context, filters):

        # TODO(henry-nash): This implementation uses the standard filtering
        # in the V3.wrap_collection. Given the large number of individual
        # assignments, this is pretty inefficient.  An alternative would be
        # to pass the filters into the driver call, so that the list size is
        # kept a minimum.

        hints = self.build_driver_hints(context, filters)
        refs = self.assignment_api.list_role_assignments()
        formatted_refs = (
            [self._format_entity(context, x) for x in refs
             if self._filter_inherited(x)])

        if ('effective' in context['query_string'] and
                self._query_filter_is_true(
                    context['query_string']['effective'])):

            formatted_refs = self._expand_indirect_assignments(context,
                                                               formatted_refs)

        return self.wrap_collection(context, formatted_refs, hints=hints)

    @controller.protected()
    def get_role_assignment(self, context):
        raise exception.NotImplemented()

    @controller.protected()
    def update_role_assignment(self, context):
        raise exception.NotImplemented()

    @controller.protected()
    def delete_role_assignment(self, context):
        raise exception.NotImplemented()


text:
from sklearn2sql_heroku.tests.regression import generic as reg_gen

reg_gen.test_model("DecisionTreeRegressor" , "diabetes" , "mssql")

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>energy.usef.agr.endpoint.dto (usef-root-pom 1.3.6 API)</title>
<meta name="date" content="2016-09-29">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

energy.usef.agr.endpoint.dto

Classes

ConnectionRestDto


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.afi.jx.lib.common.rest.dto;

/**
 *
 * @author achmad.ha
 */
public class DtoRespondLogin extends DtoRespond{

    private String userName;
    private String dealerCode;
    private String dealerName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getDealerCode() {
        return dealerCode;
    }

    public void setDealerCode(String dealerCode) {
        this.dealerCode = dealerCode;
    }

    public String getDealerName() {
        return dealerName;
    }

    public void setDealerName(String dealerName) {
        this.dealerName = dealerName;
    }
}


text:
/* eslint-disable unicorn/filename-case */
/* eslint-env browser */
/* global webkit */

// eslint-disable-next-line no-unused-vars
function show(platform, isEnabled) {
	document.body.classList.add(`platform-${platform}`);

	if (typeof isEnabled === 'boolean') {
		document.body.classList.toggle('state-on', isEnabled);
		document.body.classList.toggle('state-off', !isEnabled);
	} else {
		document.body.classList.remove('state-on');
		document.body.classList.remove('state-off');
	}
}

document.querySelector('.open-preferences').addEventListener('click', () => {
	webkit.messageHandlers.controller.postMessage('open-preferences');
});

document.querySelector('.open-help').addEventListener('click', () => {
	webkit.messageHandlers.controller.postMessage('open-help');
});


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.github.lxyscls.jvmjava.bytecode.constant;

import com.github.lxyscls.jvmjava.bytecode.base.NoOperandByteCode;
import com.github.lxyscls.jvmjava.runtimedata.Frame;

/**
 *
 * @author sk-xinyilong
 */
class AconstNull extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushRef(null);
    }
}

class IconstM1 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushInt(-1);
    }
}

class Iconst0 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushInt(0);
    }
}

class Iconst1 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushInt(1);
    }
}

class Iconst2 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushInt(2);
    }
}

class Iconst3 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushInt(3);
    }
}

class Iconst4 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushInt(4);
    }
}

class Iconst5 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushInt(5);
    }
}

class Lconst0 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushLong(0L);
    }
}

class Lconst1 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushLong(1L);
    }
}

class Fconst0 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushFloat(0.0F);
    }
}

class Fconst1 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushFloat(1.0F);
    }
}

class Fconst2 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushFloat(2.0F);
    }
}

class Dconst0 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushDouble(0.0);
    }
}

class Dconst1 extends NoOperandByteCode {
    @Override
    public void execute(Frame frame) {
        frame.getOperandStack().pushDouble(1.0);
    }
}


text:
package com.hawk.utility.example.jsr303.example1;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;

@Constraint(validatedBy = {StatusValidator.class})
@Documented
@Target( { ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Status {

}


text:
const Accepts = require('accepts');

module.exports = {
  searchDiagrams: function(request, reply) {
    const Diagram = request.server.collections(true).diagram;

    Diagram.find().then((results) => {
      reply.view('vis/diagrams.hbs',{
        diagrams: results
      })
    }).catch((err) => {
      reply(err);
    });
  },
  createDiagram: function(request, reply) {
    const Diagram = request.server.collections(true).diagram;
    const DiagramComponent = request.server.collections(true).diagram;
    var payloadDiagram = request.payload.diagram;
    var newDiagram = {
      name: payloadDiagram.name,
      components: payloadDiagram.components
    }

    Diagram.create(newDiagram).then((createdObject) => {
      request.log(['data-change','app'], {message: 'Diagram Created', object: createdObject});
      reply(createdObject);
    }).error((err)=>{
      reply(err);
    });
  },
  getDiagram: function(request, reply) {
    //Design to retrieve the shell of a diagram only.
    //Subsequent calls are really required to get the details
    const Diagram = request.server.collections(true).diagram;
    var viewParams = {
      layout: {
        fullwidth: true
      },
      diagramId: request.params.id
    }

    //If a component id was passed then pass this to the view (which will load and expand the component)
    if (request.query.componentId) {
      viewParams.componentId = request.query.componentId;
    }
    Promise.all([
      Diagram.find({id: request.params.id})
        .populate(['components'])
        .then((results) => {
        viewParams.diagram = results;
      })
    ]).then(() => {
      switch (Accepts(request.raw.req).type(['json','html'])) {
        case 'json':
          reply(viewParams);
        break;
        default:
          reply.view('vis/visbase.hbs',viewParams);
      }
    }).catch((err) => {
      reply(err);
    });
  },
  updateDiagram: function(request, reply) {
    const Diagram = request.server.collections(true).diagram;
    const DiagramComponent = request.server.collections(true).diagram;
    var payloadDiagram = request.payload.diagram;

    Diagram.find({id: request.params.id}).populate(['components']).then((dbDiagram) => {
      //Set the Diagram Properties
      dbDiagram.name = payloadDiagram.name;

      //Merge the components

      payloadDiagram.components.forEach((mergeComponent) => {
        //Find the component in the result
        var mergeTo = dbDiagram.components.find((dbDiagComponentLink) => {
          return dbDiagComponentLink.component == mergeComponent.component;
        });

        if (mergeTo) {
          //Update the properties for MergeTO
          if (mergeComponent.fixedX) {
            mergeTo.fixedX = mergeComponent.fixedX;
          }

          if (mergeComponent.fixedY) {
            mergeTo.fixedY = mergeComponent.fixedY;
          }

        } else {
          //Add the item into the component list
          serverDiagram.components.add({
            component: mergeComponent.component,
            fixedX: mergeComponent.fixedX,
            fixedY: mergeComponent.fixedY
          });
        }
      });

      //Now remove any Components on the server thate aren't on the payload
      //do this the safe way in case the collection updates
      var componentIdsInPayload = payloadDiagram.components.map((mergeComponent) => {
        return mergeComponent.component;
      });

      //Return an array of all items linking to Components not in the diagram
      var componentLinksToRemove = dbDiagram.components.filter((dbDiagComponentLink) => {
        return !(componentIdsInPayload.incudes(dbDiagComponentLink.component));
      });

      componentLinksToRemove.forEach((linkToRemove) => {
        dbDiagram.components.remove(linkToRemove.id);
      });

      //Dedupe

      dbDiagram.save().then(()=>{
        request.log(['data-change','app'], {message: 'Diagram Updated', object: dbDiagram.id});
        reply(dbDiagram);
      }).error((err) => {
        reply(err);
      });
    }).error((err)=>{
      reply(err);
    });
  },
  deleteDiagram: function(request, reply) {
    //Delete a diagram and all of its links
    const Diagram = request.server.collections(true).diagram;
    const DiagramComponent = request.server.collections(true).diagram;
    Promise.all([
      Diagram.destroy({id: request.params.id}),
      DiagramComponent.destroy({diagram: request.params.id})
    ]).then(() => {
      request.log(['data-change','app'], {message: 'Diagram Deleted', object: request.params.id});
      reply.redirect('/diagrams');
    }).catch((err) => {
      reply(err);
    });
  }
}


text:
import netaddr
from oslo_db import exception as db_exc
from oslo_utils import uuidutils
from sqlalchemy import orm

from neutron.api.rpc.agentnotifiers import metering_rpc_agent_api
from neutron.common import _deprecate
from neutron.common import constants
from neutron.db import _utils as db_utils
from neutron.db import api as db_api
from neutron.db import common_db_mixin as base_db
from neutron.db.models import l3 as l3_models
from neutron.db.models import metering as metering_models
from neutron.extensions import metering

_deprecate._moved_global('MeteringLabelRule', new_module=metering_models)
_deprecate._moved_global('MeteringLabel', new_module=metering_models)

class MeteringDbMixin(metering.MeteringPluginBase,
                      base_db.CommonDbMixin):

    def __init__(self):
        self.meter_rpc = metering_rpc_agent_api.MeteringAgentNotifyAPI()

    @staticmethod
    def _make_metering_label_dict(metering_label, fields=None):
        res = {'id': metering_label['id'],
               'name': metering_label['name'],
               'description': metering_label['description'],
               'shared': metering_label['shared'],
               'tenant_id': metering_label['tenant_id']}
        return db_utils.resource_fields(res, fields)

    def create_metering_label(self, context, metering_label):
        m = metering_label['metering_label']

        with db_api.context_manager.writer.using(context):
            metering_db = metering_models.MeteringLabel(
                id=uuidutils.generate_uuid(),
                description=m['description'],
                tenant_id=m['tenant_id'],
                name=m['name'],
                shared=m['shared'])
            context.session.add(metering_db)

        return self._make_metering_label_dict(metering_db)

    def delete_metering_label(self, context, label_id):
        with db_api.context_manager.writer.using(context):
            try:
                label = self._get_by_id(context,
                                        metering_models.MeteringLabel,
                                        label_id)
            except orm.exc.NoResultFound:
                raise metering.MeteringLabelNotFound(label_id=label_id)

            context.session.delete(label)

    def get_metering_label(self, context, label_id, fields=None):
        try:
            metering_label = self._get_by_id(context,
                                             metering_models.MeteringLabel,
                                             label_id)
        except orm.exc.NoResultFound:
            raise metering.MeteringLabelNotFound(label_id=label_id)

        return self._make_metering_label_dict(metering_label, fields)

    def get_metering_labels(self, context, filters=None, fields=None,
                            sorts=None, limit=None, marker=None,
                            page_reverse=False):
        marker_obj = self._get_marker_obj(context, 'metering_labels', limit,
                                          marker)
        return self._get_collection(context, metering_models.MeteringLabel,
                                    self._make_metering_label_dict,
                                    filters=filters, fields=fields,
                                    sorts=sorts,
                                    limit=limit,
                                    marker_obj=marker_obj,
                                    page_reverse=page_reverse)

    @staticmethod
    def _make_metering_label_rule_dict(metering_label_rule, fields=None):
        res = {'id': metering_label_rule['id'],
               'metering_label_id': metering_label_rule['metering_label_id'],
               'direction': metering_label_rule['direction'],
               'remote_ip_prefix': metering_label_rule['remote_ip_prefix'],
               'excluded': metering_label_rule['excluded']}
        return db_utils.resource_fields(res, fields)

    def get_metering_label_rules(self, context, filters=None, fields=None,
                                 sorts=None, limit=None, marker=None,
                                 page_reverse=False):
        marker_obj = self._get_marker_obj(context, 'metering_label_rules',
                                          limit, marker)

        return self._get_collection(context, metering_models.MeteringLabelRule,
                                    self._make_metering_label_rule_dict,
                                    filters=filters, fields=fields,
                                    sorts=sorts,
                                    limit=limit,
                                    marker_obj=marker_obj,
                                    page_reverse=page_reverse)

    def get_metering_label_rule(self, context, rule_id, fields=None):
        try:
            metering_label_rule = self._get_by_id(
                context, metering_models.MeteringLabelRule, rule_id)
        except orm.exc.NoResultFound:
            raise metering.MeteringLabelRuleNotFound(rule_id=rule_id)

        return self._make_metering_label_rule_dict(metering_label_rule, fields)

    def _validate_cidr(self, context, label_id, remote_ip_prefix,
                       direction, excluded):
        r_ips = self.get_metering_label_rules(context,
                                              filters={'metering_label_id':
                                                       [label_id],
                                                       'direction':
                                                       [direction],
                                                       'excluded':
                                                       [excluded]},
                                              fields=['remote_ip_prefix'])

        cidrs = [r['remote_ip_prefix'] for r in r_ips]
        new_cidr_ipset = netaddr.IPSet([remote_ip_prefix])
        if (netaddr.IPSet(cidrs) & new_cidr_ipset):
            raise metering.MeteringLabelRuleOverlaps(
                remote_ip_prefix=remote_ip_prefix)

    def create_metering_label_rule(self, context, metering_label_rule):
        m = metering_label_rule['metering_label_rule']
        try:
            with db_api.context_manager.writer.using(context):
                label_id = m['metering_label_id']
                ip_prefix = m['remote_ip_prefix']
                direction = m['direction']
                excluded = m['excluded']

                self._validate_cidr(context, label_id, ip_prefix, direction,
                                    excluded)
                metering_db = metering_models.MeteringLabelRule(
                    id=uuidutils.generate_uuid(),
                    metering_label_id=label_id,
                    direction=direction,
                    excluded=m['excluded'],
                    remote_ip_prefix=ip_prefix)
                context.session.add(metering_db)

        except db_exc.DBReferenceError:
            raise metering.MeteringLabelNotFound(label_id=label_id)

        return self._make_metering_label_rule_dict(metering_db)

    def delete_metering_label_rule(self, context, rule_id):
        with db_api.context_manager.writer.using(context):
            try:
                rule = self._get_by_id(context,
                                       metering_models.MeteringLabelRule,
                                       rule_id)
            except orm.exc.NoResultFound:
                raise metering.MeteringLabelRuleNotFound(rule_id=rule_id)
            context.session.delete(rule)

        return self._make_metering_label_rule_dict(rule)

    def _get_metering_rules_dict(self, metering_label):
        rules = []
        for rule in metering_label.rules:
            rule_dict = self._make_metering_label_rule_dict(rule)
            rules.append(rule_dict)

        return rules

    def _make_router_dict(self, router):
        res = {'id': router['id'],
               'name': router['name'],
               'tenant_id': router['tenant_id'],
               'admin_state_up': router['admin_state_up'],
               'status': router['status'],
               'gw_port_id': router['gw_port_id'],
               constants.METERING_LABEL_KEY: []}

        return res

    def _process_sync_metering_data(self, context, labels):
        all_routers = None

        routers_dict = {}
        for label in labels:
            if label.shared:
                if not all_routers:
                    all_routers = self._get_collection_query(context,
                                                             l3_models.Router)
                routers = all_routers
            else:
                routers = label.routers

            for router in routers:
                router_dict = routers_dict.get(
                    router['id'],
                    self._make_router_dict(router))

                rules = self._get_metering_rules_dict(label)

                data = {'id': label['id'], 'rules': rules}
                router_dict[constants.METERING_LABEL_KEY].append(data)

                routers_dict[router['id']] = router_dict

        return list(routers_dict.values())

    def get_sync_data_for_rule(self, context, rule):
        label = context.session.query(
            metering_models.MeteringLabel).get(
                rule['metering_label_id'])

        if label.shared:
            routers = self._get_collection_query(context, l3_models.Router)
        else:
            routers = label.routers

        routers_dict = {}
        for router in routers:
            router_dict = routers_dict.get(router['id'],
                                           self._make_router_dict(router))
            data = {'id': label['id'], 'rule': rule}
            router_dict[constants.METERING_LABEL_KEY].append(data)
            routers_dict[router['id']] = router_dict

        return list(routers_dict.values())

    def get_sync_data_metering(self, context, label_id=None, router_ids=None):
        labels = context.session.query(metering_models.MeteringLabel)

        if label_id:
            labels = labels.filter(
                metering_models.MeteringLabel.id == label_id)
        elif router_ids:
            labels = (labels.join(metering_models.MeteringLabel.routers).
                      filter(l3_models.Router.id.in_(router_ids)))

        return self._process_sync_metering_data(context, labels)

_deprecate._MovedGlobals()


text:
using UnityEngine;
using System.Collections;

public class PlatformParent : MonoBehaviour
{

    // FPS KIT [www.armedunity.com]

    public Transform platform;
    private Transform player;
    private CharacterController cc;

    void OnTriggerEnter(Collider other)
    {
        if (player) return;

        if (other.CompareTag("Player"))
        {
            player = other.transform;
            player.transform.parent = platform.transform;
            cc = player.GetComponent<CharacterController>();
            StartCoroutine(CheckStatus());
        }
    }

    IEnumerator CheckStatus()
    {

        while (player)
        {
            if (!cc.isGrounded)
            {
                player.parent = null;
                player = null;
                cc = null;
            }
            yield return null;
        }
    }

    //void OnTriggerExit ( Collider hit  ){
    //	if(player) player.parent = null;
    //}
}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

001
018
019package org.apache.hadoop.mapred.nativetask.serde;
020
021import java.io.DataInput;
022import java.io.DataOutput;
023import java.io.IOException;
024import org.apache.hadoop.classification.InterfaceAudience;
025import org.apache.hadoop.classification.InterfaceStability;
026
027/**
028 * an INativeSerializer serializes and deserializes data transferred between
029 * Java and native. {@link DefaultSerializer} provides default implementations.
030 *
031 * Note: if you implemented your customized NativeSerializer instead of DefaultSerializer,
032 * you have to make sure the native side can serialize it correctly.
033 *
034 */
035@InterfaceAudience.Public
036@InterfaceStability.Evolving
037public interface INativeSerializer<T> {
038
039  /**
040   * get length of data to be serialized. If the data length is already known (like IntWritable)
041   * and could immediately be returned from this method, it is good chance to implement customized
042   * NativeSerializer for efficiency
043   */
044  public int getLength(T w) throws IOException;
045
046  public void serialize(T w, DataOutput out) throws IOException;
047
048  public void deserialize(DataInput in, int length, T w) throws IOException;
049}


text:
namespace MassTransit.Configuration
{
    using QuartzIntegration;
    using Scheduling;

    public class ScheduleMessageConsumerDefinition :
        ConsumerDefinition<ScheduleMessageConsumer>
    {
        readonly QuartzEndpointDefinition _endpointDefinition;

        public ScheduleMessageConsumerDefinition(QuartzEndpointDefinition endpointDefinition)
        {
            _endpointDefinition = endpointDefinition;

            EndpointDefinition = endpointDefinition;
        }

        protected override void ConfigureConsumer(IReceiveEndpointConfigurator endpointConfigurator,
            IConsumerConfigurator<ScheduleMessageConsumer> consumerConfigurator)
        {
            endpointConfigurator.UseMessageRetry(r => r.Interval(5, 250));

            consumerConfigurator.Message<ScheduleMessage>(m => m.UsePartitioner(_endpointDefinition.Partition, p => p.Message.CorrelationId));
        }
    }
}


text:
package com.intellij.application.options;

import com.intellij.application.options.codeStyle.CodeStyleSchemesModel;
import com.intellij.application.options.codeStyle.excludedFiles.ExcludedFilesList;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.ex.ConfigurableWrapper;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.codeStyle.CodeStyleConstraints;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.JBColor;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.GradientViewport;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBTabbedPane;
import com.intellij.ui.components.fields.CommaSeparatedIntegersField;
import com.intellij.ui.components.fields.IntegerField;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class GeneralCodeStylePanel extends CodeStyleAbstractPanel {
  @SuppressWarnings("UnusedDeclaration")
  private static final Logger LOG = Logger.getInstance(GeneralCodeStylePanel.class);
  private List<GeneralCodeStyleOptionsProvider> myAdditionalOptions;

  private IntegerField myRightMarginField;

  private ComboBox myLineSeparatorCombo;
  private JPanel myPanel;
  private JBCheckBox myCbWrapWhenTypingReachesRightMargin;
  private JCheckBox myEnableFormatterTags;
  private JTextField myFormatterOnTagField;
  private JTextField myFormatterOffTagField;
  private JCheckBox myAcceptRegularExpressionsCheckBox;
  private JBLabel myFormatterOffLabel;
  private JBLabel myFormatterOnLabel;
  private JPanel myMarkerOptionsPanel;
  private JPanel myAdditionalSettingsPanel;
  private JCheckBox myAutodetectIndentsBox;
  private CommaSeparatedIntegersField myVisualGuides;
  private JBLabel myVisualGuidesHint;
  private JBLabel myLineSeparatorHint;
  private JBLabel myVisualGuidesLabel;
  private ExcludedFilesList myExcludedFilesList;
  private JPanel myExcludedFilesPanel;
  private JPanel myToolbarPanel;
  private JBTabbedPane myTabbedPane;
  private final JScrollPane myScrollPane;
  private static int ourSelectedTabIndex = -1;

  public GeneralCodeStylePanel(CodeStyleSettings settings) {
    super(settings);

    //noinspection unchecked
    myLineSeparatorCombo.addItem(getSystemDependantString());
    //noinspection unchecked
    myLineSeparatorCombo.addItem(getUnixString());
    //noinspection unchecked
    myLineSeparatorCombo.addItem(getWindowsString());
    //noinspection unchecked
    myLineSeparatorCombo.addItem(getMacintoshString());
    addPanelToWatch(myPanel);

    myRightMarginField.setDefaultValue(settings.getDefaultRightMargin());

    myEnableFormatterTags.addActionListener(__ -> {
      boolean tagsEnabled = myEnableFormatterTags.isSelected();
      setFormatterTagControlsEnabled(tagsEnabled);
    });

    myAutodetectIndentsBox.setBorder(JBUI.Borders.emptyTop(10));

    myPanel.setBorder(JBUI.Borders.empty(0, 10));
    myScrollPane = ScrollPaneFactory.createScrollPane(null, true);
    myScrollPane.setViewport(new GradientViewport(myPanel, JBUI.insetsTop(5), true));

    myAdditionalSettingsPanel.setLayout(new VerticalFlowLayout(true, true));
    updateGeneralOptionsPanel();

    myVisualGuidesLabel.setText(ApplicationBundle.message("settings.code.style.visual.guides") + ":");
    myVisualGuidesHint.setForeground(JBColor.GRAY);
    myVisualGuidesHint.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL));
    myLineSeparatorHint.setForeground(JBColor.GRAY);
    myLineSeparatorHint.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL));

    myExcludedFilesList.initModel();
    myToolbarPanel.add(myExcludedFilesList.getDecorator().createPanel());
    myExcludedFilesPanel
      .setBorder(IdeBorderFactory.createTitledBorder(ApplicationBundle.message("settings.code.style.general.excluded.files")));
    if (ourSelectedTabIndex >= 0) {
      myTabbedPane.setSelectedIndex(ourSelectedTabIndex);
    }
    myTabbedPane.addChangeListener(__ -> {
      //noinspection AssignmentToStaticFieldFromInstanceMethod
      ourSelectedTabIndex = myTabbedPane.getSelectedIndex();
    });
    GeneralCodeStyleOptionsProviderEP.EP_NAME.addExtensionPointListener(
      new ExtensionPointListener<GeneralCodeStyleOptionsProviderEP>() {
        @Override
        public void extensionAdded(@NotNull GeneralCodeStyleOptionsProviderEP extension,
                                   @NotNull PluginDescriptor pluginDescriptor) {
          updateGeneralOptionsPanel();
        }

        @Override
        public void extensionRemoved(@NotNull GeneralCodeStyleOptionsProviderEP extension,
                                     @NotNull PluginDescriptor pluginDescriptor) {
          updateGeneralOptionsPanel();
        }
      }, this);
  }

  private void updateGeneralOptionsPanel() {
    myAdditionalSettingsPanel.removeAll();
    myAdditionalOptions = ConfigurableWrapper.createConfigurables(GeneralCodeStyleOptionsProviderEP.EP_NAME);
    for (GeneralCodeStyleOptionsProvider provider : myAdditionalOptions) {
      JComponent generalSettingsComponent = provider.createComponent();
      if (generalSettingsComponent != null) {
        myAdditionalSettingsPanel.add(Box.createRigidArea(JBUI.size(0, 5)));
        myAdditionalSettingsPanel.add(generalSettingsComponent);
      }
    }
  }

  @Override
  protected int getRightMargin() {
    return myRightMarginField.getValue();
  }

  @Override
  @NotNull
  protected FileType getFileType() {
    return FileTypes.PLAIN_TEXT;
  }

  @Override
  protected String getPreviewText() {
    return null;
  }

  @Override
  public void apply(CodeStyleSettings settings) throws ConfigurationException {
    myVisualGuides.validateContent();
    myRightMarginField.validateContent();
    settings.setDefaultSoftMargins(myVisualGuides.getValue());
    myExcludedFilesList.apply(settings);

    settings.LINE_SEPARATOR = getSelectedLineSeparator();

    settings.setDefaultRightMargin(getRightMargin());
    settings.WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN = myCbWrapWhenTypingReachesRightMargin.isSelected();

    settings.FORMATTER_TAGS_ENABLED = myEnableFormatterTags.isSelected();
    settings.FORMATTER_TAGS_ACCEPT_REGEXP = myAcceptRegularExpressionsCheckBox.isSelected();

    settings.FORMATTER_OFF_TAG = getTagText(myFormatterOffTagField, settings.FORMATTER_OFF_TAG);
    settings.setFormatterOffPattern(compilePattern(settings, myFormatterOffTagField, settings.FORMATTER_OFF_TAG));

    settings.FORMATTER_ON_TAG = getTagText(myFormatterOnTagField, settings.FORMATTER_ON_TAG);
    settings.setFormatterOnPattern(compilePattern(settings, myFormatterOnTagField, settings.FORMATTER_ON_TAG));

    settings.AUTODETECT_INDENTS = myAutodetectIndentsBox.isSelected();

    for (GeneralCodeStyleOptionsProvider option : myAdditionalOptions) {
      option.apply(settings);
    }
  }

  private void createUIComponents() {
    myRightMarginField = new IntegerField(ApplicationBundle.message("editbox.right.margin.columns"), 0, CodeStyleConstraints.MAX_RIGHT_MARGIN);
    myVisualGuides = new CommaSeparatedIntegersField(ApplicationBundle.message("settings.code.style.visual.guides"), 0, CodeStyleConstraints.MAX_RIGHT_MARGIN, "Optional");
    myExcludedFilesList = new ExcludedFilesList();
  }

  @Nullable
  private static Pattern compilePattern(CodeStyleSettings settings, JTextField field, String patternText) {
    try {
      return Pattern.compile(patternText);
    }
    catch (PatternSyntaxException pse) {
      settings.FORMATTER_TAGS_ACCEPT_REGEXP = false;
      showError(field, ApplicationBundle.message("settings.code.style.general.formatter.marker.invalid.regexp"));
      return null;
    }
  }

  private static String getTagText(JTextField field, String defaultValue) {
    String fieldText = field.getText();
    if (StringUtil.isEmpty(field.getText())) {
      return defaultValue;
    }
    return fieldText;
  }

  @Nullable
  private String getSelectedLineSeparator() {
    if (getUnixString().equals(myLineSeparatorCombo.getSelectedItem())) {
      return "\n";
    }
    if (getMacintoshString().equals(myLineSeparatorCombo.getSelectedItem())) {
      return "\r";
    }
    if (getWindowsString().equals(myLineSeparatorCombo.getSelectedItem())) {
      return "\r\n";
    }
    return null;
  }

  @Override
  public boolean isModified(CodeStyleSettings settings) {
    if (!myVisualGuides.getValue().equals(settings.getDefaultSoftMargins())) return true;

    if (myExcludedFilesList.isModified(settings)) return true;

    if (!Comparing.equal(getSelectedLineSeparator(), settings.LINE_SEPARATOR)) {
      return true;
    }

    if (settings.WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN ^ myCbWrapWhenTypingReachesRightMargin.isSelected()) {
      return true;
    }

    if (getRightMargin() != settings.getDefaultRightMargin()) return true;

    if (myEnableFormatterTags.isSelected()) {
      if (
        !settings.FORMATTER_TAGS_ENABLED ||
        settings.FORMATTER_TAGS_ACCEPT_REGEXP != myAcceptRegularExpressionsCheckBox.isSelected() ||
        !StringUtil.equals(myFormatterOffTagField.getText(), settings.FORMATTER_OFF_TAG) ||
        !StringUtil.equals(myFormatterOnTagField.getText(), settings.FORMATTER_ON_TAG)) return true;
    }
    else {
      if (settings.FORMATTER_TAGS_ENABLED) return true;
    }

    for (GeneralCodeStyleOptionsProvider option : myAdditionalOptions) {
      if (option.isModified(settings)) return true;
    }

    return settings.AUTODETECT_INDENTS != myAutodetectIndentsBox.isSelected();
  }

  @Override
  public JComponent getPanel() {
    return myScrollPane;
  }

  @Override
  protected void resetImpl(final CodeStyleSettings settings) {
    myVisualGuides.setValue(settings.getDefaultSoftMargins());

    myExcludedFilesList.reset(settings);

    String lineSeparator = settings.LINE_SEPARATOR;
    if ("\n".equals(lineSeparator)) {
      myLineSeparatorCombo.setSelectedItem(getUnixString());
    }
    else if ("\r\n".equals(lineSeparator)) {
      myLineSeparatorCombo.setSelectedItem(getWindowsString());
    }
    else if ("\r".equals(lineSeparator)) {
      myLineSeparatorCombo.setSelectedItem(getMacintoshString());
    }
    else {
      myLineSeparatorCombo.setSelectedItem(getSystemDependantString());
    }

    myRightMarginField.setValue(settings.getDefaultRightMargin());
    myCbWrapWhenTypingReachesRightMargin.setSelected(settings.WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN);

    myAcceptRegularExpressionsCheckBox.setSelected(settings.FORMATTER_TAGS_ACCEPT_REGEXP);
    myEnableFormatterTags.setSelected(settings.FORMATTER_TAGS_ENABLED);

    myFormatterOnTagField.setText(settings.FORMATTER_ON_TAG);
    myFormatterOffTagField.setText(settings.FORMATTER_OFF_TAG);

    setFormatterTagControlsEnabled(settings.FORMATTER_TAGS_ENABLED);

    myAutodetectIndentsBox.setSelected(settings.AUTODETECT_INDENTS);

    for (GeneralCodeStyleOptionsProvider option : myAdditionalOptions) {
      option.reset(settings);
    }
  }

  private void setFormatterTagControlsEnabled(boolean isEnabled) {
    myFormatterOffTagField.setEnabled(isEnabled);
    myFormatterOnTagField.setEnabled(isEnabled);
    myAcceptRegularExpressionsCheckBox.setEnabled(isEnabled);
    myFormatterOffLabel.setEnabled(isEnabled);
    myFormatterOnLabel.setEnabled(isEnabled);
    myMarkerOptionsPanel.setEnabled(isEnabled);
  }

  @Override
  protected EditorHighlighter createHighlighter(final EditorColorsScheme scheme) {
    return EditorHighlighterFactory.getInstance().createEditorHighlighter(getFileType(), scheme, null);
  }

  @Override
  public Language getDefaultLanguage() {
    return null;
  }

  private static void showError(final JTextField field, final String message) {
    BalloonBuilder balloonBuilder = JBPopupFactory.getInstance()
      .createHtmlTextBalloonBuilder(message, MessageType.ERROR, null);
    balloonBuilder.setFadeoutTime(1500);
    final Balloon balloon = balloonBuilder.createBalloon();
    final Rectangle rect = field.getBounds();
    final Point p = new Point(0, rect.height);
    final RelativePoint point = new RelativePoint(field, p);
    balloon.show(point, Balloon.Position.below);
    Disposer.register(ProjectManager.getInstance().getDefaultProject(), balloon);
  }

  @Override
  public void setModel(@NotNull CodeStyleSchemesModel model) {
    super.setModel(model);
    myExcludedFilesList.setSchemesModel(model);
  }

  @Override
  public void dispose() {
    for (GeneralCodeStyleOptionsProvider option : myAdditionalOptions) {
      option.disposeUIResources();
    }
    super.dispose();
  }

  private static String getSystemDependantString() {
    return ApplicationBundle.message("combobox.crlf.system.dependent");
  }

  private static String getUnixString() {
    return ApplicationBundle.message("combobox.crlf.unix");
  }

  private static String getWindowsString() {
    return ApplicationBundle.message("combobox.crlf.windows");
  }

  private static String getMacintoshString() {
    return ApplicationBundle.message("combobox.crlf.mac");
  }
}


text:
//
//  BFPushNotificationHandler.h
//  OpenShop
//
//  Created by Petr Škorňok on 13.01.16.
//  Copyright © 2016 Business-Factory. All rights reserved.
//

@import Foundation;

@interface BFPushNotificationHandler : NSObject

/**
 * If the device is not registered for the remote notifications
 * present the BFPushNotificationViewController.
 */
+ (void)tryToRegisterForRemoteNotifications;
/**
 * Asks for permissions for push notifications.
 */
+ (void)askForPermissions;
/**
 * Registers device APNS ID on server.
 */
+ (void)registerDeviceWithApnsID:(nullable NSString *)apnsID;
/**
 * Handle remote notification if the userInfo dictionary is provided.
 */
+ (void)handleRemoteNotificationWithUserInfo:(nonnull NSDictionary *)userInfo;
/**
 * Handle remote notification if URL is provided.
 */
+ (void)handleRemoteNotificationWithURL:(nonnull NSURL *)url;
/**
 * Handle remote notification if targetShop, targetType and targetID are provided.
 */
+ (void)handleRemoteNotificationWithTargetShop:(nonnull NSNumber *)shopLanguageCode targetType:(BFLinkType)targetType targetID:(nonnull NSNumber *)targetID userInfo:(nullable NSDictionary *)userInfo;
/**
 * Handle remote notification banner string is provided.
 * Banner string format is specified as "targetShop:targetType:targetID" string.
 */
+ (void)handleRemoteNotificationWithBannerString:(nonnull NSString *)bannerString userInfo:(nullable NSDictionary *)userInfo;

@end


text:
class HomeController < ApplicationController

  def index
    render text: "Hello", layout: true
  end

end


text:
using System.Collections.Generic;
using MatterHackers.Agg.UI;
using MatterHackers.MatterControl.PartPreviewWindow;

namespace MatterHackers.MatterControl.DesignTools
{
	public interface IEditorDraw
	{
		void DrawEditor(InteractionLayer interactionLayer, List<Object3DView> transparentMeshes, DrawEventArgs e, ref bool suppressNormalDraw);
	}
}


text:
A Cordova plugin for uploading builds to the app store.

## Installation

This plugin can be installed from Github

```sh
cordova plugin add https://github.com/cjpearson/cordova-package-upload --save
```

It also requires the [Deliver tool](https://github.com/fastlane/deliver)

```sh
sudo gem install deliver
```

## Quick Start

To upload a build add --upload to the cordova build command.

```sh
cordova build ios --device --release --upload
```

Builds also must target a device and use a distribution provisioning profile.

## License

MIT


text:
#ifndef _JABBER_ELEMENT_H
#define _JABBER_ELEMENT_H

#include <String.h>

class JabberElement {
public:
					JabberElement();
					~JabberElement();

	void			SetName(const BString& name);
	BString			GetName() const;

	void			SetData(const BString& data);
	BString			GetData() const;

	void			SetAttr(const char** attr);
	const char **	GetAttr() const;

	int32			GetAttrCount() const;

private:
	BString			fName;
	BString			fData;
	char **			fAttr;
	int32			fAttrCount;

	void			Free();
};

#endif	// _JABBER_ELEMENT_H


text:
<?php
namespace FormKit;
use InvalidArgumentException;
use Exception;

/**
 * Form Widget Factory class
 */
class FormKit
{

    /**
     * @var bool flag to enable/disable stylesheets.
     */
    static $useStylesheet    = true;

    /**
     * @var bool flag to enable/disable javascripts.
     */
    static $useJavascript     = true;

    /**
     * @var string asset path
     *
     * @see setAssetPath method
     */
    static $assetPath;

    static function text( $name, $attributes = array() )
    {
        return new Widget\TextInput( $name , $attributes );
    }

    static function checkbox( $name, $attributes = array() )
    {
        return new Widget\CheckboxInput( $name , $attributes );
    }

    static function select($name, $attributes = array() )
    {
        return new Widget\SelectInput( $name, $attributes );
    }

    /**
     * So that we can create widgets dynamically:
     *
     *      $select = FormKit::select( 'role', array( 'options' => ... ) );
     *      $canvas = FormKit::canvas( 'canvas', array( 'options' => ... ) );
     *      $label = FormKit::label( null , array( 'options' => ... ) );
     *
     */
    static function __callStatic($name,$arguments) {
        $class = 'FormKit\Widget\\' . ucfirst($name);
        if( class_exists($class,true) ) {
            return new $class($arguments[0],$arguments[1]);
        }
        $class2 = $class . 'Input';
        if( class_exists($class2, true) ) {
            return new $class2(@$arguments[0],@$arguments[1]);
        }
        throw new InvalidArgumentException( "both $class or $class2 class not found." );
    }

    /**
     * Configure global asset path
     *
     * FormKit\Widget\BaseWidget::setAssetPath('/public/assets');
     *
     * @param string $path
     */
    static function setAssetPath($path)
    {
        static::$assetPath = $path;
    }

    static function useStylesheet($bool = true) {
        static::$useStylesheet = $bool;
    }

    static function useJavascript($bool = true) {
        static::$useJavascript = $bool;
    }

}


text:
<?php
/**
 * Network Plugins administration panel.
 *
 * @package WordPress
 * @subpackage Multisite
 * @since 3.1.0
 */

/** Load WordPress Administration Bootstrap */
require_once( './admin.php' );

if ( ! is_multisite() )
	wp_die( __( 'Multisite support is not enabled.' ) );

require( '../plugins.php' );


text:
package org.drools.workbench.models.testscenarios.shared;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class FixtureList
        implements
        List<Fixture>,
        Fixture {

    private static final long serialVersionUID = 510l;

    private ArrayList<Fixture> list = new ArrayList<Fixture>();

    public FactData getFirstFactData() {
        for ( Fixture fixture : this ) {
            if ( fixture instanceof FactData ) {
                return (FactData) fixture;
            }
        }
        return null;
    }

    public boolean isFieldNameInUse( final String fieldName ) {
        for ( Fixture fixture : this ) {
            if ( fixture instanceof FactData && ( (FactData) fixture ).isFieldNameInUse( fieldName ) ) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public boolean contains( final Object o ) {
        return list.contains( o );
    }

    @Override
    public Iterator<Fixture> iterator() {
        return list.iterator();
    }

    @Override
    public Object[] toArray() {
        return list.toArray();
    }

    @Override
    public <T> T[] toArray( T[] ts ) {
        return list.toArray( ts );
    }

    @Override
    public boolean add( final Fixture fixture ) {
        return list.add( fixture );
    }

    @Override
    public boolean remove( final Object o ) {
        return list.remove( o );
    }

    @Override
    public boolean containsAll( final Collection<?> objects ) {
        return list.containsAll( objects );
    }

    @Override
    public boolean addAll( final Collection<? extends Fixture> fixtures ) {
        return list.addAll( fixtures );
    }

    @Override
    public boolean addAll( final int i,
                           final Collection<? extends Fixture> fixtures ) {
        return list.addAll( i, fixtures );
    }

    @Override
    public boolean removeAll( final Collection<?> objects ) {
        return list.removeAll( objects );
    }

    @Override
    public boolean retainAll( final Collection<?> objects ) {
        return list.retainAll( objects );
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public Fixture get( final int i ) {
        return list.get( i );
    }

    @Override
    public Fixture set( final int i,
                        final Fixture fixture ) {
        return list.set( i, fixture );
    }

    @Override
    public void add( final int i,
                     final Fixture fixture ) {
        list.add( i, fixture );
    }

    @Override
    public Fixture remove( final int i ) {
        return list.remove( i );
    }

    @Override
    public int indexOf( final Object o ) {
        return list.indexOf( o );
    }

    @Override
    public int lastIndexOf( final Object o ) {
        return list.lastIndexOf( o );
    }

    @Override
    public ListIterator<Fixture> listIterator() {
        return list.listIterator();
    }

    @Override
    public ListIterator<Fixture> listIterator( final int i ) {
        return list.listIterator( i );
    }

    @Override
    public List<Fixture> subList( final int i,
                                  final int i1 ) {
        return list.subList( i, i1 );
    }
}


text:
'use strict'

const path = require('path')
const PLUGIN_PATH = require('../util/path').PLUGIN_PATH
const info = require(path.join(PLUGIN_PATH, 'package.json'))
const dependencies = info.dependencies

module.exports = function (program) {
  for (var name in dependencies) {
    if (/^xdc-(\S+)-command$/.test(name)) {
      const commandName = name.replace(/^xdc-(\S+)-command$/, '$1')
      const description = require(path.join(name, 'package.json')).description
      const action = (_name => () => require(_name)(program))(name)
      const command = program.command(commandName)

      command.allowUnknownOption()
      command.description(description)
      try {
        require(path.join(name, 'options'))(command)
      } catch (_) {
        // options.js 文件不存在则不处理
      }
      command.action(action)
    }
  }
}


text:
*description:*

> The Circular 'root' is very small. It contains a few methods to load the modules, manage a queue, and initialize itself.
>
> By default, Circular.init() is called on `$(document).ready()`. You can call it anytime earlier with configuration options (eg `Circular.init({debug:true})`); but it will still wait on `$(document).ready()` before processing the document. After initializing, it checks if it has an engine and starts that.
>
> That is all. All the real work happens inside modules: the **@engine** module processes the document, passes the results to the **@registry** module, which notifies the **@watchdog** module. If the watchdog sees changes happening, it waits until queue is finished, processes the changes and passes them back to the @engine. And so it cycles.
>
> As these cycles happen, you'd better not touch the document yourself, or you might end up in unpredictable situations. Instead, *Circular.queue()* your activities so they will be executed in between cycles, while Circular is sure to be idle.
>

----

##Circular core methods##

*internal methods not documented*

----

###Circular.init({options})

*example:*

  Circular.init({
	  debug : true,
	  foo   : 'bar'
  })

*description:*

> Call this before $(document).ready(), or disable `autoinit` and call it later (see config below). All modules have config options, and they are all read from this single init() call. For example, the 'debug' option in the example is provided by the @debug module.

----

###Circular.queue(func)

*example:*

	Circular.queue(function() { rewriteFooStuff('#foo'); });
	Circular.queue(function() { alert('done!'); });

*description:*

> Add `func` to the queue. Methods in the queue are executed one by one, first in, first out. Circulars 'cycle' uses the queue, so adding your own method here ensures that Circular is idle when your method executes.

----

##Circular core classes##

----

###new CircularModule({def})

*example:*

	new CircularModule({
		name	: 'alert',
		in		: function(attr,node,props) {
			alert('in: '+attr.value)
		},
		out		: function(attr,node,props) {
			alert('out: '+attr.value)
		}
	});

*description:*

> A Circular module becomes an integral part of Circular after it initializes. A module named 'foo' by default represents an attribute named 'cc-foo' and can provide methods and properties accessible via Circular expressions like `{{@foo.bar}}``, or in vanilla javascript as `Circular.foo.bar`.
>
> Circular modules should be created before Circular initializes, and the creation order is important.

*methods:*

	in		: function(attr,node,props)
	out		: function(attr,node,props)

*arguments:*

- **attr:** (*type:* object)
	an object describing the attribute that triggered this method. see the
	registry module for a detailed description of its format

- **node:** (*type:* html dom node)
	the node containing the attribute

- **props:** (*type:* object)
	'live' properties of the node as they are being processed

*return value:*

	boolean false or undefined

*description:*

> While Circular processes the document, it looks at all attributes of all nodes to see if they contain expression and/or refer to a module. The attributes are sorted:  module attributes first, in the order in which they were created, than any other attributes. The order is relevant, because some attributes (like cc-context) can influence others.
>
> Circular then loops the attributes in that order and execute the `in()` method.
>
> If in() does not return false, Circular will continue with the next attribute, and traverse into the node, depth-first, to process its children. Eventually it will bubble up and encounter your node again. It will process the same attributes as it did on the way in, but now in reverse order, and execute the `out()` method.
>
> If in() does return (real boolean) false, Circular will not process the remaining attributes and not traverse into the node. It will loop the attributes it already processed in reverse order and execute `out()`.
>
> There is only one instance of your module, which may handle several nodes in the document. If you need to remember data related to the node, for example to reuse on the way out(), be sure to relate the node to that data. `$(node).data()` is your friend.

----

----

##Circular core config##

----

*example:*

	Circular.init({
		attrprefix	: 'kp-',
		dataprefix	: 'data-',
		autoinit	: true
	})

*arguments:*

- **attrprefix:** (*type:* string, *default:* 'cc-')

The string to prefix to a module name when used as an attribute. If a module is named 'foo', its attribute will be 'cc-foo'.

- **attrprefix:** (*type:* string, *default:* 'data-')

The string to prefix to an custom attribute to make it valid html5

- **autoinit:** (*type:* boolean, *default:* true)

Wether to start Circular on `$(document).ready()` by itself. Example:

	Circular.config.autoinit=false;
	$(document).on('kp-loaded',function() {
	  Circular.init({attrprefix:'kp-'})
	});


text: export default from './LogMonitor';


text:
/**
 * tests/api/v1/profiles/getWithLimit.js
 */
'use strict';
const tu = require('../../../testUtils');
const u = require('./utils');
const getWithLimit = require('../common/getWithLimit.js').getWithLimit;
const Profile = tu.db.Profile;
const path = '/v1/profiles';

describe('tests/api/v1/profiles/getWithLimit.js >', () => {
  const modelList = [];

  before((done) => {
    const obj = {
      name: `${tu.namePrefix}testProfile`,
    };
    for (let i = 0; i < 10; i++) {
      const toCreate = JSON.parse(JSON.stringify(obj));
      toCreate.name += `-limitTest${i}-${i % 2 ? 'odd' : 'even'}`;
      modelList.push(toCreate);
    }

    Profile.bulkCreate(modelList)
    .then(() => done())
    .catch(done);
  });

  after(u.forceDelete);
  after(tu.forceDeleteUser);

  const skipWildcards = true;
  getWithLimit(path, skipWildcards);
});