text:
import {
  EventComponent,
  HostComponent,
  FunctionComponent,
} from 'shared/ReactWorkTags';
import type {Fiber} from 'react-reconciler/src/ReactFiber';
import {
  batchedEventUpdates,
  discreteUpdates,
  flushDiscreteUpdatesIfNeeded,
} from 'events/ReactGenericBatching';
import type {
  ReactEventResponder,
  ReactEventComponentInstance,
} from 'shared/ReactTypes';
import type {
  ReactNativeResponderContext,
  ReactNativeResponderEvent,
  EventPriority,
  ReactNativeEventTarget,
  ReactFaricEvent,
} from './ReactNativeTypes';
import {
  ContinuousEvent,
  UserBlockingEvent,
  DiscreteEvent,
} from './ReactNativeTypes';
import {invokeGuardedCallbackAndCatchFirstError} from 'shared/ReactErrorUtils';
import {enableUserBlockingEvents} from 'shared/ReactFeatureFlags';
import warning from 'shared/warning';
import invariant from 'shared/invariant';

// Intentionally not named imports because Rollup would use dynamic dispatch for
// CommonJS interop named imports.
import * as Scheduler from 'scheduler';
const {
  unstable_UserBlockingPriority: UserBlockingPriority,
  unstable_runWithPriority: runWithPriority,
} = Scheduler;

type EventObjectType = $Shape<PartialEventObject>;

type PartialEventObject = {
  target: ReactNativeEventTarget,
  type: string,
};

type ResponderTimeout = {|
  id: TimeoutID,
  timers: Map<number, ResponderTimer>,
|};

type ResponderTimer = {|
  isHook: boolean,
  instance: ReactNativeEventComponentInstance,
  func: () => void,
  id: number,
  timeStamp: number,
|};

type EventQueue = {
  events: Array<EventObjectType>,
  eventPriority: EventPriority,
};

type ReactNativeEventResponder = ReactEventResponder<
  ReactNativeResponderEvent,
  ReactNativeResponderContext,
>;

type ReactNativeEventComponentInstance = ReactEventComponentInstance<
  ReactNativeResponderEvent,
  ReactNativeResponderContext,
>;

const {measureInWindow} = nativeFabricUIManager;

const activeTimeouts: Map<number, ResponderTimeout> = new Map();
const rootEventTypesToEventComponentInstances: Map<
  string,
  Set<ReactNativeEventComponentInstance>,
> = new Map();
const ownershipChangeListeners: Set<
  ReactNativeEventComponentInstance,
> = new Set();
const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
const eventListeners:
  | WeakMap
  | Map<
      $Shape<PartialEventObject>,
      ($Shape<PartialEventObject>) => void,
    > = new PossiblyWeakMap();

let globalOwner = null;
let continueLocalPropagation = false;

let currentTimeStamp = 0;
let currentTimers = new Map();
let currentInstance: null | ReactNativeEventComponentInstance = null;
let currentEventQueue: null | EventQueue = null;
let currentTimerIDCounter = 0;
let currentlyInHook = false;

const eventResponderContext: ReactNativeResponderContext = {
  dispatchEvent(
    possibleEventObject: Object,
    listener: ($Shape<PartialEventObject>) => void,
    eventPriority: EventPriority,
  ): void {
    validateResponderContext();
    const {target, type, timeStamp} = possibleEventObject;

    if (target == null || type == null || timeStamp == null) {
      throw new Error(
        'context.dispatchEvent: "target", "timeStamp", and "type" fields on event object are required.',
      );
    }
    const showWarning = name => {
      if (__DEV__) {
        warning(
          false,
          '%s is not available on event objects created from event responder modules (React Flare). ' +
            'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.%s }`',
          name,
          name,
        );
      }
    };
    possibleEventObject.preventDefault = () => {
      if (__DEV__) {
        showWarning('preventDefault()');
      }
    };
    possibleEventObject.stopPropagation = () => {
      if (__DEV__) {
        showWarning('stopPropagation()');
      }
    };
    possibleEventObject.isDefaultPrevented = () => {
      if (__DEV__) {
        showWarning('isDefaultPrevented()');
      }
    };
    possibleEventObject.isPropagationStopped = () => {
      if (__DEV__) {
        showWarning('isPropagationStopped()');
      }
    };
    // $FlowFixMe: we don't need value, Flow thinks we do
    Object.defineProperty(possibleEventObject, 'nativeEvent', {
      get() {
        if (__DEV__) {
          showWarning('nativeEvent');
        }
      },
    });

    const eventObject = ((possibleEventObject: any): $Shape<
      PartialEventObject,
    >);
    const eventQueue = ((currentEventQueue: any): EventQueue);
    eventQueue.eventPriority = eventPriority;
    eventListeners.set(eventObject, listener);
    eventQueue.events.push(eventObject);
  },
  isTargetWithinNode(
    childTarget: ReactNativeEventTarget,
    parentTarget: ReactNativeEventTarget,
  ) {
    validateResponderContext();
    const childFiber = getFiberFromTarget(childTarget);
    const parentFiber = getFiberFromTarget(parentTarget);

    let node = childFiber;
    while (node !== null) {
      if (node === parentFiber) {
        return true;
      }
      node = node.return;
    }
    return false;
  },
  getTargetBoundingRect(
    target: ReactNativeEventTarget,
    callback: ({
      left: number,
      right: number,
      top: number,
      bottom: number,
    }) => void,
  ) {
    measureInWindow(target.node, (x, y, width, height) => {
      callback({
        left: x,
        right: x + width,
        top: y,
        bottom: y + height,
      });
    });
  },
  addRootEventTypes(rootEventTypes: Array<string>): void {
    validateResponderContext();
    for (let i = 0; i < rootEventTypes.length; i++) {
      const rootEventType = rootEventTypes[i];
      const eventComponentInstance = ((currentInstance: any): ReactNativeEventComponentInstance);
      registerRootEventType(rootEventType, eventComponentInstance);
    }
  },
  removeRootEventTypes(rootEventTypes: Array<string>): void {
    validateResponderContext();
    for (let i = 0; i < rootEventTypes.length; i++) {
      const rootEventType = rootEventTypes[i];

      let rootEventComponents = rootEventTypesToEventComponentInstances.get(
        rootEventType,
      );
      let rootEventTypesSet = ((currentInstance: any): ReactNativeEventComponentInstance)
        .rootEventTypes;
      if (rootEventTypesSet !== null) {
        rootEventTypesSet.delete(rootEventType);
      }
      if (rootEventComponents !== undefined) {
        rootEventComponents.delete(
          ((currentInstance: any): ReactNativeEventComponentInstance),
        );
      }
    }
  },
  setTimeout(func: () => void, delay): number {
    validateResponderContext();
    if (currentTimers === null) {
      currentTimers = new Map();
    }
    let timeout = currentTimers.get(delay);

    const timerId = currentTimerIDCounter++;
    if (timeout === undefined) {
      const timers = new Map();
      const id = setTimeout(() => {
        processTimers(timers, delay);
      }, delay);
      timeout = {
        id,
        timers,
      };
      currentTimers.set(delay, timeout);
    }
    timeout.timers.set(timerId, {
      isHook: currentlyInHook,
      instance: ((currentInstance: any): ReactNativeEventComponentInstance),
      func,
      id: timerId,
      timeStamp: currentTimeStamp,
    });
    activeTimeouts.set(timerId, timeout);
    return timerId;
  },
  clearTimeout(timerId: number): void {
    validateResponderContext();
    const timeout = activeTimeouts.get(timerId);

    if (timeout !== undefined) {
      const timers = timeout.timers;
      timers.delete(timerId);
      if (timers.size === 0) {
        clearTimeout(timeout.id);
      }
    }
  },
  getTimeStamp(): number {
    validateResponderContext();
    return currentTimeStamp;
  },
};

function getFiberFromTarget(
  target: null | ReactNativeEventTarget,
): Fiber | null {
  if (target === null) {
    return null;
  }
  return ((target.canonical._internalInstanceHandle: any): Fiber) || null;
}

function processTimers(
  timers: Map<number, ResponderTimer>,
  delay: number,
): void {
  const timersArr = Array.from(timers.values());
  currentEventQueue = createEventQueue();
  try {
    for (let i = 0; i < timersArr.length; i++) {
      const {isHook, instance, func, id, timeStamp} = timersArr[i];
      currentInstance = instance;
      currentTimeStamp = timeStamp + delay;
      currentlyInHook = isHook;
      try {
        func();
      } finally {
        activeTimeouts.delete(id);
      }
    }
    processEventQueue();
  } finally {
    currentTimers = null;
    currentInstance = null;
    currentEventQueue = null;
    currentTimeStamp = 0;
  }
}

function createFabricResponderEvent(
  topLevelType: string,
  nativeEvent: ReactFaricEvent,
  target: null | ReactNativeEventTarget,
): ReactNativeResponderEvent {
  return {
    currentTarget: target,
    nativeEvent,
    target,
    type: topLevelType,
  };
}

function validateResponderContext(): void {
  invariant(
    currentEventQueue && currentInstance,
    'An event responder context was used outside of an event cycle. ' +
      'Use context.setTimeout() to use asynchronous responder context outside of event cycle .',
  );
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
function createEventQueue(): EventQueue {
  return {
    events: [],
    eventPriority: ContinuousEvent,
  };
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
function processEventQueue(): void {
  const {events, eventPriority} = ((currentEventQueue: any): EventQueue);

  if (events.length === 0) {
    return;
  }

  switch (eventPriority) {
    case DiscreteEvent: {
      flushDiscreteUpdatesIfNeeded(currentTimeStamp);
      discreteUpdates(() => {
        batchedEventUpdates(processEvents, events);
      });
      break;
    }
    case UserBlockingEvent: {
      if (enableUserBlockingEvents) {
        runWithPriority(
          UserBlockingPriority,
          batchedEventUpdates.bind(null, processEvents, events),
        );
      } else {
        batchedEventUpdates(processEvents, events);
      }
      break;
    }
    case ContinuousEvent: {
      batchedEventUpdates(processEvents, events);
      break;
    }
  }
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
function triggerOwnershipListeners(): void {
  const listeningInstances = Array.from(ownershipChangeListeners);
  const previousInstance = currentInstance;
  const previouslyInHook = currentlyInHook;
  currentEventQueue = createEventQueue();
  try {
    for (let i = 0; i < listeningInstances.length; i++) {
      const instance = listeningInstances[i];
      const {isHook, props, responder, state} = instance;
      currentInstance = instance;
      currentlyInHook = isHook;
      const onOwnershipChange = ((responder: any): ReactNativeEventResponder)
        .onOwnershipChange;
      if (onOwnershipChange !== undefined) {
        onOwnershipChange(eventResponderContext, props, state);
      }
    }
    processEventQueue();
  } finally {
    currentInstance = previousInstance;
    currentlyInHook = previouslyInHook;
  }
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
function releaseOwnershipForEventComponentInstance(
  eventComponentInstance: ReactNativeEventComponentInstance,
): boolean {
  if (globalOwner === eventComponentInstance) {
    globalOwner = null;
    triggerOwnershipListeners();
    return true;
  }
  return false;
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
function processEvent(event: $Shape<PartialEventObject>): void {
  const type = event.type;
  const listener = ((eventListeners.get(event): any): (
    $Shape<PartialEventObject>,
  ) => void);
  invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
function processEvents(events: Array<EventObjectType>): void {
  for (let i = 0, length = events.length; i < length; i++) {
    processEvent(events[i]);
  }
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
function responderEventTypesContainType(
  eventTypes: Array<string>,
  type: string,
): boolean {
  for (let i = 0, len = eventTypes.length; i < len; i++) {
    if (eventTypes[i] === type) {
      return true;
    }
  }
  return false;
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
function shouldSkipEventComponent(
  eventResponderInstance: ReactNativeEventComponentInstance,
  responder: ReactNativeEventResponder,
  propagatedEventResponders: null | Set<ReactNativeEventResponder>,
  isHook: boolean,
): boolean {
  if (propagatedEventResponders !== null && !isHook) {
    if (propagatedEventResponders.has(responder)) {
      return true;
    }
    propagatedEventResponders.add(responder);
  }
  if (globalOwner && globalOwner !== eventResponderInstance) {
    return true;
  }
  return false;
}

function checkForLocalPropagationContinuation(
  responder: ReactNativeEventResponder,
  propagatedEventResponders: Set<ReactNativeEventResponder>,
): void {
  if (continueLocalPropagation === true) {
    propagatedEventResponders.delete(responder);
    continueLocalPropagation = false;
  }
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
function handleTargetEventResponderInstance(
  topLevelType: string,
  responderEvent: ReactNativeResponderEvent,
  eventComponentInstance: ReactNativeEventComponentInstance,
  hookComponentResponderValidation: null | Set<ReactNativeEventResponder>,
  propagatedEventResponders: null | Set<ReactNativeEventResponder>,
): void {
  const responder = eventComponentInstance.responder;
  const targetEventTypes = responder.targetEventTypes;
  // Validate the target event type exists on the responder
  if (targetEventTypes !== undefined) {
    if (responderEventTypesContainType(targetEventTypes, topLevelType)) {
      if (hookComponentResponderValidation !== null) {
        hookComponentResponderValidation.add(responder);
      }
      const {isHook, props, state} = eventComponentInstance;
      const eventListener = responder.onEvent;
      if (eventListener !== undefined) {
        if (
          shouldSkipEventComponent(
            eventComponentInstance,
            ((responder: any): ReactNativeEventResponder),
            propagatedEventResponders,
            isHook,
          )
        ) {
          return;
        }
        currentInstance = eventComponentInstance;
        currentlyInHook = isHook;
        eventListener(responderEvent, eventResponderContext, props, state);
        if (!isHook) {
          checkForLocalPropagationContinuation(
            responder,
            ((propagatedEventResponders: any): Set<ReactNativeEventResponder>),
          );
        }
      }
    }
  }
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
function traverseAndHandleEventResponderInstances(
  topLevelType: string,
  targetFiber: null | Fiber,
  nativeEvent: ReactFaricEvent,
): void {
  // Trigger event responders in this order:
  // - Bubble target phase
  // - Root phase

  const responderEvent = createFabricResponderEvent(
    topLevelType,
    nativeEvent,
    targetFiber !== null
      ? ((targetFiber.stateNode: any): ReactNativeEventTarget)
      : null,
  );
  const propagatedEventResponders: Set<ReactNativeEventResponder> = new Set();

  // We use this to know if we should check add hooks. If there are
  // no event targets, then we don't add the hook forms.
  const hookComponentResponderValidation = new Set();

  // Bubbled event phases have the notion of local propagation.
  // This means that the propgation chain can be stopped part of the the way
  // through processing event component instances.
  let node = targetFiber;
  while (node !== null) {
    const {dependencies, stateNode, tag} = node;
    if (tag === HostComponent) {
      responderEvent.currentTarget = stateNode;
    } else if (tag === EventComponent) {
      const eventComponentInstance = stateNode;
      // Switch to the current fiber tree
      node = eventComponentInstance.currentFiber;
      handleTargetEventResponderInstance(
        topLevelType,
        responderEvent,
        eventComponentInstance,
        hookComponentResponderValidation,
        propagatedEventResponders,
      );
    } else if (tag === FunctionComponent && dependencies !== null) {
      const events = dependencies.events;
      if (events !== null) {
        for (let i = 0; i < events.length; i++) {
          const eventComponentInstance = events[i];
          if (
            hookComponentResponderValidation.has(
              eventComponentInstance.responder,
            )
          ) {
            handleTargetEventResponderInstance(
              topLevelType,
              responderEvent,
              eventComponentInstance,
              null,
              null,
            );
          }
        }
      }
    }
    node = node.return;
  }
  // Reset currentTarget to be null
  responderEvent.currentTarget = null;
  // Root phase
  const rootEventInstances = rootEventTypesToEventComponentInstances.get(
    topLevelType,
  );
  if (rootEventInstances !== undefined) {
    const rootEventComponentInstances = Array.from(rootEventInstances);

    for (let i = 0; i < rootEventComponentInstances.length; i++) {
      const rootEventComponentInstance = rootEventComponentInstances[i];
      const {isHook, props, responder, state} = rootEventComponentInstance;
      const onRootEvent = responder.onRootEvent;
      if (onRootEvent !== undefined) {
        if (
          shouldSkipEventComponent(
            rootEventComponentInstance,
            responder,
            null,
            isHook,
          )
        ) {
          continue;
        }
        currentInstance = rootEventComponentInstance;
        currentlyInHook = isHook;
        onRootEvent(responderEvent, eventResponderContext, props, state);
      }
    }
  }
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
export function dispatchEventForResponderEventSystem(
  topLevelType: string,
  targetFiber: null | Fiber,
  nativeEvent: ReactFaricEvent,
): void {
  const previousEventQueue = currentEventQueue;
  const previousInstance = currentInstance;
  const previousTimers = currentTimers;
  const previousTimeStamp = currentTimeStamp;
  const previouslyInHook = currentlyInHook;
  currentTimers = null;
  currentEventQueue = createEventQueue();
  // We might want to control timeStamp another way here
  currentTimeStamp = Date.now();
  try {
    traverseAndHandleEventResponderInstances(
      topLevelType,
      targetFiber,
      nativeEvent,
    );
    processEventQueue();
  } finally {
    currentTimers = previousTimers;
    currentInstance = previousInstance;
    currentEventQueue = previousEventQueue;
    currentTimeStamp = previousTimeStamp;
    currentlyInHook = previouslyInHook;
  }
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
export function mountEventResponder(
  eventComponentInstance: ReactNativeEventComponentInstance,
) {
  const responder = ((eventComponentInstance.responder: any): ReactNativeEventResponder);
  if (responder.onOwnershipChange !== undefined) {
    ownershipChangeListeners.add(eventComponentInstance);
  }
  const onMount = responder.onMount;
  if (onMount !== undefined) {
    let {isHook, props, state} = eventComponentInstance;
    currentEventQueue = createEventQueue();
    currentInstance = eventComponentInstance;
    currentlyInHook = isHook;
    try {
      onMount(eventResponderContext, props, state);
      processEventQueue();
    } finally {
      currentEventQueue = null;
      currentInstance = null;
      currentTimers = null;
    }
  }
}

// TODO this function is almost an exact copy of the DOM version, we should
// somehow share the logic
export function unmountEventResponder(
  eventComponentInstance: ReactNativeEventComponentInstance,
): void {
  const responder = ((eventComponentInstance.responder: any): ReactNativeEventResponder);
  const onUnmount = responder.onUnmount;
  if (onUnmount !== undefined) {
    let {isHook, props, state} = eventComponentInstance;
    currentEventQueue = createEventQueue();
    currentInstance = eventComponentInstance;
    currentlyInHook = isHook;
    try {
      onUnmount(eventResponderContext, props, state);
      processEventQueue();
    } finally {
      currentEventQueue = null;
      currentInstance = null;
      currentTimers = null;
    }
  }
  try {
    currentEventQueue = createEventQueue();
    releaseOwnershipForEventComponentInstance(eventComponentInstance);
    processEventQueue();
  } finally {
    currentEventQueue = null;
  }
  if (responder.onOwnershipChange !== undefined) {
    ownershipChangeListeners.delete(eventComponentInstance);
  }
  const rootEventTypesSet = eventComponentInstance.rootEventTypes;
  if (rootEventTypesSet !== null) {
    const rootEventTypes = Array.from(rootEventTypesSet);

    for (let i = 0; i < rootEventTypes.length; i++) {
      const topLevelEventType = rootEventTypes[i];
      let rootEventComponentInstances = rootEventTypesToEventComponentInstances.get(
        topLevelEventType,
      );
      if (rootEventComponentInstances !== undefined) {
        rootEventComponentInstances.delete(eventComponentInstance);
      }
    }
  }
}

function registerRootEventType(
  rootEventType: string,
  eventComponentInstance: ReactNativeEventComponentInstance,
) {
  let rootEventComponentInstances = rootEventTypesToEventComponentInstances.get(
    rootEventType,
  );
  if (rootEventComponentInstances === undefined) {
    rootEventComponentInstances = new Set();
    rootEventTypesToEventComponentInstances.set(
      rootEventType,
      rootEventComponentInstances,
    );
  }
  let rootEventTypesSet = eventComponentInstance.rootEventTypes;
  if (rootEventTypesSet === null) {
    rootEventTypesSet = eventComponentInstance.rootEventTypes = new Set();
  }
  invariant(
    !rootEventTypesSet.has(rootEventType),
    'addRootEventTypes() found a duplicate root event ' +
      'type of "%s". This might be because the event type exists in the event responder "rootEventTypes" ' +
      'array or because of a previous addRootEventTypes() using this root event type.',
    rootEventType,
  );
  rootEventTypesSet.add(rootEventType);
  rootEventComponentInstances.add(eventComponentInstance);
}

export function addRootEventTypesForComponentInstance(
  eventComponentInstance: ReactNativeEventComponentInstance,
  rootEventTypes: Array<string>,
): void {
  for (let i = 0; i < rootEventTypes.length; i++) {
    const rootEventType = rootEventTypes[i];
    registerRootEventType(rootEventType, eventComponentInstance);
  }
}


text:
class Peptide {

private:

public:
	Peptide() {}

	Peptide(Protein* protein, int start, int end, std::map<int,PTM*> index2mod_for_pep) :
			protein(protein), start(start), end(end), index2mod_for_pep(index2mod_for_pep) {}

	Protein* protein;
	int start;
	int end;
	std::map<int,PTM*> index2mod_for_pep;
	double abundance=0;

	const char& operator[](std::size_t i);

	std::string get_sequence() const;
	std::string get_modified_sequence() const;
	int num_basic_residues() const;
	bool operator<(const Peptide& other) const;
	std::vector<unsigned int> get_composition() const;
	std::vector<unsigned int> get_composition(int charge) const;
	double calc_monoisotopic_mass();
	double monoisotopic_mass=0;

	static bool less_mz(const Peptide& a, const Peptide& b);
	bool operator==(const Peptide &other) const;

	static struct _CompareDoubleField
	{
		bool operator() (double left, const Peptide & right) {
			return left < right.monoisotopic_mass;
		}

	} CompareDoubleField;
};

#endif //MSACQUISITIONSIMULATOR_PEPTIDE_H

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using Mozu.Api.Security;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Threading;

namespace Mozu.Api.Clients.Commerce.Shipping.Admin.Carriers
{
	///
	///
	///
	public partial class CarrierCredentialSetClient 	{

		///
		///
		///
		/// <param name="filter"></param>
		/// <param name="pageSize"></param>
		/// <param name="responseFields"></param>
		/// <param name="sortBy"></param>
		/// <param name="startIndex"></param>
		/// <returns>
		///  <see cref="Mozu.Api.MozuClient" />{<see cref="Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSetCollection"/>}
		/// </returns>
		/// <example>
		///
		///   var mozuClient=GetCarrierCredentialSets( startIndex,  pageSize,  sortBy,  filter,  responseFields);
		///   var carrierCredentialSetCollectionClient = mozuClient.WithBaseAddress(url).Execute().Result();
		///
		/// </example>
		public static MozuClient<Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSetCollection> GetCarrierCredentialSetsClient(int? startIndex =  null, int? pageSize =  null, string sortBy =  null, string filter =  null, string responseFields =  null)
		{
			var url = Mozu.Api.Urls.Commerce.Shipping.Admin.Carriers.CarrierCredentialSetUrl.GetCarrierCredentialSetsUrl(startIndex, pageSize, sortBy, filter, responseFields);
			const string verb = "GET";
			var mozuClient = new MozuClient<Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSetCollection>()
									.WithVerb(verb).WithResourceUrl(url)
;
			return mozuClient;

		}

		///
		///
		///
		/// <param name="carrierId"></param>
		/// <param name="code"></param>
		/// <param name="responseFields"></param>
		/// <returns>
		///  <see cref="Mozu.Api.MozuClient" />{<see cref="Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet"/>}
		/// </returns>
		/// <example>
		///
		///   var mozuClient=GetCarrierCredentialSet( carrierId,  code,  responseFields);
		///   var carrierCredentialSetClient = mozuClient.WithBaseAddress(url).Execute().Result();
		///
		/// </example>
		public static MozuClient<Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet> GetCarrierCredentialSetClient(string carrierId, string code, string responseFields =  null)
		{
			var url = Mozu.Api.Urls.Commerce.Shipping.Admin.Carriers.CarrierCredentialSetUrl.GetCarrierCredentialSetUrl(carrierId, code, responseFields);
			const string verb = "GET";
			var mozuClient = new MozuClient<Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet>()
									.WithVerb(verb).WithResourceUrl(url)
;
			return mozuClient;

		}

		///
		///
		///
		/// <param name="carrierId"></param>
		/// <param name="responseFields"></param>
		/// <param name="carrierCredentialSet"></param>
		/// <returns>
		///  <see cref="Mozu.Api.MozuClient" />{<see cref="Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet"/>}
		/// </returns>
		/// <example>
		///
		///   var mozuClient=CreateCarrierCredentialSet( carrierCredentialSet,  carrierId,  responseFields);
		///   var carrierCredentialSetClient = mozuClient.WithBaseAddress(url).Execute().Result();
		///
		/// </example>
		public static MozuClient<Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet> CreateCarrierCredentialSetClient(Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet carrierCredentialSet, string carrierId, string responseFields =  null)
		{
			var url = Mozu.Api.Urls.Commerce.Shipping.Admin.Carriers.CarrierCredentialSetUrl.CreateCarrierCredentialSetUrl(carrierId, responseFields);
			const string verb = "POST";
			var mozuClient = new MozuClient<Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet>()
									.WithVerb(verb).WithResourceUrl(url)
									.WithBody<Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet>(carrierCredentialSet);
			return mozuClient;

		}

		///
		///
		///
		/// <param name="carrierId"></param>
		/// <param name="code"></param>
		/// <param name="responseFields"></param>
		/// <param name="carrierCredentialSet"></param>
		/// <returns>
		///  <see cref="Mozu.Api.MozuClient" />{<see cref="Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet"/>}
		/// </returns>
		/// <example>
		///
		///   var mozuClient=UpdateCarrierCredentialSet( carrierCredentialSet,  carrierId,  code,  responseFields);
		///   var carrierCredentialSetClient = mozuClient.WithBaseAddress(url).Execute().Result();
		///
		/// </example>
		public static MozuClient<Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet> UpdateCarrierCredentialSetClient(Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet carrierCredentialSet, string carrierId, string code, string responseFields =  null)
		{
			var url = Mozu.Api.Urls.Commerce.Shipping.Admin.Carriers.CarrierCredentialSetUrl.UpdateCarrierCredentialSetUrl(carrierId, code, responseFields);
			const string verb = "PUT";
			var mozuClient = new MozuClient<Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet>()
									.WithVerb(verb).WithResourceUrl(url)
									.WithBody<Mozu.Api.Contracts.ShippingAdmin.Carriers.CarrierCredentialSet>(carrierCredentialSet);
			return mozuClient;

		}

		///
		///
		///
		/// <param name="carrierId"></param>
		/// <param name="code"></param>
		/// <returns>
		///  <see cref="Mozu.Api.MozuClient" />{<see cref="System.IO.Stream"/>}
		/// </returns>
		/// <example>
		///
		///   var mozuClient=DeleteCarrierCredentialSet( carrierId,  code);
		///   var streamClient = mozuClient.WithBaseAddress(url).Execute().Result();
		///
		/// </example>
		public static MozuClient<System.IO.Stream> DeleteCarrierCredentialSetClient(string carrierId, string code)
		{
			var url = Mozu.Api.Urls.Commerce.Shipping.Admin.Carriers.CarrierCredentialSetUrl.DeleteCarrierCredentialSetUrl(carrierId, code);
			const string verb = "DELETE";
			var mozuClient = new MozuClient<System.IO.Stream>()
									.WithVerb(verb).WithResourceUrl(url)
;
			return mozuClient;

		}

	}

}


text:
<?php

declare(strict_types=1);

namespace Picodexter\ParameterEncryptionBundle\Tests\DependencyInjection\Service\Tag;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Picodexter\ParameterEncryptionBundle\DependencyInjection\Service\Tag\KeyNotEmptyDecoratorClassResolverInterface;
use Picodexter\ParameterEncryptionBundle\DependencyInjection\Service\Tag\KeyNotEmptyDecoratorDefinitionGeneratorInterface;
use Picodexter\ParameterEncryptionBundle\DependencyInjection\Service\Tag\KeyNotEmptyTagProcessor;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

class KeyNotEmptyTagProcessorTest extends TestCase
{
    /**
     * @var KeyNotEmptyDecoratorClassResolverInterface|MockObject
     */
    private $decoratorClassResolver;

    /**
     * @var KeyNotEmptyDecoratorDefinitionGeneratorInterface|MockObject
     */
    private $decoratorDefinitionGenerator;

    /**
     * @var KeyNotEmptyTagProcessor
     */
    private $processor;

    /**
     * PHPUnit: setUp.
     */
    public function setUp()
    {
        $this->decoratorClassResolver = $this->createKeyNotEmptyDecoratorClassResolverInterfaceMock();
        $this->decoratorDefinitionGenerator = $this->createKeyNotEmptyDecoratorDefinitionGeneratorInterfaceMock();

        $this->processor = new KeyNotEmptyTagProcessor(
            $this->decoratorClassResolver,
            $this->decoratorDefinitionGenerator
        );
    }

    /**
     * PHPUnit: tearDown.
     */
    public function tearDown()
    {
        $this->processor = null;
        $this->decoratorDefinitionGenerator = null;
        $this->decoratorClassResolver = null;
    }

    public function testProcessSuccessEmpty()
    {
        $container = $this->createContainerBuilderMock();

        $container->expects($this->once())
            ->method('findTaggedServiceIds')
            ->with($this->identicalTo(KeyNotEmptyTagProcessor::TAG_NAME))
            ->will($this->returnValue([]));

        $container->expects($this->never())
            ->method('setDefinition');

        $this->processor->process($container);
    }

    /**
     * @param array  $serviceTags
     * @param int    $expectedDecPriority
     *
     * @dataProvider provideProcessData
     */
    public function testProcessSuccessNotEmpty(array $serviceTags, $expectedDecPriority)
    {
        $serviceId = 'some_service';
        $taggedServices = [
            $serviceId => $serviceTags,
        ];
        $serviceClass = '\\Some\\Encrypter\\Or\\Decrypter\\Class';
        $prepDecoratorClass = '\\Correct\\Encrypter\\Or\\Decrypter\\Decorator\\Class';
        $prepDecoratorSvcId = $serviceId.KeyNotEmptyTagProcessor::DECORATOR_SERVICE_ID_SUFFIX;

        $container = $this->createContainerBuilderMock();
        $serviceDefinition = $this->createDefinitionMock();
        $decoratorDefinition = $this->createDefinitionMock();

        $container->expects($this->once())
            ->method('findTaggedServiceIds')
            ->with($this->identicalTo(KeyNotEmptyTagProcessor::TAG_NAME))
            ->will($this->returnValue($taggedServices));

        $container->expects($this->once())
            ->method('getDefinition')
            ->with($this->identicalTo($serviceId))
            ->will($this->returnValue($serviceDefinition));

        $serviceDefinition->expects($this->once())
            ->method('getClass')
            ->with()
            ->will($this->returnValue($serviceClass));

        $this->decoratorClassResolver->expects($this->once())
            ->method('getDecoratorClassForDecoratedClass')
            ->with($this->identicalTo($serviceClass))
            ->will($this->returnValue($prepDecoratorClass));

        $this->decoratorDefinitionGenerator->expects($this->once())
            ->method('createDecoratorDefinition')
            ->with(
                $this->identicalTo($prepDecoratorClass),
                $this->identicalTo($prepDecoratorSvcId),
                $this->identicalTo($serviceId),
                $this->identicalTo($expectedDecPriority)
            )
            ->will($this->returnValue($decoratorDefinition));

        $container->expects($this->once())
            ->method('setDefinition')
            ->with(
                $this->identicalTo($prepDecoratorSvcId),
                $this->identicalTo($decoratorDefinition)
            );

        $this->processor->process($container);
    }

    /**
     * Data provider.
     */
    public function provideProcessData()
    {
        return [
            'service with priority' => [
                [
                    [
                        'name' => KeyNotEmptyTagProcessor::TAG_NAME,
                        'priority' => 1234,
                    ],
                ],
                1234,
            ],
            'service without priority' => [
                [
                    [
                        'name' => KeyNotEmptyTagProcessor::TAG_NAME,
                    ],
                ],
                KeyNotEmptyTagProcessor::DEFAULT_DECORATION_PRIORITY,
            ],
        ];
    }

    /**
     * Create mock for ContainerBuilder.
     *
     * @return ContainerBuilder|MockObject
     */
    private function createContainerBuilderMock()
    {
        return $this->getMockBuilder(ContainerBuilder::class)
            ->setMethods(['findTaggedServiceIds', 'getDefinition', 'setDefinition'])
            ->getMock();
    }

    /**
     * Create mock for Definition.
     *
     * @return Definition|MockObject
     */
    private function createDefinitionMock()
    {
        return $this->getMockBuilder(Definition::class)->getMock();
    }

    /**
     * Create mock for KeyNotEmptyDecoratorClassResolverInterface.
     *
     * @return KeyNotEmptyDecoratorClassResolverInterface|MockObject
     */
    private function createKeyNotEmptyDecoratorClassResolverInterfaceMock()
    {
        return $this->getMockBuilder(KeyNotEmptyDecoratorClassResolverInterface::class)->getMock();
    }

    /**
     * Create mock for KeyNotEmptyDecoratorDefinitionGeneratorInterface.
     *
     * @return KeyNotEmptyDecoratorDefinitionGeneratorInterface|MockObject
     */
    private function createKeyNotEmptyDecoratorDefinitionGeneratorInterfaceMock()
    {
        return $this->getMockBuilder(KeyNotEmptyDecoratorDefinitionGeneratorInterface::class)->getMock();
    }
}


text:
/*

"Make an Array plugin with dynamic number of ANY datatype inputs,
 and an index input that changes the current output value of the plugin.

inputs: number, 0, 1, 2, 3, ...
outputs: output, length
Eg. feed in 8 images, and alternate between the images with number"

https://github.com/vizorvr/vizor-create/issues/31

*/

(function() {

var ArraySwitch = E2.plugins.array_switch_modulator = function ArraySwitch(core, node) {
	var that = this

	this.desc = 'Revolver style array switch. Set up n inputs, then choose which one to output.';

	this.input_slots = [
		{ name: 'number', dt: E2.dt.FLOAT, desc: 'Input number to select for output.', def: 0 }
	]

	this.output_slots = [
		{ name: 'value', dt: E2.dt.ANY, desc: 'Emits the selected input.' },
		{ name: 'length', dt: E2.dt.FLOAT, desc: 'Emits the number of inputs = the length of the array.' }
	]

	this.core = core
	this.node = node
	this.lsg = new LinkedSlotGroup(core, node, [], [this.output_slots[0]])

	this.number = 0
	this.values = []

	this.node.on('slotAdded', function() {
		that.dynInputs = node.getDynamicInputSlots()
		that.updated = true
	})

	this.node.on('slotRemoved', function() {
		that.dynInputs = node.getDynamicInputSlots()
		that.updated = true
	})
}

ArraySwitch.prototype.create_ui = function() {
	var that = this
	var layout = make('div')
	var removeButton = makeButton('Remove', 'Click to remove the last input.')
	var addButton = makeButton('Add', 'Click to add another input.')

	removeButton.css('width', '65px')
	addButton.css({ 'width': '65px', 'margin-top': '5px' })

	addButton.click(function() {
		E2.app.graphApi.addSlot(that.node.parent_graph, that.node, {
			type: E2.slot_type.input,
			name: that.dynInputs.length + '',
			dt: that.lsg.dt
		})
	})

	removeButton.click(function() {
		var inputs = that.dynInputs
		if (!inputs)
			return

		var suid = inputs[inputs.length - 1].uid
		E2.app.graphApi.removeSlot(that.node.parent_graph, that.node, suid)
	})

	layout.append(removeButton, '<br />', addButton);

	return layout
}

ArraySwitch.prototype.update_input = function(slot, data) {
	if (slot.uid === undefined) {
		if (slot.index === 0) {
			var n = Math.floor(data)
			if (this.number !== n) {
				this.number = n
			}

			for (var i=0; i < this.dynInputs.length; i++)
				this.dynInputs[i].inactive = (i !== this.number)

			return
		}
	} else { // dynamic slot
		this.values[slot.index] = data
	}
}

ArraySwitch.prototype.update_state = function() {
	if (this.number >= this.values.length) {
		this.updated = (this.value !== undefined)
		this.value = undefined
		return
	}

	if (this.value !== this.values[this.number]) {
		this.value = this.values[this.number]
		this.updated = true
	}
	else {
		this.updated = false
	}
}

ArraySwitch.prototype.update_output = function(slot) {
	if (slot.index === 1)
		return this.dynInputs.length

	if (this.value !== undefined)
		return this.value

	var def = this.core.get_default_value(this.lsg.dt)

	return def
}

ArraySwitch.prototype.connection_changed = function(on, conn, slot) {
	if (this.lsg.connection_changed(on, conn, slot))
		this.value = this.lsg.core.get_default_value(this.lsg.dt)
}

ArraySwitch.prototype.state_changed = function(ui) {
	if (!ui) {
		var slots = this.dynInputs = this.node.getDynamicInputSlots()

		for(var i = 0, len = slots.length; i < len; i++) {
			this.lsg.add_dyn_slot(slots[i])
			slots[i].inactive = false
		}

		this.number = 0
		this.value = this.lsg.infer_dt()
	}
};

})();


text:
let ActionStepFormat = require('./actionstepformat');
let Marionette = require('backbone.marionette');

let Format = function() {
    ActionStepFormat.call(this);

    this.name = "batch_weighting";
    this.group = "standard";
    this.description = _t("Take a list of batches in input, and iteratively weight each.");

    this.type = this.ACTION_TYPE_ITERATIVE;
    this.acceptFormat = ['batch_id'];
    this.dataFormat = ['batch_id'];
};

_.extend(Format.prototype, ActionStepFormat.prototype, {
    defaultFormat: function() {
        return {};
    }
});

Format.ActionStepProcessView = ActionStepFormat.ActionStepProcessView.extend({
    className: 'action-step-process',
    template: require('../templates/actionstep/process/batchweighting.html'),

    initialize: function(options) {
        options || (options = {readonly: true});

        this.listenTo(this.model, 'change', this.render, this);
    },

    onRender: function() {
    },

    onBeforeDestroy: function() {
    },

    exportInput: function() {

    },

    importData: function() {

    },

    inputsType: function() {
        return 'none';
    },

    inputsData: function() {
        return null;
    }
});

Format.ActionStepReadView = ActionStepFormat.ActionStepReadView.extend({
});

Format.ActionStepFormatDetailsView = ActionStepFormat.ActionStepFormatDetailsView.extend({
    className: 'action-step-format-details',
    // template: require('../templates/actionstep/batchweigthingdetails.html'),

    initialize: function() {
        this.listenTo(this.model, 'change', this.render, this);
    },

    onRender: function() {
        let format = this.model.get('format');
    },

    storeData: function() {
        return {
        }
    }
});

module.exports = Format;


text:
function push_log_new(info){
  var log = spreadSheet.getSheetByName('logger');
  log.appendRow(info.unshift(new Date()));
};

function push_log(info){
  var log = spreadSheet.getSheetByName('logger');
  log.appendRow(info);
};


text:
<?php

namespace Modules\Necrolab\Models\SteamUsers\Database\RecordModels;

use \Exception;
use \Framework\Core\RecordModel;

class SteamUserAchievement
extends RecordModel {
    protected $steam_user_id;

    protected $achievement_id;

    protected $achieved;
}


text:
<template>

${title}

${error}

${info}

        <form role="form">

            Identifiant:
            <input type="text" class="form-control" id="username" value.bind="username"
             placeholder="Identifiant utilisateur">

            Mot de passe:
            <input type="password" class="form-control" id="password" value.bind="password"
             placeholder="Mot de passe">

            <button type="submit" class="btn btn-primary" show.bind="canLogin"
                   click.delegate="connect()">Connexion</button>

        </form>

</template>


text:
<?php
namespace Acme\BlogBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController as Controller;

class PostAdminController extends Controller
{

}
?>


text:
import Vue from 'vue';
import Vuex from 'vuex';
import batchComments from './modules/batch_comments';

Vue.use(Vuex);

export const createStore = () =>
  new Vuex.Store({
    modules: {
      batchComments: batchComments(),
    },
  });

export default createStore();


text: FAIL: Script didn't run


text:
<?php
/**
 * 后台管理 会员等级  生成类
 * @category iCMS
 * @package iCMS_FrameWork1_RuleClass_DataProvider_User
 * @author zhangchi
 */

class UserLevelManageGen extends BaseManageGen implements IBaseManageGen{
    public function Gen(){
        $result = "";
        $method = Control::GetRequest("m","");

        switch($method){
            case "create":
                $result = self::GenCreate();
                break;
            case "list":
                $result = self::GenList();
                break;
            case "modify":
                $result = self::GenModify();
                break;
            case "modify_state":
                $result = self::AsyncModifyState();
                break;
        }
        $result = str_ireplace("{method}", $method, $result);
        return $result;
    }

    /**
     * 新增
     * @return null|string
     */
    private function GenCreate(){
        $templateContent = Template::Load("user/user_level_deal.html","common");
        $siteId = Control::GetRequest("site_id",0);
        $pageSize = Control::GetRequest("ps",0);
        $tabIndex = Control::GetRequest("tab_index",0);
        $pageIndex = Control::GetRequest("p",1);
        if($siteId > 0){
            parent::ReplaceFirst($templateContent);
            $userLevelManageData = new UserLevelManageData();
            $userGroupManageData = new UserGroupManageData();
            $userGroupAllCount = 0;
            $arrUserGroupList = $userGroupManageData->GetList($siteId,0,1000,$userGroupAllCount);
            $tagId = "user_group_list";
            Template::ReplaceList($templateContent,$arrUserGroupList,$tagId);
            if(!empty($_POST)){
                $httpPostData = $_POST;
                $result = $userLevelManageData->Create($httpPostData,$siteId);
                if($result > 0){
                    $closeTab = Control::PostRequest("CloseTab",0);
                    $tabIndex = Control::GetRequest("TabIndex",0);
                    $pageSize = Control::GetRequest("PageSize",27);
                    $pageIndex  = Control::GetRequest("PageIndex",1);
                    if($closeTab == 1){
                        Control::GoUrl("/default.php?secu=manage&mod=user_level&m=list&site_id=".$siteId."&ps=".$pageSize."&p=".$pageIndex."&tab_index=".$tabIndex);
                    }else{
                        Control::GoUrl($_SERVER["HTTP_SELF"]);
                    }
                }
            }
            $replace_arr = array(
                "{TabIndex}" => $tabIndex,
                "{PageSize}" => $pageSize,
                "{PageIndex}" => $pageIndex,
                "{UserLevelId}" => "0",
                "{SiteId}" => $siteId
            );
            $templateContent = strtr($templateContent,$replace_arr);
            parent::ReplaceWhenCreate($templateContent,$userLevelManageData->GetFields());
            parent::ReplaceEnd($templateContent);
            return $templateContent;
        }else{
            return null;
        }
    }

    /**
     * 修改
     * @return null|string
     */
    private function GenModify(){
        $templateContent = Template::Load("user/user_level_deal.html","common");
        $userLevelId = Control::GetRequest("user_level_id",0);
        $siteId = Control::GetRequest("site_id",0);
        $pageSize = Control::GetRequest("ps",0);
        $tabIndex = Control::GetRequest("tab_index",0);
        $pageIndex = Control::GetRequest("p",1);

        if($userLevelId > 0 && $siteId > 0){
            $userLevelManageData = new UserLevelManageData();
            $returnUrl = $_SERVER['HTTP_REFERER'];
            if(!empty($_POST)){
                $httpPostData = $_POST;
                $result = $userLevelManageData->Modify($httpPostData,$userLevelId);
                if($result > 0){
                    $closeTab = Control::PostRequest("CloseTab",0);
                    $tabIndex = Control::PostRequest("TabIndex",0);
                    $pageSize = Control::PostRequest("PageSize",27);
                    $pageIndex  = Control::PostRequest("PageIndex",1);
                    if($closeTab == 1){
                        Control::GoUrl("/default.php?secu=manage&mod=user_level&m=list&site_id=".$siteId."&ps=".$pageSize."&p=".$pageIndex."&tab_index=".$tabIndex);
                    }else{
                        Control::GoUrl($_SERVER["HTTP_SELF"]);
                    }
                }
            }
            $replace_arr = array(
                "{TabIndex}" => $tabIndex,
                "{PageSize}" => $pageSize,
                "{PageIndex}" => $pageIndex,
                "{UserLevelId}" => $userLevelId,
                "{SiteId}" => $siteId,
                "{ReturnUrl}" => $returnUrl
            );
            $templateContent = strtr($templateContent,$replace_arr);

            $userGroupManageData = new UserGroupManageData();
            $arrUserGroupList = $userGroupManageData->GetList($siteId,0,1000,$userGroupAllCount);
            $tagId = "user_group_list";
            Template::ReplaceList($templateContent,$arrUserGroupList,$tagId);

            $arrUserLevelOne = $userLevelManageData->GetOne($userLevelId,$siteId);
            Template::ReplaceOne($templateContent,$arrUserLevelOne);

            parent::ReplaceEnd($templateContent);
            return $templateContent;
        }else{
            return null;
        }
    }

    /**
     * 异步修改状态
     * @return null|string
     */
    private function AsyncModifyState(){
        $userLevelId = Control::GetRequest("user_level_id",0);
        $state = Control::GetRequest("state",0);

        if($userLevelId > 0){
            $userLevelManageData = new UserLevelManageData();
            $result = $userLevelManageData->ModifyState($userLevelId,$state);
            return Control::GetRequest("jsonpcallback","") .'({"result":"'.$result.'"})';
        }else{
            return null;
        }
    }

    /**
     * 获取会员组列表
     * @return mixed|null|string
     */
    private function GenList(){
        $templateContent = Template::Load("user/user_level_list.html","common");
        $siteId = Control::GetRequest("site_id",0);
        $pageIndex = Control::GetRequest("p",1);
        $pageSize = Control::GetRequest("ps",0);

        if($siteId > 0){
            $allCount = 0;
            $pageBegin = ($pageIndex - 1) * $pageSize;
            $userLevelManageData = new UserLevelManageData();
            $arrUserLevelList = $userLevelManageData->GetList($siteId,$pageBegin,$pageSize,$allCount);
            $tagId = "user_level_list";
            if(count($arrUserLevelList) > 0){
                $styleNumber = 1;
                $pagerTemplate = Template::Load("pager/pager_style$styleNumber.html","common");
                $isJs = FALSE;
                $navUrl = "/default.php?secu=manage&mod=user_level&m=list&site_id=$siteId&p={0}&ps=$pageSize";
                $jsFunctionName = "";
                $jsParamList = "";
                $pagerButton = Pager::ShowPageButton($pagerTemplate, $navUrl, $allCount, $pageSize, $pageIndex, $styleNumber, $isJs, $jsFunctionName, $jsParamList);
                Template::ReplaceList($templateContent,$arrUserLevelList,$tagId);
                $templateContent = str_ireplace("{pagerButton}", $pagerButton, $templateContent);
            }else{
                Template::RemoveCustomTag($templateContent, $tagId);
                $templateContent = str_ireplace("{pagerButton}","", $templateContent);
            }
            $arrReplace = array(
                "{SiteId}" => $siteId
            );
            $templateContent = strtr($templateContent,$arrReplace);
            parent::ReplaceEnd($templateContent);
            return $templateContent;
        }else{
            return null;
        }
    }
}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <xf86drm.h>

#include "sna.h"

#include <xf86.h>
#include <dri3.h>
#include <misyncshm.h>
#include <misyncstr.h>

static DevPrivateKeyRec sna_sync_fence_private_key;
struct sna_sync_fence {
	SyncFenceSetTriggeredFunc set_triggered;
};

static inline struct sna_sync_fence *sna_sync_fence(SyncFence *fence)
{
	return dixLookupPrivate(&fence->devPrivates, &sna_sync_fence_private_key);
}

static inline void mark_dri3_pixmap(struct sna *sna, struct sna_pixmap *priv, struct kgem_bo *bo)
{
	bo->flush = true;
	if (bo->exec)
		sna->kgem.flush = 1;
	if (bo == priv->gpu_bo)
		priv->flush |= 3;
	else
		priv->shm = true;

	sna_accel_watch_flush(sna, 1);
}

static void sna_sync_flush(struct sna *sna, struct sna_pixmap *priv)
{
	struct kgem_bo *bo = NULL;

	DBG(("%s(pixmap=%ld)\n", __FUNCTION__, priv->pixmap->drawable.serialNumber));
	assert(priv);

	if (priv->pinned & PIN_DRI3) {
		assert(priv->gpu_bo);
		assert(priv->pinned & PIN_DRI3);
		DBG(("%s: flushing prime GPU bo, handle=%ld\n", __FUNCTION__, priv->gpu_bo->handle));
		if (sna_pixmap_move_to_gpu(priv->pixmap, MOVE_READ | MOVE_WRITE | MOVE_ASYNC_HINT | __MOVE_FORCE)) {
			sna_damage_all(&priv->gpu_damage, priv->pixmap);
			bo = priv->gpu_bo;
		}
	} else {
		assert(priv->cpu_bo);
		assert(IS_STATIC_PTR(priv->ptr));
		DBG(("%s: flushing prime CPU bo, handle=%ld\n", __FUNCTION__, priv->cpu_bo->handle));
		if (sna_pixmap_move_to_cpu(priv->pixmap, MOVE_READ | MOVE_WRITE | MOVE_ASYNC_HINT))
			bo = priv->cpu_bo;
	}

	if (bo != NULL) {
		kgem_bo_submit(&sna->kgem, bo);
		kgem_bo_unclean(&sna->kgem, bo);
	}
}

static void
sna_sync_fence_set_triggered(SyncFence *fence)
{
	struct sna *sna = to_sna_from_screen(fence->pScreen);
	struct sna_sync_fence *sna_fence = sna_sync_fence(fence);

	DBG(("%s()\n", __FUNCTION__));
	sna_accel_flush(sna);

	fence->funcs.SetTriggered = sna_fence->set_triggered;
	sna_fence->set_triggered(fence);
	sna_fence->set_triggered = fence->funcs.SetTriggered;
	fence->funcs.SetTriggered = sna_sync_fence_set_triggered;
}

static void
sna_sync_create_fence(ScreenPtr screen, SyncFence *fence, Bool initially_triggered)
{
	struct sna *sna = to_sna_from_screen(screen);
	SyncScreenFuncsPtr funcs = miSyncGetScreenFuncs(screen);

	DBG(("%s()\n", __FUNCTION__));

	funcs->CreateFence = sna->dri3.create_fence;
	sna->dri3.create_fence(screen, fence, initially_triggered);
	sna->dri3.create_fence = funcs->CreateFence;
	funcs->CreateFence = sna_sync_create_fence;

	sna_sync_fence(fence)->set_triggered = fence->funcs.SetTriggered;
	fence->funcs.SetTriggered = sna_sync_fence_set_triggered;
}

static bool
sna_sync_open(struct sna *sna, ScreenPtr screen)
{
	SyncScreenFuncsPtr funcs;

	DBG(("%s()\n", __FUNCTION__));

	if (!miSyncShmScreenInit(screen))
		return false;

	if (!dixPrivateKeyRegistered(&sna_sync_fence_private_key)) {
		if (!dixRegisterPrivateKey(&sna_sync_fence_private_key,
					   PRIVATE_SYNC_FENCE,
					   sizeof(struct sna_sync_fence)))
			return false;
	}

	funcs = miSyncGetScreenFuncs(screen);
	sna->dri3.create_fence = funcs->CreateFence;
	funcs->CreateFence = sna_sync_create_fence;

	return true;
}

static int sna_dri3_open_device(ScreenPtr screen,
				RRProviderPtr provider,
				int *out)
{
	int fd;

	DBG(("%s()\n", __FUNCTION__));
	fd = intel_get_client_fd(to_sna_from_screen(screen)->dev);
	if (fd < 0)
		return -fd;

	*out = fd;
	return Success;
}

static PixmapPtr sna_dri3_pixmap_from_fd(ScreenPtr screen,
					 int fd,
					 CARD16 width,
					 CARD16 height,
					 CARD16 stride,
					 CARD8 depth,
					 CARD8 bpp)
{
	struct sna *sna = to_sna_from_screen(screen);
	PixmapPtr pixmap;
	struct sna_pixmap *priv;
	struct kgem_bo *bo;

	DBG(("%s(fd=%d, width=%d, height=%d, stride=%d, depth=%d, bpp=%d)\n",
	     __FUNCTION__, fd, width, height, stride, depth, bpp));
	if (width > INT16_MAX || height > INT16_MAX)
		return NULL;

	if ((uint32_t)width * bpp > (uint32_t)stride * 8)
		return NULL;

	if (depth < 8)
		return NULL;

	switch (bpp) {
	case 8:
	case 16:
	case 32:
		break;
	default:
		return NULL;
	}

	bo = kgem_create_for_prime(&sna->kgem, fd, (uint32_t)stride * height);
	if (bo == NULL)
		return NULL;

	/* Check for a duplicate */
	list_for_each_entry(priv, &sna->dri3.pixmaps, cow_list) {
		int other_stride = 0;
		if (bo->snoop) {
			assert(priv->cpu_bo);
			assert(IS_STATIC_PTR(priv->ptr));
			if (bo->handle == priv->cpu_bo->handle)
				other_stride = priv->cpu_bo->pitch;
		} else  {
			assert(priv->gpu_bo);
			assert(priv->pinned & PIN_DRI3);
			if (bo->handle == priv->gpu_bo->handle)
				other_stride = priv->gpu_bo->pitch;
		}
		if (other_stride) {
			pixmap = priv->pixmap;
			DBG(("%s: imported fd matches existing DRI3 pixmap=%ld\n", __FUNCTION__, pixmap->drawable.serialNumber));
			bo->handle = 0; /* fudge to prevent gem_close */
			kgem_bo_destroy(&sna->kgem, bo);
			if (width != pixmap->drawable.width ||
			    height != pixmap->drawable.height ||
			    depth != pixmap->drawable.depth ||
			    bpp != pixmap->drawable.bitsPerPixel ||
			    stride != other_stride) {
				DBG(("%s: imported fd mismatches existing DRI3 pixmap (width=%d, height=%d, depth=%d, bpp=%d, stride=%d)\n", __FUNCTION__,
				     pixmap->drawable.width,
				     pixmap->drawable.height,
				     pixmap->drawable.depth,
				     pixmap->drawable.bitsPerPixel,
				     other_stride));
				return NULL;
			}
			sna_sync_flush(sna, priv);
			pixmap->refcnt++;
			return pixmap;
		}
	}

	if (!kgem_check_surface_size(&sna->kgem,
				     width, height, bpp,
				     bo->tiling, stride, kgem_bo_size(bo))) {
		DBG(("%s: client supplied pitch=%d, size=%d too small for %dx%d surface\n",
		     __FUNCTION__, stride, kgem_bo_size(bo), width, height));
		goto free_bo;
	}

	pixmap = sna_pixmap_create_unattached(screen, 0, 0, depth);
	if (pixmap == NullPixmap)
		goto free_bo;

	if (!screen->ModifyPixmapHeader(pixmap, width, height,
					depth, bpp, stride, NULL))
		goto free_pixmap;

	priv = sna_pixmap_attach_to_bo(pixmap, bo);
	if (priv == NULL)
		goto free_pixmap;

	bo->pitch = stride;
	priv->stride = stride;

	if (bo->snoop) {
		assert(priv->cpu_bo == bo);
		pixmap->devPrivate.ptr = kgem_bo_map__cpu(&sna->kgem, priv->cpu_bo);
		if (pixmap->devPrivate.ptr == NULL)
			goto free_pixmap;

		pixmap->devKind = stride;
		priv->ptr = MAKE_STATIC_PTR(pixmap->devPrivate.ptr);
	} else {
		assert(priv->gpu_bo == bo);
		priv->pinned |= PIN_DRI3;
	}
	list_add(&priv->cow_list, &sna->dri3.pixmaps);

	mark_dri3_pixmap(sna, priv, bo);

	return pixmap;

free_pixmap:
	screen->DestroyPixmap(pixmap);
free_bo:
	kgem_bo_destroy(&sna->kgem, bo);
	return NULL;
}

static int sna_dri3_fd_from_pixmap(ScreenPtr screen,
				   PixmapPtr pixmap,
				   CARD16 *stride,
				   CARD32 *size)
{
	struct sna *sna = to_sna_from_screen(screen);
	struct sna_pixmap *priv;
	struct kgem_bo *bo = NULL;
	int fd;

	DBG(("%s(pixmap=%ld, width=%d, height=%d)\n", __FUNCTION__,
	     pixmap->drawable.serialNumber, pixmap->drawable.width, pixmap->drawable.height));
	if (pixmap == sna->front && sna->flags & SNA_TEAR_FREE) {
		DBG(("%s: DRI3 protocol cannot support TearFree frontbuffers\n", __FUNCTION__));
		return -1;
	}

	priv = sna_pixmap(pixmap);
	if (priv && IS_STATIC_PTR(priv->ptr) && priv->cpu_bo) {
		if (sna_pixmap_move_to_cpu(pixmap, MOVE_READ | MOVE_WRITE | MOVE_ASYNC_HINT))
			bo = priv->cpu_bo;
	} else {
		priv = sna_pixmap_move_to_gpu(pixmap, MOVE_READ | MOVE_WRITE | MOVE_ASYNC_HINT | __MOVE_FORCE | __MOVE_DRI);
		if (priv != NULL) {
			sna_damage_all(&priv->gpu_damage, pixmap);
			bo = priv->gpu_bo;
		}
	}
	if (bo == NULL) {
		DBG(("%s: pixmap not supported by GPU\n", __FUNCTION__));
		return -1;
	}
	assert(priv != NULL);

	if (bo->pitch > UINT16_MAX) {
		DBG(("%s: pixmap pitch (%d) too large for DRI3 protocol\n",
		     __FUNCTION__, bo->pitch));
		return -1;
	}

	fd = kgem_bo_export_to_prime(&sna->kgem, bo);
	if (fd == -1) {
		DBG(("%s: exporting handle=%d to fd failed\n", __FUNCTION__, bo->handle));
		return -1;
	}

	if (bo == priv->gpu_bo)
		priv->pinned |= PIN_DRI3;
	list_move(&priv->cow_list, &sna->dri3.pixmaps);

	mark_dri3_pixmap(sna, priv, bo);

	*stride = (priv->pinned & PIN_DRI3) ? priv->gpu_bo->pitch : priv->cpu_bo->pitch;
	*size = kgem_bo_size((priv->pinned & PIN_DRI3) ? priv->gpu_bo : priv->cpu_bo);
	DBG(("%s: exporting %s pixmap=%ld, handle=%d, stride=%d, size=%d\n",
	     __FUNCTION__,
	     (priv->pinned & PIN_DRI3) ? "GPU" : "CPU", pixmap->drawable.serialNumber,
	     (priv->pinned & PIN_DRI3) ? priv->gpu_bo->handle : priv->cpu_bo->handle,
	     *stride, *size));
	return fd;
}

static dri3_screen_info_rec sna_dri3_info = {
	.version = DRI3_SCREEN_INFO_VERSION,

	.open = sna_dri3_open_device,
	.pixmap_from_fd = sna_dri3_pixmap_from_fd,
	.fd_from_pixmap = sna_dri3_fd_from_pixmap,
};

bool sna_dri3_open(struct sna *sna, ScreenPtr screen)
{
	DBG(("%s()\n", __FUNCTION__));

	if (!sna_sync_open(sna, screen))
		return false;

	list_init(&sna->dri3.pixmaps);
	return dri3_screen_init(screen, &sna_dri3_info);
}

void sna_dri3_close(struct sna *sna, ScreenPtr screen)
{
	SyncScreenFuncsPtr funcs;

	DBG(("%s()\n", __FUNCTION__));

	funcs = miSyncGetScreenFuncs(screen);
	if (funcs)
		funcs->CreateFence = sna->dri3.create_fence;
}


text:
from django.test import TestCase
from django.contrib.auth.models import User

# Create your tests here.
from .models import Question,Answer

class QuestionTestCase(TestCase):

	def setUp(self):

		Question.objects.create(text="This is a test question?", question_type="multiple_choice")

	def test_question_is_not_null(self):

		question = Question.objects.get(text="This is a test question?")

		self.assertTrue(question.text)

	def test_question_choice_exists(self):

		question = Question.objects.get(text="This is a test question?")
		self.assertTrue(question.question_type )

class AnswerTestCase(TestCase):

	def setUp(self):
		q = Question.objects.create(text="This is a test question?", question_type="multiple_choice")

		Answer.objects.create(answers=q, text = "GOOD")

	def test_answer_is_not_null(self):

		answer = Answer.objects.get(answers=1)

		self.assertTrue(answer.answers)
		self.assertTrue(answer.text)


text:
// Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using StsServer.Network.Packets;
using Framework.Cryptography;
using Framework.Cryptography.BNet;
using Framework.Database.Auth;
using Framework.Logging;
using Framework.Misc;

namespace StsServer.Network
{
    class StsSession : IDisposable
    {
        public Account Account { get; set; }
        public int State { get; set; }
        public SRP6a SecureRemotePassword { get; set; }
        public SARC4 ClientCrypt { get; set; }
        public SARC4 ServerCrypt { get; set; }

        Socket client;
        Stack<StsPacket> packetQueue;
        byte[] dataBuffer = new byte[0x400];

        public StsSession(Socket clientSocket)
        {
            client = clientSocket;
            packetQueue = new Stack<StsPacket>();
        }

        public void Accept()
        {
            var socketEventArgs = new SocketAsyncEventArgs();

            socketEventArgs.SetBuffer(dataBuffer, 0, dataBuffer.Length);

            socketEventArgs.Completed += OnConnection;
            socketEventArgs.UserToken = client;
            socketEventArgs.SocketFlags = SocketFlags.None;

            client.ReceiveAsync(socketEventArgs);
        }

        public void OnConnection(object sender, SocketAsyncEventArgs e)
        {
            PacketLog.Write<StsPacket>(dataBuffer, e.BytesTransferred, client.RemoteEndPoint as IPEndPoint);

            if (e.BytesTransferred < 256 || e.BytesTransferred > 400)
            {
                Console.WriteLine("Wrong initialization packet.");

                Dispose();
            }
            else
            {
                // POST
                if (BitConverter.ToUInt32(dataBuffer, 0) == 0x54534F50)
                {
                    var packetData = new byte[e.BytesTransferred];

                    Buffer.BlockCopy(dataBuffer, 0, packetData, 0, e.BytesTransferred);

                    var packetInfo = GetMessageType(packetData);

                    if (packetInfo.Item1 != "Sts")
                    {
                        Console.WriteLine("Wrong packet type for first packet.");

                        Dispose();

                        return;
                    }

                    var packet = new StsPacket(packetData);

                    packet.ReadHeader(packetInfo);

                    packetData = new byte[packet.Header.DataLength];

                    Buffer.BlockCopy(packet.Data, packet.Header.Length, packetData, 0, packet.Header.DataLength);

                    packet.Data.Combine(packetData);

                    packet.ReadData(packetData);

                    StsPacketManager.Invoke(packet, this);

                    e.Completed -= OnConnection;
                    e.Completed += Process;

                    client.ReceiveAsync(e);
                }
            }
        }

        public void Process(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                var socket = e.UserToken as Socket;
                var receivedBytes = e.BytesTransferred;

                if (receivedBytes > 0)
                {
                    byte[] packetData = null;

                    if (packetQueue.Count > 0)
                    {
                        var lastPacket = packetQueue.Pop();

                        if (receivedBytes != lastPacket.Header.DataLength)
                        {
                            Console.WriteLine("Wrong data received.");

                            Dispose();

                            return;
                        }

                        packetData = new byte[receivedBytes];

                        Buffer.BlockCopy(dataBuffer, 0, packetData, 0, receivedBytes);

                        lastPacket.Data.Combine(packetData);
                        lastPacket.ReadData(packetData);

                        ProcessPacket(lastPacket);
                    }

                    if (ClientCrypt != null)
                    {
                        if (receivedBytes <= 100)
                            State = 0;

                        if (State == 0)
                            ClientCrypt.ProcessBuffer(dataBuffer, receivedBytes);
                    }

                    packetData = new byte[receivedBytes];

                    Buffer.BlockCopy(dataBuffer, 0, packetData, 0, receivedBytes);

                    // POST
                    if (BitConverter.ToUInt32(packetData, 0) == 0x54534F50)
                    {
                        var packet = new StsPacket(packetData);
                        var packetInfo = GetMessageType(packetData);

                        packet.ReadHeader(packetInfo);

                        if ((receivedBytes - packet.Header.Length) != packet.Header.DataLength)
                            packetQueue.Push(packet);
                        else
                        {
                            receivedBytes -= packet.Header.Length;

                            packetData = new byte[receivedBytes];

                            Buffer.BlockCopy(packet.Data, packet.Header.Length, packetData, 0, receivedBytes);

                            if (packetData.Length > 0)
                                packet.ReadData(packetData);

                            ProcessPacket(packet);
                        }
                    }

                    client.ReceiveAsync(e);
                }
                else
                    Dispose();
            }
            catch
            {
                Dispose();
            }
        }

        public void ProcessPacket(StsPacket packet)
        {
            PacketLog.Write<StsPacket>(packet.Data, packet.Data.Length, client.RemoteEndPoint as IPEndPoint);

            StsPacketManager.Invoke(packet, this);
        }

        public void Send(StsPacket packet)
        {
            try
            {
                packet.Finish();

                PacketLog.Write<StsPacket>(packet.Data, packet.Data.Length, client.RemoteEndPoint as IPEndPoint);

                if (ServerCrypt != null)
                    ServerCrypt.ProcessBuffer(packet.Data);

                var socketEventargs = new SocketAsyncEventArgs();

                socketEventargs.SetBuffer(packet.Data, 0, packet.Data.Length);

                socketEventargs.Completed += SendCompleted;
                socketEventargs.UserToken = packet;
                socketEventargs.RemoteEndPoint = client.RemoteEndPoint;
                socketEventargs.SocketFlags = SocketFlags.None;

                client.SendAsync(socketEventargs);
            }
            catch
            {
                Dispose();
            }
        }

        void SendCompleted(object sender, SocketAsyncEventArgs e)
        {
        }

        public Tuple<string[], int> ReadLines(BinaryReader readStream)
        {
            var position = 0;

            while (position == 0 && readStream.BaseStream.CanRead)
            {
                if (readStream.ReadByte() == 0x0D)
                {
                    if (readStream.ReadByte() == 0x0A)
                    {
                        if (readStream.ReadUInt16() == 0x0A0D)
                            position = (int)readStream.BaseStream.Position;
                    }
                }
            }

            readStream.BaseStream.Position = 0;

            var data = readStream.ReadBytes(position - 4);
            var lines = Encoding.ASCII.GetString(data).Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            return Tuple.Create(lines, position);
        }

        public Tuple<string, string[], int> GetMessageType(byte[] data)
        {
            var headerParts = ReadLines(new BinaryReader(new MemoryStream(data)));

            if (headerParts.Item1.Length >= 2)
            {
                var identifier = headerParts.Item1[0].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                if (identifier.Length == 3)
                    return Tuple.Create(identifier[1].Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)[0], headerParts.Item1, headerParts.Item2);
            }

            return Tuple.Create("Unknown", new string[0], 0);
        }

        public string GetClientInfo()
        {
            var ipEndPoint = client.RemoteEndPoint as IPEndPoint;

            return ipEndPoint != null ? ipEndPoint.Address + ":" + ipEndPoint.Port : "";
        }

        #region IDisposable Support
        private bool disposedValue = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    client.Dispose();
                }

                disposedValue = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }
        #endregion
    }
}


text:
package com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;

import org.apache.commons.lang3.SystemUtils;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.sap.prd.mobile.ios.mios.xcodeprojreader.Plist;

public class JAXBPlistParser
{
  private static final String xmlHeaders = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">";

  public Plist load(String projectFile) throws SAXException, ParserConfigurationException, FileNotFoundException,
        JAXBException
  {
    return load(new File(projectFile));
  }

  public Plist load(File projectFile) throws SAXException, ParserConfigurationException, FileNotFoundException,
        JAXBException
  {
    InputSource project = new InputSource(new FileReader(projectFile));
    return unmarshallPlist(project);
  }

  public Plist load(InputSource project) throws SAXException, ParserConfigurationException,
        JAXBException
  {
    return unmarshallPlist(project);
  }

  private Plist unmarshallPlist(InputSource project) throws SAXException,
        ParserConfigurationException,
        JAXBException
  {
    InputSource dtd = new InputSource(this.getClass().getResourceAsStream("/PropertyList-1.0.dtd"));
    SAXSource ss = createSAXSource(project, dtd);
    JAXBContext ctx = JAXBContext.newInstance(com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlist.class);
    Unmarshaller unmarshaller = ctx.createUnmarshaller();

    // unexpected elements should cause an error
    unmarshaller.setEventHandler(new ValidationEventHandler() {
      @Override
      public boolean handleEvent(ValidationEvent event)
      {
        return false;
      }
    });

    return (Plist) unmarshaller.unmarshal(ss);
  }

  private SAXSource createSAXSource(InputSource project, final InputSource dtd) throws SAXException,
        ParserConfigurationException
  {
    XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    xmlReader.setEntityResolver(new EntityResolver() {
      @Override
      public InputSource resolveEntity(String pid, String sid) throws SAXException
      {
        if (sid.equals("http://www.apple.com/DTDs/PropertyList-1.0.dtd"))
          return dtd;
        throw new SAXException("unable to resolve remote entity, sid = " + sid);
      }
    });
    SAXSource ss = new SAXSource(xmlReader, project);
    return ss;
  }

  public void save(Plist plist, String projectFile) throws JAXBException
  {
    save(plist, new File(projectFile));
  }

  public void save(Plist plist, File projectFile) throws JAXBException
  {
    try
    {
      save(plist, new FileWriter(projectFile));
    }
    catch (IOException ex)
    {
      throw new JAXBException(ex);
    }
  }

  public void save(Plist plist, Writer projectFile) throws JAXBException
  {
    marshallPlist(plist, projectFile);
  }

  private void marshallPlist(Plist plist, Writer projectFile) throws JAXBException
  {
    JAXBContext ctx = JAXBContext.newInstance(com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlist.class);
    Marshaller marshaller = ctx.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    try
    {
      marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", xmlHeaders);
    }
    catch(PropertyException ex)
    {
      marshaller.setProperty("com.sun.xml.bind.xmlHeaders", xmlHeaders);
    }
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
    marshaller.marshal(plist, projectFile);
  }

  public void convert(String projectFile, String destinationProjectFile) throws IOException
  {
    convert(new File(projectFile), new File(destinationProjectFile));
  }

  public void convert(File projectFile, File destinationProjectFile) throws IOException
  {
    if (!SystemUtils.IS_OS_MAC_OSX) {
      throw new UnsupportedOperationException("The pbxproj file conversion can only be performed on a Mac OS X " +
            "operating system as the Mac OS X specific tool 'plutil' gets called.");
    }
    Process exec = Runtime.getRuntime().exec(
          new String[] { "plutil", "-convert", "xml1", "-o", destinationProjectFile.getAbsolutePath(),
              projectFile.getAbsolutePath() });
    try
    {
      exec.waitFor();
    }
    catch (InterruptedException e)
    {
    }

    if (exec.exitValue() != 0)
    {
      throw new RuntimeException("Could not convert file (Exit Code: " + exec.exitValue() + ")");
    }
  }
}