text:
.class Lcom/android/server/usage/UsageStatsService$BinderService;
.super Landroid/app/usage/IUsageStatsManager$Stub;
.source "UsageStatsService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/usage/UsageStatsService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "BinderService"
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/usage/UsageStatsService;

# direct methods
.method private constructor <init>(Lcom/android/server/usage/UsageStatsService;)V
    .locals 0

    .prologue
    .line 376
    iput-object p1, p0, Lcom/android/server/usage/UsageStatsService$BinderService;->this$0:Lcom/android/server/usage/UsageStatsService;

    invoke-direct {p0}, Landroid/app/usage/IUsageStatsManager$Stub;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lcom/android/server/usage/UsageStatsService;Lcom/android/server/usage/UsageStatsService$1;)V
    .locals 0
    .param p1, "x0"    # Lcom/android/server/usage/UsageStatsService;
    .param p2, "x1"    # Lcom/android/server/usage/UsageStatsService$1;

    .prologue
    .line 376
    invoke-direct {p0, p1}, Lcom/android/server/usage/UsageStatsService$BinderService;-><init>(Lcom/android/server/usage/UsageStatsService;)V

    return-void
.end method

.method private hasPermission(Ljava/lang/String;)Z
    .locals 6
    .param p1, "callingPackage"    # Ljava/lang/String;

    .prologue
    const/4 v3, 0x0

    const/4 v2, 0x1

    .line 379
    invoke-static {}, Landroid/os/Binder;->getCallingUid()I

    move-result v0

    .line 380
    .local v0, "callingUid":I
    const/16 v4, 0x3e8

    if-ne v0, v4, :cond_1

    .line 391
    :cond_0
    :goto_0
    return v2

    .line 383
    :cond_1
    iget-object v4, p0, Lcom/android/server/usage/UsageStatsService$BinderService;->this$0:Lcom/android/server/usage/UsageStatsService;

    iget-object v4, v4, Lcom/android/server/usage/UsageStatsService;->mAppOps:Landroid/app/AppOpsManager;

    const/16 v5, 0x2b

    invoke-virtual {v4, v5, v0, p1}, Landroid/app/AppOpsManager;->checkOp(IILjava/lang/String;)I

    move-result v1

    .line 385
    .local v1, "mode":I
    const/4 v4, 0x3

    if-ne v1, v4, :cond_2

    .line 388
    iget-object v4, p0, Lcom/android/server/usage/UsageStatsService$BinderService;->this$0:Lcom/android/server/usage/UsageStatsService;

    invoke-virtual {v4}, Lcom/android/server/usage/UsageStatsService;->getContext()Landroid/content/Context;

    move-result-object v4

    const-string v5, "android.permission.PACKAGE_USAGE_STATS"

    invoke-virtual {v4, v5}, Landroid/content/Context;->checkCallingPermission(Ljava/lang/String;)I

    move-result v4

    if-eqz v4, :cond_0

    move v2, v3

    goto :goto_0

    .line 391
    :cond_2
    if-eqz v1, :cond_0

    move v2, v3

    goto :goto_0
.end method

# virtual methods
.method protected dump(Ljava/io/FileDescriptor;Ljava/io/PrintWriter;[Ljava/lang/String;)V
    .locals 2
    .param p1, "fd"    # Ljava/io/FileDescriptor;
    .param p2, "pw"    # Ljava/io/PrintWriter;
    .param p3, "args"    # [Ljava/lang/String;

    .prologue
    .line 454
    iget-object v0, p0, Lcom/android/server/usage/UsageStatsService$BinderService;->this$0:Lcom/android/server/usage/UsageStatsService;

    invoke-virtual {v0}, Lcom/android/server/usage/UsageStatsService;->getContext()Landroid/content/Context;

    move-result-object v0

    const-string v1, "android.permission.DUMP"

    invoke-virtual {v0, v1}, Landroid/content/Context;->checkCallingOrSelfPermission(Ljava/lang/String;)I

    move-result v0

    if-eqz v0, :cond_0

    .line 456
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string v1, "Permission Denial: can\'t dump UsageStats from pid="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-static {}, Landroid/os/Binder;->getCallingPid()I

    move-result v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ", uid="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-static {}, Landroid/os/Binder;->getCallingUid()I

    move-result v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, " without permission "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, "android.permission.DUMP"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {p2, v0}, Ljava/io/PrintWriter;->println(Ljava/lang/String;)V

    .line 462
    :goto_0
    return-void

    .line 461
    :cond_0
    iget-object v0, p0, Lcom/android/server/usage/UsageStatsService$BinderService;->this$0:Lcom/android/server/usage/UsageStatsService;

    invoke-virtual {v0, p3, p2}, Lcom/android/server/usage/UsageStatsService;->dump([Ljava/lang/String;Ljava/io/PrintWriter;)V

    goto :goto_0
.end method

.method public queryConfigurationStats(IJJLjava/lang/String;)Landroid/content/pm/ParceledListSlice;
    .locals 12
    .param p1, "bucketType"    # I
    .param p2, "beginTime"    # J
    .param p4, "endTime"    # J
    .param p6, "callingPackage"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(IJJ",
            "Ljava/lang/String;",
            ")",
            "Landroid/content/pm/ParceledListSlice",
            "<",
            "Landroid/app/usage/ConfigurationStats;",
            ">;"
        }
    .end annotation

    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 418
    move-object/from16 v0, p6

    invoke-direct {p0, v0}, Lcom/android/server/usage/UsageStatsService$BinderService;->hasPermission(Ljava/lang/String;)Z

    move-result v3

    if-nez v3, :cond_0

    .line 419
    const/4 v3, 0x0

    .line 434
    :goto_0
    return-object v3

    .line 422
    :cond_0
    invoke-static {}, Landroid/os/UserHandle;->getCallingUserId()I

    move-result v4

    .line 423
    .local v4, "userId":I
    invoke-static {}, Landroid/os/Binder;->clearCallingIdentity()J

    move-result-wide v10

    .line 425
    .local v10, "token":J
    :try_start_0
    iget-object v3, p0, Lcom/android/server/usage/UsageStatsService$BinderService;->this$0:Lcom/android/server/usage/UsageStatsService;

    move v5, p1

    move-wide v6, p2

    move-wide/from16 v8, p4

    invoke-virtual/range {v3 .. v9}, Lcom/android/server/usage/UsageStatsService;->queryConfigurationStats(IIJJ)Ljava/util/List;

    move-result-object v2

    .line 428
    .local v2, "results":Ljava/util/List;, "Ljava/util/List<Landroid/app/usage/ConfigurationStats;>;"
    if-eqz v2, :cond_1

    .line 429
    new-instance v3, Landroid/content/pm/ParceledListSlice;

    invoke-direct {v3, v2}, Landroid/content/pm/ParceledListSlice;-><init>(Ljava/util/List;)V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 432
    invoke-static {v10, v11}, Landroid/os/Binder;->restoreCallingIdentity(J)V

    goto :goto_0

    :cond_1
    invoke-static {v10, v11}, Landroid/os/Binder;->restoreCallingIdentity(J)V

    .line 434
    const/4 v3, 0x0

    goto :goto_0

    .line 432
    .end local v2    # "results":Ljava/util/List;, "Ljava/util/List<Landroid/app/usage/ConfigurationStats;>;"
    :catchall_0
    move-exception v3

    invoke-static {v10, v11}, Landroid/os/Binder;->restoreCallingIdentity(J)V

    throw v3
.end method

.method public queryEvents(JJLjava/lang/String;)Landroid/app/usage/UsageEvents;
    .locals 9
    .param p1, "beginTime"    # J
    .param p3, "endTime"    # J
    .param p5, "callingPackage"    # Ljava/lang/String;

    .prologue
    .line 439
    invoke-direct {p0, p5}, Lcom/android/server/usage/UsageStatsService$BinderService;->hasPermission(Ljava/lang/String;)Z

    move-result v0

    if-nez v0, :cond_0

    .line 440
    const/4 v0, 0x0

    .line 448
    :goto_0
    return-object v0

    .line 443
    :cond_0
    invoke-static {}, Landroid/os/UserHandle;->getCallingUserId()I

    move-result v1

    .line 444
    .local v1, "userId":I
    invoke-static {}, Landroid/os/Binder;->clearCallingIdentity()J

    move-result-wide v6

    .line 446
    .local v6, "token":J
    :try_start_0
    iget-object v0, p0, Lcom/android/server/usage/UsageStatsService$BinderService;->this$0:Lcom/android/server/usage/UsageStatsService;

    move-wide v2, p1

    move-wide v4, p3

    invoke-virtual/range {v0 .. v5}, Lcom/android/server/usage/UsageStatsService;->queryEvents(IJJ)Landroid/app/usage/UsageEvents;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-object v0

    .line 448
    invoke-static {v6, v7}, Landroid/os/Binder;->restoreCallingIdentity(J)V

    goto :goto_0

    :catchall_0
    move-exception v0

    invoke-static {v6, v7}, Landroid/os/Binder;->restoreCallingIdentity(J)V

    throw v0
.end method

.method public queryUsageStats(IJJLjava/lang/String;)Landroid/content/pm/ParceledListSlice;
    .locals 12
    .param p1, "bucketType"    # I
    .param p2, "beginTime"    # J
    .param p4, "endTime"    # J
    .param p6, "callingPackage"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(IJJ",
            "Ljava/lang/String;",
            ")",
            "Landroid/content/pm/ParceledListSlice",
            "<",
            "Landroid/app/usage/UsageStats;",
            ">;"
        }
    .end annotation

    .prologue
    .line 397
    move-object/from16 v0, p6

    invoke-direct {p0, v0}, Lcom/android/server/usage/UsageStatsService$BinderService;->hasPermission(Ljava/lang/String;)Z

    move-result v3

    if-nez v3, :cond_0

    .line 398
    const/4 v3, 0x0

    .line 412
    :goto_0
    return-object v3

    .line 401
    :cond_0
    invoke-static {}, Landroid/os/UserHandle;->getCallingUserId()I

    move-result v4

    .line 402
    .local v4, "userId":I
    invoke-static {}, Landroid/os/Binder;->clearCallingIdentity()J

    move-result-wide v10

    .line 404
    .local v10, "token":J
    :try_start_0
    iget-object v3, p0, Lcom/android/server/usage/UsageStatsService$BinderService;->this$0:Lcom/android/server/usage/UsageStatsService;

    move v5, p1

    move-wide v6, p2

    move-wide/from16 v8, p4

    invoke-virtual/range {v3 .. v9}, Lcom/android/server/usage/UsageStatsService;->queryUsageStats(IIJJ)Ljava/util/List;

    move-result-object v2

    .line 406
    .local v2, "results":Ljava/util/List;, "Ljava/util/List<Landroid/app/usage/UsageStats;>;"
    if-eqz v2, :cond_1

    .line 407
    new-instance v3, Landroid/content/pm/ParceledListSlice;

    invoke-direct {v3, v2}, Landroid/content/pm/ParceledListSlice;-><init>(Ljava/util/List;)V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 410
    invoke-static {v10, v11}, Landroid/os/Binder;->restoreCallingIdentity(J)V

    goto :goto_0

    :cond_1
    invoke-static {v10, v11}, Landroid/os/Binder;->restoreCallingIdentity(J)V

    .line 412
    const/4 v3, 0x0

    goto :goto_0

    .line 410
    .end local v2    # "results":Ljava/util/List;, "Ljava/util/List<Landroid/app/usage/UsageStats;>;"
    :catchall_0
    move-exception v3

    invoke-static {v10, v11}, Landroid/os/Binder;->restoreCallingIdentity(J)V

    throw v3
.end method


text:
package org.opencds.dss.evaluate;

import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.BindingType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.omg.dss.DSSRuntimeExceptionFault;
import org.omg.dss.EvaluationExceptionFault;
import org.omg.dss.InvalidDriDataFormatExceptionFault;
import org.omg.dss.InvalidTimeZoneOffsetExceptionFault;
import org.omg.dss.ObjectFactory;
import org.omg.dss.RequiredDataNotProvidedExceptionFault;
import org.omg.dss.UnrecognizedLanguageExceptionFault;
import org.omg.dss.UnrecognizedScopedEntityExceptionFault;
import org.omg.dss.UnsupportedLanguageExceptionFault;
import org.omg.dss.common.EntityIdentifier;
import org.omg.dss.common.ItemIdentifier;
import org.omg.dss.common.SemanticPayload;
import org.omg.dss.evaluation.Evaluate;
import org.omg.dss.evaluation.EvaluateAtSpecifiedTime;
import org.omg.dss.evaluation.EvaluateAtSpecifiedTimeResponse;
import org.omg.dss.evaluation.EvaluateIteratively;
import org.omg.dss.evaluation.EvaluateIterativelyAtSpecifiedTime;
import org.omg.dss.evaluation.EvaluateIterativelyAtSpecifiedTimeResponse;
import org.omg.dss.evaluation.EvaluateIterativelyResponse;
import org.omg.dss.evaluation.EvaluateResponse;
import org.omg.dss.evaluation.requestresponse.EvaluationResponse;
import org.omg.dss.evaluation.requestresponse.FinalKMEvaluationResponse;
import org.omg.dss.evaluation.requestresponse.KMEvaluationRequest;
import org.omg.dss.evaluation.requestresponse.KMEvaluationResultData;
import org.opencds.common.config.OpencdsConfigurator;
import org.opencds.common.structures.DSSRequestDataItem;
import org.opencds.common.structures.DSSRequestKMItem;
import org.opencds.common.structures.TimingData;
import org.opencds.common.structures.TimingDataKM;
import org.opencds.common.utilities.DSSUtility;
import org.opencds.common.utilities.DateUtility;
import org.opencds.common.utilities.XMLDateUtility;
import org.opencds.knowledgeRepository.SimpleKnowledgeRepository;
import org.opencds.service.evaluate.OpenCDSMain;

/**
 * EvaluationImpl is the primary endpoint of the SOAP web service.
 *
 * It gets a list of the required KMId to process from OpenCDSMain and loops through the following:
 * 		It gets a new instance of requiredEvaluationEngine for each KMId from EvaluationFactory and executes it
 * 		It gets the evaluationResponse from DSSEvaluationAdapterShell, and stacks it into the FinalEvaluationResponse
 * Finally it returns the FinalEvaluationResponse to the requestor.
 *
 * @author Andrew Iskander, mod by David Shields
 *
 * @version 1.0
 */
@WebService(endpointInterface = "org.omg.dss.Evaluation")
@BindingType(value = "http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/")
@XmlSeeAlso({
    ObjectFactory.class
})

public class EvaluationImpl implements org.omg.dss.Evaluation {

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

//	Date rightNow = new Date();

	/**
	 *
	 * @param date as long
	 * @return XMLGregorianCalendar
	 */
    private static XMLGregorianCalendar long2Gregorian(long date) {
    	DatatypeFactory dataTypeFactory;
    	try {
    	dataTypeFactory = DatatypeFactory.newInstance();
    	} catch (DatatypeConfigurationException e) {
    	throw new RuntimeException(e);
    	}
    	GregorianCalendar gc = new GregorianCalendar();
    	gc.setTimeInMillis(date);
    	return dataTypeFactory.newXMLGregorianCalendar(gc);
    	}

    /**
     *
     * @param date
     * @return XMLGregorianCalendar
     */
    private static XMLGregorianCalendar date2Gregorian(Date date) {
    	return long2Gregorian(date.getTime());
    	}

//    XMLGregorianCalendar rightNowTime = date2Gregorian(rightNow);
    XMLGregorianCalendar rightNowTime = date2Gregorian(new Date());

/* (non-Javadoc)
 * @see org.omg.dss.Evaluation#evaluate(org.omg.dss.evaluation.Evaluate)
 */
@Override
	public EvaluateResponse evaluate(Evaluate parameters)
		throws InvalidDriDataFormatExceptionFault,
			UnrecognizedLanguageExceptionFault,
			RequiredDataNotProvidedExceptionFault,
			UnsupportedLanguageExceptionFault,
			UnrecognizedScopedEntityExceptionFault,
			EvaluationExceptionFault,
			InvalidTimeZoneOffsetExceptionFault,
			DSSRuntimeExceptionFault
	{
		TimingData timingData = new TimingData();
		Date evalTime = new Date();
		log.debug("II: " + parameters.getInteractionId().getInteractionId().toString()
				+ "EvaluationImpl.evaluate started asOf " + DateUtility.getInstance().getDateAsString(evalTime, "yyyyMMdd HHmmss").toString());
		if (!SimpleKnowledgeRepository.isKnowledgeRepositoryInitialized()) {
			SimpleKnowledgeRepository.setFullPathToKRData(OpencdsConfigurator.getInstance().getKrFullPath());
		}

		DSSRequestDataItem dssRequestDataItem = new DSSRequestDataItem();
		dssRequestDataItem.setInteractionId(parameters.getInteractionId().getInteractionId().toString());

		EvaluateResponse evaluateResponse = new EvaluateResponse();
		evaluateResponse.setEvaluationResponse(new EvaluationResponse());

		List<KMEvaluationRequest> listKMERequest = OpenCDSMain.decodeInput(
				parameters.getEvaluationRequest(),
				//XMLDateUtility.xmlGregorian2Date(rightNowTime),
				evalTime,
				dssRequestDataItem,
				timingData);

		for (KMEvaluationRequest oneKMEvaluationRequest : listKMERequest)
		{
			DSSRequestKMItem oneRequest = new DSSRequestKMItem();
			oneRequest.setDssRequestDataItem(dssRequestDataItem);
			oneRequest.setRequestedKmId(DSSUtility.makeEIString(oneKMEvaluationRequest.getKmId()));
			oneRequest.setKmTimingData(new TimingDataKM() );
			initLogTimingsKM(oneRequest.getKmTimingData());

			Evaluater evaluater = EvaluationFactory.createEvaluater(oneRequest);
			String structuredDroolsResult = evaluater.getOneResponse(oneRequest);

			FinalKMEvaluationResponse	fkmResponse				= new FinalKMEvaluationResponse();
	        SemanticPayload 			semanticPayload			= new SemanticPayload();
	        ItemIdentifier 				itemId 					= new ItemIdentifier();
	        KMEvaluationResultData 		kmerData				= new KMEvaluationResultData();
	        List<byte[]> 				base64EncodedPayload	= new ArrayList<byte[]>();

	        try
			{
				log.debug("KMId: " + oneRequest.getRequestedKmId().toString() + " EvaluationImpl.evaluate starting one KM");
				// Quito esta linea para que no se muestre duplicada la informacion de paciente
				// log.trace("" + structuredDroolsResult);
				base64EncodedPayload 	= semanticPayload.getBase64EncodedPayload();
				base64EncodedPayload.add( structuredDroolsResult.getBytes() );

				itemId.setItemId( oneRequest.getDssRequestDataItem().getInputItemName() + ".EvaluationResult" );
				itemId.setContainingEntityId(DSSUtility.makeEI(oneRequest.getDssRequestDataItem().getInputContainingEntityId()));

		        String						kmId					= oneRequest.getRequestedKmId();
				String 						ssIdString				= SimpleKnowledgeRepository.getRequiredSSIdForKMId(kmId);
		        EntityIdentifier 			ssId 					= DSSUtility.makeEI(ssIdString);
		        semanticPayload.setInformationModelSSId(ssId);

		        kmerData.setData(semanticPayload);
		        kmerData.setEvaluationResultId(itemId);

		        fkmResponse.setKmId(DSSUtility.makeEI(oneRequest.getRequestedKmId()));
		        fkmResponse.getKmEvaluationResultData().add( kmerData );

		        oneRequest.getKmTimingData().setFinishInferenceEngineAdapterTime(new AtomicLong(System.nanoTime()));
				log.debug("KMId: " + oneRequest.getRequestedKmId().toString() + " EvaluationImpl.evaluate completed one KM");

			} catch (RuntimeException e) {
				e.printStackTrace();
				throw new DSSRuntimeExceptionFault("RuntimeException in EvaluationImpl.evaluate: " + structuredDroolsResult + e.getMessage());
			}
			evaluateResponse.getEvaluationResponse().getFinalKMEvaluationResponse().add(fkmResponse);

			logTimingsKM(oneRequest);
			oneRequest 				= null;
			structuredDroolsResult 	= null;
			evaluater 				= null;
			fkmResponse				= null;
	        semanticPayload			= null;
	        itemId 					= null;
	        kmerData				= null;
	        base64EncodedPayload	= null;
		}

		timingData.setFinishInferenceEngineLoopTime(new AtomicLong(System.nanoTime()));
		timingData.setFinishMessageRequestTime(new AtomicLong(System.nanoTime()));
		log.info("II: " + parameters.getInteractionId().getInteractionId().toString()
				+ " " + logTimings(timingData) + " EvaluationImpl.evaluate completed");

		timingData = null;
		dssRequestDataItem = null;
		listKMERequest.clear();
		listKMERequest = null;

		return evaluateResponse;
	}

@Override
	public EvaluateAtSpecifiedTimeResponse evaluateAtSpecifiedTime(EvaluateAtSpecifiedTime parameters)
			throws InvalidDriDataFormatExceptionFault,
			UnrecognizedLanguageExceptionFault,
			RequiredDataNotProvidedExceptionFault,
			UnsupportedLanguageExceptionFault,
			UnrecognizedScopedEntityExceptionFault, EvaluationExceptionFault,
			InvalidTimeZoneOffsetExceptionFault,
			DSSRuntimeExceptionFault
	{
		TimingData timingData = new TimingData();
		Date evalTime = XMLDateUtility.xmlGregorian2Date(parameters.getSpecifiedTime());
		log.debug("II: " + parameters.getInteractionId().getInteractionId().toString()
				+ " EvaluationImpl.evaluateAtSpecifiedTime started asOf " + DateUtility.getInstance().getDateAsString(evalTime, "yyyyMMdd HHmmss").toString());
		if (!SimpleKnowledgeRepository.isKnowledgeRepositoryInitialized()) {
			SimpleKnowledgeRepository.setFullPathToKRData(OpencdsConfigurator.getInstance().getKrFullPath());
		}

		DSSRequestDataItem dssRequestDataItem = new DSSRequestDataItem();
		dssRequestDataItem.setInteractionId(parameters.getInteractionId().getInteractionId().toString());

		EvaluateAtSpecifiedTimeResponse evalAtSpecTimeResponse = new EvaluateAtSpecifiedTimeResponse();
		evalAtSpecTimeResponse.setEvaluationResponse(new EvaluationResponse());

		List<KMEvaluationRequest> listKMERequest = OpenCDSMain.decodeInput(
				parameters.getEvaluationRequest(),
				//XMLDateUtility.xmlGregorian2Date(parameters.getSpecifiedTime()),
				evalTime,
				dssRequestDataItem,
				timingData);

		for (KMEvaluationRequest oneKMEvaluationRequest : listKMERequest)
		{
			DSSRequestKMItem oneRequest = new DSSRequestKMItem();
			oneRequest.setDssRequestDataItem(dssRequestDataItem);
			oneRequest.setRequestedKmId(DSSUtility.makeEIString(oneKMEvaluationRequest.getKmId()));
			oneRequest.setKmTimingData(new TimingDataKM() );
			initLogTimingsKM(oneRequest.getKmTimingData());

			Evaluater evaluater = EvaluationFactory.createEvaluater(oneRequest);
			String structuredDroolsResult = evaluater.getOneResponse(oneRequest);

			FinalKMEvaluationResponse	fkmResponse				= new FinalKMEvaluationResponse();
	        SemanticPayload 			semanticPayload			= new SemanticPayload();
	        ItemIdentifier 				itemId 					= new ItemIdentifier();
	        KMEvaluationResultData 		kmerData				= new KMEvaluationResultData();
	        List<byte[]> 				base64EncodedPayload	= new ArrayList<byte[]>();

	        try
			{
				log.debug("KMId: " + oneRequest.getRequestedKmId().toString() + " EvaluationImpl.evaluateAtSpecifiedTime starting one KM");
				log.trace("" + structuredDroolsResult);
				base64EncodedPayload 	= semanticPayload.getBase64EncodedPayload();
				base64EncodedPayload.add( structuredDroolsResult.getBytes() );

				itemId.setItemId( oneRequest.getDssRequestDataItem().getInputItemName() + ".EvaluationResult" );
				itemId.setContainingEntityId(DSSUtility.makeEI(oneRequest.getDssRequestDataItem().getInputContainingEntityId()));

		        String						kmId					= oneRequest.getRequestedKmId();
				String 						ssIdString				= SimpleKnowledgeRepository.getRequiredSSIdForKMId(kmId);
		        EntityIdentifier 			ssId 					= DSSUtility.makeEI(ssIdString);
		        semanticPayload.setInformationModelSSId(ssId);

		        kmerData.setData(semanticPayload);
		        kmerData.setEvaluationResultId(itemId);

		        fkmResponse.setKmId(DSSUtility.makeEI(oneRequest.getRequestedKmId()));
		        fkmResponse.getKmEvaluationResultData().add( kmerData );

		        oneRequest.getKmTimingData().setFinishInferenceEngineAdapterTime(new AtomicLong(System.nanoTime()));
				log.debug("KMId: " + oneRequest.getRequestedKmId().toString() + " EvaluationImpl.evaluateAtSpecifiedTime completed one KM");

			} catch (RuntimeException e) {
				e.printStackTrace();
				throw new DSSRuntimeExceptionFault("RuntimeException in EvaluationImpl.evaluateAtSpecifiedTime: " + structuredDroolsResult + e.getMessage());
			}

			evalAtSpecTimeResponse.getEvaluationResponse().getFinalKMEvaluationResponse().add(fkmResponse);
			evaluater = null;

			logTimingsKM(oneRequest);
			oneRequest 				= null;
			structuredDroolsResult 	= null;
			evaluater 				= null;
			fkmResponse				= null;
	        semanticPayload			= null;
	        itemId 					= null;
	        kmerData				= null;
	        base64EncodedPayload	= null;
		}

		timingData.setFinishInferenceEngineLoopTime(new AtomicLong(System.nanoTime()));
		timingData.setFinishMessageRequestTime(new AtomicLong(System.nanoTime()));
		log.info("II: " + parameters.getInteractionId().getInteractionId().toString()
				+ " " + logTimings(timingData) + " EvaluationImpl.evaluateAtSpecifiedTime completed");

		timingData = null;
		dssRequestDataItem = null;
		listKMERequest.clear();
		listKMERequest = null;

		return evalAtSpecTimeResponse;
	}

@Override
	public EvaluateIterativelyResponse evaluateIteratively(
			EvaluateIteratively parameters)
		throws InvalidDriDataFormatExceptionFault,
			UnrecognizedLanguageExceptionFault,
			RequiredDataNotProvidedExceptionFault,
			UnsupportedLanguageExceptionFault,
			UnrecognizedScopedEntityExceptionFault,
			EvaluationExceptionFault,
			InvalidTimeZoneOffsetExceptionFault,
			DSSRuntimeExceptionFault
	{
		log.debug("started EvaluationImpl.evaluateIteratively");
		IterativeEvaluater evaluater = EvaluationFactory.createIterativeEvaluater(parameters.getIterativeEvaluationRequest());
		EvaluateIterativelyResponse er = new EvaluateIterativelyResponse();
		er.setIterativeEvaluationResponse( evaluater.getResponse(parameters.getInteractionId(), rightNowTime, parameters.getIterativeEvaluationRequest()) );
		log.debug("completed EvaluationImpl.evaluateIteratively");
		return er;
	}

@Override
	public EvaluateIterativelyAtSpecifiedTimeResponse evaluateIterativelyAtSpecifiedTime(
			EvaluateIterativelyAtSpecifiedTime parameters)
		throws InvalidDriDataFormatExceptionFault,
			UnrecognizedLanguageExceptionFault,
			RequiredDataNotProvidedExceptionFault,
			UnsupportedLanguageExceptionFault,
			UnrecognizedScopedEntityExceptionFault,
			EvaluationExceptionFault,
			InvalidTimeZoneOffsetExceptionFault,
			DSSRuntimeExceptionFault
	{
		log.debug("started EvaluationImpl.evaluateIterativelyAtSpecifiedTime");
		IterativeEvaluater evaluater = EvaluationFactory.createIterativeEvaluater(parameters.getIterativeEvaluationRequest());
		EvaluateIterativelyAtSpecifiedTimeResponse er = new EvaluateIterativelyAtSpecifiedTimeResponse();
		er.setIterativeEvaluationResponse( evaluater.getResponse(parameters.getInteractionId(), parameters.getSpecifiedTime(), parameters.getIterativeEvaluationRequest()) );
		log.debug("completed EvaluationImpl.evaluateIterativelyAtSpecifiedTime");
		return er;
	}

/**
 * initLogTimingsKM -- clears the timing values
 *
 * @param timingDataKM
 */
private synchronized static void initLogTimingsKM(TimingDataKM timingDataKM)
	{
		timingDataKM.setStartInferenceEngineAdapterTime(new AtomicLong(System.nanoTime()));
		timingDataKM.setFinishBuildFactListsTime(new AtomicLong(0));
		timingDataKM.setFinishBuildConceptListsTime(new AtomicLong(0));
		timingDataKM.setFinishInsertKnowledgeTime(new AtomicLong(0));
		timingDataKM.setFinishStartKnowledgeSessionTime(new AtomicLong(0));
		timingDataKM.setFinishLoadGlobalsTime(new AtomicLong(0));
		timingDataKM.setFinishLoadFactListsTime(new AtomicLong(0));
		timingDataKM.setStartInferenceEngine(new AtomicLong(0));
		timingDataKM.setFinishInferenceEngine(new AtomicLong(0));
		timingDataKM.setFinishBuildOutputTime(new AtomicLong(0));
		timingDataKM.setFinishMarshalTime(new AtomicLong(0));
		timingDataKM.setFinishInferenceEngineAdapterTime(new AtomicLong(0));
	}

/**
 * logTimingsKM -- logs the timings for one KM, and returns a summary to the caller,
 * 				which can be logged at a different level than the detailed logs
 *
 * @param timingDataKM
 * @return String
 */
private synchronized static String logTimingsKM(DSSRequestKMItem oneRequest)
	{
		TimingDataKM timingDataKM	= oneRequest.getKmTimingData();
		long buildFactsTime			= timingDataKM.getFinishBuildFactListsTime().get() 			- timingDataKM.getStartInferenceEngineAdapterTime().get();
		long buildConceptsTime		= timingDataKM.getFinishBuildConceptListsTime().get()		- timingDataKM.getFinishBuildFactListsTime().get();
		long knowledgeInsertTime	= timingDataKM.getFinishInsertKnowledgeTime().get() 		- timingDataKM.getFinishBuildConceptListsTime().get();
		long startSessionTime		= timingDataKM.getFinishStartKnowledgeSessionTime().get() 	- timingDataKM.getFinishInsertKnowledgeTime().get();
		long loadGlobalsTime		= timingDataKM.getFinishLoadGlobalsTime().get() 			- timingDataKM.getFinishStartKnowledgeSessionTime().get();
		long loadFactListsTime		= timingDataKM.getFinishLoadFactListsTime().get() 			- timingDataKM.getFinishLoadGlobalsTime().get();
		long startProcessTime		= timingDataKM.getStartInferenceEngine().get() 				- timingDataKM.getFinishLoadFactListsTime().get();
		long evaluationTime			= timingDataKM.getFinishInferenceEngine().get() 			- timingDataKM.getStartInferenceEngine().get();
		long buildOutputTime		= timingDataKM.getFinishBuildOutputTime().get() 			- timingDataKM.getFinishInferenceEngine().get();
		long marshalTime			= timingDataKM.getFinishMarshalTime().get() 				- timingDataKM.getFinishBuildOutputTime().get();
		long finishKMTime			= timingDataKM.getFinishInferenceEngineAdapterTime().get() 	- timingDataKM.getFinishMarshalTime().get();

		long evaluationAdapterTime	= timingDataKM.getFinishInferenceEngineAdapterTime().get()	- timingDataKM.getStartInferenceEngineAdapterTime().get();
		long totalPrepTime			= timingDataKM.getStartInferenceEngine().get() 				- timingDataKM.getStartInferenceEngineAdapterTime().get();
		long totalOutputTime		= timingDataKM.getFinishInferenceEngineAdapterTime().get() 	- timingDataKM.getFinishInferenceEngine().get();

	    String prepTimings = "km prep: " 	+ totalPrepTime / 1000000   + " ms."
				  + " + facts=" + buildFactsTime / 1000000
				  + " + cncpts=" + buildConceptsTime / 1000000
				  + " + (knowledgeInsert=" + knowledgeInsertTime / 1000000
				  + " + startSession=" + startSessionTime / 1000000
				  + " + loadGlobals=" + loadGlobalsTime / 1000000
				  + " + loadFactLists=" + loadFactListsTime / 1000000
				  + " + startProcess=" + startProcessTime / 1000000
				  + ")";
		String droolsTimings = "km eval: " + evaluationTime / 1000000 + " ms.";
		String postTimings = "km post eval: " 	+ totalOutputTime / 1000000 + " ms. = ("
				  + "output=" + buildOutputTime / 1000000
				  + " + mrshl=" + marshalTime / 1000000
				  + " + KMPost=" + finishKMTime / 1000000
				  + ")";
		String kmTimings = " KMId: " + oneRequest.getRequestedKmId()
						+ " priProc: " + oneRequest.getRequestedKmPrimaryProcessName()
						+ " eval total: " + evaluationAdapterTime / 1000000 + " ms.";
		log.debug(prepTimings);
		log.debug(droolsTimings);
		log.debug(postTimings);
		return kmTimings;
	}

/**
 * logTimings -- logs the detailed timings about one message, and passes a summary
 * 				back which can be logged at a different level
 *
 * @param timingData
 * @return String summary timings
 */
private synchronized static String logTimings(TimingData timingData)
	{

		long startKMTime		= timingData.getStartUnmarshalTime().get() 			- timingData.getStartMessageRequestTime().get();
		long unmarshalTime		= timingData.getStartInferenceEngineLoopTime().get()- timingData.getStartUnmarshalTime().get();
		long totalPrepTime		= timingData.getStartInferenceEngineLoopTime().get()	- timingData.getStartMessageRequestTime().get();
		long evaluationTime		= timingData.getFinishInferenceEngineLoopTime().get()	- timingData.getStartInferenceEngineLoopTime().get();
		long totalOutputTime	= timingData.getFinishMessageRequestTime().get() 		- timingData.getFinishInferenceEngineLoopTime().get();

	    String prepTimings = "msg prep: " 	+ totalPrepTime / 1000000   + " ms. = (KMPrep=" + startKMTime / 1000000
	    												  + " + unMrshl=" + unmarshalTime / 1000000
	    												  + ") ";
	    String droolsTimings = "msg eval: " 	+ evaluationTime / 1000000 + " ms. ";
	    String postTimings = "msg out: " 	+ totalOutputTime / 1000000 + " ms. ";
		log.debug(prepTimings);
		log.debug(droolsTimings);
		log.debug(postTimings);

		long totalMessageTime		= timingData.getFinishMessageRequestTime().get() 		- timingData.getStartMessageRequestTime().get();

	    String totalTiming = ", msg total time: " + totalMessageTime / 1000000 + " ms. (" + prepTimings + droolsTimings + postTimings + ")";

	    return totalTiming;
	}
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef ChromeClient_h
#define ChromeClient_h

#include "AXObjectCache.h"
#include "Cursor.h"
#include "DisplayRefreshMonitor.h"
#include "FocusDirection.h"
#include "FrameLoader.h"
#include "GraphicsContext.h"
#include "HostWindow.h"
#include "LayerFlushThrottleState.h"
#include "PopupMenu.h"
#include "PopupMenuClient.h"
#include "RenderEmbeddedObject.h"
#include "ScrollTypes.h"
#include "ScrollingCoordinator.h"
#include "SearchPopupMenu.h"
#include "WebCoreKeyboardUIMode.h"
#include <runtime/ConsoleTypes.h>
#include <wtf/Forward.h>
#include <wtf/PassOwnPtr.h>
#include <wtf/Vector.h>

#if PLATFORM(IOS)
#include "PlatformLayer.h"
#define NSResponder WAKResponder
#ifndef __OBJC__
class WAKResponder;
#else
@class WAKResponder;
#endif
#endif

#if ENABLE(SQL_DATABASE)
#include "DatabaseDetails.h"
#endif

OBJC_CLASS NSResponder;

namespace WebCore {

class AccessibilityObject;
class ColorChooser;
class ColorChooserClient;
class DateTimeChooser;
class DateTimeChooserClient;
class Element;
class FileChooser;
class FileIconLoader;
class FloatRect;
class Frame;
class Geolocation;
class GraphicsContext3D;
class GraphicsLayer;
class GraphicsLayerFactory;
class HTMLInputElement;
class HitTestResult;
class IntRect;
class NavigationAction;
class Node;
class Page;
class PopupMenuClient;
class SecurityOrigin;
class ViewportConstraints;
class Widget;

struct DateTimeChooserParameters;
struct FrameLoadRequest;
struct GraphicsDeviceAdapter;
struct ViewportArguments;
struct WindowFeatures;

class ChromeClient {
public:
    virtual void chromeDestroyed() = 0;

    virtual void setWindowRect(const FloatRect&) = 0;
    virtual FloatRect windowRect() = 0;

    virtual FloatRect pageRect() = 0;

    virtual void focus() = 0;
    virtual void unfocus() = 0;

    virtual bool canTakeFocus(FocusDirection) = 0;
    virtual void takeFocus(FocusDirection) = 0;

    virtual void focusedElementChanged(Element*) = 0;
    virtual void focusedFrameChanged(Frame*) = 0;

    // The Frame pointer provides the ChromeClient with context about which
    // Frame wants to create the new Page. Also, the newly created window
    // should not be shown to the user until the ChromeClient of the newly
    // created Page has its show method called.
    // The FrameLoadRequest parameter is only for ChromeClient to check if the
    // request could be fulfilled. The ChromeClient should not load the request.
    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, const NavigationAction&) = 0;
    virtual void show() = 0;

    virtual bool canRunModal() = 0;
    virtual void runModal() = 0;

    virtual void setToolbarsVisible(bool) = 0;
    virtual bool toolbarsVisible() = 0;

    virtual void setStatusbarVisible(bool) = 0;
    virtual bool statusbarVisible() = 0;

    virtual void setScrollbarsVisible(bool) = 0;
    virtual bool scrollbarsVisible() = 0;

    virtual void setMenubarVisible(bool) = 0;
    virtual bool menubarVisible() = 0;

    virtual void setResizable(bool) = 0;

    virtual void addMessageToConsole(MessageSource, MessageLevel, const String& message, unsigned lineNumber, unsigned columnNumber, const String& sourceID) = 0;
    // FIXME: Remove this MessageType variant once all the clients are updated.
    virtual void addMessageToConsole(MessageSource source, MessageType, MessageLevel level, const String& message, unsigned lineNumber, unsigned columnNumber, const String& sourceID)
    {
        addMessageToConsole(source, level, message, lineNumber, columnNumber, sourceID);
    }

    virtual bool canRunBeforeUnloadConfirmPanel() = 0;
    virtual bool runBeforeUnloadConfirmPanel(const String& message, Frame*) = 0;

    virtual void closeWindowSoon() = 0;

    virtual void runJavaScriptAlert(Frame*, const String&) = 0;
    virtual bool runJavaScriptConfirm(Frame*, const String&) = 0;
    virtual bool runJavaScriptPrompt(Frame*, const String& message, const String& defaultValue, String& result) = 0;
    virtual void setStatusbarText(const String&) = 0;
    virtual bool shouldInterruptJavaScript() = 0;
    virtual KeyboardUIMode keyboardUIMode() = 0;

    virtual IntRect windowResizerRect() const = 0;

    // Methods used by HostWindow.
    virtual bool supportsImmediateInvalidation() { return false; }
    virtual void invalidateRootView(const IntRect&) = 0;
    virtual void invalidateContentsAndRootView(const IntRect&) = 0;
    virtual void invalidateContentsForSlowScroll(const IntRect&) = 0;
    virtual void scroll(const IntSize&, const IntRect&, const IntRect&) = 0;
#if USE(TILED_BACKING_STORE)
    virtual void delegatedScrollRequested(const IntPoint&) = 0;
#endif
    virtual IntPoint screenToRootView(const IntPoint&) const = 0;
    virtual IntRect rootViewToScreen(const IntRect&) const = 0;
#if PLATFORM(IOS)
    virtual IntPoint accessibilityScreenToRootView(const IntPoint&) const = 0;
    virtual IntRect rootViewToAccessibilityScreen(const IntRect&) const = 0;
#endif
    virtual PlatformPageClient platformPageClient() const = 0;
    virtual void scrollbarsModeDidChange() const = 0;
#if ENABLE(CURSOR_SUPPORT)
    virtual void setCursor(const Cursor&) = 0;
    virtual void setCursorHiddenUntilMouseMoves(bool) = 0;
#endif
#if ENABLE(REQUEST_ANIMATION_FRAME) && !USE(REQUEST_ANIMATION_FRAME_TIMER)
    virtual void scheduleAnimation() = 0;
#endif
    // End methods used by HostWindow.

    virtual FloatSize screenSize() const { return const_cast<ChromeClient*>(this)->windowRect().size(); }
    virtual FloatSize availableScreenSize() const { return const_cast<ChromeClient*>(this)->windowRect().size(); }

    virtual void dispatchViewportPropertiesDidChange(const ViewportArguments&) const { }

    virtual void contentsSizeChanged(Frame*, const IntSize&) const = 0;
    virtual void scrollRectIntoView(const IntRect&) const { }; // Currently only Mac has a non empty implementation.

    virtual bool shouldUnavailablePluginMessageBeButton(RenderEmbeddedObject::PluginUnavailabilityReason) const { return false; }
    virtual void unavailablePluginButtonClicked(Element*, RenderEmbeddedObject::PluginUnavailabilityReason) const { }
    virtual void mouseDidMoveOverElement(const HitTestResult&, unsigned modifierFlags) = 0;

    virtual void setToolTip(const String&, TextDirection) = 0;

    virtual void print(Frame*) = 0;

    virtual Color underlayColor() const { return Color(); }

    virtual void pageExtendedBackgroundColorDidChange(Color) const { }

#if ENABLE(SQL_DATABASE)
    virtual void exceededDatabaseQuota(Frame*, const String& databaseName, DatabaseDetails) = 0;
#endif

    // Callback invoked when the application cache fails to save a cache object
    // because storing it would grow the database file past its defined maximum
    // size or past the amount of free space on the device.
    // The chrome client would need to take some action such as evicting some
    // old caches.
    virtual void reachedMaxAppCacheSize(int64_t spaceNeeded) = 0;

    // Callback invoked when the application cache origin quota is reached. This
    // means that the resources attempting to be cached via the manifest are
    // more than allowed on this origin. This callback allows the chrome client
    // to take action, such as prompting the user to ask to increase the quota
    // for this origin. The totalSpaceNeeded parameter is the total amount of
    // storage, in bytes, needed to store the new cache along with all of the
    // other existing caches for the origin that would not be replaced by
    // the new cache.
    virtual void reachedApplicationCacheOriginQuota(SecurityOrigin*, int64_t totalSpaceNeeded) = 0;

#if ENABLE(DASHBOARD_SUPPORT)
    virtual void annotatedRegionsChanged();
#endif

    virtual void populateVisitedLinks();

    virtual bool shouldReplaceWithGeneratedFileForUpload(const String& path, String& generatedFilename);
    virtual String generateReplacementFile(const String& path);

#if ENABLE(IOS_TOUCH_EVENTS)
    virtual void didPreventDefaultForEvent() = 0;
#endif

    virtual std::chrono::milliseconds eventThrottlingDelay() { return std::chrono::milliseconds::zero(); };

#if PLATFORM(IOS)
    virtual void didReceiveMobileDocType(bool) = 0;
    virtual void setNeedsScrollNotifications(Frame*, bool) = 0;
    virtual void observedContentChange(Frame*) = 0;
    virtual void clearContentChangeObservers(Frame*) = 0;
    virtual void notifyRevealedSelectionByScrollingFrame(Frame*) = 0;

    enum LayoutType { NormalLayout, Scroll };
    virtual void didLayout(LayoutType = NormalLayout) = 0;
    virtual void didStartOverflowScroll() = 0;
    virtual void didEndOverflowScroll() = 0;

    // FIXME: Remove this functionality. This functionality was added to workaround an issue (<rdar://problem/5973875>)
    // where the unconfirmed text in a text area would be removed when a person clicks in the text area before a
    // suggestion is shown. We should fix this issue in <rdar://problem/5975559>.
    virtual void suppressFormNotifications() = 0;
    virtual void restoreFormNotifications() = 0;

    virtual void didFlushCompositingLayers() { }

    virtual bool fetchCustomFixedPositionLayoutRect(IntRect&) { return false; }

    virtual void updateViewportConstrainedLayers(HashMap<PlatformLayer*, std::unique_ptr<ViewportConstraints>>&, HashMap<PlatformLayer*, PlatformLayer*>&) { }

    virtual void addOrUpdateScrollingLayer(Node*, PlatformLayer* scrollingLayer, PlatformLayer* contentsLayer, const IntSize& scrollSize, bool allowHorizontalScrollbar, bool allowVerticalScrollbar) = 0;
    virtual void removeScrollingLayer(Node*, PlatformLayer* scrollingLayer, PlatformLayer* contentsLayer) = 0;

    virtual void webAppOrientationsUpdated() = 0;
    virtual void showPlaybackTargetPicker(bool hasVideo) = 0;
#endif

#if ENABLE(ORIENTATION_EVENTS)
    virtual int deviceOrientation() const = 0;
#endif

#if ENABLE(INPUT_TYPE_COLOR)
    virtual PassOwnPtr<ColorChooser> createColorChooser(ColorChooserClient*, const Color&) = 0;
#endif

#if ENABLE(DATE_AND_TIME_INPUT_TYPES) && !PLATFORM(IOS)
    virtual PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) = 0;
#endif

    virtual void runOpenPanel(Frame*, PassRefPtr<FileChooser>) = 0;
    // Asynchronous request to load an icon for specified filenames.
    virtual void loadIconForFiles(const Vector<String>&, FileIconLoader*) = 0;

    virtual void elementDidFocus(const Node*) { };
    virtual void elementDidBlur(const Node*) { };

    virtual bool shouldPaintEntireContents() const { return false; }
    virtual bool hasStablePageScaleFactor() const { return true; }

    // Allows ports to customize the type of graphics layers created by this page.
    virtual GraphicsLayerFactory* graphicsLayerFactory() const { return nullptr; }

#if USE(REQUEST_ANIMATION_FRAME_DISPLAY_MONITOR)
    virtual PassRefPtr<DisplayRefreshMonitor> createDisplayRefreshMonitor(PlatformDisplayID) const { return nullptr; }
#endif

    // Pass 0 as the GraphicsLayer to detatch the root layer.
    virtual void attachRootGraphicsLayer(Frame*, GraphicsLayer*) = 0;
    // Sets a flag to specify that the next time content is drawn to the window,
    // the changes appear on the screen in synchrony with updates to GraphicsLayers.
    virtual void setNeedsOneShotDrawingSynchronization() = 0;
    // Sets a flag to specify that the view needs to be updated, so we need
    // to do an eager layout before the drawing.
    virtual void scheduleCompositingLayerFlush() = 0;
    // Returns whether or not the client can render the composited layer,
    // regardless of the settings.
    virtual bool allowsAcceleratedCompositing() const { return true; }
    // Supply a layer that will added as an overlay over other document layers (scrolling with the document).
    virtual GraphicsLayer* documentOverlayLayerForFrame(Frame&) { return nullptr; }

    enum CompositingTrigger {
        ThreeDTransformTrigger = 1 << 0,
        VideoTrigger = 1 << 1,
        PluginTrigger = 1 << 2,
        CanvasTrigger = 1 << 3,
        AnimationTrigger = 1 << 4,
        FilterTrigger = 1 << 5,
        ScrollableInnerFrameTrigger = 1 << 6,
        AnimatedOpacityTrigger = 1 << 7,
        AllTriggers = 0xFFFFFFFF
    };
    typedef unsigned CompositingTriggerFlags;

    // Returns a bitfield indicating conditions that can trigger the compositor.
    virtual CompositingTriggerFlags allowedCompositingTriggers() const { return static_cast<CompositingTriggerFlags>(AllTriggers); }

    // Returns true if layer tree updates are disabled.
    virtual bool layerTreeStateIsFrozen() const { return false; }

    virtual bool adjustLayerFlushThrottling(LayerFlushThrottleState::Flags) { return false; }

    virtual PassRefPtr<ScrollingCoordinator> createScrollingCoordinator(Page*) const { return nullptr; }

#if PLATFORM(WIN) && USE(AVFOUNDATION)
    virtual GraphicsDeviceAdapter* graphicsDeviceAdapter() const { return 0; }
#endif

    virtual bool supportsFullscreenForNode(const Node*) { return false; }
    virtual void enterFullscreenForNode(Node*) { }
    virtual void exitFullscreenForNode(Node*) { }
    virtual bool requiresFullscreenForVideoPlayback() { return false; }

#if ENABLE(FULLSCREEN_API)
    virtual bool supportsFullScreenForElement(const Element*, bool) { return false; }
    virtual void enterFullScreenForElement(Element*) { }
    virtual void exitFullScreenForElement(Element*) { }
    virtual void setRootFullScreenLayer(GraphicsLayer*) { }
#endif

#if USE(TILED_BACKING_STORE)
    virtual IntRect visibleRectForTiledBackingStore() const { return IntRect(); }
#endif

#if PLATFORM(COCOA)
    virtual NSResponder *firstResponder() { return 0; }
    virtual void makeFirstResponder(NSResponder *) { }
    // Focuses on the containing view associated with this page.
    virtual void makeFirstResponder() { }
#endif

#if PLATFORM(IOS)
    // FIXME: Come up with a more descriptive name for this function and make it platform independent (if possible).
    virtual bool isStopping() = 0;
#endif

    virtual void enableSuddenTermination() { }
    virtual void disableSuddenTermination() { }

#if PLATFORM(WIN)
    virtual void setLastSetCursorToCurrentCursor() = 0;
    virtual void AXStartFrameLoad() = 0;
    virtual void AXFinishFrameLoad() = 0;
#endif

#if ENABLE(TOUCH_EVENTS)
    virtual void needTouchEvents(bool) = 0;
#endif

    virtual bool selectItemWritingDirectionIsNatural() = 0;
    virtual bool selectItemAlignmentFollowsMenuWritingDirection() = 0;
    // Checks if there is an opened popup, called by RenderMenuList::showPopup().
    virtual bool hasOpenedPopup() const = 0;
    virtual PassRefPtr<PopupMenu> createPopupMenu(PopupMenuClient*) const = 0;
    virtual PassRefPtr<SearchPopupMenu> createSearchPopupMenu(PopupMenuClient*) const = 0;

    virtual void postAccessibilityNotification(AccessibilityObject*, AXObjectCache::AXNotification) { }

    virtual void notifyScrollerThumbIsVisibleInRect(const IntRect&) { }
    virtual void recommendedScrollbarStyleDidChange(int /*newStyle*/) { }

    enum DialogType {
        AlertDialog = 0,
        ConfirmDialog = 1,
        PromptDialog = 2,
        HTMLDialog = 3
    };
    virtual bool shouldRunModalDialogDuringPageDismissal(const DialogType&, const String& dialogMessage, FrameLoader::PageDismissalType) const { UNUSED_PARAM(dialogMessage); return true; }

    virtual void numWheelEventHandlersChanged(unsigned) = 0;

    virtual bool isSVGImageChromeClient() const { return false; }

#if ENABLE(POINTER_LOCK)
    virtual bool requestPointerLock() { return false; }
    virtual void requestPointerUnlock() { }
    virtual bool isPointerLocked() { return false; }
#endif

    virtual void logDiagnosticMessage(const String& message, const String& description, const String& status) { UNUSED_PARAM(message); UNUSED_PARAM(description); UNUSED_PARAM(status); }

    virtual FloatSize minimumWindowSize() const { return FloatSize(100, 100); };

    virtual bool isEmptyChromeClient() const { return false; }

    virtual String plugInStartLabelTitle(const String& mimeType) const { UNUSED_PARAM(mimeType); return String(); }
    virtual String plugInStartLabelSubtitle(const String& mimeType) const { UNUSED_PARAM(mimeType); return String(); }
    virtual String plugInExtraStyleSheet() const { return String(); }
    virtual String plugInExtraScript() const { return String(); }

    virtual void didAssociateFormControls(const Vector<RefPtr<Element>>&) { };
    virtual bool shouldNotifyOnFormChanges() { return false; };

    virtual void didAddHeaderLayer(GraphicsLayer*) { }
    virtual void didAddFooterLayer(GraphicsLayer*) { }

    virtual bool shouldUseTiledBackingForFrameView(const FrameView*) const { return false; }

#if ENABLE(SUBTLE_CRYPTO)
    virtual bool wrapCryptoKey(const Vector<uint8_t>&, Vector<uint8_t>&) const { return false; }
    virtual bool unwrapCryptoKey(const Vector<uint8_t>&, Vector<uint8_t>&) const { return false; }
#endif

protected:
    virtual ~ChromeClient() { }
};

}
#endif // ChromeClient_h


text:
package com.tinkerpop.rexster;

import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import org.codehaus.jettison.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;

public class GraphResourceIntegrationTest extends AbstractGraphResourceIntegrationTest {

    public GraphResourceIntegrationTest() throws Exception {
        super();
    }

    @Test
    public void getGraph() {
        for (GraphTestHolder tg : this.testGraphs) {
            ClientRequest request = ClientRequest.create().build(createUri("/" + tg.getGraphName()), "GET");
            ClientResponse response = this.client().handle(request);

            Assert.assertNotNull(response);
            Assert.assertEquals(ClientResponse.Status.OK, response.getClientResponseStatus());

            JSONObject json = response.getEntity(JSONObject.class);
            Assert.assertNotNull(json);
            Assert.assertTrue(json.has("name"));
            Assert.assertEquals(tg.getGraphName(), json.optString("name"));
            Assert.assertTrue(json.has(Tokens.QUERY_TIME));
            Assert.assertTrue(json.optDouble(Tokens.QUERY_TIME) > 0);
            Assert.assertTrue(json.has(Tokens.UP_TIME));
            Assert.assertTrue(json.has(Tokens.READ_ONLY));
            Assert.assertTrue(json.has("version"));
            Assert.assertTrue(json.has("type"));
            Assert.assertEquals(tg.getGraphType(), json.optString("type"));
        }
    }
}


text:
import Ember from 'ember';
import {
  moduleForComponent,
  test
} from 'ember-qunit';

moduleForComponent('input-credit-card-expiration', {

});

test('it renders', function(assert) {
  assert.expect(2);
  var component = this.subject();
  assert.equal(component._state, 'preRender');

  this.render();
  assert.equal(component._state, 'inDOM');
});

test('should format month shorthand correctly', function(assert) {
  var component = this.subject();

  this.render();

  Ember.run(function() {
    component.set('month', '4');
  });

  Ember.run(function() {
    assert.equal( component.get('value'), '04 / ');
  });
});

test('should format forward slash shorthand correctly', function(assert) {
  var component = this.subject();
  this.render();

  Ember.run(function() {
    component.set('month', '8');
  });

  var e = $.Event('keypress');
      e.which = 47; // '/'

  Ember.run(function() {
    component.$().trigger(e);
  });

  Ember.run(function() {
    var value = component.get('value');
    assert.equal(value, '08 / ');
  });
});

test('should only allow numbers', function(assert) {
  var component = this.subject();
  this.render();

  Ember.run(function() {
    component.set('month', '4');
  });

  var e = $.Event('keypress');
      e.which = 100; // 'd'

  component.$().trigger(e);

  Ember.run(function() {
    assert.equal( component.get('value'), '04 / ');
  });
});

test('should only allow six numbers', function(assert) {
  var component = this.subject();
  this.render();

  Ember.run(function() {
    component.set('month', '4');
    component.set('year', '2015');
  });

  var e = $.Event('keypress');
      e.which = 52; // 'd'

  component.$().trigger(e);

  Ember.run(function() {
    assert.equal( component.get('value'), '04 / 2015');
  });
});


text:
function ADStaleUserCleanup {
    Param (
        [Parameter(ValueFromPipeline)]
        [string[]]$Username,
        [int]$DisableAfter
    )
    Process {
        $UserAccount = Get-ADUser -Identity $Username
        If ($UserAccount.lastlogintime -lt (Get-Date).AddDays(-$DisableAfter)) {
            $UserAccount | Disable-ADUser
            Set-ADUser -Identity $UserAccount.Username -Description "Account Disabled"
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>cadastrar-prestadoras-do-pat</id>
    <dbId>1538</dbId>
    <nome>Cadastrar Prestadoras do PAT</nome>
    <sigla></sigla>
    <descricao>As empresas prestadoras de serviço de alimentação coletiva que desejam ter o registro no PAT devem encaminhar a documentação exigida, por estabelecimento; além disso, a prestadora deve possuir no Cadastro Nacional de Pessoas Jurídicas – CNPJ, do Ministério da Fazenda, o código de classificação nacional de atividades econômicas - CNAE n° 82.99-7-02 (emissão de vales-alimentação, vales-transporte e similares); após o envio da documentação, é realizada a análise e, se a requerente preencher os requisitos, é a ela enviado um ofício por meio do qual é comunicado o seu registro no PAT, juntamente com uma lista de verificação  da documentação necessária, abaixo elencada.</descricao>
    <contato>pat@mte.gov.br</contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>true</servico-digital>
    <link-servico-digital>https://mpdg-hom-ps.lecom.com.br/processos/iniciar</link-servico-digital>
    <solicitantes>
        <solicitante id="1366">
            <tipo>Pessoa jurídica</tipo>
            <requisitos>Possuir no Cadastro Nacional de Pessoas Jurídicas – CNPJ, do Ministério da Fazenda, o código de classificação nacional de atividades econômicas - CNAE n° 82.99-7-02 (emissão de vales-alimentação, vales-transporte e similares).</requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <nao-estimado-ainda/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="3095">
            <titulo>Envio de documentação pelo solicitante</titulo>
            <descricao>As empresas prestadoras de serviço de alimentação coletiva que desejam ter o registro no PAT encaminham a documentação necessária .</descricao>
            <documentos>
                <default>
                    <item id="2649">I – preenchimento do requerimento disponível em http://www.trabalho.gov.br/pat, no link: Como se cadastrar no PAT e Empresas Prestadoras de Serviços de Alimentação Coletiva;
II – ficha de registro no PAT devidamente preenchida, conforme modelo disponível em http://www.trabalho.gov.br/pat, no link: Como se cadastrar no PAT e empresas prestadoras de serviços de alimentação coletiva;</item>
                    <item id="2650">III – cópia do contrato social da empresa;
IV – comprovante da existência de vínculo empregatício ou contratual com o profissional nutricionista indicado como responsável técnico pelo PAT, e indicação do número do seu registro no Programa;
V – indicação da abrangência territorial de utilização do documento de legitimação;</item>
                    <item id="2651">VI – declaração de que a empresa tem ou não filial que comercializará documento de legitimação. Caso positivo, apresentar a documentação do(s) respectivo(s) nutricionista(s) solicitada no item V;</item>
                    <item id="2652">- Modelo do documento de legitimação: (verso)

Nome, endereço e CNPJ da prestadora de serviços de alimentação coletiva;
A expressão "válido somente para aquisição de gêneros alimentícios" se o documento de legitimação for alimentação- convênio;
A expressão "válido somente para pagamento de refeições" se o documento de legitimação for refeição- convênio.</item>
                    <item id="2653">VII – identificação do mecanismo de segurança do documento de legitimação.

OBSERVAÇÃO: Somente serão deferidos os pedidos de registro dos estabelecimentos que indiquem no Cadastro Nacional de Pessoas Jurídicas – CNPJ, do Ministério da Fazenda, o código de classificação nacional de atividades econômicas - CNAE n° 82.99-7- 02 (emissão de vales-alimentação, vales-transporte e similares).</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3327" tipo="web">
                        <descricao>https://mpdg-hom-ps.lecom.com.br/processos/iniciar?codserv=1538</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="3096">
            <titulo>Análise da documentação</titulo>
            <descricao>A documentação será analisada para verificar se todos os documentos exigidos foram enviados pelo solicitante.</descricao>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3328" tipo="web">
                        <descricao>https://mpdg-hom-ps.lecom.com.br/processos/iniciar?codserv=1538</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="3097">
            <titulo>Resposta ao solicitante</titulo>
            <descricao>Após a análise da documentação é enviado ofício ao solicitante por meio do qual é comunicado o deferimento/indeferimento de seu registro no PAT, juntamente com uma lista de verificação da documentação apresentada.</descricao>
            <documentos>
                <default>
                    <item id="2654">Lista de verificação, ofício e comprovante de registro no PAT</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3329" tipo="web">
                        <descricao>https://mpdg-hom-ps.lecom.com.br/processos/iniciar?codserv=1538</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/2844" dbId="37546">
        <nomeOrgao>Ministério do Trabalho  (MTB)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="3" idServicoSegmento="3129">Empresas</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Trabalho</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="4059">Cadastro</item>
        <item id="4060">Prestadora</item>
        <item id="4061">PAT</item>
    </palavras-chave>
    <legislacoes>
        <item id="992">Lei nº 6.321, de 14 de abril de 1976;
Decreto nº 5, de 14 de janeiro de 1991;
Portaria Interministerial nº 05, de 30 de novembro de 1999;
Portaria SIT/DSST nº 03, de 1º de março de 2002.</item>
    </legislacoes>
</servico>


text:
package fi.solita.jsonmigraine.internal;

import fi.solita.jsonmigraine.api.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;

public class AnnotationUpgraderProvider implements UpgraderProvider {

    public boolean isUpgradeable(Class<?> type) {
        return type.isAnnotationPresent(Upgradeable.class);
    }

    @Override
    public Upgrader getUpgrader(Class<?> type) {
        Class<? extends Upgrader> upgrader = getRequiredAnnotation(type, Upgradeable.class).value();
        try {
            Constructor<? extends Upgrader> c = upgrader.getDeclaredConstructor();
            c.setAccessible(true);
            return c.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static <T extends Annotation> T getRequiredAnnotation(Class<?> type, Class<T> annotationClass) {
        T annotation = type.getAnnotation(annotationClass);
        if (annotation == null) {
            throw new IllegalArgumentException(
                    "Expected " + type + " to be annotated with " + annotationClass + " but the annotation was missing");
        }
        return annotation;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TAlex.MathCore.ExpressionEvaluation.Trees;
using TAlex.MathCore.ExpressionEvaluation.Trees.Builders;
using TAlex.MathCore.ExpressionEvaluation.Trees.Metadata;
using TAlex.MathCore.NumericalAnalysis;
using TAlex.MathCore.NumericalAnalysis.NumericalIntegration;
using TAlex.MathCore.Performance;

namespace TAlex.MathCore.ExpressionEvaluation.ComplexExpressions.Functions
{
    [DisplayName("Integration")]
    [Category(Categories.Calculus)]
    [Section(Sections.Integration)]
    [Description("Calculates the numerical value of the definite integral complex function of one variable using adaptive method.")]
    [FunctionSignature("integ", "expression expr", "real a", "real b", "variable var")]
    [ExampleUsage("integ(sin(x), 0, pi, x)", "2")]
    [ExampleUsage("integ(e^x, -inf, 0, x)", "1")]
    [ExampleUsage("integ(x, 0, 10, x)", "50")]
    public class IntegrationFuncExpression : MultiaryExpression<Object>
    {
        protected ComplexIntegrator Integrator;

        public IntegrationFuncExpression(Expression<Object> exprExpression, Expression<Object> aExpression, Expression<Object> bExpression, Expression<Object> varExpression)
            : base(exprExpression, aExpression, bExpression, varExpression)
        {
            Integrator = new ComplexAdaptiveIntegrator();
        }

        public override object Evaluate()
        {
            Func<Complex, Complex> targetFunc = Expressions[0].EvaluateAsFunction<Complex>(Expressions[3]);
            double a = Expressions[1].EvaluateAsReal();
            double b = Expressions[2].EvaluateAsReal();

            return Integrator.Integrate(targetFunc, a, b);
        }
    }

    [DisplayName("1st derivation")]
    [Category(Categories.Calculus)]
    [Section(Sections.Derivation)]
    [Description("Calculates the value of the central derivative of the first order.")]
    [FunctionSignature("derive", "expression expr", "complex x", "variable var")]
    [ExampleUsage("derive(sin(x), pi/2, x)", "0")]
    public class FirstDerivationFuncExpression : TernaryExpression<Object>
    {
        public FirstDerivationFuncExpression(Expression<Object> exprExpression, Expression<Object> xExpression, Expression<Object> varExpression)
            : base(exprExpression, xExpression, varExpression)
        {
        }

        public override object Evaluate()
        {
            Func<Complex, Complex> targetFunc = FirstExpression.EvaluateAsFunction<Complex>(ThirdExpression);
            Complex x = SecondExpression.EvaluateAsComplex();

            return NumericalDerivation.FirstDerivative(targetFunc, x);
        }
    }

    [DisplayName("2nd derivation")]
    [Category(Categories.Calculus)]
    [Section(Sections.Derivation)]
    [Description("Calculates the value of the central derivative of the second order.")]
    [FunctionSignature("derive2", "expression expr", "complex x", "variable var")]
    [ExampleUsage("derive2(e^x, 1, x)", "2.71828182845911")]
    public class SecondDerivationFuncExpression : TernaryExpression<Object>
    {
        public SecondDerivationFuncExpression(Expression<Object> exprExpression, Expression<Object> xExpression, Expression<Object> varExpression)
            : base(exprExpression, xExpression, varExpression)
        {
        }

        public override object Evaluate()
        {
            Func<Complex, Complex> targetFunc = FirstExpression.EvaluateAsFunction<Complex>(ThirdExpression);
            Complex x = SecondExpression.EvaluateAsComplex();

            return NumericalDerivation.SecondDerivative(targetFunc, x);
        }
    }

    [DisplayName("3rd derivation")]
    [Category(Categories.Calculus)]
    [Section(Sections.Derivation)]
    [Description("Calculates the value of the central derivative of the third order.")]
    [FunctionSignature("derive3", "expression expr", "complex x", "variable var")]
    [ExampleUsage("derive3(1 + x^2, 1, x)", "0")]
    public class ThirdDerivationFuncExpression : TernaryExpression<Object>
    {
        public ThirdDerivationFuncExpression(Expression<Object> exprExpression, Expression<Object> xExpression, Expression<Object> varExpression)
            : base(exprExpression, xExpression, varExpression)
        {
        }

        public override object Evaluate()
        {
            Func<Complex, Complex> targetFunc = FirstExpression.EvaluateAsFunction<Complex>(ThirdExpression);
            Complex x = SecondExpression.EvaluateAsComplex();

            return NumericalDerivation.ThirdDerivative(targetFunc, x);
        }
    }

    [DisplayName("4th derivation")]
    [Category(Categories.Calculus)]
    [Section(Sections.Derivation)]
    [Description("Calculates the value of the central derivative of the fourth order.")]
    [FunctionSignature("derive4", "expression expr", "complex x", "variable var")]
    [ExampleUsage("derive4(sin(x^2), 2, x)", "-59.1602336374673")]
    public class FourthDerivationFuncExpression : TernaryExpression<Object>
    {
        public FourthDerivationFuncExpression(Expression<Object> exprExpression, Expression<Object> xExpression, Expression<Object> varExpression)
            : base(exprExpression, xExpression, varExpression)
        {
        }

        public override object Evaluate()
        {
            Func<Complex, Complex> targetFunc = FirstExpression.EvaluateAsFunction<Complex>(ThirdExpression);
            Complex x = SecondExpression.EvaluateAsComplex();

            return NumericalDerivation.FourthDerivative(targetFunc, x);
        }
    }

    [DisplayName("Summation of a sequance")]
    [Category(Categories.Calculus)]
    [Section(Sections.Sequence)]
    [Description("Calculates the sum of a sequence using initial value m and end value n.")]
    [FunctionSignature("sums", "expression expr", "integer m", "integer n", "variable var")]
    [ExampleUsage("sums(x^2/2, 2, 3, x)", "6.5")]
    [ExampleUsage("sums(sin(x + 2i), 0, 10, x)", "5.30916680950373 - 1.51402470396589i")]
    public class SummationSequanceFuncExpression : MultiaryExpression<Object>
    {
        public SummationSequanceFuncExpression(Expression<Object> exprExpression, Expression<Object> mExpression, Expression<Object> nExpression, Expression<Object> varExpression)
            : base(exprExpression, mExpression, nExpression, varExpression)
        {
        }

        public override object Evaluate()
        {
            Func<Complex, Complex> targetFunc = Expressions[0].EvaluateAsFunction<Complex>(Expressions[3]);
            int m = Expressions[1].EvaluateAsInt32();
            int n = Expressions[2].EvaluateAsInt32();
            PerformanceManager.Current.EnsureAcceptableIterationCount(Math.Abs(n - m));

            return Sequence.Summation(targetFunc, m, n);
        }
    }

    [DisplayName("Product of a sequance")]
    [Category(Categories.Calculus)]
    [Section(Sections.Sequence)]
    [Description("Calculates the product of a sequence using initial value m and end value n.")]
    [FunctionSignature("prods", "expression expr", "integer m", "integer n", "variable var")]
    [ExampleUsage("prods(x^2 / 2, 2, 3, x)", "9")]
    [ExampleUsage("prods(x * 2i, 0, 10, x)", "0")]
    public class ProductSequanceFuncExpression : MultiaryExpression<Object>
    {
        public ProductSequanceFuncExpression(Expression<Object> exprExpression, Expression<Object> mExpression, Expression<Object> nExpression, Expression<Object> varExpression)
            : base(exprExpression, mExpression, nExpression, varExpression)
        {
        }

        public override object Evaluate()
        {
            Func<Complex, Complex> targetFunc = Expressions[0].EvaluateAsFunction<Complex>(Expressions[3]);
            int m = Expressions[1].EvaluateAsInt32();
            int n = Expressions[2].EvaluateAsInt32();
            PerformanceManager.Current.EnsureAcceptableIterationCount(Math.Abs(n - m));

            return Sequence.Product(targetFunc, m, n);
        }
    }
}


text:
<sky-split-view [messageStream]="splitViewStream">
  <sky-split-view-drawer [ariaLabel]="'Transaction list'" [width]="listWidth">
    <sky-repeater [activeIndex]="activeIndex">
      <sky-repeater-item
        *ngFor="let item of items; let i = index"
        (click)="onItemClick(i)"
        (keyup.enter)="onItemClick(i)"
      >
        <sky-repeater-item-content>
          {{ item.amount }}

          {{ item.date }}

          {{ item.vendor }}
        </sky-repeater-item-content>
      </sky-repeater-item>
    </sky-repeater>
  </sky-split-view-drawer>

  <sky-split-view-workspace ariaLabel="Transaction form">
    <sky-split-view-workspace-content class="sky-padding-even-xl">
      <form [formGroup]="splitViewDemoForm" (ngSubmit)="onApprove()">
        <sky-definition-list labelWidth="150px">
          <sky-definition-list-content>
            <sky-definition-list-label>
              Receipt amount
            </sky-definition-list-label>
            <sky-definition-list-value>
              {{ activeRecord.amount }}
            </sky-definition-list-value>
          </sky-definition-list-content>
          <sky-definition-list-content>
            <sky-definition-list-label> Date </sky-definition-list-label>
            <sky-definition-list-value>
              {{ activeRecord.date }}
            </sky-definition-list-value>
          </sky-definition-list-content>
          <sky-definition-list-content>
            <sky-definition-list-label> Vendor </sky-definition-list-label>
            <sky-definition-list-value>
              {{ activeRecord.vendor }}
            </sky-definition-list-value>
          </sky-definition-list-content>
          <sky-definition-list-content>
            <sky-definition-list-label>
              Receipt image
            </sky-definition-list-label>
            <sky-definition-list-value>
              {{ activeRecord.receiptImage }}
            </sky-definition-list-value>
          </sky-definition-list-content>
        </sky-definition-list>

          <sky-input-box>

              Approved amount

            <input
              class="sky-form-control"
              formControlName="approvedAmount"
              name="approvedAmount"
              type="text"
              skyId
              #amountInput
            />
          </sky-input-box>

          <sky-input-box>

              Comments

            <textarea
              class="sky-form-control"
              formControlName="comments"
              name="comments"
              skyId
              #commentsInput
            ></textarea>
          </sky-input-box>

      </form>
    </sky-split-view-workspace-content>
    <sky-split-view-workspace-footer>
      <sky-summary-action-bar id="summary-action-bar">
        <sky-summary-action-bar-actions>
          <sky-summary-action-bar-primary-action (actionClick)="onApprove()">
            Approve expense
          </sky-summary-action-bar-primary-action>
          <sky-summary-action-bar-secondary-actions>
            <sky-summary-action-bar-secondary-action (actionClick)="onDeny()">
              Deny expense
            </sky-summary-action-bar-secondary-action>
          </sky-summary-action-bar-secondary-actions>
        </sky-summary-action-bar-actions>
      </sky-summary-action-bar>
    </sky-split-view-workspace-footer>
  </sky-split-view-workspace>
</sky-split-view>


text:
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { Component, ViewChild } from '@angular/core';
import { CoreCommentsProvider } from '@core/comments/providers/comments';
import { CoreCommentsCommentsComponent } from '@core/comments/components/comments/comments';
import { AddonModAssignSubmissionPluginComponent } from '../../../classes/submission-plugin-component';

/**
 * Component to render a comments submission plugin.
 */
@Component({
    selector: 'addon-mod-assign-submission-comments',
    templateUrl: 'addon-mod-assign-submission-comments.html'
})
export class AddonModAssignSubmissionCommentsComponent extends AddonModAssignSubmissionPluginComponent {
    @ViewChild(CoreCommentsCommentsComponent) commentsComponent: CoreCommentsCommentsComponent;

    constructor(protected commentsProvider: CoreCommentsProvider) {
        super();
    }

    /**
     * Invalidate the data.
     *
     * @return {Promise<any>} Promise resolved when done.
     */
    invalidate(): Promise<any> {
        return this.commentsProvider.invalidateCommentsData('module', this.assign.cmid, 'assignsubmission_comments',
                this.submission.id, 'submission_comments');
    }

    /**
     * Show the comments.
     */
    showComments(): void {
        this.commentsComponent && this.commentsComponent.openComments();
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>statsmodels.tsa.statespace.representation.Representation.initialize_known — statsmodels v0.10.1 documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.tsa.statespace.representation.Representation.initialize_stationary" href="statsmodels.tsa.statespace.representation.Representation.initialize_stationary.html" />
    <link rel="prev" title="statsmodels.tsa.statespace.representation.Representation.initialize_diffuse" href="statsmodels.tsa.statespace.representation.Representation.initialize_diffuse.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Time Series Analysis by State Space Methods statespace |

statsmodels.tsa.statespace.representation.Representation |

statsmodels.tsa.statespace.representation.Representation.initialize_known¶

method

Representation.initialize_known(constant, stationary_cov)[source]¶

Initialize the statespace model with known distribution for initial
state.

These values are assumed to be known with certainty or else
filled with parameters during, for example, maximum likelihood
estimation.

Parameters

constantarray_like

Known mean of the initial state vector.

stationary_covarray_like

Known covariance matrix of the initial state vector.

Previous topic

statsmodels.tsa.statespace.representation.Representation.initialize_diffuse

Next topic

statsmodels.tsa.statespace.representation.Representation.initialize_stationary

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

        © Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 2.1.2.


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

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 * Information about an individual group deployment in a bulk deployment operation.
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BulkDeploymentResult implements Serializable, Cloneable, StructuredPojo {

    /** The time, in ISO format, when the deployment was created. */
    private String createdAt;
    /** The ARN of the group deployment. */
    private String deploymentArn;
    /** The ID of the group deployment. */
    private String deploymentId;
    /** The current status of the group deployment: ''InProgress'', ''Building'', ''Success'', or ''Failure''. */
    private String deploymentStatus;
    /** The type of the deployment. */
    private String deploymentType;
    /** Details about the error. */
    private java.util.List<ErrorDetail> errorDetails;
    /** The error message for a failed deployment */
    private String errorMessage;
    /** The ARN of the Greengrass group. */
    private String groupArn;

    /**
     * The time, in ISO format, when the deployment was created.
     *
     * @param createdAt
     *        The time, in ISO format, when the deployment was created.
     */

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    /**
     * The time, in ISO format, when the deployment was created.
     *
     * @return The time, in ISO format, when the deployment was created.
     */

    public String getCreatedAt() {
        return this.createdAt;
    }

    /**
     * The time, in ISO format, when the deployment was created.
     *
     * @param createdAt
     *        The time, in ISO format, when the deployment was created.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BulkDeploymentResult withCreatedAt(String createdAt) {
        setCreatedAt(createdAt);
        return this;
    }

    /**
     * The ARN of the group deployment.
     *
     * @param deploymentArn
     *        The ARN of the group deployment.
     */

    public void setDeploymentArn(String deploymentArn) {
        this.deploymentArn = deploymentArn;
    }

    /**
     * The ARN of the group deployment.
     *
     * @return The ARN of the group deployment.
     */

    public String getDeploymentArn() {
        return this.deploymentArn;
    }

    /**
     * The ARN of the group deployment.
     *
     * @param deploymentArn
     *        The ARN of the group deployment.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BulkDeploymentResult withDeploymentArn(String deploymentArn) {
        setDeploymentArn(deploymentArn);
        return this;
    }

    /**
     * The ID of the group deployment.
     *
     * @param deploymentId
     *        The ID of the group deployment.
     */

    public void setDeploymentId(String deploymentId) {
        this.deploymentId = deploymentId;
    }

    /**
     * The ID of the group deployment.
     *
     * @return The ID of the group deployment.
     */

    public String getDeploymentId() {
        return this.deploymentId;
    }

    /**
     * The ID of the group deployment.
     *
     * @param deploymentId
     *        The ID of the group deployment.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BulkDeploymentResult withDeploymentId(String deploymentId) {
        setDeploymentId(deploymentId);
        return this;
    }

    /**
     * The current status of the group deployment: ''InProgress'', ''Building'', ''Success'', or ''Failure''.
     *
     * @param deploymentStatus
     *        The current status of the group deployment: ''InProgress'', ''Building'', ''Success'', or ''Failure''.
     */

    public void setDeploymentStatus(String deploymentStatus) {
        this.deploymentStatus = deploymentStatus;
    }

    /**
     * The current status of the group deployment: ''InProgress'', ''Building'', ''Success'', or ''Failure''.
     *
     * @return The current status of the group deployment: ''InProgress'', ''Building'', ''Success'', or ''Failure''.
     */

    public String getDeploymentStatus() {
        return this.deploymentStatus;
    }

    /**
     * The current status of the group deployment: ''InProgress'', ''Building'', ''Success'', or ''Failure''.
     *
     * @param deploymentStatus
     *        The current status of the group deployment: ''InProgress'', ''Building'', ''Success'', or ''Failure''.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BulkDeploymentResult withDeploymentStatus(String deploymentStatus) {
        setDeploymentStatus(deploymentStatus);
        return this;
    }

    /**
     * The type of the deployment.
     *
     * @param deploymentType
     *        The type of the deployment.
     * @see DeploymentType
     */

    public void setDeploymentType(String deploymentType) {
        this.deploymentType = deploymentType;
    }

    /**
     * The type of the deployment.
     *
     * @return The type of the deployment.
     * @see DeploymentType
     */

    public String getDeploymentType() {
        return this.deploymentType;
    }

    /**
     * The type of the deployment.
     *
     * @param deploymentType
     *        The type of the deployment.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see DeploymentType
     */

    public BulkDeploymentResult withDeploymentType(String deploymentType) {
        setDeploymentType(deploymentType);
        return this;
    }

    /**
     * The type of the deployment.
     *
     * @param deploymentType
     *        The type of the deployment.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see DeploymentType
     */

    public BulkDeploymentResult withDeploymentType(DeploymentType deploymentType) {
        this.deploymentType = deploymentType.toString();
        return this;
    }

    /**
     * Details about the error.
     *
     * @return Details about the error.
     */

    public java.util.List<ErrorDetail> getErrorDetails() {
        return errorDetails;
    }

    /**
     * Details about the error.
     *
     * @param errorDetails
     *        Details about the error.
     */

    public void setErrorDetails(java.util.Collection<ErrorDetail> errorDetails) {
        if (errorDetails == null) {
            this.errorDetails = null;
            return;
        }

        this.errorDetails = new java.util.ArrayList<ErrorDetail>(errorDetails);
    }

    /**
     * Details about the error.
     *

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

     *
     * @param errorDetails
     *        Details about the error.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BulkDeploymentResult withErrorDetails(ErrorDetail... errorDetails) {
        if (this.errorDetails == null) {
            setErrorDetails(new java.util.ArrayList<ErrorDetail>(errorDetails.length));
        }
        for (ErrorDetail ele : errorDetails) {
            this.errorDetails.add(ele);
        }
        return this;
    }

    /**
     * Details about the error.
     *
     * @param errorDetails
     *        Details about the error.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BulkDeploymentResult withErrorDetails(java.util.Collection<ErrorDetail> errorDetails) {
        setErrorDetails(errorDetails);
        return this;
    }

    /**
     * The error message for a failed deployment
     *
     * @param errorMessage
     *        The error message for a failed deployment
     */

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    /**
     * The error message for a failed deployment
     *
     * @return The error message for a failed deployment
     */

    public String getErrorMessage() {
        return this.errorMessage;
    }

    /**
     * The error message for a failed deployment
     *
     * @param errorMessage
     *        The error message for a failed deployment
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BulkDeploymentResult withErrorMessage(String errorMessage) {
        setErrorMessage(errorMessage);
        return this;
    }

    /**
     * The ARN of the Greengrass group.
     *
     * @param groupArn
     *        The ARN of the Greengrass group.
     */

    public void setGroupArn(String groupArn) {
        this.groupArn = groupArn;
    }

    /**
     * The ARN of the Greengrass group.
     *
     * @return The ARN of the Greengrass group.
     */

    public String getGroupArn() {
        return this.groupArn;
    }

    /**
     * The ARN of the Greengrass group.
     *
     * @param groupArn
     *        The ARN of the Greengrass group.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BulkDeploymentResult withGroupArn(String groupArn) {
        setGroupArn(groupArn);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getCreatedAt() != null)
            sb.append("CreatedAt: ").append(getCreatedAt()).append(",");
        if (getDeploymentArn() != null)
            sb.append("DeploymentArn: ").append(getDeploymentArn()).append(",");
        if (getDeploymentId() != null)
            sb.append("DeploymentId: ").append(getDeploymentId()).append(",");
        if (getDeploymentStatus() != null)
            sb.append("DeploymentStatus: ").append(getDeploymentStatus()).append(",");
        if (getDeploymentType() != null)
            sb.append("DeploymentType: ").append(getDeploymentType()).append(",");
        if (getErrorDetails() != null)
            sb.append("ErrorDetails: ").append(getErrorDetails()).append(",");
        if (getErrorMessage() != null)
            sb.append("ErrorMessage: ").append(getErrorMessage()).append(",");
        if (getGroupArn() != null)
            sb.append("GroupArn: ").append(getGroupArn());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof BulkDeploymentResult == false)
            return false;
        BulkDeploymentResult other = (BulkDeploymentResult) obj;
        if (other.getCreatedAt() == null ^ this.getCreatedAt() == null)
            return false;
        if (other.getCreatedAt() != null && other.getCreatedAt().equals(this.getCreatedAt()) == false)
            return false;
        if (other.getDeploymentArn() == null ^ this.getDeploymentArn() == null)
            return false;
        if (other.getDeploymentArn() != null && other.getDeploymentArn().equals(this.getDeploymentArn()) == false)
            return false;
        if (other.getDeploymentId() == null ^ this.getDeploymentId() == null)
            return false;
        if (other.getDeploymentId() != null && other.getDeploymentId().equals(this.getDeploymentId()) == false)
            return false;
        if (other.getDeploymentStatus() == null ^ this.getDeploymentStatus() == null)
            return false;
        if (other.getDeploymentStatus() != null && other.getDeploymentStatus().equals(this.getDeploymentStatus()) == false)
            return false;
        if (other.getDeploymentType() == null ^ this.getDeploymentType() == null)
            return false;
        if (other.getDeploymentType() != null && other.getDeploymentType().equals(this.getDeploymentType()) == false)
            return false;
        if (other.getErrorDetails() == null ^ this.getErrorDetails() == null)
            return false;
        if (other.getErrorDetails() != null && other.getErrorDetails().equals(this.getErrorDetails()) == false)
            return false;
        if (other.getErrorMessage() == null ^ this.getErrorMessage() == null)
            return false;
        if (other.getErrorMessage() != null && other.getErrorMessage().equals(this.getErrorMessage()) == false)
            return false;
        if (other.getGroupArn() == null ^ this.getGroupArn() == null)
            return false;
        if (other.getGroupArn() != null && other.getGroupArn().equals(this.getGroupArn()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode());
        hashCode = prime * hashCode + ((getDeploymentArn() == null) ? 0 : getDeploymentArn().hashCode());
        hashCode = prime * hashCode + ((getDeploymentId() == null) ? 0 : getDeploymentId().hashCode());
        hashCode = prime * hashCode + ((getDeploymentStatus() == null) ? 0 : getDeploymentStatus().hashCode());
        hashCode = prime * hashCode + ((getDeploymentType() == null) ? 0 : getDeploymentType().hashCode());
        hashCode = prime * hashCode + ((getErrorDetails() == null) ? 0 : getErrorDetails().hashCode());
        hashCode = prime * hashCode + ((getErrorMessage() == null) ? 0 : getErrorMessage().hashCode());
        hashCode = prime * hashCode + ((getGroupArn() == null) ? 0 : getGroupArn().hashCode());
        return hashCode;
    }

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

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.greengrass.model.transform.BulkDeploymentResultMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package com.norwand.game.management.gamedata.player.states;

import com.badlogic.gdx.graphics.Pixmap;
import com.norwand.game.management.gamedata.GameData;
import com.norwand.game.management.gamedata.player.Capacity;
import com.norwand.game.management.gamedata.player.Player;
import com.norwand.game.management.gamedata.player.PlayerState;
import com.norwand.game.resources.ImagesHolder;
import com.norwand.game.utility.objects.Position;

/**
 * Created by Valentin Marechal on 18/05/2016.
 */
public class PS_Falling extends PlayerState{

    public PS_Falling(Player player) {
        super(player);
    }

    private int counter;

    @Override
    public void update() {
        ++counter;
        if(counter > 39){
            player.state = new PS_Iddle(player);
            Position respawn = GameData.get().currentfloor.getClosestRespawnPoint(new Position(player.x,player.y));
            player.x = respawn.x;
            player.y = respawn.y;
            player.info.health -= 0.25;
        }
    }

    @Override
    public Pixmap getSprite() {

            return  ImagesHolder.playerset.getTile(104+(counter/10));
    }

    @Override
    public void onTap(Position pos) {
    }

    @Override
    public void onMoveTo(Position pos) {
    }

    @Override
    public void onStop() {
    }

    @Override
    public void onSkillUsed(Position pos, Capacity capacity) {
    }
}


text:
/*
 * Internal header file supporting Python
 * for com.ibm.streamsx.topology.
 *
 * This is not part of any public api for
 * the toolkit or toolkit with decorated
 * SPL Python operators.
 *
 * Functionality related to operators
 */

#ifndef __SPL__SPLPY_OP_H
#define __SPL__SPLPY_OP_H

#include "splpy_general.h"
#include "splpy_ec_api.h"

namespace streamsx {
  namespace topology {

class SplpyOp {
  public:
      SplpyOp(SPL::Operator *op, const char * spl_setup_py) :
          op_(op),
          callable_(NULL),
          pydl_(NULL)

#if __SPLPY_EC_MODULE_OK
          , opc_(NULL)
#endif

      {
          pydl_ = SplpySetup::loadCPython(spl_setup_py);
#if __SPLPY_EC_MODULE_OK

          SplpyGIL lock;
          opc_ = PyLong_FromVoidPtr((void*)op);
          if (opc_ == NULL)
              throw SplpyGeneral::pythonException("capsule");
#endif
      }

      ~SplpyOp()
      {
        {
          SplpyGIL lock;

          if (callable_ != NULL)
              Py_DECREF(callable_);

#if __SPLPY_EC_MODULE_OK
          if (opc_ != NULL)
              Py_DECREF(opc_);
#endif
        }
        if (pydl_ != NULL)
          (void) dlclose(pydl_);
      }

      SPL::Operator * op() {
         return op_;
      }

      void setCallable(PyObject * callable) {
           callable_ = callable;
      }
      PyObject * callable() {
          return callable_;
      }

      /**
       * Actions for a Python operator on prepareToShutdown
       * Flush any pending output.
      */
      void prepareToShutdown() {
          SplpyGIL lock;
          if (callable_) {
             // Call _shutdown_op which will invoke
             // __exit__ on the users object if
             // it's a class instance and has
             // __enter__ and __exit__
             // callVoid steals the reference to callable_
             Py_INCREF(callable_);
             SplpyGeneral::callVoidFunction(
               "streamsx.ec", "_shutdown_op", callable_, NULL);
          }
          SplpyGeneral::flush_PyErrPyOut();
      }

#if __SPLPY_EC_MODULE_OK
      // Get the capture with a new ref
      PyObject * opc() {
         Py_INCREF(opc_);
         return opc_;
      }

      // Set the operator capsule as a Python thread local
      // use streamsx.ec._set_opc so that it is availble
      // through the operator's class __init__ function.
      void setopc() {
         SplpyGeneral::callVoidFunction(
               "streamsx.ec", "_set_opc", opc(), NULL);
      }

      // Clear the thread local for the operator capsule
      void clearopc() {
          SplpyGeneral::callVoidFunction(
               "streamsx.ec", "_clear_opc",
               NULL, NULL);
      }
#endif

   private:
      SPL::Operator *op_;

      // Python object used to process tuples
      PyObject *callable_;

      // Handle to libpythonX.Y.so
      void * pydl_;

#if __SPLPY_EC_MODULE_OK
      // PyLong of op_
      PyObject *opc_;
#endif
};

}}

#endif


text:
* Ruby
* Bundler

## Install

```
$ bundle install
```

## Test

```
$ bundle exec ruby ./test/fizzbuzz_test.rb
```

## See Also

* <https://github.com/seattlerb/minitest>

## Author

* Yusuke Wada <http://github.com/yusukebe>


text:
Examples for DeadlineCommand, Events, REST API and so forth.  Have a look around!

Back to the [top level](https://github.com/ThinkboxSoftware/Deadline).

![End](../thinkbox_tiny.png)