text:
/* */
"format cjs";
/*
 * L.Control.Attribution is used for displaying attribution on the map (added by default).
 */

L.Control.Attribution = L.Control.extend({
	options: {
		position: 'bottomright',
		prefix: 'Leaflet'
	},

	initialize: function (options) {
		L.setOptions(this, options);

		this._attributions = {};
	},

	onAdd: function (map) {
		this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
		L.DomEvent.disableClickPropagation(this._container);

		for (var i in map._layers) {
			if (map._layers[i].getAttribution) {
				this.addAttribution(map._layers[i].getAttribution());
			}
		}

		map
		    .on('layeradd', this._onLayerAdd, this)
		    .on('layerremove', this._onLayerRemove, this);

		this._update();

		return this._container;
	},

	onRemove: function (map) {
		map
		    .off('layeradd', this._onLayerAdd)
		    .off('layerremove', this._onLayerRemove);

	},

	setPrefix: function (prefix) {
		this.options.prefix = prefix;
		this._update();
		return this;
	},

	addAttribution: function (text) {
		if (!text) { return; }

		if (!this._attributions[text]) {
			this._attributions[text] = 0;
		}
		this._attributions[text]++;

		this._update();

		return this;
	},

	removeAttribution: function (text) {
		if (!text) { return; }

		if (this._attributions[text]) {
			this._attributions[text]--;
			this._update();
		}

		return this;
	},

	_update: function () {
		if (!this._map) { return; }

		var attribs = [];

		for (var i in this._attributions) {
			if (this._attributions[i]) {
				attribs.push(i);
			}
		}

		var prefixAndAttribs = [];

		if (this.options.prefix) {
			prefixAndAttribs.push(this.options.prefix);
		}
		if (attribs.length) {
			prefixAndAttribs.push(attribs.join(', '));
		}

		this._container.innerHTML = prefixAndAttribs.join(' | ');
	},

	_onLayerAdd: function (e) {
		if (e.layer.getAttribution) {
			this.addAttribution(e.layer.getAttribution());
		}
	},

	_onLayerRemove: function (e) {
		if (e.layer.getAttribution) {
			this.removeAttribution(e.layer.getAttribution());
		}
	}
});

L.Map.mergeOptions({
	attributionControl: true
});

L.Map.addInitHook(function () {
	if (this.options.attributionControl) {
		this.attributionControl = (new L.Control.Attribution()).addTo(this);
	}
});

L.control.attribution = function (options) {
	return new L.Control.Attribution(options);
};

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using HockeyApp.Models.Users;

namespace HockeyApp.Models.Posts
{
    [Table("ReplyVotes", Schema = "post")]
    public class ReplyVote
    {
        [Key, Column(Order = 0)]
        public long ReplyId { get; set; }
        public virtual Reply Reply { get; set; }

        [Key, Column(Order = 1)]
        public long UserId { get; set; }
        public virtual User User { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime VoteDate { get; set; }

        public bool Vote { get; set; }
    }
}


text:
package game

type Effect interface{}

type EffectWillAttach interface {
	EffectWillAttach(Game) error
}

type EffectDidAttach interface {
	EffectDidAttach(Game) error
}

type EffectWillDetach interface {
	EffectWillDetach(Game) error
}

type EffectDidDetach interface {
	EffectDidDetach(Game) error
}


text:
<?php

namespace Kunstmaan\TranslatorBundle\Tests\Service\Importer;

use Kunstmaan\TranslatorBundle\Model\Import\ImportCommand;
use Kunstmaan\TranslatorBundle\Tests\unit\WebTestCase;
use Symfony\Component\HttpKernel\Kernel;

class ImportCommandHandlerTest extends WebTestCase
{
    private $importCommandHandler;

    public function setUp()
    {
        static::bootKernel(['test_case' => 'TranslatorBundleTest', 'root_config' => 'config.yaml']);
        $container = static::$kernel->getContainer();
        static::loadFixtures($container);

        $this->importCommandHandler = $container->get('kunstmaan_translator.service.importer.command_handler');
    }

    /**
     * @group handler
     */
    public function testExecuteImportCommand()
    {
        $importCommand = new ImportCommand();
        $importCommand
            ->setForce(false)
            ->setLocales(false)
            ->setGlobals(true)
            ->setDefaultBundle(false);

        $this->assertEquals(7, $this->importCommandHandler->executeImportCommand($importCommand));
    }

    public function testdetermineLocalesToImport()
    {
        $importCommand = new ImportCommand();
        $importCommand
            ->setForce(false)
            ->setLocales(false)
            ->setGlobals(true)
            ->setDefaultBundle(false);

        $locales = $this->importCommandHandler->determineLocalesToImport($importCommand);
        $this->assertEquals(array('nl', 'en', 'de'), $locales);
    }

    public function testParseRequestedLocalesMulti()
    {
        $locale = 'nl,De,   FR';
        $expectedArray = array('nl', 'de', 'fr');
        $locales = $this->importCommandHandler->parseRequestedLocales($locale);
        $this->assertEquals($expectedArray, $locales);
    }

    public function testParseRequestedLocalesSingle()
    {
        $locale = 'dE';
        $expectedArray = array('de');
        $locales = $this->importCommandHandler->parseRequestedLocales($locale);
        $this->assertEquals($expectedArray, $locales);
    }

    public function testParseRequestedLocalesArray()
    {
        $locale = array('dE', 'NL', 'es');
        $expectedArray = array('de', 'nl', 'es');
        $locales = $this->importCommandHandler->parseRequestedLocales($locale);
        $this->assertEquals($expectedArray, $locales);
    }

    /**
     * @group legacy
     */
    public function testImportBundleTranslationFiles()
    {
        if (Kernel::VERSION_ID >= 40000) {
            $this->markTestSkipped('Skip symfony 3 test');
        }

        $importCommand = new ImportCommand();
        $importCommand
            ->setForce(false)
            ->setLocales(false)
            ->setGlobals(true)
            ->setDefaultBundle('own');

        $this->assertEquals(0, $this->importCommandHandler->importBundleTranslationFiles($importCommand));
    }

    public function testImportSf4TranslationFiles()
    {
        if (Kernel::VERSION_ID < 40000) {
            $this->markTestSkipped('Skip symfony 4 test');
        }

        $importCommand = new ImportCommand();
        $importCommand
            ->setForce(false)
            ->setLocales(false)
            ->setGlobals(true)
            ->setDefaultBundle('own');

        $this->assertEquals(7, $this->importCommandHandler->importBundleTranslationFiles($importCommand));
    }
}


text:
<readable><title>2561319255_ce5ede291e</title><content>
A girl is jumping in the air while holding an orange and white guitar .
A girl with a guitar .
A young barefooted girl leaps in the air while playing a toy guitar .
A young girl jumping with a Guitar Hero guitar
A young girl jumps while playing a red and white guitar .
</content></readable>


text:
Back

Messages

        <textarea placeholder="Message"></textarea>Send

Sunday, Feb 9,12:58

Hey Cortana

Cortana

Hi, what can I help?

Wednesday, Feb 12,19:33

I want to add a contact.

Cortana

Great, here you are.

Cortana

Add contact

Phone

                    <input type="tel" placeholder="Phone"/>

Cool

Can you adjust volume for me?

Cortana

Volume control

Volume

                      <input type="range" min="0" max="100" value="50" step="0.1"/>

Cool, list my todo list.

Cortana

TODO list

                    <input type="checkbox" name="ks-checkbox" value="Books" checked="checked"/>

Read a books

                    <input type="checkbox" name="ks-checkbox" value="Movies"/>

Watch a movies

                    <input type="checkbox" name="ks-checkbox" value="Food"/>

Tast food

                    <input type="checkbox" name="ks-checkbox" value="Drinks"/>

Have some drinks

Done, thanks, Bye!

Cortana

My pleasure! Byebye!

Delivered 1 week ago


text:
require 'action_view/helpers'

class ParsedItem
	include ActionView::Helpers
	include Scraper

	attr_reader :number, :type, :ward, :title,
							:sections, :recommendations

	# TO DO:
	# 	1. Create proper association between item and ward

	def initialize(item_number, item)
		@item            = item

		@number          = item_number
		@item_type_id    = find_item_type_id
		@ward            = find_ward
		@title           = find_item_title
		@sections        = hash_sections(raw_html)
		@sections[:ward] = @ward

		@item 					 = nil
	end

	def to_h
		{
			number:       @number,
			item_type_id: @item_type_id,
			title:        @title,
			sections:     @sections,
		}
	end

	private
	attr_reader :item
	def find_item_type_id
		type = item.xpath("//table[@class='border']/tr/td/p/font").first.text.capitalize.chop
		ItemType.where("name = ?", type).first.id
	end

	def find_ward
		item.xpath("//table[@class='border']/tr/td/p/font")
				.last
				.text
				.chop
				.sub("Ward:", "")
				.split(", ")
				.map { |i| i.to_i unless i == "All"; i }
	end

	def find_item_title
		item.xpath('//table/tr/td/font/b').first.text
	end

	def raw_html
		item_tables = item.xpath('//table')
		item.xpath('//table')[2..item_tables.length]
	end

	def hash_sections(contents)

		sections = Hash.new('')
		current_section = ""

		contents.css('td').map do |node|
			if node.css('p').length > 0
				sections[current_section] << node.css('p')
																				 .map(&:text)
																				 .reject(&:blank?)
																				 .join("\n\n")
			elsif is_header?(node)
				current_section = node.text
				sections[current_section] = ""
			else
				content = node.to_s
				sections[current_section] <<  sanitize(whitewash(content), tags: %w(div p a span br))
			end
		end.flatten
		sections
	end

	def whitewash(section)
		Loofah.fragment(section).scrub!(:whitewash).to_s
	end

	def is_header?(node)
		is_bold?(node) && !is_italic?(node) && match_keywords?(node)
	end

	def is_bold?(node)
		node.css('b').length > 0
	end

	def is_italic?(node)
		node.css('i').length > 0
	end

	def match_keywords?(node)
		keywords = [
			"Recommendations",
			"Decision Advice and Other Information",
			"Origin",
			"Summary",
			"Background Information",
			"Speakers",
			"Communications",
			"Declared Interests"
		]

		keywords.any? { |keyword| node.text[keyword] }
	end

end


text:
require 'spec_helper'
describe Chef::Provider::Git do

  before(:each) do
    STDOUT.stub(:tty?).and_return(true)
    Chef::Log.level = :info

    @current_resource = Chef::Resource::Git.new("web2.0 app")
    @current_resource.revision("d35af14d41ae22b19da05d7d03a0bafc321b244c")

    @resource = Chef::Resource::Git.new("web2.0 app")
    @resource.repository "git://github.com/opscode/chef.git"
    @resource.destination "/my/deploy/dir"
    @resource.revision "d35af14d41ae22b19da05d7d03a0bafc321b244c"
    @node = Chef::Node.new
    @events = Chef::EventDispatch::Dispatcher.new
    @run_context = Chef::RunContext.new(@node, {}, @events)
    @provider = Chef::Provider::Git.new(@resource, @run_context)
    @provider.current_resource = @current_resource
  end

  context "determining the revision of the currently deployed checkout" do

    before do
      @stdout = double("standard out")
      @stderr = double("standard error")
      @exitstatus = double("exitstatus")
    end

    it "sets the current revision to nil if the deploy dir does not exist" do
      ::File.should_receive(:exist?).with("/my/deploy/dir/.git").and_return(false)
      @provider.find_current_revision.should be_nil
    end

    it "determines the current revision when there is one" do
      ::File.should_receive(:exist?).with("/my/deploy/dir/.git").and_return(true)
      @stdout = "9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13\n"
      @provider.should_receive(:shell_out!).with('git rev-parse HEAD', {:cwd => '/my/deploy/dir', :returns => [0,128]}).and_return(double("ShellOut result", :stdout => @stdout))
      @provider.find_current_revision.should eql("9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13")
    end

    it "gives the current revision as nil when there is no current revision" do
      ::File.should_receive(:exist?).with("/my/deploy/dir/.git").and_return(true)
      @stderr = "fatal: Not a git repository (or any of the parent directories): .git"
      @stdout = ""
      @provider.should_receive(:shell_out!).with('git rev-parse HEAD', :cwd => '/my/deploy/dir', :returns => [0,128]).and_return(double("ShellOut result", :stdout => "", :stderr => @stderr))
      @provider.find_current_revision.should be_nil
    end
  end

  it "creates a current_resource with the currently deployed revision when a clone exists in the destination dir" do
    @provider.stub(:find_current_revision).and_return("681c9802d1c62a45b490786c18f0b8216b309440")
    @provider.load_current_resource
    @provider.current_resource.name.should eql(@resource.name)
    @provider.current_resource.revision.should eql("681c9802d1c62a45b490786c18f0b8216b309440")
  end

  it "keeps the node and resource passed to it on initialize" do
    @provider.node.should equal(@node)
    @provider.new_resource.should equal(@resource)
  end

  context "resolving revisions to a SHA" do

    before do
      @git_ls_remote = "git ls-remote \"git://github.com/opscode/chef.git\" "
    end

    it "returns resource.revision as is if revision is already a full SHA" do
      @provider.target_revision.should eql("d35af14d41ae22b19da05d7d03a0bafc321b244c")
    end

    it "converts resource.revision from a tag to a SHA" do
      @resource.revision "v1.0"
      @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" +
                 "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n")
      @provider.should_receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout))
      @provider.target_revision.should eql("503c22a5e41f5ae3193460cca044ed1435029f53")
    end

    it "converts resource.revision from an annotated tag to the tagged SHA (not SHA of tag)" do
      @resource.revision "v1.0"
      @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" +
                 "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n" +
                 "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0^{}\n")
      @provider.should_receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout))
      @provider.target_revision.should eql("663c22a5e41f5ae3193460cca044ed1435029f53")
    end

    it "raises an invalid remote reference error if you try to deploy from ``origin'' and assertions are run" do
      @resource.revision "origin/"
      @provider.action = :checkout
      @provider.define_resource_requirements
      ::File.stub(:directory?).with("/my/deploy").and_return(true)
      lambda {@provider.process_resource_requirements}.should raise_error(Chef::Exceptions::InvalidRemoteGitReference)
    end

    it "raises an unresolvable git reference error if the revision can't be resolved to any revision and assertions are run" do
      @resource.revision "FAIL, that's the revision I want"
      @provider.action = :checkout
      @provider.should_receive(:shell_out!).and_return(double("ShellOut result", :stdout => "\n"))
      @provider.define_resource_requirements
      lambda { @provider.process_resource_requirements }.should raise_error(Chef::Exceptions::UnresolvableGitReference)
    end

    it "does not raise an error if the revision can't be resolved when assertions are not run" do
      @resource.revision "FAIL, that's the revision I want"
      @provider.should_receive(:shell_out!).and_return(double("ShellOut result", :stdout => "\n"))
      @provider.target_revision.should == nil
    end

    it "does not raise an error when the revision is valid and assertions are run." do
      @resource.revision "0.8-alpha"
      @stdout = "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n"
      @provider.should_receive(:shell_out!).with(@git_ls_remote + "\"0.8-alpha*\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout))
      @provider.action = :checkout
      ::File.stub(:directory?).with("/my/deploy").and_return(true)
      @provider.define_resource_requirements
      lambda { @provider.process_resource_requirements }.should_not raise_error
    end

    it "gives the latest HEAD revision SHA if nothing is specified" do
      @stdout =<<-SHAS
28af684d8460ba4793eda3e7ac238c864a5d029a\tHEAD
503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha
28af684d8460ba4793eda3e7ac238c864a5d029a\trefs/heads/master
c44fe79bb5e36941ce799cee6b9de3a2ef89afee\trefs/tags/0.5.2
14534f0e0bf133dc9ff6dbe74f8a0c863ff3ac6d\trefs/tags/0.5.4
d36fddb4291341a1ff2ecc3c560494e398881354\trefs/tags/0.5.6
9e5ce9031cbee81015de680d010b603bce2dd15f\trefs/tags/0.6.0
9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13\trefs/tags/0.6.2
014a69af1cdce619de82afaf6cdb4e6ac658fede\trefs/tags/0.7.0
fa8097ff666af3ce64761d8e1f1c2aa292a11378\trefs/tags/0.7.2
44f9be0b33ba5c10027ddb030a5b2f0faa3eeb8d\trefs/tags/0.7.4
d7b9957f67236fa54e660cc3ab45ffecd6e0ba38\trefs/tags/0.7.8
b7d19519a1c15f1c1a324e2683bd728b6198ce5a\trefs/tags/0.7.8^{}
ebc1b392fe7e8f0fbabc305c299b4d365d2b4d9b\trefs/tags/chef-server-package
SHAS
      @resource.revision ''
      @provider.should_receive(:shell_out!).with(@git_ls_remote + "\"HEAD\"", {:log_tag=>"git[web2.0 app]"}).and_return(double("ShellOut result", :stdout => @stdout))
      @provider.target_revision.should eql("28af684d8460ba4793eda3e7ac238c864a5d029a")
    end
  end

  it "responds to :revision_slug as an alias for target_revision" do
    @provider.should respond_to(:revision_slug)
  end

  context "with an ssh wrapper" do
    let(:deploy_user)  { "deployNinja" }
    let(:wrapper)      { "do_it_this_way.sh" }
    let(:expected_cmd) { 'git clone  "git://github.com/opscode/chef.git" "/my/deploy/dir"' }
    let(:default_options) do
      {
        :user => deploy_user,
        :environment => { "GIT_SSH" => wrapper, "HOME" => "/home/deployNinja" },
        :log_tag => "git[web2.0 app]"
      }
    end
    before do
      @resource.user deploy_user
      @resource.ssh_wrapper wrapper
      Etc.stub(:getpwnam).and_return(double("Struct::Passwd", :name => @resource.user, :dir => "/home/deployNinja"))
    end
    context "without a timeout set" do
      it "clones a repo with default git options" do
        @provider.should_receive(:shell_out!).with(expected_cmd, default_options)
        @provider.clone
      end
    end
    context "with a timeout set" do
      let (:seconds) { 10 }
      before { @resource.timeout(seconds) }
      it "clones a repo with amended git options" do
        @provider.should_receive(:shell_out!).with(expected_cmd, default_options.merge(:timeout => seconds))
        @provider.clone
      end
    end
    context "with a specific home" do
      let (:override_home) do
        {"HOME" => "/home/masterNinja"}
      end
      let(:overrided_options) do
        {
          :user => deploy_user,
          :environment => { "GIT_SSH" => wrapper, "HOME" => "/home/masterNinja" },
          :log_tag => "git[web2.0 app]"
        }
      end
      before do
        @resource.environment(override_home)
      end
      before { @resource.environment(override_home) }
      it "clones a repo with amended git options with specific home" do
        @provider.should_receive(:shell_out!).with(expected_cmd, overrided_options)
        @provider.clone
      end
    end
  end

  it "runs a clone command with escaped destination" do
    @resource.user "deployNinja"
    Etc.stub(:getpwnam).and_return(double("Struct::Passwd", :name => @resource.user, :dir => "/home/deployNinja"))
    @resource.destination "/Application Support/with/space"
    @resource.ssh_wrapper "do_it_this_way.sh"
    expected_cmd = "git clone  \"git://github.com/opscode/chef.git\" \"/Application Support/with/space\""
    @provider.should_receive(:shell_out!).with(expected_cmd, :user => "deployNinja",
                                                :environment =>{"GIT_SSH"=>"do_it_this_way.sh",
                                                                "HOME" => "/home/deployNinja"},
                                                :log_tag => "git[web2.0 app]")
    @provider.clone
  end

  it "compiles a clone command using --depth for shallow cloning" do
    @resource.depth 5
    expected_cmd = "git clone --depth 5 \"git://github.com/opscode/chef.git\" \"/my/deploy/dir\""
    @provider.should_receive(:shell_out!).with(expected_cmd, :log_tag => "git[web2.0 app]")
    @provider.clone
  end

  it "compiles a clone command with a remote other than ``origin''" do
    @resource.remote "opscode"
    expected_cmd = "git clone -o opscode \"git://github.com/opscode/chef.git\" \"/my/deploy/dir\""
    @provider.should_receive(:shell_out!).with(expected_cmd, :log_tag => "git[web2.0 app]")
    @provider.clone
  end

  it "runs a checkout command with default options and uses -B to reset branches if necessary" do
    expected_cmd = 'git checkout -B deploy d35af14d41ae22b19da05d7d03a0bafc321b244c'
    @provider.should_receive(:shell_out!).with(expected_cmd, :cwd => "/my/deploy/dir",
                                                             :log_tag => "git[web2.0 app]")
    @provider.checkout
  end

  it "runs an enable_submodule command" do
    @resource.enable_submodules true
    expected_cmd = "git submodule sync"
    @provider.should_receive(:shell_out!).with(expected_cmd, :cwd => "/my/deploy/dir",
                                                             :log_tag => "git[web2.0 app]")
    expected_cmd = "git submodule update --init --recursive"
    @provider.should_receive(:shell_out!).with(expected_cmd, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
    @provider.enable_submodules
  end

  it "does nothing for enable_submodules if resource.enable_submodules #=> false" do
    @provider.should_not_receive(:shell_out!)
    @provider.enable_submodules
  end

  it "runs a sync command with default options" do
    @provider.should_receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository)
    expected_cmd = "git fetch origin && git fetch origin --tags && git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c"
    @provider.should_receive(:shell_out!).with(expected_cmd, :cwd=> "/my/deploy/dir", :log_tag => "git[web2.0 app]")
    @provider.fetch_updates
  end

  it "runs a sync command with the user and group specified in the resource" do
    @resource.user("whois")
    Etc.stub(:getpwnam).and_return(double("Struct::Passwd", :name => @resource.user, :dir => "/home/whois"))
    @resource.group("thisis")
    @provider.should_receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository)
    expected_cmd = "git fetch origin && git fetch origin --tags && git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c"
    @provider.should_receive(:shell_out!).with(expected_cmd, :cwd => "/my/deploy/dir",
                                                :user => "whois", :group => "thisis",
                                                :log_tag => "git[web2.0 app]",
                                                :environment=>{"HOME"=>"/home/whois"})
    @provider.fetch_updates
  end

  it "configures remote tracking branches when remote is ``origin''" do
    @resource.remote "origin"
    @provider.should_receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository)
    fetch_command = "git fetch origin && git fetch origin --tags && git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c"
    @provider.should_receive(:shell_out!).with(fetch_command, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
    @provider.fetch_updates
  end

  it "configures remote tracking branches when remote is not ``origin''" do
    @resource.remote "opscode"
    @provider.should_receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository)
    fetch_command = "git fetch opscode && git fetch opscode --tags && git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c"
    @provider.should_receive(:shell_out!).with(fetch_command, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
    @provider.fetch_updates
  end

  context "configuring remote tracking branches" do

    it "checks if a remote with this name already exists" do
      command_response = double('shell_out')
      command_response.stub(:exitstatus) { 1 }
      expected_command = "git config --get remote.#{@resource.remote}.url"
      @provider.should_receive(:shell_out!).with(expected_command,
                                                 :cwd => "/my/deploy/dir",
                                                 :log_tag => "git[web2.0 app]",
                                                 :returns => [0,1,2]).and_return(command_response)
      add_remote_command = "git remote add #{@resource.remote} #{@resource.repository}"
      @provider.should_receive(:shell_out!).with(add_remote_command,
                                                 :cwd => "/my/deploy/dir",
                                                 :log_tag => "git[web2.0 app]")
      @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
    end

    it "runs the config with the user and group specified in the resource" do
      @resource.user("whois")
      @resource.group("thisis")
      Etc.stub(:getpwnam).and_return(double("Struct::Passwd", :name => @resource.user, :dir => "/home/whois"))
      command_response = double('shell_out')
      command_response.stub(:exitstatus) { 1 }
      expected_command = "git config --get remote.#{@resource.remote}.url"
      @provider.should_receive(:shell_out!).with(expected_command,
                                                 :cwd => "/my/deploy/dir",
                                                 :log_tag => "git[web2.0 app]",
                                                 :user => "whois",
                                                 :group => "thisis",
                                                 :environment=>{"HOME"=>"/home/whois"},
                                                 :returns => [0,1,2]).and_return(command_response)
      add_remote_command = "git remote add #{@resource.remote} #{@resource.repository}"
      @provider.should_receive(:shell_out!).with(add_remote_command,
                                                 :cwd => "/my/deploy/dir",
                                                 :log_tag => "git[web2.0 app]",
                                                 :user => "whois",
                                                 :group => "thisis",
                                                 :environment=>{"HOME"=>"/home/whois"})
      @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
    end

    describe "when a remote with a given name hasn't been configured yet" do
      it "adds a new remote " do
        command_response = double('shell_out')
        command_response.stub(:exitstatus) { 1 }
        check_remote_command = "git config --get remote.#{@resource.remote}.url"
        @provider.should_receive(:shell_out!).with(check_remote_command,
                                                   :cwd => "/my/deploy/dir",
                                                   :log_tag => "git[web2.0 app]",
                                                   :returns => [0,1,2]).and_return(command_response)
        expected_command = "git remote add #{@resource.remote} #{@resource.repository}"
        @provider.should_receive(:shell_out!).with(expected_command,
                                                   :cwd => "/my/deploy/dir",
                                                   :log_tag => "git[web2.0 app]")
        @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
      end
    end

    describe "when a remote with a given name has already been configured" do
      it "updates remote url when the url is different" do
        command_response = double('shell_out')
        command_response.stub(:exitstatus) { 0 }
        command_response.stub(:stdout) { "some_other_url" }
        check_remote_command = "git config --get remote.#{@resource.remote}.url"
        @provider.should_receive(:shell_out!).with(check_remote_command,
                                                   :cwd => "/my/deploy/dir",
                                                   :log_tag => "git[web2.0 app]",
                                                   :returns => [0,1,2]).and_return(command_response)
        expected_command = "git config --replace-all remote.#{@resource.remote}.url #{@resource.repository}"
        @provider.should_receive(:shell_out!).with(expected_command,
                                                   :cwd => "/my/deploy/dir",
                                                   :log_tag => "git[web2.0 app]")
        @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
      end

      it "doesn't update remote url when the url is the same" do
        command_response = double('shell_out')
        command_response.stub(:exitstatus) { 0 }
        command_response.stub(:stdout) { @resource.repository }
        check_remote_command = "git config --get remote.#{@resource.remote}.url"
        @provider.should_receive(:shell_out!).with(check_remote_command,
                                                   :cwd => "/my/deploy/dir",
                                                   :log_tag => "git[web2.0 app]",
                                                   :returns => [0,1,2]).and_return(command_response)
        unexpected_command = "git config --replace-all remote.#{@resource.remote}.url #{@resource.repository}"
        @provider.should_not_receive(:shell_out!).with(unexpected_command,
                                                       :cwd => "/my/deploy/dir",
                                                       :log_tag => "git[web2.0 app]")
        @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
      end

      it "resets remote url when it has multiple values" do
        command_response = double('shell_out')
        command_response.stub(:exitstatus) { 2 }
        check_remote_command = "git config --get remote.#{@resource.remote}.url"
        @provider.should_receive(:shell_out!).with(check_remote_command,
                                                   :cwd => "/my/deploy/dir",
                                                   :log_tag => "git[web2.0 app]",
                                                   :returns => [0,1,2]).and_return(command_response)
        expected_command = "git config --replace-all remote.#{@resource.remote}.url #{@resource.repository}"
        @provider.should_receive(:shell_out!).with(expected_command,
                                                   :cwd => "/my/deploy/dir",
                                                   :log_tag => "git[web2.0 app]")
        @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
      end
    end
  end

  it "raises an error if the git clone command would fail because the enclosing directory doesn't exist" do
    @provider.stub(:shell_out!)
    lambda {@provider.run_action(:sync)}.should raise_error(Chef::Exceptions::MissingParentDirectory)
  end

  it "does a checkout by cloning the repo and then enabling submodules" do
    # will be invoked in load_current_resource
    ::File.stub(:exist?).with("/my/deploy/dir/.git").and_return(false)

    ::File.stub(:exist?).with("/my/deploy/dir").and_return(true)
    ::File.stub(:directory?).with("/my/deploy").and_return(true)
    ::Dir.stub(:entries).with("/my/deploy/dir").and_return(['.','..'])
    @provider.should_receive(:clone)
    @provider.should_receive(:checkout)
    @provider.should_receive(:enable_submodules)
    @provider.run_action(:checkout)
    # Even though an actual run will cause an update to occur, the fact that we've stubbed out
    # the actions above will prevent updates from registering
    # @resource.should be_updated
  end

  it "does not call checkout if enable_checkout is false" do
    # will be invoked in load_current_resource
    ::File.stub(:exist?).with("/my/deploy/dir/.git").and_return(false)

    ::File.stub(:exist?).with("/my/deploy/dir").and_return(true)
    ::File.stub(:directory?).with("/my/deploy").and_return(true)
    ::Dir.stub(:entries).with("/my/deploy/dir").and_return(['.','..'])

    @resource.enable_checkout false
    @provider.should_receive(:clone)
    @provider.should_not_receive(:checkout)
    @provider.should_receive(:enable_submodules)
    @provider.run_action(:checkout)
  end

  # REGRESSION TEST: on some OSes, the entries from an empty directory will be listed as
  # ['..', '.'] but this shouldn't change the behavior
  it "does a checkout by cloning the repo and then enabling submodules when the directory entries are listed as %w{.. .}" do
    ::File.stub(:exist?).with("/my/deploy/dir/.git").and_return(false)
    ::File.stub(:exist?).with("/my/deploy/dir").and_return(false)
    ::File.stub(:directory?).with("/my/deploy").and_return(true)
    ::Dir.stub(:entries).with("/my/deploy/dir").and_return(['..','.'])
    @provider.should_receive(:clone)
    @provider.should_receive(:checkout)
    @provider.should_receive(:enable_submodules)
    @provider.should_receive(:add_remotes)
    @provider.run_action(:checkout)
   # @resource.should be_updated
  end

  it "should not checkout if the destination exists or is a non empty directory" do
    # will be invoked in load_current_resource
    ::File.stub(:exist?).with("/my/deploy/dir/.git").and_return(false)

    ::File.stub(:exist?).with("/my/deploy/dir").and_return(true)
    ::File.stub(:directory?).with("/my/deploy").and_return(true)
    ::Dir.stub(:entries).with("/my/deploy/dir").and_return(['.','..','foo','bar'])
    @provider.should_not_receive(:clone)
    @provider.should_not_receive(:checkout)
    @provider.should_not_receive(:enable_submodules)
    @provider.should_not_receive(:add_remotes)
    @provider.run_action(:checkout)
    @resource.should_not be_updated
  end

  it "syncs the code by updating the source when the repo has already been checked out" do
    ::File.should_receive(:exist?).with("/my/deploy/dir/.git").and_return(true)
    ::File.stub(:directory?).with("/my/deploy").and_return(true)
    @provider.should_receive(:find_current_revision).exactly(1).and_return('d35af14d41ae22b19da05d7d03a0bafc321b244c')
    @provider.should_not_receive(:fetch_updates)
    @provider.should_receive(:add_remotes)
    @provider.run_action(:sync)
    @resource.should_not be_updated
  end

  it "marks the resource as updated when the repo is updated and gets a new version" do
    ::File.should_receive(:exist?).with("/my/deploy/dir/.git").and_return(true)
    ::File.stub(:directory?).with("/my/deploy").and_return(true)
    # invoked twice - first time from load_current_resource
    @provider.should_receive(:find_current_revision).exactly(1).and_return('d35af14d41ae22b19da05d7d03a0bafc321b244c')
    @provider.stub(:target_revision).and_return('28af684d8460ba4793eda3e7ac238c864a5d029a')
    @provider.should_receive(:fetch_updates)
    @provider.should_receive(:enable_submodules)
    @provider.should_receive(:add_remotes)
    @provider.run_action(:sync)
   # @resource.should be_updated
  end

  it "does not fetch any updates if the remote revision matches the current revision" do
    ::File.should_receive(:exist?).with("/my/deploy/dir/.git").and_return(true)
    ::File.stub(:directory?).with("/my/deploy").and_return(true)
    @provider.stub(:find_current_revision).and_return('d35af14d41ae22b19da05d7d03a0bafc321b244c')
    @provider.stub(:target_revision).and_return('d35af14d41ae22b19da05d7d03a0bafc321b244c')
    @provider.should_not_receive(:fetch_updates)
    @provider.should_receive(:add_remotes)
    @provider.run_action(:sync)
    @resource.should_not be_updated
  end

  it "clones the repo instead of fetching it if the deploy directory doesn't exist" do
    ::File.stub(:directory?).with("/my/deploy").and_return(true)
    ::File.should_receive(:exist?).with("/my/deploy/dir/.git").exactly(2).and_return(false)
    @provider.should_receive(:action_checkout)
    @provider.should_not_receive(:shell_out!)
    @provider.run_action(:sync)
   # @resource.should be_updated
  end

  it "clones the repo instead of fetching updates if the deploy directory is empty" do
    ::File.should_receive(:exist?).with("/my/deploy/dir/.git").exactly(2).and_return(false)
    ::File.stub(:directory?).with("/my/deploy").and_return(true)
    ::File.stub(:directory?).with("/my/deploy/dir").and_return(true)
    @provider.stub(:sync_command).and_return("huzzah!")
    @provider.should_receive(:action_checkout)
    @provider.should_not_receive(:shell_out!).with("huzzah!", :cwd => "/my/deploy/dir")
    @provider.run_action(:sync)
    #@resource.should be_updated
  end

  it "does an export by cloning the repo then removing the .git directory" do
    @provider.should_receive(:action_checkout)
    FileUtils.should_receive(:rm_rf).with(@resource.destination + "/.git")
    @provider.run_action(:export)
    @resource.should be_updated
  end

  describe "calling add_remotes" do
    it "adds a new remote for each entry in additional remotes hash" do
      @resource.additional_remotes({:opscode => "opscode_repo_url",
        :another_repo => "some_other_repo_url"})
      STDOUT.stub(:tty?).and_return(false)
      command_response = double('shell_out')
      command_response.stub(:exitstatus) { 0 }
      @resource.additional_remotes.each_pair do |remote_name, remote_url|
        @provider.should_receive(:setup_remote_tracking_branches).with(remote_name, remote_url)
      end
      @provider.add_remotes
    end
  end

  describe "calling multiple_remotes?" do
    before(:each) do
      @command_response = double('shell_out')
    end

    describe "when check remote command returns with status 2" do
      it "returns true" do
        @command_response.stub(:exitstatus) { 2 }
        @provider.multiple_remotes?(@command_response).should be_true
      end
    end

    describe "when check remote command returns with status 0" do
      it "returns false" do
        @command_response.stub(:exitstatus) { 0 }
        @provider.multiple_remotes?(@command_response).should be_false
      end
    end

    describe "when check remote command returns with status 0" do
      it "returns false" do
        @command_response.stub(:exitstatus) { 1 }
        @provider.multiple_remotes?(@command_response).should be_false
      end
    end
  end

  describe "calling remote_matches?" do
    before(:each) do
      @command_response = double('shell_out')
    end

    describe "when output of the check remote command matches the repository url" do
      it "returns true" do
        @command_response.stub(:exitstatus) { 0 }
        @command_response.stub(:stdout) { @resource.repository }
        @provider.remote_matches?(@resource.repository, @command_response).should be_true
      end
    end

    describe "when output of the check remote command doesn't match the repository url" do
      it "returns false" do
        @command_response.stub(:exitstatus) { 0 }
        @command_response.stub(:stdout) { @resource.repository + "test" }
        @provider.remote_matches?(@resource.repository, @command_response).should be_false
      end
    end
  end
end


text:
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;

public class PlotControl extends Composite implements PaintListener
{
    private static Point SIZE_MINIMUM = new Point(200, 100);
    private static Point SIZE_DEFAULT = new Point(500, 200);
    private static int CHUNK_SIZE = 3;

    private Point size;
    private Canvas canvas;
    private GC gc;
    private PlotSetup plotSetup;

    public PlotControl(Composite parent, int style)
    {
        super(parent, style);

        this.setLayout(new FillLayout());

        size = new Point(SIZE_DEFAULT.x, SIZE_DEFAULT.y);

        canvas = new Canvas(this, SWT.NONE);
        canvas.setLocation(0, 0);
        canvas.addPaintListener(this);
        canvas.pack();

        gc = new GC(canvas);

        this.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));

        pack();
    }

    public Point computeSize(int xhint, int yhint, boolean changed)
    {
        Point computed = new Point(SIZE_DEFAULT.x, SIZE_DEFAULT.y);

        // if they're asking for a hint bigger than our default size, use the
        // hinted size
        if (xhint != SWT.DEFAULT && xhint > computed.x)
            computed.x = xhint;
        if (yhint != SWT.DEFAULT && yhint > computed.y)
            computed.y = yhint;

        return computed;
    }

    public void setSize(int x, int y)
    {
        size.x = Math.max(x, SIZE_MINIMUM.x);
        size.y = Math.max(y, SIZE_MINIMUM.y);
    }

    public Point computeSize(int xhint, int yhint)
    {
        return computeSize(xhint, yhint, true);
    }

    public void setSize(Point p)
    {
        setSize(p.x, p.y);
    }

    public void pack(boolean changed)
    {
        setSize(SIZE_DEFAULT.x, SIZE_DEFAULT.y);
    }

    public void pack()
    {
        pack(true);
    }

    public void setBackground(Color background)
    {
        super.setBackground(background);
        canvas.setBackground(background);
    }

    public void setPlotSetup(PlotSetup plotSetup)
    {
        this.plotSetup = plotSetup;
    }

    public void paintControl(PaintEvent e)
    {
        // handle if this is a resize event
        // TODO: really we should handle resizeevents with a ControlListener
        if (e.width != size.x || e.height != size.y)
            setSize(e.width, e.height);

        // reference: if we use "domain", or "range" we're talking about the
        // domain/range of the actual data points.  when we talk about "x" and
        // "y", we're talking about the coordinates used to paint the control.
        int domainStart = plotSetup.getDomainStart();
        int domainEnd = plotSetup.getDomainEnd();
        int domainSize = domainEnd - domainStart;
        int domainStepping = plotSetup.getDomainStepping();
        int domainPoints = (domainSize / domainStepping) + 1;

        // if we're using the inverse style of multiple stacking, then we need to correct
        // the range start...
        if((plotSetup.getMultipleStyle() & PlotSetup.MULTIPLE_STYLE_INVERSE) == PlotSetup.MULTIPLE_STYLE_INVERSE)
        {
            plotSetup.setRangeStart(0 - plotSetup.getRangeEnd());
        }

        // how much we need to stretch to fill this control
        int xStepping = (size.x / (domainPoints - 1));

        // we "chunk" so that we don't use enormous amounts of memory for large datasets
        // so figure out how much to paint at a time
        int chunkSize = (domainPoints <= CHUNK_SIZE || CHUNK_SIZE == 0) ? domainPoints : CHUNK_SIZE;

        PlotRenderer plotRenderer = new PlotRendererStandard(plotSetup, size.x, size.y, chunkSize);

        xStepping = plotRenderer.getXStepping();

        for(int domain = domainStart, x = 0;
            domain <= domainEnd;
            domain += (chunkSize * domainStepping), x += (chunkSize * xStepping))
        {
            int[][] polygonPoints = new int[plotSetup.getPlotData().size()][];
            int[][] polylinePoints = new int[plotSetup.getPlotData().size()][];

            for(int i = 0; i < plotSetup.getPlotData().size(); i++)
            {
                // setup the data to stack upon, if necessary
                int diff = (plotSetup.getMultipleStyle() & PlotSetup.MULTIPLE_STYLE_INVERSE) == PlotSetup.MULTIPLE_STYLE_INVERSE ? 2 : 1;
                int[] polygonStack = (i >= diff) ? polygonPoints[i - diff] : null;
                int[] polylineStack = (i >= diff) ? polylinePoints[i - diff] : null;

                polygonPoints[i] = plotRenderer.getPolygon(i, x, xStepping, domain, domainEnd, domainStepping, polygonStack);
                polylinePoints[i] = plotRenderer.getPolyline(i, x, xStepping, domain, domainEnd, domainStepping, polylineStack);
            }

            for(int i = plotSetup.getPlotData().size() - 1; i >= 0; i--)
            {
                drawPolygon(polygonPoints[i], (PlotData)plotSetup.getPlotData().get(i));
                drawPolyline(polylinePoints[i], (PlotData)plotSetup.getPlotData().get(i));
            }
        }

        drawLabel(plotRenderer);
    }

    private void drawLabel(PlotRenderer plotRenderer)
    {
        gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_BLACK));
        gc.setLineWidth(1);
        gc.setLineStyle(SWT.LINE_SOLID);

        drawLabelAxes(plotRenderer);

        gc.setAlpha(plotSetup.getGuideAlpha());
        gc.setLineStyle(plotSetup.getGuideLineStyle());

        if(plotSetup.getRangeGuideStepping() > 0)
            drawLabelRange(plotRenderer);

        if(plotSetup.getDomainGuideStepping() > 0)
            drawLabelDomain(plotRenderer);
    }

    private void drawLabelAxes(PlotRenderer plotRenderer)
    {
        int xOrigin = plotRenderer.computeX(0);
        int yOrigin = plotRenderer.computeY(0);

        // draw the axes in solid, always

        gc.drawLine(0, yOrigin, size.x, yOrigin);
        gc.drawLine(xOrigin, 0, xOrigin, size.y);
    }

    private void drawLabelRange(PlotRenderer plotRenderer)
    {
        for(int rangeGuide = plotSetup.getRangeStart();
            rangeGuide <= plotSetup.getRangeEnd();
            rangeGuide += plotSetup.getRangeGuideStepping())
        {
            // we've already drawn the axes
            if(rangeGuide != 0)
            {
                int yLabel = plotRenderer.computeY(rangeGuide);
                gc.drawLine(0, yLabel, size.x, yLabel);
            }
        }
    }

    private void drawLabelDomain(PlotRenderer plotRenderer)
    {
        for(int domainGuide = plotSetup.getDomainStart();
            domainGuide <= plotSetup.getDomainEnd();
            domainGuide += plotSetup.getDomainGuideStepping())
        {
            // we've already drawn the axes
            if(domainGuide != 0)
            {
                int xGuide = plotRenderer.computeX(domainGuide);
                gc.drawLine(xGuide, 0, xGuide, size.y);
            }
        }
    }

    private void drawPolygon(int[] polygonPoints, PlotData data)
    {
        if(data.getFillColor() == null)
            return;

        gc.setAlpha(data.getAlpha());
        gc.setBackground(data.getFillColor());
        gc.fillPolygon(polygonPoints);
    }

    private void drawPolyline(int[] polylinePoints, PlotData data)
    {
        if(data.getStrokeColor() == null)
            return;

        gc.setAlpha(data.getAlpha());
        gc.setForeground(data.getStrokeColor());
        gc.setLineWidth(data.getStrokeWidth());
        gc.setLineStyle(SWT.LINE_SOLID);
        gc.drawPolyline(polylinePoints);
    }

    public void dispose()
    {
        super.dispose();
        gc.dispose();
    }
}


text:
from nose.plugins.attrib import attr

from tests import WordPressTestCase

from wordpress_xmlrpc.methods import pages, posts
from wordpress_xmlrpc.wordpress import WordPressPage

class TestPages(WordPressTestCase):

    @attr('pages')
    @attr('pycompat')
    def test_page_repr(self):
        page = WordPressPage()
        repr(page)

    @attr('pages')
    def test_get_page_status_list(self):
        status_list = self.client.call(pages.GetPageStatusList())
        self.assertTrue(isinstance(status_list, dict))

    @attr('pages')
    def test_get_page_templates(self):
        templates = self.client.call(pages.GetPageTemplates())
        self.assertTrue(isinstance(templates, dict))
        self.assertTrue('Default' in templates)

    @attr('pages')
    def test_get_pages(self):
        page_list = self.client.call(posts.GetPosts({'post_type': 'page'}, results_class=WordPressPage))
        self.assert_list_of_classes(page_list, WordPressPage)

    @attr('pages')
    def test_page_lifecycle(self):
        page = WordPressPage()
        page.title = 'Test Page'
        page.content = 'This is my test page.'

        # create the page
        page_id = self.client.call(posts.NewPost(page))
        self.assertTrue(page_id)

        # fetch the newly created page
        page2 = self.client.call(posts.GetPost(page_id, results_class=WordPressPage))
        self.assertTrue(isinstance(page2, WordPressPage))
        self.assertEqual(str(page2.id), page_id)

        # edit the page
        page2.content += '
Updated: This page has been updated.'
        response = self.client.call(posts.EditPost(page_id, page2))
        self.assertTrue(response)

        # delete the page
        response = self.client.call(posts.DeletePost(page_id))
        self.assertTrue(response)

    @attr('pages')
    def test_page_parent(self):
        parent_page = WordPressPage()
        parent_page.title = 'Parent page'
        parent_page.content = 'This is the parent page'
        parent_page.id = self.client.call(posts.NewPost(parent_page))
        self.assertTrue(parent_page.id)

        child_page = WordPressPage()
        child_page.title = 'Child page'
        child_page.content = 'This is the child page'
        child_page.parent_id = parent_page.id
        child_page.id = self.client.call(posts.NewPost(child_page))
        self.assertTrue(child_page.id)

        # re-fetch to confirm parent_id worked
        child_page2 = self.client.call(posts.GetPost(child_page.id))
        self.assertTrue(child_page2)
        self.assertEquals(child_page.parent_id, child_page2.parent_id)

        # cleanup
        self.client.call(posts.DeletePost(parent_page.id))
        self.client.call(posts.DeletePost(child_page.id))


text:
const _ = require("lodash");
const Bluebird = require("bluebird");
const express = require("express");
const Feed = require("../src/feed");
const helper = require("../src/helper");
const router = express.Router();
const ua = require("universal-analytics");
const tracking = require("../src/tracking");
const sort = require('fast-sort');

router.get("/", function(req, res, next) {
  if (req.headers.accept.includes("text/html")) {
    handleHtmlRequest(req, res, next);
  } else {
    handleJsonRequest(req, res, next);
  }
});

module.exports = router;

function getYesterday() {
  let date = new Date();

  date.setDate(date.getDate() - 1);

  return date;
}

async function handleHtmlRequest(req, res, next) {
  const sections = [
    "introduction",
    "usage",
    "options",
    "hosting",
    "development",
    "caching",
    "analytics"
  ];

  const supportRequestsTillNextAd = await tracking.supportRequestsTillNextAd();

  res.render("index", {
    title: "FeedrApp",
    sections,
    tracking: {
      today: await tracking.getDataFor(new Date()),
      yesterday: await tracking.getDataFor(getYesterday()),
      supportRequestsTillNextAd: 250 - (supportRequestsTillNextAd || 0),
      supporters: await tracking.getSupportersOverTime()
    }
  });
}

function handleJsonRequest(req, res, next) {
  getResponseData(req)
    .then(function(feed) {
      if (req.query.callback) {
        res.set("Content-Type", "text/javascript; charset=utf-8");
        res.send(`${req.query.callback}(${JSON.stringify(feed)});`);
      } else {
        res.json(feed);
      }
    })
    .then(() => trackRequest(req));
}

function sortEntries(arr, order) {
  if (!order) {
    return arr;
  }

  const match = order.match(/^(-){0,1}(.*)$/);
  const orderMethod = match[1] ? 'desc' : 'asc';
  const orderField = match[2];

  return sort(arr)[orderMethod](entry => entry[orderField]);
}

function getFeedData(feedUrls, feedOptions) {
  const errors = [];

  return Promise.all(
    feedUrls.map(feedUrl =>
      new Feed(feedUrl).read(feedOptions).catch(e => {
        errors.push(e);
      })
    )
  ).then(feeds => {
    if (errors.length > 0 && feeds.filter(f => !!f).length === 0) {
      throw errors[0];
    }

    return feeds.reduce(
      (acc, feed = {}) => ({
        ...feed,
        ...acc,
        entries: sortEntries(
          (acc.entries || []).concat(feed.entries || []),
          feedOptions.order
        )
      }),
      {}
    );
  });
}

function getResponseData(req) {
  const feedUrl = req.query.q;
  const feedOptions = _.pick(req.query, ["num", "encoding", "order"]);

  if (feedUrl) {
    return getFeedData(feedUrl.split(","), feedOptions)
      .then(feed => {
        return {
          responseStatus: 200,
          responseDetails: null,
          responseData: { feed }
        };
      })
      .catch(error => {
        console.error({ feedUrl, error });
        return helper.badRequest({
          message: "Parsing the provided feed url failed."
        });
      });
  } else {
    return Bluebird.resolve(
      helper.badRequest({
        message: "No q param found!",
        details:
          'Please add a query parameter "q" to the request URL which points to a feed!'
      })
    );
  }
}

function trackRequest(req) {
  // ua('UA-100419142-1', { https: true })
  //   .pageview(req.originalUrl)
  //   .send();
}


text:
package com.mvc.constroller;
import java.lang.annotation.Annotation;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.mvc.domain.Admin;
import com.mvc.service.SelectService;
import com.mvc.service.SysMenuService;
import com.mvc.util.EasyuiTreeNode;
import com.mvc.util.WebFrontHelper;

@Controller
public class MainController{
    public MainController() {}
    @Resource
 		private SysMenuService sysMenuService;

    @RequestMapping(value = "/main", method = {RequestMethod.GET,RequestMethod.POST})

    public String registPostsss(Model model){

    		WebFrontHelper webtree = new WebFrontHelper();
    		EasyuiTreeNode node = webtree.buildTreeForEasyuiTree(this.sysMenuService.findAll());

    		model.addAttribute("treeJson", new Gson().toJson(node.getChildren()));

        return "/main";

    }

}


text:
<?php // Fetch current user information
$user = wp_get_current_user(); ?>
<?php // Get the API up and running for the extension listing
$api = new Layers_API(); ?>

	<?php $this->header( __( 'Dashboard' , 'layerswp' ) ); ?>

<?php _e( 'Start Using Layers' , 'layerswp' ); ?>

								<?php _e( 'Follow the easy steps to creating amazing layouts quickly and easily. ' , 'layerswp' ); ?>

						<a href="<?php echo admin_url( 'admin.php?page=layers-get-started' ); ?>" class="layers-button btn-large btn-primary">
							<?php _e( 'Get Started →' , 'layerswp' ); ?>

<?php _e( 'Layers Pages' , 'layerswp' ); ?>

							<?php foreach( layers_get_builder_pages() as $page ) { ?>

									<a class="layers-page-list-title" href="<?php echo admin_url( 'post.php?post=' . $page->ID . '&action=edit' ); ?>"><?php echo $page->post_title; ?>

										<a href="<?php echo admin_url( 'customize.php?url=' . esc_url( get_the_permalink() ) ); ?>"><?php _e( 'Edit Layout' , 'layerswp' ); ?> |
										<a href="<?php echo admin_url( 'post.php?post=' . $page->ID . '&action=edit' ); ?>"><?php _e( 'Edit' , 'layerswp' ); ?> |
										<a href="<?php echo get_the_permalink( $page->ID ); ?>"><?php _e( 'View' , 'layerswp' ); ?>

							<?php }?>

							<a href="<?php echo admin_url( 'admin.php?page=layers-add-new-page' ); ?>" class="layers-button btn-primary">
								<?php _e( 'Add New Page' , 'layerswp' ); ?>

<?php _e( 'Extensions' , 'layerswp' ); ?>

							<?php foreach( $api->get_extension_list() as $extension_key => $extension_details ) { ?>

										<?php echo $extension_details[ 'title' ]; ?>

									<?php if( isset( $extension_details[ 'description' ] ) ){ ?>

											<?php echo $extension_details[ 'description' ]; ?>

									<?php } ?>
									<?php if( isset( $extension_details[ 'available' ] ) && false == $extension_details[ 'available' ] ) { ?>

											<button class="layers-button btn-subtle" disabled="disabled"><?php _e( 'Coming soon' , 'layerswp' ); ?></button>

									<?php } else { ?>
										<?php if( isset( $extension_details[ 'links' ] ) && ( isset( $extension_details[ 'links' ][ 'purchase' ] ) || isset( $extension_details[ 'links' ][ 'details' ] ) ) ){ ?>

													<?php if( NULL != $extension_details[ 'links' ][ 'purchase' ] ) { ?>
														<a class="layers-button" href="<?php echo $extension_details[ 'links' ][ 'purchase' ]; ?>" target="_blank">
															<?php _e( 'Purchase' , 'layerswp' ) ;?>

													<?php } ?>
													<?php if( NULL != $extension_details[ 'links' ][ 'details' ] ) { ?>
														<a class="layers-button btn-link" href="<?php echo $extension_details[ 'links' ][ 'details' ]; ?>" target="_blank">
															<?php _e( 'More Details' , 'layerswp' ) ;?>

													<?php } ?>

										<?php } ?>
									<?php } ?>

							<?php } // foreach extensions ?>

<?php _e( 'What you need' , 'layerswp' ); ?>

<?php _e( 'WordPress 4.0' , 'layerswp' ); ?>

									<?php _e( 'Layers requires you run the latest version of WordPress, please make sure you\'re up to date!' , 'layerswp' ); ?>

									<?php if( 4.0 <= get_bloginfo('version') ) { ?>
										<?php _e( 'You\'re up to date' , 'layerswp' ); ?>
									<?php } else { ?>
										<a class="layers-button btn-primary" href="<?php echo admin_url( '/update-core.php' ); ?>" target="_blank"><?php _e( 'Update WordPress' , 'layerswp' ); ?>
									<?php } ?>

<?php _e( 'The Layers Updater' , 'layerswp' ); ?>

									<?php _e( 'Make sure you\'re always running the latest version of Layers by installing the Layers Updater' , 'layerswp' ); ?>

									<?php if( class_exists( 'Layers_Updater' ) ) { ?>
										<?php _e( 'Installed' , 'layerswp' ); ?>
									<?php } else { ?>
										<?php _e( sprintf( 'Get the Layers Updater', 'http://www.layerswp.com/download/layers-updater/' ) , 'layerswp' ); ?>
									<?php } ?>

					<?php $videos = array(
						'adding-a-widget',
						'widget-slider',
						'design-bar'
					);
					$use_video = $videos[ array_rand($videos) ]; ?>

<?php _e( 'Helpful Tips' , 'layerswp' ); ?>

							<?php layers_show_html5_video( 'http://cdn.oboxsites.com/layers/videos/' . $use_video . '.mp4', 490 ); ?>

<?php $this->footer(); ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/category_frame_expression"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"></FrameLayout>
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:scrollbars="none">
        <GridView
            android:id="@+id/category_gv_item"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </GridView>
    </HorizontalScrollView>
</LinearLayout>


text:
package net.firejack.platform.service.directory.broker.application;

import net.firejack.platform.api.directory.domain.Application;
import net.firejack.platform.core.broker.ServiceBroker;
import net.firejack.platform.core.domain.SimpleIdentifier;
import net.firejack.platform.core.model.registry.directory.ApplicationModel;
import net.firejack.platform.core.request.ServiceRequest;
import net.firejack.platform.core.response.ServiceResponse;
import net.firejack.platform.core.store.registry.IApplicationStore;
import net.firejack.platform.web.statistics.annotation.TrackDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@TrackDetails
@Component
public class DeleteApplicationBroker extends ServiceBroker
        <ServiceRequest<SimpleIdentifier<Long>>, ServiceResponse<Application>> {

    @Autowired
    @Qualifier("applicationStore")
    private IApplicationStore store;

    @Override
    protected ServiceResponse<Application> perform(ServiceRequest<SimpleIdentifier<Long>> request) throws Exception {
        Long applicationId = request.getData().getIdentifier();

        ServiceResponse<Application> response;
        if (applicationId == null) {
            response = new ServiceResponse<Application>("Application Id is null", false);
        } else {
            ApplicationModel model = store.findById(applicationId);
            if (model == null) {
                response = new ServiceResponse<Application>("No application was found by specified id", false);
            } else {
                try {
                    store.delete(model);
                    response = new ServiceResponse<Application>("Application has successfully deleted.", true);
                } catch (Throwable e) {
                    logger.error(e.getMessage(), e);
                    response = new ServiceResponse<Application>(
                            "Failed to delete application by specified Id. Reason: " + e.getMessage(), false);
                }
            }
        }
        return response;
    }

}


text:
<?php

use Litipk\BigNumbers\Decimal as Decimal;
use PHPUnit\Framework\TestCase;

date_default_timezone_set('UTC');

class DecimalFromDecimalTest extends TestCase
{
    public function testBasicCase()
    {
        $n1 = Decimal::fromString('3.45');

        $this->assertTrue(Decimal::fromDecimal($n1)->equals($n1));
        $this->assertTrue(Decimal::fromDecimal($n1, 2)->equals($n1));

        $this->assertTrue(Decimal::fromDecimal($n1, 1)->equals(Decimal::fromString('3.5')));
        $this->assertTrue(Decimal::fromDecimal($n1, 0)->equals(Decimal::fromString('3')));
    }
}


text:
"""
An implementation of stochastic max-pooling, based on

Stochastic Pooling for Regularization of Deep Convolutional Neural Networks
Matthew D. Zeiler, Rob Fergus, ICLR 2013
"""

__authors__ = "Mehdi Mirza"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["Mehdi Mirza", "Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "Mehdi Mirza"
__email__ = "mirzamom@iro"

import numpy
import theano
from theano import tensor
from theano.gof.op import get_debug_values
from pylearn2.utils.rng import make_theano_rng

def stochastic_max_pool_bc01(bc01, pool_shape, pool_stride, image_shape, rng = None):
    """
    .. todo::

        WRITEME properly

    Stochastic max pooling for training as defined in:

    Stochastic Pooling for Regularization of Deep Convolutional Neural Networks
    Matthew D. Zeiler, Rob Fergus

    Parameters
    ----------
    bc01 : theano 4-tensor
        in format (batch size, channels, rows, cols),
        IMPORTANT: All values should be positive
    pool_shape : tuple
        shape of the pool region (rows, cols)
    pool_stride : tuple
        strides between pooling regions (row stride, col stride)
    image_shape : tuple
        avoid doing some of the arithmetic in theano
    rng : theano random stream
    """
    r, c = image_shape
    pr, pc = pool_shape
    rs, cs = pool_stride

    batch = bc01.shape[0]
    channel = bc01.shape[1]

    rng = make_theano_rng(rng, 2022, which_method='multinomial')

    # Compute index in pooled space of last needed pool
    # (needed = each input pixel must appear in at least one pool)
    def last_pool(im_shp, p_shp, p_strd):
        rval = int(numpy.ceil(float(im_shp - p_shp) / p_strd))
        assert p_strd * rval + p_shp >= im_shp
        assert p_strd * (rval - 1) + p_shp < im_shp
        return rval
    # Compute starting row of the last pool
    last_pool_r = last_pool(image_shape[0] ,pool_shape[0], pool_stride[0]) * pool_stride[0]
    # Compute number of rows needed in image for all indexes to work out
    required_r = last_pool_r + pr

    last_pool_c = last_pool(image_shape[1] ,pool_shape[1], pool_stride[1]) * pool_stride[1]
    required_c = last_pool_c + pc

    # final result shape
    res_r = int(numpy.floor(last_pool_r/rs)) + 1
    res_c = int(numpy.floor(last_pool_c/cs)) + 1

    for bc01v in get_debug_values(bc01):
        assert not numpy.any(numpy.isinf(bc01v))
        assert bc01v.shape[2] == image_shape[0]
        assert bc01v.shape[3] == image_shape[1]

    # padding
    padded = tensor.alloc(0.0, batch, channel, required_r, required_c)
    name = bc01.name
    if name is None:
        name = 'anon_bc01'
    bc01 = tensor.set_subtensor(padded[:,:, 0:r, 0:c], bc01)
    bc01.name = 'zero_padded_' + name

    # unraveling
    window = tensor.alloc(0.0, batch, channel, res_r, res_c, pr, pc)
    window.name = 'unravlled_winodows_' + name

    for row_within_pool in xrange(pool_shape[0]):
        row_stop = last_pool_r + row_within_pool + 1
        for col_within_pool in xrange(pool_shape[1]):
            col_stop = last_pool_c + col_within_pool + 1
            win_cell = bc01[:,:,row_within_pool:row_stop:rs, col_within_pool:col_stop:cs]
            window  =  tensor.set_subtensor(window[:,:,:,:, row_within_pool, col_within_pool], win_cell)

    # find the norm
    norm = window.sum(axis = [4, 5])
    norm = tensor.switch(tensor.eq(norm, 0.0), 1.0, norm)
    norm = window / norm.dimshuffle(0, 1, 2, 3, 'x', 'x')
    # get prob
    prob = rng.multinomial(pvals = norm.reshape((batch * channel * res_r * res_c, pr * pc)), dtype='float32')
    # select
    res = (window * prob.reshape((batch, channel, res_r, res_c,  pr, pc))).max(axis=5).max(axis=4)
    res.name = 'pooled_' + name

    return tensor.cast(res, theano.config.floatX)

def weighted_max_pool_bc01(bc01, pool_shape, pool_stride, image_shape, rng = None):
    """
    This implements test time probability weighted pooling defined in:

    Stochastic Pooling for Regularization of Deep Convolutional Neural Networks
    Matthew D. Zeiler, Rob Fergus

    Parameters
    ----------
    bc01 : theano 4-tensor
        minibatch in format (batch size, channels, rows, cols),
        IMPORTANT: All values should be poitivie
    pool_shape : theano 4-tensor
        shape of the pool region (rows, cols)
    pool_stride : tuple
        strides between pooling regions (row stride, col stride)
    image_shape : tuple
        avoid doing some of the arithmetic in theano
    """
    r, c = image_shape
    pr, pc = pool_shape
    rs, cs = pool_stride

    batch = bc01.shape[0]
    channel = bc01.shape[1]

    rng = make_theano_rng(rng, 2022, which_method='multinomial')

    # Compute index in pooled space of last needed pool
    # (needed = each input pixel must appear in at least one pool)
    def last_pool(im_shp, p_shp, p_strd):
        rval = int(numpy.ceil(float(im_shp - p_shp) / p_strd))
        assert p_strd * rval + p_shp >= im_shp
        assert p_strd * (rval - 1) + p_shp < im_shp
        return rval
    # Compute starting row of the last pool
    last_pool_r = last_pool(image_shape[0] ,pool_shape[0], pool_stride[0]) * pool_stride[0]
    # Compute number of rows needed in image for all indexes to work out
    required_r = last_pool_r + pr

    last_pool_c = last_pool(image_shape[1] ,pool_shape[1], pool_stride[1]) * pool_stride[1]
    required_c = last_pool_c + pc

    # final result shape
    res_r = int(numpy.floor(last_pool_r/rs)) + 1
    res_c = int(numpy.floor(last_pool_c/cs)) + 1

    for bc01v in get_debug_values(bc01):
        assert not numpy.any(numpy.isinf(bc01v))
        assert bc01v.shape[2] == image_shape[0]
        assert bc01v.shape[3] == image_shape[1]

    # padding
    padded = tensor.alloc(0.0, batch, channel, required_r, required_c)
    name = bc01.name
    if name is None:
        name = 'anon_bc01'
    bc01 = tensor.set_subtensor(padded[:,:, 0:r, 0:c], bc01)
    bc01.name = 'zero_padded_' + name

    # unraveling
    window = tensor.alloc(0.0, batch, channel, res_r, res_c, pr, pc)
    window.name = 'unravlled_winodows_' + name

    for row_within_pool in xrange(pool_shape[0]):
        row_stop = last_pool_r + row_within_pool + 1
        for col_within_pool in xrange(pool_shape[1]):
            col_stop = last_pool_c + col_within_pool + 1
            win_cell = bc01[:,:,row_within_pool:row_stop:rs, col_within_pool:col_stop:cs]
            window  =  tensor.set_subtensor(window[:,:,:,:, row_within_pool, col_within_pool], win_cell)

    # find the norm
    norm = window.sum(axis = [4, 5])
    norm = tensor.switch(tensor.eq(norm, 0.0), 1.0, norm)
    norm = window / norm.dimshuffle(0, 1, 2, 3, 'x', 'x')
    # average
    res = (window * norm).sum(axis=[4,5])
    res.name = 'pooled_' + name

    return res.reshape((batch, channel, res_r, res_c))


text:
package org.apache.weex.ui.action;

import org.apache.weex.WXSDKInstance;
import org.apache.weex.WXSDKManager;
import org.apache.weex.ui.component.richtext.WXRichText;
import java.util.HashMap;
import java.util.Map;

public class GraphicActionUpdateRichtextAttr extends BasicGraphicAction{

    public GraphicActionUpdateRichtextAttr(WXSDKInstance instance, String ref, HashMap<String, String> attrs, String parentRef, String richTextRef){
        super(instance, richTextRef);
        WXRichText richText =  (WXRichText) WXSDKManager.getInstance().getWXRenderManager()
                .getWXComponent(getPageId(), richTextRef);
        if(richText != null) {
            Map<String, Object> map = new HashMap<>();
            map.putAll(attrs);
            richText.updateChildNodeAttrs(ref, map);
        }
    }
    @Override
    public void executeAction() {
    }

}


text:
urls = {
    "home": "/",
    "discover": "/discover",
    "login": "/login",
    "register": "/register",
    "forgot-password": "/forgot-password",

    "change-password": "/change-password/{0}", # user.token
    "change-email": "/change-email/{0}", # user.email_token
    "cancel-account": "/cancel-account/{0}", # auth.token.get_token_for_user(user)
    "invitation": "/invitation/{0}", # membership.token

    "user": "/profile/{0}", # user.username

    "project": "/project/{0}", # project.slug

    "epics": "/project/{0}/epics/", # project.slug
    "epic": "/project/{0}/epic/{1}", # project.slug, epic.ref

    "backlog": "/project/{0}/backlog/", # project.slug
    "taskboard": "/project/{0}/taskboard/{1}", # project.slug, milestone.slug
    "kanban": "/project/{0}/kanban/", # project.slug

    "userstory": "/project/{0}/us/{1}", # project.slug, us.ref
    "task": "/project/{0}/task/{1}", # project.slug, task.ref

    "issues": "/project/{0}/issues", # project.slug
    "issue": "/project/{0}/issue/{1}", # project.slug, issue.ref

    "wiki": "/project/{0}/wiki/{1}", # project.slug, wikipage.slug

    "team": "/project/{0}/team/", # project.slug

    "project-transfer": "/project/{0}/transfer/{1}", # project.slug, project.transfer_token

    "project-admin": "/login?next=/project/{0}/admin/project-profile/details", # project.slug
}


text:
<?php

namespace Zend\Pdf\Action;

/**
 * PDF 'Import field values from a file' action
 * PDF 1.2+ feature
 *
 * @uses       \Zend\Pdf\Action\AbstractAction
 * @package    Zend_PDF
 * @subpackage Zend_PDF_Action
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class ImportData extends AbstractAction
{
}


text:
using System;
using System.Text;

namespace Tamir.SharpSsh.java.lang
{
	/// <summary>
	/// Summary description for StringBuffer.
	/// </summary>
	public class StringBuffer
	{
		StringBuilder sb;
		public StringBuffer()
		{
			sb = new StringBuilder();
		}

		public StringBuffer(string s)
		{
			sb = new StringBuilder(s);
		}

		public StringBuffer(StringBuilder sb):this(sb.ToString())
		{
		}

		public StringBuffer(Tamir.SharpSsh.java.String s):this(s.ToString())
		{
		}

		public StringBuffer append(string s)
		{
			sb.Append(s);
			return this;
		}

		public StringBuffer append(char s)
		{
			sb.Append(s);
			return this;
		}

		public StringBuffer append(Tamir.SharpSsh.java.String s)
		{
			return append(s.ToString());
		}

		public StringBuffer delete(int start, int end)
		{
			sb.Remove(start, end-start);
			return this;
		}

		public override string ToString()
		{
			return sb.ToString();
		}

		public string toString()
		{
			return ToString();
		}

	}
}


text:
import all from '../src/all';

describe('all', function() {
  let validators;
  const props = {
    key: 'value'
  };
  const propName = 'key';
  const componentName = 'TestComponent';

  beforeEach(function() {
    validators = [
      sinon.stub(),
      sinon.stub(),
      sinon.stub()
    ];
  });

  it('with no arguments provided', function() {
    expect(() => {
      all();
    }).to.throw(Error, /No validations provided/);
  });

  it('with invalid arguments provided', function() {
    expect(() => {
      all(1);
    }).to.throw(Error, /Invalid arguments, must be functions/);
  });

  it('validates each validation', function() {
    const allValidator = all(...validators);

    const result = allValidator(props, propName, componentName);
    expect(result).to.equal(undefined);

    validators.forEach(x => {
      x.should.have.been.calledOnce
        .and.calledWith(props, propName, componentName);
    });
  });

  it('returns first validation failure', function() {
    const err = new Error('Failure');
    validators[1].returns(err);
    const allValidator = all(...validators);

    const result = allValidator(props, propName, componentName);
    expect(result).to.equal(err);

    validators[0].should.have.been.calledOnce
      .and.calledWith(props, propName, componentName);

    validators[1].should.have.been.calledOnce
      .and.calledWith(props, propName, componentName);

    validators[2].should.not.have.been.called;
  });
});


text:
#ifndef T_FS_H
#define T_FS_H

// global FS interface

struct MapData;
class AActor;

void T_PreprocessScripts();
void T_LoadScripts(MapData * map);
void T_AddSpawnedThing(AActor * );

#endif


text:
<?php
/**
 * Created by PhpStorm.
 * User: gseidel
 * Date: 23.07.18
 * Time: 17:46
 */

namespace Enhavo\Bundle\MultiTenancyBundle\EventListener;

use Enhavo\Bundle\MultiTenancyBundle\Model\TenantAwareInterface;
use Enhavo\Bundle\MultiTenancyBundle\Tenant\TenantManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;

class TenantAwareSubscriber implements EventSubscriberInterface
{
    /** @var TenantManager */
    private $manager;

    public function __construct(TenantManager $manager)
    {
        $this->manager = $manager;
    }

    public static function getSubscribedEvents()
    {
        return array(
            'enhavo_app.pre_create' => ['preCreate', 10]    // Needs to run before RoutingBundle AutoGenerators
        );
    }

    public function preCreate(ResourceControllerEvent $event)
    {
        $resource = $event->getSubject();
        if($resource instanceof TenantAwareInterface) {
            $resource->setTenant($this->manager->getTenant()->getKey());
        }
    }
}


text:
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import render_to_response
from django.contrib import messages
from django.template import RequestContext
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
import json

#TODO: Logout views on each page
# Create a header part and include in all pages

login_url = '/middaymeal/'

from models import *
from forms import *

@login_required(login_url=login_url)
def edit_child(request, child_id=None):

    if child_id:

        try:
            child = Child.objects.get(pk=child_id)
            child_data = {'name': child.name,
                          'date_of_birth': child.date_of_birth,
                          'aanganwadi': child.aanganwadi}
            childform = ChildEntryForm(initial=child_data)

            child_condition = ChildConditions.objects.filter(child=child)[0]
            child_condition_data  = {'weight': child_condition.weight,
                                    'height': child_condition.height,
                                    'age': child_condition.age,
                                    'body_mass_index': child_condition.body_mass_index,
                                    'date_of_entry': child_condition.date_of_entry}
            childconditionform = ChildConditionForm(initial=child_condition_data)

            child = Child.objects.get(pk=child_id)

        except ObjectDoesNotExist:
            messages.error(request, 'This child entry is not present')
    else:
        childform = ChildEntryForm()
        childconditionform = ChildConditionForm()

    if request.POST:

        childform = ChildEntryForm(request.POST)
        childconditionform = ChildConditionForm(request.POST)

        if childform.is_valid() and childconditionform.is_valid():
            if not child:
                child = childform.save()
            b = childconditionform.save(commit=False)
            b.child = child
            b.save()
            aanganwadi_name = request.POST['aanganwadi']
            return HttpResponseRedirect('/middaymeal/children/%s' %aanganwadi_name)

    return render_to_response('middaymeal/child_entry.html',{
        'childform': childform,
        'childconditionform': childconditionform,
}, context_instance=RequestContext(request))

def create_user(request):

    if request.POST:

        form = SignUpForm(request.POST)

        if form.is_valid():

            user_profile = form.save(commit=False)
            name = form.cleaned_data['name']
            password = form.cleaned_data['password']
            user = User.objects.create_user(username=name, password=password)
            user.save()

#            if not created:
#                messages.error(request, 'User already exists with same name ')

            category_form_data = {'super': 'super',
                             'district': form.cleaned_data['district'],
                             'block': form.cleaned_data['block'],
                             'panchayat': form.cleaned_data['panchayat'],
                             'village': form.cleaned_data['village'],
                             'aanganwadi': form.cleaned_data['aanganwadi']
                            }

            user_profile.category_data = json.dumps(category_form_data)
            user_profile.user = user
            user_profile.save()
            messages.success(request, 'Signup successful')
            return HttpResponseRedirect('/middaymeal/')

    else:
        form = SignUpForm()

    return render_to_response('middaymeal/signup.html',
                              {'form': form},
                              context_instance=RequestContext(request))

def login_user(request):

    form = LoginForm(request.POST or None)

    if form.is_valid():

        username = form.cleaned_data['name']
        password = form.cleaned_data['password']
        user = authenticate(username=username, password=password)

        if user is not None:

            if user.is_active:
                login(request, user)

            if user.is_staff:
                return HttpResponseRedirect('/middaymeal/districts')

            user_profile = UserProfile.objects.filter(user=user)[0]
            category = user_profile.category
            category_data = json.loads(user_profile.category_data)
            category_name = category_data[str(category)]
            return HttpResponseRedirect('/middaymeal/details/%s/%s' %(category, category_name))

        return HttpResponse('Invaild username or password')

    return render_to_response('middaymeal/login.html',
                             {'form': form},
                             context_instance=RequestContext(request))

@login_required(login_url=login_url)
def view_category_details(request, category=None, category_name=None):

        if category=='super':
            return HttpResponseRedirect('/middaymeal/districts')
        if category=='district':
            return HttpResponseRedirect('/middaymeal/blocks/%s' %category_name)
        if category=='block':
            return HttpResponseRedirect('/middaymeal/panchayats/%s' %category_name)
        if category=='panchayat':
            return HttpResponseRedirect('/middaymeal/villages/%s' %category_name)
        if category=='village':
            return HttpResponseRedirect('/middaymeal/aanganwadis/%s' %category_name)
        if category=='aanganwadi':
            return HttpResponseRedirect('/middaymeal/children/%s' %category_name)

        return HttpResponse('No category defined for user')

@login_required(login_url=login_url)
def view_districts(request):

    districts = District.objects.filter(state='Uttarakhand')
    return render_to_response('middaymeal/districts.html',
                             {'districts': districts},
                             context_instance=RequestContext(request))

@login_required(login_url=login_url)
def view_blocks(request, district_name=None):

    if district_name:

        district = District.objects.get(pk=district_name)
        blocks = Block.objects.filter(district=district)
        return render_to_response('middaymeal/blocks.html',
                                 {'blocks': blocks},
                                 context_instance=RequestContext(request))

    return HttpResponse('No blocks in this district')

@login_required(login_url=login_url)
def view_panchayats(request, block_name=None):

    if block_name:

        block = Block.objects.get(pk=block_name)
        panchayats = Panchayat.objects.filter(block=block)
        return render_to_response('middaymeal/panchayats.html',
                                 {'panchayats': panchayats},
                                 context_instance=RequestContext(request))

    return HttpResponse('No panchayat in this block')

@login_required(login_url=login_url)
def view_villages(request, panchayat_name=None):

    if panchayat_name:

        panchayat = Panchayat.objects.get(pk=panchayat_name)
        villages = Village.objects.filter(panchayat=panchayat)
        return render_to_response('middaymeal/villages.html',
                                 {'villages': villages},
                                 context_instance=RequestContext(request))

    return HttpResponse('No villages in this panchayat')

@login_required(login_url=login_url)
def view_aanganwadis(request, village_name=None):

    if village_name:

        village = Village.objects.get(pk=village_name)
        aanganwadis = Aanganwadi.objects.filter(village=village)
        return render_to_response('middaymeal/aanganwadis.html',
                                 {'aanganwadis': aanganwadis},
                                 context_instance=RequestContext(request))

    return HttpResponse('No panchayat in this block')

@login_required(login_url=login_url)
def view_children(request, aanganwadi_name=None):

        if aanganwadi_name:

            try:
                aanganwadi = Aanganwadi.objects.filter(pk=aanganwadi_name)[0]
            except IndexError:
                return HttpResponse('No such aanganwadi exists')

            try:
                children = Child.objects.filter(aanganwadi=aanganwadi)
                children_info = []

                for child in children:
                    child_details = ChildConditions.objects.filter(child=child)
                    child_info = {}
                    child_info['child']= child.as_dict()
                    child_info['conditions']=[]

                    for condition in child_details:
                        condition = condition.as_dict()
                        child_info['conditions'].append(condition)

                    children_info.append(child_info)

            except ObjectDoesNotExist:
                return HttpResponse('No children in this aanganwadi')

            return render_to_response('middaymeal/child_details.html',
                                     {'children_info': children_info},
                                     context_instance=RequestContext(request))

@login_required(login_url=login_url)
def view_child_details(request, child_id=None):

    if child_id:
        child = Child.objects.get(pk=child_id)
        child_details = ChildConditions.objects.filter(child=child)

        child_info = {}
        child_info['child']= child.as_dict()
        child_info['conditions']=[]

        for condition in child_details:
            condition = condition.as_dict()
            child_info['conditions'].append(condition)

        return render_to_response('middaymeal/child_track.html',
                                  {'child_info': child_info},
                                  context_instance=RequestContext(request))

@login_required(login_url=login_url)
def logout_user(request):
    logout(request)
    return HttpResponseRedirect('/middaymeal/')


text:
package org.bdgenomics.avocado.postprocessing

import org.bdgenomics.adam.avro.{ ADAMContig, ADAMGenotype, ADAMVariant }
import org.bdgenomics.adam.models.ADAMVariantContext
import org.bdgenomics.avocado.stats.AvocadoConfigAndStats
import org.scalatest.FunSuite

class FilterDepthSuite extends FunSuite {

  test("do not filter genotypes that have no depth info") {
    val contig = ADAMContig.newBuilder
      .setContigName("0")
      .build
    val variant = ADAMVariant.newBuilder
      .setContig(contig)
      .setPosition(0)
      .setReferenceAllele("A")
      .setVariantAllele("C")
      .build
    val gt1 = ADAMGenotype.newBuilder
      .setVariant(variant)
      .build()

    val seq = Seq(gt1, gt1, gt1)
    val filt = new DepthFilter(10)

    assert(filt.filterGenotypes(seq).length === 3)
  }

  test("do not filter genotypes that have sufficient coverage") {
    val contig = ADAMContig.newBuilder
      .setContigName("0")
      .build
    val variant = ADAMVariant.newBuilder
      .setContig(contig)
      .setPosition(0)
      .setReferenceAllele("A")
      .setVariantAllele("C")
      .build
    val gt1 = ADAMGenotype.newBuilder
      .setVariant(variant)
      .setReadDepth(10)
      .build()

    val seq = Seq(gt1, gt1)
    val filt = new DepthFilter(10)

    assert(filt.filterGenotypes(seq).length === 2)
  }

  test("filter genotypes that have low coverage") {
    val contig = ADAMContig.newBuilder
      .setContigName("0")
      .build
    val variant = ADAMVariant.newBuilder
      .setContig(contig)
      .setPosition(0)
      .setReferenceAllele("A")
      .setVariantAllele("C")
      .build
    val gt1 = ADAMGenotype.newBuilder
      .setVariant(variant)
      .setReadDepth(5)
      .build()

    val seq = Seq(gt1, gt1)
    val filt = new DepthFilter(10)

    assert(filt.filterGenotypes(seq).length === 0)
  }

  test("do not filter genotypes that have no depth info or that have sufficient coverage") {
    val contig = ADAMContig.newBuilder
      .setContigName("0")
      .build
    val variant = ADAMVariant.newBuilder
      .setContig(contig)
      .setPosition(0)
      .setReferenceAllele("A")
      .setVariantAllele("C")
      .build
    val gt1 = ADAMGenotype.newBuilder
      .setVariant(variant)
      .setSampleId("me")
      .build()
    val gt2 = ADAMGenotype.newBuilder
      .setVariant(variant)
      .setSampleId("you")
      .setReadDepth(15)
      .build()

    val seq = Seq(gt1, gt1, gt2, gt2)
    val filt = new DepthFilter(10)

    assert(filt.filterGenotypes(seq).length === 4)
  }

  test("do not filter genotypes that have no depth info but filter low coverage calls") {
    val contig = ADAMContig.newBuilder
      .setContigName("0")
      .build
    val variant = ADAMVariant.newBuilder
      .setContig(contig)
      .setPosition(0)
      .setReferenceAllele("A")
      .setVariantAllele("C")
      .build
    val gt1 = ADAMGenotype.newBuilder
      .setVariant(variant)
      .setSampleId("me")
      .build()
    val gt2 = ADAMGenotype.newBuilder
      .setVariant(variant)
      .setSampleId("you")
      .setReadDepth(6)
      .build()

    val seq = Seq(gt1, gt1, gt2, gt2)
    val filt = new DepthFilter(10)

    assert(filt.filterGenotypes(seq).length === 2)
    assert(filt.filterGenotypes(seq).filter(_.getSampleId == "me").length === 2)
    assert(filt.filterGenotypes(seq).filter(_.getSampleId == "you").length === 0)
  }
}


text:
package org.mockito.internal.verification;

import static org.mockito.internal.exceptions.Reporter.wantedAtMostX;
import static org.mockito.internal.invocation.InvocationMarker.markVerified;
import static org.mockito.internal.invocation.InvocationsFinder.findInvocations;

import java.util.Iterator;
import java.util.List;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.invocation.InvocationMatcher;
import org.mockito.invocation.MatchableInvocation;
import org.mockito.internal.verification.api.VerificationData;
import org.mockito.invocation.Invocation;
import org.mockito.verification.VerificationMode;

public class AtMost implements VerificationMode {

    private final int maxNumberOfInvocations;

    public AtMost(int maxNumberOfInvocations) {
        if (maxNumberOfInvocations < 0) {
            throw new MockitoException("Negative value is not allowed here");
        }
        this.maxNumberOfInvocations = maxNumberOfInvocations;
    }

    public void verify(VerificationData data) {
        List<Invocation> invocations = data.getAllInvocations();
        MatchableInvocation wanted = data.getTarget();

        List<Invocation> found = findInvocations(invocations, wanted);
        int foundSize = found.size();
        if (foundSize > maxNumberOfInvocations) {
            throw wantedAtMostX(maxNumberOfInvocations, foundSize);
        }

        removeAlreadyVerified(found);
        markVerified(found, wanted);
    }

    @Override
    public VerificationMode description(String description) {
        return VerificationModeFactory.description(this, description);
    }

    private void removeAlreadyVerified(List<Invocation> invocations) {
        for (Iterator<Invocation> iterator = invocations.iterator(); iterator.hasNext(); ) {
            Invocation i = iterator.next();
            if (i.isVerified()) {
                iterator.remove();
            }
        }
    }
}