text:
<?php

namespace Oro\Bundle\EmailBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class EmailTemplateSelectType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $choices = function (Options $options) {
            if (empty($options['selectedEntity'])) {
                return [];
            }

            return null;
        };

        $defaultConfigs = array(
            'placeholder' => 'oro.email.form.choose_template',
        );

        // this normalizer allows to add/override config options outside.
        $that              = $this;
        $configsNormalizer = function (Options $options, $configs) use (&$defaultConfigs, $that) {
            return array_merge($defaultConfigs, $configs);
        };

        $resolver->setRequired(
            array(
                'data_route',
                'depends_on_parent_field'
            )
        );

        $resolver->setDefaults(
            array(
                'label'                   => null,
                'class'                   => 'OroEmailBundle:EmailTemplate',
                'property'                => 'name',
                'query_builder'           => null,
                'depends_on_parent_field' => 'entityName',
                'target_field'            => null,
                'selectedEntity'          => null,
                'choices'                 => $choices,
                'configs'                 => $defaultConfigs,
                'empty_value'             => '',
                'empty_data'              => null,
                'required'                => true,
                'data_route'              => 'oro_api_get_emailtemplates',
                'data_route_parameter'    => 'entityName'
            )
        );
        $resolver->setNormalizers(
            array(
                'configs' => $configsNormalizer
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        $config = $form->getConfig();
        $view->vars['depends_on_parent_field'] = $config->getOption('depends_on_parent_field');
        $view->vars['data_route'] = $config->getOption('data_route');
        $view->vars['data_route_parameter'] = $config->getOption('data_route_parameter');
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->getBlockPrefix();
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'oro_email_template_list';
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return 'genemu_jqueryselect2_translatable_entity';
    }
}


text:
package com.orientechnologies.orient.core.db.record;

import com.orientechnologies.orient.core.db.ODatabaseComplex;
import com.orientechnologies.orient.core.id.OClusterPosition;
import com.orientechnologies.orient.core.iterator.ORecordIteratorCluster;
import com.orientechnologies.orient.core.record.ORecord;

/**
 * Generic interface for record based Database implementations.
 *
 * @author Luca Garulli
 */
public interface ODatabaseRecord extends ODatabaseComplex<ORecord> {

  /**
   * Browses all the records of the specified cluster.
   *
   * @param iClusterName
   *          Cluster name to iterate
   * @return Iterator of ODocument instances
   */
  public <REC extends ORecord> ORecordIteratorCluster<REC> browseCluster(String iClusterName);

  public <REC extends ORecord> ORecordIteratorCluster<REC> browseCluster(String iClusterName,
      OClusterPosition startClusterPosition, OClusterPosition endClusterPosition, boolean loadTombstones);

  /**
   * Browses all the records of the specified cluster of the passed record type.
   *
   * @param iClusterName
   *          Cluster name to iterate
   * @param iRecordClass
   *          The record class expected
   * @return Iterator of ODocument instances
   */
  public <REC extends ORecord> ORecordIteratorCluster<REC> browseCluster(String iClusterName, Class<REC> iRecordClass);

  public <REC extends ORecord> ORecordIteratorCluster<REC> browseCluster(String iClusterName, Class<REC> iRecordClass,
      OClusterPosition startClusterPosition, OClusterPosition endClusterPosition, boolean loadTombstones);

  /**
   * Returns the record for a OIdentifiable instance. If the argument received already is a ORecord instance, then it's returned as
   * is, otherwise a new ORecord is created with the identity received and returned.
   *
   * @param iIdentifiable
   * @return A ORecord instance
   */
  public <RET extends ORecord> RET getRecord(OIdentifiable iIdentifiable);

  /**
   * Returns the default record type for this kind of database.
   */
  public byte getRecordType();

  /**
   * Returns true if current configuration retains objects, otherwise false
   *
   * @see #setRetainRecords(boolean)
   */
  public boolean isRetainRecords();

  /**
   * Specifies if retain handled objects in memory or not. Setting it to false can improve performance on large inserts. Default is
   * enabled.
   *
   * @param iValue
   *          True to enable, false to disable it.
   * @see #isRetainRecords()
   */
  public ODatabaseRecord setRetainRecords(boolean iValue);

  /**
   * Checks if the operation on a resource is allowed for the current user.
   *
   * @param iResource
   *          Resource where to execute the operation
   * @param iOperation
   *          Operation to execute against the resource
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public <DB extends ODatabaseRecord> DB checkSecurity(String iResource, int iOperation);

  /**
   * Checks if the operation on a resource is allowed for the current user. The check is made in two steps:
   *

   *

   * Access to all the resource as *

   *

   * Access to the specific target resource

   *

   *
   * @param iResourceGeneric
   *          Resource where to execute the operation, i.e.: database.clusters
   * @param iOperation
   *          Operation to execute against the resource
   * @param iResourceSpecific
   *          Target resource, i.e.: "employee" to specify the cluster name.
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public <DB extends ODatabaseRecord> DB checkSecurity(String iResourceGeneric, int iOperation, Object iResourceSpecific);

  /**
   * Checks if the operation against multiple resources is allowed for the current user. The check is made in two steps:
   *

   *

   * Access to all the resource as *

   *

   * Access to the specific target resources

   *

   *
   * @param iResourceGeneric
   *          Resource where to execute the operation, i.e.: database.clusters
   * @param iOperation
   *          Operation to execute against the resource
   * @param iResourcesSpecific
   *          Target resources as an array of Objects, i.e.: ["employee", 2] to specify cluster name and id.
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public <DB extends ODatabaseRecord> DB checkSecurity(String iResourceGeneric, int iOperation, Object... iResourcesSpecific);

  /**
   * Tells if validation of record is active. Default is true.
   *
   * @return true if it's active, otherwise false.
   */
  public boolean isValidationEnabled();

  /**
   * Enables or disables the record validation.
   *
   * @param iEnabled
   *          True to enable, false to disable
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public <DB extends ODatabaseRecord> DB setValidationEnabled(boolean iEnabled);

}

redpajama_set_name: RedPajamaGithub


text:
export const initialState = {
  loading: false,
  loaded: false,
  error: false,
  data: []
};

const setLoading = (state, loading) => ({ ...state, loading });
const setError = (state, error) => ({ ...state, error });
const setLoaded = (state, loaded) => ({ ...state, loaded });

export default {
  fetchStoriesInit: state => setLoading(state, true),
  fetchStoriesReady: (state, { payload }) =>
    setLoaded(setLoading({ ...state, data: payload }, false), true),
  fetchStoriesFail: state => setError(state, true)
};


text:
import React from 'react';
import { shallow } from 'enzyme';
import { Platform } from 'react-native';

import { CommentInput } from 'components';

describe('<CommentInput />', () => {
  const defaultProps = {
    users: [],
    userHasPushPermission: true,
    issueLocked: false,
    locale: '',
    onSubmit: () => {},
  };

  it('should render styled TextInput and send Icon if user has push permissions and issue is not locked', () => {
    const wrapper = shallow(<CommentInput {...defaultProps} />);

    expect(wrapper.find('Styled(TextInput)').length).toEqual(1);
    expect(wrapper.find('Styled(Icon)[name="send"]').length).toEqual(1);
  });

  it('should not render styled Text and lock Icon if user has push permissions and issue is not locked', () => {
    const wrapper = shallow(<CommentInput {...defaultProps} />);

    expect(wrapper.find('Styled(Text)').length).toEqual(0);
    expect(wrapper.find('Icon').length).toEqual(0);
  });

  it('should not render styled TextInput and send Icon if user does not have push permissions and issue is locked', () => {
    const wrapper = shallow(
      <CommentInput
        {...defaultProps}
        userHasPushPermission={false}
        issueLocked={true}
      />
    );

    expect(wrapper.find('Styled(TextInput)').length).toEqual(0);
    expect(wrapper.find('Styled(Icon)[name="send"]').length).toEqual(0);
  });

  it('should render styled Text and lock Icon if user does not have push permissions and issue is locked', () => {
    const wrapper = shallow(
      <CommentInput
        {...defaultProps}
        userHasPushPermission={false}
        issueLocked={true}
      />
    );

    expect(wrapper.find('Styled(Text)').length).toEqual(1);
    expect(wrapper.find('Icon').length).toEqual(1);
  });

  it('should render styled TextInput and send Icon if user has push permissions and issue is locked', () => {
    const wrapper = shallow(
      <CommentInput {...defaultProps} issueLocked={true} />
    );

    expect(wrapper.find('Styled(TextInput)').length).toEqual(1);
    expect(wrapper.find('Styled(Icon)[name="send"]').length).toEqual(1);
  });

  it('should not render styled Text and lock Icon if user has push permissions and issue is locked', () => {
    const wrapper = shallow(
      <CommentInput {...defaultProps} issueLocked={true} />
    );

    expect(wrapper.find('Styled(Text)').length).toEqual(0);
    expect(wrapper.find('Icon').length).toEqual(0);
  });

  it('should not render styled Text and lock Icon if user does not have push permissions and issue is not locked', () => {
    const wrapper = shallow(
      <CommentInput {...defaultProps} userHasPushPermission={false} />
    );

    expect(wrapper.find('Styled(Text)').length).toEqual(0);
    expect(wrapper.find('Icon').length).toEqual(0);
  });

  it('should render styled TextInput and send Icon if user does not have push permissions and issue is not locked', () => {
    const wrapper = shallow(
      <CommentInput {...defaultProps} userHasPushPermission={false} />
    );

    expect(wrapper.find('Styled(TextInput)').length).toEqual(1);
    expect(wrapper.find('Styled(Icon)[name="send"]').length).toEqual(1);
  });

  it('should update the state text if value is changed', () => {
    const wrapper = shallow(<CommentInput {...defaultProps} />);

    const input = wrapper.find('Styled(TextInput)');

    input.simulate('changeText', 'Changed text');

    expect(wrapper.state('text')).toEqual('Changed text');
  });

  it('should call handleSubmit method when submitted', () => {
    const wrapper = shallow(<CommentInput {...defaultProps} />);

    const handleSubmitSpy = jest.spyOn(wrapper.instance(), 'handleSubmit');

    wrapper.instance().forceUpdate();

    wrapper.find('Styled(TextInput)').simulate('changeText', 'Changed text');

    wrapper
      .find('Styled(Icon)[name="send"]')
      .parent()
      .simulate('press');

    expect(handleSubmitSpy).toHaveBeenCalled();
  });

  it('should change the content size', () => {
    const wrapper = shallow(<CommentInput {...defaultProps} />);

    wrapper.find('Styled(TextInput)').simulate('contentSizeChange', {
      nativeEvent: {
        contentSize: {
          height: 10,
        },
      },
    });

    expect(wrapper.state('height')).toBe(10);
  });

  it('should call handleSubmitEditing method in Android when onSubmitEditing event is raised', () => {
    const wrapper = shallow(<CommentInput {...defaultProps} />);

    const handleSubmitEditingSpy = jest.spyOn(
      wrapper.instance(),
      'handleSubmitEditing'
    );

    wrapper.instance().forceUpdate();

    Platform.OS = 'android';

    wrapper.find('Styled(TextInput)').simulate('submitEditing', {
      nativeEvent: {
        text: 'Changed by submitEditing',
      },
    });

    expect(handleSubmitEditingSpy).toHaveBeenCalled();

    expect(wrapper.state('text')).toEqual('Changed by submitEditing\n');
  });
});


text:
from __future__ import unicode_literals

"""
File:   client.py
Author: goodspeed
Email:  cacique1103@gmail.com
Github: https://github.com/zongxiao
Date:   2015-02-06
Description: Weixin OAuth2
"""

from . import oauth2
from .bind import bind_method
from .helper import genarate_signature

SUPPORTED_FORMATS = ['', 'json']

class WeixinAPI(oauth2.OAuth2API):

    host = "open.weixin.qq.com"
    base_path = ""
    access_token_field = "access_token"
    authorize_url = "https://open.weixin.qq.com/connect/qrconnect"
    access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token"
    refresh_token_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token"
    protocol = "https"
    api_name = "Weixin"
    x_ratelimit_remaining = None
    x_ratelimit = None

    def __init__(self, *args, **kwargs):
        format = kwargs.get('format', '')
        if format in SUPPORTED_FORMATS:
            self.format = format
        else:
            raise Exception("Unsupported format")
        super(WeixinAPI, self).__init__(*args, **kwargs)

    validate_token = bind_method(path='/sns/auth',
                                 accepts_parameters=['openid'],
                                 response_type="entry")

    user = bind_method(path="/sns/userinfo",
                       accepts_parameters=["openid"],
                       response_type="entry")

class WeixinMpAPI(oauth2.OAuth2API):

    host = "open.weixin.qq.com"
    base_path = ""
    access_token_field = "access_token"
    authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize"
    access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token"
    refresh_token_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token"
    client_credential_token_url = "https://api.weixin.qq.com/cgi-bin/token"
    protocol = "https"
    api_name = "WeixinMp"
    x_ratelimit_remaining = None
    x_ratelimit = None

    def __init__(self, *args, **kwargs):
        self.mp_token = kwargs.get('mp_token', None)
        self.timestamp = kwargs.get('timestamp', None)
        self.nonce = kwargs.get('nonce', None)
        self.signature = kwargs.get('signature', None)
        self.echostr = kwargs.get('echostr', None)
        self.xml_body = kwargs.get('xml_body', None)
        self.grant_type = kwargs.get('grant_type', None)
        format = kwargs.get('format', '')

        if format in SUPPORTED_FORMATS:
            self.format = format
        else:
            raise Exception("Unsupported format")
        super(WeixinMpAPI, self).__init__(*args, **kwargs)

    def validate_signature(self):
        params = {
            'timestamp': self.timestamp,
            'token': self.mp_token,
            'nonce': self.nonce
        }
        signature = genarate_signature(params)
        return signature == self.signature

    user = bind_method(path="/sns/userinfo",
                       accepts_parameters=["openid"],
                       response_type="entry")

    jsapi_ticket = bind_method(path='/cgi-bin/ticket/getticket',
                               accepts_parameters=['type'],
                               response_type="entry")


text: export * from '@/module';


text:
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using Newtonsoft.Json.Linq;
using Star.Layoff.DtsComponents.Common;
using Star.Layoff.DtsComponents.Utilities;
using System;
using System.Collections.Generic;
using System.Text;

namespace Star.Layoff.DtsComponents
{
    [
        DtsPipelineComponent(ComponentType = ComponentType.Transform,
            CurrentVersion = 4,
            DisplayName = "JSON Derived Columns",
            Description = "Derive columns from JSON objects",
            RequiredProductLevel = Microsoft.SqlServer.Dts.Runtime.Wrapper.DTSProductLevel.DTSPL_NONE,
            UITypeName = "Star.Layoff.DtsComponents.UI.TxJSONDerivedUI, Star.Layoff.DtsComponents.DtsComponentUI")
    ]
    public class TxJSONDerived : PipelineComponent
    {
        private Dictionary<string, PipelineColumnInfo> mappingPaths;
        private PipelineColumnInfo inputColInfo;

        public override void ProvideComponentProperties()
        {
            // start out clean, remove anything put on by the base class
            RemoveAllInputsOutputsAndCustomProperties();

            // error dispositions
            ComponentMetaData.UsesDispositions = true;

            // Add the mapping property.
            var propMapping = ComponentMetaData.CustomPropertyCollection.New();
            propMapping.Name = Constants.PropMapping;
            propMapping.Description = "Mapping (in json format)";
            propMapping.Value = string.Empty;

            IDTSInput100 input = ComponentMetaData.InputCollection.New();
            input.Name = "JSON input";

            IDTSOutput100 output = ComponentMetaData.OutputCollection.New();
            output.Name = "Output";
            output.SynchronousInputID = input.ID;
            output.ExternalMetadataColumnCollection.IsUsed = false;

            // Get the assembly version and set that as our current version.
            SetComponentVersion();

            // Insert an error output.
            var errorOutput = ComponentMetaData.OutputCollection.New();
            errorOutput.Name = "ErrorOutput";
            errorOutput.IsErrorOut = true;
            errorOutput.SynchronousInputID = input.ID;
            errorOutput.ExclusionGroup = 1;
        }

        //public override IDTSCustomProperty100 SetComponentProperty(string propertyName, object propertyValue)
        //{
        //    if (propertyName == propMappingName)
        //    {
        //        this.mappingPaths = JsonParser.GetPropertyList((string)propertyValue);
        //    }

        //    return base.SetComponentProperty(propertyName, propertyValue);
        //}

        /// <summary>
        /// Disallow inserting an input by throwing an error.
        /// </summary>
        /// <param name="insertPlacement">unused</param>
        /// <param name="inputID">unused</param>
        /// <returns>N/A</returns>
        public override IDTSInput100 InsertInput(DTSInsertPlacement insertPlacement, int inputID)
        {
            bool bCancel;

            ErrorSupport.FireError(HResults.DTS_E_CANTADDINPUT, out bCancel);
            throw new PipelineComponentHResultException(HResults.DTS_E_CANTADDINPUT);
        }

        /// <summary>
        /// Disallow inserting an output by throwing an error.
        /// </summary>
        /// <param name="insertPlacement">unused</param>
        /// <param name="outputID">unused</param>
        /// <returns>N/A</returns>
        public override IDTSOutput100 InsertOutput(DTSInsertPlacement insertPlacement, int outputID)
        {
            bool bCancel;

            ErrorSupport.FireError(HResults.DTS_E_CANTADDOUTPUT, out bCancel);
            throw new PipelineComponentHResultException(HResults.DTS_E_CANTADDOUTPUT);
        }

        /// <summary>
        /// Disallow deleting an input by throwing an error.
        /// </summary>
        /// <param name="inputID">N/A</param>
        public override void DeleteInput(int inputID)
        {
            bool bCancel;

            ErrorSupport.FireError(HResults.DTS_E_CANTDELETEINPUT, out bCancel);
            throw new PipelineComponentHResultException(HResults.DTS_E_CANTDELETEINPUT);
        }

        /// <summary>
        /// Disallow deleting an output by throwing an error.
        /// </summary>
        /// <param name="outputID">unused</param>
        public override void DeleteOutput(int outputID)
        {
            bool bCancel;

            ErrorSupport.FireError(HResults.DTS_E_CANTDELETEOUTPUT, out bCancel);
            throw new PipelineComponentHResultException(HResults.DTS_E_CANTDELETEOUTPUT);
        }

        /// <summary>
        /// Disallow inserting an output column by throwing an error.
        /// </summary>
        /// <param name="outputID">unused</param>
        /// <param name="outputColumnIndex">unused</param>
        /// <param name="name">unused</param>
        /// <param name="description">unused</param>
        /// <returns>N/A</returns>
        public override IDTSOutputColumn100 InsertOutputColumnAt(int outputID, int outputColumnIndex, string name, string description)
        {
            bool bCancel;

            ErrorSupport.FireError(HResults.DTS_E_CANTADDCOLUMN, out bCancel);
            throw new PipelineComponentHResultException(HResults.DTS_E_CANTADDCOLUMN);
        }

        /// <summary>
        /// Disallow deleting an output column by throwing an error.
        /// </summary>
        /// <param name="outputID">unused</param>
        /// <param name="outputColumnID">unused</param>
        public override void DeleteOutputColumn(int outputID, int outputColumnID)
        {
            bool bCancel;

            ErrorSupport.FireError(HResults.DTS_E_CANTDELETECOLUMN, out bCancel);
            throw new PipelineComponentHResultException(HResults.DTS_E_CANTDELETECOLUMN);
        }

        public override IDTSInputColumn100 SetUsageType(int inputID, IDTSVirtualInput100 virtualInput, int lineageID, DTSUsageType usageType)
        {
            if (usageType == DTSUsageType.UT_READWRITE)
            {
                bool bCancel;
                ErrorSupport.FireErrorWithArgs(
                    HResults.DTS_E_CANTSETUSAGETYPETOREADWRITE,
                    out bCancel, virtualInput.IdentificationString, lineageID);
                throw new PipelineComponentHResultException(HResults.DTS_E_CANTSETUSAGETYPETOREADWRITE);
            }
            else
            {
                return base.SetUsageType(inputID, virtualInput, lineageID, usageType);
            }
        }

        public override void SetOutputColumnDataTypeProperties(int iOutputID, int iOutputColumnID, DataType eDataType, int iLength, int iPrecision, int iScale, int iCodePage)
        {
            if (eDataType != DataType.DT_WSTR && eDataType != DataType.DT_STR &&
                eDataType != DataType.DT_IMAGE && eDataType != DataType.DT_NTEXT && eDataType != DataType.DT_TEXT)
            {
                throw new PipelineComponentHResultException(HResults.DTS_E_UNEXPECTEDCOLUMNDATATYPE);
            }

            var output = ComponentMetaData.OutputCollection.FindObjectByID(iOutputID);
            var col = output.OutputColumnCollection.FindObjectByID(iOutputColumnID);
            col.SetDataTypeProperties(eDataType, iLength, iPrecision, iScale, iCodePage);
        }

        public override void ReinitializeMetaData()
        {
            // baseclass may have some work to do here
            base.ReinitializeMetaData();

            int iErrorOutID = 0, iErrorOutIndex = 0;
            GetErrorOutputInfo(ref iErrorOutID, ref iErrorOutIndex);
            var outputMain = ComponentMetaData.OutputCollection[iErrorOutIndex == 0 ? 1 : 0];
            var inputMain = ComponentMetaData.InputCollection[0];

            // start fresh
            inputMain.InputColumnCollection.RemoveAll();

            var propMapping = ComponentMetaData.CustomPropertyCollection[Constants.PropMapping];
            if (propMapping != null && !string.IsNullOrEmpty((string)propMapping.Value))
            {
                int i = 0;
                // clear the current output columns
                outputMain.OutputColumnCollection.RemoveAll();

                foreach (var prop in JsonParser.GetPropertyList((string)propMapping.Value))
                {
                    var outputCol = outputMain.OutputColumnCollection.NewAt(i++);
                    outputCol.Name = prop;
                    outputCol.SetDataTypeProperties(DataType.DT_WSTR, 50, 0, 0, 0);
                }
            }
        }

        public override DTSValidationStatus Validate()
        {
            var status = base.Validate();
            if (status == DTSValidationStatus.VS_ISCORRUPT)
            {
                return status;
            }

            // should have one input, one column
            if (ComponentMetaData.InputCollection.Count != 1 ||
                ComponentMetaData.InputCollection[0].InputColumnCollection.Count != 1)
            {
                return DTSValidationStatus.VS_ISCORRUPT;
            }

            // should have two outputs
            if (ComponentMetaData.OutputCollection.Count > 2)
            {
                return DTSValidationStatus.VS_ISCORRUPT;
            }

            var inputMain = ComponentMetaData.InputCollection[0];
            var eDataType = inputMain.InputColumnCollection[0].DataType;

            if (eDataType != DataType.DT_WSTR && eDataType != DataType.DT_STR &&
                eDataType != DataType.DT_IMAGE && eDataType != DataType.DT_NTEXT && eDataType != DataType.DT_TEXT)
            {
                throw new PipelineComponentHResultException(HResults.DTS_E_UNEXPECTEDCOLUMNDATATYPE);
            }

            int iErrorOutID = 0, iErrorOutIndex = 0;
            GetErrorOutputInfo(ref iErrorOutID, ref iErrorOutIndex);
            var outputMain = ComponentMetaData.OutputCollection[iErrorOutIndex == 0 ? 1 : 0];

            for (var i = 0; i < outputMain.OutputColumnCollection.Count; i++)
            {
                var col = outputMain.OutputColumnCollection[i];
                eDataType = col.DataType;
                if (eDataType != DataType.DT_WSTR && eDataType != DataType.DT_STR &&
                    eDataType != DataType.DT_IMAGE && eDataType != DataType.DT_NTEXT && eDataType != DataType.DT_TEXT)
                {
                    throw new PipelineComponentHResultException(HResults.DTS_E_UNEXPECTEDCOLUMNDATATYPE);
                }
            }

            return DTSValidationStatus.VS_ISVALID;
        }

        public override void PreExecute()
        {
            // baseclass may need to do some work
            base.PreExecute();

            int iErrorOutID = 0, iErrorOutIndex = 0;
            GetErrorOutputInfo(ref iErrorOutID, ref iErrorOutIndex);
            var outputMain = ComponentMetaData.OutputCollection[iErrorOutIndex == 0 ? 1 : 0];
            // input should be only one column
            var inputMain = ComponentMetaData.InputCollection[0];

            // in case outputMain is null, let it throw, just like an assertion
            this.mappingPaths = new Dictionary<string, PipelineColumnInfo>(outputMain.OutputColumnCollection.Count);

            // buffer layout is only fixed during PreExecute phase, keep a copy
            // of the buffer column index
            // it's a synchronous transform so that always look up via the input
            // buffer
            for (var i = 0; i < outputMain.OutputColumnCollection.Count; i++)
            {
                var col = outputMain.OutputColumnCollection[i];

                this.mappingPaths[col.Name] = new PipelineColumnInfo()
                {
                    BufferColumnIndex = BufferManager.FindColumnByLineageID(inputMain.Buffer, col.LineageID),
                    InOutColumnIndex = i
                };
            }

            this.inputColInfo = new PipelineColumnInfo
            {
                BufferColumnIndex = BufferManager.FindColumnByLineageID(inputMain.Buffer, inputMain.InputColumnCollection[0].LineageID),
                InOutColumnIndex = 0
            };
        }

        public override void ProcessInput(int inputID, PipelineBuffer buffer)
        {
            while (buffer.NextRow())
            {
                var col = this.inputColInfo.BufferColumnIndex;
                var inputType = buffer.GetColumnInfo(col).DataType;
                string inputValue = string.Empty;
                if (inputType == DataType.DT_IMAGE)
                {
                    inputValue = Encoding.UTF8.GetString(buffer.GetBlobData(col, 0, (int)buffer.GetBlobLength(col)));
                }
                else if (inputType == DataType.DT_STR || inputType == DataType.DT_WSTR ||
                    inputType == DataType.DT_TEXT || inputType == DataType.DT_NTEXT)
                {
                    inputValue = buffer.GetString(col);
                }

                JObject obj = JObject.Parse(inputValue);
                foreach (var mapping in this.mappingPaths)
                {
                    var token = obj.SelectToken(mapping.Key, false);
                    if (token == null)
                    {
                        continue;
                    }

                    var outputType = buffer.GetColumnInfo(mapping.Value.BufferColumnIndex).DataType;
                    if (outputType == DataType.DT_IMAGE)
                    {
                        buffer.AddBlobData(mapping.Value.BufferColumnIndex, Encoding.UTF8.GetBytes(token.ToString()));
                    }
                    else if (outputType == DataType.DT_STR || outputType == DataType.DT_WSTR ||
                        outputType == DataType.DT_TEXT || outputType == DataType.DT_NTEXT)
                    {
                        buffer.SetString(mapping.Value.BufferColumnIndex, token.ToString());
                    }
                }
            }
        }

        private void SetComponentVersion()
        {
            // Get the assembly version and set that as our current version.
            DtsPipelineComponentAttribute attr = (DtsPipelineComponentAttribute)
                    Attribute.GetCustomAttribute(this.GetType(), typeof(DtsPipelineComponentAttribute), false);

            ComponentMetaData.Version = attr.CurrentVersion;
        }

        public override void PerformUpgrade(int pipelineVersion)
        {
            // Get the assembly version and set that as our current version.
            SetComponentVersion();
        }
    }
}


text:
/*
 * Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model.
 */

using System;

namespace Amazon.DynamoDBv2.Model
{
    /// <summary>
    /// Configuration for accessing Amazon Scan service
    /// </summary>
    public partial class ScanResponse : ScanResult
    {
        /// <summary>
        /// Gets and sets the ScanResult property.
        /// Represents the output of a Scan operation.
        /// </summary>
        [Obsolete(@"This property has been deprecated. All properties of the ScanResult class are now available on the ScanResponse class. You should use the properties on ScanResponse instead of accessing them through ScanResult.")]
        public ScanResult ScanResult
        {
            get
            {
                return this;
            }
        }
    }
}


text:
namespace Poco {

class Foundation_API UUID
	/// A UUID is an identifier that is unique across both space and time,
	/// with respect to the space of all UUIDs. Since a UUID is a fixed
	/// size and contains a time field, it is possible for values to
	/// rollover (around A.D. 3400, depending on the specific algorithm
	/// used). A UUID can be used for multiple purposes, from tagging
	/// objects with an extremely short lifetime, to reliably identifying
	/// very persistent objects across a network.
	/// This class implements a Universal Unique Identifier,
	/// as specified in Appendix A of the DCE 1.1 Remote Procedure
	/// Call Specification (http://www.opengroup.org/onlinepubs/9629399/),
	/// RFC 2518 (WebDAV), section 6.4.1 and the UUIDs and GUIDs internet
	/// draft by Leach/Salz from February, 1998
	/// (http://ftp.ics.uci.edu/pub/ietf/webdav/uuid-guid/draft-leach-uuids-guids-01.txt)
	/// and also
	/// http://www.ietf.org/internet-drafts/draft-mealling-uuid-urn-03.txt
{
public:
	enum Version
	{
		UUID_TIME_BASED = 0x01,
		UUID_DCE_UID    = 0x02,
		UUID_NAME_BASED = 0x03,
		UUID_RANDOM     = 0x04
	};

	UUID();
		/// Creates a nil (all zero) UUID.

	UUID(const UUID& uuid);
		/// Copy constructor.

	explicit UUID(const std::string& uuid);
		/// Parses the UUID from a string.

	explicit UUID(const char* uuid);
		/// Parses the UUID from a string.

	~UUID();
		/// Destroys the UUID.

	UUID& operator = (const UUID& uuid);
		/// Assignment operator.

	void swap(UUID& uuid);
		/// Swaps the UUID with another one.

	void parse(const std::string& uuid);
		/// Parses the UUID from its string representation.

	bool tryParse(const std::string& uuid);
		/// Tries to interpret the given string as an UUID.
		/// If the UUID is syntactically valid, assigns the
		/// members and returns true. Otherwise leaves the
		/// object unchanged and returns false.

	std::string toString() const;
		/// Returns a string representation of the UUID consisting
		/// of groups of hexadecimal digits separated by hyphens.

	void copyFrom(const char* buffer);
		/// Copies the UUID (16 bytes) from a buffer or byte array.
		/// The UUID fields are expected to be
		/// stored in network byte order.
		/// The buffer need not be aligned.

	void copyTo(char* buffer) const;
		/// Copies the UUID to the buffer. The fields
		/// are in network byte order.
		/// The buffer need not be aligned.
		/// There must have room for at least 16 bytes.

	Version version() const;
		/// Returns the version of the UUID.

	int variant() const;
		/// Returns the variant number of the UUID:
		///   - 0 reserved for NCS backward compatibility
		///   - 2 the Leach-Salz variant (used by this class)
		///   - 6 reserved, Microsoft Corporation backward compatibility
		///   - 7 reserved for future definition

	bool operator == (const UUID& uuid) const;
	bool operator != (const UUID& uuid) const;
	bool operator <  (const UUID& uuid) const;
	bool operator <= (const UUID& uuid) const;
	bool operator >  (const UUID& uuid) const;
	bool operator >= (const UUID& uuid) const;

	bool isNull() const;
		/// Returns true iff the UUID is nil (in other words,
		/// consists of all zeros).

	static const UUID& null();
		/// Returns a null/nil UUID.

	static const UUID& dns();
		/// Returns the namespace identifier for the DNS namespace.

	static const UUID& uri();
		/// Returns the namespace identifier for the URI (former URL) namespace.

	static const UUID& oid();
		/// Returns the namespace identifier for the OID namespace.

	static const UUID& x500();
		/// Returns the namespace identifier for the X500 namespace.

protected:
	UUID(UInt32 timeLow, UInt32 timeMid, UInt32 timeHiAndVersion, UInt16 clockSeq, UInt8 node[]);
	UUID(const char* bytes, Version version);
	int compare(const UUID& uuid) const;
	static void appendHex(std::string& str, UInt8 n);
	static void appendHex(std::string& str, UInt16 n);
	static void appendHex(std::string& str, UInt32 n);
	static UInt8 nibble(char hex);
	void fromNetwork();
	void toNetwork();

private:
	UInt32 _timeLow;
	UInt16 _timeMid;
	UInt16 _timeHiAndVersion;
	UInt16 _clockSeq;
	UInt8  _node[6];

	friend class UUIDGenerator;
};

//
// inlines
//
inline bool UUID::operator == (const UUID& uuid) const
{
	return compare(uuid) == 0;
}

inline bool UUID::operator != (const UUID& uuid) const
{
	return compare(uuid) != 0;
}

inline bool UUID::operator < (const UUID& uuid) const
{
	return compare(uuid) < 0;
}

inline bool UUID::operator <= (const UUID& uuid) const
{
	return compare(uuid) <= 0;
}

inline bool UUID::operator > (const UUID& uuid) const
{
	return compare(uuid) > 0;
}

inline bool UUID::operator >= (const UUID& uuid) const
{
	return compare(uuid) >= 0;
}

inline UUID::Version UUID::version() const
{
	return Version(_timeHiAndVersion >> 12);
}

inline bool UUID::isNull() const
{
	return compare(null()) == 0;
}

inline void swap(UUID& u1, UUID& u2)
{
	u1.swap(u2);
}

} // namespace Poco

#endif // Foundation_UUID_INCLUDED


text:
ActiveRecord::Schema.define(version: 20140924112928) do

  create_table "comments", force: true do |t|
    t.integer  "post_id"
    t.string   "author"
    t.text     "content"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "comments", ["post_id"], name: "index_comments_on_post_id"

  create_table "posts", force: true do |t|
    t.string   "title"
    t.text     "body"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "state"
    t.string   "slug"
  end

  add_index "posts", ["slug"], name: "index_posts_on_slug"

end


text:
<?php

namespace Zephir\Optimizers\FunctionCall;

use Zephir\Optimizers\IsTypeOptimizerAbstract;

/**
 * IsStringOptimizer
 *
 * Optimizes calls to 'is_string' using internal function
 */
class IsResourceOptimizer extends IsTypeOptimizerAbstract
{
    protected function getType()
    {
        return 'IS_RESOURCE';
    }
}


text:
package org.squbs

package object testkit {
  case object TestPing
  case object TestPong
}


text:
package io.apiman.manager.api.beans.members;

import java.io.Serializable;

/**
 * Models a user's membership in a role for a given organization.
 *
 * @author eric.wittmann@redhat.com
 */
public class MemberRoleBean implements Serializable {

    private static final long serialVersionUID = 7645338035552144540L;

    private String roleId;
    private String roleName;

    /**
     * Constructor.
     */
    public MemberRoleBean() {
    }

    /**
     * @return the roleId
     */
    public String getRoleId() {
        return roleId;
    }

    /**
     * @param roleId the roleId to set
     */
    public void setRoleId(String roleId) {
        this.roleId = roleId;
    }

    /**
     * @return the roleName
     */
    public String getRoleName() {
        return roleName;
    }

    /**
     * @param roleName the roleName to set
     */
    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    @SuppressWarnings("nls")
    public String toString() {
        return "MemberRoleBean [roleId=" + roleId + ", roleName=" + roleName + "]";
    }

}


text:
package org.auraframework.system;

import java.io.Serializable;
import java.util.Set;

import org.auraframework.def.DefDescriptor;
import org.auraframework.def.DefDescriptor.DefType;
import org.auraframework.def.Definition;
import org.auraframework.def.DescriptorFilter;
import org.auraframework.throwable.quickfix.QuickFixException;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;

/**
 * Public interface for retrieving aura definitions.
 *
 * This interface has several implementations with highly variable performance parameters.
 * There should be no assumption that exists/getDef/find are efficient.
 *
 * Note: The typing here is as bogus as it gets. T is not valid.
 */
public interface DefRegistry<T extends Definition> extends Serializable {

    /**
     * Return the definition for this descriptor, or null if it does not exist.
     *
     * This will only load the definition, it will not fully compile it.
     *
     * @throws QuickFixException
     */
    @CheckForNull
    T getDef(DefDescriptor<T> descriptor) throws QuickFixException;

    /**
     * Return true if the find methods work.
     *
     * @return true if find will not throw 'UnsupportedOperationException'
     */
    boolean hasFind();

    /**
     * Given a descriptor that contains search patterns or wildcards, return a
     * set of Descriptors for all existing Definitions who have source that
     * exists. Does not compile the definitions if they were not already
     * compiled, and does not guarantee that they can compile.
     */
    @NonNull
    Set<DefDescriptor<T>> find(@NonNull DefDescriptor<T> matcher);

    /**
     * Given a string that contains search patterns or wildcards, return a set
     * of Descriptors for all existing Definitions who have source that exists.
     * Does not compile the definitions if they were not already compiled, and
     * does not guarantee that they can compile.
     */
    @NonNull
    Set<DefDescriptor<?>> find(@NonNull DescriptorFilter matcher);

    /**
     * Save the given definition back to appropriate source location.
     */
    void save(T def);

    /**
     * Returns true if the source related to the descriptor exists. Does not
     * compile the definition if it was not already compiled, and does not
     * guarantee that it can compile.
     */
    boolean exists(DefDescriptor<T> descriptor);

    /**
     * The DefTypes that this registry handles (returns)
     */
    @NonNull
    Set<DefType> getDefTypes();

    /**
     * The Prefixes that this registry handles
     */
    @NonNull
    Set<String> getPrefixes();

    /**
     * Returns a Set of namespaces for which this registry is authoritative. "*"
     * indicates that the registry should be used when no other registry has
     * registered for a namespace.
     */
    @NonNull
    Set<String> getNamespaces();

    /**
     * Get the source file for a descriptor.
     *
     * This is not always available, and so may return null even if the descriptor has a definition.
     */
    @CheckForNull
    Source<T> getSource(DefDescriptor<T> descriptor);

    /**
     * Clear this registry of all defs it might be storing
     */
    void clear();

    /**
     * return true if the caller can cache the value.
     *
     * This means that the def for a descriptor should not be mutable. The only exception here is that
     * change notifications will flush the cache.
     */
    boolean isCacheable();

    /**
     * Return true if registry cannot change after creation.
     *
     * There is an implicit assumption that static registries are fast, and thus need not be cached
     * by the implementation.
     */
    boolean isStatic();
}


text:
package conn

import (
	"io"
	"net"
	"time"

	key "github.com/djbarber/ipfs-hack/blocks/key"
	ic "github.com/djbarber/ipfs-hack/p2p/crypto"
	filter "github.com/djbarber/ipfs-hack/p2p/net/filter"
	peer "github.com/djbarber/ipfs-hack/p2p/peer"

	msgio "github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/jbenet/go-msgio"
	ma "github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	manet "github.com/djbarber/ipfs-hack/Godeps/_workspace/src/github.com/jbenet/go-multiaddr-net"
)

// Map maps Keys (Peer.IDs) to Connections.
type Map map[key.Key]Conn

type PeerConn interface {
	io.Closer

	// LocalPeer (this side) ID, PrivateKey, and Address
	LocalPeer() peer.ID
	LocalPrivateKey() ic.PrivKey
	LocalMultiaddr() ma.Multiaddr

	// RemotePeer ID, PublicKey, and Address
	RemotePeer() peer.ID
	RemotePublicKey() ic.PubKey
	RemoteMultiaddr() ma.Multiaddr
}

// Conn is a generic message-based Peer-to-Peer connection.
type Conn interface {
	PeerConn

	// ID is an identifier unique to this connection.
	ID() string

	// can't just say "net.Conn" cause we have duplicate methods.
	LocalAddr() net.Addr
	RemoteAddr() net.Addr
	SetDeadline(t time.Time) error
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error

	msgio.Reader
	msgio.Writer
}

// Dialer is an object that can open connections. We could have a "convenience"
// Dial function as before, but it would have many arguments, as dialing is
// no longer simple (need a peerstore, a local peer, a context, a network, etc)
type Dialer struct {

	// Dialer is an optional manet.Dialer to use.
	Dialer manet.Dialer

	// LocalPeer is the identity of the local Peer.
	LocalPeer peer.ID

	// LocalAddrs is a set of local addresses to use.
	LocalAddrs []ma.Multiaddr

	// PrivateKey used to initialize a secure connection.
	// Warning: if PrivateKey is nil, connection will not be secured.
	PrivateKey ic.PrivKey

	// Wrapper to wrap the raw connection (optional)
	Wrapper func(manet.Conn) manet.Conn
}

// Listener is an object that can accept connections. It matches net.Listener
type Listener interface {

	// Accept waits for and returns the next connection to the listener.
	Accept() (net.Conn, error)

	// Addr is the local address
	Addr() net.Addr

	// Multiaddr is the local multiaddr address
	Multiaddr() ma.Multiaddr

	// LocalPeer is the identity of the local Peer.
	LocalPeer() peer.ID

	SetAddrFilters(*filter.Filters)

	// Close closes the listener.
	// Any blocked Accept operations will be unblocked and return errors.
	Close() error
}

// EncryptConnections is a global parameter because it should either be
// enabled or _completely disabled_. I.e. a node should only be able to talk
// to proper (encrypted) networks if it is encrypting all its transports.
// Running a node with disabled transport encryption is useful to debug the
// protocols, achieve implementation interop, or for private networks which
// -- for whatever reason -- _must_ run unencrypted.
var EncryptConnections = true


text:
<?php

namespace Darsyn\IP\Tests\Formatter;

use Darsyn\IP\Exception\Formatter\FormatException;
use Darsyn\IP\Formatter\ConsistentFormatter as Formatter;
use Darsyn\IP\Formatter\ProtocolFormatterInterface;
use PHPUnit\Framework\TestCase;

class ConsistentFormatterTest extends TestCase
{
    /** @var \Darsyn\IP\Formatter\ProtocolFormatterInterface $formatter */
    private $formatter;

    /** @before */
    protected function setUpWithoutReturnDeclaration()
    {
        $this->formatter = new Formatter;
    }

    /**
     * @test
     */
    public function testFormatterIsInstanceOfInterface()
    {
        $this->assertInstanceOf(ProtocolFormatterInterface::class, $this->formatter);
    }

    /**
     * @test
     * @dataProvider \Darsyn\IP\Tests\DataProvider\Formatter\ConsistentFormatter::getValidBinarySequences()
     */
    public function testFormatterReturnsCorrectProtocolString($value, $expected)
    {
        $this->assertSame($expected, $this->formatter->ntop($value));
    }

    /**
     * @test
     * @dataProvider \Darsyn\IP\Tests\DataProvider\Formatter\ConsistentFormatter::getInvalidBinarySequences()
     */
    public function testFormatterThrowsExceptionOnInvalidBinarySequences($value)
    {
        $this->expectException(\Darsyn\IP\Exception\Formatter\FormatException::class);
        try {
            $this->formatter->ntop($value);
        } catch (FormatException $e) {
            $this->assertSame($value, $e->getSuppliedBinary());
            throw $e;
        }
        $this->fail();
    }
}


text:
package com.iticket.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.iticket.model.api.ClientMember;
import com.iticket.model.program.Program;
import com.iticket.model.schedule.Price2Stand;
import com.iticket.model.schedule.Schedule;
import com.iticket.model.schedule.SchedulePrice;
import com.iticket.model.schedule.ScheduleSeat;
import com.iticket.model.schedule.ScheduleStand;
import com.iticket.model.schedule.ScheduleVenueArea;
import com.iticket.model.stadium.Seat;
import com.iticket.model.stadium.Venue;
import com.iticket.model.stadium.VenueArea;
import com.iticket.service.IException;
import com.iticket.service.ScheduleService;
import com.iticket.support.ResultCode;
import com.iticket.util.BeanUtil;
import com.iticket.util.BindUtils;
import com.iticket.util.StringUtil;
import com.iticket.web.util.WebUtils;
import com.iticket.xml.XHelp;
import com.iticket.xml.XPrice2Stand;
import com.iticket.xml.XPrice2StandList;
import com.iticket.xml.XSchedulePrice;
import com.iticket.xml.XSchedulePriceList;

@Service("scheduleService")
public class ScheduleServiceImpl extends BaseServiceImpl implements ScheduleService{
	private String getUploadPath(){
		return config.getString("uploadPath");
	}
	@Override
	public Schedule addSchedule(ClientMember member, Long stadiumId, Long scheduleId, Long venueId, String seat, String venueBackground, String fileType, HttpServletRequest request)
			throws IException {
		if(venueId==null){
			throw new IException("场地id不能为空");
		}
		Venue venue = baseDao.getObject(Venue.class, venueId);
		if(venue==null){
			throw new IException("场地不存在");
		}
		if(!venue.getStadiumId().equals(member.getStadiumId())){
			throw IException.ILLEGAL;
		}
		Schedule s = null;
		String fileName = null;
		Long layoutId = null;
		List<VenueArea> venueAreaList = new ArrayList<VenueArea>();
		if(scheduleId!=null){
			s = baseDao.getObject(Schedule.class, scheduleId);
			if(!s.getStadiumId().equals(stadiumId)){
				throw IException.ILLEGAL;
			}
			if(!StringUtils.equals(s.getSeat(), seat)){
				throw new IException("不能由选座改为普通场次,或有普通场次转化为选座");
			}
			fileName = s.getVenueBackground();
			layoutId = s.getLayoutId();
		}else {
			s = new Schedule(member.getId());
			venueAreaList = baseDao.getObjectListByField(VenueArea.class, "venueId", venueId);
			if(venueAreaList.size()==0){
				throw new IException("还未设置基础区域,请先设置区域才开场次");
			}
		}
		BindUtils.bindData(s, WebUtils.getRequestMap(request));
		if(StringUtils.isBlank(s.getCode())){
			throw new IException("场次编号不能为空");
		}
		if(StringUtils.isBlank(s.getCnName())){
			throw new IException("场次名称不能为空");
		}
		if(StringUtils.isBlank(s.getCnName())){
			throw new IException("场次名称不能为空");
		}
		if(StringUtils.isBlank(s.getSeat())){
			throw new IException("是否为支持选座不能为空");
		}
		if(StringUtils.isBlank(s.getFixed())){
			throw new IException("是否为固定时间不能为空");
		}
		if(StringUtils.equals(s.getFixed(), "Y")) {
			if(s.getPlayTime()==null){
				throw new IException("场次时间不能为空");
			}
		}else {
			if(s.getPlayEndTime()==null){
				throw new IException("无固定时间的场次,结束时间不能为空");
			}
		}
		if(StringUtils.isBlank(s.getActive())){
			throw new IException("是否激活不能为空");
		}
		if(s.getProgramId()==null){
			throw new IException("项目不能为空");
		}else {
			Program program = baseDao.getObject(Program.class, s.getProgramId());
			if(program==null){
				throw new IException("项目不存在");
			}
		}
		if(StringUtils.isNotBlank(venueBackground)){
			try {
				byte[] x = Hex.decodeHex(venueBackground.toCharArray());
				String ext = StringUtils.contains(fileType, ".") ? fileType : "."+fileType;
				fileName = "schedule/" + StringUtil.getRandomString(12).toLowerCase() + ext;
				File file = new File(getUploadPath() + fileName);
				FileUtils.writeByteArrayToFile(file, x);
			}  catch (Exception e) {
				e.printStackTrace();
				throw new IException("处理图片异常");
			}
		}else {
			fileName = venue.getBackground();
		}
		s.setStadiumId(stadiumId);
		s.setLayoutId(layoutId);
		s.setVenueBackground(fileName);
		s.setDelStatus("N");
		baseDao.saveObject(s);
		if(scheduleId==null){
			boolean hasSeat = StringUtils.equals(seat, "Y");
			if(hasSeat){
				for(VenueArea area : venueAreaList){
					if(area.hasSeat()){
						ScheduleVenueArea sarea = new ScheduleVenueArea(s, area);
						baseDao.saveObject(sarea);
						List<Seat> bSeatList = baseDao.getObjectListByField(Seat.class, "venueAreaId", area.getId());
						for(Seat bSeat : bSeatList){
							ScheduleSeat sseat = new ScheduleSeat(s, bSeat, sarea);
							baseDao.saveObject(sseat);
						}
					}else {
						ScheduleVenueArea sarea = new ScheduleVenueArea(s, area);
						baseDao.saveObject(sarea);
					}
				}
			}else {
				for(VenueArea area : venueAreaList){
					if(!area.hasSeat()){
						ScheduleVenueArea sarea = new ScheduleVenueArea(s, area);
						baseDao.saveObject(sarea);
					}
				}
			}
		}
		return s;
	}
	@Override
	public void addSchedulePrice(ClientMember member, Long scheduleId, String priceBody)
			throws IException {
		Schedule schedule = baseDao.getObject(Schedule.class, scheduleId);
		if(schedule==null){
			throw new IException("场次不存在");
		}
		if(!schedule.getStadiumId().equals(member.getStadiumId())){
			throw IException.ILLEGAL;
		}
		ResultCode<XSchedulePriceList> code = XHelp.getBean(priceBody, "schedulePriceList");
		if(!code.isSuccess()){
			throw new IException(code.getMsg());
		}
		List<SchedulePrice> nxpList = new ArrayList<SchedulePrice>();
		List<XSchedulePrice> xpList = code.getRetval().getSchedulePriceList();
		for(XSchedulePrice xp : xpList){
			SchedulePrice nxp = null;
			if(xp.getPriceId()!=null){
				nxp = baseDao.getObject(SchedulePrice.class, xp.getPriceId());
			}else {
				nxp = new SchedulePrice(member);
			}
			BeanUtil.copyProperties(nxp, xp);
			schedule.setProgramId(schedule.getProgramId());
			nxpList.add(nxp);
		}
		baseDao.saveObjectList(nxpList);
	}
	@Override
	public void addScheduleStandPrice(ClientMember member, Long scheduleId, String priceBody)
			throws IException {
		Schedule schedule = baseDao.getObject(Schedule.class, scheduleId);
		if(schedule==null){
			throw new IException("场次不存在");
		}
		if(!schedule.getStadiumId().equals(member.getStadiumId())){
			throw IException.ILLEGAL;
		}
		ResultCode<XSchedulePriceList> code = XHelp.getBean(priceBody, "schedulePriceList");
		if(!code.isSuccess()){
			throw new IException(code.getMsg());
		}
		List<SchedulePrice> nxpList = new ArrayList<SchedulePrice>();
		List<XSchedulePrice> xpList = code.getRetval().getSchedulePriceList();
		for(XSchedulePrice xp : xpList){
			SchedulePrice nxp = null;
			if(xp.getPriceId()!=null){
				nxp = baseDao.getObject(SchedulePrice.class, xp.getPriceId());
			}else {
				nxp = new SchedulePrice(member);
			}
			BeanUtil.copyProperties(nxp, xp);
			schedule.setProgramId(schedule.getProgramId());
			nxpList.add(nxp);
		}
		baseDao.saveObjectList(nxpList);
	}

	@Override
	public void addPrice2Stand(ClientMember member, Long scheduleId, Long scheduleVenueAreaId, String p2sBody)
			throws IException {
		Schedule schedule = baseDao.getObject(Schedule.class, scheduleId);
		if(schedule==null){
			throw new IException("场次不存在");
		}
		if(!schedule.getStadiumId().equals(member.getStadiumId())){
			throw IException.ILLEGAL;
		}
		ScheduleVenueArea sva = baseDao.getObject(ScheduleVenueArea.class, scheduleVenueAreaId);
		if(sva==null){
			throw new IException("场次区域不存在");
		}
		if(sva.hasSeat()){
			throw new IException("该区域是座位场次,不能设置站票价格");
		}
		dbLogger.warn(p2sBody);
		ResultCode<XPrice2StandList> code = XHelp.getBean(p2sBody, "price2StandList");
		if(!code.isSuccess()){
			throw new IException(code.getMsg());
		}
		List<Price2Stand> resList = new ArrayList<Price2Stand>();
		List<XPrice2Stand> xpList = code.getRetval().getPrice2StandList();
		Map<String, Price2Stand> oldMap = new HashMap<String, Price2Stand>();
		int vlimit = 0, total = 0;
		for(XPrice2Stand xp2s : xpList){
			String pskey = xp2s.getPriceId() + "_" + scheduleVenueAreaId;
			Price2Stand p2s = baseDao.getObject(Price2Stand.class, pskey);
			if(p2s==null){
				p2s = new Price2Stand(member, schedule, xp2s.getPriceId(), scheduleVenueAreaId);
			}else {
				oldMap.put(pskey, p2s);
			}
			p2s.setTotal(xp2s.getTotal());
			p2s.setVlimit(xp2s.getVlimit());
			resList.add(p2s);
			vlimit = vlimit + xp2s.getVlimit();
			total = total + xp2s.getTotal();
		}
		if(total>sva.getTotal()){
			throw new IException("总数不能大于场地区域总数");
		}
		if(vlimit>sva.getVlimit()){
			throw new IException("限制数不能大于场地区域限制总数");
		}
		if(total<=vlimit){
			throw new IException("站票总量不能小于限制总数");
		}
		baseDao.saveObjectList(resList);
		List<ScheduleStand> removeList = new ArrayList<ScheduleStand>();
		List<ScheduleStand> standList = new ArrayList<ScheduleStand>();
		for(Price2Stand res : resList){
			int count = res.getTotal()-res.getVlimit();
			if(oldMap.containsKey(res.getPskey())){
				Price2Stand old = oldMap.get(res.getPskey());
				int oldCount = old.getTotal() - old.getVlimit();
				int diff = oldCount - count;
				if(diff>0){
					List<ScheduleStand> tmpList = getScheduleStand(old, diff);
					removeList.addAll(tmpList);
				}else if(diff<0){
					diff = Math.abs(diff);
					for(int i=1;i<=diff;i++){
						ScheduleStand stand = new ScheduleStand(schedule, res.getPriceId(), scheduleVenueAreaId);
						standList.add(stand);
					}
				}
			}else {
				for(int i=1;i<=count;i++){
					ScheduleStand stand = new ScheduleStand(schedule, res.getPriceId(), scheduleVenueAreaId);
					standList.add(stand);
				}
			}
		}
		baseDao.saveObjectList(standList);
		updScheudlePriceSnum(scheduleId);
	}
	private List<ScheduleStand> getScheduleStand(Price2Stand p2s, int count){
		DetachedCriteria query = DetachedCriteria.forClass(ScheduleStand.class);
		query.add(Restrictions.eq("priceId", p2s.getPriceId()));
		query.add(Restrictions.eq("scheduleVenueAreaId", p2s.getScheduleVenueAreaId()));
		query.add(Restrictions.eq("status", ScheduleStand.STATUS_FREE));
		List<ScheduleStand> standList = baseDao.findByCriteria(query, 0, count);
		return standList;
	}
	@Override
	public void updScheudlePriceSnum(Long scheduleId){
		List<SchedulePrice> spriceList = baseDao.getObjectListByField(SchedulePrice.class, "scheduleId", scheduleId);
		Map<Long, Integer> quantityMap = new HashMap<Long, Integer>();
		Schedule schedule = baseDao.getObject(Schedule.class, scheduleId);
		if(schedule.supportSeat()){
			String hql = "select count(*) from ScheduleSeat s where s.priceId=?";
			for(SchedulePrice sprice : spriceList){
				int q = Integer.valueOf(baseDao.findByHql(hql, sprice.getId()).get(0)+"");
				Integer tmp = quantityMap.get(sprice.getId());
				if(tmp==null){
					tmp = 0;
				}
				quantityMap.put(sprice.getId(), tmp + q);
			}
		}else {
			String hql = "select count(*) from ScheduleStand s where s.priceId=?";
			for(SchedulePrice sprice : spriceList){
				int q = Integer.valueOf(baseDao.findByHql(hql, sprice.getId()).get(0)+"");
				Integer tmp = quantityMap.get(sprice.getId());
				if(tmp==null){
					tmp = 0;
				}
				quantityMap.put(sprice.getId(), tmp + q);
			}
		}
		for(SchedulePrice sprice : spriceList){
			sprice.setSnum(quantityMap.get(sprice.getId()));
		}
		baseDao.saveObjectList(spriceList);
	}
}


text:
{- |
Module : Cantor.Build.Maven
Copyright : Copyright (C) 2014 Krzysztof Langner
License : BSD3

Maintainer : Krzysztof Langner <klangner@gmail.com>
Stability : alpha
Portability : portable

Parser for Maven POM file.
-}
module Cantor.Build.Maven ( parseFile ) where

import Text.XML.HXT.Core
import Data.Tree.NTree.TypeDefs
import Text.XML.HXT.XPath.XPathEval
import Cantor.Build.BuildSystem(BuildSystem, mkBuildSystem)

-- | Parse POM file.
parseFile :: FilePath -> IO BuildSystem
parseFile fp = do
    xs <- runX (readDocument [] fp)
    let bs = bsFromPom fp (head xs)
    return bs

-- Read metadata from pom XML
bsFromPom :: FilePath -> XmlTree -> BuildSystem
bsFromPom fp xt = mkBuildSystem fp "Maven" (readName xt)

-- Get project group from POM.
--readGroup :: XmlTree -> String
--readGroup = getNodeText "/project/groupId/text()"

-- Get project artifact from POM.
--readArtifact :: XmlTree -> String
--readArtifact = getNodeText "/project/artifactId/text()"

-- Get project name from POM.
readName :: XmlTree -> String
readName = getNodeText "/project/name/text()"

-- Get project description from POM.
--readDesc :: XmlTree -> String
--readDesc = getNodeText "/project/description/text()"

-- Get text from given node
getNodeText :: String -> XmlTree -> String
getNodeText xpath dom = case getXPath xpath dom of
                         [NTree (XText a) _] -> a
                         _ -> ""


text:
<?php
namespace MarcosHoo\PropelEloquent;

use Propel\Generator\Model\Behavior;

class EloquentBehavior extends Behavior
{
    public function objectAttributes()
    {
        $table = $this->getTable()->getName();
        return "
protected \$__accessor = false;

protected \$table = '$table';
        ";
    }

    public function objectMethods()
    {
        $mutators = "\n";

        foreach ($this->getTable()->getColumns() as $col) {
            $class = $this->getTableFullClassName();
            $name = $col->getName();
            $phpname = $col->getPhpName();
            $mutators .= "/**
 * Set the value of [{$name}] column.
 *
 * @param string \$v new value
 * @return \$this|\{$class} The current object (for fluent API support)
 */
public function set{$phpname}Temp(\$value)
{
    \$result = \$this->set{$phpname}Attribute(\$value);
    \$this->attributes['{$name}'] = \$this->{$name};

    return \$result;
}

/**
 * Attribute {$name} accessor.
 *
 * @param mixed \$value
 * @return mixed
 */
public function get{$phpname}Attribute(\$value)
{
    return \$this->get{$phpname}();
}

";
        }

        return $mutators .
            '/**
 * Get an attribute from the model.
 *
 * @param  string  $key
 * @return mixed
 */
public function getAttribute($key)
{
    $method = \'get\' . str_replace(\' \', \'\', ucwords(str_replace(\'_\', \' \', $key)));
    try {
        $accessor = $this->__accessor;
        $this->__accessor = true;
        $value = call_user_func([$this, $method]);
        $this->__accessor = $accessor;
        return $value;
    } catch (\BadMethodCallException $e) {
        return $this->getRelationValue($key);
    }
}

/**
 * Set a given attribute on the model.
 *
 * @param  string  $key
 * @param  mixed  $value
 * @return $this
 */
public function setAttribute($key, $value)
{
    $method = \'set\' . str_replace(\' \', \'\', ucwords(str_replace(\'_\', \' \', $key)));
    try {
        return call_user_func([$this, $method], $value);
    } catch (\BadMethodCallException $e) {
        return null;
    }
}

/**
 * Dynamically retrieve attributes on the model.
 *
 * @param  string  $key
 * @return mixed
 */
public function __get($key)
{
    return $this->getAttribute($key);
}

/**
 * Dynamically set attributes on the model.
 *
 * @param  string  $key
 * @param  mixed  $value
 * @return void
 */
public function __set($key, $value)
{
    return $this->setAttribute($key, $value);
}

/**
 * Sync propel and eloquent attributes.
 */
protected function syncAttributes()
{
' . implode("\n", array_map(function ($col) {
                return "    \$this->attributes['{$col->getName()}'] = \$this->{$col->getName()};";
            }, $this->getTable()->getColumns())) . '
}

/**
 * Set the array of model attributes. No checking is done.
 *
 * @param  array  $attributes
 * @param  bool  $sync
 * @return $this
 */
public function setRawAttributes(array $attributes, $sync = false)
{
    if (!isset($attributes[0])) {
        foreach ($attributes as $key => $value) {
            $this->setAttribute($key, $value);
        }
    } else {
        $this->hydrateThis($attributes, 0, false, TableMap::TYPE_FIELDNAME);
    }

    if ($sync) {
        $this->syncOriginal();
    }

    return $this;
}

/**
 * Hydrates (populates) the object variables with values from the database resultset.
 *
 * @see hydrateThis()
 */
public function hydrateThis($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM)
{
    $result = $this->propelHydrate($row, $startcol, $rehydrate, $indexType);

    $this->syncAttributes();

    return $result;
}

/**
 * Create a collection of models from plain arrays.
 *
 * @param  array  $items
 * @param  string|null  $connection
 * @return \Illuminate\Database\Eloquent\Collection
 */
public static function hydrateTemp(array $items, $connection = null)
{
    $stdToArray = function ($obj) use (&$stdToArray) {
        $reaged = (array)$obj;
        foreach ($reaged as $key => &$field) {
            if (is_object($field)) {
                $field = $stdToArray($field);
            }
        }
        return $reaged;
    };

    $model = new static;

    foreach ($items as &$item) {
        $attributes = $stdToArray($item);
        $item = clone $model;
        $item->setRawAttributes($attributes, true);
        $item->setNew(false);
    }

    return $model->newCollection($items);
}

/**
 * Save the model to the database.
 *
 * @param  array  $options
 * @return bool
 */
public function saveTemp(array $options = [])
{
    if ($this->fireModelEvent(\'saving\') === false) {
        return false;
    }

    $con = null;

    if (is_array($options) && count($options)) {
        if ($options[0] instanceOf ConnectionInterface) {
            $con = $options[0];
            unset($options[0]);
        }
    } elseif (isset($options[0]) &&  $options[0] instanceOf ConnectionInterface) {
        $con = $options;
    }

    if ($con === null) {
        $con = Propel::getServiceContainer()->getWriteConnection(' . $this->getTableClassName() . 'TableMap::DATABASE_NAME);
    }

    $affectedRows = $this->saveThis($con);

    $this->finishSave($options);

    return $affectedRows;
}

/**
 * Delete the model from the database.
 *
 * @return bool|null
 * @throws \Exception
 */
public function deleteTemp()
{
    $options = func_get_args();

    $con = null;

    if (is_array($options) && count($options)) {
        if ($options[0] instanceOf ConnectionInterface) {
            $con = $options[0];
            unset($options[0]);
        }
    } elseif (isset($options[0]) &&  $options[0] instanceOf ConnectionInterface) {
        $con = $options;
    }

    if ($con === null) {
        $con = Propel::getServiceContainer()->getWriteConnection(' . $this->getTableClassName() . 'TableMap::DATABASE_NAME);
    }

    if (!$this->isNew()) {
        if ($this->fireModelEvent(\'deleting\') === false) {
            return false;
        }

        // Here, we\'ll touch the owning models, verifying these timestamps get updated
        // for the models. This will allow any caching to get broken on the parents
        // by the timestamp. Then we will go ahead and delete the model instance.
        $this->touchOwners();

        $this->deleteThis($con);

        $this->exists = false;

        // Once the model has been deleted, we will fire off the deleted event so that
        // the developers may hook into post-delete operations. We will then return
        // a boolean true as the delete is presumably successful on the database.
        $this->fireModelEvent(\'deleted\', false);

        return true;
    } else {
       return false;
    }
}
';
    }

    public function getTableNameSpace()
    {
        return $this->getTable()->getNamespace();
    }

    public function getTableClassName()
    {
        return $this->getTable()->getPhpName();
    }

    public function getTableFullClassName()
    {
        return $this->getTableNameSpace() . '\\' . $this->getTableClassName();
    }

    protected function fixPackageName(&$script)
    {
        $matches = null;
        $pattern = "/@package +propel.*(\.[A-Za-z_0-9]+)( +)?/";
        $package = str_replace('\\', '.', $this->getTableNameSpace());
        preg_match($pattern, $script, $matches);
        if (isset($matches[1])) {
            $replacement = "@package {$package}{$matches[1]}";
            $script = preg_replace($pattern, $replacement, $script);
        }
    }

    protected function changeClassDeclaration(&$script)
    {
        $matches = null;
        $pattern = '/(\n+\/\*\*.*abstract +class +[A-Za-z_0-9]+ +)(extends +([A-Za-z_0-9]+) +)?(implements +[A-Za-z_0-9]+)(( |\n)+)?{/sm';
        preg_match($pattern, $script, $matches);
        if ($matches[2] == '') {
            $replacement = "use \Illuminate\Database\Eloquent\Model as EloquentModel;\n{$matches[1]}extends EloquentModel {$matches[4]}{$matches[5]}{";
            $script = preg_replace($pattern, $replacement, $script);
        } else {
            $replacement = "use \Illuminate\Database\Eloquent\Model as EloquentModel;\n{$matches[1]}extends EloquentModel {$matches[4]}{$matches[5]}{\n    use {$matches[3]};\n";
            $script = preg_replace($pattern, $replacement, $script);
        }
    }

    protected function changeConstructor(&$script)
    {
        $matches = null;
        $pattern = '/( +\/\*\*\n +\* Initializes.*public +function +__construct\()(\)( +)?(\n+)?( +)?{( +)?(\n+)?)( +)?(\$this->applyDefaultValues\(\);( +)?(\n+))(( +)})/sm';
        preg_match($pattern, $script, $matches);
        if (count($matches)) {
            $replacement = "{$matches[1]}array \$attributes = []{$matches[2]}{$matches[8]}parent::__construct(\$attributes);\n{$matches[8]}{$matches[9]}{$matches[12]}";
            $script = preg_replace($pattern, $replacement, $script);
        } else {
            $pattern = '/( +\/\*\*\n +\* Initializes.*public +function +__construct\()(\)( +)?(\n+)?( +)?{)([ \n]+)?(\n( +)})/sm';
            preg_match($pattern, $script, $matches);
            $replacement = "{$matches[1]}array \$attributes = []{$matches[2]}\n{$matches[8]}    parent::__construct(\$attributes);{$matches[7]}";
            $script = preg_replace($pattern, $replacement, $script);
        }
    }

    protected function renameSetMethods(&$script)
    {
        $matches = null;

        foreach ($this->getTable()->getColumns() as $col) {
            $phpname = $col->getPhpName();
            $pattern = "/function set{$phpname}\(/";
            $replacement = "function set{$phpname}Attribute(";
            $script = preg_replace($pattern, $replacement, $script);
        }

        $pattern = "/function +(set[a-zA-Z0-9_]+)Temp\(/";
        preg_match($pattern, $script, $matches);
        if (isset($matches[1])) {
            $replacement = 'function ${1}(';
            $script = preg_replace($pattern, $replacement, $script);
        }
    }

    protected function renameHydrateMethod(&$script)
    {
        $pattern = "/public +function +hydrate\(/";
        $replacement = "protected function propelHydrate(";
        $script = preg_replace($pattern, $replacement, $script);

        $pattern = '/\$this->hydrate\(/';
        $replacement = '$this->hydrateThis(';
        $script = preg_replace($pattern, $replacement, $script);

        $pattern = '/\$obj->hydrate\(/';
        $replacement = '$obj->hydrateThis(';
        $script = preg_replace($pattern, $replacement, $script);

        $pattern = "/ hydrateTemp\(/";
        $replacement = " hydrate(";
        $script = preg_replace($pattern, $replacement, $script);
    }

    public function renameSaveMethods(&$script)
    {
        $pattern = '/function +save\(/';
        $replacement = 'function saveThis(';
        $script = preg_replace($pattern, $replacement, $script);

        $pattern = '/(\$[A-Za-z_0-9]+)->save\(\$con\)/';
        preg_match($pattern, $script, $matches);
        if (isset($matches[1]) && $matches[1] !== '$this') {
            $replacement = '${1}->save(${1} instanceof EloquentModel ? [$con] : $con)';
            $script = preg_replace($pattern, $replacement, $script);
        }

        $pattern = '/(\$this->([A-Za-z_0-9]+))->save\(\$con\)/';
        preg_match($pattern, $script, $matches);
        if (isset($matches[2])) {
            $replacement = '$this->${2}->save($this->${2} instanceof EloquentModel ? [$con] : $con)';
            $script = preg_replace($pattern, $replacement, $script);
        }

        $pattern = '/\$this->save\((.*)\)/';
        preg_match($pattern, $script, $matches);
        $con = isset($matches[1]) ? $matches[1] : '';
        $replacement = "\$this->save([{$con}])";
        $script = preg_replace($pattern, $replacement, $script);

        $pattern = '/ saveTemp\(/';
        $replacement = ' save(';
        $script = preg_replace($pattern, $replacement, $script);

        $pattern = '/\$this->saveTemp\(/';
        $replacement = '$this->save(';
        $script = preg_replace($pattern, $replacement, $script);
    }

    public function renameDeleteMethods(&$script)
    {
        $pattern = '/public +function +delete\(/';
        $replacement = 'protected function deleteThis(';
        $script = preg_replace($pattern, $replacement, $script);

        $pattern = '/(\$[A-Za-z_0-9]+)->delete\(\$con\)/';
        preg_match($pattern, $script, $matches);
        if (isset($matches[1]) && $matches[1] !== '$this') {
            $replacement = '${1}->delete(${1} instanceof EloquentModel ? [$con] : $con)';
            $script = preg_replace($pattern, $replacement, $script);
        }

        $pattern = '/(\$this->([A-Za-z_0-9]+))->delete\(\$con\)/';
        preg_match($pattern, $script, $matches);
        if (isset($matches[2])) {
            $replacement = '$this->${2}->delete($this->${2} instanceof EloquentModel ? [$con] : $con)';
            $script = preg_replace($pattern, $replacement, $script);
        }

        $pattern = '/\$this->delete\((.*)\)/';
        preg_match($pattern, $script, $matches);
        $con = isset($matches[1]) ? $matches[1] : '';
        $replacement = "\$this->delete([{$con}])";
        $script = preg_replace($pattern, $replacement, $script);

        $pattern = '/ deleteTemp\(/';
        $replacement = ' delete(';
        $script = preg_replace($pattern, $replacement, $script);

        $pattern = '/\$this->deleteTemp\(/';
        $replacement = '$this->delete(';
        $script = preg_replace($pattern, $replacement, $script);
    }

    protected function changePrePostMethods(&$script)
    {
        $pattern = "/if +\(is_callable\('parent::(pre|post)[a-zA-Z0-9_]+'\)\) +{/";
        $replacement = 'if (($p = get_parent_class(self::class)) && (new \ReflectionClass($p))->hasMethod(__FUNCTION__)) {';
        $script = preg_replace($pattern, $replacement, $script);
    }

    protected function changeMagicCallMethod(&$script)
    {
        $pattern = '/throw new BadMethodCallException\(sprintf\(\'Call to undefined method: %s.\', \$name\)\);/';
        $replacement = 'return parent::__call($name, $params);';
        $script = preg_replace($pattern, $replacement, $script);
    }

    public function setTableMapTypeFieldNameAsDefault(&$script)
    {
        $pattern = '/toArray\(TableMap::TYPE_PHPNAME/';
        $replacement = 'toArray(TableMap::TYPE_FIELDNAME';
        $script = preg_replace($pattern, $replacement, $script);

        $pattern = '/\ype += +TableMap::TYPE_PHPNAME/';
        $replacement = 'ype = TableMap::TYPE_FIELDNAME';
        $script = preg_replace($pattern, $replacement, $script);
    }

    public function replaceDateTimeAccessors(&$script)
    {
        $pattern = '/return \$this->([A-Za-z_0-9]+) instanceof \\\DateTimeInterface \? \$this->([A-Za-z_0-9]+)->format\(\$format\) : null;/';
        preg_match($pattern, $script, $matches);
        if (isset($matches[2])) {
            $replacement = <<<EOD
            \$res = null;
            \$time = \$this->\${2} ? \$this->\${2}->getTimestamp() : false;
            if (\$time) {
                \$format = preg_replace('/(\w)/','\\\\\\\\\\\\\\\${1}', \$format);
                \$format = preg_replace('/\\\\\\\\\\\\\\\\\\\\\\\\\(\w)/', '\\\${1}', \$format);
                \$format = strtr(\$format, [
                    '\d' => '%d',
                    '\D' => '%a',
                    '\j' => '%e',
                    '\l' => '%A',
                    '\N' => '%u',
                    '\S' => '%%S',
                    '\w' => '%w',
                    '\z' => '%%%%z',
                    '\W' => '%V',
                    '\F' => '%B',
                    '\m' => '%m',
                    '\M' => '%b',
                    '\\n' => '%%%%n',
                    '\\t' => '%%%%t',
                    '\L' => '%%%%L',
                    '\o' => '%C%y',
                    '\Y' => '%Y',
                    '\y' => '%y',
                    '\a' => '%p',
                    '\A' => '%p',
                    '\B' => '%%%%B',
                    '\g' => '%%%%g',
                    '\G' => '%%%%G',
                    '\h' => '%I',
                    '\H' => '%H',
                    '\i' => '%M',
                    '\s' => '%S',
                    '\u' => '%%%%u',
                    '\e' => '%Z',
                    '\I' => '%%%%I',
                    '\O' => '%%%%O',
                    '\P' => '%%%%P',
                    '\T' => '%z',
                    '\Z' => '%%%%Z',
                    '\c' => '%%%%c',
                    '\r' => '%%%%r',
                    '\U' => '%%%%U',
                ]);
                \$res = strftime(\$format, \$time);
                \$res = strtr(\$res, [
                    '%%%%S' => date('S', \$time),
                    '%%%%z' => date('z', \$time),
                    '%%%%n' => date('n', \$time),
                    '%%%%t' => date('t', \$time),
                    '%%%%L' => date('L', \$time),
                    '%%%%B' => date('B', \$time),
                    '%%%%g' => date('g', \$time),
                    '%%%%G' => date('G', \$time),
                    '%%%%u' => date('u', \$time),
                    '%%%%I' => date('I', \$time),
                    '%%%%O' => date('O', \$time),
                    '%%%%P' => date('P', \$time),
                    '%%%%Z' => date('Z', \$time),
                    '%%%%c' => date('c', \$time),
                    '%%%%r' => date('r', \$time),
                    '%%%%U' => date('U', \$time),
                ]);
            }
            return \$res;
EOD;
            $script = preg_replace($pattern, $replacement, $script);
        }
    }

    public function tableMapFilter(&$script)
    {
        $this->fixPackageName($script);
        $this->renameSaveMethods($script);
        $this->renameHydrateMethod($script);
    }

    public function queryFilter(&$script)
    {
        $this->fixPackageName($script);
        $this->renameSaveMethods($script);
        $this->renameHydrateMethod($script);
    }

    public function objectFilter(&$script)
    {
        $this->fixPackageName($script);
        $this->changeClassDeclaration($script);
        $this->changeConstructor($script);
        $this->renameSetMethods($script);
        $this->renameSaveMethods($script);
        $this->renameDeleteMethods($script);
        $this->renameHydrateMethod($script);
        $this->changePrePostMethods($script);
        $this->changeMagicCallMethod($script);
        $this->setTableMapTypeFieldNameAsDefault($script);
        $this->replaceDateTimeAccessors($script);
    }
}


text:
main = print getProblem17Value

-- Sets of numbers:
-- 1-19: fixed number of digits for each number (19)
-- [2-9]0: tens place from 2-9 (8)
-- [2-9][1-9]: tens place from 2-9 plus ones place from 1-9 (8*9=72)
-- [1-9]00: hundreds place from 1-9 plus 'hundred' (9)
-- [1-9][01-19]: hundreds place from 1-9 plus 'hundred and' plus 1-19 (9*19=171)
-- [1-9][2-9]0: hundreds place from 1-9 plus 'hundred and' plus tens place from 2-9 (9*8=72)
-- [1-9][2-9][1-9]: hundreds place from 1-9 plus 'hundred and' plus tens place from 2-9 plus ones place from 1-9 (9*8*9=648)
-- 1000: 'one thousand' = 11 digits (1)
getProblem17Value :: Integer
getProblem17Value = oneToNineteen + tens + tens_oneToNine + hundreds + hundreds_oneToNineteen + hundreds_tens + hundreds_tens_oneToNine + oneThousand
    where hundred = 7
          hundredAnd = 10
          oneThousand = 11
          oneToNine = sum $ map getNumDigits [1..9]
          oneToNineteen = sum $ map getNumDigits [1..19]
          tens = sum $ map getNumDigits [20,30..90]
          tens_oneToNine = 8 * oneToNine + 9 * tens
          hundreds = oneToNine + 9 * hundred
          hundreds_oneToNineteen = 19 * oneToNine + 9 * 19 * hundredAnd + 9 * oneToNineteen
          hundreds_tens = 8 * oneToNine + 9 * 8 * hundredAnd + 9 * tens
          hundreds_tens_oneToNine = 8 * 9 * oneToNine + 9 * 8 * 9 * hundredAnd + 9 * 9 * tens + 9 * 8 * oneToNine

getNumDigits :: Integer -> Integer
getNumDigits 1 = 3  -- one
getNumDigits 2 = 3  -- two
getNumDigits 3 = 5  -- three
getNumDigits 4 = 4  -- four
getNumDigits 5 = 4  -- five
getNumDigits 6 = 3  -- six
getNumDigits 7 = 5  -- seven
getNumDigits 8 = 5  -- eight
getNumDigits 9 = 4  -- nine
getNumDigits 10 = 3 -- ten
getNumDigits 11 = 6 -- eleven
getNumDigits 12 = 6 -- twelve
getNumDigits 13 = 8 -- thirteen
getNumDigits 14 = 8 -- fourteen
getNumDigits 15 = 7 -- fifteen
getNumDigits 16 = 7 -- sixteen
getNumDigits 17 = 9 -- seventeen
getNumDigits 18 = 8 -- eighteen
getNumDigits 19 = 8 -- nineteen
getNumDigits 20 = 6 -- twenty
getNumDigits 30 = 6 -- thirty
getNumDigits 40 = 5 -- forty
getNumDigits 50 = 5 -- fifty
getNumDigits 60 = 5 -- sixty
getNumDigits 70 = 7 -- seventy
getNumDigits 80 = 6 -- eighty
getNumDigits 90 = 6 -- ninety


text:
/* */
'use strict';
var geocoder = require("./geocoder"),
    util = require("./util");
var GeocoderControl = L.Control.extend({
  includes: L.Mixin.Events,
  options: {
    position: 'topleft',
    pointZoom: 16,
    keepOpen: false,
    autocomplete: false
  },
  initialize: function(_, options) {
    L.Util.setOptions(this, options);
    this.setURL(_);
    this._updateSubmit = L.bind(this._updateSubmit, this);
    this._updateAutocomplete = L.bind(this._updateAutocomplete, this);
    this._chooseResult = L.bind(this._chooseResult, this);
  },
  setURL: function(_) {
    this.geocoder = geocoder(_, {accessToken: this.options.accessToken});
    return this;
  },
  getURL: function() {
    return this.geocoder.getURL();
  },
  setID: function(_) {
    return this.setURL(_);
  },
  setTileJSON: function(_) {
    return this.setURL(_.geocoder);
  },
  _toggle: function(e) {
    if (e)
      L.DomEvent.stop(e);
    if (L.DomUtil.hasClass(this._container, 'active')) {
      L.DomUtil.removeClass(this._container, 'active');
      this._results.innerHTML = '';
      this._input.blur();
    } else {
      L.DomUtil.addClass(this._container, 'active');
      this._input.focus();
      this._input.select();
    }
  },
  _closeIfOpen: function(e) {
    if (L.DomUtil.hasClass(this._container, 'active') && !this.options.keepOpen) {
      L.DomUtil.removeClass(this._container, 'active');
      this._results.innerHTML = '';
      this._input.blur();
    }
  },
  onAdd: function(map) {
    var container = L.DomUtil.create('div', 'leaflet-control-mapbox-geocoder leaflet-bar leaflet-control'),
        link = L.DomUtil.create('a', 'leaflet-control-mapbox-geocoder-toggle mapbox-icon mapbox-icon-geocoder', container),
        results = L.DomUtil.create('div', 'leaflet-control-mapbox-geocoder-results', container),
        wrap = L.DomUtil.create('div', 'leaflet-control-mapbox-geocoder-wrap', container),
        form = L.DomUtil.create('form', 'leaflet-control-mapbox-geocoder-form', wrap),
        input = L.DomUtil.create('input', '', form);
    link.href = '#';
    link.innerHTML = ' ';
    input.type = 'text';
    input.setAttribute('placeholder', 'Search');
    L.DomEvent.addListener(form, 'submit', this._geocode, this);
    L.DomEvent.addListener(input, 'keyup', this._autocomplete, this);
    L.DomEvent.disableClickPropagation(container);
    this._map = map;
    this._results = results;
    this._input = input;
    this._form = form;
    if (this.options.keepOpen) {
      L.DomUtil.addClass(container, 'active');
    } else {
      this._map.on('click', this._closeIfOpen, this);
      L.DomEvent.addListener(link, 'click', this._toggle, this);
    }
    return container;
  },
  _updateSubmit: function(err, resp) {
    L.DomUtil.removeClass(this._container, 'searching');
    this._results.innerHTML = '';
    if (err || !resp) {
      this.fire('error', {error: err});
    } else {
      var features = [];
      if (resp.results && resp.results.features) {
        features = resp.results.features;
      }
      if (features.length === 1) {
        this.fire('autoselect', {feature: features[0]});
        this.fire('found', {results: resp.results});
        this._chooseResult(features[0]);
        this._closeIfOpen();
      } else if (features.length > 1) {
        this.fire('found', {results: resp.results});
        this._displayResults(features);
      } else {
        this._displayResults(features);
      }
    }
  },
  _updateAutocomplete: function(err, resp) {
    this._results.innerHTML = '';
    if (err || !resp) {
      this.fire('error', {error: err});
    } else {
      var features = [];
      if (resp.results && resp.results.features) {
        features = resp.results.features;
      }
      if (features.length) {
        this.fire('found', {results: resp.results});
      }
      this._displayResults(features);
    }
  },
  _displayResults: function(features) {
    for (var i = 0,
        l = Math.min(features.length, 5); i < l; i++) {
      var feature = features[i];
      var name = feature.place_name;
      if (!name.length)
        continue;
      var r = L.DomUtil.create('a', '', this._results);
      var text = ('innerText' in r) ? 'innerText' : 'textContent';
      r[text] = name;
      r.href = '#';
      (L.bind(function(feature) {
        L.DomEvent.addListener(r, 'click', function(e) {
          this._chooseResult(feature);
          L.DomEvent.stop(e);
          this.fire('select', {feature: feature});
        }, this);
      }, this))(feature);
    }
    if (features.length > 5) {
      var outof = L.DomUtil.create('span', '', this._results);
      outof.innerHTML = 'Top 5 of ' + features.length + '  results';
    }
  },
  _chooseResult: function(result) {
    if (result.bbox) {
      this._map.fitBounds(util.lbounds(result.bbox));
    } else if (result.center) {
      this._map.setView([result.center[1], result.center[0]], (this._map.getZoom() === undefined) ? this.options.pointZoom : Math.max(this._map.getZoom(), this.options.pointZoom));
    }
  },
  _geocode: function(e) {
    L.DomEvent.preventDefault(e);
    if (this._input.value === '')
      return this._updateSubmit();
    L.DomUtil.addClass(this._container, 'searching');
    this.geocoder.query(this._input.value, this._updateSubmit);
  },
  _autocomplete: function(e) {
    if (!this.options.autocomplete)
      return ;
    if (this._input.value === '')
      return this._updateAutocomplete();
    this.geocoder.query(this._input.value, this._updateAutocomplete);
  }
});
module.exports.GeocoderControl = GeocoderControl;
module.exports.geocoderControl = function(_, options) {
  return new GeocoderControl(_, options);
};


text:
<?php
$attributes = array('id' => 'certificate-verification');
echo form_open('/mariner_certificates/verify', $attributes);?>

	<?php echo form_label('Search Key'); ?>
	<?php
		$data = array(
              'name'        => 'search_key',
              'id'          => 'search_key',
//              'value'       =>  get_propery_from_object($certRecord, 'certificate_id'),
              'class'  		=> 'textfield'
            );
	?>

<?php echo form_input($data);?>

	<?php
		$data = array(
              'name'        => 'verify',
              'id'          => 'verify-button',
              'value'       => '',
              'class'  		=> 'form-button required'
            );
		?>

<?php echo form_submit($data); ?>

<?php echo form_close(); ?>


text:
namespace PopForums.Models
{
	public class ForumTopicContainer : PagedTopicContainer
	{
		public Forum Forum { get; set; }
		public ForumPermissionContext PermissionContext { get; set; }
	}
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Tinian Island, N. Mariana Is, West Tinian Airport, MP</location>
	<station_id>PGWT</station_id>
	<latitude>14.98333</latitude>
	<longitude>145.61667</longitude>
	<observation_time>Last Updated on Jan 5 2016, 11:54 am LST</observation_time>
        <observation_time_rfc822>Tue, 05 Jan 2016 11:54:00 +1000</observation_time_rfc822>
	<weather>Partly Cloudy</weather>
	<temperature_string>82.0 F (28.0 C)</temperature_string>
	<temp_f>82.0</temp_f>
	<temp_c>28.0</temp_c>
	<relative_humidity>70</relative_humidity>
	<wind_string>Northeast at 17.3 MPH (15 KT)</wind_string>
	<wind_dir>Northeast</wind_dir>
	<wind_degrees>60</wind_degrees>
	<wind_mph>17.3</wind_mph>
	<wind_kt>15</wind_kt>
	<pressure_in>30.01</pressure_in>
	<dewpoint_string>71.6 F (22.0 C)</dewpoint_string>
	<dewpoint_f>71.6</dewpoint_f>
	<dewpoint_c>22.0</dewpoint_c>
	<heat_index_string>86 F (30 C)</heat_index_string>
      	<heat_index_f>86</heat_index_f>
      	<heat_index_c>30</heat_index_c>
	<visibility_mi>7.00</visibility_mi>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/PGWT.html</two_day_history_url>
	<icon_url_name>sct.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/PGWT.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>