text:
<?php

namespace Serge\ShopBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Category
 *
 * @ORM\Table(name="category")
 * @ORM\Entity(repositoryClass="Serge\ShopBundle\Entity\CategoryRepository")
 */
class Category
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    private $description;

    /**
     * @var
     *
     * @ORM\ManyToMany(targetEntity="Product", inversedBy="categories")
     * @ORM\JoinTable(name="category_product")
     */
    private $products;

    /**
     * @var
     *
     * @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
     */
    private $children;

    /**
     * @var
     *
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
     */
    private $parent;

    public function __construct()
    {
        $this->products = new ArrayCollection();
        $this->children = new ArrayCollection();
    }

    public function __toString()
    {
        return $this->name;
    }

    /**
     * @param  $children
     */
    public function setChildren($children)
    {
        $this->children = $children;
    }

    /**
     * @return
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * @param  $parent
     */
    public function setParent($parent)
    {
        $this->parent = $parent;
    }

    /**
     * @return
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Category
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Category
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * @return
     */
    public function getProducts()
    {
        return $this->products;
    }

    /**
     * @param Product $product
     */
    public function addProduct(Product $product)
    {
        $this->products->add($product);
    }

    /**
     * @param Product $product
     */
    public function removeProduct(Product $product)
    {
        $this->products->removeElement($product);
    }

    /**
     * @param  $products
     */
    public function setProducts($products)
    {
        $this->products = $products;
    }

    /**
     * @return string
     */
    public function getSupplierCode()
    {
        return $this->supplierCode;
    }

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


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe "Dynamoid::Fields" do

  before do
    @address = Address.new
  end

  it 'declares read attributes' do
    @address.city.should be_nil
  end

  it 'declares write attributes' do
    @address.city = 'Chicago'
    @address.city.should == 'Chicago'
  end

  it 'declares a query attribute' do
    @address.city?.should be_false

    @address.city = 'Chicago'

    @address.city?.should be_true
  end

  it 'automatically declares id' do
    lambda {@address.id}.should_not raise_error
  end

  it 'automatically declares and fills in created_at and updated_at' do
    @address.save

    @address = @address.reload
    @address.created_at.should_not be_nil
    @address.created_at.class.should == DateTime
    @address.updated_at.should_not be_nil
    @address.updated_at.class.should == DateTime
  end

  context 'with a saved address' do
    before do
      @address = Address.create(:deliverable => true)
      @original_id = @address.id
    end

    it 'should write an attribute correctly' do
      @address.write_attribute(:city, 'Chicago')
    end

    it 'should write an attribute with an alias' do
      @address[:city] = 'Chicago'
    end

    it 'should read a written attribute' do
      @address.write_attribute(:city, 'Chicago')
      @address.read_attribute(:city).should == 'Chicago'
    end

    it 'should read a written attribute with the alias' do
      @address.write_attribute(:city, 'Chicago')
      @address[:city].should == 'Chicago'
    end

    it 'should update all attributes' do
      @address.expects(:save).once.returns(true)
      @address.update_attributes(:city => 'Chicago')
      @address[:city].should == 'Chicago'
      @address.id.should == @original_id
    end

    it 'should update one attribute' do
      @address.expects(:save).once.returns(true)
      @address.update_attribute(:city, 'Chicago')
      @address[:city].should == 'Chicago'
      @address.id.should == @original_id
    end

    it 'adds in dirty methods for attributes' do
      @address.city = 'Chicago'
      @address.save

      @address.city = 'San Francisco'

      @address.city_was.should == 'Chicago'
    end

    it 'returns all attributes' do
      Address.attributes.should == {:id=>{:type=>:string}, :created_at=>{:type=>:datetime}, :updated_at=>{:type=>:datetime}, :city=>{:type=>:string}, :options=>{:type=>:serialized}, :deliverable => {:type => :boolean}}
    end
  end

  it "gives a warning when setting a single value larger than the maximum item size" do
    Dynamoid.logger.expects(:warn).with(regexp_matches(/city field has a length of 66000/))
    Address.new city: ("Ten chars " * 6_600)
  end

  context 'default values for fields' do
    before do
      @clazz = Class.new do
        include Dynamoid::Document

        field :name, :string, :default => 'x'
        field :uid, :integer, :default => lambda { 42 }

        def self.name
          'Document'
        end
      end

      @doc = @clazz.new
    end

    it 'returns default value' do
      @doc.name.should eq('x')
      @doc.uid.should eq(42)
    end

    it 'should save default value' do
      @doc.save!
      @doc.reload.name.should eq('x')
      @doc.uid.should eq(42)
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
module Syntax
  module Highlighter
    module Rails
      VERSION = "3.0.83.1.1"
    end
  end
end


text:
package com.thoughtworks.selenium.corebased;

import com.thoughtworks.selenium.*;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import java.util.regex.Pattern;

public class TestGetTextContent extends SeleneseTestNgHelper {
	@Test public void testGetTextContent() throws Exception {
		selenium.open("../tests/html/test_gettextcontent.html");
		verifyTrue(selenium.isTextPresent("Text1"));
		verifyFalse(selenium.isTextPresent("Text2"));
		verifyFalse(selenium.isTextPresent("Text3"));
		verifyFalse(selenium.isTextPresent("Text4"));
		verifyFalse(selenium.isTextPresent("Text5"));
		verifyFalse(selenium.isTextPresent("Text6"));
		verifyFalse(selenium.isTextPresent("Text7"));
		verifyFalse(selenium.isTextPresent("Text8"));
	}
}


text:
<?php

namespace Acme\StoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table (name = "Product")
 */
class Product {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column (type = "string", length = 100)
     */
    protected $name;

    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    protected $price;
    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

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

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set price
     *
     * @param decimal $price
     */
    public function setPrice($price)
    {
        $this->price = $price;
    }

    /**
     * Get price
     *
     * @return decimal
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set description
     *
     * @param text $description
     */
    public function setDescription($description)
    {
        $this->description = $description;
    }

    /**
     * Get description
     *
     * @return text
     */
    public function getDescription()
    {
        return $this->description;
    }
}


text:
package datastore

import (
	"testing"

	pb "google.golang.org/genproto/googleapis/datastore/v1"
)

func TestInterfaceToProtoNilKey(t *testing.T) {
	var iv *Key
	pv, err := interfaceToProto(iv, false)
	if err != nil {
		t.Fatalf("nil key: interfaceToProto: %v", err)
	}

	_, ok := pv.ValueType.(*pb.Value_NullValue)
	if !ok {
		t.Errorf("nil key: type:\ngot: %T\nwant: %T", pv.ValueType, &pb.Value_NullValue{})
	}
}


text:
// Copyright (c) MOSA Project. Licensed under the New BSD License.

using Mosa.Internal.Plug;

namespace Mosa.TestWorld.x86.Tests
{
	internal class PlugTestCase
	{
		// Incomplete implementations that plugs will implement
		public static int Double(int a)
		{
			return 0;
		}

		public static int AddOne(int a)
		{
			return 0;
		}

		public int AddZ2Z(int z)
		{
			return 0;
		}
	}

	[Type("Mosa.TestWorld.x86.Tests.PlugTestCase")]
	internal static class PlugTestImplementation
	{
		public static int AddOne(int a)
		{
			return a + 1;
		}

		[Method("Mosa.TestWorld.x86.Tests.PlugTestCase.Double")]
		public static int Double(int a)
		{
			return a + a;
		}

		public static int AddZ2Z(ref PlugTestCase plugTestCase, int z)
		{
			return z + z;
		}
	}

	public class PlugTestTest : KernelTest
	{
		public PlugTestTest()
			: base("Plug")
		{
			testMethods.AddLast(PlugTestTest1);
			testMethods.AddLast(PlugTestTest2);
			testMethods.AddLast(PlugTestTest3);
		}

		public static bool PlugTestTest1()
		{
			return PlugTestCase.AddOne(10) == 11;
		}

		public static bool PlugTestTest2()
		{
			return PlugTestCase.Double(10) == 20;
		}

		public static bool PlugTestTest3()
		{
			PlugTestCase test = new PlugTestCase();
			return test.AddZ2Z(11) == 22;
		}
	}
}


text:
require 'test_helper'
require 'barby/barcode/ean_8'

class EAN8Test < Barby::TestCase

  describe 'validations' do

    before do
      @valid = EAN8.new('1234567')
    end

    it "should be valid with 7 digits" do
      assert @valid.valid?
    end

    it "should not be valid with less than 7 digits" do
      @valid.data = '123456'
      refute @valid.valid?
    end

    it "should not be valid with more than 7 digits" do
      @valid.data = '12345678'
      refute @valid.valid?
    end

    it "should not be valid with non-digits" do
      @valid.data = 'abcdefg'
      refute @valid.valid?
    end

  end

  describe 'checksum' do

    before :each do
      @code = EAN8.new('5512345')
    end

    it "should have the expected weighted_sum" do
      @code.weighted_sum.must_equal 53
    end

    it "should have the expected checksum" do
      @code.checksum.must_equal 7
    end

  end

  describe 'data' do

    before :each do
      @data = '5512345'
      @code = EAN8.new(@data)
    end

    it "should have the expected data" do
      @code.data.must_equal @data
    end

    it "should have the expected odd_and_even_numbers" do
      @code.odd_and_even_numbers.must_equal [[5,3,1,5],[4,2,5]]
    end

    it "should have the expected left_numbers" do
      #EAN-8 includes the first character in the left-hand encoding, unlike EAN-13
      @code.left_numbers.must_equal [5,5,1,2]
    end

    it "should have the expected right_numbers" do
      @code.right_numbers.must_equal [3,4,5,7]
    end

    it "should return the data with checksum on to_s" do
      @code.to_s.must_equal '55123457'
    end

  end

  describe 'encoding' do

    before :each do
      @code = EAN8.new('5512345')
    end

    it "should have the expected left_parity_map" do
      @code.left_parity_map.must_equal [:odd, :odd, :odd, :odd]
    end

    it "should have the expected left_encoding" do
      @code.left_encoding.must_equal '0110001011000100110010010011'
    end

    it "should have the expected right_encoding" do
      @code.right_encoding.must_equal '1000010101110010011101000100'
    end

  end

end


text:
#include "ToolTipWindow.h"

BEGIN_EVENT_TABLE(ToolTipWindow, wxPopupWindow)

    EVT_PAINT(              ToolTipWindow::OnPaint )
    EVT_MOTION(             ToolTipWindow::OnMouseMotion )
    EVT_MOUSE_CAPTURE_LOST( ToolTipWindow::OnMouseCaptureLost )

END_EVENT_TABLE()

ToolTipWindow::ToolTipWindow(wxWindow *parent, const wxString& text, const wxPoint& position)
{

    m_region    = wxRect(0, 0, 0, 0);
    m_useRegion = false;

    Create(parent);
    SetText(text);

    wxPoint point;

    if (position == wxDefaultPosition)
    {

        // Move the window to the cursor position.
        wxGetMousePosition(&point.x, &point.y);

        // We want to show the tip below the mouse, not over it
        //
        // NB: the reason we use "/ 2" here is that we don't know where the current
        //     cursors hot spot is... it would be nice if we could find this out
        //     though
        point.y += wxSystemSettings::GetMetric(wxSYS_CURSOR_Y) / 2;

    }
    else
    {
        point = position;
    }

    Position(point, wxSize(0, 0));

    Show(true);

}

ToolTipWindow::~ToolTipWindow()
{
    // If we still have the mouse capture, release it.
    if (GetCapture() == this)
    {
        ReleaseMouse();
    }
}

void ToolTipWindow::SetRegion(const wxRect& region)
{

    m_region    = region;
    m_useRegion = true;

    // Capture the mouse events so we can tell when the cursor moves.
    CaptureMouse();

}

void ToolTipWindow::SetText(const wxString& text)
{

    wxClientDC dc(this);
    dc.SetFont(GetFont());

    // calculate the length: we want each line be no longer than maxLength
    // pixels and we only break lines at words boundary
    wxString current;
    wxCoord height, width, widthMax = 0;
    m_heightLine = 0;

    bool breakLine = false;
    for ( const wxChar *p = text.c_str(); ; p++ )
    {
        if ( *p == _T('\n') || *p == _T('\0') )
        {
            dc.GetTextExtent(current, &width, &height);
            if ( width > widthMax )
                widthMax = width;

            if ( height > m_heightLine )
                m_heightLine = height;

            m_textLines.Add(current);

            if ( !*p )
            {
                // end of text
                break;
            }

            current.clear();
            breakLine = false;
        }
        else if ( breakLine && (*p == _T(' ') || *p == _T('\t')) )
        {
            // word boundary - break the line here
            m_textLines.Add(current);
            current.clear();
            breakLine = false;
        }
        else // line goes on
        {
            current += *p;
            dc.GetTextExtent(current, &width, &height);

            if ( width > widthMax )
                widthMax = width;

            if ( height > m_heightLine )
                m_heightLine = height;
        }
    }

    // take into account the border size and the margins
    width  = 2*(s_textMargin + 1) + widthMax;
    height = 2*(s_textMargin + 1) + wx_truncate_cast(wxCoord, m_textLines.GetCount()) * m_heightLine;
    SetClientSize(width, height);
    SetSize(0, 0, width, height);
}

void ToolTipWindow::OnPaint(wxPaintEvent& event)
{

    wxPaintDC dc(this);

    wxRect rect;
    wxSize size = GetClientSize();
    rect.width = size.x;
    rect.height = size.y;

    // First fill the background.

    wxColour bgColor = wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK);
    wxColour fgColor = wxSystemSettings::GetColour(wxSYS_COLOUR_INFOTEXT);

    dc.SetBrush(wxBrush(bgColor, wxSOLID));
    dc.SetPen( wxPen(fgColor, 1, wxSOLID) );
    dc.DrawRectangle(rect);

    // Draw the text line by line.

    dc.SetTextBackground(bgColor);
    dc.SetTextForeground(fgColor);
    dc.SetFont(GetFont());

    wxPoint pt;
    pt.x = s_textMargin;
    pt.y = s_textMargin;

    size_t count = m_textLines.GetCount();

    for ( size_t n = 0; n < count; n++ )
    {
        dc.DrawText(m_textLines[n], pt);
        pt.y += m_heightLine;
    }

}

void ToolTipWindow::OnMouseMotion(wxMouseEvent& event)
{

    wxPoint point = ClientToScreen(event.GetPosition());

    if (m_useRegion && !m_region.Contains(point))
    {
        // If the cursor has left the region, destroy the tool tip.
        if (!wxPendingDelete.Member(this))
        {
            wxPendingDelete.Append(this);
        }
    }

    event.Skip();

}

void ToolTipWindow::OnMouseCaptureLost(wxMouseCaptureLostEvent& event)
{
    if (!wxPendingDelete.Member(this))
    {
        wxPendingDelete.Append(this);
    }
}


text:
import {createSelector} from 'reselect';
import {FILTERS} from './actions';

export const filterTodos = createSelector(
    [
        state => state.todos,
        state => state.filter
    ],
    (todos, filter) => {
        switch (filter) {
            case FILTERS.SHOW_ALL:
                return todos;
            case FILTERS.SHOW_COMPLETED:
                return todos.filter(todo => todo.completed);
            case FILTERS.SHOW_ACTIVE:
                return todos.filter(todo => !todo.completed);
        }
    }
);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 2(1-6): 318 (1948)

#### Original name
Acanthostigma glabrescens Petr.

### Remarks
null


text:
package dmillerw.remoteio.tile;

import dmillerw.remoteio.tile.core.TileCore;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.*;

/**
 * @author dmillerw
 */
public class TileMachineReservoir extends TileCore implements IFluidHandler {

    public boolean filled = false;

    @Override
    public void writeCustomNBT(NBTTagCompound nbt) {
        nbt.setBoolean("filled", filled);
    }

    @Override
    public void readCustomNBT(NBTTagCompound nbt) {
        filled = nbt.getBoolean("filled");
    }

    @Override
    public void updateEntity() {
        if (!worldObj.isRemote && worldObj.getTotalWorldTime() % 20 == 0) {
            update();
            if (filled) push();
        }
    }

    @Override
    public void onNeighborUpdated() {
        update();
    }

    private void update() {
        int found = 0;
        for (ForgeDirection forgeDirection : ForgeDirection.VALID_DIRECTIONS) {
            Block block = worldObj.getBlock(xCoord + forgeDirection.offsetX, yCoord + forgeDirection.offsetY, zCoord + forgeDirection.offsetZ);
            if (block != null && (block == Blocks.water || block == Blocks.flowing_water)) found++;
        }
        boolean newFilled = found >= 2;
        if (filled != newFilled) worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
        filled = newFilled;
    }

    private void push() {
        int found = 0;
        for (ForgeDirection forgeDirection : ForgeDirection.VALID_DIRECTIONS) {
            TileEntity tileEntity = worldObj.getTileEntity(xCoord + forgeDirection.offsetX, yCoord + forgeDirection.offsetY, zCoord + forgeDirection.offsetZ);
            if (tileEntity != null && tileEntity instanceof IFluidHandler) found++;
        }

        final int amount = (int) ((float) FluidContainerRegistry.BUCKET_VOLUME / (float) found);

        for (ForgeDirection forgeDirection : ForgeDirection.VALID_DIRECTIONS) {
            TileEntity tileEntity = worldObj.getTileEntity(xCoord + forgeDirection.offsetX, yCoord + forgeDirection.offsetY, zCoord + forgeDirection.offsetZ);
            if (tileEntity != null && tileEntity instanceof IFluidHandler) {
                ((IFluidHandler) tileEntity).fill(forgeDirection.getOpposite(), new FluidStack(FluidRegistry.WATER, amount), true);
            }
        }
    }

    @Override
    public int fill(ForgeDirection from, FluidStack resource, boolean doFill) {
        return 0;
    }

    @Override
    public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {
        return new FluidStack(FluidRegistry.WATER, resource.amount);
    }

    @Override
    public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
        return new FluidStack(FluidRegistry.WATER, maxDrain);
    }

    @Override
    public boolean canFill(ForgeDirection from, Fluid fluid) {
        return false;
    }

    @Override
    public boolean canDrain(ForgeDirection from, Fluid fluid) {
        return true;
    }

    @Override
    public FluidTankInfo[] getTankInfo(ForgeDirection from) {
        return new FluidTankInfo[]{
                new FluidTankInfo(new FluidStack(FluidRegistry.WATER, FluidContainerRegistry.BUCKET_VOLUME), FluidContainerRegistry.BUCKET_VOLUME)
        };
    }
}


text:
@implementation MKSharedCache (Symbols)

//|++++++++++++++++++++++++++++++++++++|//
- (MKDSCLocalSymbols*)localSymbols
{
    if (_localSymbols == nil) {
        NSError *e = nil;

        _localSymbols = [[MKDSCLocalSymbols alloc] initWithSharedCache:self error:&e];
        if (_localSymbols == nil)
            MK_PUSH_UNDERLYING_WARNING(localSymbols, e, @"Could not load local symbols.");
    }

    return _localSymbols;
}

@end


text:
package org.hammerlab.guacamole.variants

import java.io.OutputStream

import org.apache.avro.generic.GenericDatumWriter
import org.apache.avro.io.EncoderFactory
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{ FileSystem, Path }
import org.apache.hadoop.mapred.FileAlreadyExistsException
import org.apache.spark.rdd.RDD
import org.apache.spark.{ HashPartitioner, SparkContext }
import org.bdgenomics.adam.rdd.variant.GenotypeRDD
import org.bdgenomics.formats.avro.{ Genotype => BDGGenotype }
import org.bdgenomics.utils.cli.ParquetArgs
import org.codehaus.jackson.JsonFactory
import org.hammerlab.commands.Args
import org.hammerlab.guacamole.logging.LoggingUtils.progress
import org.kohsuke.args4j.{ Option => Args4jOption }

/**
 * Arguments for writing output genotypes.
 *
 * Supports writing VCF, JSON, and Parquet formats.
 */
trait GenotypeOutputArgs
  extends ParquetArgs {

  self: Args =>

  @Args4jOption(
    name = "--out",
    metaVar = "VARIANTS_OUT",
    required = false,
    usage = "Variant output path. If not specified, print to screen."
  )
  var variantOutput: String = ""

  lazy val outputPathStr = variantOutput.stripMargin

  @Args4jOption(
    name = "--out-chunks",
    required = false,
    usage = "When writing out to json format, number of chunks to coalesce the genotypes RDD into."
  )
  var outChunks: Int = 1

  @Args4jOption(
    name = "--max-genotypes",
    required = false,
    usage = "Maximum number of genotypes to output. 0 (default) means output all genotypes."
  )
  var maxGenotypes: Int = 0

  /**
   * Perform validation of command line arguments at startup.
   * This allows some late failures (e.g. output file already exists) to be surfaced more quickly.
   */
  override def validate(sc: SparkContext): Unit = {
    if (outputPathStr.toLowerCase.endsWith(".vcf")) {
      val outputPath = new Path(outputPathStr)
      val filesystem = outputPath.getFileSystem(sc.hadoopConfiguration)
      if (filesystem.exists(outputPath)) {
        throw new FileAlreadyExistsException("Output directory " + outputPath + " already exists")
      }
    }
  }

  /**
   * Write out an RDD of Genotype instances to a file.
   *
   * @param genotypes ADAM genotypes (i.e. the variants)
   */
  def writeVariants(genotypes: GenotypeRDD): Unit = {

    val subsetGenotypes =
      if (maxGenotypes > 0) {
        progress(s"Subsetting to ${maxGenotypes} genotypes.")
        genotypes.copy(rdd = genotypes.rdd.sample(withReplacement = false, maxGenotypes, 0))
      } else {
        genotypes
      }

    writeSortedSampledVariants(subsetGenotypes)
  }

  private def writeSortedSampledVariants(genotypes: GenotypeRDD): Unit = {

    if (outputPathStr.isEmpty || outputPathStr.toLowerCase.endsWith(".json")) {
      writeJSONVariants(genotypes.rdd)
    } else if (outputPathStr.toLowerCase.endsWith(".vcf")) {
      progress(s"Writing genotypes to VCF file: $outputPathStr")
      val variantsRDD = genotypes.toVariantContextRDD
      val sortedCoalescedRDD =
        variantsRDD
          .rdd
          .keyBy(v => (v.variant.variant.getStart, v.variant.variant.getEnd))
          .repartitionAndSortWithinPartitions(new HashPartitioner(1))
          .values

      variantsRDD
        .copy(rdd = sortedCoalescedRDD)
        .saveAsVcf(outputPathStr)
    } else {
      progress(s"Writing genotypes to: $outputPathStr.")
      genotypes.saveAsParquet(
        outputPathStr,
        blockSize,
        pageSize,
        compressionCodec,
        disableDictionaryEncoding
      )
    }
  }

  private def writeJSONVariants(genotypes: RDD[BDGGenotype]): Unit = {
    val out: OutputStream =
      if (outputPathStr.isEmpty) {
        progress("Writing genotypes to stdout.")
        System.out
      } else {
        progress(s"Writing genotypes as JSON to: $outputPathStr")
        val filesystem = FileSystem.get(new Configuration())
        val path = new Path(outputPathStr)
        filesystem.create(path, true)
      }

    val coalescedGenotypes =
      if (outChunks > 0)
        genotypes.coalesce(outChunks)
      else
        genotypes

    coalescedGenotypes.persist()

    // Write each Genotype with a JsonEncoder.
    val schema = BDGGenotype.getClassSchema
    val writer = new GenericDatumWriter[Object](schema)
    val encoder = EncoderFactory.get.jsonEncoder(schema, out)
    val generator = new JsonFactory().createJsonGenerator(out)
    generator.useDefaultPrettyPrinter()
    encoder.configure(generator)
    var partitionNum = 0
    val numPartitions = coalescedGenotypes.partitions.length
    while (partitionNum < numPartitions) {
      progress(s"Collecting partition ${partitionNum + 1} of $numPartitions")

      val chunk =
        coalescedGenotypes
          .mapPartitionsWithIndex((num, genotypes) => {
            if (num == partitionNum)
              genotypes
            else
              Iterator.empty
          })
          .collect

      chunk.foreach(genotype => {
        writer.write(genotype, encoder)
        encoder.flush()
      })

      partitionNum += 1
    }

    out.write("\n".getBytes())
    generator.close()
    coalescedGenotypes.unpersist()
  }
}


text:
[![Node.js CI](https://github.com/swapnilnakate7/AngularJsTemplate/actions/workflows/node.js.yml/badge.svg?branch=master)](https://github.com/swapnilnakate7/AngularJsTemplate/actions/workflows/node.js.yml)

Latest Bootstrap and AngularJS read to start Template
* Download As .zip and then extract
* start npm go to unzipped directory
* run command `npm install`
* run command `npm run dev` to start running application in watch mode/ hot reload
* run command `npm run build` to build the application and generate the latest files in /build folder
* start second npm in another cmd/cli
* run command `npm start` and visit http://localhost:8080 to confirm if it's working


text:
"""
    pytest_pipeline.mark
    ~~~~~~~~~~~~~~~~~~~~

    Marks for pipeline run tests.

"""
# (c) 2014-2020 Wibowo Arindrarto <bow@bow.web.id>

import sys
from functools import wraps

# trying to emulate Python's builtin argument handling here
# so we can have decorators with optional arguments
def before_run(__firstarg=None, order=sys.maxsize, **kwargz):
    # first case: when decorator has no args
    # TODO: can we have less duplication here?
    if callable(__firstarg) and len(kwargz) == 0:

        func = __firstarg
        assert not hasattr(func, "_before_run_order"), \
            "Can not set existing '_before_run_order' attribute"

        func._before_run_order = order

        @wraps(func)
        def wrapped(self, *args, **kwargs):
            return func(self, *args, **kwargs)

        return wrapped
    # other cases: when decorator has args
    elif __firstarg is None:
        def onion(func):       # layers, right?
            assert not hasattr(func, "_before_run_order"), (
                "Can not set existing '_before_run_order' attribute"
            )
            func._before_run_order = order

            @wraps(func)
            def wrapped(self, *args, **kwargs):
                return func(self, *args, **kwargs)

            return wrapped

        return onion

    # fall through other cases
    raise ValueError("Decorator 'before_run' set incorrectly")


text:
"""
Contain API views that facilitate dealing with Facebook authentication.
"""

from django.contrib.auth.models import AnonymousUser
from rest_framework import generics
from rest_framework.exceptions import NotAuthenticated, PermissionDenied

class APIViewPermissionMixin:
    """
    A mixin for API views that provides a method for verifying permissions
    on different request types on the API view.
    """

    @staticmethod
    def raise_auth_error() -> None:
        """
        Raise an exception that indicates the user couldn't be authenticated.
        """
        raise NotAuthenticated("Couldn't authenticate user.")

    @staticmethod
    def raise_permission_error() -> None:
        """
        Raise an exception that indicates the user doesn't have permission for
        the requested operation.
        """
        raise PermissionDenied("User doesn't have permission for this action.")

    def verify_permission(self, user, request_type):
        """
        Checks whether a user has the permission to perform a request of
        certain type on this API view.

        :param user: The user.
        :param request_type: The type of the request: post, put, etc.
        """
        perm_code = getattr(self, request_type.lower() + '_perm_code')
        if perm_code is not None:
            if user is None or isinstance(user, AnonymousUser):
                self.raise_auth_error()
            if not user.has_perm(perm_code):
                self.raise_permission_error()

# pylint: disable=too-many-ancestors
class FBAuthListCreateAPIView(generics.ListCreateAPIView,
                              APIViewPermissionMixin):
    """
    A list and create API view with Facebook authentication enabled on
    requests.
    """

    def get(self, request, *args, **kwargs):
        """
        Implementation of HTTP GET request.
        """
        self.verify_permission(request.user, 'get')
        return super(FBAuthListCreateAPIView, self).get(
            request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        """
        Implementation of HTTP POST request.
        """
        self.verify_permission(request.user, 'post')
        return super(FBAuthListCreateAPIView, self).post(
            request, *args, **kwargs)

# pylint: enable=too-many-ancestors

# pylint: disable=too-many-ancestors
class FBAuthRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView,
                                         APIViewPermissionMixin):
    """
    A retrieve, update, and destroy API view with Facebook authentication
    enabled on requests.
    """

    def get(self, request, *args, **kwargs):
        """
        Implementation of HTTP GET request.
        """
        self.verify_permission(request.user, 'get')
        return super(FBAuthRetrieveUpdateDestroyAPIView, self).get(
            request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        """
        Implementation of HTTP POST request.
        """
        self.verify_permission(request.user, 'post')
        return self.put(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        """
        Implementation of HTTP PUT request.
        """
        self.verify_permission(request.user, 'put')
        return super(FBAuthRetrieveUpdateDestroyAPIView, self).put(
            request, *args, **kwargs)

    def patch(self, request, *args, **kwargs):
        """
        Implementation of HTTP PATCH request.
        """
        self.verify_permission(request.user, 'patch')
        return super(FBAuthRetrieveUpdateDestroyAPIView, self).patch(
            request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        """
        Implementation of HTTP DELETE request.
        """
        self.verify_permission(request.user, 'delete')
        return super(FBAuthRetrieveUpdateDestroyAPIView, self).delete(
            request, *args, **kwargs)
# pylint: enable=too-many-ancestors


text:
package hudson.remoting;

import org.jenkinsci.remoting.CallableDecorator;
import java.util.concurrent.*;

/**
 * List of {@link CallableDecorator} that provides aggregated decoration operation.
 *
 * @author Kohsuke Kawaguchi
 */
class CallableDecoratorList extends CopyOnWriteArrayList<CallableDecorator> {
    <V> java.util.concurrent.Callable<V> wrapCallable(java.util.concurrent.Callable<V> r) {
        for (CallableDecorator d : this)
            r = applyDecorator(r, d);
        return r;
    }

    private <V> java.util.concurrent.Callable<V> applyDecorator(final java.util.concurrent.Callable<V> inner, final CallableDecorator filter) {
        return new java.util.concurrent.Callable<V>() {
            public V call() throws Exception {
                return filter.call(inner);
            }
        };
    }

    <V,T extends Throwable> Callable<V,T> wrapUserRequest(final Callable<V,T> c) {
        Callable<V,T> decorated = c;

        for (CallableDecorator d : this)
            decorated = d.userRequest(c,decorated);

        return decorated;
    }

    // this class isn't actually getting serialized, but this makes FindBugs happy
    private static final long serialVersionUID = 1L;
}