text:
require 'spec_helper'

describe Mailer do
  context "Err Notification" do
    include EmailSpec::Helpers
    include EmailSpec::Matchers

    let(:notice)  { Fabricate(:notice, :message => "class < ActionController::Base") }
    let!(:user)   { Fabricate(:admin) }

    before do
      notice.backtrace.lines.last.update_attributes(:file => "[PROJECT_ROOT]/path/to/file.js")
      notice.app.update_attributes(
        :asset_host => "http://example.com",
        :notify_all_users => true
      )
      notice.problem.update_attributes :notices_count => 3

      @email = Mailer.err_notification(notice).deliver
    end

    it "should send the email" do
      expect(ActionMailer::Base.deliveries.size).to eq 1
    end

    it "should html-escape the notice's message for the html part" do
      expect(@email).to have_body_text("class < ActionController::Base")
    end

    it "should have inline css" do
      expect(@email).to have_body_text('<p class="backtrace" style="')
    end

    it "should have links to source files" do
      expect(@email).to have_body_text('path/to/file.js')
    end

    it "should have the error count in the subject" do
      expect(@email.subject).to match( /^\(3\) / )
    end

    context 'with a very long message' do
      let(:notice)  { Fabricate(:notice, :message => 6.times.collect{|a| "0123456789" }.join('')) }
      it "should truncate the long message" do
        expect(@email.subject).to match( / \d{47}\.{3}$/ )
      end
    end
  end

  context "Comment Notification" do
    include EmailSpec::Helpers
    include EmailSpec::Matchers

    let!(:notice) { Fabricate(:notice) }
    let!(:comment) { Fabricate.build(:comment, :err => notice.problem) }
    let!(:watcher) { Fabricate(:watcher, :app => comment.app) }
    let(:recipients) { ['recipient@example.com', 'another@example.com']}

    before do
      comment.stub(:notification_recipients).and_return(recipients)
      Fabricate(:notice, :err => notice.err)
      @email = Mailer.comment_notification(comment).deliver
    end

    it "should send the email" do
      expect(ActionMailer::Base.deliveries.size).to eq 1
    end

    it "should be sent to comment notification recipients" do
      expect(@email.to).to eq recipients
    end

    it "should have the notices count in the body" do
      expect(@email).to have_body_text("This err has occurred 2 times")
    end

    it "should have the comment body" do
      expect(@email).to have_body_text(comment.body)
    end
  end
end


text:
package org.broad.igv.tools.converters;

import org.broad.igv.feature.*;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.tribble.GFFCodec;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.TestUtils;
import htsjdk.tribble.Feature;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.List;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

/**
 * @author Jim Robinson
 * @date 2/15/12
 */
public class GFFtoBedTest {

    @Test
    public void testConvert() throws Exception {

        File inputFile = new File(TestUtils.DATA_DIR, "gff/gene.unsorted.gff3");
        File outputFile = new File(TestUtils.DATA_DIR, "out/gene.bed");

        // Convert
        GFFtoBed.convert(inputFile, outputFile);

        // Now compare features from both files, they should be identical

        BufferedReader gffReader = null;
        BufferedReader bedReader = null;
        try {
            Genome genome = null; // Not needed for this test
            gffReader = new BufferedReader(new FileReader(inputFile));
            GFFParser parser = new GFFParser();
            GFFCodec.Version version = inputFile.getPath().endsWith(".gff3") ? GFFCodec.Version.GFF3 : GFFCodec.Version.GFF2;
            GFFCodec codec = new GFFCodec(version, null);
            List<Feature> gffFeatures = parser.loadFeatures(gffReader, genome, codec);

            bedReader = new BufferedReader(new FileReader(outputFile));
            FeatureParser bedParser = AbstractFeatureParser.getInstanceFor(new ResourceLocator(outputFile.getAbsolutePath()), null);
            List<Feature> bedFeatures = bedParser.loadFeatures(bedReader, genome);

            assertTrue(gffFeatures.size() > 0);
            assertEquals(gffFeatures.size(), bedFeatures.size());
            for (int i = 0; i < gffFeatures.size(); i++) {
                BasicFeature gffFeature = (BasicFeature) gffFeatures.get(i);
                BasicFeature bedFeature = (BasicFeature) bedFeatures.get(i);

                compare(gffFeature, bedFeature);

            }

        } finally {
            gffReader.close();
        }

    }

    private void compare(BasicFeature gffFeature, BasicFeature bedFeature) {

        assertEquals(gffFeature.getChr(), bedFeature.getChr());
        assertEquals(gffFeature.getStart(), bedFeature.getStart());
        assertEquals(gffFeature.getEnd(), bedFeature.getEnd());
        assertEquals(gffFeature.getStrand(), bedFeature.getStrand());
        assertEquals(gffFeature.getColor(), bedFeature.getColor());
        //BED features don't have a type
        //assertEquals(gffFeature.getType(), bedFeature.getType());
        assertEquals(gffFeature.getStart(), bedFeature.getThickStart());
        assertEquals(gffFeature.getThickEnd(), bedFeature.getThickEnd());
        if (!Float.isNaN(gffFeature.getScore())) {
            assertEquals(gffFeature.getScore(), bedFeature.getScore());
        }
        assertEquals(gffFeature.getExonCount(), bedFeature.getExonCount());

        List<Exon> gffExons = gffFeature.getExons();
        List<Exon> bedExons = bedFeature.getExons();

        // This is broken for sure, disable for now
//        for (int i = 0; i < gffExons.size(); i++) {
//
//            Exon gffExon = gffExons.get(i);
//            Exon bedExon = bedExons.get(i);
//            assertEquals(gffExon.getCdStart(), bedExon.getCdStart());
//            assertEquals(gffExon.getCodingLength(), bedExon.getCodingLength());
//            assertEquals(gffExon.getCdEnd(), bedExon.getCdEnd());
//            assertEquals(gffExon.getReadingShift(), bedExon.getReadingShift());
//        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.gradoop.flink.model.api.functions;

import org.apache.flink.api.common.functions.GroupReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.gradoop.common.model.impl.pojo.GraphHead;

import java.io.Serializable;

/**
 * Marker interface for reduce functions used for group by isomorphism operator.
 * Such functions can be used to calculate aggregates based on graph heads.
 * For example, to count isomorphic graphs in a collection.
 */
public interface GraphHeadReduceFunction
  extends GroupReduceFunction<Tuple2<String, GraphHead>, GraphHead>, Serializable {
}


text:
package main

import (
	"fmt"
)

func main() {

	m := CreateMap()

	fmt.Println("FindMapValue: ", FindMapValue(m, "Bob"))
	fmt.Println("FindMapValue: ", FindMapValue(m, "John"))

	result, i := AddMapValue(m, "NewBob", "NewIDE")
	fmt.Println("Added: ", result, "Total: ", i)

	fmt.Println("Update: ", UpdateMapValue(m, "Bob", "Vim"))
	fmt.Println("Update: ", UpdateMapValue(m, "John", "Vim"))

	fmt.Println("Deleted! Map Length Now: ", DeleteMapValue(m, "Bob"))

	fmt.Println("Bob Exist? ", NameExist(m, "Bob"))
	fmt.Println("John Exist? ", NameExist(m, "John"))
	fmt.Println("NewBob Exist? ", NameExist(m, "NewBob"))

}

func Run() {
	fmt.Println("Run!")
}

func CreateMap() map[string]string {

	var m map[string]string
	m = make(map[string]string)

	m["John"] = "LiteIDE"
	m["Bob"] = "IntelliJ"

	return m
}

func CreateMap2() map[string]string {

	//shorthand map declaration
	m := map[string]string{
		"John": "LiteIDE",
		"Bob":  "IntelliJ",
	}
	return m
}

func FindMapValue(m map[string]string, name string) (ide string) {

	return m[name]
}

func AddMapValue(m map[string]string, name, newIde string) (map[string]string, int) {

	m[name] = newIde

	return m, len(m)
}

func UpdateMapValue(m map[string]string, name, newIde string) map[string]string {

	m[name] = newIde

	return m
}

func DeleteMapValue(m map[string]string, name string) (mapLength int) {

	delete(m, name)

	return len(m)
}

func NameExist(m map[string]string, name string) (exists bool) {

	if _, exists = m[name]; exists {
		return exists
	}
	return
}


text:
public class Main {
	public static void main(String[] args){
		Cachorro c = new Cachorro("Pastor Alemão", 1, 12);
		Gato g = new Gato("Sphinx", 1, 7);

		ManadaVirgula mVirgula = new ManadaVirgula();
		ManadaSustenido mSustenido = new ManadaSustenido();

		mVirgula.adicionarAnimal(c);
		mSustenido.adicionarAnimal(c);

		mVirgula.adicionarAnimal(g);
		mSustenido.adicionarAnimal(g);

		System.out.println(mVirgula.estorar());
		System.out.println(mSustenido.estorar());

	}

}


text:
using System;

using Org.BouncyCastle.Utilities.Encoders;

namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
    internal class SecP160R1Curve
        : AbstractFpCurve
    {
        public static readonly BigInteger q = new BigInteger(1,
            Hex.Decode("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"));

        private const int SecP160R1_DEFAULT_COORDS = COORD_JACOBIAN;

        protected readonly SecP160R1Point m_infinity;

        public SecP160R1Curve()
            : base(q)
        {
            this.m_infinity = new SecP160R1Point(this, null, null);

            this.m_a = FromBigInteger(new BigInteger(1,
                Hex.Decode("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC")));
            this.m_b = FromBigInteger(new BigInteger(1,
                Hex.Decode("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45")));
            this.m_order = new BigInteger(1, Hex.Decode("0100000000000000000001F4C8F927AED3CA752257"));
            this.m_cofactor = BigInteger.One;

            this.m_coord = SecP160R1_DEFAULT_COORDS;
        }

        protected override ECCurve CloneCurve()
        {
            return new SecP160R1Curve();
        }

        public override  bool SupportsCoordinateSystem(int coord)
        {
            switch (coord)
            {
            case COORD_JACOBIAN:
                return true;
            default:
                return false;
            }
        }

        public virtual BigInteger Q
        {
            get { return q; }
        }

        public override ECPoint Infinity
        {
            get { return m_infinity; }
        }

        public override int FieldSize
        {
            get { return q.BitLength; }
        }

        public override ECFieldElement FromBigInteger(BigInteger x)
        {
            return new SecP160R1FieldElement(x);
        }

        protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression)
        {
            return new SecP160R1Point(this, x, y, withCompression);
        }

        protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
        {
            return new SecP160R1Point(this, x, y, zs, withCompression);
        }
    }
}


text:
package org.jivesoftware.smackx.provider;

import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.provider.PacketExtensionProvider;
import org.jivesoftware.smackx.jingle.media.PayloadType;
import org.jivesoftware.smackx.packet.JingleDescription;
import org.xmlpull.v1.XmlPullParser;

/**
 * Parser for a Jingle description
 *
 * @author Alvaro Saurin <alvaro.saurin@gmail.com>
 */
public abstract class JingleDescriptionProvider implements PacketExtensionProvider {

    /**
     * Default constructor
     */
    public JingleDescriptionProvider() {
        super();
    }

    /**
     * Parse a iq/jingle/description/payload-type element.
     *
     * @param parser
     *            the input to parse
     * @return a payload type element
     * @throws Exception
     */
    protected PayloadType parsePayload(final XmlPullParser parser) throws Exception {
        int ptId = 0;
        String ptName;
        int ptChannels = 0;

        try {
            ptId = Integer.parseInt(parser.getAttributeValue("", "id"));
        } catch (Exception e) {
        }

        ptName = parser.getAttributeValue("", "name");

        try {
            ptChannels = Integer.parseInt(parser.getAttributeValue("", "channels"));
        } catch (Exception e) {
        }

        return new PayloadType(ptId, ptName, ptChannels);
    }

    /**
     * Parse a iq/jingle/description element.
     *
     * @param parser
     *            the input to parse
     * @return a description element
     * @throws Exception
     */
    public PacketExtension parseExtension(final XmlPullParser parser) throws Exception {
        boolean done = false;
        JingleDescription desc = getInstance();

        while (!done) {
            int eventType = parser.next();
            String name = parser.getName();

            if (eventType == XmlPullParser.START_TAG) {
                if (name.equals(PayloadType.NODENAME)) {
                    desc.addPayloadType(parsePayload(parser));
                } else {
                    throw new Exception("Unknow element \"" + name + "\" in content.");
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                if (name.equals(JingleDescription.NODENAME)) {
                    done = true;
                }
            }
        }
        return desc;
    }

    /**
     * Return a new instance of this class. Subclasses must overwrite this
     * method.
     */
    protected abstract JingleDescription getInstance();

    /**
     * Jingle audio
     */
    public static class Audio extends JingleDescriptionProvider {

        /**
         * Default constructor
         */
        public Audio() {
            super();
        }

        /**
         * Parse an audio payload type.
         */
        public PayloadType parsePayload(final XmlPullParser parser) throws Exception {
            PayloadType pte = super.parsePayload(parser);
            PayloadType.Audio pt = new PayloadType.Audio(pte);
            int ptClockRate = 0;

            try {
                ptClockRate = Integer.parseInt(parser.getAttributeValue("", "clockrate"));
            } catch (Exception e) {
            }
            pt.setClockRate(ptClockRate);

            return pt;
        }

        /**
         * Get a new instance of this object.
         */
        protected JingleDescription getInstance() {
            return new JingleDescription.Audio();
        }
    }
}


text:
describe CustomFields::TargetHelpers do

  before(:each) do
    @post = build_post_with_rules
  end

  context '#grouping fields' do

    it 'returns empty arrays if no rules' do
      @post.stubs(:custom_fields_recipe).returns({ 'rules' => [] })

      expect(@post.select_custom_fields).to be_empty
      expect(@post.file_custom_fields).to be_empty
      expect(@post.has_many_custom_fields).to be_empty
      expect(@post.many_to_many_custom_fields).to be_empty
    end

    it 'groups select fields' do
      expect(@post.select_custom_fields).to eq %w[category]
    end

    it 'groups file fields' do
      expect(@post.file_custom_fields).to eq %w[illustration author_picture]
    end

    it 'groups has_many fields including the inverse_of property' do
      expect(@post.has_many_custom_fields).to eq [%w[projects project], %w[illustrations project]]
    end

    it 'groups many_to_many fields including the field name to get the target ids' do
      expect(@post.many_to_many_custom_fields).to eq [%w[contributors contributor_ids]]
    end

  end

  context '#returning safe setters' do

    before(:each) do
      @names = @post.custom_fields_safe_setters
    end

    it 'includes setters for string' do
      expect(@names.include?('author_name')).to be true
    end

    it 'includes setters for boolean' do
      expect(@names.include?('visible')).to be true
    end

    it 'includes setters for integer' do
      expect(@names.include?('int_count')).to be true
    end

    it 'includes setters for float' do
      expect(@names.include?('float_count')).to be true
    end

    it 'includes setters for money' do
      expect(@names.include?('formatted_donation')).to be true
    end

    it 'includes setters for date' do
      expect(@names.include?('formatted_posted_at')).to be true
    end

    it 'includes setters for file' do
      expect(@names.include?('illustration')).to be true
      expect(@names.include?('remove_illustration')).to be true
    end

    it 'includes setters for select' do
      expect(@names.include?('category_id')).to be true
      expect(@names.include?('category')).to be false
    end

    it 'includes setters for integer' do
      expect(@names.include?('int_count')).to be true
      expect(@names.include?('remove_int_count')).to be false
    end

    it 'includes setters for float' do
      expect(@names.include?('float_count')).to be true
      expect(@names.include?('remove_float_count')).to be false
    end

    it 'includes setters for belongs_to' do
      expect(@names.include?('ghost_writer_id')).to be true
      expect(@names.include?('position_in_ghost_writer')).to be true
      expect(@names.include?('ghost_writer')).to be false
    end

    it 'does not include setters for has_many and many_to_many' do
      expect(@names.include?('contributors')).to be false
      expect(@names.include?('projects')).to be false
    end

  end

  context '#returning basic attributes' do

    before(:each) do
      %w[
        category formatted_posted_at visible author_name illustration?
        author_picture? int_count float_count formatted_donation
      ].each do |meth|
        @post.stubs(meth.to_sym).returns(nil)
      end
    end

    it 'calls the getter for string' do
      @post.class.expects(:string_attribute_get).with(@post, 'author_name').returns({})
      @post.custom_fields_basic_attributes
    end

    it 'calls the getter for integer' do
      @post.class.expects(:integer_attribute_get).with(@post, 'int_count').returns({})
      @post.custom_fields_basic_attributes
    end

    it 'calls the getter for float' do
      @post.class.expects(:float_attribute_get).with(@post, 'float_count').returns({})
      @post.custom_fields_basic_attributes
    end

    it 'calls the getter for money' do
      @post.class.expects(:money_attribute_get).with(@post, 'donation').returns({})
      @post.custom_fields_basic_attributes
    end

    it 'calls the getter for boolean' do
      @post.class.expects(:boolean_attribute_get).with(@post, 'visible').returns({})
      @post.custom_fields_basic_attributes
    end

    it 'calls the getter for date' do
      @post.class.expects(:date_attribute_get).with(@post, 'posted_at').returns({})
      @post.custom_fields_basic_attributes
    end

    it 'calls the getter for file' do
      @post.class.expects(:file_attribute_get).once.with(@post, 'illustration').returns({})
      @post.class.expects(:file_attribute_get).once.with(@post, 'author_picture').returns({})
      @post.custom_fields_basic_attributes
    end

    it 'calls the getter for select' do
      @post.class.expects(:select_attribute_get).with(@post, 'category').returns({})
      @post.custom_fields_basic_attributes
    end

    it 'does not call the getter for belongs_to, has_many and many_to_many' do
      @post.class.expects(:belongs_to_attribute_get).never
      @post.class.expects(:has_many_attribute_get).never
      @post.class.expects(:many_to_many_attribute_get).never
      @post.custom_fields_basic_attributes
    end

  end

  context '#setting basic attributes' do

    before(:each) do
      %w[
        category= formatted_posted_at= visible=
        author_name= int_count= float_count= money=
      ].each do |meth|
        @post.stubs(meth.to_sym).returns(nil)
      end
    end

    it 'calls the setter for string' do
      @post.class.expects(:string_attribute_set).with(@post, 'author_name', {}).returns({})
      @post.custom_fields_basic_attributes = {}
    end

    it 'calls the setter for boolean' do
      @post.class.expects(:boolean_attribute_set).with(@post, 'visible', {}).returns({})
      @post.custom_fields_basic_attributes = {}
    end

    it 'calls the setter for integer' do
      @post.class.expects(:integer_attribute_set).with(@post, 'int_count', {}).returns({})
      @post.custom_fields_basic_attributes = {}
    end

    it 'calls the setter for float' do
      @post.class.expects(:float_attribute_set).with(@post, 'float_count', {}).returns({})
      @post.custom_fields_basic_attributes = {}
    end

    it 'calls the setter for money' do
      @post.class.expects(:money_attribute_set).with(@post, 'donation', {}).returns({})
      @post.custom_fields_basic_attributes = {}
    end

    it 'calls the setter for date' do
      @post.class.expects(:date_attribute_set).with(@post, 'posted_at', {}).returns({})
      @post.custom_fields_basic_attributes = {}
    end

    it 'calls the setter for file' do
      @post.class.expects(:file_attribute_set).once.with(@post, 'illustration', {}).returns({})
      @post.class.expects(:file_attribute_set).once.with(@post, 'author_picture', {}).returns({})
      @post.custom_fields_basic_attributes = {}
    end

    it 'calls the setter for select' do
      @post.class.expects(:select_attribute_set).with(@post, 'category', {}).returns({})
      @post.custom_fields_basic_attributes = {}
    end

    it 'does not call the setter for belongs_to, has_many and many_to_many' do
      @post.class.expects(:belongs_to_attribute_set).never
      @post.class.expects(:has_many_attribute_set).never
      @post.class.expects(:many_to_many_attribute_set).never
      @post.custom_fields_basic_attributes = {}
    end

  end

  context '#returning methods' do

    before(:each) do
      @methods = @post.custom_fields_methods
    end

    it 'includes the default method name for string, select, boolean, integer, float, has_many and many_to_many fields' do
      %w[
        author_name category visible projects illustrations
        contributors int_count float_count
      ].each do |name|
        expect(@methods.include?(name)).to be true
      end
    end

    it 'also includes another method name for select (<name>_id)' do
      expect(@methods.include?('category_id')).to be true
    end

    it 'includes the method name for files' do
      expect(@methods.include?('illustration_url')).to be true
      expect(@methods.include?('illustration')).to be false
      expect(@methods.include?('author_picture_url')).to be true
      expect(@methods.include?('author_picture')).to be false
    end

    it 'includes the method name for dates' do
      expect(@methods.include?('formatted_posted_at')).to be true
      expect(@methods.include?('posted_at')).to be false
    end

    it 'includes the method name for money' do
      expect(@methods.include?('formatted_donation')).to be true
      expect(@methods.include?('donation')).to be false
    end

    it 'includes the method name for belongs_to relationships' do
      expect(@methods.include?('formatted_posted_at')).to be true
      expect(@methods.include?('posted_at')).to be false
    end

    it 'includes the method name for the has_many and many_to_many relationships' do
      %w[contributors projects illustrations].each do |name|
        expect(@methods.include?(name)).to be true
      end
    end

    it 'filters the list by passing a block' do
      block = @post.custom_fields_methods do |rules|
        %w[string boolean integer float].include?(rules['type'])
      end

      expect(block).to eq %w[visible author_name int_count float_count]
    end

  end

  protected

  def build_post_with_rules
    Post.new(title: 'Hello world').tap do |post|
      post.stubs(:custom_fields_recipe).returns({
        'rules' => [
          { 'name' => 'category',       'type' => 'select', 'required' => false, 'localized' => false },
          { 'name' => 'posted_at',      'type' => 'date', 'required' => false, 'localized' => false },
          { 'name' => 'visible',        'type' => 'boolean', 'required' => false, 'localized' => false },
          { 'name' => 'ghost_writer',   'type' => 'belongs_to', class_name: 'Person', 'required' => false, 'localized' => false },
          { 'name' => 'illustration',   'type' => 'file', 'required' => false, 'localized' => false },
          { 'name' => 'author_name',    'type' => 'string', 'required' => false, 'localized' => false },
          { 'name' => 'author_picture', 'type' => 'file', 'required' => false, 'localized' => false },
          { 'name' => 'contributors',   'type' => 'many_to_many', 'class_name' => 'Person', 'inverse_of' => 'posts', 'required' => false, 'localized' => false },
          { 'name' => 'projects',       'type' => 'has_many', 'class_name' => 'Project', 'inverse_of' => 'project', 'required' => false, 'localized' => false },
          { 'name' => 'illustrations',  'type' => 'has_many', 'class_name' => 'PostImage', 'inverse_of' => 'project', 'required' => false, 'localized' => false },
          { 'name' => 'int_count',      'type' => 'integer', 'required' => false, 'localized' => false },
          { 'name' => 'float_count',    'type' => 'float', 'required' => false, 'localized' => false },
          { 'name' => 'donation',       'type' => 'money', 'required' => false, 'localized' => false },
        ]
      })
    end
  end

end


text:
module RuboCop
  module Cop
    module Rails
      # Checks for the use of output calls like puts and print
      #
      # @safety
      #   This cop's autocorrection is unsafe because depending on the Rails log level configuration,
      #   changing from `puts` to `Rails.logger.debug` could result in no output being shown.
      #
      # @example
      #   # bad
      #   puts 'A debug message'
      #   pp 'A debug message'
      #   print 'A debug message'
      #
      #   # good
      #   Rails.logger.debug 'A debug message'
      class Output < Base
        include RangeHelp
        extend AutoCorrector

        MSG = "Do not write to stdout. Use Rails's logger if you want to log."
        RESTRICT_ON_SEND = %i[ap p pp pretty_print print puts binwrite syswrite write write_nonblock].freeze

        def_node_matcher :output?, <<~PATTERN
          (send nil? {:ap :p :pp :pretty_print :print :puts} ...)
        PATTERN

        def_node_matcher :io_output?, <<~PATTERN
          (send
            {
              (gvar #match_gvar?)
              {(const nil? :STDOUT) (const nil? :STDERR)}
            }
            {:binwrite :syswrite :write :write_nonblock}
            ...)
        PATTERN

        def on_send(node)
          return unless (output?(node) || io_output?(node)) && node.arguments?

          range = offense_range(node)

          add_offense(range) do |corrector|
            corrector.replace(range, 'Rails.logger.debug')
          end
        end

        private

        def match_gvar?(sym)
          %i[$stdout $stderr].include?(sym)
        end

        def offense_range(node)
          if node.receiver
            range_between(node.loc.expression.begin_pos, node.loc.selector.end_pos)
          else
            node.loc.selector
          end
        end
      end
    end
  end
end


text:
<?php

namespace Taco\Console;

/**
 * Volba aplikace.
 * Example `--name Name`.
 */
abstract class OptionItem
{

	/**
	 * Jméno volby: --name (bez pomlček).
	 * @var string:1..40
	 */
	private $name;

	/**
	 * Zkrácený název: -n (bez pomlček).
	 * @var string:1
	 */
	private $shortname;

	/**
	 * Důkladný popis.
	 * @var string:1..
	 */
	private $description;

	/**
	 * Defaultní hodnota.
	 */
	private $defaultValue;

	/**
	 * Obsahuje defaultní hodnotu? Defaultní hodnota může být i NULL
	 * nebo False, proto potřebujeme tento příznak.
	 * @var bool
	 */
	private $useDefaultValue = False;

	/**
	 * @param string:1..40
	 * @param string:1..
	 */
	function __construct($name, $description)
	{
		TypeUtils::assert($name, 'string:1..40');
		TypeUtils::assert($description, 'string:1..');
		$this->name = $name;
		$this->description = $description;
	}

	/**
	 * @param string|int|float|closure
	 */
	function setDefaultValue($val)
	{
		$this->defaultValue = $val;
		$this->useDefaultValue = True;
		return $this;
	}

	/**
	 * @param string:1
	 */
	function setShortname($name)
	{
		TypeUtils::assert($name, 'string:1');
		$this->shortname = $name;
	}

	/**
	 * Zkrácený název: -n (bez pomlček).
	 * @return string:1
	 */
	function getShortname()
	{
		return $this->shortname;
	}

	/**
	 * Jméno volby: --name (bez pomlček).
	 * @return string:1..40
	 */
	function getName()
	{
		return $this->name;
	}

	/**
	 * @return Type
	 */
	abstract function getType();

	/**
	 * Důkladný popis: "Jméno projektu".
	 * @return string:1..
	 */
	function getDescription()
	{
		return $this->description;
	}

	/**
	 * @return bool
	 */
	function hasDefaultValue()
	{
		return (bool)$this->useDefaultValue;
	}

	function getDefaultValue()
	{
		if (is_callable($this->defaultValue)) {
			$cb = $this->defaultValue;
			return $cb();
		}
		return $this->defaultValue;
	}

	/**
	 * Zpracování vstupní hodnoty na sanitovanou. Případně to řve, když je blbost.
	 */
	function parse($val)
	{
		return (string)$val;
	}

	/**
	 * Minimální a maximální počet prvků.
	 * @return int
	 */
	function getValence()
	{
		return 1;
	}

}

/**
 * Nenese žádnou hodnotu, je jen příznakem. Obvykle se převede na name => True
 */
class FlagOptionItem extends OptionItem
{

	/**
	 * @param string:1..40
	 * @param string:1..
	 */
	function __construct($name, $description)
	{
		parent::__construct($name, $description);
		$this->setDefaultValue(False);
	}

	function getType()
	{
		return new TypeBool();
	}

	/**
	 * Zpracování vstupní hodnoty na sanitovanou. Případně to řve, když je blbost.
	 */
	function parse($val)
	{
		return !$val;
	}

	/**
	 * Minimální a maximální počet prvků.
	 * @return int
	 */
	function getValence()
	{
		return 0;
	}

}

/**
 * Omezení je definováno typem.
 */
class ConstraintOptionItem extends OptionItem
{

	private $type;

	function __construct(Type $type, $name, $description)
	{
		parent::__construct($name, $description);
		$this->type = $type;
	}

	function parse($val)
	{
		return $this->type->cast($val);
	}

	/**
	 * @return Type
	 */
	function getType()
	{
		return $this->type;
	}

}


text:
<!DOCTYPE html>

    <title>{% block title %}{% endblock %} | AU Web Portal API</title>
    {% block head %}
      <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.css') }}">

    {% endblock %}

AU Web Portal API

      {% set breadcrumb = [
        ('/', 'home', 'Home'),
        ('/test/', 'test', 'Test'),
      ]-%}
      {% set active_page = active_page|default('index') -%}

        {% for href, id, caption in breadcrumb %}
          {% if id == active_page %}

{{ caption }}

          {% elif active_page != 'home' %}

{{ caption }}

          {% endif %}
        {% endfor %}

      {% block content %}
      {% endblock %}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Picea maximowiczii var. senanensis Hayashi

### Remarks
null


text:
namespace BitCoinSharp
{
    public class InventoryItem
    {
        public enum ItemType
        {
            Error,
            Transaction,
            Block
        }

        public ItemType Type { get; private set; }
        public Sha256Hash Hash { get; private set; }

        public InventoryItem(ItemType type, Sha256Hash hash)
        {
            Type = type;
            Hash = hash;
        }

        public override string ToString()
        {
            return Type + ": " + Hash;
        }
    }
}


text:
'use strict';

/**
 *  get and showes  by key fingerprint
 *  TODO: if user is a notary or crytonomimica user - offer to add verification
 */

var controller_name = "cryptonomica.controller.key";

var controller = angular.module(controller_name, []);

controller.controller(controller_name, [
        '$scope',
        '$rootScope',
        '$http',
        'GApi',
        'GAuth',
        'GData',
        '$state',
        '$log',
        '$timeout',
        '$stateParams',
        '$cookies',
        'FileSaver',
        'Blob',
        // 'UserService',
        function showkeyCtrl($scope,
                             $rootScope,
                             $http,
                             GApi,
                             GAuth,
                             GData,
                             $state,
                             $log,
                             $timeout,
                             $stateParams,
                             $cookies,
                             FileSaver,
                             Blob
                             // UserService
        ) {
            //
            GAuth.checkAuth().then(
                function () {
                    $scope.alert = null;
                    $rootScope.getUserData(); // async?
                },
                function () {
                    //$rootScope.getUserData();
                    $log.error("[showkey.controller.js] GAuth.checkAuth() - unsuccessful");
                    $scope.alert = "User not logged in";
                }
            );
            //
            $scope.dateOptions = {
                changeYear: true,
                changeMonth: true,
                yearRange: '1900:-0'};
            //
            $log.info("$stateParams.fingerprint : " + $stateParams.fingerprint);
            var showKey = function () {
                $scope.key = {};
                GApi.executeAuth(
                    'pgpPublicKeyAPI',
                    'getPGPPublicKeyByFingerprint', //
                    {"fingerprint": $stateParams.fingerprint}
                ).then(
                    function (resp) {
                        $log.info("[key.controller.js] showKey() - resp: ");
                        $log.info(resp);
                        $scope.key = resp;
                        $scope.alert = null;
                    },
                    function (error) {
                        $log.error("[key.controller.js] showKey() - error: ");
                        $log.error(error);
                        $scope.alert = error;
                        $scope.key.error = error;
                    }
                );
            };
            showKey();

            $log.info("[key.controller.js] $scope.key: ");
            $log.info($scope.key);
            //
            $scope.download = function (text) {
                var data = new Blob([text], {type: 'text/plain;charset=utf-8'});
                FileSaver.saveAs(data, 'key.asc');
            };
            // key verification:
            $scope.KeyVerificationFormShow = false;
            $scope.KeyVerificationFormShowToggle = function () {
                $scope.KeyVerificationFormShow = !$scope.KeyVerificationFormShow;
            };
            // net.cryptonomica.forms.VerifyPGPPublicKeyForm:
            // private String webSafeString; // ..............1
            // private String verificationInfo; // ...........2
            // private String basedOnDocument; // ............3
            /*------------------------*/
            // net.cryptonomica.returns.VerifyPGPPublicKeyReturn
            // String MessageToUser;
            // VerificationGeneralView verificationGeneralView;
            // PGPPublicKeyGeneralView pgpPublicKeyGeneralView;
            // UserProfileGeneralView userProfileGeneralView;
            /*-------------------------*/
            $scope.VerifyPGPPublicKeyForm = {};
            $scope.verifyPGPPublicKeyFormSubmit = function () {
                if ($scope.KeyVerificationFORM.$valid && $scope.key.cryptonomicaUserId) {
                    verifyKey();
                } else if ($scope.KeyVerificationFORM.$invalid) {
                    $log.error("$scope.KeyVerificationFORM.$valid :"
                        + $scope.KeyVerificationFORM.$valid);
                } else {
                    $log.error("$scope.key.cryptonomicaUserId: " + $scope.key.cryptonomicaUserId);
                }
            };
            var verifyKey = function () {
                $rootScope.progressbar.start();
                //
                $scope.VerifyPGPPublicKeyForm.webSafeString = $stateParams.websafestring;
                // $scope.VerifyPGPPublicKeyForm.verificationInfo - from the form
                // $scope.VerifyPGPPublicKeyForm.basedOnDocument  - from the form
                $log.info("$scope.VerifyPGPPublicKeyForm : ");
                $log.info($scope.VerifyPGPPublicKeyForm);
                //
                GApi.executeAuth(
                    'notaryAPI',
                    'verifyPGPPublicKey',
                    $scope.VerifyPGPPublicKeyForm // net.cryptonomica.forms.VerifyPGPPublicKeyForm
                ).then(
                    function (resp) { // net.cryptonomica.returns.VerifyPGPPublicKeyReturn
                        // String MessageToUser;
                        // VerificationGeneralView verificationGeneralView;
                        // PGPPublicKeyGeneralView pgpPublicKeyGeneralView;
                        // UserProfileGeneralView userProfileGeneralView;
                        $log.info("[key.controller.js] $scope.verifyKey() - resp: ");
                        $log.info(resp);
                        $scope.VerifyPGPPublicKeyForm = {}; // clear form
                        $scope.VerifyPGPPublicKeyReturn = resp;
                        $scope.key = resp.pgpPublicKeyGeneralView;
                        $timeout($rootScope.progressbar.complete(), 1000);
                    },
                    function (error) {
                        $log.error("[key.controller.js] $scope.verifyKey() - error: ");
                        $log.error(error);
                        $scope.verifyKeyError = error;
                        $timeout($rootScope.progressbar.complete(), 1000);
                    }
                );

            }

        }
    ]
);


text:
require 'bundler/setup'
require 'test/unit'
require 'turn/autorun'
require 'shoulda'

$LOAD_PATH << 'lib'

class TestCase < Test::Unit::TestCase
end


text: A BTClickable is the superclass for objects that want to receive clicks and hover events.


text:
package com.google.places.showcase.entity;

import com.google.gson.annotations.SerializedName;

import java.util.List;

/**
 * Place class to use with Google Places APIs
 */
public class Place {

    @SerializedName("formatted_address")
    private String address;

    @SerializedName("icon")
    private String icon;

    @SerializedName("id")
    private String id;

    @SerializedName("place_id")
    private String placeId;

    @SerializedName("name")
    private String name;

    @SerializedName("types")
    private List<String> types;

    @SerializedName("photos")
    private List<PlacePhoto> photos;

    @SerializedName("rating")
    private double rating;

    @SerializedName("international_phone_number")
    private String phone;

    @SerializedName("website")
    private String website;

    @SerializedName("url")
    private String url;

    @SerializedName("geometry")
    private Geometry geometry;

    // getters and setters
    public List<PlacePhoto> getPhotos() {
        return photos;
    }

    public void setPhotos(List<PlacePhoto> photos) {
        this.photos = photos;
    }

    public double getRating() {
        return rating;
    }

    public void setRating(double rating) {
        this.rating = rating;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPlaceId() {
        return placeId;
    }

    public void setPlaceId(String placeId) {
        this.placeId = placeId;
    }

    public String getName() {
        return name;
    }

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

    public List<String> getTypes() {
        return types;
    }

    public void setTypes(List<String> types) {
        this.types = types;
    }

    public PlaceLocation getLocation() {
        if (geometry != null) {
            return geometry.location;
        }
        return null;
    }

    public void setLocation(PlaceLocation location) {
        if (this.geometry == null) {
            this.geometry = new Geometry();
        }
        this.geometry.location = location;
    }
}


text:
'use strict';

function myFunction (name, iceCreamFlavor) {
  console.log(`${name} really likes ${iceCreamFlavor} ice cream.`)
}

let args = ['Gabe', 'Vanilla'];

myFunction(...args);


text:
package org.hisp.dhis.artemis;

/**
 * Constants representing actual queue names.
 * <P>
 * All members of this class are immutable.
 *
 * @author Luciano Fiandesio
 */
public final class Topics
{
    public static final String METADATA_TOPIC_NAME = "dhis2.topic.metadata";

    public static final String AGGREGATE_TOPIC_NAME = "dhis2.topic.aggregate";

    public static final String TRACKER_TOPIC_NAME = "dhis2.topic.tracker";

    public static final String TRACKER_IMPORT_JOB_TOPIC_NAME = "dhis2.jobs.tracker";

    public static final String TRACKER_IMPORT_NOTIFICATION_TOPIC_NAME = "dhis2.jobs.tracker.notifications";

    public static final String TRACKER_IMPORT_RULE_ENGINE_TOPIC_NAME = "dhis2.jobs.tracker.rule.engine";
}


text:
<!doctype html>

    <meta charset="utf-8">

    <title>Do: Managing versions of program code with Git</title>

    <meta name="description" content="A framework for easily creating beautiful presentations using HTML">
    <meta name="author" content="Hakim El Hattab">

    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <link rel="stylesheet" href="css/reveal.min.css">
    <link rel="stylesheet" href="css/theme/moon.css" id="theme">
    <link rel="stylesheet" href="css/git-talk.css" id="theme">

    <link rel="stylesheet" href="lib/css/zenburn.css">

Do: Managing versions of program code with Git

            Ben Holmes, IT Services
 github.com/bdvholmes

Motivation

Playing spot the difference

Image Gareth Bellamy

Common indicators that something is going wrong:

File names have dates in

Files are called things like "old" or "latest"

Whole directories have multiple copies

One person can work at a time

Memory sticks / emails

Source control

Image picsishouldshare

Version control systems

Recording change by change

We want to know

What changed in which files

Who made the change

When the change was made

We might want to have

File locks

Branching

Merging

Tagging

A single, central source of truth

vs

Distributed structure

Git Logo by Jason Long

Key facts

Free and open source

Cheap branching

Distributed

Flexible workflows

Great community

Voodoo magic

Image elasticcamel

Basic concepts in Git

Commits

Lets start with an example

A message to the future

Example

Branches

Tags

Staging area

A basic git workflow

1. Pull changes

2. Make small code changes

3. Commit as you go

Write a message to describe the change you just made

4. Push your changes

Git will try to merge your code automatically

You may need to resolve conflicts

For bigger changes

Create a new branch before you start

Merge the branch back in when you are happy

Eventually you will be able to

Ammend your last commit

Ammend all of your commits

Rewrite history altogether

Make people cry

git push --force

More advanced workflows

Atlassian tutorials

Git tools and clients

The command line

Git gui

Github for mac

Integration

... and many more

GitHub

Git hosting

Free for public repositories

Live demo!!

Honorable mention

Bitbucket

Where to go from here

The Git website

http://git-scm.com/

Online Git tutorial

Command line Git in 15 minutes

http://try.github.io/levels/1/challenges/1

Atlassian do tutorials too...

GitHub

See the code for this talk, fix my typos

https://github.com/bdvholmes/git-intro-talk

Questions?

ben.holmes@it.ox.ac.uk


text:
<?php
require_once 'PHPUnit/Framework.php';
require_once('recess/database/PdoDsnSettings.php');
require_once 'recess/database/sql/RecessDatabaseSqlAllTests.php';
require_once 'recess/database/pdo/RecessDatabasePdoAllTests.php';
require_once 'recess/database/orm/RecessDatabaseOrmAllTests.php';

class RecessDatabaseAllTests
{
    public static function suite()
    {
        $suite = new PHPUnit_Framework_TestSuite('recess.database');

        $suite->addTestSuite(RecessDatabaseSqlAllTests::suite());
 		$suite->addTestSuite(RecessDatabasePdoAllTests::suite());
 		$suite->addTestSuite(RecessDatabaseOrmAllTests::suite());

        return $suite;
    }
}
?>


text:
"""
Analyze the templates for placeholders of this module.
"""
from template_analyzer.djangoanalyzer import get_node_instances
from fluent_contents.models import PlaceholderData
from fluent_contents.templatetags.fluent_contents_tags import PagePlaceholderNode

__all__ = ('get_template_placeholder_data',)

def get_template_placeholder_data(template):
    """
    Return the placeholders found in a template,
    wrapped in a :class:`~fluent_contents.models.containers.PlaceholderData` object.

    This function looks for the :class:`~fluent_contents.templatetags.fluent_contents_tags.PagePlaceholderNode` nodes
    in the template, using the :func:`~template_analyzer.djangoanalyzer.get_node_instances` function
    of `django-template-analyzer <https://github.com/edoburu/django-template-analyzer>`_.

    :param template:  The Template object, or nodelist to scan.
    :rtype: list of :class:`~fluent_contents.models.PlaceholderData`
    """
    # Find the instances.
    nodes = get_node_instances(template, PagePlaceholderNode)

    # Avoid duplicates, wrap in a class.
    names = set()
    result = []
    for pageplaceholdernode in nodes:
        data = PlaceholderData(
            slot=pageplaceholdernode.get_slot(),
            title=pageplaceholdernode.get_title(),
            role=pageplaceholdernode.get_role(),
            fallback_language=pageplaceholdernode.get_fallback_language(),
        )

        if data.slot not in names:
            result.append(data)
            names.add(data.slot)

    return result


text:
@implementation CTCategoryCell

@end


text:
package android.fiddle.house.opengl;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLU;
import android.opengl.GLSurfaceView.Renderer;

public class GlRenderer implements Renderer {

    private Triangle 	triangle;	// the triangle to be drawn

    /** Constructor */
    public GlRenderer() {
        this.triangle = new Triangle();
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        // clear Screen and Depth Buffer
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        // Reset the Modelview Matrix
        gl.glLoadIdentity();

        // Drawing
        gl.glTranslatef(0.0f, 0.0f, -5.0f);		// move 5 units INTO the screen
        // is the same as moving the camera 5 units away
        triangle.draw(gl);						// Draw the triangle

    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        if(height == 0) { 						//Prevent A Divide By Zero By
            height = 1; 						//Making Height Equal One
        }

        gl.glViewport(0, 0, width, height); 	//Reset The Current Viewport
        gl.glMatrixMode(GL10.GL_PROJECTION); 	//Select The Projection Matrix
        gl.glLoadIdentity(); 					//Reset The Projection Matrix

        //Calculate The Aspect Ratio Of The Window
        GLU.gluPerspective(gl, 45.0f, (float)width / (float)height, 0.1f, 100.0f);

        gl.glMatrixMode(GL10.GL_MODELVIEW); 	//Select The Modelview Matrix
        gl.glLoadIdentity(); 					//Reset The Modelview Matrix
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    }
}


text:
class Counters < ActiveRecord::Migration
  def self.up
    create_table :counters do |t|
      t.integer :counter
      t.integer :counter_1_day_ago
      t.integer :counter_2_days_ago
      t.integer :counter_last_day
      t.integer :counter_last_2_days
      t.integer :counter_last_monday
      t.integer :counter_last_tuesday
      t.integer :counter_last_wednesday
      t.string :counter_data, :limit => 2048
    end
  end

  def self.down
    drop_table :counters
  end
end


text: This is the partial for contact.


text:
package org.anddev.andengine.util.modifier;

import org.anddev.andengine.util.modifier.ease.IEaseFunction;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 23:29:22 - 19.03.2010
 */
public abstract class BaseSingleValueSpanModifier<T> extends BaseDurationModifier<T> {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	private final float mFromValue;
	private final float mValueSpan;

	protected final IEaseFunction mEaseFunction;

	// ===========================================================
	// Constructors
	// ===========================================================

	public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue) {
		this(pDuration, pFromValue, pToValue, null, IEaseFunction.DEFAULT);
	}

	public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IEaseFunction pEaseFunction) {
		this(pDuration, pFromValue, pToValue, null, pEaseFunction);
	}

	public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IModifierListener<T> pModifierListener) {
		this(pDuration, pFromValue, pToValue, pModifierListener, IEaseFunction.DEFAULT);
	}

	public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IModifierListener<T> pModifierListener, final IEaseFunction pEaseFunction) {
		super(pDuration, pModifierListener);
		this.mFromValue = pFromValue;
		this.mValueSpan = pToValue - pFromValue;
		this.mEaseFunction = pEaseFunction;
	}

	protected BaseSingleValueSpanModifier(final BaseSingleValueSpanModifier<T> pBaseSingleValueSpanModifier) {
		super(pBaseSingleValueSpanModifier);
		this.mFromValue = pBaseSingleValueSpanModifier.mFromValue;
		this.mValueSpan = pBaseSingleValueSpanModifier.mValueSpan;
		this.mEaseFunction = pBaseSingleValueSpanModifier.mEaseFunction;
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	protected abstract void onSetInitialValue(final T pItem, final float pValue);
	protected abstract void onSetValue(final T pItem, final float pPercentageDone, final float pValue);

	@Override
	protected void onManagedInitialize(final T pItem) {
		this.onSetInitialValue(pItem, this.mFromValue);
	}

	@Override
	protected void onManagedUpdate(final float pSecondsElapsed, final T pItem) {
		final float percentageDone = this.mEaseFunction.getPercentage(this.getSecondsElapsed(), this.mDuration);

		this.onSetValue(pItem, percentageDone, this.mFromValue + percentageDone * this.mValueSpan);
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
<?xml version="1.0" ?>
<xmcda:XMCDA xmlns:xmcda="http://www.decision-deck.org/2016/XMCDA-3.0.2"
			 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			 xsi:schemaLocation="http://www.decision-deck.org/2016/XMCDA-3.0.2 http://www.decision-deck.org/xmcda/_downloads/XMCDA-3.0.2.xsd">
	<categoriesProfiles>
		<categoryProfile>
			<categoryID>C1</categoryID>
			<central>
				<alternativeID>b1d2</alternativeID>
			</central>
		</categoryProfile>
		<categoryProfile>
			<categoryID>C2</categoryID>
			<central>
				<alternativeID>b2d2</alternativeID>
			</central>
		</categoryProfile>
	</categoriesProfiles>
</xmcda:XMCDA>


text:
import sys

print '---------' 'Basic constraints'

from amara import bindery, xml_print
from amara.bindery.model import *

MONTY_XML = """<monty>
  <python spam="eggs">What do you mean "bleh"</python>
  <python ministry="abuse">But I was looking for argument</python>
</monty>"""

doc = bindery.parse(MONTY_XML)

c = constraint(u'@ministry')
try:
    doc.monty.python.xml_model.add_constraint(c, validate=True)
except bindery.BinderyError, e:
    print e

doc.monty.python.xml_attributes[None, u'ministry'] = u'argument'
doc.monty.python.xml_model.add_constraint(c, validate=True)

#print dir(doc)
#print dir(doc.monty.python)

#print doc.monty.python.xml_namespaces[None]
#print doc.xml_namespaces

print
print '---------' 'Attribute constraint class'

doc = bindery.parse(MONTY_XML)

c = attribute_constraint(None, u'ministry', u'nonesuch')
doc.monty.python.xml_model.add_constraint(c, validate=True)

xml_print(doc)

print
print '---------' 'Child element constraint class'

SVG = """<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" baseProfile="full"
    xmlns="http://www.w3.org/2000/svg">
  <title>A pair of lines and a pair of ellipses</title>
  <g>
    <ellipse cx="150" cy="100" rx="100" ry="50"/>
    <line x1="450" y1="50" x2="550" y2="150"/>
  </g>
  <g>
    <title>Rotated shapes</title>
    <ellipse cx="150" cy="300" rx="100" ry="50"
        transform="rotate(20)"/>
    <line x1="350" y1="200" x2="450" y2="300"
        transform="rotate(20)"/>
  </g>
</svg>
"""

from amara.namespaces import *
doc = bindery.parse(SVG)

c = child_element_constraint(SVG_NAMESPACE, u'title', u'[NO TITLE]')
doc.svg.g.xml_model.add_constraint(c, validate=True)

xml_print(doc)

print
print '---------' 'Examplotron model def'

LABEL_MODEL = '''<?xml version="1.0" encoding="utf-8"?>
<labels>
  <label>
    <name>[Addressee name]</name>
    <address>
      <street>[Address street info]</street>
      <city>[City]</city>
      <state>[State abbreviation]</state>
    </address>
  </label>
</labels>
'''

VALID_LABEL_XML = '''<?xml version="1.0" encoding="utf-8"?>
<labels>
  <label>
    <name>Thomas Eliot</name>
    <address>
      <street>3 Prufrock Lane</street>
      <city>Stamford</city>
      <state>CT</state>
    </address>
  </label>
</labels>
'''

INVALID_LABEL_XML = '''<?xml version="1.0" encoding="utf-8"?>
<labels>
  <label>
    <quote>What thou lovest well remains, the rest is dross</quote>
    <name>Ezra Pound</name>
    <address>
      <street>45 Usura Place</street>
      <city>Hailey</city>
      <state>ID</state>
    </address>
  </label>
</labels>
'''

from amara.bindery.model import *
label_model = examplotron_model(LABEL_MODEL)
doc = bindery.parse(VALID_LABEL_XML, model=label_model)
doc.xml_validate()

doc = bindery.parse(INVALID_LABEL_XML, model=label_model)
try:
    doc.xml_validate()
except bindery.BinderyError, e:
    print e

xml_print(doc)

print
print '---------' 'Binding defaults'

LABEL_MODEL = '''<?xml version="1.0" encoding="utf-8"?>
<labels>
  <label>
    <quote>What thou lovest well remains, the rest is dross</quote>
    <name>Ezra Pound</name>
    <address>
      <street>45 Usura Place</street>
      <city>Hailey</city>
      <state>ID</state>
    </address>
  </label>
</labels>
'''

TEST_LABEL_XML = '''<?xml version="1.0" encoding="utf-8"?>
<labels>
  <label>
    <name>Thomas Eliot</name>
    <address>
      <street>3 Prufrock Lane</street>
      <city>Stamford</city>
      <state>CT</state>
    </address>
  </label>
</labels>
'''

#An alternative to fixup that updates the binding object behavior without updating the XML itself
#Note: you can choose to combine binding defaults with fixup, if you like, but many usage patterns will tend to use one or the other: either you want a mechnism to normalize the XML itself, or a mechanism for smooth handling of non-normalized XML

#doc = bindery.parse(LABEL_XML)
#doc.labels.label.xml_model.set_default_value(None, u'quote', None)

from amara.bindery.model import *
label_model = examplotron_model(LABEL_MODEL)
doc = bindery.parse(TEST_LABEL_XML, model=label_model)
print doc.labels.label.quote #None, rather than raising AttributeError
#doc.xml_validate()

sys.exit(0)

doc = bindery.parse(INVALID_LABEL_XML, model=label_model)
doc.labels.label.xml_model.debug(doc.labels.label)
doc.labels.label.xml_model.validate()
doc.xml_model.validate()

print
print '---------' 'Bindery and operator'

RSS = 'http://feeds.feedburner.com/ClevelandClinicHealthTalkPodcast'
ATOM1 = 'http://uche.ogbuji.net/tech/publications.atom'

import operator
import itertools
from amara import bindery

ATOM1 = 'http://zepheira.com/news/atom/entries/'
ATOM2 = 'http://ma.gnolia.com/atom/full/people/Uche'

doc1 = bindery.parse(ATOM1)
doc2 = bindery.parse(ATOM2)
combined = itertools.chain(*[doc.feed.entry for doc in (doc1, doc2)])
for node in sorted(combined, key=operator.attrgetter('updated')):
    print node.title

print '---------' 'Merge XBEL'

BM1 = 'bm1.xbel'
BM2 = 'bm2.xbel'
from amara import bindery, xml_print

def merge_folders(folder1, folder2):
    #Yes, the list must be copied to avoid mutate-while-iterate bugs
    for child in folder2.xml_select('*'):
        #No need to copy title element
        if child.xml_qname == u'title': continue
        elif child.xml_qname == u'folder':
            for a_folder in folder1.folder:
                if unicode(child.title) == unicode(a_folder.title):
                    merge_folders(a_folder, child)
                    break
            else:
                folder1.xml_append(child)
        else:
            folder1.xml_append(child)
    return

def xbel_merge(xbel1, xbel2):
    for child in xbel2.xml_select('*'):
        if child.xml_qname == u'folder':
            for a_folder in xbel1.folder:
                if unicode(child.title) == unicode(a_folder.title):
                    merge_folders(a_folder, child)
                    break
            else:
                xbel1.xml_append(child)
        elif child.xml_qname == u'bookmark':
            xbel1.xml_append(child)
    return

doc1 = bindery.parse(BM1)
doc2 = bindery.parse(BM2)
xbel_merge(doc1.xbel, doc2.xbel)
xml_print(doc1, indent=True)

print
print '---------' 'Merge XBEL by grouping iterators'

BM1 = 'bm1.xbel'
BM2 = 'bm2.xbel'
import itertools
import functools
from amara import bindery, xml_print
from amara.bindery.util import property_str_getter

title_getter = functools.partial(property_str_getter, 'title')

def merge(f1, f2):
    folders = sorted(itertools.chain(f1.folder or [], f2.folder or []),
                     key=title_getter)
    folder_groups = itertools.groupby(folders, title_getter)
    for ftitle, folders in folder_groups:
        main = folders.next()
        rest = list(folders)
        for f in rest:
            merge(main, f)
        if main.xml_parent != f1:
            f1.xml_append(main)
    #All non-folder, non-title elements
    for e in f2.xml_select(u'*[not(self::folder or self::title)]'):
        f1.xml_append(e)
    return

doc1 = bindery.parse(BM1)
doc2 = bindery.parse(BM2)
merge(doc1.xbel, doc2.xbel)
xml_print(doc1, indent=True)


text:
package com.gs.obevocomparer.data;

import java.io.Serializable;
import java.util.Map;
import java.util.Set;

public interface CatoDataSchema extends Serializable {

    CatoDataObject createDataObject();

    Set<String> getFields();

    Map<String, String> getMappedFields();
}


text:
package com.lingganhezi.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.lingganhezi.myapp.AppContext;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.util.LruCache;
import android.util.Log;

public class BitmapCache implements ImageCache {
	private final static String TAG = BitmapCache.class.getSimpleName();

	private final static int APP_VERSION = 1;// 这里长期使用同一个缓存,所以这里版本号不变
	private final static String DEFAULT_CACHE_DIR = "Image";
	private final static int DISK_CACHE_SIZE = 1024 * 1024 * 100; // 100MB
	private final static int MEMORY_CACHE_SIZE = 1024 * 1024 * 20; // 20MB

	private static BitmapCache mInstance;
	private DiskLruCache cacheL2;
	private LruCache<String, Bitmap> cacheL1;

	/**
	 * 处理保存用的线程池
	 */
	private ExecutorService mThreadPool = Executors.newSingleThreadExecutor();

	public static BitmapCache getInstance() {
		if (mInstance == null) {
			mInstance = new BitmapCache();
		}
		return mInstance;
	}

	private BitmapCache() {
		cacheL1 = new LruCache<String, Bitmap>(MEMORY_CACHE_SIZE);
		File cacheDir = new File(AppContext.getInstance().getCacheDir(), DEFAULT_CACHE_DIR);
		try {
			cacheL2 = DiskLruCache.open(cacheDir, APP_VERSION, 1, DISK_CACHE_SIZE);
		} catch (IOException e) {
			Log.e(TAG, "openCache", e);
		}
	}

	@Override
	public Bitmap getBitmap(String url) {
		Bitmap b = cacheL1.get(url);
		if (b == null) {
			b = getDataFromCacheL2(url);
		}
		return b;
	}

	@Override
	public void putBitmap(final String url, final Bitmap bitmap) {
		mThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				cacheL1.put(url, bitmap);
				saveDataToCacheL2(url, bitmap);
			}
		});
	}

	/**
	 * 保存的磁盘
	 *
	 * @param key
	 * @param bitmap
	 */
	private void saveDataToCacheL2(String key, Bitmap bitmap) {
		try {
			String pKey = StringHelper.MD5Encode(key);
			DiskLruCache.Editor editor = cacheL2.edit(pKey);
			if (editor != null) {
				OutputStream outputStream = editor.newOutputStream(0);
				boolean isSuccessfull = true;
				try {
					bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
				} catch (Exception e) {
					isSuccessfull = false;
				}
				if (isSuccessfull) {
					editor.commit();
				} else {
					editor.abort();
				}
				cacheL2.flush();
			}
		} catch (Exception e) {
			Log.w(TAG, "saveDataToCacheL2");
		}

	}

	// 从DiskLruCache中读取数据
	private Bitmap getDataFromCacheL2(String key) {
		Bitmap bitmap = null;
		try {
			String pKey = StringHelper.MD5Encode(key);
			// 第二步:依据key获取到其对应的snapshot
			DiskLruCache.Snapshot snapshot = cacheL2.get(pKey);
			if (snapshot != null) {
				// 第三步:从snapshot中获取到InputStream
				InputStream inputStream = snapshot.getInputStream(0);
				bitmap = BitmapFactory.decodeStream(inputStream);
			}
		} catch (Exception e) {
			Log.w(TAG, "getDataFroCacheL2");
		}
		return bitmap;

	}

	/**
	 * 清除磁盘缓存
	 *
	 * @throws IOException
	 */
	public void cleanCacheL2() throws IOException {
		cacheL2.delete();
	}
}


text:
package io.fabric8.mq.controller.camel;

import org.apache.activemq.command.Message;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Processor;
import org.apache.camel.component.jms.JmsBinding;
import org.apache.camel.impl.DefaultConsumer;

public class ControllerConsumer extends DefaultConsumer implements MessageInterceptor {
    private final JmsBinding jmsBinding = new JmsBinding();

    public ControllerConsumer(Endpoint endpoint, Processor processor) {
        super(endpoint, processor);
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();
        ((ControllerEndpoint) getEndpoint()).addMessageInterceptor(this);
    }

    @Override
    protected void doStop() throws Exception {
        ((ControllerEndpoint) getEndpoint()).removeMessageInterceptor(this);
        super.doStop();
    }

    @Override
    public void intercept(MessageRouter messageRouter, Message message) {
        Exchange exchange = getEndpoint().createExchange(ExchangePattern.InOnly);

        exchange.setIn(new ControllerJmsMessage(messageRouter, (javax.jms.Message) message, jmsBinding));
        exchange.setProperty(Exchange.BINDING, jmsBinding);
        try {
            getProcessor().process(exchange);
        } catch (Exception e) {
            exchange.setException(e);
        }

        if (exchange.getException() != null) {
            getExceptionHandler().handleException("Error processing intercepted message: " + message, exchange, exchange.getException());
        }
    }

}


text:
<?php

	//Create connection with the database
	$dbserver = "localhost";
	$dbusername = "root";
	$dbpassword = "root";
	$dbname = "cascades_clinic";

	$db = new mysqli($dbserver, $dbusername, $dbpassword, $dbname);

?>


text:
                {{ $index + 1 }}
                {{ listener | userFullName }}


text:
package com.WiseHollow.Fundamentals.Commands;

import com.WiseHollow.Fundamentals.DataCollection.PlayerData;
import com.WiseHollow.Fundamentals.Language;
import com.WiseHollow.Fundamentals.Settings;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

/**
 * Created by John on 10/13/2016.
 */
public class CommandSetHome implements CommandExecutor
{
    @Override
    public boolean onCommand(CommandSender sender, Command command, String cmd, String[] args)
    {
        if (!(sender instanceof Player))
        {
            sender.sendMessage(Language.YouMustBeLoggedIn);
            return true;
        }

        Player player = (Player) sender;
        if (!sender.hasPermission("Fundamentals.SetHome"))
        {
            player.sendMessage(Language.DoesNotHavePermission);
            return true;
        }

        if (args.length == 0)
            return false;

        PlayerData pd = PlayerData.GetPlayerData(player);

        int amount = pd.getHomes().size();
        if (!Settings.HasPermissionForHomeAmount(player, amount + 1))
        {
            player.sendMessage(Language.PREFIX_WARNING + "You do not have permission for more homes.");
            return true;
        }

        String name = args[0];
        pd.setHome(name);

        player.sendMessage(Language.PREFIX + "Home has been set!");
        return true;
    }
}


text:
module Myer
  class Error < StandardError; end

  class CmdFailed < Error; end
  class DecryptionFailed < Error; end
end


text:
package org.assertj.core.error;

/**
 * Creates an error message indicating that an assertion that verifies a group of elements is not empty failed. A group of
 * elements can be a collection, an array or a {@code String}.
 *
 * @author Alex Ruiz
 */
public class ShouldNotBeEmpty extends BasicErrorMessageFactory {

  private static final ShouldNotBeEmpty INSTANCE = new ShouldNotBeEmpty();

  /**
   * Returns the singleton instance of this class.
   * @return the singleton instance of this class.
   */
  public static ErrorMessageFactory shouldNotBeEmpty() {
    return INSTANCE;
  }

  private ShouldNotBeEmpty() {
    super("%nExpecting actual not to be empty");
  }

}