text:
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;

namespace System.IO.Pipes
{
    public abstract partial class PipeStream : Stream
    {
        internal const bool CheckOperationsRequiresSetHandle = true;
        internal ThreadPoolBoundHandle _threadPoolBinding;

        internal static string GetPipePath(string serverName, string pipeName)
        {
            string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
            if (String.Equals(normalizedPipePath, @"\\.\pipe\" + AnonymousPipeName, StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
            }
            return normalizedPipePath;
        }

        /// Throws an exception if the supplied handle does not represent a valid pipe.
        /// <param name="safePipeHandle">The handle to validate.</param>
        internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
        {
            // Check that this handle is infact a handle to a pipe.
            if (Interop.Kernel32.GetFileType(safePipeHandle) != Interop.Kernel32.FileTypes.FILE_TYPE_PIPE)
            {
                throw new IOException(SR.IO_InvalidPipeHandle);
            }
        }

        /// Initializes the handle to be used asynchronously.
        /// <param name="handle">The handle.</param>
        private void InitializeAsyncHandle(SafePipeHandle handle)
        {
            // If the handle is of async type, bind the handle to the ThreadPool so that we can use
            // the async operations (it's needed so that our native callbacks get called).
            _threadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle);
        }

        private void UninitializeAsyncHandle()
        {
            if (_threadPoolBinding != null)
                _threadPoolBinding.Dispose();
        }

        [SecurityCritical]
        private unsafe int ReadCore(Span<byte> buffer)
        {
            int errorCode = 0;
            int r = ReadFileNative(_handle, buffer, null, out errorCode);

            if (r == -1)
            {
                // If the other side has broken the connection, set state to Broken and return 0
                if (errorCode == Interop.Errors.ERROR_BROKEN_PIPE ||
                    errorCode == Interop.Errors.ERROR_PIPE_NOT_CONNECTED)
                {
                    State = PipeState.Broken;
                    r = 0;
                }
                else
                {
                    throw Win32Marshal.GetExceptionForWin32Error(errorCode, String.Empty);
                }
            }
            _isMessageComplete = (errorCode != Interop.Errors.ERROR_MORE_DATA);

            Debug.Assert(r >= 0, "PipeStream's ReadCore is likely broken.");

            return r;
        }

        [SecuritySafeCritical]
        private Task<int> ReadAsyncCore(Memory<byte> buffer, CancellationToken cancellationToken)
        {
            var completionSource = new ReadWriteCompletionSource(this, buffer, cancellationToken, isWrite: false);

            // Queue an async ReadFile operation and pass in a packed overlapped
            int errorCode = 0;
            int r;
            unsafe
            {
                r = ReadFileNative(_handle, buffer.Span, completionSource.Overlapped, out errorCode);
            }

            // ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper
            // returns -1. This will return the following:
            // - On error, r==-1.
            // - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
            // - On async requests that completed sequentially, r==0
            //
            // You will NEVER RELIABLY be able to get the number of buffer read back from this call
            // when using overlapped structures!  You must not pass in a non-null lpNumBytesRead to
            // ReadFile when using overlapped structures!  This is by design NT behavior.
            if (r == -1)
            {
                switch (errorCode)
                {
                    // One side has closed its handle or server disconnected.
                    // Set the state to Broken and do some cleanup work
                    case Interop.Errors.ERROR_BROKEN_PIPE:
                    case Interop.Errors.ERROR_PIPE_NOT_CONNECTED:
                        State = PipeState.Broken;

                        unsafe
                        {
                            // Clear the overlapped status bit for this special case. Failure to do so looks
                            // like we are freeing a pending overlapped.
                            completionSource.Overlapped->InternalLow = IntPtr.Zero;
                        }

                        completionSource.ReleaseResources();
                        UpdateMessageCompletion(true);
                        return s_zeroTask;

                    case Interop.Errors.ERROR_IO_PENDING:
                        break;

                    default:
                        throw Win32Marshal.GetExceptionForWin32Error(errorCode);
                }
            }

            completionSource.RegisterForCancellation();
            return completionSource.Task;
        }

        [SecurityCritical]
        private unsafe void WriteCore(ReadOnlySpan<byte> buffer)
        {
            int errorCode = 0;
            int r = WriteFileNative(_handle, buffer, null, out errorCode);

            if (r == -1)
            {
                throw WinIOError(errorCode);
            }
            Debug.Assert(r >= 0, "PipeStream's WriteCore is likely broken.");
        }

        [SecuritySafeCritical]
        private Task WriteAsyncCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
        {
            var completionSource = new ReadWriteCompletionSource(this, buffer, cancellationToken, isWrite: true);
            int errorCode = 0;

            // Queue an async WriteFile operation and pass in a packed overlapped
            int r;
            unsafe
            {
                r = WriteFileNative(_handle, buffer.Span, completionSource.Overlapped, out errorCode);
            }

            // WriteFile, the OS version, will return 0 on failure, but this WriteFileNative
            // wrapper returns -1. This will return the following:
            // - On error, r==-1.
            // - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
            // - On async requests that completed sequentially, r==0
            //
            // You will NEVER RELIABLY be able to get the number of buffer written back from this
            // call when using overlapped structures!  You must not pass in a non-null
            // lpNumBytesWritten to WriteFile when using overlapped structures!  This is by design
            // NT behavior.
            if (r == -1 && errorCode != Interop.Errors.ERROR_IO_PENDING)
            {
                completionSource.ReleaseResources();
                throw WinIOError(errorCode);
            }

            completionSource.RegisterForCancellation();
            return completionSource.Task;
        }

        // Blocks until the other end of the pipe has read in all written buffer.
        [SecurityCritical]
        public void WaitForPipeDrain()
        {
            CheckWriteOperations();
            if (!CanWrite)
            {
                throw Error.GetWriteNotSupported();
            }

            // Block until other end of the pipe has read everything.
            if (!Interop.Kernel32.FlushFileBuffers(_handle))
            {
                throw WinIOError(Marshal.GetLastWin32Error());
            }
        }

        // Gets the transmission mode for the pipe.  This is virtual so that subclassing types can
        // override this in cases where only one mode is legal (such as anonymous pipes)
        public virtual PipeTransmissionMode TransmissionMode
        {
            [SecurityCritical]
            [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
            get
            {
                CheckPipePropertyOperations();

                if (_isFromExistingHandle)
                {
                    int pipeFlags;
                    if (!Interop.Kernel32.GetNamedPipeInfo(_handle, out pipeFlags, IntPtr.Zero, IntPtr.Zero,
                            IntPtr.Zero))
                    {
                        throw WinIOError(Marshal.GetLastWin32Error());
                    }
                    if ((pipeFlags & Interop.Kernel32.PipeOptions.PIPE_TYPE_MESSAGE) != 0)
                    {
                        return PipeTransmissionMode.Message;
                    }
                    else
                    {
                        return PipeTransmissionMode.Byte;
                    }
                }
                else
                {
                    return _transmissionMode;
                }
            }
        }

        // Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
        // access. If that passes, call to GetNamedPipeInfo will succeed.
        public virtual int InBufferSize
        {
            [SecurityCritical]
            [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
            get
            {
                CheckPipePropertyOperations();
                if (!CanRead)
                {
                    throw new NotSupportedException(SR.NotSupported_UnreadableStream);
                }

                int inBufferSize;
                if (!Interop.Kernel32.GetNamedPipeInfo(_handle, IntPtr.Zero, IntPtr.Zero, out inBufferSize, IntPtr.Zero))
                {
                    throw WinIOError(Marshal.GetLastWin32Error());
                }

                return inBufferSize;
            }
        }

        // Gets the buffer size in the outbound direction for the pipe. This uses cached version
        // if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
        // However, returning cached is good fallback, especially if user specified a value in
        // the ctor.
        public virtual int OutBufferSize
        {
            [SecurityCritical]
            [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
            get
            {
                CheckPipePropertyOperations();
                if (!CanWrite)
                {
                    throw new NotSupportedException(SR.NotSupported_UnwritableStream);
                }

                int outBufferSize;

                // Use cached value if direction is out; otherwise get fresh version
                if (_pipeDirection == PipeDirection.Out)
                {
                    outBufferSize = _outBufferSize;
                }
                else if (!Interop.Kernel32.GetNamedPipeInfo(_handle, IntPtr.Zero, out outBufferSize,
                    IntPtr.Zero, IntPtr.Zero))
                {
                    throw WinIOError(Marshal.GetLastWin32Error());
                }

                return outBufferSize;
            }
        }

        public virtual PipeTransmissionMode ReadMode
        {
            [SecurityCritical]
            get
            {
                CheckPipePropertyOperations();

                // get fresh value if it could be stale
                if (_isFromExistingHandle || IsHandleExposed)
                {
                    UpdateReadMode();
                }
                return _readMode;
            }
            [SecurityCritical]
            [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
            set
            {
                // Nothing fancy here.  This is just a wrapper around the Win32 API.  Note, that NamedPipeServerStream
                // and the AnonymousPipeStreams override this.

                CheckPipePropertyOperations();
                if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
                {
                    throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
                }

                unsafe
                {
                    int pipeReadType = (int)value << 1;
                    if (!Interop.Kernel32.SetNamedPipeHandleState(_handle, &pipeReadType, IntPtr.Zero, IntPtr.Zero))
                    {
                        throw WinIOError(Marshal.GetLastWin32Error());
                    }
                    else
                    {
                        _readMode = value;
                    }
                }
            }
        }

        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        [SecurityCritical]
        private unsafe int ReadFileNative(SafePipeHandle handle, Span<byte> buffer, NativeOverlapped* overlapped, out int errorCode)
        {
            DebugAssertHandleValid(handle);
            Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative.");

            // You can't use the fixed statement on an array of length 0. Note that async callers
            // check to avoid calling this first, so they can call user's callback
            if (buffer.Length == 0)
            {
                errorCode = 0;
                return 0;
            }

            int r = 0;
            int numBytesRead = 0;

            fixed (byte* p = &buffer.DangerousGetPinnableReference())
            {
                r = _isAsync ?
                    Interop.Kernel32.ReadFile(handle, p, buffer.Length, IntPtr.Zero, overlapped) :
                    Interop.Kernel32.ReadFile(handle, p, buffer.Length, out numBytesRead, IntPtr.Zero);
            }

            if (r == 0)
            {
                // In message mode, the ReadFile can inform us that there is more data to come.
                errorCode = Marshal.GetLastWin32Error();
                return errorCode == Interop.Errors.ERROR_MORE_DATA ?
                    numBytesRead :
                    -1;
            }
            else
            {
                errorCode = 0;
                return numBytesRead;
            }
        }

        [SecurityCritical]
        private unsafe int WriteFileNative(SafePipeHandle handle, ReadOnlySpan<byte> buffer, NativeOverlapped* overlapped, out int errorCode)
        {
            DebugAssertHandleValid(handle);
            Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative.");

            // You can't use the fixed statement on an array of length 0. Note that async callers
            // check to avoid calling this first, so they can call user's callback
            if (buffer.Length == 0)
            {
                errorCode = 0;
                return 0;
            }

            int r = 0;
            int numBytesWritten = 0;

            fixed (byte* p = &buffer.DangerousGetPinnableReference())
            {
                r = _isAsync ?
                    Interop.Kernel32.WriteFile(handle, p, buffer.Length, IntPtr.Zero, overlapped) :
                    Interop.Kernel32.WriteFile(handle, p, buffer.Length, out numBytesWritten, IntPtr.Zero);
            }

            if (r == 0)
            {
                errorCode = Marshal.GetLastWin32Error();
                return -1;
            }
            else
            {
                errorCode = 0;
                return numBytesWritten;
            }
        }

        [SecurityCritical]
        internal static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability)
        {
            Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES);
            if ((inheritability & HandleInheritability.Inheritable) != 0)
            {
                secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES);
                secAttrs.bInheritHandle = Interop.BOOL.TRUE;
            }
            return secAttrs;
        }

        ///
        /// Determine pipe read mode from Win32
        ///
        [SecurityCritical]
        private void UpdateReadMode()
        {
            int flags;
            if (!Interop.Kernel32.GetNamedPipeHandleState(SafePipeHandle, out flags, IntPtr.Zero, IntPtr.Zero,
                    IntPtr.Zero, IntPtr.Zero, 0))
            {
                throw WinIOError(Marshal.GetLastWin32Error());
            }

            if ((flags & Interop.Kernel32.PipeOptions.PIPE_READMODE_MESSAGE) != 0)
            {
                _readMode = PipeTransmissionMode.Message;
            }
            else
            {
                _readMode = PipeTransmissionMode.Byte;
            }
        }

        ///
        /// Filter out all pipe related errors and do some cleanup before calling Error.WinIOError.
        ///
        /// <param name="errorCode"></param>
        [SecurityCritical]
        internal Exception WinIOError(int errorCode)
        {
            switch (errorCode)
            {
                case Interop.Errors.ERROR_BROKEN_PIPE:
                case Interop.Errors.ERROR_PIPE_NOT_CONNECTED:
                case Interop.Errors.ERROR_NO_DATA:
                    // Other side has broken the connection
                    _state = PipeState.Broken;
                    return new IOException(SR.IO_PipeBroken, Win32Marshal.MakeHRFromErrorCode(errorCode));

                case Interop.Errors.ERROR_HANDLE_EOF:
                    return Error.GetEndOfFile();

                case Interop.Errors.ERROR_INVALID_HANDLE:
                    // For invalid handles, detect the error and mark our handle
                    // as invalid to give slightly better error messages.  Also
                    // help ensure we avoid handle recycling bugs.
                    _handle.SetHandleAsInvalid();
                    _state = PipeState.Broken;
                    break;
            }

            return Win32Marshal.GetExceptionForWin32Error(errorCode);
        }
    }
}


text:
require "codeclimate-test-reporter"
CodeClimate::TestReporter.start

require "pry"
require "rspec"
require "rack/content_length_setter"

redpajama_set_name: RedPajamaGithub


text:
package gov.nih.nci.rembrandt.dbbean;

import java.sql.Date;

import gov.nih.nci.rembrandt.queryservice.resultset.ResultSet;

/**
* caIntegrator License
*
* Copyright 2001-2005 Science Applications International Corporation ("SAIC").
* The software subject to this notice and license includes both human readable source code form and machine readable,
* binary, object code form ("the caIntegrator Software"). The caIntegrator Software was developed in conjunction with
* the National Cancer Institute ("NCI") by NCI employees and employees of SAIC.
* To the extent government employees are authors, any rights in such works shall be subject to Title 17 of the United States
* Code, section 105.
* This caIntegrator Software License (the "License") is between NCI and You. "You (or "Your") shall mean a person or an
* entity, and all other entities that control, are controlled by, or are under common control with the entity. "Control"
* for purposes of this definition means (i) the direct or indirect power to cause the direction or management of such entity,
*  whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii)
* beneficial ownership of such entity.
* This License is granted provided that You agree to the conditions described below. NCI grants You a non-exclusive,
* worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and royalty-free right and license in its rights
* in the caIntegrator Software to (i) use, install, access, operate, execute, copy, modify, translate, market, publicly
* display, publicly perform, and prepare derivative works of the caIntegrator Software; (ii) distribute and have distributed
* to and by third parties the caIntegrator Software and any modifications and derivative works thereof;
* and (iii) sublicense the foregoing rights set out in (i) and (ii) to third parties, including the right to license such
* rights to further third parties. For sake of clarity, and not by way of limitation, NCI shall have no right of accounting
* or right of payment from You or Your sublicensees for the rights granted under this License. This License is granted at no
* charge to You.
* 1. Your redistributions of the source code for the Software must retain the above copyright notice, this list of conditions
*    and the disclaimer and limitation of liability of Article 6, below. Your redistributions in object code form must reproduce
*    the above copyright notice, this list of conditions and the disclaimer of Article 6 in the documentation and/or other materials
*    provided with the distribution, if any.
* 2. Your end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This
*    product includes software developed by SAIC and the National Cancer Institute." If You do not include such end-user
*    documentation, You shall include this acknowledgment in the Software itself, wherever such third-party acknowledgments
*    normally appear.
* 3. You may not use the names "The National Cancer Institute", "NCI" "Science Applications International Corporation" and
*    "SAIC" to endorse or promote products derived from this Software. This License does not authorize You to use any
*    trademarks, service marks, trade names, logos or product names of either NCI or SAIC, except as required to comply with
*    the terms of this License.
* 4. For sake of clarity, and not by way of limitation, You may incorporate this Software into Your proprietary programs and
*    into any third party proprietary programs. However, if You incorporate the Software into third party proprietary
*    programs, You agree that You are solely responsible for obtaining any permission from such third parties required to
*    incorporate the Software into such third party proprietary programs and for informing Your sublicensees, including
*    without limitation Your end-users, of their obligation to secure any required permissions from such third parties
*    before incorporating the Software into such third party proprietary software programs. In the event that You fail
*    to obtain such permissions, You agree to indemnify NCI for any claims against NCI by such third parties, except to
*    the extent prohibited by law, resulting from Your failure to obtain such permissions.
* 5. For sake of clarity, and not by way of limitation, You may add Your own copyright statement to Your modifications and
*    to the derivative works, and You may provide additional or different license terms and conditions in Your sublicenses
*    of modifications of the Software, or any derivative works of the Software as a whole, provided Your use, reproduction,
*    and distribution of the Work otherwise complies with the conditions stated in this License.
* 6. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO,
*    THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
*    IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SAIC, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT,
*    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
*    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
*    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*    OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/

public class PriorChemotherapy implements ResultSet{

	public final static String PRIOR_CHEMOTRX_ID = "priorChemotrxId";
	public final static String PATIENT_DID = "patientDid";
	public final static String INSTITUTION_ID = "institutionId";
	public final static String DATASET_ID = "datasetId";
	public final static String TIME_POINT = "timePoint";
	public final static String AGENT_ID = "agentId";
	public final static String AGENT_NAME = "AGENT_NAME";
	public final static String COURSE_COUNT = "courseCount";
	public final static String DOSE_START_DATE = "doseStartDate";
	public final static String DOSE_STOP_DATE = "doseStopDate";
	public final static String STUDY_SOURCE = "studySource";
	public final static String PROTOCOL_NUMBER = "protocolNumber";

	 private Long priorChemotrxId;
	 private Long patientDid;
	 private Long institutionId;
	 private Long datasetId;
	 private String timePoint;
	 private Long agentId;
	 private String agentName;
	 private Long courseCount;
	 private Date doseStartDate;
	 private Date doseStopDate;
	 private String studySource;
	 private String protocolNumber;
	/**
	 * @return Returns the agentId.
	 */
	public Long getAgentId() {
		return agentId;
	}
	/**
	 * @param agentId The agentId to set.
	 */
	public void setAgentId(Long agentId) {
		this.agentId = agentId;
	}
	/**
	 * @return Returns the agentName.
	 */
	public String getAgentName() {
		return agentName;
	}
	/**
	 * @param agentName The agentName to set.
	 */
	public void setAgentName(String agentName) {
		this.agentName = agentName;
	}
	/**
	 * @return Returns the courseCount.
	 */
	public Long getCourseCount() {
		return courseCount;
	}
	/**
	 * @param courseCount The courseCount to set.
	 */
	public void setCourseCount(Long courseCount) {
		this.courseCount = courseCount;
	}
	/**
	 * @return Returns the datasetId.
	 */
	public Long getDatasetId() {
		return datasetId;
	}
	/**
	 * @param datasetId The datasetId to set.
	 */
	public void setDatasetId(Long datasetId) {
		this.datasetId = datasetId;
	}
	/**
	 * @return Returns the doseStartDate.
	 */
	public Date getDoseStartDate() {
		return doseStartDate;
	}
	/**
	 * @param doseStartDate The doseStartDate to set.
	 */
	public void setDoseStartDate(Date doseStartDate) {
		this.doseStartDate = doseStartDate;
	}
	/**
	 * @return Returns the doseStopDate.
	 */
	public Date getDoseStopDate() {
		return doseStopDate;
	}
	/**
	 * @param doseStopDate The doseStopDate to set.
	 */
	public void setDoseStopDate(Date doseStopDate) {
		this.doseStopDate = doseStopDate;
	}
	/**
	 * @return Returns the institutionId.
	 */
	public Long getInstitutionId() {
		return institutionId;
	}
	/**
	 * @param institutionId The institutionId to set.
	 */
	public void setInstitutionId(Long institutionId) {
		this.institutionId = institutionId;
	}
	/**
	 * @return Returns the patientDid.
	 */
	public Long getPatientDid() {
		return patientDid;
	}
	/**
	 * @param patientDid The patientDid to set.
	 */
	public void setPatientDid(Long patientDid) {
		this.patientDid = patientDid;
	}
	/**
	 * @return Returns the priorChemotrxId.
	 */
	public Long getPriorChemotrxId() {
		return priorChemotrxId;
	}
	/**
	 * @param priorChemotrxId The priorChemotrxId to set.
	 */
	public void setPriorChemotrxId(Long priorChemotrxId) {
		this.priorChemotrxId = priorChemotrxId;
	}
	/**
	 * @return Returns the protocolNumber.
	 */
	public String getProtocolNumber() {
		return protocolNumber;
	}
	/**
	 * @param protocolNumber The protocolNumber to set.
	 */
	public void setProtocolNumber(String protocolNumber) {
		this.protocolNumber = protocolNumber;
	}
	/**
	 * @return Returns the studySource.
	 */
	public String getStudySource() {
		return studySource;
	}
	/**
	 * @param studySource The studySource to set.
	 */
	public void setStudySource(String studySource) {
		this.studySource = studySource;
	}
	/**
	 * @return Returns the timePoint.
	 */
	public String getTimePoint() {
		return timePoint;
	}
	/**
	 * @param timePoint The timePoint to set.
	 */
	public void setTimePoint(String timePoint) {
		this.timePoint = timePoint;
	}

}


text:
Controllers.MerchantList = function(view_proxy) {
	var populateTable = Repo.Merchant.all.p(compose(view_proxy.table.set, map(compose('.row', Views.MerchantRow))), {}),

			//+ openDetail :: {row: TableViewRow} -> IO
			openDetail = function(e) {
				compose(Windows.Application.navigation.open_, '.win', Windows.MerchantDetail, '.row.merchant')(e);
			}

  view_proxy.win.addEventListener('open', populateTable);
	view_proxy.table.addEventListener('click', openDetail);
};


text:
// karma configuration
const karma_conf = {
  basePath: '../../',
  browserNoActivityTimeout: 1000000,
  browsers: [ 'Chrome', 'Firefox' ],
  client: {
    captureConsole: true,
    mocha: {'ui': 'tdd', timeout: 3000}
  },
  envPreprocessor: [
    'TEST_ENV'
  ],
  webpack: {

  },
  files: [
    // Define test files.
    {pattern: './tests/unit/NafInterface.test.js'},
    {pattern: './tests/unit/NafLogger.test.js'},
    {pattern: './tests/unit/utils.test.js'},
    {pattern: './tests/unit/NetworkConnection.test.js'},
    {pattern: './tests/unit/networked.test.js'},
    {pattern: './tests/unit/networked_remote.test.js'},
    {pattern: './tests/unit/NetworkEntities.test.js'},
    {pattern: './tests/unit/Schemas.test.js'},
    {pattern: './tests/unit/ChildEntityCache.test.js'},
    {pattern: './src/**/*.js', included: false}
  ],
    frameworks: ['mocha', 'sinon-chai', 'chai-shallow-deep-equal', 'webpack'],
    preprocessors: {
    'tests/unit/**/*.js': ['webpack', 'env'],
      'src/**/*.js': ['coverage']
  },
  plugins: [
    'karma-webpack',
    'karma-mocha',
    'karma-sinon-chai',
    'karma-chai-shallow-deep-equal',
    'karma-mocha-reporter',
    'karma-chrome-launcher',
    'karma-firefox-launcher',
    'karma-coverage',
    'karma-env-preprocessor'
  ],
  reporters: ['mocha', 'coverage'],
  logLevel: 'INFO',
  colors: true,
  singleRun: true
  // restartOnFileChange: true
};

// Apply configuration
module.exports = function (config) {
  config.set(karma_conf);
};


text:
package com.igormaznitsa.meta.checker.extracheck;

import static com.igormaznitsa.meta.common.utils.Assertions.fail;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.apache.bcel.classfile.AnnotationEntry;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.ParameterAnnotationEntry;
import org.apache.bcel.generic.Type;

import com.igormaznitsa.meta.annotation.MayContainNull;
import com.igormaznitsa.meta.annotation.MustNotContainNull;
import com.igormaznitsa.meta.checker.Context;
import com.igormaznitsa.meta.checker.Utils;

public final class MethodParameterChecker {

  private static final Class<?>[] CLASSES_WHERE_POSSIBLE_NULL = new Class<?>[]{java.util.List.class, java.util.Vector.class, java.util.Queue.class};

  private static final Set<String> CACHED_CLASS_NAMES_POSITIVE_RECOGNIZED = new HashSet<String>();
  private static final Set<String> CACHED_CLASS_NAMES_NEGATIVE_RECOGNIZED = new HashSet<String>();

  private static final Set<String> ANNOTATIONS_FOR_OBJECT = classesToNameSet(javax.annotation.Nullable.class, javax.annotation.Nonnull.class, "org.jetbrains.annotations.Nullable", "org.jetbrains.annotations.NotNull");
  private static final Set<String> ANNOTATIONS_FOR_ARRAY_OR_COLLECTION = classesToNameSet(MayContainNull.class, MustNotContainNull.class);

  private static final String RETURN_TYPE_NOTIFICATION = "Return type must be marked by either @%s or @%s";
  private static final String RETURN_TYPE_NOTIFICATION_WRONG_TYPE = "Non-object result type can't be marked by either @%s or @%s";
  private static final String ARG_TYPE_NOTIFICATION = "Arg. #%d must be marked by either @%s or @%s";

  public static void checkReturnTypeForNullable(final Context context, final Method method) {
    final Type returnType = method.getReturnType();
    final AnnotationEntry[] annotations = method.getAnnotationEntries();
    if (isNullableType(returnType)) {
      if (!hasAnnotationFromSet(annotations, ANNOTATIONS_FOR_OBJECT)) {
        context.error(String.format(RETURN_TYPE_NOTIFICATION, Utils.extractClassName(Nullable.class.getName()), Utils.extractClassName(Nonnull.class.getName())), true);
      }
    } else {
      if (hasAnnotationFromSet(annotations, ANNOTATIONS_FOR_OBJECT)) {
        context.error(String.format(RETURN_TYPE_NOTIFICATION_WRONG_TYPE, Utils.extractClassName(Nullable.class.getName()), Utils.extractClassName(Nonnull.class.getName())), true);
      }
    }
  }

  public static void checkReturnTypeForMayContainNull(final Context context, final Method method) {
    final Type returnType = method.getReturnType();
    if (isNullableType(returnType)) {
      final AnnotationEntry[] annotations = method.getAnnotationEntries();

      if (isArrayOfObjectsOrCollection(context, returnType) && !hasAnnotationFromSet(annotations, ANNOTATIONS_FOR_ARRAY_OR_COLLECTION)) {
        context.error(String.format(RETURN_TYPE_NOTIFICATION, Utils.extractClassName(MayContainNull.class.getName()), Utils.extractClassName(MustNotContainNull.class.getName())), true);
      }
    }
  }

  private static boolean shouldSkipFirstMethodArg(final JavaClass klazz, final Method method) {
    if (klazz.isNested() && "<init>".equals(method.getName()) && method.getArgumentTypes().length>0){
      if (klazz.isStatic()) return false;
      final String firstArgType = method.getArgumentTypes()[0].getSignature();
      final String outerKlazzSignature = 'L'+Utils.extractOuterClassName(klazz.getClassName())+';';
      return firstArgType.equals(outerKlazzSignature);
    }
    return method.getName().equals("<init>") && klazz.isNested() && !klazz.isStatic();
  }

  public static void checkParamsTypeForNullable(final Context context, final Method method) {
    final Type[] arguments = method.getArgumentTypes();
    final ParameterAnnotationEntry[] paramAnnotations = method.getParameterAnnotationEntries();

    final boolean ignoreFirst = shouldSkipFirstMethodArg(context.getProcessingClass(), method);
    final int argLength = arguments.length;
    final int realArgLength = ignoreFirst ? argLength - 1 : argLength;

    int paramAnnoIndex = 0;
    for (int argIndex = 0; argIndex < argLength; argIndex++) {
      if (ignoreFirst && argIndex == 0) {
        continue;
      }
      if (isNullableType(arguments[argIndex])
          && (paramAnnoIndex >= paramAnnotations.length || !hasParameterAnnotationFromSet(realArgLength, paramAnnoIndex, paramAnnotations, ANNOTATIONS_FOR_OBJECT))) {
        context.error(String.format(ARG_TYPE_NOTIFICATION, argIndex + 1, Utils.extractClassName(Nullable.class.getName()), Utils.extractClassName(Nonnull.class.getName())), true);
      }
      paramAnnoIndex++;
    }
  }

  public static void checkParamsTypeForMayContainNull(final Context context, final Method method) {
    final Type[] arguments = method.getArgumentTypes();
    final ParameterAnnotationEntry[] paramAnnotations = method.getParameterAnnotationEntries();

    final boolean ignoreFirst = shouldSkipFirstMethodArg(context.getProcessingClass(), method);
    final int argLength = arguments.length;
    final int realArgLength = ignoreFirst ? argLength - 1 : argLength;

    int paramAnnoIndex = 0;
    for (int argIndex = 0; argIndex < argLength; argIndex++) {
      if (ignoreFirst && argIndex == 0) {
        continue;
      }

      if (isNullableType(arguments[argIndex]) && isArrayOfObjectsOrCollection(context, arguments[argIndex])
          && (paramAnnoIndex >= paramAnnotations.length || !hasParameterAnnotationFromSet(realArgLength, paramAnnoIndex, paramAnnotations, ANNOTATIONS_FOR_ARRAY_OR_COLLECTION))) {
        context.error(String.format(ARG_TYPE_NOTIFICATION, argIndex + 1, Utils.extractClassName(MayContainNull.class.getName()), Utils.extractClassName(MustNotContainNull.class.getName())), true);
      }
      paramAnnoIndex++;
    }
  }

  private static Set<String> classesToNameSet(final Object... klazzes) {
    final Set<String> result = new HashSet<String>();
    for (final Object k : klazzes) {
      if (k instanceof Class) {
        result.add(Utils.makeSignatureForClass((Class<?>) k));
      } else if (k instanceof String) {
        result.add(Utils.makeSignatureForClass((String) k));
      } else {
        throw fail("Unexpected object type [" + k + ']');
      }
    }
    return result;
  }

  private static boolean isNullableType(final Type type) {
    final String signature = type.getSignature();
    return signature.length() > 0 && (signature.charAt(0) == '[' || signature.charAt(0) == 'L');
  }

  private static boolean isArrayOfObjectsOrCollection(final Context context, final Type type) {
    final String signature = type.getSignature();

    final int arrayLastChar = signature.lastIndexOf('[');

    if (arrayLastChar > 0) {
      return true;
    }

    if (signature.endsWith(";")) {
      if (arrayLastChar >= 0) {
        return true;
      }
    } else {
      return false;
    }

    if (CACHED_CLASS_NAMES_POSITIVE_RECOGNIZED.contains(signature)) {
      return true;
    }
    if (CACHED_CLASS_NAMES_NEGATIVE_RECOGNIZED.contains(signature)) {
      return false;
    }

    return investigateClassThatCanContainNull(context, signature);
  }

  private static boolean investigateClassThatCanContainNull(final Context context, final String classTypeInInsideFormat) {
    final String klazzName = Utils.classNameToNormalView(classTypeInInsideFormat);
    final File classFile = new File(context.getTargetDirectoryFolder(), klazzName.replace('.', '/') + ".class");
    if (classFile.isFile()) {
      try {
        final JavaClass jclazz = new ClassParser(classFile.getAbsolutePath()).parse();

        for (final String interfaceName : jclazz.getInterfaceNames()) {
          if (investigateClassThatCanContainNull(context, Utils.makeSignatureForClass(interfaceName))) {
            CACHED_CLASS_NAMES_POSITIVE_RECOGNIZED.add(classTypeInInsideFormat);
            return true;
          }
        }

        final String superclassName = jclazz.getSuperclassName();
        if (superclassName != null && !superclassName.equals("java.lang.Object")) {
          final String superClassInInsideFormat = Utils.makeSignatureForClass(superclassName);
          if (investigateClassThatCanContainNull(context, superClassInInsideFormat)) {
            CACHED_CLASS_NAMES_POSITIVE_RECOGNIZED.add(classTypeInInsideFormat);
            return true;
          }
        }
      } catch (Exception ex) {
        context.warning("Can't parse class file : " + classFile.getAbsolutePath(), false);
      }
    } else {
      // it is possible that it is standard class
      final String normalClassName = klazzName.replace('$', '.');
      try {
        final Class<?> klazz = Class.forName(normalClassName);
        for (final Class<?> klazzWherePossibleNull : CLASSES_WHERE_POSSIBLE_NULL) {
          if (klazzWherePossibleNull.isAssignableFrom(klazz)) {
            CACHED_CLASS_NAMES_POSITIVE_RECOGNIZED.add(classTypeInInsideFormat);
            return true;
          }
        }
      } catch (ClassNotFoundException ex) {
      }
    }
    CACHED_CLASS_NAMES_NEGATIVE_RECOGNIZED.add(classTypeInInsideFormat);
    return false;
  }

  private static boolean hasAnnotationFromSet(final AnnotationEntry[] annotations, final Set<String> namesToFind) {
    for (final AnnotationEntry a : annotations) {
      if (namesToFind.contains(a.getAnnotationType())) {
        return true;
      }
    }
    return false;
  }

  private static boolean hasParameterAnnotationFromSet(final int numberOfArguments, int indexInParamAnnotations, final ParameterAnnotationEntry[] paramAnnotations, final Set<String> namesToFind) {
    while (indexInParamAnnotations < paramAnnotations.length) {
      for (final AnnotationEntry a : paramAnnotations[indexInParamAnnotations].getAnnotationEntries()) {
        if (namesToFind.contains(a.getAnnotationType())) {
          return true;
        }
      }
      indexInParamAnnotations += numberOfArguments;
    }
    return false;
  }

}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using NUnit.Framework;
using ServiceStack.DataAnnotations;

namespace ServiceStack.OrmLite.MySql.Tests.UseCase
{
    public enum PhoneType
    {
        Home,
        Work,
        Mobile,
    }

    public enum AddressType
    {
        Home,
        Work,
        Other,
    }

    public class Address
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string ZipCode { get; set; }
        public string State { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }

    public class Customer
    {
        public Customer()
        {
            this.PhoneNumbers = new Dictionary<PhoneType, string>();
            this.Addresses = new Dictionary<AddressType, Address>();
        }

        [AutoIncrement] // Creates Auto primary key
        public int Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        [Index(Unique = true)] // Creates Unique Index
        public string Email { get; set; }

        public Dictionary<PhoneType, string> PhoneNumbers { get; set; }

        public Dictionary<AddressType, Address> Addresses { get; set; }

        public DateTime CreatedAt { get; set; }
    }

    public class Order
    {
        [AutoIncrement]
        public int Id { get; set; }

        [References(typeof(Customer))] //Creates Foreign Key
        public int CustomerId { get; set; }

        [References(typeof(Employee))] //Creates Foreign Key
        public int EmployeeId { get; set; }

        public Address ShippingAddress { get; set; } //Blobbed (no Address table)

        public DateTime? OrderDate { get; set; }

        public DateTime? RequiredDate { get; set; }

        public DateTime? ShippedDate { get; set; }

        public int? ShipVia { get; set; }

        public decimal Freight { get; set; }

        public decimal Total { get; set; }
    }

    public class OrderDetail
    {
        [AutoIncrement]
        public int Id { get; set; }

        [References(typeof(Order))] //Creates Foreign Key
        public int OrderId { get; set; }

        public int ProductId { get; set; }

        public decimal UnitPrice { get; set; }

        public short Quantity { get; set; }

        public decimal Discount { get; set; }
    }

    public class Employee
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

    public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public decimal UnitPrice { get; set; }
    }

    [TestFixture]
    public class CustomerOrdersUseCase
    {
        //Stand-alone class, No other configs, nothing but POCOs.
        [Test]
        public void Run()
        {
            //Setup SQL Server Connection Factory
            var dbFactory = new OrmLiteConnectionFactory(
                ConfigurationManager.ConnectionStrings["testDb"].ConnectionString,
                MySqlDialectProvider.Instance);

            //Non-intrusive: All extension methods hang off System.Data.* interfaces
            IDbConnection dbConn = dbFactory.OpenDbConnection();
            IDbCommand dbCmd = dbConn.CreateCommand();

            //Re-Create all table schemas:
            dbCmd.DropTable<OrderDetail>();
            dbCmd.DropTable<Order>();
            dbCmd.DropTable<Customer>();
            dbCmd.DropTable<Product>();
            dbCmd.DropTable<Employee>();

            dbCmd.CreateTable<Employee>();
            dbCmd.CreateTable<Product>();
            dbCmd.CreateTable<Customer>();
            dbCmd.CreateTable<Order>();
            dbCmd.CreateTable<OrderDetail>();

            dbCmd.Insert(new Employee { Id = 1, Name = "Employee 1" });
            dbCmd.Insert(new Employee { Id = 2, Name = "Employee 2" });
            var product1 = new Product { Id = 1, Name = "Product 1", UnitPrice = 10 };
            var product2 = new Product { Id = 2, Name = "Product 2", UnitPrice = 20 };
            dbCmd.Save(product1, product2);

            var customer = new Customer
            {
                FirstName = "Orm",
                LastName = "Lite",
                Email = "ormlite@servicestack.net",
                PhoneNumbers =
                    {
                        { PhoneType.Home, "555-1234" },
                        { PhoneType.Work, "1-800-1234" },
                        { PhoneType.Mobile, "818-123-4567" },
                    },
                Addresses =
                    {
                        { AddressType.Work, new Address { Line1 = "1 Street", Country = "US", State = "NY", City = "New York", ZipCode = "10101" } },
                    },
                CreatedAt = DateTime.UtcNow,
            };
            dbCmd.Insert(customer);

            var customerId = dbCmd.GetLastInsertId(); //Get Auto Inserted Id
            customer = dbCmd.QuerySingle<Customer>(new { customer.Email }); //Query
            Assert.That(customer.Id, Is.EqualTo(customerId));

            //Direct access to System.Data.Transactions:
            using (var trans = dbCmd.BeginTransaction(IsolationLevel.ReadCommitted))
            {
                var order = new Order
                {
                    CustomerId = customer.Id,
                    EmployeeId = 1,
                    OrderDate = DateTime.UtcNow,
                    Freight = 10.50m,
                    ShippingAddress = new Address { Line1 = "3 Street", Country = "US", State = "NY", City = "New York", ZipCode = "12121" },
                };
                dbCmd.Save(order); //Inserts 1st time

                order.Id = (int)dbCmd.GetLastInsertId(); //Get Auto Inserted Id

                var orderDetails = new[] {
                    new OrderDetail
                    {
                        OrderId = order.Id,
                        ProductId = product1.Id,
                        Quantity = 2,
                        UnitPrice = product1.UnitPrice,
                    },
                    new OrderDetail
                    {
                        OrderId = order.Id,
                        ProductId = product2.Id,
                        Quantity = 2,
                        UnitPrice = product2.UnitPrice,
                        Discount = .15m,
                    }
                };

                dbCmd.Insert(orderDetails);

                order.Total = orderDetails.Sum(x => x.UnitPrice * x.Quantity * x.Discount) + order.Freight;

                dbCmd.Save(order); //Updates 2nd Time

                trans.Commit();
            }
        }
    }

}


text:
@implementation ExampleAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // 1. Create the UIWebView example
    ExampleUIWebViewController* UIWebViewExampleController = [[ExampleUIWebViewController alloc] init];
    UIWebViewExampleController.tabBarItem.title             = @"UIWebView";

    // 2. Create the tab footer and add the UIWebView example
    UITabBarController *tabBarController = [[UITabBarController alloc] init];
    [tabBarController addChildViewController:UIWebViewExampleController];

    // 3. Create the  WKWebView example for devices >= iOS 8
    if([WKWebView class]) {
        ExampleWKWebViewController* WKWebViewExampleController = [[ExampleWKWebViewController alloc] init];
        WKWebViewExampleController.tabBarItem.title             = @"WKWebView";
        [tabBarController addChildViewController:WKWebViewExampleController];
    }

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

//    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:tabBarController];

    self.window.rootViewController = tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

@end


text:
package com.gerken.gumbo.graph;

import java.util.ArrayList;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

public class PathSegment {

	public static final int TYPE_NORMAL = 0;
	public static final int TYPE_LOOPBACK_TO = 1;
	public static final int TYPE_LOOPBACK_FROM = 2;

	private WayPoint	from;
	private WayPoint	to;
	private int			type;

	private boolean		directFrom = false;
	private boolean 	directTo = false;

	private double 		angleFrom = 0.0;
	private double 		angleTo = 0.0;

	private double		cutoverSubLevel;

	private ArrayList<WayPoint> innerPath;

	private double indirectDist = 20.0;

	public PathSegment(WayPoint from, WayPoint to, int type) {
		this.from = from;
		this.to = to;
		this.type = type;
	}

	public WayPoint getFrom() {
		return from;
	}

	public WayPoint getTo() {
		return to;
	}

	public int getType() {
		return type;
	}

	public boolean isDirectFrom() {
		return directFrom;
	}

	public void setDirectFrom(boolean directFrom) {
		this.directFrom = directFrom;
	}

	public boolean isDirectTo() {
		return directTo;
	}

	public void setDirectTo(boolean directTo) {
		this.directTo = directTo;
	}

	public double getAngleFrom() {
		return angleFrom;
	}

	public void setAngleFrom(double angleFrom) {
		this.angleFrom = angleFrom;
	}

	public double getAngleTo() {
		return angleTo;
	}

	public void setAngleTo(double angleTo) {
		this.angleTo = angleTo;
	}

	public double getCutoverSubLevel() {
		return cutoverSubLevel;
	}

	public void setCutoverSubLevel(double cutoverSubLevel) {
		this.cutoverSubLevel = cutoverSubLevel;
	}

	public JSONObject asJson() {
		JSONObject jobj = new JSONObject();
		try {
			JSONArray jarr = new JSONArray();
			for (WayPoint wp: innerPath) {
				jarr.put(wp.getCoordinatesJson());
			}
			jobj.put("innerPath", jarr);
//			jobj.put("angleFrom", angleFrom);
//			jobj.put("angleTo", angleTo);
		} catch (Throwable e) {
			try { jobj.put("error", e.toString()); } catch (Throwable t) { }
		}

		return jobj;
	}

	public void layoutInnerPath(double[] x) {
		from = new WayPoint(x[from.getDepth()], from.getLeftToRight());
		to = new WayPoint(x[to.getDepth()], to.getLeftToRight());
		innerPath = new ArrayList<WayPoint>();
		if (type == TYPE_NORMAL) {
			innerPath.add(from);
			if (!directFrom) {
				double angle = from.angleTo(to) + angleFrom;
				WayPoint wp = from.movePolar(angle,indirectDist);
				innerPath.add(wp);
			}
			if (!directTo) {
				WayPoint wp = innerPath.get(innerPath.size()-1);
				double angle = wp.angleTo(to) + Math.PI - angleTo;
				wp = to.movePolar(angle,indirectDist);
				innerPath.add(wp);
			}
			innerPath.add(to);
		} else if (type == TYPE_LOOPBACK_TO) {

			// Layout the path for the final segment in the loopback edge.
			// This segment ends at the "to" node

			innerPath.add(from);

			// from "from" back for 1/2 cutover sublevel
			innerPath.add(new WayPoint(from.getDepth()-(cutoverSubLevel/2.0), from.getLeftToRight()));

			// to the midpoint between from and to, but back to cutover sublevel
			innerPath.add(new WayPoint(from.getDepth()-cutoverSubLevel, (from.getLeftToRight()+to.getLeftToRight()) / 2.0 ));

			// same height as "to" but back by cutover sublevel
			innerPath.add(new WayPoint(to.getDepth()-(cutoverSubLevel/2.0), to.getLeftToRight()));

			double y = from.getDepth();

			innerPath.add(to);

		} else if (type == TYPE_LOOPBACK_FROM) {

			// Layout the path for the first segment in the loopback edge.
			// This segment begins at the "from" node

			innerPath.add(from);

			// from "from" back for 1/2 cutover sublevel
			innerPath.add(new WayPoint(from.getDepth()+(cutoverSubLevel/2.0), from.getLeftToRight()));

			// to the midpoint between from and to, but back to cutover sublevel
			innerPath.add(new WayPoint(from.getDepth()+cutoverSubLevel, (from.getLeftToRight()+to.getLeftToRight()) / 2.0 ));

			// same height as "to" but back by cutover sublevel
			innerPath.add(new WayPoint(to.getDepth()+(cutoverSubLevel/2.0), to.getLeftToRight()));

			double y = from.getDepth();

			innerPath.add(to);

		}
	}

}


text:
from __future__ import division
from visual import *
from visual.graph import *

#control visualizer window
scene.width = 600
scene.height = 760

#objects
ceiling = box(pos=vector(0,0,0), size = (0.2,0.01,0.2))
block = sphere(radius=.025, color=color.yellow)
spring=helix(pos=ceiling.pos, color=color.orange, radius=.01)

block.m = .450 #mass of holder weights
L0 = .10 #meters
ks = 15 #spring constant

block.trail = curve(color=block.color)

#graphs
gdisplay(xtitle='Seconds', ytitle='Meters', x=600, y=0, width=600, height=300)
ygraph = gcurve(color=color.yellow)

#physical constants
g = 0 #m/s^2

#simulation parameters
delta_t = .001
simtime = 10 #seconds

t = 0 #simulation time is 0

amp = .09 #cm amplitude of oscilation
yeq = -L0 - block.m*g/ks

#initial values
block.pos = vector(0,yeq-amp,0) #displace block from equilibrium position
block.v = vector(0,0,0) #start at rest
block.p = block.m*block.v #momentum of block

spring.axis = block.pos - ceiling.pos

#imporve display
scene.autoscale = 0 #dont zoom camera
scene.center = vector(0,yeq,0)

#calculation loop
while t < simtime:
    rate(10000)

    #calculate L vector
    L =block.pos - spring.pos
    Lmag = mag(L)
    Lhat = -L/Lmag

    #force of spring on block
    stretch = Lmag - L0
    Fmag_bspring = ks * stretch
    Fhat_bspring = Lhat
    F_bspring  = Fmag_bspring * Fhat_bspring

    #other force on block
    Fmag_b = block.m * 9.8
    Fhat_b = vector(0,-1,0)
    F_b = Fmag_b * Fhat_b

    #net force on block
    Fnet_b = F_b + F_bspring

    #apply momentum principle
    deltap_block = Fnet_b * delta_t
    block.p = block.p + deltap_block

    #update position
    deltar_block = (block.p/block.m)*delta_t
    block.pos = block.pos + deltar_block

    #add points to block trail
    block.trail.append(pos=block.pos)

    #add data points to ygraph
    ygraph.plot(pos=(t, block.pos.y))

    #update axis of spring
    spring.axis = block.pos

    #update time
    t = t + delta_t


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using QuantConnect.Logging;

namespace QuantConnect.Statistics
{
    /// <summary>
    /// The <see cref="StatisticsBuilder"/> class creates summary and rolling statistics from trades, equity and benchmark points
    /// </summary>
    public static class StatisticsBuilder
    {
        /// <summary>
        /// Generates the statistics and returns the results
        /// </summary>
        /// <param name="trades">The list of closed trades</param>
        /// <param name="profitLoss">Trade record of profits and losses</param>
        /// <param name="pointsEquity">The list of daily equity values</param>
        /// <param name="pointsPerformance">The list of algorithm performance values</param>
        /// <param name="pointsBenchmark">The list of benchmark values</param>
        /// <param name="startingCapital">The algorithm starting capital</param>
        /// <param name="totalFees">The total fees</param>
        /// <param name="totalTransactions">The total number of transactions</param>
        /// <returns>Returns a <see cref="StatisticsResults"/> object</returns>
        public static StatisticsResults Generate(
            List<Trade> trades,
            SortedDictionary<DateTime, decimal> profitLoss,
            List<ChartPoint> pointsEquity,
            List<ChartPoint> pointsPerformance,
            List<ChartPoint> pointsBenchmark,
            decimal startingCapital,
            decimal totalFees,
            int totalTransactions)
        {
            var equity = ChartPointToDictionary(pointsEquity);

            var firstDate = equity.Keys.FirstOrDefault().Date;
            var lastDate = equity.Keys.LastOrDefault().Date;

            var totalPerformance = GetAlgorithmPerformance(firstDate, lastDate, trades, profitLoss, equity, pointsPerformance, pointsBenchmark, startingCapital);
            var rollingPerformances = GetRollingPerformances(firstDate, lastDate, trades, profitLoss, equity, pointsPerformance, pointsBenchmark, startingCapital);
            var summary = GetSummary(totalPerformance, totalFees, totalTransactions);

            return new StatisticsResults(totalPerformance, rollingPerformances, summary);
        }

        /// <summary>
        /// Returns the performance of the algorithm in the specified date range
        /// </summary>
        /// <param name="fromDate">The initial date of the range</param>
        /// <param name="toDate">The final date of the range</param>
        /// <param name="trades">The list of closed trades</param>
        /// <param name="profitLoss">Trade record of profits and losses</param>
        /// <param name="equity">The list of daily equity values</param>
        /// <param name="pointsPerformance">The list of algorithm performance values</param>
        /// <param name="pointsBenchmark">The list of benchmark values</param>
        /// <param name="startingCapital">The algorithm starting capital</param>
        /// <returns>The algorithm performance</returns>
        private static AlgorithmPerformance GetAlgorithmPerformance(
            DateTime fromDate,
            DateTime toDate,
            List<Trade> trades,
            SortedDictionary<DateTime, decimal> profitLoss,
            SortedDictionary<DateTime, decimal> equity,
            List<ChartPoint> pointsPerformance,
            List<ChartPoint> pointsBenchmark,
            decimal startingCapital)
        {
            var periodTrades = trades.Where(x => x.ExitTime.Date >= fromDate && x.ExitTime < toDate.AddDays(1)).ToList();
            var periodProfitLoss = new SortedDictionary<DateTime, decimal>(profitLoss.Where(x => x.Key >= fromDate && x.Key.Date < toDate.AddDays(1)).ToDictionary(x => x.Key, y => y.Value));
            var periodEquity = new SortedDictionary<DateTime, decimal>(equity.Where(x => x.Key.Date >= fromDate && x.Key.Date < toDate.AddDays(1)).ToDictionary(x => x.Key, y => y.Value));

            var benchmark = ChartPointToDictionary(pointsBenchmark, fromDate, toDate);
            var performance = ChartPointToDictionary(pointsPerformance, fromDate, toDate);

            // we need to have the same dates in the performance and benchmark dictionaries,
            // so we add missing dates with zero value
            var missingPerformanceDates = benchmark.Keys.Where(x => !performance.ContainsKey(x));
            foreach (var date in missingPerformanceDates)
            {
                performance.Add(date, 0m);
            }

            var listPerformance = new List<double>();
            performance.Values.ToList().ForEach(i => listPerformance.Add((double)(i / 100)));

            var listBenchmark = CreateBenchmarkDifferences(benchmark, periodEquity);

            EnsureSameLength(listPerformance, listBenchmark);

            var runningCapital = equity.Count == periodEquity.Count ? startingCapital : periodEquity.Values.FirstOrDefault();

            return new AlgorithmPerformance(periodTrades, periodProfitLoss, periodEquity, listPerformance, listBenchmark, runningCapital);
        }

        /// <summary>
        /// Returns the rolling performances of the algorithm
        /// </summary>
        /// <param name="firstDate">The first date of the total period</param>
        /// <param name="lastDate">The last date of the total period</param>
        /// <param name="trades">The list of closed trades</param>
        /// <param name="profitLoss">Trade record of profits and losses</param>
        /// <param name="equity">The list of daily equity values</param>
        /// <param name="pointsPerformance">The list of algorithm performance values</param>
        /// <param name="pointsBenchmark">The list of benchmark values</param>
        /// <param name="startingCapital">The algorithm starting capital</param>
        /// <returns>A dictionary with the rolling performances</returns>
        private static Dictionary<string, AlgorithmPerformance> GetRollingPerformances(
            DateTime firstDate,
            DateTime lastDate,
            List<Trade> trades,
            SortedDictionary<DateTime, decimal> profitLoss,
            SortedDictionary<DateTime, decimal> equity,
            List<ChartPoint> pointsPerformance,
            List<ChartPoint> pointsBenchmark,
            decimal startingCapital)
        {
            var rollingPerformances = new Dictionary<string, AlgorithmPerformance>();

            var monthPeriods = new[] { 1, 3, 6, 12 };
            foreach (var monthPeriod in monthPeriods)
            {
                var ranges = GetPeriodRanges(monthPeriod, firstDate, lastDate);

                foreach (var period in ranges)
                {
                    var key = "M" + monthPeriod + "_" + period.EndDate.ToString("yyyyMMdd");
                    var periodPerformance = GetAlgorithmPerformance(period.StartDate, period.EndDate, trades, profitLoss, equity, pointsPerformance, pointsBenchmark, startingCapital);
                    rollingPerformances[key] = periodPerformance;
                }
            }

            return rollingPerformances;
        }

        /// <summary>
        /// Returns a summary of the algorithm performance as a dictionary
        /// </summary>
        private static Dictionary<string, string> GetSummary(AlgorithmPerformance totalPerformance, decimal totalFees, int totalTransactions)
        {
            return new Dictionary<string, string>
            {
                { "Total Trades", totalTransactions.ToString(CultureInfo.InvariantCulture) },
                { "Average Win", Math.Round(totalPerformance.PortfolioStatistics.AverageWinRate.SafeMultiply100(), 2).ToString(CultureInfo.InvariantCulture) + "%"  },
                { "Average Loss", Math.Round(totalPerformance.PortfolioStatistics.AverageLossRate.SafeMultiply100(), 2).ToString(CultureInfo.InvariantCulture) + "%" },
                { "Compounding Annual Return", Math.Round(totalPerformance.PortfolioStatistics.CompoundingAnnualReturn.SafeMultiply100(), 3).ToString(CultureInfo.InvariantCulture) + "%" },
                { "Drawdown", Math.Round(totalPerformance.PortfolioStatistics.Drawdown.SafeMultiply100(), 3).ToString(CultureInfo.InvariantCulture) + "%" },
                { "Expectancy", Math.Round(totalPerformance.PortfolioStatistics.Expectancy, 3).ToString(CultureInfo.InvariantCulture) },
                { "Net Profit", Math.Round(totalPerformance.PortfolioStatistics.TotalNetProfit.SafeMultiply100(), 3).ToString(CultureInfo.InvariantCulture) + "%"},
                { "Sharpe Ratio", Math.Round((double)totalPerformance.PortfolioStatistics.SharpeRatio, 3).ToString(CultureInfo.InvariantCulture) },
                { "Loss Rate", Math.Round(totalPerformance.PortfolioStatistics.LossRate.SafeMultiply100()).ToString(CultureInfo.InvariantCulture) + "%" },
                { "Win Rate", Math.Round(totalPerformance.PortfolioStatistics.WinRate.SafeMultiply100()).ToString(CultureInfo.InvariantCulture) + "%" },
                { "Profit-Loss Ratio", Math.Round(totalPerformance.PortfolioStatistics.ProfitLossRatio, 2).ToString(CultureInfo.InvariantCulture) },
                { "Alpha", Math.Round((double)totalPerformance.PortfolioStatistics.Alpha, 3).ToString(CultureInfo.InvariantCulture) },
                { "Beta", Math.Round((double)totalPerformance.PortfolioStatistics.Beta, 3).ToString(CultureInfo.InvariantCulture) },
                { "Annual Standard Deviation", Math.Round((double)totalPerformance.PortfolioStatistics.AnnualStandardDeviation, 3).ToString(CultureInfo.InvariantCulture) },
                { "Annual Variance", Math.Round((double)totalPerformance.PortfolioStatistics.AnnualVariance, 3).ToString(CultureInfo.InvariantCulture) },
                { "Information Ratio", Math.Round((double)totalPerformance.PortfolioStatistics.InformationRatio, 3).ToString(CultureInfo.InvariantCulture) },
                { "Tracking Error", Math.Round((double)totalPerformance.PortfolioStatistics.TrackingError, 3).ToString(CultureInfo.InvariantCulture) },
                { "Treynor Ratio", Math.Round((double)totalPerformance.PortfolioStatistics.TreynorRatio, 3).ToString(CultureInfo.InvariantCulture) },
                { "Total Fees", "$" + totalFees.ToString("0.00", CultureInfo.InvariantCulture) }
            };
        }

        private static decimal SafeMultiply100(this decimal value)
        {
            const decimal max = decimal.MaxValue/100m;
            if (value >= max) return decimal.MaxValue;
            return value*100m;
        }

        /// <summary>
        /// Helper class for rolling statistics
        /// </summary>
        private class PeriodRange
        {
            internal DateTime StartDate { get; set; }
            internal DateTime EndDate { get; set; }
        }

        //
        /// <summary>
        /// Gets a list of date ranges for the requested monthly period
        /// </summary>
        /// <remarks>The first and last ranges created are partial periods</remarks>
        /// <param name="periodMonths">The number of months in the period (valid inputs are [1, 3, 6, 12])</param>
        /// <param name="firstDate">The first date of the total period</param>
        /// <param name="lastDate">The last date of the total period</param>
        /// <returns>The list of date ranges</returns>
        private static IEnumerable<PeriodRange> GetPeriodRanges(int periodMonths, DateTime firstDate, DateTime lastDate)
        {
            // get end dates
            var date = lastDate.Date;
            var endDates = new List<DateTime>();
            do
            {
                endDates.Add(date);
                date = new DateTime(date.Year, date.Month, 1).AddDays(-1);
            } while (date >= firstDate);

            // build period ranges
            var ranges = new List<PeriodRange> { new PeriodRange { StartDate = firstDate, EndDate = endDates[endDates.Count - 1] } };
            for (var i = endDates.Count - 2; i >= 0; i--)
            {
                var startDate = ranges[ranges.Count - 1].EndDate.AddDays(1).AddMonths(1 - periodMonths);
                if (startDate < firstDate) startDate = firstDate;

                ranges.Add(new PeriodRange
                {
                    StartDate = startDate,
                    EndDate = endDates[i]
                });
            }

            return ranges;
        }

        /// <summary>
        /// Convert the charting data into an equity array.
        /// </summary>
        /// <remarks>This is required to convert the equity plot into a usable form for the statistics calculation</remarks>
        /// <param name="points">ChartPoints Array</param>
        /// <param name="fromDate">An optional starting date</param>
        /// <param name="toDate">An optional ending date</param>
        /// <returns>SortedDictionary of the equity decimal values ordered in time</returns>
        private static SortedDictionary<DateTime, decimal> ChartPointToDictionary(IEnumerable<ChartPoint> points, DateTime? fromDate = null, DateTime? toDate = null)
        {
            var dictionary = new SortedDictionary<DateTime, decimal>();

            foreach (var point in points)
            {
                var x = Time.UnixTimeStampToDateTime(point.x);

                if (fromDate != null && x.Date < fromDate) continue;
                if (toDate != null && x.Date >= ((DateTime)toDate).AddDays(1)) break;

                dictionary[x] = point.y;
            }

            return dictionary;
        }

        /// <summary>
        /// Creates a list of benchmark differences for the period
        /// </summary>
        /// <param name="benchmark">The benchmark values</param>
        /// <param name="equity">The equity values</param>
        /// <returns>The list of benchmark differences</returns>
        private static List<double> CreateBenchmarkDifferences(SortedDictionary<DateTime, decimal> benchmark, SortedDictionary<DateTime, decimal> equity)
        {
            // to find the delta in benchmark for first day, we need to know the price at
            // the opening moment of the day, but since we cannot find this, we cannot find
            // the first benchmark's delta, so we start looking for data in a inexistent day.
            // If running a short backtest this will skew results, longer backtests will not be affected much
            var dtPrevious = new DateTime();

            var listBenchmark = new List<double>();

            var minDate = equity.Keys.FirstOrDefault().AddDays(-1);
            var maxDate = equity.Keys.LastOrDefault();

            // Get benchmark performance array for same period:
            benchmark.Keys.ToList().ForEach(dt =>
            {
                if (dt >= minDate && dt <= maxDate)
                {
                    decimal previous;
                    if (benchmark.TryGetValue(dtPrevious, out previous) && previous != 0)
                    {
                        var deltaBenchmark = (benchmark[dt] - previous) / previous;
                        listBenchmark.Add((double)deltaBenchmark);
                    }
                    else
                    {
                        listBenchmark.Add(0);
                    }
                    dtPrevious = dt;
                }
            });

            return listBenchmark;
        }

        /// <summary>
        /// Ensures the performance list and benchmark list have the same length, padding with trailing zeros
        /// </summary>
        /// <param name="listPerformance">The performance list</param>
        /// <param name="listBenchmark">The benchmark list</param>
        private static void EnsureSameLength(List<double> listPerformance, List<double> listBenchmark)
        {
            // THIS SHOULD NEVER HAPPEN --> But if it does, log it and fail silently.
            while (listPerformance.Count < listBenchmark.Count)
            {
                listPerformance.Add(0);
                Log.Trace("StatisticsBuilder.EnsureSameLength(): Padded Performance");
            }
            while (listPerformance.Count > listBenchmark.Count)
            {
                listBenchmark.Add(0);
                Log.Trace("StatisticsBuilder.EnsureSameLength(): Padded Benchmark");
            }
        }

    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>CCS Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="$relpath/search.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

MSP430 Driver Library
    1.90.00.65

Main Page

Modules

Data Structures

Files

Related Pages

cygdrive

c

msp430-driverlib

driverlib

MSP430FR57xx

deprecated

CCS

CCS Directory Reference

Files

file  	CCS/msp430fr57xxgeneric.h [code]

Copyright  2014, Texas Instruments Incorporated


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace Meadow.Raspberry
{
    /// <summary>
    /// Defines the correct ID of a pin.
    /// </summary>
    public static class GpioPinUtils
    {
        private static readonly Dictionary<int, int> _PinNumberMap = new Dictionary<int, int>
        {
            { 1, 0 }, { 2, 0 }, { 3, 2 }, { 4, 0 }, { 5, 3 },
            { 6, 0 }, { 7, 4 }, { 8, 14 }, { 9, 0 }, { 10, 15 },

            { 11, 17 }, { 12, 18 }, { 13, 27 }, { 14, 0 }, { 15, 22 },
            { 16, 23 }, { 17, 0 }, { 18, 24 }, { 19, 10 }, { 20, 0 },

            { 21, 9 }, { 22, 25 }, { 23, 11 }, { 24, 8 }, { 25, 0 },
            { 26, 7 }, { 27, 0 }, { 28, 0 }, { 29, 5 }, { 30, 0 },

            { 31, 6 }, { 32, 12 }, { 33, 13 }, { 34, 0 }, { 35, 19 },
            { 36, 16 }, { 37, 26 }, { 38, 20 }, { 39, 0 }, { 40, 21 }
        };

        /// <summary>
        /// Converts a physical pin number to a GPIO pin number.
        /// </summary>
        /// <param name="physicalPinNumber">The physical pin number.</param>
        /// <returns>The GPIO pin number alias of the specified physical pin number.</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="physicalPinNumber"/> is not between 1 and 40 inclusive.</exception>
        [SuppressMessage("ReSharper", "ExceptionNotDocumented")]
        public static int PhysicalNumberToGpioNumber(int physicalPinNumber)
        {
            if (physicalPinNumber < 1 || physicalPinNumber > 40)
            {
                throw new ArgumentOutOfRangeException(nameof(physicalPinNumber), $"{nameof(physicalPinNumber)} must be between 1 and 40.");
            }

            return _PinNumberMap[physicalPinNumber];
        }

        /// <summary>
        /// Converts a GPIO pin number to a physical pin number.
        /// </summary>
        /// <param name="gpioPinNumber">The GPIO pin number.</param>
        /// <param name="bThrowOnInvalidPin">Whether to throw an exception if the specified GPIO pin number is not valid. If false 0 will be returned on failure instead.</param>
        /// <returns>The physical pin number alias of the specified GPIO pin number.</returns>
        /// <exception cref="ArgumentException">Invalid GPIO pin number.</exception>
        public static int GpioNumberToPhysicalnumber(int gpioPinNumber, bool bThrowOnInvalidPin = true)
        {
            int result = _PinNumberMap.FirstOrDefault(p => p.Value == gpioPinNumber).Value;

            if (bThrowOnInvalidPin && result == 0)
            {
                throw new ArgumentException("Invalid GPIO pin number.", nameof(gpioPinNumber));
            }

            return result;
        }
    }
}


text:
using QuantConnect.Data;
using QuantConnect.Data.Market;

namespace QuantConnect.Securities.Option
{
    /// <summary>
    /// Class implements default underlying constant volatility estimator (<see cref="IQLUnderlyingVolatilityEstimator"/>.), that projects the underlying own volatility
    /// model into corresponding option pricing model.
    /// </summary>
    public class ConstantQLUnderlyingVolatilityEstimator : IQLUnderlyingVolatilityEstimator
    {
        /// <summary>
        /// Indicates whether volatility model has been warmed ot not
        /// </summary>
        public bool IsReady { get; private set; }

        /// <summary>
        /// Returns current estimate of the underlying volatility
        /// </summary>
        /// <param name="security">The option security object</param>
        /// <param name="slice">The current data slice. This can be used to access other information
        /// available to the algorithm</param>
        /// <param name="contract">The option contract to evaluate</param>
        /// <returns>The estimate</returns>
        public double Estimate(Security security, Slice slice, OptionContract contract)
        {
            var option = security as Option;

            if (option != null &&
                option.Underlying != null &&
                option.Underlying.VolatilityModel != null &&
                option.Underlying.VolatilityModel.Volatility > 0m)
            {
                IsReady = true;
                return (double)option.Underlying.VolatilityModel.Volatility;
            }

            return 0.0;
        }
    }
}


text:
package com.baidu.cc;

import org.springframework.util.Assert;

import com.baidu.bjf.remoting.mcpack.OperationTimeoutMcpackRpcProxyFactoryBean;
import com.baidu.cc.interfaces.ExtConfigServerService;

/**
 *
 * Client API utility class to access configuration center server.
 *
 * @author xiemalin
 * @since 1.0.1.0
 */
public class ConfigCenterClient {

    /**
     * Configuration center server URI.
     */
    private String ccServerUrl;

    /**
     * Configuration center server user name.
     */
    private String ccUser;

    /**
     * Configuration center server password.
     */
    private String ccPassword;

    /**
     * Request configuration version
     */
    private long ccVersion;

    /**
     * 版本名称,如果不为空,则忽略ccVersion
     */
    private String ccVersionName;

    /**
     * default connection time out value.
     */
    public static final int DEFAULT_CONNECTION_TIMEOUT = 2000;

    /**
     * connection time out value to connect configuration center server.
     */
    private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;

    /**
     * default read time out value.
     */
    public static final int DEFAULT_READ_TIMEOUT = 2000;

    /**
     * set read time out value on reading value from configuration center server.
     */
    private int readTimeout = DEFAULT_READ_TIMEOUT;

    /**
     * default call back interval value.
     */
    public static final long DEFAULT_CALLBACK_INTERVAL = 2000L;

    /**
     * set call back listen call back interval
     */
    private long callbackInteval = DEFAULT_CALLBACK_INTERVAL;

    /**
     * project name
     */
    private String projectName;

    /**
     * set project name
     * @param projectName the projectName to set
     */
    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    /**
     * environment name
     */
    private String envName;

    /**
     * set environment name
     * @param envName the envName to set
     */
    public void setEnvName(String envName) {
        this.envName = envName;
    }

    /**
     * request configuration environment id under specified version.
     */
    private long ccEnvId;

    /**
     * crate {@link ConfigLoader}
     * @return {@link ConfigLoader} instance
     */
    public ConfigLoader createConfigLoader() {
        ccServerUrl = Constants.getServerUrl(ccServerUrl);
        Assert.hasLength(ccServerUrl, "property 'ccServerUrl' is blank.");

        ExtConfigServerService configServerService = createConfigService(ccServerUrl,
                connectionTimeout, readTimeout);

        ConfigLoader configLoader = new ConfigLoader();
        configLoader.setCcEnvId(Constants.getEnvId(String.valueOf(ccEnvId)));
        configLoader.setCcVersion(Constants.getVersion(String.valueOf(ccVersion)));
        configLoader.setProjectName(Constants.getProjectName(projectName));
        configLoader.setEnvName(Constants.getEnvName(envName));
        configLoader.setCcUser(Constants.getUser(ccUser));
        configLoader.setCcPassword(Constants.getPassword(ccPassword));
        configLoader.setCallbackInteval(callbackInteval);
        configLoader.setCcVersionName(Constants.getVersionName(ccVersionName));

        configLoader.setConfigServerService(configServerService);

        configLoader.init();

        return configLoader;
    }

    /**
     * To create {@link ExtConfigServerService} proxy instance.
     *
     * @param ccServerUrl configuration server url
     * @param connectionTimeout connection time out value in ms.
     * @param readTimeout read time out value in ms.
     * @return proxy instance.
     */
    private ExtConfigServerService createConfigService(String ccServerUrl, int connectionTimeout,
            int readTimeout) {
        OperationTimeoutMcpackRpcProxyFactoryBean proxy = new OperationTimeoutMcpackRpcProxyFactoryBean();
        proxy.setServiceUrl(Constants.getServerUrl(ccServerUrl));
        proxy.setServiceInterface(ExtConfigServerService.class);
        proxy.setConnectionTimeout(connectionTimeout);
        proxy.setSoTimeout(readTimeout);

        // do initial
        proxy.afterPropertiesSet();

        return (ExtConfigServerService) proxy.getObject();
    }

    /**
     * set ccServerUrl value to ccServerUrl
     * @param ccServerUrl the ccServerUrl to set
     */
    public void setCcServerUrl(String ccServerUrl) {
        this.ccServerUrl = ccServerUrl;
    }

    /**
     * set ccUser value to ccUser
     * @param ccUser the ccUser to set
     */
    public void setCcUser(String ccUser) {
        this.ccUser = ccUser;
    }

    /**
     * set ccPassword value to ccPassword
     * @param ccPassword the ccPassword to set
     */
    public void setCcPassword(String ccPassword) {
        this.ccPassword = ccPassword;
    }

    /**
     * set ccVersion value to ccVersion
     * @param ccVersion the ccVersion to set
     */
    public void setCcVersion(long ccVersion) {
        this.ccVersion = ccVersion;
    }

    /**
     * set ccVersionName value to ccVersionName
     * @param ccVersionName the ccVersionName to set
     */
    public void setCcVersionName(String ccVersionName) {
        this.ccVersionName = ccVersionName;
    }

    /**
     * set connectionTimeout value to connectionTimeout
     * @param connectionTimeout the connectionTimeout to set
     */
    public void setConnectionTimeout(int connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    /**
     * set readTimeout value to readTimeout
     * @param readTimeout the readTimeout to set
     */
    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }

    /**
     * set callbackInteval value to callbackInteval
     * @param callbackInteval the callbackInteval to set
     */
    public void setCallbackInteval(long callbackInteval) {
        this.callbackInteval = callbackInteval;
    }

    /**
     * set ccEnvId value to ccEnvId
     * @param ccEnvId the ccEnvId to set
     */
    public void setCcEnvId(long ccEnvId) {
        this.ccEnvId = ccEnvId;
    }

}


text:
var exec = require('child_process').exec;
var stats = require('./stats.js');
var downloader = require('./downloader');

var Track = require('../public/scripts/track.js');

var ConversionQueue = function() {};

ConversionQueue.prototype.add = function(req, url, conversionID, callback) {
    exec('casperjs scpwnr.js --log-level=error --format=server ' + url, function(error, stdout, stderr) {
        // Emit an error if conversion script fails
        if (error != null) {
            req.io.emit('conversion-error', {
                id: conversionID,
                consoleMsg: {
                    stdout: stdout,
                    stderr: stderr
                }
            });
            return;
        }

        var tracks = [];

        // Go through all good lines in console output, to retrieve artist|title|url
        var pattern = '(.+)\\|(.+)\\|(.+)\\|(.+)\\|(.*)'
        var regex = new RegExp(pattern, 'gm');
        var goodOutputLines = stdout.match(regex);
        // Remove global for enabling "match" to give capturing groups
        regex = new RegExp(pattern);

        // Filling all tracks with good infos
        for (var i in goodOutputLines) {
            var trackInfos = goodOutputLines[i].match(regex);
            var newTrack = new Track(trackInfos[1], trackInfos[2], trackInfos[3], trackInfos[4], trackInfos[5]);
            tracks.push(newTrack);
        }

        req.io.emit('conversion-finish', {
            id: conversionID,
            tracks: tracks
        });

        for (var i in tracks) {
            // Download the track
            downloader.download(tracks[i], conversionID, req, callback);
        }

    });
};

var module;
if (module && module.exports) {
    module.exports = new ConversionQueue();
}


text:
package org.revenj.postgres.jinq.transform.handlers;

import ch.epfl.labos.iu.orm.queryll2.symbolic.MethodCallValue;
import ch.epfl.labos.iu.orm.queryll2.symbolic.MethodSignature;
import ch.epfl.labos.iu.orm.queryll2.symbolic.TypedValueVisitorException;
import org.revenj.postgres.jinq.jpqlquery.FunctionExpression;
import org.revenj.postgres.jinq.transform.MethodHandlerVirtual;
import org.revenj.postgres.jinq.transform.SymbExToColumns;
import org.revenj.postgres.jinq.jpqlquery.BinaryExpression;
import org.revenj.postgres.jinq.jpqlquery.ColumnExpressions;
import org.revenj.postgres.jinq.jpqlquery.ConstantExpression;
import org.revenj.postgres.jinq.transform.SymbExPassDown;

import java.util.Collections;
import java.util.List;

public class SubstringHandler implements MethodHandlerVirtual {
	@Override
	public List<MethodSignature> getSupportedSignatures() {
		return Collections.singletonList(
				new MethodSignature("java/lang/String", "substring", "(II)Ljava/lang/String;")
		);
	}

	@Override
	public ColumnExpressions<?> handle(
			MethodCallValue.VirtualMethodCallValue val,
			SymbExPassDown in,
			SymbExToColumns columns) throws TypedValueVisitorException {
		SymbExPassDown passdown = SymbExPassDown.with(val, false);
		ColumnExpressions<?> base = val.base.visit(columns, passdown);
		ColumnExpressions<?> startIndex = val.args.get(0).visit(columns, passdown);
		ColumnExpressions<?> endIndex = val.args.get(1).visit(columns, passdown);
		return ColumnExpressions.singleColumn(base.reader,
				FunctionExpression.threeParam("SUBSTRING",
						base.getOnlyColumn(),
						new BinaryExpression(startIndex.getOnlyColumn(), "+", new ConstantExpression("1")),
						new BinaryExpression(endIndex.getOnlyColumn(), "-", startIndex.getOnlyColumn())));
	}
}