text:
package ca.uhn.fhir.jpa.dao;

import static org.hamcrest.Matchers.stringContainsInOrder;
import static org.junit.Assert.*;

import java.io.IOException;
import java.io.InputStreamReader;

import org.hl7.fhir.instance.model.api.IIdType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jpa.dao.IFhirResourceDaoValueSet.ValidateCodeResult;
import ca.uhn.fhir.jpa.provider.ResourceProviderDstu2Test;
import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt;
import ca.uhn.fhir.model.dstu2.composite.CodingDt;
import ca.uhn.fhir.model.dstu2.resource.Bundle;
import ca.uhn.fhir.model.dstu2.resource.ValueSet;
import ca.uhn.fhir.model.primitive.CodeDt;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.model.primitive.UriDt;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "/hapi-fhir-server-resourceproviders-dstu2.xml", "/fhir-jpabase-spring-test-config.xml" })
public class FhirResourceDaoValueSetDstu2Test {

	private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirResourceDaoValueSetDstu2Test.class);

	private static IIdType vsid;

	@Autowired
	private FhirContext myCtx;

	@Autowired
	@Qualifier("mySystemDaoDstu2")
	private IFhirSystemDao<Bundle> mySystemDao;

	@Autowired
	@Qualifier("myValueSetDaoDstu2")
	private IFhirResourceDaoValueSet<ValueSet> myValueSetDao;

	@Before
	@Transactional
	public void before01() {
		if (vsid == null) {
			FhirSystemDaoDstu2Test.doDeleteEverything(mySystemDao);
		}
	}

	@Before
	@Transactional
	public void before02() {
		if (vsid == null) {
			ValueSet upload = myCtx.newXmlParser().parseResource(ValueSet.class, new InputStreamReader(ResourceProviderDstu2Test.class.getResourceAsStream("/extensional-case-2.xml")));
			upload.setId("");
			vsid = myValueSetDao.create(upload).getId().toUnqualifiedVersionless();
		}
	}

	@Test
	public void testValidateCodeOperationByCodeAndSystemBad() {
		UriDt valueSetIdentifier = null;
		IdDt id = null;
		CodeDt code = new CodeDt("8450-9-XXX");
		UriDt system = new UriDt("http://loinc.org");
		StringDt display = null;
		CodingDt coding = null;
		CodeableConceptDt codeableConcept = null;
		ValidateCodeResult result = myValueSetDao.validateCode(valueSetIdentifier, id, code, system, display, coding, codeableConcept);
		assertFalse(result.isResult());
	}

	@Test
	public void testValidateCodeOperationByCodeAndSystemGood() {
		UriDt valueSetIdentifier = null;
		IdDt id = null;
		CodeDt code = new CodeDt("8450-9");
		UriDt system = new UriDt("http://loinc.org");
		StringDt display = null;
		CodingDt coding = null;
		CodeableConceptDt codeableConcept = null;
		ValidateCodeResult result = myValueSetDao.validateCode(valueSetIdentifier, id, code, system, display, coding, codeableConcept);
		assertTrue(result.isResult());
		assertEquals("Systolic blood pressure--expiration", result.getDisplay());
	}

	@Test
	public void testValidateCodeOperationByIdentifierAndCodeAndSystem() {
		UriDt valueSetIdentifier = new UriDt("http://www.healthintersections.com.au/fhir/ValueSet/extensional-case-2");
		IdDt id = null;
		CodeDt code = new CodeDt("11378-7");
		UriDt system = new UriDt("http://loinc.org");
		StringDt display = null;
		CodingDt coding = null;
		CodeableConceptDt codeableConcept = null;
		ValidateCodeResult result = myValueSetDao.validateCode(valueSetIdentifier, id, code, system, display, coding, codeableConcept);
		assertTrue(result.isResult());
		assertEquals("Systolic blood pressure at First encounter", result.getDisplay());
	}

	@Test
	public void testValidateCodeOperationByIdentifierAndCodeAndSystemAndBadDisplay() {
		UriDt valueSetIdentifier = new UriDt("http://www.healthintersections.com.au/fhir/ValueSet/extensional-case-2");
		IdDt id = null;
		CodeDt code = new CodeDt("11378-7");
		UriDt system = new UriDt("http://loinc.org");
		StringDt display = new StringDt("Systolic blood pressure at First encounterXXXX");
		CodingDt coding = null;
		CodeableConceptDt codeableConcept = null;
		ValidateCodeResult result = myValueSetDao.validateCode(valueSetIdentifier, id, code, system, display, coding, codeableConcept);
		assertFalse(result.isResult());
		assertEquals("Systolic blood pressure at First encounter", result.getDisplay());
	}

	@Test
	public void testValidateCodeOperationByIdentifierAndCodeAndSystemAndGoodDisplay() {
		UriDt valueSetIdentifier = new UriDt("http://www.healthintersections.com.au/fhir/ValueSet/extensional-case-2");
		IdDt id = null;
		CodeDt code = new CodeDt("11378-7");
		UriDt system = new UriDt("http://loinc.org");
		StringDt display = new StringDt("Systolic blood pressure at First encounter");
		CodingDt coding = null;
		CodeableConceptDt codeableConcept = null;
		ValidateCodeResult result = myValueSetDao.validateCode(valueSetIdentifier, id, code, system, display, coding, codeableConcept);
		assertTrue(result.isResult());
		assertEquals("Systolic blood pressure at First encounter", result.getDisplay());
	}

	@Test
	public void testValidateCodeOperationByResourceIdAndCodeableConcept() {
		UriDt valueSetIdentifier = null;
		IIdType id = vsid;
		CodeDt code = null;
		UriDt system = null;
		StringDt display = null;
		CodingDt coding = null;
		CodeableConceptDt codeableConcept = new CodeableConceptDt("http://loinc.org", "11378-7");
		ValidateCodeResult result = myValueSetDao.validateCode(valueSetIdentifier, id, code, system, display, coding, codeableConcept);
		assertTrue(result.isResult());
		assertEquals("Systolic blood pressure at First encounter", result.getDisplay());
	}

	@Test
	public void testValidateCodeOperationByResourceIdAndCodeAndSystem() {
		UriDt valueSetIdentifier = null;
		IIdType id = vsid;
		CodeDt code = new CodeDt("11378-7");
		UriDt system = new UriDt("http://loinc.org");
		StringDt display = null;
		CodingDt coding = null;
		CodeableConceptDt codeableConcept = null;
		ValidateCodeResult result = myValueSetDao.validateCode(valueSetIdentifier, id, code, system, display, coding, codeableConcept);
		assertTrue(result.isResult());
		assertEquals("Systolic blood pressure at First encounter", result.getDisplay());
	}

	@Test
	public void testValueSetExpandOperation() throws IOException {
		String resp;

		ValueSet expanded = myValueSetDao.expand(vsid, null);
		resp = myCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(expanded);
		ourLog.info(resp);
		// @formatter:off
		assertThat(resp,
			stringContainsInOrder("<ValueSet xmlns=\"http://hl7.org/fhir\">",
				"<expansion>",
					"<contains>",
						"<system value=\"http://loinc.org\"/>",
						"",
						"<display value=\"Systolic blood pressure at First encounter\"/>",
					"</contains>",
					"<contains>",
						"<system value=\"http://loinc.org\"/>",
						"",
						"<display value=\"Systolic blood pressure--expiration\"/>",
					"</contains>",
				"</expansion>"
					));
		//@formatter:on

		/*
		 * Filter with display name
		 */

		expanded = myValueSetDao.expand(vsid, new StringDt("systolic"));
		resp = myCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(expanded);
		ourLog.info(resp);
		//@formatter:off
		assertThat(resp, stringContainsInOrder(
				"",
				"<display value=\"Systolic blood pressure at First encounter\"/>"));
		//@formatter:on

		/*
		 * Filter with code
		 */

		expanded = myValueSetDao.expand(vsid, new StringDt("11378"));
		resp = myCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(expanded);
		ourLog.info(resp);
		//@formatter:off
		assertThat(resp, stringContainsInOrder(
				"",
				"<display value=\"Systolic blood pressure at First encounter\"/>"));
		//@formatter:on
	}

}


text:
package br.com.minaciolog.gerenciador.beans;

import java.sql.Date;

public class Job {

    private int codigo;
    private int codigoECalc;
    private String titulo;
    private int codigoOS;
    private Date dataEntrada;
    private Date dataSaida;
    private double valor;
    private int qtdParcelas;
    private String Observacao;
    private int codigoCliente;
    private int tipoFaturamento;
    private float bv;
    private float bvAgencia;
    private float bvProdutor;
    private String cliente;

    /**
     * @return the codigo
     */
    public int getCodigo() {
        return codigo;
    }

    /**
     * @param codigo the codigo to set
     */
    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }

    /**
     * @return the titulo
     */
    public String getTitulo() {
        return titulo;
    }

    /**
     * @param titulo the titulo to set
     */
    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    /**
     * @return the codigoOS
     */
    public int getCodigoOS() {
        return codigoOS;
    }

    /**
     * @param codigoOS the codigoOS to set
     */
    public void setCodigoOS(int codigoOS) {
        this.codigoOS = codigoOS;
    }

    /**
     * @return the dataEntrada
     */
    public Date getDataEntrada() {
        return dataEntrada;
    }

    /**
     * @param dataEntrada the dataEntrada to set
     */
    public void setDataEntrada(Date dataEntrada) {
        this.dataEntrada = dataEntrada;
    }

    /**
     * @return the dataSaida
     */
    public Date getDataSaida() {
        return dataSaida;
    }

    /**
     * @param dataSaida the dataSaida to set
     */
    public void setDataSaida(Date dataSaida) {
        this.dataSaida = dataSaida;
    }

    /**
     * @return the valor
     */
    public double getValor() {
        return valor;
    }

    /**
     * @param valor the valor to set
     */
    public void setValor(double valor) {
        this.valor = valor;
    }

    /**
     * @return the qtdParcelas
     */
    public int getQtdParcelas() {
        return qtdParcelas;
    }

    /**
     * @param qtdParcelas the qtdParcelas to set
     */
    public void setQtdParcelas(int qtdParcelas) {
        this.qtdParcelas = qtdParcelas;
    }

    /**
     * @return the codigoCliente
     */
    public int getCodigoCliente() {
        return codigoCliente;
    }

    /**
     * @param codigoCliente the codigoCliente to set
     */
    public void setCodigoCliente(int codigoCliente) {
        this.codigoCliente = codigoCliente;
    }

    /**
     * @return the tipoFaturamento
     */
    public int getTipoFaturamento() {
        return tipoFaturamento;
    }

    /**
     * @param tipoFaturamento the tipoFaturamento to set
     */
    public void setTipoFaturamento(int tipoFaturamento) {
        this.tipoFaturamento = tipoFaturamento;
    }

    /**
     * @return the Observacao
     */
    public String getObservacao() {
        return Observacao;
    }

    /**
     * @param Observacao the Observacao to set
     */
    public void setObservacao(String Observacao) {
        this.Observacao = Observacao;
    }

    /**
     * @return the codigoECalc
     */
    public int getCodigoECalc() {
        return codigoECalc;
    }

    /**
     * @param codigoECalc the codigoECalc to set
     */
    public void setCodigoECalc(int codigoECalc) {
        this.codigoECalc = codigoECalc;
    }

    /**
     * @return the bv
     */
    public float getBv() {
        return bv;
    }

    /**
     * @param bv the bv to set
     */
    public void setBv(float bv) {
        this.bv = bv;
    }

    /**
     * @return the bvAgencia
     */
    public float getBvAgencia() {
        return bvAgencia;
    }

    /**
     * @param bvAgencia the bvAgencia to set
     */
    public void setBvAgencia(float bvAgencia) {
        this.bvAgencia = bvAgencia;
    }

    /**
     * @return the bvProdutor
     */
    public float getBvProdutor() {
        return bvProdutor;
    }

    /**
     * @param bvProdutor the bvProdutor to set
     */
    public void setBvProdutor(float bvProdutor) {
        this.bvProdutor = bvProdutor;
    }

    /**
     * @return the cliente
     */
    public String getCliente() {
        return cliente;
    }

    /**
     * @param cliente the cliente to set
     */
    public void setCliente(String cliente) {
        this.cliente = cliente;
    }

}

redpajama_set_name: RedPajamaGithub


text:
@protocol GPUImageTextureDelegate <NSObject>
- (void)textureNoLongerNeededForTarget:(id <GPUImageInput>)arg1;
@end


text:
using System;
using System.Net;

namespace Orleans.Runtime.Host
{
    /// <summary>
    /// Host program for the Orleans Silo when it is being run on Windows Server machine.
    /// </summary>
    /// <seealso cref="SiloHost"/>
    public class WindowsServerHost : IDisposable
    {
        /// <summary> Debug flag, produces some additional log information while starting the Silo.
        /// </summary>
        public bool Debug
        {
            get { return SiloHost != null && SiloHost.Debug; }
            set { SiloHost.Debug = value; }
        }

        /// <summary> Reference to the SiloHost in this process. </summary>
        public SiloHost SiloHost { get; private set; }

        /// <summary> Initialization function -- loads silo config information. </summary>
        public void Init()
        {
            SiloHost.LoadOrleansConfig();
        }

        /// <summary>
        /// Run fucntion for the Silo.
        /// </summary>
        /// <remarks>
        /// If the Silo starts up successfully, then this method will block and not return
        /// until the silo shutdown event is triggered, or the silo shuts down for some other reason.
        /// If the silo fails to star, then a StartupError.txt summary file will be written,
        /// and a process mini-dump will be created in the current working directory.
        /// </remarks>
        /// <returns>Returns <c>false</c> is Silo failed to start up correctly.</returns>
        public int Run()
        {
            bool ok;

            try
            {
                SiloHost.InitializeOrleansSilo();
                ok = SiloHost.StartOrleansSilo();

                if (ok)
                {
                    ConsoleText.WriteStatus(string.Format("Successfully started Orleans silo '{0}' as a {1} node.", SiloHost.Name, SiloHost.Type));
                    SiloHost.WaitForOrleansSiloShutdown();
                }
                else
                {
                    ConsoleText.WriteError(string.Format("Failed to start Orleans silo '{0}' as a {1} node.", SiloHost.Name, SiloHost.Type));
                }

                ConsoleText.WriteStatus(string.Format("Orleans silo '{0}' shutdown.", SiloHost.Name));
            }
            catch (Exception exc)
            {
                SiloHost.ReportStartupError(exc);
                TraceLogger.CreateMiniDump();
                ok = false;
            }

            return ok ? 0 : 1;
        }

        /// <summary>
        /// Parse command line arguments, to allow override of some silo runtime config settings.
        /// </summary>
        /// <param name="args">Command line arguments, as received by the Main program.</param>
        /// <returns></returns>
        public bool ParseArguments(string[] args)
        {
            string siloName = Dns.GetHostName(); // Default to machine name
            SiloHost = new SiloHost(siloName);

            int argPos = 1;
            for (int i = 0; i < args.Length; i++)
            {
                string a = args[i];
                if (a.StartsWith("-") || a.StartsWith("/"))
                {
                    switch (a.ToLowerInvariant())
                    {
                        case "/?":
                        case "/help":
                        case "-?":
                        case "-help":
                            // Query usage help
                            return false;
                        case "/debug":
                            SiloHost.Debug = true;
                            break;
                        default:
                            ConsoleText.WriteError("Bad command line arguments supplied: " + a);
                            return false;
                    }
                }
                else if (a.Contains("="))
                {
                    string[] split = a.Split('=');
                    if (String.IsNullOrEmpty(split[1]))
                    {
                        ConsoleText.WriteError("Bad command line arguments supplied: " + a);
                        return false;
                    }
                    switch (split[0].ToLowerInvariant())
                    {
                        case "deploymentid":
                            SiloHost.DeploymentId = split[1];
                            break;
                        case "deploymentgroup":
                            ConsoleText.WriteError("Ignoring deprecated command line argument: " + a);
                            break;
                        default:
                            ConsoleText.WriteError("Bad command line arguments supplied: " + a);
                            return false;
                    }
                }
                // unqualified arguments below
                else if (argPos == 1)
                {
                    SiloHost.Name = a;
                    argPos++;
                }
                else if (argPos == 2)
                {
                    SiloHost.ConfigFileName = a;
                    argPos++;
                }
                else
                {
                    // Too many command line arguments
                    ConsoleText.WriteError("Too many command line arguments supplied: " + a);
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Print usage info to console window, showing cmd-line params for OrleansHost.exe
        /// </summary>
        public void PrintUsage()
        {
            ConsoleText.WriteUsage(
@"USAGE:
    OrleansHost.exe [<siloName> [<configFile>]] [DeploymentId=<idString>] [/debug]
Where:
    <siloName>      - Name of this silo in the Config file list (optional)
    <configFile>    - Path to the Config file to use (optional)
    DeploymentId=<idString>
                    - Which deployment group this host instance should run in (optional)
    /debug          - Turn on extra debug output during host startup (optional)");
        }

        /// <summary>
        /// Dispose this host.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
        }

        protected virtual void Dispose(bool dispose)
        {
            SiloHost.Dispose();
            SiloHost = null;
        }
    }
}


text:
package ca.uhn.fhir.rest.param;

import java.util.Set;

public class QualifierDetails {

	private String myColonQualifier;
	private String myDotQualifier;
	private String myParamName;
	private String myWholeQualifier;

	public boolean passes(Set<String> theQualifierWhitelist, Set<String> theQualifierBlacklist) {
		if (theQualifierWhitelist != null) {
			if (!theQualifierWhitelist.contains(".*")) {
				if (myDotQualifier != null) {
					if (!theQualifierWhitelist.contains(myDotQualifier)) {
						return false;
					}
				} else {
					if (!theQualifierWhitelist.contains(".")) {
						return false;
					}
				}
			}
		}
		if (theQualifierBlacklist != null) {
			if (myDotQualifier != null) {
				if (theQualifierBlacklist.contains(myDotQualifier)) {
					return false;
				}
			}
			if (myColonQualifier != null) {
				if (theQualifierBlacklist.contains(myColonQualifier)) {
					return false;
				}
			}
		}

		return true;
	}

	public void setParamName(String theParamName) {
		myParamName = theParamName;
	}

	public String getParamName() {
		return myParamName;
	}

	public void setColonQualifier(String theColonQualifier) {
		myColonQualifier = theColonQualifier;
	}

	public void setDotQualifier(String theDotQualifier) {
		myDotQualifier = theDotQualifier;
	}

	public String getWholeQualifier() {
		return myWholeQualifier;
	}

	public void setWholeQualifier(String theWholeQualifier) {
		myWholeQualifier = theWholeQualifier;
	}

	public static QualifierDetails extractQualifiersFromParameterName(String theParamName) {
		QualifierDetails retVal = new QualifierDetails();
		if (theParamName == null || theParamName.length() == 0) {
			return retVal;
		}

		int dotIdx = -1;
		int colonIdx = -1;
		for (int idx = 0; idx < theParamName.length(); idx++) {
			char nextChar = theParamName.charAt(idx);
			if (nextChar == '.' && dotIdx == -1) {
				dotIdx = idx;
			} else if (nextChar == ':' && colonIdx == -1) {
				colonIdx = idx;
			}
		}

		if (dotIdx != -1 && colonIdx != -1) {
			if (dotIdx < colonIdx) {
				retVal.setDotQualifier(theParamName.substring(dotIdx, colonIdx));
				retVal.setColonQualifier(theParamName.substring(colonIdx));
				retVal.setParamName(theParamName.substring(0, dotIdx));
				retVal.setWholeQualifier(theParamName.substring(dotIdx));
			} else {
				retVal.setColonQualifier(theParamName.substring(colonIdx, dotIdx));
				retVal.setDotQualifier(theParamName.substring(dotIdx));
				retVal.setParamName(theParamName.substring(0, colonIdx));
				retVal.setWholeQualifier(theParamName.substring(colonIdx));
			}
		} else if (dotIdx != -1) {
			retVal.setDotQualifier(theParamName.substring(dotIdx));
			retVal.setParamName(theParamName.substring(0, dotIdx));
			retVal.setWholeQualifier(theParamName.substring(dotIdx));
		} else if (colonIdx != -1) {
			retVal.setColonQualifier(theParamName.substring(colonIdx));
			retVal.setParamName(theParamName.substring(0, colonIdx));
			retVal.setWholeQualifier(theParamName.substring(colonIdx));
		} else {
			retVal.setParamName(theParamName);
			retVal.setColonQualifier(null);
			retVal.setDotQualifier(null);
			retVal.setWholeQualifier(null);
		}

		return retVal;
	}

}


text:
layout: post
title: Exame de 3ª Chamada
date: 2006-09-19 10:35:11.000000000 +01:00
type: post
published: true
status: publish
categories: []
tags: []
meta:
  spaces_3b4c7ab08b2559d7e6deed6ee4bb7aaa_permalink: http://cid-bdfcf232da5f8179.users.api.live.net/Users(-4756660806184107655)/Blogs('BDFCF232DA5F8179!102')/Entries('BDFCF232DA5F8179!504')?authkey=hSbGhYtz7bY%24
author:
  login: fmcarvalho
  email: mcarvalho@cc.isel.ipl.pt
  display_name: fmcarvalho
  first_name: ''
  last_name: ''
---

Neste semestre foi criada uma 3ª chamada de exame a realizar no mês de Setembro, devido ao desaparecimento de algumas cadeiras resultantes da adequação dos cursos a Bolonha.

Inicialmente pensei escrever neste post, porque é que não concordava com a existência de uma 3ª chamada. Em vez disso, vou deixar escrito apenas que numa das provas que realizei, eram esperados 40 alunos, apareceram 10 e nenhum entregou.


text:
"""webservices URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from pyws.adapters._django import serve
from server import server

urlpatterns = [
    url(r'^admin/', admin.site.urls), url('^api/(.*)', serve, {'server': server}),
]


text:
package org.apache.isis.applib.services.command;

import java.sql.Timestamp;

import org.apache.isis.applib.Identifier;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.Command.ExecuteIn;
import org.apache.isis.applib.annotation.Command.Persistence;
import org.apache.isis.applib.annotation.Optional;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.clock.Clock;
import org.apache.isis.applib.services.HasTransactionId;
import org.apache.isis.applib.services.background.BackgroundCommandService;
import org.apache.isis.applib.services.background.BackgroundService;
import org.apache.isis.applib.services.bookmark.Bookmark;
import org.apache.isis.applib.services.bookmark.BookmarkService;
import org.apache.isis.applib.services.eventbus.ActionDomainEvent;
import org.apache.isis.applib.services.iactn.Interaction;
import org.apache.isis.applib.services.publish.EventMetadata;
import org.apache.isis.applib.services.publish.EventPayload;
import org.apache.isis.applib.services.wrapper.WrapperFactory;
import org.apache.isis.schema.cmd.v1.CommandDto;

/**
 * Represents the intention to invoke either an action or modify a property.  This intention is reified as a
 * {@link Command#getMemento() memento} by way of the (internal) <tt>CommandDtoServiceInternal</tt> domain service;
 * typically corresponding to the XML equivalent of a {@link CommandDto}.
 *
 *

 *     The {@link Command} interface also captures details of the corresponding action invocation (or property edit),
 *     specifically when that action/edit {@link Command#getStartedAt() started} or
 *     {@link Command#getCompletedAt() completed}, and its result, either a {@link Command#getResult() return value}
 *     or an {@link Command#getException() exception}.  The {@link Command3} sub-interface also captures the stack
 *     of {@link ActionDomainEvent}s.
 *

 *
 *

 *     Note that when invoking an action, other actions may be invoked courtesy of the {@link WrapperFactory}.  These
 *     "sub-actions" do not modify the contents of the command object; in other words think of the command
 *     object as representing the outer-most originating action.
 *

 *
 *

 *     One of the responsibilities of the command is to generate unique sequence numbers for a given transactionId.
 *     This is done by {@link #next(String)}.  There are three possible sequences that might be generated:
 *     the sequence of changed domain objects being published by the {@link org.apache.isis.applib.services.publish.PublishingService#publish(EventMetadata, EventPayload)}; the
 *     sequence of wrapped action invocations (each being published), and finally one or more background commands
 *     that might be scheduled via the {@link BackgroundService}.
 *

 *
 */
public interface Command extends HasTransactionId {

    /**
     * @deprecated - in previous versions this was the value for {@link #getTargetAction()} if this command represents an edit of an object's property (rather than an action); now though the property's name is used (ie same as actions).
     */
    @Deprecated
    String ACTION_IDENTIFIER_FOR_EDIT = "(edit)";

    //region > user (property)
    /**
     * The user that created the command.
     */

    String getUser();
    /**
     * NOT API: intended to be called only by the framework.
     *
     *

     * Implementation notes: set when the Isis PersistenceSession is opened.
     */
    void setUser(String user);
    //endregion

    //region > timestamp (property)

    /**
     * The date/time at which this command was created.
     */
    Timestamp getTimestamp();
    /**
     * NOT API: intended to be called only by the framework.
     *
     *

     * Implementation notes: set when the Isis PersistenceSession is opened.  Uses the applib {@link Clock}.
     */
    void setTimestamp(Timestamp timestamp);

    //endregion

    //region > target (property)

    /**
     * {@link Bookmark} of the target object (entity or service) on which this action was performed.
     *
     *

     * Will only be populated if a {@link BookmarkService} has been configured.
     */
    Bookmark getTarget();
    /**
     * NOT API: intended to be called only by the framework.
     *
     *

     * Implementation notes: set when the action is invoked (in the ActionInvocationFacet).
     */
    void setTarget(Bookmark target);

    //endregion

    //region > memberIdentifier (property)

    /**
     * Holds a string representation of the invoked action, or the edited property, equivalent to
     * {@link Identifier#toClassAndNameIdentityString()}.
     */
    String getMemberIdentifier();

    /**
     * NOT API: intended to be called only by the framework.
     *
     *

     * Implementation notes: set when the action is invoked (in <tt>ActionInvocationFacet</tt>) or in
     * property edited (in <tt>PropertySetterFacet</tt>).
     */
    void setMemberIdentifier(String memberIdentifier);

    //endregion

    //region > targetClass (property)

    /**
     * A human-friendly description of the class of the target object.
     */
    String getTargetClass();

    /**
     * NOT API: intended to be called only by the framework.
     *
     *

     * Implementation notes: set when the action is invoked (in the <tt>ActionInvocationFacet</t>).
     */
    void setTargetClass(String targetClass);

    //endregion

    //region > targetAction (property)

    /**
     * The human-friendly name of the action invoked/property edited on the target object.
     *
     *

     *     NB: in earlier versions, if the command represented an edit of a property, then it held the special value "{@value ACTION_IDENTIFIER_FOR_EDIT}".  This is NO LONGER the case; it simply holds the member.
     *

     */
    String getTargetAction();

    /**
     * NOT API: intended to be called only by the framework.
     *
     *

     * Implementation notes: set when the action is invoked (in the <tt>ActionInvocationFacet</tt>) or property edited
     * (in the <tt>PropertySetterOrClearFacet</tt>).
     */
    void setTargetAction(String targetAction);

    //endregion

    //region > arguments (property)

    /**
     * A human-friendly description of the arguments with which the action was invoked.
     */
    String getArguments();

    /**
     * NOT API: intended to be called only by the framework.
     *
     *

     * Implementation notes: set when the action is invoked (in the <tt>ActionInvocationFacet</tt>).
     */
    void setArguments(final String arguments);

    //endregion

    //region > memento (property)

    /**
     * A formal (XML or similar) specification of the action to invoke/being invoked.
     */
    String getMemento();

    /**
     * NOT API: intended to be called only by the framework.
     *
     *

     * Implementation notes: set when the action is invoked (in the <tt>ActionInvocationFacet</tt>).
     */
    void setMemento(final String memento);

    //endregion

    //region > executeIn (property)

    /**
     * The mechanism by which this command is to be executed, either synchronously "in the
     * {@link ExecuteIn#FOREGROUND foreground}" or is to be executed asynchronously "in the
     * {@link ExecuteIn#BACKGROUND background}" through the {@link BackgroundCommandService}.
     */
    ExecuteIn getExecuteIn();

    /**
     * NOT API: intended to be called only by the framework.
     */
    void setExecuteIn(final ExecuteIn executeIn);

    //endregion

    //region > executor (property)

    enum Executor {
        /**
         * Command being executed by the end-user.
         */
        USER,
        /**
         * Command being executed by a background execution service.
         */
        BACKGROUND,
        /**
         * Command being executed for some other reason, eg as result of redirect-after-post, or the homePage action.
         */
        OTHER
    }

    /**
     * The (current) executor of this command.
     *
     *

     * Note that (even for implementations of {@link BackgroundCommandService} that persist {@link Command}s), this
     * property is never (likely to be) persisted, because it is always updated to indicate how the command is
     * currently being executed.
     *
     *

     * If the {@link #getExecutor() executor} matches the required {@link #getExecuteIn() execution policy}, then the
     * command actually is executed.  The combinations are:
     *

     *
executor = USER, executeIn = FOREGROUND, then execute

     *
executor = USER, executeIn = BACKGROUND, then persist and return persisted command as a placeholder for the result

     *
executor = BACKGROUND, executeIn = FOREGROUND, then ignore

     *
executor = BACKGROUND, executeIn = BACKGROUND, then execute, update the command with result

     *

     *
     */
    Executor getExecutor();

    /**
     * NOT API: intended to be called only by the framework.
     */
    void setExecutor(final Executor executor);

    //endregion

    //region > startedAt (property, deprecated)

    /**
     * For an command that has actually been executed, holds the date/time at which the {@link Interaction} that
     * executed the command started.
     *
     * @deprecated - see {@link Interaction#getStartedAt()}.
     */
    @Deprecated
    Timestamp getStartedAt();

    /**
     * NOT API: intended to be called only by the framework.
     *
     * @deprecated - see {@link Interaction#getCurrentExecution()} and {@link org.apache.isis.applib.services.iactn.Interaction.Execution#setStartedAt(Timestamp)}.
     */
    @Deprecated
    void setStartedAt(Timestamp startedAt);

    //endregion

    //region > completedAt (property, deprecated)

    /**
     * For an command that has actually been executed, holds the date/time at which the {@link Interaction} that
     * executed the command completed.
     *
     * @deprecated - see {@link Interaction#getCurrentExecution()} and  {@link org.apache.isis.applib.services.iactn.Interaction.Execution#getCompletedAt()}.
     */
    @Deprecated
    Timestamp getCompletedAt();

    /**
     * NOT API: intended to be called only by the framework.
     *
     * @deprecated - see {@link org.apache.isis.applib.services.iactn.Interaction.Execution#setCompletedAt(Timestamp)}.
     */
    @Deprecated
    void setCompletedAt(Timestamp completedAt);

    //endregion

    //region > parent (property)

    /**
     * For actions created through the {@link BackgroundService} and {@link BackgroundCommandService},
     * captures the parent action.
     */
    Command getParent();

    /**
     * NOT API: intended to be called only by the framework.
     */
    void setParent(final Command parent);

    //endregion

    //region > exception (property, deprecated)

    /**
     * For an command that has actually been executed, holds the exception stack
     * trace if the action invocation/property modification threw an exception.
     *
     * @deprecated - see {@link Interaction#getCurrentExecution()} and  {@link org.apache.isis.applib.services.iactn.Interaction.Execution#getThrew()} instead.
     */
    @Deprecated
    @Optional
    String getException();

    /**
     * NOT API: intended to be called only by the framework.
     */
    void setException(String stackTrace);

    //endregion

    //region > result (property, deprecated)

    /**
     * For an command that has actually been executed, holds a {@link Bookmark} to the object returned by the corresponding action/property modification.
     *
     * @deprecated - see {@link Interaction#getCurrentExecution()} and  {@link org.apache.isis.applib.services.iactn.Interaction.Execution#getReturned()} instead.
     */
    @Deprecated
    Bookmark getResult();

    /**
     * NOT API: intended to be called only by the framework.
     */
    void setResult(Bookmark resultBookmark);

    //endregion

    //region > persistence (property)

    /**
     * Whether this command should ultimately be persisted (if the configured {@link BackgroundCommandService} supports
     * it) or not.
     *
     *

     * If the action to be executed has been annotated with the {@link Action#command()} attribute
     * then (unless its {@link Action#commandPersistence()} persistence} attribute has been set to a different value
     * than its default of {@link org.apache.isis.applib.annotation.CommandPersistence#PERSISTED persisted}), the
     * {@link Command} object will be persisted.
     *
     *

     * However, it is possible to prevent the {@link Command} object from ever being persisted by setting the
     * {@link org.apache.isis.applib.annotation.Action#commandPersistence() persistence} attribute to
     * {@link org.apache.isis.applib.annotation.CommandPersistence#NOT_PERSISTED}, or it can be set to
     * {@link org.apache.isis.applib.annotation.CommandPersistence#IF_HINTED}, meaning it is dependent
     * on whether {@link #setPersistHint(boolean) a hint has been set} by some other means.
     *
     *

     * For example, a {@link BackgroundCommandService} implementation that creates persisted background commands ought
     * associate them (via its {@link Command#getParent() parent}) to an original persisted
     * {@link Command}.  The hinting mechanism allows the service to suggest that the parent command be persisted so
     * that the app can then provide a mechanism to find all child background commands for that original parent command.
     */
    Persistence getPersistence();

    /**
     * NOT API: intended to be called only by the framework.
     */
    void setPersistence(final Persistence persistence);
    //endregion

    //region > persistHint (programmatic)

    /**
     * Whether that this {@link Command} should be persisted, if possible.
     */
    @Programmatic
    boolean isPersistHint();

    /**
     * Hint that this {@link Command} should be persisted, if possible.
     *
     *

     * NOT API: intended to be called only by the framework.
     *
     * @see #getPersistence()
     */
    @Programmatic
    void setPersistHint(boolean persistHint);
    //endregion

    //region > next (programmatic, deprecated)

    /**
     * NOT API: intended to be called only by the framework.
     *
     * @deprecated - no longer used (the framework uses {@link Interaction#next(String)} instead).
     */
    @Deprecated
    @Programmatic
    int next(final String sequenceAbbr);

    //endregion

}


text:
"""
Created on Jan 1, 2016

@author: Gregory Kramida
"""
from lxml import etree
import numpy as np
from calib import camera as camera_module, geom, rig
from calib.geom import Pose
from calib.camera import Camera

IMAGE_POINTS = "image_points"
FRAME_NUMBERS = "frame_numbers"
OBJECT_POINT_SET = "object_point_set"
POSES = "poses"
CALIBRATION_INTERVALS = "calibration_intervals"

def load_frame_data(archive, videos, board_height=None,
                    board_width=None, board_square_size=None,
                    verbose=True):
    if verbose:
        print("Loading object & image positions from archive.")

    if OBJECT_POINT_SET in archive:
        object_point_set = archive[OBJECT_POINT_SET]
    else:
        object_point_set = geom.generate_board_object_points(board_height, board_width, board_square_size)

    video_by_name = {}
    for video in videos:
        video_by_name[video.name] = video

    # legacy frame numbers
    if FRAME_NUMBERS in archive:
        frame_numbers = archive[FRAME_NUMBERS]
        for video in videos:
            video.usable_frames = {}
            i_key = 0
            for key in frame_numbers:
                video.usable_frames[key] = i_key
                i_key += 1
        if verbose:
            print("Loaded {:d} usable frame numbers for all cameras in legacy format.".format(len(frame_numbers)))

    for array_name, value in archive.items():
        if array_name.startswith(IMAGE_POINTS):
            vid_name = array_name[len(IMAGE_POINTS):]
            video_by_name[vid_name].image_points = value
            if verbose:
                print("Loaded {:d} image point sets for camera {:s}".format(len(value), vid_name), flush=True)
        elif array_name.startswith(FRAME_NUMBERS) and not array_name == FRAME_NUMBERS:
            vid_name = array_name[len(FRAME_NUMBERS):]
            video = video_by_name[vid_name]
            video.usable_frames = {}
            i_key = 0
            for key in value:
                video.usable_frames[key] = i_key
                i_key += 1
            if verbose:
                print("Loaded {:d} usable frame numbers for camera {:s}".format(len(value), vid_name), flush=True)
        elif array_name.startswith(POSES):
            vid_name = array_name[len(POSES):]
            # process poses
            video_by_name[vid_name].poses = [Pose(T) for T in value]
            if verbose:
                print("Loaded {:d} poses for camera {:s}".format(len(value), vid_name), flush=True)

    return object_point_set

def save_frame_data(archive, path, videos, object_point_set, verbose=True):
    if verbose:
        print("Saving corners to {0:s}".format(path))
    for video in videos:
        archive[IMAGE_POINTS + str(video.name)] = video.image_points
        archive[FRAME_NUMBERS + str(video.name)] = list(video.usable_frames.keys())
        if len(video.poses) > 0:
            archive[POSES + str(video.name)] = np.array([pose.T for pose in video.poses])

    archive[OBJECT_POINT_SET] = object_point_set
    np.savez_compressed(path, **archive)

def load_calibration_intervals(archive, videos, verbose=True):
    if verbose:
        print("Loading calibration frame intervals from archive.")
    if CALIBRATION_INTERVALS in archive:
        ranges = archive[CALIBRATION_INTERVALS]
        if len(videos) != ranges.shape[0]:
            raise ValueError("Need to have the same number of rows in the frame_ranges array as the number of cameras.")
        ix_cam = 0
        for video in videos:
            video.calibration_interval = tuple(ranges[ix_cam])
            ix_cam += 1
    else:
        raise ValueError("No calibration intervals found in the provided archive.")

def save_calibration_intervals(archive, path, videos, verbose=True):
    if verbose:
        print("Saving calibration intervals to {0:s}".format(path))
    ranges = []
    for video in videos:
        if video.calibration_interval is None:
            raise ValueError("Expecting all cameras to have valid calibration frame ranges. Got: None")
        ranges.append(video.calibration_interval)
    ranges = np.array(ranges)
    archive[CALIBRATION_INTERVALS] = ranges
    np.savez_compressed(path, **archive)

def load_opencv_stereo_calibration(path):
    """
    Load stereo calibration information from xml file
    @type path: str
    @param path: video_path to xml file
    @return stereo calibration: loaded from the given xml file
    @rtype calib.data.StereoRig
    """
    tree = etree.parse(path)
    stereo_calib_elem = tree.find("Rig")
    return rig.Rig.from_xml(stereo_calib_elem)

def load_opencv_single_calibration(path):
    """
    Load single-camera calibration information from xml file
    @type path: str
    @param path: video_path to xml file
    @return calibration info: loaded from the given xml file
    @rtype calib.data.CameraIntrinsics
    """
    tree = etree.parse(path)
    calib_elem = tree.find(Camera.Intrinsics.__name__)
    return Camera.Intrinsics.from_xml(calib_elem)

def load_opencv_calibration(path):
    """
    Load any kind (stereo or single) of calibration result from the file
    @type path: str
    @param path: path to xml file
    @return calibration info: loaded from the given xml file
    @rtype calib.data.CameraIntrinsics | calib.data.StereoRig
    """
    tree = etree.parse(path)
    first_elem = tree.getroot().getchildren()[0]
    class_name = first_elem.tag
    modules = [camera_module, rig]
    object_class = None
    for module in modules:
        if hasattr(module, class_name):
            object_class = getattr(module, class_name)
    if object_class is None:
        # legacy formats
        if class_name == "_StereoRig":
            object_class = rig.Rig
        elif class_name == "CameraIntrinsics":
            object_class = Camera.Intrinsics
        else:
            raise ValueError("Unexpected calibration format in file {:s}, got XML tag {:s}. "
                             "For legacy StereoRig files, be sure to rename the tag to _StereoRig."
                             .format(path, class_name))
    calib_info = object_class.from_xml(first_elem)
    return calib_info

def save_opencv_calibration(path, calibration_info):
    root = etree.Element("opencv_storage")
    calibration_info.to_xml(root)
    et = etree.ElementTree(root)
    with open(path, 'wb') as f:
        et.write(f, encoding="utf-8", xml_declaration=True, pretty_print=True)
    # little hack necessary to replace the single quotes (that OpenCV doesn't like) with double quotes
    s = open(path).read()
    s = s.replace("'", "\"")
    with open(path, 'w') as f:
        f.write(s)
        f.flush()

def save_opencv_xml_file(path, xml_generator):
    """
    Save something in opencv's XML format
    @param path: path where to save the file
    @param xml_generator: function that accepts an LXML root element as a parameter and generates all the necessary XML
    to go in the file
    """
    root = etree.Element("opencv_storage")
    xml_generator(root)
    et = etree.ElementTree(root)
    with open(path, 'wb') as f:
        et.write(f, encoding="utf-8", xml_declaration=True, pretty_print=True)
    # little hack necessary to replace the single quotes (that OpenCV doesn't like) with double quotes
    s = open(path).read()
    s = s.replace("'", "\"")
    with open(path, 'w') as f:
        f.write(s)
        f.flush()


text:
var chai = require('chai');
var assert = chai.assert;
var jsonSchemaValidator = require('./');
var projectConfigSchema = require('../../optimizely/project_config_schema');
var sprintf = require('sprintf');
var testData = require('../../../tests/test_data.js');

var ERROR_MESSAGES = require('../enums').ERROR_MESSAGES;

describe('lib/utils/json_schema_validator', function() {
  describe('APIs', function() {
    describe('validate', function() {
      it('should validate the given object against the specified schema', function() {
        assert.isTrue(jsonSchemaValidator.validate({'type': 'number'}, 4));
      });

      it('should throw an error if the object is not valid', function() {
        assert.throws(function() {
          jsonSchemaValidator.validate({'type': 'number'}, 'not a number');
        }, sprintf(ERROR_MESSAGES.INVALID_DATAFILE, 'JSON_SCHEMA_VALIDATOR', 'instance is not of a type(s) number'));
      });

      it('should throw an error if no schema is passed in', function() {
        assert.throws(function() {
          jsonSchemaValidator.validate();
        }, sprintf(ERROR_MESSAGES.JSON_SCHEMA_EXPECTED, 'JSON_SCHEMA_VALIDATOR'));
      });

      it('should throw an error if no json object is passed in', function() {
        assert.throws(function() {
          jsonSchemaValidator.validate({'type': 'number'});
        }, sprintf(ERROR_MESSAGES.NO_JSON_PROVIDED, 'JSON_SCHEMA_VALIDATOR'));
      });

      it('should validate specified New Optimizely datafile if comparing to New Optimizely schema', function() {
        assert.isTrue(jsonSchemaValidator.validate(projectConfigSchema.V2, testData.getTestProjectConfigNewOptly()));
      });

      it('should throw an error if New Optimizely datafile is compared to Classic Optimizely schema', function() {
        assert.throws(function() {
          jsonSchemaValidator.validate(projectConfigSchema.V1, testData.getTestProjectConfigNewOptly());
        }, sprintf(ERROR_MESSAGES.INVALID_DATAFILE,
                   'JSON_SCHEMA_VALIDATOR',
                   'instance requires property "dimensions"'));
      });

      it('should validate specified Classic Optimizely datafile', function() {
        assert.isTrue(jsonSchemaValidator.validate(projectConfigSchema.V1, testData.getTestProjectConfig()));
      });

      it('should throw an error if Classic Optimizely datafile is compared to New Optimizely schema', function() {
        assert.throws(function() {
          jsonSchemaValidator.validate(projectConfigSchema.V2, testData.getTestProjectConfig());
        }, sprintf(ERROR_MESSAGES.INVALID_DATAFILE,
                   'JSON_SCHEMA_VALIDATOR',
                   'instance.groups[0].experiments[0] requires property "layerId"'));
      });
    });
  });
});


text:
require "thor/shell/basic"

module GemSuit
  class CLI < Thor
    module Base
      module Shell

        def self.included(base)
          base.send :include, InstanceMethods
        end

        module InstanceMethods

          def shell
            @shell ||= Thor::Shell::Basic.new
          end

          def is?(*args)
            shell.send :is?, *args
          end

          def agree?(question, default = nil)
            opts   = %w(y n).collect{|x| !default.nil? && x =~ is?(default) ? x.upcase : x}
            answer = ask question, opts, default
            !!(answer =~ is?(:yes))
          end

          def ask(question, opts = nil, default = nil)
            in_brackets = [opts, default].compact.first
            statement   = [question, ("[#{in_brackets}]" unless in_brackets.nil?)].compact.join " "

            answer = shell.ask statement if options.interactive? || default.nil?
            answer.nil? || answer.empty? ? default.to_s : answer
          end

        end

      end
    end
  end
end


text:
package com.castlemock.repository.core.file.project;

import com.castlemock.model.core.Saveable;
import com.castlemock.repository.core.file.FileRepository;
import org.dozer.Mapping;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;

public abstract class AbstractProjectFileRepository<T extends AbstractProjectFileRepository.ProjectFile, D> extends FileRepository<T, D, String> {

    @XmlRootElement(name = "project")
    public static abstract class ProjectFile implements Saveable<String> {

        @Mapping("id")
        private String id;

        @Mapping("name")
        private String name;

        @Mapping("description")
        private String description;

        @Mapping("updated")
        private Date updated;

        @Mapping("created")
        private Date created;

        @XmlElement
        @Override
        public String getId() {
            return id;
        }

        @Override
        public void setId(String id) {
            this.id = id;
        }

        @XmlElement
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @XmlElement
        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        @XmlElement
        public Date getUpdated() {
            return updated;
        }

        public void setUpdated(Date updated) {
            this.updated = updated;
        }

        @XmlElement
        public Date getCreated() {
            return created;
        }

        public void setCreated(Date created) {
            this.created = created;
        }

    }

}


text:
package org.andstatus.todoagenda.util;

import java.util.concurrent.atomic.AtomicLong;

public class InstanceId {
    /**
     * IDs used for testing purposes to identify instances of reference types.
     */
    private static final AtomicLong PREV_INSTANCE_ID = new AtomicLong(0);

    private InstanceId() {
    }

    /**
     * @return Unique for this process long value, numbers are given in the order starting from 1
     */
    public static long next() {
        return PREV_INSTANCE_ID.incrementAndGet();
    }
}


text:
/*
* Author: Maire Kehoe (mkehoe@ie.ibm.com)
* Date: 8 Jun 2011
* BaseTitleAccessibilityCategoryTest.java
*/
package com.ibm.xsp.test.framework.registry.annotate;

import com.ibm.xsp.test.framework.XspTestUtil;

/**
 *
 * @author Maire Kehoe (mkehoe@ie.ibm.com)
 */
public class BaseTitleAccessibilityTest extends
        TitleAccessibilityTest {

    @Override
    protected String[][] getExtraConfig() {
        String[][] config = super.getExtraConfig();
        config = XspTestUtil.concat(config, new String[][]{
                //Boolean indicating whether to test the xsp-config and .xsp files in the project
                //where the junit tests are being run, defaults to false.
                {"target.local.xspconfigs","false"},
        });
        return config;
    }
}


text:
import { Language24 } from "../../";

export = Language24;


text:
define([

        'angular',

    ], function(angular) {
    'use strict';

    function DashboardUserMapController($scope, $rootScope, uiGmapGoogleMapApi) {

        var controller = this;

        this.clusterCalculator = function(markers, numStyles) {

            var markerInstances = markers.values(),
                markerLength = 0,
                stressLevelSum = 0;

            angular.forEach(markerInstances, function(markerInstance, index) {
                stressLevelSum += markerInstance.model.averageStressLevel;
                markerLength++;

                angular.forEach(markerInstance.stressMarkers, function(stressMarker, index) {
                    stressLevelSum += stressMarker;
                    markerLength++;
                });

            });

            var title = "Average stress level in this area. Detected : " + markerLength + " stress changes.";
            var count = Math.round(stressLevelSum / markerLength);

            var customIconsMap = {
                1 : 1, // blue
                2 : 1, // blue
                3 : 1, // blue
                4 : 2, // yellow
                5 : 3  // red
            };

            return {
                text: count,
                index: customIconsMap[count],
                title: title
            };

        };

        $scope.map = {
            center:  {
                latitude: 53.88954020000001,
                longitude: 27.649613300000055
            },
            options : {
                scrollwheel: false
            },
            zoom: 12,
            control : {}
        };

        $scope.clusterOptions = {
            calculator : controller.clusterCalculator,
            minimumClusterSize : 5
        };

        uiGmapGoogleMapApi.then(function(maps) {});

        $scope.stressMarkers = [];
        $scope.locations = [];

        $scope.setMapMarkers = function(points) {
            if(points && points.length) {
                $scope.stressMarkers = $scope.initMarkers(points);
            }
        };

        function calculateAverageStressLevel(stressMarkers) {
            var summ = 0;

            angular.forEach(stressMarkers, function(stress) {
                summ += stress;
            });

            return Math.round(summ / stressMarkers.length);
        }

        $scope.initMarkers = function(points) {

            var markers = $scope.stressMarkers;

            angular.forEach(points, function(point, index) {

                if(point.locations) {
                    $scope.addLocationsToMap(point);
                }

                //remove duplicates
                var newMarker = true;

                angular.forEach(markers, function(marker, index) {

                    if(marker.geolocation.latitude === point.geolocation.latitude &&
                        marker.geolocation.longitude === point.geolocation.longitude) {
                        newMarker = false;
                        marker.stressMarkers.push(point.stressLevel);
                        // marker.averageStressLevel = calculateAverageStressLevel(marker.stressMarkers, marker);
                        calculateCustomIcon(marker);
                        return false;
                    }

                });

                if(newMarker) {
                    $scope.createNewMarker(markers, point);
                }

            });

            return markers;

        };

        $scope.addNewLocation = function(location) {

            location.coords = {
                longitude : location.geometry.location.lng,
                latitude : location.geometry.location.lat
            };

            location.vicinity = location.vicinity ? location.vicinity : 'Unnamed vicinity';

            location.name = '
 Vicinity: ' + location.vicinity + '
' +
                            '
' + location.name + '
';

            location.customIcon = 'http://maps.google.com/mapfiles/kml/pal5/icon13.png';

            location.show = false;

            location.onClick = function(object, event, point) {
                closeOpenedWindows(point);
            };

            $scope.locations.push(location);

        };

        $scope.addLocationsToMap = function(point) {

            angular.forEach(point.locations, function(location, index) {

                var newLocation = true;

                if(location.types) {

                    angular.forEach(location.types, function(googleLocationType, index) {

                        if(googleLocationType === "colloquial_area") {
                            newLocation = false;
                            return false;
                        }

                    });

                    if(newLocation) {
                        angular.forEach($scope.locations, function(storedLocation, index) {

                            if(storedLocation.geometry.location.lat === location.geometry.location.lat &&
                                storedLocation.geometry.location.lng === location.geometry.location.lng) {

                                newLocation = false;

                                if(storedLocation.name.indexOf(location.name) === -1) {
                                    storedLocation.markerOptions.zIndex = storedLocation.markerOptions.zIndex ? storedLocation.markerOptions.zIndex + 1 : 1;
                                    storedLocation.name = storedLocation.name + '
' + location.name + '
';
                                }

                                return false;
                            }

                        });
                    }

                    if(newLocation) {

                        location.markerOptions = {
                            draggable : false,
                            zIndex : 1
                        };

                        $scope.addNewLocation(location);
                    }

                }

            });
        };

        var levelMap = {
            1 : 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=1|21a9e1|ffffff',
            2 : 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=2|1988b6|ffffff',
            3 : 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=3|00a651|ffffff',
            4 : 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=4|fad839|000000',
            5 : 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=5|cc2424|ffffff'
        };

        function closeOpenedWindows(point) {
            angular.forEach($scope.stressMarkers, function(marker) {
                marker.show = marker.id === point.id;
            });

            angular.forEach($scope.locations, function(location) {
                location.show = false;
            });
        }

        function calculateCustomIcon(point) {

            if(point.travelType === 'car' && point.carEvent) {

                if(point.carEvent === 'Heavy braking') {

                    point.customIcon = '/images/stop.png';

                } else if(point.carEvent === 'Accelerate') {

                    point.customIcon =  '/images/acs.png';

                } else {

                    point.customIcon = 'http://maps.google.com/mapfiles/kml/pal2/icon39.png';

                }

                if(!point.marker) {
                    point.marker = {};
                }

                point.marker.icon = point.customIcon;

            } else {
                point.customIcon = levelMap[point.stressLevel];
            }
        }

        $scope.createNewMarker = function(markers, point) {
            point.show = false;
            point.stressMarkers = [point.stressLevel];
            point.averageStressLevel = point.stressLevel;

            point.onClick = function(object, event, point) {
                closeOpenedWindows(point);
            };

            if(point.marker && point.marker.description) {

                point.title = '
';

                if(point.marker.time) {
                    point.title +='
' + point.marker.time.time + ' ' + point.marker.time.date + '
';
                }
                if(point.weather) {

                    point.title +='
';

                    if(point.weather.weatherIconUrl) {
                        if(point.weather.weatherIconUrl && point.weather.weatherIconUrl[0].value) {
                            point.title +='';
                        }
                    }

                    if(point.weather.tempF) {
                        point.title += ' ' + point.weather.tempF + '°F ';
                    }

                    if(point.weather.pressure){
                        point.title += '' + point.weather.pressure + 'mb ';
                    }
                    if(point.weather.humidity){
                        point.title += '' + point.weather.humidity + '%
 ';
                    }

                }

                point.title += '
' + point.marker.description + '

';

            }
            calculateCustomIcon(point);

            markers.push(point);
        };

        $scope.highlightTimelineEvent = function(id){
            $rootScope.$broadcast('markerClicked', id);
        };

        $scope.calculateNextMarkers = function(points) {
            if(points && points.length) {
                $scope.stressMarkers = $scope.initMarkers(points);
            }
        };

        //todo find old marker and replace
        $scope.addNewMarker = function(point) {
            $scope.createNewMarker($scope.stressMarkers, point);
        };

    }

    return  DashboardUserMapController;
});


text:
package org.fest.assertions.api;

import java.util.Map;

import org.fest.test.ExpectedException;
import org.fest.util.Maps;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

/**
 * Tests for {@link MapAssert#doesNotContainKey(Object)}.
 *
 * @author Nicolas François
 * @author Yvonne Wang
 */
public class MapAssert_doesNotContainKey_Test  {
  @Rule
  public ExpectedException thrown = ExpectedException.none();
  private Map<String, String> actual = Maps.newHashMap();
  private String key = "ten";
  private MapAssert assertions;

  @Before
  public void setUp() {
    actual.put("one", "apple");
    assertions = new MapAssert(actual);
  }

  @Test
  public void should_pass_if_actual_does_not_contain_given_key() {
    assertions.doesNotContainKey(key);
  }

  @Test
  public void should_throw_error_if_actual_is_null() {
    thrown.expect(AssertionError.class);
    assertions = new MapAssert(null);
    assertions.doesNotContainKey(key);
  }

  @Test
  public void should_pass_if_key_is_null_and_actual_does_not_have_null_key() {
    key = null;
    assertions.doesNotContainKey(key);
  }

  @Test
  public void should_pass_if_actual_is_empty() {
    actual = Maps.newHashMap();
    assertions = new MapAssert(actual);
    assertions.doesNotContainKey(key);
  }

  @Test
  public void should_fail_if_actual_contains_given_key() {
    thrown.expect(AssertionError.class);
    assertions.doesNotContainKey("one");
  }
}


text:
<link rel="import" href="../polymer/polymer.html">

<polymer-element name="event-card" attributes="event">
  <template>

      <paper-shadow z="1"></paper-shadow>

        {{ eventString }}

  </template>

</polymer-element>


text:
Provides various native pointer-to-type (<type> *)
representations.


text:
.. image:: https://img.shields.io/pypi/v/zipp.svg
   :target: https://pypi.org/project/zipp

.. image:: https://img.shields.io/pypi/pyversions/zipp.svg

.. image:: https://github.com/jaraco/zipp/workflows/tests/badge.svg
   :target: https://github.com/jaraco/zipp/actions?query=workflow%3A%22tests%22
   :alt: tests

.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
   :target: https://github.com/psf/black
   :alt: Code style: Black

.. .. image:: https://readthedocs.org/projects/skeleton/badge/?version=latest
..    :target: https://skeleton.readthedocs.io/en/latest/?badge=latest

.. image:: https://img.shields.io/badge/skeleton-2022-informational
   :target: https://blog.jaraco.com/skeleton

.. image:: https://tidelift.com/badges/package/pypi/zipp
   :target: https://tidelift.com/subscription/pkg/pypi-zipp?utm_source=pypi-zipp&utm_medium=readme

A pathlib-compatible Zipfile object wrapper. Official backport of the standard library
`Path object <https://docs.python.org/3.8/library/zipfile.html#path-objects>`_.

Compatibility
=============

New features are introduced in this third-party library and later merged
into CPython. The following table indicates which versions of this library
were contributed to different versions in the standard library:

.. list-table::
   :header-rows: 1

   * - zipp
     - stdlib
   * - 3.9
     - 3.12
   * - 3.5
     - 3.11
   * - 3.3
     - 3.9
   * - 1.0
     - 3.8

Usage
=====

Use ``zipp.Path`` in place of ``zipfile.Path`` on any Python.

For Enterprise
==============

Available as part of the Tidelift Subscription.

This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.

`Learn more <https://tidelift.com/subscription/pkg/pypi-zipp?utm_source=pypi-zipp&utm_medium=referral&utm_campaign=github>`_.

Security Contact
================

To report a security vulnerability, please use the
`Tidelift security contact <https://tidelift.com/security>`_.
Tidelift will coordinate the fix and disclosure.


text:
package de.businesscode.bcdui.web.i18n;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.ListResourceBundle;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import de.businesscode.bcdui.binding.BindingSet;
import de.businesscode.bcdui.binding.Bindings;
import de.businesscode.bcdui.toolbox.Configuration;
import de.businesscode.sqlengine.SQLEngine;
import de.businesscode.util.Utils;
import de.businesscode.util.jdbc.Closer;

public class I18nDbResources extends ListResourceBundle {
  public static final String BCDUI_LANG_VAR_NAME = "bcdui.lang";
  public static final String BCDUI_DECIMAL_SEPARATOR = "bcdui.dec.sep";
  public static final String BCDUI_GROUPING_SEPARATOR = "bcdui.group.sep";
  public static final String BCDUI_DATE_PATTERN = "bcdui.date.pattern";
  public static final String BCDUI_DATETIME_PATTERN = "bcdui.datetime.pattern";
  public static final String BCDUI_XSLT_DATE_PATTERN = "bcdui.xslt.date.pattern";
  public static final String BCDUI_XSLT_DATETIME_PATTERN = "bcdui.xslt.datetime.pattern";
  public static final String BCDUI_DATE_SEPARATOR = "bcdui.date.separator";

  private static final String SESSION_KEY_CONTENTS = I18nDbResources.class.getName();

  private Locale lang;
  private Logger logger;
  private Connection con;
  private String decimalSeparator;
  private String groupSeparator;
  private String datePattern;
  private String dateTimePattern;
  private String xsltDatePattern;
  private String xsltDateTimePattern;
  private String dateSeparator;
  private ResourceBundle messagesBundle;
  private HttpSession session;

  private static final String selectFileSQL=
      " #set( $k = $bindings.bcd_i18n ) "+
      " SELECT" +
      "   $k.key-" +
      " , $k.value-" +
      " FROM $k.getPlainTableName()" +
      " WHERE $k.lang- = ?" +
      " UNION" +
      " SELECT" +
      "   $k.key-" +
      " , $k.value-" +
      " FROM $k.getPlainTableName() v2" +
      " WHERE $k.lang- = 'default'" +
      " AND $k.key- NOT IN (SELECT $k.key- FROM $k.getPlainTableName() WHERE $k.key- = v2.$k.key- and $k.lang- = ?)";

  /**
   * I18nDbResources
   */
  public I18nDbResources(HttpSession session, Connection con) {
    this.session = session;

    this.lang = (Locale) session.getAttribute(I18nDbResources.BCDUI_LANG_VAR_NAME);
    this.decimalSeparator = (String) session.getAttribute(I18nDbResources.BCDUI_DECIMAL_SEPARATOR);
    this.groupSeparator = (String) session.getAttribute(I18nDbResources.BCDUI_GROUPING_SEPARATOR);

    this.datePattern = (String) session.getAttribute(I18nDbResources.BCDUI_DATE_PATTERN);
    this.dateSeparator = (String) session.getAttribute(I18nDbResources.BCDUI_DATE_SEPARATOR);
    this.xsltDatePattern = (String) session.getAttribute(I18nDbResources.BCDUI_XSLT_DATE_PATTERN);

    this.dateTimePattern = (String) session.getAttribute(I18nDbResources.BCDUI_DATETIME_PATTERN);
    this.xsltDateTimePattern = (String) session.getAttribute(I18nDbResources.BCDUI_XSLT_DATETIME_PATTERN);

    this.logger = LogManager.getLogger(this.getClass());
    this.con = con;
    try {
      this.messagesBundle = ResourceBundle.getBundle("i18n/messages", this.lang, new Control(){
      @Override
      public Locale getFallbackLocale(String baseName, Locale locale) {
        return Locale.ROOT;
      }
    });
    }
    catch (Exception e) {
      this.messagesBundle = null;
    }
  }
  /**
   * @see java.util.ListResourceBundle#getContents()
   */
  @Override
  protected Object[][] getContents() {
    Object[][] con = (Object[][])this.session.getAttribute(SESSION_KEY_CONTENTS);
    if(con == null) {
      con = retrieveContents();
      this.session.setAttribute(SESSION_KEY_CONTENTS, con);
    }

    return con;
  }

  public static Connection getControlConnection() throws Exception{
    BindingSet bs  = Bindings.getInstance().get("bcd_i18n", new ArrayList<String>());
    Connection con = Configuration.getInstance().getManagedConnection(bs.getJdbcResourceName());
    return con;
  }

  public static String getTransformSQL(String sql){
    String fe = new SQLEngine().transform(sql);
    return fe;
  }

  private Object[][] retrieveContents() {

    Map<String, String> map = new HashMap<String, String>();

    Connection connection = null;

    boolean gotBinding = true;
    try {connection = getControlConnection();} catch (Exception ex) {
      gotBinding  = false;
    }

    if (gotBinding) {
      if (lang != null) {
        PreparedStatement stmt = null;
        ResultSet result = null;

        try{

          SimpleDateFormat monthFormat = new SimpleDateFormat("MMM",lang);
          Calendar calendar = Utils.getDefaultCalendar(lang);
          calendar.set(Calendar.DAY_OF_MONTH,1);
          for(int i = 0; i < 12; i++){
            calendar.set(Calendar.MONTH, i);
            map.put("bcdui.month." + (i+1), monthFormat.format(calendar.getTime()));
          }

          String sql = getTransformSQL(selectFileSQL);
          stmt = connection.prepareStatement(sql);

          stmt.setString(1, lang.toString());
          stmt.setString(2, lang.toString());

          result = stmt.executeQuery();

          while (result.next()) {
            map.put(result.getString(1), result.getString(2));
          }
          if (decimalSeparator != null) {
            map.put(I18nDbResources.BCDUI_DECIMAL_SEPARATOR, decimalSeparator);
          }
          if (groupSeparator != null) {
            map.put(I18nDbResources.BCDUI_GROUPING_SEPARATOR, groupSeparator);
          }
          if (datePattern != null) {
            map.put(I18nDbResources.BCDUI_DATE_PATTERN, datePattern);
          }
          if (dateTimePattern != null) {
              map.put(I18nDbResources.BCDUI_DATETIME_PATTERN, dateTimePattern);
          }
          if (dateSeparator != null) {
            map.put(I18nDbResources.BCDUI_DATE_SEPARATOR, dateSeparator);
          }
          if (xsltDatePattern != null) {
            map.put(I18nDbResources.BCDUI_XSLT_DATE_PATTERN, xsltDatePattern);
          }
          if (xsltDateTimePattern != null) {
              map.put(I18nDbResources.BCDUI_XSLT_DATETIME_PATTERN, xsltDateTimePattern);
          }
          else{
            if (datePattern != null && dateSeparator != null){
              map.put(I18nDbResources.BCDUI_XSLT_DATE_PATTERN, datePattern.replace(dateSeparator, ""));
            }
          }
          if (messagesBundle != null) {
            try {
              Enumeration<String> keys = messagesBundle.getKeys();
              while (keys.hasMoreElements()) {
                String nextKey = keys.nextElement();
                map.put(nextKey, messagesBundle.getString(nextKey));
              }
            }
            catch (Exception e) {
              // do nothing
            }
          }
        }
        catch (Exception e) {
          throw new RuntimeException(e);
        }
        finally{
          Closer.closeAllSQLObjects(result, stmt);
        }
      }
      else {
        // debug:
        logger.warn("No language defined!");
      }
    }
    else {
      // debug:
      logger.warn("I18nDbResources table name was not found!");
    }
    // convert to array
    Set<String> keySet = map.keySet();
    String[][] resultArray = new String[keySet.size()][keySet.size()];
    int i = 0;
    for (String str : keySet) {
      resultArray[i][0] = str;
      resultArray[i][1] = map.get(str);
      i++;
    }

    return resultArray;
  }

  @Deprecated
  public Locale getLang() {
    return lang;
  }

  @Deprecated
  public void setLang(Locale lang) {
    this.lang = lang;
  }

  public Locale getLanguage() {
    return lang;
  }

  public void setLanguage(Locale lang) {
    this.lang = lang;
  }

  public Logger getLogger() {
    return logger;
  }

  public void setLogger(Logger logger) {
    this.logger = logger;
  }

  @Deprecated
  public Connection getCon() {
    return con;
  }

  @Deprecated
  public void setCon(Connection con) {
    this.con = con;
  }

  public Connection getConnection() {
    return con;
  }

  public void setConnection(Connection con) {
    this.con = con;
  }

  public String getDecimalSeparator() {
    return decimalSeparator;
  }

  public void setDecimalSeparator(String decimalSeparator) {
    this.decimalSeparator = decimalSeparator;
  }

  public String getGroupSeparator() {
    return groupSeparator;
  }

  public void setGroupSeparator(String groupSeparator) {
    this.groupSeparator = groupSeparator;
  }

  public String getDatePattern() {
    return datePattern;
  }

  public void setDatePattern(String datePattern) {
    this.datePattern = datePattern;
  }

  public String getDateTimePattern() {
    return dateTimePattern;
  }

  public void setDateTimePattern(String dateTimePattern) {
    this.dateTimePattern = dateTimePattern;
  }

  public String getXsltDatePattern() {
    return xsltDatePattern;
  }

  public void setXsltDatePattern(String xsltDatePattern) {
    this.xsltDatePattern = xsltDatePattern;
  }

  public String getXsltDateTimePattern() {
    return xsltDateTimePattern;
  }

  public void setXsltDateTimePattern(String xsltDateTimePattern) {
    this.xsltDateTimePattern = xsltDateTimePattern;
  }

  public String getDateSeparator() {
    return dateSeparator;
  }

  public void setDateSeparator(String dateSeparator) {
    this.dateSeparator = dateSeparator;
  }

  public ResourceBundle getMessagesBundle() {
    return messagesBundle;
  }

  public void setMessagesBundle(ResourceBundle messagesBundle) {
    this.messagesBundle = messagesBundle;
  }

}


text:
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE TupleSections #-}
{- sv2v
 - Author: Zachary Snow <zach@zachjs.com>
 -
 - Conversion for `parameter type` in module instantiations
 -}

module Convert.ParamType (convert) where

import Control.Monad.Writer.Strict
import Data.Either (isRight, lefts)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set

import Convert.Traverse
import Language.SystemVerilog.AST

type TypeMap = Map.Map Identifier Type
type Modules = Map.Map Identifier TypeMap

type Instance = Map.Map Identifier (Type, IdentSet)
type Instances = Map.Map String (Identifier, Instance)

type IdentSet = Set.Set Identifier
type DeclMap = Map.Map Identifier Decl
type UsageMap = [(Identifier, Set.Set Identifier)]

convert :: [AST] -> [AST]
convert files =
    files'''
    where
        modules = execWriter $
            mapM (collectDescriptionsM collectDescriptionM) files
        (files', instancesRaw) =
            runWriter $ mapM (mapM convertDescriptionM) files
        instances = Map.elems instancesRaw

        -- add type parameter instantiations
        files'' = map (concatMap explodeDescription) files'
        explodeDescription :: Description -> [Description]
        explodeDescription part@(Part _ _ _ _ name _ _) =
            (part :) $
            filter (not . alreadyExists) $
            map (rewriteModule part) theseInstances
            where
                theseInstances = map snd $ filter ((== name) . fst) instances
                alreadyExists = flip Map.member modules . moduleName
                moduleName :: Description -> Identifier
                moduleName = \(Part _ _ _ _ x _ _) -> x
        explodeDescription other = [other]

        -- remove or reduce source modules that are no longer needed
        files''' = map (map reduceTypeDefaults . filter keepDescription) files''
        -- produce a typed and untyped instantiation graph
        (usedUntypedModules, usedTypedModules) =
            both (Map.fromListWith Set.union) $
            execWriter $ mapM (mapM collectUsageM) files''
        collectUsageM :: Description -> Writer (UsageMap, UsageMap) ()
        collectUsageM part@(Part _ _ _ _ name _ _) =
            tell $ both makeList $ execWriter $
                (collectModuleItemsM collectModuleItemM) part
            where makeList s = zip (Set.toList s) (repeat $ Set.singleton name)
        collectUsageM _ = return ()
        collectModuleItemM :: ModuleItem -> Writer (IdentSet, IdentSet) ()
        collectModuleItemM (Instance m bindings _ _ _) =
            if all (isRight . snd) bindings
                then tell (Set.singleton m, Set.empty)
                else tell (Set.empty, Set.singleton m)
        collectModuleItemM _ = return ()
        both f (x, y) = (f x, f y) -- simple tuple map helper

        -- identify if a module is still in use
        keepDescription :: Description -> Bool
        keepDescription (Part _ _ _ _ name _ _) =
            isNewModule
            || isntTyped
            || isUsedAsUntyped
            || isUsedAsTyped && isInstantiatedViaNonTyped
            || allTypesHaveDefaults && notInstantiated && isntTemplateTagged
            where
                maybeTypeMap = Map.lookup name modules
                Just typeMap = maybeTypeMap
                isNewModule = maybeTypeMap == Nothing
                isntTyped = Map.null typeMap
                isUsedAsTyped = Map.member name usedTypedModules
                isUsedAsUntyped = Map.member name usedUntypedModules
                isInstantiatedViaNonTyped = untypedUsageSearch $ Set.singleton name
                allTypesHaveDefaults = all (/= UnknownType) (Map.elems typeMap)
                notInstantiated = lookup name instances == Nothing
                isntTemplateTagged = not $ isTemplateTagged name
        keepDescription _ = True

        -- instantiate the type parameters if this is a used default instance
        reduceTypeDefaults :: Description -> Description
        reduceTypeDefaults part@(Part _ _ _ _ name _ _) =
            if shouldntReduce
                then part
                else traverseModuleItems (traverseDecls rewriteDecl) part
            where
                shouldntReduce =
                    Map.notMember name modules || Map.null typeMap ||
                    any (== UnknownType) (Map.elems typeMap) ||
                    isTemplateTagged name
                typeMap = modules Map.! name
                rewriteDecl :: Decl -> Decl
                rewriteDecl (ParamType Parameter x t) =
                    ParamType Localparam x t
                rewriteDecl other = other
        reduceTypeDefaults other = other

        -- modules can be recursive; this checks if a typed module is not
        -- connected to any modules which are themselves used as typed modules
        untypedUsageSearch :: IdentSet -> Bool
        untypedUsageSearch visited =
            any (flip Map.notMember usedTypedModules) visited
            || Set.size visited /= Set.size visited'
                && untypedUsageSearch visited'
            where
                visited' =
                    Set.union visited $
                    Set.unions $
                    Set.map expandSet visited
                expandSet :: Identifier -> IdentSet
                expandSet ident =
                    Map.findWithDefault Set.empty ident usedTypedModules

        -- substitute in a particular instance's parameter types
        rewriteModule :: Description -> Instance -> Description
        rewriteModule part inst =
            Part attrs extern kw ml m' p (additionalParamItems ++ items')
            where
                Part attrs extern kw ml m p items = part
                m' = moduleInstanceName m inst
                items' = map rewriteModuleItem items
                rewriteModuleItem = traverseNestedModuleItems $ traverseNodes
                    rewriteExpr rewriteDecl rewriteType rewriteLHS rewriteStmt
                rewriteDecl :: Decl -> Decl
                rewriteDecl (ParamType Parameter x t) =
                    ParamType kind x $ rewriteType $
                    case Map.lookup x inst of
                        Nothing -> t
                        Just (t', _) -> t'
                    where kind = if Map.null inst
                                    then Parameter
                                    else Localparam
                rewriteDecl other =
                    traverseDeclNodes rewriteType rewriteExpr other
                additionalParamItems = concatMap makeAddedParams $
                    Map.toList $ Map.map snd inst
                rewriteExpr :: Expr -> Expr
                rewriteExpr orig@(Dot (Ident x) y) =
                    if x == m
                        then Dot (Ident m') y
                        else orig
                rewriteExpr other =
                    traverseExprTypes rewriteType $
                    traverseSinglyNestedExprs rewriteExpr other
                rewriteLHS :: LHS -> LHS
                rewriteLHS orig@(LHSDot (LHSIdent x) y) =
                    if x == m
                        then LHSDot (LHSIdent m') y
                        else orig
                rewriteLHS other =
                    traverseLHSExprs rewriteExpr $
                    traverseSinglyNestedLHSs rewriteLHS other
                rewriteType :: Type -> Type
                rewriteType =
                    traverseTypeExprs rewriteExpr .
                    traverseSinglyNestedTypes rewriteType
                rewriteStmt :: Stmt -> Stmt
                rewriteStmt =
                    traverseStmtLHSs rewriteLHS .
                    traverseStmtExprs rewriteExpr .
                    traverseSinglyNestedStmts rewriteStmt

        makeAddedParams :: (Identifier, IdentSet) -> [ModuleItem]
        makeAddedParams (paramName, identSet) =
            map (MIPackageItem . Decl) $
            map toTypeParam idents ++ map toParam idents
            where
                idents = Set.toList identSet
                toParam :: Identifier -> Decl
                toParam ident =
                    Param Parameter typ name (RawNum 0)
                    where
                        typ = Alias (addedParamTypeName paramName ident) []
                        name = addedParamName paramName ident
                toTypeParam :: Identifier -> Decl
                toTypeParam ident = ParamType Parameter name UnknownType
                    where name = addedParamTypeName paramName ident

-- write down module parameter names and type parameters
collectDescriptionM :: Description -> Writer Modules ()
collectDescriptionM part@(Part _ _ _ _ name _ _) =
    tell $ Map.singleton name typeMap
    where
        typeMap = Map.fromList $ execWriter $
            collectModuleItemsM (collectDeclsM collectDeclM) part
        collectDeclM :: Decl -> Writer [(Identifier, Type)] ()
        collectDeclM (ParamType Parameter x v) = tell [(x, v)]
        collectDeclM _ = return ()
collectDescriptionM _ = return ()

-- generate a "unique" name for a particular module type instance
moduleInstanceName :: Identifier -> Instance -> Identifier
moduleInstanceName (TemplateTag m) inst =
    moduleInstanceName m inst
moduleInstanceName m inst =
    if Map.null inst
        then TemplateTag m
        else m ++ "_" ++ shortHash (m, inst)

-- used to tag modules created for delayed type parameter instantiation
pattern TemplateTag :: Identifier -> Identifier
pattern TemplateTag x = '~' : x
isTemplateTagged :: Identifier -> Bool
isTemplateTagged TemplateTag{} = True
isTemplateTagged _ = False

-- checks where a type is sufficiently resolved to be substituted
isSimpleType :: Type -> Bool
isSimpleType typ =
    (not $ typeIsUnresolved typ) &&
    case typ of
        IntegerVector{} -> True
        IntegerAtom  {} -> True
        NonInteger   {} -> True
        Implicit     {} -> True
        Struct _ fields _ -> all (isSimpleType . fst) fields
        Union  _ fields _ -> all (isSimpleType . fst) fields
        _ -> False

-- returns whether a top-level type contains any dimension queries or
-- hierarchical references
typeIsUnresolved :: Type -> Bool
typeIsUnresolved =
    getAny . execWriter . collectTypeExprsM
    (collectNestedExprsM collectUnresolvedExprM)
    where
        collectUnresolvedExprM :: Expr -> Writer Any ()
        collectUnresolvedExprM DimsFn {} = tell $ Any True
        collectUnresolvedExprM DimFn  {} = tell $ Any True
        collectUnresolvedExprM Dot    {} = tell $ Any True
        collectUnresolvedExprM _ = return ()

prepareTypeExprs :: Identifier -> Identifier -> Type -> (Type, (IdentSet, DeclMap))
prepareTypeExprs instanceName paramName =
    runWriter . traverseNestedTypesM
        (traverseTypeExprsM $ traverseNestedExprsM prepareExpr)
    where
        prepareExpr :: Expr -> Writer (IdentSet, DeclMap) Expr
        prepareExpr e@Call{} = do
            tell (Set.empty, Map.singleton x decl)
            prepareExpr $ Ident x
            where
                decl = Param Localparam (TypeOf e) x e
                x = instanceName ++ "_sv2v_pfunc_" ++ shortHash e
        prepareExpr (Ident x) = do
            tell (Set.singleton x, Map.empty)
            return $ Ident $ paramName ++ '_' : x
        prepareExpr other = return other

addedParamName :: Identifier -> Identifier -> Identifier
addedParamName paramName var = paramName ++ '_' : var

addedParamTypeName :: Identifier -> Identifier -> Identifier
addedParamTypeName paramName var = paramName ++ '_' : var ++ "_type"

convertDescriptionM :: Description -> Writer Instances Description
convertDescriptionM (Part attrs extern kw liftetime name ports items) =
    mapM convertModuleItemM items >>=
        return . Part attrs extern kw liftetime name ports
convertDescriptionM other = return other

convertGenItemM :: GenItem -> Writer Instances GenItem
convertGenItemM (GenModuleItem item) =
    convertModuleItemM item >>= return . GenModuleItem
convertGenItemM other =
    traverseSinglyNestedGenItemsM convertGenItemM other

-- attempt to rewrite instantiations with type parameters
convertModuleItemM :: ModuleItem -> Writer Instances ModuleItem
convertModuleItemM orig@(Instance m bindings x r p) =
    if hasOnlyExprs then
        return orig
    else if not hasUnresolvedTypes then do
        let m' = moduleInstanceName m resolvedTypes
        tell $ Map.singleton m' (m, resolvedTypes)
        return $ Generate $ map GenModuleItem $
            map (MIPackageItem . Decl) addedDecls ++
            [Instance m' (additionalBindings ++ exprBindings) x r p]
    else if isTemplateTagged m then
        return orig
    else do
        let m' = TemplateTag m
        tell $ Map.singleton m' (m, Map.empty)
        return $ Instance m' bindings x r p
    where
        hasOnlyExprs = all (isRight . snd) bindings
        hasUnresolvedTypes = any (not . isSimpleType) (lefts $ map snd bindings)

        -- determine the types corresponding to each type parameter
        bindingsMap = Map.fromList bindings
        resolvedTypesWithDecls = Map.mapMaybeWithKey resolveType bindingsMap
        resolvedTypes = Map.map (\(a, (b, _)) -> (a, b)) resolvedTypesWithDecls
        addedDecls = Map.elems $ Map.unions $ map (snd . snd) $
            Map.elems resolvedTypesWithDecls
        resolveType :: Identifier -> TypeOrExpr -> Maybe (Type, (IdentSet, DeclMap))
        resolveType _ Right{} = Nothing
        resolveType paramName (Left t) =
            Just $ prepareTypeExprs x paramName t

        -- leave only the normal expression params behind
        exprBindings = filter (isRight . snd) bindings

        -- create additional parameters needed to specify existing type params
        additionalBindings = concatMap makeAddedParams $
            Map.toList $ Map.map snd resolvedTypes
        makeAddedParams :: (Identifier, IdentSet) -> [ParamBinding]
        makeAddedParams (paramName, identSet) =
            map toTypeParam idents ++ map toParam idents
            where
                idents = Set.toList identSet
                toParam :: Identifier -> ParamBinding
                toParam ident =
                    (addedParamName paramName ident, Right $ Ident ident)
                toTypeParam :: Identifier -> ParamBinding
                toTypeParam ident =
                    (addedParamTypeName paramName ident, Left $ TypeOf $ Ident ident)

convertModuleItemM (Generate items) =
    mapM convertGenItemM items >>= return . Generate
convertModuleItemM (MIAttr attr item) =
    convertModuleItemM item >>= return . MIAttr attr
convertModuleItemM other = return other


text:
use crate::errors::*;
use crate::proto;
use std::collections::HashMap;
use std::io::Read;

pub trait DataProvider: Send + Sync {
    fn meta_proto(&self) -> Result<proto::Meta>;
    fn data(
        &self,
        node_id: &str,
        node_attributes: &[&str],
    ) -> Result<HashMap<String, Box<dyn Read + Send>>>;
}


text:
$.components.register("clockpicker", {
  mode: "default",
  defaults: {
    donetext: "Done"
  }
});


text:
"""
h2/frame_buffer
~~~~~~~~~~~~~~~

A data structure that provides a way to iterate over a byte buffer in terms of
frames.
"""
from hyperframe.exceptions import UnknownFrameError, InvalidFrameError
from hyperframe.frame import (
    Frame, HeadersFrame, ContinuationFrame, PushPromiseFrame
)

from .exceptions import (
    ProtocolError, FrameTooLargeError, FrameDataMissingError
)

# To avoid a DOS attack based on sending loads of continuation frames, we limit
# the maximum number we're perpared to receive. In this case, we'll set the
# limit to 64, which means the largest encoded header block we can receive by
# default is 262144 bytes long, and the largest possible *at all* is 1073741760
# bytes long.
#
# This value seems reasonable for now, but in future we may want to evaluate
# making it configurable.
CONTINUATION_BACKLOG = 64

class FrameBuffer(object):
    """
    This is a data structure that expects to act as a buffer for HTTP/2 data
    that allows iteraton in terms of H2 frames.
    """
    def __init__(self, server=False):
        self.data = b''
        self.max_frame_size = 0
        self._preamble = b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n' if server else b''
        self._preamble_len = len(self._preamble)
        self._headers_buffer = []

    def add_data(self, data):
        """
        Add more data to the frame buffer.

        :param data: A bytestring containing the byte buffer.
        """
        if self._preamble_len:
            data_len = len(data)
            of_which_preamble = min(self._preamble_len, data_len)

            if self._preamble[:of_which_preamble] != data[:of_which_preamble]:
                raise ProtocolError("Invalid HTTP/2 preamble.")

            data = data[of_which_preamble:]
            self._preamble_len -= of_which_preamble
            self._preamble = self._preamble[of_which_preamble:]

        self.data += data

    def _parse_frame_header(self, data):
        """
        Parses the frame header from the data. Either returns a tuple of
        (frame, length), or throws an exception. The returned frame may be None
        if the frame is of unknown type.
        """
        try:
            frame, length = Frame.parse_frame_header(data[:9])
        except UnknownFrameError as e:
            # Here we do something a bit odd. We want to consume the frame data
            # as consistently as possible, but we also don't ever want to yield
            # None. Instead, we make sure that, if there is no frame, we
            # recurse into ourselves.
            length = e.length
            frame = None
        except ValueError as e:
            # The frame header is invalid. This is a ProtocolError
            raise ProtocolError("Invalid frame header received: %s" % str(e))

        return frame, length

    def _validate_frame_length(self, length):
        """
        Confirm that the frame is an appropriate length.
        """
        if length > self.max_frame_size:
            raise FrameTooLargeError(
                "Received overlong frame: length %d, max %d" %
                (length, self.max_frame_size)
            )

    def _update_header_buffer(self, f):
        """
        Updates the internal header buffer. Returns a frame that should replace
        the current one. May throw exceptions if this frame is invalid.
        """
        # Check if we're in the middle of a headers block. If we are, this
        # frame *must* be a CONTINUATION frame with the same stream ID as the
        # leading HEADERS or PUSH_PROMISE frame. Anything else is a
        # ProtocolError. If the frame *is* valid, append it to the header
        # buffer.
        if self._headers_buffer:
            stream_id = self._headers_buffer[0].stream_id
            valid_frame = (
                f is not None and
                isinstance(f, ContinuationFrame) and
                f.stream_id == stream_id
            )
            if not valid_frame:
                raise ProtocolError("Invalid frame during header block.")

            # Append the frame to the buffer.
            self._headers_buffer.append(f)
            if len(self._headers_buffer) > CONTINUATION_BACKLOG:
                raise ProtocolError("Too many continuation frames received.")

            # If this is the end of the header block, then we want to build a
            # mutant HEADERS frame that's massive. Use the original one we got,
            # then set END_HEADERS and set its data appopriately. If it's not
            # the end of the block, lose the current frame: we can't yield it.
            if 'END_HEADERS' in f.flags:
                f = self._headers_buffer[0]
                f.flags.add('END_HEADERS')
                f.data = b''.join(x.data for x in self._headers_buffer)
                self._headers_buffer = []
            else:
                f = None
        elif (isinstance(f, (HeadersFrame, PushPromiseFrame)) and
                'END_HEADERS' not in f.flags):
            # This is the start of a headers block! Save the frame off and then
            # act like we didn't receive one.
            self._headers_buffer.append(f)
            f = None

        return f

    # The methods below support the iterator protocol.
    def __iter__(self):
        return self

    def next(self):  # Python 2
        # First, check that we have enough data to successfully parse the
        # next frame header. If not, bail. Otherwise, parse it.
        if len(self.data) < 9:
            raise StopIteration()

        try:
            f, length = self._parse_frame_header(self.data)
        except InvalidFrameError:  # pragma: no cover
            raise ProtocolError("Received frame with invalid frame header.")

        # Next, check that we have enough length to parse the frame body. If
        # not, bail, leaving the frame header data in the buffer for next time.
        if len(self.data) < length + 9:
            raise StopIteration()

        # Confirm the frame has an appropriate length.
        self._validate_frame_length(length)

        # Don't try to parse the body if we didn't get a frame we know about:
        # there's nothing we can do with it anyway.
        if f is not None:
            try:
                f.parse_body(memoryview(self.data[9:9+length]))
            except InvalidFrameError:
                raise FrameDataMissingError("Frame data missing or invalid")

        # At this point, as we know we'll use or discard the entire frame, we
        # can update the data.
        self.data = self.data[9+length:]

        # Pass the frame through the header buffer.
        f = self._update_header_buffer(f)

        # If we got a frame we didn't understand or shouldn't yield, rather
        # than return None it'd be better if we just tried to get the next
        # frame in the sequence instead. Recurse back into ourselves to do
        # that. This is safe because the amount of work we have to do here is
        # strictly bounded by the length of the buffer.
        return f if f is not None else self.next()

    def __next__(self):  # Python 3
        return self.next()


text:
package tar

/*
   Utility for working with tar archives.
*/

import (
	"archive/tar"
	"compress/gzip"
	"io"
)

// ReadArchive reads a tar archive from the given io.Reader and runs the given
// callback function for each file in the archive.
func ReadArchive(archive io.Reader, cb func(string, io.Reader) error) error {
	r := tar.NewReader(archive)
	for {
		header, err := r.Next()
		if err == io.EOF {
			return nil
		} else if err != nil {
			return err
		}
		if header.Typeflag == tar.TypeReg {
			if err := cb(header.Name, r); err != nil {
				return err
			}
		}
	}
}

// ReadGzipArchive reads a gzipped tar archive from the given io.Reader and runs
// the given callback function for each file in the archive.
func ReadGzipArchive(archive io.Reader, cb func(string, io.Reader) error) error {
	r, err := gzip.NewReader(archive)
	if err != nil {
		return err
	}
	return ReadArchive(r, cb)
}