text:
.. BBC Microbit Micropython documentation master file, created by
   sphinx-quickstart on Tue Oct 20 10:41:30 2015.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

BBC micro:bit MicroPython documentation
=======================================

Welcome!

The BBC micro:bit is a small computing device for children. One of the
languages it understands is the popular Python programming language. The
version of Python that runs on the BBC micro:bit is called MicroPython.

This documentation includes lessons for teachers
and API documentation for developers (check out the index on the left). We hope
you enjoy developing for the BBC micro:bit using MicroPython.

If you're a new programmer, teacher or unsure where to start, begin with the tutorials.

.. image:: comic.png

To get involved with the community subscribe to the microbit@python.org
mailing list (https://mail.python.org/mailman/listinfo/microbit).

.. note::

    This project is under active development. Please help other
    developers by adding tips, how-tos, and Q&A to this document.
    Thanks!

Projects related to MicroPython on the BBC micro:bit include:

* `Mu <https://github.com/ntoll/mu>`_ - a simple code editor for kids, teachers and beginner programmers. Probably the easiest way for people to program MicroPython on the BBC micro:bit.
* `uFlash <http://uflash.readthedocs.org/en/latest/>`_ - a command line tool for flashing raw Python scripts onto a BBC micro:bit.

.. toctree::
    :maxdepth: 2
    :caption: Tutorials

    tutorials/introduction
    tutorials/hello
    tutorials/images
    tutorials/buttons
    tutorials/io
    tutorials/music
    tutorials/random
    tutorials/movement
    tutorials/gestures
    tutorials/direction
    tutorials/storage
    tutorials/speech
    tutorials/network
    tutorials/radio
    tutorials/next

.. toctree::
   :maxdepth: 2
   :caption: API Reference

   microbit_micropython_api.rst
   microbit.rst
   accelerometer.rst
   ble.rst
   button.rst
   compass.rst
   display.rst
   filesystem.rst
   i2c.rst
   image.rst
   music.rst
   neopixel.rst
   os.rst
   pin.rst
   radio.rst
   random.rst
   speech.rst
   spi.rst
   uart.rst

.. toctree::
   :maxdepth: 2
   :caption: Developer Guide

   devguide/installation
   devguide/flashfirmware
   devguide/repl
   devguide/devfaq
   devguide/contributing

.. toctree::
   :maxdepth: 2
   :caption: Indices and tables

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
using System.Collections.Generic;

namespace Fixie.AutoRun.Events
{
   public class ShowSettingsEvent
   {
      public SolutionSettings Settings { get; set; }
      public IReadOnlyCollection<string> Configurations { get; set; }
      public IReadOnlyCollection<string> Platforms { get; set; }
   }
}

redpajama_set_name: RedPajamaGithub


text:
package it.smartcommunitylab.aac.manager;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import javax.script.ScriptException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.nimbusds.jwt.JWTClaimsSet;

import delight.nashornsandbox.NashornSandbox;
import delight.nashornsandbox.NashornSandboxes;
import delight.nashornsandbox.exceptions.ScriptCPUAbuseException;
import it.smartcommunitylab.aac.Config;
import it.smartcommunitylab.aac.Config.CLAIM_TYPE;
import it.smartcommunitylab.aac.common.InvalidDefinitionException;
import it.smartcommunitylab.aac.dto.AccountProfile;
import it.smartcommunitylab.aac.dto.BasicProfile;
import it.smartcommunitylab.aac.dto.ClientClaimProfileDTO;
import it.smartcommunitylab.aac.dto.ServiceDTO;
import it.smartcommunitylab.aac.dto.ServiceDTO.ServiceClaimDTO;
import it.smartcommunitylab.aac.dto.UserClaimProfileDTO;
import it.smartcommunitylab.aac.model.ClientAppInfo;
import it.smartcommunitylab.aac.model.ClientClaim;
import it.smartcommunitylab.aac.model.ClientDetailsEntity;
import it.smartcommunitylab.aac.model.Role;
import it.smartcommunitylab.aac.model.ServiceClaim;
import it.smartcommunitylab.aac.model.User;
import it.smartcommunitylab.aac.model.UserClaim;
import it.smartcommunitylab.aac.repository.ClientClaimRepository;
import it.smartcommunitylab.aac.repository.ClientDetailsRepository;
import it.smartcommunitylab.aac.repository.UserClaimRepository;

/**
 * @author raman
 *
 */
@Component
@Transactional
public class ClaimManager {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserManager userManager;
	@Autowired
	private ProfileManager profileManager;
	@Autowired
	private ServiceManager serviceManager;
	@Autowired
	private UserClaimRepository userClaimRepository;
	@Autowired
	private ClientClaimRepository clientClaimRepository;
    @Autowired
    private ClientDetailsRepository clientDetailsRepository;

	private Set<String> profileScopes = Sets.newHashSet(Config.SCOPE_BASIC_PROFILE);
	private Set<String> accountScopes = Sets.newHashSet(Config.SCOPE_ACCOUNT_PROFILE);
	private Set<String> roleScopes = Sets.newHashSet(Config.SCOPE_ROLE, Config.SCOPE_GROUP);

	// claims that should not be overwritten
	private Set<String> reservedScopes = JWTClaimsSet.getRegisteredNames();
	private Set<String> systemScopes = Sets.newHashSet("scope", "token_type", "client_id", "active", "roles", "groups", "username", "user_name", "space");

	private static final ObjectMapper mapper = new ObjectMapper();

	/**
	 * Create user claims map considering the authorized scopes, authorized claims and request claims.
	 * The claims are constructed based on the user roles, user info, and accounts info
	 * @param user
	 * @param authorities
	 * @param client
	 * @param scopes
	 * @param authorizedClaims
	 * @param requestedClaims
	 * @return
	 */
	@Transactional(readOnly = true)
	public Map<String, Object> getUserClaims(String userId, Collection<? extends GrantedAuthority> authorities, ClientDetailsEntity client, Set<String> scopes, JsonObject authorizedClaims, JsonObject requestedClaims) {
		ClientAppInfo appInfo = ClientAppInfo.convert(client.getAdditionalInformation());
		try {
			return createUserClaims(userId, authorities, appInfo.getClaimMapping(), scopes, authorizedClaims, requestedClaims, appInfo.getUniqueSpaces(), appInfo.getRolePrefixes(), true, null);
		} catch (InvalidDefinitionException e) {
			// never arrives here
			return null;
		}
	}

	/**
	 * Return claims explicitly associated to the client application
	 * @param clientId
	 * @param scopes
	 * @return
	 */
	@Transactional(readOnly = true)
	public Map<String, Object> getClientClaims(String clientId, Set<String> scopes) {
		List<ClientClaim> claims = clientClaimRepository.findByClient(clientId);
		if (claims.isEmpty()) return Collections.emptyMap();

		Map<String, Object> res = new HashMap<>();
		Set<String> allowedByScope = getClaimsForScopeSet(scopes);
		Set<String> authorizedByClaims = Collections.emptySet();
		Set<String> requestedByClaims = Collections.emptySet();

		for (ClientClaim claim: claims) {
			String qname = ServiceClaim.qualifiedName(claim.getClaim().getService().getNamespace(), claim.getClaim().getClaim());
			if (claimAllowed(qname, allowedByScope, authorizedByClaims, requestedByClaims)) {
				res.put(qname, ServiceClaim.typedValue(claim.getClaim(), claim.getValue()));
			}
		}
		return res;
	}

	/**
	 * Create user claims map considering the authorized scopes.
	 * The claims are constructed based on the user roles, user info, and accounts info
	 * @param user
	 * @param appInfo
	 * @param scopes
	 * @param authorizedClaims
	 * @param requestedClaims
	 * @return
	 * @throws InvalidDefinitionException
	 */
	@Transactional(readOnly = true)
	public Map<String, Object> validateUserClaimsForClientApp(User user, ClientAppInfo appInfo, Set<String> scopes) throws InvalidDefinitionException {
		return createUserClaims(user.getId().toString(), user.getRoles(), appInfo.getClaimMapping(), scopes, null, null, appInfo.getUniqueSpaces(), appInfo.getRolePrefixes(), false, null);
	}

	/**
	 * Validate service claim mapping definition. Check if and only if the valid claims are produced
	 * @param user
	 * @param serviceId
	 * @param mapping
	 * @param scopes
	 * @return
	 * @throws InvalidDefinitionException
	 */
	@Transactional(readOnly = true)
	public Map<String, Object> validateClaimMapping(User user, String serviceId, String mapping, Set<String> scopes) throws InvalidDefinitionException {
		Map<String, Object> res = createUserClaims(user.getId().toString(), user.getRoles(), mapping, scopes, null, null, null, null, false, serviceId);
		ServiceDTO service = serviceManager.getService(serviceId);
		service.setClaims(serviceManager.getServiceClaims(serviceId));
		validateMappedClaims(res, service);
		return res;
	}

	/**
	 * Get users with the stored claims for the specified service
	 * @param owner
	 * @param serviceId
	 * @param name
	 * @param page
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<UserClaimProfileDTO> getServiceUserClaims(User owner, String serviceId, String name, Pageable page) {
		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return new PageImpl<>(Collections.emptyList());
		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		if (name == null) name = "";
		Page<Object[]> userData = userClaimRepository.findUserDataByService(serviceId.toLowerCase(), name.toLowerCase(), page);
		return userData.map(arr -> new UserClaimProfileDTO(arr[0] == null ? null: ((Long)arr[0]).toString(), (String)arr[1]));
	}

	/**
	 * Get custom claims of the user for the specified service
	 * @param owner
	 * @param serviceId
	 * @param userId
	 * @return
	 */
	@Transactional(readOnly = true)
	public UserClaimProfileDTO getServiceUserClaims(User owner, String serviceId, String userId) {
		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return null;
		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		List<UserClaim> claims = userClaimRepository.findByUserAndService(Long.parseLong(userId), serviceId);
		UserClaimProfileDTO user = new UserClaimProfileDTO();
		User dbUser = claims.get(0).getUser();

		if (claims.isEmpty()) {
			dbUser = userManager.findOne(Long.parseLong(userId));
		} else {
			dbUser = claims.get(0).getUser();
		}
		user.setUserId(dbUser.getId().toString());
		user.setUsername(dbUser.getUsername());
		user.setClaims(new HashMap<>());
		claims.forEach(uc -> user.getClaims().put(ServiceClaim.qualifiedName(service.getNamespace(), uc.getClaim().getClaim()), ServiceClaim.typedValue(uc.getClaim(), uc.getValue())));
		return user;

	}
	@Transactional(readOnly = true)
	public UserClaimProfileDTO getServiceUserClaimsForUsername(User owner, String serviceId, String username) {
		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return null;
		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		List<UserClaim> claims = userClaimRepository.findByUsernameAndService(username, serviceId);
		UserClaimProfileDTO user = new UserClaimProfileDTO();
		user.setUsername(username);
		user.setClaims(new HashMap<>());
		claims.forEach(uc -> user.getClaims().put(ServiceClaim.qualifiedName(service.getNamespace(), uc.getClaim().getClaim()), ServiceClaim.typedValue(uc.getClaim(), uc.getValue())));
		return user;

	}

	/**
	 * Update claims for the specified user
	 * @param owner
	 * @param serviceId
	 * @param userId
	 * @param dto
	 * @return
	 * @throws InvalidDefinitionException
	 */
	public UserClaimProfileDTO saveServiceUserClaims(User owner, String serviceId, String userId, UserClaimProfileDTO dto) throws InvalidDefinitionException {
		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return null;
		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		List<UserClaim> claims = userClaimRepository.findByUserAndService(Long.parseLong(userId), serviceId);
		if (!claims.isEmpty()) {
			userClaimRepository.delete(claims);
		}
		Map<String, ServiceClaim> qClaims = serviceManager.getServiceClaimsDB(serviceId).stream().collect(Collectors.toMap(c -> ServiceClaim.qualifiedName(service.getNamespace(), c.getClaim()), c -> c));
		User dbUser = userManager.findOne(Long.parseLong(userId));

		for (Entry<String, Object> entry : dto.getClaims().entrySet()) {
			if (!qClaims.containsKey(entry.getKey())) {
				throw new SecurityException("Unauthorized claim modification: " + serviceId+", "+ entry.getKey());
			}
			ServiceClaim serviceClaim = qClaims.get(entry.getKey());
			UserClaim uc = new UserClaim();
			uc.setUser(dbUser);
			if (dbUser.getUsername() != null) uc.setUsername(dbUser.getUsername().toLowerCase());
			uc.setValue(retrieveClaimValue(entry, serviceClaim));
			uc.setClaim(serviceClaim);
			userClaimRepository.save(uc);
		}

		return getServiceUserClaims(owner, serviceId, userId);
	}

	public UserClaimProfileDTO saveServiceUserClaimsByUsername(User owner, String serviceId, String username, UserClaimProfileDTO dto) throws InvalidDefinitionException {
		User user = userManager.getUserByUsername(username);
		if (user != null) {
			return saveServiceUserClaims(owner, serviceId, user.getId().toString(), dto);
		}

		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return null;
		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		List<UserClaim> claims = userClaimRepository.findByUsernameAndService(username, serviceId);
		if (!claims.isEmpty()) {
			userClaimRepository.delete(claims);
		}
		Map<String, ServiceClaim> qClaims = serviceManager.getServiceClaimsDB(serviceId).stream().collect(Collectors.toMap(c -> ServiceClaim.qualifiedName(service.getNamespace(), c.getClaim()), c -> c));

		Map<String, Object> resClaims = new HashMap<>();
		for (Entry<String, Object> entry : dto.getClaims().entrySet()) {
			if (!qClaims.containsKey(entry.getKey())) {
				throw new SecurityException("Unauthorized claim modification: " + serviceId+", "+ entry.getKey());
			}
			ServiceClaim serviceClaim = qClaims.get(entry.getKey());
			UserClaim uc = new UserClaim();
			uc.setUser(null);
			uc.setUsername(username.toLowerCase());
			uc.setValue(retrieveClaimValue(entry, serviceClaim));
			uc.setClaim(serviceClaim);
			userClaimRepository.save(uc);
			resClaims.put(entry.getKey(), entry.getValue());
		}

		UserClaimProfileDTO res = new UserClaimProfileDTO();
		res.setUsername(username.toLowerCase());
		res.setClaims(resClaims);
		return res;

	}

	protected String retrieveClaimValue(Entry<String, Object> entry, ServiceClaim serviceClaim)
			throws InvalidDefinitionException {
		if (!ServiceClaim.ofType(entry.getValue(), serviceClaim.isMultiple(), serviceClaim.getType())) {
			throw new InvalidDefinitionException("Invalid claim value. Claim "+ entry.getKey() +", " +entry.getValue());
		}
		try {
			return mapper.writeValueAsString(entry.getValue());
		} catch (JsonProcessingException e) {
			throw new InvalidDefinitionException("Invalid claim value. Claim "+ entry.getKey() +", " +entry.getValue());
		}
	}

	public void deleteServiceUserClaims(User owner, String serviceId, String userId) {
		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return;
		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		userClaimRepository.delete(userClaimRepository.findByUserAndService(Long.parseLong(userId), serviceId));
	}
	public void deleteServiceUserClaimsByUsername(User owner, String serviceId, String username) {
		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return;
		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		userClaimRepository.delete(userClaimRepository.findByUsernameAndService(username, serviceId));
	}

	private Map<String, Object> createUserClaims(String userId, Collection<? extends GrantedAuthority> authorities, String mapping, Set<String> scopes, JsonObject authorizedClaims, JsonObject requestedClaims, Collection<String> uniqueSpaces, Collection<String> rolePrefixes, boolean suppressErrors, String excludedServiceId) throws InvalidDefinitionException {
		AccountProfile ui = profileManager.getAccountProfileById(userId);

		// get the base object
		Map<String, Object> obj = toBaseJson(ui);

		/*
		 * OpenID claims
		 * see https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
		 */
	      //TODO rework as per spec: profile etc should be filters
        //openid
        if(scopes.contains(Config.SCOPE_OPENID)) {
            obj.putAll(toOpenIdJson(ui));
        }
		//profile
		if(scopes.contains(Config.SCOPE_PROFILE)) {
		    obj.putAll(toProfileJson(ui));
		}

        // email
        if (scopes.contains(Config.SCOPE_EMAIL)) {
            obj.putAll(toEmailJson(ui));
        }

        //address
        //TODO

        //phone
        //TODO

        /*
         * AAC claims
         * (we can override openId claims)
         */
		//basic profile
        if (!Sets.intersection(scopes, profileScopes).isEmpty()) {
            obj.putAll(toProfileJson(ui));
        }

		//account
		if (!Sets.intersection(scopes, accountScopes).isEmpty()) {
			// account profiles
			AccountProfile accounts = profileManager.getAccountProfileById(userId);
			if (accounts != null && accounts.getAccounts() != null) {
				obj.put("accounts", accounts.getAccounts());
			}
		}

		//roles
		if (!Sets.intersection(scopes, roleScopes).isEmpty()) {
			try {
				Collection<? extends GrantedAuthority> filtered = authorities;
				if (rolePrefixes != null) {
					filtered = filtered.stream().filter(a -> {
						return rolePrefixes.stream().anyMatch(rp -> rp != null && a.getAuthority().toLowerCase().startsWith(rp));
					}).collect(Collectors.toSet());
				}
				Set<Role> roles = filtered.stream().map(a -> Role.parse(a.getAuthority())).collect(Collectors.toSet());

				if(scopes.contains(Config.SCOPE_ROLE)) {
				    //append roles as authorities list
				    populateRoleClaims(roles, obj);
				}

                if(scopes.contains(Config.SCOPE_GROUP)) {
                    //append groups as authorities list
                    populateGroupClaims(roles, obj);
                }

				//spaces
				if(uniqueSpaces != null && !uniqueSpaces.isEmpty()) {
				    //merge and output a fixed claim for spaces selections
				    Set<String> spaces = new HashSet<>();
				    for(Role r : roles) {
				        if(uniqueSpaces.contains(r.getContext())) {
				            spaces.add(r.getSpace());
				        }
				    }

				    //output only if populated
				    if(spaces.size() == 1) {
				        obj.put("space", spaces.iterator().next());
				    } else if (spaces.size() > 1) {
				        obj.put("space", spaces.toArray(new String[0]));
				    }
				}

			} catch (Exception e) {
				logger.error("error fetching roles for user "+userId, e);
			}
		}

		Set<String> allowedByScope = getClaimsForScopeSet(scopes);
		Set<String> authorizedByClaims = extractUserInfoClaimsIntoSet(authorizedClaims);
		Set<String> requestedByClaims = extractUserInfoClaimsIntoSet(requestedClaims);

		/*
		 * Filtering
		 */
		logger.trace("generated claims before filtering "+obj.toString());

		// Filter claims by performing a manual intersection of claims that are allowed by the given scope, requested, and authorized.
		// We cannot use Sets.intersection() or similar because Entry<> objects will evaluate to being unequal if their values are
		// different, whereas we are only interested in matching the Entry<>'s key values.
		Map<String, Object> result = new HashMap<String, Object>();
		for (Entry<String, Object> entry : obj.entrySet()) {

			if (claimAllowed(entry.getKey(), allowedByScope, authorizedByClaims, requestedByClaims)) {
					result.put(entry.getKey(), entry.getValue());
			} // otherwise there were specific claims requested and this wasn't one of them
		}
	    logger.trace("generated claims after filtering "+result.toString());

		// read store used claims and filter them for the scopes
		Map<String, Object> userClaims = getAllowedUserClaims(userId, allowedByScope, authorizedByClaims, requestedByClaims);
		result.putAll(userClaims);
		logger.trace("Claims after adding filtered user claims "+result.toString());

		// generate claims from service functions of the corresponding services. Add only new claims to the result
		for(String s: scopes) {
			//break for "default"
			if("default".equals(s)) {
				continue;
			}
			ServiceDTO service = serviceManager.getScopeService(s);
			if (service != null && service.getClaimMapping() != null && !service.getServiceId().equalsIgnoreCase(excludedServiceId)) {
				try {
					Map<String, Object> serviceMapping = customMapping(service.getClaimMapping(), new HashMap<>(result));
					serviceMapping = filterMappedClaims(serviceMapping, service);
					for (Entry<String, Object> entry : serviceMapping.entrySet()) {
						// skip generated claims or claims set explicitly
						if (!result.containsKey(entry.getKey()) && claimAllowed(entry.getKey(), allowedByScope, authorizedByClaims, requestedByClaims)) {
								result.put(entry.getKey(), entry.getValue());
						}
					}
				} catch (InvalidDefinitionException e) {
					if (suppressErrors) {
					    logger.error("custom mapping failed: "+e.getMessage()+". Service id: " + service.getServiceId());
					} else {
						throw e;
					}

				}
			}
		}
		logger.trace("Claims after adding mapped service claims "+result.toString());

		// apply mapping to correct result
		Map<String, Object> copy = new HashMap<>(result);
		try {
			obj = customMapping(mapping, copy);
		} catch (InvalidDefinitionException e) {
			if (suppressErrors) {
				logger.error("error mapping claims for user "+userId, e);
			} else {
				throw e;
			}
		}
		copy.clear();
		// keep all the new claims apart the system ones
		for (Entry<String, Object> entry : obj.entrySet()) {
			// skip system claims
			if (systemScopes.contains(entry.getKey()))  continue;
			copy.put(entry.getKey(), entry.getValue());

		}
		// add the system claims back from the original version
		for (String key : systemScopes) {
			if (result.containsKey(key)) {
				copy.put(key, result.get(key));
			}
		}

		//strip all reserved since they will be handled by jwt service
        for (String key : reservedScopes) {
            if (copy.containsKey(key)) {
                copy.remove(key);
            }
        }

        logger.trace("claims after custom mapping "+copy.toString());

		return copy;
	}

	/**
	 * Filter claim by the specified Service
	 * @param serviceMapping
	 * @param service
	 */
	private Map<String, Object> filterMappedClaims(Map<String, Object> serviceMapping, ServiceDTO service) {
		// verify that the result contains only the claims of this service
		Map<String, Object> res = new HashMap<>(serviceMapping);
		for (Entry<String, Object> entry : serviceMapping.entrySet()) {
			if (!service.claimMap().containsKey(entry.getKey())) {
				res.remove(entry.getKey());
			}
		}
		return res;
	}

	/**
	 * @param serviceMapping
	 * @param service
	 */
	private void validateMappedClaims(Map<String, Object> serviceMapping, ServiceDTO service) throws InvalidDefinitionException {
		// verify that the result contains only the claims of in correct format
		for (Entry<String, Object> entry : serviceMapping.entrySet()) {
			ServiceClaimDTO claim = service.claimMap().get(entry.getKey());
			if (claim == null) {
				throw new InvalidDefinitionException("Unknow claim: "+ entry.getKey());
			}
			Object v = entry.getValue();
			if (v != null) {
				if (!ServiceClaim.ofType(v, claim.isMultiple(), CLAIM_TYPE.get(claim.getType()))) {
					throw new InvalidDefinitionException("Invalid claim value. Claim " + claim.getClaim() +", value = " + v);
				}
			}
		}
	}

	protected Map<String, Object> getAllowedUserClaims(String userId, Set<String> allowedByScope, Set<String> authorizedByClaims, Set<String> requestedByClaims) {
		List<UserClaim> userClaims = userClaimRepository.findByUser(Long.parseLong(userId));
		Map<String, Object> claimMap = new HashMap<>();
		for (UserClaim uc : userClaims) {
			String qname = ServiceClaim.qualifiedName(uc.getClaim().getService().getNamespace(), uc.getClaim().getClaim());
			if (claimAllowed(qname, allowedByScope, authorizedByClaims, requestedByClaims)) {
				claimMap.put(qname, ServiceClaim.typedValue(uc.getClaim(), uc.getValue()));
			}
		}
		return  claimMap;
	}

	private boolean claimAllowed(String claim, Set<String> allowedByScope, Set<String> authorizedByClaims, Set<String> requestedByClaims) {
		return
				// it's allowed either by scope or by the authorized claims (either way is fine with us)
				(allowedByScope.contains(claim) || authorizedByClaims.contains(claim)) &&
				// the requested claims are empty (so we allow all), or they're not empty and this claim was specifically asked for
    			(requestedByClaims.isEmpty() || requestedByClaims.contains(claim));
	}

	/**
	 * Custom mapping for the user claims if defined by client
	 * @param user
	 * @param client
	 * @param obj
	 * @return
	 */
	private Map<String, Object> customMapping(String mapping, Map<String, Object> obj) throws InvalidDefinitionException {
		if (StringUtils.isEmpty(mapping)) return new HashMap<>(obj);

		String func = mapping;
		try {
			return executeScript(obj, func);
		} catch (ScriptCPUAbuseException e) {
			throw new InvalidDefinitionException("Script resource abuse: " + e.getMessage());
		} catch (Exception e) {
			throw new InvalidDefinitionException("Execution error: " + e.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	private Map<String, Object> executeScript(Map<String, Object> obj, String func) throws ScriptException, IOException {
		//TODO use a threadPool/cache to avoid the expensive sandbox creation at each call
	    NashornSandbox sandbox = createSandbox();
		try {
			ObjectMapper mapper = new ObjectMapper();
			StringWriter writer = new StringWriter();
			writer.append("claims = ");
			mapper.writeValue(writer, obj);
			writer.append(";");
			writer.append(func);
			writer.append("; result = JSON.stringify(claimMapping(claims))");
			sandbox.eval(writer.toString());
			String o = (String)sandbox.get("result");
			return mapper.readValue(o, HashMap.class);
		} finally {
			sandbox.getExecutor().shutdown();
		}
	}

	/**
	 * @param ui
	 * @return
	 */
    private Map<String, Object> toBaseJson(BasicProfile ui) {

        Map<String, Object> obj = new HashMap<>();
        // disable sub since it is reserved
//		obj.put("sub", ui.getUserId());

        return obj;
    }

    private Map<String, Object> toOpenIdJson(AccountProfile ui) {

        Map<String, Object> obj = new HashMap<>();
        obj.put("preferred_username", ui.getUsername());
        // also write username in alternate claim
        obj.put("username", ui.getUsername());
        // also write username in a spring-friendly form
        //https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/UserAuthenticationConverter.java
        obj.put("user_name", ui.getUsername());

        return obj;
    }

    private Map<String, Object> toProfileJson(AccountProfile ui) {

        Map<String, Object> obj = new HashMap<>();
        obj.put("name", ui.getSurname() + " " + ui.getName());
        obj.put("given_name", ui.getName());
        obj.put("family_name", ui.getSurname());

        //write username claims here so we get them even without openid scope
        obj.put("preferred_username", ui.getUsername());
        // also write username in alternate claim
        obj.put("username", ui.getUsername());
        // also write username in a spring-friendly form
        //https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/UserAuthenticationConverter.java
        obj.put("user_name", ui.getUsername());

        return obj;
    }

    private Map<String, Object> toEmailJson(AccountProfile ui) {

        Map<String, Object> obj = new HashMap<>();
        if (ui.getAccounts() != null) {
        	for (String account: ui.getAccounts().keySet()) {
        		Map<String, String> attrs = ui.getAccounts().get(account);
        		if (attrs.containsKey(Config.USER_ATTR_EMAIL)) {
        	        obj.put("email", ui.getUsername());
        	        obj.put("email_verified", true);
        	        return obj;
        		}
        	}
        }

        return obj;
    }

	private Set<String> getClaimsForScopeSet(Set<String> scopes) {
		return serviceManager.getClaimsForScopes(scopes);
	}

	/**
	 * Pull the claims that have been targeted into a set for processing.
	 * Returns an empty set if the input is null.
	 * @param claims the claims request to process
	 */
	private Set<String> extractUserInfoClaimsIntoSet(JsonObject claims) {
		Set<String> target = new HashSet<>();
		if (claims != null) {
			JsonObject userinfoAuthorized = claims.getAsJsonObject("userinfo");
			if (userinfoAuthorized != null) {
				for (Entry<String, JsonElement> entry : userinfoAuthorized.entrySet()) {
					target.add(entry.getKey());
				}
			}
		}
		return target;
	}

    private void populateGroupClaims(Set<Role> roles, Map<String, Object> claims) {
        if (roles != null) {

            // build list of "groups" (as plain array)
            // define a group as context+space, ignoring role
            Set<String> groups = new HashSet<>();
            for (Role role : roles) {
//                if (!StringUtils.isEmpty(role.getContext()) && !StringUtils.isEmpty(role.getSpace())) {
//                    groups.add(role.getContext() + "/" + role.getSpace());
//                }
                if (!StringUtils.isEmpty(role.getSpace())) {
                    groups.add(role.asSlug());
                }
            }
            claims.put("groups", groups.toArray(new String[0]));
        }
    }

	private void populateRoleClaims(Set<Role> roles, Map<String, Object> claims) {
		if (roles != null) {
            // build roles list as plain array
            Set<String> rolesList = new HashSet<>();
            for (Role role : roles) {
                rolesList.add(role.getAuthority());
            }
            claims.put("roles", rolesList.toArray(new String[0]));
//            if (!claims.containsKey("authorities")) {
//                claims.put("authorities", claims.get("roles"));
//            }
            // build also as realm/resource claims
            Set<String> realmRoles = new HashSet<>();
            for (Role role : roles) {
                if(StringUtils.isEmpty(role.getContext()) && StringUtils.isEmpty(role.getSpace())) {
                    realmRoles.add(role.getRole());
                }
            }
//            net.minidev.json.JSONObject realmRoleObj = new net.minidev.json.JSONObject();
//            realmRoleObj.put("roles", realmRoles.toArray(new String[0]));
//            claims.put("realm_access", realmRoleObj);

            Map<String,Set<String>> resourceRoles = new HashMap<>();
            for (Role role : roles) {
                // role is context/space:role
                if(!StringUtils.isEmpty(role.getContext()) && !StringUtils.isEmpty(role.getSpace())) {
                    // put as context/space:role
                    String key = role.getContext()+ "/"+role.getSpace();
                    if(!resourceRoles.containsKey(key)) {
                        resourceRoles.put(key, new HashSet<String>());
                    }
                    resourceRoles.get(key).add(role.getRole());
                } else if(!StringUtils.isEmpty(role.getContext()) && StringUtils.isEmpty(role.getSpace())) {
                    //put as context:role
                    if(!resourceRoles.containsKey(role.getContext())) {
                        resourceRoles.put(role.getContext(), new HashSet<String>());
                    }
                    resourceRoles.get(role.getContext()).add(role.getRole());
                }
            }

//            net.minidev.json.JSONObject resourceRolesObj = new net.minidev.json.JSONObject();
//            for(String res : resourceRoles.keySet()) {
//                net.minidev.json.JSONObject resObj = new net.minidev.json.JSONObject();
//                resObj.put("roles", resourceRoles.get(res).toArray(new String[0]));
//                resourceRolesObj.put(res, resObj);
//            }
//            claims.put("resource_access", resourceRolesObj);

            //MOVED to custom scope
//            // also build list of "groups" (as plain array)
//            // define a group as context+space, ignoring role
//            Set<String> groups = new HashSet<>();
//            for (Role role : roles) {
////                if (!StringUtils.isEmpty(role.getContext()) && !StringUtils.isEmpty(role.getSpace())) {
////                    groups.add(role.getContext() + "/" + role.getSpace());
////                }
//            	if (!StringUtils.isEmpty(role.getSpace())) {
//            		groups.add(role.asSlug());
//            	}
//            }
//            claims.put("groups", groups.toArray(new String[0]));
        }
	}

	private NashornSandbox createSandbox() {
		NashornSandbox sandbox;
		sandbox = NashornSandboxes.create();
		sandbox.setMaxCPUTime(100);
		sandbox.setMaxMemory(10*1024*1024);
		sandbox.setMaxPreparedStatements(30); // because preparing scripts for execution is expensive
		sandbox.setExecutor(Executors.newSingleThreadExecutor());
		return sandbox;
	}
//
//	public static void main(String[] args) throws Exception {
//		Map<String, Object> res = new ClaimManager().executeScript(
//				Collections.singletonMap("key", "value"),
//				"function(claims) {claims['a'] = 'b'; return claims;}"
//		);
//		System.err.println(res);
//	}

	/**
	 * @param owner
	 * @param serviceId
	 * @param name
	 * @param page
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<ClientClaimProfileDTO> getServiceClientClaims(User owner, String serviceId, Pageable page) {
		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return new PageImpl<>(Collections.emptyList());

		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		Page<String[]> clientData = clientClaimRepository.findClientDataByService(serviceId.toLowerCase(), page);
		return clientData.map(arr -> new ClientClaimProfileDTO(arr[0], arr[1]));
	}

	/**
	 * @param owner
	 * @param serviceId
	 * @param clientId
	 * @return
	 */
	@Transactional(readOnly = true)
	public ClientClaimProfileDTO getServiceClientClaims(User owner, String serviceId, String clientId) {
		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return null;

		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		List<ClientClaim> claims = clientClaimRepository.findByClientAndService(clientId, serviceId);
		ClientClaimProfileDTO clientClaims = new ClientClaimProfileDTO();
		ClientDetailsEntity client = null;

		if (claims.isEmpty()) {
			client = clientDetailsRepository.findByClientId(clientId);
		} else {
			client = claims.get(0).getClient();
		}
		clientClaims.setClientId(clientId);
		clientClaims.setName(client.getName());
		clientClaims.setClaims(new HashMap<>());
		claims.forEach(cc -> clientClaims.getClaims().put(ServiceClaim.qualifiedName(service.getNamespace(), cc.getClaim().getClaim()), ServiceClaim.typedValue(cc.getClaim(), cc.getValue())));
		return clientClaims;
	}

	/**
	 * @param owner
	 * @param serviceId
	 * @param clientId
	 * @param dto
	 * @return
	 * @throws InvalidDefinitionException
	 */
	public ClientClaimProfileDTO saveServiceClientClaims(User owner, String serviceId, String clientId, ClientClaimProfileDTO dto) throws InvalidDefinitionException {
		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return null;
		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		List<ClientClaim> claims = clientClaimRepository.findByClientAndService(clientId, serviceId);
		if (!claims.isEmpty()) {
			clientClaimRepository.delete(claims);
		}
		Map<String, ServiceClaim> qClaims = serviceManager.getServiceClaimsDB(serviceId).stream().collect(Collectors.toMap(c -> ServiceClaim.qualifiedName(service.getNamespace(), c.getClaim()), c -> c));
		ClientDetailsEntity client = clientDetailsRepository.findByClientId(clientId);

		for (Entry<String, Object> entry : dto.getClaims().entrySet()) {
			if (!qClaims.containsKey(entry.getKey())) {
				throw new SecurityException("Unauthorized claim modification: " + serviceId+", "+ entry.getKey());
			}
			ServiceClaim serviceClaim = qClaims.get(entry.getKey());
			ClientClaim cc = new ClientClaim();
			cc.setClient(client);
			cc.setValue(retrieveClaimValue(entry, serviceClaim));
			cc.setClaim(serviceClaim);
			clientClaimRepository.save(cc);
		}

		return getServiceClientClaims(owner, serviceId, clientId);
	}

	/**
	 * @param owner
	 * @param serviceId
	 * @param clientId
	 */
	public void deleteServiceClientClaims(User owner, String serviceId, String clientId) {
		Set<String> userContexts = serviceManager.getUserContexts(owner);
		ServiceDTO service = serviceManager.getService(serviceId.toLowerCase());
		if (service == null) return;
		if (!userContexts.contains(service.getContext())) {
			throw new SecurityException("Not authorized to access service " + serviceId);
		}
		clientClaimRepository.delete(clientClaimRepository.findByClientAndService(clientId, serviceId));
	}
}


text:
require("nixio")
require("luci.util")

LmClient = luci.util.class()

-- Must match send size if messages exceed this size
local RECVSIZE = 8192

function LmClient._connect(self)
  if self.sock then return true end

  local sock = nixio.socket("unix", "dgram")
  -- autobind to an abstract address, optionally I could explicitly specify
  -- an abstract name such as "\0linkmeter"..pid
  -- Abstract socket namespace is only supported on Linux
  if not sock:bind("") then
    sock:close()
    return nil, "bind"
  end
  if not sock:connect("/var/run/linkmeter.sock") then
    sock:close()
    return nil, "connect"
  end

  self.sock = sock
  return true
end

function LmClient.close(self)
  if self.sock then
    self.sock:close()
    self.sock = nil
  end
end

function LmClient.query(self, qry, keepopen)
  local rc = {self:_connect()}
  if not rc[1] then return unpack(rc) end

  if self.sock:send(qry) == 0 then
    return nil, "send"
  end

  local polle = { { fd = self.sock, events = nixio.poll_flags("in") } }
  local r
  while true do
    if nixio.poll(polle, 1500) then
      local l = self.sock:recv(RECVSIZE)
      r = (r or "") .. l
      if #l < RECVSIZE then break end
    else
      r = r or { nil, "poll" }
      break
    end
  end

  if not keepopen then self:close() end
  if type(r) == "table" then
    return unpack(r)
  else
    return r
  end
end

function LmClient.stream(self, qry, fn)
  local rc = {self:_connect()}
  if not rc[1] then return unpack(rc) end

  if self.sock:send(qry) == 0 then
    return nil, "send"
  end

  local polle = { { fd = self.sock, events = nixio.poll_flags("in") } }
  while nixio.poll(polle, 7500) do
    local r = self.sock:recv(RECVSIZE)
    if r == "ERR" then break end
    fn(r)
  end

  self:close()
  return nil, "eof"
end

-- Command line execution
if arg and arg[0]:find("lmclient") then
  local qry = arg[1] or "$LMSU"
  local strm
  if qry:sub(1,1) == "@" then
    strm = true
    qry = qry:sub(2)
  end
  if qry:sub(1,1) ~= "$" then
    qry = "$" .. qry
  end

  if strm then
    print(LmClient:stream(qry, function (r)
      io.stdout:write(r)
      io.stdout:write('\n')
      io.stdout:flush()
    end))
  else
    print(LmClient():query(qry))
  end
end


text:
copyright:
 years: 2015, 2016

---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen:.screen}
{:codeblock:.codeblock}

# Registrando um dispositivo com userId
{: #register_device_with_userId}
Última atualização: 07 de dezembro de 2016
{: .last-updated}

Para registrar-se para notificação baseada em userId, conclua as etapas a seguir:

## Android
{: android-register}

Inicialize a classe MFPPush com a chave `AppGUID` e `clientSecret` do serviço {{site.data.keyword.mobilepushshort}}.
```
// Initialize the MFPPush
push = MFPPush.getInstance();
push.initialize(getApplicationContext(),"AppGUID", "clientSecret");
```
	{: codeblock}

- **AppGUID**: esta é a chave AppGUID do serviço
{{site.data.keyword.mobilepushshort}}.
- **clientSecret**: esta é a chave clientSecret do serviço
{{site.data.keyword.mobilepushshort}}.

  Use a API **registerDeviceWithUserId** para registrar o dispositivo para {{site.data.keyword.mobilepushshort}}.
```
// Register the device to {{site.data.keyword.mobilepushshort}}.
push.registerDeviceWithUserId("userId",new MFPPushResponseListener<String>() {
  @Override
	    public void onSuccess(String deviceId) {
    Log.d("Device is registered with Push Service.");
  }
  @Override
    public void onFailure(MFPPushException ex) {
      Log.d("Error registering with Push Service...\n"
        + "Push notifications will not be received.");
  }
});
```
	{: codeblock}

- **userId**: transmita o valor exclusivo de userId para registrar-se no {{site.data.keyword.mobilepushshort}}.

**Nota:** para ativar
{{site.data.keyword.mobilepushshort}} destinado por UserId, assegure-se de
registrar o dispositivo com um userId e também de passar o 'clientSecret'
que é alocado quando os serviços {{site.data.keyword.mobilepushshort}} são
provisionados. O registro do dispositivo falhará sem um clientSecret válido.

## Cordova
{: cordova}

Use as APIs a seguir para registrar para {{site.data.keyword.mobilepushshort}} baseadas em UserId.

```
// Register device for push notification with UserId
var options = {"userId": "Your User Id value"};
BMSPush.registerDevice(options,success, failure);
```
	{: codeblock}

- **userId**: transmita o valor exclusivo de userId para registrar-se no {{site.data.keyword.mobilepushshort}}.

## Objective-C
{: objc-register}

Use as APIs a seguir para registrar-se para {{site.data.keyword.mobilepushshort}} baseado em
UserId.
```
// Initialize the MFPPush
IMFPushClient* push = [IMFPushClient sharedInstance];
[push initializeWithAppGUID:@"appGUID" clientSecret:@"clientSecret"];
```
	{: codeblock}

- **AppGUID**: esta é a chave AppGUID do serviço
{{site.data.keyword.mobilepushshort}}.
- **clientSecret**: esta é a chave clientSecret do serviço
{{site.data.keyword.mobilepushshort}}.

Use a API **registerWithUserId** para registrar o dispositivo para {{site.data.keyword.mobilepushshort}}.
```
// Register the device to push notifications service.
[push registerWithDeviceToken:deviceToken WithUserId:@"userId" completionHandler:^(IMFResponse *response, NSError *error) {
  NSString *message=@"";
	if (error){
        message = [NSString stringWithFormat:@"Error registering for push notifications: %@", error.description];
        NSLog(@"%@",message);
    } else {
     message=@"Successfully registered for push notifications";
        NSLog(@"%@",message);
    }
}];
```
	{: codeblock}

- **userId**: transmita o valor exclusivo de userId para registrar-se no
{{site.data.keyword.mobilepushshort}}.

## Swift
{: swift-register}

```
// Initialize the BMSPushClient
let push =  BMSPushClient.sharedInstance
push.initializeWithAppGUID("appGUID", clientSecret:"clientSecret")
```
	{: codeblock}

- **AppGUID**: esta é a chave AppGUID do serviço
{{site.data.keyword.mobilepushshort}}.
- **clientSecret**: esta é a chave clientSecret do serviço
{{site.data.keyword.mobilepushshort}}.

Use a API **registerWithUserId** para registrar o dispositivo para {{site.data.keyword.mobilepushshort}}.

```
// Register the device to Push Notifications service.
push.registerWithDeviceToken("deviceToken", WithUserId: "userId")  { (response, statusCode, error) -> Void in
if error.isEmpty {
  print( "Response during device registration : \(response)")
        print( "status code during device registration : \(statusCode)")
    } else {
  print( "Error during device registration \(error) ")
    }
  }
```
	{: codeblock}

- **userId**: transmita o valor exclusivo de userId para registrar-se no
{{site.data.keyword.mobilepushshort}}.

## Google Chrome, Safari e Mozilla Firefox
{: web-register}

Use as APIs a seguir para registrar-se para notificações baseadas em userId. Inicialize
o SDK com `app GUID`, `app Region` e
`Client Secret`.

```
var bmsPush = new BMSPush();
var params = {
    "appGUID":"push app GUID",
    "appRegion":"App Region",
    "clientSecret":"Push Client Secret"
    }
  bmsPush.initialize(params, function(response){
          alert(response.response)
    })
```
	{: codeblock}

Após inicializado com sucesso o registro do aplicativo da web com o userId.

```
bmsPush.registerWithUserId("UserId", function(response) {
 alert(response.response)
  })
```
	{: codeblock}

## Apps Google Chrome e Extensões
{: web-register-new}

Use as APIs a seguir para registrar-se para notificações baseadas em userId. Inicialize
o SDK com `app GUID`, `app Region` e
`Client Secret`.

```
var bmsPush = new BMSPush();
var params = {
    "appGUID":"push app GUID",
    "appRegion":"App Region",
    "clientSecret":"Push Client Secret"
    }
  bmsPush.initialize(params, function(response){
          alert(response.response)
    })
```
	{: codeblock}

Após a inicialização bem-sucedida, será necessário registrar o aplicativo da web com o userId.

```
bmsPush.registerWithUserId("UserId", function(response) {
 alert(response.response)
  })
```
	{: codeblock}

# Usando notificações baseadas em userId
{: #using_userid}

As notificações baseadas em userId são mensagens de notificação destinadas a
um usuário específico. Muitos dispositivos podem ser
registrados com um usuário. As etapas a seguir descrevem como enviar notificações baseadas em ID do usuário.

1. No painel **Notificação push**, selecione a opção
**Enviar notificações**.
1. Selecione **UserId** na lista de opções **Enviar para**.
1. No campo **ID do usuário**, procure o ID do usuário que deseja usar e, em seguida, clique em
**+Incluir**.![Tela de notificações](images/user_notification.jpg)
1. No campo **Mensagem**, insira o texto que você deseja enviar em sua notificação.
1. Clique em **Enviar**.


text:
TABLE.marc
{
    font-size: 14px;
    width: auto;
}

TABLE.marc TD
{
   vertical-align:text-top;
}

/*
TABLE.marc TD.content
{
    white-space:pre-wrap;
}
*/

TABLE.marc TR.header
{
    background-color: #eeeeee;
}

TABLE.marc TD.fieldname
{
    border: 0px;
    border-top: 1px;
    border-style: dotted;
    border-color: #cccccc;
}

TABLE.marc TD.fieldname, TABLE.marc TD.indicator, TABLE.marc TR.header TD.content, TABLE.marc SPAN
{
     font-family: "Courier New", Tahoma, Arial, Helvetica, sans-serif;
     font-weight: bold;

}

TABLE.marc TD.indicator
{
    padding-left: 4px;
    padding-right: 4px;

    border: 0px;
    border-left: 1px;
    border-right: 1px;
    border-style: dotted;
    border-color: #eeeeee;
}

TABLE.marc SPAN
{
    margin: 2px;
    margin-left: 0px;

    border: 1px;
    border-style: solid;
    border-color: #cccccc;

    padding-top: 2px;
    padding-bottom: 2px;
    padding-left: 3px;
    padding-right: 3px;
    font-weight: bold;
    color: Blue;
    background-color: Yellow;

}


text:
package driver;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import files.RootedSourcePath;

/**
 * This class resolves the dependencies between source files used at
 * compile-time.
 *
 * Macro definitions are contained in macro files (.javam extension). There may
 * be zero or more macro definitions in one such file.
 *
 * There is currently no visibility control mechanism for macros, which means
 * that all macros are accessible from everywhere. Macros do however behave like
 * classes when it comes to accessing other classes (this comes from the fact
 * that macros are compiled into classes).
 *
 * Macro files may depend on other macro files or on regular source files (to be
 * used at compile-time). The regular source files may themselves depend on
 * macros or on other source files. We need to find an ordering of source files
 * such that all dependencies are met and no loops occur.
 *
 * The mechanism through which dependencies between macros and sources files are
 * defined is the require statement, a modified form of import statement. You
 * can learn more about the require statement in the javadoc of
 * {@link RequiresParser}.
 *
 * Macro files and source files used at compile time can also rely on
 * pre-compiled classes without hurdles (using the regular import statements).
 * The compiled classes (.class or .jar) just needs to be retrievable via
 * caxap's own classpath.
 *
 * It is important to note that due to the way dependencies are resolved, the
 * prelude (package declaration + import/require statements) in each file used
 * at compile-time can't contain macro calls.
 *
 * If a file requires a macro, the macro can be used anywhere in the file
 * (except, as said above, in the prelude of files used at compile-time). A
 * macro may be used in the file that defines it after the definition is
 * complete. A given macro's call cannot appear in its own expansion code,
 * neither can another macro's call which expand to a call of the given macro.
 * Macros whose expansion code use the given macro can't be called either.
 */
public class DependencyResolver
{
  /*****************************************************************************
   * Finds an ordering of macro and regular source files that satisfies all
   * compile-time dependencies. If no such ordering can be found - because
   * there is a circular dependency - throws an error.
   *
   * {@see {@link DependencyResolver}}
   */
  public static List<SourceFile> resolve(
    List<RootedSourcePath> macroPaths, List<RootedSourcePath> sourcePaths)
  {
    return new DependencyResolver().run(macroPaths, sourcePaths);
  }

  /****************************************************************************/
  private final SourceRepository repo = Context.get().repo;

  /****************************************************************************/
  private List<SourceFile> run(
    List<RootedSourcePath> macroPaths, List<RootedSourcePath> sourcePaths)
  {
    repo.hint(macroPaths);
    repo.hint(sourcePaths);

    List<SourceFile> files = new ArrayList<>();

    for (RootedSourcePath path : macroPaths) {
      files.add(repo.get(path));
    }

    Set <SourceFile> set     = detectCycles(files);
    List<SourceFile> ordered = parseOrdering(set);

    for (SourceFile file : ordered) {
      file.declareUsedAtCompileTime();
    }

    for (RootedSourcePath path : sourcePaths) {
      SourceFile file = repo.get(path);

      if (!set.contains(file)) {
        ordered.add(file);
      }
    }

    return ordered;
  }

  /*****************************************************************************
   * Detect cycles in files dependencies, using the direct dependencies stored
   * in the Requires object associated to each SourceFile. If a cycle is
   * encountered, throws an error. Returns the set of visited SourceFile.
   *
   * Checks for cycles by walking the dependency graph recursively, starting
   * from each file (= each node in the graph). This would normally result in
   * passing many times over the same file. But once a file has been checked, it
   * is guaranteed not to belong to any cycle. Therefore, we keep a set of
   * checked file to avoid to duplicate work.
   */
  private Set<SourceFile> detectCycles(List<SourceFile> files)
  {
    Set<SourceFile> checked = new HashSet<>();

    for (SourceFile file : files)
    if (!checked.contains(file)) {
      detectCycles(file, checked, new HashSet<SourceFile>());
      checked.add(file);
    }

    return checked;
  }

  /*****************************************************************************
   * Detects cycles by recursively walking $file and keeping files on the
   * current path in $visited. $checked is explained in
   * {@link DependencyResolver#detectCycles()}.
   */
  private void detectCycles(
    SourceFile file, Set<SourceFile> checked, Set<SourceFile> visited)
  {
    for (SourceFile dependency : file.requires().dependencies())
    if (!checked.contains(dependency))
    {
      // if visited did already contain $dependency
      if (!visited.add(dependency)) {
        throw new Error("Dependency loop detect for macro class \""
          + dependency + "\", via macro class \"" + file + "\".");
      }

      detectCycles(dependency, checked, visited);
      visited.remove(dependency);
      checked.add(dependency);
    }
  }

  /*****************************************************************************
   * Return an ordering of $files that respects the dependencies between them.
   *
   * If the need should arise, the time complexity of this algorithm can be
   * diminished by adding a HashSet that mirrors the content of the list.
   */
  private List<SourceFile> parseOrdering(Collection<SourceFile> files)
  {
    List<SourceFile> ordering = new ArrayList<>(files.size());

    for (SourceFile file : files)
    if (!ordering.contains(file)) {
      parseOrdering(file, ordering);
    }

    return ordering;
  }

  /*****************************************************************************
   * Adds $file to $ordering, ensuring that the dependencies of $file precedes
   * it in the $ordering, adding them recursively if needed.
   */
  private void parseOrdering(SourceFile file, List<SourceFile> ordering)
  {
    for (SourceFile dependency : file.requires().dependencies())
    if (!ordering.contains(dependency)) {
      parseOrdering(dependency, ordering);
    }

    ordering.add(file);
  }
}


text:
/**
 *
 */
package uk.ac.ox.cs.johnlyle.tpmwebsocket.message;

import org.java_websocket.WebSocket;

import uk.ac.ox.cs.johnlyle.tpmwebsocket.ServerState;

/**
 * @author johl
 *
 */
public class Register extends Message implements IMessage, ReplyMessage {

	private String subject = "Register";

	public String getSubject() {
		return subject;
	}

	@Override
	public void respond(ServerState context, WebSocket conn) {
		context.send(conn, this);
	}

}


text:
from circuits.core.handlers import handler

"""Component Setup Tests

Tests that event handlers of a Component are
automatically registered as event handlers.
"""

from circuits import Component, Manager

class App(Component):

    def test(self, event, *args, **kwargs):
        pass

class A(Component):
    pass

class B(Component):

    informed = False

    @handler("prepare_unregister", channel="*")
    def _on_prepare_unregister(self, event, c):
        if event.in_subtree(self):
            self.informed = True

class Base(Component):

    channel = "base"

class C(Base):

    channel = "c"

def test_basic():
    m = Manager()

    app = App()
    app.register(m)

    assert app.test in app._handlers.get("test", set())

    app.unregister()
    while m:
        m.flush()

    assert not m._handlers

def test_complex():
    m = Manager()

    a = A()
    b = B()

    a.register(m)
    b.register(a)

    assert a in m
    assert a.root == m
    assert a.parent == m
    assert b in a
    assert b.root == m
    assert b.parent == a

    a.unregister()
    while m:
        m.flush()

    assert b.informed
    assert a not in m
    assert a.root == a
    assert a.parent == a
    assert b in a
    assert b.root == a
    assert b.parent == a

def test_subclassing_with_custom_channel():
    base = Base()

    assert base.channel == "base"

    c = C()

    assert c.channel == "c"


text:
using GitVersion.Common;
using GitVersion.Configuration;
using GitVersion.Extensions;
using Microsoft.Extensions.Options;

namespace GitVersion;

public class GitVersionContextFactory : IGitVersionContextFactory
{
    private readonly IConfigurationProvider configurationProvider;
    private readonly IRepositoryStore repositoryStore;
    private readonly IOptions<GitVersionOptions> options;

    public GitVersionContextFactory(IConfigurationProvider configurationProvider, IRepositoryStore repositoryStore, IOptions<GitVersionOptions> options)
    {
        this.configurationProvider = configurationProvider.NotNull();
        this.repositoryStore = repositoryStore.NotNull();
        this.options = options.NotNull();
    }

    public GitVersionContext Create(GitVersionOptions gitVersionOptions)
    {
        var currentBranch = this.repositoryStore.GetTargetBranch(gitVersionOptions.RepositoryInfo.TargetBranch);
        if (currentBranch == null)
            throw new InvalidOperationException("Need a branch to operate on");

        var currentCommit = this.repositoryStore.GetCurrentCommit(currentBranch, gitVersionOptions.RepositoryInfo.CommitId);

        var configuration = this.configurationProvider.Provide(this.options.Value.ConfigInfo.OverrideConfig);
        if (currentBranch.IsDetachedHead)
        {
            var branchForCommit = this.repositoryStore.GetBranchesContainingCommit(currentCommit, onlyTrackedBranches: gitVersionOptions.Settings.OnlyTrackedBranches).OnlyOrDefault();
            currentBranch = branchForCommit ?? currentBranch;
        }

        var currentCommitTaggedVersion = this.repositoryStore.GetCurrentCommitTaggedVersion(currentCommit, configuration.TagPrefix);
        var numberOfUncommittedChanges = this.repositoryStore.GetNumberOfUncommittedChanges();

        return new GitVersionContext(currentBranch, currentCommit, configuration, currentCommitTaggedVersion, numberOfUncommittedChanges);
    }
}


text:
/**
 * Title: Console
 *
 * To be done.
 */

#ifndef __SIEGE_CORE_CONSOLE_H__
#define __SIEGE_CORE_CONSOLE_H__

#include "../common.h"

#ifdef __cplusplus
extern "C"
{
#endif // __cplusplus

SGbool SG_CALL _sgConsoleInit(void);
SGbool SG_CALL _sgConsoleDeinit(void);

/// \todo TODO

#ifdef __cplusplus
}
#endif // __cplusplus

#endif // __SIEGE_CORE_CONSOLE_H__


text:
/**
 * types
 * @authors yanjixiong
 * @date    2016-07-12 16:59:21
 */

export const TREE_FORWARD = 'TREE_FORWARD'
export const TREE_BACK = 'TREE_BACK'

export const SEARCH_PEOPLE = 'SEARCH_PEOPLE'
export const SEARCH_PUBLIC_ACCOUNT = 'SEARCH_PUBLIC_ACCOUNT'
export const SEARCH_GROUP = 'SEARCH_GROUP'

export const INIT = 'INIT'

export const GET_CHILDREN = 'GET_CHILDREN'


text:
from django.db import models

from dnd.models.abstract import AbstractDnDModel
from dnd.constants.database import STND_CHAR_LIMIT, STND_ID_CHAR_LIMIT

class ActionTimeDuration(AbstractDnDModel):
    """
    A length of time in actions.
    """

    time = models.IntegerField(blank=False)

# TODO: Make a measurement module:
#   - mass
#   - time
#   - distance
#   - volume
#   - cost


text:
package org.wso2.carbon.dataservices.task.internal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.dataservices.task.DSTaskConstants;
import org.wso2.carbon.ntask.core.service.TaskService;

/**
 * @scr.component name="dataservices.task" immediate="true"
 * @scr.reference name="ntask.component" interface="org.wso2.carbon.ntask.core.service.TaskService"
 * cardinality="1..1" policy="dynamic" bind="setTaskService" unbind="unsetTaskService"
 **/
public class DSTaskServiceComponent {

    private static final Log log = LogFactory.getLog(DSTaskServiceComponent.class);

    private static TaskService taskService;

    protected void activate(ComponentContext ctxt) {
        try {
            /* register the data service task type */
            getTaskService().registerTaskType(DSTaskConstants.DATA_SERVICE_TASK_TYPE);
            if (log.isDebugEnabled()) {
                log.debug("Data Services task bundle is activated ");
            }
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            /* don't throw exception */
        }
    }

    protected void deactivate(ComponentContext ctxt) {
        log.debug("Data Services task bundle is deactivated ");
    }

    protected void setTaskService(TaskService taskService) {
        if (log.isDebugEnabled()) {
            log.debug("Setting the Task Service");
        }
        DSTaskServiceComponent.taskService = taskService;
    }

    protected void unsetTaskService(TaskService taskService) {
        if (log.isDebugEnabled()) {
            log.debug("Unsetting the Task Service");
        }
        DSTaskServiceComponent.taskService = null;
    }

    public static TaskService getTaskService() {
        return DSTaskServiceComponent.taskService;
    }

}


text:
package org.auraframework.integration.test.service;

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

import org.auraframework.Aura;
import org.auraframework.def.ComponentDef;
import org.auraframework.impl.AuraImplTestCase;

public class AuraComponentServiceImplTest extends AuraImplTestCase {

    public AuraComponentServiceImplTest(String name) {
        super(name);
    }

    public void testGetComponent() throws Exception {
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("attr", "yo");
        assertNotNull(Aura.getInstanceService().getInstance("test:child1", ComponentDef.class, attributes));
    }

}


text:
Welcome to s3workers's documentation!
======================================

Contents:

.. toctree::
   :maxdepth: 2

   readme
   installation
   usage
   contributing
   authorshistory

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
#include "qskeleton/Parameters.hpp"

#include <memory>
#include <vector>

namespace qskeleton {

namespace internal {

template<class Inequalities>
class Pivoting {
public:
    typedef std::vector<size_t> Indexes;
    using Type = Parameters::PivotingType;

    static std::unique_ptr<Pivoting> create(Type type, const Indexes& indexes);
    virtual ~Pivoting() = default;
    virtual bool isOver() const = 0; //{ return (used == indexes.size()); }
    virtual size_t getNext(const Inequalities& inequalities) = 0; //{ return indexes[used++]; }
};

template<class Inequalities>
std::unique_ptr<Pivoting<Inequalities>> Pivoting<Inequalities>::create(Type type, const Indexes& indexes)
{
    switch (type) {
        case Type::MinIndex: return make_unique<PivotingMinIndex<Inequalities>>(indexes);
        default: throw std::invalid_argument("Unsupported value of pivoting type");
    }
}

template<class Inequalities>
class PivotingMinIndex : public Pivoting<Inequalities> {
public:
    PivotingMinIndex(const Indexes& indexes) :
        indexes(indexes),
        used(0)
    {}
    virtual bool isOver() const { return (used == indexes.size()); }
    virtual size_t getNext(const Inequalities& inequalities) { return indexes[used++]; }
private:
    const Indexes& indexes;
    size_t used;
};

} // namespace qskeleton::internal

} // namespace qskeleton

#endif


text:
import asyncio
from ..enerpi import (EnerpiStreamer, LOGGER, EnerpiSensor, CONF_HOST, CONF_PORT, CONF_PREFIX,
                      CONF_SCAN_INTERVAL, CONF_DELTA_REFRESH, CONF_DEVICES, CONF_MAIN_POWER, CONF_LASTWEEK)

##########################################
# ENERPI PLATFORM:
##########################################
# noinspection PyUnusedLocal
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info):
    """Setup the enerPI Platform sensors getting the platform config from discovery_info."""
    devices_enerpi_hosts = []
    if discovery_info:
        is_master = True
        master_enerpi_added = False
        for clean_name, config_enerpi_host in discovery_info.items():
            LOGGER.debug('enerpi sensors config: {}'.format(config_enerpi_host))
            host = config_enerpi_host.get(CONF_HOST)
            port = config_enerpi_host.get(CONF_PORT)
            prefix = config_enerpi_host.get(CONF_PREFIX)
            devices = config_enerpi_host.get(CONF_DEVICES)
            main_power = config_enerpi_host.get(CONF_MAIN_POWER)
            data_refresh = config_enerpi_host.get(CONF_SCAN_INTERVAL)
            delta_refresh = config_enerpi_host.get(CONF_DELTA_REFRESH)
            lastweek_consumption = config_enerpi_host.get(CONF_LASTWEEK)

            streamer = EnerpiStreamer(hass, clean_name, host, port, prefix,
                                      devices, main_power, lastweek_consumption,
                                      data_refresh, delta_refresh, is_master)
            is_master = False
            devices_enerpi_hosts.append(EnerpiSensor(streamer, clean_name))
            LOGGER.info('enerPI platform sensors "{}". Sensors added: **{}**'.format(clean_name, devices))
    else:
        LOGGER.warn('No enerPI sensors present in configuration.')
        return False
    if devices_enerpi_hosts:
        async_add_devices(devices_enerpi_hosts)
    else:
        return False


text:
"""
  Created on Jan 21, 2020

  @author: alfoa, wangc
  SGD Regressor

"""
#Internal Modules (Lazy Importer)--------------------------------------------------------------------
#Internal Modules (Lazy Importer) End----------------------------------------------------------------

#External Modules------------------------------------------------------------------------------------
#External Modules End--------------------------------------------------------------------------------

#Internal Modules------------------------------------------------------------------------------------
from ....SupervisedLearning.ScikitLearn import ScikitLearnBase
from ....utils import InputData, InputTypes
#Internal Modules End--------------------------------------------------------------------------------

class SGDRegressor(ScikitLearnBase):
  """
    SGD Regressor
  """
  info = {'problemtype':'regression', 'normalize':True}

  def __init__(self):
    """
      Constructor that will appropriately initialize a supervised learning object
      @ In, None
      @ Out, None
    """
    super().__init__()
    import sklearn
    import sklearn.linear_model
    self.model = sklearn.linear_model.SGDRegressor

  @classmethod
  def getInputSpecification(cls):
    """
      Method to get a reference to a class that specifies the input data for
      class cls.
      @ In, cls, the class for which we are retrieving the specification
      @ Out, inputSpecification, InputData.ParameterInput, class to use for
        specifying input of cls.
    """
    specs = super(SGDRegressor, cls).getInputSpecification()
    specs.description = r"""The \xmlNode{SGDRegressor} implements regularized linear models with stochastic
                        gradient descent (SGD) learning for regression: the gradient of the loss is estimated each sample at
                        a time and the model is updated along the way with a decreasing strength schedule
                        (aka learning rate). For best results using the default learning rate schedule, the
                        data should have zero mean and unit variance.
                        This implementation works with data represented as dense or sparse arrays of floating
                        point values for the features. The model it fits can be controlled with the loss parameter;
                        by default, it fits a linear support vector machine (SVM).
                        The regularizer is a penalty added to the loss function that shrinks model parameters towards
                        the zero vector using either the squared euclidean norm L2 or the absolute norm L1 or a
                        combination of both (Elastic Net). If the parameter update crosses the 0.0 value because
                        of the regularizer, the update is truncated to $0.0$ to allow for learning sparse models and
                        achieve online feature selection.
                        This implementation works with data represented as dense arrays of floating point values for the features.
                        \zNormalizationPerformed{SGDRegressor}
                        """
    specs.addSub(InputData.parameterInputFactory("loss", contentType=InputTypes.makeEnumType("loss", "lossType",['squared_loss', 'huber','epsilon_insensitive','squared_epsilon_insensitive']),
                                                 descr=r"""The loss function to be used.
                                                 The ``squared\_loss'' refers to the ordinary least squares fit. ``huber'' modifies ``squared\_loss'' to focus less on getting outliers correct by
                                                 switching from squared to linear loss past a distance of epsilon. ``epsilon\_insensitive'' ignores errors less than epsilon and is linear past
                                                 that; this is the loss function used in SVR. ``squared\_epsilon\_insensitive'' is the same but becomes squared loss past a tolerance of epsilon.
                                                 """, default='squared_loss'))
    specs.addSub(InputData.parameterInputFactory("penalty", contentType=InputTypes.makeEnumType("penalty", "penaltyType",['l2', 'l1', 'elasticnet']),
                                                 descr=r"""The penalty (aka regularization term) to be used. Defaults to ``l2'' which is the standard regularizer for linear SVM models.
                                                 ``l1'' and ``elasticnet'' might bring sparsity to the model (feature selection) not achievable with ``l2''.""", default='l2'))
    specs.addSub(InputData.parameterInputFactory("alpha", contentType=InputTypes.FloatType,
                                                 descr=r"""Constant that multiplies the regularization term. The higher the value, the stronger the regularization. Also used to compute
                                                 the learning rate when set to learning_rate is set to ``optimal''.""", default=0.0001))
    specs.addSub(InputData.parameterInputFactory("l1_ratio", contentType=InputTypes.FloatType,
                                                 descr=r"""The Elastic Net mixing parameter, with $0 <= l1\_ratio <= 1$. $l1\_ratio=0$ corresponds to L2 penalty, $l1\_ratio=1$ to L1.
                                                 Only used if penalty is ``elasticnet''.""", default=0.15))
    specs.addSub(InputData.parameterInputFactory("fit_intercept", contentType=InputTypes.BoolType,
                                                 descr=r"""Whether the intercept should be estimated or not. If False,
                                                  the data is assumed to be already centered.""", default=True))
    specs.addSub(InputData.parameterInputFactory("max_iter", contentType=InputTypes.IntegerType,
                                                 descr=r"""The maximum number of passes over the training data (aka epochs).""", default=1000))
    specs.addSub(InputData.parameterInputFactory("tol", contentType=InputTypes.FloatType,
                                                 descr=r"""The stopping criterion. If it is not None, training will stop when $(loss > best\_loss - tol)$ for $n\_iter\_no\_change$
                                                 consecutive epochs.""", default=1e-3))
    specs.addSub(InputData.parameterInputFactory("shuffle", contentType=InputTypes.BoolType,
                                                 descr=r"""TWhether or not the training data should be shuffled after each epoch """, default=True))
    specs.addSub(InputData.parameterInputFactory("epsilon", contentType=InputTypes.FloatType,
                                                 descr=r"""Epsilon in the epsilon-insensitive loss functions; only if loss is ``huber'', ``epsilon\_insensitive'', or
                                                 ``squared\_epsilon\_insensitive''. For ``huber'', determines the threshold at which it becomes less important to get the
                                                 prediction exactly right. For epsilon-insensitive, any differences between the current prediction and the correct label
                                                 are ignored if they are less than this threshold.""", default=0.1))
    specs.addSub(InputData.parameterInputFactory("learning_rate", contentType=InputTypes.makeEnumType("learning_rate", "learningType",['constant', 'optimal', 'invscaling','adaptive']),
                                                 descr=r"""The learning rate schedule:
                                                 \begin{itemize}
                                                  \item constant: $eta = eta0$
                                                  \item optimal: $eta = 1.0 / (alpha * (t + t0))$ where t0 is chosen by a heuristic proposed by Leon Bottou.
                                                  \item invscaling: $eta = eta0 / pow(t, power\_t)$
                                                  \item adaptive: $eta = eta0$, as long as the training keeps decreasing. Each time n\_iter\_no\_change consecutive epochs fail
                                                  to decrease the training loss by tol or fail to increase validation score by tol if early\_stopping is True, the current
                                                  learning rate is divided by 5.
                                                 \end{itemize}
                                                 """, default='optimal'))
    specs.addSub(InputData.parameterInputFactory("eta0", contentType=InputTypes.FloatType,
                                                 descr=r"""The initial learning rate for the ``constant'', ``invscaling'' or ``adaptive'' schedules. The default value is 0.0
                                                 as eta0 is not used by the default schedule ``optimal''.""", default=0.0))
    specs.addSub(InputData.parameterInputFactory("power_t", contentType=InputTypes.FloatType,
                                                 descr=r"""The exponent for inverse scaling learning rate.""", default=0.5))
    specs.addSub(InputData.parameterInputFactory("early_stopping", contentType=InputTypes.BoolType,
                                                 descr=r"""hether to use early stopping to terminate training when validation score is not
                                                 improving. If set to True, it will automatically set aside a stratified fraction of training
                                                 data as validation and terminate training when validation score is not improving by at least
                                                 tol for n\_iter\_no\_change consecutive epochs.""", default=False))
    specs.addSub(InputData.parameterInputFactory("validation_fraction", contentType=InputTypes.FloatType,
                                                 descr=r"""The proportion of training data to set aside as validation set for early stopping.
                                                 Must be between 0 and 1. Only used if early\_stopping is True.""", default=0.1))
    specs.addSub(InputData.parameterInputFactory("n_iter_no_change", contentType=InputTypes.IntegerType,
                                                descr=r"""Number of iterations with no improvement to wait before early stopping.""", default=5))
    specs.addSub(InputData.parameterInputFactory("random_state", contentType=InputTypes.IntegerType,
                                                 descr=r"""Used to shuffle the training data, when shuffle is set to
                                                 True. Pass an int for reproducible output across multiple function calls.""",
                                                 default=None))
    specs.addSub(InputData.parameterInputFactory("verbose", contentType=InputTypes.IntegerType,
                                                 descr=r"""The verbosity level""", default=0))
    specs.addSub(InputData.parameterInputFactory("warm_start", contentType=InputTypes.BoolType,
                                                 descr=r"""When set to True, reuse the solution of the previous call
                                                 to fit as initialization, otherwise, just erase the previous solution.""", default=False))
    specs.addSub(InputData.parameterInputFactory("average", contentType=InputTypes.BoolType,
                                                 descr=r"""When set to True, computes the averaged SGD weights accross
                                                 all updates and stores the result in the coef_ attribute.""", default=False))
    return specs

  def _handleInput(self, paramInput):
    """
      Function to handle the common parts of the distribution parameter input.
      @ In, paramInput, ParameterInput, the already parsed input.
      @ Out, None
    """
    super()._handleInput(paramInput)
    settings, notFound = paramInput.findNodesAndExtractValues(['loss','penalty','alpha','l1_ratio','fit_intercept',
                                                               'max_iter','tol','shuffle','epsilon', 'learning_rate',
                                                               'eta0','power_t','early_stopping','validation_fraction',
                                                               'n_iter_no_change', 'random_state', 'verbose', 'warm_start',
                                                               'average'])
    # notFound must be empty
    assert(not notFound)
    self.initializeModel(settings)


text:
class Store::Cached < Store
	attr_reader :db
	attr_reader :cache, :working

	def initialize db, cache = Store::Memory.new, working = Store::Memory.new
		@db = db
		@cache = cache
		@working_blank = working
		@working = working.dup
	end

	def load opts = {}, &blk
		batch = @cache.batch
		@db.range(opts).each do |k, v|
			batch[k] = v
		end.onend do
			batch.apply
			blk.call if blk
		end
		self
	end

	def unload opts = {}
		t = @working
		@working = @working_blank.dup
		batch = @cache.batch
		@cache.range(opts).each do |k, v|
			batch.del k
		end
		batch.apply
		@working = t
		self
	end

	def apply batch
		@cache.apply batch
		@working.apply batch
		# @working.merge! batch
		self
	end

	def get key
		val = @cache[key]
		if val == nil
			begin
				val = @db[key]
				@cache[key] = val
			rescue
			end
		end
		val
	end

	def _range from, to
		# @data.select { |key, val| key >= from && key <= to }.map { |key, val| [key, val] }
		@cache._range from, to
	end

	def save
		@db.apply Hash[*@working.range.flat_map{|kv|kv}]
		@working = @working_blank.dup
		self
	end

	def dup
		Store::Cached.new @db.dup, @cache.dup, @working_blank.dup
	end
end


text:
The [MQTT](http://mqtt.org/) consumer plugin reads from
specified MQTT topics and adds messages to InfluxDB.
The plugin expects messages in the
[Telegraf Input Data Formats](https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md).

### Configuration:

```toml
# Read metrics from MQTT topic(s)
[[inputs.mqtt_consumer]]
  ## MQTT broker URLs to be used. The format should be scheme://host:port,
  ## schema can be tcp, ssl, or ws.
  servers = ["tcp://localhost:1883"]

  ## QoS policy for messages
  ##   0 = at most once
  ##   1 = at least once
  ##   2 = exactly once
  ##
  ## When using a QoS of 1 or 2, you should enable persistent_session to allow
  ## resuming unacknowledged messages.
  qos = 0

  ## Connection timeout for initial connection in seconds
  connection_timeout = "30s"

  ## Topics to subscribe to
  topics = [
    "telegraf/host01/cpu",
    "telegraf/+/mem",
    "sensors/#",
  ]

  # if true, messages that can't be delivered while the subscriber is offline
  # will be delivered when it comes back (such as on service restart).
  # NOTE: if true, client_id MUST be set
  persistent_session = false
  # If empty, a random client ID will be generated.
  client_id = ""

  ## username and password to connect MQTT server.
  # username = "telegraf"
  # password = "metricsmetricsmetricsmetrics"

  ## Optional TLS Config
  # tls_ca = "/etc/telegraf/ca.pem"
  # tls_cert = "/etc/telegraf/cert.pem"
  # tls_key = "/etc/telegraf/key.pem"
  ## Use TLS but skip chain & host verification
  # insecure_skip_verify = false

  ## Data format to consume.
  ## Each data format has its own unique set of configuration options, read
  ## more about them here:
  ## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
  data_format = "influx"
```

### Tags:

- All measurements are tagged with the incoming topic, ie
`topic=telegraf/host01/cpu`


text:
#pragma once

#include <stdint.h>

namespace facebook { namespace memcache { namespace globals {

/**
 * @return lazy-initialized hostid.
 */
uint32_t hostid();

}}} // facebook::memcache


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/timing/performance_navigation_timing.h"

#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"

namespace blink {

class PerformanceNavigationTimingTest : public PageTestBase {
 protected:
  AtomicString GetNavigationType(WebNavigationType type, Document* document) {
    return PerformanceNavigationTiming::GetNavigationType(type, document);
  }
};

TEST_F(PerformanceNavigationTimingTest, GetNavigationType) {
  GetPage().SetVisibilityState(mojom::blink::PageVisibilityState::kHidden,
                               /*initial_state=*/false);
  AtomicString returned_type =
      GetNavigationType(kWebNavigationTypeBackForward, &GetDocument());
  EXPECT_EQ(returned_type, "back_forward");

  GetPage().SetVisibilityState(mojom::blink::PageVisibilityState::kVisible,
                               /*initial_state=*/false);
  returned_type =
      GetNavigationType(kWebNavigationTypeFormResubmitted, &GetDocument());
  EXPECT_EQ(returned_type, "navigate");
}
}  // namespace blink


text:
var DateTimePickerHours, DateTimePickerMinutes, DateTimePickerTime, Glyphicon, React;

React = require('react');

DateTimePickerMinutes = require('./DateTimePickerMinutes');

DateTimePickerHours = require('./DateTimePickerHours');

var Glyphicon = require('react-bootstrap').Glyphicon;

var Constants = require('./Constants');

DateTimePickerTime = React.createClass({displayName: "DateTimePickerTime",
  propTypes: {
    setSelectedHour: React.PropTypes.func.isRequired,
    setSelectedMinute: React.PropTypes.func.isRequired,
    subtractHour: React.PropTypes.func.isRequired,
    addHour: React.PropTypes.func.isRequired,
    subtractMinute: React.PropTypes.func.isRequired,
    addMinute: React.PropTypes.func.isRequired,
    viewDate: React.PropTypes.object.isRequired,
    selectedDate: React.PropTypes.object.isRequired,
    togglePeriod: React.PropTypes.func.isRequired,
    mode: React.PropTypes.oneOf([Constants.MODE_DATE, Constants.MODE_DATETIME, Constants.MODE_TIME])
  },
  getInitialState: function() {
    return {
      minutesDisplayed: false,
      hoursDisplayed: false
    };
  },
  goBack: function() {
    return this.setState({
      minutesDisplayed: false,
      hoursDisplayed: false
    });
  },
  showMinutes: function() {
    return this.setState({
      minutesDisplayed: true
    });
  },
  showHours: function() {
    return this.setState({
      hoursDisplayed: true
    });
  },
  renderMinutes: function() {
    if (this.state.minutesDisplayed) {
      return React.createElement(DateTimePickerMinutes, React.__spread({},  this.props, {onSwitch: this.goBack}));
    } else {
      return null;
    }
  },
  renderHours: function() {
    if (this.state.hoursDisplayed) {
      return React.createElement(DateTimePickerHours, React.__spread({},  this.props, {onSwitch: this.goBack}));
    } else {
      return null;
    }
  },
  renderPicker: function() {
    if (!this.state.minutesDisplayed && !this.state.hoursDisplayed) {
      return (
      React.createElement("div", {className: "timepicker-picker"},
        React.createElement("table", {className: "table-condensed"},
          React.createElement("tbody", null,
            React.createElement("tr", null,
              React.createElement("td", null, React.createElement("a", {className: "btn", onClick: this.props.addHour}, React.createElement(Glyphicon, {glyph: "chevron-up"}))),

              React.createElement("td", {className: "separator"}),

              React.createElement("td", null, React.createElement("a", {className: "btn", onClick: this.props.addMinute}, React.createElement(Glyphicon, {glyph: "chevron-up"}))),

              React.createElement("td", {className: "separator"})
            ),

            React.createElement("tr", null,
              React.createElement("td", null, React.createElement("span", {className: "timepicker-hour", onClick: this.showHours}, this.props.selectedDate.format('h'))),

              React.createElement("td", {className: "separator"}, ":"),

              React.createElement("td", null, React.createElement("span", {className: "timepicker-minute", onClick: this.showMinutes}, this.props.selectedDate.format('mm'))),

              React.createElement("td", {className: "separator"}),

              React.createElement("td", null, React.createElement("button", {className: "btn btn-primary", onClick: this.props.togglePeriod, type: "button"}, this.props.selectedDate.format('A')))
            ),

            React.createElement("tr", null,
              React.createElement("td", null, React.createElement("a", {className: "btn", onClick: this.props.subtractHour}, React.createElement(Glyphicon, {glyph: "chevron-down"}))),

              React.createElement("td", {className: "separator"}),

              React.createElement("td", null, React.createElement("a", {className: "btn", onClick: this.props.subtractMinute}, React.createElement(Glyphicon, {glyph: "chevron-down"}))),

              React.createElement("td", {className: "separator"})
            )
          )
        )
      )
      );
    } else {
      return '';
    }
  },
  render: function() {
    return (
        React.createElement("div", {className: "timepicker"},
          this.renderPicker(),

          this.renderHours(),

          this.renderMinutes()
        )
    );
  }
});

module.exports = DateTimePickerTime;