text:
#ifndef TUDAT_CREATEONEWAYDOPPLERPARTIALS_H
#define TUDAT_CREATEONEWAYDOPPLERPARTIALS_H

#include <vector>
#include <map>

#include <memory>

#include <Eigen/Core>

#include "Tudat/Mathematics/Interpolators/interpolator.h"

#include "Tudat/Astrodynamics/ObservationModels/ObservableCorrections/lightTimeCorrection.h"
#include "Tudat/SimulationSetup/EstimationSetup/createCartesianStatePartials.h"
#include "Tudat/SimulationSetup/EstimationSetup/createLightTimeCalculator.h"
#include "Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/oneWayDopplerPartial.h"
#include "Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/twoWayDopplerPartial.h"
#include "Tudat/Astrodynamics/OrbitDetermination/EstimatableParameters/initialTranslationalState.h"
#include "Tudat/Astrodynamics/ObservationModels/linkTypeDefs.h"
#include "Tudat/Astrodynamics/ObservationModels/observableTypes.h"
#include "Tudat/Astrodynamics/ObservationModels/twoWayDopplerObservationModel.h"
#include "Tudat/SimulationSetup/EstimationSetup/createLightTimeCorrectionPartials.h"

namespace tudat
{

namespace observation_partials
{

//! Function to generate one-way doppler partial wrt a single  parameter.
/*!
 *  Function to generate one-way doppler partial wrt a single  parameter, for a single link ends (which must contain a
 *  transmitter and receiever  linkEndType).
 *  \tparam ParameterType Type of parameter (double for size 1, VectorXd for larger size).
 *  \param oneWayDopplerLinkEnds Link ends (transmitter and receiever) for which one-way doppler partials are to be calculated
 *  (i.e. for which  one-way doppler observations are to be processed).
 *  \param bodyMap List of all bodies, for creating one-way doppler partial.
 *  \param parameterToEstimate Object of current parameter that is to be estimated.
 *  \param oneWayDopplerScaler Object scale position partials to one-way doppler partials for current link ends.
 *  \param lightTimeCorrectionPartialObjects List of light time correction partials to be used (empty by default)
 *  \return One-way doppler partial object wrt a single parameter (is nullptr if no parameter dependency exists).
 */
template< typename ParameterType >
std::shared_ptr< ObservationPartial< 1 > > createOneWayDopplerPartialWrtParameter(
        const observation_models::LinkEnds oneWayDopplerLinkEnds,
        const simulation_setup::NamedBodyMap& bodyMap,
        const std::shared_ptr< estimatable_parameters::EstimatableParameter< ParameterType > > parameterToEstimate,
        const std::shared_ptr< OneWayDopplerScaling > oneWayDopplerScaler,
        const std::vector< std::shared_ptr< observation_partials::LightTimeCorrectionPartial > >&
        lightTimeCorrectionPartialObjects =
        std::vector< std::shared_ptr< observation_partials::LightTimeCorrectionPartial > >( ) )
{
    if( std::dynamic_pointer_cast< OneWayDopplerScaling >( oneWayDopplerScaler ) == nullptr )
    {
        throw std::runtime_error( "Error, expected one-way doppler scaling when making one-way doppler partial" );
    }
    std::shared_ptr< ObservationPartial< 1 > > oneWayDopplerPartial;

    {
        std::map< observation_models::LinkEndType, std::shared_ptr< CartesianStatePartial > > positionPartials =
                createCartesianStatePartialsWrtParameter( oneWayDopplerLinkEnds, bodyMap, parameterToEstimate );

        // Create one-doppler partials if any position partials are created (i.e. if any dependency exists).
        std::shared_ptr< OneWayDopplerPartial > testOneWayDopplerPartial  = std::make_shared< OneWayDopplerPartial >(
                    std::dynamic_pointer_cast< OneWayDopplerScaling >( oneWayDopplerScaler ),
                    positionPartials, parameterToEstimate->getParameterName( ),
                    lightTimeCorrectionPartialObjects );

        if( positionPartials.size( ) > 0 || testOneWayDopplerPartial->getNumberOfLighTimeCorrectionPartialsFunctions( ) > 0
                || oneWayDopplerScaler->getProperTimeParameterDependencySize( parameterToEstimate->getParameterName( ) ) > 0 )
        {
            oneWayDopplerPartial = testOneWayDopplerPartial;
        }
    }

    // Return doppler partial object (nullptr if no dependency exists).
    return oneWayDopplerPartial;
}

//! Function to generate one-way doppler partial wrt a position of a body.
/*!
 *  Function to generate one-way doppler partial wrt a position of a body, for a single link ends (which must contain a
 *  transmitter and receiever  linkEndType).
 *  \param oneWayDopplerLinkEnds Link ends (transmitter and receiever) for which one-way doppler partials are to be calculated
 *  (i.e. for which one-way doppler observations are to be processed).
 *  \param bodyMap List of all bodies, for creating one-way doppler partial.
 *  \param bodyToEstimate Name of body wrt position of which a partial is to be created.
 *  \param oneWayDopplerScaler Object scale position partials to one-way doppler partials for current link ends.
 *  \param lightTimeCorrectionPartialObjects List of light time correction partials to be used (empty by default)
 *  \return One-way doppler partial object wrt a current position of a body (is nullptr if no parameter dependency exists).
 */
std::shared_ptr< OneWayDopplerPartial > createOneWayDopplerPartialWrtBodyState(
        const observation_models::LinkEnds oneWayDopplerLinkEnds,
        const simulation_setup::NamedBodyMap& bodyMap,
        const std::string bodyToEstimate,
        const std::shared_ptr< PositionPartialScaling > oneWayDopplerScaler,
        const std::vector< std::shared_ptr< observation_partials::LightTimeCorrectionPartial > >&
        lightTimeCorrectionPartialObjects =
        std::vector< std::shared_ptr< observation_partials::LightTimeCorrectionPartial > >( ) );

//! Function to create an object that computes the scaling of the state partials to obtain proper time rate partials
/*!
 * Function to create an object that computes the scaling of the state partials to obtain proper time rate partials. A single
 * scaling object is used for a single link end of the one-way Doppler partials
 * \param dopplerProperTimeInterface Object that is used to computed proper-time rate in one-way Doppler modelkkl
 * \param oneWayDopplerLinkEnds Link ends of observable
 * \param linkEndAtWhichPartialIsComputed Link end for which proper-time partials are to be created
 * \return Scaling object for proper-time rate partials
 */
std::shared_ptr< OneWayDopplerProperTimeComponentScaling > createDopplerProperTimePartials(
        const std::shared_ptr< observation_models::DopplerProperTimeRateInterface > dopplerProperTimeInterface,
        const observation_models::LinkEnds oneWayDopplerLinkEnds,
        const observation_models::LinkEndType linkEndAtWhichPartialIsComputed  );

//! Function to generate one-way doppler partials and associated scaler for single link end.
/*!
 *  Function to generate one-way doppler partials and associated scaler for all parameters that are to be estimated,
 *  for a single link ends.
 *  The set of parameters and bodies that are to be estimated, as well as the set of link ends
 *  (each of which must contain a transmitter and receiever linkEndType) that are to be used.
 *  \param oneWayDopplerLinkEnds Link ends (transmitter and receiever) for which one-way doppler partials are to be calculated
 *  (i.e. for which one-way doppler observations are to be processed).
 *  \param bodyMap List of all bodies, for creating one-way doppler partials.
 *  \param parametersToEstimate Set of parameters that are to be estimated (in addition to initial states of
 *  requested bodies)
 *  \param transmitterDopplerProperTimeInterface Proper time rate calculator for transmitter
 *  \param receiverDopplerProperTimeInterface Proper time rate calculator for receiver
 *  \param lightTimeCorrections List of light time correction partials to be used (empty by default)
 *  \param useBiasPartials Boolean to denote whether this function should create partials w.r.t. observation bias parameters
 *  \return Set of observation partials with associated indices in complete vector of parameters that are estimated,
 *  representing all  necessary one-way doppler partials of a single link end, and OneWayDopplerScaling, object, used for
 *  scaling the position partial members of all OneWayDopplerPartials in link end.
 */
template< typename ParameterType >
std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > createOneWayDopplerPartials(
        const observation_models::LinkEnds oneWayDopplerLinkEnds,
        const simulation_setup::NamedBodyMap& bodyMap,
        const std::shared_ptr< estimatable_parameters::EstimatableParameterSet< ParameterType > > parametersToEstimate,
        const std::shared_ptr< observation_models::DopplerProperTimeRateInterface > transmitterDopplerProperTimeInterface,
        const std::shared_ptr< observation_models::DopplerProperTimeRateInterface > receiverDopplerProperTimeInterface,
        const std::vector< std::shared_ptr< observation_models::LightTimeCorrection > >& lightTimeCorrections =
        std::vector< std::shared_ptr< observation_models::LightTimeCorrection > >( ),
        const bool useBiasPartials = true )
{
    std::vector< std::shared_ptr< observation_partials::LightTimeCorrectionPartial > > lightTimeCorrectionPartialObjects;
    if( lightTimeCorrections.size( ) > 0 )
    {
        lightTimeCorrectionPartialObjects = observation_partials::createLightTimeCorrectionPartials( lightTimeCorrections );
    }

    std::function< Eigen::Vector6d( const double )> transmitterNumericalStateDerivativeFunction =
            std::bind( &numerical_derivatives::computeCentralDifferenceFromFunction< Eigen::Vector6d, double >,
                         observation_models::getLinkEndCompleteEphemerisFunction< double, double >(
                             oneWayDopplerLinkEnds.at( observation_models::transmitter ), bodyMap ), std::placeholders::_1, 100.0,
                         numerical_derivatives::order8 );
    std::function< Eigen::Vector6d( const double )> receiverNumericalStateDerivativeFunction =
            std::bind( numerical_derivatives::computeCentralDifferenceFromFunction< Eigen::Vector6d, double >,
                         observation_models::getLinkEndCompleteEphemerisFunction< double, double >(
                             oneWayDopplerLinkEnds.at( observation_models::receiver ), bodyMap ), std::placeholders::_1, 100.0,
                         numerical_derivatives::order8 );

    // Create scaling object, to be used for all one-way doppler partials in current link end.
    std::shared_ptr< OneWayDopplerProperTimeComponentScaling > transmitterProperTimePartials =
            createDopplerProperTimePartials( transmitterDopplerProperTimeInterface, oneWayDopplerLinkEnds,
                                             observation_models::transmitter );
    std::shared_ptr< OneWayDopplerProperTimeComponentScaling > receiverProperTimePartials =
            createDopplerProperTimePartials( receiverDopplerProperTimeInterface, oneWayDopplerLinkEnds,
                                             observation_models::receiver  );

    std::shared_ptr< OneWayDopplerScaling > oneWayDopplerScaling = std::make_shared< OneWayDopplerScaling >(
                std::bind( &linear_algebra::evaluateSecondBlockInStateVector, transmitterNumericalStateDerivativeFunction, std::placeholders::_1 ),
                std::bind( &linear_algebra::evaluateSecondBlockInStateVector, receiverNumericalStateDerivativeFunction, std::placeholders::_1 ),
                transmitterProperTimePartials,
                receiverProperTimePartials );

    // Initialize vector index variables.
    int currentIndex = 0;
    std::pair< int, int > currentPair = std::pair< int, int >( currentIndex, 1 );

    SingleLinkObservationPartialList dopplerPartials;

    std::vector< std::shared_ptr< estimatable_parameters::EstimatableParameter<
            Eigen::Matrix< ParameterType, Eigen::Dynamic, 1 > > > > initialDynamicalParameters =
            parametersToEstimate->getEstimatedInitialStateParameters( );

    // Iterate over list of bodies of which the partials of the accelerations acting on them are required.
    for( unsigned int i = 0; i < initialDynamicalParameters.size( ); i++ )
    {
        std::string acceleratedBody;
        if( initialDynamicalParameters.at( i )->getParameterName( ).first == estimatable_parameters::initial_body_state ||
                ( initialDynamicalParameters.at( i )->getParameterName( ).first == estimatable_parameters::arc_wise_initial_body_state ) )
        {
            acceleratedBody = initialDynamicalParameters.at( i )->getParameterName( ).second.first;
        }
        else
        {
            throw std::runtime_error( "Error when making one way doppler partials, could not identify parameter " +
                                      std::to_string(
                                          initialDynamicalParameters.at( i )->getParameterName( ).first ) );
        }

        // Create position one-way doppler partial for current body
        std::shared_ptr< ObservationPartial< 1 > > currentDopplerPartialWrtPosition = createOneWayDopplerPartialWrtBodyState(
                    oneWayDopplerLinkEnds, bodyMap, acceleratedBody, oneWayDopplerScaling, lightTimeCorrectionPartialObjects );

        // Check if partial is non-nullptr (i.e. whether dependency exists between current doppler and current body)
        if( currentDopplerPartialWrtPosition != nullptr )
        {
            // Add partial to the list.
            currentPair = std::pair< int, int >( currentIndex, 6 );
            dopplerPartials[ currentPair ] = currentDopplerPartialWrtPosition;
        }

        // Increment current index by size of body initial state (6).
        currentIndex += 6;
    }

    // Iterate over all double parameters that are to be estimated.
    std::map< int, std::shared_ptr< estimatable_parameters::EstimatableParameter< double > > > doubleParametersToEstimate =
            parametersToEstimate->getDoubleParameters( );
    for( std::map< int, std::shared_ptr< estimatable_parameters::EstimatableParameter< double > > >::iterator
         parameterIterator =
         doubleParametersToEstimate.begin( ); parameterIterator != doubleParametersToEstimate.end( ); parameterIterator++ )
    {
        // Create position one-way doppler partial for current parameter
        std::shared_ptr< ObservationPartial< 1 > > currentDopplerPartial = createOneWayDopplerPartialWrtParameter(
                    oneWayDopplerLinkEnds, bodyMap, parameterIterator->second,
                    oneWayDopplerScaling, lightTimeCorrectionPartialObjects );

        // Check if partial is non-nullptr (i.e. whether dependency exists between current doppler and current parameter)
        if( currentDopplerPartial != nullptr )
        {
            // Add partial to the list.
            currentPair = std::pair< int, int >( parameterIterator->first, 1 );
            dopplerPartials[ currentPair ] = currentDopplerPartial;
        }
    }

    // Iterate over all vector parameters that are to be estimated.
    std::map< int, std::shared_ptr< estimatable_parameters::EstimatableParameter< Eigen::VectorXd > > >
            vectorParametersToEstimate =
            parametersToEstimate->getVectorParameters( );
    for( std::map< int, std::shared_ptr< estimatable_parameters::EstimatableParameter< Eigen::VectorXd  > > >::iterator
         parameterIterator =
         vectorParametersToEstimate.begin( ); parameterIterator != vectorParametersToEstimate.end( ); parameterIterator++ )
    {

        std::shared_ptr< ObservationPartial< 1 > > currentDopplerPartial;
        if( !isParameterObservationLinkProperty( parameterIterator->second->getParameterName( ).first )  )
        {
            currentDopplerPartial = createOneWayDopplerPartialWrtParameter(
                        oneWayDopplerLinkEnds, bodyMap, parameterIterator->second, oneWayDopplerScaling,
                        lightTimeCorrectionPartialObjects );
        }
        else
        {
            currentDopplerPartial = createObservationPartialWrtLinkProperty< 1 >(
                        oneWayDopplerLinkEnds, observation_models::one_way_doppler, parameterIterator->second, useBiasPartials );
        }

        // Check if partial is non-nullptr (i.e. whether dependency exists between current doppler and current parameter)
        if( currentDopplerPartial != nullptr )
        {
            // Add partial to the list.
            currentPair = std::pair< int, int >( parameterIterator->first,
                                                 parameterIterator->second->getParameterSize( ) );
            dopplerPartials[ currentPair ] = currentDopplerPartial;
        }
    }

    // Return complete set of partials and scaling object.
    return std::make_pair( dopplerPartials, oneWayDopplerScaling );
}

//! Function to generate one-way doppler partials for all parameters that are to be estimated, for all sets of link ends.
/*!
 *  Function to generate one-way doppler partials for all parameters that are to be estimated, for all sets of link ends.
 *  The one-way doppler partials are generated per set of link ends. The set of parameters and bodies that are to be
 *  estimated, as well as the set of link ends (each of which must contain a transmitter and receiever linkEndType)
 *  that are to be used.
 *  \param observationModelList List of all observation models (must be one-way Doppler) for which partials are to be created,
 *  with map key being the link ends
 *  \param bodyMap List of all bodies, for creating one-way doppler partials.
 *  \param parametersToEstimate Set of parameters that are to be estimated (in addition to initial states
 *  of requested bodies)
 *  \param useBiasPartials Boolean to denote whether this function should create partials w.r.t. observation bias parameters
 *  \return Map of SingleLinkObservationPartialList, representing all necessary one-way doppler partials of a single link end,
 *  and OneWayDopplerScaling, object, used for scaling the position partial members of all OneWayDopplerPartials in link end.
 */
template< typename ObservationScalarType, typename TimeType >
std::map< observation_models::LinkEnds, std::pair< SingleLinkObservationPartialList,
std::shared_ptr< PositionPartialScaling > > > createOneWayDopplerPartials(
        const std::map< observation_models::LinkEnds,
        std::shared_ptr< observation_models::ObservationModel< 1, ObservationScalarType, TimeType > > > observationModelList,
        const simulation_setup::NamedBodyMap& bodyMap,
        const std::shared_ptr< estimatable_parameters::EstimatableParameterSet< ObservationScalarType > > parametersToEstimate,
        const bool useBiasPartials = true )
{
    // Declare return list.
    std::map< observation_models::LinkEnds, std::pair< SingleLinkObservationPartialList,
            std::shared_ptr< PositionPartialScaling > > > dopplerPartials;

    // Iterate over all link ends.
    for( auto linkIterator: observationModelList )
    {
        // Check if required link end types are present
        if( ( linkIterator.first.count( observation_models::receiver ) == 0 ) ||
                ( linkIterator.first.count( observation_models::transmitter ) == 0 ) )
        {
            throw std::runtime_error( "Error when making 1-way doppler partials, did not find both receiver and transmitter in link ends" );

        }

        std::shared_ptr< observation_models::OneWayDopplerObservationModel< ObservationScalarType, TimeType > >
                dopplerObservationModel =
                std::dynamic_pointer_cast< observation_models::OneWayDopplerObservationModel
                < ObservationScalarType, TimeType > >( linkIterator.second );

        std::vector< std::shared_ptr< observation_models::LightTimeCorrection > > singleLinkLightTimeCorrections;
        if( dopplerObservationModel == nullptr )
        {
            throw std::runtime_error( "Error when making one-way Doppler partials. Type is inconsistent" );
        }
        else
        {
            singleLinkLightTimeCorrections = dopplerObservationModel->getLightTimeCalculator( )->getLightTimeCorrection( );
        }

        // Create doppler partials for current link ends
        dopplerPartials[ linkIterator.first ] = createOneWayDopplerPartials< ObservationScalarType >(
                    linkIterator.first, bodyMap, parametersToEstimate,
                    dopplerObservationModel->getTransmitterProperTimeRateCalculator( ),
                    dopplerObservationModel->getReceiverProperTimeRateCalculator( ),
                    singleLinkLightTimeCorrections, useBiasPartials );
    }

    // Return complete set of link ends.
    return dopplerPartials;
}

//! Function to generate tow-way Doppler partials and associated scaler for single link ends.
/*!
 *  Function to generate tow-way Doppler partials and associated scaler for all parameters that are to be estimated,
 *  for a single link ends set.
 *  The set of parameters and bodies that are to be estimated, as well as the set of link ends
 *  (each of which must contain a transmitter and receiever linkEndType) that are to be used.
 *  The tow-way Doppler partials are built from one-way Doppler partials of the constituent links
 *  \param twoWayDopplerLinkEnds Link ends (transmitter and receiever) for which tow-way Doppler partials are to be calculated
 *  (i.e. for which tow-way Doppler observations are to be processed).
 *  \param twoWayObservationModel Observation model for two-way Doppler for which partials are to be created
 *  \param bodyMap List of all bodies, for creating tow-way Doppler partials.
 *  \param parametersToEstimate Set of parameters that are to be estimated (in addition to initial states of
 *  requested bodies)
 *  \param lightTimeCorrections List of light time correction partials to be used (empty by default). First vector entry is
 *  index of link in 2-way link ends (up and downlink), second vector is list of light-time corrections.
 *  \return Set of observation partials with associated indices in complete vector of parameters that are estimated,
 *  representing all  necessary two-way Doppler partials of a single link end, and TwoWayDopplerScaling, object, used for
 *  scaling the position partial members of all TwoWayDopplerPartials in link end.
 */
template< typename ParameterType, typename TimeType >
std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > createTwoWayDopplerPartials(
        const observation_models::LinkEnds& twoWayDopplerLinkEnds,
        const std::shared_ptr< observation_models::TwoWayDopplerObservationModel< ParameterType, TimeType > >
        twoWayObservationModel,
        const simulation_setup::NamedBodyMap& bodyMap,
        const std::shared_ptr< estimatable_parameters::EstimatableParameterSet< ParameterType > > parametersToEstimate,
        const std::vector< std::vector< std::shared_ptr< observation_models::LightTimeCorrection > > > lightTimeCorrections =
        std::vector< std::vector< std::shared_ptr< observation_models::LightTimeCorrection > > >( ) )

{

    // Define list of constituent one-way partials.
    typedef std::vector< std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > >
            OneWayPartialList;
    OneWayPartialList constituentOneWayDopplerPartials;
    OneWayPartialList constituentOneWayRangePartials;

    int numberOfLinkEnds = 3;
    observation_models::LinkEnds currentLinkEnds;

    // Iterate over all links in the two-way Doppler observable
    std::vector< std::function< double( const double, const observation_models::LinkEndType ) > > oneWayDopplerModels;
    std::vector< std::shared_ptr< observation_models::LightTimeCorrection > > currentLightTimeCorrections;
    for( int i = 0; i < numberOfLinkEnds - 1; i++ )
    {
        currentLightTimeCorrections.clear( );
        if( lightTimeCorrections.size( ) > 0 )
        {
            currentLightTimeCorrections = lightTimeCorrections.at( i );
        }

        // Define links for current one-way Doppler link
        currentLinkEnds.clear( );
        currentLinkEnds[ observation_models::transmitter ] = twoWayDopplerLinkEnds.at(
                    observation_models::getNWayLinkEnumFromIndex( i, 3 ) );
        currentLinkEnds[ observation_models::receiver ] = twoWayDopplerLinkEnds.at(
                    observation_models::getNWayLinkEnumFromIndex( i + 1, 3 ) );

        std::shared_ptr< observation_models::DopplerProperTimeRateInterface > transmitterDopplerProperTimeInterface;
        std::shared_ptr< observation_models::DopplerProperTimeRateInterface > receiverDopplerProperTimeInterface;
        if( i == 0 )
        {
            transmitterDopplerProperTimeInterface =
                    twoWayObservationModel->getUplinkDopplerCalculator( )->getTransmitterProperTimeRateCalculator( );
            receiverDopplerProperTimeInterface =
                    twoWayObservationModel->getUplinkDopplerCalculator( )->getReceiverProperTimeRateCalculator( );
            oneWayDopplerModels.push_back(
                        observation_models::getSizeOneObservationFunctionAtDoublePrecisionFromObservationModel<
                        ParameterType, TimeType >( twoWayObservationModel->getUplinkDopplerCalculator( ) ) );

        }
        else if( i == 1 )
        {
            transmitterDopplerProperTimeInterface =
                    twoWayObservationModel->getDownlinkDopplerCalculator( )->getTransmitterProperTimeRateCalculator( );
            receiverDopplerProperTimeInterface =
                    twoWayObservationModel->getDownlinkDopplerCalculator( )->getReceiverProperTimeRateCalculator( );
            oneWayDopplerModels.push_back(
                        observation_models::getSizeOneObservationFunctionAtDoublePrecisionFromObservationModel<
                        ParameterType, TimeType >( twoWayObservationModel->getDownlinkDopplerCalculator( ) ) );
        }

        // Create one-way Doppler partials for current link
        constituentOneWayDopplerPartials.push_back(
                    createOneWayDopplerPartials(
                        currentLinkEnds, bodyMap, parametersToEstimate, transmitterDopplerProperTimeInterface,
                        receiverDopplerProperTimeInterface, currentLightTimeCorrections, false ) );
        constituentOneWayRangePartials.push_back(
                    createOneWayRangePartials( currentLinkEnds, bodyMap, parametersToEstimate,
                                               currentLightTimeCorrections ) );
    }

    // Retrieve sorted (by parameter index and link index) one-way range partials and (by link index) opne-way range partials
    std::vector< std::shared_ptr< OneWayDopplerScaling > > oneWayDopplerScalers;
    std::vector< std::shared_ptr< OneWayRangeScaling > > oneWayRangeScalings;

    std::map< std::pair< int, int >, std::map< int, std::shared_ptr< ObservationPartial< 1 > > > > sortedOneWayDopplerPartials;
    std::map< std::pair< int, int >, std::map< int, std::shared_ptr< ObservationPartial< 1 > > > > sortedOneWayRangePartials;

    std::map< std::pair< int, int >, estimatable_parameters::EstimatebleParameterIdentifier > parameterIdList;
    for( unsigned int i = 0; i < constituentOneWayDopplerPartials.size( ); i++ )
    {
        // Retrieve one-way Doppler paritals
        oneWayDopplerScalers.push_back( std::dynamic_pointer_cast< OneWayDopplerScaling >
                                        ( constituentOneWayDopplerPartials.at( i ).second ) );
        oneWayRangeScalings.push_back( std::dynamic_pointer_cast< OneWayRangeScaling >
                                       ( constituentOneWayRangePartials.at( i ).second ) );

        // Iterate over all one-way Doppler partials of current link
        for( SingleLinkObservationPartialList::iterator parameterIterator = constituentOneWayDopplerPartials.at( i ).first.begin( );
             parameterIterator != constituentOneWayDopplerPartials.at( i ).first.end( ); parameterIterator++ )
        {
            sortedOneWayDopplerPartials[ parameterIterator->first ][ i ] = parameterIterator->second;
            if( parameterIdList.count( parameterIterator->first ) == 0 )
            {
                parameterIdList[ parameterIterator->first ] = parameterIterator->second->getParameterIdentifier( );
            }
            else if( parameterIdList.at( parameterIterator->first ) != parameterIterator->second->getParameterIdentifier( ) )
            {
                throw std::runtime_error( "Error when making two way Doppler partial, parameter indices in Doppler are inconsistent" );
            }
        }

        // Iterate over all one-way range partials of current link
        for( SingleLinkObservationPartialList::iterator parameterIterator = constituentOneWayRangePartials.at( i ).first.begin( );
             parameterIterator != constituentOneWayRangePartials.at( i ).first.end( ); parameterIterator++ )
        {
            sortedOneWayRangePartials[ parameterIterator->first ][ i ] = parameterIterator->second;
            if( parameterIdList.count( parameterIterator->first ) == 0 )
            {
                parameterIdList[ parameterIterator->first ] = parameterIterator->second->getParameterIdentifier( );
            }
            else if( parameterIdList.at( parameterIterator->first ) != parameterIterator->second->getParameterIdentifier( ) )
            {
                throw std::runtime_error( "Error when making two way Doppler partial, parameter indices in range are inconsistent" );
            }
        }
    }

    // Create two-way Doppler scaling object
    std::shared_ptr< TwoWayDopplerScaling > twoWayDopplerScaler = std::make_shared< TwoWayDopplerScaling >(
                oneWayDopplerScalers, oneWayRangeScalings, oneWayDopplerModels );

    // Define return partial list
    SingleLinkObservationPartialList twoWayDopplerPartialList;

    // Create two-way Doppler partial objects
    for( std::map< std::pair< int, int >, std::map< int, std::shared_ptr< ObservationPartial< 1 > > > >::iterator sortedPartialIterator =
         sortedOneWayDopplerPartials.begin( ); sortedPartialIterator != sortedOneWayDopplerPartials.end( ); sortedPartialIterator++ )
    {
        std::map< int, std::shared_ptr< ObservationPartial< 1 > > > currentDopplerPartialList = sortedPartialIterator->second;
        std::map< int, std::shared_ptr< ObservationPartial< 1 > > > currentRangePartialList;
        if( sortedOneWayRangePartials.count( sortedPartialIterator->first ) != 0 )
        {
            currentRangePartialList = sortedOneWayRangePartials.at( sortedPartialIterator->first );
        }

        twoWayDopplerPartialList[ sortedPartialIterator->first ] = std::make_shared< TwoWayDopplerPartial >(
                    twoWayDopplerScaler, currentDopplerPartialList, currentRangePartialList,
                    parameterIdList.at( sortedPartialIterator->first ), numberOfLinkEnds );
    }

    // Create two-way Doppler partial objects that only have range dependencies.
    for( std::map< std::pair< int, int >, std::map< int, std::shared_ptr< ObservationPartial< 1 > > > >::iterator sortedPartialIterator =
         sortedOneWayRangePartials.begin( ); sortedPartialIterator != sortedOneWayRangePartials.end( ); sortedPartialIterator++ )
    {
        if( sortedOneWayDopplerPartials.count( sortedPartialIterator->first ) == 0 )
        {
            std::map< int, std::shared_ptr< ObservationPartial< 1 > > > currentDopplerPartialList;
            std::map< int, std::shared_ptr< ObservationPartial< 1 > > > currentRangePartialList = sortedPartialIterator->second;

            twoWayDopplerPartialList[ sortedPartialIterator->first ] = std::make_shared< TwoWayDopplerPartial >(
                        twoWayDopplerScaler, currentDopplerPartialList, currentRangePartialList,
                        parameterIdList.at( sortedPartialIterator->first ), numberOfLinkEnds );
        }
    }

    // Create two-way Doppler partials
    std::map< int, std::shared_ptr< estimatable_parameters::EstimatableParameter< Eigen::VectorXd > > >
            vectorParametersToEstimate =  parametersToEstimate->getVectorParameters( );
    for( std::map< int, std::shared_ptr< estimatable_parameters::EstimatableParameter< Eigen::VectorXd  > > >::iterator
         parameterIterator =
         vectorParametersToEstimate.begin( ); parameterIterator != vectorParametersToEstimate.end( ); parameterIterator++ )
    {

        std::shared_ptr< ObservationPartial< 1 > > currentTwoWayDopplerPartial;
        if( isParameterObservationLinkProperty( parameterIterator->second->getParameterName( ).first )  )
        {
            currentTwoWayDopplerPartial = createObservationPartialWrtLinkProperty< 1 >(
                        twoWayDopplerLinkEnds, observation_models::two_way_doppler, parameterIterator->second );
        }

        // Check if partial is non-nullptr (i.e. whether dependency exists between current doppler and current parameter)
        if( currentTwoWayDopplerPartial != nullptr )
        {
            // Add partial to the list.
            std::pair< double, double > currentPair = std::pair< int, int >( parameterIterator->first,
                                                 parameterIterator->second->getParameterSize( ) );
            twoWayDopplerPartialList[ currentPair ] = currentTwoWayDopplerPartial;
        }
    }

    return std::make_pair( twoWayDopplerPartialList, twoWayDopplerScaler );
}

//! Function to generate two-way Doppler partials for all parameters that are to be estimated, for all sets of link ends.
/*!
 *  Function to generate two-way Doppler partials for all parameters that are to be estimated, for all sets of link ends.
 *  The two-way Doppler partials are generated per set of link ends. The set of parameters and bodies that are to be
 *  estimated, as well as the set of link ends (each of which must contain a transmitter and receiever linkEndType)
 *  that are to be used.
 *  The two-way Doppler partials are built from one-way range partials of the constituent links
 *  \param observationModelList List of all two-way Doppler models (as a function of LinkEnds) for which partials are to be
 *  created.
 *  \param bodyMap List of all bodies, for creating two-way Doppler partials.
 *  \param parametersToEstimate Set of parameters that are to be estimated (in addition to initial states
 *  of requested bodies)
 *  \param lightTimeCorrections List of light time correction used (empty by default). First vector entry is
 *  index of link in 2-way link ends (up and downlink), second vector is list of light-time corrections.
 *  \return Map of SingleLinkObservationPartialList, representing all necessary two-way Doppler partials of a single link end,
 *  and TwoWayDopplerScaling, object, used for scaling the position partial members of all TwoWayDopplerPartials in link end.
 */
template< typename ParameterType, typename TimeType >
std::map< observation_models::LinkEnds, std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > >
createTwoWayDopplerPartials(
        const std::map< observation_models::LinkEnds,
        std::shared_ptr< observation_models::ObservationModel< 1, ParameterType, TimeType > > > observationModelList,
        const simulation_setup::NamedBodyMap& bodyMap,
        const std::shared_ptr< estimatable_parameters::EstimatableParameterSet< ParameterType > > parametersToEstimate,
        const std::map< observation_models::LinkEnds,
        std::vector< std::vector< std::shared_ptr< observation_models::LightTimeCorrection > > > >& lightTimeCorrections =
        std::map< observation_models::LinkEnds,
        std::vector< std::vector< std::shared_ptr< observation_models::LightTimeCorrection > > > >( ) )
{
    std::map< observation_models::LinkEnds,
            std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > > partialMap;
    std::vector< std::vector< std::shared_ptr< observation_models::LightTimeCorrection > > > currentLightTimeCorrections;

    // Iterate over all sets of link ends, and  create associated two-way Doppler partials
    for( typename std::map< observation_models::LinkEnds,
         std::shared_ptr< observation_models::ObservationModel< 1, ParameterType, TimeType > > >::const_iterator modelIterator =
         observationModelList.begin( ); modelIterator != observationModelList.end( ); modelIterator++ )
    {
        // Retrieve light-time corrections
        if( lightTimeCorrections.count( modelIterator->first ) > 0 )
        {
            currentLightTimeCorrections = lightTimeCorrections.at( modelIterator->first );
        }
        else
        {
            currentLightTimeCorrections.clear( );
        }

        // Create two-way Doppler partials for current LinkEnds
        partialMap[ modelIterator->first ] = createTwoWayDopplerPartials< ParameterType, TimeType >(
                    modelIterator->first, std::dynamic_pointer_cast< observation_models::TwoWayDopplerObservationModel<
                    ParameterType, TimeType > >( modelIterator->second ), bodyMap, parametersToEstimate,
                    currentLightTimeCorrections );
    }

    return partialMap;
}

}

}

#endif // TUDAT_CREATEONEWAYDOPPLERPARTIALS_H


text:
package lispy;

import java.util.List;

@SuppressWarnings("rawtypes")
public interface Function {
	Object apply(List args);
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const expect = require('chai').expect;
const path = require('path');

describe('utils : stripVersion', () => {
  const stripVersion = require('../../dist/utils/strip-version').default;

  describe('when a non scoped dependency is provided', () => {
    const dependency = '/path/to/dependency';

    describe('when a version is included', () => {
      const name = stripVersion(dependency + '@1.0.0');

      it('should return the dependency without the version', () => {
        expect(name).to.equal(path.join('/path/to/dependency'));
      });
    });

    describe('when a version is not included', () => {
      const name = stripVersion(dependency);

      it('should return the unmodified dependency', () => {
        expect(name).to.equal(path.join('/path/to/dependency'));
      });
    });
  });

  describe('when a scoped dependency is provided', () => {
    const dependency = '/path/to/@the-scoped/package';

    describe('when a version is included', () => {
      const name = stripVersion(dependency + '@1.2.3');

      it('should return the dependency without the version', () => {
        expect(name).to.equal(path.join('/path/to/@the-scoped/package'));
      });
    });

    describe('when a version is not included', () => {
      const name = stripVersion(dependency);

      it('should return the unmodified dependency', () => {
        expect(name).to.equal(path.join('/path/to/@the-scoped/package'));
      });
    });
  });
});


text:
using namespace 	std;
using namespace 	sf;

int main()
{
  Event			event;
  //Joystick		joy00;
  Hero			*hero;

  hero = new Hero();

  RenderWindow window(VideoMode(800,600), "Gotcha Game Industry");
  window.setFramerateLimit(60);

  while(window.isOpen())
    {
      while(window.pollEvent(event))
	{
	  if (event.type ==  Event::Closed)
	    {
	      window.close();
	      break;
	    }
	  else if (event.type == Event::KeyPressed)
	    {
	      if(event.key.code == Keyboard::D)
		{
		  hero->moveHero(RIGHT);
		}
	      else if(event.key.code == Keyboard::Q)
		{
		  cout << "BLOCKED \n";
		  hero->moveHero(LEFT);
		}
	    }

	}

      window.clear();
      window.draw( *(hero->getSprite()) );
      window.display();
    }
  return EXIT_SUCCESS;

};


text:
$packageName = 'outlookaddressbookview'
$url = 'http://www.nirsoft.net/utils/outlookaddressbookview.zip'
$checksum = 'c628f351cc6b5c28904c886cc5378eee77dfec2e584e90c8a73efa3005b383e7'
$checksumType = 'sha256'
$url64 = 'http://www.nirsoft.net/utils/outlookaddressbookview-x64.zip'
$checksum64 = 'c38f2f4503405f96dfc732ea90dc171c9e0c521df51ec4b1526edf828b056d45'
$checksumType64 = 'sha256'
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$installFile = Join-Path $toolsDir "$($packageName).exe"

Install-ChocolateyZipPackage -PackageName "$packageName" `
                             -Url "$url" `
                             -UnzipLocation "$toolsDir" `
                             -Url64bit "$url64" `
                             -Checksum "$checksum" `
                             -ChecksumType "$checksumType" `
                             -Checksum64 "$checksum64" `
                             -ChecksumType64 "$checksumType64"

Set-Content -Path ("$installFile.gui") `
            -Value $null


text:
require 'rubygems'
require 'sinatra'
require 'google/api_client'

enable :sessions

# FILL IN THIS SECTION
# ------------------------
DATA_OBJECT = "BUCKET/OBJECT" # This is the {bucket}/{object} name you are using for the language file.
CLIENT_EMAIL = "YOUR_CLIENT_ID@developer.gserviceaccount.com" # Email of service account
KEYFILE = 'YOUR_KEY_FILE.p12' # Filename of the private key
PASSPHRASE = 'notasecret' # Passphrase for private key
PROJECT = 'YOUR_PROJECT_ID' # The id of your project
# ------------------------

configure do
  client = Google::APIClient.new(
    :application_name => 'Ruby Prediction sample',
    :application_version => '1.0.0')

  # Authorize service account
  key = Google::APIClient::PKCS12.load_key(KEYFILE, PASSPHRASE)
  asserter = Google::APIClient::JWTAsserter.new(
     CLIENT_EMAIL,
     ['https://www.googleapis.com/auth/prediction','https://www.googleapis.com/auth/devstorage.full_control'],
     key)
  client.authorization = asserter.authorize()

  # Since we're saving the API definition to the settings, we're only retrieving
  # it once (on server start) and saving it between requests.
  # If this is still an issue, you could serialize the object and load it on
  # subsequent runs.
  prediction = client.discovered_api('prediction', 'v1.6')

  set :api_client, client
  set :prediction, prediction
end

def api_client; settings.api_client; end
def prediction; settings.prediction; end

get '/' do
  erb :index
end

get '/train' do
  training = prediction.trainedmodels.insert.request_schema.new
  training.id = 'language-sample'
  training.storage_data_location = DATA_OBJECT
  result = api_client.execute(
    :api_method => prediction.trainedmodels.insert,
    :headers => {'Content-Type' => 'application/json'},
    :body_object => training,
    :parameters => {'project' => PROJECT}
  )

  return [
    200,
    [["Content-Type", "application/json"]],
    ::JSON.generate({"status" => "success"})
  ]
end

get '/checkStatus' do
  result = api_client.execute(
    :api_method => prediction.trainedmodels.get,
    :parameters => {'id' => 'language-sample', 'project' => PROJECT}
  )

  return [
    200,
    [["Content-Type", "application/json"]],
    assemble_json_body(result)
  ]
end

post '/predict' do
  input = prediction.trainedmodels.predict.request_schema.new
  input.input = {}
  input.input.csv_instance = [params["input"]]
  result = api_client.execute(
    :api_method => prediction.trainedmodels.predict,
    :parameters => {'id' => 'language-sample', 'project' => PROJECT},
    :headers => {'Content-Type' => 'application/json'},
    :body_object => input
  )

  return [
    200,
    [["Content-Type", "application/json"]],
    assemble_json_body(result)
  ]
end

def assemble_json_body(result)
  # Assemble some JSON our client-side code can work with.
  json = {}
  if result.status != 200
    if result.data["error"]
      message = result.data["error"]["errors"].first["message"]
      json["message"] = "#{message} [#{result.status}]"
    else
      json["message"] = "Error. [#{result.status}]"
    end
    json["response"] = ::JSON.parse(result.body)
    json["status"] = "error"
  else
    json["response"] = ::JSON.parse(result.body)
    json["status"] = "success"
  end
  return ::JSON.generate(json)
end


text:
package daemon_test

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/leanovate/microtools/logging"
	"github.com/stretchr/testify/require"
	"github.com/untoldwind/trustless/daemon"
)

func TestServiceResource(t *testing.T) {
	require := require.New(t)
	resource := daemon.NewRootResource(nil, logging.NewSimpleLoggerNull(logging.Options{}))

	request, _ := http.NewRequest("GET", "/", nil)

	result, err := resource.Get(request)
	require.Nil(err)
	doc, ok := result.(*daemon.ServiceDocument)
	require.True(ok)
	require.NotNil(doc.Links)
	require.NotEmpty(doc.Links["self"].Href)
	require.NotEmpty(doc.Links["v1"].Href)

	matcher := resource.SubResources()
	require.NotNil(matcher)

	request, _ = http.NewRequest("GET", "/v1", nil)
	response := httptest.NewRecorder()
	require.True(matcher("/v1", response, request))
	require.Equal(response.Code, 200)
}


text:
var testPackage = require('../../helpers/test-package');
var Dgeni = require('dgeni');

var getDocFromAlias, aliasMap;

describe('getDocFromAlias', () => {
  beforeEach(() => {
    var dgeni = new Dgeni([testPackage('links-package', true)]);
    var injector = dgeni.configureInjector();
    aliasMap = injector.get('aliasMap');
    getDocFromAlias = injector.get('getDocFromAlias');
  });

  it('should return an array of docs that match the alias', () => {
    var doc1 = {aliases: ['a', 'b', 'c']};
    var doc2 = {aliases: ['a', 'b']};
    var doc3 = {aliases: ['a']};
    aliasMap.addDoc(doc1);
    aliasMap.addDoc(doc2);
    aliasMap.addDoc(doc3);

    expect(getDocFromAlias('a')).toEqual([doc1, doc2, doc3]);
    expect(getDocFromAlias('b')).toEqual([doc1, doc2]);
    expect(getDocFromAlias('c')).toEqual([doc1]);
  });

  it('should filter ambiguous docs by calling each disambiguator', () => {
    getDocFromAlias.disambiguators = [
      (alias, originatingDoc, docs) => docs.filter(doc => doc.name.indexOf('X') !== -1), // only if X appears in name
      (alias, originatingDoc, docs) => docs.filter(doc => doc.name.indexOf('Y') !== -1)  // only if Y appears in name
    ];

    var doc1 = {name: 'X', aliases: ['a', 'b', 'c']};
    var doc2 = {name: 'Y', aliases: ['a', 'b']};
    var doc3 = {name: 'XY', aliases: ['a', 'c']};
    aliasMap.addDoc(doc1);
    aliasMap.addDoc(doc2);
    aliasMap.addDoc(doc3);

    // doc1 and doc2 get removed as they don't both have X and Y in name
    expect(getDocFromAlias('a')).toEqual([doc3]);
    // doc2 gets removed as it has no X; then we have only one doc left so second disambiguator never runs
    expect(getDocFromAlias('b')).toEqual([doc1]);
    // doc1 gets removed as it has no Y; then we have only one doc left (which would anyway pass 2nd disambiguator)
    expect(getDocFromAlias('c')).toEqual([doc3]);
  });
});


text:
package RoomManager

import (
	"Config"
	"Room"
	"Router"
	"Socket"
	"log"
	"net"
	"strconv"
	"sync"
	"time"

	"github.com/syndtr/goleveldb/leveldb"
	"github.com/syndtr/goleveldb/leveldb/opt"
	dbutil "github.com/syndtr/goleveldb/leveldb/util"
	cDebug "github.com/tj/go-debug"
)

var debugOut = cDebug.Debug("RoomManager")

type RoomManager struct {
	ln          *net.TCPListener
	goingClose  chan bool
	router      *Router.Router
	rooms       map[string]*Room.Room
	roomsLocker sync.RWMutex
	db          *leveldb.DB
}

func (m *RoomManager) init() error {
	m.goingClose = make(chan bool)
	m.rooms = make(map[string]*Room.Room)
	m.router = Router.MakeRouter("request")
	m.router.Register("roomlist", m.handleRoomList)
	m.router.Register("newroom", m.handleNewRoom)

	config := Config.GetConfig()

	ideal_port, ok := config["manager_port"].(int)
	if ideal_port <= 0 || !ok {
		log.Println("Manager port is not configured, using default ", ideal_port)
		ideal_port = 18573
	}

	var addr, err = net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(ideal_port))
	if err != nil {
		// handle error
		return err
	}
	m.ln, err = net.ListenTCP("tcp", addr)
	if err != nil {
		// handle error
		return err
	}

	log.Println("RoomManager is listening on port", ideal_port)

	m.recovery()
	go m.shortenRooms()

	return nil
}

func (m *RoomManager) recovery() error {
	db, err := leveldb.OpenFile("./db", nil)
	m.db = db

	iter := db.NewIterator(dbutil.BytesPrefix([]byte("room-")), nil)
	for iter.Next() {
		// Use key/value.
		//key := iter.Key()
		value := iter.Value()
		info, err := parseRoomRuntimeInfo(value)
		if err != nil {
			log.Println("room is corrupted", iter.Key())
			continue
		}
		room, err := Room.RecoverRoom(info)
		if err != nil {
			log.Println("room is corrupted", iter.Key())
			continue
		}
		debugOut("Room recovered", string(value))

		m.roomsLocker.Lock()
		m.rooms[room.Options.Name] = room
		m.roomsLocker.Unlock()
		go func(room *Room.Room, m *RoomManager) {
			roomName := room.Options.Name
			room.Run()
			m.waitRoomClosed(roomName)
		}(room, m)

	}
	iter.Release()
	err = iter.Error()
	return err
}

func (m *RoomManager) shortenRooms() {
	for {
		select {
		case <-time.After(time.Hour):
			iter := m.db.NewIterator(dbutil.BytesPrefix([]byte("room-")), nil)

			batch := new(leveldb.Batch)

			for iter.Next() {
				value := iter.Value()
				info, err := parseRoomRuntimeInfo(value)
				if info.Expiration > 1 && err == nil {
					info.Expiration = info.Expiration - 1

					info_to_insert, err := info.ToJson()
					if err != nil {
						log.Println(err)
						continue
					}
					batch.Put(iter.Key(), info_to_insert)
				} else {
					// delete expired or corrupted room
					batch.Delete(iter.Key())
				}

			}
			iter.Release()
			m.db.Write(batch, nil)
		case _, _ = <-m.goingClose:
			return
		}
	}
}

func (m *RoomManager) waitRoomClosed(roomName string) {
	m.roomsLocker.Lock()
	defer m.roomsLocker.Unlock()
	delete(m.rooms, roomName)
	m.db.Delete([]byte("room-"+roomName), &opt.WriteOptions{false})
}

func (m *RoomManager) Close() {
	m.roomsLocker.Lock()
	defer m.roomsLocker.Unlock()
	close(m.goingClose)
	m.db.Close()
	m.ln.Close()
}

func (m *RoomManager) Run() (err error) {
	err = m.init()
	if err != nil {
		return err
	}
	for {
		select {
		case _, _ = <-m.goingClose:
			return err
		default:
			conn, err := m.ln.AcceptTCP()
			if err != nil {
				// handle error
				continue
			}
			m.processClient(Socket.MakeSocketClient(conn))
		}
	}
	return err
}

//主要业务代码
func (m *RoomManager) processClient(client *Socket.SocketClient) {
	go func() {
		for {
			select {
			case _, _ = <-m.goingClose:
				return
			case pkg, ok := <-client.PackageChan:
				if !ok {
					return
				}
				if pkg.PackageType == Socket.MANAGER {
					err := m.router.OnMessage(pkg.Unpacked, client)
					if err != nil {
						client.Close()
					}
				}
			case _, _ = <-client.GoingClose:
				return
			}
		}
	}()
}

func ServeManager() *RoomManager {
	return &RoomManager{}
}


text:
package org.ucombinator.scheme.transform

import org.ucombinator.scheme.syntax._
import scala.collection.immutable.{Map => ImmMap}

class FlatClosureConverter extends ProgramTransformer {

  private var prog: Program = null

  // BUG: Keyword must be unused elsewhere.
  val currentClosureKeyword = SKeyword.from("clo")
  val environmentName = SName.gensym("env")

  def apply(prog: Program): Program = {
    this.prog = prog
    prog match {
      case Program(decs, defs, init) => {
        val newDecs = decs
        val newDefs = defs map this.apply
        Program(newDecs, newDefs, this.apply(init))
      }
    }
  }

  private def apply(exp: Exp): Exp = {
    exp match {

      // WARNING: WATCH CASE ORDERING AND ATOMICS!

      case Ref(name) => {
        if (prog.valueOfGlobal(name).isLambda) {
          Closure(Ref(name), ClosureStruct(List()), List())
        } else {
          exp
        }
      }

      case Begin(Body(List(), cmds)) =>
        Begin(Body(List(), cmds map this.apply))

      case lam@Lambda(formals, body) => {
        val convertedBody = this.apply(body)
        val frees = ((lam.free -- prog.globals).toList) sort ((a: SName, b: SName) => (a <= b))
        val t = ClosureStruct(frees)
        val values = frees map (name => Ref(name))
        // val newEnv = MakeStruct(t,values)

        val env = Ref(environmentName)
        val newFormals = KeywordFormal(currentClosureKeyword, environmentName) :: formals
        val rebinds = ImmMap() ++ (frees map (name => (name, StructGet(env, name, t))))
        val newBody = convertedBody substitute rebinds
        Closure(Lambda(newFormals, newBody), t, values)
      }

      case Let(bindings, body) =>
        Let(bindings map (_.map(this.apply)), this.apply(body))

      case SetCell(exp, value) =>
        SetCell(this(exp), this.apply(value))

      case SetVar(name, value) =>
        SetVar(name, this.apply(value))

      case (_: Unspecified | _: CPS | _: Lit) => exp

      case _: Prim => Closure(exp, ClosureStruct(List()), List())

      case MakeStruct(ty, values) =>
        MakeStruct(ty, values map this.apply)
      case StructGet(base, field, ty) =>
        StructGet(this(base), field, ty)

      case MakeCell(value) => MakeCell(this.apply(value))

      case CellGet(cell) => CellGet(this.apply(cell))

      case App(f: Prim, arguments) =>
        App(f, arguments map this.apply)

      case App(f@Ref(name), args) if prog.globals contains name => {
        App(f, KeywordArgument(currentClosureKeyword, Unspecified()) :: (args map this.apply))
      }

      case App(f, args) => {
        Call(this.apply(f), currentClosureKeyword, args map this.apply)
      }
    }
  }

  private def apply(body: Body): Body = {
    body match {
      case Body(List(), exps) => Body(List(), exps map this.apply)
    }
  }

  private def apply(d: Def): Def = {
    // Assumes global.

    d match {
      case VarDef(name, lam@Lambda(formals, body)) => {
        val clo = this.apply(lam)
        clo match {
          case Closure(newLam, ClosureStruct(List()), List()) => VarDef(name, newLam)
        }
      }
      case VarDef(name, exp) => {
        VarDef(name, this.apply(exp))
      }
      case _ => throw new Exception()
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <name value="WordPad2" />
  <executable value="%ProgramFiles%\Windows NT\Accessories\wordpad.exe" />
  <parameters value="" />
  <displayName value="WordPad2 (RunAsService)" />
  <description value="WordPad sample for RunAsService..." />
  <exitHooks value="RestartHook" />
  <email>
    <address>
      <to value="" />
      <from value="" />
    </address>
    <smtp>
      <host value="" />
      <port value="" />
      <login value="" />
      <password value="" />
    </smtp>
    <subject value="Warning: {0} [Service] - Process has exited !"/>
  </email>
</configuration>


text:
package pushka

import scala.language.implicitConversions

package object json extends PushkaJsonBackend {

  implicit val printer = new JsonPrinter()
  implicit val parser = new JsonParser()
}


text:
"use strict";

var express = require('express'),
    http = require('http'),
    fs = require('fs'),
    _und = require("underscore"),
    async = require('async'),
    path = require("path"),
    config = require('./client_secrets.json'),

    hbs = require('hbs'),

    app = express(),
    server;

app.locals.mirrorClient = require('mirror-api-client')({
    clientId: config.web.client_id,
    clientSecret: config.web.client_secret,
    redirectUri: config.web.redirect_uris[0],
    scope: config.web.scope
});

// Allow node to be run with proxy passing
app.enable('trust proxy');

// View templating & rendering through handlebars.js
app.set('view engine', 'html');
app.set('views', __dirname + '/app/views' );
app.engine('html', hbs.__express);
hbs.registerPartials(__dirname + '/app/views/partials');

//var helperFiles = fs.readdirSync(__dirname+'/app/helpers');
hbs.registerHelper( 'inArray', require(__dirname+'/app/helpers/inArray.js') );

// Compression (gzip), body parsing, URL encoding
app.use( express.compress() );
app.use( express.methodOverride() );
app.use( express.urlencoded() );            // Needed to parse POST data sent as JSON payload
app.use( express.json() );

// Session setup
app.use( express.cookieParser( config.session_secret || 'mirror-glass-secret') );    // populates req.signedCookies, required by session()
app.use( express.session() );                                                        // populates req.session, needed for CSRF

// CSRF for XSS protection - populates req.csrfToken()
app.use(express.csrf());

// Logging config
app.configure('local', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
    app.use(express.errorHandler());
});

// Pre-route handling
app.use( function(req, res, next){
    res.locals.message = req.session.message;
    res.locals.csrfToken = req.csrfToken();
    //console.log('pre-route call, res.locals.message = ' + res.locals.message);
    next();
});

// Setup routes
app.use("/assets", express.static(__dirname + "/public/assets"));
require('./app/routes')(app);

// Error handling
app.use( function(err, req, res, next){
    console.log('Error handler called with error:', err);
    if(!req.session.userId) return res.redirect( req.app.locals.mirrorClient.getAuthUrl() );
    res.locals.message = err || res.locals.message;
    res.locals.alert = (err ? 'danger' : 'success');
    return res.render('index');
});

// Public static assets served from /public directory
app.use("/public", express.static(__dirname+'/public'));

// Run the server
server = http.createServer(app).listen( 3000 );
console.log((new Date()).toString()+ ":: glasstasks server listening on port 3000, environment:: ", app.settings.env);

//function start(){
    //server = http.createServer(app).listen( process.env.PORT || config.port);
    //logger.info((new Date()).toString()+ ":: glasstasks server listening on port::", server.address().port, ", environment:: ", app.settings.env);
//}

//exports.start = start;
//exports.app = app;


text:
[![Apache 2.0 licensed][license]](#license)

This is Spindle, a set of plug-ins for the [Twine](https://github.com/bbcarchdev/twine)
RDF workflow engine and [Quilt](https://github.com/bbcarchdev/quilt)
Linked Data web application which implement the business logic of the
[Research & Education Space platform](https://bbcarchdev.github.io/res/).

## Contributing

To contribute to Spindle, fork this repository and commit your changes to the
`develop` branch. For larger changes, you should create a feature branch with
a meaningful name, for example one derived from the [issue number](https://github.com/bbcarchdev/spindle/issues/).

Once you are satisfied with your contribution, open a pull request and describe
the changes you've made.

## License

Spindle is licensed under the terms of the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)

Copyright © 2014-2016 BBC.

[license]: https://img.shields.io/badge/license-Apache%202.0-blue.svg


text:
title: Starting Up
author: Justin Ball
layout: post
permalink: "/2008/03/14/starting-up/"
tags:
  - "business"
  - "business"
  - "start ups"
date: '2008-03-14T06:00:00Z'
templateKey: blog-post
path: "/starting-up"
description: ''
---

I am not a serious entrepreneur, but I have started up a few companies over the years. One I sold. One we folded and I still run one - [ThePlanCollection.com.][1]

 [1]: http://www.theplancollection.com "Buy some house plans already."

[I ran across this article with startup tips][2]. My favorite tip is 'outsource to middle America'. I would have to say there are a lot of smart people that choose to not live in the startup hot beds because life is cheaper elsewhere. The only disadvantage of living out of the mainstream is that your non-virtual interactions are limited - user group meetings and presentations are harder. Technology is changing that as communities come online. I and my partner rarely meet at all anymore. We do everything over IM. It forces us to focus on what needs to be done rather than spend time shooting the bull.

 [2]: http://www.calacanis.com/2008/03/07/how-to-save-money-running-a-startup-17-really-good-tips/


text:
using System.Collections.Generic;

using Shouldly;

using Stove.Domain.Repositories;
using Stove.NHibernate.Tests.Entities;
using Stove.NHibernate.Tests.Sessions;

using Xunit;

namespace Stove.NHibernate.Tests
{
    public class General_Repository_With_Interception_Enabled : StoveNHibernateTestBase
    {
        public General_Repository_With_Interception_Enabled() : base(true)
        {
            Building(builder => { }).Ok();
            StoveSession.UserId = 1;
            UsingSession<PrimaryStoveSessionContext>(session => { session.Save(new Product("TShirt")); });
        }

        [Fact]
        public async void GetAllAsync_should_work()
        {
            List<Product> products = await The<IRepository<Product>>().GetAllListAsync();
            products.Count.ShouldBe(1);
        }
    }
}


text:
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace TodoSPA
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app) {

            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidAudience  = ConfigurationManager.AppSettings["ida:Audience"],
                    },
                    Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                });
        }
    }
}


text:
package com.android.ide.common.resources;

import static com.android.resources.ResourceType.ATTR;
import static com.android.resources.ResourceType.DIMEN;
import static com.android.resources.ResourceType.ID;
import static com.android.resources.ResourceType.LAYOUT;

import com.android.ide.common.rendering.api.ResourceValue;
import com.android.resources.ResourceType;

import junit.framework.TestCase;

public class ResourceUrlTest extends TestCase {
    @SuppressWarnings("ConstantConditions")
    public void testParseResource() {
        assertNull(ResourceUrl.parse(""));
        assertNull(ResourceUrl.parse("not_a_resource"));
        assertNull(ResourceUrl.parse("@null"));
        assertNull(ResourceUrl.parse("@empty"));
        assertNull(ResourceUrl.parse("@undefined"));
        assertNull(ResourceUrl.parse("@?"));
        assertNull(ResourceUrl.parse("@android:layout"));
        assertNull(ResourceUrl.parse("@layout"));

        assertEquals("foo", ResourceUrl.parse("@id/foo").name);
        assertEquals(ID, ResourceUrl.parse("@id/foo").type);
        assertFalse(ResourceUrl.parse("@id/foo").framework);
        assertFalse(ResourceUrl.parse("@id/foo").create);
        assertFalse(ResourceUrl.parse("@id/foo").theme);

        assertEquals("foo", ResourceUrl.parse("@+id/foo").name);
        assertEquals(ID, ResourceUrl.parse("@+id/foo").type);
        assertFalse(ResourceUrl.parse("@+id/foo").framework);
        assertTrue(ResourceUrl.parse("@+id/foo").create);

        assertEquals(LAYOUT, ResourceUrl.parse("@layout/foo").type);
        assertEquals(DIMEN, ResourceUrl.parse("@dimen/foo").type);
        assertFalse(ResourceUrl.parse("@dimen/foo").framework);
        assertEquals("foo", ResourceUrl.parse("@android:dimen/foo").name);
        assertEquals(DIMEN, ResourceUrl.parse("@android:dimen/foo").type);
        assertTrue(ResourceUrl.parse("@android:dimen/foo").framework);
        assertEquals("foo", ResourceUrl.parse("@layout/foo").name);
        assertEquals("foo", ResourceUrl.parse("@dimen/foo").name);
        assertEquals(ATTR, ResourceUrl.parse("?attr/foo").type);
        assertTrue(ResourceUrl.parse("?attr/foo").theme);
        assertEquals("foo", ResourceUrl.parse("?attr/foo").name);
        assertFalse(ResourceUrl.parse("?attr/foo").framework);
        assertEquals(ATTR, ResourceUrl.parse("?foo").type);
        assertEquals("foo", ResourceUrl.parse("?foo").name);
        assertFalse(ResourceUrl.parse("?foo").framework);
        assertEquals(ATTR, ResourceUrl.parse("?android:foo").type);
        assertEquals("foo", ResourceUrl.parse("?android:foo").name);
        assertTrue(ResourceUrl.parse("?android:foo").framework);
        assertTrue(ResourceUrl.parse("?android:foo").theme);
        assertFalse(ResourceUrl.parse("?foo", false).framework);
        assertTrue(ResourceUrl.parse("?android:foo", false).framework);
        assertTrue(ResourceUrl.parse("?foo", true).framework);
        assertTrue(ResourceUrl.parse("?attr/foo", true).framework);

        assertEquals("@+id/foo", ResourceUrl.parse("@+id/foo").toString());
        assertEquals("@layout/foo", ResourceUrl.parse("@layout/foo").toString());
        assertEquals("@android:layout/foo", ResourceUrl.parse("@android:layout/foo").toString());
        assertEquals("?android:attr/foo", ResourceUrl.parse("?android:foo").toString());

        assertTrue(ResourceUrl.parse("@id/foo").hasValidName());
        assertFalse(ResourceUrl.parse("@id/foo bar").hasValidName());
        assertFalse(ResourceUrl.parse("@id/").hasValidName());
        assertFalse(ResourceUrl.parse("@id/?").hasValidName());
        assertFalse(ResourceUrl.parse("@id/123").hasValidName());
        assertFalse(ResourceUrl.parse("@id/ab+").hasValidName());
    }

    public void testCreateFromResourceValue() {
        assertEquals("@android:string/foo",
            ResourceUrl.create(new ResourceValue(ResourceType.STRING, "foo", true)).toString());
        assertEquals("@string/foo",
            ResourceUrl.create(new ResourceValue(ResourceType.STRING, "foo", false)).toString());
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>hu.unideb.inf.reversi</groupId>
	<artifactId>Reversi-JavaFx-Application</artifactId>
	<version>1.0</version>
	<packaging>pom</packaging>

	<description>Programozási technológiákra és környezetekre írt Reversi alkalmazás, amely egy kétszemélyes játék</description>
	<inceptionYear>2016</inceptionYear>

	<modules>
		<module>reversi-core</module>
		<module>reversi-service-client-api</module>
		<module>reversi-service</module>
		<module>reversi-view</module>
	</modules>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.SourceEncoding>UTF-8</project.reporting.SourceEncoding>
	</properties>

	<developers>
		<developer>
			<name>Iványi-Nagy Gábor</name>
			<email>gabilampard@gmail.com</email>
			<roles>
				<role>developer</role>
			</roles>
		</developer>
	</developers>

	<organization>
		<name>Debreceni Egyetem Informatika Kar</name>
	</organization>

	<licenses>
		<license>
			<name>MIT License</name>
			<url>http://www.opensource.org/licenses/mit-license.php</url>
		</license>
	</licenses>

	<scm>
		<url>https://github.com/gabichelsea/Reversi-JavaFx</url>
		<connection>scm:git:git://github.com/gabichelsea/Reversi-JavaFx.git</connection>
		<developerConnection>scm:git:git@github.com:gabichelsea/Reversi-JavaFx.git</developerConnection>
	</scm>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.slf4j</groupId>
				<artifactId>slf4j-api</artifactId>
				<version>1.7.21</version>
			</dependency>
			<dependency>
				<groupId>ch.qos.logback</groupId>
				<artifactId>logback-core</artifactId>
				<version>1.1.6</version>
			</dependency>
			<dependency>
				<groupId>ch.qos.logback</groupId>
				<artifactId>logback-classic</artifactId>
				<version>1.1.6</version>
			</dependency>

			<dependency>
				<groupId>junit</groupId>
				<artifactId>junit</artifactId>
				<version>4.12</version>
				<scope>test</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.5.1</version>
					<configuration>
						<source>1.8</source>
						<target>1.8</target>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>

		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-enforcer-plugin</artifactId>
				<version>1.4.1</version>
				<executions>
					<execution>
						<phase>validate</phase>
						<goals>
							<goal>enforce</goal>
						</goals>
						<configuration>
							<rules>
								<requireJavaVersion>
									<version>1.8</version>
								</requireJavaVersion>
							</rules>
						</configuration>
					</execution>
				</executions>
			</plugin>

		</plugins>
	</build>

	<reporting>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.10.3</version>
				<configuration>
					<show>private</show>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-report-plugin</artifactId>
				<version>2.19.1</version>
				<configuration>
					<includes>
						<include>**/*Suite.java</include>
					</includes>
					<aggregate>true</aggregate>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jxr-plugin</artifactId>
				<version>2.5</version>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
				<version>2.7</version>
				<reportSets>
					<reportSet>
						<id>cobertura</id>
						<reports>
							<report>cobertura</report>
						</reports>
						<configuration>
							<aggregate>true</aggregate>
						</configuration>
					</reportSet>
				</reportSets>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-checkstyle-plugin</artifactId>
				<version>2.17</version>
				<configuration>
					<configLocation>src/main/resources/checkstyle.xml</configLocation>
				</configuration>
			</plugin>
		</plugins>

	</reporting>

</project>


text:
<resources>
    <string name="app_name">Ballad of the Sword Dancer</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_game">GameActivity</string>
    <string name="title_activity_select">SelectActivity</string>
</resources>


text:
import numpy as np
import pandas as pd
import os, sys, argparse
import cv2
import yaml  #replacing pickle with yaml
import datetime  #useful for debugging in notebooks

# Defining helper functions

# initialize the list of points for the rectangle bbox,
# the temporaray endpoint of the drawing rectangle
# the list of all bounding boxes of selected rois
# and boolean indicating wether drawing of mouse
# is performed or not

#WARNING: The mouse button might be the MIDDLE ONE!!!
rect_endpoint_tmp = []
rect_bbox = []

drawing = False  #this have to be False for drawing to work properly!!!

def check_boxes(img_clean, bbox_list, im_width, im_height):
    def draw_all_boxes():
        img = img_clean.copy()

        for b in bbox_list:
            cv2.rectangle(
                img, (b[0], b[1]), (b[2], b[3]),
                color=(0, 255, 0),
                thickness=2)
        cv2.imshow('image', img)

    # mouse callback function
    def draw_rect_roi(event, x, y, flags, param):
        # grab references to the global variables
        global rect_bbox, rect_endpoint_tmp, drawing

        # if the left mouse button was clicked, record the starting
        # (x, y) coordinates and indicate that drawing is being
        # performed. set rect_endpoint_tmp empty list.
        if event == cv2.EVENT_LBUTTONDOWN:
            rect_endpoint_tmp = []
            rect_bbox = [(x, y)]
            drawing = True

        # check to see if the left mouse button was released
        elif event == cv2.EVENT_LBUTTONUP:
            # record the ending (x, y) coordinates and indicate that
            # drawing operation is finished
            rect_bbox.append((x, y))
            drawing = False

            # draw a rectangle around the region of interest
            p_1, p_2 = rect_bbox

            # for bbox find upper left and bottom right points
            p_1x, p_1y = p_1
            p_2x, p_2y = p_2

            lx = min(p_1x, p_2x)
            ty = min(p_1y, p_2y)
            rx = max(p_1x, p_2x)
            by = max(p_1y, p_2y)

            # add bbox to list if both points are different
            if (lx, ty) != (rx, by):
                if abs(lx - rx) > 5:
                    if abs(ty - by) > 5:
                        bbox = [lx, ty, rx, by]
                        bbox_list.append(bbox)

        # if mouse is drawing set tmp rectangle endpoint to (x,y)
        elif event == cv2.EVENT_MOUSEMOVE and drawing:
            rect_endpoint_tmp = [(x, y)]
        elif event == cv2.EVENT_LBUTTONDBLCLK:
            npbx = np.asarray(bbox_list)
            selected_box = ((x > npbx[:, 0]) & (y > npbx[:, 1]) &
                            (x < npbx[:, 2]) & (y < npbx[:, 3]))
            if np.sum(selected_box) == 1:
                bbox_list.remove(npbx[selected_box].tolist()[0])
            if np.sum(selected_box) > 1:
                potentials = npbx[selected_box]
                areas = (potentials[:, 2] - potentials[:, 0]) * (
                    potentials[:, 3] - potentials[:, 1])
                bbox_list.remove(potentials[np.argmin(areas)].tolist())
            draw_all_boxes()

    cv2.namedWindow('image', cv2.WINDOW_GUI_EXPANDED)
    #cv2.resizeWindow('image', im_width, im_height)
    cv2.resizeWindow('image', 1900, 1100)
    cv2.moveWindow('image', 20,20)
    cv2.setMouseCallback('image', draw_rect_roi)
    draw_all_boxes()
    # keep looping until the 'c' key is pressed
    stop = False
    while True:
        # display the image and wait for a keypress
        if not drawing:
            draw_all_boxes()
            #cv2.imshow('image', img)
        elif drawing and rect_endpoint_tmp:
            rect_cpy = img_clean.copy()
            start_point = rect_bbox[0]
            end_point_tmp = rect_endpoint_tmp[0]
            cv2.rectangle(rect_cpy, start_point, end_point_tmp, (0, 255, 0), 2)
            cv2.imshow('image', rect_cpy)

        key = cv2.waitKey(1)  #& 0xFF
        # if the 'c' key is pressed, break from the loop
        if key == ord('c'):
            break
        if key == ord('q'):
            stop = True
            break
    # close all open windows
    cv2.destroyAllWindows()
    #cv2.waitKey(1)
    return stop

def main(args):
    #Load data
    data_dir = args.ddir[0] + '/'  #in case we forgot '/'
    print('Opening file' + args.config[0])
    with open(args.config[0], 'r') as configfile:
        config = yaml.safe_load(configfile)

    trained_annotations_fname = data_dir + config['annotations_dir'] + config['pretrained_annotations_fname']
    checked_annotations_fname = data_dir + config['annotations_dir'] +  config['checked_annotations_fname']
    im_width = config['IMAGE_W']  #size of training images for yolo
    im_height = config['IMAGE_H']

    resume = args.resume
    from_scratch = args.from_scratch

    if from_scratch:
        print('Not showing any bounding boxes. You are annotating from scratch. Remove relevant flag to use ourput of your previous training (or generic model)')

    if resume:
        print('Restoring previous session!')

    preped_images_dir = data_dir + config['preped_images_dir']

    with open(trained_annotations_fname, 'r') as fp:
        all_imgs = yaml.safe_load(fp)

    if not resume:
        new_imgs = []
    else:
        with open(checked_annotations_fname, 'r') as fp:
            new_imgs = yaml.safe_load(fp)

    for i in range(len(all_imgs)):
        fname = all_imgs[i]['filename']
        if resume:
            if any(doneimg['filename'] == fname for doneimg in new_imgs):
                continue
        img_data = {'object': []}
        img_data['filename'] = fname
        img_data['width'] = all_imgs[i]['width']
        img_data['height'] = all_imgs[i]['height']
        sys.stdout.write('\r')
        sys.stdout.write(fname + ", " + str(i) + ' of ' + str(
            len(all_imgs)) + " \n=====================================\n")
        sys.stdout.flush()

        boxes = []
        if not from_scratch:
            for obj in all_imgs[i]['object']:
                boxes.append(
                    [obj['xmin'], obj['ymin'], obj['xmax'], obj['ymax']])

        #do box processing
        img = cv2.imread(data_dir + fname)
        if check_boxes(img, boxes, im_width, im_height):
            break
        for b in boxes:
            obj = {}
            if ((b[2] - b[0]) * (b[3] - b[1])) < 10:
                continue
            obj['name'] = 'aoi'
            obj['xmin'] = int(b[0])
            obj['ymin'] = int(b[1])
            obj['xmax'] = int(b[2])
            obj['ymax'] = int(b[3])
            img_data['object'] += [obj]

        new_imgs += [img_data]

    #print(all_imgs)
    with open(checked_annotations_fname, 'w') as handle:
        yaml.dump(new_imgs, handle)

    print("Done!")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Annotate or correct annotations from non-domain specific model. To remove annotation double left click. To add one, Middle Click and move. \'c\' accepts changes and goes to the next image, \'q\' ends the session and saves files done so far (resume option is used to continue this work).',epilog='Any issues and clarifications: github.com/ctorney/uavtracker/issues')
    parser.add_argument('--config', '-c', required=True, nargs=1, help='Your yml config file')
    parser.add_argument('--ddir', '-d', required=True, nargs=1, help='Root of your data directory' )
    parser.add_argument('--resume', '-r', default=False, action='store_true',
                        help='Continue a session of annotation (it will access output file and re-start when you left off)')
    parser.add_argument('--from-scratch', '-f', default=False, action='store_true',
                        help='Annotate files from scratch without any existing bounding boxes')

    args = parser.parse_args()
    main(args)


text:
(function (Raphael) {
	'use strict';

    var arcBase = { thickness: 40, radius: 100, total: 100, animTime: 1500, animType: 'bounce' };
    var circleBase = { radius: 70, thickness: 10 };
    var arrowBase = { src: 'arrow-right.jpg', width: 80, height: 80, animTime: 1000 };
    var paperBase = { centerX: 0, centerY: 0 };
    var backgroundBase = { color: '#E0E0E0', radius: 100, thickness: 40 };

    var jp = function (paper) {
        paper.customAttributes.arc = function (xloc, yloc, value, total, R) {
            var alpha = 360 / total * value,
                a = (90 - alpha) * Math.PI / 180,
                x = xloc + R * Math.cos(a),
                y = yloc - R * Math.sin(a),
                path;
            if (total === value) {
                path = [
                    ['M', xloc, yloc - R],
                    ['A', R, R, 0, 1, 1, xloc - 0.01, yloc - R]
                ];
            } else {
                path = [
                    ['M', xloc, yloc - R],
                    ['A', R, R, 0, +(alpha > 180), 1, x, y]
                ];
            }
            return {
                path: path
            };
        };

        return paper;
    };

    var jparc = function (paper, options) {
        options.thickness = options.thickness || arcBase.thickness;
        options.radius = options.radius || arcBase.radius;
        options.total = options.total || arcBase.total;
        options.animTime = options.animTime || arcBase.animTime;
        options.animType = options.animType || arcBase.animType;

        var arc = paper.path().attr({
            'stroke': options.color,
            'stroke-width': options.thickness,
            arc: [paperBase.centerX, paperBase.centerY, 0, options.total, options.radius]
        });

        arc.animate({
            arc: [paperBase.centerX, paperBase.centerY, options.completeness, options.total, options.radius]
        }, options.animTime, options.animType);

        return arc;
    };

    var jparcs = function (paper, arcs, options) {
        for(var i = 0, n = arcs.length; i < n; i++) {
            jparc(paper, arcs[i], options);
        }
    };

    var jpcircle = function (paper, options, defaultOptions) {
        options.thickness = options.thickness || defaultOptions.thickness;
        options.radius = options.radius || defaultOptions.radius;

        var circle = paper.circle(paperBase.centerX, paperBase.centerY, options.radius);

        circle.attr({ stroke: options.color, 'stroke-width': options.thickness });

        return circle;
    };

    var jparrow = function (paper, options) {
        options.src = options.src || arrowBase.src;
        options.width = options.width || arrowBase.width;
        options.height = options.height || arrowBase.height;
        options.animTime = options.animTime || arrowBase.animTime;

        var arrow = paper.image(options.src, paperBase.centerX - options.width / 2, paperBase.centerY - options.height / 2, options.width, options.height);

        arrow.animate({ transform: 'r' + options.angle }, options.animTime, options.animType);

        return arrow;
    };

    var pauline = function (paper, arrow, circle, arcs, background, options) {
        jp(paper);

        paperBase.centerX = (paper.width / 2) || paperBase.centerX;
        paperBase.centerY = (paper.height / 2) || paperBase.centerY;
        arcBase.radius = (paperBase.centerX - arcs.thickness / 2) || arcBase.radius;
        circleBase.radius = (arcBase.radius - arcs.thickness / 2 - circle.thickness) || circleBase.radius;
        backgroundBase.radius = arcBase.radius || backgroundBase.radius;
        backgroundBase.thickness = arcs.thickness || backgroundBase.thickness;

        jpcircle(paper, background, backgroundBase);
        jparcs(paper, arcs, options);
        jpcircle(paper, circle, circleBase);
        jparrow(paper, arrow);
    };

    Raphael.fn.pauline3 = function (arrow, circle, arcs, background, options) {
        pauline(this, arrow, circle, arcs, background, options);
        return this;
    };
} (Raphael));


text:
/* Generated By:JJTree: Do not edit this line. Node.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=true,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package org.cs3.prolog.connector.internal.cterm.parser;

/**
 * All AST nodes must implement this interface. It provides basic machinery for
 * constructing the parent and child relationships between nodes.
 */
@SuppressWarnings("javadoc")
public interface Node {

  /** This method is called after the node has been made the current
    node.  It indicates that child nodes can now be added to it. */
  public void jjtOpen();

  /** This method is called after all the child nodes have been
    added. */
  public void jjtClose();

  /** This pair of methods are used to inform the node of its
    parent. */
  public void jjtSetParent(Node n);
  public Node jjtGetParent();

  /** This method tells the node to add its argument to the node's
    list of children.  */
  public void jjtAddChild(Node n, int i);

  /** This method returns a child node.  The children are numbered
     from zero, left to right. */
  public Node jjtGetChild(int i);

  /** Return the number of children the node has. */
  public int jjtGetNumChildren();

  /** Accept the visitor. **/
  public Object jjtAccept(CanonicalTermParserVisitor visitor, Object data);
}
/* JavaCC - OriginalChecksum=c8edf0f618d92fda7660807db2ec0366 (do not edit this line) */


text:
namespace sails {

class ResponsePacket;
class RequestPacket;
namespace net {
class Connector;
}
namespace base {
template<typename T, typename D>
class ThreadQueue;
class Timer;
}
class TicketSession {
 public:
  TicketSession(uint32_t sn, google::protobuf::Message* response,
                google::protobuf::Closure* done) {
    this->sn = sn;
    this->response = response;
    this->done = done;
    this->errcode = 1;
    calltime = 0;  // 为了性能这里不设置为time(NULL),而是能系统统一的计时器
  }
  uint32_t sn;
  uint32_t calltime;  // 用于查检超时
  uint8_t errcode;  // 1初始值,0成功,-1解析出错,-2连接断开, -3超时
  std::condition_variable notify;
  google::protobuf::Closure* done;  // 用于异步请求
  google::protobuf::Message* response;
  std::string response_raw;
};

class RpcChannelImp : public ::google::protobuf::RpcChannel {
 public:
  RpcChannelImp(std::string ip, int port);
  ~RpcChannelImp();

  bool init();

  // 发心跳包, 断线自动重连
  void KeepLive(bool keeplive) {
    this->keeplive = keeplive;
  }

  void CallMethod(const google::protobuf::MethodDescriptor* method,
                  google::protobuf::RpcController* controller,
                  const google::protobuf::Message* request,
                  google::protobuf::Message* response,
                  google::protobuf::Closure* done);

  std::string RawCallMethod(const std::string& service_name,
                            const std::string& method_name,
                            const std::string& request_data,
                            int data_type = 1);

 private:
  int sync_call(const google::protobuf::MethodDescriptor *method,
                google::protobuf::RpcController* controller,
                const google::protobuf::Message* request,
                google::protobuf::Message* response);

  void async_all(const google::protobuf::MethodDescriptor *method,
                 google::protobuf::RpcController* controller,
                 const google::protobuf::Message* request,
                 google::protobuf::Message* response,
                 google::protobuf::Closure* done);

  static void send_request(RpcChannelImp* channel);
  static void recv_response(RpcChannelImp* channel);

  static sails::ResponsePacket* parser(
      net::Connector *connector);

  void reset_ticket();

  // 检查调用是否超时
  static void check_call_timeout(void * data);

 private:
  net::Connector* connector;
  std::string ip;
  int port;
  uint32_t sn;  // 包序列

  bool stop;
  bool keeplive;
  bool isbreak;
  struct sigaction sigpipe_action;

  base::ThreadQueue<RequestPacket*, std::deque<RequestPacket*>>* request_list;
  //  base::ThreadQueue<ResponsePacket*> response_list;
  std::mutex request_mutex;
  std::map<uint32_t, TicketSession*> ticketManager;
  std::thread *send_thread;
  // 异步请求时,回调的线程也用它,所以要保证回调方法能尽快完成
  std::thread *recv_thread;
  base::Timer* timer;  // 用于检查调用是否超时
  uint32_t timeout;  // 0永不超时,默认是10s
  uint32_t now;
};

}  // namespace sails

#endif  //  SRC_RPC_CHANNEL_H_


text:
package org.zalando.intellij.swagger.completion.field.completion.openapi;

import com.intellij.codeInsight.completion.CompletionResultSet;
import org.zalando.intellij.swagger.completion.CompletionHelper;
import org.zalando.intellij.swagger.completion.field.FieldCompletion;
import org.zalando.intellij.swagger.completion.field.model.openapi.OpenApiFields;

class DiscriminatorCompletion extends FieldCompletion {

  DiscriminatorCompletion(
      final CompletionHelper completionHelper, final CompletionResultSet completionResultSet) {
    super(completionHelper, completionResultSet);
  }

  public void fill() {
    OpenApiFields.discriminator().forEach(this::addUnique);
  }
}


text:
angular.module('orderCloud')
    .factory('ocOrderShipments', OrderCloudOrderShipmentsService)
;

function OrderCloudOrderShipmentsService($q, OrderCloudSDK) {
    var service = {
        List: _list
    };

    function _list(orderID, page, pageSize, OrderLineItems) {
        var df = $q.defer();

        var options = {
            orderID: orderID,
            page: page,
            pageSize: pageSize
        };
        OrderCloudSDK.Me.ListShipments(options)
            .then(function(data) {
                getShipmentItems(data);
            });

        function getShipmentItems(data) {
            var queue = [];

            angular.forEach(data.Items, function(shipment) {
                queue.push((function() {
                    var d = $q.defer();

                    OrderCloudSDK.Me.ListShipmentItems(shipment.ID)
                        .then(function(shipmentItems) {
                            shipment.Items = shipmentItems.Items;
                            d.resolve();
                        });

                    return d.promise;
                })());
            });

            $q.all(queue).then(function() {
                getLineItems(data);
            });
        }

        function getLineItems(data) {
            angular.forEach(data.Items, function(shipment) {
                angular.forEach(shipment.Items, function(shipmentItem) {
                    shipmentItem.LineItem = _.findWhere(OrderLineItems.Items, {ID: shipmentItem.LineItemID});
                });
            });

            analyzeShippingAddresses(data);
        }

        function analyzeShippingAddresses(data) {
            angular.forEach(data.Items, function(shipment) {
                var shippingAddressCount = _.uniq(_.map(shipment.Items, function(item) { return (item.LineItem.ShippingAddress ? (item.LineItem.ShippingAddress.ID ? item.LineItem.ShippingAddress.ID : item.LineItem.ShippingAddress.Street1) : item.LineItem.ShippingAddressID); })).length;
                shipment.ShippingAddress = (shippingAddressCount == 1) ? shipment.Items[0].LineItem.ShippingAddress : null;
            });

            df.resolve(data);
        }

        return df.promise;
    }

    return service;
}


text:
module DocFrac
  class Convert
    attr_accessor :text
    def initialize(from, to)
      @from_format = DocFrac::Format.new(from)
      @to_format = DocFrac::Format.new(to)
      @text = ""
    end

    def convert
      from_file = "/tmp/#{DocFrac::Utilities.random_string}.#{@from_format.ext}"
      to_file = "/tmp/#{DocFrac::Utilities.random_string}.#{@to_format.ext}"
      File.open(from_file, "w") {|f| f.write(@text) }
      `docfrac #{@from_format.format_text} #{from_file} #{@to_format.format_text} #{to_file}`
      file = File.open(to_file, "r").read
      File.delete(from_file, to_file)
      return file
    end
  end
end


text:
Setup
=====

Just create a database, preferably in PostgreSQL, and make the necessary db settings in ``scielomanager/settings_local.include``.

run ``make setup`` et voilà.

Docs
====

See more information about this project in http://docs.scielo.org

Build status
============

.. image:: https://travis-ci.org/scieloorg/scielo-manager.png?branch=master :target: https://travis-ci.org/scieloorg/scielo-manager
`See Build details <https://travis-ci.org/scieloorg/scielo-manager>`_

i18n status
===========

**Current internationalization status**

.. image:: https://www.transifex.com/projects/p/scielomanager/resource/english/chart/image_png
`Help with translations <https://www.transifex.com/projects/p/scielomanager/resource/english/>`_

Use License
===========

FreeBSD 2-clause::

    Copyright (c) 2012, SciELO <scielo-dev@googlegroups.com>
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification,
    are permitted provided that the following conditions are met:

        Redistributions of source code must retain the above copyright notice,
        this list of conditions and the following disclaimer.

        Redistributions in binary form must reproduce the above copyright notice,
        this list of conditions and the following disclaimer in the documentation
        and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.