text:
package codechicken.lib.render;

import codechicken.lib.colour.ColourRGBA;
import codechicken.lib.lighting.LC;
import codechicken.lib.lighting.LightMatrix;
import codechicken.lib.util.Copyable;
import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Transformation;
import codechicken.lib.vec.Vector3;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.IBlockAccess;

import java.util.ArrayList;

/**
 * The core of the CodeChickenLib render system.
 * Rendering operations are written to avoid object allocations by reusing static variables.
 */
public class CCRenderState
{
    private static int nextOperationIndex;

    public static int registerOperation() {
        return nextOperationIndex++;
    }

    public static int operationCount() {
        return nextOperationIndex;
    }

    /**
     * Represents an operation to be run for each vertex that operates on and modifies the current state
     */
    public static interface IVertexOperation
    {
        /**
         * Load any required references and add dependencies to the pipeline based on the current model (may be null)
         * Return false if this operation is redundant in the pipeline with the given model
         */
        public boolean load();

        /**
         * Perform the operation on the current render state
         */
        public void operate();

        /**
         * Get the unique id representing this type of operation. Duplicate operation IDs within the pipeline may have unexpected results.
         * ID shoulld be obtained from CCRenderState.registerOperation() and stored in a static variable
         */
        public int operationID();
    }

    private static ArrayList<VertexAttribute<?>> vertexAttributes = new ArrayList<VertexAttribute<?>>();
    private static int registerVertexAttribute(VertexAttribute<?> attr) {
        vertexAttributes.add(attr);
        return vertexAttributes.size()-1;
    }

    public static VertexAttribute<?> getAttribute(int index) {
        return vertexAttributes.get(index);
    }

    /**
     * Management class for a vertex attrute such as colour, normal etc
     * This class should handle the loading of the attrute from an array provided by IVertexSource.getAttributes or the computation of this attrute from others
     * @param <T> The array type for this attrute eg. int[], Vector3[]
     */
    public static abstract class VertexAttribute<T> implements IVertexOperation
    {
        public final int attributeIndex = registerVertexAttribute(this);
        private final int operationIndex = registerOperation();
        /**
         * Set to true when the attrute is part of the pipeline. Should only be managed by CCRenderState when constructing the pipeline
         */
        public boolean active = false;

        /**
         * Construct a new array for storage of vertex attrutes in a model
         */
        public abstract T newArray(int length);

        @Override
        public int operationID() {
            return operationIndex;
        }
    }

    public static void arrayCopy(Object src, int srcPos, Object dst, int destPos, int length) {
        System.arraycopy(src, srcPos, dst, destPos, length);
        if(dst instanceof Copyable[]) {
            Object[] oa = (Object[])dst;
            Copyable<Object>[] c = (Copyable[])dst;
            for(int i = destPos; i < destPos+length; i++)
                if(c[i] != null)
                    oa[i] = c[i].copy();
        }
    }

    public static <T> T copyOf(VertexAttribute<T> attr, T src, int length) {
        T dst = attr.newArray(length);
        arrayCopy(src, 0, dst, 0, ((Object[])src).length);
        return dst;
    }

    public static interface IVertexSource
    {
        public Vertex5[] getVertices();

        /**
         * Gets an array of vertex attrutes
         * @param attr The vertex attrute to get
         * @param <T> The attrute array type
         * @return An array, or null if not computed
         */
        public <T> T getAttributes(VertexAttribute<T> attr);

        /**
         * @return True if the specified attrute is provided by this model, either by returning an array from getAttributes or by setting the state in prepareVertex
         */
        public boolean hasAttribute(VertexAttribute<?> attr);

        /**
         * Callback to set CCRenderState for a vertex before the pipeline runs
         */
        public void prepareVertex();
    }

    public static VertexAttribute<Vector3[]> normalAttrib = new VertexAttribute<Vector3[]>() {
        private Vector3[] normalRef;

        @Override
        public Vector3[] newArray(int length) {
            return new Vector3[length];
        }

        @Override
        public boolean load() {
            normalRef = model.getAttributes(this);
            if(model.hasAttribute(this))
                return normalRef != null;

            if(model.hasAttribute(sideAttrib)) {
                pipeline.addDependency(sideAttrib);
                return true;
            }
            throw new IllegalStateException("Normals requested but neither normal or side attrutes are provided by the model");
        }

        @Override
        public void operate() {
            if(normalRef != null)
                setNormal(normalRef[vertexIndex]);
            else
                setNormal(Rotation.axes[side]);
        }
    };
    public static VertexAttribute<int[]> colourAttrib = new VertexAttribute<int[]>() {
        private int[] colourRef;

        @Override
        public int[] newArray(int length) {
            return new int[length];
        }

        @Override
        public boolean load() {
            colourRef = model.getAttributes(this);
            return colourRef != null || !model.hasAttribute(this);
        }

        @Override
        public void operate() {
            if(colourRef != null)
                setColour(ColourRGBA.multiply(baseColour, colourRef[vertexIndex]));
            else
                setColour(baseColour);
        }
    };
    public static VertexAttribute<int[]> lightingAttrib = new VertexAttribute<int[]>() {
        private int[] colourRef;

        @Override
        public int[] newArray(int length) {
            return new int[length];
        }

        @Override
        public boolean load() {
            if(!computeLighting || !useColour || !model.hasAttribute(this))
                return false;

            colourRef = model.getAttributes(this);
            if(colourRef != null) {
                pipeline.addDependency(colourAttrib);
                return true;
            }
            return false;
        }

        @Override
        public void operate() {
            setColour(ColourRGBA.multiply(colour, colourRef[vertexIndex]));
        }
    };
    public static VertexAttribute<int[]> sideAttrib = new VertexAttribute<int[]>() {
        private int[] sideRef;

        @Override
        public int[] newArray(int length) {
            return new int[length];
        }

        @Override
        public boolean load() {
            sideRef = model.getAttributes(this);
            if(model.hasAttribute(this))
                return sideRef != null;

            pipeline.addDependency(normalAttrib);
            return true;
        }

        @Override
        public void operate() {
            if(sideRef != null)
                side = sideRef[vertexIndex];
            else
                side = CCModel.findSide(normal);
        }
    };
    /**
     * Uses the position of the lightmatrix to compute LC if not provided
     */
    public static VertexAttribute<LC[]> lightCoordAttrib = new VertexAttribute<LC[]>() {
        private LC[] lcRef;
        private Vector3 vec = new Vector3();//for computation
        private Vector3 pos = new Vector3();

        @Override
        public LC[] newArray(int length) {
            return new LC[length];
        }

        @Override
        public boolean load() {
            lcRef = model.getAttributes(this);
            if(model.hasAttribute(this))
                return lcRef != null;

            pos.set(lightMatrix.pos.x, lightMatrix.pos.y, lightMatrix.pos.z);
            pipeline.addDependency(sideAttrib);
            pipeline.addRequirement(Transformation.operationIndex);
            return true;
        }

        @Override
        public void operate() {
            if(lcRef != null)
                lc.set(lcRef[vertexIndex]);
            else
                lc.compute(vec.set(vert.vec).sub(pos), side);
        }
    };

    //pipeline state
    public static IVertexSource model;
    public static int firstVertexIndex;
    public static int lastVertexIndex;
    public static int vertexIndex;
    public static CCRenderPipeline pipeline = new CCRenderPipeline();

    //context
    public static int baseColour;
    public static int alphaOverride;
    public static boolean useNormals;
    public static boolean computeLighting;
    public static boolean useColour;
    public static LightMatrix lightMatrix = new LightMatrix();

    //vertex outputs
    public static Vertex5 vert = new Vertex5();
    public static boolean hasNormal;
    public static Vector3 normal = new Vector3();
    public static boolean hasColour;
    public static int colour;
    public static boolean hasBrightness;
    public static int brightness;

    //attrute storage
    public static int side;
    public static LC lc = new LC();

    public static void reset() {
        model = null;
        pipeline.reset();
        useNormals = hasNormal = hasBrightness = hasColour = false;
        useColour = computeLighting = true;
        baseColour = alphaOverride = -1;
    }

    public static void setPipeline(IVertexOperation... ops) {
        pipeline.setPipeline(ops);
    }

    public static void setPipeline(IVertexSource model, int start, int end, IVertexOperation... ops) {
        pipeline.reset();
        setModel(model, start, end);
        pipeline.setPipeline(ops);
    }

    public static void bindModel(IVertexSource model) {
        if(CCRenderState.model != model) {
            CCRenderState.model = model;
            pipeline.rebuild();
        }
    }

    public static void setModel(IVertexSource source) {
        setModel(source, 0, source.getVertices().length);
    }

    public static void setModel(IVertexSource source, int start, int end) {
        bindModel(source);
        setVertexRange(start, end);
    }

    public static void setVertexRange(int start, int end) {
        firstVertexIndex = start;
        lastVertexIndex = end;
    }

    public static void render(IVertexOperation... ops) {
        setPipeline(ops);
        render();
    }

    public static void render() {
        Vertex5[] verts = model.getVertices();
        for(vertexIndex = firstVertexIndex; vertexIndex < lastVertexIndex; vertexIndex++) {
            model.prepareVertex();
            vert.set(verts[vertexIndex]);
            runPipeline();
            writeVert();
        }
    }

    public static void runPipeline() {
        pipeline.operate();
    }

    public static void writeVert() {
        if(hasNormal)
            Tessellator.instance.setNormal((float)normal.x, (float)normal.y, (float)normal.z);
        if(hasColour)
            Tessellator.instance.setColorRGBA(colour>>>24, colour>>16 & 0xFF, colour>>8 & 0xFF, alphaOverride >= 0 ? alphaOverride : colour & 0xFF);
        if(hasBrightness)
            Tessellator.instance.setBrightness(brightness);
        Tessellator.instance.addVertexWithUV(vert.vec.x, vert.vec.y, vert.vec.z, vert.uv.u, vert.uv.v);
    }

    public static void setNormal(double x, double y, double z) {
        hasNormal = true;
        normal.set(x, y, z);
    }

    public static void setNormal(Vector3 n) {
        hasNormal = true;
        normal.set(n);
    }

    public static void setColour(int c) {
        hasColour = true;
        colour = c;
    }

    public static void setBrightness(int b) {
        hasBrightness = true;
        brightness = b;
    }

    public static void setBrightness(IBlockAccess world, int x, int y, int z) {
        setBrightness(world.getBlock(x, y, z).getMixedBrightnessForBlock(world, x, y, z));
    }

    public static void pullLightmap() {
        setBrightness((int)OpenGlHelper.lastBrightnessY << 16 | (int)OpenGlHelper.lastBrightnessX);
    }

    /**
     * Compact helper for setting dynamic rendering context. Uses normals and doesn't compute lighting
     */
    public static void setDynamic() {
        useNormals = true;
        computeLighting = false;
    }

    public static void changeTexture(String texture) {
        changeTexture(new ResourceLocation(texture));
    }

    public static void changeTexture(ResourceLocation texture) {
        Minecraft.getMinecraft().renderEngine.bindTexture(texture);
    }

    public static void startDrawing() {
        startDrawing(7);
    }

    public static void startDrawing(int mode) {
        Tessellator.instance.startDrawing(mode);
        if(hasColour)
            Tessellator.instance.setColorRGBA(colour>>>24, colour>>16 & 0xFF, colour>>8 & 0xFF, alphaOverride >= 0 ? alphaOverride : colour & 0xFF);
        if(hasBrightness)
            Tessellator.instance.setBrightness(brightness);
    }

    public static void draw() {
        Tessellator.instance.draw();
    }
}


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

namespace Xvvm.Mvvm
{
    // Mimics ObservableCollection in terms of interfaces, while also is an IObservableReadOnlyList.
    public interface IObservableList<T> : IObservableReadOnlyList<T>
        , IList<T>, IList, ICollection<T>, ICollection
    {
        void Move(int oldIndex, int newIndex);

        void AddRange(List<T> range);
        void ResetTo(List<T> newItems);
    }
}

redpajama_set_name: RedPajamaGithub


text:
I am a Computer Science student and Software Developer, aiming at developing software professionally. Currently I have my Bachelor of Science and am working on my Master of Engineering. I plan to write a master thesis about something with Machine Learning (ML). Currently I learn about ML in online courses.

In my free time I like to learn Mandarin, play table tennis, play chess and many chess variants, read fantasy and science-fiction novels and play computer games, mostly Little Fighter 2.

% author: Zelphir
% date: 2016-05-18


text:
License: MIT

Platform: iOs

## Very simple way to play audios from urls in iOs

DLSimpleURLAudioPlayer can play audios files from urls using `AVPlayer`. You can set the artist's name , audio name and cover art.

#### The Player View Controller (DLSimpleURLAudioPlayerViewController)

iPhone 5s

![Alt][screenshot2]

iPad

![Alt][screenshot1]

[screenshot1]: https://github.com/DanielLimaDF/DLSimpleURLAudioPlayer/blob/master/Screenshots/ipad_1.png
[screenshot2]: https://github.com/DanielLimaDF/DLSimpleURLAudioPlayer/blob/master/Screenshots/iphone5s1.png

#### Device Control Center

iPhone

![Alt][screenshot3]

iPad

![Alt][screenshot4]

[screenshot3]: https://github.com/DanielLimaDF/DLSimpleURLAudioPlayer/blob/master/Screenshots/iphone6s2.PNG
[screenshot4]: https://github.com/DanielLimaDF/DLSimpleURLAudioPlayer/blob/master/Screenshots/ipad_3.jpg

#### Device Lock Screen

iPhone 6

![Alt][screenshot5]

iPad

![Alt][screenshot6]

[screenshot5]: https://github.com/DanielLimaDF/DLSimpleURLAudioPlayer/blob/master/Screenshots/iphone6s1.png
[screenshot6]: https://github.com/DanielLimaDF/DLSimpleURLAudioPlayer/blob/master/Screenshots/ipad_2.jpg

## Usage

DLSimpleURLAudioPlayer is designed to work with a View Controller. Simply create a `Segue` to DLSimpleURLAudioPlayerViewController and enter the audio queue to be executed along with the first audio to be played by AvPlayer

```obj-c

//You can, for example, create a vector of Audio objects somewhere

NSInteger CurrentSelectAudio = 0;

NSMutableArray *YourArrayAudioList = [[NSMutableArray alloc]init];

Audio *song1 = [[Audio alloc]init];
Audio *song2 = [[Audio alloc]init];
Audio *song3 = [[Audio alloc]init];

//Set info:
[song1 setTitle:@"Title 1"];
[song1 setAuthor:@"Artist name"];
[song1 setCover:@"http://yoururl.com/youraudiofile1.mp3"];

[song2 setTitle:@"Title 2"];
[song2 setAuthor:@"Artist name"];
[song2 setCover:@"http://yoururl.com/youraudiofile2.mp3"];

[song3 setTitle:@"Title 3"];
[song3 setAuthor:@"Artist name"];
[song3 setCover:@"http://yoururl.com/youraudiofile3.mp3"];

//Add to array
[YourArrayAudioList addObject:song1];
[YourArrayAudioList addObject:song2];
[YourArrayAudioList addObject:song3];

//Pass the array and the current audio index via prepareForSegue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@"goAudioPlayerGo"]) {
        DLSimpleURLAudioPlayerViewController *playerView = [segue destinationViewController];
        playerView.audioList = YourArrayAudioList;
        [playerView setSelectedAudio:CurrentSelectAudio];
    }
}
```

I recommend that you download and run the project to better understand how it works.

## Offline content

DLSimpleURLAudioPlayer also supports offline content. If you download the audio file the framework will identify that it exists locally and will play it from the device's Documents folder instead of loading the file again.

## License

DLSimpleURLAudioPlayer is available under the MIT license. See the LICENSE file for more info.

## Notes

The songs and the audiobook used as an example in this project are Public Domain in Brazil. They were obtained on http://www.dominiopublico.gov.br/


text:
package org.apache.giraph.block_app.framework.block;

import java.util.Iterator;

import org.apache.giraph.block_app.framework.piece.AbstractPiece;
import org.apache.giraph.function.Consumer;

/**
 * Composable unit of execution. Used to combine other Blocks into
 * bigger units. Each Piece represents a Block itself.
 *
 * Execution is represented as an iterator across Pieces.
 *
 * The whole application run is represented by a single block at the end.
 */
@SuppressWarnings("rawtypes")
public interface Block extends Iterable<AbstractPiece> {
  /**
   * Create iterator representing all pieces needed to be executed
   * in this block.
   *
   * After Iterator.next call returns, master compute of returned Piece is
   * guaranteed to be called before calling hasNext/next on the iterator.
   * (allows for iterators logic to depend on the execution dynamically,
   * and not be only static)
   */
  @Override
  Iterator<AbstractPiece> iterator();

  /**
   * Calls consumer for each Piece:
   * - in no particular order
   * - potentially calling multiple times on same Piece
   * - even if Piece might never be returned in the iterator
   * - it will be called at least once for every piece that is
   *   going to be returned by iterator
   *
   * Can be used for static analysis/introspection of the block,
   * without actually executing them.
   */
  void forAllPossiblePieces(Consumer<AbstractPiece> consumer);
}


text:
describe('Node', () => {
  let host;

  beforeEach(() => {
    host = document.createElement('div');
  });

  describe('appendChild', () => {
    let m1, m2;

    // For some reason this test has side effects and fails ever other run.
    it.skip('should connect a custom element', () => {
      class CustomElement extends HTMLElement {
        constructor() {
          super();
          this.connectedCallback = jest.fn();
        }
      }
      const node = new CustomElement();
      host.appendChild(node);
      expect(node.connectedCallback.mock.calls.length).toEqual(1);
    });

    it('should connect a fragment of elements', () => {});
  });

  describe('insertBefore', () => {
    it('should connect a custom element', () => {});

    it('should connect a fragment of elements', () => {});
  });

  describe('removeChild', () => {
    it('should connect a custom element', () => {});

    it('should connect a fragment of elements', () => {});
  });

  describe('replaceChild', () => {
    it('should connect a custom element', () => {});

    it('should connect a fragment of elements', () => {});
  });

  describe('cloneNode', () => {
    function testCloneEquality(source, clone, deeplyCloned) {
      expect(clone.nodeName).toEqual(source.nodeName);

      if (clone.attributes) {
        clone.attributes.forEach(({ name, value }) =>
          expect(value).toEqual(source.getAttribute(name))
        );
      }

      expect(clone.nodeType).toEqual(source.nodeType);

      if (deeplyCloned) {
        expect(clone.textContent).toEqual(source.textContent);

        expect(clone.childNodes.length).toEqual(source.childNodes.length);
        if (clone.childNodes) {
          clone.childNodes.forEach((child, i) => {
            testCloneEquality(source.childNodes[i], child, true);
          });
        }
      } else {
        expect(clone.childNodes.length).toEqual(0);
      }
    }

    beforeEach(() => {
      const child = document.createElement('span');
      child.setAttribute('clone-this', 'test');
      child.appendChild(document.createTextNode('example text child'));
      const grandchild = document.createElement('div');
      grandchild.setAttribute('id', '42');
      grandchild.appendChild(document.createTextNode('grandchild text node'));
      child.appendChild(grandchild);

      host.appendChild(child);
      host.setAttribute('clone-this', 'test');
    });

    it('clones an element shallowly', () => {
      const clone = host.cloneNode();
      testCloneEquality(host, clone, false);
    });

    it('clones an element deeply', () => {
      const clone = host.cloneNode(true);
      testCloneEquality(host, clone, true);
    });
  });

  describe('content', () => {
    it('should return a documentFragment containing all children', () => {
      for (let i = 0; i < 10; i++) {
        const child = document.createElement('span');
        child.textContent = i;
        host.appendChild(child);
      }
      const content = host.content;
      expect(content.childNodes.length).toEqual(10);
      for (let i = 0; i < 10; i++) {
        expect(content.childNodes[i].textContent).toEqual(i.toString());
      }
    });
  });

  describe('textContent', () => {
    it('should get textContent', () => {
      const text = 'Hello Bob!';
      const div = document.createElement('div');
      div.appendChild(document.createTextNode(text));
      expect(div.textContent).toEqual(text);
    });

    it('should set textContent', () => {
      const div = document.createElement('div');
      const text = `Hello World!`;
      div.textContent = text;
      expect(div.textContent).toEqual(text);

      const newText = `Hello Bob!`;
      div.textContent = newText;
      expect(div.textContent).toEqual(newText);
    });
  });
});


text:
package db

import (
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"net/url"
	"reflect"

	"github.com/coreos/go-oidc/oidc"
	"github.com/go-gorp/gorp"

	"github.com/coreos/dex/client"
	"github.com/coreos/dex/pkg/log"
	"github.com/coreos/dex/repo"
)

const (
	clientTableName      = "client_identity"
	trustedPeerTableName = "trusted_peers"

	// postgres error codes
	pgErrorCodeUniqueViolation = "23505" // unique_violation
)

var (
	localHostRedirectURL = mustParseURL("http://localhost:0")
)

func init() {
	register(table{
		name:    clientTableName,
		model:   clientModel{},
		autoinc: false,
		pkey:    []string{"id"},
	})

	register(table{
		name:    trustedPeerTableName,
		model:   trustedPeerModel{},
		autoinc: false,
		pkey:    []string{"client_id", "trusted_client_id"},
	})
}

func newClientModel(cli client.Client) (*clientModel, error) {
	hashed, err := client.HashSecret(cli.Credentials)
	if err != nil {
		return nil, err
	}

	if cli.Public {
		// Metadata.Valid(), and therefore json.Unmarshal(metadata) complains
		// when there's no RedirectURIs, so we set them to a fixed value here,
		// and remove it when translating back to a client.Client
		cli.Metadata.RedirectURIs = []url.URL{
			localHostRedirectURL,
		}
	}

	bmeta, err := json.Marshal(&cli.Metadata)
	if err != nil {
		return nil, err
	}

	cim := clientModel{
		ID:       cli.Credentials.ID,
		Secret:   hashed,
		Metadata: string(bmeta),
		DexAdmin: cli.Admin,
		Public:   cli.Public,
	}

	return &cim, nil
}

type clientModel struct {
	ID       string `db:"id"`
	Secret   []byte `db:"secret"`
	Metadata string `db:"metadata"`
	DexAdmin bool   `db:"dex_admin"`
	Public   bool   `db:"public"`
}

type trustedPeerModel struct {
	ClientID        string `db:"client_id"`
	TrustedClientID string `db:"trusted_client_id"`
}

func (m *clientModel) Client() (*client.Client, error) {
	ci := client.Client{
		Credentials: oidc.ClientCredentials{
			ID: m.ID,
		},
		Admin:  m.DexAdmin,
		Public: m.Public,
	}

	if err := json.Unmarshal([]byte(m.Metadata), &ci.Metadata); err != nil {
		return nil, err
	}

	if ci.Public {
		ci.Metadata.RedirectURIs = []url.URL{}
	}

	return &ci, nil
}

func NewClientRepo(dbm *gorp.DbMap) client.ClientRepo {
	return newClientRepo(dbm)
}

func newClientRepo(dbm *gorp.DbMap) *clientRepo {
	return &clientRepo{
		db: &db{dbm},
	}
}

type clientRepo struct {
	*db
}

func (r *clientRepo) Get(tx repo.Transaction, clientID string) (client.Client, error) {
	m, err := r.executor(tx).Get(clientModel{}, clientID)
	if err == sql.ErrNoRows || m == nil {
		return client.Client{}, client.ErrorNotFound
	}
	if err != nil {
		return client.Client{}, err
	}

	cim, ok := m.(*clientModel)
	if !ok {
		log.Errorf("expected clientModel but found %v", reflect.TypeOf(m))
		return client.Client{}, errors.New("unrecognized model")
	}

	ci, err := cim.Client()
	if err != nil {
		return client.Client{}, err
	}

	return *ci, nil
}

func (r *clientRepo) GetSecret(tx repo.Transaction, clientID string) ([]byte, error) {
	m, err := r.getModel(tx, clientID)
	if err != nil || m == nil {
		return nil, err
	}
	return m.Secret, nil
}

func (r *clientRepo) Update(tx repo.Transaction, cli client.Client) error {
	if cli.Credentials.ID == "" {
		return client.ErrorNotFound
	}
	// make sure this client exists already
	_, err := r.get(tx, cli.Credentials.ID)
	if err != nil {
		return err
	}
	err = r.update(tx, cli)
	if err != nil {
		return err
	}
	return nil
}

var alreadyExistsCheckers []func(err error) bool

func registerAlreadyExistsChecker(f func(err error) bool) {
	alreadyExistsCheckers = append(alreadyExistsCheckers, f)
}

// isAlreadyExistsErr detects database error codes for failing a unique constraint.
//
// Because database drivers are optionally compiled, use registerAlreadyExistsChecker to
// register driver specific implementations.
func isAlreadyExistsErr(err error) bool {
	for _, checker := range alreadyExistsCheckers {
		if checker(err) {
			return true
		}
	}
	return false
}

func (r *clientRepo) New(tx repo.Transaction, cli client.Client) (*oidc.ClientCredentials, error) {
	cim, err := newClientModel(cli)
	if err != nil {
		return nil, err
	}

	if err := r.executor(tx).Insert(cim); err != nil {
		if isAlreadyExistsErr(err) {
			return nil, client.ErrorDuplicateClientID
		}
		return nil, err
	}

	cc := oidc.ClientCredentials{
		ID:     cli.Credentials.ID,
		Secret: cli.Credentials.Secret,
	}

	return &cc, nil
}

func (r *clientRepo) All(tx repo.Transaction) ([]client.Client, error) {
	qt := r.quote(clientTableName)
	q := fmt.Sprintf("SELECT * FROM %s", qt)
	objs, err := r.executor(tx).Select(&clientModel{}, q)
	if err != nil {
		return nil, err
	}

	cs := make([]client.Client, len(objs))
	for i, obj := range objs {
		m, ok := obj.(*clientModel)
		if !ok {
			return nil, errors.New("unable to cast client identity to clientModel")
		}

		ci, err := m.Client()
		if err != nil {
			return nil, err
		}
		cs[i] = *ci
	}
	return cs, nil
}

func NewClientRepoFromClients(dbm *gorp.DbMap, cs []client.LoadableClient) (client.ClientRepo, error) {
	repo := NewClientRepo(dbm).(*clientRepo)
	for _, c := range cs {
		cm, err := newClientModel(c.Client)
		if err != nil {
			return nil, err
		}
		err = repo.executor(nil).Insert(cm)
		if err != nil {
			return nil, err
		}

		err = repo.SetTrustedPeers(nil, c.Client.Credentials.ID, c.TrustedPeers)
		if err != nil {
			return nil, err
		}

	}
	return repo, nil
}

func (r *clientRepo) get(tx repo.Transaction, clientID string) (client.Client, error) {
	cm, err := r.getModel(tx, clientID)
	if err != nil {
		return client.Client{}, err
	}

	cli, err := cm.Client()
	if err != nil {
		return client.Client{}, err
	}

	return *cli, nil
}

func (r *clientRepo) getModel(tx repo.Transaction, clientID string) (*clientModel, error) {
	ex := r.executor(tx)

	m, err := ex.Get(clientModel{}, clientID)
	if err != nil {
		return nil, err
	}

	if m == nil {
		return nil, client.ErrorNotFound
	}

	cm, ok := m.(*clientModel)
	if !ok {
		log.Errorf("expected clientModel but found %v", reflect.TypeOf(m))
		return nil, errors.New("unrecognized model")
	}
	return cm, nil
}

func (r *clientRepo) update(tx repo.Transaction, cli client.Client) error {
	ex := r.executor(tx)
	cm, err := newClientModel(cli)
	if err != nil {
		return err
	}
	_, err = ex.Update(cm)
	return err
}

func (r *clientRepo) GetTrustedPeers(tx repo.Transaction, clientID string) ([]string, error) {
	ex := r.executor(tx)
	if clientID == "" {
		return nil, client.ErrorInvalidClientID
	}

	qt := r.quote(trustedPeerTableName)
	var ids []string
	_, err := ex.Select(&ids, fmt.Sprintf("SELECT trusted_client_id from %s where client_id = $1", qt), clientID)

	if err != nil {
		if err != sql.ErrNoRows {
			return nil, err
		}
		return nil, nil
	}

	return ids, nil
}

func (r *clientRepo) SetTrustedPeers(tx repo.Transaction, clientID string, clientIDs []string) error {
	ex := r.executor(tx)
	qt := r.quote(trustedPeerTableName)

	// First delete all existing rows
	_, err := ex.Exec(fmt.Sprintf("DELETE from %s where client_id = $1", qt), clientID)
	if err != nil {
		return err
	}

	// Ensure that the client exists.
	_, err = r.get(tx, clientID)
	if err != nil {
		return err
	}

	// Set the clients
	rows := []interface{}{}
	for _, curID := range clientIDs {
		rows = append(rows, &trustedPeerModel{
			ClientID:        clientID,
			TrustedClientID: curID,
		})
	}
	err = ex.Insert(rows...)
	if err != nil {
		return err
	}

	return nil
}

func mustParseURL(s string) url.URL {
	u, err := url.Parse(s)
	if err != nil {
		panic(err)
	}
	return *u
}


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * file upload functions
 *
 * @package phpMyAdmin
 */

/**
 *
 * @todo replace error messages with localized string
 * @todo when uploading a file into a blob field, should we also consider using
 *       chunks like in import? UPDATE `table` SET `field` = `field` + [chunk]
 * @package phpMyAdmin
 */
class PMA_File
{
    /**
     * @var string the temporary file name
     * @access protected
     */
    var $_name = null;

    /**
     * @var string the content
     * @access protected
     */
    var $_content = null;

    /**
     * @var string the error message
     * @access protected
     */
    var $_error_message = '';

    /**
     * @var bool whether the file is temporary or not
     * @access protected
     */
    var $_is_temp = false;

    /**
     * @var string type of compression
     * @access protected
     */
    var $_compression = null;

    /**
     * @var integer
     */
    var $_offset = 0;

    /**
     * @var integer size of chunk to read with every step
     */
    var $_chunk_size = 32768;

    /**
     * @var resource file handle
     */
    var $_handle = null;

    /**
     * @var boolean whether to decompress content before returning
     */
    var $_decompress = false;

    /**
     * @var string charset of file
     */
    var $_charset = null;

    /**
     * @staticvar string most recent BLOB repository reference
    */
    static $_recent_bs_reference = NULL;

    /**
     * constructor
     *
     * @access  public
     * @uses    PMA_File::setName()
     * @param   string  $name   file name
     */
    function __construct($name = false)
    {
        if ($name) {
            $this->setName($name);
        }
    }

    /**
     * destructor
     *
     * @see     PMA_File::cleanUp()
     * @access  public
     * @uses    PMA_File::cleanUp()
     */
    function __destruct()
    {
        $this->cleanUp();
    }

    /**
     * deletes file if it is temporary, usally from a moved upload file
     *
     * @access  public
     * @uses    PMA_File::delet()
     * @uses    PMA_File::isTemp()
     * @return  boolean success
     */
    function cleanUp()
    {
        if ($this->isTemp()) {
            return $this->delete();
        }

        return true;
    }

    /**
     * deletes the file
     *
     * @access  public
     * @uses    PMA_File::getName()
     * @uses    unlink()
     * @return  boolean success
     */
    function delete()
    {
        return unlink($this->getName());
    }

    /**
     * checks or sets the temp flag for this file
     * file objects with temp flags are deleted with object destruction
     *
     * @access  public
     * @uses    PMA_File::$_is_temp to set and read it
     * @param   boolean sets the temp flag
     * @return  boolean PMA_File::$_is_temp
     */
    function isTemp($is_temp = null)
    {
        if (null !== $is_temp) {
            $this->_is_temp = (bool) $is_temp;
        }

        return $this->_is_temp;
    }

    /**
     * accessor
     *
     * @access  public
     * @uses    PMA_File::$_name
     * @param   string  $name   file name
     */
    function setName($name)
    {
        $this->_name = trim($name);
    }

    /**
     * @access  public
     * @uses    PMA_File::getName()
     * @uses    PMA_File::isUploaded()
     * @uses    PMA_File::checkUploadedFile()
     * @uses    PMA_File::isReadable()
     * @uses    PMA_File::$_content
     * @uses    function_exists()
     * @uses    file_get_contents()
     * @uses    filesize()
     * @uses    fread()
     * @uses    fopen()
     * @uses    bin2hex()
     * @return  string  binary file content
     */
    function getContent($as_binary = true, $offset = 0, $length = null)
    {
        if (null === $this->_content) {
            if ($this->isUploaded() && ! $this->checkUploadedFile()) {
                return false;
            }

            if (! $this->isReadable()) {
                return false;
            }

            if (function_exists('file_get_contents')) {
                $this->_content = file_get_contents($this->getName());
            } elseif ($size = filesize($this->getName())) {
                $this->_content = fread(fopen($this->getName(), 'rb'), $size);
            }
        }

        if (! empty($this->_content) && $as_binary) {
            return '0x' . bin2hex($this->_content);
        }

        if (null !== $length) {
            return substr($this->_content, $offset, $length);
        } elseif ($offset > 0) {
            return substr($this->_content, $offset);
        }

        return $this->_content;
    }

    /**
     * @access  public
     * @uses    PMA_File::getName()
     * @uses    is_uploaded_file()
     */
    function isUploaded()
    {
        return is_uploaded_file($this->getName());
    }

    /**
     * accessor
     *
     * @access  public
     * @uses    PMA_File::$name as return value
     * @return  string  PMA_File::$_name
     */
    function getName()
    {
        return $this->_name;
    }

    /**
     * @todo replace error message with localized string
     * @access  public
     * @uses    PMA_File::isUploaded()
     * @uses    PMA_File::setName()
     * @uses    PMA_File::$_error_message
     * @param   string  name of file uploaded
     * @return  boolean success
     */
    function setUploadedFile($name)
    {
        $this->setName($name);

        if (! $this->isUploaded()) {
            $this->setName(null);
            $this->_error_message = 'not an uploaded file';
            return false;
        }

        return true;
    }

    /**
     * @access  public
     * @uses    PMA_File::fetchUploadedFromTblChangeRequestMultiple()
     * @uses    PMA_File::setUploadedFile()
     * @uses    PMA_File::setRecentBLOBReference()
     * @uses    curl_setopt_array()
     * @uses    PMA_File::$_error_message
     * @uses    $_FILES
     * @param   string  $key the md5 hash of the column name
     * @param   string  $rownumber
     * @return  boolean success
     */
    function setUploadedFromTblChangeRequest($key, $rownumber)
    {
        if (! isset($_FILES['fields_upload'])  || empty($_FILES['fields_upload']['name']['multi_edit'][$rownumber][$key])) {
            return false;
        }
        $file = PMA_File::fetchUploadedFromTblChangeRequestMultiple($_FILES['fields_upload'], $rownumber, $key);

        // for blobstreaming
        $is_bs_upload = FALSE;

        // check if this field requires a repository upload
        if (isset($_REQUEST['upload_blob_repo']['multi_edit'][$rownumber][$key])) {
            $is_bs_upload = ($_REQUEST['upload_blob_repo']['multi_edit'][$rownumber][$key] == "on") ? TRUE : FALSE;
        }
        // if request is an upload to the BLOB repository
        if ($is_bs_upload) {
            $bs_db = $_REQUEST['db'];
            $bs_table = $_REQUEST['table'];
            $tmp_filename = $file['tmp_name'];
            $tmp_file_type = $file['type'];

            if (! $tmp_file_type) {
                $tmp_file_type = NULL;
            }

            if (! $bs_db || ! $bs_table) {
                $this->_error_message = $GLOBALS['strUploadErrorUnknown'];
                return FALSE;
            }
            $blob_url =  PMA_BS_UpLoadFile($bs_db, $bs_table, $tmp_file_type, $tmp_filename);
            PMA_File::setRecentBLOBReference($blob_url);
         }   // end if ($is_bs_upload)

        // check for file upload errors
        switch ($file['error']) {
            // we do not use the PHP constants here cause not all constants
            // are defined in all versions of PHP - but the correct constants names
            // are given as comment
            case 0: //UPLOAD_ERR_OK:
                return $this->setUploadedFile($file['tmp_name']);
                break;
            case 4: //UPLOAD_ERR_NO_FILE:
                break;
            case 1: //UPLOAD_ERR_INI_SIZE:
                $this->_error_message = __('The uploaded file exceeds the upload_max_filesize directive in php.ini.');
                break;
            case 2: //UPLOAD_ERR_FORM_SIZE:
                $this->_error_message = __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.');
                break;
            case 3: //UPLOAD_ERR_PARTIAL:
                $this->_error_message = __('The uploaded file was only partially uploaded.');
                break;
            case 6: //UPLOAD_ERR_NO_TMP_DIR:
                $this->_error_message = __('Missing a temporary folder.');
                break;
            case 7: //UPLOAD_ERR_CANT_WRITE:
                $this->_error_message = __('Failed to write file to disk.');
                break;
            case 8: //UPLOAD_ERR_EXTENSION:
                $this->_error_message = __('File upload stopped by extension.');
                break;
            default:
                $this->_error_message = __('Unknown error in file upload.');
        } // end switch

        return false;
    }

    /**
     * strips some dimension from the multi-dimensional array from $_FILES
     *
     * <code>
     * $file['name']['multi_edit'][$rownumber][$key] = [value]
     * $file['type']['multi_edit'][$rownumber][$key] = [value]
     * $file['size']['multi_edit'][$rownumber][$key] = [value]
     * $file['tmp_name']['multi_edit'][$rownumber][$key] = [value]
     * $file['error']['multi_edit'][$rownumber][$key] = [value]
     *
     * // becomes:
     *
     * $file['name'] = [value]
     * $file['type'] = [value]
     * $file['size'] = [value]
     * $file['tmp_name'] = [value]
     * $file['error'] = [value]
     * </code>
     *
     * @todo re-check if requirements changes to PHP >= 4.2.0
     * @access  public
     * @static
     * @param   array   $file       the array
     * @param   string  $rownumber
     * @param   string  $key
     * @return  array
     */
    function fetchUploadedFromTblChangeRequestMultiple($file, $rownumber, $key)
    {
        $new_file = array(
            'name' => $file['name']['multi_edit'][$rownumber][$key],
            'type' => $file['type']['multi_edit'][$rownumber][$key],
            'size' => $file['size']['multi_edit'][$rownumber][$key],
            'tmp_name' => $file['tmp_name']['multi_edit'][$rownumber][$key],
            'error' => $file['error']['multi_edit'][$rownumber][$key],
        );

        return $new_file;
    }

    /**
     * sets the name if the file to the one selected in the tbl_change form
     *
     * @access  public
     * @uses    $_REQUEST
     * @uses    PMA_File::setLocalSelectedFile()
     * @uses    is_string()
     * @param   string  $key the md5 hash of the column name
     * @param   string  $rownumber
     * @return  boolean success
     */
    function setSelectedFromTblChangeRequest($key, $rownumber = null)
    {
        if (! empty($_REQUEST['fields_uploadlocal']['multi_edit'][$rownumber][$key])
         && is_string($_REQUEST['fields_uploadlocal']['multi_edit'][$rownumber][$key])) {
            // ... whether with multiple rows ...
            // for blobstreaming
            $is_bs_upload = FALSE;

            // check if this field requires a repository upload
            if (isset($_REQUEST['upload_blob_repo']['multi_edit'][$rownumber][$key])) {
                $is_bs_upload = ($_REQUEST['upload_blob_repo']['multi_edit'][$rownumber][$key] == "on") ? TRUE : FALSE;
            }

            // is a request to upload file to BLOB repository using uploadDir mechanism
            if ($is_bs_upload) {
                $bs_db = $_REQUEST['db'];
                $bs_table = $_REQUEST['table'];
                $tmp_filename = $GLOBALS['cfg']['UploadDir'] . '/' . $_REQUEST['fields_uploadlocal_' . $key]['multi_edit'][$rownumber];

                // check if fileinfo library exists
                if ($PMA_Config->get('FILEINFO_EXISTS')) {
                // attempt to init fileinfo
                    $finfo = finfo_open(FILEINFO_MIME);

                    // fileinfo exists
                    if ($finfo) {
                        // pass in filename to fileinfo and close fileinfo handle after
                        $tmp_file_type = finfo_file($finfo, $tmp_filename);
                        finfo_close($finfo);
                    }
                } else {
                    // no fileinfo library exists, use file command
                    $tmp_file_type = exec("file -bi " . escapeshellarg($tmp_filename));
                }

                if (! $tmp_file_type) {
                    $tmp_file_type = NULL;
                }

                if (! $bs_db || !$bs_table) {
                    $this->_error_message = $GLOBALS['strUploadErrorUnknown'];
                    return FALSE;
                }
                $blob_url = PMA_BS_UpLoadFile($bs_db, $bs_table, $tmp_file_type, $tmp_filename);
                PMA_File::setRecentBLOBReference($blob_url);
            }   // end if ($is_bs_upload)

            return $this->setLocalSelectedFile($_REQUEST['fields_uploadlocal']['multi_edit'][$rownumber][$key]);
        } else {
            return false;
        }
    }

    /**
     * @access  public
     * @uses    PMA_File->$_error_message as return value
     * @return  string  error message
     */
    function getError()
    {
        return $this->_error_message;
    }

    /**
     * @access  public
     * @uses    PMA_File->$_error_message to check it
     * @return  boolean whether an error occured or not
     */
    function isError()
    {
        return ! empty($this->_error_message);
    }

    /**
     * checks the superglobals provided if the tbl_change form is submitted
     * and uses the submitted/selected file
     *
     * @access  public
     * @uses    PMA_File::setUploadedFromTblChangeRequest()
     * @uses    PMA_File::setSelectedFromTblChangeRequest()
     * @param   string  $key the md5 hash of the column name
     * @param   string  $rownumber
     * @return  boolean success
     */
    function checkTblChangeForm($key, $rownumber)
    {
        if ($this->setUploadedFromTblChangeRequest($key, $rownumber)) {
            // well done ...
            $this->_error_message = '';
            return true;
        } elseif ($this->setSelectedFromTblChangeRequest($key, $rownumber)) {
            // well done ...
            $this->_error_message = '';
            return true;
        }
        // all failed, whether just no file uploaded/selected or an error

        return false;
    }

    /**
     *
     * @access  public
     * @uses    PMA_File::setName()
     * @uses    PMA_securePath()
     * @uses    PMA_userDir()
     * @uses    $GLOBALS['cfg']['UploadDir']
     * @param   string  $name
     * @return  boolean success
     */
    function setLocalSelectedFile($name)
    {
        if (empty($GLOBALS['cfg']['UploadDir'])) return false;

        $this->setName(PMA_userDir($GLOBALS['cfg']['UploadDir']) . PMA_securePath($name));
        if (! $this->isReadable()) {
            $this->_error_message = __('File could not be read');
            $this->setName(null);
            return false;
        }

        return true;
    }

    /**
     * @access  public
     * @uses    PMA_File::getName()
     * @uses    is_readable()
     * @uses    ob_start()
     * @uses    ob_end_clean()
     * @return  boolean whether the file is readable or not
     */
    function isReadable()
    {
        // suppress warnings from being displayed, but not from being logged
        // any file access outside of open_basedir will issue a warning
        ob_start();
        $is_readable = is_readable($this->getName());
        ob_end_clean();
        return $is_readable;
    }

    /**
     * If we are on a server with open_basedir, we must move the file
     * before opening it. The FAQ 1.11 explains how to create the "./tmp"
     * directory - if needed
     *
     * @todo replace error message with localized string
     * @todo move check of $cfg['TempDir'] into PMA_Config?
     * @access  public
     * @uses    $cfg['TempDir']
     * @uses    PMA_File::isReadable()
     * @uses    PMA_File::getName()
     * @uses    PMA_File::setName()
     * @uses    PMA_File::isTemp()
     * @uses    PMA_File::$_error_message
     * @uses    is_dir()
     * @uses    mkdir()
     * @uses    chmod()
     * @uses    is_writable()
     * @uses    basename()
     * @uses    move_uploaded_file()
     * @uses    ob_start()
     * @uses    ob_end_clean()
     * @return  boolean whether uploaded fiel is fine or not
     */
    function checkUploadedFile()
    {
        if ($this->isReadable()) {
            return true;
        }

        if (empty($GLOBALS['cfg']['TempDir']) || ! is_writable($GLOBALS['cfg']['TempDir'])) {
            // cannot create directory or access, point user to FAQ 1.11
            $this->_error_message = __('Error moving the uploaded file, see [a@./Documentation.html#faq1_11@Documentation]FAQ 1.11[/a]');
            return false;
        }

        $new_file_to_upload = tempnam(realpath($GLOBALS['cfg']['TempDir']), basename($this->getName()));

        // suppress warnings from being displayed, but not from being logged
        // any file access outside of open_basedir will issue a warning
        ob_start();
        $move_uploaded_file_result = move_uploaded_file($this->getName(), $new_file_to_upload);
        ob_end_clean();
        if (! $move_uploaded_file_result) {
            $this->_error_message = 'error while moving uploaded file';
            return false;
        }

        $this->setName($new_file_to_upload);
        $this->isTemp(true);

        if (! $this->isReadable()) {
            $this->_error_message = 'cannot read (moved) upload file';
            return false;
        }

        return true;
    }

    /**
     * Detects what compression filse uses
     *
     * @todo    move file read part into readChunk() or getChunk()
     * @todo    add support for compression plugins
     * @uses    PMA_File::$_compression to set it
     * @uses    PMA_File::getName()
     * @uses    fopen()
     * @uses    fread()
     * @uses    strlen()
     * @uses    fclose()
     * @uses    chr()
     * @uses    substr()
     * @access  protected
     * @return  string MIME type of compression, none for none
     */
    function _detectCompression()
    {
        // suppress warnings from being displayed, but not from being logged
        // f.e. any file access outside of open_basedir will issue a warning
        ob_start();
        $file = fopen($this->getName(), 'rb');
        ob_end_clean();

        if (! $file) {
            $this->_error_message = __('File could not be read');
            return false;
        }

        /**
         * @todo
         * get registered plugins for file compression

        foreach (PMA_getPlugins($type = 'compression') as $plugin) {
            if (call_user_func_array(array($plugin['classname'], 'canHandle'), array($this->getName()))) {
                $this->setCompressionPlugin($plugin);
                break;
            }
        }
         */

        $test = fread($file, 4);
        $len = strlen($test);
        fclose($file);

        if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
            $this->_compression = 'application/gzip';
        } elseif ($len >= 3 && substr($test, 0, 3) == 'BZh') {
            $this->_compression = 'application/bzip2';
        } elseif ($len >= 4 && $test == "PK\003\004") {
            $this->_compression = 'application/zip';
        } else {
            $this->_compression = 'none';
        }

        return $this->_compression;
    }

    /**
     * whether the content should be decompressed before returned
     */
    function setDecompressContent($decompress)
    {
        $this->_decompress = (bool) $decompress;
    }

    function getHandle()
    {
        if (null === $this->_handle) {
            $this->open();
        }
        return $this->_handle;
    }

    function setHandle($handle)
    {
        $this->_handle = $handle;
    }

    /**
     *
     */
    function open()
    {
        if (! $this->_decompress) {
            $this->_handle = @fopen($this->getName(), 'r');
        }

        switch ($this->getCompression()) {
            case false:
                return false;
            case 'application/bzip2':
                if ($GLOBALS['cfg']['BZipDump'] && @function_exists('bzopen')) {
                    $this->_handle = @bzopen($this->getName(), 'r');
                } else {
                    $this->_error_message = sprintf(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'), $this->getCompression());
                    return false;
                }
                break;
            case 'application/gzip':
                if ($GLOBALS['cfg']['GZipDump'] && @function_exists('gzopen')) {
                    $this->_handle = @gzopen($this->getName(), 'r');
                } else {
                    $this->_error_message = sprintf(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'), $this->getCompression());
                    return false;
                }
                break;
            case 'application/zip':
                if ($GLOBALS['cfg']['ZipDump'] && @function_exists('zip_open')) {
                    include_once './libraries/zip_extension.lib.php';
                    $result = PMA_getZipContents($this->getName());
                    if (! empty($result['error'])) {
                        $this->_error_message = PMA_Message::rawError($result['error']);
                        return false;
                    } else {
                        $this->content_uncompressed = $result['data'];
                    }
                    unset($result);
                } else {
                    $this->_error_message = sprintf(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'), $this->getCompression());
                    return false;
                }
                break;
            case 'none':
                $this->_handle = @fopen($this->getName(), 'r');
                break;
            default:
                $this->_error_message = sprintf(__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.'), $this->getCompression());
                return false;
                break;
        }

    }

    function getCharset()
    {
        return $this->_charset;
    }

    function setCharset($charset)
    {
        $this->_charset = $charset;
    }

    /**
     * @uses    PMA_File::$_compression as return value
     * @uses    PMA_File::detectCompression()
     * @return  string MIME type of compression, none for none
     * @access  public
     */
    function getCompression()
    {
        if (null === $this->_compression) {
            return $this->_detectCompression();
        }

        return $this->_compression;
    }

    /**
     * advances the file pointer in the file handle by $length bytes/chars
     *
     * @param   integer $length numbers of chars/bytes to skip
     * @return  boolean
     * @todo this function is unused
     */
    function advanceFilePointer($length)
    {
        while ($length > 0) {
            // Disable read progresivity, otherwise we eat all memory!
            $read_multiply = 1; // required?
            $this->getNextChunk($length);
            $length -= $this->getChunkSize();
        }
    }

    /**
     * http://bugs.php.net/bug.php?id=29532
     * bzip reads a maximum of 8192 bytes on windows systems
     * @todo this function is unused
     */
    function getNextChunk($max_size = null)
    {
        if (null !== $max_size) {
            $size = min($max_size, $this->getChunkSize());
        } else {
            $size = $this->getChunkSize();
        }

        // $result = $this->handler->getNextChunk($size);
        $result = '';
        switch ($this->getCompression()) {
            case 'application/bzip2':
                $result = '';
                while (strlen($result) < $size - 8192 && ! feof($this->getHandle())) {
                    $result .= bzread($this->getHandle(), $size);
                }
                break;
            case 'application/gzip':
                $result = gzread($this->getHandle(), $size);
                break;
            case 'application/zip':
                /*
                 * if getNextChunk() is used some day,
                 * replace this code by code similar to the one
                 * in open()
                 *
                include_once './libraries/unzip.lib.php';
                $import_handle = new SimpleUnzip();
                $import_handle->ReadFile($this->getName());
                if ($import_handle->Count() == 0) {
                    $this->_error_message = __('No files found inside ZIP archive!');
                    return false;
                } elseif ($import_handle->GetError(0) != 0) {
                    $this->_error_message = __('Error in ZIP archive:')
                        . ' ' . $import_handle->GetErrorMsg(0);
                    return false;
                } else {
                    $result = $import_handle->GetData(0);
                }
                 */
                break;
            case 'none':
                $result = fread($this->getHandle(), $size);
                break;
            default:
                return false;
        }

        echo $size . ' - ';
        echo strlen($result) . ' - ';
        echo (@$GLOBALS['__len__'] += strlen($result)) . ' - ';
        echo $this->_error_message;
        echo '<hr />';

        if ($GLOBALS['charset_conversion']) {
            $result = PMA_convert_string($this->getCharset(), $GLOBALS['charset'], $result);
        } else {
            /**
             * Skip possible byte order marks (I do not think we need more
             * charsets, but feel free to add more, you can use wikipedia for
             * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
             *
             * @todo BOM could be used for charset autodetection
             */
            if ($this->getOffset() === 0) {
                // UTF-8
                if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
                    $result = substr($result, 3);
                // UTF-16 BE, LE
                } elseif (strncmp($result, "\xFE\xFF", 2) == 0
                 || strncmp($result, "\xFF\xFE", 2) == 0) {
                    $result = substr($result, 2);
                }
            }
        }

        $this->_offset += $size;
        if (0 === $result) {
            return true;
        }
        return $result;
    }

    function getOffset()
    {
        return $this->_offset;
    }

    function getChunkSize()
    {
        return $this->_chunk_size;
    }

    function setChunkSize($chunk_size)
    {
        $this->_chunk_size = (int) $chunk_size;
    }

    function getContentLength()
    {
        return strlen($this->_content);
    }

    function eof()
    {
        if ($this->getHandle()) {
            return feof($this->getHandle());
        } else {
            return ($this->getOffset() >= $this->getContentLength());
        }

    }

    /**
     * sets reference to most recent BLOB repository reference
     *
     * @access  public
     * @param   string - BLOB repository reference
    */
    static function setRecentBLOBReference($ref)
    {
        PMA_File::$_recent_bs_reference = $ref;
    }

    /**
     * retrieves reference to most recent BLOB repository reference
     *
     * @access  public
     * @return  string - most recent BLOB repository reference
    */
    static function getRecentBLOBReference()
    {
        $ref = PMA_File::$_recent_bs_reference;
        PMA_File::$_recent_bs_reference = NULL;

        return $ref;
    }
}
?>


text:
Octopost
========

Octopost is an app that gives you a graphical user interface for creating and writing your blog posts and octopress pages.


text:
/*
 *= require jquery.alerts/jquery.alerts
*/

#card_options {
  padding-top: 30px;
}


text:
require "json"

module Rbots::Plugin
  # The GoogleImages API has been deprecated :(
  class GoogleImages
    include Hipbot::Plugin

    ANIMATE_ME_DESC = [
      "animate me <query> - The same thing as `image me`, except adds a few",
      "parameters to try to return an animated GIF instead.",
    ].join(" ").freeze
    IMAGE_ME_DESC = [
      "image me <query> - Queries Google Images for <query> and returns a",
      "random top result.",
    ].join(" ").freeze
    PNG_SUFFIX = "#.png".freeze
    SEARCH_URL = "http://ajax.googleapis.com/ajax/services/search/images".freeze

    desc(ANIMATE_ME_DESC)
    on(/(?:animate)(?: me)? (.*)/i) do |match|
      reply_if image_url(match, true)
    end

    desc(IMAGE_ME_DESC)
    on(/(?:image|img)(?: me)? (.*)/i) do |match|
      reply_if image_url(match)
    end

    desc 'stanley me - returns a selfie of stanley'
    on /stanley me\s+$/ do
      reply_if image_url('axolotl')
    end

    private

    def reply_if(m)
      reply m if m
    end

    def image_url(query, animated = false)
      params = {
        "q" => query,
        "safe" => "active",
        "v" => "1.0",
        "zsz" => 8,
      }
      params["imgtype"] = "animated" if animated
      uri = URI(SEARCH_URL)
      uri.query = params.map { |pair| pair.join("=") }.join("&")
      response_data = JSON.parse(Net::HTTP.get(uri))
      images = response_data["responseData"]["results"]
      images.length.zero? ? "" : images.sample["unescapedUrl"].concat(PNG_SUFFIX)
    end
  end
end


text:
const Organizations = new Meteor.Collection("organizations");

export default Organizations;


text:
#ifndef __XMLSEC_OPENSSL_X509_H__
#define __XMLSEC_OPENSSL_X509_H__

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#ifndef XMLSEC_NO_X509

#include <openssl/x509.h>

#include <xmlsec/xmlsec.h>
#include <xmlsec/keys.h>
#include <xmlsec/transforms.h>

/**
 * XMLSEC_STACK_OF_X509:
 *
 * Macro. To make docbook happy.
 */
#define XMLSEC_STACK_OF_X509            STACK_OF(X509)

/**
 * XMLSEC_STACK_OF_X509_CRL:
 *
 * Macro. To make docbook happy.
 */
#define XMLSEC_STACK_OF_X509_CRL        STACK_OF(X509_CRL)

/**
 * xmlSecOpenSSLKeyDataX509Id:
 *
 * The OpenSSL X509 data klass.
 */
#define xmlSecOpenSSLKeyDataX509Id \
        xmlSecOpenSSLKeyDataX509GetKlass()
XMLSEC_CRYPTO_EXPORT xmlSecKeyDataId    xmlSecOpenSSLKeyDataX509GetKlass(void);

XMLSEC_CRYPTO_EXPORT X509*              xmlSecOpenSSLKeyDataX509GetKeyCert(xmlSecKeyDataPtr data);
XMLSEC_CRYPTO_EXPORT int                xmlSecOpenSSLKeyDataX509AdoptKeyCert(xmlSecKeyDataPtr data,
                                                                         X509* cert);

XMLSEC_CRYPTO_EXPORT int                xmlSecOpenSSLKeyDataX509AdoptCert(xmlSecKeyDataPtr data,
                                                                         X509* cert);
XMLSEC_CRYPTO_EXPORT X509*              xmlSecOpenSSLKeyDataX509GetCert (xmlSecKeyDataPtr data,
                                                                         xmlSecSize pos);
XMLSEC_CRYPTO_EXPORT xmlSecSize         xmlSecOpenSSLKeyDataX509GetCertsSize(xmlSecKeyDataPtr data);

XMLSEC_CRYPTO_EXPORT int                xmlSecOpenSSLKeyDataX509AdoptCrl(xmlSecKeyDataPtr data,
                                                                         X509_CRL* crl);
XMLSEC_CRYPTO_EXPORT X509_CRL*          xmlSecOpenSSLKeyDataX509GetCrl  (xmlSecKeyDataPtr data,
                                                                         xmlSecSize pos);
XMLSEC_CRYPTO_EXPORT xmlSecSize         xmlSecOpenSSLKeyDataX509GetCrlsSize(xmlSecKeyDataPtr data);

XMLSEC_CRYPTO_EXPORT xmlSecKeyDataPtr   xmlSecOpenSSLX509CertGetKey     (X509* cert);

/**
 * xmlSecOpenSSLKeyDataRawX509CertId:
 *
 * The OpenSSL raw X509 certificate klass.
 */
#define xmlSecOpenSSLKeyDataRawX509CertId \
        xmlSecOpenSSLKeyDataRawX509CertGetKlass()
XMLSEC_CRYPTO_EXPORT xmlSecKeyDataId    xmlSecOpenSSLKeyDataRawX509CertGetKlass(void);

/**
 * xmlSecOpenSSLX509StoreId:
 *
 * The OpenSSL X509 store klass.
 */
#define xmlSecOpenSSLX509StoreId \
        xmlSecOpenSSLX509StoreGetKlass()
XMLSEC_CRYPTO_EXPORT xmlSecKeyDataStoreId xmlSecOpenSSLX509StoreGetKlass(void);
XMLSEC_CRYPTO_EXPORT X509*              xmlSecOpenSSLX509StoreFindCert  (xmlSecKeyDataStorePtr store,
                                                                         xmlChar *subjectName,
                                                                         xmlChar *issuerName,
                                                                         xmlChar *issuerSerial,
                                                                         xmlChar *ski,
                                                                         xmlSecKeyInfoCtx* keyInfoCtx);
XMLSEC_CRYPTO_EXPORT X509*              xmlSecOpenSSLX509StoreVerify    (xmlSecKeyDataStorePtr store,
                                                                         XMLSEC_STACK_OF_X509* certs,
                                                                         XMLSEC_STACK_OF_X509_CRL* crls,
                                                                         xmlSecKeyInfoCtx* keyInfoCtx);
XMLSEC_CRYPTO_EXPORT int                xmlSecOpenSSLX509StoreAdoptCert (xmlSecKeyDataStorePtr store,
                                                                         X509* cert,
                                                                         xmlSecKeyDataType type);
XMLSEC_CRYPTO_EXPORT int                xmlSecOpenSSLX509StoreAdoptCrl  (xmlSecKeyDataStorePtr store,
                                                                         X509_CRL* crl);
XMLSEC_CRYPTO_EXPORT int                xmlSecOpenSSLX509StoreAddCertsPath(xmlSecKeyDataStorePtr store,
                                                                         const char* path);
XMLSEC_CRYPTO_EXPORT int                xmlSecOpenSSLX509StoreAddCertsFile(xmlSecKeyDataStorePtr store,
                                                                         const char* file);

#endif /* XMLSEC_NO_X509 */

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __XMLSEC_OPENSSL_X509_H__ */


text:
package org.apache.flink.table.runtime.operators.over.frame;

import org.apache.flink.table.data.RowData;
import org.apache.flink.table.runtime.context.ExecutionContext;
import org.apache.flink.table.runtime.dataview.PerKeyStateDataViewStore;
import org.apache.flink.table.runtime.generated.AggsHandleFunction;
import org.apache.flink.table.runtime.generated.GeneratedAggsHandleFunction;
import org.apache.flink.table.runtime.util.ResettableExternalBuffer;

/**
 * The insensitive window frame calculates the statements which shouldn't care the window frame, for
 * example RANK/DENSE_RANK/PERCENT_RANK/CUME_DIST/ROW_NUMBER.
 */
public class InsensitiveOverFrame implements OverWindowFrame {

    private GeneratedAggsHandleFunction aggsHandleFunction;
    private AggsHandleFunction processor;

    public InsensitiveOverFrame(GeneratedAggsHandleFunction aggsHandleFunction) {
        this.aggsHandleFunction = aggsHandleFunction;
    }

    @Override
    public void open(ExecutionContext ctx) throws Exception {
        processor =
                aggsHandleFunction.newInstance(ctx.getRuntimeContext().getUserCodeClassLoader());
        processor.open(new PerKeyStateDataViewStore(ctx.getRuntimeContext()));

        this.aggsHandleFunction = null;
    }

    @Override
    public void prepare(ResettableExternalBuffer rows) throws Exception {
        // reset the accumulator value
        processor.setAccumulators(processor.createAccumulators());
    }

    @Override
    public RowData process(int index, RowData current) throws Exception {
        processor.accumulate(current);
        return processor.getValue();
    }
}


text:
BOOL IsPasswordCreationUserEnabled();

// Whether the password manager branding UI update feature is enabled.
BOOL IsPasswordManagerBrandingUpdateEnable();

// Whether favicons should be displayed.
BOOL IsFaviconEnabled();

#endif  // IOS_CHROME_CREDENTIAL_PROVIDER_EXTENSION_UI_FEATURE_FLAGS_H_


text:
/* jshint quotmark: single */
/* jshint evil: true */

var squiffy = {};

(function () {
    'use strict';

    squiffy.story = {};

    var initLinkHandler = function () {
        var handleLink = function (link) {
            if (link.hasClass('disabled')) return;
            var passage = link.data('passage');
            var section = link.data('section');
            var rotateAttr = link.attr('data-rotate');
            var sequenceAttr = link.attr('data-sequence');
            if (passage) {
                disableLink(link);
                squiffy.set('_turncount', squiffy.get('_turncount') + 1);
                passage = processLink(passage);
                if (passage) {
                    currentSection.append('
');
                    squiffy.story.passage(passage);
                }
                var turnPassage = '@' + squiffy.get('_turncount');
                if (turnPassage in squiffy.story.section.passages) {
                    squiffy.story.passage(turnPassage);
                }
                if ('@last' in squiffy.story.section.passages && squiffy.get('_turncount')>= squiffy.story.section.passageCount) {
                    squiffy.story.passage('@last');
                }
            }
            else if (section) {
                currentSection.append('
');
                disableLink(link);
                section = processLink(section);
                squiffy.story.go(section);
            }
            else if (rotateAttr || sequenceAttr) {
                var result = rotate(rotateAttr || sequenceAttr, rotateAttr ? link.text() : '');
                link.html(result[0].replace(/"/g, '"').replace(/'/g, '\''));
                var dataAttribute = rotateAttr ? 'data-rotate' : 'data-sequence';
                link.attr(dataAttribute, result[1]);
                if (!result[1]) {
                    disableLink(link);
                }
                if (link.attr('data-attribute')) {
                    squiffy.set(link.attr('data-attribute'), result[0]);
                }
                squiffy.story.save();
            }
        };

        squiffy.ui.output.on('click', 'a.squiffy-link', function () {
            handleLink(jQuery(this));
        });

        squiffy.ui.output.on('keypress', 'a.squiffy-link', function (e) {
            if (e.which !== 13) return;
            handleLink(jQuery(this));
        });

        squiffy.ui.output.on('mousedown', 'a.squiffy-link', function (event) {
            event.preventDefault();
        });
    };

    var disableLink = function (link) {
        link.addClass('disabled');
        link.attr('tabindex', -1);
    }

    squiffy.story.begin = function () {
        if (!squiffy.story.load()) {
            squiffy.story.go(squiffy.story.start);
        }
    };

    var processLink = function(link) {
        link = String(link);
        var sections = link.split(',');
        var first = true;
        var target = null;
        sections.forEach(function (section) {
            section = section.trim();
            if (startsWith(section, '@replace ')) {
                replaceLabel(section.substring(9));
            }
            else {
                if (first) {
                    target = section;
                }
                else {
                    setAttribute(section);
                }
            }
            first = false;
        });
        return target;
    };

    var setAttribute = function(expr) {
    expr = expr.replace(/^(\w*\s*):=(.*)$/, (match,name,value) => (name + "=" + squiffy.ui.processText(value)));
        var lhs, rhs, op, value;
        var setRegex = /^([\w]*)\s*=\s*(.*)$/;
        var setMatch = setRegex.exec(expr);
        if (setMatch) {
            lhs = setMatch[1];
            rhs = setMatch[2];
            if (isNaN(rhs)) {
                if(startsWith(rhs,"@")) rhs=squiffy.get(rhs.substring(1));
                squiffy.set(lhs, rhs);
            }
            else {
                squiffy.set(lhs, parseFloat(rhs));
            }
        }
        else {
            var incDecRegex = /^([\w]*)\s*([\+\-\*\/])=\s*(.*)$/;
            var incDecMatch = incDecRegex.exec(expr);
            if (incDecMatch) {
                lhs = incDecMatch[1];
                op = incDecMatch[2];
                rhs = incDecMatch[3];
                if(startsWith(rhs,"@")) rhs=squiffy.get(rhs.substring(1));
                rhs = parseFloat(rhs);
                value = squiffy.get(lhs);
                if (value === null) value = 0;
                if (op == '+') {
                    value += rhs;
                }
                if (op == '-') {
                    value -= rhs;
                }
                if (op == '*') {
                    value *= rhs;
                }
                if (op == '/') {
                    value /= rhs;
                }
                squiffy.set(lhs, value);
            }
            else {
                value = true;
                if (startsWith(expr, 'not ')) {
                    expr = expr.substring(4);
                    value = false;
                }
                squiffy.set(expr, value);
            }
        }
    };

    var replaceLabel = function(expr) {
        var regex = /^([\w]*)\s*=\s*(.*)$/;
        var match = regex.exec(expr);
        if (!match) return;
        var label = match[1];
        var text = match[2];
        if (text in squiffy.story.section.passages) {
            text = squiffy.story.section.passages[text].text;
        }
        else if (text in squiffy.story.sections) {
            text = squiffy.story.sections[text].text;
        }
        var stripParags = /^
(.*)<\/p>$/;
        var stripParagsMatch = stripParags.exec(text);
        if (stripParagsMatch) {
            text = stripParagsMatch[1];
        }
        var $labels = squiffy.ui.output.find('.squiffy-label-' + label);
        $labels.fadeOut(1000, function() {
            $labels.html(squiffy.ui.processText(text));
            $labels.fadeIn(1000, function() {
                squiffy.story.save();
            });
        });
    };

    squiffy.story.go = function(section) {
        squiffy.set('_transition', null);
        newSection();
        squiffy.story.section = squiffy.story.sections[section];
        if (!squiffy.story.section) return;
        squiffy.set('_section', section);
        setSeen(section);
        var master = squiffy.story.sections[''];
        if (master) {
            squiffy.story.run(master);
            squiffy.ui.write(master.text);
        }
        squiffy.story.run(squiffy.story.section);
        // The JS might have changed which section we're in
        if (squiffy.get('_section') == section) {
            squiffy.set('_turncount', 0);
            squiffy.ui.write(squiffy.story.section.text);
            squiffy.story.save();
        }
    };

    squiffy.story.run = function(section) {
        if (section.clear) {
            squiffy.ui.clearScreen();
        }
        if (section.attributes) {
            processAttributes(section.attributes.map(line => line.replace(/^random\s*:\s*(\w+)\s*=\s*(.+)/i, (line, attr, options) => (options = options.split("|")) ? attr + " = " + options[Math.floor(Math.random() * options.length)] : line)));
        }
        if (section.js) {
            section.js();
        }
    };

    squiffy.story.passage = function(passageName) {
        var passage = squiffy.story.section.passages[passageName];
        var masterSection = squiffy.story.sections[''];
        if (!passage && masterSection) passage = masterSection.passages[passageName];
        if (!passage) return;
        setSeen(passageName);
        if (masterSection) {
            var masterPassage = masterSection.passages[''];
            if (masterPassage) {
                squiffy.story.run(masterPassage);
                squiffy.ui.write(masterPassage.text);
            }
        }
        var master = squiffy.story.section.passages[''];
        if (master) {
            squiffy.story.run(master);
            squiffy.ui.write(master.text);
        }
        squiffy.story.run(passage);
        squiffy.ui.write(passage.text);
        squiffy.story.save();
    };

    var processAttributes = function(attributes) {
        attributes.forEach(function (attribute) {
            if (startsWith(attribute, '@replace ')) {
                replaceLabel(attribute.substring(9));
            }
            else {
                setAttribute(attribute);
            }
        });
    };

    squiffy.story.restart = function() {
        if (squiffy.ui.settings.persist && window.localStorage) {
            var keys = Object.keys(localStorage);
            jQuery.each(keys, function (idx, key) {
                if (startsWith(key, squiffy.story.id)) {
                    localStorage.removeItem(key);
                }
            });
        }
        else {
            squiffy.storageFallback = {};
        }
        if (squiffy.ui.settings.scroll === 'element') {
            squiffy.ui.output.html('');
            squiffy.story.begin();
        }
        else {
            location.reload();
        }
    };

    squiffy.story.save = function() {
        squiffy.set('_output', squiffy.ui.output.html());
    };

    squiffy.story.load = function() {
        var output = squiffy.get('_output');
        if (!output) return false;
        squiffy.ui.output.html(output);
        currentSection = jQuery('#' + squiffy.get('_output-section'));
        squiffy.story.section = squiffy.story.sections[squiffy.get('_section')];
        var transition = squiffy.get('_transition');
        if (transition) {
            eval('(' + transition + ')()');
        }
        return true;
    };

    var setSeen = function(sectionName) {
        var seenSections = squiffy.get('_seen_sections');
        if (!seenSections) seenSections = [];
        if (seenSections.indexOf(sectionName) == -1) {
            seenSections.push(sectionName);
            squiffy.set('_seen_sections', seenSections);
        }
    };

    squiffy.story.seen = function(sectionName) {
        var seenSections = squiffy.get('_seen_sections');
        if (!seenSections) return false;
        return (seenSections.indexOf(sectionName) > -1);
    };

    squiffy.ui = {};

    var currentSection = null;
    var screenIsClear = true;
    var scrollPosition = 0;

    var newSection = function() {
        if (currentSection) {
            disableLink(jQuery('.squiffy-link', currentSection));
        currentSection.find('input').each(function () {
                set ($(this).data('attribute') || this.id, this.value);
                this.disabled = true;
        });
        currentSection.find("[contenteditable]").each(function () {
                set ($(this).data('attribute') || this.id, this.innerHTML);
                this.disabled = true;
        });
                currentSection.find('textarea').each(function () {
                set ($(this).data('attribute') || this.id, this.value);
                this.disabled = true;
        });

        }

        var sectionCount = squiffy.get('_section-count') + 1;
        squiffy.set('_section-count', sectionCount);
        var id = 'squiffy-section-' + sectionCount;
        currentSection = jQuery('
', {
            id: id,
        }).appendTo(squiffy.ui.output);
        squiffy.set('_output-section', id);
    };

    squiffy.ui.write = function(text) {
        screenIsClear = false;
        scrollPosition = squiffy.ui.output.height();
        currentSection.append(jQuery('
').html(squiffy.ui.processText(text)));
        squiffy.ui.scrollToEnd();
    };

    squiffy.ui.clearScreen = function() {
        squiffy.ui.output.html('');
        screenIsClear = true;
        newSection();
    };

    squiffy.ui.scrollToEnd = function() {
        var scrollTo, currentScrollTop, distance, duration;
        if (squiffy.ui.settings.scroll === 'element') {
            scrollTo = squiffy.ui.output[0].scrollHeight - squiffy.ui.output.height();
            currentScrollTop = squiffy.ui.output.scrollTop();
            if (scrollTo > currentScrollTop) {
                distance = scrollTo - currentScrollTop;
                duration = distance / 0.4;
                squiffy.ui.output.stop().animate({ scrollTop: scrollTo }, duration);
            }
        }
        else {
            scrollTo = scrollPosition;
            currentScrollTop = Math.max(jQuery('body').scrollTop(), jQuery('html').scrollTop());
            if (scrollTo > currentScrollTop) {
                var maxScrollTop = jQuery(document).height() - jQuery(window).height();
                if (scrollTo > maxScrollTop) scrollTo = maxScrollTop;
                distance = scrollTo - currentScrollTop;
                duration = distance / 0.5;
                jQuery('body,html').stop().animate({ scrollTop: scrollTo }, duration);
            }
        }
    };

    squiffy.ui.processText = function(text) {
        function process(text, data) {
            var containsUnprocessedSection = false;
            var open = text.indexOf('{');
            var close;

            if (open > -1) {
                var nestCount = 1;
                var searchStart = open + 1;
                var finished = false;

                while (!finished) {
                    var nextOpen = text.indexOf('{', searchStart);
                    var nextClose = text.indexOf('}', searchStart);

                    if (nextClose > -1) {
                        if (nextOpen > -1 && nextOpen < nextClose) {
                            nestCount++;
                            searchStart = nextOpen + 1;
                        }
                        else {
                            nestCount--;
                            searchStart = nextClose + 1;
                            if (nestCount === 0) {
                                close = nextClose;
                                containsUnprocessedSection = true;
                                finished = true;
                            }
                        }
                    }
                    else {
                        finished = true;
                    }
                }
            }

            if (containsUnprocessedSection) {
                var section = text.substring(open + 1, close);
                var value = processTextCommand(section, data);
                text = text.substring(0, open) + value + process(text.substring(close + 1), data);
            }

            return (text);
        }

        function processTextCommand(text, data) {
            if (startsWith(text, 'if ')) {
                return processTextCommand_If(text, data);
            }
            else if (startsWith(text, 'else:')) {
                return processTextCommand_Else(text, data);
            }
            else if (startsWith(text, 'label:')) {
                return processTextCommand_Label(text, data);
            }
            else if (/^rotate[: ]/.test(text)) {
                return processTextCommand_Rotate('rotate', text, data);
            }
            else if (/^sequence[: ]/.test(text)) {
                return processTextCommand_Rotate('sequence', text, data);
            }
            else if (text in squiffy.story.section.passages) {
                return process(squiffy.story.section.passages[text].text, data);
            }
            else if (text in squiffy.story.sections) {
                return process(squiffy.story.sections[text].text, data);
            }
            else if (startsWith(text,'@') && !startsWith(text,'@replace')) {
                processAttributes(text.substring(1).split(","));
                return "";
            }
            return squiffy.get(text);
        }

        function processTextCommand_If(section, data) {
            var command = section.substring(3);
            var colon = command.indexOf(':');
            if (colon == -1) {
                return ('{if ' + command + '}');
            }

            var text = command.substring(colon + 1);
            var condition = command.substring(0, colon);
            condition = condition.replace("<", "<");
            var operatorRegex = /([\w ]*)(=|<=|>=|<>|<|>)(.*)/;
            var match = operatorRegex.exec(condition);

            var result = false;

            if (match) {
                var lhs = squiffy.get(match[1]);
                var op = match[2];
                var rhs = match[3];

                if(startsWith(rhs,'@')) rhs=squiffy.get(rhs.substring(1));

                if (op == '=' && lhs == rhs) result = true;
                if (op == '<>' && lhs != rhs) result = true;
                if (op == '>' && lhs > rhs) result = true;
                if (op == '<' && lhs < rhs) result = true;
                if (op == '>=' && lhs >= rhs) result = true;
                if (op == '<=' && lhs <= rhs) result = true;
            }
            else {
                var checkValue = true;
                if (startsWith(condition, 'not ')) {
                    condition = condition.substring(4);
                    checkValue = false;
                }

                if (startsWith(condition, 'seen ')) {
                    result = (squiffy.story.seen(condition.substring(5)) == checkValue);
                }
                else {
                    var value = squiffy.get(condition);
                    if (value === null) value = false;
                    result = (value == checkValue);
                }
            }

            var textResult = result ? process(text, data) : '';

            data.lastIf = result;
            return textResult;
        }

        function processTextCommand_Else(section, data) {
            if (!('lastIf' in data) || data.lastIf) return '';
            var text = section.substring(5);
            return process(text, data);
        }

        function processTextCommand_Label(section, data) {
            var command = section.substring(6);
            var eq = command.indexOf('=');
            if (eq == -1) {
                return ('{label:' + command + '}');
            }

            var text = command.substring(eq + 1);
            var label = command.substring(0, eq);

            return '' + process(text, data) + '';
        }

        function processTextCommand_Rotate(type, section, data) {
            var options;
            var attribute = '';
            if (section.substring(type.length, type.length + 1) == ' ') {
                var colon = section.indexOf(':');
                if (colon == -1) {
                    return '{' + section + '}';
                }
                options = section.substring(colon + 1);
                attribute = section.substring(type.length + 1, colon);
            }
            else {
                options = section.substring(type.length + 1);
            }
            var rotation = rotate(options.replace(/"/g, '"').replace(/'/g, '''));
            if (attribute) {
                squiffy.set(attribute, rotation[0]);
            }
            return '' + rotation[0] + '';
        }

        var data = {
            fulltext: text
        };
        return process(text, data);
    };

    squiffy.ui.transition = function(f) {
        squiffy.set('_transition', f.toString());
        f();
    };

    squiffy.storageFallback = {};

    squiffy.set = function(attribute, value) {
        if (typeof value === 'undefined') value = true;
        if (squiffy.ui.settings.persist && window.localStorage) {
            localStorage[squiffy.story.id + '-' + attribute] = JSON.stringify(value);
        }
        else {
            squiffy.storageFallback[attribute] = JSON.stringify(value);
        }
        squiffy.ui.settings.onSet(attribute, value);
    };

    squiffy.get = function(attribute) {
        var result;
        if (squiffy.ui.settings.persist && window.localStorage) {
            result = localStorage[squiffy.story.id + '-' + attribute];
        }
        else {
            result = squiffy.storageFallback[attribute];
        }
        if (!result) return null;
        return JSON.parse(result);
    };

    var startsWith = function(string, prefix) {
        return string.substring(0, prefix.length) === prefix;
    };

    var rotate = function(options, current) {
        var colon = options.indexOf(':');
        if (colon == -1) {
            return [options, current];
        }
        var next = options.substring(0, colon);
        var remaining = options.substring(colon + 1);
        if (current) remaining += ':' + current;
        return [next, remaining];
    };

    var methods = {
        init: function (options) {
            var settings = jQuery.extend({
                scroll: 'body',
                persist: true,
                restartPrompt: true,
                onSet: function (attribute, value) {}
            }, options);

            squiffy.ui.output = this;
            squiffy.ui.restart = jQuery(settings.restart);
            squiffy.ui.settings = settings;

            if (settings.scroll === 'element') {
                squiffy.ui.output.css('overflow-y', 'auto');
            }

            initLinkHandler();
            squiffy.story.begin();

            return this;
        },
        get: function (attribute) {
            return squiffy.get(attribute);
        },
        set: function (attribute, value) {
            squiffy.set(attribute, value);
        },
        restart: function () {
            if (!squiffy.ui.settings.restartPrompt || confirm('Are you sure you want to restart?')) {
                squiffy.story.restart();
            }
        }
    };

    jQuery.fn.squiffy = function (methodOrOptions) {
        if (methods[methodOrOptions]) {
            return methods[methodOrOptions]
                .apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof methodOrOptions === 'object' || ! methodOrOptions) {
            return methods.init.apply(this, arguments);
        } else {
            jQuery.error('Method ' +  methodOrOptions + ' does not exist');
        }
    };
})();

var get = squiffy.get;
var set = squiffy.set;


text:
var mock = require('../../index'),
	get = require('./get');

describe('get by params', function(){
	beforeEach(function(){
		mock([
			{
				request: {
					path: '/users',
					method: 'GET'
				},
				response: {
					status: 200
				}
			},
			{
				request: {
					path: '/users',
					method: 'GET',
					params: {
						name: 'unknown'
					}
				},
				response: {
					status: 500,
					data: {
						error: 'no user found'
					}
				}
			},
			{
				request: {
					path: '/users',
					method: 'GET',
					params: {
						name: 'Charlie'
					}
				},
				response: {
					data: {
						name: 'Charlie'
					}
				}
			},
			{
				request: {
					path: '/users',
					method: 'GET',
					params: {
						name: 'Charlie',
						city: 'Houston'
					}
				},
				response: {
					data: {
						name: 'Charlie in Houston'
					}
				}
			}
		]);
	});

	afterEach(function(){
		mock.teardown();
	});

	it('matches by params', function(){
		get();

		var searchButton = element(by.id('user-search-button'));

		element(by.id('user-query')).sendKeys('Charlie');
		searchButton.click();

		expect(element(by.id('user-data')).getText()).toContain('Charlie');
		expect(element(by.id('successMsg')).getText()).toBe('User found: Charlie');

		element(by.id('user-query-city')).sendKeys('Houston');
		searchButton.click();

		expect(element(by.id('user-data')).getText()).toContain('Charlie in Houston');
		expect(element(by.id('successMsg')).getText()).toBe('User found: Charlie');

		element(by.id('user-query')).clear().sendKeys('unknown');
		element(by.id('user-query-city')).clear();
		searchButton.click();

		var errElement = element(by.id('errorMsg'));
		expect(errElement.isDisplayed()).toBe(true);
		expect(errElement.getText()).toBe('no user found');
	});
});