text:
package Hadouken::Plugin::Boobs;

use strict;
use warnings;

use Hadouken ':acl_modes';

use TryCatch;

our $VERSION = '0.1';
our $AUTHOR  = 'dek';

# Description of this command.
sub command_comment {
    my $self = shift;

    return "Get a random synonym for boobs";
}

# Clean name of command.
sub command_name {
    my $self = shift;

    return "boobs";
}

sub command_regex {

    return 'boobs$';
}

# Return 1 if OK.
# 0 if does not pass ACL.
sub acl_check {
    my ( $self, %aclentry ) = @_;

    my $permissions = $aclentry{'permissions'};
    my $who         = $aclentry{'who'};
    my $channel     = $aclentry{'channel'};
    my $message     = $aclentry{'message'};

    # Hadouken::BIT_ADMIN OR Hadouken::BIT_WHITELIST OR Hadouken::BIT_OP Hadouken::NOT_RIP
    #my $minimum_perms = (1 << 0) | (1 << 1) | (1 << 3);

    #my $acl_min = (1 << Hadouken::BIT_ADMIN) | (1 << Hadouken::BIT_WHITELIST) | (1 << Hadouken::NOT_RIP);

    #my $value = ($permissions & $minimum_perms);

    #warn $value;

    #if($value > 0) {
    # At least one of the items is set.
    #    return 1;
    #}

    # Or you can do it with the function Hadouken exports.
    # Make sure at least one of these flags is set.
    if (   $self->check_acl_bit( $permissions, Hadouken::BIT_ADMIN )
        || $self->check_acl_bit( $permissions, Hadouken::BIT_WHITELIST )
        || $self->check_acl_bit( $permissions, Hadouken::BIT_OP ) )
    {

        return 1;
    }

    return 0;
} ## ---------- end sub acl_check

# Return 1 if OK (and then callback can be called)
# Return 0 and the callback will not be called.
sub command_run {
    my ( $self, $nick, $host, $message, $channel, $is_admin, $is_whitelisted ) = @_;
    my ( $cmd, $arg ) = split( / /, lc($message), 2 );

    try {
        my $line;
        open( my $fh, '<' . $self->{Owner}->{ownerdir} . '/../data/hooters' ) or die $!;
        srand;
        rand($.) < 1 && ( $line = $_ ) while <$fh>;
        close($fh);

        $self->send_server( PRIVMSG => $channel, "[boobs] - " . lc($line) );

    }
    catch ($e) {
        warn $e;
    }

    return 1;
} ## ---------- end sub command_run

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Hadouken::Plugin::Boobs - Boobs plugin.

=head1 DESCRIPTION

A plugin for Hadouken which makes learning new words
fun. Specifically ones meaning boobs.

=head1 AUTHOR

dek <dek@whilefalsedo.com>

=cut

redpajama_set_name: RedPajamaGithub


text:
package com.langellu.jobs;

import com.langellu.jobs.annotations.On;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.concurrent.CountDownLatch;

/**
 * Created by langellu on 27/03/2017.
 */
@On("0/1 * * * * ?")
public class OnTestJob implements Job{

    private CountDownLatch latch;

    public OnTestJob(int latch) {
        this.latch = new CountDownLatch(latch);
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        latch.countDown();
    }

    public CountDownLatch getLatch() {
        return latch;
    }
}


text:
package net.sf.jabref.gui.preftabs;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

import net.sf.jabref.gui.IconTheme;
import net.sf.jabref.gui.OSXCompatibleToolbar;
import net.sf.jabref.gui.help.HelpAction;
import net.sf.jabref.logic.help.HelpFile;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.layout.format.NameFormatter;
import net.sf.jabref.preferences.JabRefPreferences;

import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;

public class NameFormatterTab extends JPanel implements PrefsTab {

    private final JabRefPreferences prefs;
    private boolean tableChanged;

    private final JTable table;

    private int rowCount = -1;

    private final List<TableRow> tableRows = new ArrayList<>(10);

    static class TableRow {

        private String name;

        private String format;

        public TableRow() {
            this("");
        }

        public TableRow(String name) {
            this(name, NameFormatter.DEFAULT_FORMAT);
        }

        public TableRow(String name, String format) {
            this.name = name;
            this.format = format;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getFormat() {
            return format;
        }

        public void setFormat(String format) {
            this.format = format;
        }
    }

    /**
     * Tab to create custom Name Formatters
     *
     */
    public NameFormatterTab(JabRefPreferences prefs) {
        this.prefs = Objects.requireNonNull(prefs);
        setLayout(new BorderLayout());

        TableModel tableModel = new AbstractTableModel() {

            @Override
            public int getRowCount() {
                return rowCount;
            }

            @Override
            public int getColumnCount() {
                return 2;
            }

            @Override
            public Object getValueAt(int row, int column) {
                if (row >= tableRows.size()) {
                    return "";
                }
                TableRow tr = tableRows.get(row);
                if (tr == null) {
                    return "";
                }
                // Only two columns
                if (column == 0) {
                    return tr.getName();
                } else {
                    return tr.getFormat();
                }
            }

            @Override
            public String getColumnName(int col) {
                return col == 0 ? Localization.lang("Formatter name") :
                    Localization.lang("Format string");
            }

            @Override
            public Class<String> getColumnClass(int column) {
                return String.class;
            }

            @Override
            public boolean isCellEditable(int row, int col) {
                return true;
            }

            @Override
            public void setValueAt(Object value, int row, int col) {
                tableChanged = true;

                // Make sure the vector is long enough.
                while (row >= tableRows.size()) {
                    tableRows.add(new TableRow());
                }

                TableRow rowContent = tableRows.get(row);

                if (col == 0) {
                    rowContent.setName(value.toString());
                } else {
                    rowContent.setFormat(value.toString());
                }
            }
        };

        table = new JTable(tableModel);

        TableColumnModel columnModel = table.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(140);
        columnModel.getColumn(1).setPreferredWidth(400);

        FormLayout layout = new FormLayout("1dlu, 8dlu, left:pref, 4dlu, fill:pref", "");

        DefaultFormBuilder builder = new DefaultFormBuilder(layout);

        JPanel pan = new JPanel();

        JPanel tabPanel = new JPanel();
        tabPanel.setLayout(new BorderLayout());
        JScrollPane scrollPane = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        table.setPreferredScrollableViewportSize(new Dimension(250, 200));
        scrollPane.setMinimumSize(new Dimension(250, 300));
        scrollPane.setPreferredSize(new Dimension(600, 300));
        tabPanel.add(scrollPane, BorderLayout.CENTER);

        JToolBar toolBar = new OSXCompatibleToolbar(SwingConstants.VERTICAL);
        toolBar.setFloatable(false);
        toolBar.setBorder(null);
        toolBar.add(new AddRowAction());
        toolBar.add(new DeleteRowAction());
        toolBar.add(new HelpAction(Localization.lang("Help on Name Formatting"),
                HelpFile.CUSTOM_EXPORTS_NAME_FORMATTER).getHelpButton());

        tabPanel.add(toolBar, BorderLayout.EAST);

        builder.appendSeparator(Localization.lang("Special name formatters"));
        builder.nextLine();
        builder.append(pan);
        builder.append(tabPanel);
        builder.nextLine();

        pan = builder.getPanel();
        pan.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        add(pan, BorderLayout.CENTER);
    }

    @Override
    public void setValues() {
        tableRows.clear();
        List<String> names = prefs.getStringList(JabRefPreferences.NAME_FORMATER_KEY);
        List<String> formats = prefs.getStringList(JabRefPreferences.NAME_FORMATTER_VALUE);

        for (int i = 0; i < names.size(); i++) {
            if (i < formats.size()) {
                tableRows.add(new TableRow(names.get(i), formats.get(i)));
            } else {
                tableRows.add(new TableRow(names.get(i)));
            }
        }
        rowCount = tableRows.size() + 5;
    }

    class DeleteRowAction extends AbstractAction {

        public DeleteRowAction() {
            super("Delete row", IconTheme.JabRefIcon.REMOVE_NOBOX.getIcon());
            putValue(Action.SHORT_DESCRIPTION, Localization.lang("Delete rows"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            tableChanged = true;

            int[] selectedRows = table.getSelectedRows();

            int numberDeleted = 0;

            for (int i = selectedRows.length - 1; i >= 0; i--) {
                if (selectedRows[i] < tableRows.size()) {
                    tableRows.remove(selectedRows[i]);
                    numberDeleted++;
                }
            }

            rowCount -= numberDeleted;

            if (selectedRows.length > 1) {
                table.clearSelection();
            }

            table.revalidate();
            table.repaint();
        }
    }

    class AddRowAction extends AbstractAction {

        public AddRowAction() {
            super("Add row", IconTheme.JabRefIcon.ADD_NOBOX.getIcon());
            putValue(Action.SHORT_DESCRIPTION, Localization.lang("Insert rows"));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = table.getSelectedRows();
            if (rows.length == 0) {
                // No rows selected, so we just add one at the end.
                rowCount++;
                table.revalidate();
                table.repaint();
                return;
            }
            for (int i = 0; i < rows.length; i++) {
                if (((rows[i] + i) - 1) < tableRows.size()) {
                    tableRows.add(Math.max(0, (rows[i] + i) - 1), new TableRow());
                }
            }
            rowCount += rows.length;
            if (rows.length > 1) {
                table.clearSelection();
            }
            table.revalidate();
            table.repaint();
            tableChanged = true;
        }
    }

    /**
     * Store changes to table preferences. This method is called when the user
     * clicks Ok.
     *
     */
    @Override
    public void storeSettings() {

        if (table.isEditing()) {
            int col = table.getEditingColumn();
            int row = table.getEditingRow();
            table.getCellEditor(row, col).stopCellEditing();
        }

        // Now we need to make sense of the contents the user has made to the
        // table setup table.
        if (tableChanged) {
            // First we remove all rows with empty names.
            int i = 0;
            while (i < tableRows.size()) {
                if (tableRows.get(i).getName().isEmpty()) {
                    tableRows.remove(i);
                } else {
                    i++;
                }
            }
            // Then we make lists

            List<String> names = new ArrayList<>(tableRows.size());
            List<String> formats = new ArrayList<>(tableRows.size());

            for (TableRow tr : tableRows) {
                names.add(tr.getName());
                formats.add(tr.getFormat());
            }

            // Finally, we store the new preferences.
            prefs.putStringList(JabRefPreferences.NAME_FORMATER_KEY, names);
            prefs.putStringList(JabRefPreferences.NAME_FORMATTER_VALUE, formats);
        }
    }

    @Override
    public boolean validateSettings() {
        return true;
    }

    @Override
    public String getTabName() {
        return Localization.lang("Name formatter");
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:weightSum="2"
      android:background="#FFFFFF">
   <RelativeLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
       android:orientation="horizontal"
         android:background="#FFFFFF">
    <ImageView
        android:id="@+id/equipImageView1"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_margin="10dp"
        android:src="@drawable/back" />
    <TextView
     android:id="@+id/equipTextView1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignTop="@+id/equipImageView1"
     android:layout_centerHorizontal="true"
      android:textSize="20sp"
     android:text="器材详情" />
         <ImageView
         android:id="@+id/equipImageView3"
         android:layout_width="wrap_content"
         android:layout_height="20dp"
         android:layout_marginTop="10dp"
         android:layout_alignParentRight="true"
         android:paddingRight="10dp"
         android:src="@drawable/share1" />

   <ImageView
     android:id="@+id/equipImageView2"
     android:layout_width="wrap_content"
     android:layout_height="20dp"
      android:layout_marginTop="10dp"
     android:layout_toLeftOf="@id/equipImageView3"
     android:src="@drawable/share" />

    </RelativeLayout>

    <ListView
        android:id="@+id/equipImageView4"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_margin="5dp"
        android:src="@android:color/holo_blue_bright" />
  <RelativeLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">
    <ImageView
        android:id="@+id/equipImageView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:src="@drawable/location" />
     <TextView
         android:id="@+id/equipTextView2"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_margin="15dp"
         android:layout_toRightOf="@id/equipImageView5"
         android:text="北京市朝阳区" />

     <ImageView
         android:id="@+id/equipImageView6"
         android:layout_width="wrap_content"
         android:layout_height="20dp"
         android:layout_alignParentRight="true"
         android:layout_margin="10dp"
         android:layout_alignBottom="@id/equipImageView5"
         android:src="@drawable/shaixuan" />
   </RelativeLayout>
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
         >
         <View
             android:id="@+id/equipSplit01"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="8dip"
        android:background="#cccccc" />
          <ImageView
     android:id="@+id/equipImageView7"
     android:layout_width="15dp"
     android:layout_height="25dp"
     android:layout_below="@id/equipSplit01"
     android:paddingLeft="5dp"
     android:paddingTop="10dp"
     android:src="@drawable/ladder" />
        <TextView
     android:id="@+id/equipTextView3"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_toRightOf="@id/equipImageView7"
         android:layout_below="@id/equipSplit01"
    android:layout_margin="10dp"
     android:text="李女士" />

        <View
             android:id="@+id/equipSplit03"
        android:layout_width="1dp"
        android:layout_height="35dp"
         android:layout_centerHorizontal="true"
          android:layout_below="@id/equipSplit01"
        android:background="#cccccc" />
  <ImageView
     android:id="@+id/equipImageView01"
     android:layout_width="20dp"
     android:layout_height="15dp"
    android:layout_below="@id/equipSplit01"
        android:layout_margin="10dp"
      android:layout_toRightOf="@id/equipSplit03"
     android:background="@drawable/sendmessage" />
  <TextView
     android:id="@+id/textView4"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_toRightOf="@id/equipImageView01"
      android:layout_below="@id/equipSplit01"
         android:layout_margin="10dp"
        android:layout_marginLeft="10dp"
     android:text="发送消息" />
         <View
             android:id="@+id/equipSplit02"
        android:layout_width="match_parent"
        android:layout_height="1dp"
           android:layout_below="@id/equipImageView7"
        android:layout_marginTop="10dip"
        android:background="#cccccc" />

 <ImageView
     android:id="@+id/equipImageView02"
     android:layout_width="15dp"
     android:layout_height="15dp"
     android:layout_alignLeft="@id/equipImageView7"
     android:layout_margin="5dp"
  android:layout_below="@id/equipSplit02"
     android:background="@drawable/similar" />
  <TextView
     android:id="@+id/equipTextView5"
  android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_toRightOf="@id/equipImageView02"
         android:layout_below="@id/equipSplit02"
    android:layout_marginTop="10dp"
     android:text="找相似" />

   <ImageView
         android:id="@+id/equipImageView003"
         android:layout_width="wrap_content"
         android:layout_height="15dp"
        android:layout_alignParentRight="true"
       android:layout_below="@id/equipSplit02"
         android:layout_margin="10dp"
         android:src="@drawable/shaixuan" />
          <View
             android:id="@+id/equipSplit04"
        android:layout_width="match_parent"
        android:layout_height="1dp"
           android:layout_below="@id/equipImageView003"
        android:layout_marginTop="5dip"
        android:background="#cccccc" />
          <ImageView
     android:id="@+id/equipImageView03"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@id/equipImageView7"
  android:layout_below="@id/equipSplit04"
     android:src="@android:drawable/ic_menu_add" />
  <TextView
     android:id="@+id/equipTextView6"
  android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_toRightOf="@id/equipImageView03"
         android:layout_below="@id/equipSplit04"
    android:layout_margin="10dp"
     android:text="器材搭配" />

   <ImageView
         android:id="@+id/equipImageView004"
         android:layout_width="wrap_content"
         android:layout_height="15dp"
        android:layout_alignParentRight="true"
       android:layout_below="@id/equipSplit04"
         android:layout_margin="10dp"
         android:src="@drawable/shaixuan" />
          <View
             android:id="@+id/equipSplit05"
        android:layout_width="match_parent"
        android:layout_height="1dp"
           android:layout_below="@id/equipImageView004"
        android:layout_marginTop="5dip"
        android:background="#cccccc" />
  </RelativeLayout>
   <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="?android:attr/listDivider"
         >

    </LinearLayout>

</LinearLayout>


text:
//========= Copyright 2014, Valve Corporation, All rights reserved. ===========
//
// Purpose: Adds SteamVR render support to existing camera objects
//
//=============================================================================

using UnityEngine;
using System.Collections;
using System.Reflection;
using Valve.VR;
using System;
using VRGIN.Core;
using VRGIN.Helpers;

[RequireComponent(typeof(Camera))]
public class SteamVR_Camera : ProtectedBehaviour
{
	[SerializeField]
	private Transform _head;
	public Transform head { get { return _head; } }
	public Transform offset { get { return _head; } } // legacy
	public Transform origin { get { return _head.parent; } }

	[SerializeField]
	private Transform _ears;
	public Transform ears { get { return _ears; } }

	public Ray GetRay()
	{
		return new Ray(_head.position, _head.forward);
	}

	public bool wireframe = false;

	[SerializeField]
	private SteamVR_CameraFlip flip;

	#region Materials

	static public Material blitMaterial;

	// Using a single shared offscreen buffer to render the scene.  This needs to be larger
	// than the backbuffer to account for distortion correction.  The default resolution
	// gives us 1:1 sized pixels in the center of view, but quality can be adjusted up or
	// down using the following scale value to balance performance.
	static public float sceneResolutionScale = 1.0f;
	static private RenderTexture _sceneTexture;
	static public RenderTexture GetSceneTexture(bool hdr)
	{
		var vr = SteamVR.instance;
		if (vr == null)
			return null;

		int w = (int)(vr.sceneWidth * sceneResolutionScale);
		int h = (int)(vr.sceneHeight * sceneResolutionScale);
		int aa = QualitySettings.antiAliasing == 0 ? 1 : QualitySettings.antiAliasing;
		var format = hdr ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;

		if (_sceneTexture != null)
		{
			if (_sceneTexture.width != w || _sceneTexture.height != h || _sceneTexture.antiAliasing != aa || _sceneTexture.format != format)
			{
				Console.WriteLine(string.Format("Recreating scene texture.. Old: {0}x{1} MSAA={2} [{3}] New: {4}x{5} MSAA={6} [{7}]",
					_sceneTexture.width, _sceneTexture.height, _sceneTexture.antiAliasing, _sceneTexture.format, w, h, aa, format));
                UnityEngine.Object.Destroy(_sceneTexture);
				_sceneTexture = null;
			}
		}

		if (_sceneTexture == null)
		{
            System.Console.WriteLine("creating render texture...");
			_sceneTexture = new RenderTexture(w, h, 0, format);
			_sceneTexture.antiAliasing = aa;

#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 || UNITY_4_5)
			// OpenVR assumes floating point render targets are linear unless otherwise specified.
			var colorSpace = (hdr && QualitySettings.activeColorSpace == ColorSpace.Gamma) ? EColorSpace.Gamma : EColorSpace.Auto;
			SteamVR.Unity.SetColorSpace(colorSpace);
#endif
            _sceneTexture.Create();
		}

		return _sceneTexture;
	}

	#endregion

	#region Enable / Disable

	void OnDisable()
	{
		SteamVR_Render.Remove(this);
	}

	void OnEnable()
	{
        try
        {
#if !(UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 || UNITY_4_5)
		// Convert camera rig for native OpenVR integration.
		var t = transform;
		if (head != t)
		{
			Expand();

			t.parent = origin;

			while (head.childCount > 0)
				head.GetChild(0).parent = t;
			DestroyImmediate(head.gameObject);
			_head = t;
		}

		if (flip != null)
		{
			DestroyImmediate(flip);
			flip = null;
		}

		if (!SteamVR.usingNativeSupport)
		{
			enabled = false;
			return;
		}
#else
            System.Console.WriteLine("OK");
            // Bail if no hmd is connected
            var vr = SteamVR.instance;
            if (vr == null)
            {
                if (head != null)
                {
                    head.GetComponent<SteamVR_GameView>().enabled = false;
                    head.GetComponent<SteamVR_TrackedObject>().enabled = false;
                }

                if (flip != null)
                    flip.enabled = false;

                enabled = false;
                return;
            }

            // Ensure rig is properly set up
            Expand();
            System.Console.WriteLine("OK2");

            if (blitMaterial == null)
            {
                System.Console.WriteLine("OK3");

                blitMaterial = new Material(UnityHelper.GetShader("SteamVR_Blit"));
                System.Console.WriteLine("OK4" + blitMaterial == null);

            }

            // Set remaining hmd specific settings
            var camera = GetComponent<Camera>();
            camera.fieldOfView = vr.fieldOfView;
            camera.aspect = vr.aspect;
            camera.eventMask = 0;           // disable mouse events
            camera.orthographic = false;    // force perspective
            camera.enabled = false;         // manually rendered by SteamVR_Render
            System.Console.WriteLine("OK5");

            if (camera.actualRenderingPath != RenderingPath.Forward && QualitySettings.antiAliasing > 1)
            {
                Console.WriteLine("MSAA only supported in Forward rendering path. (disabling MSAA)");
                QualitySettings.antiAliasing = 0;
            }

            // Ensure game view camera hdr setting matches
            var headCam = head.GetComponent<Camera>();
            if (headCam != null)
            {
                headCam.hdr = camera.hdr;
                headCam.renderingPath = camera.renderingPath;
            }
#endif
            System.Console.WriteLine("OK6");

            try
            {
                ears.GetComponent<SteamVR_Ears>().vrcam = this;
            }
            catch (System.Exception e)
            {
                Logger.Info("Ears not found");
            }
            System.Console.WriteLine("OK7");

            SteamVR_Render.Add(this);
            System.Console.WriteLine("OK8");
        } catch(Exception e2)
        {
            Console.WriteLine(e2);
        }
    }

    #endregion

    #region Functionality to ensure SteamVR_Camera component is always the last component on an object

    protected override void OnAwake() { ForceLast(); }

	static Hashtable values;

	public void ForceLast()
	{
        try
        {
            if (values != null)
            {
                // Restore values on new instance
                foreach (DictionaryEntry entry in values)
                {
                    var f = entry.Key as FieldInfo;
                    f.SetValue(this, entry.Value);
                }
                values = null;
            }
            else
            {
                // Make sure it's the last component
                var components = GetComponents<Component>();

                // But first make sure there aren't any other SteamVR_Cameras on this object.
                for (int i = 0; i < components.Length; i++)
                {
                    var c = components[i] as SteamVR_Camera;
                    if (c != null && c != this)
                    {
                        if (c.flip != null)
                            DestroyImmediate(c.flip);
                        DestroyImmediate(c);
                    }
                }

                components = GetComponents<Component>();

#if !(UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 || UNITY_4_5)
			if (this != components[components.Length - 1])
			{
#else
                if (this != components[components.Length - 1] || flip == null)
                {
                    if (flip == null)
                        flip = gameObject.AddComponent<SteamVR_CameraFlip>();
#endif
                    // Store off values to be restored on new instance
                    values = new Hashtable();
                    var fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                    foreach (var f in fields)
                        if (f.IsPublic || f.IsDefined(typeof(SerializeField), true))
                            values[f] = f.GetValue(this);

                    var go = gameObject;
                    DestroyImmediate(this);
                    go.AddComponent<SteamVR_Camera>().ForceLast();
                }
            }
        } catch(Exception e)
        {
            Console.WriteLine(e);
        }
	}

	#endregion

	#region Expand / Collapse object hierarchy

#if UNITY_EDITOR
	public bool isExpanded { get { return head != null && transform.parent == head; } }
#endif
	const string eyeSuffix = " (eye)";
	const string earsSuffix = " (ears)";
	const string headSuffix = " (head)";
	const string originSuffix = " (origin)";
	public string baseName { get { return name.EndsWith(eyeSuffix) ? name.Substring(0, name.Length - eyeSuffix.Length) : name; } }

	// Object hierarchy creation to make it easy to parent other objects appropriately,
	// otherwise this gets called on demand at runtime. Remaining initialization is
	// performed at startup, once the hmd has been identified.
	public void Expand()
	{
        try
        {
            var _origin = transform.parent;
            if (_origin == null)
            {
                _origin = new GameObject(name + originSuffix).transform;
                _origin.localPosition = transform.localPosition;
                _origin.localRotation = transform.localRotation;
                _origin.localScale = transform.localScale;
            }

            if (head == null)
            {
                _head = new GameObject(name + headSuffix, typeof(SteamVR_GameView), typeof(SteamVR_TrackedObject)).transform;
                head.parent = _origin;
                head.position = transform.position;
                head.rotation = transform.rotation;
                head.localScale = Vector3.one;
                head.tag = tag;

                var camera = head.GetComponent<Camera>();
                camera.clearFlags = CameraClearFlags.Nothing;
                camera.cullingMask = 0;
                camera.eventMask = 0;
                camera.orthographic = true;
                camera.orthographicSize = 1;
                camera.nearClipPlane = 0;
                camera.farClipPlane = 1;
                camera.useOcclusionCulling = false;
            }

            if (transform.parent != head)
            {
                transform.parent = head;
                transform.localPosition = Vector3.zero;
                transform.localRotation = Quaternion.identity;
                transform.localScale = Vector3.one;

                while (transform.childCount > 0)
                    transform.GetChild(0).parent = head;

                var guiLayer = GetComponent<GUILayer>();
                if (guiLayer != null)
                {
                    DestroyImmediate(guiLayer);
                    head.gameObject.AddComponent<GUILayer>();
                }

                var audioListener = GetComponent<AudioListener>();
                if (audioListener != null)
                {
                    DestroyImmediate(audioListener);
                    _ears = new GameObject(name + earsSuffix, typeof(SteamVR_Ears)).transform;
                    ears.parent = _head;
                    ears.localPosition = Vector3.zero;
                    ears.localRotation = Quaternion.identity;
                    ears.localScale = Vector3.one;
                }
            }

            if (!name.EndsWith(eyeSuffix))
                name += eyeSuffix;

        } catch(Exception e) {
            Console.WriteLine(e);
        }
	}

	public void Collapse()
	{
        try
        {
            transform.parent = null;

            // Move children and components from head back to camera.
            while (head.childCount > 0)
                head.GetChild(0).parent = transform;

            var guiLayer = head.GetComponent<GUILayer>();
            if (guiLayer != null)
            {
                DestroyImmediate(guiLayer);
                gameObject.AddComponent<GUILayer>();
            }

            if (ears != null)
            {
                while (ears.childCount > 0)
                    ears.GetChild(0).parent = transform;

                DestroyImmediate(ears.gameObject);
                _ears = null;

                gameObject.AddComponent(typeof(AudioListener));
            }

            if (origin != null)
            {
                // If we created the origin originally, destroy it now.
                if (origin.name.EndsWith(originSuffix))
                {
                    // Reparent any children so we don't accidentally delete them.
                    var _origin = origin;
                    while (_origin.childCount > 0)
                        _origin.GetChild(0).parent = _origin.parent;

                    DestroyImmediate(_origin.gameObject);
                }
                else
                {
                    transform.parent = origin;
                }
            }

            DestroyImmediate(head.gameObject);
            _head = null;

            if (name.EndsWith(eyeSuffix))
                name = name.Substring(0, name.Length - eyeSuffix.Length);
        } catch(Exception e)
        {
            Console.WriteLine(e);
        }
	}

	#endregion

#if (UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 || UNITY_4_5)

	#region Render callbacks

	void OnPreRender()
	{
        try
        {
            if (flip)
                flip.enabled = (SteamVR_Render.Top() == this && SteamVR.instance.graphicsAPI == EGraphicsAPIConvention.API_DirectX);

            var headCam = head.GetComponent<Camera>();
            if (headCam != null)
                headCam.enabled = (SteamVR_Render.Top() == this);

            if (wireframe)
                GL.wireframe = true;
        } catch( Exception e)
        {
            Console.WriteLine(e);
        }
	}

	void OnPostRender()
	{
        try
        {
            if (wireframe)
                GL.wireframe = false;

        } catch(Exception e) {
            Console.WriteLine(e);

        }
	}

	void OnRenderImage(RenderTexture src, RenderTexture dest)
	{
        try
        {
            if (SteamVR_Render.Top() == this)
            {
                int eventID;
                if (SteamVR_Render.eye == EVREye.Eye_Left)
                {
                    // Get gpu started on work early to avoid bubbles at the top of the frame.
                    SteamVR_Utils.QueueEventOnRenderThread(SteamVR.Unity.k_nRenderEventID_Flush);

                    eventID = SteamVR.Unity.k_nRenderEventID_SubmitL;
                }
                else
                {
                    eventID = SteamVR.Unity.k_nRenderEventID_SubmitR;
                }
                // Queue up a call on the render thread to Submit our render target to the compositor.
                SteamVR_Utils.QueueEventOnRenderThread(eventID);
                //Texture_t t = new Texture_t() { eColorSpace = EColorSpace.Auto, eType = EGraphicsAPIConvention.API_DirectX, handle = _sceneTexture.GetNativeTexturePtr() };
                //VRTextureBounds_t b = SteamVR_Render.eye == EVREye.Eye_Left ? SteamVR.instance.textureBounds[0] : SteamVR.instance.textureBounds[1];
                //var res = OpenVR.Compositor.Submit(SteamVR_Render.eye, ref t, ref b, EVRSubmitFlags.Submit_Default);
                //Console.WriteLine(res);
            }
            Graphics.SetRenderTarget(dest);

            SteamVR_Camera.blitMaterial.mainTexture = src;

            GL.PushMatrix();
            GL.LoadOrtho();
            SteamVR_Camera.blitMaterial.SetPass(0);
            GL.Begin(GL.QUADS);
            GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(-1, 1, 0);
            GL.TexCoord2(1.0f, 0.0f); GL.Vertex3(1, 1, 0);
            GL.TexCoord2(1.0f, 1.0f); GL.Vertex3(1, -1, 0);
            GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(-1, -1, 0);
            GL.End();
            GL.PopMatrix();

            Graphics.SetRenderTarget(null);
        } catch(Exception e)
        {
            Console.WriteLine(e);
        }
	}

	#endregion

#endif
}


text:
'''
Unit tests for finance.slippage
'''
from collections import namedtuple
import datetime
from math import sqrt

from nose_parameterized import parameterized
import numpy as np
import pandas as pd
import pytz

from zipline.assets import Equity, Future
from zipline.data.data_portal import DataPortal
from zipline.finance.asset_restrictions import NoRestrictions
from zipline.finance.order import Order
from zipline.finance.slippage import (
    EquitySlippageModel,
    fill_price_worse_than_limit_price,
    FutureSlippageModel,
    SlippageModel,
    VolatilityVolumeShare,
    VolumeShareSlippage,
    FixedBasisPointsSlippage,
)
from zipline.protocol import DATASOURCE_TYPE, BarData
from zipline.testing import (
    create_minute_bar_data,
    tmp_bcolz_equity_minute_bar_reader,
)
from zipline.testing.fixtures import (
    WithAssetFinder,
    WithCreateBarData,
    WithDataPortal,
    WithSimParams,
    WithTradingCalendars,
    ZiplineTestCase,
)
from zipline.utils.classproperty import classproperty
from zipline.utils.pandas_utils import normalize_date

TestOrder = namedtuple('TestOrder', 'limit direction')

class SlippageTestCase(WithCreateBarData,
                       WithSimParams,
                       WithDataPortal,
                       ZiplineTestCase):
    START_DATE = pd.Timestamp('2006-01-05 14:31', tz='utc')
    END_DATE = pd.Timestamp('2006-01-05 14:36', tz='utc')
    SIM_PARAMS_CAPITAL_BASE = 1.0e5
    SIM_PARAMS_DATA_FREQUENCY = 'minute'
    SIM_PARAMS_EMISSION_RATE = 'daily'

    ASSET_FINDER_EQUITY_SIDS = (133,)
    ASSET_FINDER_EQUITY_START_DATE = pd.Timestamp('2006-01-05', tz='utc')
    ASSET_FINDER_EQUITY_END_DATE = pd.Timestamp('2006-01-07', tz='utc')
    minutes = pd.DatetimeIndex(
        start=START_DATE,
        end=END_DATE - pd.Timedelta('1 minute'),
        freq='1min'
    )

    @classproperty
    def CREATE_BARDATA_DATA_FREQUENCY(cls):
        return cls.sim_params.data_frequency

    @classmethod
    def make_equity_minute_bar_data(cls):
        yield 133, pd.DataFrame(
            {
                'open': [3.0, 3.0, 3.5, 4.0, 3.5],
                'high': [3.15, 3.15, 3.15, 3.15, 3.15],
                'low': [2.85, 2.85, 2.85, 2.85, 2.85],
                'close': [3.0, 3.5, 4.0, 3.5, 3.0],
                'volume': [2000, 2000, 2000, 2000, 2000],
            },
            index=cls.minutes,
        )

    @classmethod
    def init_class_fixtures(cls):
        super(SlippageTestCase, cls).init_class_fixtures()
        cls.ASSET133 = cls.asset_finder.retrieve_asset(133)

    def test_allowed_asset_types(self):
        # Custom equities model.
        class MyEquitiesModel(EquitySlippageModel):
            def process_order(self, data, order):
                return 0, 0

        self.assertEqual(MyEquitiesModel.allowed_asset_types, (Equity,))

        # Custom futures model.
        class MyFuturesModel(FutureSlippageModel):
            def process_order(self, data, order):
                return 0, 0

        self.assertEqual(MyFuturesModel.allowed_asset_types, (Future,))

        # Custom model for both equities and futures.
        class MyMixedModel(EquitySlippageModel, FutureSlippageModel):
            def process_order(self, data, order):
                return 0, 0

        self.assertEqual(MyMixedModel.allowed_asset_types, (Equity, Future))

        # Equivalent custom model for both equities and futures.
        class MyMixedModel(SlippageModel):
            def process_order(self, data, order):
                return 0, 0

        self.assertEqual(MyMixedModel.allowed_asset_types, (Equity, Future))

        SomeType = type('SomeType', (object,), {})

        # A custom model that defines its own allowed types should take
        # precedence over the parent class definitions.
        class MyCustomModel(EquitySlippageModel, FutureSlippageModel):
            allowed_asset_types = (SomeType,)

            def process_order(self, data, order):
                return 0, 0

        self.assertEqual(MyCustomModel.allowed_asset_types, (SomeType,))

    def test_fill_price_worse_than_limit_price(self):
        non_limit_order = TestOrder(limit=None, direction=1)
        limit_buy = TestOrder(limit=1.5, direction=1)
        limit_sell = TestOrder(limit=1.5, direction=-1)

        for price in [1, 1.5, 2]:
            self.assertFalse(
                fill_price_worse_than_limit_price(price, non_limit_order)
            )

        self.assertFalse(fill_price_worse_than_limit_price(1, limit_buy))
        self.assertFalse(fill_price_worse_than_limit_price(1.5, limit_buy))
        self.assertTrue(fill_price_worse_than_limit_price(2, limit_buy))

        self.assertTrue(fill_price_worse_than_limit_price(1, limit_sell))
        self.assertFalse(fill_price_worse_than_limit_price(1.5, limit_sell))
        self.assertFalse(fill_price_worse_than_limit_price(2, limit_sell))

    def test_orders_limit(self):
        slippage_model = VolumeShareSlippage()
        slippage_model.data_portal = self.data_portal

        # long, does not trade
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': 100,
                'filled': 0,
                'asset': self.ASSET133,
                'limit': 3.5})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[3],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        # long, does not trade - impacted price worse than limit price
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': 100,
                'filled': 0,
                'asset': self.ASSET133,
                'limit': 3.5})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[3],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        # long, does trade
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': 100,
                'filled': 0,
                'asset': self.ASSET133,
                'limit': 3.6})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[3],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 1)
        txn = orders_txns[0][1]

        expected_txn = {
            'price': float(3.50021875),
            'dt': datetime.datetime(
                2006, 1, 5, 14, 34, tzinfo=pytz.utc),
            # we ordered 100 shares, but default volume slippage only allows
            # for 2.5% of the volume.  2.5% * 2000 = 50 shares
            'amount': int(50),
            'asset': self.ASSET133,
            'order_id': open_orders[0].id
        }

        self.assertIsNotNone(txn)

        for key, value in expected_txn.items():
            self.assertEquals(value, txn[key])

        # short, does not trade
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': -100,
                'filled': 0,
                'asset': self.ASSET133,
                'limit': 3.5})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[0],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        # short, does not trade - impacted price worse than limit price
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': -100,
                'filled': 0,
                'asset': self.ASSET133,
                'limit': 3.5})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[0],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        # short, does trade
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': -100,
                'filled': 0,
                'asset': self.ASSET133,
                'limit': 3.4})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[1],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 1)
        _, txn = orders_txns[0]

        expected_txn = {
            'price': float(3.49978125),
            'dt': datetime.datetime(
                2006, 1, 5, 14, 32, tzinfo=pytz.utc),
            'amount': int(-50),
            'asset': self.ASSET133,
        }

        self.assertIsNotNone(txn)

        for key, value in expected_txn.items():
            self.assertEquals(value, txn[key])

    def test_orders_stop_limit(self):
        slippage_model = VolumeShareSlippage()
        slippage_model.data_portal = self.data_portal

        # long, does not trade
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': 100,
                'filled': 0,
                'asset': self.ASSET133,
                'stop': 4.0,
                'limit': 3.0})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[2],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[3],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        # long, does not trade - impacted price worse than limit price
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': 100,
                'filled': 0,
                'asset': self.ASSET133,
                'stop': 4.0,
                'limit': 3.5})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[2],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[3],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        # long, does trade
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': 100,
                'filled': 0,
                'asset': self.ASSET133,
                'stop': 4.0,
                'limit': 3.6})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[2],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[3],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 1)
        _, txn = orders_txns[0]

        expected_txn = {
            'price': float(3.50021875),
            'dt': datetime.datetime(
                2006, 1, 5, 14, 34, tzinfo=pytz.utc),
            'amount': int(50),
            'asset': self.ASSET133
        }

        for key, value in expected_txn.items():
            self.assertEquals(value, txn[key])

        # short, does not trade

        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': -100,
                'filled': 0,
                'asset': self.ASSET133,
                'stop': 3.0,
                'limit': 4.0})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[0],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[1],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        # short, does not trade - impacted price worse than limit price
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': -100,
                'filled': 0,
                'asset': self.ASSET133,
                'stop': 3.0,
                'limit': 3.5})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[0],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[1],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        # short, does trade
        open_orders = [
            Order(**{
                'dt': datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                'amount': -100,
                'filled': 0,
                'asset': self.ASSET133,
                'stop': 3.0,
                'limit': 3.4})
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[0],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[1],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 1)
        _, txn = orders_txns[0]

        expected_txn = {
            'price': float(3.49978125),
            'dt': datetime.datetime(2006, 1, 5, 14, 32, tzinfo=pytz.utc),
            'amount': int(-50),
            'asset': self.ASSET133,
        }

        for key, value in expected_txn.items():
            self.assertEquals(value, txn[key])

class VolumeShareSlippageTestCase(WithCreateBarData,
                                  WithSimParams,
                                  WithDataPortal,
                                  ZiplineTestCase):

    START_DATE = pd.Timestamp('2006-01-05 14:31', tz='utc')
    END_DATE = pd.Timestamp('2006-01-05 14:36', tz='utc')
    SIM_PARAMS_CAPITAL_BASE = 1.0e5
    SIM_PARAMS_DATA_FREQUENCY = 'minute'
    SIM_PARAMS_EMISSION_RATE = 'daily'

    ASSET_FINDER_EQUITY_SIDS = (133,)
    ASSET_FINDER_EQUITY_START_DATE = pd.Timestamp('2006-01-05', tz='utc')
    ASSET_FINDER_EQUITY_END_DATE = pd.Timestamp('2006-01-07', tz='utc')
    minutes = pd.DatetimeIndex(
        start=START_DATE,
        end=END_DATE - pd.Timedelta('1 minute'),
        freq='1min'
    )

    @classproperty
    def CREATE_BARDATA_DATA_FREQUENCY(cls):
        return cls.sim_params.data_frequency

    @classmethod
    def make_equity_minute_bar_data(cls):
        yield 133, pd.DataFrame(
            {
                'open': [3.00],
                'high': [3.15],
                'low': [2.85],
                'close': [3.00],
                'volume': [200],
            },
            index=[cls.minutes[0]],
        )

    @classmethod
    def make_futures_info(cls):
        return pd.DataFrame({
            'sid': [1000],
            'root_symbol': ['CL'],
            'symbol': ['CLF06'],
            'start_date': [cls.ASSET_FINDER_EQUITY_START_DATE],
            'end_date': [cls.ASSET_FINDER_EQUITY_END_DATE],
            'multiplier': [500],
            'exchange': ['CMES'],
        })

    @classmethod
    def make_future_minute_bar_data(cls):
        yield 1000, pd.DataFrame(
            {
                'open': [5.00],
                'high': [5.15],
                'low': [4.85],
                'close': [5.00],
                'volume': [100],
            },
            index=[cls.minutes[0]],
        )

    @classmethod
    def init_class_fixtures(cls):
        super(VolumeShareSlippageTestCase, cls).init_class_fixtures()
        cls.ASSET133 = cls.asset_finder.retrieve_asset(133)
        cls.ASSET1000 = cls.asset_finder.retrieve_asset(1000)

    def test_volume_share_slippage(self):

        slippage_model = VolumeShareSlippage()

        open_orders = [
            Order(
                dt=datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                amount=100,
                filled=0,
                asset=self.ASSET133
            )
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[0],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 1)
        _, txn = orders_txns[0]

        expected_txn = {
            'price': float(3.0001875),
            'dt': datetime.datetime(2006, 1, 5, 14, 31, tzinfo=pytz.utc),
            'amount': int(5),
            'asset': self.ASSET133,
            'type': DATASOURCE_TYPE.TRANSACTION,
            'order_id': open_orders[0].id
        }

        self.assertIsNotNone(txn)

        # TODO: Make expected_txn an Transaction object and ensure there
        # is a __eq__ for that class.
        self.assertEquals(expected_txn, txn.__dict__)

        open_orders = [
            Order(
                dt=datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                amount=100,
                filled=0,
                asset=self.ASSET133
            )
        ]

        # Set bar_data to be a minute ahead of last trade.
        # Volume share slippage should not execute when there is no trade.
        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[1],
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 0)

    def test_volume_share_slippage_with_future(self):
        slippage_model = VolumeShareSlippage(volume_limit=1, price_impact=0.3)

        open_orders = [
            Order(
                dt=datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                amount=10,
                filled=0,
                asset=self.ASSET1000,
            ),
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.minutes[0],
        )

        orders_txns = list(
            slippage_model.simulate(bar_data, self.ASSET1000, open_orders)
        )

        self.assertEquals(len(orders_txns), 1)
        _, txn = orders_txns[0]

        # We expect to fill the order for all 10 contracts. The volume for the
        # futures contract in this bar is 100, so our volume share is:
        #     10.0 / 100 = 0.1
        # The current price is 5.0 and the price impact is 0.3, so the expected
        # impacted price is:
        #     5.0 + (5.0 * (0.1 ** 2) * 0.3) = 5.015
        expected_txn = {
            'price': 5.015,
            'dt': datetime.datetime(2006, 1, 5, 14, 31, tzinfo=pytz.utc),
            'amount': 10,
            'asset': self.ASSET1000,
            'type': DATASOURCE_TYPE.TRANSACTION,
            'order_id': open_orders[0].id,
        }

        self.assertIsNotNone(txn)
        self.assertEquals(expected_txn, txn.__dict__)

class VolatilityVolumeShareTestCase(WithCreateBarData,
                                    WithSimParams,
                                    WithDataPortal,
                                    ZiplineTestCase):

    ASSET_START_DATE = pd.Timestamp('2006-02-10')

    TRADING_CALENDAR_STRS = ('NYSE', 'us_futures')
    TRADING_CALENDAR_PRIMARY_CAL = 'us_futures'

    @classmethod
    def init_class_fixtures(cls):
        super(VolatilityVolumeShareTestCase, cls).init_class_fixtures()
        cls.ASSET = cls.asset_finder.retrieve_asset(1000)

    @classmethod
    def make_futures_info(cls):
        return pd.DataFrame({
            'sid': [1000, 1001],
            'root_symbol': ['CL', 'FV'],
            'symbol': ['CLF07', 'FVF07'],
            'start_date': [cls.ASSET_START_DATE, cls.START_DATE],
            'end_date': [cls.END_DATE, cls.END_DATE],
            'multiplier': [500, 500],
            'exchange': ['CMES', 'CMES'],
        })

    @classmethod
    def make_future_minute_bar_data(cls):
        data = list(
            super(
                VolatilityVolumeShareTestCase, cls,
            ).make_future_minute_bar_data()
        )
        # Make the first month's worth of data NaN to simulate cases where a
        # futures contract does not exist yet.
        data[0][1].loc[:cls.ASSET_START_DATE] = np.NaN
        return data

    def test_calculate_impact_buy(self):
        answer_key = [
            # We ordered 10 contracts, but are capped at 100 * 0.05 = 5
            (91485.500085168125, 5),
            (91486.500085169057, 5),
            (None, None),
        ]
        order = Order(
            dt=pd.Timestamp.now(tz='utc').round('min'),
            asset=self.ASSET,
            amount=10,
        )
        self._calculate_impact(order, answer_key)

    def test_calculate_impact_sell(self):
        answer_key = [
            # We ordered -10 contracts, but are capped at -(100 * 0.05) = -5
            (91485.499914831875, -5),
            (91486.499914830943, -5),
            (None, None),
        ]
        order = Order(
            dt=pd.Timestamp.now(tz='utc').round('min'),
            asset=self.ASSET,
            amount=-10,
        )
        self._calculate_impact(order, answer_key)

    def _calculate_impact(self, test_order, answer_key):
        model = VolatilityVolumeShare(volume_limit=0.05)
        first_minute = pd.Timestamp('2006-03-31 11:35AM', tz='UTC')

        next_3_minutes = self.trading_calendar.minutes_window(first_minute, 3)
        remaining_shares = test_order.open_amount

        for i, minute in enumerate(next_3_minutes):
            data = self.create_bardata(simulation_dt_func=lambda: minute)
            new_order = Order(
                dt=data.current_dt, asset=self.ASSET, amount=remaining_shares,
            )
            price, amount = model.process_order(data, new_order)

            self.assertEqual(price, answer_key[i][0])
            self.assertEqual(amount, answer_key[i][1])

            amount = amount or 0
            if remaining_shares < 0:
                remaining_shares = min(0, remaining_shares - amount)
            else:
                remaining_shares = max(0, remaining_shares - amount)

    def test_calculate_impact_without_history(self):
        model = VolatilityVolumeShare(volume_limit=1)
        late_start_asset = self.asset_finder.retrieve_asset(1000)
        early_start_asset = self.asset_finder.retrieve_asset(1001)

        cases = [
            # History will look for data before the start date.
            (pd.Timestamp('2006-01-05 11:35AM', tz='UTC'), early_start_asset),
            # Start day of the futures contract; no history yet.
            (pd.Timestamp('2006-02-10 11:35AM', tz='UTC'), late_start_asset),
            # Only a week's worth of history data.
            (pd.Timestamp('2006-02-17 11:35AM', tz='UTC'), late_start_asset),
        ]

        for minute, asset in cases:
            data = self.create_bardata(simulation_dt_func=lambda: minute)

            order = Order(dt=data.current_dt, asset=asset, amount=10)
            price, amount = model.process_order(data, order)

            avg_price = (
                data.current(asset, 'high') + data.current(asset, 'low')
            ) / 2
            expected_price = \
                avg_price * (1 + model.NO_DATA_VOLATILITY_SLIPPAGE_IMPACT)

            self.assertAlmostEqual(price, expected_price, delta=0.001)
            self.assertEqual(amount, 10)

    def test_impacted_price_worse_than_limit(self):
        model = VolatilityVolumeShare(volume_limit=0.05)

        # Use all the same numbers from the 'calculate_impact' tests. Since the
        # impacted price is 59805.5, which is worse than the limit price of
        # 59800, the model should return None.
        minute = pd.Timestamp('2006-03-01 11:35AM', tz='UTC')
        data = self.create_bardata(simulation_dt_func=lambda: minute)
        order = Order(
            dt=data.current_dt, asset=self.ASSET, amount=10, limit=59800,
        )
        price, amount = model.process_order(data, order)

        self.assertIsNone(price)
        self.assertIsNone(amount)

    def test_low_transaction_volume(self):
        # With a volume limit of 0.001, and a bar volume of 100, we should
        # compute a transaction volume of 100 * 0.001 = 0.1, which gets rounded
        # down to zero. In this case we expect no amount to be transacted.
        model = VolatilityVolumeShare(volume_limit=0.001)

        minute = pd.Timestamp('2006-03-01 11:35AM', tz='UTC')
        data = self.create_bardata(simulation_dt_func=lambda: minute)
        order = Order(dt=data.current_dt, asset=self.ASSET, amount=10)
        price, amount = model.process_order(data, order)

        self.assertIsNone(price)
        self.assertIsNone(amount)

class MarketImpactTestCase(WithCreateBarData, ZiplineTestCase):

    ASSET_FINDER_EQUITY_SIDS = (1,)

    @classmethod
    def make_equity_minute_bar_data(cls):
        trading_calendar = cls.trading_calendars[Equity]
        return create_minute_bar_data(
            trading_calendar.minutes_for_sessions_in_range(
                cls.equity_minute_bar_days[0],
                cls.equity_minute_bar_days[-1],
            ),
            cls.asset_finder.equities_sids,
        )

    def test_window_data(self):
        session = pd.Timestamp('2006-03-01')
        minute = self.trading_calendar.minutes_for_session(session)[1]
        data = self.create_bardata(simulation_dt_func=lambda: minute)
        asset = self.asset_finder.retrieve_asset(1)

        mean_volume, volatility = VolatilityVolumeShare(0.0)._get_window_data(
            data, asset, window_length=20,
        )

        #                            close  volume
        # 2006-01-31 00:00:00+00:00   29.0   119.0
        # 2006-02-01 00:00:00+00:00   30.0   120.0
        # 2006-02-02 00:00:00+00:00   31.0   121.0
        # 2006-02-03 00:00:00+00:00   32.0   122.0
        # 2006-02-06 00:00:00+00:00   33.0   123.0
        # 2006-02-07 00:00:00+00:00   34.0   124.0
        # 2006-02-08 00:00:00+00:00   35.0   125.0
        # 2006-02-09 00:00:00+00:00   36.0   126.0
        # 2006-02-10 00:00:00+00:00   37.0   127.0
        # 2006-02-13 00:00:00+00:00   38.0   128.0
        # 2006-02-14 00:00:00+00:00   39.0   129.0
        # 2006-02-15 00:00:00+00:00   40.0   130.0
        # 2006-02-16 00:00:00+00:00   41.0   131.0
        # 2006-02-17 00:00:00+00:00   42.0   132.0
        # 2006-02-21 00:00:00+00:00   43.0   133.0
        # 2006-02-22 00:00:00+00:00   44.0   134.0
        # 2006-02-23 00:00:00+00:00   45.0   135.0
        # 2006-02-24 00:00:00+00:00   46.0   136.0
        # 2006-02-27 00:00:00+00:00   47.0   137.0
        # 2006-02-28 00:00:00+00:00   48.0   138.0

        # Mean volume is (119 + 138) / 2 = 128.5
        self.assertEqual(mean_volume, 128.5)

        # Volatility is closes.pct_change().std() * sqrt(252)
        reference_vol = pd.Series(range(29, 49)).pct_change().std() * sqrt(252)
        self.assertEqual(volatility, reference_vol)

class OrdersStopTestCase(WithSimParams,
                         WithAssetFinder,
                         WithTradingCalendars,
                         ZiplineTestCase):

    START_DATE = pd.Timestamp('2006-01-05 14:31', tz='utc')
    END_DATE = pd.Timestamp('2006-01-05 14:36', tz='utc')
    SIM_PARAMS_CAPITAL_BASE = 1.0e5
    SIM_PARAMS_DATA_FREQUENCY = 'minute'
    SIM_PARAMS_EMISSION_RATE = 'daily'
    ASSET_FINDER_EQUITY_SIDS = (133,)
    minutes = pd.DatetimeIndex(
        start=START_DATE,
        end=END_DATE - pd.Timedelta('1 minute'),
        freq='1min'
    )

    @classmethod
    def init_class_fixtures(cls):
        super(OrdersStopTestCase, cls).init_class_fixtures()
        cls.ASSET133 = cls.asset_finder.retrieve_asset(133)

    STOP_ORDER_CASES = {
        # Stop orders can be long/short and have their price greater or
        # less than the stop.
        #
        # A stop being reached is conditional on the order direction.
        # Long orders reach the stop when the price is greater than the stop.
        # Short orders reach the stop when the price is less than the stop.
        #
        # Which leads to the following 4 cases:
        #
        #                    |   long   |   short  |
        # | price > stop     |          |          |
        # | price < stop     |          |          |
        #
        # Currently the slippage module acts according to the following table,
        # where 'X' represents triggering a transaction
        #                    |   long   |   short  |
        # | price > stop     |          |     X    |
        # | price < stop     |    X     |          |
        #
        # However, the following behavior *should* be followed.
        #
        #                    |   long   |   short  |
        # | price > stop     |    X     |          |
        # | price < stop     |          |     X    |

        'long | price gt stop': {
            'order': {
                'dt': pd.Timestamp('2006-01-05 14:30', tz='UTC'),
                'amount': 100,
                'filled': 0,
                'stop': 3.5
            },
            'event': {
                'dt': pd.Timestamp('2006-01-05 14:31', tz='UTC'),
                'volume': 2000,
                'price': 4.0,
                'high': 3.15,
                'low': 2.85,
                'close': 4.0,
                'open': 3.5
            },
            'expected': {
                'transaction': {
                    'price': 4.00025,
                    'dt': pd.Timestamp('2006-01-05 14:31', tz='UTC'),
                    'amount': 50,
                }
            }
        },
        'long | price lt stop': {
            'order': {
                'dt': pd.Timestamp('2006-01-05 14:30', tz='UTC'),
                'amount': 100,
                'filled': 0,
                'stop': 3.6
            },
            'event': {
                'dt': pd.Timestamp('2006-01-05 14:31', tz='UTC'),
                'volume': 2000,
                'price': 3.5,
                'high': 3.15,
                'low': 2.85,
                'close': 3.5,
                'open': 4.0
            },
            'expected': {
                'transaction': None
            }
        },
        'short | price gt stop': {
            'order': {
                'dt': pd.Timestamp('2006-01-05 14:30', tz='UTC'),
                'amount': -100,
                'filled': 0,
                'stop': 3.4
            },
            'event': {
                'dt': pd.Timestamp('2006-01-05 14:31', tz='UTC'),
                'volume': 2000,
                'price': 3.5,
                'high': 3.15,
                'low': 2.85,
                'close': 3.5,
                'open': 3.0
            },
            'expected': {
                'transaction': None
            }
        },
        'short | price lt stop': {
            'order': {
                'dt': pd.Timestamp('2006-01-05 14:30', tz='UTC'),
                'amount': -100,
                'filled': 0,
                'stop': 3.5
            },
            'event': {
                'dt': pd.Timestamp('2006-01-05 14:31', tz='UTC'),
                'volume': 2000,
                'price': 3.0,
                'high': 3.15,
                'low': 2.85,
                'close': 3.0,
                'open': 3.0
            },
            'expected': {
                'transaction': {
                    'price': 2.9998125,
                    'dt': pd.Timestamp('2006-01-05 14:31', tz='UTC'),
                    'amount': -50,
                }
            }
        },
    }

    @parameterized.expand(sorted(
        (name, case['order'], case['event'], case['expected'])
        for name, case in STOP_ORDER_CASES.items()
    ))
    def test_orders_stop(self, name, order_data, event_data, expected):
        data = order_data
        data['asset'] = self.ASSET133
        order = Order(**data)

        if expected['transaction']:
            expected['transaction']['asset'] = self.ASSET133
        event_data['asset'] = self.ASSET133

        assets = (
            (133, pd.DataFrame(
                {
                    'open': [event_data['open']],
                    'high': [event_data['high']],
                    'low': [event_data['low']],
                    'close': [event_data['close']],
                    'volume': [event_data['volume']],
                },
                index=[pd.Timestamp('2006-01-05 14:31', tz='UTC')],
            )),
        )
        days = pd.date_range(
            start=normalize_date(self.minutes[0]),
            end=normalize_date(self.minutes[-1])
        )
        with tmp_bcolz_equity_minute_bar_reader(
                self.trading_calendar, days, assets) as reader:
            data_portal = DataPortal(
                self.asset_finder, self.trading_calendar,
                first_trading_day=reader.first_trading_day,
                equity_minute_reader=reader,
            )

            slippage_model = VolumeShareSlippage()

            try:
                dt = pd.Timestamp('2006-01-05 14:31', tz='UTC')
                bar_data = BarData(
                    data_portal,
                    lambda: dt,
                    self.sim_params.data_frequency,
                    self.trading_calendar,
                    NoRestrictions(),
                )

                _, txn = next(slippage_model.simulate(
                    bar_data,
                    self.ASSET133,
                    [order],
                ))
            except StopIteration:
                txn = None

            if expected['transaction'] is None:
                self.assertIsNone(txn)
            else:
                self.assertIsNotNone(txn)

                for key, value in expected['transaction'].items():
                    self.assertEquals(value, txn[key])

class FixedBasisPointsSlippageTestCase(WithCreateBarData,
                                       ZiplineTestCase):

    START_DATE = pd.Timestamp('2006-01-05', tz='utc')
    END_DATE = pd.Timestamp('2006-01-05', tz='utc')

    ASSET_FINDER_EQUITY_SIDS = (133,)

    first_minute = (
        pd.Timestamp('2006-01-05 9:31', tz='US/Eastern').tz_convert('UTC')
    )

    @classmethod
    def make_equity_minute_bar_data(cls):
        yield 133, pd.DataFrame(
            {
                'open': [2.9],
                'high': [3.15],
                'low': [2.85],
                'close': [3.00],
                'volume': [200],
            },
            index=[cls.first_minute],
        )

    @classmethod
    def init_class_fixtures(cls):
        super(FixedBasisPointsSlippageTestCase, cls).init_class_fixtures()
        cls.ASSET133 = cls.asset_finder.retrieve_asset(133)

    @parameterized.expand([
        # Volume limit of 10% on an order of 100 shares. Since the bar volume
        # is 200, we should hit the limit and only fill 20 shares.
        ('5bps_over_vol_limit', 5, 0.1, 100, 3.0015, 20),
        # Same as previous, but on the short side.
        ('5bps_negative_over_vol_limit', 5, 0.1, -100, 2.9985, -20),
        # Volume limit of 10% on an order of 10 shares. We should fill the full
        # amount.
        ('5bps_under_vol_limit', 5, 0.1, 10, 3.0015, 10),
        # Same as previous, but on the short side.
        ('5bps_negative_under_vol_limit', 5, 0.1, -10, 2.9985, -10),
        # Change the basis points value.
        ('10bps', 10, 0.1, 100, 3.003, 20),
        # Change the volume limit points value.
        ('20pct_volume_limit', 5, 0.2, 100, 3.0015, 40),
    ])
    def test_fixed_bps_slippage(self,
                                name,
                                basis_points,
                                volume_limit,
                                order_amount,
                                expected_price,
                                expected_amount):

        slippage_model = FixedBasisPointsSlippage(basis_points=basis_points,
                                                  volume_limit=volume_limit)

        open_orders = [
            Order(
                dt=datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                amount=order_amount,
                filled=0,
                asset=self.ASSET133
            )
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.first_minute
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 1)
        _, txn = orders_txns[0]

        expected_txn = {
            'price': expected_price,
            'dt': datetime.datetime(2006, 1, 5, 14, 31, tzinfo=pytz.utc),
            'amount': expected_amount,
            'asset': self.ASSET133,
            'type': DATASOURCE_TYPE.TRANSACTION,
            'order_id': open_orders[0].id
        }

        self.assertIsNotNone(txn)
        self.assertEquals(expected_txn, txn.__dict__)

    @parameterized.expand([
        # Volume limit for the bar is 20. We've ordered 10 total shares.
        # We should fill both orders completely.
        ('order_under_limit', 9, 1, 9, 1),
        # Volume limit for the bar is 20. We've ordered 21 total shares.
        # The second order should have one share remaining after fill.
        ('order_over_limit', -3, 18, -3, 17),
    ])
    def test_volume_limit(self, name,
                          first_order_amount,
                          second_order_amount,
                          first_order_fill_amount,
                          second_order_fill_amount):

        slippage_model = FixedBasisPointsSlippage(basis_points=5,
                                                  volume_limit=0.1)

        open_orders = [
            Order(
                dt=datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                amount=order_amount,
                filled=0,
                asset=self.ASSET133
            )
            for order_amount in [first_order_amount, second_order_amount]
        ]

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.first_minute,
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEquals(len(orders_txns), 2)

        _, first_txn = orders_txns[0]
        _, second_txn = orders_txns[1]
        self.assertEquals(first_txn['amount'], first_order_fill_amount)
        self.assertEquals(second_txn['amount'], second_order_fill_amount)

    def test_broken_constructions(self):
        with self.assertRaises(ValueError) as e:
            FixedBasisPointsSlippage(basis_points=-1)

        self.assertEqual(
            str(e.exception),
            "FixedBasisPointsSlippage() expected a value greater than "
            "or equal to 0 for argument 'basis_points', but got -1 instead."
        )

        with self.assertRaises(ValueError) as e:
            FixedBasisPointsSlippage(volume_limit=0)

        self.assertEqual(
            str(e.exception),
            "FixedBasisPointsSlippage() expected a value strictly "
            "greater than 0 for argument 'volume_limit', but got 0 instead."
        )

    def test_fill_zero_shares(self):
        slippage_model = FixedBasisPointsSlippage(basis_points=5,
                                                  volume_limit=0.1)

        # since the volume limit for the bar is 20, the first order will be
        # filled and there will be a transaction for it, and the second order
        # will order zero shares so there should not be a transaction for it.
        open_orders = [
            Order(
                dt=datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                amount=20,
                filled=0,
                asset=self.ASSET133
            )
        ] * 2

        bar_data = self.create_bardata(
            simulation_dt_func=lambda: self.first_minute
        )

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))

        self.assertEqual(1, len(orders_txns))

        # ordering zero shares should result in zero transactions
        open_orders = [
            Order(
                dt=datetime.datetime(2006, 1, 5, 14, 30, tzinfo=pytz.utc),
                amount=0,
                filled=0,
                asset=self.ASSET133
            )
        ]

        orders_txns = list(slippage_model.simulate(
            bar_data,
            self.ASSET133,
            open_orders,
        ))
        self.assertEqual(0, len(orders_txns))


text:
namespace System {

    using System;
    using System.Runtime.InteropServices;

    public interface IServiceProvider
    {
        // Interface does not need to be marked with the serializable attribute
        Object GetService(Type serviceType);
    }
}


text:
/*
 * (c) 2009 Mathews Lab, University of Rochester Medical Center.
 *
 * This software is part of a group specifically designed for the RNAstructure
 * secondary structure prediction program.
 */

package ur_rna.RNAstructureUI.windows;

import ur_rna.RNAstructureUI.menus.RolloverMenu;
import ur_rna.RNAstructureUI.utilities.FileFilters;
import ur_rna.RNAstructureUI.utilities.FileField;
import ur_rna.RNAstructureUI.utilities.FieldPanel.FilePanel;
import ur_rna.RNAstructureUI.utilities.FieldPanel.NumberPanel;
import ur_rna.RNAstructureUI.utilities.NumberField.IntegerField;
import ur_rna.RNAstructureUI.utilities.SimpleDialogHandler;
import ur_rna.RNAstructureUI.utilities.StandardFileChooser;

/**
 * A class responsible for initializing and running the Dynalign refold
 * module, which refolds a previous Dynalign calculation from a save file.
 *
 * @author Jessica S. Reuter
 */
public class DynalignRefoldWindow
	extends ModuleWindow {
	private static final long serialVersionUID = 20120802;

	/**
	 * Constructor.
	 *

	 * Note that since the Dynalign save file knows its nucleic acid type, the
	 * exact nucleic acid type this window uses doesn't matter, and the
	 * nucleic acid type is specified as an empty string.
	 */
	public DynalignRefoldWindow() {
		super( "", "Refold From Dynalign Save File" );
	}

	@Override
	protected void executeModuleAction( String command ) {

		// Get any input controls from the window that handle actions.
		FilePanel files = (FilePanel)getInputControl( 1 );

		// If the action comes from the "Alignment File" button, try to select
		// an alignment file, and if one was selected set its name.
		if( command.equals( "Alignment File" ) ) {
			String file = StandardFileChooser.getSaveName(FileFilters.Alignment);
			if( file != null ) { files.setFile( 4, file ); }
		}

		// If the action comes from one of the "CT File" buttons, try to
		// select a CT file, and if one was selected set its name, based on
		// its index.
		else if( command.startsWith( "CT File" ) ) {
			String file = StandardFileChooser.getSaveName(FileFilters.CT);
			if( file != null ) {
				int index = ( command.endsWith( "1" ) ) ? 2 : 3;
				files.setFile( index, file );
			}
		}

		// If the action comes from the "Save File" button, get a Dynalign
		// save file and initialize a data structure.
		else if( command.equals( "Save File" ) ) {

			// Attempt to select the file.
			// If no file was selected, return.
			// Otherwise, set the file in the input panel.
			String file = StandardFileChooser.getOpenName(FileFilters.Dynalign);
			if( file == null ) { return; }
			else { files.setFile( 1, file ); }

			// Create a data structure.
			// If an error occurred creating the data structure, show an error
			// and return.
			String result =
				backend.buildRefoldDynalignDataStructure( file );
			if( !verifyBackendResult(result, "File: %s", file) ) { return; }

			// Enable the menus.
			menuBar.enableMenus();
		}
	}

	@Override
	protected void makeInputControls() {

		// Create the file input panel.
		FileField save = FileField.createDisabled( "Save File" );
		FileField ct1 = FileField.createEnabled( "CT File 1" );
		FileField ct2 = FileField.createEnabled( "CT File 2" );
		FileField align = FileField.createEnabled( "Alignment File" );
		FilePanel files = new FilePanel( this, save, ct1, ct2, align );
		files.setPanelWidth( 400 );
		files.makePanel();

		IntegerField energy =
			new IntegerField( "Max % Energy Difference", 20, 0 );
		IntegerField structures =
			new IntegerField( "Max Number of Structures", 750, 1 );
		IntegerField windowStruct =
			new IntegerField( "Structure Window Size", 0, 0 );
		IntegerField windowAlign =
			new IntegerField( "Alignment Window Size", 0, 0 );
		NumberPanel params =
			new NumberPanel( energy, structures, windowStruct, windowAlign );
		params.setPanelWidth( 300 );
		params.makePanel();

		// Add the components in their proper places.
		setGrid( 2, 1 );
		setFillHorizontal();
		placeComponent( 0, 0, files );
		setGrid( 1, 1 );
		placeComponent( 0, 1, params );
		makeStartButton( 1, 1 );
	}

	@Override
	protected void runMainCalculation() {

		// Get all input controls from the window.
		FilePanel files = (FilePanel)getInputControl( 1 );
		NumberPanel params = (NumberPanel)getInputControl( 2 );

		// Get the data from the file input panel.
		// If an error occurred while retrieving data, return.
		files.getFile( 1 );
		String ct1 = files.getFile( 2 );
		String ct2 = files.getFile( 3 );
		String align = files.getFile( 4 );
		if( files.isError() ) { return; }

		// Get the data from the parameters panel.
		Integer percent = ((IntegerField)params.getField( 1 )).getValue();
		Integer structures = ((IntegerField)params.getField( 2 )).getValue();
		Integer windowStr = ((IntegerField)params.getField( 3 )).getValue();
		Integer windowAli = ((IntegerField)params.getField( 4 )).getValue();

		// Run the calculation.
		// If an error occurred during calculation, return.
		showProgressBarDeterminate();
		String result =
			backend.runDynalignRefold(
				ct1, ct2, align, percent, structures, windowStr, windowAli );
		finishModule( result );
		if( !result.equals( "" ) ) { return; }

		// If the user wants to draw structures, draw them.
		String query = "Do you want to draw structures?";
		String doDraw = new SimpleDialogHandler().makeTwoChoicesDialog( query );
		if( doDraw.equals( "OK" ) ) {
			DrawingWindow one = new DrawingWindow( ct1 );
			DrawingWindow two = new DrawingWindow( ct2 );
			if( ( one.isError() == false ) && ( two.isError() == false ) ) {
				one.viewWindow();
				two.viewWindow();
			}
		}
	}

	@Override
	protected RolloverMenu[] setMenus() { return null; }
}


text:
package server

import (
	"context"
	"github.com/treeder/functions/api/models"
)

type RunnerListener interface {
	// BeforeDispatch called before a function run
	BeforeDispatch(ctx context.Context, route *models.Route) error
	// AfterDispatch called after a function run
	AfterDispatch(ctx context.Context, route *models.Route) error
}

// AddRunListeners adds a listener that will be fired before and after a function run.
func (s *Server) AddRunnerListener(listener RunnerListener) {
	s.runnerListeners = append(s.runnerListeners, listener)
}

func (s *Server) FireBeforeDispatch(ctx context.Context, route *models.Route) error {
	for _, l := range s.runnerListeners {
		err := l.BeforeDispatch(ctx, route)
		if err != nil {
			return err
		}
	}
	return nil
}

func (s *Server) FireAfterDispatch(ctx context.Context, route *models.Route) error {
	for _, l := range s.runnerListeners {
		err := l.AfterDispatch(ctx, route)
		if err != nil {
			return err
		}
	}
	return nil
}


text: <!DOCTYPE html>


text:
<?php

namespace Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor;

use Symfony\Component\HttpFoundation\Request;

/**
 * CookieTokenExtractor
 *
 * @author Nicolas Cabot <n.cabot@lexik.fr>
 */
class CookieTokenExtractor implements TokenExtractorInterface
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @param string $name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * @param Request $request
     *
     * @return string
     */
    public function extract(Request $request)
    {
        if (!$request->cookies->has($this->name)) {
            return false;
        }

        return $request->cookies->get($this->name);
    }
}


text:
package slack

import (
	"testing"
	"text/template"

	"github.com/ejholmes/slash"
	"github.com/remind101/conveyor"
	"github.com/remind101/conveyor/builder"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"golang.org/x/net/context"
)

const fakeUUID = "01234567-89ab-cdef-0123-456789abcdef"

func init() {
	newID = func() string { return fakeUUID }
}

func TestBuild(t *testing.T) {
	q := new(mockBuildQueue)
	r := new(mockBranchResolver)
	b := &Build{
		Queue:          q,
		branchResolver: r,
		urlTmpl:        template.Must(template.New("url").Parse("http://conveyor/logs/{{.ID}}")),
	}

	ctx := slash.WithParams(context.Background(), map[string]string{
		"owner":  "remind101",
		"repo":   "acme-inc",
		"branch": "master",
	})

	r.On("resolveBranch", "remind101", "acme-inc", "master").Return("sha", nil)
	q.On("Push", ctx, builder.BuildOptions{
		ID:         fakeUUID,
		Repository: "remind101/acme-inc",
		Sha:        "sha",
		Branch:     "master",
	}).Return(nil)

	rec := &fakeResponder{responses: make(chan slash.Response, 1)}
	resp, err := b.ServeCommand(ctx, rec, slash.Command{})
	assert.Equal(t, "One moment...", resp.Text)
	assert.NoError(t, err)

	resp = <-rec.responses
	assert.Equal(t, "Building remind101/acme-inc@master: http://conveyor/logs/01234567-89ab-cdef-0123-456789abcdef", resp.Text)
}

type mockBuildQueue struct {
	mock.Mock
}

func (m *mockBuildQueue) Push(ctx context.Context, options builder.BuildOptions) error {
	args := m.Called(ctx, options)
	return args.Error(0)
}

func (m *mockBuildQueue) Subscribe(chan conveyor.BuildContext) error {
	return nil
}

type mockBranchResolver struct {
	mock.Mock
}

func (m *mockBranchResolver) resolveBranch(owner, repo, branch string) (string, error) {
	args := m.Called(owner, repo, branch)
	return args.String(0), args.Error(1)
}

type fakeResponder struct {
	responses chan slash.Response
}

func (r *fakeResponder) Respond(resp slash.Response) error {
	r.responses <- resp
	return nil
}


text:
all:
	gcc ntpdatehttp.c -lcurl -o ntpdatehttp

clean:
	$(RM) ntpdatehttp


text:
[Cerca](http://cerca-language.herokuapp.com)

1. Remove Google Analytics script tag from index.html

2. Microsoft Translator services credentials should be stored in environment variables:
  * CERCA_MST_ID
  * CERCA_MST_SECRET

3. After deployment run in ssh shell:
`python phoneticfy.py en ./data/google-10000-english-no-swears.txt`

## Credits
* [google-1000-english](https://github.com/first20hours/google-10000-english)


text:
/**
 * Created on: Jan 28, 2013
 */
package com.tubros.constraints.api
package problem

import scalaz._

import org.junit.runner.RunWith
import org.scalatest._
import org.scalatest.junit.JUnitRunner

/**
 * The '''ProblemSpec''' type verifies
 * [[com.tubros.constraints.api.problem.Problem]] to ensure it provides the
 * behaviour needed by the primary CSP problem abstraction.
 *
 * @author svickers
 *
 */
@RunWith (classOf[JUnitRunner])
class ProblemSpec
	extends ProjectSpec
{
	"A Problem" should "require at least one Equation" in
	{
		val problem = Problem (
			new Equation[Int] with DerivedValueSupport[Int] {
				def apply = 'x := 99;
				}
			);

		problem.equations.size shouldBe (1);
	}
}


text:
namespace exegesis {
namespace x86 {

// Adds the missing operand size override prefix to the binary encoding
// specification of instruction where it is missing. We detect such instructions
// finding groups of instructions that have the same binary encoding, but where
// some of them use 16-bit operand, while others use 32-bit operands.
// Note that this transform depends on operand types being added to the vendor
// syntax section of the instruction.
absl::Status AddOperandSizeOverridePrefix(InstructionSetProto* instruction_set);

// Adds operand size override prefix usage to the encoding specifications of the
// legacy instructions in 'instruction_set'. This transform must run after other
// transforms modifying the operand size override status.
absl::Status AddOperandSizeOverridePrefixUsage(
    InstructionSetProto* instruction_set);

// Adds the operand size override prefix to 16-bit versions of instructions with
// implicit operands. Because these instructions have no operand, we have no way
// of detecting the 16-bit version other than through their mnemonics.
absl::Status AddOperandSizeOverrideToInstructionsWithImplicitOperands(
    InstructionSetProto* instruction_set);

// Adds the operand size override prefix to 16-bit versions of instructions
// where the generic 16-bit detection fails. This function handles instructions
// where there are two versions with two different sizes, but the sizes are not
// strictly 16-bit and 32-bit. They are typically either 16/64-bit instructions
// or 32/48-bit instructions (16-bit selector + 16/32-bit offset).
absl::Status AddOperandSizeOverrideToSpecialCaseInstructions(
    InstructionSetProto* instruction_set);

// Adds another version with operand size override for instructions that
// existence of an operand size override is optional.
absl::Status AddOperandSizeOverrideVersionForSpecialCaseInstructions(
    InstructionSetProto* instruction_set);

}  // namespace x86
}  // namespace exegesis

#endif  // EXEGESIS_X86_CLEANUP_INSTRUCTION_SET_OPERAND_SIZE_OVERRIDE_H_


text:
/**
 * In order to provide fast and flexible logging, this project uses Cocoa Lumberjack.
 *
 * The Google Code page has a wealth of documentation if you have any questions.
 * https://github.com/robbiehanson/CocoaLumberjack
 *
 * Here's what you need to know concerning how logging is setup for CocoaHTTPServer:
 *
 * There are 4 log levels:
 * - Error
 * - Warning
 * - Info
 * - Verbose
 *
 * In addition to this, there is a Trace flag that can be enabled.
 * When tracing is enabled, it spits out the methods that are being called.
 *
 * Please note that tracing is separate from the log levels.
 * For example, one could set the log level to warning, and enable tracing.
 *
 * All logging is asynchronous, except errors.
 * To use logging within your own custom files, follow the steps below.
 *
 * Step 1:
 * Import this header in your implementation file:
 *
 * #import "HTTPLogging.h"
 *
 * Step 2:
 * Define your logging level in your implementation file:
 *
 * // Log levels: off, error, warn, info, verbose
 * static const int httpLogLevel = HTTP_LOG_LEVEL_VERBOSE;
 *
 * If you wish to enable tracing, you could do something like this:
 *
 * // Debug levels: off, error, warn, info, verbose
 * static const int httpLogLevel = HTTP_LOG_LEVEL_INFO | HTTP_LOG_FLAG_TRACE;
 *
 * Step 3:
 * Replace your NSLog statements with HTTPLog statements according to the severity of the message.
 *
 * NSLog(@"Fatal error, no dohickey found!"); -> HTTPLogError(@"Fatal error, no dohickey found!");
 *
 * HTTPLog works exactly the same as NSLog.
 * This means you can pass it multiple variables just like NSLog.
**/

//#import "DDLog.h"
#import <CocoaLumberjack/DDLog.h>

// Define logging context for every log message coming from the HTTP server.
// The logging context can be extracted from the DDLogMessage from within the logging framework,
// which gives loggers, formatters, and filters the ability to optionally process them differently.

#define HTTP_LOG_CONTEXT 80

// Configure log levels.

#define HTTP_LOG_FLAG_ERROR   (1 << 0) // 0...00001
#define HTTP_LOG_FLAG_WARN    (1 << 1) // 0...00010
#define HTTP_LOG_FLAG_INFO    (1 << 2) // 0...00100
#define HTTP_LOG_FLAG_VERBOSE (1 << 3) // 0...01000

#define HTTP_LOG_LEVEL_OFF     0                                              // 0...00000
#define HTTP_LOG_LEVEL_ERROR   (HTTP_LOG_LEVEL_OFF   | HTTP_LOG_FLAG_ERROR)   // 0...00001
#define HTTP_LOG_LEVEL_WARN    (HTTP_LOG_LEVEL_ERROR | HTTP_LOG_FLAG_WARN)    // 0...00011
#define HTTP_LOG_LEVEL_INFO    (HTTP_LOG_LEVEL_WARN  | HTTP_LOG_FLAG_INFO)    // 0...00111
#define HTTP_LOG_LEVEL_VERBOSE (HTTP_LOG_LEVEL_INFO  | HTTP_LOG_FLAG_VERBOSE) // 0...01111

// Setup fine grained logging.
// The first 4 bits are being used by the standard log levels (0 - 3)
//
// We're going to add tracing, but NOT as a log level.
// Tracing can be turned on and off independently of log level.

#define HTTP_LOG_FLAG_TRACE   (1 << 4) // 0...10000

// Setup the usual boolean macros.

#define HTTP_LOG_ERROR   (httpLogLevel & HTTP_LOG_FLAG_ERROR)
#define HTTP_LOG_WARN    (httpLogLevel & HTTP_LOG_FLAG_WARN)
#define HTTP_LOG_INFO    (httpLogLevel & HTTP_LOG_FLAG_INFO)
#define HTTP_LOG_VERBOSE (httpLogLevel & HTTP_LOG_FLAG_VERBOSE)
#define HTTP_LOG_TRACE   (httpLogLevel & HTTP_LOG_FLAG_TRACE)

// Configure asynchronous logging.
// We follow the default configuration,
// but we reserve a special macro to easily disable asynchronous logging for debugging purposes.

#define HTTP_LOG_ASYNC_ENABLED   YES

#define HTTP_LOG_ASYNC_ERROR   ( NO && HTTP_LOG_ASYNC_ENABLED)
#define HTTP_LOG_ASYNC_WARN    (YES && HTTP_LOG_ASYNC_ENABLED)
#define HTTP_LOG_ASYNC_INFO    (YES && HTTP_LOG_ASYNC_ENABLED)
#define HTTP_LOG_ASYNC_VERBOSE (YES && HTTP_LOG_ASYNC_ENABLED)
#define HTTP_LOG_ASYNC_TRACE   (YES && HTTP_LOG_ASYNC_ENABLED)

// Define logging primitives.

#define HTTPLogError(frmt, ...)    LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_ERROR,   httpLogLevel, HTTP_LOG_FLAG_ERROR,  \
                                                  HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)

#define HTTPLogWarn(frmt, ...)     LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_WARN,    httpLogLevel, HTTP_LOG_FLAG_WARN,   \
                                                  HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)

#define HTTPLogInfo(frmt, ...)     LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_INFO,    httpLogLevel, HTTP_LOG_FLAG_INFO,    \
                                                  HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)

#define HTTPLogVerbose(frmt, ...)  LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_VERBOSE, httpLogLevel, HTTP_LOG_FLAG_VERBOSE, \
                                                  HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)

#define HTTPLogTrace()             LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_TRACE,   httpLogLevel, HTTP_LOG_FLAG_TRACE, \
                                                  HTTP_LOG_CONTEXT, @"%@[%p]: %@", THIS_FILE, self, THIS_METHOD)

#define HTTPLogTrace2(frmt, ...)   LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_TRACE,   httpLogLevel, HTTP_LOG_FLAG_TRACE, \
                                                  HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)

#define HTTPLogCError(frmt, ...)      LOG_C_MAYBE(HTTP_LOG_ASYNC_ERROR,   httpLogLevel, HTTP_LOG_FLAG_ERROR,   \
                                                  HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)

#define HTTPLogCWarn(frmt, ...)       LOG_C_MAYBE(HTTP_LOG_ASYNC_WARN,    httpLogLevel, HTTP_LOG_FLAG_WARN,    \
                                                  HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)

#define HTTPLogCInfo(frmt, ...)       LOG_C_MAYBE(HTTP_LOG_ASYNC_INFO,    httpLogLevel, HTTP_LOG_FLAG_INFO,    \
                                                  HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)

#define HTTPLogCVerbose(frmt, ...)    LOG_C_MAYBE(HTTP_LOG_ASYNC_VERBOSE, httpLogLevel, HTTP_LOG_FLAG_VERBOSE, \
                                                  HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)

#define HTTPLogCTrace()               LOG_C_MAYBE(HTTP_LOG_ASYNC_TRACE,   httpLogLevel, HTTP_LOG_FLAG_TRACE, \
                                                  HTTP_LOG_CONTEXT, @"%@[%p]: %@", THIS_FILE, self, __FUNCTION__)

#define HTTPLogCTrace2(frmt, ...)     LOG_C_MAYBE(HTTP_LOG_ASYNC_TRACE,   httpLogLevel, HTTP_LOG_FLAG_TRACE, \
                                                  HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)