text:
export * from './AppSettings';
export * from './AppSettingsStore';

export * from './SharePointSettings';
export * from './SharePointSettingsStore';

export * from './ScriptFolder';
export * from './ScriptFile';
export * from './ScriptsStore';

export * from './PageSettings';
export * from './WebPartSettings';
export * from './PagesStore';

export * from './Util';

redpajama_set_name: RedPajamaGithub


text:
#import <Foundation/Foundation.h>

/**
 @summary We want to avoid capturing layer instances on a background queue, but we want a way to cancel rendering
 immediately if another display pass begins.  ASSentinel is owned by the layer and passed to the background
 block.
 */
@interface ASSentinel : NSObject

/**
 Returns the current value of the sentinel.
 */
- (int32_t)value;

/**
 Atomically increments the value and returns the new value.
 */
- (int32_t)increment;

@end


text:
require 'helpers'

describe GamesDice::Die do
  before do
    # Set state of default PRNG
    srand(4567)
  end

  describe '#new' do
    it 'should return an object that represents e.g. a six-sided die' do
      die = GamesDice::Die.new(6)
      expect(die.min).to eql 1
      expect(die.max).to eql 6
      expect(die.sides).to eql 6
    end

    it 'should accept any object with a rand(Integer) method as the second param' do
      prng = TestPRNG.new
      die = GamesDice::Die.new(20, prng)
      [16, 7, 3, 11, 16, 18, 20, 7].each do |expected|
        expect(die.roll).to eql expected
        expect(die.result).to eql expected
      end
    end
  end

  describe '#roll and #result' do
    it "should return results based on Ruby's internal rand() by default" do
      die = GamesDice::Die.new(10)
      [5, 4, 10, 4, 7, 8, 1, 9].each do |expected|
        expect(die.roll).to eql expected
        expect(die.result).to eql expected
      end
    end
  end

  describe '#min and #max' do
    it 'should calculate correct min, max' do
      die = GamesDice::Die.new(20)
      expect(die.min).to eql 1
      expect(die.max).to eql 20
    end
  end

  describe '#probabilities' do
    it "should return the die's probability distribution as a GamesDice::Probabilities object" do
      die = GamesDice::Die.new(6)
      probs = die.probabilities
      expect(probs).to be_a GamesDice::Probabilities

      expect(probs.to_h).to be_valid_distribution

      expect(probs.p_eql(1)).to be_within(1e-10).of 1 / 6.0
      expect(probs.p_eql(2)).to be_within(1e-10).of 1 / 6.0
      expect(probs.p_eql(3)).to be_within(1e-10).of 1 / 6.0
      expect(probs.p_eql(4)).to be_within(1e-10).of 1 / 6.0
      expect(probs.p_eql(5)).to be_within(1e-10).of 1 / 6.0
      expect(probs.p_eql(6)).to be_within(1e-10).of 1 / 6.0

      expect(probs.expected).to be_within(1e-10).of 3.5
    end
  end

  describe '#all_values' do
    it 'should return array with one result value per side' do
      die = GamesDice::Die.new(8)
      expect(die.all_values).to eql [1, 2, 3, 4, 5, 6, 7, 8]
    end
  end

  describe '#each_value' do
    it 'should iterate through all sides of the die' do
      die = GamesDice::Die.new(10)
      arr = []
      die.each_value { |x| arr << x }
      expect(arr).to eql [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    end
  end
end


text:
package com.github.sparkfy.network.protocol;

import com.github.sparkfy.network.buffer.ManagedBuffer;
import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
import io.netty.channel.FileRegion;
import io.netty.util.AbstractReferenceCounted;
import io.netty.util.ReferenceCountUtil;
import java.io.IOException;
import java.nio.channels.WritableByteChannel;

/**
 * A wrapper message that holds two separate pieces (a header and a body).
 *
 * The header must be a ByteBuf, while the body can be a ByteBuf or a FileRegion.
 */
class MessageWithHeader extends AbstractReferenceCounted implements FileRegion {

  private final ManagedBuffer managedBuffer;
  private final ByteBuf header;
  private final int headerLength;
  private final Object body;
  private final long bodyLength;
  private long totalBytesTransferred;

  /**
   * Construct a new MessageWithHeader.
   *
   * @param managedBuffer the {@link ManagedBuffer} that the message body came from. This needs to
   *                      be passed in so that the buffer can be freed when this message is
   *                      deallocated. Ownership of the caller's reference to this buffer is
   *                      transferred to this class, so if the caller wants to continue to use the
   *                      ManagedBuffer in other messages then they will need to call retain() on
   *                      it before passing it to this constructor. This may be null if and only if
   *                      `body` is a {@link FileRegion}.
   * @param header the message header.
   * @param body the message body. Must be either a {@link ByteBuf} or a {@link FileRegion}.
   * @param bodyLength the length of the message body, in bytes.
     */
  MessageWithHeader(
       ManagedBuffer managedBuffer,
      ByteBuf header,
      Object body,
      long bodyLength) {
    Preconditions.checkArgument(body instanceof ByteBuf || body instanceof FileRegion,
            "Body must be a ByteBuf or a FileRegion.");
    this.managedBuffer = managedBuffer;
    this.header = header;
    this.headerLength = header.readableBytes();
    this.body = body;
    this.bodyLength = bodyLength;
  }

  @Override
  public long count() {
    return headerLength + bodyLength;
  }

  @Override
  public long position() {
    return 0;
  }

  @Override
  public long transfered() {
    return totalBytesTransferred;
  }

  /**
   * This code is more complicated than you would think because we might require multiple
   * transferTo invocations in order to transfer a single MessageWithHeader to avoid busy waiting.
   *
   * The contract is that the caller will ensure position is properly set to the total number
   * of bytes transferred so far (i.e. value returned by transfered()).
   */
  @Override
  public long transferTo(final WritableByteChannel target, final long position) throws IOException {
    Preconditions.checkArgument(position == totalBytesTransferred, "Invalid position.");
    // Bytes written for header in this call.
    long writtenHeader = 0;
    if (header.readableBytes() > 0) {
      writtenHeader = copyByteBuf(header, target);
      totalBytesTransferred += writtenHeader;
      if (header.readableBytes() > 0) {
        return writtenHeader;
      }
    }

    // Bytes written for body in this call.
    long writtenBody = 0;
    if (body instanceof FileRegion) {
      writtenBody = ((FileRegion) body).transferTo(target, totalBytesTransferred - headerLength);
    } else if (body instanceof ByteBuf) {
      writtenBody = copyByteBuf((ByteBuf) body, target);
    }
    totalBytesTransferred += writtenBody;

    return writtenHeader + writtenBody;
  }

  @Override
  protected void deallocate() {
    header.release();
    ReferenceCountUtil.release(body);
    if (managedBuffer != null) {
      managedBuffer.release();
    }
  }

  private int copyByteBuf(ByteBuf buf, WritableByteChannel target) throws IOException {
    int written = target.write(buf.nioBuffer());
    buf.skipBytes(written);
    return written;
  }
}


text:
<?php

namespace Richpolis\FrontendBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Richpolis\FrontendBundle\Repository\BotellasRepository;

class MensajesType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('tituloEn','text',array('label'=>'Titulo Ingles'))
            ->add('tituloEs','text',array('label'=>'Titulo Español'))
            ->add('mensajeEn','textarea', array(
                    'attr' => array(
                        'class' => 'tinymce',
                        'data-theme' => 'advanced' // Skip it if you want to use default theme
                    ),'label'=>'Mensaje Ingles'
                ))
            ->add('mensajeEs','textarea', array(
                    'attr' => array(
                        'class' => 'tinymce',
                        'data-theme' => 'advanced' // Skip it if you want to use default theme
                    ),'label'=>'Mensaje Español'
                ))
            ->add('file','file',array(
                'label'=>'Imagen',
                'required'=>false,
                ))
            ->add('clase')
            ->add('style')
            ->add('isHowToMix',null,array('label'=>'How to Mix?','required'=>false))
            ->add('isActive',null,array('label'=>'Activo?','required'=>false))
            ->add('botella','entity', array(
                'class' => 'FrontendBundle:Botellas',
                'query_builder' => function(BotellasRepository $er) {
                        return $er->createQueryBuilder('u')
                                ->orderBy('u.id', 'ASC');
                },
                'property'  => 'botella',
                'label'     => 'Botella',
                'multiple'  => false
            ))
            ->add('imagen','hidden')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Richpolis\FrontendBundle\Entity\Mensajes'
        ));
    }

    public function getName()
    {
        return 'richpolis_frontendbundle_mensajestype';
    }
}


text:
Percona-Server-5.1
==================

# DISCONTINUED PROJECT
Percona-Server-5.1 cloned from Percona Bazaar
This project was created to help me learn Jenkins, and I did not like Bazaar (so, so slow) so I put it into Github.
I have a job pull from Bazaar, make sure my stuff is there and put it here into Github.
I was planning on packaging my own debs so I could inject custom things into the package, but now I've changed my mind and am just going to use Percona's official Ubuntu packages, and inject via a separate package that re-owns the config files with dpkg divert.
http://www.percona.com/doc/percona-server/5.5/installation/apt_repo.html

#I install with this run in the shell

gpg --keyserver  hkp://keys.gnupg.net --recv-keys 1C4CBDCDCD2EFD2A
gpg -a --export CD2EFD2A | sudo apt-key add -

if [ ! -f /etc/apt/sources.list.d/percona.list ]
 then
    echo "deb http://repo.percona.com/apt $(grep DISTRIB_CODENAME /etc/lsb-release | sed 's/=/ /' | awk '{ print $2 }') main" | sudo tee /etc/apt/sources.list.d/percona.list
    echo "deb-src http://repo.percona.com/apt $(grep DISTRIB_CODENAME /etc/lsb-release | sed 's/=/ /' | awk '{ print $2 }') main" | sudo tee -a /etc/apt/sources.list.d/percona.list
else
    echo "Percona sources exist, $(cat /etc/apt/sources.list.d/percona.list)"
fi
#Sometimes it doesn't configure right, so you have to just rerun that line
apt-get update

#Percona SERVER
apt-get install mailutils percona-server-client-5.1 libmysqlclient18 percona-server-server-5.1 libdbd-mysql-perl postfix mailutils
touch /var/log/{btmp,lastlog,wtmp}

#Percona CLIENT
apt-get install mailutils percona-server-client-5.1 libmysqlclient16 libdbd-mysql-perl postfix


text:
<!DOCTYPE html>

<title>Cultural Heritage Object</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"/>
<link type="text/css" rel="stylesheet" href="/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="/css/bootstrap-theme.min.css" />
<link type="text/css" rel="stylesheet" href="/css/layout.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

(navbar)

CH Object

  <form th:object="${cho}" role="form" >
  </form>

ID

Title

Date

Medium

CreditLine

Description

Gallery Text

   <form role="form">

      Comment:
      <textarea class="form-control" rows="5" id="comment"></textarea>

  </form>

      	ID
        Title
        Date
        Medium
        Credit Line
        Description
        Gallery Text

(footer)


text:
package com.pinhuba.common.pack;

import com.pinhuba.common.util.EnumUtil;
import com.pinhuba.core.pojo.OaChatGroups;
import com.pinhuba.core.pojo.OaChatters;
import com.pinhuba.core.pojo.OaForums;
import com.pinhuba.core.pojo.OaPosts;
import com.pinhuba.core.pojo.OaVote;

public class OacommunHqlPack {
	//查询所有分组信息
	public static String packChatGroupQuery(OaChatGroups groups, String emp, long companyId) {
		StringBuffer result = new StringBuffer();
		HqlPack.getStringLikerPack(groups.getOaChatgpName(), "oaChatgpName", result);
		HqlPack.getStringEqualPack(emp, "recordId", result);
		HqlPack.getNumEqualPack(companyId, "companyId",result);
		return result.toString();
	}

	//查询通讯手册记录信息
	public static String packCommunicationQuery(OaChatters chatter, String emp, long companyId) {
		StringBuffer result = new StringBuffer();
		HqlPack.getStringLikerPack(chatter.getOaChatEmp(), "oaChatEmp", result);
		HqlPack.getStringLikerPack(chatter.getOaChatCom(), "oaChatCom", result);
		HqlPack.getNumEqualPack(chatter.getOaChatGroup(), "oaChatGroup", result);
		HqlPack.getNumEqualPack(chatter.getOaChatSex(), "oaChatSex", result);
		HqlPack.getNumEqualPack(chatter.getOaIsShare(), "oaIsShare", result);
		HqlPack.getStringEqualPack(emp, "recordId", result);
		HqlPack.getNumEqualPack(companyId, "companyId",result);
		return result.toString();
	}

	//不分页查询分组信息
	public static String packGroupQuery(String emp, long companyId){
		StringBuffer result = new StringBuffer();
		HqlPack.getStringEqualPack(emp, "recordId", result);
		HqlPack.getNumEqualPack(companyId, "companyId",result);
		return result.toString();
	}

	// 查询共享给自己的通讯手册记录
	public static String packChatShare(String emp, long companyId){
		StringBuffer result = new StringBuffer();
		String emptep = emp+",";
		HqlPack.getStringLikerPack(emptep, "oaShareEmp", result);
		HqlPack.getNumEqualPack(EnumUtil.OA_COMMUNICATION_IS_SHARE.SHARE.value, "oaIsShare",result);
		HqlPack.getNumEqualPack(companyId, "companyId",result);
		return result.toString();
	}
	//查询论坛版块信息
	public static String packForumsQuery(OaForums forums, long companyId) {
		StringBuffer result = new StringBuffer();
		HqlPack.getStringLikerPack(forums.getOaForumName(), "oaForumName", result);
		HqlPack.getStringEqualPack(forums.getOaForumEmp(), "oaForumEmp", result);
		HqlPack.getStringEqualPack(forums.getOaForumAdmin(), "oaForumAdmin", result);
		HqlPack.timeBuilder(forums.getOaForumTime(), "oaForumTime", result, false,false);
		HqlPack.getNumEqualPack(companyId, "companyId",result);
		return result.toString();
	}

	//查询帖子信息
	public static String packPostsQuery(OaPosts posts, long companyId) {
		StringBuffer result = new StringBuffer();
		HqlPack.getStringLikerPack(posts.getOaPostName(), "oaPostName", result);
		HqlPack.getStringEqualPack(posts.getOaPostEmp(), "oaPostEmp", result);
		HqlPack.getNumEqualPack(posts.getOaPostForum(), "oaPostForum",result);
		HqlPack.getNumEqualPack(posts.getOaIsBoutique(), "oaIsBoutique",result);
		HqlPack.timeBuilder(posts.getOaPostTime(), "oaPostTime", result, false,true);
		HqlPack.getNumEqualPack(companyId, "companyId",result);
		result.append(" and model.oaIsPost = "+EnumUtil.OA_IS_POSTS.POSTS.value);
		return result.toString();
	}

	//无条件,无分页查询版块信息
	public static String packNoForumQuery(long companyId){
		StringBuffer result = new StringBuffer();
		HqlPack.getNumEqualPack(companyId, "companyId",result);
		return result.toString();
	}

	//查询帖子回复信息
	public static String packRegPostsQuery(long postid,long companyId){
		StringBuffer result = new StringBuffer();
		HqlPack.getNumEqualPack(postid, "oaPostReg",result);
		HqlPack.getNumEqualPack(companyId, "companyId",result);
		return result.toString();
	}

	//查询投票记录信息(投票页面用)
	public static String packVoteQuery(OaVote vote, long companyId,String empId,String depId) {
		StringBuffer result = new StringBuffer();
		result.append("select vote.* from oa_vote vote,hrm_employee emp where vote.oa_vote_emp = emp.hrm_employee_id");

		SqlPack.getStringLikerPack(vote.getOaVoteName(), "vote.oa_vote_name", result);
		SqlPack.getNumEqualPack(vote.getOaChooseType(), "vote.oa_choose_type", result);
		SqlPack.getNumEqualPack(vote.getOaIsAnonymous(), "vote.oa_is_anonymous", result);
		SqlPack.getNumEqualPack(vote.getOaVoteType(), "vote.oa_vote_type", result);
		if(vote.getEmployee() != null){
		        SqlPack.getStringLikerPack(vote.getEmployee().getHrmEmployeeName(), "emp.hrm_employee_name", result);
		}
		SqlPack.timeBuilder(vote.getOaVoteStart(),"vote.oa_vote_start",result,false,true);
		SqlPack.timeBuilder(vote.getOaVoteEnd(),"vote.oa_vote_end",result,false,true);
		SqlPack.getNumEqualPack(vote.getOaVoteStatus(), "vote.oa_vote_status",result);
		SqlPack.getNumEqualPack(companyId, "vote.company_id",result);

//		result.append(" and ( vote.oa_range_emp like '%"+empId+"%' or CheckStrInArr('"+depId+"',vote.oa_range_dep)>0   or vote.oa_vote_emp ='"+empId.substring(0, empId.length()-1)+"')");
		result.append(" and ( vote.oa_range_emp like '%"+empId+"%' or INSTR(vote.oa_range_dep,'"+depId+"')>0   or vote.oa_vote_emp ='"+empId.substring(0, empId.length()-1)+"')");

		return result.toString();
	}

	//查询投票记录信息(投票管理页面用)
	public static String packVoteManagerQuery(OaVote vote, long companyId) {
		StringBuffer result = new StringBuffer();
		HqlPack.getStringLikerPack(vote.getOaVoteName(), "oaVoteName", result);
		HqlPack.getNumEqualPack(vote.getOaChooseType(), "oaChooseType", result);
		HqlPack.getNumEqualPack(vote.getOaIsAnonymous(), "oaIsAnonymous", result);
		HqlPack.getNumEqualPack(vote.getOaVoteType(), "oaVoteType", result);
		HqlPack.getStringEqualPack(vote.getOaVoteEmp(), "oaVoteEmp", result);
		HqlPack.timeBuilder(vote.getOaVoteStart(),"oaVoteStart",result,false,true);
		HqlPack.timeBuilder(vote.getOaVoteEnd(),"oaVoteEnd",result,false,true);
		HqlPack.getNumEqualPack(vote.getOaVoteStatus(), "oaVoteStatus",result);
		HqlPack.getNumEqualPack(companyId, "companyId",result);
		return result.toString();
	}
}


text:
Every experiment is a simulation of robot interacting with its environment.
A robot is controlled by a controller which may be any algorithm that transforms observation vectors into action vectors. Currently implemented controllers include Recurrent Neural Network and Linear Perceptron.
Environment also defines a fitness measure that outputs score at the end of simulation. This score could be used as a guide to evolve increasingly competent robot controllers with a blackbox optimization method such as Genetic Algorithm.

##Experiment 0: "avoid"

In this experiment a puck-shaped robot with 9 distance sensors tries to control its wheels' speeds to avoid driving over balls randomly spawned in its 10x10 area.
To run this experiment type `node experiment.js`
You can speed up the experiment by running it in clustered mode: `node experiment.js cluster 3`, tune the number to N-1 of cores available on your machine.


text:
package com.atomgraph.core.exception;

import com.sun.jersey.api.client.ClientResponse;

/**
 * A runtime exception thrown by a client that signals a failure to process the HTTP request or HTTP response.
 *
 * @author Martynas Jusevičius {@literal <martynas@atomgraph.com>}
 */
public class ClientException extends RuntimeException
{

    private final ClientResponse cr;

    public ClientException(ClientResponse cr)
    {
        super(cr.getStatusInfo().getReasonPhrase());
        this.cr = cr;
    }

    public ClientResponse getClientResponse()
    {
        return cr;
    }

}


text:
BEGIN_REPLICANT_NAMESPACE

class pending_call_robust : public pending_robust
{
    public:
        pending_call_robust(int64_t id,
                            const char* object,
                            const char* func,
                            const char* input, size_t input_sz,
                            replicant_returncode* status,
                            char** output, size_t* output_sz);
        virtual ~pending_call_robust() throw ();

    public:
        virtual std::auto_ptr<e::buffer> request(uint64_t nonce);
        virtual bool resend_on_failure();
        virtual void handle_response(client* cl,
                                     std::auto_ptr<e::buffer> msg,
                                     e::unpacker up);

    private:
        const std::string m_object;
        const std::string m_func;
        const std::string m_input;
        char** m_output;
        size_t* m_output_sz;

    private:
        pending_call_robust(const pending_call_robust&);
        pending_call_robust& operator = (const pending_call_robust&);
};

END_REPLICANT_NAMESPACE

#endif // replicant_client_pending_call_robust_h_


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="Florismart.Neverendingview.Droid.Sample">
	<uses-sdk />
	<application android:label="Florismart.Neverendingview.Droid.Sample">
	</application>
</manifest>


text:
using Melanchall.DryWetMidi.Composing;
using Melanchall.DryWetMidi.MusicTheory;
using Melanchall.DryWetMidi.Interaction;
using NUnit.Framework;

namespace Melanchall.DryWetMidi.Tests.Composing
{
    [TestFixture]
    public sealed partial class PatternBuilderTests
    {
        #region Test methods

        #region StepBack

        [Test]
        public void StepBack()
        {
            var pattern = new PatternBuilder()
                .MoveToTime(new MetricTimeSpan(0, 0, 10))
                .StepForward(new MetricTimeSpan(0, 0, 30))
                .StepBack(new MetricTimeSpan(0, 0, 37))

                .Note(Notes.A0)

                .Build();

            PatternTestUtilities.TestNotes(pattern, new[]
            {
                new NoteInfo(NoteName.A, 0, new MetricTimeSpan(0, 0, 3), MusicalTimeSpan.Quarter)
            });
        }

        [Test]
        public void StepBack_BeyondZero()
        {
            var pattern = new PatternBuilder()
                .MoveToTime(new MetricTimeSpan(0, 0, 10))
                .StepForward(new MetricTimeSpan(0, 0, 30))
                .StepBack(new MetricTimeSpan(0, 1, 37))

                .Note(Notes.A0)

                .Build();

            PatternTestUtilities.TestNotes(pattern, new[]
            {
                new NoteInfo(NoteName.A, 0, new MetricTimeSpan(0, 0, 0), MusicalTimeSpan.Quarter)
            });
        }

        [Test]
        public void StepBack_DefaultStep()
        {
            var pattern = new PatternBuilder()
                .MoveToTime(MusicalTimeSpan.Whole)
                .StepBack()
                .Note(Notes.A0)
                .Build();

            PatternTestUtilities.TestNotes(pattern, new[]
            {
                new NoteInfo(NoteName.A, 0, MusicalTimeSpan.Half.SingleDotted(), MusicalTimeSpan.Quarter)
            });
        }

        [Test]
        public void StepBack_CustomStep()
        {
            var pattern = new PatternBuilder()
                .SetStep(MusicalTimeSpan.Sixteenth)
                .MoveToTime(MusicalTimeSpan.Whole)
                .StepBack()
                .Note(Notes.A0)
                .Build();

            PatternTestUtilities.TestNotes(pattern, new[]
            {
                new NoteInfo(NoteName.A, 0, 15 * MusicalTimeSpan.Sixteenth, MusicalTimeSpan.Quarter)
            });
        }

        #endregion

        #region StepBack

        [Test]
        public void StepForward()
        {
            var pattern = new PatternBuilder()
                .StepForward(new MetricTimeSpan(0, 0, 30))
                .Note(Notes.A0)
                .Build();

            PatternTestUtilities.TestNotes(pattern, new[]
            {
                new NoteInfo(NoteName.A, 0, new MetricTimeSpan(0, 0, 30), PatternBuilder.DefaultNoteLength)
            });
        }

        [Test]
        public void StepForward_DefaultStep()
        {
            var pattern = new PatternBuilder()
                .StepForward()
                .Note(Notes.A0)
                .Build();

            PatternTestUtilities.TestNotes(pattern, new[]
            {
                new NoteInfo(NoteName.A, 0, PatternBuilder.DefaultStep, PatternBuilder.DefaultNoteLength)
            });
        }

        [Test]
        public void StepForward_CustomStep()
        {
            var pattern = new PatternBuilder()
                .SetStep(MusicalTimeSpan.Sixteenth)
                .StepForward()
                .Note(Notes.A0)
                .Build();

            PatternTestUtilities.TestNotes(pattern, new[]
            {
                new NoteInfo(NoteName.A, 0, MusicalTimeSpan.Sixteenth, PatternBuilder.DefaultNoteLength)
            });
        }

        #endregion

        #region MoveToTime

        [Test]
        public void MoveToTime()
        {
            var pattern = new PatternBuilder()
                .MoveToTime(new MetricTimeSpan(1, 0, 0))
                .Note(Notes.A0)
                .Build();

            PatternTestUtilities.TestNotes(pattern, new[]
            {
                new NoteInfo(NoteName.A, 0, new MetricTimeSpan(1, 0, 0), PatternBuilder.DefaultNoteLength)
            });
        }

        #endregion

        #region MoveToPreviousTime

        [Test]
        public void MoveToPreviousTime()
        {
            var pattern = new PatternBuilder()
                .Note(Notes.A0)
                .MoveToPreviousTime()
                .Note(Notes.B0)
                .Build();

            PatternTestUtilities.TestNotes(pattern, new[]
            {
                new NoteInfo(NoteName.A, 0, null, PatternBuilder.DefaultNoteLength),
                new NoteInfo(NoteName.B, 0, null, PatternBuilder.DefaultNoteLength)
            });
        }

        [Test]
        public void MoveToPreviousTime_Pattern()
        {
            var subPattern = new PatternBuilder()
                .Note(Notes.A0)
                .Build();

            var pattern = new PatternBuilder()
                .Pattern(subPattern)
                .MoveToPreviousTime()
                .Note(Notes.B0)
                .Build();

            PatternTestUtilities.TestNotes(pattern, new[]
            {
                new NoteInfo(NoteName.A, 0, null, PatternBuilder.DefaultNoteLength),
                new NoteInfo(NoteName.B, 0, null, PatternBuilder.DefaultNoteLength)
            });
        }

        #endregion

        #endregion
    }
}


text:
function [input_zoh input_dt] = zero_order_hold(time_ct,input_ct,time_dt,sigma)
% function input_zoh = zero_order_hold(time_ct,input_ct,time_dt)
% implements zero order hold, converts continuous time input to a sampled and held input
% time_ct: "continous time" sample points
% time_dt: sample and hold sample points
% input_ct: input signal

%      output = 0;
%      for n = 1:length(input)
%          output = output + input(n).*rectangularPulse(fs.*time - 1/2 - n);
%      end
%      input_dt = interp1()
%      output_ct = resample_adc_as_sh(intput_dt, n, length(input_ct))';
    if nargin < 4
        sigma = 0;
    end
    % sample input ideally
    input_dt = interp1(time_ct,input_ct,time_dt); % FIX ME

    % add jitter
    jitter = normrnd(0,sigma,size(input_dt,1),size(input_dt,2));
    input_dt = input_dt + gradient(input_dt,mean(time_dt)) .* jitter;

    % reconstruct continuous time version
    length_ct = length(time_ct);
    j = 1;
    input_zoh = zeros(length_ct,1);
    for i = 1:length_ct
        % track input
        input_zoh(i) = input_dt(j);
        % track next input when clock period ends
        if j < length(input_dt) && time_ct(i) >= time_dt(j+1)
            j = j + 1;
        end
    end
    % this fixes an off by one error...
    input_zoh = [input_zoh(2:end); input_zoh(end)];
    input_zoh = input_zoh';
end


text:
package com.datatorrent.demos.wordcount;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.datatorrent.api.DefaultInputPort;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.common.util.BaseOperator;

// Computes word frequency counts per window and emits them at each endWindow. The output is a
// list of pairs (word, frequency).
//
public class WindowWordCount extends BaseOperator
{
  private static final Logger LOG = LoggerFactory.getLogger(WindowWordCount.class);

  // wordMap : word => frequency
  protected Map<String, WCPair> wordMap = new HashMap<>();

  public final transient DefaultInputPort<String> input = new DefaultInputPort<String>()
  {
    @Override
    public void process(String word)
    {
      WCPair pair = wordMap.get(word);
      if (null != pair) {    // word seen previously
        pair.freq += 1;
        return;
      }

      // new word
      pair = new WCPair();
      pair.word = word;
      pair.freq = 1;
      wordMap.put(word, pair);
    }
  };

  // output port which emits the list of word frequencies for current window
  // fileName => list of (word, freq) pairs
  //
  public final transient DefaultOutputPort<List<WCPair>> output = new DefaultOutputPort<>();

  @Override
  public void endWindow()
  {
    LOG.info("WindowWordCount: endWindow");

    // got EOF; if no words found, do nothing
    if (wordMap.isEmpty()) return;

    // have some words; emit single map and reset for next file
    final ArrayList<WCPair> list = new ArrayList<>(wordMap.values());
    output.emit(list);
    list.clear();
    wordMap.clear();
  }

}


text:
This is my personal go playground / notebook while learning the language

## Requirements

#### OSX

Install go through Homebrew with following command.

```
brew reinstall go --with-cc-all
```

For libgit support install libgit2 and go dependecy

```
brew install libgit2
go get github.com/libgit2/git2go
```


text:
require_relative '../../../lib/kvm'

KVM.load_conf

begin
    puts DomainList.info
rescue StandardError => e
    STDERR.puts e.message
    exit(-1)
end


text:
<?php
// add tag column to streamer_table

include '../header.php';

$sql = "alter table streamer_table add column enable SMALLINT default 1";
$manager->query($sql);

?>


text: static const char TY_(release_date)[] = "https://github.com/w3c/tidy-html5/tree/c63cc39";


text:
<?xml version="1.0"?>
<ruleset name="Aggregator rules"
         xmlns="http://pmd.sf.net/ruleset/1.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
         xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
    <rule ref="rulesets/cleancode.xml">
    </rule>
    <rule ref="rulesets/codesize.xml">
    </rule>
    <rule ref="rulesets/controversial.xml">
    </rule>
    <rule ref="rulesets/naming.xml">
        <exclude name="LongVariable" />
        <exclude name="ShortVariable" />
    </rule>
    <rule ref="rulesets/naming.xml/LongVariable">
        <properties>
            <property name="maximum" value="35" />
        </properties>
    </rule>
    <rule ref="rulesets/naming.xml/ShortVariable">
        <properties>
            <property name="minimum" value="1" />
        </properties>
    </rule>
    <rule ref="rulesets/controversial.xml">
    </rule>
    <rule ref="rulesets/design.xml">
        <exclude name="CouplingBetweenObjects" />
    </rule>
    <rule ref="rulesets/design.xml/CouplingBetweenObjects">
        <properties>
            <property name="minimum" value="9" />
        </properties>
    </rule>
</ruleset>


text:
namespace Microsoft.Azure.Management.SignalR.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Describes the properties of a resource type that has been onboarded to
    /// private link service
    /// </summary>
    public partial class ShareablePrivateLinkResourceProperties
    {
        /// <summary>
        /// Initializes a new instance of the
        /// ShareablePrivateLinkResourceProperties class.
        /// </summary>
        public ShareablePrivateLinkResourceProperties()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// ShareablePrivateLinkResourceProperties class.
        /// </summary>
        /// <param name="description">The description of the resource type that
        /// has been onboarded to private link service</param>
        /// <param name="groupId">The resource provider group id for the
        /// resource that has been onboarded to private link service</param>
        /// <param name="type">The resource provider type for the resource that
        /// has been onboarded to private link service</param>
        public ShareablePrivateLinkResourceProperties(string description = default(string), string groupId = default(string), string type = default(string))
        {
            Description = description;
            GroupId = groupId;
            Type = type;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the description of the resource type that has been
        /// onboarded to private link service
        /// </summary>
        [JsonProperty(PropertyName = "description")]
        public string Description { get; set; }

        /// <summary>
        /// Gets or sets the resource provider group id for the resource that
        /// has been onboarded to private link service
        /// </summary>
        [JsonProperty(PropertyName = "groupId")]
        public string GroupId { get; set; }

        /// <summary>
        /// Gets or sets the resource provider type for the resource that has
        /// been onboarded to private link service
        /// </summary>
        [JsonProperty(PropertyName = "type")]
        public string Type { get; set; }

    }
}


text:
var config = {};

// mongo uri
config.mongoURI = {
  development: "mongodb://localhost/node-stripe-charge",
  test: "mongodb://localhost/node-stripe-charge-test",
  production: process.env.MONGOLAB_URI
};

module.exports = config;


text:
class PrintTextBlock extends AbstractBlock {

    private interpreter: Interpreter;
    private robotModels: RobotModel[];
    private EXPECTED_NUMBER_OF_OUTBOUND_LINKS = 1;

    constructor(node: DiagramNode, outboundLinks: Link[], interpreter: Interpreter, robotModels: RobotModel[]) {
        super(node, outboundLinks);
        this.interpreter = interpreter;
        this.robotModels = robotModels;
    }

    public run(): void {
        var output = this.node.getName(); + "\n";
        this.checkExpectedNumberOfOutboundLinks(this.EXPECTED_NUMBER_OF_OUTBOUND_LINKS);

        var properties = this.node.getChangeableProperties();
        var parser = new Parser();
        var x = parser.parseExpression(properties["XCoordinateText"].value, this.interpreter);
        var y = parser.parseExpression(properties["YCoordinateText"].value, this.interpreter);

        var text = properties["PrintText"].value;

        for (var modelId = 0; modelId < this.robotModels.length; modelId++) {
            var model = this.robotModels[modelId];
            model.getDisplayWidget().drawText(x, y, text, this.interpreter.getEnvironmentVariable("painterColor"));
        }

        console.log(output);
    }

    public getNextNodeId(): string {
        return this.outboundLinks[0].getJointObject().get('target').id;
    }

}


text:
using System;
using System.Xml.Serialization;

namespace HoloXPLOR.Data.DataForge
{
    [XmlRoot(ElementName = "BTCompareNow")]
    public partial class BTCompareNow : BTNode
    {
        [XmlArray(ElementName = "Condition")]
        [XmlArrayItem(Type = typeof(BTInputString))]
        [XmlArrayItem(Type = typeof(BTInputStringValue))]
        [XmlArrayItem(Type = typeof(BTInputStringVar))]
        [XmlArrayItem(Type = typeof(BTInputStringBB))]
        public BTInputString[] Condition { get; set; }

    }
}


text:
#include "Driver.h"

#include "Buffer.h"
#include "SessionData.h"

DriverCounter::DriverCounter(DriverCounter *const next, const char *const name) : mNext(next), mName(name), mKey(getEventKey()), mEnabled(false) {
}

DriverCounter::~DriverCounter() {
	delete mName;
}

Driver *Driver::head = NULL;

Driver::Driver() : next(head) {
	head = this;
}

SimpleDriver::~SimpleDriver() {
	DriverCounter *counters = mCounters;
	while (counters != NULL) {
		DriverCounter *counter = counters;
		counters = counter->getNext();
		delete counter;
	}
}

DriverCounter *SimpleDriver::findCounter(const Counter &counter) const {
	for (DriverCounter *driverCounter = mCounters; driverCounter != NULL; driverCounter = driverCounter->getNext()) {
		if (strcmp(driverCounter->getName(), counter.getType()) == 0) {
			return driverCounter;
		}
	}

	return NULL;
}

bool SimpleDriver::claimCounter(const Counter &counter) const {
	return findCounter(counter) != NULL;
}

bool SimpleDriver::countersEnabled() const {
	for (DriverCounter *counter = mCounters; counter != NULL; counter = counter->getNext()) {
		if (counter->isEnabled()) {
			return true;
		}
	}
	return false;
}

void SimpleDriver::resetCounters() {
	for (DriverCounter *counter = mCounters; counter != NULL; counter = counter->getNext()) {
		counter->setEnabled(false);
	}
}

void SimpleDriver::setupCounter(Counter &counter) {
	DriverCounter *const driverCounter = findCounter(counter);
	if (driverCounter == NULL) {
		counter.setEnabled(false);
		return;
	}
	driverCounter->setEnabled(true);
	counter.setKey(driverCounter->getKey());
}

int SimpleDriver::writeCounters(mxml_node_t *root) const {
	int count = 0;
	for (DriverCounter *counter = mCounters; counter != NULL; counter = counter->getNext()) {
		mxml_node_t *node = mxmlNewElement(root, "counter");
		mxmlElementSetAttr(node, "name", counter->getName());
		++count;
	}

	return count;
}

PolledDriver::~PolledDriver() {
}

void PolledDriver::read(Buffer *const buffer) {
	for (DriverCounter *counter = getCounters(); counter != NULL; counter = counter->getNext()) {
		if (!counter->isEnabled()) {
			continue;
		}
		buffer->event64(counter->getKey(), counter->read());
	}
}


text:
<?php

class SiteController extends Controller {

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        if(!Yii::app()->user->isGuest){
            $this->redirect($this->createAbsoluteUrl('/list/'));
        }
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login()){
                $this->redirect($this->createAbsoluteUrl('/list/'));
            }
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

}


text:
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <utility>

#ifndef SRC_VARIABLES_SERVER_NAME_H_
#define SRC_VARIABLES_SERVER_NAME_H_

#include "src/variables/variable.h"

namespace modsecurity {

class Transaction;
namespace Variables {

class ServerName : public Variable {
 public:
    ServerName()
        : Variable("SERVER_NAME") { }

    void evaluate(Transaction *transaction,
        Rule *rule,
        std::vector<const collection::Variable *> *l) {
        transaction->m_variableServerName.evaluate(l);
    }
};

}  // namespace Variables
}  // namespace modsecurity

#endif  // SRC_VARIABLES_SERVER_NAME_H_


text:
require_relative "version_info"

module Gitlab
  class Upgrader
    def execute
      puts "GitLab #{current_version.major} upgrade tool"
      puts "Your version is #{current_version}"
      puts "Latest available version for GitLab #{current_version.major} is #{latest_version}"

      if latest_version?
        puts "You are using the latest GitLab version"
      else
        puts "Newer GitLab version is available"
        answer = if ARGV.first == "-y"
                   "yes"
                 else
                   prompt("Do you want to upgrade (yes/no)? ", %w{yes no})
                 end

        if answer == "yes"
          upgrade
        else
          exit 0
        end
      end
    end

    def latest_version?
      current_version >= latest_version
    end

    def current_version
      @current_version ||= Gitlab::VersionInfo.parse(current_version_raw)
    end

    def latest_version
      @latest_version ||= Gitlab::VersionInfo.parse(latest_version_raw)
    end

    def current_version_raw
      File.read(File.join(gitlab_path, "VERSION")).strip
    end

    def latest_version_raw
      git_tags = `git ls-remote --tags origin | grep tags\/v#{current_version.major}`
      git_tags = git_tags.lines.to_a.select { |version| version =~ /v\d\.\d\.\d\Z/ }
      last_tag = git_tags.last.match(/v\d\.\d\.\d/).to_s
    end

    def update_commands
      {
        "Stash changed files" => "git stash",
        "Get latest code" => "git fetch",
        "Switch to new version" => "git checkout v#{latest_version}",
        "Install gems" => "bundle",
        "Migrate DB" => "bundle exec rake db:migrate RAILS_ENV=production",
        "Recompile assets" => "bundle exec rake assets:clean assets:precompile RAILS_ENV=production",
        "Clear cache" => "bundle exec rake cache:clear RAILS_ENV=production"
      }
    end

    def upgrade
      update_commands.each do |title, cmd|
        puts title
        puts " -> #{cmd}"
        if system(cmd)
          puts " -> OK"
        else
          puts " -> FAILED"
          puts "Failed to upgrade. Try to repeat task or proceed with upgrade manually "
          exit 1
        end
      end

      puts "Done"
    end

    def gitlab_path
      File.expand_path(File.join(File.dirname(__FILE__), '../..'))
    end

    # Prompt the user to input something
    #
    # message - the message to display before input
    # choices - array of strings of acceptable answers or nil for any answer
    #
    # Returns the user's answer
    def prompt(message, choices = nil)
      begin
        print(message)
        answer = STDIN.gets.chomp
      end while !choices.include?(answer)
      answer
    end
  end
end


text:
class MockupsController < ApplicationController
  def week_plan
    @todo_list  = TodoList.last
  end
end


text:
/**
 * Created by soundit on 17/01/2017.
 */

interface Write<T> {
    create: (item:T, callback: (error: any, result: any) => void) => void;
    update: (item:T, callback: (error: any, result: any) => void) => void;
    delete: (item:T, callback: (error: any, result: any) => void) => void;
    deleteById: (id:number, callback: (error: any, result: any) => void) => void;

}

export = Write;


text:
package org.apache.drill.exec.planner.common;

import org.eigenbase.rel.RelNode;

public interface DrillRelNode extends RelNode {

}


text:
namespace DddFramework
{
    public interface IDomainEvent
    {
    }
}


text:
from __future__ import division
import os
import sys
import logging
import argparse
from argparse import RawDescriptionHelpFormatter
import matplotlib
import numpy as np
import pandas as pd
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
from matplotlib.backends.backend_pdf import PdfPages
from statsmodels.sandbox.regression.predstd import wls_prediction_std
from secimtools.dataManager import logger as sl
from secimtools.dataManager.flags import Flags
from secimtools.dataManager.interface import wideToDesign
from secimtools.visualManager import module_lines as lines
from secimtools.visualManager import module_scatter as scatter
from secimtools.visualManager.manager_color import colorHandler
from secimtools.visualManager.manager_figure import figureHandler

def getOptions():
    """ Function to pull in arguments """
    description = """ """
    parser = argparse.ArgumentParser(description=description,
                                    formatter_class=RawDescriptionHelpFormatter)
    # Standard Input
    standard = parser.add_argument_group(title="Standard input",
                        description="Standard input for SECIM tools.")
    standard.add_argument("-i","--input", dest="input", action="store",
                        required=True, help="Input dataset in wide format.")
    standard.add_argument("-d","--design", dest="design", action="store",
                        required=True, help="Design file.")
    standard.add_argument("-id","--ID", dest="uniqID", action="store", required=True,
                        help="Name of the column with unique identifiers.")
    standard.add_argument("-g","--group", dest="group", action="store", required=True,
                        help="Group/treatment identifier in design file [Optional].")
    standard.add_argument("-o","--order", dest="order", action="store", required=True,
                        help="Name of the column on design file that contains "\
                        "run order")
    standard.add_argument("-l","--levels",dest="levels",action="store",
                        required=False, default=False, help="Different groups to"\
                        " sort by separeted by commas.")
    # Tool Output
    output = parser.add_argument_group(title="Required Output")
    output.add_argument("-f","--fig", dest="figure", action="store",
                        required=True, help="Name of PDF to save scatter plots.")
    output.add_argument("-t","--table", dest="table", action="store",
                        required=True, help="Name of table for scatter plots")
    output.add_argument("-fl","--flags", dest="flags", action="store",
                        required=True, help="Name of table flags")
    # Dev Options
    dev = parser.add_argument_group(title="Development Settings")
    dev.add_argument("-dg","--debug", dest="debug", action="store_true",
                        required=False, help="Add debugging log output.")
    # Plot Options
    plot = parser.add_argument_group(title='Plot options')
    plot.add_argument("-pal","--palette",dest="palette",action='store',
                    required=False, default="tableau", help="Name of the "\
                    "palette to use.")
    plot.add_argument("-col","--color",dest="color",action="store",
                    required=False, default="Tableau_20", help="Name of a valid"\
                    " color scheme on the selected palette")
    args = parser.parse_args()
    # Standardize paths
    args.input  = os.path.abspath(args.input)
    args.table  = os.path.abspath(args.table)
    args.flags  = os.path.abspath(args.flags)
    args.figure = os.path.abspath(args.figure)
    args.design = os.path.abspath(args.design)
    if args.levels:
        args.levels = args.levels.split(",")
    return (args)

def runRegression(data):
    """
    Run each column through regression and then concatenate the outputed series
    to a single dataframe.

    :Arguments:
        :type data: pandas.dataFrame
        :param data: A Pandas dataFrame with a transpose version of the original
                    data and runOrder as index.

    :Returns:
        :rtype res_df: pandas.dataFrame
        :return res_df: Results of the regression.
    """
    res = list()
    for colName in data.columns:
        column = data[colName]
        # Drop missing values and make sure everything is numeric
        clean = column.dropna().reset_index()
        clean.columns = ["run", "val"]
        try:
            clean["run"] = clean["run"].astype('float64')
        except ValueError as e:
            logger.error("Invalid runOrder value found: - {}".format(str(e)))
            sys.exit(1)

        # Fit model
        model   = smf.ols(formula="val ~ run", data=clean, missing="drop")
        results = model.fit()
        slope   = results.params["run"]
        pval    = results.pvalues["run"]
        rsq     = results.rsquared
        fitted  = results.fittedvalues

        #Returning
        out =  pd.Series(name=column.name,
                data={"name":column.name,
                "x":clean["run"],
                "y":clean["val"],
                "res":results,
                "slope":slope,
                "pval":pval,
                "rsq":rsq,
                "fitted":fitted})
        res.append(out)

    # Concatenating results
    res_df = pd.concat(res,axis=1)
    res_df = res_df.T

    # Drop rows that are missing regression results
    res_df.dropna(inplace=True)

    # Returning results of regressions
    return (res_df)

def plotSignificantROR(data, pdf, palette):
    """
    Plot a scatter plot of x vs y.

    :Arguments:

        :type row:
        :param row:

        :type pdf: PdfPages
        :param pdf: pdf object to store scatterplots

        :type des: pandas DataFrame
        :param des: design file

        :type groupName: string
        :param groupName: name of group
    """
    # Iterates over all rows in the dataframe
    # Make scatter plot if p-pvalue is less than 0.05
    for index,row in data.iterrows():
        if row["pval"] > 0.05: continue
        #plotSignificantROR(row,pdf,dat.design,args.group)

        # Get 95% CI
        prstd, lower, upper = wls_prediction_std(row["res"])

        # Sort CIs for Plotting
        toPlot = pd.DataFrame({"x": row["x"], "lower": lower, "upper": upper})
        toPlot.sort_values(by="x", inplace=True)

        # Create plot
        fh = figureHandler(proj="2d", figsize=(14,8))

        #Plot scatterplot
        scatter.scatter2D(ax=fh.ax[0],x=row["x"],  y=row["y"],colorList=palette.list_colors)

        # Plot cutoffs
        lines.drawCutoff(ax=fh.ax[0],x=row["x"],   y=row["fitted"],  c="c")
        lines.drawCutoff(ax=fh.ax[0],x=toPlot["x"],y=toPlot["lower"],c="r")
        lines.drawCutoff(ax=fh.ax[0],x=toPlot["x"],y=toPlot["upper"],c="r")

        # Formatting
        ymin, ymax = fh.ax[0].get_ylim()
        fh.formatAxis(xTitle="Run Order", yTitle="Value", ylim=(ymin,ymax*1.2),
        figTitle=u"{} Scatter plot (fitted regression line and prediction bands"\
        " included)".format(row["name"]))

        # Shrink figure
        fh.shrink()

        # Add legend to figure
        fh.makeLegend(ax=fh.ax[0], ucGroups=palette.ugColors, group=palette.combName)

        #Add text to the ax
        fh.ax[0].text(.7, .85, u"Slope= {0:.4f}\n(p-value = {1:.4f})\n"\
            "$R^2$ = {2:4f}".format(round(row["slope"],4), round(row["pval"],4),
            round(row["rsq"],4)),transform=fh.ax[0].transAxes, fontsize=12)

        # Save to PDF
        fh.addToPdf(pdf)

def main(args):
    """Perform run order regression analysis"""

    if args.levels and args.group:
        levels = [args.group]+args.levels
    elif args.group and not args.levels:
        levels = [args.group]
    else:
        levels = []

    logger.info("Loading data with the Interface")
    dat = wideToDesign(args.input, args.design, args.uniqID, args.group,
                        runOrder=args.order, anno=args.levels, logger=logger)

    # Remove samples with missing data
    dat.dropMissing()
    # Get remaining Sample IDs for dataframe filtering
    sample_ids = dat.wide.index.tolist()
    # Set color palette and get colors
    palette = colorHandler(pal=args.palette, col=args.color)
    logger.info(u"Using {0} color scheme from {1} palette".format(args.color, args.palette))
    palette.getColors(dat.design,levels)

    # Transpose Data so compounds are columns, set the runOrder as index
    # and drop the colum with the groups from the tranposed wide.
    trans = dat.transpose()
    trans.set_index(dat.runOrder, inplace=True)
    trans.drop(dat.group, axis=1, inplace=True)
    trans = trans.loc[:,sample_ids]
    # Run regressions
    logger.info("Running Regressions")
    ror_df = runRegression(trans)

    # Creating flags flags for pvals 0.05 and 0.1
    ror_flags = Flags(index=ror_df.index)
    ror_flags.addColumn(column="flag_feature_runOrder_pval_05",
                        mask=(ror_df["pval"]<=0.05))
    ror_flags.addColumn(column="flag_feature_runOrder_pval_01",
                        mask=(ror_df["pval"]<=0.01))

    # Plot Results
    # Open a multiple page PDF for plots
    logger.info("Plotting Results")
    with PdfPages(args.figure) as pdf:
        plotSignificantROR(ror_df, pdf, palette)

        # If not pages
        if pdf.get_pagecount() == 0:
            fig = plt.figure()
            fig.text(0.5, 0.4, "There were no features significant for plotting.", fontsize=12)
            pdf.savefig(fig)

    # Write  results and flasg to TSV files
    ror_df.to_csv(args.table, sep="\t", float_format="%.4f", index_label=args.uniqID,
                columns=["pval","rsq","slope"])
    ror_flags.df_flags.to_csv(args.flags, sep="\t", index_label=args.uniqID)

if __name__ == "__main__":
    """Run if executed on the command line"""
    args = getOptions()
    logger = logging.getLogger()
    if args.debug:
        sl.setLogger(logger, logLevel="debug")
        DEBUG = True
    else:
        sl.setLogger(logger)
    # Print logger info
    logger.info(u"""Importing data with following parameters:
            \tWide: {0}
            \tDesign: {1}
            \tUnique ID: {2}
            \tGroup: {3}
            \tRun Order: {4}
            \tLevels: {5}
            """ .format(args.input, args.design, args.uniqID, args.group,
                args.order,args.levels))

    main(args)


text:
package remote

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gogo/protobuf/proto"
	"github.com/golang/snappy"
	"github.com/opentracing/opentracing-go"
	"github.com/pkg/errors"
	"github.com/prometheus/client_golang/prometheus"
	config_util "github.com/prometheus/common/config"
	"github.com/prometheus/common/model"
	"github.com/prometheus/common/version"

	"github.com/opentracing-contrib/go-stdlib/nethttp"
	"github.com/prometheus/prometheus/prompb"
)

const maxErrMsgLen = 256

var userAgent = fmt.Sprintf("Prometheus/%s", version.Version)

var (
	remoteReadQueriesTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "read_queries_total",
			Help:      "The total number of remote read queries.",
		},
		[]string{remoteName, endpoint, "code"},
	)
	remoteReadQueries = prometheus.NewGaugeVec(
		prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "remote_read_queries",
			Help:      "The number of in-flight remote read queries.",
		},
		[]string{remoteName, endpoint},
	)
	remoteReadQueryDuration = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Namespace: namespace,
			Subsystem: subsystem,
			Name:      "read_request_duration_seconds",
			Help:      "Histogram of the latency for remote read requests.",
			Buckets:   append(prometheus.DefBuckets, 25, 60),
		},
		[]string{remoteName, endpoint},
	)
)

func init() {
	prometheus.MustRegister(remoteReadQueriesTotal, remoteReadQueries, remoteReadQueryDuration)
}

// Client allows reading and writing from/to a remote HTTP endpoint.
type Client struct {
	remoteName string // Used to differentiate clients in metrics.
	url        *config_util.URL
	Client     *http.Client
	timeout    time.Duration

	readQueries         prometheus.Gauge
	readQueriesTotal    *prometheus.CounterVec
	readQueriesDuration prometheus.Observer
}

// ClientConfig configures a client.
type ClientConfig struct {
	URL              *config_util.URL
	Timeout          model.Duration
	HTTPClientConfig config_util.HTTPClientConfig
}

// ReadClient uses the SAMPLES method of remote read to read series samples from remote server.
// TODO(bwplotka): Add streamed chunked remote read method as well (https://github.com/prometheus/prometheus/issues/5926).
type ReadClient interface {
	Read(ctx context.Context, query *prompb.Query) (*prompb.QueryResult, error)
}

// newReadClient creates a new client for remote read.
func newReadClient(name string, conf *ClientConfig) (ReadClient, error) {
	httpClient, err := config_util.NewClientFromConfig(conf.HTTPClientConfig, "remote_storage_read_client", false, false)
	if err != nil {
		return nil, err
	}

	return &Client{
		remoteName:          name,
		url:                 conf.URL,
		Client:              httpClient,
		timeout:             time.Duration(conf.Timeout),
		readQueries:         remoteReadQueries.WithLabelValues(name, conf.URL.String()),
		readQueriesTotal:    remoteReadQueriesTotal.MustCurryWith(prometheus.Labels{remoteName: name, endpoint: conf.URL.String()}),
		readQueriesDuration: remoteReadQueryDuration.WithLabelValues(name, conf.URL.String()),
	}, nil
}

// NewWriteClient creates a new client for remote write.
func NewWriteClient(name string, conf *ClientConfig) (WriteClient, error) {
	httpClient, err := config_util.NewClientFromConfig(conf.HTTPClientConfig, "remote_storage_write_client", false, false)
	if err != nil {
		return nil, err
	}

	t := httpClient.Transport
	httpClient.Transport = &nethttp.Transport{
		RoundTripper: t,
	}

	return &Client{
		remoteName: name,
		url:        conf.URL,
		Client:     httpClient,
		timeout:    time.Duration(conf.Timeout),
	}, nil
}

type RecoverableError struct {
	error
}

// Store sends a batch of samples to the HTTP endpoint, the request is the proto marshalled
// and encoded bytes from codec.go.
func (c *Client) Store(ctx context.Context, req []byte) error {
	httpReq, err := http.NewRequest("POST", c.url.String(), bytes.NewReader(req))
	if err != nil {
		// Errors from NewRequest are from unparsable URLs, so are not
		// recoverable.
		return err
	}
	httpReq.Header.Add("Content-Encoding", "snappy")
	httpReq.Header.Set("Content-Type", "application/x-protobuf")
	httpReq.Header.Set("User-Agent", userAgent)
	httpReq.Header.Set("X-Prometheus-Remote-Write-Version", "0.1.0")
	ctx, cancel := context.WithTimeout(ctx, c.timeout)
	defer cancel()

	httpReq = httpReq.WithContext(ctx)

	if parentSpan := opentracing.SpanFromContext(ctx); parentSpan != nil {
		var ht *nethttp.Tracer
		httpReq, ht = nethttp.TraceRequest(
			parentSpan.Tracer(),
			httpReq,
			nethttp.OperationName("Remote Store"),
			nethttp.ClientTrace(false),
		)
		defer ht.Finish()
	}

	httpResp, err := c.Client.Do(httpReq)
	if err != nil {
		// Errors from Client.Do are from (for example) network errors, so are
		// recoverable.
		return RecoverableError{err}
	}
	defer func() {
		io.Copy(ioutil.Discard, httpResp.Body)
		httpResp.Body.Close()
	}()

	if httpResp.StatusCode/100 != 2 {
		scanner := bufio.NewScanner(io.LimitReader(httpResp.Body, maxErrMsgLen))
		line := ""
		if scanner.Scan() {
			line = scanner.Text()
		}
		err = errors.Errorf("server returned HTTP status %s: %s", httpResp.Status, line)
	}
	if httpResp.StatusCode/100 == 5 {
		return RecoverableError{err}
	}
	return err
}

// Name uniquely identifies the client.
func (c Client) Name() string {
	return c.remoteName
}

// Endpoint is the remote read or write endpoint.
func (c Client) Endpoint() string {
	return c.url.String()
}

// Read reads from a remote endpoint.
func (c *Client) Read(ctx context.Context, query *prompb.Query) (*prompb.QueryResult, error) {
	c.readQueries.Inc()
	defer c.readQueries.Dec()

	req := &prompb.ReadRequest{
		// TODO: Support batching multiple queries into one read request,
		// as the protobuf interface allows for it.
		Queries: []*prompb.Query{
			query,
		},
	}
	data, err := proto.Marshal(req)
	if err != nil {
		return nil, errors.Wrapf(err, "unable to marshal read request")
	}

	compressed := snappy.Encode(nil, data)
	httpReq, err := http.NewRequest("POST", c.url.String(), bytes.NewReader(compressed))
	if err != nil {
		return nil, errors.Wrap(err, "unable to create request")
	}
	httpReq.Header.Add("Content-Encoding", "snappy")
	httpReq.Header.Add("Accept-Encoding", "snappy")
	httpReq.Header.Set("Content-Type", "application/x-protobuf")
	httpReq.Header.Set("User-Agent", userAgent)
	httpReq.Header.Set("X-Prometheus-Remote-Read-Version", "0.1.0")

	ctx, cancel := context.WithTimeout(ctx, c.timeout)
	defer cancel()

	httpReq = httpReq.WithContext(ctx)

	if parentSpan := opentracing.SpanFromContext(ctx); parentSpan != nil {
		var ht *nethttp.Tracer
		httpReq, ht = nethttp.TraceRequest(
			parentSpan.Tracer(),
			httpReq,
			nethttp.OperationName("Remote Read"),
			nethttp.ClientTrace(false),
		)
		defer ht.Finish()
	}

	start := time.Now()
	httpResp, err := c.Client.Do(httpReq)
	if err != nil {
		return nil, errors.Wrap(err, "error sending request")
	}
	defer func() {
		io.Copy(ioutil.Discard, httpResp.Body)
		httpResp.Body.Close()
	}()
	c.readQueriesDuration.Observe(time.Since(start).Seconds())
	c.readQueriesTotal.WithLabelValues(strconv.Itoa(httpResp.StatusCode)).Inc()

	compressed, err = ioutil.ReadAll(httpResp.Body)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("error reading response. HTTP status code: %s", httpResp.Status))
	}

	if httpResp.StatusCode/100 != 2 {
		return nil, errors.Errorf("remote server %s returned HTTP status %s: %s", c.url.String(), httpResp.Status, strings.TrimSpace(string(compressed)))
	}

	uncompressed, err := snappy.Decode(nil, compressed)
	if err != nil {
		return nil, errors.Wrap(err, "error reading response")
	}

	var resp prompb.ReadResponse
	err = proto.Unmarshal(uncompressed, &resp)
	if err != nil {
		return nil, errors.Wrap(err, "unable to unmarshal response body")
	}

	if len(resp.Results) != len(req.Queries) {
		return nil, errors.Errorf("responses: want %d, got %d", len(req.Queries), len(resp.Results))
	}

	return resp.Results[0], nil
}


text:
import java.util.Scanner;

public class Circle3 {
    public static void main(String[] args) {

     Scanner scan = new Scanner(System.in);
     final double PI = 3.14159;

     System.out.println("Please enter a value for the radius...");
     int radius1 = scan.nextInt();
     double area1 = PI * radius1 * radius1;
     double circumference1 = 2 * (PI * radius1);

     System.out.println("The area of a circle with radius " + radius1 +
                        " is " + area1);
     System.out.println("The circumference of a circle with radius " +
                        radius1 + " is " + circumference1);

     int radius2 = radius1 * 2;
     double area2 = PI * radius2 * radius2;
     double circumference2 = 2 * (PI * radius2);

     System.out.println("The area of a circle with radius " + radius2 +
                        " is " + area2);
     System.out.println("The circumference of a circle with radius " +
                        radius2 + " is " + circumference2);

     double growthFactor = area2 / area1;

     System.out.println("The factor in which the area grew between the " +
                        "first and second area is " + growthFactor);

    }
}


text:
No more modification on this version !
==========
I'm currently developping a new version of tokenize, it can be found here https://github.com/zellerda/Tokenize2

Tokenize
==========

jQuery Tokenize is a plugin which allows your users to select multiple items from a predefined list or ajax, using autocompletion as they type to find each item. You may have seen a similar type of text entry when filling in the recipients field sending messages on facebook or tags on tumblr.

 - Intuitive UI for selecting multiple items from a large list
 - Easy to skin / style purely in css, no images required
 - Supports any backend which can generate JSON, including PHP, Rails, Django, ASP.net
 - Callbacks when items are added or removed from the list
 - Select, delete and navigate items using the mouse or keyboard
 - Sortable items
 - Support jQuery 1.11+ and jQuery 2+

Documentation and Demo : [https://www.zellerda.com/projects/jquery/tokenize](https://www.zellerda.com/projects/jquery/tokenize)

Changelog
---------
jQuery Tokenize 2.6
 - [Issue #69] Add onDropdownShow event
 - [Issue #80] Fix jQuery 2.1.4 ajax issue when using hash in search input
 - [Issue #81] Add onDuplicateToken option
 - [Issue #82] Adding trim on adding tokens
 - [Issue #84] Adding the possibility to set multiples delimiters

jQuery Tokenize 2.5.2 - 24 October 2015
 - [Issue #57] Add bower package definition
 - [Issue #64] Add ajax error handler in option
 - [Issue #66] Add searchMinLength parameter
 - Fix potential XSS issue on adding tokens

jQuery Tokenize 2.5.1 - 11 August 2015
 - [Issue #59] Fix sortable call when sortable option is false

jQuery Tokenize 2.5 - 11 August 2015
 - [Issue #53][Issue #54] Fix Firefox behavior with selected attribute
 - Fix re-ordering of element when deleted
 - Fix some return values toArray() method
 - Change some return types for api method
 - Add new api access (more easy)

jQuery Tokenize 2.4.3 - 22 July 2015
 - Fix remap function

jQuery Tokenize 2.4.2 - 22 July 2015
 - [Issue #37] Add Focused class on Tokenize:focus
 - [Issue #43] Fix delimiter for non-english keyboard layouts
 - [Issue #44] Remove disabled element from search
 - [Issue #48] Add resize option for TokensContainer block
 - [Issue #52] Add remap function
 - [Issue #53] Small changes in attribute set
 - Remove selection on TokensContainer
 - Add delimiter option
 - Return the object for each api method
 - Fix initialization of tokenize when calling twice
 - Fix missing bottom padding

jQuery Tokenize 2.4.1 - 1 June 2015
 - [Issue #36] Fix jquery exception when enter doubles quotes
 - [Issue #35] Fix debounce function

jQuery Tokenize 2.4 - 18 May 2015
 - Add sortable option (experimental)
 - [Issue #31] Add new event when an element is added to dropdown

jQuery Tokenize 2.3.2 - 28 April 2015
 - Fix clear method

jQuery Tokenize 2.3.1 - 24 April 2015
 - [Issue #22] Add debounce options for Ajax queries
 - [Issue #21] Add current tokenize object for all callback function with e parameter

jQuery Tokenize 2.3 - 09 February 2015
 - [Issue #15] Add enable and disable method for api

jQuery Tokenize 2.2.2 - 29 December 2014
 - [Issue #14] Fix adding tokens from Ajax when newElements is false
 - [Issue #13] Add clear method
 - Change search input background color to transparent
 - Add placeholder and displayDropdownOnFocus options
 - Remove maxlength option to the input if searchMaxLength is 0

jQuery Tokenize 2.2.1 - 21 October 2014
 - [Issue #3] Fix whitespace in code

jQuery Tokenize 2.2 - 21 October 2014
 - [Issue #1] Fix maxElements configuration was enforced across all objects in document
 - [Issue #2] Fix the display of "x" for non UTF-8 websites

jQuery Tokenize 2.1 - 7 August 2014
 - Fix loading of multiple dom elements
 - Add JSONP support
 - Add options to personalize fields
 - Add loop when move in drop down
 - Remove validator option

jQuery Tokenize 2.0 - 7 October 2013
 - Add callbacks
 - Add maxElements option
 - Fix missing add token on click when only one element
 - Fix box width - Use css instead
 - Fix add default token execute onAddToken

jQuery Tokenize 1.0 - 26 February 2013
 - Fix backspace key to close the drop down
 - Fix dropdown background
 - Fix drop down item height when is less than options.size
 - Fix click event out off the control
 - Fix click on input when the last pending delete is deleted

jQuery Tokenize beta-0.1 - 3 April 2012
 - First version


text:
Given 'I am on $page_name' do |page_name|
  visit path_to page_name
end

When 'I click "$target"' do |target|
  click_link_or_button target
end

When /^I fill in the following( for the last line item)?:$/ do |last, table|
  scope = last ? '.line_item:last-of-type' : 'html'
  within scope do
    table.rows_hash.each do |field, value|
      begin
        fill_in field, with: value
      rescue Capybara::ElementNotFound
        select value, from: field
      end
    end
  end
end

When 'I go to $page_name' do |page_name|
  visit path_to page_name
end

Then 'I should be on $page_name' do |page_name|
  expect(page.current_path).to be == path_to(page_name)
end

Then 'I should see "$text"' do |text|
  expect(page).to have_text text
end

Then 'I should see the following form fields:' do |table|
  table.rows_hash.each do |field, value|
    begin
      expect(page).to have_field field, with: value
    rescue RSpec::Expectations::ExpectationNotMetError
      expect(page).to have_select field, selected: value
    end
  end
end


text:
import R from 'ramda';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Button from 'material-ui/Button';
import { TableCell } from 'material-ui/Table';
import { withRouter } from 'react-router';
import Typography from 'material-ui/Typography';
import AlertDialog from '../../common/alertDialog';
import CustomGridColumn from '../../common/grid/customGridColumn';
import VerificationFilter from './verificationFilter';
import PaginatedList from '../../common/list/paginatedList';
import TableWithStateInUrl from '../../common/hoc/tableWithStateInUrl';
import { getVerificationReport } from '../../../reducers/partnerReportsGeneration';
import { loadVerificationReportsList } from '../../../reducers/reportsVerificationList';
import { isQueryChanged } from '../../../helpers/apiHelper';
import PartnerNameCell from './partnerNameCell';
import Loader from '../../common/loader';
import { checkPermission, AGENCY_PERMISSIONS } from '../../../helpers/permissions';

const messages = {
  exportReport: 'Export report',
  report: 'Report download',
};

class VerificationContainer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showDownloadInfo: false,
      downloadInfo: null,
    };
  }

  componentWillMount() {
    const { query } = this.props;
    this.props.loadReports(query);
  }

  shouldComponentUpdate(nextProps) {
    const { query } = this.props;

    if (isQueryChanged(nextProps, query)) {
      this.props.loadReports(nextProps.location.query);
      return false;
    }

    return true;
  }

  /* eslint-disable class-methods-use-this */
  tableCell({ row, column, value }) {
    if (column.name === 'legal_name') {
      return (<PartnerNameCell
        isVerified={row.is_verified}
        flagInfo={row.flagging_status}
        legalName={row.legal_name}
      />);
    }

    return <TableCell><Typography>{value}</Typography></TableCell>;
  }

  verificationReport() {
    const { query, getVerificationReports } = this.props;

    const queryPage = R.dissoc('page', query);
    const queryPageSize = R.dissoc('page_size', queryPage);

    getVerificationReports(queryPageSize).then((data) => {
      this.setState({
        showDownloadInfo: true,
        downloadInfo: data.length > 0 && data[0],
      });
    });
  }

  render() {
    const { items, columns, totalCount, loading, query,
      reportsLoading, hasVerificationReportPermission } = this.props;

    const queryParams = R.omit(['page', 'page_size'], query);

    return (
      <React.Fragment>
        <Loader fullscreen loading={reportsLoading || loading} />
        <CustomGridColumn>
          <VerificationFilter />
          {!R.isEmpty(queryParams)
            && hasVerificationReportPermission
             && <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
               <Button
                 style={{ marginRight: '15px' }}
                 raised
                 color="accent"
                 onTouchTap={() => this.verificationReport()}
               >
                 {messages.exportReport}
               </Button>
             </div>}
          {!R.isEmpty(queryParams) && <TableWithStateInUrl
            component={PaginatedList}
            items={items}
            columns={columns}
            itemsCount={totalCount}
            loading={loading}
            templateCell={this.tableCell}
          />}
        </CustomGridColumn>
        <AlertDialog
          trigger={!!this.state.showDownloadInfo}
          title={messages.report}
          text={this.state.downloadInfo}
          handleDialogClose={() => this.setState({ showDownloadInfo: false })}
        />
      </React.Fragment>
    );
  }
}

VerificationContainer.propTypes = {
  items: PropTypes.array.isRequired,
  columns: PropTypes.array.isRequired,
  totalCount: PropTypes.number.isRequired,
  loadReports: PropTypes.func.isRequired,
  loading: PropTypes.bool.isRequired,
  getVerificationReports: PropTypes.func,
  query: PropTypes.object,
  reportsLoading: PropTypes.bool.isRequired,
  hasVerificationReportPermission: PropTypes.bool.isRequired,
};

const mapStateToProps = (state, ownProps) => ({
  items: state.reportVerificationList.items,
  totalCount: state.reportVerificationList.totalCount,
  columns: state.reportVerificationList.columns,
  loading: state.reportVerificationList.loading,
  query: ownProps.location.query,
  reportsLoading: state.generatePartnerReports.loading,
  hasVerificationReportPermission:
    checkPermission(AGENCY_PERMISSIONS.RUN_REPORT_CFEI_MANAGEMENT, state),
});

const mapDispatch = dispatch => ({
  loadReports: params => dispatch(loadVerificationReportsList(params)),
  getVerificationReports: params => dispatch(getVerificationReport(params)),
});

const connectedVerificationContainer =
    connect(mapStateToProps, mapDispatch)(VerificationContainer);
export default withRouter(connectedVerificationContainer);


text:
typedef int32 v810_timestamp_t;

#define V810_FAST_MAP_SHIFT	16
#define V810_FAST_MAP_PSIZE     (1 << V810_FAST_MAP_SHIFT)
#define V810_FAST_MAP_TRAMPOLINE_SIZE	1024

// Exception codes
enum
{
 ECODE_TRAP_BASE =	0xFFA0,
 ECODE_INVALID_OP = 	0xFF90,
 ECODE_ZERO_DIV =	0xFF80, // Integer divide by 0
 ECODE_FIV =		0xFF70, // Floating point invalid operation
 ECODE_FZD =		0xFF68, // Floating point zero division
 ECODE_FOV = 		0xFF64, // Floating point overflow
//#define ECODE_FUD	0xFF62 // Floating point underflow(unused on V810)
//#define ECODE_FPR	0xFF61 // Floating point precision degradation(unused on V810)
 ECODE_FRO = 		0xFF60 // Floating point reserved operand
};

enum
{
 INVALID_OP_HANDLER_ADDR = 0xFFFFFF90, // Invalid opcode/instruction code!
 ZERO_DIV_HANDLER_ADDR = 0xFFFFFF80, // Integer divide by 0 exception
 FPU_HANDLER_ADDR = 0xFFFFFF60, // FPU exception
 TRAP_HANDLER_BASE = 0xFFFFFFA0 // TRAP instruction
};

//System Register Defines (these are the only valid system registers!)
#define EIPC     0       //Exeption/Interupt PC
#define EIPSW    1       //Exeption/Interupt PSW

#define FEPC     2       //Fatal Error PC
#define FEPSW    3       //Fatal Error PSW

#define ECR      4       //Exception Cause Register
#define PSW      5       //Program Status Word
#define PIR      6       //Processor ID Register
#define TKCW     7       //Task Controll Word
#define CHCW     24      //Cashe Controll Word
#define ADDTRE   25      //ADDTRE

//PSW Specifics
#define PSW_IA  0xF0000 // All Interupt bits...
#define PSW_I3  0x80000
#define PSW_I2  0x40000
#define PSW_I1  0x20000
#define PSW_I0  0x10000

#define PSW_NP  0x08000
#define PSW_EP  0x04000

#define PSW_AE	0x02000

#define PSW_ID  0x01000

#define PSW_FRO 0x00200 // Floating point reserved operand(set on denormal, NaN, or indefinite)
#define PSW_FIV 0x00100 // Floating point invalid operation(set when trying to convert a number too large to an (un)signed integer)

#define PSW_FZD 0x00080 // Floating point divide by zero
#define PSW_FOV 0x00040 // Floating point overflow
#define PSW_FUD 0x00020 // Floating point underflow
#define PSW_FPR	0x00010 // Floating point precision degradation

#define PSW_CY  0x00008
#define PSW_OV  0x00004
#define PSW_S   0x00002
#define PSW_Z   0x00001

//condition codes
#define COND_V  0
#define COND_C  1
#define COND_Z  2
#define COND_NH 3
#define COND_S  4
#define COND_T  5
#define COND_LT 6
#define COND_LE 7
#define COND_NV 8
#define COND_NC 9
#define COND_NZ 10
#define COND_H  11
#define COND_NS 12
#define COND_F  13
#define COND_GE 14
#define COND_GT 15

#define TESTCOND_V                      (S_REG[PSW]&PSW_OV)

#define TESTCOND_L                      (S_REG[PSW]&PSW_CY)
#define TESTCOND_C	TESTCOND_L

#define TESTCOND_E                      (S_REG[PSW]&PSW_Z)
#define TESTCOND_Z	TESTCOND_E

#define TESTCOND_NH             ( (S_REG[PSW]&PSW_Z) || (S_REG[PSW]&PSW_CY) )
#define TESTCOND_N                      (S_REG[PSW]&PSW_S)
#define TESTCOND_S	TESTCOND_N

#define TESTCOND_LT             ( (!!(S_REG[PSW]&PSW_S)) ^ (!!(S_REG[PSW]&PSW_OV)) )
#define TESTCOND_LE             ( ((!!(S_REG[PSW]&PSW_S)) ^ (!!(S_REG[PSW]&PSW_OV))) || (S_REG[PSW]&PSW_Z) )
#define TESTCOND_NV             (!(S_REG[PSW]&PSW_OV))

#define TESTCOND_NL             (!(S_REG[PSW]&PSW_CY))
#define TESTCOND_NC	TESTCOND_NL

#define TESTCOND_NE             (!(S_REG[PSW]&PSW_Z))
#define TESTCOND_NZ	TESTCOND_NE

#define TESTCOND_H                      ( !((S_REG[PSW]&PSW_Z) || (S_REG[PSW]&PSW_CY)) )
#define TESTCOND_P                      (!(S_REG[PSW] & PSW_S))
#define TESTCOND_NS	TESTCOND_P

#define TESTCOND_GE             (!((!!(S_REG[PSW]&PSW_S))^(!!(S_REG[PSW]&PSW_OV))))
#define TESTCOND_GT             (! (((!!(S_REG[PSW]&PSW_S))^(!!(S_REG[PSW]&PSW_OV))) || (S_REG[PSW]&PSW_Z)) )

// Tag layout
//  Bit 0-21: TAG31-TAG10
//  Bit 22-23: Validity bits(one for each 4-byte subblock)
//  Bit 24-27: NECRV("Reserved")
//  Bit 28-31: 0

typedef enum
{
 V810_EMU_MODE_FAST = 0,
 V810_EMU_MODE_ACCURATE = 1,
 _V810_EMU_MODE_COUNT
} V810_Emu_Mode;

class V810
{
 public:

 V810() MDFN_COLD;
 ~V810() MDFN_COLD;

 // Pass TRUE for vb_mode if we're emulating a VB-specific enhanced V810 CPU core
 bool Init(V810_Emu_Mode mode, bool vb_mode) MDFN_COLD;
 void Kill(void) MDFN_COLD;

 void SetInt(int level);

 void SetMemWriteBus32(uint8 A, bool value) MDFN_COLD;
 void SetMemReadBus32(uint8 A, bool value) MDFN_COLD;

 void SetMemReadHandlers(uint8 MDFN_FASTCALL (*read8)(v810_timestamp_t &, uint32), uint16 MDFN_FASTCALL (*read16)(v810_timestamp_t &, uint32), uint32 MDFN_FASTCALL (*read32)(v810_timestamp_t &, uint32)) MDFN_COLD;
 void SetMemWriteHandlers(void MDFN_FASTCALL (*write8)(v810_timestamp_t &, uint32, uint8), void MDFN_FASTCALL (*write16)(v810_timestamp_t &, uint32, uint16), void MDFN_FASTCALL (*write32)(v810_timestamp_t &, uint32, uint32)) MDFN_COLD;

 void SetIOReadHandlers(uint8 MDFN_FASTCALL (*read8)(v810_timestamp_t &, uint32), uint16 MDFN_FASTCALL (*read16)(v810_timestamp_t &, uint32), uint32 MDFN_FASTCALL (*read32)(v810_timestamp_t &, uint32)) MDFN_COLD;
 void SetIOWriteHandlers(void MDFN_FASTCALL (*write8)(v810_timestamp_t &, uint32, uint8), void MDFN_FASTCALL (*write16)(v810_timestamp_t &, uint32, uint16), void MDFN_FASTCALL (*write32)(v810_timestamp_t &, uint32, uint32)) MDFN_COLD;

 // Length specifies the number of bytes to map in, at each location specified by addresses[] (for mirroring)
 uint8 *SetFastMap(uint32 addresses[], uint32 length, unsigned int num_addresses, const char *name, bool writable) MDFN_COLD;

 INLINE void ResetTS(v810_timestamp_t new_base_timestamp)
 {
  assert(next_event_ts > v810_timestamp);

  next_event_ts -= (v810_timestamp - new_base_timestamp);
  v810_timestamp = new_base_timestamp;
 }

 INLINE void SetEventNT(const v810_timestamp_t timestamp)
 {
  next_event_ts = timestamp;
 }

 INLINE v810_timestamp_t GetEventNT(void)
 {
  return(next_event_ts);
 }

 v810_timestamp_t Run(int32 MDFN_FASTCALL (*event_handler)(const v810_timestamp_t timestamp));
 void Exit(void);

 void Reset(void) MDFN_COLD;

 #ifdef WANT_DEBUGGER
 void CheckBreakpoints(void (*callback)(int type, uint32 address, uint32 value, unsigned int len), uint16 MDFN_FASTCALL (*peek16)(const v810_timestamp_t, uint32), uint32 MDFN_FASTCALL (*peek32)(const v810_timestamp_t, uint32));
 void SetCPUHook(void (*newhook)(const v810_timestamp_t timestamp, uint32 PC), void (*new_ADDBT)(uint32, uint32, uint32));
 #endif

 enum
 {
  GSREG_PR = 0,
  GSREG_SR = 32,
  GSREG_PC = 64,
  GSREG_TIMESTAMP
 };

 uint32 GetRegister(unsigned int which, char *special, const uint32 special_len);
 void SetRegister(unsigned int which, uint32 value);

 uint32 GetPC(void);
 void SetPC(uint32);

 INLINE uint32 GetPR(unsigned int which)
 {
  return which ? P_REG[which] : 0;
 }

 private:

 // Make sure P_REG[] is the first variable/array in this class, so non-zerfo offset encoding(at assembly level) isn't necessary to access it.
 uint32 P_REG[32];  // Program registers pr0-pr31
 uint32 S_REG[32];  // System registers sr0-sr31
 uint32 PC;
 uint8 *PC_ptr;
 uint8 *PC_base;

 uint32 IPendingCache;
 void RecalcIPendingCache(void);

 public:
 v810_timestamp_t v810_timestamp;	// Will never be less than 0.

 private:
 v810_timestamp_t next_event_ts;

 enum
 {
  LASTOP_NORMAL = 0,
  LASTOP_LOAD = 1,
  LASTOP_STORE = 2,
  LASTOP_IN = 3,
  LASTOP_OUT = 4,
  LASTOP_HEAVY_MATH = 5
 };

 V810_Emu_Mode EmuMode;
 bool VBMode;

 void Run_Fast(int32 MDFN_FASTCALL (*event_handler)(const v810_timestamp_t timestamp)) NO_INLINE;
 void Run_Accurate(int32 MDFN_FASTCALL (*event_handler)(const v810_timestamp_t timestamp)) NO_INLINE;

 #ifdef WANT_DEBUGGER
 void Run_Fast_Debug(int32 MDFN_FASTCALL (*event_handler)(const v810_timestamp_t timestamp)) NO_INLINE;
 void Run_Accurate_Debug(int32 MDFN_FASTCALL (*event_handler)(const v810_timestamp_t timestamp)) NO_INLINE;
 #endif

 uint8 MDFN_FASTCALL (*MemRead8)(v810_timestamp_t &timestamp, uint32 A);
 uint16 MDFN_FASTCALL (*MemRead16)(v810_timestamp_t &timestamp, uint32 A);
 uint32 MDFN_FASTCALL (*MemRead32)(v810_timestamp_t &timestamp, uint32 A);

 void MDFN_FASTCALL (*MemWrite8)(v810_timestamp_t &timestamp, uint32 A, uint8 V);
 void MDFN_FASTCALL (*MemWrite16)(v810_timestamp_t &timestamp, uint32 A, uint16 V);
 void MDFN_FASTCALL (*MemWrite32)(v810_timestamp_t &timestamp, uint32 A, uint32 V);

 uint8 MDFN_FASTCALL (*IORead8)(v810_timestamp_t &timestamp, uint32 A);
 uint16 MDFN_FASTCALL (*IORead16)(v810_timestamp_t &timestamp, uint32 A);
 uint32 MDFN_FASTCALL (*IORead32)(v810_timestamp_t &timestamp, uint32 A);

 void MDFN_FASTCALL (*IOWrite8)(v810_timestamp_t &timestamp, uint32 A, uint8 V);
 void MDFN_FASTCALL (*IOWrite16)(v810_timestamp_t &timestamp, uint32 A, uint16 V);
 void MDFN_FASTCALL (*IOWrite32)(v810_timestamp_t &timestamp, uint32 A, uint32 V);

 bool MemReadBus32[256];      // Corresponding to the upper 8 bits of the memory address map.
 bool MemWriteBus32[256];

 int32 lastop;    // Set to -1 on FP/MUL/DIV, 0x100 on LD, 0x200 on ST, 0x400 on in, 0x800 on out, and the actual opcode * 2(or >= 0) on everything else.

 #define LASTOP_LD       0x100
 #define LASTOP_ST       0x200
 #define LASTOP_IN       0x400
 #define LASTOP_OUT      0x800

 enum
 {
  HALT_NONE = 0,
  HALT_HALT = 1,
  HALT_FATAL_EXCEPTION = 2
 };

 uint8 Halted;

 bool Running;

 int ilevel;

 bool in_bstr;
 uint16 in_bstr_to;

 bool bstr_subop(v810_timestamp_t &timestamp, int sub_op, int arg1);
 void fpu_subop(v810_timestamp_t &timestamp, int sub_op, int arg1, int arg2);

 void Exception(uint32 handler, uint16 eCode);

 // Caching-related:
 typedef struct
 {
  uint32 tag;
  uint32 data[2];
  bool data_valid[2];
 } V810_CacheEntry_t;

 V810_CacheEntry_t Cache[128];

 // Bitstring variables.
 uint32 src_cache;
 uint32 dst_cache;
 bool have_src_cache, have_dst_cache;

 uint8 *FastMap[(1ULL << 32) / V810_FAST_MAP_PSIZE];

 #ifdef WANT_DEBUGGER
 void (*CPUHook)(const v810_timestamp_t timestamp, uint32 PC);
 void (*ADDBT)(uint32 old_PC, uint32 new_PC, uint32);
 #endif

 // For CacheDump and CacheRestore
 void CacheOpMemStore(v810_timestamp_t &timestamp, uint32 A, uint32 V);
 uint32 CacheOpMemLoad(v810_timestamp_t &timestamp, uint32 A);

 void CacheClear(v810_timestamp_t &timestamp, uint32 start, uint32 count);
 void CacheDump(v810_timestamp_t &timestamp, const uint32 SA);
 void CacheRestore(v810_timestamp_t &timestamp, const uint32 SA);

 uint32 RDCACHE(v810_timestamp_t &timestamp, uint32 addr);
 //
 // End caching related
 //

 uint16 RDOP(v810_timestamp_t &timestamp, uint32 addr, uint32 meow = 2);
 void SetFlag(uint32 n, bool condition);
 void SetSZ(uint32 value);

 void SetSREG(v810_timestamp_t &timestamp, unsigned int which, uint32 value);
 uint32 GetSREG(unsigned int which);

 bool IsSubnormal(uint32 fpval);
 void FPU_Math_Template(uint32 (V810_FP_Ops::*func)(uint32, uint32), uint32 arg1, uint32 arg2);
 void FPU_DoException(void);
 bool CheckFPInputException(uint32 fpval);
 bool FPU_DoesExceptionKillResult(void);
 void SetFPUOPNonFPUFlags(uint32 result);

 uint32 BSTR_RWORD(v810_timestamp_t &timestamp, uint32 A);
 void BSTR_WWORD(v810_timestamp_t &timestamp, uint32 A, uint32 V);
 bool Do_BSTR_Search(v810_timestamp_t &timestamp, const int inc_mul, unsigned int bit_test);

 V810_FP_Ops fpo;

 uint8 DummyRegion[V810_FAST_MAP_PSIZE + V810_FAST_MAP_TRAMPOLINE_SIZE];
};

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/GeoSchnitzeljagd.WebServices.iml" filepath="$PROJECT_DIR$/.idea/GeoSchnitzeljagd.WebServices.iml" />
    </modules>
  </component>
</project>


text:
<!doctype html>

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


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

	<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
	<meta content="2013-12-25 10:18:47 -0700" http-equiv="change-date" />
	<title>RM 14</title>

	<link rel="stylesheet" href='../css/bpi.css' >

Romanos 14

1Ora, ao que é fraco na fé, acolhei-o, mas não para condenar-lhe os escrúpulos.

2Um crê que de tudo se pode comer, e outro, que é fraco, come só legumes.

3Quem come não despreze a quem não come; e quem não come não julgue a quem come; pois Deus o acolheu.

4Quem és tu, que julgas o servo alheio? Para seu próprio senhor ele está em pé ou cai; mas estará firme, porque poderoso é o Senhor para o firmar.

5Um faz diferença entre dia e dia, mas outro julga iguais todos os dias. Cada um esteja inteiramente convicto em sua própria mente.

6Aquele que faz caso do dia, para o Senhor o faz. E quem come, para o Senhor come, porque dá graças a Deus; e quem não come, para o Senhor não come, e dá graças a Deus.

7Porque nenhum de nós vive para si, e nenhum morre para si.

8Pois, se vivemos, para o Senhor vivemos; se morremos, para o Senhor morremos. De sorte que, quer vivamos quer morramos, somos do Senhor.

9Porque foi para isto mesmo que Cristo morreu e tornou a viver, para ser Senhor tanto de mortos como de vivos.

10Mas tu, por que julgas teu irmão? Ou tu, também, por que desprezas teu irmão? Pois todos havemos de comparecer ante o tribunal de Deus.

11Porque está escrito: Por minha vida, diz o Senhor, diante de mim se dobrará todo joelho, e toda língua louvará a Deus.

12Assim, pois, cada um de nós dará conta de si mesmo a Deus.

13Portanto não nos julguemos mais uns aos outros; antes o seja o vosso propósito não pôr tropeço ou escândalo ao vosso irmão.

14Eu sei, e estou certo no Senhor Jesus, que nada é de si mesmo imundo a não ser para aquele que assim o considera; para esse é imundo.

15Pois, se pela tua comida se entristece teu irmão, já não andas segundo o amor. Não faças perecer por causa da tua comida aquele por quem Cristo morreu.

16Não seja pois censurado o vosso bem;

17porque o reino de Deus não consiste no comer e no beber, mas na justiça, na paz, e na alegria no Espírito Santo.

18Pois quem nisso serve a Cristo agradável é a Deus e aceito aos homens.

19Assim, pois, sigamos as coisas que servem para a paz e as que contribuem para a edificação mútua.

20Não destruas por causa da comida a obra de Deus. Na verdade tudo é limpo, mas é um mal para o homem dar motivo de tropeço pelo comer.

21Bom é não comer carne, nem beber vinho, nem fazer outra coisa em que teu irmão tropece.

22A fé que tens, guarda-a contigo mesmo diante de Deus. Bem-aventurado aquele que não se condena a si mesmo naquilo que aprova.

23Mas aquele que tem dúvidas, se come está condenado, porque o que faz não provém da fé; e tudo o que não provém da fé é pecado.

Almeida Revista e Atualizada© Copyright © 1993 Sociedade Bíblica do Brasil. Todos os direitos reservados. Texto bíblico utilizado com autorização. Saiba mais sobre a Sociedade Bíblica do Brasil. A Sociedade Bíblica do Brasil trabalha para que a Bíblia esteja, efetivamente, ao alcance de todos e seja lida por todos. A SBB é uma entidade sem fins lucrativos, dedicada a promover o desenvolvimento integral do ser humano.


text:
package br.edu.fanor.progweb.arquitetura.utils;

public class MessageEmail {

	private String destino;
	 private String titulo;
	 private String mensagem;

	 public String getDestino() {
	 return destino;
	 }

	 public void setDestino(String destino) {
	 this.destino = destino;
	 }

	 public String getMensagem() {
	 return mensagem;
	 }

	 public void setMensagem(String mensagem) {
	 this.mensagem = mensagem;
	 }

	 public String getTitulo() {
	 return titulo;
	 }

	 public void setTitulo(String titulo) {
	 this.titulo = titulo;
	 }

}


text:
from optparse import OptionParser
import format_obj
import format_js
import sys
import os

formats = {
    'js': format_js,
    'obj': format_obj,
}

if __name__ == '__main__':
    # parse command line
    help = 'one of: ' + ', '.join(formats)
    parser = OptionParser('usage: [options] input_file output_file')
    parser.add_option('--scale', dest='scale', help='scales the model')
    parser.add_option('--center', action='store_true', help='centers the model above the origin')
    parser.add_option('--compute_normals', action='store_true', help='computes smoothed normals')
    parser.add_option('--in', dest='input_format', help=help)
    parser.add_option('--out', dest='output_format', help=help)
    options, args = parser.parse_args()

    # validate command line
    if len(args) != 2:
        parser.print_help()
        sys.exit()

    # parse formats
    in_path, out_path = args
    in_fmt, out_fmt = options.input_format, options.output_format
    in_fmt = in_fmt if in_fmt else os.path.splitext(in_path)[1][1:]
    out_fmt = out_fmt if out_fmt else os.path.splitext(out_path)[1][1:]
    if in_fmt not in formats:
        print 'error: unsupported format "%s"' % in_fmt
        sys.exit()
    if out_fmt not in formats:
        print 'error: unsupported format "%s"' % out_fmt
        sys.exit()

    # perform conversion
    try:
        # load model
        in_file = open(in_path, 'rb')
        print 'loading', os.path.basename(in_path)
        model = formats[in_fmt].load(in_file)

        # handle conversion options
        if options.center:
            print 'centering model'
            model.center()
        if options.compute_normals:
            print 'computing normals'
            model.compute_normals()
        if options.scale:
			print 'scaling model'
			model.scale(float(options.scale))

        # save model
        out_file = open(out_path, 'wb')
        print 'saving', os.path.basename(out_path)
        formats[out_fmt].dump(model, out_file)
    except IOError, e:
        print e


text:
@class NSArray, NSMutableArray;

@interface ALSoundSourcePool : NSObject
{
    NSMutableArray *sources;
}

+ (id)pool;
- (void).cxx_destruct;
- (void)addSource:(id)arg1;
- (void)dealloc;
- (id)getFreeSource:(_Bool)arg1;
- (id)init;
- (void)moveToHead:(int)arg1;
- (void)removeSource:(id)arg1;
@property(readonly, retain, nonatomic) NSArray *sources; // @synthesize sources;

@end


text:
package remote

import (
	"fmt"
	"reflect"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/prometheus/common/model"
	"github.com/prometheus/prometheus/config"
	"github.com/prometheus/prometheus/prompb"
)

type TestStorageClient struct {
	receivedSamples map[string][]*prompb.Sample
	expectedSamples map[string][]*prompb.Sample
	wg              sync.WaitGroup
	mtx             sync.Mutex
}

func NewTestStorageClient() *TestStorageClient {
	return &TestStorageClient{
		receivedSamples: map[string][]*prompb.Sample{},
		expectedSamples: map[string][]*prompb.Sample{},
	}
}

func (c *TestStorageClient) expectSamples(ss model.Samples) {
	c.mtx.Lock()
	defer c.mtx.Unlock()

	for _, s := range ss {
		ts := labelProtosToLabels(MetricToLabelProtos(s.Metric)).String()
		c.expectedSamples[ts] = append(c.expectedSamples[ts], &prompb.Sample{
			Timestamp: int64(s.Timestamp),
			Value:     float64(s.Value),
		})
	}
	c.wg.Add(len(ss))
}

func (c *TestStorageClient) waitForExpectedSamples(t *testing.T) {
	c.wg.Wait()

	c.mtx.Lock()
	defer c.mtx.Unlock()
	for ts, expectedSamples := range c.expectedSamples {
		if !reflect.DeepEqual(expectedSamples, c.receivedSamples[ts]) {
			t.Fatalf("%s: Expected %v, got %v", ts, expectedSamples, c.receivedSamples[ts])
		}
	}
}

func (c *TestStorageClient) Store(req *prompb.WriteRequest) error {
	c.mtx.Lock()
	defer c.mtx.Unlock()
	count := 0
	for _, ts := range req.Timeseries {
		labels := labelProtosToLabels(ts.Labels).String()
		for _, sample := range ts.Samples {
			count++
			c.receivedSamples[labels] = append(c.receivedSamples[labels], sample)
		}
	}
	c.wg.Add(-count)
	return nil
}

func (c *TestStorageClient) Name() string {
	return "teststorageclient"
}

func TestSampleDelivery(t *testing.T) {
	// Let's create an even number of send batches so we don't run into the
	// batch timeout case.
	n := config.DefaultQueueConfig.Capacity * 2

	samples := make(model.Samples, 0, n)
	for i := 0; i < n; i++ {
		name := model.LabelValue(fmt.Sprintf("test_metric_%d", i))
		samples = append(samples, &model.Sample{
			Metric: model.Metric{
				model.MetricNameLabel: name,
			},
			Value: model.SampleValue(i),
		})
	}

	c := NewTestStorageClient()
	c.expectSamples(samples[:len(samples)/2])

	cfg := config.DefaultQueueConfig
	cfg.MaxShards = 1
	m := NewQueueManager(nil, cfg, nil, nil, c)

	// These should be received by the client.
	for _, s := range samples[:len(samples)/2] {
		m.Append(s)
	}
	// These will be dropped because the queue is full.
	for _, s := range samples[len(samples)/2:] {
		m.Append(s)
	}
	m.Start()
	defer m.Stop()

	c.waitForExpectedSamples(t)
}

func TestSampleDeliveryOrder(t *testing.T) {
	ts := 10
	n := config.DefaultQueueConfig.MaxSamplesPerSend * ts

	samples := make(model.Samples, 0, n)
	for i := 0; i < n; i++ {
		name := model.LabelValue(fmt.Sprintf("test_metric_%d", i%ts))
		samples = append(samples, &model.Sample{
			Metric: model.Metric{
				model.MetricNameLabel: name,
			},
			Value:     model.SampleValue(i),
			Timestamp: model.Time(i),
		})
	}

	c := NewTestStorageClient()
	c.expectSamples(samples)
	m := NewQueueManager(nil, config.DefaultQueueConfig, nil, nil, c)

	// These should be received by the client.
	for _, s := range samples {
		m.Append(s)
	}
	m.Start()
	defer m.Stop()

	c.waitForExpectedSamples(t)
}

// TestBlockingStorageClient is a queue_manager StorageClient which will block
// on any calls to Store(), until the `block` channel is closed, at which point
// the `numCalls` property will contain a count of how many times Store() was
// called.
type TestBlockingStorageClient struct {
	numCalls uint64
	block    chan bool
}

func NewTestBlockedStorageClient() *TestBlockingStorageClient {
	return &TestBlockingStorageClient{
		block:    make(chan bool),
		numCalls: 0,
	}
}

func (c *TestBlockingStorageClient) Store(_ *prompb.WriteRequest) error {
	atomic.AddUint64(&c.numCalls, 1)
	<-c.block
	return nil
}

func (c *TestBlockingStorageClient) NumCalls() uint64 {
	return atomic.LoadUint64(&c.numCalls)
}

func (c *TestBlockingStorageClient) unlock() {
	close(c.block)
}

func (c *TestBlockingStorageClient) Name() string {
	return "testblockingstorageclient"
}

func (t *QueueManager) queueLen() int {
	t.shardsMtx.Lock()
	defer t.shardsMtx.Unlock()
	queueLength := 0
	for _, shard := range t.shards.queues {
		queueLength += len(shard)
	}
	return queueLength
}

func TestSpawnNotMoreThanMaxConcurrentSendsGoroutines(t *testing.T) {
	// Our goal is to fully empty the queue:
	// `MaxSamplesPerSend*Shards` samples should be consumed by the
	// per-shard goroutines, and then another `MaxSamplesPerSend`
	// should be left on the queue.
	n := config.DefaultQueueConfig.MaxSamplesPerSend * 2

	samples := make(model.Samples, 0, n)
	for i := 0; i < n; i++ {
		name := model.LabelValue(fmt.Sprintf("test_metric_%d", i))
		samples = append(samples, &model.Sample{
			Metric: model.Metric{
				model.MetricNameLabel: name,
			},
			Value: model.SampleValue(i),
		})
	}

	c := NewTestBlockedStorageClient()
	cfg := config.DefaultQueueConfig
	cfg.MaxShards = 1
	cfg.Capacity = n
	m := NewQueueManager(nil, cfg, nil, nil, c)

	m.Start()

	defer func() {
		c.unlock()
		m.Stop()
	}()

	for _, s := range samples {
		m.Append(s)
	}

	// Wait until the runShard() loops drain the queue.  If things went right, it
	// should then immediately block in sendSamples(), but, in case of error,
	// it would spawn too many goroutines, and thus we'd see more calls to
	// client.Store()
	//
	// The timed wait is maybe non-ideal, but, in order to verify that we're
	// not spawning too many concurrent goroutines, we have to wait on the
	// Run() loop to consume a specific number of elements from the
	// queue... and it doesn't signal that in any obvious way, except by
	// draining the queue.  We cap the waiting at 1 second -- that should give
	// plenty of time, and keeps the failure fairly quick if we're not draining
	// the queue properly.
	for i := 0; i < 100 && m.queueLen() > 0; i++ {
		time.Sleep(10 * time.Millisecond)
	}

	if m.queueLen() != config.DefaultQueueConfig.MaxSamplesPerSend {
		t.Fatalf("Failed to drain QueueManager queue, %d elements left",
			m.queueLen(),
		)
	}

	numCalls := c.NumCalls()
	if numCalls != uint64(1) {
		t.Errorf("Saw %d concurrent sends, expected 1", numCalls)
	}
}


text:
<Record>
<Term>Enterobiasis</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Oxyuriasis</ParentTerm>
<ClassificationPath>Parasitic Diseases/Helminthiasis/Nematode Infections/Secernentea Infections/Oxyurida Infections/Oxyuriasis/Enterobiasis</ClassificationPath>
<BroaderTerm>Oxyurida Infections</BroaderTerm>
<BroaderTerm>Nematode Infections</BroaderTerm>
<BroaderTerm>Oxyuriasis</BroaderTerm>
<BroaderTerm>Secernentea Infections</BroaderTerm>
<BroaderTerm>Helminthiasis</BroaderTerm>
<BroaderTerm>Enterobiasis</BroaderTerm>
<BroaderTerm>Parasitic Diseases</BroaderTerm>
<Synonym>Enterobiasis</Synonym>
<Synonym>Enterobiases</Synonym>
<Synonym>Oxyuris vermicularis Infections</Synonym>
<Synonym>Enterobius vermicularis Infections</Synonym>
<Synonym>Oxyuris vermicularis Infection</Synonym>
<Synonym>Enterobius vermicularis Infection</Synonym>
<Description>Infection with nematodes of the genus ENTEROBIUS; E. vermicularis, the pinworm of man, causes a crawling sensation and pruritus. This condition results in scratching the area, occasionally causing scarification.</Description>
<Source>MeSH</Source>
</Record>