text:
'use strict';

import * as mocha from 'mocha';
import { X12Parser, X12QueryEngine, X12Interchange } from '../core';

let fs = require('fs');

describe('X12QueryEngine', () => {

    it('should handle basic element references', () => {
        let edi = fs.readFileSync('tests/test-data/850.edi', 'utf8');
        let parser = new X12Parser(true);
        let engine = new X12QueryEngine(parser);
        let results = engine.query(edi, 'REF02');

        if (results.length !== 2) {
            throw new Error('Expected two matching elements for REF02.');
        }
    });

    it('should handle qualified element references', () => {
        let edi = fs.readFileSync('tests/test-data/850.edi', 'utf8');
        let parser = new X12Parser(true);
        let engine = new X12QueryEngine(parser);
        let results = engine.query(edi, 'REF02:REF01["DP"]');

        if (results.length !== 1) {
            throw new Error('Expected one matching element for REF02:REF01["DP"].');
        }

        else if (results[0].element.value !== '038') {
            throw new Error('Expected REF02 to be "038".')
        }
    });

    it('should handle segment path element references', () => {
        let edi = fs.readFileSync('tests/test-data/850.edi', 'utf8');
        let parser = new X12Parser(true);
        let engine = new X12QueryEngine(parser);
        let results = engine.query(edi, 'PO1-PID05:PID01["F"]');

        if (results.length !== 6) {
            throw new Error('Expected six matching elements for PO1-PID05:PID01["F"].');
        }
    });

    it('should handle HL path element references', () => {
        let edi = fs.readFileSync('tests/test-data/856.edi', 'utf8');
        let parser = new X12Parser(true);
        let engine = new X12QueryEngine(parser);
        let results = engine.query(edi, 'HL+S+O+I-LIN03');

        if (results.length !== 2) {
            throw new Error('Expected two matching elements for HL+S+O+I-LIN03.');
        }
    });

    it('should return valid range information for segments and elements', () => {
        let edi = fs.readFileSync('tests/test-data/850.edi', 'utf8');
        let parser = new X12Parser(true);
        let engine = new X12QueryEngine(parser);
        let result = engine.querySingle(edi, 'BEG03');

        if (result.segment.range.start.line !== 3) {
            throw new Error(`Start line for segment is incorrect; found ${result.segment.range.start.line}, expected 3.`);
        }

        if (result.segment.range.start.character !== 0) {
            throw new Error(`Start char for segment is incorrect; found ${result.segment.range.start.character}, expected 0.`);
        }

        if (result.element.range.start.line !== 3) {
            throw new Error(`Start line for element is incorrect; found ${result.element.range.start.line}, expected 3.`);
        }

        if (result.element.range.start.character !== 10) {
            throw new Error(`Start char for element is incorrect; found ${result.element.range.start.character}, expected 10.`);
        }

        if (result.segment.range.end.line !== 3) {
            throw new Error(`End line for segment is incorrect; found ${result.segment.range.end.line}, expected 3.`);
        }

        if (result.segment.range.end.character !== 41) {
            throw new Error(`End char for segment is incorrect; found ${result.segment.range.end.character}, expected 41.`);
        }

        if (result.element.range.end.line !== 3) {
            throw new Error(`End line for element is incorrect; found ${result.element.range.end.line}, expected 3.`);
        }

        if (result.element.range.end.character !== 20) {
            throw new Error(`End char for element is incorrect; found ${result.element.range.end.character}, expected 20.`);
        }
    });

    it('should handle envelope queries', () => {
        let edi = fs.readFileSync('tests/test-data/850.edi', 'utf8');
        let parser = new X12Parser(true);
        let engine = new X12QueryEngine(parser);
        let results = engine.query(edi, 'ISA06');

        if (results.length === 1) {
            if (results[0].element.value.trim() !== '4405197800') {
                throw new Error(`Expected 4405197800, found ${results[0].element.value}.`);
            }
        }

        else {
            throw new Error(`Expected exactly one result. Found ${results.length}.`);
        }
    });

    it('should handle queries for files with line feed segment terminators', () => {
        let edi = fs.readFileSync('tests/test-data/850_2.edi', 'utf8');
        let parser = new X12Parser(true);
        let engine = new X12QueryEngine(parser);
        let results = engine.query(edi, 'REF02:REF01["DP"]');

        if (results.length === 1) {
            if (results[0].element.value.trim() !== '038') {
                throw new Error(`Expected 038, found ${results[0].element.value}.`);
            }
        }

        else {
            throw new Error(`Expected exactly one result. Found ${results.length}.`);
        }
    });

    it('should handle chained qualifiers', () => {
        let edi = fs.readFileSync('tests/test-data/850.edi', 'utf8');
        let parser = new X12Parser(true);
        let engine = new X12QueryEngine(parser);
        let results = engine.query(edi, 'REF02:REF01["DP"]:BEG02["SA"]');

        if (results.length === 1) {
            if (results[0].element.value.trim() !== '038') {
                throw new Error(`Expected 038, found ${results[0].element.value}.`);
            }
        }

        else {
            throw new Error(`Expected exactly one result. Found ${results.length}.`);
        }
    });
});


text:
@interface PodsDummy_Pods_CollectionViewCellWithAutoLayout : NSObject
@end
@implementation PodsDummy_Pods_CollectionViewCellWithAutoLayout
@end

redpajama_set_name: RedPajamaGithub


text:
import EmberObject from "@ember/object";

/**
 * AutoLocation will select the best location option based off browser support with the priority order: history, hash, none.
 */
export default class AutoLocation extends EmberObject {}


text:
"""
Editra session file manager.

"""

__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: ed_session.py 70097 2011-12-22 21:36:43Z CJP $"
__revision__ = "$Revision: 70097 $"

#-----------------------------------------------------------------------------#
# Imports
import wx
import os
import cPickle

# Editra Imports
import util
import ed_cmdbar
import ed_glob
import profiler
import ed_msg
import ebmlib

#-----------------------------------------------------------------------------#
# Globals
_ = wx.GetTranslation

#-----------------------------------------------------------------------------#

class SessionManager(object):
    """Simple editing session manager helper class"""
    def __init__(self, savedir):
        """@param savedir: directory to load/save session files at"""
        super(SessionManager, self).__init__()

        # Attributes
        self.__default = '__default' # default session file name
        self._sessiondir = savedir
        self._sessionext = '.session'

    #---- Properties ----#
    DefaultSession = property(lambda self: self.__default)

    SessionDir = property(lambda self: self._sessiondir,
                          lambda self, dpath: setattr(self, '_sessiondir', dpath))

    def _SetExtension(self, ext):
        assert ext.startswith('.')
        self._sessionext = ext
    SessionExtension = property(lambda self: self._sessionext,
                                lambda self, ext: self._SetExtension(ext))
    Sessions = property(lambda self: self.GetSavedSessions())

    #---- Implementation ----#

    def DeleteSession(self, name):
        """Delete the specified session name
        @param name: session name
        @return: bool

        """
        rval = True
        session = self.PathFromSessionName(name)
        if os.path.exists(session):
            try:
                os.remove(session)
            except OSError:
                rval = False
        return rval

    def GetSavedSessions(self):
        """Get the list of available saved sessions by display name
        @return: list of strings

        """
        sessions = list()
        defaultSession = None
        for session in os.listdir(self.SessionDir):
            if session.endswith(self.SessionExtension):
                path = os.path.join(self.SessionDir, session)
                sName = self.SessionNameFromPath(path)
                if session.startswith(self.__default):
                    defaultSession = sName
                else:
                    sessions.append(sName)
        sessions.sort()
        if defaultSession:
            sessions.insert(0, defaultSession)
        return sessions

    def LoadSession(self, name):
        """Load a named session
        @param name: session name
        @return: list of paths

        """
        session = self.PathFromSessionName(name)
        assert os.path.exists(session)
        flist = list()
        with open(session, 'rb') as f_handle:
            # Load and validate file
            try:
                flist = cPickle.load(f_handle)
                # TODO: Extend in future to support loading sessions
                #       for multiple windows.
                flist = flist.get('win1', list())
                for item in flist:
                    if type(item) not in (unicode, str):
                        raise TypeError("Invalid item in unpickled sequence")
            except (cPickle.UnpicklingError, TypeError, EOFError), e:
                util.Log("[ed_session][err] %s" % e)
                raise e # Re throw
        return flist

    def SaveSession(self, name, paths):
        """Save the given list of files as a session with the given name
        @param name: session name
        @param paths: list of file paths
        @return: bool

        """
        session = self.PathFromSessionName(name)
        bOk = False
        with open(session, 'wb') as f_handle:
            try:
                # TODO multi window support
                sdata = dict(win1=paths)
                cPickle.dump(sdata, f_handle)
                bOk = True
            except Exception, msg:
                util.Log("[ed_session][err] Failed to SaveSessionFile: %s" % msg)

        return bOk

    def PathFromSessionName(self, session):
        """Get the full path to store a session file
        @param session: string base name (no extension)

        """
        name = session + self.SessionExtension
        path = os.path.join(self.SessionDir, name)
        return path

    def SessionNameFromPath(self, path):
        """Get the sessions display name from its path"""
        assert path.endswith(self.SessionExtension)
        name = os.path.basename(path)
        name = name.rsplit('.', 1)[0]
        return name

#-----------------------------------------------------------------------------#

class EdSessionMgr(SessionManager):
    """Editra specific session manager implementation"""
    __metaclass__ = ebmlib.Singleton
    def __init__(self):
        super(EdSessionMgr, self).__init__(ed_glob.CONFIG['SESSION_DIR'])

#-----------------------------------------------------------------------------#

class EdSessionBar(ed_cmdbar.CommandBarBase):
    """Command bar for managing editing sessions"""
    class meta:
        id = ed_glob.ID_SESSION_BAR

    def __init__(self, parent):
        super(EdSessionBar, self).__init__(parent)

        # Attributes
        self._sch = wx.Choice(self)

        # Setup
        self.__DoLayout()
        self._saveb = self.AddPlateButton(_("Save"), ed_glob.ID_SAVE)
        self._saveb.Name = "SaveButton"
        self._saveasb = self.AddPlateButton(_("Save As"), ed_glob.ID_SAVEAS)
        self._saveasb.Name = "SaveAsButton"
        self._delb = self.AddPlateButton(_("Delete"), ed_glob.ID_DELETE)
        self._delb.Name = "DeleteButton"
        self.UpdateSessionList()

        # Event Handlers
        self._saveb.Bind(wx.EVT_BUTTON, self.OnSaveSession)
        self._saveasb.Bind(wx.EVT_BUTTON, self.OnSaveSession)
        self._delb.Bind(wx.EVT_BUTTON, self.OnDeleteSession)
        self._sch.Bind(wx.EVT_CHOICE, self.OnChangeSession)
        self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI, self._delb)
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)

        # Message Handlers
        ed_msg.Subscribe(self.OnConfigMsg,
                         ed_msg.EDMSG_PROFILE_CHANGE + ('LAST_SESSION',))

    def __DoLayout(self):
        self.AddControl(wx.StaticText(self, label=_("Session:")), wx.ALIGN_LEFT)
        self.AddControl(self._sch, wx.ALIGN_LEFT)

    def OnDestroy(self, evt):
        """Cleanup message handlers"""
        if self:
            ed_msg.Unsubscribe(self.OnConfigMsg)
        evt.Skip()

    def GetSelectedSession(self):
        """Get the currently selected session
        @return: string (internal session name)

        """
        if self._sch.Selection == 0:
            return EdSessionMgr().DefaultSession
        else:
            return self._sch.StringSelection

    def OnChangeSession(self, evt):
        """Current session changed in choice control"""
        util.Log(u"[ed_session][info] OnChangeSession: %s" % self._sch.StringSelection)
        ed_msg.PostMessage(ed_msg.EDMSG_SESSION_DO_LOAD,
                           self.GetSelectedSession(),
                           self.TopLevelParent.Id)

    def OnConfigMsg(self, msg):
        """Configuration update callback"""
        if self:
            self.UpdateSessionList()

    def OnSaveSession(self, evt):
        """Save the current session"""
        ofiles = list()
        util.Log("[ed_session][info] OnSaveSession")
        if evt.EventObject is self._saveb:
            ed_msg.PostMessage(ed_msg.EDMSG_FILE_GET_OPENED, ofiles,
                               self.TopLevelParent.Id)
            util.Log("[ed_session][info] OnSaveSession: %d files" % len(ofiles))
            EdSessionMgr().SaveSession(self.GetSelectedSession(), ofiles)
        elif evt.EventObject is self._saveasb:
            ed_msg.PostMessage(ed_msg.EDMSG_SESSION_DO_SAVE,
                               context=self.TopLevelParent.Id)
            # Bar will be updated by config change if the save succeeds
        else:
            evt.Skip()

    def OnDeleteSession(self, evt):
        """Delete the current session"""
        if evt.EventObject is self._delb:
            ses = self.GetSelectedSession()
            if ses != EdSessionMgr().DefaultSession:
                EdSessionMgr().DeleteSession(ses)
                # Switch back to default session
                profiler.Profile_Set('LAST_SESSION',
                                     EdSessionMgr().DefaultSession)
        else:
            evt.Skip()

    def OnBarShown(self):
        """Update the session list"""
        self.UpdateSessionList()

    def OnUpdateUI(self, evt):
        """Handle UpdateUI events"""
        if evt.EventObject is self._delb:
            evt.Enable(self._sch.Selection > 0)
        else:
            evt.Skip()

    def UpdateSessionList(self):
        """Update the session list"""
        sessions = EdSessionMgr().Sessions
        if len(sessions):
            sessions[0] = _("Default")
            self._sch.Items = sessions
            self.UpdateSelectedSession()
            self.Layout()
            self.Refresh()

    def UpdateSelectedSession(self):
        """Select the currently configured session"""
        ses = profiler.Profile_Get('LAST_SESSION')
        if ses:
            if ses == EdSessionMgr().DefaultSession:
                self._sch.SetSelection(0)
            elif ses in self._sch.Items:
                self._sch.SetStringSelection(ses)


text:
package ro.isdc.wro.model.resource.support.hash;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.zip.CRC32;
import java.util.zip.Checksum;

import org.apache.commons.io.IOUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Uses CRC32 algorithm for creating fingerprint.
 *
 * @author Alex Objelean
 * @since 1.4.7
 * @created 17 Jun 2012
 */
public class CRC32HashStrategy
    implements HashStrategy {
  private static final Logger LOG = LoggerFactory.getLogger(CRC32HashStrategy.class);
  /**
   * A short name of this hashBuilder.
   */
  public static final String ALIAS = "CRC32";
  /**
   * {@inheritDoc}
   */
  public String getHash(final InputStream input)
    throws IOException {
    if (input == null) {
      throw new IllegalArgumentException("Content cannot be null!");
    }
    try{
      LOG.debug("creating hash using CRC32 algorithm");
      final Checksum checksum = new CRC32();
      final byte[] bytes = new byte[1024];
      int len = 0;
      while ((len = input.read(bytes)) >= 0) {
        checksum.update(bytes, 0, len);
      }

      final String hash = new BigInteger(Long.toString(checksum.getValue())).toString(16);
      LOG.debug("CRC32 hash: {}", hash);
      return hash;
    }finally{
      IOUtils.closeQuietly(input);
    }
  }
}


text:
using KaVE.Commons.Model.Naming;
using KaVE.Commons.Model.Naming.CodeElements;
using KaVE.JetBrains.Annotations;

namespace KaVE.Commons.Model.TypeShapes
{
    public class MethodHierarchy : BaseMemberHierarchy<IMethodName>
    {
        public MethodHierarchy() : base(Names.UnknownMethod) {}

        public MethodHierarchy([NotNull] IMethodName n) : base(n) {}
    }
}


text:
package org.orekit.propagation.numerical;

import java.util.ArrayList;
import java.util.List;

import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.ode.nonstiff.AdaptiveStepsizeIntegrator;
import org.hipparchus.ode.nonstiff.DormandPrince853Integrator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.orekit.Utils;
import org.orekit.bodies.CR3BPFactory;
import org.orekit.bodies.CR3BPSystem;
import org.orekit.errors.OrekitException;
import org.orekit.frames.Frame;
import org.orekit.orbits.CR3BPDifferentialCorrection;
import org.orekit.orbits.HaloOrbit;
import org.orekit.orbits.LibrationOrbitFamily;
import org.orekit.orbits.LibrationOrbitType;
import org.orekit.orbits.RichardsonExpansion;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.integration.AdditionalEquations;
import org.orekit.propagation.numerical.cr3bp.CR3BPForceModel;
import org.orekit.propagation.numerical.cr3bp.CR3BPMultipleShooter;
import org.orekit.propagation.numerical.cr3bp.STMEquations;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.AbsolutePVCoordinates;
import org.orekit.utils.LagrangianPoints;
import org.orekit.utils.PVCoordinates;

public class CR3BPMultipleShooterTest {

    @Test
    public void testHaloOrbit() {

        final CR3BPSystem syst = CR3BPFactory.getEarthMoonCR3BP();
        final AbsoluteDate date = AbsoluteDate.J2000_EPOCH;
        final HaloOrbit h1 = new HaloOrbit(new RichardsonExpansion(syst, LagrangianPoints.L1), 8E6, LibrationOrbitFamily.NORTHERN);

        // Adaptive stepsize boundaries
        final double minStep = 1E-12;
        final double maxstep = 0.001;

        // Integrator tolerances
        final double positionTolerance = 1E-5;
        final double velocityTolerance = 1E-5;
        final double massTolerance = 1.0e-6;
        final double[] vecAbsoluteTolerances = {positionTolerance, positionTolerance, positionTolerance, velocityTolerance, velocityTolerance, velocityTolerance, massTolerance };
        final double[] vecRelativeTolerances =
                        new double[vecAbsoluteTolerances.length];

        // Integrator definition
        final AdaptiveStepsizeIntegrator integrator =
                        new DormandPrince853Integrator(minStep, maxstep,
                                                       vecAbsoluteTolerances,
                                                       vecRelativeTolerances);
        final int narcs = 1;
        final List<AdditionalEquations> cr3bpAdditionalEquations = new ArrayList<AdditionalEquations>(narcs) ;
        cr3bpAdditionalEquations.add(new STMEquations(syst));

        // Propagator definition for CR3BP
        final List<NumericalPropagator> propagatorList = new ArrayList<NumericalPropagator>(narcs);
        final NumericalPropagator propagator = new NumericalPropagator(integrator);
        propagator.setOrbitType(null);
        propagator.setIgnoreCentralAttraction(true);
        propagator.addForceModel(new CR3BPForceModel(syst));

        // Add new set of additional equations to the propagator
        propagator.addAdditionalEquations(cr3bpAdditionalEquations.get(0));

        propagatorList.add(propagator);

        // First guess trajectory definition

        final PVCoordinates firstGuess1 = h1.getInitialPV();
        final PVCoordinates firstGuess2 = new PVCoordinates(firstGuess1.getPosition().add(new Vector3D(0.1,0,0)), firstGuess1.getVelocity().negate());
        final double arcDuration = h1.getOrbitalPeriod()/2;

        List<SpacecraftState> firstGuessList = new ArrayList<SpacecraftState>(narcs + 1) ;;
        firstGuessList.add(new SpacecraftState(new AbsolutePVCoordinates(syst.getRotatingFrame(),
                                                                         date,
                                                                         firstGuess1)));
        firstGuessList.add(new SpacecraftState(new AbsolutePVCoordinates(syst.getRotatingFrame(),
                                                                         date.shiftedBy(arcDuration),
                                                                         firstGuess2)));

        // Multiple Shooting definition
        final CR3BPMultipleShooter multipleShooting = new CR3BPMultipleShooter(firstGuessList, propagatorList, cr3bpAdditionalEquations, arcDuration, 1E-8);
        multipleShooting.setPatchPointComponentFreedom(1, 1, false);
        multipleShooting.setPatchPointComponentFreedom(1, 2, false);
        multipleShooting.setPatchPointComponentFreedom(1, 3, false);
        multipleShooting.setPatchPointComponentFreedom(1, 5, false);
        multipleShooting.setPatchPointComponentFreedom(2, 1, false);
        multipleShooting.setPatchPointComponentFreedom(2, 3, false);
        multipleShooting.setPatchPointComponentFreedom(2, 5, false);
        multipleShooting.setEpochFreedom(1, false);
        multipleShooting.setEpochFreedom(2, false);
        multipleShooting.addConstraint(1, 1, 1.0e-5);

        // Differential correction
        h1.applyDifferentialCorrection();
        final PVCoordinates initialPVDC = h1.getInitialPV();
        final double periodDC = h1.getOrbitalPeriod();

        // Multiple shooting computation
        List<SpacecraftState> result = multipleShooting.compute();
        final AbsolutePVCoordinates initialPVMS = result.get(0).getAbsPVA();
        final double periodMS = 2 * result.get(1).getDate().durationFrom(result.get(0).getDate());

        Assert.assertEquals(0.0, initialPVDC.getPosition().getY(), 1E-15);
        Assert.assertEquals(0.0, initialPVDC.getVelocity().getX(), 1E-15);
        Assert.assertEquals(0.0, initialPVDC.getVelocity().getZ(), 1E-15);

        Assert.assertEquals(0.0, initialPVMS.getPosition().getY(), 1E-15);
        Assert.assertEquals(0.0, initialPVMS.getVelocity().getX(), 1E-15);
        Assert.assertEquals(0.0, initialPVMS.getVelocity().getZ(), 1E-15);

        Assert.assertEquals(initialPVDC.getPosition().getX(), initialPVMS.getPosition().getX(), 6.6E-4);
        Assert.assertEquals(initialPVDC.getPosition().getZ(), initialPVMS.getPosition().getZ(), 1.0E-15);
        Assert.assertEquals(initialPVDC.getVelocity().getY(), initialPVMS.getVelocity().getY(), 7.2E-3);

        Assert.assertEquals(periodDC, periodMS, 3.0E-2);
    }

    @Test(expected=OrekitException.class)
    public void testLagrangianError() {
        CR3BPSystem syst = CR3BPFactory.getEarthMoonCR3BP();
        final HaloOrbit h = new HaloOrbit(new RichardsonExpansion(syst, LagrangianPoints.L3), 8E6, LibrationOrbitFamily.NORTHERN);
        h.getClass();
    }

    @Test(expected=OrekitException.class)
    public void testDifferentialCorrectionError() {

        CR3BPSystem syst = CR3BPFactory.getEarthMoonCR3BP();

        final double orbitalPeriod = 1;

        final PVCoordinates firstGuess = new PVCoordinates(new Vector3D(0.0, 1.0, 2.0), new Vector3D(3.0, 4.0, 5.0));

        final PVCoordinates initialConditions =
                        new CR3BPDifferentialCorrection(firstGuess, syst, orbitalPeriod).compute(LibrationOrbitType.HALO);
        initialConditions.toString();
    }

    @Test(expected=OrekitException.class)
    public void testSTMError() {
        // Time settings
        final AbsoluteDate initialDate =
                        new AbsoluteDate(1996, 06, 25, 0, 0, 00.000,
                                         TimeScalesFactory.getUTC());
        CR3BPSystem syst = CR3BPFactory.getEarthMoonCR3BP();

        final Frame Frame = syst.getRotatingFrame();

        // Define a Northern Halo orbit around Earth-Moon L1 with a Z-amplitude
        // of 8 000 km
        HaloOrbit h = new HaloOrbit(new RichardsonExpansion(syst, LagrangianPoints.L1), 8E6, LibrationOrbitFamily.SOUTHERN);

        final PVCoordinates pv = new PVCoordinates(new Vector3D(0.0, 1.0, 2.0), new Vector3D(3.0, 4.0, 5.0));

        final AbsolutePVCoordinates initialAbsPV =
                        new AbsolutePVCoordinates(Frame, initialDate, pv);

        // Creating the initial spacecraftstate that will be given to the
        // propagator
        final SpacecraftState s = new SpacecraftState(initialAbsPV);

        final PVCoordinates manifold = h.getManifolds(s, true);
        manifold.getMomentum();
    }

    @Before
    public void setUp() {
        Utils.setDataRoot("cr3bp:regular-data");
    }
}


text:
.list,.pan{
position:absolute;
width:100%;
height:50px;
padding:0;
margin:0;
}
body{
margin:0;
padding:0;
font-family: "Times New Roman";
}
li{
list-style-type:none;
float:left;
background:#3df;
height:100%;
line-height:50px;
text-align:center;
width:25%;
margin:0;
color:#000;
font-weight: bold;
letter-spacing:0px;
}
.settingpanel{
position:absolute;
background:#fff;
width:500px;
height:500px;
top:50%;
left:50%;
z-index:1;
border:1px solid #000;
margin-top:-250px;
margin-left:-250px;
overflow:hidden;
display:none;
}
.header{
height:50px;
width:100%;
text-align: center;
line-height:50px;
background:#e91e63;
color:#fff;
font-size:20px;
font-weight: bold;
letter-spacing: 5px;
}
.active{
background:#fff;
}
.codearea{
position:absolute;
top:55px;
width:50%;
height:100%;
}
textarea{
width:100%;
height:80%;
display:none;
outline:none;
}
textarea.active{
display:block;
background:#000;
color:#fff;
}
iframe.result{
top:55px;
position:absolute;
width:50%;
height:80%;
left:50%;
}
.setopt{
position:absolute;
top:100px;
width:100%;
height:100%;
text-align:center;
display:none;
}
.setopt.active{
display:block;
}
.setopt textarea{
display:block;
}
h3{
margin:0;
padding:0;
float:left;
margin-left:5%;
line-height:50px;
}
.modules{
background:#f1f1f1;
margin-bottom:1px;
width:100%;
height:50px;
position:relative;
}
.modules .ip{
width:35%;
}
.modules input{
margin:0;
padding:0;
position:absolute;
float:right;
height:47px;
left:65%;
border:none;
border-bottom:3px solid #3df;
outline:none;
background:#f1f1f1;
}
.sbmit,.run{
width:100px;
height:50px;
background:#e91e63;
color:#fff;
line-height: 50px;
float:right;
margin:10px;
box-shadow:0 0 20px rgba(0,0,0,0.5);
text-align:center;
}
.run{
position:absolute;
top:90%;
z-index:2;

}
.toggle{
position:relative;
width:40px;
height:10px;
background:#ccc;
border-radius: 30px;
display: inline-block;
padding:5px;
}
.toggle input{
display:none;
}
.slide{
position:absolute;
width:30px;
height:30px;
border-radius:50%;
background:rgb(250,56,19);
left:0px;
top:50%;
margin-top:-15px;
transition:0.5s;
}
input:checked + .slide{
background:#0f0;
transform:translateX(20px);
}
.opt{
float:left;
width:50%;
}
.switch{
float:right;
width:50%;
margin-top:0px;
}
.set{
margin-top:20px;
}


text:
require 'test_helper'

module Rez

  describe PointSerializer do

    let(:point) { FactoryGirl.create(:paragraph) }

    it 'serializes the Point to JSON' do
      serialized = PointSerializer.new(point).to_json
      serialized.must_equal %Q({"point":{"id":#{point.id},"text":"#{point.text}","rank":#{point.rank},"point_type":"paragraph"}})
    end
  end
end


text:
package org.rsna.ctp;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.rsna.ctp.servlets.ConfigurationServlet;
import org.rsna.ctp.servlets.DBVerifierServlet;
import org.rsna.ctp.servlets.DecipherServlet;
import org.rsna.ctp.servlets.DicomAnonymizerServlet;
import org.rsna.ctp.servlets.IDMapServlet;
import org.rsna.ctp.servlets.LookupServlet;
import org.rsna.ctp.servlets.ObjectTrackerServlet;
import org.rsna.ctp.servlets.QuarantineServlet;
import org.rsna.ctp.servlets.ScriptServlet;
import org.rsna.ctp.servlets.ServerServlet;
import org.rsna.ctp.servlets.ShutdownServlet;
import org.rsna.ctp.servlets.StatusServlet;
import org.rsna.ctp.servlets.SummaryServlet;
import org.rsna.server.Authenticator;
import org.rsna.server.HttpServer;
import org.rsna.server.ServletSelector;
import org.rsna.server.Users;
import org.rsna.servlets.ApplicationServer;
import org.rsna.servlets.EnvironmentServlet;
import org.rsna.servlets.LogServlet;
import org.rsna.servlets.LoggerLevelServlet;
import org.rsna.servlets.LoginServlet;
import org.rsna.servlets.SysPropsServlet;
import org.rsna.servlets.UserManagerServlet;
import org.rsna.servlets.UserServlet;
import org.rsna.util.Cache;
import org.rsna.util.ClasspathUtil;
import org.rsna.util.FileUtil;
import org.rsna.util.HttpUtil;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * The ClinicalTrialProcessor program.
 */
public class ClinicalTrialProcessor {

	static final File libraries = new File("libraries");
	static final String mainClassName = "org.rsna.ctp.ClinicalTrialProcessor";
	static boolean running = true;
	static Logger logger = null;

	/**
	 * The main method of the ClinicalTrialProcessor program.
	 * This method just instantiates the main class.
	 * IMPORTANT: This approach requires that <u>all</u> the
	 * directories containing the libraries used by the program
	 * appear in the java.ext.dirs list. This is done by the
	 * CTP-startup program when it launches CTP. It is also done
	 * by the Windows service. The extensions must include the
	 * directory containing CTP.jar plus the CTP/libraries
	 * directory.
	 */
	public static void main(String[] args) {
		//Set the context classloader to allow dcm4che to load its classes
		Thread.currentThread().setContextClassLoader(ClinicalTrialProcessor.class.getClassLoader());

		//Instantiate the main class
		new ClinicalTrialProcessor();
	}

	/**
	 * The startup method of the ClinicalTrialProcessor program.
	 * This method is used when running CTP as a Windows service.
	 * It does not return until the stopService method is called
	 * independently by the service manager.
	 */
	public static void startService(String[] args) {
		System.out.println("Start [ServiceManager]");
		main(args);
		while (running) {
			try { Thread.sleep(2000); }
			catch (Exception ignore) { }
		}
		if (logger != null) logger.info("startService returned\n");
	}

	/**
	 * The shutdown method of the ClinicalTrialProcessor program.
	 * This method is used when running CTP as a Windows service.
	 * This method makes an HTTP connection to the ShutdownServlet
	 * to trigger the plugins and pipelines to close down gracefully.
	 */
	public static void stopService(String[] args) {
		try {
			Configuration config = Configuration.getInstance();
			boolean ssl = config.getServerSSL();
			int port = config.getServerPort();

			URL url = new URL( "http" + (ssl?"s":"") + "://127.0.0.1:" + port + "/shutdown" );
			HttpURLConnection conn = HttpUtil.getConnection(url);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("servicemanager", "stayalive");
			conn.connect();

			String result = FileUtil.getText( conn.getInputStream() );
			if (result.contains("Goodbye.")) {
				System.out.println("Normal shutdown [ServiceManager]");
				running = false;
			}
			else System.out.println("Unable to service the shutdown request from ServiceManager.");
		}
		catch (Exception keepRunning) { keepRunning.printStackTrace(); }
		if (logger != null) logger.info("stopService returned");
	}

	/**
	 * The constructor of the ClinicalTrialProcessor program.
	 * There is no UI presented by the program. All access to
	 * the configuration and status of the program is presented
	 * through the HTTP server.
	 */
	public ClinicalTrialProcessor() {

		//Set up the classpath
		ClasspathUtil.addJARs( new File("libraries") );

		//Initialize Log4J
		File logs = new File("logs");
		logs.mkdirs();
		File logProps = new File("log4j.properties");
		PropertyConfigurator.configure(logProps.getAbsolutePath());
		logger = Logger.getLogger(ClinicalTrialProcessor.class);

		//Instantiate the singleton Cache and clear it.
		Cache.getInstance(new File("CACHE")).clear();

		//Get the configuration
		Configuration config = Configuration.getInstance();

		//Instantiate the singleton Users class
		Users users = Users.getInstance(config.getUsersClassName(), config.getServerElement());

		//Add the CTP roles
		String[] roles = { "read", "delete", "import", "qadmin", "guest", "proxy" };
		for (String role : roles) users.addRole(role);

		//Disable session timeouts for the server
		Authenticator.getInstance().setSessionTimeout( 0L );

		//Create the ServletSelector for the HttpServer
		ServletSelector selector =
				new ServletSelector(
						new File("ROOT"),
						config.getRequireAuthentication());

		//Add in the servlets
		selector.addServlet("login",		LoginServlet.class);
		selector.addServlet("users",		UserManagerServlet.class);
		selector.addServlet("user",			UserServlet.class);
		selector.addServlet("logs",			LogServlet.class);
		selector.addServlet("configuration",ConfigurationServlet.class);
		selector.addServlet("status",		StatusServlet.class);
		selector.addServlet("quarantines",	QuarantineServlet.class);
		selector.addServlet("idmap",		IDMapServlet.class);
		selector.addServlet("objecttracker",ObjectTrackerServlet.class);
		selector.addServlet("databaseverifier",DBVerifierServlet.class);
		selector.addServlet("decipher",		DecipherServlet.class);
		selector.addServlet("system",		SysPropsServlet.class);
		selector.addServlet("environment",	EnvironmentServlet.class);
		selector.addServlet("daconfig",		DicomAnonymizerServlet.class);
		selector.addServlet("script",		ScriptServlet.class);
		selector.addServlet("lookup",		LookupServlet.class);
		selector.addServlet("webstart",		ApplicationServer.class);
		selector.addServlet("level",		LoggerLevelServlet.class);
		selector.addServlet("shutdown",		ShutdownServlet.class);
		selector.addServlet("server",		ServerServlet.class);
		selector.addServlet("summary",		SummaryServlet.class);

		//Instantiate the server.
		int port = config.getServerPort();
		boolean ssl = config.getServerSSL();
		HttpServer httpServer = null;
		try { httpServer = new HttpServer(ssl, port, selector); }
		catch (Exception ex) {
			logger.error("Unable to instantiate the HTTP Server on port "+port, ex);
			System.exit(0);
		}

		//Start the system
		config.start(httpServer);
	}

}