text:
import functools
import os
import re
import urlparse

import webob
from xml.dom import minidom

from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova.compute import task_states
from nova.compute import utils as compute_utils
from nova.compute import vm_states
from nova import exception
from nova.openstack.common import cfg
from nova.openstack.common import log as logging
from nova import quota

osapi_opts = [
    cfg.IntOpt('osapi_max_limit',
               default=1000,
               help='the maximum number of items returned in a single '
                    'response from a collection resource'),
    cfg.StrOpt('osapi_compute_link_prefix',
               default=None,
               help='Base URL that will be presented to users in links '
                    'to the OpenStack Compute API'),
    cfg.StrOpt('osapi_glance_link_prefix',
               default=None,
               help='Base URL that will be presented to users in links '
                    'to glance resources'),
]
CONF = cfg.CONF
CONF.register_opts(osapi_opts)

LOG = logging.getLogger(__name__)
QUOTAS = quota.QUOTAS

XML_NS_V11 = 'http://docs.openstack.org/compute/api/v1.1'

_STATE_MAP = {
    vm_states.ACTIVE: {
        'default': 'ACTIVE',
        task_states.REBOOTING: 'REBOOT',
        task_states.REBOOTING_HARD: 'HARD_REBOOT',
        task_states.UPDATING_PASSWORD: 'PASSWORD',
        task_states.REBUILDING: 'REBUILD',
        task_states.REBUILD_BLOCK_DEVICE_MAPPING: 'REBUILD',
        task_states.REBUILD_SPAWNING: 'REBUILD',
        task_states.MIGRATING: 'MIGRATING',
        task_states.RESIZE_PREP: 'RESIZE',
        task_states.RESIZE_MIGRATING: 'RESIZE',
        task_states.RESIZE_MIGRATED: 'RESIZE',
        task_states.RESIZE_FINISH: 'RESIZE',
    },
    vm_states.BUILDING: {
        'default': 'BUILD',
    },
    vm_states.STOPPED: {
        'default': 'SHUTOFF',
    },
    vm_states.RESIZED: {
        'default': 'VERIFY_RESIZE',
        # Note(maoy): the OS API spec 1.1 doesn't have CONFIRMING_RESIZE
        # state so we comment that out for future reference only.
        #task_states.RESIZE_CONFIRMING: 'CONFIRMING_RESIZE',
        task_states.RESIZE_REVERTING: 'REVERT_RESIZE',
    },
    vm_states.PAUSED: {
        'default': 'PAUSED',
    },
    vm_states.SUSPENDED: {
        'default': 'SUSPENDED',
    },
    vm_states.RESCUED: {
        'default': 'RESCUE',
    },
    vm_states.ERROR: {
        'default': 'ERROR',
    },
    vm_states.DELETED: {
        'default': 'DELETED',
    },
    vm_states.SOFT_DELETED: {
        'default': 'DELETED',
    },
}

def status_from_state(vm_state, task_state='default'):
    """Given vm_state and task_state, return a status string."""
    task_map = _STATE_MAP.get(vm_state, dict(default='UNKNOWN'))
    status = task_map.get(task_state, task_map['default'])
    if status == "UNKNOWN":
        LOG.error(_("status is UNKNOWN from vm_state=%(vm_state)s "
                    "task_state=%(task_state)s. Bad upgrade or db "
                    "corrupted?") % locals())
    return status

def vm_state_from_status(status):
    """Map the server status string to a vm state."""
    for state, task_map in _STATE_MAP.iteritems():
        status_string = task_map.get("default")
        if status.lower() == status_string.lower():
            return state

def get_pagination_params(request):
    """Return marker, limit tuple from request.

    :param request: `wsgi.Request` possibly containing 'marker' and 'limit'
                    GET variables. 'marker' is the id of the last element
                    the client has seen, and 'limit' is the maximum number
                    of items to return. If 'limit' is not specified, 0, or
                    > max_limit, we default to max_limit. Negative values
                    for either marker or limit will cause
                    exc.HTTPBadRequest() exceptions to be raised.

    """
    params = {}
    if 'limit' in request.GET:
        params['limit'] = _get_limit_param(request)
    if 'marker' in request.GET:
        params['marker'] = _get_marker_param(request)
    return params

def _get_limit_param(request):
    """Extract integer limit from request or fail."""
    try:
        limit = int(request.GET['limit'])
    except ValueError:
        msg = _('limit param must be an integer')
        raise webob.exc.HTTPBadRequest(explanation=msg)
    if limit < 0:
        msg = _('limit param must be positive')
        raise webob.exc.HTTPBadRequest(explanation=msg)
    return limit

def _get_marker_param(request):
    """Extract marker id from request or fail."""
    return request.GET['marker']

def limited(items, request, max_limit=CONF.osapi_max_limit):
    """Return a slice of items according to requested offset and limit.

    :param items: A sliceable entity
    :param request: ``wsgi.Request`` possibly containing 'offset' and 'limit'
                    GET variables. 'offset' is where to start in the list,
                    and 'limit' is the maximum number of items to return. If
                    'limit' is not specified, 0, or > max_limit, we default
                    to max_limit. Negative values for either offset or limit
                    will cause exc.HTTPBadRequest() exceptions to be raised.
    :kwarg max_limit: The maximum number of items to return from 'items'
    """
    try:
        offset = int(request.GET.get('offset', 0))
    except ValueError:
        msg = _('offset param must be an integer')
        raise webob.exc.HTTPBadRequest(explanation=msg)

    try:
        limit = int(request.GET.get('limit', max_limit))
    except ValueError:
        msg = _('limit param must be an integer')
        raise webob.exc.HTTPBadRequest(explanation=msg)

    if limit < 0:
        msg = _('limit param must be positive')
        raise webob.exc.HTTPBadRequest(explanation=msg)

    if offset < 0:
        msg = _('offset param must be positive')
        raise webob.exc.HTTPBadRequest(explanation=msg)

    limit = min(max_limit, limit or max_limit)
    range_end = offset + limit
    return items[offset:range_end]

def get_limit_and_marker(request, max_limit=CONF.osapi_max_limit):
    """get limited parameter from request."""
    params = get_pagination_params(request)
    limit = params.get('limit', max_limit)
    limit = min(max_limit, limit)
    marker = params.get('marker')

    return limit, marker

def limited_by_marker(items, request, max_limit=CONF.osapi_max_limit):
    """Return a slice of items according to the requested marker and limit."""
    limit, marker = get_limit_and_marker(request, max_limit)

    limit = min(max_limit, limit)
    start_index = 0
    if marker:
        start_index = -1
        for i, item in enumerate(items):
            if 'flavorid' in item:
                if item['flavorid'] == marker:
                    start_index = i + 1
                    break
            elif item['id'] == marker or item.get('uuid') == marker:
                start_index = i + 1
                break
        if start_index < 0:
            msg = _('marker [%s] not found') % marker
            raise webob.exc.HTTPBadRequest(explanation=msg)
    range_end = start_index + limit
    return items[start_index:range_end]

def get_id_from_href(href):
    """Return the id or uuid portion of a url.

    Given: 'http://www.foo.com/bar/123?q=4'
    Returns: '123'

    Given: 'http://www.foo.com/bar/abc123?q=4'
    Returns: 'abc123'

    """
    return urlparse.urlsplit("%s" % href).path.split('/')[-1]

def remove_version_from_href(href):
    """Removes the first api version from the href.

    Given: 'http://www.nova.com/v1.1/123'
    Returns: 'http://www.nova.com/123'

    Given: 'http://www.nova.com/v1.1'
    Returns: 'http://www.nova.com'

    """
    parsed_url = urlparse.urlsplit(href)
    url_parts = parsed_url.path.split('/', 2)

    # NOTE: this should match vX.X or vX
    expression = re.compile(r'^v([0-9]+|[0-9]+\.[0-9]+)(/.*|$)')
    if expression.match(url_parts[1]):
        del url_parts[1]

    new_path = '/'.join(url_parts)

    if new_path == parsed_url.path:
        msg = _('href %s does not contain version') % href
        LOG.debug(msg)
        raise ValueError(msg)

    parsed_url = list(parsed_url)
    parsed_url[2] = new_path
    return urlparse.urlunsplit(parsed_url)

def check_img_metadata_properties_quota(context, metadata):
    if metadata is None:
        return
    try:
        QUOTAS.limit_check(context, metadata_items=len(metadata))
    except exception.OverQuota:
        expl = _("Image metadata limit exceeded")
        raise webob.exc.HTTPRequestEntityTooLarge(explanation=expl,
                                                headers={'Retry-After': 0})

    #  check the key length.
    if isinstance(metadata, dict):
        for key, value in metadata.iteritems():
            if len(key) == 0:
                expl = _("Image metadata key cannot be blank")
                raise webob.exc.HTTPBadRequest(explanation=expl)
            if len(key) > 255:
                expl = _("Image metadata key too long")
                raise webob.exc.HTTPBadRequest(explanation=expl)
    else:
        expl = _("Invalid image metadata")
        raise webob.exc.HTTPBadRequest(explanation=expl)

def dict_to_query_str(params):
    # TODO(throughnothing): we should just use urllib.urlencode instead of this
    # But currently we don't work with urlencoded url's
    param_str = ""
    for key, val in params.iteritems():
        param_str = param_str + '='.join([str(key), str(val)]) + '&'

    return param_str.rstrip('&')

def get_networks_for_instance_from_nw_info(nw_info):
    networks = {}
    for vif in nw_info:
        ips = vif.fixed_ips()
        floaters = vif.floating_ips()
        label = vif['network']['label']
        if label not in networks:
            networks[label] = {'ips': [], 'floating_ips': []}

        networks[label]['ips'].extend(ips)
        networks[label]['floating_ips'].extend(floaters)
    return networks

def get_networks_for_instance(context, instance):
    """Returns a prepared nw_info list for passing into the view builders

    We end up with a data structure like::

        {'public': {'ips': [{'addr': '10.0.0.1', 'version': 4},
                            {'addr': '2001::1', 'version': 6}],
                    'floating_ips': [{'addr': '172.16.0.1', 'version': 4},
                                     {'addr': '172.16.2.1', 'version': 4}]},
         ...}
    """
    nw_info = compute_utils.get_nw_info_for_instance(instance)
    return get_networks_for_instance_from_nw_info(nw_info)

def raise_http_conflict_for_instance_invalid_state(exc, action):
    """Return a webob.exc.HTTPConflict instance containing a message
    appropriate to return via the API based on the original
    InstanceInvalidState exception.
    """
    attr = exc.kwargs.get('attr')
    state = exc.kwargs.get('state')
    if attr and state:
        msg = _("Cannot '%(action)s' while instance is in %(attr)s %(state)s")
    else:
        # At least give some meaningful message
        msg = _("Instance is in an invalid state for '%(action)s'")
    raise webob.exc.HTTPConflict(explanation=msg % locals())

class MetadataDeserializer(wsgi.MetadataXMLDeserializer):
    def deserialize(self, text):
        dom = minidom.parseString(text)
        metadata_node = self.find_first_child_named(dom, "metadata")
        metadata = self.extract_metadata(metadata_node)
        return {'body': {'metadata': metadata}}

class MetaItemDeserializer(wsgi.MetadataXMLDeserializer):
    def deserialize(self, text):
        dom = minidom.parseString(text)
        metadata_item = self.extract_metadata(dom)
        return {'body': {'meta': metadata_item}}

class MetadataXMLDeserializer(wsgi.XMLDeserializer):

    def extract_metadata(self, metadata_node):
        """Marshal the metadata attribute of a parsed request."""
        if metadata_node is None:
            return {}
        metadata = {}
        for meta_node in self.find_children_named(metadata_node, "meta"):
            key = meta_node.getAttribute("key")
            metadata[key] = self.extract_text(meta_node)
        return metadata

    def _extract_metadata_container(self, datastring):
        dom = minidom.parseString(datastring)
        metadata_node = self.find_first_child_named(dom, "metadata")
        metadata = self.extract_metadata(metadata_node)
        return {'body': {'metadata': metadata}}

    def create(self, datastring):
        return self._extract_metadata_container(datastring)

    def update_all(self, datastring):
        return self._extract_metadata_container(datastring)

    def update(self, datastring):
        dom = minidom.parseString(datastring)
        metadata_item = self.extract_metadata(dom)
        return {'body': {'meta': metadata_item}}

metadata_nsmap = {None: xmlutil.XMLNS_V11}

class MetaItemTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        sel = xmlutil.Selector('meta', xmlutil.get_items, 0)
        root = xmlutil.TemplateElement('meta', selector=sel)
        root.set('key', 0)
        root.text = 1
        return xmlutil.MasterTemplate(root, 1, nsmap=metadata_nsmap)

class MetadataTemplateElement(xmlutil.TemplateElement):
    def will_render(self, datum):
        return True

class MetadataTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = MetadataTemplateElement('metadata', selector='metadata')
        elem = xmlutil.SubTemplateElement(root, 'meta',
                                          selector=xmlutil.get_items)
        elem.set('key', 0)
        elem.text = 1
        return xmlutil.MasterTemplate(root, 1, nsmap=metadata_nsmap)

def check_snapshots_enabled(f):
    @functools.wraps(f)
    def inner(*args, **kwargs):
        if not CONF.allow_instance_snapshots:
            LOG.warn(_('Rejecting snapshot request, snapshots currently'
                       ' disabled'))
            msg = _("Instance snapshots are not permitted at this time.")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        return f(*args, **kwargs)
    return inner

class ViewBuilder(object):
    """Model API responses as dictionaries."""

    def _get_links(self, request, identifier, collection_name):
        return [{
            "rel": "self",
            "href": self._get_href_link(request, identifier, collection_name),
        },
        {
            "rel": "bookmark",
            "href": self._get_bookmark_link(request,
                                            identifier,
                                            collection_name),
        }]

    def _get_next_link(self, request, identifier, collection_name):
        """Return href string with proper limit and marker params."""
        params = request.params.copy()
        params["marker"] = identifier
        prefix = self._update_compute_link_prefix(request.application_url)
        url = os.path.join(prefix,
                           request.environ["nova.context"].project_id,
                           collection_name)
        return "%s?%s" % (url, dict_to_query_str(params))

    def _get_href_link(self, request, identifier, collection_name):
        """Return an href string pointing to this object."""
        prefix = self._update_compute_link_prefix(request.application_url)
        return os.path.join(prefix,
                            request.environ["nova.context"].project_id,
                            collection_name,
                            str(identifier))

    def _get_bookmark_link(self, request, identifier, collection_name):
        """Create a URL that refers to a specific resource."""
        base_url = remove_version_from_href(request.application_url)
        base_url = self._update_compute_link_prefix(base_url)
        return os.path.join(base_url,
                            request.environ["nova.context"].project_id,
                            collection_name,
                            str(identifier))

    def _get_collection_links(self,
                              request,
                              items,
                              collection_name,
                              id_key="uuid"):
        """Retrieve 'next' link, if applicable."""
        links = []
        limit = int(request.params.get("limit", 0))
        if limit and limit == len(items):
            last_item = items[-1]
            if id_key in last_item:
                last_item_id = last_item[id_key]
            elif 'id' in last_item:
                last_item_id = last_item["id"]
            else:
                last_item_id = last_item["flavorid"]
            links.append({
                "rel": "next",
                "href": self._get_next_link(request,
                                            last_item_id,
                                            collection_name),
            })
        return links

    def _update_link_prefix(self, orig_url, prefix):
        if not prefix:
            return orig_url
        url_parts = list(urlparse.urlsplit(orig_url))
        prefix_parts = list(urlparse.urlsplit(prefix))
        url_parts[0:2] = prefix_parts[0:2]
        return urlparse.urlunsplit(url_parts)

    def _update_glance_link_prefix(self, orig_url):
        return self._update_link_prefix(orig_url,
                                        CONF.osapi_glance_link_prefix)

    def _update_compute_link_prefix(self, orig_url):
        return self._update_link_prefix(orig_url,
                                        CONF.osapi_compute_link_prefix)


text:
package org.apache.syncope.core.persistence.jpa.entity;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Random;
import javax.validation.ValidationException;
import org.apache.syncope.common.lib.SyncopeConstants;
import org.apache.syncope.common.lib.types.AttributableType;
import org.apache.syncope.common.lib.types.EntityViolationType;
import org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException;
import org.apache.syncope.core.persistence.api.dao.PlainAttrDAO;
import org.apache.syncope.core.persistence.api.dao.PlainSchemaDAO;
import org.apache.syncope.core.persistence.api.dao.UserDAO;
import org.apache.syncope.core.persistence.api.entity.user.UPlainAttr;
import org.apache.syncope.core.persistence.api.entity.user.UPlainAttrUniqueValue;
import org.apache.syncope.core.persistence.api.entity.user.UPlainSchema;
import org.apache.syncope.core.persistence.api.entity.user.User;
import org.apache.syncope.core.persistence.jpa.AbstractTest;
import org.apache.syncope.core.misc.security.Encryptor;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class AttrTest extends AbstractTest {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private PlainAttrDAO plainAttrDAO;

    @Autowired
    private PlainSchemaDAO userSchemaDAO;

    @Test
    public void findById() {
        UPlainAttr attribute = plainAttrDAO.find(100L, UPlainAttr.class);
        assertNotNull("did not find expected attribute schema", attribute);
        attribute = plainAttrDAO.find(104L, UPlainAttr.class);
        assertNotNull("did not find expected attribute schema", attribute);
    }

    @Test
    public void read() {
        UPlainAttr attribute = plainAttrDAO.find(100L, UPlainAttr.class);
        assertNotNull(attribute);
        assertTrue(attribute.getValues().isEmpty());
        assertNotNull(attribute.getUniqueValue());
    }

    @Test
    public void save() throws ClassNotFoundException {
        User user = userDAO.find(1L);

        UPlainSchema emailSchema = userSchemaDAO.find("email", UPlainSchema.class);
        assertNotNull(emailSchema);

        UPlainAttr attribute = entityFactory.newEntity(UPlainAttr.class);
        attribute.setSchema(emailSchema);
        attribute.setOwner(user);

        Exception thrown = null;
        try {
            attribute.addValue("john.doe@gmail.com", attrUtilFactory.getInstance(AttributableType.USER));
            attribute.addValue("mario.rossi@gmail.com", attrUtilFactory.getInstance(AttributableType.USER));
        } catch (ValidationException e) {
            thrown = e;
        }
        assertNull("no validation exception expected here ", thrown);

        try {
            attribute.addValue("http://www.apache.org", attrUtilFactory.getInstance(AttributableType.USER));
        } catch (ValidationException e) {
            thrown = e;
        }
        assertNotNull("validation exception expected here ", thrown);
    }

    @Test
    public void saveWithEnum() throws ClassNotFoundException {
        User user = userDAO.find(1L);

        UPlainSchema gender = userSchemaDAO.find("gender", UPlainSchema.class);
        assertNotNull(gender);
        assertNotNull(gender.getType());
        assertNotNull(gender.getEnumerationValues());

        UPlainAttr attribute = entityFactory.newEntity(UPlainAttr.class);
        attribute.setSchema(gender);
        attribute.setOwner(user);
        user.addPlainAttr(attribute);

        Exception thrown = null;

        try {
            attribute.addValue("A", attrUtilFactory.getInstance(AttributableType.USER));
        } catch (ValidationException e) {
            thrown = e;
        }
        assertNotNull("validation exception expected here ", thrown);

        attribute.addValue("M", attrUtilFactory.getInstance(AttributableType.USER));

        InvalidEntityException iee = null;
        try {
            userDAO.save(user);
        } catch (InvalidEntityException e) {
            iee = e;
        }
        assertNull(iee);
    }

    @Test
    public void validateAndSave() {
        User user = userDAO.find(1L);

        final UPlainSchema emailSchema = userSchemaDAO.find("email", UPlainSchema.class);
        assertNotNull(emailSchema);

        final UPlainSchema fullnameSchema = userSchemaDAO.find("fullname", UPlainSchema.class);
        assertNotNull(fullnameSchema);

        UPlainAttr attribute = entityFactory.newEntity(UPlainAttr.class);
        attribute.setSchema(emailSchema);

        UPlainAttrUniqueValue uauv = entityFactory.newEntity(UPlainAttrUniqueValue.class);
        uauv.setAttr(attribute);
        uauv.setSchema(fullnameSchema);
        uauv.setStringValue("a value");

        attribute.setUniqueValue(uauv);

        user.addPlainAttr(attribute);

        InvalidEntityException iee = null;
        try {
            userDAO.save(user);
            fail();
        } catch (InvalidEntityException e) {
            iee = e;
        }
        assertNotNull(iee);
        // for attribute
        assertTrue(iee.hasViolation(EntityViolationType.InvalidValueList));
        // for uauv
        assertTrue(iee.hasViolation(EntityViolationType.InvalidUPlainSchema));
    }

    @Test
    public void saveWithEncrypted() throws Exception {
        User user = userDAO.find(1L);

        final UPlainSchema obscureSchema = userSchemaDAO.find("obscure", UPlainSchema.class);
        assertNotNull(obscureSchema);
        assertNotNull(obscureSchema.getSecretKey());
        assertNotNull(obscureSchema.getCipherAlgorithm());

        UPlainAttr attribute = entityFactory.newEntity(UPlainAttr.class);
        attribute.setSchema(obscureSchema);
        attribute.addValue("testvalue", attrUtilFactory.getInstance(AttributableType.USER));
        attribute.setOwner(user);
        user.addPlainAttr(attribute);

        userDAO.save(user);

        UPlainAttr obscure = user.getPlainAttr("obscure");
        assertNotNull(obscure);
        assertEquals(1, obscure.getValues().size());
        assertEquals(Encryptor.getInstance(obscureSchema.getSecretKey()).
                encode("testvalue", obscureSchema.getCipherAlgorithm()), obscure.getValues().get(0).getStringValue());
    }

    @Test
    public void saveWithBinary() throws UnsupportedEncodingException {
        User user = userDAO.find(1L);

        final UPlainSchema photoSchema = userSchemaDAO.find("photo", UPlainSchema.class);
        assertNotNull(photoSchema);
        assertNotNull(photoSchema.getMimeType());

        final byte[] bytes = new byte[20];
        new Random().nextBytes(bytes);
        final String photoB64Value = new String(Base64.encode(bytes), SyncopeConstants.DEFAULT_ENCODING);

        UPlainAttr attribute = entityFactory.newEntity(UPlainAttr.class);
        attribute.setSchema(photoSchema);
        attribute.addValue(photoB64Value, attrUtilFactory.getInstance(AttributableType.USER));
        attribute.setOwner(user);
        user.addPlainAttr(attribute);

        userDAO.save(user);

        UPlainAttr obscure = user.getPlainAttr("photo");
        assertNotNull(obscure);
        assertEquals(1, obscure.getValues().size());
        assertTrue(Arrays.equals(bytes, obscure.getValues().get(0).getBinaryValue()));
    }

    @Test
    public void delete() {
        UPlainAttr attribute = plainAttrDAO.find(104L, UPlainAttr.class);
        String attrSchemaName = attribute.getSchema().getKey();

        plainAttrDAO.delete(attribute.getKey(), UPlainAttr.class);

        UPlainSchema schema = userSchemaDAO.find(attrSchemaName, UPlainSchema.class);
        assertNotNull("user attribute schema deleted when deleting values", schema);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
  The aim of this topic is:
    Find the longest common substring of two input strings
    Return the pair of (longest lenght and pair of longest start position (in 1, in2))
    the start position pair must be such as input1[in1:in1+length-1] == input2[in2:in2+length-1]
*/

#pragma once
#include <cstddef>
#include <string>
#include <utility>

// Algorithm to be tested

std::pair<std::size_t, std::pair<std::size_t, std::size_t>> longest_common_substr(std::string const& input1, std::string const& input2);


text:
Nw.js based media player.

Used packages:
* musicmetadata


text:
/* Test of gpr synchronization support. */

#include "src/core/lib/support/spinlock.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>
#include <stdio.h>
#include <stdlib.h>
#include "test/core/util/test_config.h"

/* ------------------------------------------------- */
/* Tests for gpr_spinlock. */
struct test {
  int thread_count; /* number of threads */
  gpr_thd_id *threads;

  int64_t iterations; /* number of iterations per thread */
  int64_t counter;
  int incr_step; /* how much to increment/decrement refcount each time */

  gpr_spinlock mu; /* protects iterations, counter */
};

/* Return pointer to a new struct test. */
static struct test *test_new(int threads, int64_t iterations, int incr_step) {
  struct test *m = gpr_malloc(sizeof(*m));
  m->thread_count = threads;
  m->threads = gpr_malloc(sizeof(*m->threads) * (size_t)threads);
  m->iterations = iterations;
  m->counter = 0;
  m->thread_count = 0;
  m->incr_step = incr_step;
  m->mu = GPR_SPINLOCK_INITIALIZER;
  return m;
}

/* Return pointer to a new struct test. */
static void test_destroy(struct test *m) {
  gpr_free(m->threads);
  gpr_free(m);
}

/* Create m->threads threads, each running (*body)(m) */
static void test_create_threads(struct test *m, void (*body)(void *arg)) {
  int i;
  for (i = 0; i != m->thread_count; i++) {
    gpr_thd_options opt = gpr_thd_options_default();
    gpr_thd_options_set_joinable(&opt);
    GPR_ASSERT(gpr_thd_new(&m->threads[i], body, m, &opt));
  }
}

/* Wait until all threads report done. */
static void test_wait(struct test *m) {
  int i;
  for (i = 0; i != m->thread_count; i++) {
    gpr_thd_join(m->threads[i]);
  }
}

/* Test several threads running (*body)(struct test *m) for increasing settings
   of m->iterations, until about timeout_s to 2*timeout_s seconds have elapsed.
   If extra!=NULL, run (*extra)(m) in an additional thread.
   incr_step controls by how much m->refcount should be incremented/decremented
   (if at all) each time in the tests.
   */
static void test(const char *name, void (*body)(void *m), int timeout_s,
                 int incr_step) {
  int64_t iterations = 1024;
  struct test *m;
  gpr_timespec start = gpr_now(GPR_CLOCK_REALTIME);
  gpr_timespec time_taken;
  gpr_timespec deadline = gpr_time_add(
      start, gpr_time_from_micros((int64_t)timeout_s * 1000000, GPR_TIMESPAN));
  fprintf(stderr, "%s:", name);
  while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0) {
    if (iterations < INT64_MAX / 2) iterations <<= 1;
    fprintf(stderr, " %ld", (long)iterations);
    m = test_new(10, iterations, incr_step);
    test_create_threads(m, body);
    test_wait(m);
    if (m->counter != m->thread_count * m->iterations * m->incr_step) {
      fprintf(stderr, "counter %ld  threads %d  iterations %ld\n",
              (long)m->counter, m->thread_count, (long)m->iterations);
      GPR_ASSERT(0);
    }
    test_destroy(m);
  }
  time_taken = gpr_time_sub(gpr_now(GPR_CLOCK_REALTIME), start);
  fprintf(stderr, " done %lld.%09d s\n", (long long)time_taken.tv_sec,
          (int)time_taken.tv_nsec);
}

/* Increment m->counter on each iteration; then mark thread as done.  */
static void inc(void *v /*=m*/) {
  struct test *m = v;
  int64_t i;
  for (i = 0; i != m->iterations; i++) {
    gpr_spinlock_lock(&m->mu);
    m->counter++;
    gpr_spinlock_unlock(&m->mu);
  }
}

/* Increment m->counter under lock acquired with trylock, m->iterations times;
   then mark thread as done.  */
static void inctry(void *v /*=m*/) {
  struct test *m = v;
  int64_t i;
  for (i = 0; i != m->iterations;) {
    if (gpr_spinlock_trylock(&m->mu)) {
      m->counter++;
      gpr_spinlock_unlock(&m->mu);
      i++;
    }
  }
}

/* ------------------------------------------------- */

int main(int argc, char *argv[]) {
  grpc_test_init(argc, argv);
  test("spinlock", &inc, 1, 1);
  test("spinlock try", &inctry, 1, 1);
  return 0;
}


text:
using AnnuaireCertifies.Domaine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AnnuaireCertifies.Business.Depots
{
    public partial interface IDepotIntervenantRoleContrat
    {
        IEnumerable<IntervenantRoleContratResult> GetContratsCadresAutresRoles(long utilisateurID, long intervenantRoleID);
    }
}


text:
package com.esri.gpt.catalog.gxe;
import com.esri.gpt.framework.context.ConfigurationException;
import com.esri.gpt.framework.util.Val;
import com.esri.gpt.framework.xml.DomUtil;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * A component XML file associated with a Geoportal XML editor definition.
 */
public class GxeFile {

  /** class variables ========================================================= */

  /** The Logger. */
  private static Logger LOGGER = Logger.getLogger(GxeFile.class.getName());

  /** instance variables ====================================================== */
  private List<URI> baseLocations = new ArrayList<URI>();
  private boolean   isRoot = false;
  private String    location;
  private GxeFile   parent;
  private URL       referencedUrl;

  /** constructors ============================================================ */

  /** Default constructor */
  public GxeFile() {}

  /**
   * Constructs with a parent file and reference location.
   * @param parent the parent file from which this external reference was made
   * @param location the file location
   */
  public GxeFile(GxeFile parent, String location) {
    this.setParent(parent);
    this.setLocation(location);
  }

  /** properties ============================================================== */

  /**
   * Gets the base locations.
   * @return the base locations
   */
  public List<URI> getBaseLocations() {
    return this.baseLocations;
  }

  /**
   * Sets the base locations.
   * @param locations the base locations
   */
  public void setBaseLocations(List<URI> locations) {
    this.baseLocations = locations;
  }

  /**
   * Indicates whether or not the file is the definition root.
   * @return true if this is the root
   */
  public boolean getIsRoot() {
    return this.isRoot;
  }

  /**
   * Indicates whether or not the file is the definition root.
   * @param isRoot true if this is the root
   */
  public void setIsRoot(boolean isRoot) {
    this.isRoot = isRoot;
  }

  /**
   * Gets the location.
   * @return the location
   */
  public String getLocation() {
    return this.location;
  }

  /**
   * Sets the location.
   * @param location the location
   */
  public void setLocation(String location) {
    this.location = location;
  }

  /**
   * Gets the parent.
   * @return the parent
   */
  public GxeFile getParent() {
    return this.parent;
  }
  /**
   * Sets the parent.
   * @param parent the parent
   */
  public void setParent(GxeFile parent) {
    this.parent = parent;
  }

  /**
   * Gets the URL that was referenced while loading the DOM.
   * @return the referenced URL
   */
  public URL getReferencedUrl() {
    return this.referencedUrl;
  }

  /** methods ================================================================= */

  /**
   * Finds the root node within a document.
   * @param dom the document
   * @return the root node
   */
  public Node findRoot(Document dom) {
    NodeList nl = dom.getChildNodes();
    for (int i=0; i<nl.getLength(); i++) {
      Node nd = nl.item(i);
      if (nd.getNodeType() == Node.ELEMENT_NODE) {
        return nd;
      }
    }
    return null;
  }

  /**
   * Establishes the base location inheritance precedence.
   * @param dom the active XML document.
   * @throws Exception if an exception occurs
   */
  private void inheritBaseLocations(Document dom) throws Exception {
    String ns = GxeContext.URI_GXE;
    Node root = this.findRoot(dom);
    Node nd = root.getAttributes().getNamedItemNS(ns,"extends");
    if (nd != null) {
      String loc = Val.chkStr(nd.getNodeValue());
      if (loc.length() > 0) {
        URL locUrl = Thread.currentThread().getContextClassLoader().getResource(loc);
        if (locUrl != null) {
          InputSource src = new InputSource(locUrl.toExternalForm());
          Document domExtends = DomUtil.makeDomFromSource(src,true);
          String baseLoc = locUrl.toExternalForm();
          int nIdx = baseLoc.lastIndexOf("/");
          if (nIdx != -1) baseLoc = baseLoc.substring(0,nIdx);
          this.getBaseLocations().add(new URI(baseLoc+"/"));
          this.inheritBaseLocations(domExtends);
        }
      }
    }
  }

  /**
   * Loads the XML document object model (org.w3c.dom.Document).
   * @throws Exception if an exception occurs
   */
  public Document loadDom()  {
    Document dom = null;
    try {
      URL url = this.makeUrl();
      InputSource src = new InputSource(url.toExternalForm());
      dom = DomUtil.makeDomFromSource(src,true);
      if (this.getIsRoot()) {
        this.setBaseLocations(new ArrayList<URI>());
        String baseLoc = url.toExternalForm();
        int nIdx = baseLoc.lastIndexOf("/");
        if (nIdx != -1) baseLoc = baseLoc.substring(0,nIdx);
        this.getBaseLocations().add(new URI(baseLoc+"/"));
        this.inheritBaseLocations(dom);
      }
    } catch (Exception e) {
      String msg = "Error loading XML file: "+Val.chkStr(this.getLocation());
      msg += ", "+Val.chkStr(e.toString());
      LOGGER.log(Level.CONFIG,msg,e);
      throw new ConfigurationException(msg,e);
    }
    return dom;
  }

  /**
   * Returns the URL for the file.
   * @return the associated url
   * @throws IOException if the URL cannot be generated
   */
  public URL makeUrl() throws Exception {

    // return the reference if it was already established
    if (this.referencedUrl != null) return this.referencedUrl;

    String loc = Val.chkStr(this.getLocation());
    URL locUrl = null;

    // determine the base location URIs
    URI rootUri = null;
    List<URI> baseUris = null;
    GxeFile parentFile = this;
    while (parentFile != null) {
      if (parentFile.isRoot) {
        baseUris = parentFile.getBaseLocations();
        break;
      }
      parentFile = parentFile.getParent();
    }
    boolean hasBaseUris = (baseUris != null) && (baseUris.size() > 0);
    if (hasBaseUris) rootUri = baseUris.get(0);

    if (locUrl == null) {
      locUrl = Thread.currentThread().getContextClassLoader().getResource(loc);
    }

    if ((locUrl == null) && !loc.startsWith("$base")) {
      if ((this.getParent() != null) && (this.getParent().getReferencedUrl() != null)) {
        try {
          URL parentUrl = this.getParent().getReferencedUrl();
          URI parentUri = parentUrl.toURI();
          URI thisUri = parentUri.resolve(loc);
          File thisFile = new File(thisUri);
          locUrl = thisUri.toURL();
          if (!thisFile.exists() && hasBaseUris && (rootUri != null)) {
            URI relUri = rootUri.relativize(thisUri);
            int n = baseUris.size();
            for (int i=0; i<n; i++) {
              URI testUri = baseUris.get(i).resolve(relUri);
              // this won't work for http based URIs
              if ((new File(testUri)).exists()) {
                locUrl = testUri.toURL();
                break;
              }
            }
          }
        } catch (URISyntaxException e) {
          LOGGER.log(Level.CONFIG,"While attemting to load: "+loc+", error: "+e.toString(),e);
        }
      }
    }

    if ((locUrl == null) && loc.startsWith("$base")) {
      String relLoc = Val.chkStr(loc.substring(5));
      if (relLoc.startsWith("/")) relLoc = Val.chkStr(relLoc.substring(1));
      if ((relLoc.length() > 0) && hasBaseUris) {
        try {
          URI relUri = new URI(relLoc);
          int n = baseUris.size();
          for (int i=0; i<n; i++) {
            URI testUri = baseUris.get(i).resolve(relUri);
            // this won't work for http based URIs
            if ((new File(testUri)).exists()) {
              locUrl = testUri.toURL();
              break;
            }
          }
        } catch (URISyntaxException e) {
          LOGGER.log(Level.CONFIG,"While attemting to load: "+loc+", error: "+e.toString(),e);
        }
      }
    }

    // throw an exception if the URL was not generated, otherwise save and return the reference
    if (locUrl == null) {
      throw new IOException("Unable to create resource URL for path: "+loc);
    } else {
      this.referencedUrl = locUrl;
    }
    return this.referencedUrl;
  }

}


text:
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@

package example;

import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;

public final class MainPanel extends JPanel {
  private MainPanel() {
    super(new BorderLayout());

    JComboBox<ComboItem> combo0 = new JComboBox<ComboItem>(makeModel()) {
      @Override public void updateUI() {
        super.updateUI();
        setRenderer(new CheckComboBoxRenderer<>());
      }
    };

    JComboBox<ComboItem> combo1 = new JComboBox<ComboItem>(makeModel()) {
      @Override public void updateUI() {
        super.updateUI();
        setEditable(true);
        setRenderer(new CheckComboBoxRenderer<>());
        setEditor(new CheckComboBoxEditor());
      }
    };

    Box box = Box.createVerticalBox();
    box.add(makeTitledPanel("setEditable(false), setRenderer(...)", combo0));
    box.add(Box.createVerticalStrut(5));
    box.add(makeTitledPanel("setEditable(true), setRenderer(...), setEditor(...)", combo1));
    box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    add(box, BorderLayout.NORTH);
    setPreferredSize(new Dimension(320, 240));
  }

  private static ComboItem[] makeModel() {
    return new ComboItem[] {
        new ComboItem(true, true, "00000"),
        new ComboItem(true, false, "11111"),
        new ComboItem(false, true, "22222"),
        new ComboItem(false, false, "33333")
    };
  }

  private static Component makeTitledPanel(String title, Component c) {
    JPanel p = new JPanel(new BorderLayout());
    p.setBorder(BorderFactory.createTitledBorder(title));
    p.add(c);
    return p;
  }

  public static void main(String[] args) {
    EventQueue.invokeLater(MainPanel::createAndShowGui);
  }

  private static void createAndShowGui() {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
      ex.printStackTrace();
      Toolkit.getDefaultToolkit().beep();
    }
    JFrame frame = new JFrame("@title@");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(new MainPanel());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

@SuppressWarnings("PMD.DataClass")
class ComboItem {
  private boolean enabled;
  private boolean editable;
  private String text;

  protected ComboItem() {
    this(false, false, "");
  }

  protected ComboItem(boolean enabled, boolean editable, String text) {
    this.enabled = enabled;
    this.editable = editable;
    this.text = text;
  }

  public boolean isEnabled() {
    return enabled;
  }

  public void setEnabled(boolean enabled) {
    this.enabled = enabled;
  }

  public boolean isEditable() {
    return editable;
  }

  public void setEditable(boolean editable) {
    this.editable = editable;
  }

  public String getText() {
    return text;
  }

  public void setText(String text) {
    this.text = text;
  }
}

class CheckComboBoxRenderer<E extends ComboItem> implements ListCellRenderer<E> {
  private static final Color SELECTED_BGC = new Color(0x64_C8_FF);
  private final EditorPanel renderer = new EditorPanel(new ComboItem());

  @Override public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) {
    renderer.setItem(value);
    if (isSelected && index >= 0) {
      renderer.setOpaque(true);
      renderer.setBackground(SELECTED_BGC);
    } else {
      renderer.setOpaque(false);
      renderer.setBackground(Color.WHITE);
    }
    return renderer;
  }
}

class CheckComboBoxEditor implements ComboBoxEditor {
  private final EditorPanel editor = new EditorPanel(new ComboItem());

  @Override public void selectAll() {
    editor.selectAll();
  }

  @Override public Object getItem() {
    return editor.getItem();
  }

  @Override public void setItem(Object anObject) {
    EventQueue.invokeLater(() -> {
      Container c = SwingUtilities.getAncestorOfClass(JComboBox.class, getEditorComponent());
      if (c instanceof JComboBox) {
        JComboBox<?> combo = (JComboBox<?>) c;
        int idx = combo.getSelectedIndex();
        if (idx >= 0 && idx != editor.getEditingIndex()) {
          // System.out.println("setItem: " + idx);
          editor.setEditingIndex(idx);
        }
      }
    });
    if (anObject instanceof ComboItem) {
      editor.setItem((ComboItem) anObject);
    } else {
      editor.setItem(new ComboItem());
    }
  }

  @Override public Component getEditorComponent() {
    return editor;
  }

  @Override public void addActionListener(ActionListener l) {
    // System.out.println("addActionListener: " + l.getClass().getName());
    editor.addActionListener(l);
  }

  @Override public void removeActionListener(ActionListener l) {
    // System.out.println("removeActionListener: " + l.getClass().getName());
    editor.removeActionListener(l);
  }
}

final class EditorPanel extends JPanel {
  private final JCheckBox enabledCheck = new JCheckBox();
  private final JCheckBox editableCheck = new JCheckBox();
  private final JTextField textField = new JTextField("", 16);
  private final transient ComboItem data;
  private int editingIndex = -1;

  /* default */ EditorPanel(ComboItem data) {
    super();
    this.data = data;
    setItem(data);

    enabledCheck.addActionListener(e -> {
      Container c = SwingUtilities.getAncestorOfClass(JComboBox.class, this);
      if (c instanceof JComboBox) {
        JComboBox<?> combo = (JComboBox<?>) c;
        ComboItem item = (ComboItem) combo.getItemAt(editingIndex);
        item.setEnabled(((JCheckBox) e.getSource()).isSelected());
        editableCheck.setEnabled(item.isEnabled());
        textField.setEnabled(item.isEnabled());
        combo.setSelectedIndex(editingIndex);
      }
    });
    enabledCheck.setOpaque(false);
    enabledCheck.setFocusable(false);

    editableCheck.addActionListener(e -> {
      Container c = SwingUtilities.getAncestorOfClass(JComboBox.class, this);
      if (c instanceof JComboBox) {
        JComboBox<?> combo = (JComboBox<?>) c;
        ComboItem item = (ComboItem) combo.getItemAt(editingIndex);
        item.setEditable(((JCheckBox) e.getSource()).isSelected());
        textField.setEditable(item.isEditable());
        combo.setSelectedIndex(editingIndex);
      }
    });
    editableCheck.setOpaque(false);
    editableCheck.setFocusable(false);

    textField.addActionListener(e -> {
      Container c = SwingUtilities.getAncestorOfClass(JComboBox.class, this);
      if (c instanceof JComboBox) {
        JComboBox<?> combo = (JComboBox<?>) c;
        ComboItem item = (ComboItem) combo.getItemAt(editingIndex);
        item.setText(((JTextField) e.getSource()).getText());
        combo.setSelectedIndex(editingIndex);
      }
    });
    textField.setBorder(BorderFactory.createEmptyBorder());
    textField.setOpaque(false);

    setOpaque(false);
    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));

    add(enabledCheck);
    add(editableCheck);
    add(textField);
  }

  public int getEditingIndex() {
    return editingIndex;
  }

  public void setEditingIndex(int idx) {
    this.editingIndex = idx;
  }

  public ComboItem getItem() {
    data.setEnabled(enabledCheck.isSelected());
    data.setEditable(editableCheck.isSelected());
    data.setText(textField.getText());
    return data;
  }

  public void setItem(ComboItem item) {
    enabledCheck.setSelected(item.isEnabled());

    editableCheck.setSelected(item.isEditable());
    editableCheck.setEnabled(item.isEnabled());

    textField.setText(item.getText());
    textField.setEnabled(item.isEnabled());
    textField.setEditable(item.isEditable());
  }

  public void selectAll() {
    textField.requestFocusInWindow();
    textField.selectAll();
  }

  public void addActionListener(ActionListener l) {
    textField.addActionListener(l);
    enabledCheck.addActionListener(l);
    editableCheck.addActionListener(l);
  }

  public void removeActionListener(ActionListener l) {
    textField.removeActionListener(l);
    enabledCheck.removeActionListener(l);
    editableCheck.removeActionListener(l);
  }
}


text:
require 'spec_helper'
require 'encase/container'
require 'encase'

module Encase
  class Lorem
  end

  class MyBox
    include Encase

    needs :apples, :mangoes
    needs :oranges
  end

  describe Container do
    let(:container) {
      Container.new
    }

    it 'can store objects' do
      container.object(:lorem, 'lorem')
      expect(container.lookup(:lorem)).to eq('lorem')
    end

    it 'can store factories' do
      container.factory(:lorem, Lorem)
      expect(container.lookup(:lorem)).to be_a(Lorem)
    end

    it 'can store singletons' do
      container.singleton(:lorem, Lorem)
      instance1 = container.lookup(:lorem)
      instance2 = container.lookup(:lorem)

      expect(instance1).to eq(instance2)
    end

    it 'can be configured with a DSL' do
      container.configure do
        object :lorem, 'lorem'
        factory :lipsum, Lorem
        singleton :dolor, Lorem
      end

      expect(container.lookup(:lorem)).to eq('lorem')
      expect(container.lookup(:lipsum)).to be_a(Lorem)

      instance1 = container.lookup(:dolor)
      instance2 = container.lookup(:dolor)

      expect(instance1).to eq(instance2)
    end

    it 'raises a KeyError for unknown keys' do
      expect {
        container.lookup(:unknown_key)
      }.to raise_error(KeyError)
    end

    it 'can create nested containers' do
      child = container.child()
      grand_child = child.child()

      expect(grand_child.parent).to eq(child)
      expect(child.parent).to eq(container)
      expect(container.parent).to be_nil
    end

    it 'can lookup values from nested containers' do
      child = container.child()
      grand_child = child.child()

      container.object(:lorem, 'in_container')
      child.object(:lorem, 'in_child')
      grand_child.object(:lorem, 'in_grand_child')

      expect(grand_child.lookup(:lorem)).to eq('in_grand_child')

      grand_child.unregister(:lorem)
      expect(grand_child.lookup(:lorem)).to eq('in_child')

      child.unregister(:lorem)
      expect(grand_child.lookup(:lorem)).to eq('in_container')
    end

    it 'can clear the container store' do
      container.object(:lorem, 'lorem')
      container.object(:ipsum, 'ipsum')
      container.object(:dolor, 'dolor')

      container.clear

      expect(container.contains?(:lorem)).to be_false
      expect(container.contains?(:ipsum)).to be_false
      expect(container.contains?(:dolor)).to be_false
    end

    it 'can inject dependencies' do
      container.configure do
        object :apples, 10
        object :mangoes, 20
        object :oranges, 30
        factory :box, MyBox
      end

      box = container.lookup(:box)
      expect(box.apples).to eq(10)
      expect(box.mangoes).to eq(20)
      expect(box.oranges).to eq(30)
    end

    it 'can inject dependencies lazily' do
      container.configure do
        object :apples, -> { 10 }
        object :mangoes, -> { 20 }
        object :oranges, -> { 30 }
        factory :box, -> { MyBox }
      end

      box = container.lookup(:box)
      expect(box.apples).to eq(10)
      expect(box.mangoes).to eq(20)
      expect(box.oranges).to eq(30)
    end

    it 'assigns container on injection' do
      class DummyObjectToBeInjected
        include Encase
        needs :lorem
      end

      container.object(:lorem, 'lorem')
      container.factory(:dummy, DummyObjectToBeInjected)

      dummy = container.lookup(:dummy)
      expect(dummy.container).to eq(container)
    end

    it 'call on_inject hook after injection' do
      class DummyWithOnInject
        include Encase
        needs :lorem
        attr_accessor :injected

        def on_inject
          self.injected = true
        end
      end

      container.object(:lorem, 'lorem')
      container.factory(:dummy, DummyWithOnInject)

      dummy = container.lookup(:dummy)
      expect(dummy.injected).to be_true
    end

    it 'can chain calls' do
      c = container.object(:a, 'foo')
      c.object(:b, 'bar')
      c.factory(:c, Object)
      c = c.singleton(:d, Object)

      expect(c).to eq(container)
    end

    context 'Performance', :benchmark => true do
      require 'benchmark'

      it 'can store 100s of dependencies quickly' do
        runtime = Benchmark.realtime do
          container.configure do
            10000.times do |i|
              item = "item#{i}"
              object item.to_sym, item
            end
          end
        end

        expect(runtime).to be < 0.1
      end

      it 'can lookup 100s of dependencies quickly' do
        class ClassWithManyDeps
          include Encase

          100.times do |i|
            needs "item#{i}".to_sym
          end
        end

        container.configure do
          100.times do |i|
            item = "item#{i}"
            object item.to_sym, item
          end

          factory :lorem, ClassWithManyDeps
        end

        runtime = Benchmark.realtime do
          100.times do |i|
            container.lookup(:lorem)
          end
        end

        expect(runtime).to be < 0.1
      end
    end

    context 'Needs with class inheritance' do
      it 'can recognize needs in parent class' do
        class MyGrandParent
          include Encase
          needs :a
        end

        class MyParent < MyGrandParent
          include Encase
          needs :b
        end

        class MyChild < MyParent
          include Encase
          needs :c
        end

        class MyGrandChild < MyChild
        end

        container.configure do
          object :a, 'A'
          object :b, 'B'
          object :c, 'C'

          factory :me, MyGrandChild
        end

        me = container.lookup(:me)
        expect(me.a).to eq('A')
        expect(me.b).to eq('B')
        expect(me.c).to eq('C')
      end
    end

    context 'Nested Container with lazy resolution' do
      it 'can resolve logger lazily issue #4' do
        class Logger
        end

        class MagicLogger
        end

        class House
          include Encase
          needs :logger
        end

        container = Container.new
        container.configure do
          object :logger, Logger.new
          factory :house, House
        end

        child = container.child
        child.configure do
          object :logger, MagicLogger.new
        end

        house = child.lookup(:house)
        expect(house.logger).to be_a(MagicLogger)
      end
    end
  end
end


text:
/*!
 * @title: scrollb.js
 * @author: Daniel Stuessy
 * @version: 1.2
 * @description: A JavaScript class for making custom HTML scrollbars.
 * @license: MIT License
 */
var ScrollBar = (function () {

	/**
	 * A Class representing a scroll bar.
	 *
	 * It takes a few options as parameters
	 * then creates and attaches a div element
	 * to a given parent to act as a scrollbar.
	 *
	 * @param {object} options A JavaScript hash table holding values for the scrollbar.
	 * @return {undefined}
	 */
	function ScrollBar (options) {

		// SET PROPERTIES
		this.id = options.id;
		this.selectorID = options.selectorID;
		this.el = options.el,
		this.el = (this.selectorID != null) ? document.getElementById( this.selectorID ) : this.el;
		this.scrollEl = document.createElement('div');
		this.parentEl = this.el.parentNode;
		this.mousedown = false;
		this.beforeScrollClick = ( options.beforeScrollClick || function () {} );
		this.afterScrollClick = ( options.afterScrollClick || function () {} );
		this.duringScroll = ( options.duringScroll || function () {} ); // not currently used
		this.duringNotScroll = ( options.duringNotScroll || function () {} ); // not currently used
		this.outerHeight;
		this.scrollHeight;
		this.ratio;
		this.height;

		// SET SIZE
		this.setSize();
		// SET POSITION
		this.setPosition();

		// DISPLAY SCROLLBAR
		this.display();

		// SET POSITION
		this.setPosition();
		this.display();

		// SET EVENT LISTENERS
		this.setEventListeners();
	}

	// SET PROTOTYPE FUNCTIONS
	/**
	 * Sets the CSS properties for the ScrollBar,
	 * then appends it to the parentNode of the
	 * this.el element.
	 *
	 * @return {undefined}
	 */
	ScrollBar.prototype.display = function () {

		this.scrollEl.id = this.id;

		this.scrollEl.style.position = 'absolute';
		this.scrollEl.style.height = this.height + 'px';
		this.scrollEl.style.top = this.top + 'px';
		this.scrollEl.style.left = this.right + 'px';

		this.parentEl.appendChild(this.scrollEl);
	};
	/**
	 * Sets the size of the ScrollBar.
	 *
	 * Obtains ratio and times it by the scrollbar's
	 * outerHeight.
	 *
	 *
	 * @return {undefined}
	 */
	ScrollBar.prototype.setSize = function () {

		this.setRatio();

		// set height
		this.height = this.outerHeight * this.ratio;
	};
	/**
	 * Sets the top and right position of the
	 * scroll bar.
	 *
	 * @return {undefined}
	 */
	ScrollBar.prototype.setPosition = function () {
		this.top = this.el.offsetTop + this.el.clientTop + (this.el.scrollTop * this.ratio);
		var rectEl = this.el.getBoundingClientRect();
		this.right = this.el.offsetLeft + this.el.clientLeft + this.el.clientWidth - this.scrollEl.clientWidth;
	};
	/**
	 * Sets the ratio fo the ScrollBar.
	 *
	 * Obtains the current heights for "this.el",
	 * and divides its "clientHeight" by its
	 * "scrollHeight".
	 *
	 * @return {undefined}
	 */
	ScrollBar.prototype.setRatio = function () {
		this.setHeights();
		this.ratio = this.outerHeight / this.scrollHeight;
	};
	/**
	 * Obtains the heights of the ScrollBar's
	 * "this.el" element: clientHeight and
	 * scrollHeight.
	 *
	 * @return {undefined}
	 */
	ScrollBar.prototype.setHeights = function () {
		this.outerHeight = this.el.clientHeight;
		this.scrollHeight = this.el.scrollHeight;
	};
	/**
	 * Sets all the event listeners for the ScrollBar.
	 *
	 * @return {undefined}
	 */
	ScrollBar.prototype.setEventListeners = function () {

		var scrollEl = document.getElementById(this.id);
		var body = document.getElementsByTagName('body')[0];

		// ON SCROLL EVENT
		this.el.onscroll = function () {
			this.setPosition();
			this.display();
		}.bind(this);

		// ON MOUSEDOWN
		this.scrollEl.onmousedown = function (e) {

			this.mousedown = true;
			this.scrollCenterY = e.offsetY;

			body.style['cursor'] = 'default';
			body.style['-webkit-touch-callout'] = 'none';
			body.style['-webkit-user-select'] = 'none';
			body.style['-khtml-user-select'] = 'none';
			body.style['-moz-user-select'] = 'none';
			body.style['-ms-user-select'] = 'none';
			body.style['user-select'] = 'none';

			this.beforeScrollClick(this);
		}.bind(this);

		// ON MOUSEUP
		window.onmouseup = function () {
			if (this.mousedown) {

				this.mousedown = false;
				this.scrollCenterX = undefined;
				this.scrollCenterY = undefined;

				body.style['cursor'] = '';
				body.style['-webkit-touch-callout'] = '';
				body.style['-webkit-user-select'] = '';
				body.style['-khtml-user-select'] = '';
				body.style['-moz-user-select'] = '';
				body.style['-ms-user-select'] = '';
				body.style['user-select'] = '';

				this.afterScrollClick(this);
			}
		}.bind(this);

		// ON MOUSEMOVE
		window.onmousemove = function (e) {
			if (this.mousedown) {
				var mouseY = e.clientY;
				var mouseDeltaY = e.movementY; //mouseY - (this.scrollCenterY + this.top);
				this.el.scrollTop = this.el.scrollTop + (mouseDeltaY / this.ratio);
			}
		}.bind(this);
	};

	return ScrollBar;
})();


text:
The file `streamer.js` implements a server, that accepts connections on port 3000 and starts sending image data to them live from a camera on the machine the server is running on.

Each time a connection is made the following data is sent:

* one `UInt16` for the width of the image
* one `UInt16` for the height of the image
* `3 * width * height` bytes of RGB data for the actual image
* `0` byte signifying the end of the image

##Consumer
Your task is to establish a connection to the server in `streamer.js` and save the output from it as a png file. Implement a `Transform` stream that takes the bytes sent from the server as input and produces a `Buffer` with the data to be written to the png file.

Write each frame you get from the server as a separate png file.

You can use the [png node module](https://www.npmjs.org/package/png) or [pngjs](https://www.npmjs.org/package/pngjs) for creating the file.

##Faking a video source
If you want to use a fake video instance you can look into [v4l2loopback](https://github.com/umlaeute/v4l2loopback), which can create a fake video device for you. Then you just need to feed it some signal, which you could do with gstreamer [as shown here](https://github.com/umlaeute/v4l2loopback/wiki/Gstreamer).


text:
require "graphql"

class MutationType
  def call
    GraphQL::ObjectType.define do
      name "MutationType"
      description "The mutation root of this schema"

      field :createUser, Types::User[:create_mutation]
      field :updateUser, Types::User[:update_mutation]
      field :destroyUser, Types::User[:destroy_mutation]
    end
  end
end


text:
.class public Landroid/renderscript/Short3;
.super Ljava/lang/Object;
.source "Short3.java"

# instance fields
.field public x:S

.field public y:S

.field public z:S

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 28
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 29
    return-void
.end method

.method public constructor <init>(SSS)V
    .locals 0
    .parameter "initX"
    .parameter "initY"
    .parameter "initZ"

    .prologue
    .line 31
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 32
    iput-short p1, p0, Landroid/renderscript/Short3;->x:S

    .line 33
    iput-short p2, p0, Landroid/renderscript/Short3;->y:S

    .line 34
    iput-short p3, p0, Landroid/renderscript/Short3;->z:S

    .line 35
    return-void
.end method


text:
#include <string.h>

#include <gtest/gtest.h>

#include <grpc/support/log.h>

#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/security/context/security_context.h"
#include "test/core/util/test_config.h"

TEST(AuthContextTest, EmptyContext) {
  grpc_core::RefCountedPtr<grpc_auth_context> ctx =
      grpc_core::MakeRefCounted<grpc_auth_context>(nullptr);
  grpc_auth_property_iterator it;

  gpr_log(GPR_INFO, "test_empty_context");
  ASSERT_NE(ctx, nullptr);
  ASSERT_EQ(grpc_auth_context_peer_identity_property_name(ctx.get()), nullptr);
  it = grpc_auth_context_peer_identity(ctx.get());
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), nullptr);
  it = grpc_auth_context_property_iterator(ctx.get());
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), nullptr);
  it = grpc_auth_context_find_properties_by_name(ctx.get(), "foo");
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), nullptr);
  ASSERT_EQ(grpc_auth_context_set_peer_identity_property_name(ctx.get(), "bar"),
            0);
  ASSERT_EQ(grpc_auth_context_peer_identity_property_name(ctx.get()), nullptr);
  ctx.reset(DEBUG_LOCATION, "test");
}

TEST(AuthContextTest, SimpleContext) {
  grpc_core::RefCountedPtr<grpc_auth_context> ctx =
      grpc_core::MakeRefCounted<grpc_auth_context>(nullptr);
  grpc_auth_property_iterator it;
  size_t i;

  gpr_log(GPR_INFO, "test_simple_context");
  ASSERT_NE(ctx, nullptr);
  grpc_auth_context_add_cstring_property(ctx.get(), "name", "chapi");
  grpc_auth_context_add_cstring_property(ctx.get(), "name", "chapo");
  grpc_auth_context_add_cstring_property(ctx.get(), "foo", "bar");
  ASSERT_EQ(ctx->properties().count, 3);
  ASSERT_EQ(
      grpc_auth_context_set_peer_identity_property_name(ctx.get(), "name"), 1);

  ASSERT_STREQ(grpc_auth_context_peer_identity_property_name(ctx.get()),
               "name");
  it = grpc_auth_context_property_iterator(ctx.get());
  for (i = 0; i < ctx->properties().count; i++) {
    const grpc_auth_property* p = grpc_auth_property_iterator_next(&it);
    ASSERT_EQ(p, &ctx->properties().array[i]);
  }
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), nullptr);

  it = grpc_auth_context_find_properties_by_name(ctx.get(), "foo");
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), &ctx->properties().array[2]);
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), nullptr);

  it = grpc_auth_context_peer_identity(ctx.get());
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), &ctx->properties().array[0]);
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), &ctx->properties().array[1]);
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), nullptr);

  ctx.reset(DEBUG_LOCATION, "test");
}

TEST(AuthContextTest, ChainedContext) {
  grpc_core::RefCountedPtr<grpc_auth_context> chained =
      grpc_core::MakeRefCounted<grpc_auth_context>(nullptr);
  grpc_auth_context* chained_ptr = chained.get();
  grpc_core::RefCountedPtr<grpc_auth_context> ctx =
      grpc_core::MakeRefCounted<grpc_auth_context>(std::move(chained));

  grpc_auth_property_iterator it;
  size_t i;

  gpr_log(GPR_INFO, "test_chained_context");
  grpc_auth_context_add_cstring_property(chained_ptr, "name", "padapo");
  grpc_auth_context_add_cstring_property(chained_ptr, "foo", "baz");
  grpc_auth_context_add_cstring_property(ctx.get(), "name", "chapi");
  grpc_auth_context_add_cstring_property(ctx.get(), "name", "chap0");
  grpc_auth_context_add_cstring_property(ctx.get(), "foo", "bar");
  ASSERT_EQ(
      grpc_auth_context_set_peer_identity_property_name(ctx.get(), "name"), 1);

  ASSERT_STREQ(grpc_auth_context_peer_identity_property_name(ctx.get()),
               "name");
  it = grpc_auth_context_property_iterator(ctx.get());
  for (i = 0; i < ctx->properties().count; i++) {
    const grpc_auth_property* p = grpc_auth_property_iterator_next(&it);
    ASSERT_EQ(p, &ctx->properties().array[i]);
  }
  for (i = 0; i < chained_ptr->properties().count; i++) {
    const grpc_auth_property* p = grpc_auth_property_iterator_next(&it);
    ASSERT_EQ(p, &chained_ptr->properties().array[i]);
  }
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), nullptr);

  it = grpc_auth_context_find_properties_by_name(ctx.get(), "foo");
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), &ctx->properties().array[2]);
  ASSERT_EQ(grpc_auth_property_iterator_next(&it),
            &chained_ptr->properties().array[1]);
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), nullptr);

  it = grpc_auth_context_peer_identity(ctx.get());
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), &ctx->properties().array[0]);
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), &ctx->properties().array[1]);
  ASSERT_EQ(grpc_auth_property_iterator_next(&it),
            &chained_ptr->properties().array[0]);
  ASSERT_EQ(grpc_auth_property_iterator_next(&it), nullptr);

  ctx.reset(DEBUG_LOCATION, "test");
}

TEST(AuthContextTest, ContextWithExtension) {
  class SampleExtension : public grpc_auth_context::Extension {};
  grpc_core::RefCountedPtr<grpc_auth_context> ctx =
      grpc_core::MakeRefCounted<grpc_auth_context>(nullptr);
  // Just set the extension, the goal of this test is to catch any memory
  // leaks when context goes out of scope.
  ctx->set_extension(std::make_unique<SampleExtension>());
}

int main(int argc, char** argv) {
  grpc::testing::TestEnvironment env(&argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import permission_utils.model_mixins

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ("know_me", "0001_initial"),
    ]

    operations = [
        migrations.CreateModel(
            name="KMUserAccessor",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                (
                    "created_at",
                    models.DateTimeField(
                        auto_now_add=True,
                        help_text="The time that the accessor was created.",
                        verbose_name="created at",
                    ),
                ),
                (
                    "email",
                    models.EmailField(
                        help_text="The email address used to invite the user.",
                        max_length=254,
                        verbose_name="email",
                    ),
                ),
                (
                    "is_accepted",
                    models.BooleanField(
                        default=False,
                        help_text="The KMUser has accepted the access.",
                        verbose_name="is accepted",
                    ),
                ),
                (
                    "is_admin",
                    models.BooleanField(
                        default=False,
                        help_text="A boolean indicating if the user has admin access.",
                        verbose_name="is admin",
                    ),
                ),
                (
                    "updated_at",
                    models.DateTimeField(
                        auto_now=True,
                        help_text="The time that the accessor was last updated.",
                        verbose_name="updated at",
                    ),
                ),
                (
                    "km_user",
                    models.ForeignKey(
                        help_text="The Know Me user this accessor grants access to.",
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="km_user_accessors",
                        related_query_name="km_user_accessor",
                        to="know_me.KMUser",
                        verbose_name="Know Me user",
                    ),
                ),
                (
                    "user_with_access",
                    models.ForeignKey(
                        null=True,
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="km_user_accessors",
                        related_query_name="km_user_accessor",
                        to=settings.AUTH_USER_MODEL,
                        verbose_name="user",
                    ),
                ),
            ],
            options={
                "verbose_name": "Know Me user accessor",
                "verbose_name_plural": "Know Me user accessors",
            },
            bases=(
                permission_utils.model_mixins.IsAuthenticatedMixin,
                models.Model,
            ),
        ),
        migrations.AlterUniqueTogether(
            name="kmuseraccessor",
            unique_together=set([("km_user", "user_with_access")]),
        ),
    ]


text:
set -euo pipefail

function main() {
	local mac='/usr/local/MacGPG2/libexec/pinentry-mac.app/Contents/MacOS/pinentry-mac'
	local other="$(which pinentry)"

	local dothis=''
	if test -x "${mac}"
	then
		dothis="${mac}"
	else
		dothis="${other}"
	fi

	exec "${dothis}" "${@}"
}

main


text:
namespace policy {

// Constants related to the device management protocol.
namespace dm_protocol {

// Name extern constants for URL query parameters.
POLICY_EXPORT extern const char kParamAgent[];
POLICY_EXPORT extern const char kParamAppType[];
POLICY_EXPORT extern const char kParamCritical[];
POLICY_EXPORT extern const char kParamDeviceID[];
POLICY_EXPORT extern const char kParamDeviceType[];
POLICY_EXPORT extern const char kParamLastError[];
POLICY_EXPORT extern const char kParamOAuthToken[];
POLICY_EXPORT extern const char kParamPlatform[];
POLICY_EXPORT extern const char kParamRequest[];
POLICY_EXPORT extern const char kParamRetry[];

// String extern constants for the device and app type we report to the server.
POLICY_EXPORT extern const char kValueAppType[];
POLICY_EXPORT extern const char kValueDeviceType[];
POLICY_EXPORT extern const char kValueRequestAutoEnrollment[];
POLICY_EXPORT extern const char kValueRequestPolicy[];
POLICY_EXPORT extern const char kValueRequestRegister[];
POLICY_EXPORT extern const char kValueRequestApiAuthorization[];
POLICY_EXPORT extern const char kValueRequestUnregister[];
POLICY_EXPORT extern const char kValueRequestUploadCertificate[];
POLICY_EXPORT extern const char kValueRequestDeviceStateRetrieval[];
POLICY_EXPORT extern const char kValueRequestUploadStatus[];
POLICY_EXPORT extern const char kValueRequestRemoteCommands[];
POLICY_EXPORT extern const char kValueRequestDeviceAttributeUpdatePermission[];
POLICY_EXPORT extern const char kValueRequestDeviceAttributeUpdate[];
POLICY_EXPORT extern const char kValueRequestGcmIdUpdate[];
POLICY_EXPORT extern const char kValueRequestCheckAndroidManagement[];
POLICY_EXPORT extern const char kValueRequestCertBasedRegister[];

// Policy type strings for the policy_type field in PolicyFetchRequest.
POLICY_EXPORT extern const char kChromeDevicePolicyType[];
POLICY_EXPORT extern const char kChromeUserPolicyType[];
POLICY_EXPORT extern const char kChromePublicAccountPolicyType[];
POLICY_EXPORT extern const char kChromeExtensionPolicyType[];
POLICY_EXPORT extern const char kChromeSigninExtensionPolicyType[];

// These codes are sent in the |error_code| field of PolicyFetchResponse.
enum PolicyFetchStatus {
  POLICY_FETCH_SUCCESS = 200,
  POLICY_FETCH_ERROR_NOT_FOUND = 902,
};

}  // namespace dm_protocol

// The header used to transmit the policy ID for this client.
POLICY_EXPORT extern const char kChromePolicyHeader[];

// Information about the verification key used to verify that policy signing
// keys are valid.
POLICY_EXPORT std::string GetPolicyVerificationKey();
POLICY_EXPORT extern const char kPolicyVerificationKeyHash[];

// Status codes for communication errors with the device management service.
// This enum is used to define the buckets for an enumerated UMA histogram.
// Hence,
//   (a) existing enumerated constants should never be deleted or reordered, and
//   (b) new constants should only be appended at the end of the enumeration.
enum DeviceManagementStatus {
  // All is good.
  DM_STATUS_SUCCESS = 0,
  // Request payload invalid.
  DM_STATUS_REQUEST_INVALID = 1,
  // The HTTP request failed.
  DM_STATUS_REQUEST_FAILED = 2,
  // The server returned an error code that points to a temporary problem.
  DM_STATUS_TEMPORARY_UNAVAILABLE = 3,
  // The HTTP request returned a non-success code.
  DM_STATUS_HTTP_STATUS_ERROR = 4,
  // Response could not be decoded.
  DM_STATUS_RESPONSE_DECODING_ERROR = 5,
  // Service error: Management not supported.
  DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED = 6,
  // Service error: Device not found.
  DM_STATUS_SERVICE_DEVICE_NOT_FOUND = 7,
  // Service error: Device token invalid.
  DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID = 8,
  // Service error: Activation pending.
  DM_STATUS_SERVICE_ACTIVATION_PENDING = 9,
  // Service error: The serial number is not valid or not known to the server.
  DM_STATUS_SERVICE_INVALID_SERIAL_NUMBER = 10,
  // Service error: The device id used for registration is already taken.
  DM_STATUS_SERVICE_DEVICE_ID_CONFLICT = 11,
  // Service error: The licenses have expired or have been exhausted.
  DM_STATUS_SERVICE_MISSING_LICENSES = 12,
  // Service error: The administrator has deprovisioned this client.
  DM_STATUS_SERVICE_DEPROVISIONED = 13,
  // Service error: Device registration for the wrong domain.
  DM_STATUS_SERVICE_DOMAIN_MISMATCH = 14,
  // Client error: Request could not be signed.
  DM_STATUS_CANNOT_SIGN_REQUEST = 15,
  // Service error: Policy not found. Error code defined by the DM folks.
  DM_STATUS_SERVICE_POLICY_NOT_FOUND = 902,
};

// List of modes that the device can be locked into.
enum DeviceMode {
  DEVICE_MODE_PENDING,             // The device mode is not yet available.
  DEVICE_MODE_NOT_SET,             // The device is not yet enrolled or owned.
  DEVICE_MODE_CONSUMER,            // The device is locally owned as consumer
                                   // device.
  DEVICE_MODE_ENTERPRISE,          // The device is enrolled as an enterprise
                                   // device.
  DEVICE_MODE_ENTERPRISE_AD,       // The device has joined AD.
  DEVICE_MODE_LEGACY_RETAIL_MODE,  // The device is enrolled as a retail kiosk
                                   // device. Even though retail mode is
                                   // deprecated, we still check for this device
                                   // mode so that if an existing device is
                                   // still enrolled in retail mode, we take the
                                   // appropriate action (currently, launching
                                   // offline demo mode).
  DEVICE_MODE_CONSUMER_KIOSK_AUTOLAUNCH,  // The device is locally owned as
                                          // consumer kiosk with ability to auto
                                          // launch a kiosk webapp.
};

}  // namespace policy

#endif  // COMPONENTS_POLICY_CORE_COMMON_CLOUD_CLOUD_POLICY_CONSTANTS_H_


text:
package org.cogroo.tools.checker.rules.validator;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.cogroo.entities.Mistake;
import org.cogroo.text.Document;
import org.cogroo.tools.checker.rules.applier.RulesApplier;

public class RulePostValidatorProvider implements RulePostValidator {

  private static final Map<String, RulePostValidator> VALIDATORS;

  static {
    Map<String, RulePostValidator> _validator = new HashMap<String, RulePostValidator>();

    // TODO: comentado para LABXP 2015
//    _validator.put(id("124"), new Rule124Validator());

    VALIDATORS = Collections.unmodifiableMap(_validator);
  }

  private static String id(String value) {
    return RulesApplier.ID_PREFIX + value;
  }

  @Override
  public boolean isValid(Mistake mistake, Document doc) {
    if (VALIDATORS.containsKey(mistake.getRuleIdentifier())) {
      return VALIDATORS.get(mistake.getRuleIdentifier()).isValid(mistake, doc);
    }
    return true;
  }
}


text:
/**
* LoginController
* @namespace crowdsource.authentication.controllers
*/
(function () {
  'use strict';

  angular
    .module('crowdsource.authentication.controllers')
    .controller('LoginController', LoginController);

  LoginController.$inject = ['$window', '$location', '$scope', 'Authentication', 'cfpLoadingBar', '$alert'];

  /**
  * @namespace LoginController
  */
  function LoginController($window, $location, $scope, Authentication, cfpLoadingBar, $alert) {
    var vm = this;

    vm.login = login;

    activate();

    /**
    * @name activate
    * @desc Actions to be performed when this controller is instantiated
    * @memberOf crowdsource.authentication.controllers.LoginController
    */
    function activate() {
      // If the user is authenticated, they should not be here.
      if (Authentication.isAuthenticated()) {
        $location.url('/');
      }
    }

    /**
    * @name login
    * @desc Log the user in
    * @memberOf crowdsource.authentication.controllers.LoginController
    */
    function login() {
      cfpLoadingBar.start();

      Authentication.login(vm.email, vm.password).then(function success(data, status) {

        Authentication.setAuthenticatedAccount(data.data);
        //$window.location = '/home'
            Authentication.getOauth2Token(data.data.username, vm.password,
                "password", data.data.client_id, data.data.client_secret).then(function success(data, status) {
                Authentication.setOauth2Token(data.data);
                $window.location = '/home'
              }, function error(data, status) {
                    vm.error = data.data.detail;
                    $scope.form.$setPristine();
              });
      }, function error(data, status) {
          vm.error = data.data.detail;
          $scope.form.$setPristine();

      }).finally(function () {
        cfpLoadingBar.complete();
      });
    }
  }
})();


text:
<?php
    session_start();
//    var_dump($_SESSION) ;
?>

<?php

if (!isset($test)) {
    $test = '';
}
if (!isset($tools)) {
    $tools = '';
}
if (!isset($resources)) {
    $resources = '';
}

?>

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#painstmenu">
                Toggle navigation

            </button>

        Piper Instrumentation

                <li class="model-select <?= $test ?>" id="test-menu-select">Test

                <li class="model-select <?= $resources ?>" id="resc-menu-select">Resources

                <li class="model-select <?= $tools ?>" id="tools-menu-select">Tools

                <?php if(isset($_SESSION['USER_MODE'])) {
                    if($_SESSION['USER_MODE']='ADMIN') { ?>

                 <?php   }
                }
                ?>

                    Action


text:
package org.apache.geode.distributed.internal.membership.gms.messenger;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.protocols.UNICAST3;
import org.jgroups.protocols.pbcast.NAKACK2;
import org.jgroups.protocols.pbcast.NakAckHeader2;
import org.jgroups.stack.IpAddress;
import org.jgroups.stack.Protocol;
import org.jgroups.util.UUID;

/**
 * InterceptUDP replaces the regular UDP JGroups messaging protocol for unit testing. It does not
 * create a datagram socket and is only set up to record message counts and respond to Unicast to
 * keep it from retransmitting
 */
public class InterceptUDP extends Protocol {

  static final int MEMBERSHIP_PORT = 12345;

  private final short nakackHeaderId = ClassConfigurator.getProtocolId(NAKACK2.class);
  private final short unicastHeaderId = ClassConfigurator.getProtocolId(UNICAST3.class);

  UUID uuid;
  // IpAddress addr;
  // Map<UUID, IpAddress> addressMap;
  int unicastSentDataMessages;
  int mcastSentDataMessages;

  boolean collectMessages = false;
  List<Message> collectedMessages = new LinkedList<>();

  public InterceptUDP() {
    // uuid = new UUID();
    // try {
    // addr = new IpAddress("localhost", MEMBERSHIP_PORT);
    // } catch (UnknownHostException e) {
    // throw new RuntimeException("unexpected exception", e);
    // }
    // addressMap = new HashMap<>();
    // addressMap.put(uuid, addr);
  }

  @Override
  public Object up(Event evt) {
    return up_prot.up(evt);
  }

  @Override
  public Object down(Event evt) {
    switch (evt.getType()) {
      case Event.MSG:
        handleMessage((Message) evt.getArg());
        return null;
      case Event.SET_LOCAL_ADDRESS:
        uuid = (UUID) evt.getArg();
        break;
    }
    return down_prot.down(evt);
  }

  private void handleMessage(Message msg) {
    if (collectMessages) {
      collectedMessages.add(msg);
    }
    Object o = msg.getHeader(nakackHeaderId);
    if (o != null) {
      mcastSentDataMessages++;
    } else {
      o = msg.getHeader(unicastHeaderId);
      if (o != null) {
        UNICAST3.Header hdr = (UNICAST3.Header) o;
        switch (hdr.type()) {
          case UNICAST3.Header.DATA:
            unicastSentDataMessages++;
            Message response = new Message(uuid, msg.getDest(), null);
            response.putHeader(unicastHeaderId, UNICAST3.Header.createAckHeader(hdr.seqno(),
                hdr.connId(), System.currentTimeMillis()));
            up_prot.up(new Event(Event.MSG, response));
            break;
        }
      }
    }
  }
}


text:
'use strict';

var _                 = require('mano').i18n.bind('View: Statistics')
  , memoize           = require('memoizee')
  , location          = require('mano/lib/client/location')
  , queryHandlerConf  = require('../apps/statistics/flow-query-conf')
  , setupQueryHandler = require('../utils/setup-client-query-handler')
  , getData           = require('mano/lib/client/xhr-driver').get
  , copy              = require('es5-ext/object/copy')
  , ObservableValue   = require('observable-value')
  , dateFromToBlock   = require('./components/filter-bar/select-date-range-safe-fallback')
  , getDurationDaysHours = require('./utils/get-duration-days-hours-fine-grain');

var queryServer = memoize(function (query) {
	return getData('/get-dashboard-data/', query);
}, {
	normalizer: function (args) { return JSON.stringify(args[0]); },
	max: 1000
});

exports._parent = require('./user-base');

exports['dashboard-nav'] = { class: { 'submitted-menu-item-active': true } };

var getTablesFromData = function (certData) {
	return list(certData, function (item) {
		return [
			section({ class: 'section-secondary' },
				h4(item.header),
				table(
					{ class: 'statistics-table statistics-table-registrations' },
					thead(
						th({ class: 'statistics-table-header-waiting' }, _("Category")),
						th({ class: 'statistics-table-header-waiting' }, _("Certificate")),
						th({ class: 'statistics-table-header-waiting' }, _("Number of issued"))
					),
					tbody(
						list(item.data, function (row) {
							if (!row) return;

							return tr(list(row, function (cell) {
								return td({ class: 'statistics-table-number' }, cell);
							}));
						})
					)
				)),
			br()
		];
	});
};

var renderPendingToNonPendingCount = function (data) {
	return section({ class: 'section-secondary' },
		table(
			{ class: 'statistics-table statistics-table-registrations' },
			thead(
				th({ class: 'statistics-table-header-waiting' }, _("Role")),
				th({ class: 'statistics-table-header-waiting' }, _("All cases")),
				th({ class: 'statistics-table-header-waiting' }, _("Cases leading to validation")),
				th({ class: 'statistics-table-header-waiting' }, _("Cases leading to send back")),
				th({ class: 'statistics-table-header-waiting' }, _("Cases leading to rejection")),
				th({ class: 'statistics-table-header-waiting' }, _("Cases leading to pause"))
			),
			tbody(data.map(function (value) {
				return list(Object.keys(value), function (key) {
					return tr(
						td({ class: 'statistics-table-number' }, value[key].label),
						td({ class: 'statistics-table-number' }, value[key].all),
						td({ class: 'statistics-table-number' }, value[key].approved),
						td({ class: 'statistics-table-number' }, value[key].sentBack),
						td({ class: 'statistics-table-number' }, value[key].rejected),
						td({ class: 'statistics-table-number' }, value[key].paused)
					);
				});
			}))
		));
};

var renderApprovedByRoleWithTimes = function (data) {
	return section({ class: 'section-secondary' },
		table(
			{ class: 'statistics-table statistics-table-registrations' },
			thead(
				th({ class: 'statistics-table-header-waiting' }, _("Service")),
				th({ class: 'statistics-table-header-waiting' }, _("Role")),
				th({ class: 'statistics-table-header-waiting' }, _("Cases")),
				th({ class: 'statistics-table-header-waiting' }, _("Average time"))
			),
			tbody(data.map(function (value) {
				return list(Object.keys(value), function (key) {
					var stepEntry = value[key];
					return list(Object.keys(stepEntry.services), function (serviceName) {
						var serviceEntry = stepEntry.services[serviceName];
						return tr(
							td({ class: 'statistics-table-number' }, serviceEntry.label),
							td({ class: 'statistics-table-number' }, stepEntry.label),
							td({ class: 'statistics-table-number' }, serviceEntry.count),
							td({ class: 'statistics-table-number' }, serviceEntry.avgTime ?
									getDurationDaysHours(serviceEntry.avgTime) : "-")
						);
					});
				});
			}))
		));
};

var renderApprovedByRoleWithTimeRanges = function (data) {
	return section({ class: 'section-secondary' },
		table(
			{ class: 'statistics-table statistics-table-registrations' },
			thead(
				th({ class: 'statistics-table-header-waiting' }, _("Service")),
				th({ class: 'statistics-table-header-waiting' }, _("Role")),
				th({ class: 'statistics-table-header-waiting' }, _("Less than 1 hour")),
				th({ class: 'statistics-table-header-waiting' }, _("Between 1 and 5 hours")),
				th({ class: 'statistics-table-header-waiting' }, _("More than 5 hours"))
			),
			tbody(data.map(function (value) {
				return list(Object.keys(value), function (key) {
					var stepEntry = value[key];
					return list(Object.keys(stepEntry.services), function (serviceName) {
						var serviceEntry = stepEntry.services[serviceName];
						return tr(
							td({ class: 'statistics-table-number' }, serviceEntry.label),
							td({ class: 'statistics-table-number' }, stepEntry.label),
							td({ class: 'statistics-table-number' }, serviceEntry.countLessThanHour),
							td({ class: 'statistics-table-number' }, serviceEntry.countBetweenHourAnd5Hours),
							td({ class: 'statistics-table-number' }, serviceEntry.countOver5Hours)
						);
					});
				});
			}))
		));
};

exports['sub-main'] = {
	class: { content: true },
	content: function () {
		var queryHandler, data = {}, handlerConf;

		data.certificatesIssued = new ObservableValue([]);
		data.pendingToNonPendingCount = new ObservableValue({});
		data.approvedByRoleWithTimes = new ObservableValue({});

		handlerConf = queryHandlerConf.slice(0);
		queryHandler = setupQueryHandler(handlerConf,
			location, '/');

		queryHandler.on('query', function (query) {
			var serverQuery = copy(query);
			if (serverQuery.dateFrom) {
				serverQuery.dateFrom = serverQuery.dateFrom.toJSON();
			}
			if (serverQuery.dateTo) {
				serverQuery.dateTo = serverQuery.dateTo.toJSON();
			}
			queryServer(serverQuery).done(function (serverData) {
				data.certificatesIssued.value = serverData.certificatesIssued;
				data.pendingToNonPendingCount.value = serverData.pendingToNonPendingCount;
				data.approvedByRoleWithTimes.value = serverData.approvedByRoleWithTimes;
			});
		});

		section({ class: 'first-out-of-section-element date-period-selector-out-of-section-block' },
			form({ action: '/', autoSubmit: true },
				dateFromToBlock(),
				p({ class: 'submit' }, input({ type: 'submit' }))));

		section({ class: "section-primary" },
			h3(_("Certficates issued")),
			getTablesFromData(data.certificatesIssued));

		section({ class: "section-primary" },
			h3(_("Send back to correction")),
			renderPendingToNonPendingCount(data.pendingToNonPendingCount));

		section({ class: "section-primary" },
			h3(_("Times of processing until approval")),
			renderApprovedByRoleWithTimes(data.approvedByRoleWithTimes));

		section({ class: "section-primary" },
			h3(_("Duration of the process")),
			renderApprovedByRoleWithTimeRanges(data.approvedByRoleWithTimes));
	}
};