text:
package org.apache.asterix.replication.storage;

import java.io.DataInput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.asterix.common.ioopcallbacks.AbstractLSMIOOperationCallback;
import org.apache.asterix.common.storage.ResourceReference;
import org.apache.asterix.replication.logging.TxnLogUtil;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexOperationContext;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexReplicationJob;
import org.apache.hyracks.storage.am.lsm.common.api.LSMOperationType;
import org.apache.hyracks.storage.am.lsm.common.impls.AbstractLSMIndex;
import org.apache.hyracks.storage.am.lsm.common.impls.AbstractLSMIndexFileManager;

public class LSMComponentProperties {

    private AtomicInteger numberOfFiles;
    private String componentId;
    private long lsnOffset;
    private long originalLSN;
    private String nodeId;
    private Long replicaLSN;
    private String maskPath = null;
    private String replicaPath = null;
    private LSMOperationType opType;

    public LSMComponentProperties(ILSMIndexReplicationJob job, String nodeId) {
        this.nodeId = nodeId;
        componentId = LSMComponentProperties.getLSMComponentID((String) job.getJobFiles().toArray()[0]);
        numberOfFiles = new AtomicInteger(job.getJobFiles().size());
        originalLSN = LSMComponentProperties.getLSMComponentLSN((AbstractLSMIndex) job.getLSMIndex(),
                job.getLSMIndexOperationContext());
        opType = job.getLSMOpType();
    }

    public LSMComponentProperties() {
    }

    public static long getLSMComponentLSN(AbstractLSMIndex lsmIndex, ILSMIndexOperationContext ctx) {
        long componentLSN = -1;
        try {
            componentLSN = ((AbstractLSMIOOperationCallback) lsmIndex.getIOOperationCallback())
                    .getComponentLSN(ctx.getComponentsToBeReplicated());
        } catch (HyracksDataException e) {
            e.printStackTrace();
        }
        if (componentLSN < 0) {
            componentLSN = 0;
        }
        return componentLSN;
    }

    public void serialize(OutputStream out) throws IOException {
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeUTF(componentId);
        dos.writeUTF(nodeId);
        dos.writeInt(numberOfFiles.get());
        dos.writeLong(originalLSN);
        dos.writeLong(lsnOffset);
        dos.writeInt(opType.ordinal());
    }

    public static LSMComponentProperties create(DataInput input) throws IOException {
        LSMComponentProperties lsmCompProp = new LSMComponentProperties();
        lsmCompProp.componentId = input.readUTF();
        lsmCompProp.nodeId = input.readUTF();
        lsmCompProp.numberOfFiles = new AtomicInteger(input.readInt());
        lsmCompProp.originalLSN = input.readLong();
        lsmCompProp.lsnOffset = input.readLong();
        lsmCompProp.opType = LSMOperationType.values()[input.readInt()];
        return lsmCompProp;
    }

    public String getMaskPath(ReplicaResourcesManager resourceManager) throws HyracksDataException {
        if (maskPath == null) {
            LSMIndexFileProperties afp = new LSMIndexFileProperties(this);
            maskPath = getReplicaComponentPath(resourceManager) + File.separator + afp.getFileName()
                    + ReplicaResourcesManager.LSM_COMPONENT_MASK_SUFFIX;
        }
        return maskPath;
    }

    public String getReplicaComponentPath(ReplicaResourcesManager resourceManager) throws HyracksDataException {
        if (replicaPath == null) {
            LSMIndexFileProperties afp = new LSMIndexFileProperties(this);
            replicaPath = resourceManager.getIndexPath(afp);
        }
        return replicaPath;
    }

    /***
     * @param filePath
     *            any file of the LSM component
     * @return a unique id based on the timestamp of the component
     */
    public static String getLSMComponentID(String filePath) {
        final ResourceReference ref = ResourceReference.of(filePath);
        final String fileUniqueTimestamp =
                ref.getName().substring(0, ref.getName().lastIndexOf(AbstractLSMIndexFileManager.DELIMITER));
        return Paths.get(ref.getRelativePath().toString(), fileUniqueTimestamp).toString();
    }

    public String getComponentId() {
        return componentId;
    }

    public long getOriginalLSN() {
        return originalLSN;
    }

    public String getNodeId() {
        return nodeId;
    }

    public int markFileComplete() {
        return numberOfFiles.decrementAndGet();
    }

    public Long getReplicaLSN() {
        return replicaLSN;
    }

    public void setReplicaLSN(Long replicaLSN) {
        this.replicaLSN = replicaLSN;
    }

    public LSMOperationType getOpType() {
        return opType;
    }

    public String getNodeUniqueLSN() {
        return TxnLogUtil.getNodeUniqueLSN(nodeId, originalLSN);
    }
}


text:
import {
  ComponentRef,
  Injectable,
  NgZone,
  OnDestroy,
  Type,
} from '@angular/core';
import { NavigationStart, Router } from '@angular/router';
import {
  SkyAppWindowRef,
  SkyCoreAdapterService,
  SkyDynamicComponentService,
} from '@skyux/core';

import { Subject, fromEvent } from 'rxjs';
import { take, takeUntil, takeWhile } from 'rxjs/operators';

import { SkyFlyoutInstance } from './flyout-instance';
import { SkyFlyoutComponent } from './flyout.component';
import { SkyFlyoutCloseArgs } from './types/flyout-close-args';
import { SkyFlyoutConfig } from './types/flyout-config';
import { SkyFlyoutMessage } from './types/flyout-message';
import { SkyFlyoutMessageType } from './types/flyout-message-type';

/**
 * Launches flyouts and provides a common look and feel.
 * This service dynamically generates the flyout component and appends it directly to the
 * document's `body` element. The `SkyFlyoutInstance` class watches for and triggers flyout events.
 */
@Injectable({
  providedIn: 'any',
})
export class SkyFlyoutService implements OnDestroy {
  #host: ComponentRef<SkyFlyoutComponent> | undefined;
  #removeAfterClosed = false;
  #isOpening = false;
  #ngUnsubscribe = new Subject<boolean>();

  #coreAdapter: SkyCoreAdapterService;
  #windowRef: SkyAppWindowRef;
  #dynamicComponentService: SkyDynamicComponentService;
  #router: Router;
  #ngZone: NgZone;

  constructor(
    coreAdapter: SkyCoreAdapterService,
    windowRef: SkyAppWindowRef,
    dynamicComponentService: SkyDynamicComponentService,
    router: Router,
    ngZone: NgZone
  ) {
    this.#coreAdapter = coreAdapter;
    this.#windowRef = windowRef;
    this.#dynamicComponentService = dynamicComponentService;
    this.#router = router;
    this.#ngZone = ngZone;
  }

  public ngOnDestroy(): void {
    this.#removeListners();
    if (this.#host) {
      this.#removeHostComponent();
    }
  }

  /**
   * Closes the flyout. This method also removes the flyout's HTML elements from the DOM.
   * @param args Arguments used when closing the flyout.
   */
  public close(args?: SkyFlyoutCloseArgs): void {
    if (this.#host && !this.#isOpening) {
      this.#host.instance.messageStream.next({
        type: SkyFlyoutMessageType.Close,
        data: {
          ignoreBeforeClose: args ? args.ignoreBeforeClose : false,
        },
      });
    }
  }

  /**
   * Opens a flyout and displays the specified component.
   * @param component Specifies the component to render.
   * @param config Specifies the flyout configuration passed to the specified component's constructor.
   */
  public open<T>(
    component: Type<T>,
    config?: SkyFlyoutConfig
  ): SkyFlyoutInstance<T> {
    // isOpening flag will prevent close() from firing when open() is also fired.
    this.#isOpening = true;
    this.#windowRef.nativeWindow.setTimeout(() => {
      this.#isOpening = false;
    });

    if (!this.#host) {
      this.#host = this.#createHostComponent();

      this.#router.events
        .pipe(takeWhile(() => this.#host !== undefined))
        .subscribe((event) => {
          if (event instanceof NavigationStart) {
            this.close();

            // Sanity check - if the host still exists after animations should have completed - remove host
            this.#ngZone.onStable.pipe(take(1)).subscribe(() => {
              if (this.#host) {
                this.#removeHostComponent();
              }
            });
          }
        });
    }

    const flyout = this.#host.instance.attach(component, config);

    this.#addListeners(flyout);

    return flyout;
  }

  #createHostComponent(): ComponentRef<SkyFlyoutComponent> {
    this.#host =
      this.#dynamicComponentService.createComponent(SkyFlyoutComponent);
    return this.#host;
  }

  #removeHostComponent(): void {
    if (this.#host) {
      this.#dynamicComponentService.removeComponent(this.#host);
      this.#host = undefined;
    }
  }

  #addListeners<T>(flyout: SkyFlyoutInstance<T>): void {
    /* istanbul ignore else */
    if (this.#host) {
      const flyoutInstance = this.#host.instance;

      let doClose = false;

      /**
       * Handles when to close a flyout.
       * Note: We're using `mouseup` in order to capture the parent of certain targets that will be
       * deleted immediately after being clicked. If we use `click`, the event is fired after the
       * element is removed from the DOM making it impossible to check the parent's z-index
       * relative to the flyout's container.
       */
      fromEvent(document, 'mouseup')
        .pipe(takeUntil(this.#ngUnsubscribe))
        .subscribe((event: Event) => {
          doClose = false;

          if (this.#host?.instance.isDragging) {
            return;
          }

          if (flyoutInstance.flyoutRef?.nativeElement.contains(event.target)) {
            return;
          }

          const isAbove =
            event.target === document || !event.target
              ? false
              : this.#coreAdapter.isTargetAboveElement(
                  event.target,
                  flyoutInstance.flyoutRef?.nativeElement
                );

          /* istanbul ignore else */
          if (!isAbove) {
            doClose = true;
          }
        });

      /**
       * Check if we should close the flyout specifically on a `click` event so that we can keep
       * it open when consumers fire another `click` event on a trigger button. Since the consumer
       * will likely use a `click` event to open the flyout, we want to wait for that event to fire
       * before determining if the flyout should be closed.
       */
      fromEvent(document, 'click')
        .pipe(takeUntil(this.#ngUnsubscribe))
        .subscribe(() => {
          if (doClose) {
            this.close();
          }
        });

      this.#removeAfterClosed = false;
      flyoutInstance.messageStream
        .pipe(takeUntil(this.#ngUnsubscribe))
        .subscribe((message: SkyFlyoutMessage) => {
          if (message.type === SkyFlyoutMessageType.Close) {
            this.#removeAfterClosed = true;
            this.#isOpening = false;
          }
        });

      flyout.closed.pipe(take(1)).subscribe(() => {
        this.#removeListners();
        if (this.#removeAfterClosed) {
          this.#removeHostComponent();
        }
      });
    }
  }

  #removeListners(): void {
    this.#ngUnsubscribe.next(true);
    this.#ngUnsubscribe.unsubscribe();
    this.#ngUnsubscribe = new Subject<boolean>();
  }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @fileoverview This file describes the externs API for V8-specific objects.
 * @externs
 */

/**
 * Stack frame elements in V8.
 * @constructor
 */
function CallSite() {}

/**
 * Runs the garbage collector, provided that you start V8 with --expose-gc or
 * Chrome with --js-flags="--expose-gc".
 * See https://v8.dev/docs/memory-leaks
 * @type {undefined|function()}
 */
CallSite.prototype.gc;

/**
 * Returns the value of this.
 * @return {Object|undefined}
 */
CallSite.prototype.getThis = function() {};

/**
 * Returns the type of this as a string. This is the name of the function stored
 * in the constructor field of this, if available, otherwise the object's
 * [[Class]] internal property.
 * @return {string|undefined}
 */
CallSite.prototype.getTypeName = function() {};

/**
 * Returns the current function.
 * @return {!Function|undefined}
 */
CallSite.prototype.getFunction = function() {};

/**
 * Returns the name of the current function, typically its name property. If a
 * name property is not available an attempt will be made to try to infer a name
 * from the function's context.
 * @return {string|undefined}
 */
CallSite.prototype.getFunctionName = function() {};

/**
 * Returns the name of the property of this or one of its prototypes that holds
 * the current function.
 * @return {string|undefined}
 */
CallSite.prototype.getMethodName = function() {};

/**
 * If this function was defined in a script returns the name of the script
 * @return {string|undefined}
 */
CallSite.prototype.getFileName = function() {};

/**
 * If this function was defined in a script returns the current line number.
 * @return {number|undefined}
 */
CallSite.prototype.getLineNumber = function() {};

/**
 * If this function was defined in a script returns the current column number.
 * @return {number|undefined}
 */
CallSite.prototype.getColumnNumber = function() {};

/**
 * If this function was created using a call to eval, returns a CallSite object
 * representing the location where eval was called
 * @return {CallSite|undefined}
 */
CallSite.prototype.getEvalOrigin = function() {};

/**
 * Is this a toplevel invocation, that is, is this the global object?
 * @return {boolean}
 */
CallSite.prototype.isToplevel = function() {};

/**
 * Does this call take place in code defined by a call to eval?
 * @return {boolean}
 */
CallSite.prototype.isEval = function() {};

/**
 * Is this call in native V8 code?
 * @return {boolean}
 */
CallSite.prototype.isNative = function() {};

/**
 * Is this a constructor call?
 * @return {boolean}
 */
CallSite.prototype.isConstructor = function() {};


text:
<?php

require_once '../../../vendor/autoload.php';
require_once '../../../apikey.php';

$token  = new \Tmdb\ApiToken(TMDB_API_KEY);
$client = new \Tmdb\Client($token);

$result = $client->getSearchApi()->searchKeyword('scary');

var_dump($result);


text:
package timerandbuzzer.cs.ualberta.ca.timerandbuzzer;

/**
 * Created by xzhang9 on 10/3/15.
 */
public class playersRecord4 {
    protected String PlayersRecord4;
    public playersRecord4(String PlayersRecord){
        this.PlayersRecord4=PlayersRecord;
    }

    public String GetRecord(){
        return this.PlayersRecord4;
    }
    public String toString() {
        return GetRecord();
    }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using System.Xml.Serialization;

namespace Igor
{
	[System.Serializable]
	public class LinkedEntityManager<EntityType> : XMLSerializable where EntityType : LinkedEntity<EntityType>, new() {

		[System.NonSerialized]
		public List<EntityLink<EntityType>> StartingEntities = new List<EntityLink<EntityType>>();
		[System.NonSerialized]
		public List<EntityLink<EntityType>> EndingEntities = new List<EntityLink<EntityType>>();

		public LinkedEntityManager() : base()
		{
		}

		public virtual void LoadEntities()
		{
			SerializeEntityManager(false);
		}

		public virtual void SaveEntities()
		{
			SerializeEntityManager(true);
			SerializeAllEntities(true);
		}

	#if UNITY_EDITOR
		public virtual void AddEntity(EntityType NewEntity)
		{
			bool bHasFilenameAlready = false;

			foreach(EntityType CurrentEntity in Entities)
			{
				if(CurrentEntity.GetFilename() == NewEntity.GetFilename())
				{
					bHasFilenameAlready = true;
				}
			}

			if(bHasFilenameAlready)
			{
				NewEntity.EditorSetFilename(EditorGetUniqueEntityFilename(NewEntity.GetFilename()));

				AddEntity(NewEntity);
			}
			else
			{
				Entities.Add(NewEntity);
			}
		}

		public virtual void RemoveEntity(EntityType EntityToRemove)
		{
			for(int CurrentIndex = 0; CurrentIndex < Entities.Count; ++CurrentIndex)
			{
				EntityType CurrentEntity = Entities[CurrentIndex];

				if(CurrentEntity.GetFilename() == EntityToRemove.GetFilename())
				{
					Entities.RemoveAt(CurrentIndex);

					break;
				}
			}
		}

		public virtual List<EntityType> EditorGetEntityList()
		{
			return Entities;
		}

		public virtual string EditorGetUniqueEntityFilename(string OriginalFilename)
		{
			string BaseFilePath = GetDefaultEntityPath();
			// The XML we use for some of the metadata on the editor side doesn't like spaces so we need to swap them out
			string TestFile = OriginalFilename.Replace(" ", "_");
			int CurrentIndex = 0;

			while(File.Exists(BaseFilePath + TestFile + ".xml"))
			{
				TestFile = OriginalFilename + "-" + (++CurrentIndex);
			}

			return TestFile;
		}
	#endif // UNITY_EDITOR

		protected List<EntityType> Entities = new List<EntityType>();

		public virtual int GetEntityCount()
		{
			return Entities.Count;
		}

		public virtual string GetEntityListFilename()
		{
			return "Assets/Resources/EntityList.xml";
		}

		public virtual string GetDefaultEntityPath()
		{
			return "Assets/Resources/Entities/";
		}

		protected virtual string GetManagerName()
		{
			return "LinkedEntityManager";
		}

		protected virtual string GetEntityListName()
		{
			return "EntityList";
		}

		protected virtual string GetEntityElementName()
		{
			return "LinkedEntityFilename";
		}

		protected virtual void SerializeEntityManager(bool bSaving)
		{
			if(bSaving)
			{
				SerializeListOwnerPrefixFixup();
			}

			LinkedEntityManager<EntityType> Instance = new LinkedEntityManager<EntityType>();
			XMLSerializable.SerializeFromXML<LinkedEntityManager<EntityType>>(GetEntityListFilename(), ref Instance, bSaving);
		}

		public override void SerializeListOwnerPrefixFixup()
		{
			base.SerializeListOwnerPrefixFixup();

			ListFixup<EntityType>(ref StartingEntities, this, "Input", XMLSerializable.LinkType.LINK_StartLink);
			ListFixup<EntityType>(ref EndingEntities, this, "Output", XMLSerializable.LinkType.LINK_EndLink);

			for(int CurrentEntity = 0; CurrentEntity < Entities.Count; ++CurrentEntity)
			{
				Entities[CurrentEntity].SerializeListOwnerPrefixFixup();
			}
		}

		public override void SerializeXML()
		{
			base.SerializeXML();
			SerializeBegin(GetManagerName());

			SerializeEntityList();

			SerializeBeginEndNodes();
		}

		public virtual void SerializeEntityList()
		{
			SerializeStringList<EntityType>(GetEntityListName(), GetEntityElementName(), EntityToFilename, ref Entities);
		}

		public virtual void SerializeBeginEndNodes()
		{
			EntityLink<EntityType>.SerializingLinkType = XMLSerializable.LinkType.LINK_StartLink;
			SerializeListEmbedded<EntityLink<EntityType>>("StartNodes", "StartNode", ref StartingEntities);
			EntityLink<EntityType>.SerializingLinkType = XMLSerializable.LinkType.LINK_EndLink;
			SerializeListEmbedded<EntityLink<EntityType>>("EndNodes", "EndNode", ref EndingEntities);
			EntityLink<EntityType>.SerializingLinkType = XMLSerializable.LinkType.LINK_NormalLink;
		}

		public virtual void CreateAndAddNewStartEndNodeConnection(string ConnectionName, XMLSerializable.LinkType NodeType)
		{
			if(NodeType == XMLSerializable.LinkType.LINK_StartLink)
			{
				EntityLink<EntityType> StartLink = new EntityLink<EntityType>();
				StartLink.CurrentLinkType = XMLSerializable.LinkType.LINK_StartLink;
				StartLink.Name = ConnectionName;
				StartingEntities.Add(StartLink);
			}
			else if(NodeType == XMLSerializable.LinkType.LINK_EndLink)
			{
				EntityLink<EntityType> EndLink = new EntityLink<EntityType>();
				EndLink.CurrentLinkType = XMLSerializable.LinkType.LINK_EndLink;
				EndLink.Name = ConnectionName;
				EndingEntities.Add(EndLink);
			}
		}

		public virtual void ReplicateList<OtherType>(ref List<EntityLink<OtherType>> Source, ref List<EntityLink<EntityType>> Destination, XMLSerializable.LinkType ListType)
																															where OtherType : LinkedEntity<OtherType>, new()
		{
			List<EntityLink<EntityType>> NodesToProcess = new List<EntityLink<EntityType>>();

			for(int CurrentLocalNode = 0; CurrentLocalNode < Destination.Count; ++CurrentLocalNode)
			{
				bool bFound = false;

				for(int CurrentNode = 0; CurrentNode < Source.Count; ++CurrentNode)
				{
					if(Source[CurrentNode].Name == Destination[CurrentLocalNode].Name)
					{
						bFound = true;
						break;
					}
				}

				if(!bFound)
				{
					NodesToProcess.Add(Destination[CurrentLocalNode]);
					Destination.RemoveAt(CurrentLocalNode);
					--CurrentLocalNode;
				}
			}

			for(int CurrentNode = 0; CurrentNode < NodesToProcess.Count; ++CurrentNode)
			{
				BreakLinksToLink(NodesToProcess[CurrentNode]);
			}

			for(int CurrentNode = 0; CurrentNode < Source.Count; ++CurrentNode)
			{
				bool bFound = false;

				for(int CurrentLocalNode = 0; CurrentLocalNode < Destination.Count; ++CurrentLocalNode)
				{
					if(Destination[CurrentLocalNode].Name == Source[CurrentNode].Name)
					{
						bFound = true;
						break;
					}
				}

				if(!bFound)
				{
					CreateAndAddNewStartEndNodeConnection(Source[CurrentNode].Name, ListType);
				}
			}
		}

		public virtual void BreakLinksToLink(EntityLink<EntityType> SourceLink)
		{
			for(int CurrentRemoteLink = 0; CurrentRemoteLink < SourceLink.LinkedEntities.Count; ++CurrentRemoteLink)
			{
				SourceLink.LinkedEntities[CurrentRemoteLink].BreakLink(SourceLink);
			}
		}

		public override void CreateStaticNodesIfNotPresent()
		{
			base.CreateStaticNodesIfNotPresent();
		}

		public virtual void EntityToFilename(ref EntityType SourceEntity, ref string SavedFilename)
		{
			if(SourceEntity != null)
			{
				SavedFilename = SourceEntity.GetEntityName() + ":=:" + SourceEntity.GetFilename();
			}
			else if(SavedFilename != null)
			{
				string[] Delimiters = { ":=:" };
				string[] NameTypeString = SavedFilename.Split(Delimiters, System.StringSplitOptions.None);
				string TypeString = NameTypeString[0];
				string NameString = NameTypeString[1];

				CreateOrUpdateEntityFromFilename(NameString, ref Entities, TypeUtils.GetNewObjectOfTypeString(TypeString), TypeUtils.GetXMLSerializerForTypeString(TypeString));
			}
		}

		protected virtual void CreateOrUpdateEntityFromFilename(string EntityFilename, ref List<EntityType> ListToConvert, object NewObject, XmlSerializer NewSerializer)
		{
			for(int CurrentEntityIndex = 0; CurrentEntityIndex < ListToConvert.Count; ++CurrentEntityIndex)
			{
				EntityType CurrentEntity = ListToConvert[CurrentEntityIndex];
				if(CurrentEntity.GetFilename() == EntityFilename)
				{
					EntityType SerializedEntity = (EntityType)NewObject;

					if(SerializedEntity != null)
					{
						SerializeEntity(EntityFilename, ref SerializedEntity, false, NewSerializer);
	#if UNITY_EDITOR
						ListToConvert[CurrentEntityIndex].EditorUpdateDataFrom(SerializedEntity);
	#endif // UNITY_EDITOR
					}

					return;
				}
			}

			EntityType NewEntity = (EntityType)NewObject;

			if(NewEntity != null)
			{
				SerializeEntity(EntityFilename, ref NewEntity, false, NewSerializer);
				ListToConvert.Add(NewEntity);
			}
		}

		protected virtual void SerializeAllEntities(bool bSaving)
		{
			if(bSaving)
			{
				for(int CurrentEntity = 0; CurrentEntity < Entities.Count; ++CurrentEntity)
				{
					EntityType CurrentCopy = Entities[CurrentEntity];
					SerializeEntity(CurrentCopy.GetFilename(), ref CurrentCopy, true, TypeUtils.GetXMLSerializerForTypeString(CurrentCopy.GetEntityName()));
				}
			}
		}

		protected virtual void SerializeEntity(string EntityFilename, ref EntityType ToSerialize, bool bSaving, XmlSerializer Serializer)
		{
			XMLSerializable.SerializeFromXML<EntityType>(GetDefaultEntityPath() + EntityFilename + ".xml", ref ToSerialize, bSaving, Serializer);
		}

		public virtual EntityType GetEntityByFileName(string FileName)
		{
			foreach(EntityType CurrentEntity in Entities)
			{
				if(CurrentEntity.GetFilename() == FileName)
				{
					return CurrentEntity;
				}
			}

			return null;
		}

		public override void PostSerialize()
		{
			base.PostSerialize();

			if(bReading)
			{
				SerializeListOwnerPrefixFixup();

				foreach(EntityType CurrentEntity in Entities)
				{
					CurrentEntity.FixupLinks();
				}
			}
		}

		public virtual void FixupStartEndLink(EntityLink<EntityType> SourceLink, string DestLinkFilename, string DestLinkName, XMLSerializable.LinkType TypeName)
		{
			EntityType DestEntity = GetEntityByFileName(DestLinkFilename);

			if(DestEntity != null)
			{
				EntityLink<EntityType> DestinationLink = ((EntityType)DestEntity).GetLinkByName(DestLinkName);

				if(DestinationLink != null)
				{
					SourceLink.EstablishLink(DestinationLink);
					DestinationLink.EstablishLink(SourceLink);
				}
			}
			else
			{
				string InvertLinkType = (DestLinkName.StartsWith("Input") ? DestLinkName.Replace("Input", "Output") : DestLinkName.Replace("Output", "Input"));

				EntityLink<EntityType> DestinationLink = GetLinkByName(InvertLinkType);

				if(DestinationLink != null)
				{
					SourceLink.EstablishLink(DestinationLink);
					DestinationLink.EstablishLink(SourceLink);
				}
			}
		}

		public virtual EntityLink<EntityType> GetLinkByName(string LinkName)
		{
			if(LinkName.StartsWith("Input"))
			{
				string LookupName = LinkName.Substring(5);
				foreach(EntityLink<EntityType> CurrentLink in EndingEntities)
				{
					if(CurrentLink.Name == LookupName)
					{
						return CurrentLink;
					}
				}
			}
			else if(LinkName.StartsWith("Output"))
			{
				string LookupName = LinkName.Substring(6);
				foreach(EntityLink<EntityType> CurrentLink in StartingEntities)
				{
					if(CurrentLink.Name == LookupName)
					{
						return CurrentLink;
					}
				}
			}

			return null;
		}
	}
}

#endif // IGOR_RUNTIME || UNITY_EDITOR


text:
$ErrorActionPreference = 'Stop'

$packageArgs = @{
  packageName            = 'freevideoeditor'
  fileType               = 'exe'
  url                    = 'http://downloads.videosoftdev.com/video_tools/video_editor.exe'
  checksum               = '8b9e05110e0d75cae069d46e734d7dd885688ca7419313eb3cd525b11a70a121'
  checksumType           = 'sha256'
  silentArgs             = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART'
  validExitCodes         = @(0)
  softwareName           = 'VSDC Free Video Editor*'
}
Install-ChocolateyPackage @packageArgs


text:
package com.porterhead.exception;

import com.porterhead.api.ErrorResponse;

/**
 * Created by iainporter on 06/11/2014.
 */
public class BadClientCredentialsException extends ErrorResponse {

    public BadClientCredentialsException(String errorMessage) {
        super("401", "Client Credentials were incorrect", "Client Credentials were incorrect. Useage: Base64Encode(username:password) ");
    }
}


text:
import { isFunction, isObject } from './utils';

// Based heavily on Ember's DSL
// To keep it simple each nested level of the router is only aware of its own nested level
// ie. naming and redirects can only be used relative to the current level and no wildcards are allowed
// It is up to the application to ask for more complicated navigation
// Each Route options object must have a path and either tag or a redirect method defined
// Helpers index and notFound default the path and names, and only take options or redirect function directly
export default class RouterDSL {
  constructor(parent) {
    this.fullName = this.fullName.bind(this);
    // adds routes
    this.route = this.route.bind(this);
    this.addRoute = this.addRoute.bind(this);
    this.generateFn = this.generateFn.bind(this);
    this.parent = parent;
    this.matches = [];
    this.explicitIndex = false;
  }

  fullName(name) {
    if (!this.parent) return name;
    return this.parent + "." + name;
  }

  route(name, options = {}, callback) {
    var dsl;
    if (!callback) {
      // no children
      return this.addRoute(name, options);
    }
    dsl = new RouterDSL(this.fullName(name));
    callback.call(dsl, dsl);
    return this.addRoute(name, options, dsl.generateFn());
  }

  // adds index for nested levels
  index(options, callback) {
    // redirect with dynamic args, no callback possible
    if (isFunction(options)) {
      return this.addRoute('index', { path: '/', redirect: options });
    }
    // index route
    if (isObject(options)) {
      return this.route('index', Object.assign({}, options, { path: '/' }), callback);
    }
  }

  // adds handler for not found route
  notFound(options) {
    // redirect with dynamic args, no callback possible
    if (isFunction(options)) {
      return this.addRoute('not_found', { path: '/not-found', redirect: options });
    }
    // index route
    if (isObject(options)) {
      return this.route('not_found', Object.assign({}, options, { path: '/not-found' }));
    }
  }

  addRoute(name, options, callback) {
    var handler, handlerOptions, ref;
    handlerOptions = Object.assign({}, options);
    delete handlerOptions.path;
    handler = Object.assign({ name: this.fullName(name) }, handlerOptions);
    if (((ref = options.path) === '/' || ref === '') || name.slice(-5) === 'index') {
      this.explicitIndex = true;
    }
    return this.matches.push([options.path || `/${name.replace(/_/g, '-')}`, handler, callback]);
  }

  generateFn() {
    if (!this.explicitIndex) {
      // add empty index
      this.index({});
    }
    return (match) => {
      var dslMatch;
      for (let i = 0, len = this.matches.length; i < len; i++) {
        dslMatch = this.matches[i];
        match(dslMatch[0]).to(dslMatch[1], dslMatch[2]);
      }
    };
  }

  static map(callback) {
    var dsl;
    dsl = new RouterDSL();
    callback.call(dsl, dsl);
    return dsl;
  }

};


text:
<?php
/*
 * Example 16 - How to create a regular subscription.
 */

try
{
	/*
	 * Initialize the Mollie API library with your API key or OAuth access token.
	 */
	include "initialize.php";

	/*
	 * Determine the url parts to these example files.
	 */
	$protocol = isset($_SERVER['HTTPS']) && strcasecmp('off', $_SERVER['HTTPS']) !== 0 ? "https" : "http";
	$hostname = $_SERVER['HTTP_HOST'];
	$path     = dirname(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF']);

	/**
	 * Retrieve the last created customer for this example.
	 * If no customers are created yet, run example 11.
	 */
	$customer = $mollie->customers->all(0, 1)->data[0];

	/*
	 * Generate a unique subscription id for this example. It is important to include this unique attribute
	 * in the webhookUrl (below) so new payments can be associated with this subscription.
	 */
	$my_subscription = time();

	/*
	 * Customer Subscription creation parameters.
	 *
	 * See: https://www.mollie.com/nl/docs/reference/subscriptions/create
	 */
	$subscription = $mollie->customers_subscriptions->with($customer)->create(array(
		"amount"      => 10.00,
		"times"       => 12,
		"interval"    => "1 month",
		"description" => "My subscription",
		"method"      => NULL,
		"webhookUrl"  => "https://example.org/subscription-payment-webhook/$my_subscription",
	));

	/*
	 * The subscription will be either pending or active depending on whether the customer has
	 * a pending or valid mandate. If the customer has no mandates an error is returned. You
	 * should then set up a "first payment" for the customer (example 14).
	 */

	echo "
The subscription status is '" . htmlspecialchars($subscription->status) . "'.
\n";
	echo "
";
	echo 'id.'">18-cancel-subscription
';
	echo "
";
}
catch (Mollie_API_Exception $e)
{
	echo "API call failed: " . htmlspecialchars($e->getMessage());
}


text:
package com.intellij.android.designer.designSurface.layout.caption;

import com.intellij.android.designer.designSurface.layout.AbstractFlowBaseOperation;
import com.intellij.android.designer.model.RadViewComponent;
import com.intellij.designer.designSurface.EditableArea;
import com.intellij.designer.designSurface.FeedbackLayer;
import com.intellij.designer.designSurface.OperationContext;
import com.intellij.designer.designSurface.feedbacks.LineInsertFeedback;
import com.intellij.designer.model.RadComponent;
import com.intellij.ui.JBColor;

import javax.swing.*;
import java.awt.*;
import java.util.List;

/**
 * @author Alexander Lobas
 */
public abstract class VerticalCaptionFlowBaseOperation<T extends RadViewComponent> extends AbstractFlowBaseOperation {
  protected final T myMainContainer;
  private final EditableArea myMainArea;
  private LineInsertFeedback myMainInsertFeedback;
  private int myMainXLocation;

  public VerticalCaptionFlowBaseOperation(T mainContainer,
                                          RadComponent container,
                                          OperationContext context,
                                          EditableArea mainArea) {
    super(container, context, false);
    myMainContainer = mainContainer;
    myMainArea = mainArea;
  }

  @Override
  protected void createFeedback() {
    super.createFeedback();

    if (myMainInsertFeedback == null) {
      FeedbackLayer layer = myMainArea.getFeedbackLayer();

      Rectangle bounds = myMainContainer.getBounds(layer);
      myMainXLocation = bounds.x;

      myMainInsertFeedback = new LineInsertFeedback(JBColor.GREEN, true);
      myMainInsertFeedback.size(getMainFeedbackWidth(layer, myMainXLocation), 0);

      layer.add(myMainInsertFeedback);
      layer.repaint();
    }
  }

  protected int getMainFeedbackWidth(FeedbackLayer layer, int mainXLocation) {
    List<RadComponent> children = myMainContainer.getChildren();
    Rectangle lastChildBounds = children.get(children.size() - 1).getBounds(layer);
    return lastChildBounds.x + lastChildBounds.width - mainXLocation;
  }

  @Override
  public void showFeedback() {
    super.showFeedback();
    Point location = SwingUtilities.convertPoint(myInsertFeedback.getParent(),
                                                 myInsertFeedback.getLocation(),
                                                 myMainArea.getFeedbackLayer());
    myMainInsertFeedback.setLocation(myMainXLocation, location.y);
  }

  @Override
  public void eraseFeedback() {
    super.eraseFeedback();
    if (myMainInsertFeedback != null) {
      FeedbackLayer layer = myMainArea.getFeedbackLayer();
      layer.remove(myMainInsertFeedback);
      layer.repaint();
      myMainInsertFeedback = null;
    }
  }
}


text:
import { schema } from 'normalizr';

const tacticSchema = new schema.Entity('tactics');

export default tacticSchema;


text:
<?php
# MantisBT - A PHP based bugtracking system

# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MantisBT.  If not, see <http://www.gnu.org/licenses/>.

require_api( 'authentication_api.php' );
require_api( 'constant_inc.php' );
require_api( 'database_api.php' );
require_api( 'error_api.php' );
require_api( 'helper_api.php' );
require_api( 'lang_api.php' );
require_api( 'user_api.php' );
require_api( 'utility_api.php' );

/**
 * Create a new profile for the user, return the ID of the new profile
 * @param integer $p_user_id     A valid user identifier.
 * @param string  $p_platform    Value for profile platform.
 * @param string  $p_os          Value for profile operating system.
 * @param string  $p_os_build    Value for profile operation system build.
 * @param string  $p_description Description of profile.
 * @return integer
 */
function profile_create( $p_user_id, $p_platform, $p_os, $p_os_build, $p_description ) {
	$p_user_id = (int)$p_user_id;

	if( ALL_USERS != $p_user_id ) {
		user_ensure_unprotected( $p_user_id );
	}

	# platform cannot be blank
	if( is_blank( $p_platform ) ) {
		error_parameters( lang_get( 'platform' ) );
		trigger_error( ERROR_EMPTY_FIELD, ERROR );
	}

	# os cannot be blank
	if( is_blank( $p_os ) ) {
		error_parameters( lang_get( 'os' ) );
		trigger_error( ERROR_EMPTY_FIELD, ERROR );
	}

	# os_build cannot be blank
	if( is_blank( $p_os_build ) ) {
		error_parameters( lang_get( 'version' ) );
		trigger_error( ERROR_EMPTY_FIELD, ERROR );
	}

	# Add profile
	db_param_push();
	$t_query = 'INSERT INTO {user_profile}
				    ( user_id, platform, os, os_build, description )
				  VALUES
				    ( ' . db_param() . ', ' . db_param() . ', ' . db_param() . ', ' . db_param() . ', ' . db_param() . ' )';
	db_query( $t_query, array( $p_user_id, $p_platform, $p_os, $p_os_build, $p_description ) );

	return db_insert_id( db_get_table( 'user_profile' ) );
}

/**
 * Delete a profile for the user
 *
 * Note that although profile IDs are currently globally unique, the existing
 * code included the user_id in the query and I have chosen to keep that for
 * this API as it hides the details of id implementation from users of the API
 * @param integer $p_user_id    A valid user identifier.
 * @param integer $p_profile_id A profile identifier.
 * @return void
 */
function profile_delete( $p_user_id, $p_profile_id ) {
	if( ALL_USERS != $p_user_id ) {
		user_ensure_unprotected( $p_user_id );
	}

	# Delete the profile
	db_param_push();
	$t_query = 'DELETE FROM {user_profile} WHERE id=' . db_param() . ' AND user_id=' . db_param();
	db_query( $t_query, array( $p_profile_id, $p_user_id ) );
}

/**
 * Update a profile for the user
 * @param integer $p_user_id     A valid user identifier.
 * @param integer $p_profile_id  A profile identifier.
 * @param string  $p_platform    Value for profile platform.
 * @param string  $p_os          Value for profile operating system.
 * @param string  $p_os_build    Value for profile operation system build.
 * @param string  $p_description Description of profile.
 * @return void
 */
function profile_update( $p_user_id, $p_profile_id, $p_platform, $p_os, $p_os_build, $p_description ) {
	if( ALL_USERS != $p_user_id ) {
		user_ensure_unprotected( $p_user_id );
	}

	# platform cannot be blank
	if( is_blank( $p_platform ) ) {
		error_parameters( lang_get( 'platform' ) );
		trigger_error( ERROR_EMPTY_FIELD, ERROR );
	}

	# os cannot be blank
	if( is_blank( $p_os ) ) {
		error_parameters( lang_get( 'os' ) );
		trigger_error( ERROR_EMPTY_FIELD, ERROR );
	}

	# os_build cannot be blank
	if( is_blank( $p_os_build ) ) {
		error_parameters( lang_get( 'version' ) );
		trigger_error( ERROR_EMPTY_FIELD, ERROR );
	}

	# Add item
	db_param_push();
	$t_query = 'UPDATE {user_profile}
				  SET platform=' . db_param() . ',
				  	  os=' . db_param() . ',
					  os_build=' . db_param() . ',
					  description=' . db_param() . '
				  WHERE id=' . db_param() . ' AND user_id=' . db_param();
	db_query( $t_query, array( $p_platform, $p_os, $p_os_build, $p_description, $p_profile_id, $p_user_id ) );
}

/**
 * Return a profile row from the database
 * @param integer $p_user_id    A valid user identifier.
 * @param integer $p_profile_id A profile identifier.
 * @return array
 */
function profile_get_row( $p_user_id, $p_profile_id ) {
	db_param_push();
	$t_query = 'SELECT * FROM {user_profile} WHERE id=' . db_param() . ' AND user_id=' . db_param();
	$t_result = db_query( $t_query, array( $p_profile_id, $p_user_id ) );

	return db_fetch_array( $t_result );
}

/**
 * Return a profile row from the database
 * @param integer $p_profile_id A profile identifier.
 * @return array
 * @todo relationship of this function to profile_get_row?
 */
function profile_get_row_direct( $p_profile_id ) {
	db_param_push();
	$t_query = 'SELECT * FROM {user_profile} WHERE id=' . db_param();
	$t_result = db_query( $t_query, array( $p_profile_id ) );

	return db_fetch_array( $t_result );
}

/**
 * Return an array containing all rows for a given user
 * @param integer $p_user_id   A valid user identifier.
 * @param boolean $p_all_users Include profiles for all users.
 * @return array
 */
function profile_get_all_rows( $p_user_id, $p_all_users = false ) {
	db_param_push();
	$t_query_where = 'user_id = ' . db_param();
	$t_param[] = (int)$p_user_id;

	if( $p_all_users && ALL_USERS != $p_user_id ) {
		$t_query_where .= ' OR user_id = ' . db_param();
		$t_param[] = ALL_USERS;
	}

	$t_query = 'SELECT * FROM {user_profile} WHERE ' . $t_query_where . ' ORDER BY platform, os, os_build';
	$t_result = db_query( $t_query, $t_param );

	$t_rows = array();

	while( $t_row = db_fetch_array( $t_result ) ) {
		array_push( $t_rows, $t_row );
	}

	return $t_rows;
}

/**
 * Return an array containing all profiles for a given user,
 * including global profiles
 * @param integer $p_user_id A valid user identifier.
 * @return array
 */
function profile_get_all_for_user( $p_user_id ) {
	return profile_get_all_rows( $p_user_id, $p_user_id != ALL_USERS );
}

/**
 * Return an array of strings containing unique values for the specified field based
 * on private and public profiles accessible to the specified user.
 * @param string  $p_field   Field name of the profile to retrieve.
 * @param integer $p_user_id A valid user identifier.
 * @return array
 */
function profile_get_field_all_for_user( $p_field, $p_user_id = null ) {
	$c_user_id = ( $p_user_id === null ) ? auth_get_current_user_id() : $p_user_id;

	switch( $p_field ) {
		case 'id':
		case 'user_id':
		case 'platform':
		case 'os':
		case 'os_build':
		case 'description':
			$c_field = $p_field;
			break;
		default:
			trigger_error( ERROR_GENERIC, ERROR );
	}

	db_param_push();
	$t_query = 'SELECT DISTINCT ' . $c_field . '
				  FROM {user_profile}
				  WHERE ( user_id=' . db_param() . ' ) OR ( user_id = 0 )
				  ORDER BY ' . $c_field;
	$t_result = db_query( $t_query, array( $c_user_id ) );

	$t_rows = array();

	while( $t_row = db_fetch_array( $t_result ) ) {
		array_push( $t_rows, $t_row[$c_field] );
	}

	return $t_rows;
}

/**
 * Return an array containing all profiles used in a given project
 * @param integer $p_project_id A valid project identifier.
 * @return array
 */
function profile_get_all_for_project( $p_project_id ) {
	$t_project_where = helper_project_specific_where( $p_project_id );

	$t_query = 'SELECT DISTINCT(up.id), up.user_id, up.platform, up.os, up.os_build
				  FROM {user_profile} up, {bug} b
				  WHERE ' . $t_project_where . '
				  AND up.id = b.profile_id
				  ORDER BY up.platform, up.os, up.os_build';
	$t_result = db_query( $t_query );

	$t_rows = array();

	while( $t_row = db_fetch_array( $t_result ) ) {
		array_push( $t_rows, $t_row );
	}

	return $t_rows;
}

/**
 * Returns the default profile
 * @param integer $p_user_id A valid user identifier.
 * @return string
 */
function profile_get_default( $p_user_id ) {
	db_param_push();
	$t_query = 'SELECT default_profile FROM {user_pref} WHERE user_id=' . db_param();
	$t_result = db_query( $t_query, array( $p_user_id ) );

	$t_default_profile = (int)db_result( $t_result, 0, 0 );

	return $t_default_profile;
}

/**
 * Returns whether the specified profile is global
 * @param integer $p_profile_id A valid profile identifier.
 * @return boolean
 */
function profile_is_global( $p_profile_id ) {
	$t_row = profile_get_row( ALL_USERS, $p_profile_id );
	return( $t_row !== false );
}


text:
var EventEmitter = require('events').EventEmitter,
    util = require('util'),
    VarnishClient = require('./varnish_client');

// @param opts extrac configurations:
//    max_queue - max number of items in queue, defaults to 2000
//                new items will be discarded
//    max_recon_retries - max number of reconnection attempts
//                        defaults to 120
//    recon_interval_ms - interval in milliseconds between
//                        reconnection attempts. Defaults to 1000.
//
function VarnishQueue(host, port, secret, opts) {
    var self = this;
    var queue = [];
    var ready = false;
    var reconnectTimer = null;
    var reconnectTries = 0;
    opts = opts || {};
    if ( ! opts.hasOwnProperty('max_queue') ) opts.max_queue = 2000;
    if ( ! opts.hasOwnProperty('max_recon_retries') ) opts.max_recon_retries = 120;
    if ( ! opts.hasOwnProperty('recon_interval_ms') ) opts.recon_interval_ms = 1000;

    var MAX_QUEUE = opts.max_queue;
    var MAX_RECONNECT_TRIES = opts.max_recon_retries;
    var RECONNECT_INTERVAL = opts.recon_interval_ms;

    var client = new VarnishClient(host, port, secret);

    self.debug = false;

    function log() {
        self.debug && console.log.apply(console, arguments);
    }

    // attach a dummy callback to error event to avoid nodejs throws an exception and closes the process
    self.on('error', function(e) {
        log("error", e);
    });

    client.on('connect', function() {
        clearInterval(reconnectTimer);
        reconnectTries = 0;
    });

    client.on('ready', function() {
        ready = true;
        log('sending pending');
        _send_pending();
    });

    function reconnect() {
        ready = false;
        clearInterval(reconnectTimer);
        reconnectTimer = setInterval(function() {
            client.connect();
            ++reconnectTries;
            if(reconnectTries >= MAX_RECONNECT_TRIES) {
                var err = new Error('max reconnect tries, aborting');
                err.code = 'ABORT_RECONNECT';
                self.emit('error', err);
                clearInterval(reconnectTimer);
            }
        }, RECONNECT_INTERVAL);
    }
    client.on('close', reconnect);
    client.on('error', function(err) {
      console.log("Varnish connection error: " + err);
      reconnect();
    });

    function _send_pending(empty_callback) {
        if(!ready) return;
        var c = queue.pop();
        if(!c) return;
        client.run_cmd(c, function() {
            if(queue.length > 0) {
                process.nextTick(_send_pending);
            } else {
                if(empty_callback) {
                    empty_callback();
                }
                self.emit('empty');
            }
        });
    }

    self.run_cmd = function(cmd, nodup) {
        if ( nodup && queue.indexOf(cmd) != -1 ) {
          log("skip duplicated varnish command in queue: " + cmd);
          return;
        }
        queue.push(cmd);
        if(queue.length > MAX_QUEUE) {
            console.log("varnish command queue too long, removing commands");
            var err = new Error("varnish command queue too long, removing commands");
            err.code = 'TOO_LONG';
            self.emit('error', err);
            queue.pop();
        }
        if(ready) {
            _send_pending();
        }
    };

    self.end = function() {
        _send_pending(function() {
            client.close();
        });
    };
}

util.inherits(VarnishQueue, EventEmitter);

module.exports = VarnishQueue;


text:
from flask.ext.wtf import Form
from wtforms import TextField, TextAreaField, SubmitField, PasswordField
from wtforms.validators import DataRequired

class ContactForm(Form):
	response_form = TextField("Form")
	response_content = TextField("Content")
	submit = SubmitField("Send")

class Submission(Form):
	submit = SubmitField("Submit")

class LoginForm(Form):
    """Form class for user login."""
    email = TextField('email', validators=[DataRequired()])
    password = PasswordField('password', validators=[DataRequired()])
   # remember_me = BooleanField('Remember me', default = False)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

  <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />

  <title>BBCodeizer</title>

  <link type="text/css" media="screen" href="rdoc.css" rel="stylesheet" />

BBCodeizer

This is the API documentation for 'BBCodeizer'.

Files

README

Classes/Modules

BBCodeizeHelper

Bbcodeizer

Methods

#bbcodeize — BBCodeizeHelper

[Validate]

Generated with the Darkfish
      Rdoc Generator 2.


text:
require 'reel'

$:.unshift ::File.expand_path('../../../lib', __FILE__)
require 'e'

class Chat < E
  map :/
  Users = []

  def index
    render
  end

  def chat user
    render
  end

  def login user
    event_stream do |stream|
      Users.each {|u| u.event('welcome'); u.data(user)}
      Users << stream
      stream.on_error { Users.delete stream }
    end
  end

  def post_message user
    msg = render_p(:message)
    Users.each { |u| u.data msg }
    msg
  end

end

Chat.run server: :Reel


text:
using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("OxyPlot.Xamarin.Android")]
[assembly: AssemblyDescription("OxyPlot for Xamarin.Android")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("OxyPlot")]
[assembly: AssemblyProduct("OxyPlot")]
[assembly: AssemblyCopyright("Copyright (c) 2014 OxyPlot contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The version numbers are updated by the build script. See ~/appveyor.yml
[assembly: AssemblyVersion("0.0.1")]
[assembly: AssemblyInformationalVersion("0.0.1-alpha")]
[assembly: AssemblyFileVersion("0.0.1")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]


text:
package io.github.marcelbraghetto.dailydeviations.features.application;

import android.app.Activity;
import android.app.Application;
import android.support.annotation.NonNull;
import android.webkit.WebView;

import javax.inject.Inject;

import io.github.marcelbraghetto.dailydeviations.features.application.logic.MainAppLogic;
import io.github.marcelbraghetto.dailydeviations.framework.foundation.dagger.AppComponent;
import io.github.marcelbraghetto.dailydeviations.framework.foundation.dagger.AppDaggerModule;
import io.github.marcelbraghetto.dailydeviations.framework.foundation.dagger.DaggerAppComponent;
import io.github.marcelbraghetto.dailydeviations.framework.foundation.utils.BasicActivityLifecycleCallbacks;

/**
 * Created by Marcel Braghetto on 24/02/16.
 */
public class MainApp extends Application {
    private static MainApp sSelf;
    private AppComponent mAppComponent;
    @Inject MainAppLogic mLogic;

    @Override
    public void onCreate() {
        super.onCreate();
        sSelf = this;
        mAppComponent = buildDaggerComponent();
        getDagger().inject(this);
        mLogic.begin();

        registerActivityLifecycleCallbacks(new BasicActivityLifecycleCallbacks() {
            @Override
            public void onActivityStarted(Activity activity) {
                mLogic.activityStarted();
            }

            @Override
            public void onActivityStopped(Activity activity) {
                mLogic.activityStopped();
            }
        });

        warmupWebView();
    }

    /**
     * From Lollipop onward, constructing a WebView is very expensive the first time
     * so we are going to warm it up here before the user might try to open something
     * needing a web view and be presented with a jarring main thread freeze.
     */
    private void warmupWebView() {
        new WebView(getApplicationContext());
    }

    @NonNull
    protected AppComponent buildDaggerComponent() {
        return DaggerAppComponent
                .builder()
                .appDaggerModule(new AppDaggerModule(this))
                .build();
    }

    @NonNull
    public static AppComponent getDagger() {
        return sSelf.mAppComponent;
    }
}


text:
package br.ufes.inf.lprm.scene.test.temporal.model.event;

import br.ufes.inf.lprm.scene.test.temporal.model.TemporalEntity;
import org.kie.api.definition.type.Duration;
import org.kie.api.definition.type.Role;
import org.kie.api.definition.type.Timestamp;

import java.io.Serializable;

@Role(Role.Type.EVENT)
@Timestamp("start")
@Duration("duration")
public class Event implements Serializable, TemporalEntity {

    private static final long serialVersionUID = 1L;
    private long start;
    private long duration;
    private boolean finished;
    private String id;

    public Event(String id, long start, long duration) {
        this.id = id;
        this.start = start;
        this.duration = duration;
    }

    public long getStart() {
        return start;
    }

    public long getDuration() {
        return duration;
    }

    public String getId() {
        return id;
    }

    public boolean isFinished() {
        return finished;
    }

    public Event setFinished(boolean finished) {
        this.finished = finished;
        return this;
    }

    public long getEnd() {
        return start + duration;
    }

    @Override
    public TemporalEntity.Type getTemporalType() {
        return Type.EVENT;
    }
}


text:
package org.apache.pulsar.common.policies.data;

/**
 * Inactive topic deletion mode.
 */
public enum InactiveTopicDeleteMode {

    /**
     * The topic can be deleted when no subscriptions and no active producers.
     */
    delete_when_no_subscriptions,

    /**
     * The topic can be deleted when all subscriptions catchup and no active producers/consumers.
     */
    delete_when_subscriptions_caught_up
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using AmmySidekick;

namespace Ammy.Test.Workbench
{
  public partial class App : Application
  {
    [STAThread]
    public static void Main()
    {
      App app = new App();
      app.InitializeComponent();

      RuntimeUpdateHandler.Register(app, "/" + AmmySidekick.Ammy.GetAssemblyName(app) + ";component/App.g.xaml");

      app.Run();
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace TinyNavigationHelper.Abstraction
{
    public static class ParameterSetter
    {
        public static bool CanSet(Type type)
        {
            try
            {
                var property = type.GetRuntimeProperty("NavigationParameter");

                if (property != null)
                {
                    return true;
                }
            }
            catch (Exception)
            {
            }

            return false;
        }

        public static void Set(object view, object parameter)
        {
            try
            {
                var property = view.GetType().GetRuntimeProperty("NavigationParameter");

                if(property != null)
                {
                    property.SetValue(view, parameter);
                }
            }
            catch (Exception)
            {

            }

        }
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <TextView
            android:id="@+id/main_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="20dp"
            android:text="@string/textview"/>

    <!-- This nested layout contains views of its own -->
    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

        <!-- Set OnClickListener
            to trigger results when pressed -->
        <Button
                android:id="@+id/main_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:layout_marginLeft="20dp"
                android:text="@string/button" />

        <!-- Shows an image from your drawable resources -->
        <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:layout_marginLeft="20dp"
                android:src="@drawable/ic_launcher" />

        <!-- Closing tag for the horizontal nested layout -->
    </LinearLayout>

    <!-- Displays keyboard when touched -->
    <EditText
            android:id="@+id/main_edittext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="20dp"
            android:hint="@string/hint" />

    <!-- List whose dataset is defined in code with an adapter -->
    <ListView
            android:id="@+id/main_listview"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_marginTop="20dp" />
</LinearLayout>


text:
package org.apache.commons.scxml2;

import java.io.Serializable;

/**
 * Implementation of the SCXML specification required In() builtin predicate.
 */
public class Builtin implements Serializable {

    /**
     * Serial version UID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * Implements the In() predicate for SCXML documents. The method
     * name chosen is different since "in" is a reserved token
     * in some expression languages.
     *
     * Simple ID based comparator, assumes IDs are unique.
     *
     * @param ctx variable context
     * @param state The State ID to compare with
     * @return Whether this State is current active
     */
    @SuppressWarnings("unchecked")
    public static boolean isMember(final Context ctx, final String state) {
        return ((Status)ctx.getSystemContext().getPlatformVariables().get(SCXMLSystemContext.STATUS_KEY)).isInState(state);
    }
}


text:
pub const HEADER: &'static str = r#"
    extern crate mock_me_test_context;
    let _mock_me_test_context_instance = mock_me_test_context::get_test_context();
"#;

#[derive(Debug, PartialEq)]
pub struct InjectMatch {
    pub identifier: String,
    pub function_to_mock: String,
}

#[derive(Debug, PartialEq)]
pub struct MockMatch {
    pub identifier: String,
    pub function_to_mock: String,
    pub function_signature: String
}

pub fn get_inject_matches(attr_str: &str) -> Vec<InjectMatch> {
    let p = Parser::new(attr_str);
    p.get_inject_matches()
}

pub fn get_mock_matches(attr_str: &str) -> Vec<MockMatch> {
    let p = Parser::new(attr_str);
    p.get_mock_matches()
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn inject_macro_values_should_parse_correctly() {
        let token_string = r#"( id_1 = "db_fake" , id_2 = "other_fake" )"#;

        let inject_matches = get_inject_matches(token_string);
        assert_eq!(inject_matches, vec![
            InjectMatch { identifier: "id_1".to_string(), function_to_mock: "db_fake".to_string() },
            InjectMatch { identifier: "id_2".to_string(), function_to_mock: "other_fake".to_string() },
        ]);
    }

    #[test]
    fn mock_macro_values_should_parse_correctly() {
        let token_string = r#"(
            id_1 = "external_db_call: fn(u32) -> String" , id_2 =
            "other_call: fn() -> String" )"#;

        let mock_matches = get_mock_matches(token_string);
        assert_eq!(mock_matches, vec![
            MockMatch {
                identifier: "id_1".to_string(),
                function_to_mock: "external_db_call".to_string(),
                function_signature: "fn(u32) -> String".to_string()
            },
            MockMatch{
                identifier: "id_2".to_string(),
                function_to_mock: "other_call".to_string(),
                function_signature: "fn() -> String".to_string()
            }
        ]);
    }
}

// inspired in https://limpet.net/mbrubeck/2014/08/11/toy-layout-engine-2.html
struct Parser<'a> {
    pos: usize,
    input: &'a str
}

impl<'a> Parser<'a> {
    fn new(input: &'a str) -> Self {
        Parser { pos: 0, input: input }
    }

    fn get_inject_matches(mut self) -> Vec<InjectMatch> {
        self.execute(Parser::consume_inject_match)
    }

    fn get_mock_matches(mut self) -> Vec<MockMatch> {
        self.execute(Parser::consume_mock_match)
    }

    fn execute<F, R>(&mut self, mut consume_function: F) -> Vec<R> where F: FnMut(&mut Self) -> R {
        let mut result = Vec::new();

        assert_eq!(self.consume_char(), '(');

        loop {
            self.consume_whitespace();

            if self.eof() || self.next_char() == ')' {
                break;
            }

            let item = consume_function(self);
            result.push(item);

            if !self.consume_has_separator() {
                break;
            }
        }

        self.consume_whitespace();
        assert_eq!(self.consume_char(), ')');
        result
    }

    fn consume_has_separator(&mut self) -> bool {
        self.consume_whitespace();

        let mut has_next = false;
        if self.next_char() == ',' {
            has_next = true;
            self.consume_char();
        }

        has_next
    }

    fn consume_inject_match(&mut self) -> InjectMatch {
        let identifier = self.parse_text();

        self.consume_whitespace();
        assert_eq!(self.consume_char(), '=');
        self.consume_whitespace();

        assert_eq!(self.consume_char(), '"');
        let function_to_mock = self.parse_text();
        self.consume_whitespace();
        assert_eq!(self.consume_char(), '"');

        InjectMatch { identifier: identifier, function_to_mock: function_to_mock }
    }

    fn consume_mock_match(&mut self) -> MockMatch {
        let identifier = self.parse_text();

        self.consume_whitespace();
        assert_eq!(self.consume_char(), '=');
        self.consume_whitespace();

        assert_eq!(self.consume_char(), '"');
        let function_to_mock = self.parse_text();
        self.consume_whitespace();
        assert_eq!(self.consume_char(), ':');
        self.consume_whitespace();
        let function_signature = self.consume_while(|c| c != '"');
        assert_eq!(self.consume_char(), '"');

        MockMatch {
            identifier: identifier,
            function_to_mock: function_to_mock,
            function_signature: function_signature
        }
    }

    fn next_char(&self) -> char {
        self.input.as_bytes()[self.pos] as char
    }

    fn eof(&self) -> bool {
        self.pos >= self.input.len()
    }

    fn consume_char(&mut self) -> char {
        let cur_char = self.input.as_bytes()[self.pos];
        self.pos += 1;
        cur_char as char
    }

    fn consume_while<F>(&mut self, test: F) -> String where F: Fn(char) -> bool {
        let mut result = String::new();

        while !self.eof() && test(self.next_char()) {
            result.push(self.consume_char());
        }

        result
    }

    fn consume_whitespace(&mut self) {
        self.consume_while(char::is_whitespace);
    }

    fn parse_text(&mut self) -> String {
        self.consume_while(|c| c.is_alphanumeric() || c == '_')
    }
}


text:
package org.apache.aries.samples.blog.persistence.jpa;

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

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.aries.samples.blog.api.persistence.BlogPersistenceService;
import org.apache.aries.samples.blog.api.persistence.Entry;
import org.apache.aries.samples.blog.persistence.jpa.entity.AuthorImpl;
import org.apache.aries.samples.blog.persistence.jpa.entity.EntryImpl;

/**
 * This class is the implementation of the blogPersistenceService
 */
public class BlogPersistenceServiceImpl implements BlogPersistenceService {

	private EntityManager em;

	public BlogPersistenceServiceImpl() {
	}

	public void setEntityManager(EntityManager e) {
		em = e;
	}

	public void createAuthor(String email, Date dob, String name,
			String displayName, String bio) {
		AuthorImpl a = new AuthorImpl();
		a.setEmail(email);
		a.setName(name);
		a.setDisplayName(displayName);
		a.setBio(bio);
		a.setDob(dob);
		em.persist(a);

	}

	public void createBlogPost(String authorEmail, String title,
			String blogText, List<String> tags) {

		AuthorImpl a = em.find(AuthorImpl.class, authorEmail);
		EntryImpl b = new EntryImpl();

		Date publishDate = new Date(System.currentTimeMillis());

		b.setBlogText(blogText);
		b.setAuthor(a);
		b.setTitle((title == null) ? "" : title);
		b.setPublishDate(publishDate);
		b.setTags((tags == null) ? new ArrayList<String>() : tags);

		a.updateEntries(b);
		em.persist(b);
		em.merge(b.getAuthor());
	}

	public Entry findBlogEntryByTitle(String title) {
		Query q = em
				.createQuery("SELECT e FROM BLOGENTRY e WHERE e.title = ?1");
		q.setParameter(1, title);
		Entry b = (Entry) q.getSingleResult();
		return b;
	}

	public List<AuthorImpl> getAllAuthors() {
		@SuppressWarnings("unchecked")
		List<AuthorImpl> list = em.createQuery("SELECT a FROM AUTHOR a")
				.getResultList();

		return list;
	}

	public List<EntryImpl> getAllBlogEntries() {
		@SuppressWarnings("unchecked")
		List<EntryImpl> list = em.createQuery(
				"SELECT b FROM BLOGENTRY b ORDER BY b.publishDate DESC")
				.getResultList();
		return list;

	}

	public int getNoOfBlogEntries() {
		Number n = (Number) em.createQuery(
				"SELECT COUNT(b) FROM BLOGENTRY b").getSingleResult();
		return n.intValue();
	}

	public List<EntryImpl> getBlogEntries(int firstPostIndex, int noOfPosts) {
		Query q = em
				.createQuery("SELECT b FROM BLOGENTRY b ORDER BY b.publishDate DESC");
		q.setFirstResult(firstPostIndex);
		q.setMaxResults(noOfPosts);

		@SuppressWarnings("unchecked")
		List<EntryImpl> list = q.getResultList();

		return list;
	}

	public AuthorImpl getAuthor(String emailAddress) {
		AuthorImpl a = em.find(AuthorImpl.class, emailAddress);
		return a;
	}

	public List<EntryImpl> getBlogEntriesModifiedBetween(Date start, Date end) {
		Query q = em
				.createQuery("SELECT b FROM BLOGENTRY b WHERE (b.updatedDate >= :start AND b.updatedDate <= :end) OR (b.publishDate >= :start AND b.publishDate <= :end) ORDER BY b.publishDate ASC");
		q.setParameter("start", start);
		q.setParameter("end", end);

		@SuppressWarnings("unchecked")
		List<EntryImpl> list = q.getResultList();

		return list;
	}

	public List<EntryImpl> getBlogsForAuthor(String emailAddress) {

		List<EntryImpl> list = em.find(AuthorImpl.class, emailAddress)
				.getEntries();

		return list;

	}

	public void updateAuthor(String email, Date dob, String name,
			String displayName, String bio) {
		AuthorImpl a = em.find(AuthorImpl.class, email);
		a.setEmail(email);
		a.setName(name);
		a.setDisplayName(displayName);
		a.setBio(bio);
		a.setDob(dob);
		em.merge(a);
	}

	public void updateBlogEntry(long id, String email, String title,
			String blogText, List<String> tags, Date updatedDate) {
		EntryImpl b = em.find(EntryImpl.class, id);
		b.setTitle(title);
		b.setBlogText(blogText);
		b.setTags(tags);
		b.setUpdatedDate(updatedDate);

		em.merge(b);
	}

	public void removeAuthor(String emailAddress) {
		em.remove(em.find(AuthorImpl.class, emailAddress));
	}

	public void removeBlogEntry(long id) {
		EntryImpl b = em.find(EntryImpl.class, id);
		b = em.merge(b);
		b.getAuthor().getEntries().remove(b);

		em.remove(em.merge(b));
		em.merge(b.getAuthor());

	}

	public EntryImpl getBlogEntryById(long postId) {
		EntryImpl b =  em.find(EntryImpl.class, postId);
		return b;
	}

	public void setPublishDate (long postId, Date date) {
		//Added for testing
		EntryImpl b = em.find(EntryImpl.class, postId);
		b.setPublishDate(date);
		em.merge(b);
	}

	public void setUpdatedDate (long postId, Date date) {
		//Added for testing
		EntryImpl b = em.find(EntryImpl.class, postId);
		b.setUpdatedDate(date);
		em.merge(b);
	}
}


text:
import test from 'ava';
import React from 'react';
import { mount, shallow } from 'enzyme';
import asyncComponent from '../src/asyncComponent.js';

const TestComponent = () =>
TEST
;

test('asyncComponent: Test placeholder', t => {
  const Container = asyncComponent(() => Promise.resolve(null), { placeholder: <TestComponent /> });
  const tree = shallow(<Container />);

  t.true(tree.contains(<TestComponent />));
});

test('asyncComponent: Test loading module', t => {
  const promise = Promise.resolve(TestComponent);
  const Container = asyncComponent(() => promise);
  const tree = mount(<Container />);

  return promise.then(() => {
    t.true(tree.contains(<TestComponent />));
  });
});

test('asyncComponent: Test unmount', t => {
  const promise = Promise.resolve(TestComponent);
  const Container = asyncComponent(() => promise);
  const tree = mount(<Container />);

  tree.unmount();

  return promise.then(() => {
    t.is(tree.type(), undefined);
  });
});


text:
<?php

/**
*
* Categorie
*
* This class was generated by a script. Please be careful changing it.
* Regenerate it will erase all changes!
*/

namespace App\Models\Tables;

use Helpers\DB\Entity;

class Categorie extends Entity {
    public $titre;     // varchar(80)

    public function __construct(
        $titre = "",
    $id = false) {
        parent::__construct($id);

        $this->titre = $titre;
    }
}
?>


text:
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview A class for downloading remote files and storing them
 * locally using the HTML5 FileSystem API.
 *
 * The directory structure is of the form /HASH/URL/BASENAME:
 *
 * The HASH portion is a three-character slice of the hash of the URL. Since the
 * filesystem has a limit of about 5000 files per directory, this should divide
 * the downloads roughly evenly among about 5000 directories, thus allowing for
 * at most 5000^2 downloads.
 *
 * The URL portion is the (sanitized) full URL used for downloading the file.
 * This is used to ensure that each file ends up in a different location, even
 * if the HASH and BASENAME are the same.
 *
 * The BASENAME portion is the basename of the URL. It's used for the filename
 * proper so that the local filesystem: URL will be downloaded to a file with a
 * recognizable name.
 *
 */

goog.provide('goog.net.FileDownloader');
goog.provide('goog.net.FileDownloader.Error');

goog.require('goog.Disposable');
goog.require('goog.asserts');
goog.require('goog.async.Deferred');
goog.require('goog.crypt.hash32');
goog.require('goog.debug.Error');
goog.require('goog.events');
goog.require('goog.events.EventHandler');
goog.require('goog.fs');
goog.require('goog.fs.DirectoryEntry');
goog.require('goog.fs.Error');
goog.require('goog.fs.FileSaver');
goog.require('goog.net.EventType');
goog.require('goog.net.XhrIo');
goog.require('goog.net.XhrIoPool');
goog.require('goog.object');

/**
 * A class for downloading remote files and storing them locally using the
 * HTML5 filesystem API.
 *
 * @param {!goog.fs.DirectoryEntry} dir The directory in which the downloaded
 *     files are stored. This directory should be solely managed by
 *     FileDownloader.
 * @param {goog.net.XhrIoPool=} opt_pool The pool of XhrIo objects to use for
 *     downloading files.
 * @constructor
 * @extends {goog.Disposable}
 * @final
 */
goog.net.FileDownloader = function(dir, opt_pool) {
  goog.net.FileDownloader.base(this, 'constructor');

  /**
   * The directory in which the downloaded files are stored.
   * @type {!goog.fs.DirectoryEntry}
   * @private
   */
  this.dir_ = dir;

  /**
   * The pool of XHRs to use for capturing.
   * @type {!goog.net.XhrIoPool}
   * @private
   */
  this.pool_ = opt_pool || new goog.net.XhrIoPool();

  /**
   * A map from URLs to active downloads running for those URLs.
   * @type {!Object<!goog.net.FileDownloader.Download_>}
   * @private
   */
  this.downloads_ = {};

  /**
   * The handler for URL capturing events.
   * @type {!goog.events.EventHandler<!goog.net.FileDownloader>}
   * @private
   */
  this.eventHandler_ = new goog.events.EventHandler(this);
};
goog.inherits(goog.net.FileDownloader, goog.Disposable);

/**
 * Download a remote file and save its contents to the filesystem. A given file
 * is uniquely identified by its URL string; this means that the relative and
 * absolute URLs for a single file are considered different for the purposes of
 * the FileDownloader.
 *
 * Returns a Deferred that will contain the downloaded blob. If there's an error
 * while downloading the URL, this Deferred will be passed the
 * {@link goog.net.FileDownloader.Error} object as an errback.
 *
 * If a download is already in progress for the given URL, this will return the
 * deferred blob for that download. If the URL has already been downloaded, this
 * will fail once it tries to save the downloaded blob.
 *
 * When a download is in progress, all Deferreds returned for that download will
 * be branches of a single parent. If all such branches are cancelled, or if one
 * is cancelled with opt_deepCancel set, then the download will be cancelled as
 * well.
 *
 * @param {string} url The URL of the file to download.
 * @return {!goog.async.Deferred} The deferred result blob.
 */
goog.net.FileDownloader.prototype.download = function(url) {
  if (this.isDownloading(url)) {
    return this.downloads_[url].deferred.branch(true /* opt_propagateCancel */);
  }

  var download = new goog.net.FileDownloader.Download_(url, this);
  this.downloads_[url] = download;
  this.pool_.getObject(goog.bind(this.gotXhr_, this, download));
  return download.deferred.branch(true /* opt_propagateCancel */);
};

/**
 * Return a Deferred that will fire once no download is active for a given URL.
 * If there's no download active for that URL when this is called, the deferred
 * will fire immediately; otherwise, it will fire once the download is complete,
 * whether or not it succeeds.
 *
 * @param {string} url The URL of the download to wait for.
 * @return {!goog.async.Deferred} The Deferred that will fire when the download
 *     is complete.
 */
goog.net.FileDownloader.prototype.waitForDownload = function(url) {
  var deferred = new goog.async.Deferred();
  if (this.isDownloading(url)) {
    this.downloads_[url].deferred.addBoth(function() {
      deferred.callback(null);
    }, this);
  } else {
    deferred.callback(null);
  }
  return deferred;
};

/**
 * Returns whether or not there is an active download for a given URL.
 *
 * @param {string} url The URL of the download to check.
 * @return {boolean} Whether or not there is an active download for the URL.
 */
goog.net.FileDownloader.prototype.isDownloading = function(url) {
  return url in this.downloads_;
};

/**
 * Load a downloaded blob from the filesystem. Will fire a deferred error if the
 * given URL has not yet been downloaded.
 *
 * @param {string} url The URL of the blob to load.
 * @return {!goog.async.Deferred} The deferred Blob object. The callback will be
 *     passed the blob. If a file API error occurs while loading the blob, that
 *     error will be passed to the errback.
 */
goog.net.FileDownloader.prototype.getDownloadedBlob = function(url) {
  return this.getFile_(url).
      addCallback(function(fileEntry) { return fileEntry.file(); });
};

/**
 * Get the local filesystem: URL for a downloaded file. This is different from
 * the blob: URL that's available from getDownloadedBlob(). If the end user
 * accesses the filesystem: URL, the resulting file's name will be determined by
 * the download filename as opposed to an arbitrary GUID. In addition, the
 * filesystem: URL is connected to a filesystem location, so if the download is
 * removed then that URL will become invalid.
 *
 * Warning: in Chrome 12, some filesystem: URLs are opened inline. This means
 * that e.g. HTML pages given to the user via filesystem: URLs will be opened
 * and processed by the browser.
 *
 * @param {string} url The URL of the file to get the URL of.
 * @return {!goog.async.Deferred} The deferred filesystem: URL. The callback
 *     will be passed the URL. If a file API error occurs while loading the
 *     blob, that error will be passed to the errback.
 */
goog.net.FileDownloader.prototype.getLocalUrl = function(url) {
  return this.getFile_(url).
      addCallback(function(fileEntry) { return fileEntry.toUrl(); });
};

/**
 * Return (deferred) whether or not a URL has been downloaded. Will fire a
 * deferred error if something goes wrong when determining this.
 *
 * @param {string} url The URL to check.
 * @return {!goog.async.Deferred} The deferred boolean. The callback will be
 *     passed the boolean. If a file API error occurs while checking the
 *     existence of the downloaded URL, that error will be passed to the
 *     errback.
 */
goog.net.FileDownloader.prototype.isDownloaded = function(url) {
  var deferred = new goog.async.Deferred();
  var blobDeferred = this.getDownloadedBlob(url);
  blobDeferred.addCallback(function() {
    deferred.callback(true);
  });
  blobDeferred.addErrback(function(err) {
    if (err.code == goog.fs.Error.ErrorCode.NOT_FOUND) {
      deferred.callback(false);
    } else {
      deferred.errback(err);
    }
  });
  return deferred;
};

/**
 * Remove a URL from the FileDownloader.
 *
 * This returns a Deferred. If the removal is completed successfully, its
 * callback will be called without any value. If the removal fails, its errback
 * will be called with the {@link goog.fs.Error}.
 *
 * @param {string} url The URL to remove.
 * @return {!goog.async.Deferred} The deferred used for registering callbacks on
 *     success or on error.
 */
goog.net.FileDownloader.prototype.remove = function(url) {
  return this.getDir_(url, goog.fs.DirectoryEntry.Behavior.DEFAULT).
      addCallback(function(dir) { return dir.removeRecursively(); });
};

/**
 * Save a blob for a given URL. This works just as through the blob were
 * downloaded form that URL, except you specify the blob and no HTTP request is
 * made.
 *
 * If the URL is currently being downloaded, it's indeterminate whether the blob
 * being set or the blob being downloaded will end up in the filesystem.
 * Whichever one doesn't get saved will have an error. To ensure that one or the
 * other takes precedence, use {@link #waitForDownload} to allow the download to
 * complete before setting the blob.
 *
 * @param {string} url The URL at which to set the blob.
 * @param {!Blob} blob The blob to set.
 * @param {string=} opt_name The name of the file. If this isn't given, it's
 *     determined from the URL.
 * @return {!goog.async.Deferred} The deferred used for registering callbacks on
 *     success or on error. This can be cancelled just like a {@link #download}
 *     Deferred. The objects passed to the errback will be
 *     {@link goog.net.FileDownloader.Error}s.
 */
goog.net.FileDownloader.prototype.setBlob = function(url, blob, opt_name) {
  var name = this.sanitize_(opt_name || this.urlToName_(url));
  var download = new goog.net.FileDownloader.Download_(url, this);
  this.downloads_[url] = download;
  download.blob = blob;
  this.getDir_(download.url, goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE).
      addCallback(function(dir) {
        return dir.getFile(
            name, goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE);
      }).
      addCallback(goog.bind(this.fileSuccess_, this, download)).
      addErrback(goog.bind(this.error_, this, download));
  return download.deferred.branch(true /* opt_propagateCancel */);
};

/**
 * The callback called when an XHR becomes available from the XHR pool.
 *
 * @param {!goog.net.FileDownloader.Download_} download The download object for
 *     this download.
 * @param {!goog.net.XhrIo} xhr The XhrIo object for downloading the page.
 * @private
 */
goog.net.FileDownloader.prototype.gotXhr_ = function(download, xhr) {
  if (download.cancelled) {
    this.freeXhr_(xhr);
    return;
  }

  this.eventHandler_.listen(
      xhr, goog.net.EventType.SUCCESS,
      goog.bind(this.xhrSuccess_, this, download));
  this.eventHandler_.listen(
      xhr, [goog.net.EventType.ERROR, goog.net.EventType.ABORT],
      goog.bind(this.error_, this, download));
  this.eventHandler_.listen(
      xhr, goog.net.EventType.READY,
      goog.bind(this.freeXhr_, this, xhr));

  download.xhr = xhr;
  xhr.setResponseType(goog.net.XhrIo.ResponseType.ARRAY_BUFFER);
  xhr.send(download.url);
};

/**
 * The callback called when an XHR succeeds in downloading a remote file.
 *
 * @param {!goog.net.FileDownloader.Download_} download The download object for
 *     this download.
 * @private
 */
goog.net.FileDownloader.prototype.xhrSuccess_ = function(download) {
  if (download.cancelled) {
    return;
  }

  var name = this.sanitize_(this.getName_(
      /** @type {!goog.net.XhrIo} */ (download.xhr)));
  var resp = /** @type {ArrayBuffer} */ (download.xhr.getResponse());
  if (!resp) {
    // This should never happen - it indicates the XHR hasn't completed, has
    // failed or has been cleaned up.  If it does happen (eg. due to a bug
    // somewhere) we don't want to pass null to getBlob - it's not valid and
    // triggers a bug in some versions of WebKit causing it to crash.
    this.error_(download);
    return;
  }

  download.blob = goog.fs.getBlob(resp);
  delete download.xhr;

  this.getDir_(download.url, goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE).
      addCallback(function(dir) {
        return dir.getFile(
            name, goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE);
      }).
      addCallback(goog.bind(this.fileSuccess_, this, download)).
      addErrback(goog.bind(this.error_, this, download));
};

/**
 * The callback called when a file that will be used for saving a file is
 * successfully opened.
 *
 * @param {!goog.net.FileDownloader.Download_} download The download object for
 *     this download.
 * @param {!goog.fs.FileEntry} file The newly-opened file object.
 * @private
 */
goog.net.FileDownloader.prototype.fileSuccess_ = function(download, file) {
  if (download.cancelled) {
    file.remove();
    return;
  }

  download.file = file;
  file.createWriter().
      addCallback(goog.bind(this.fileWriterSuccess_, this, download)).
      addErrback(goog.bind(this.error_, this, download));
};

/**
 * The callback called when a file writer is succesfully created for writing a
 * file to the filesystem.
 *
 * @param {!goog.net.FileDownloader.Download_} download The download object for
 *     this download.
 * @param {!goog.fs.FileWriter} writer The newly-created file writer object.
 * @private
 */
goog.net.FileDownloader.prototype.fileWriterSuccess_ = function(
    download, writer) {
  if (download.cancelled) {
    download.file.remove();
    return;
  }

  download.writer = writer;
  writer.write(/** @type {!Blob} */ (download.blob));
  this.eventHandler_.listenOnce(
      writer,
      goog.fs.FileSaver.EventType.WRITE_END,
      goog.bind(this.writeEnd_, this, download));
};

/**
 * The callback called when file writing ends, whether or not it's successful.
 *
 * @param {!goog.net.FileDownloader.Download_} download The download object for
 *     this download.
 * @private
 */
goog.net.FileDownloader.prototype.writeEnd_ = function(download) {
  if (download.cancelled || download.writer.getError()) {
    this.error_(download, download.writer.getError());
    return;
  }

  delete this.downloads_[download.url];
  download.deferred.callback(download.blob);
};

/**
 * The error callback for all asynchronous operations. Ensures that all stages
 * of a given download are cleaned up, and emits the error event.
 *
 * @param {!goog.net.FileDownloader.Download_} download The download object for
 *     this download.
 * @param {goog.fs.Error=} opt_err The file error object. Only defined if the
 *     error was raised by the file API.
 * @private
 */
goog.net.FileDownloader.prototype.error_ = function(download, opt_err) {
  if (download.file) {
    download.file.remove();
  }

  if (download.cancelled) {
    return;
  }

  delete this.downloads_[download.url];
  download.deferred.errback(
      new goog.net.FileDownloader.Error(download, opt_err));
};

/**
 * Abort the download of the given URL.
 *
 * @param {!goog.net.FileDownloader.Download_} download The download to abort.
 * @private
 */
goog.net.FileDownloader.prototype.cancel_ = function(download) {
  goog.dispose(download);
  delete this.downloads_[download.url];
};

/**
 * Get the directory for a given URL. If the directory already exists when this
 * is called, it will contain exactly one file: the downloaded file.
 *
 * This not only calls the FileSystem API's getFile method, but attempts to
 * distribute the files so that they don't overload the filesystem. The spec
 * says directories can't contain more than 5000 files
 * (http://www.w3.org/TR/file-system-api/#directories), so this ensures that
 * each file is put into a subdirectory based on its SHA1 hash.
 *
 * All parameters are the same as in the FileSystem API's Entry#getFile method.
 *
 * @param {string} url The URL corresponding to the directory to get.
 * @param {goog.fs.DirectoryEntry.Behavior} behavior The behavior to pass to the
 *     underlying method.
 * @return {!goog.async.Deferred} The deferred DirectoryEntry object.
 * @private
 */
goog.net.FileDownloader.prototype.getDir_ = function(url, behavior) {
  // 3 hex digits provide 16**3 = 4096 different possible dirnames, which is
  // less than the maximum of 5000 entries. Downloaded files should be
  // distributed roughly evenly throughout the directories due to the hash
  // function, allowing many more than 5000 files to be downloaded.
  //
  // The leading ` ensures that no illegal dirnames are accidentally used. % was
  // previously used, but Chrome has a bug (as of 12.0.725.0 dev) where
  // filenames are URL-decoded before checking their validity, so filenames
  // containing e.g. '%3f' (the URL-encoding of :, an invalid character) are
  // rejected.
  var dirname = '`' + Math.abs(goog.crypt.hash32.encodeString(url)).
      toString(16).substring(0, 3);

  return this.dir_.
      getDirectory(dirname, goog.fs.DirectoryEntry.Behavior.CREATE).
      addCallback(function(dir) {
        return dir.getDirectory(this.sanitize_(url), behavior);
      }, this);
};

/**
 * Get the file for a given URL. This will only retrieve files that have already
 * been saved; it shouldn't be used for creating the file in the first place.
 * This is because the filename isn't necessarily determined by the URL, but by
 * the headers of the XHR response.
 *
 * @param {string} url The URL corresponding to the file to get.
 * @return {!goog.async.Deferred} The deferred FileEntry object.
 * @private
 */
goog.net.FileDownloader.prototype.getFile_ = function(url) {
  return this.getDir_(url, goog.fs.DirectoryEntry.Behavior.DEFAULT).
      addCallback(function(dir) {
        return dir.listDirectory().addCallback(function(files) {
          goog.asserts.assert(files.length == 1);
          // If the filesystem somehow gets corrupted and we end up with an
          // empty directory here, it makes sense to just return the normal
          // file-not-found error.
          return files[0] || dir.getFile('file');
        });
      });
};

/**
 * Sanitize a string so it can be safely used as a file or directory name for
 * the FileSystem API.
 *
 * @param {string} str The string to sanitize.
 * @return {string} The sanitized string.
 * @private
 */
goog.net.FileDownloader.prototype.sanitize_ = function(str) {
  // Add a prefix, since certain prefixes are disallowed for paths. None of the
  // disallowed prefixes start with '`'. We use ` rather than % for escaping the
  // filename due to a Chrome bug (as of 12.0.725.0 dev) where filenames are
  // URL-decoded before checking their validity, so filenames containing e.g.
  // '%3f' (the URL-encoding of :, an invalid character) are rejected.
  return '`' + str.replace(/[\/\\<>:?*"|%`]/g, encodeURIComponent).
      replace(/%/g, '`');
};

/**
 * Gets the filename specified by the XHR. This first attempts to parse the
 * Content-Disposition header for a filename and, failing that, falls back on
 * deriving the filename from the URL.
 *
 * @param {!goog.net.XhrIo} xhr The XHR containing the response headers.
 * @return {string} The filename.
 * @private
 */
goog.net.FileDownloader.prototype.getName_ = function(xhr) {
  var disposition = xhr.getResponseHeader('Content-Disposition');
  var match = disposition &&
      disposition.match(/^attachment *; *filename="(.*)"$/i);
  if (match) {
    // The Content-Disposition header allows for arbitrary backslash-escaped
    // characters (usually " and \). We want to unescape them before using them
    // in the filename.
    return match[1].replace(/\\(.)/g, '$1');
  }

  return this.urlToName_(xhr.getLastUri());
};

/**
 * Extracts the basename from a URL.
 *
 * @param {string} url The URL.
 * @return {string} The basename.
 * @private
 */
goog.net.FileDownloader.prototype.urlToName_ = function(url) {
  var segments = url.split('/');
  return segments[segments.length - 1];
};

/**
 * Remove all event listeners for an XHR and release it back into the pool.
 *
 * @param {!goog.net.XhrIo} xhr The XHR to free.
 * @private
 */
goog.net.FileDownloader.prototype.freeXhr_ = function(xhr) {
  goog.events.removeAll(xhr);
  this.pool_.addFreeObject(xhr);
};

/** @override */
goog.net.FileDownloader.prototype.disposeInternal = function() {
  delete this.dir_;
  goog.dispose(this.eventHandler_);
  delete this.eventHandler_;
  goog.object.forEach(this.downloads_, function(download) {
    download.deferred.cancel();
  }, this);
  delete this.downloads_;
  goog.dispose(this.pool_);
  delete this.pool_;

  goog.net.FileDownloader.base(this, 'disposeInternal');
};

/**
 * The error object for FileDownloader download errors.
 *
 * @param {!goog.net.FileDownloader.Download_} download The download object for
 *     the download in question.
 * @param {goog.fs.Error=} opt_fsErr The file error object, if this was a file
 *     error.
 *
 * @constructor
 * @extends {goog.debug.Error}
 * @final
 */
goog.net.FileDownloader.Error = function(download, opt_fsErr) {
  goog.net.FileDownloader.Error.base(
      this, 'constructor', 'Error capturing URL ' + download.url);

  /**
   * The URL the event relates to.
   * @type {string}
   */
  this.url = download.url;

  if (download.xhr) {
    this.xhrStatus = download.xhr.getStatus();
    this.xhrErrorCode = download.xhr.getLastErrorCode();
    this.message += ': XHR failed with status ' + this.xhrStatus +
        ' (error code ' + this.xhrErrorCode + ')';
  } else if (opt_fsErr) {
    this.fileError = opt_fsErr;
    this.message += ': file API failed (' + opt_fsErr.message + ')';
  }
};
goog.inherits(goog.net.FileDownloader.Error, goog.debug.Error);

/**
 * The status of the XHR. Only set if the error was caused by an XHR failure.
 * @type {number|undefined}
 */
goog.net.FileDownloader.Error.prototype.xhrStatus;

/**
 * The error code of the XHR. Only set if the error was caused by an XHR
 * failure.
 * @type {goog.net.ErrorCode|undefined}
 */
goog.net.FileDownloader.Error.prototype.xhrErrorCode;

/**
 * The file API error. Only set if the error was caused by the file API.
 * @type {goog.fs.Error|undefined}
 */
goog.net.FileDownloader.Error.prototype.fileError;

/**
 * A struct containing the data for a single download.
 *
 * @param {string} url The URL for the file being downloaded.
 * @param {!goog.net.FileDownloader} downloader The parent FileDownloader.
 * @extends {goog.Disposable}
 * @constructor
 * @private
 */
goog.net.FileDownloader.Download_ = function(url, downloader) {
  goog.net.FileDownloader.Download_.base(this, 'constructor');

  /**
   * The URL for the file being downloaded.
   * @type {string}
   */
  this.url = url;

  /**
   * The Deferred that will be fired when the download is complete.
   * @type {!goog.async.Deferred}
   */
  this.deferred = new goog.async.Deferred(
      goog.bind(downloader.cancel_, downloader, this));

  /**
   * Whether this download has been cancelled by the user.
   * @type {boolean}
   */
  this.cancelled = false;

  /**
   * The XhrIo object for downloading the file. Only set once it's been
   * retrieved from the pool.
   * @type {goog.net.XhrIo}
   */
  this.xhr = null;

  /**
   * The name of the blob being downloaded. Only sey once the XHR has completed,
   * if it completed successfully.
   * @type {?string}
   */
  this.name = null;

  /**
   * The downloaded blob. Only set once the XHR has completed, if it completed
   * successfully.
   * @type {Blob}
   */
  this.blob = null;

  /**
   * The file entry where the blob is to be stored. Only set once it's been
   * loaded from the filesystem.
   * @type {goog.fs.FileEntry}
   */
  this.file = null;

  /**
   * The file writer for writing the blob to the filesystem. Only set once it's
   * been loaded from the filesystem.
   * @type {goog.fs.FileWriter}
   */
  this.writer = null;
};
goog.inherits(goog.net.FileDownloader.Download_, goog.Disposable);

/** @override */
goog.net.FileDownloader.Download_.prototype.disposeInternal = function() {
  this.cancelled = true;
  if (this.xhr) {
    this.xhr.abort();
  } else if (this.writer && this.writer.getReadyState() ==
             goog.fs.FileSaver.ReadyState.WRITING) {
    this.writer.abort();
  }

  goog.net.FileDownloader.Download_.base(this, 'disposeInternal');
};