text:
package org.jetbrains.plugins.groovy.runner;

import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.util.ProgramParametersUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PathMacroManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SimpleJavaSdkType;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizer;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.refactoring.listeners.RefactoringElementAdapter;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import com.intellij.util.PathUtil;
import com.intellij.util.SystemProperties;
import consulo.java.execution.configurations.OwnJavaParameters;
import consulo.java.module.extension.JavaModuleExtension;
import org.jdom.Element;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;

/**
 * @author peter
 */
public class GroovyScriptRunConfiguration extends ModuleBasedConfiguration<RunConfigurationModule> implements CommonJavaRunConfigurationParameters, RefactoringListenerProvider
{

	private static final Logger LOG = Logger.getInstance(GroovyScriptRunConfiguration.class);
	private String vmParams;
	private String workDir;
	private boolean isDebugEnabled;
	@javax.annotation.Nullable
	private String scriptParams;
	@javax.annotation.Nullable
	private String scriptPath;
	private final Map<String, String> envs = new LinkedHashMap<String, String>();
	public boolean passParentEnv = true;

	public GroovyScriptRunConfiguration(final String name, final Project project, final ConfigurationFactory factory)
	{
		super(name, new RunConfigurationModule(project), factory);
		workDir = PathUtil.getLocalPath(project.getBaseDir());
	}

	@Override
	protected ModuleBasedConfiguration createInstance()
	{
		return new GroovyScriptRunConfiguration(getName(), getProject(), getFactory());
	}

	public void setWorkDir(String dir)
	{
		workDir = dir;
	}

	public String getWorkDir()
	{
		return workDir;
	}

	@Nullable
	public Module getModule()
	{
		return getConfigurationModule().getModule();
	}

	public Collection<Module> getValidModules()
	{
		Module[] modules = ModuleManager.getInstance(getProject()).getModules();
		final GroovyScriptRunner scriptRunner = findConfiguration();
		if(scriptRunner == null)
		{
			return Arrays.asList(modules);
		}

		ArrayList<Module> res = new ArrayList<Module>();
		for(Module module : modules)
		{
			if(scriptRunner.isValidModule(module))
			{
				res.add(module);
			}
		}
		return res;
	}

	@javax.annotation.Nullable
	private GroovyScriptRunner findConfiguration()
	{
		final VirtualFile scriptFile = getScriptFile();
		if(scriptFile == null)
		{
			return null;
		}

		final PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(scriptFile);
		if(!(psiFile instanceof GroovyFile))
		{
			return null;
		}

		final GroovyFile groovyFile = (GroovyFile) psiFile;
		if(groovyFile.isScript())
		{
			return GroovyScriptUtil.getScriptType(groovyFile).getRunner();
		}
		else
		{
			return new DefaultGroovyScriptRunner();
		}
	}

	public void readExternal(Element element) throws InvalidDataException
	{
		PathMacroManager.getInstance(getProject()).expandPaths(element);
		super.readExternal(element);
		readModule(element);
		scriptPath = ExternalizablePath.localPathValue(JDOMExternalizer.readString(element, "path"));
		vmParams = JDOMExternalizer.readString(element, "vmparams");
		scriptParams = JDOMExternalizer.readString(element, "params");
		final String wrk = JDOMExternalizer.readString(element, "workDir");
		if(!".".equals(wrk))
		{
			workDir = ExternalizablePath.localPathValue(wrk);
		}
		isDebugEnabled = Boolean.parseBoolean(JDOMExternalizer.readString(element, "debug"));
		envs.clear();
		JDOMExternalizer.readMap(element, envs, null, "env");
	}

	public void writeExternal(Element element) throws WriteExternalException
	{
		super.writeExternal(element);
		writeModule(element);
		JDOMExternalizer.write(element, "path", ExternalizablePath.urlValue(scriptPath));
		JDOMExternalizer.write(element, "vmparams", vmParams);
		JDOMExternalizer.write(element, "params", scriptParams);
		JDOMExternalizer.write(element, "workDir", ExternalizablePath.urlValue(workDir));
		JDOMExternalizer.write(element, "debug", isDebugEnabled);
		JDOMExternalizer.writeMap(element, envs, null, "env");
		PathMacroManager.getInstance(getProject()).collapsePathsRecursively(element);
	}

	public RunProfileState getState(@Nonnull Executor executor, @Nonnull ExecutionEnvironment environment) throws ExecutionException
	{
		final VirtualFile script = getScriptFile();
		if(script == null)
		{
			throw new CantRunException("Cannot find script " + scriptPath);
		}

		final GroovyScriptRunner scriptRunner = findConfiguration();
		if(scriptRunner == null)
		{
			throw new CantRunException("Unknown script type " + scriptPath);
		}

		final Module module = getModule();
		if(!scriptRunner.ensureRunnerConfigured(module, this, executor, getProject()))
		{
			return null;
		}

		final boolean tests = ProjectRootManager.getInstance(getProject()).getFileIndex().isInTestSourceContent(script);

		final JavaCommandLineState state = new JavaCommandLineState(environment)
		{
			@Nonnull
			@Override
			protected OSProcessHandler startProcess() throws ExecutionException
			{
				final OSProcessHandler handler = super.startProcess();
				handler.setShouldDestroyProcessRecursively(true);
				if(scriptRunner.shouldRefreshAfterFinish())
				{
					handler.addProcessListener(new ProcessAdapter()
					{
						@Override
						public void processTerminated(ProcessEvent event)
						{
							if(!ApplicationManager.getApplication().isDisposed())
							{
								VirtualFileManager.getInstance().asyncRefresh(null);
							}
						}
					});
				}

				return handler;
			}

			protected OwnJavaParameters createJavaParameters() throws ExecutionException
			{
				OwnJavaParameters params = createJavaParametersWithSdk(module);
				ProgramParametersUtil.configureConfiguration(params, GroovyScriptRunConfiguration.this);
				scriptRunner.configureCommandLine(params, module, tests, script, GroovyScriptRunConfiguration.this);

				return params;
			}
		};

		state.setConsoleBuilder(TextConsoleBuilderFactory.getInstance().createBuilder(getProject()));
		return state;
	}

	public void setScriptParameters(String scriptParameters)
	{
		scriptParams = scriptParameters;
	}

	@Override
	public RefactoringElementListener getRefactoringElementListener(PsiElement element)
	{
		if(scriptPath == null || !scriptPath.equals(getPathByElement(element)))
		{
			return null;
		}

		final PsiClass classToRun = GroovyRunnerUtil.getRunningClass(element);

		if(element instanceof GroovyFile)
		{
			return new RefactoringElementAdapter()
			{
				@Override
				protected void elementRenamedOrMoved(@Nonnull PsiElement newElement)
				{
					if(newElement instanceof GroovyFile)
					{
						GroovyFile file = (GroovyFile) newElement;
						setScriptPath(file.getVirtualFile().getPath());

						final PsiClass newClassToRun = GroovyRunnerUtil.getRunningClass(newElement);
						if(newClassToRun instanceof GroovyScriptClass)
						{
							setName(GroovyRunnerUtil.getConfigurationName(file.getScriptClass(), getConfigurationModule()));
						}
					}
				}

				@Override
				public void undoElementMovedOrRenamed(@Nonnull PsiElement newElement, @Nonnull String oldQualifiedName)
				{
					elementRenamedOrMoved(newElement);
				}
			};
		}
		else if(element instanceof PsiClass && element.getManager().areElementsEquivalent(element, classToRun))
		{
			return new RefactoringElementAdapter()
			{
				@Override
				protected void elementRenamedOrMoved(@Nonnull PsiElement newElement)
				{
					setName(((PsiClass) newElement).getName());
				}

				@Override
				public void undoElementMovedOrRenamed(@Nonnull PsiElement newElement, @Nonnull String oldQualifiedName)
				{
					elementRenamedOrMoved(newElement);
				}
			};
		}
		return null;
	}

	@Nullable
	private static String getPathByElement(@Nonnull PsiElement element)
	{
		PsiFile file = element.getContainingFile();
		if(file == null)
		{
			return null;
		}
		VirtualFile vfile = file.getVirtualFile();
		if(vfile == null)
		{
			return null;
		}
		return vfile.getPath();
	}

	public static OwnJavaParameters createJavaParametersWithSdk(@Nullable Module module)
	{
		OwnJavaParameters params = new OwnJavaParameters();
		params.setCharset(null);

		if(module != null)
		{
			final Sdk sdk = ModuleUtilCore.getSdk(module, JavaModuleExtension.class);
			if(sdk != null)
			{
				params.setJdk(sdk);
			}
		}
		if(params.getJdk() == null)
		{
			params.setJdk(new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome()));
		}
		return params;
	}

	@javax.annotation.Nullable
	private VirtualFile getScriptFile()
	{
		if(scriptPath == null)
		{
			return null;
		}
		return LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(scriptPath));
	}

	@Nullable
	private PsiClass getScriptClass()
	{
		final VirtualFile scriptFile = getScriptFile();
		if(scriptFile == null)
		{
			return null;
		}
		final PsiFile file = PsiManager.getInstance(getProject()).findFile(scriptFile);
		return GroovyRunnerUtil.getRunningClass(file);
	}

	public SettingsEditor<? extends RunConfiguration> getConfigurationEditor()
	{
		return new GroovyRunConfigurationEditor();
	}

	@Override
	public void checkConfiguration() throws RuntimeConfigurationException
	{
		super.checkConfiguration();
		final PsiClass toRun = getScriptClass();
		if(toRun == null)
		{
			throw new RuntimeConfigurationWarning(GroovyBundle.message("class.does.not.exist"));
		}
		if(toRun instanceof GrTypeDefinition)
		{
			if(!GroovyRunnerUtil.canBeRunByGroovy(toRun))
			{
				throw new RuntimeConfigurationWarning(GroovyBundle.message("class.can't be executed"));
			}
		}
		else if(!(toRun instanceof GroovyScriptClass))
		{
			throw new RuntimeConfigurationWarning(GroovyBundle.message("script.file.is.not.groovy.file"));
		}
	}

	@Override
	public void setVMParameters(String value)
	{
		vmParams = value;
	}

	@Override
	public String getVMParameters()
	{
		return vmParams;
	}

	@Override
	public boolean isAlternativeJrePathEnabled()
	{
		throw new UnsupportedOperationException();
	}

	@Override
	public void setAlternativeJrePathEnabled(boolean enabled)
	{
		throw new UnsupportedOperationException();
	}

	@Override
	public String getAlternativeJrePath()
	{
		throw new UnsupportedOperationException();
	}

	@Override
	public void setAlternativeJrePath(String path)
	{
		throw new UnsupportedOperationException();
	}

	@Override
	public String getRunClass()
	{
		return null;
	}

	@Override
	public String getPackage()
	{
		return null;
	}

	@Override
	public void setProgramParameters(@javax.annotation.Nullable String value)
	{
		LOG.error("Don't add program parameters to Groovy script run configuration. Use Script parameters instead");
	}

	@Override
	public String getProgramParameters()
	{
		return null;
	}

	@Nullable
	public String getScriptParameters()
	{
		return scriptParams;
	}

	@Override
	public void setWorkingDirectory(@javax.annotation.Nullable String value)
	{
		workDir = value;
	}

	@Override
	public String getWorkingDirectory()
	{
		return workDir;
	}

	@Override
	public void setEnvs(@Nonnull Map<String, String> envs)
	{
		this.envs.clear();
		this.envs.putAll(envs);
	}

	@Nonnull
	@Override
	public Map<String, String> getEnvs()
	{
		return envs;
	}

	@Override
	public void setPassParentEnvs(boolean passParentEnvs)
	{
		this.passParentEnv = passParentEnvs;
	}

	@Override
	public boolean isPassParentEnvs()
	{
		return passParentEnv;
	}

	public boolean isDebugEnabled()
	{
		return isDebugEnabled;
	}

	public void setDebugEnabled(boolean debugEnabled)
	{
		isDebugEnabled = debugEnabled;
	}

	@Nullable
	public String getScriptPath()
	{
		return scriptPath;
	}

	public void setScriptPath(@Nullable String scriptPath)
	{
		this.scriptPath = scriptPath;
	}
}


text:
#ifndef GLIBC_TDEP_H
#define GLIBC_TDEP_H

struct gdbarch;

extern CORE_ADDR glibc_skip_solib_resolver (struct gdbarch *gdbarch,
					    CORE_ADDR);

#endif /* glibc-tdep.h */

redpajama_set_name: RedPajamaGithub


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;

namespace TTC2017.SmartGrids.SubstationStandard.Enumerations
{

    public class DirectionModeKindConverter : System.ComponentModel.TypeConverter
    {

        public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType)
        {
            return (sourceType == typeof(string));
        }

        public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType)
        {
            return (destinationType == typeof(string));
        }

        public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if ((value == null))
            {
                return default(DirectionModeKind);
            }
            string valueString = value.ToString();
            if ((valueString == "nonDirectional"))
            {
                return DirectionModeKind.NonDirectional;
            }
            if ((valueString == "forward"))
            {
                return DirectionModeKind.Forward;
            }
            if ((valueString == "reverse"))
            {
                return DirectionModeKind.Reverse;
            }
            return default(DirectionModeKind);
        }

        public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType)
        {
            if ((value == null))
            {
                return null;
            }
            DirectionModeKind valueCasted = ((DirectionModeKind)(value));
            if ((valueCasted == DirectionModeKind.NonDirectional))
            {
                return "nonDirectional";
            }
            if ((valueCasted == DirectionModeKind.Forward))
            {
                return "forward";
            }
            if ((valueCasted == DirectionModeKind.Reverse))
            {
                return "reverse";
            }
            throw new ArgumentOutOfRangeException("value");
        }
    }
}


text:
package com.hazelcast.internal.cluster.impl.operations;

import com.hazelcast.cluster.ClusterState;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.internal.cluster.impl.ClusterDataSerializerHook;
import com.hazelcast.internal.cluster.impl.ClusterServiceImpl;
import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.impl.AllowedDuringPassiveState;
import com.hazelcast.spi.impl.NodeEngineImpl;

import static com.hazelcast.internal.util.ThreadUtil.createThreadName;

public class ShutdownNodeOp extends AbstractClusterOperation implements AllowedDuringPassiveState {

    @Override
    public void run() {
        final ClusterServiceImpl clusterService = getService();
        final ILogger logger = getLogger();

        final ClusterState clusterState = clusterService.getClusterState();

        if (clusterState == ClusterState.PASSIVE) {
            NodeEngineImpl nodeEngine = (NodeEngineImpl) getNodeEngine();
            if (nodeEngine.isRunning()) {
                logger.info("Shutting down node in cluster passive state. Requested by: " + getCallerAddress());
                new Thread(() -> {
                    Node node = nodeEngine.getNode();
                    node.hazelcastInstance.getLifecycleService().shutdown();
                }, createThreadName(nodeEngine.getHazelcastInstance().getName(), ".clusterShutdown")).start();
            } else {
                logger.info("Node is already shutting down. NodeState: " + nodeEngine.getNode().getState());
            }
        } else {
            logger.severe("Can not shut down node because cluster is in " + clusterState + " state. Requested by: "
                    + getCallerAddress());
        }
    }

    @Override
    public int getClassId() {
        return ClusterDataSerializerHook.SHUTDOWN_NODE;
    }
}


text:
package reshapes.drawing

import reshapes.figures.Shape
import rescala._

abstract class Command {
  def execute(shapes: List[Shape]): List[Shape]

  def revert(shapes: List[Shape]): List[Shape]

  def description: String
}

/**
 * Deletes a given shape
 */
class DeleteShape(shapeToDelete: Shape) extends Command {
  override def execute(shapes: List[Shape]) =
    shapes filterNot (_ == shapeToDelete)

  override def revert(shapes: List[Shape]) =
    shapeToDelete :: shapes

  override def description = "Delete %s".format(shapeToDelete)
}

/**
 * Creates a new shape
 */
class CreateShape(shapeToCreate: Shape) extends Command {
  override def execute(shapes: List[Shape]) =
    shapeToCreate :: shapes

  override def revert(shapes: List[Shape]) =
    shapes filterNot (_ == shapeToCreate)

  override def description = "Create %s".format(shapeToCreate)
}

/**
 * Edits a shape, i.e. replaces a shape by a new one
 */
class EditShape(shapeBeforeEdit: Shape, shapeAfterEdit: Shape) extends Command {
  override def execute(shapes: List[Shape]) =
    shapeAfterEdit :: shapes filterNot (_ == shapeBeforeEdit)

  override def revert(shapes: List[Shape]) =
    shapeBeforeEdit :: shapes filterNot (_ == shapeAfterEdit)

  override def description = "Edit %s".format(shapeAfterEdit)
}

/**
 * Adds all shapes of given Events with currently selected Events.
 */
class MergeDrawingSpaces(eventToMerge: DrawingSpaceState) extends Command {
  val eventTitle = eventToMerge.fileName
  val otherShapes = eventToMerge.shapes

  override def execute(shapes: List[Shape]) =
    otherShapes.now ::: shapes

  override def revert(shapes: List[Shape]) =
    shapes filterNot (otherShapes.now contains _)

  override def description = "Merge with %s".format(eventTitle.now)
}


text:
package edu.gemini.spModel.gemini.niri;

import edu.gemini.pot.sp.ISPObservation;
import edu.gemini.pot.sp.SPComponentType;
import edu.gemini.shared.util.immutable.*;
import edu.gemini.skycalc.Angle;
import edu.gemini.spModel.config.ConfigPostProcessor;
import edu.gemini.spModel.config.injector.ConfigInjector;
import edu.gemini.spModel.config.injector.obswavelength.ObsWavelengthCalc2;
import edu.gemini.spModel.config2.Config;
import edu.gemini.spModel.config2.ConfigSequence;
import edu.gemini.spModel.config2.ItemKey;
import edu.gemini.spModel.core.Site;
import edu.gemini.spModel.data.ISPDataObject;
import edu.gemini.spModel.data.config.DefaultParameter;
import edu.gemini.spModel.data.config.DefaultSysConfig;
import edu.gemini.spModel.data.config.ISysConfig;
import edu.gemini.spModel.data.config.StringParameter;
import edu.gemini.spModel.data.property.PropertyProvider;
import edu.gemini.spModel.data.property.PropertySupport;
import edu.gemini.spModel.gemini.altair.AltairParams;
import edu.gemini.spModel.gemini.altair.InstAltair;
import edu.gemini.spModel.gemini.calunit.calibration.CalConfigBuilderUtil;
import edu.gemini.spModel.gemini.calunit.smartgcal.CalibrationKey;
import edu.gemini.spModel.gemini.calunit.smartgcal.CalibrationKeyProvider;
import edu.gemini.spModel.gemini.calunit.smartgcal.keys.CalibrationKeyImpl;
import edu.gemini.spModel.gemini.calunit.smartgcal.keys.ConfigKeyNiri;
import edu.gemini.spModel.gemini.niri.Niri.*;
import edu.gemini.spModel.guide.GuideProbe;
import edu.gemini.spModel.guide.GuideProbeProvider;
import edu.gemini.spModel.guide.GuideProbeUtil;
import edu.gemini.spModel.obs.plannedtime.CommonStepCalculator;
import edu.gemini.spModel.obs.plannedtime.ExposureCalculator;
import edu.gemini.spModel.obs.plannedtime.PlannedTime;
import edu.gemini.spModel.obs.plannedtime.PlannedTime.CategorizedTime;
import edu.gemini.spModel.obs.plannedtime.PlannedTime.CategorizedTimeGroup;
import edu.gemini.spModel.obs.plannedtime.PlannedTime.Category;
import edu.gemini.spModel.obs.plannedtime.PlannedTime.StepCalculator;
import edu.gemini.spModel.obscomp.InstConfigInfo;
import edu.gemini.spModel.obscomp.SPInstObsComp;
import edu.gemini.spModel.pio.ParamSet;
import edu.gemini.spModel.pio.Pio;
import edu.gemini.spModel.pio.PioFactory;
import edu.gemini.spModel.seqcomp.SeqConfigNames;

import java.beans.PropertyDescriptor;

import java.util.*;

import static edu.gemini.spModel.seqcomp.SeqConfigNames.INSTRUMENT_KEY;

/**
 * The NIRI instrument.
 */
public final class InstNIRI extends SPInstObsComp implements PropertyProvider, GuideProbeProvider, StepCalculator, CalibrationKeyProvider, ConfigPostProcessor {

    // for serialization
    private static final long serialVersionUID = 2L;

    /**
     * Updated version for changes in 2008B *
     */
    private static final String VERSION = "2007B-1";

    /**
     * This obs component's SP type.
     */
    public static final SPComponentType SP_TYPE =
            SPComponentType.INSTRUMENT_NIRI;

    public static final double DEF_EXPOSURE_TIME = 60.0;
    public static int DEF_FASTMODE_EXPOSURES = 1;
    public static final String INSTRUMENT_NAME_PROP = "NIRI";

    // Properties
    public static final PropertyDescriptor BEAM_SPLITTER_PROP;
    public static final PropertyDescriptor CAMERA_PROP;
    public static final PropertyDescriptor COADDS_PROP;
    public static final PropertyDescriptor DISPERSER_PROP;
    public static final PropertyDescriptor EXPOSURE_TIME_PROP;
    public static final PropertyDescriptor FILTER_PROP;
    public static final PropertyDescriptor FOCUS_PROP;
    public static final PropertyDescriptor MASK_PROP;
    public static final PropertyDescriptor POS_ANGLE_PROP;
    public static final PropertyDescriptor READ_MODE_PROP;
    public static final PropertyDescriptor BUILTIN_ROI_PROP;
    public static final PropertyDescriptor WELL_DEPTH_PROP;
    public static final PropertyDescriptor FAST_MODE_PROP;
    public static final ItemKey FAST_MODE_KEY = new ItemKey(INSTRUMENT_KEY, "fastModeExposures");

    private static final Map<String, PropertyDescriptor> PRIVATE_PROP_MAP = new TreeMap<>();
    public static final Map<String, PropertyDescriptor> PROPERTY_MAP = Collections.unmodifiableMap(PRIVATE_PROP_MAP);

    private static PropertyDescriptor initProp(String propName, boolean query, boolean iter) {
        PropertyDescriptor pd;
        pd = PropertySupport.init(propName, InstNIRI.class, query, iter);
        PRIVATE_PROP_MAP.put(pd.getName(), pd);
        return pd;
    }

    static {
        final boolean query_yes = true;
        final boolean iter_yes = true;
        final boolean query_no = false;
        final boolean iter_no = false;

        BEAM_SPLITTER_PROP = initProp("beamSplitter", query_yes, iter_yes);
        BUILTIN_ROI_PROP = initProp(BuiltinROI.KEY.getName(), query_no, iter_yes);
        CAMERA_PROP = initProp("camera", query_yes, iter_yes);
        COADDS_PROP = initProp("coadds", query_no, iter_yes);
        DISPERSER_PROP = initProp("disperser", query_yes, iter_yes);
        EXPOSURE_TIME_PROP = initProp("exposureTime", query_no, iter_yes);
        FILTER_PROP = initProp(Filter.KEY.getName(), query_yes, iter_yes);
        FOCUS_PROP = initProp("focus", query_no, iter_yes);
        MASK_PROP = initProp("mask", query_yes, iter_yes);
        POS_ANGLE_PROP = initProp("posAngle", query_no, iter_no);
        READ_MODE_PROP = initProp(ReadMode.KEY.getName(), query_yes, iter_yes);
        WELL_DEPTH_PROP = initProp("wellDepth", query_no, iter_no);
        FAST_MODE_PROP = initProp(FAST_MODE_KEY.getName(), query_no, iter_yes);
    }

    private Camera _camera = Camera.DEFAULT;
    private Disperser _disperser = Disperser.DEFAULT;
    private Mask _mask = Mask.DEFAULT;
    private Filter _filter = Filter.DEFAULT;
    private BeamSplitter _splitter = BeamSplitter.DEFAULT;
    private ReadMode _readMode = ReadMode.DEFAULT;
    private WellDepth _wellDepth = WellDepth.DEFAULT;
    private BuiltinROI _builtinROI = BuiltinROI.DEFAULT;
    // The number of fast mode reads
    private int _fastModeExposures = DEF_FASTMODE_EXPOSURES;

    public InstNIRI() {
        super(SP_TYPE);
        // Override the default exposure time
        _exposureTime = DEF_EXPOSURE_TIME;
        setVersion(VERSION);
    }

    /**
     * Implementation of the clone method.
     */
    public Object clone() {
        // No problems cloning here since private variables are immutable
        return super.clone();
    }

    @Override
    public Set<Site> getSite() {
        return Site.SET_GN;
    }

    public Map<String, PropertyDescriptor> getProperties() {
        return PROPERTY_MAP;
    }

    public String getPhaseIResourceName() {
        return "gemNIRI";
    }

    public enum Mode {
        imaging,
        spectroscopy,;

        private static Mode getMode(InstNIRI niri) {
            return niri._disperser == Disperser.NONE ? imaging : spectroscopy;
        }
    }

    public Mode getMode() {
        return Mode.getMode(this);
    }

    private static class SetupTimeKey {
        private final Mode _mode;
        private final AltairParams.Mode _altairMode;

        SetupTimeKey(Mode mode) {
            if (mode == null) throw new IllegalArgumentException("mode must not be null");
            _mode = mode;
            _altairMode = null;
        }

        SetupTimeKey(Mode mode, AltairParams.Mode altairMode) {
            if (mode == null) throw new IllegalArgumentException("mode must not be null");
            if (altairMode == null) throw new IllegalArgumentException("altair mode must not be null");
            _mode = mode;
            _altairMode = altairMode;
        }

        public boolean equals(Object other) {
            if (!(other instanceof SetupTimeKey)) return false;
            SetupTimeKey that = (SetupTimeKey) other;
            return _mode == that._mode && (_altairMode == that._altairMode);
        }

        public int hashCode() {
            if (_altairMode != null) {
                return 37 * _mode.hashCode() + _altairMode.hashCode();
            } else {
                return _mode.hashCode();
            }
        }
    }

    public static double getFilterChangeOverheadSec() {
        return 30.0;
    }

    private static final Map<SetupTimeKey, Double> SETUP_TIME = new HashMap<>();

    static {
        SETUP_TIME.put(new SetupTimeKey(Mode.imaging), 6 * 60.);
        SETUP_TIME.put(new SetupTimeKey(Mode.imaging, AltairParams.Mode.NGS), 10 * 60.);
        SETUP_TIME.put(new SetupTimeKey(Mode.imaging, AltairParams.Mode.NGS_FL), 10 * 60.);
        SETUP_TIME.put(new SetupTimeKey(Mode.imaging, AltairParams.Mode.LGS), 15 * 60.);
        SETUP_TIME.put(new SetupTimeKey(Mode.imaging, AltairParams.Mode.LGS_P1), 15 * 60.);
        SETUP_TIME.put(new SetupTimeKey(Mode.imaging, AltairParams.Mode.LGS_OI), 15 * 60.); // not really supported
        SETUP_TIME.put(new SetupTimeKey(Mode.spectroscopy), 13 * 60.);
        SETUP_TIME.put(new SetupTimeKey(Mode.spectroscopy, AltairParams.Mode.NGS), 20 * 60.);
        SETUP_TIME.put(new SetupTimeKey(Mode.spectroscopy, AltairParams.Mode.NGS_FL), 20 * 60.);
        SETUP_TIME.put(new SetupTimeKey(Mode.spectroscopy, AltairParams.Mode.LGS), 25 * 60.);
        SETUP_TIME.put(new SetupTimeKey(Mode.spectroscopy, AltairParams.Mode.LGS_P1), 25 * 60.);
        SETUP_TIME.put(new SetupTimeKey(Mode.spectroscopy, AltairParams.Mode.LGS_OI), 25 * 60.); // not really supported
    }

    public static double getSetupTime(Mode mode) {
        return SETUP_TIME.get(new SetupTimeKey(mode));
    }

    public static double getSetupTime(Mode mode, AltairParams.Mode altairMode) {
        return SETUP_TIME.get(new SetupTimeKey(mode, altairMode));
    }

    /**
     * Return the setup time in seconds before observing can begin.
     */
    public double getSetupTime(ISPObservation obs) {
        // OT-243: 10 and 20 min
        // OT-470:
        //     NIRI + Altair imaging setup time should be 15 min
        //     NIRI + Altair spectroscopy setup should be 30 min
        //     NIRI spectroscopy setup time should add an extra 10 min for every
        //        additional hour of integration (for recentering in the slit)

        //SCT-219/OT-637: Add additional overhead for acquisitions with LGS

        // Update for SCT-275.  New values for the 6 different combinations of
        // imaging/spectroscopy vs. no AO/natural GS/laser GS.  Since this
        // crap gets confusing, I made a SETUP_TIME table to just lookup the
        // value.

        final Mode mode = getMode();
        final InstAltair altair = InstAltair.lookupAltair(obs);
        return (altair == null) ? getSetupTime(mode) : getSetupTime(mode, altair.getMode());
    }

    @Override
    public CategorizedTimeGroup calc(final Config cur, final Option<Config> prev) {
        final Collection<CategorizedTime> times = new ArrayList<>();

        // Add filter change overhead if necessary.
        if (PlannedTime.isUpdated(cur, prev, Filter.KEY)) {
            times.add(CategorizedTime.fromSeconds(Category.CONFIG_CHANGE, getFilterChangeOverheadSec(), "Filter"));
        }

        // Add readout time.
        final int coadds = ExposureCalculator.instance.coadds(cur);
        final ReadMode readMode = (ReadMode) cur.getItemValue(ReadMode.KEY);
        final BuiltinROI roi = (BuiltinROI) cur.getItemValue(BuiltinROI.KEY);

        final Option<NiriReadoutTime> nrt = NiriReadoutTime.lookup(roi, readMode);
        nrt.foreach(niriReadoutTime -> {
            times.add(CategorizedTime.fromSeconds(Category.DHS_WRITE, niriReadoutTime.dhsWrite));
            times.add(CategorizedTime.fromSeconds(Category.READOUT, niriReadoutTime.getReadout(coadds)));
        });

        // Add exposure time
        final double exp = ExposureCalculator.instance.exposureTimeSec(cur);
        final int fast = (Integer) cur.getItemValue(FAST_MODE_KEY);
        final double secs = fast * exp * coadds;
        times.add(CategorizedTime.fromSeconds(Category.EXPOSURE, secs));

        return CommonStepCalculator.instance.calc(cur, prev).addAll(times);
    }

    /**
     * Return the science area based upon the current camera.
     *
     * @return an array giving the size of the detector in arcsec
     */
    public double[] getScienceArea() {
        // If a mask has been applied, shrink the width.
        // The size depends upon the selected camera.
        // Index 0 is width, 1 is length/height

        final ROIDescription roi = _builtinROI.getROIDescription();
        final Mask m = getMask();
        final double height = _getCorrectHeight(m, roi);
        double width = height;
        if (m != Mask.MASK_IMAGING && m != Mask.PINHOLE_MASK) {
            // must be a slit
            width = m.getWidth();
        } else if (_builtinROI == BuiltinROI.SPEC_1024_512) {
            width *= 2.; // XXX This would seem to be a special case...
        }
        return new double[]{width, height};
    }

    /**
     * A private method to return the minimum size for the height based upon
     * the BeamSplitter or Camera
     *

     * The algorithm is to get the height of the camera and beamsplitter and
     * use the smaller of the two.  The only trick is that beamsplitter can be
     * set to SAME_AS_CAMERA, which means that the beamsplitter can't always
     * know its height and needs to know the camera too.
     */
    private double _getCorrectHeight(Mask m, ROIDescription roi) {
        Camera c = getCamera();
        double cheight = c.getScienceAreaHeight(roi);
        // Must pass Camera to BeamSplitter to handle the SAME_AS_CAMERA option.
        double bheight = getBeamSplitter().getScienceAreaHeight(c, roi);
        double height = (cheight < bheight) ? cheight : bheight;

        // Else it's spectroscopic mode so use the height of the mask too
        if (m != Mask.MASK_IMAGING && m != Mask.PINHOLE_MASK) {
            double mheight = m.getHeight(roi);
            height = (mheight < height) ? mheight : height;
        }
        return height;
    }

    /**
     * Return the Camera as a {@link Niri.Camera Camera }
     * object.
     */
    public Camera getCamera() {
        return _camera;
    }

    /**
     * Set the camera.
     */
    public void setCamera(Camera newValue) {
        Camera oldValue = getCamera();
        if (oldValue != newValue) {
            _camera = newValue;
            firePropertyChange(CAMERA_PROP.getName(), oldValue, newValue);
        }
    }

    /**
     * Set the camera with a String.
     */
    private void _setCamera(String name) {
        Camera oldValue = getCamera();
        setCamera(Camera.getCamera(name, oldValue));
    }

    /**
     * Get the disperser.
     */
    public Disperser getDisperser() {
        return _disperser;
    }

    /**
     * Set the disperser.
     */
    public void setDisperser(Disperser newValue) {
        Disperser oldValue = getDisperser();
        if (oldValue != newValue) {
            _disperser = newValue;
            firePropertyChange(DISPERSER_PROP.getName(), oldValue, newValue);
        }
    }

    /**
     * Set the disperser with a String.
     */
    private void _setDisperser(String name) {
        Disperser oldValue = getDisperser();
        setDisperser(Disperser.getDisperser(name, oldValue));
    }

    /**
     * Get the beam splitter.
     */
    public BeamSplitter getBeamSplitter() {
        return _splitter;
    }

    /**
     * Set the beam splitter.
     */
    public void setBeamSplitter(BeamSplitter newValue) {
        BeamSplitter oldValue = getBeamSplitter();
        if (oldValue != newValue) {
            _splitter = newValue;
            firePropertyChange(BEAM_SPLITTER_PROP.getName(), oldValue, newValue);
        }
    }

    /**
     * Set the beam splitter with a String.
     */
    private void _setBeamSplitter(String name) {
        BeamSplitter oldValue = getBeamSplitter();
        setBeamSplitter(BeamSplitter.getBeamSplitter(name, oldValue));
    }

    /**
     * Get the detector read mode.
     */
    public ReadMode getReadMode() {
        return _readMode;
    }

    /**
     * Set the read mode.
     */
    public void setReadMode(ReadMode newValue) {
        ReadMode oldValue = getReadMode();
        if (oldValue != newValue) {
            _readMode = newValue;
            firePropertyChange(READ_MODE_PROP.getName(), oldValue, newValue);
        }
    }

    /**
     * Set the read mode with a String.
     */
    private void _setReadMode(String name) {
        ReadMode oldValue = getReadMode();
        setReadMode(ReadMode.getReadMode(name, oldValue));
    }

    /**
     * Get the detector well depth.
     */
    public WellDepth getWellDepth() {
        return _wellDepth;
    }

    /**
     * Set the well depth.
     */
    public void setWellDepth(WellDepth newValue) {
        WellDepth oldValue = getWellDepth();
        if (oldValue != newValue) {
            _wellDepth = newValue;
            firePropertyChange(WELL_DEPTH_PROP.getName(), oldValue, newValue);
        }
    }

    /**
     * Set the well depth with a String.
     */
    private void _setWellDepth(String name) {
        WellDepth oldValue = getWellDepth();
        setWellDepth(WellDepth.getWellDepth(name, oldValue));
    }

    /**
     * Get the mask.
     */
    public Mask getMask() {
        return _mask;
    }

    /**
     * Set the mask.
     */
    public void setMask(Mask newValue) {
        Mask oldValue = getMask();
        if (oldValue != newValue) {
            _mask = newValue;
            firePropertyChange(MASK_PROP.getName(), oldValue, newValue);
        }
    }

    /**
     * Set the mask.
     */
    private void _setMask(String name) {
        Mask oldValue = getMask();
        setMask(Mask.getMask(name, oldValue));
    }

    /**
     * Get the filter.
     */
    public Filter getFilter() {
        return _filter;
    }

    /**
     * Set the filter.
     */
    public void setFilter(Filter newValue) {
        Filter oldValue = getFilter();
        if (oldValue != newValue) {
            _filter = newValue;
            firePropertyChange(FILTER_PROP.getName(), oldValue, newValue);
        }
    }

    /**
     * Get the filter index, going through both filter lists to match
     * the code.
     */
//    public int getFilterIndex() {
//        Filter f = getFilter();
//        return f.ordinal();
//    }

    /**
     * Set the filter. This method is needed as public by the NIRI
     * editor which currentl sets things via Strings.
     */
    private void _setFilter(String name) {
        Filter oldValue = getFilter();
        setFilter(Filter.getFilter(name, oldValue));
    }

    /**
     * Set the mode for the builtin ROI.  The default is full size of the
     * detector.
     */
    public void setBuiltinROI(BuiltinROI newValue) {
        BuiltinROI oldValue = getBuiltinROI();
        if (newValue != oldValue) {
            _builtinROI = newValue;
            firePropertyChange(BUILTIN_ROI_PROP.getName(), oldValue, newValue);
        }
    }

    /**
     * Set the builtin ROI with a String.
     */
    private void _setBuiltinROI(String name) {
        BuiltinROI oldValue = getBuiltinROI();
        setBuiltinROI(BuiltinROI.getBuiltinROI(name, oldValue));
    }

    /**
     * Return the current value for the stage mode.
     */
    public BuiltinROI getBuiltinROI() {
        return _builtinROI;
    }

    /**
     * Return the (read-only, static) value for focus.
     */
    public Focus getFocus() {
        return new Focus();
    }

    public void setFocus(Focus focus) {
        // Required for reflection
    }

    /**
     * Returns the number of fast mode exposures.
     *
     * @return fast mode exposures as an int
     */
    public int getFastModeExposures() {
        return _fastModeExposures;
    }

    /**
     * Set the value for fast mode exposures
     *
     * @param newValue the new value for exposures
     */
    public void setFastModeExposures(int newValue) {
        if (newValue < 1) newValue = 1;
        int oldValue = _fastModeExposures;
        if (newValue != oldValue) {
            _fastModeExposures = newValue;
            firePropertyChange(FAST_MODE_PROP.getName(), oldValue, newValue);
        }
    }

    /**
     * Get the number of fast mode exposures as a String.
     */
    public String getFastModeExposuresAsString() {
        return Integer.toString(_fastModeExposures);
    }

    /**
     * Set the fast mode exposures with a String.
     */
    private void _setFastModeExposures(String newValue) {
        setFastModeExposures(Integer.parseInt(newValue));
    }

    /**
     * Return a parameter set describing the current state of this object.
     */
    public ParamSet getParamSet(PioFactory factory) {
        ParamSet paramSet = super.getParamSet(factory);

        Pio.addParam(factory, paramSet, CAMERA_PROP.getName(), _camera.name());
        Pio.addParam(factory, paramSet, DISPERSER_PROP.getName(), _disperser.name());
        Pio.addParam(factory, paramSet, MASK_PROP.getName(), _mask.name());
        Pio.addParam(factory, paramSet, FILTER_PROP.getName(), _filter.name());
        Pio.addParam(factory, paramSet, BEAM_SPLITTER_PROP.getName(), _splitter.name());
        Pio.addParam(factory, paramSet, READ_MODE_PROP.getName(), _readMode.name());
        Pio.addParam(factory, paramSet, WELL_DEPTH_PROP.getName(), _wellDepth.name());
        Pio.addParam(factory, paramSet, BUILTIN_ROI_PROP.getName(), getBuiltinROI().name());
        Pio.addParam(factory, paramSet, FAST_MODE_PROP.getName(), getFastModeExposuresAsString());

        return paramSet;
    }

    /**
     * Set the state of this object from the given parameter set.
     */
    public void setParamSet(ParamSet paramSet) {
        super.setParamSet(paramSet);

        String v;
        v = Pio.getValue(paramSet, CAMERA_PROP.getName());
        if (v != null) {
            _setCamera(v);
        }
        v = Pio.getValue(paramSet, DISPERSER_PROP.getName());
        if (v != null) {
            _setDisperser(v);
        }
        v = Pio.getValue(paramSet, MASK_PROP.getName());
        if (v != null) {
            _setMask(v);
        }
        v = Pio.getValue(paramSet, FILTER_PROP.getName());
        if (v != null) {
            _setFilter(v);
        }
        v = Pio.getValue(paramSet, BEAM_SPLITTER_PROP.getName());
        if (v != null) {
            _setBeamSplitter(v);
        }
        v = Pio.getValue(paramSet, READ_MODE_PROP.getName());
        if (v != null) {
            _setReadMode(v);
        }
        v = Pio.getValue(paramSet, WELL_DEPTH_PROP.getName());
        if (v != null) {
            _setWellDepth(v);
        }
        v = Pio.getValue(paramSet, BUILTIN_ROI_PROP.getName());
        if (v != null) {
            _setBuiltinROI(v);
        }
        v = Pio.getValue(paramSet, FAST_MODE_PROP.getName());
        if (v != null) {
            _setFastModeExposures(v);
        }
    }

    /**
     * Return the configuration for this component.
     */
    public ISysConfig getSysConfig() {
        ISysConfig sc = new DefaultSysConfig(SeqConfigNames.INSTRUMENT_CONFIG_NAME);

        // Fill in the current values.
        sc.putParameter(StringParameter.getInstance(ISPDataObject.VERSION_PROP, getVersion()));
        sc.putParameter(DefaultParameter.getInstance(FILTER_PROP.getName(), getFilter()));
        sc.putParameter(DefaultParameter.getInstance(MASK_PROP.getName(), getMask()));
        sc.putParameter(DefaultParameter.getInstance(DISPERSER_PROP.getName(), getDisperser()));
        sc.putParameter(DefaultParameter.getInstance(BEAM_SPLITTER_PROP.getName(), getBeamSplitter()));
        sc.putParameter(DefaultParameter.getInstance(READ_MODE_PROP.getName(), getReadMode()));
        sc.putParameter(DefaultParameter.getInstance(WELL_DEPTH_PROP.getName(), getWellDepth()));
        sc.putParameter(DefaultParameter.getInstance(CAMERA_PROP.getName(), getCamera()));
        sc.putParameter(DefaultParameter.getInstance(BUILTIN_ROI_PROP.getName(), getBuiltinROI()));
        sc.putParameter(DefaultParameter.getInstance(FOCUS_PROP.getName(), getFocus()));
        sc.putParameter(DefaultParameter.getInstance(EXPOSURE_TIME_PROP.getName(), getExposureTime()));
        sc.putParameter(DefaultParameter.getInstance(POS_ANGLE_PROP.getName(), getPosAngleDegrees()));
        sc.putParameter(DefaultParameter.getInstance(COADDS_PROP.getName(), getCoadds()));
        sc.putParameter(DefaultParameter.getInstance(FAST_MODE_PROP.getName(), getFastModeExposures()));

        return sc;
    }

    /**
     * Return a list of InstConfigInfo objects describing the instrument's
     * queryable configuration parameters.
     */
    public static List<InstConfigInfo> getInstConfigInfo() {
        List<InstConfigInfo> configInfo = new LinkedList<>();
        configInfo.add(new InstConfigInfo(CAMERA_PROP));
        configInfo.add(new InstConfigInfo(DISPERSER_PROP));
        configInfo.add(new InstConfigInfo(MASK_PROP));
        configInfo.add(new InstConfigInfo(FILTER_PROP));
        configInfo.add(new InstConfigInfo(BEAM_SPLITTER_PROP));
        configInfo.add(new InstConfigInfo(READ_MODE_PROP));
        return configInfo;
    }

    private static Collection<GuideProbe> GUIDE_PROBES = GuideProbeUtil.instance.createCollection(NiriOiwfsGuideProbe.instance);

    public Collection<GuideProbe> getGuideProbes() {
        return GUIDE_PROBES;
    }

    public static final ConfigInjector<String> WAVELENGTH_INJECTOR = ConfigInjector.create(
            new ObsWavelengthCalc2<Disperser, Filter>() {
                public PropertyDescriptor descriptor1() {
                    return DISPERSER_PROP;
                }

                public PropertyDescriptor descriptor2() {
                    return FILTER_PROP;
                }

                public String calcWavelength(Disperser d, Filter f) {
                    return InstNIRI.calcWavelength(d, f);
                }
            }
    );

    public static String calcWavelength(Disperser d, Filter f) {
        return (d == Disperser.NONE) ? f.getWavelengthAsString() : d.getCentralWavelengthAsString();
    }

    @Override public ConfigSequence postProcessSequence(ConfigSequence in) {
        Config[] configs = in.getAllSteps();

        for (Config c : configs) {
            if (CalConfigBuilderUtil.isCalStep(c)) {
                c.putItem(ReadMode.KEY, ReadMode.IMAG_1TO25);
            }
        }

        return new ConfigSequence(configs);
    }

    @Override
    public CalibrationKey extractKey(ISysConfig instrumentConfig) {
        Niri.Disperser disperser = (Niri.Disperser) get(instrumentConfig, InstNIRI.DISPERSER_PROP);
        Niri.Filter filter = (Niri.Filter) get(instrumentConfig, InstNIRI.FILTER_PROP);
        Niri.Mask mask = (Niri.Mask) get(instrumentConfig, InstNIRI.MASK_PROP);
        Niri.Camera camera = (Niri.Camera) get(instrumentConfig, InstNIRI.CAMERA_PROP);
        Niri.BeamSplitter beamSplitter = (Niri.BeamSplitter) get(instrumentConfig, InstNIRI.BEAM_SPLITTER_PROP);

        ConfigKeyNiri config = new ConfigKeyNiri(disperser, filter, mask, camera, beamSplitter);
        return new CalibrationKeyImpl(config);
    }

    @Override public Angle pwfs1VignettingClearance() {
        switch (getCamera()) {
            case F6:     return Angle.arcmins(5.7);
            case F14:    return Angle.arcmins(5.3);
            case F32 :   return Angle.arcmins(4.8);
            case F32_PV: return Angle.arcmins(4.8);
            default:     return super.pwfs1VignettingClearance();
        }
    }

    @Override public Angle pwfs2VignettingClearance() {
        switch (getCamera()) {
            case F6:     return Angle.arcmins(5.2);
            case F14:    return Angle.arcmins(4.8);
            case F32 :   return Angle.arcmins(4.3);
            case F32_PV: return Angle.arcmins(4.3);
            default:     return super.pwfs2VignettingClearance();
        }
    }

}


text:
namespace BookShop.Data.EntityConfiguration
{
    using Microsoft.EntityFrameworkCore;

    using BookShop.Models;
    using Microsoft.EntityFrameworkCore.Metadata.Builders;

    class CategoryConfiguration : IEntityTypeConfiguration<Category>
    {
        public void Configure(EntityTypeBuilder<Category> builder)
        {
            builder.HasKey(e => e.CategoryId);

            builder.Property(e => e.Name)
                .IsRequired(true)
                .IsUnicode(true)
                .HasMaxLength(50);
        }
    }
}


text:
<!DOCTYPE html>

	<title>Procedural textures Library</title>

0

	<canvas id="renderCanvas"></canvas>


text:
#include "XmlRpcResponse.h"

const int XmlRpcResponse::BAD_REQUEST;
const int XmlRpcResponse::INVALID_METHOD;
const int XmlRpcResponse::SERVER_ERROR;

std::string XmlRpcResponse::constructFault(int errCode, const std::string& errMsg) {
  char buf[30];

  sprintf(buf, "%d", errCode);
  std::string ret =
    "<methodResponse>\n"
    "  <fault>\n"
    "    <value>\n"
    "      <struct>\n"
    "        <member>\n"
    "          <name>faultCode</name>\n"
    "          <value><int>";
  ret += buf;
  ret += "</int></value>\n"
    "          </member>\n"
    "        <member>\n"
    "          <name>faultString</name>\n"
    "          <value><string>" + errMsg + "</string></value>\n"
    "          </member>\n"
    "        </struct>\n"
    "      </value>\n"
    "    </fault>\n"
    "  </methodResponse>\n";
  return ret;
} // constructFault

std::string XmlRpcResponse::constructSuccess(const std::string& retVal) {
  std::string r;
  if (retVal.empty()) {
    r =
    "<methodResponse>\n"
    "  </methodResponse>\n";
  }
  else {
    r =
    "<methodResponse>\n"
    "  <params>\n"
    "    <param>\n"
    "      <value>" + retVal + "</value>\n"
    "      </param>\n"
    "    </params>\n"
    "  </methodResponse>\n";
  }
  return r;
} // constructSuccess

void XmlRpcResponse::parseFault(std::istream& in, int& errorCode,
				mace::string& errorString)
  throw(mace::SerializationException) {
  // Assumes the <fault> tag has already been read, does NOT
  // read the </fault> tag at the end
  mace::SerializationUtil::expectTag(in, "<value>");
  mace::SerializationUtil::expectTag(in, "<struct>");
  mace::SerializationUtil::expectTag(in, "<member>");
  mace::SerializationUtil::expectTag(in, "<name>");
  mace::SerializationUtil::expect(in, "faultCode");
  mace::SerializationUtil::expectTag(in, "</name>");
  mace::SerializationUtil::expectTag(in, "<value>");
  mace::deserializeXML_RPC(in, &errorCode, errorCode);
  mace::SerializationUtil::expectTag(in, "</value>");
  mace::SerializationUtil::expectTag(in, "</member>");
  mace::SerializationUtil::expectTag(in, "<member>");
  mace::SerializationUtil::expectTag(in, "<name>");
  mace::SerializationUtil::expect(in, "faultString");
  mace::SerializationUtil::expectTag(in, "</name>");
  mace::SerializationUtil::expectTag(in, "<value>");
  mace::deserializeXML_RPC(in, &errorString, errorString);
  mace::SerializationUtil::expectTag(in, "</value>");
  mace::SerializationUtil::expectTag(in, "</member>");
  mace::SerializationUtil::expectTag(in, "</struct>");
  mace::SerializationUtil::expectTag(in, "</value>");
} // parseFault


text:
#include <pyhrol.h>

struct myClass
{
  typedef std::map<std::string, std::string> strings_t;
  strings_t strings;
};

class PyType: public pyhrol::TypeMap<myClass>, public pyhrol::TypeWrapper<myClass>
{
  PyType()
    : pyhrol::TypeBase<myClass>("MyClass", "help")
  {
  }

  virtual void constructor(myClass &obj, pyhrol::Tuples &_args) const
  {
    PYHROL_AFTER_PARSE_TUPLE(_args)
    PYHROL_AFTER_BUILD_VALUE(_args)

    new (&obj) myClass;

    PYHROL_AFTER_EXECUTE_DEFAULT(_args)
  }

  virtual void destructor(myClass &obj) const
  {
    obj.~myClass();
  }

  virtual void print(std::ostream &os, const myClass &obj) const
  {
    bool delimit = false;
    os << '{';
    for (myClass::strings_t::const_iterator iter = obj.strings.begin(), iter_end = obj.strings.end(); iter != iter_end; iter ++)
    {
      if (delimit)
      {
        os << ", ";
      }
      os << iter->first << " = " << iter->second;
      delimit = true;
    }
    os << '}';
  }
  virtual Py_ssize_t length(const pyhrol::Ptr<const myClass> &obj) const
  {
    return obj->strings.size();
  }

  virtual void get(const pyhrol::Ptr<const myClass> &obj, pyhrol::Tuples &_args) const
  {
    const char *arg;
    long long num;
    std::string res;

    PYHROL_PARSE_TUPLE_1(NULL, _args, arg)
    PYHROL_PARSE_TUPLE_1(NULL, _args, num)
    PYHROL_AFTER_PARSE_TUPLE(_args)
    PYHROL_BUILD_VALUE_1(NULL, _args, res.c_str())
    PYHROL_AFTER_BUILD_VALUE(_args)

    std::ostringstream ostr;
    switch (_args.parsed_variant())
    {
      case 0:
        ostr << arg;
        break;
      case 1:
        ostr << num;
        break;
    }
    res = obj->strings.at(ostr.str());

    PYHROL_AFTER_EXECUTE_DEFAULT(_args)
  }

  virtual void del(const pyhrol::Ptr<myClass> &obj, pyhrol::Tuples &_args) const
  {
    const char *arg;
    long long num;

    PYHROL_PARSE_TUPLE_1(NULL, _args, arg)
    PYHROL_PARSE_TUPLE_1(NULL, _args, num)
    PYHROL_AFTER_PARSE_TUPLE(_args)
    PYHROL_AFTER_BUILD_VALUE(_args)

    std::ostringstream ostr;
    switch (_args.parsed_variant())
    {
      case 0:
        ostr << arg;
        break;
      case 1:
        ostr << num;
        break;
    }

    if (!obj->strings.erase(ostr.str()))
    {
      throw std::out_of_range(std::string("Item \"") + ostr.str() + "\" not found");
    }

    PYHROL_AFTER_EXECUTE_DEFAULT(_args)
  }

  virtual void assign(const pyhrol::Ptr<myClass> &obj, pyhrol::Tuples &_args) const
  {
    const char *key_str, *value_str;
    long long key_num, value_num;

    PYHROL_PARSE_TUPLE_2(NULL, _args, key_str, value_str)
    PYHROL_PARSE_TUPLE_2(NULL, _args, key_str, value_num)
    PYHROL_PARSE_TUPLE_2(NULL, _args, key_num, value_str)
    PYHROL_PARSE_TUPLE_2(NULL, _args, key_num, value_num)
    PYHROL_AFTER_PARSE_TUPLE(_args)
    PYHROL_AFTER_BUILD_VALUE(_args)

    std::ostringstream key, value;
    switch (_args.parsed_variant())
    {
      case 0:
        key << key_str;
        value << value_str;
        break;
      case 1:
        key << key_str;
        value << value_num;
        break;
      case 2:
        key << key_num;
        value << value_str;
        break;
      case 3:
        key << key_num;
        value << value_num;
        break;
    }

    if (!obj->strings.insert(myClass::strings_t::value_type(key.str(), value.str())).second)
    {
      throw std::out_of_range(std::string("Item \"") + key.str() + "\" already exists");
    }

    PYHROL_AFTER_EXECUTE_DEFAULT(_args)
  }

  static void init() __attribute__ ((constructor))
  {
    m_get(new PyType);
  }
};


text:
require "noodall-components-promo-driver/engine"

module NoodallComponentsPromoDriver
end


text:
package com.xorlev.simon.util

import java.lang.String
import java.text.SimpleDateFormat
import java.util.Date
import org.joda.time.{DateTimeZone, DateTime}
import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}
import com.google.common.net.MediaType

/**
 * 2012-11-28
 * @author Michael Rose <elementation@gmail.com>
 */

object HeaderUtil {
  val RFC1123_DATE_PATTERN:String = "EEE, dd MMM yyyy HH:mm:ss zzz"

  def formatDate(timestamp: Long): String = {
    new DateTime(timestamp).withZone(DateTimeZone.UTC).toString(RFC1123_DATE_PATTERN)
  }

  def now(): String = {
    DateTime.now().withZone(DateTimeZone.UTC).toString(RFC1123_DATE_PATTERN)
  }

  // None is 10
  // 1.0 => 10
  // 0.9 => 9
  // More specific is higher
  def parseAccept(accept: String): List[String] = {
    accept.split(",").map(_.trim).reverse.zipWithIndex.map { s =>
      //println(s)
      val parts = s._1.split(";")
      val scoreModifier = if (parts.size > 1) {
        val typeParts = parts(1).split("=").map(_.trim)

        (Option(typeParts(1)).map(_.toDouble).getOrElse(1.0) * 10).ceil.toInt
      } else 10

      (s._1, s._2 + scoreModifier)
    }.toList.sortWith((k1,k2) => k1._2 > k2._2).map(_._1)
  }
}


text:
package in.twizmwaz.cardinal.module.modules.stats;

import in.twizmwaz.cardinal.Cardinal;
import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.chat.ChatConstant;
import in.twizmwaz.cardinal.chat.UnlocalizedChatMessage;
import in.twizmwaz.cardinal.event.CardinalDeathEvent;
import in.twizmwaz.cardinal.event.MatchEndEvent;
import in.twizmwaz.cardinal.event.MatchStartEvent;
import in.twizmwaz.cardinal.event.PlayerChangeTeamEvent;
import in.twizmwaz.cardinal.module.Module;
import in.twizmwaz.cardinal.module.modules.chatChannels.ChatChannelModule;
import in.twizmwaz.cardinal.module.modules.chatChannels.GlobalChannel;
import in.twizmwaz.cardinal.module.modules.matchTimer.MatchTimer;
import in.twizmwaz.cardinal.module.modules.matchTranscript.MatchTranscript;
import in.twizmwaz.cardinal.module.modules.team.TeamModule;
import in.twizmwaz.cardinal.settings.Settings;
import in.twizmwaz.cardinal.util.StringUtils;
import in.twizmwaz.cardinal.util.TeamUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class Stats implements Module {

    private List<MatchTracker> stats;
    private Map<OfflinePlayer, TeamModule> playerTeams = Maps.newHashMap();

    protected Stats() {
        stats = Lists.newArrayList();
    }

    @Override
    public void unload() {
        HandlerList.unregisterAll(this);
    }

    public void add(MatchTracker tracker) {
        stats.add(tracker);
    }

    @EventHandler
    public void onCardinalDeath(CardinalDeathEvent event) {
        this.add(new MatchTracker(event.getPlayer(), event.getKiller(), event.getPlayer().getItemInHand()));
    }

    public int getKillsByPlayer(OfflinePlayer player) {
        int kills = 0;
        if (player == null) return 0;
        for (MatchTracker tracker : this.stats) {
            if (tracker.getKiller() != null && tracker.getKiller().equals(player)) {
                kills++;
            }
        }
        return kills;
    }

    public int getDeathsByPlayer(OfflinePlayer player) {
        int deaths = 0;
        if (player == null) return 0;
        for (MatchTracker tracker : this.stats) {
            if (tracker.getPlayer().equals(player)) {
                deaths++;
            }
        }
        return deaths;
    }

    public int getTotalKills() {
        int kills = 0;
        for (MatchTracker tracker : this.stats) {
            if (tracker.getKiller() != null) {
                kills++;
            }
        }
        return kills;
    }

    public int getTotalDeaths() {
        int deaths = 0;
        for (MatchTracker tracker : this.stats) {
            deaths++;
        }
        return deaths;
    }

    public double getKdByPlayer(OfflinePlayer player) {
        double kd;
        if (player == null) return 0;
        kd = getDeathsByPlayer(player) == 0 ? (double) getKillsByPlayer(player) : (double) getKillsByPlayer(player) / (double) getDeathsByPlayer(player);
        return kd;
    }

    /**
     * Sends player stats to player
     */
    @EventHandler
    public void onMatchEnd(MatchEndEvent event) {
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (Settings.getSettingByName("Stats") != null && Settings.getSettingByName("Stats").getValueByPlayer(player).getValue().equalsIgnoreCase("on")) {
                player.sendMessage(ChatColor.GRAY + "Kills: " + ChatColor.GREEN + getKillsByPlayer(player) + ChatColor.AQUA + " | " + ChatColor.GRAY + "Deaths: " + ChatColor.DARK_RED + getDeathsByPlayer(player) + ChatColor.AQUA + " | " + ChatColor.GRAY + "KD: " + ChatColor.GOLD + (Math.round(getKdByPlayer(player) / 100.0) * 100.0));
            }
        }

        /* if (Cardinal.getInstance().getConfig().getBoolean("html.upload")) {
        	Bukkit.getScheduler().scheduleSyncDelayedTask(GameHandler.getGameHandler().getPlugin(), new Runnable() {
            	public void run() {
                	ChatChannelModule global = GameHandler.getGameHandler().getMatch().getModules().getModule(GlobalChannel.class);
                	global.sendLocalizedMessage(new UnlocalizedChatMessage(ChatColor.GOLD + "{0}", ChatConstant.UI_MATCH_REPORT_UPLOAD.asMessage()));
                	String result = uploadStats();
                	if (result == null || result.contains("error"))
                    	global.sendLocalizedMessage(new UnlocalizedChatMessage(ChatColor.RED + "{0}", ChatConstant.UI_MATCH_REPORT_FAILED.asMessage()));
                	else global.sendLocalizedMessage(new UnlocalizedChatMessage(ChatColor.GREEN + "{0}", ChatConstant.UI_MATCH_REPORT_SUCCESS.asMessage(new UnlocalizedChatMessage(result))));
            	}
        	}, 20);
        } */
    }

    @EventHandler
    public void onPlayerJoinTeam(PlayerChangeTeamEvent event) {
        this.playerTeams.put(event.getPlayer(), event.getNewTeam());
    }

    @EventHandler
    public void onMatchStart(MatchStartEvent event) {
        try {
            File template = new File(GameHandler.getGameHandler().getMatchFile() + "/statistics.html");
            OutputStream out = new FileOutputStream(template);
            IOUtils.copy(GameHandler.getGameHandler().getPlugin().getResource("statistics.html"), out);
            out.close();
        } catch (IOException e) {
            Bukkit.getLogger().warning("Unable to copy template statistics file!");
            e.printStackTrace();
        }
    }

    private File generateStats() throws IOException {
        File file = new File(GameHandler.getGameHandler().getMatchFile() + "/statistics.html");
        Document document = Jsoup.parse(file, "utf-8");
        for (Element element : document.getElementsContainingOwnText("%mapName")) {
            element.text(element.text().replace("%mapName", GameHandler.getGameHandler().getMatch().getLoadedMap().getName()));
        }

        for (Element element : document.getElementsContainingOwnText("%date")) {
            element.text(element.text().replace("%date", new Date().toString()));
        }

        for (Element element : document.getElementsContainingOwnText("%kills")) {
            element.text(element.text().replace("%kills", Integer.toString(getTotalKills())));
        }

        for (Element element : document.getElementsContainingOwnText("%deaths")) {
            element.text(element.text().replace("%deaths", Integer.toString(getTotalDeaths())));
        }

        for (Element element : document.getElementsContainingOwnText("%matchTime")) {
            element.text(element.text().replace("%matchTime", StringUtils.formatTime(GameHandler.getGameHandler().getMatch().getModules().getModule(MatchTimer.class).getEndTime())));
        }

        Element teams = document.getElementById("teams");
        for (TeamModule team : TeamUtils.getTeams()) {
            teams.appendElement("h3").text(team.getName());
            for (Map.Entry<OfflinePlayer, TeamModule> entry : playerTeams.entrySet()) {
                if (entry.getValue() == team) {
                    if (!team.isObserver()) {
                        teams.appendElement("p").text(entry.getKey().getName() + ": Kills: " + getKillsByPlayer(entry.getKey()) + ", Deaths: " + getDeathsByPlayer(entry.getKey()) + ", KD: " + (Math.round(getKdByPlayer(entry.getKey()) / 100.0) * 100.0)).attr("class", "media-body");
                    }
                    else teams.appendElement("p").text(entry.getKey().getName());
                }
            }
        }
        Element transcript = document.getElementById("transcript");
        if (GameHandler.getGameHandler().getMatch().getModules().getModule(MatchTranscript.class).getLog() != null)
            transcript.appendElement("pre").text(GameHandler.getGameHandler().getMatch().getModules().getModule(MatchTranscript.class).getLog());
        Writer writer = new PrintWriter(file);
        writer.write(document.html());
        writer.close();
        return file;
    }

    public String uploadStats() {
        try {
            HttpPost post = new HttpPost("http://m.twizmwaz.in/uploadmatch.php");
            NameValuePair id = new BasicNameValuePair("id", GameHandler.getGameHandler().getMatch().getUuid().toString().replaceAll("-", ""));
            MultipartEntityBuilder fileBuilder = MultipartEntityBuilder.create().addBinaryBody("match", generateStats());
            fileBuilder.addPart(id.getName(), new StringBody(id.getValue(), ContentType.TEXT_HTML));
            post.setEntity(fileBuilder.build());
            HttpClient client = HttpClientBuilder.create().build();
            return EntityUtils.toString(client.execute(post).getEntity());
        } catch (Exception e) {
            Bukkit.getLogger().warning("Unable to upload statistics");
            e.printStackTrace();
            return null;
        }
    }
}


text:
<?php

namespace Barryvdh\Debugbar\DataCollector;

use DebugBar\DataCollector\DataCollector;
use DebugBar\DataCollector\DataCollectorInterface;
use DebugBar\DataCollector\Renderable;

class SessionCollector extends DataCollector implements DataCollectorInterface, Renderable
{
    /** @var  \Symfony\Component\HttpFoundation\Session\SessionInterface|\Illuminate\Contracts\Session\Session $session */
    protected $session;

    /**
     * Create a new SessionCollector
     *
     * @param \Symfony\Component\HttpFoundation\Session\SessionInterface|\Illuminate\Contracts\Session\Session $session
     */
    public function __construct($session)
    {
        $this->session = $session;
    }

    /**
     * {@inheritdoc}
     */
    public function collect()
    {
        $data = [];
        foreach ($this->session->all() as $key => $value) {
            $data[$key] = is_string($value) ? $value : $this->formatVar($value);
        }
        return $data;
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'session';
    }

    /**
     * {@inheritDoc}
     */
    public function getWidgets()
    {
        return [
            "session" => [
                "icon" => "archive",
                "widget" => "PhpDebugBar.Widgets.VariableListWidget",
                "map" => "session",
                "default" => "{}"
            ]
        ];
    }
}


text:
<?xml version="1.0" encoding="windows-1252" ?>
<adfc-config xmlns="http://xmlns.oracle.com/adf/controller" version="1.2">
  <task-flow-definition id="opportunities-createTF">
    <default-activity id="__1">opportunities-create</default-activity>
    <view id="opportunities-create">
      <page>/sample_fragments/opportunities-create.jsff</page>
    </view>
    <use-page-fragments/>
  </task-flow-definition>
</adfc-config>


text: require 'cloud_bit/client'


text:
<?php

namespace Lolart\Bundle\EmbedTagBundle\Converter\XmlText;

use DOMDocument;
use eZ\Publish\Core\FieldType\XmlText\Converter;
use DOMXPath;

/**
 * This converter converts regular video links (e.g. https://youtube.com/watch?<videoId>)
 * to corresponding embed links, to be used in the XSL stylesheet.
 *
 * @author Jérôme Vieilledent <lolautruche@gmail.com>
 */
class VideoPreConverter implements Converter
{
    const CUSTOMTAG_NAMESPACE = 'http://ez.no/namespaces/ezpublish3/custom/';

    /**
     * Array of video options, indexed by vendor identifier (e.g. "youtube", "vimeo").
     * Each entry consists of a hash of options:
     *  - default_width
     *  - default_height
     *  - embed_pattern
     *  - regexp
     *
     * "embed_pattern" is the pattern for the final embed URL. It contains a "$$$VIDEO$$$" token, to be replaced
     * by the video ID.
     *
     * "regexp" is the regular expression used for video ID extraction.
     *
     * @var array
     */
    private $videoProviderOptions;

    public function __construct( array $videoProviderOptions )
    {
        $this->videoProviderOptions = $videoProviderOptions;
    }

    public function convert( DOMDocument $xmlDoc )
    {
        $xpath = new DOMXPath( $xmlDoc );

        foreach ( $this->videoProviderOptions as $identifier => $options )
        {
            $tags = $xpath->query( "//custom[@name='$identifier']" );
            foreach ( $tags as $tag )
            {
                /** @var \DOMElement $tag */
                if ( !$tag->getAttributeNS( self::CUSTOMTAG_NAMESPACE, 'videoWidth' ) )
                {
                    $tag->setAttributeNS( self::CUSTOMTAG_NAMESPACE, 'videoWidth', $options['default_width'] );
                }

                if ( !$tag->getAttributeNS( self::CUSTOMTAG_NAMESPACE, 'videoHeight' ) )
                {
                    $tag->setAttributeNS( self::CUSTOMTAG_NAMESPACE, 'videoHeight', $options['default_height'] );
                }

                preg_match( $options['regexp'], $tag->getAttributeNS( self::CUSTOMTAG_NAMESPACE, 'video' ), $matches );
                if ( isset( $matches['videoId'] ) )
                {
                    $embedLink = str_replace( '$$$VIDEO$$$', $matches['videoId'], $options['embed_pattern'] );
                    $tag->setAttributeNS( self::CUSTOMTAG_NAMESPACE, 'video', $embedLink );
                }
            }
        }
    }
}


text:
package com.swfarm.biz.product.web;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.chain.srv.ChainManagementService;
import com.swfarm.pub.utils.SpringUtils;

public class ImportSaleSuitesController extends AbstractController {

	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) req;
		Map fileMap = multiRequest.getFileMap();
		if (fileMap.values().size() > 0) {
			MultipartFile file = (MultipartFile) fileMap.values().iterator()
					.next();
			String[] originalNames = file.getOriginalFilename().split("\\.");
			// 默认支持Excel 2003
			String type = "xls";
			if (originalNames.length == 2 && StringUtils.isNotEmpty(originalNames[1])) {
				type = originalNames[1];
			}
			importSaleSuites(file.getInputStream(), type);
		}
		return new ModelAndView("redirect:/product/salesuites.shtml");
	}

	private Object getCellValue(Cell cell) {
		Object cellValue = null;
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING:
			cellValue = cell.getRichStringCellValue().getString();
			break;
		case Cell.CELL_TYPE_NUMERIC:
			if (DateUtil.isCellDateFormatted(cell)) {
				cellValue = cell.getDateCellValue();
			} else {
				NumberFormat numberFormat = NumberFormat.getNumberInstance();
				numberFormat.setMinimumFractionDigits(0);
				numberFormat.setGroupingUsed(false);
				cellValue = numberFormat.format(cell.getNumericCellValue());
			}
			break;
		case Cell.CELL_TYPE_BOOLEAN:
			cellValue = cell.getBooleanCellValue();
			break;
		case Cell.CELL_TYPE_FORMULA:
			cellValue = cell.getCellFormula();
			break;
		default:
			cellValue = null;
		}
		return cellValue;
	}

	private void importSaleSuites(InputStream is, String type) {
		try {
			Sheet sheet = null;
			if ("xlsx".equalsIgnoreCase(type)) {
				XSSFWorkbook xb = new XSSFWorkbook(is);
				sheet = xb.getSheetAt(0);
			} else {
				HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
				sheet = wb.getSheetAt(0);
			}
			List<String[]> suiteInfoList = new ArrayList<String[]>();
			int rowIndex = 0;
			for (Row row : sheet) {
				if (rowIndex++ > 0) {
					String[] suiteInfo = new String[9];
					// article number
					Cell articleNumberCell = row.getCell(0);
					if (articleNumberCell != null) {
						Object cellValue = getCellValue(articleNumberCell);
						if (cellValue != null) {
							suiteInfo[0] = cellValue.toString();
						}
					}
					// suite name
					Cell nameCell = row.getCell(1);
					if (nameCell != null) {
						Object cellValue = getCellValue(nameCell);
						if (cellValue != null) {
							suiteInfo[1] = cellValue.toString();
						}
					}
					// status
					Cell statusCell = row.getCell(2);
					if (statusCell != null) {
						Object cellValue = getCellValue(statusCell);
						if (cellValue != null) {
							suiteInfo[2] = cellValue.toString();
						}
					}
					// combination
					Cell combinationCell = row.getCell(3);
					if (combinationCell != null) {
						Object cellValue = getCellValue(combinationCell);
						if (cellValue != null) {
							suiteInfo[3] = cellValue.toString();
						}
					}
					// editor name
					Cell editorNameCell = row.getCell(4);
					if (editorNameCell != null) {
						Object cellValue = getCellValue(editorNameCell);
						if (cellValue != null) {
							suiteInfo[4] = cellValue.toString();
						}
					}
					// enroll date
					Cell enrollDateCell = row.getCell(5);
					if (enrollDateCell != null) {
						Object cellValue = getCellValue(enrollDateCell);
						if (cellValue != null) {
							suiteInfo[5] = cellValue.toString();
						}
					}
					// check article number
					if (StringUtils.isNotEmpty(suiteInfo[0])) {
						suiteInfoList.add(suiteInfo);
					}
				}
			}
			is.close();
			importSaleSuites(suiteInfoList);
		} catch (FileNotFoundException e) {
			logger.warn(e.getMessage(), e);
		} catch (IOException e) {
			logger.warn(e.getMessage(), e);
		}
	}

	private void importSaleSuites(List<String[]> saleSuiteInfoList) {
		ChainManagementService chainManagementService = (ChainManagementService) SpringUtils
				.getBean("chainManagementService");
		for (Iterator<String[]> iter = saleSuiteInfoList.iterator(); iter
				.hasNext();) {
			String[] saleSuiteInfo = iter.next();
			chainManagementService.importSaleSuite(saleSuiteInfo);
		}
	}
}


text:
import Ember from 'ember';
import Constants from 'ember-data-model-maker/utils/constants';

const { Inflector, String } = Ember;

// Converts models/fields to objects that can be represented as JSON
export default function getModelInfo(controller) {
  const models = controller.store.peekAll('domainModel');
  const adapter = controller.get('adapter');
  let fields = [];
  let fieldObject = {};
  let modelObject = {};
  let modelObjects = [];
  let newModelObjects = [];

  controller.set('modelObjects', []);

  models.forEach(function (model, index) {
    fields[index] = [];

    model.get('fields').then(function (currentFields) {
      currentFields.forEach(function (field, i) {
        let fieldName   = field.get('name');
        const fieldType = field.get('type');

        fieldName = (fieldName === '')? '<field name>' : fieldName;

        switch (adapter) {
          case Constants.ADAPTER_ACTIVEMODEL:
            if (fieldType === 'hasMany') {
              fieldName = Ember.Inflector.inflector.singularize(fieldName);
              fieldName = Ember.String.decamelize(fieldName) + '_ids';
            } else if (fieldType === 'belongsTo') {
              fieldName = Ember.String.decamelize(fieldName) + '_id';
            } else {
              fieldName = Ember.String.decamelize(fieldName);
            }
            break;
          case Constants.ADAPTER_REST:
            fieldName = Ember.String.camelize(fieldName);
            break;
          case Constants.ADAPTER_JSONAPI:
            fieldName = Ember.String.dasherize(fieldName);
            break;
        }

        const relatedTo = (fieldType === 'hasMany' || fieldType === 'belongsTo') ? field.get('relatedTo') : null;

        fieldObject = {
          name:             field.get('name'),
          jsonPropertyName: fieldName,
          type:             fieldType,
          relatedTo:        relatedTo
        };

        if (i === currentFields.get('length') - 1) {
          fieldObject.lastField = true;
        }

        fields[index].push(fieldObject);
        fieldObject = {};
      });

      modelObject = {
        name:   model.get('name'),
        fields: fields[index]
      };

      if (index === models.get('length') - 1) {
        modelObject.lastModel = true;
      }

      modelObjects = controller.get('modelObjects');
      if (modelObjects.length) {
        modelObjects.forEach(function (mo) {
          if (mo.name !== modelObject.name) {
            newModelObjects.push(mo);
          }
        });
      }

      // Make a copy of the object and push to array (to fix references -- this is inside a loop)
      newModelObjects.push(JSON.parse(JSON.stringify(modelObject)));

      if (newModelObjects.length) {
        controller.set('modelObjects', newModelObjects);
        newModelObjects = [];
      }
    });
  });
}


text:
package com.java.io.test;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.List;

public class Classroom implements Externalizable {

	private Teacher teacher;

	private List<Student> students;

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeObject(teacher);
		out.writeObject(students);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		this.teacher = (Teacher) in.readObject();
		this.students = (List<Student>) in.readObject();
	}

	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}

	public List<Student> getStudents() {
		return students;
	}

	public void setStudents(List<Student> students) {
		this.students = students;
	}

	@Override
	public String toString() {
		return "Classroom [teacher=" + teacher + ", students=" + students + "]";
	}

}


text:
@interface PodsDummy_Pods_XRoundImage_Tests : NSObject
@end
@implementation PodsDummy_Pods_XRoundImage_Tests
@end


text:
module BatotoRipper
  VERSION = '0.2.1'.freeze
end


text:
namespace postgres {
    ///
    /// \brief Convert complex type to postgres type
    /// \param[in] c Input type
    /// \return Postgres type
    ///
    std::string to_type(const db::column_value_type &c) noexcept;

    ///
    /// \brief Get type from postgres type
    /// \param[in] t Type name
    /// \param[in] size Size of type
    /// \param[in] def Default value
    /// \param[in] _primary_key True if primary key
    /// \param[in] _unique_key True if unique key or part of that
    /// \param[in] _not_null True if can't be null
    /// \return Complex type
    ///
    db::column_value_type from_type(const std::string &t, const size_t size, const std::string &def, const bool _primary_key = false, const bool _unique_key = false, const bool _not_null = false) noexcept;
}


text:
class Salesforce::Product2 < Salesforce::SfBase
  set_table_name 'product2s'
end


text:
<?php
include_once('common.php');
$parts = explode('/', $_SERVER['QUERY_STRING']);
$callsign = array_shift($parts);
$request = implode('/', $parts);
$station = get_station(['callsign' => $callsign]);

if($station) {
  // Don't redirect unless needed
  $url = 'http://' . $station['base_url'] . '/' . implode("/", array_map("rawurlencode", explode("/", $request)));

  if (
    strpos($request, '.xml') !== false ||
    strpos($request, '.pls') !== false ||
    strpos($request, '.m3u') !== false ||
    array_search($request, ['my_uuid', 'heartbeat', 'help', 'stats']) !== false
  ) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $data = curl_exec($ch);
    $info = curl_getinfo($ch);
    header('Content-Type: ' . $info['content_type']);
    header('X-Forwarded-URL: ' . $url);

    echo $data;

  } else {
    header('Location: ' . $url);
  }
}


text:
import torch
from torch.autograd import Variable
from torchvision import models
import sys
import numpy as np
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import dataset
from prune import *
import argparse
from operator import itemgetter
from heapq import nsmallest
import pdb
import time

class ModifiedVGG16Model(torch.nn.Module):
    def __init__(self):
        super(ModifiedVGG16Model, self).__init__()

        model = models.vgg11(pretrained=True)
        self.features = model.features

        for param in self.features.parameters():
            param.requires_grad = False

        self.classifier = model.classifier
        # self.classifier = nn.Sequential(
        #     nn.Dropout(),
        #     nn.Linear(25088, 4096),
        #     nn.ReLU(inplace=True),
        #     nn.Dropout(),
        #     nn.Linear(4096, 4096),
        #     nn.ReLU(inplace=True),
        #     nn.Linear(4096, 2))

    def forward(self, x):
        x = self.features(x)
        x = x.view(x.size(0), -1)
        x = self.classifier(x)
        return x

class FilterPrunner:
    def __init__(self, model):
        self.model = model
        self.reset()

    def reset(self):
        # self.activations = []
        # self.gradients = []
        # self.grad_index = 0
        # self.activation_to_layer = {}
        self.filter_ranks = {}

    def forward(self, x):
        self.activations = []
        self.gradients = []
        self.grad_index = 0
        self.activation_to_layer = {}

        activation_index = 0
        for layer, (name, module) in enumerate(self.model.features._modules.items()):
            x = module(x)
            if isinstance(module, torch.nn.modules.conv.Conv2d):
                x.register_hook(self.compute_rank)
                self.activations.append(x)
                self.activation_to_layer[activation_index] = layer
                activation_index += 1

        return self.model.classifier(x.view(x.size(0), -1))

    def compute_rank(self, grad):
        # print "Hook executed"
        # pdb.set_trace()
        activation_index = len(self.activations) - self.grad_index - 1
        activation = self.activations[activation_index]
        values = torch.sum((activation * grad), dim=-1).sum(dim=-1).sum(dim=0).data

        # Normalize the rank by the filter dimensions
        values = values / (activation.size(0) * activation.size(2) * activation.size(3))

        if activation_index not in self.filter_ranks:
            self.filter_ranks[activation_index] = torch.FloatTensor(activation.size(1)).zero_().cuda()

        self.filter_ranks[activation_index] += values
        self.grad_index += 1

    def lowest_ranking_filters(self, num):
        data = []
        for i in sorted(self.filter_ranks.keys()):
            for j in range(self.filter_ranks[i].size(0)):
                data.append((self.activation_to_layer[i], j, self.filter_ranks[i][j]))

        return nsmallest(num, data, itemgetter(2))

    def normalize_ranks_per_layer(self):
        for i in self.filter_ranks:
            v = torch.abs(self.filter_ranks[i])
            v = v / np.sqrt(torch.sum(v * v))
            self.filter_ranks[i] = v.cpu()

    def get_prunning_plan(self, num_filters_to_prune):
        filters_to_prune = self.lowest_ranking_filters(num_filters_to_prune)

        # After each of the k filters are prunned,
        # the filter index of the next filters change since the model is smaller.
        filters_to_prune_per_layer = {}
        for (l, f, _) in filters_to_prune:
            if l not in filters_to_prune_per_layer:
                filters_to_prune_per_layer[l] = []
            filters_to_prune_per_layer[l].append(f)

        for l in filters_to_prune_per_layer:
            filters_to_prune_per_layer[l] = sorted(filters_to_prune_per_layer[l])
            for i in range(len(filters_to_prune_per_layer[l])):
                filters_to_prune_per_layer[l][i] = filters_to_prune_per_layer[l][i] - i

        filters_to_prune = []
        for l in filters_to_prune_per_layer:
            for i in filters_to_prune_per_layer[l]:
                filters_to_prune.append((l, i))

        return filters_to_prune

class PrunningFineTuner_VGG16:
    def __init__(self, train_path, test_path, model):
        self.train_data_loader = dataset.loader(train_path)
        self.test_data_loader = dataset.test_loader(test_path)

        self.model = model
        self.criterion = torch.nn.CrossEntropyLoss()
        self.prunner = FilterPrunner(self.model)
        self.model.train()

    def test(self):
        self.model.eval()
        correct = 0
        total = 0

        for i, (batch, label) in enumerate(self.test_data_loader):
            batch = batch.cuda()
            output = model(Variable(batch))
            pred = output.data.max(1)[1]
            correct += pred.cpu().eq(label).sum()
            total += label.size(0)

        print "Accuracy :", float(correct) / total

        self.model.train()

    def train(self, optimizer=None, epoches=10):
        if optimizer is None:
            optimizer = \
                optim.SGD(model.classifier.parameters(),
                          lr=0.0001, momentum=0.9, weight_decay=1e-6, nesterov=True)

        for i in range(epoches):
            print "Epoch: ", i
            self.train_epoch(optimizer)
            self.test()
        print "Finished fine tuning."

    def train_batch(self, optimizer, batch, label, rank_filters):
        self.model.zero_grad()
        input = Variable(batch)

        if rank_filters:
            output = self.prunner.forward(input)
            self.criterion(output, Variable(label)).backward()
        else:
            self.criterion(self.model(input), Variable(label)).backward()
            optimizer.step()

    def train_epoch(self, optimizer=None, rank_filters=False):
        for batch, label in self.train_data_loader:
            self.train_batch(optimizer, batch.cuda(), label.cuda(), rank_filters)

    def get_candidates_to_prune(self, num_filters_to_prune):
        self.prunner.reset()

        self.train_epoch(rank_filters=True)

        self.prunner.normalize_ranks_per_layer()

        return self.prunner.get_prunning_plan(num_filters_to_prune)

    def total_num_filters(self):
        filters = 0
        for name, module in self.model.features._modules.items():
            if isinstance(module, torch.nn.modules.conv.Conv2d):
                filters = filters + module.out_channels
        return filters

    def prune(self):
        # Get the accuracy before prunning
        self.test()
        self.model.train()

        # Make sure all the layers are trainable
        for param in self.model.features.parameters():
            param.requires_grad = True

        number_of_filters = self.total_num_filters()
        num_filters_to_prune_per_iteration = 512
        iterations = int(float(number_of_filters) / num_filters_to_prune_per_iteration)

        iterations = int(iterations * 2.0 / 3)

        print "Number of prunning iterations to reduce 67% filters", iterations

        for _ in range(iterations):
            print "Ranking filters.. "
            prune_targets = self.get_candidates_to_prune(num_filters_to_prune_per_iteration)
            layers_prunned = {}
            for layer_index, filter_index in prune_targets:
                if layer_index not in layers_prunned:
                    layers_prunned[layer_index] = 0
                layers_prunned[layer_index] = layers_prunned[layer_index] + 1

            print "Layers that will be prunned", layers_prunned
            print "Prunning filters.. "
            model = self.model.cpu()
            # pdb.set_trace()
            for layer_index, filter_index in prune_targets:
                model = prune_vgg16_conv_layer(model, layer_index, filter_index)

                # set parameters of only the layer corresponding to layer_index and the next layer to true.
				# Also the last layer parameters are always true

                # firstly, parameters for all the layers are set to false
                for param in model.parameters():
                    param.requires_grad = False

                # set the last fc layer parameter true
                for _, module in model.classifier._modules.items()[::-1]:
					if isinstance(module, torch.nn.Linear):
						for param in module.parameters():
							param.requires_grad = True

				# set parameters of only the layer corresponding to layer_index and the next layer to true.
                _, curr_layer = model.features._modules.items()[layer_index]
                for param in curr_layer.parameters():
                    param.requires_grad = True

                # get the next conv layer and set it as learnable
                offset = 1
                next_conv_found = False

                while layer_index + offset < len(model.features._modules.items()):
					_, res = model.features._modules.items()[layer_index + offset]
					if isinstance(res, torch.nn.modules.conv.Conv2d):
						next_conv_found = True
						for param in res.parameters():
							param.requires_grad = True
						break
					offset = offset + 1

                if not next_conv_found:  # if true, then the curr_layer was the last conv layer, so find the next fc layer
					for _, module in model.classifier._modules.items():
						if isinstance(module, torch.nn.Linear):
							for param in module.parameters():
								param.requires_grad = True

                model = model.cuda()
                print "Fine tuning to recover from prunning iteration. Two conv layers and all classifier layers will be trained"
                optimizer = optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=0.001,
									  momentum=0.9, weight_decay=1e-6, nesterov=True)
                self.train(optimizer, epoches=4)
                model = model.cpu()

            # for param in model.features.parameters():
            #     param.requires_grad = True
            # self.model = model.cuda()

            message = str(100 * float(self.total_num_filters()) / number_of_filters) + "%"
            print "Filters prunned", str(message)
            self.test()
            # print "Fine tuning to recover from prunning iteration."
            # optimizer = optim.SGD(self.model.parameters(), lr=0.001, momentum=0.9, weight_decay=1e-6, nesterov=True)
            # self.train(optimizer, epoches=3)

        for param in model.parameters():
            param.requires_grad = True
	    model = model.cuda()
        self.model = model

        optimizer = optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=0.001,
							  momentum=0.9, weight_decay=1e-6, nesterov=True)
        print "Finished. Going to fine tune the model a bit more"
        self.train(optimizer, epoches=4)
        torch.save(model, "model_prunned")

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--train", dest="train", action="store_true")
    parser.add_argument("--prune", dest="prune", action="store_true")
    parser.add_argument("--train_path", type=str, default="/data1/VisionDatasets/ImageNet_Fall2011/ILSVRC2012_grouped/train")
    parser.add_argument("--test_path", type=str, default="/data1/VisionDatasets/ImageNet_Fall2011/ILSVRC2012_grouped/test")
    parser.set_defaults(train=False)
    parser.set_defaults(prune=False)
    args = parser.parse_args()
    return args

if __name__ == '__main__':
    t1 = time.time()
    args = get_args()

    if args.train:
        model = ModifiedVGG16Model().cuda()
    elif args.prune:
        model = torch.load("model").cuda()

    fine_tuner = PrunningFineTuner_VGG16(args.train_path, args.test_path, model)

    if args.train:
        fine_tuner.train(epoches=8)
        torch.save(model, "model")

    elif args.prune:
        fine_tuner.prune()
    print "Time elapsed: ", time.time() - t1, " seconds"


text:
cd ~/Dropbox/Grad\ Life/thesis/
python -m tensorboard.main --logdir output


text:
from tests.utils import service_ok

import pytest

from owslib.csw import CatalogueServiceWeb

SERVICE_URL = 'http://gis.armf.bg:8080/geoserver/csw'

@pytest.mark.online
@pytest.mark.skipif(not service_ok(SERVICE_URL),
                    reason='service is unreachable')
def test_csw_geoserver():
    c = CatalogueServiceWeb(SERVICE_URL)
    c.getrecords2(typenames='csw:Record')
    assert c.results.get('returned') > 0
    assert c.results.get('nextrecord') > 0
    assert c.results.get('matches') > 0


text:
package example.passwordmanager;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class AddNewSecureNoteActivity extends AppCompatActivity
{
    private static final int IMG_ID = 2130837626;

    private DatabaseReference mDatabaseReference;
    private EditText name, note;
    private Button save;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_new_secure_note);

        mDatabaseReference = FirebaseDatabase.getInstance().getReference();

        name = (EditText) findViewById(R.id.edt_entry_name);
        note = (EditText) findViewById(R.id.edtInput);

        save = (Button) findViewById(R.id.btn_save);

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String pushKey = mDatabaseReference.push().getKey();

                ListEntry obj = new ListEntry.ListEntryBuilder
                (
                    IMG_ID,
                    name.getText().toString(),
                    "SOME DEFAULT DESCRIPTION",
                    pushKey,
                    new SimpleDateFormat("dd/MM/yyyy", Locale.UK).format(new Date())
                )
                .setSecureNote(note.getText().toString())
                .build();
                mDatabaseReference.child("entries/" + pushKey).setValue(obj);
                finish();
            }
        });
    }
}


text:
require('lookup-multicast-dns/global')
var net = require('net')
var jsonStream = require('duplex-json-stream')

var username = process.argv[2] || 'guest'
var hostname = (process.argv[3] || 'anon') + '.local'

var socket = jsonStream(net.connect(10000, hostname))

process.stdin.on('data', function (data) {
  var message = data.toString().trim()
  socket.write({username: username, message: message})
})

socket.on('data', function (data) {
  console.log(data.username + '> ' + data.message)
})


text:
package org.kaazing.gateway.transport;

import java.net.SocketAddress;
import java.util.Arrays;

import javax.security.auth.Subject;

import org.apache.mina.core.service.TransportMetadata;
import org.apache.mina.core.session.IoSession;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.kaazing.gateway.resource.address.ResourceAddressFactory;
import org.kaazing.gateway.transport.test.Expectations;
import org.kaazing.mina.core.service.IoServiceEx;
import org.kaazing.mina.core.session.IoSessionEx;
import org.kaazing.test.util.LoggingRule;
import org.kaazing.test.util.MethodExecutionTrace;

public class TransportExceptionMonitorTest
{
    public static long TEST_SESSION_NUMBER = 23;

    @Rule
    public JUnitRuleMockery context = new JUnitRuleMockery();

    private static final String ERROR_MESSAGE = "ERROR";
    private static final String EXCEPTION_MESSAGE = "EXCEPTION";

    public TestRule trace = new MethodExecutionTrace();

    private LoggingRule checkLogMessageRule = new LoggingRule();

    @Rule
    public TestRule chain = RuleChain.outerRule(trace).around(checkLogMessageRule);

    @Test(expected=Error.class)
    public void exceptionCaughtShouldRethrowError() throws Exception {
        IoSession session = context.mock(IoSession.class);
        new TransportExceptionMonitor().exceptionCaught(new Error(ERROR_MESSAGE), session);
    }

    @Test
    public void shouldLogMessageIncludingSession() throws Exception {
        IoSessionEx session = context.mock(IoSessionEx.class, "session");
        IoServiceEx service = context.mock(IoServiceEx.class, "service");
        TransportMetadata metadata = context.mock(TransportMetadata.class, "metadata");
        ResourceAddressFactory addressFactory = ResourceAddressFactory.newResourceAddressFactory();
        String addressURI = "ws://localhost:2121/jms";
        SocketAddress address = addressFactory.newResourceAddress(addressURI);
        Subject subject = new Subject();

        context.checking(new Expectations() {
            {
                allowing(session).getService(); will(returnValue(service));
                oneOf(session).getId(); will(returnValue(TEST_SESSION_NUMBER));
                oneOf(service).getTransportMetadata(); will(returnValue(metadata));
                oneOf(session).getTransportMetadata(); will(returnValue(metadata));
                allowing(metadata).getName(); will(returnValue("wsn"));
                oneOf(session).getAttribute(with(any(Object.class))); will(returnValue(null));
                oneOf(session).getLocalAddress(); will(returnValue(address));
                oneOf(session).getRemoteAddress(); will(returnValue(address));
                oneOf(session).getSubject(); will(returnValue(subject));
                oneOf(session).setAttribute(with(any(Object.class)), with(any(String.class)));
            }
        });
        new TransportExceptionMonitor().exceptionCaught(new NullPointerException(EXCEPTION_MESSAGE), session);
        checkLogMessageRule.expectPatterns(Arrays.asList("\\[wsn#23 127.0.0.1:2121\\] java.lang.NullPointerException: EXCEPTION"));
    }

    @Test
    public void shouldLogMessageIncludingNullSession() throws Exception {
        new TransportExceptionMonitor().exceptionCaught(new NullPointerException(EXCEPTION_MESSAGE), null);
        checkLogMessageRule.expectPatterns(Arrays.asList("Unexpected exception."));
    }
}