text:
package com.tectonica.jonix.onix2;

import com.tectonica.jonix.common.JPU;
import com.tectonica.jonix.common.ListOfOnixDataComposite;
import com.tectonica.jonix.common.OnixComposite.OnixSuperComposite;
import com.tectonica.jonix.common.codelist.Languages;
import com.tectonica.jonix.common.codelist.RecordSourceTypes;
import com.tectonica.jonix.common.codelist.TextCaseFlags;
import com.tectonica.jonix.common.codelist.TextFormats;
import com.tectonica.jonix.common.codelist.TransliterationSchemes;
import com.tectonica.jonix.common.struct.JonixOnOrderDetail;

import java.io.Serializable;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DO NOT EDIT MANUALLY
 */

/**
 *
Stock quantity composite

 *

 * A repeatable group of data elements which together specify a quantity of stock and, where a supplier has more than
 * one warehouse, a supplier location. Optional.
 *

 *

 *

 * Reference name
 * <tt><Stock></tt>
 *

 *

 * Short tag
 * <tt><stock></tt>
 *

 *

 *

 * This tag may be included in the following composites:
 *

 *
<{@link SupplyDetail}>

 *

 *

 * Possible placements within ONIX message:
 *

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link SupplyDetail} ⯈ {@link Stock}

 *

 *
 * @since Onix-2.1
 */
public class Stock implements OnixSuperComposite, Serializable {
    private static final long serialVersionUID = 1L;

    public static final String refname = "Stock";
    public static final String shortname = "stock";

    /////////////////////////////////////////////////////////////////////////////////
    // ATTRIBUTES
    /////////////////////////////////////////////////////////////////////////////////

    public TextFormats textformat;

    public TextCaseFlags textcase;

    public Languages language;

    public TransliterationSchemes transliteration;

    /**
     * (type: DateOrDateTime)
     */
    public String datestamp;

    public RecordSourceTypes sourcetype;

    public String sourcename;

    /////////////////////////////////////////////////////////////////////////////////
    // CONSTRUCTION
    /////////////////////////////////////////////////////////////////////////////////

    private boolean initialized;
    private final boolean exists;
    private final org.w3c.dom.Element element;
    public static final Stock EMPTY = new Stock();

    public Stock() {
        exists = false;
        element = null;
        initialized = true; // so that no further processing will be done on this intentionally-empty object
    }

    public Stock(org.w3c.dom.Element element) {
        exists = true;
        initialized = false;
        this.element = element;
        textformat = TextFormats.byCode(JPU.getAttribute(element, "textformat"));
        textcase = TextCaseFlags.byCode(JPU.getAttribute(element, "textcase"));
        language = Languages.byCode(JPU.getAttribute(element, "language"));
        transliteration = TransliterationSchemes.byCode(JPU.getAttribute(element, "transliteration"));
        datestamp = JPU.getAttribute(element, "datestamp");
        sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype"));
        sourcename = JPU.getAttribute(element, "sourcename");
    }

    @Override
    public void _initialize() {
        if (initialized) {
            return;
        }
        initialized = true;

        JPU.forElementsOf(element, e -> {
            final String name = e.getNodeName();
            switch (name) {
                case StockQuantityCoded.refname:
                case StockQuantityCoded.shortname:
                    stockQuantityCoded = new StockQuantityCoded(e);
                    break;
                case LocationIdentifier.refname:
                case LocationIdentifier.shortname:
                    locationIdentifier = new LocationIdentifier(e);
                    break;
                case LocationName.refname:
                case LocationName.shortname:
                    locationName = new LocationName(e);
                    break;
                case OnHand.refname:
                case OnHand.shortname:
                    onHand = new OnHand(e);
                    break;
                case OnOrder.refname:
                case OnOrder.shortname:
                    onOrder = new OnOrder(e);
                    break;
                case CBO.refname:
                case CBO.shortname:
                    cbo = new CBO(e);
                    break;
                case OnOrderDetail.refname:
                case OnOrderDetail.shortname:
                    onOrderDetails = JPU.addToList(onOrderDetails, new OnOrderDetail(e));
                    break;
                default:
                    break;
            }
        });
    }

    /**
     * @return whether this tag (<Stock> or <stock>) is explicitly provided in the ONIX XML
     */
    @Override
    public boolean exists() {
        return exists;
    }

    @Override
    public org.w3c.dom.Element getXmlElement() {
        return element;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // MEMBERS
    /////////////////////////////////////////////////////////////////////////////////

    private StockQuantityCoded stockQuantityCoded = StockQuantityCoded.EMPTY;

    /**
     *

     * A group of data elements which together specify coded stock level without stating the exact quantity of stock.
     * Either <StockQuantityCoded> or <OnHand> is mandatory in each occurrence of the <Stock>
     * composite, even if the onhand quantity is zero. Non-repeating.
     *

     * Jonix-Comment: this field is required
     */
    public StockQuantityCoded stockQuantityCoded() {
        _initialize();
        return stockQuantityCoded;
    }

    private LocationIdentifier locationIdentifier = LocationIdentifier.EMPTY;

    /**
     *

     * A group of data elements which together define the identifier of a stock location in accordance with a specified
     * scheme, and allowing different types of location identifier to be supported without defining additional data
     * elements. Optional and non-repeating.
     *

     * Jonix-Comment: this field is optional
     */
    public LocationIdentifier locationIdentifier() {
        _initialize();
        return locationIdentifier;
    }

    private LocationName locationName = LocationName.EMPTY;

    /**
     *

     * The name of a stock location. Optional and non-repeating.
     *

     * Jonix-Comment: this field is optional
     */
    public LocationName locationName() {
        _initialize();
        return locationName;
    }

    private OnHand onHand = OnHand.EMPTY;

    /**
     *

     * The quantity of stock on hand. Either <StockQuantityCoded> or <OnHand> is mandatory in each
     * occurrence of the <Stock> composite, even if the onhand quantity is zero. Non-repeating.
     *

     * Jonix-Comment: this field is optional
     */
    public OnHand onHand() {
        _initialize();
        return onHand;
    }

    private OnOrder onOrder = OnOrder.EMPTY;

    /**
     *

     * The quantity of stock on order. Optional and non-repeating.
     *

     * Jonix-Comment: this field is optional
     */
    public OnOrder onOrder() {
        _initialize();
        return onOrder;
    }

    private CBO cbo = CBO.EMPTY;

    /**
     *

     * The quantity of stock on order which is already committed to meet backorders. Optional and non-repeating.
     *

     * Jonix-Comment: this field is optional
     */
    public CBO cbo() {
        _initialize();
        return cbo;
    }

    private ListOfOnixDataComposite<OnOrderDetail, JonixOnOrderDetail> onOrderDetails = ListOfOnixDataComposite.empty();

    /**
     *

     * A repeatable group of data elements which together specify details of a stock shipment currently awaited,
     * normally from overseas. Optional.
     *

     * Jonix-Comment: this list may be empty
     */
    public ListOfOnixDataComposite<OnOrderDetail, JonixOnOrderDetail> onOrderDetails() {
        _initialize();
        return onOrderDetails;
    }
}


text:
namespace Microsoft.Graph
{
    public partial class UserMailFoldersCollectionRequestBuilder
    {
        /// <summary>
        /// Gets the Deleted Items mail folder request builder.
        /// </summary>
        public IMailFolderRequestBuilder DeletedItems
        {
            get { return new MailFolderRequestBuilder(this.AppendSegmentToRequestUrl(Constants.Url.DeletedItems), this.Client); }
        }

        /// <summary>
        /// Gets the Drafts mail folder request builder.
        /// </summary>
        public IMailFolderRequestBuilder Drafts
        {
            get { return new MailFolderRequestBuilder(this.AppendSegmentToRequestUrl(Constants.Url.Drafts), this.Client); }
        }

        /// <summary>
        /// Gets the Inbox mail folder request builder.
        /// </summary>
        public IMailFolderRequestBuilder Inbox
        {
            get { return new MailFolderRequestBuilder(this.AppendSegmentToRequestUrl(Constants.Url.Inbox), this.Client); }
        }

        /// <summary>
        /// Gets the Sent Items mail folder request builder.
        /// </summary>
        public IMailFolderRequestBuilder SentItems
        {
            get { return new MailFolderRequestBuilder(this.AppendSegmentToRequestUrl(Constants.Url.SentItems), this.Client); }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Fridge\SubscriptionBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class FridgeSubscriptionExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {

        if (!isset($configs[0]['user_class'])) {
            throw new \InvalidArgumentException(
                'The "user_class" option must be set for the "fridge_subscription" bundle'
            );
        }

        if (!isset($configs[0]['stripe_sk'])) {
            throw new \InvalidArgumentException(
                'The "stripe_sk" option must be set for the "fridge_subscription" bundle'
            );
        }

        $container->setParameter(
            'fridge_subscription.user_class',
            $configs[0]['user_class']
        );

        $container->setParameter(
            'fridge_subscription.stripe_sk',
            $configs[0]['stripe_sk']
        );

        $container->setParameter(
            'fridge_subscription.enable_listeners',
            $configs[0]['enable_listeners']
        );

        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}


text: Flow and correlation study in heavy ion collisions


text:
using ACE.Demo.Contracts.Services;
using ACE.WS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace ACE.Demo.Web.Controllers
{
    public class HomeController : ControllerBase
    {
        public HomeController(IServiceBus serviceBus)
            : base(null, serviceBus)
        {
        }

        public async Task<ActionResult> Index()
        {
            IEnumerable<Investment> investments =
                await ServiceBus.InvokeAsync<GetInvestmentsRequest, IEnumerable<Investment>>(new GetInvestmentsRequest());
            return View(investments);
        }
    }
}


text:
package com.zebdar.tom.chat;

/**
 * Created by Administrator on 2017/6/23.
 */

public class MessageTypes {

    public static final String MSG_TYPE_TEXT="msg_type_text";//文本消息
    public static final String MSG_TYPE_IMG="msg_type_img";//图片
    public static final String MSG_TYPE_VOICE="msg_type_voice";//语音
    public static final String MSG_TYPE_LOCATION="msg_type_location";//位置
}


text:
import contextlib
import signal
import socket
import sys
import threading

def run_interactive_shell(serverFunc, stdin=True, stdout=True, port=5005):
 addr = '127.0.0.1'

 readyFlag = threading.Event()
 t = threading.Thread(target=console_loop, args=(addr, port, readyFlag, stdin, stdout))
 t.setDaemon(True)
 t.start()

 start_socket_server(serverFunc, addr, port, readyFlag)

 try:
  t.join()
 except KeyboardInterrupt:
  pass

def start_socket_server(serverFunc, addr, port, readyFlag=None):
 with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  abortFlag = threading.Event()

  def sigHandler(sig, frame):
   if not abortFlag.isSet():
    print("Aborting...")
    abortFlag.set()
  oldHandler = signal.signal(signal.SIGINT, sigHandler)

  sock.settimeout(1)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  sock.bind((addr, port))
  sock.listen(0)

  if readyFlag:
   readyFlag.set()

  while True:
   try:
    conn, addr = sock.accept()
    break
   except socket.timeout:
    if abortFlag.isSet():
     conn = None
     break

  signal.signal(signal.SIGINT, oldHandler)
  serverFunc(conn)

def console_loop(addr, port, readyFlag=None, stdin=True, stdout=True):
 if readyFlag:
  readyFlag.wait()
 with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
  sock.connect((addr, port))
  stopped = threading.Event()
  if stdin:
   t = threading.Thread(target=stdin_loop, args=(sock, stopped))
   t.setDaemon(True)
   t.start()
  if stdout:
   stdout_loop(sock)
  stopped.set()
  if stdin:
   print('Please press enter')
   t.join()

def stdin_loop(sock, stoppedFlag):
 while not stoppedFlag.isSet():
  try:
   sock.send(sys.stdin.readline().encode('latin1', 'replace'))
  except ConnectionError:
   break

def stdout_loop(sock):
 while True:
  try:
   d = sock.recv(4096)
   if d == b'':
    raise ConnectionError()
   sys.stdout.write(d.decode('latin1', 'replace'))
   sys.stdout.flush()
  except ConnectionError:
   break


text:
window.initializeCodeFolding = function(show) {

  // handlers for show-all and hide all
  $("#rmd-show-all-code").click(function() {
    $('div.r-code-collapse').each(function() {
      $(this).collapse('show');
    });
  });
  $("#rmd-hide-all-code").click(function() {
    $('div.r-code-collapse').each(function() {
      $(this).collapse('hide');
    });
  });

  // index for unique code element ids
  var currentIndex = 1;

  // select all R code blocks
  var rCodeBlocks = $('pre.r, pre.python, pre.bash, pre.sql, pre.cpp, pre.stan, pre.julia, pre.foldable');
  rCodeBlocks.each(function() {

    // create a collapsable div to wrap the code in
    var div = $('

');
    var showThis = (show || $(this).hasClass('fold-show')) && !$(this).hasClass('fold-hide');
    var id = 'rcode-643E0F36' + currentIndex++;
    div.attr('id', id);
    $(this).before(div);
    $(this).detach().appendTo(div);

    // add a show code button right above
    var showCodeText = $('' + (showThis ? 'Hide' : 'Code') + '');
    var showCodeButton = $('<button type="button" class="btn btn-default btn-xs btn-secondary btn-sm code-folding-btn pull-right float-right"></button>');
    showCodeButton.append(showCodeText);
    showCodeButton
        .attr('data-toggle', 'collapse')
        .attr('data-target', '#' + id)
        .attr('aria-expanded', showThis)
        .attr('aria-controls', id);

    var buttonRow = $('

');
    var buttonCol = $('

');

    buttonCol.append(showCodeButton);
    buttonRow.append(buttonCol);

    div.before(buttonRow);

    // show the div if necessary
    if (showThis) div.collapse('show');

    // update state of button on show/hide
    //   * Change text
    //   * add a class for intermediate states styling
    div.on('hide.bs.collapse', function () {
      showCodeText.text('Code');
      showCodeButton.addClass('btn-collapsing');
    });
    div.on('hidden.bs.collapse', function () {
      showCodeButton.removeClass('btn-collapsing');
    });
    div.on('show.bs.collapse', function () {
      showCodeText.text('Hide');
      showCodeButton.addClass('btn-expanding');
    });
    div.on('shown.bs.collapse', function () {
      showCodeButton.removeClass('btn-expanding');
    });

  });

}


text:
package org.apache.samoa.streams.fs;

import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.MiniDFSCluster.Builder;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.samoa.streams.fs.HDFSFileStreamSource;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class HDFSFileStreamSourceTest {

  private static final String[] HOSTS = { "localhost" };
  private static final String BASE_DIR = "/minidfsTest";
  private static final int NUM_FILES_IN_DIR = 4;
  private static final int NUM_NOISE_FILES_IN_DIR = 2;

  private HDFSFileStreamSource streamSource;

  private Configuration config;
  private MiniDFSCluster hdfsCluster;
  private String hdfsURI;

  @Before
  public void setUp() throws Exception {
    // Start MiniDFSCluster
    MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(new Configuration()).hosts(HOSTS).numDataNodes(1)
        .format(true);
    hdfsCluster = builder.build();
    hdfsCluster.waitActive();
    hdfsURI = "hdfs://localhost:" + hdfsCluster.getNameNodePort();

    // Construct stream source
    streamSource = new HDFSFileStreamSource();

    // General config
    config = new Configuration();
    config.set("fs.defaultFS", hdfsURI);
  }

  @After
  public void tearDown() throws Exception {
    hdfsCluster.shutdown();
  }

  /*
   * Init tests
   */
  @Test
  public void testInitWithSingleFileAndExtension() {
    // write input file
    writeSimpleFiles(BASE_DIR, "txt", 1);

    // init with path to input file
    streamSource.init(config, BASE_DIR + "/1.txt", "txt");

    // assertions
    assertEquals("Size of filePaths is not correct.", 1, streamSource.getFilePathListSize(), 0);
    String fn = streamSource.getFilePathAt(0);
    assertTrue("Incorrect file in filePaths.",
        fn.equals(BASE_DIR + "/1.txt") || fn.equals(hdfsURI + BASE_DIR + "1.txt"));
  }

  @Test
  public void testInitWithSingleFileAndNullExtension() {
    // write input file
    writeSimpleFiles(BASE_DIR, "txt", 1);

    // init with path to input file
    streamSource.init(config, BASE_DIR + "/1.txt", null);

    // assertions
    assertEquals("Size of filePaths is not correct.", 1, streamSource.getFilePathListSize(), 0);
    String fn = streamSource.getFilePathAt(0);
    assertTrue("Incorrect file in filePaths.",
        fn.equals(BASE_DIR + "/1.txt") || fn.equals(hdfsURI + BASE_DIR + "1.txt"));
  }

  @Test
  public void testInitWithFolderAndExtension() {
    // write input files & noise files
    writeSimpleFiles(BASE_DIR, "txt", NUM_FILES_IN_DIR);
    writeSimpleFiles(BASE_DIR, null, NUM_NOISE_FILES_IN_DIR);

    // init with path to input dir
    streamSource.init(config, BASE_DIR, "txt");

    // assertions
    assertEquals("Size of filePaths is not correct.", NUM_FILES_IN_DIR, streamSource.getFilePathListSize(), 0);
    Set<String> filenames = new HashSet<String>();
    for (int i = 1; i <= NUM_FILES_IN_DIR; i++) {
      String targetFn = BASE_DIR + "/" + Integer.toString(i) + ".txt";
      filenames.add(targetFn);
      filenames.add(hdfsURI + targetFn);
    }
    for (int i = 0; i < NUM_FILES_IN_DIR; i++) {
      String fn = streamSource.getFilePathAt(i);
      assertTrue("Incorrect file in filePaths:" + fn, filenames.contains(fn));
    }
  }

  @Test
  public void testInitWithFolderAndNullExtension() {
    // write input file
    writeSimpleFiles(BASE_DIR, null, NUM_FILES_IN_DIR);

    // init with path to input dir
    streamSource.init(config, BASE_DIR, null);

    // assertions
    assertEquals("Size of filePaths is not correct.", NUM_FILES_IN_DIR, streamSource.getFilePathListSize(), 0);
    Set<String> filenames = new HashSet<String>();
    for (int i = 1; i <= NUM_FILES_IN_DIR; i++) {
      String targetFn = BASE_DIR + "/" + Integer.toString(i);
      filenames.add(targetFn);
      filenames.add(hdfsURI + targetFn);
    }
    for (int i = 0; i < NUM_FILES_IN_DIR; i++) {
      String fn = streamSource.getFilePathAt(i);
      assertTrue("Incorrect file in filePaths:" + fn, filenames.contains(fn));
    }
  }

  /*
   * getNextInputStream tests
   */
  @Test
  public void testGetNextInputStream() {
    // write input files & noise files
    writeSimpleFiles(BASE_DIR, "txt", NUM_FILES_IN_DIR);

    // init with path to input dir
    streamSource.init(config, BASE_DIR, "txt");

    // call getNextInputStream & assertions
    Set<String> contents = new HashSet<String>();
    for (int i = 1; i <= NUM_FILES_IN_DIR; i++) {
      contents.add(Integer.toString(i));
    }
    for (int i = 0; i < NUM_FILES_IN_DIR; i++) {
      InputStream inStream = streamSource.getNextInputStream();
      assertNotNull("Unexpected end of input stream list.", inStream);

      BufferedReader rd = new BufferedReader(new InputStreamReader(inStream));
      String inputRead = null;
      try {
        inputRead = rd.readLine();
      } catch (IOException ioe) {
        fail("Fail reading from stream at index:" + i + ioe.getMessage());
      }
      assertTrue("File content is incorrect.", contents.contains(inputRead));
      Iterator<String> it = contents.iterator();
      while (it.hasNext()) {
        if (it.next().equals(inputRead)) {
          it.remove();
          break;
        }
      }
    }

    // assert that another call to getNextInputStream will return null
    assertNull("Call getNextInputStream after the last file did not return null.", streamSource.getNextInputStream());
  }

  /*
   * getCurrentInputStream tests
   */
  public void testGetCurrentInputStream() {
    // write input files & noise files
    writeSimpleFiles(BASE_DIR, "txt", NUM_FILES_IN_DIR);

    // init with path to input dir
    streamSource.init(config, BASE_DIR, "txt");

    // call getNextInputStream, getCurrentInputStream & assertions
    for (int i = 0; i <= NUM_FILES_IN_DIR; i++) { // test also after-end-of-list
      InputStream inStream1 = streamSource.getNextInputStream();
      InputStream inStream2 = streamSource.getCurrentInputStream();
      assertSame("Incorrect current input stream.", inStream1, inStream2);
    }
  }

  /*
   * reset tests
   */
  public void testReset() {
    // write input files & noise files
    writeSimpleFiles(BASE_DIR, "txt", NUM_FILES_IN_DIR);

    // init with path to input dir
    streamSource.init(config, BASE_DIR, "txt");

    // Get the first input string
    InputStream firstInStream = streamSource.getNextInputStream();
    String firstInput = null;
    assertNotNull("Unexpected end of input stream list.", firstInStream);

    BufferedReader rd1 = new BufferedReader(new InputStreamReader(firstInStream));
    try {
      firstInput = rd1.readLine();
    } catch (IOException ioe) {
      fail("Fail reading from stream at index:0" + ioe.getMessage());
    }

    // call getNextInputStream a few times
    streamSource.getNextInputStream();

    // call reset, call next, assert that output is 1 (the first file)
    try {
      streamSource.reset();
    } catch (IOException ioe) {
      fail("Fail resetting stream source." + ioe.getMessage());
    }

    InputStream inStream = streamSource.getNextInputStream();
    assertNotNull("Unexpected end of input stream list.", inStream);

    BufferedReader rd2 = new BufferedReader(new InputStreamReader(inStream));
    String inputRead = null;
    try {
      inputRead = rd2.readLine();
    } catch (IOException ioe) {
      fail("Fail reading from stream at index:0" + ioe.getMessage());
    }
    assertEquals("File content is incorrect.", firstInput, inputRead);
  }

  private void writeSimpleFiles(String path, String ext, int numOfFiles) {
    // get filesystem
    FileSystem dfs;
    try {
      dfs = hdfsCluster.getFileSystem();
    } catch (IOException ioe) {
      fail("Could not access MiniDFSCluster" + ioe.getMessage());
      return;
    }

    // create basedir
    Path basedir = new Path(path);
    try {
      dfs.mkdirs(basedir);
    } catch (IOException ioe) {
      fail("Could not create DIR:" + path + "\n" + ioe.getMessage());
      return;
    }

    // write files
    for (int i = 1; i <= numOfFiles; i++) {
      String fn = null;
      if (ext != null) {
        fn = Integer.toString(i) + "." + ext;
      } else {
        fn = Integer.toString(i);
      }

      try {
        OutputStream fin = dfs.create(new Path(path, fn));
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(fin));
        wr.write(Integer.toString(i));
        wr.close();
        fin.close();
      } catch (IOException ioe) {
        fail("Fail writing to input file: " + fn + " in directory: " + path + ioe.getMessage());
      }
    }
  }

}


text:
require 'spec_helper'

describe 'couchpotato::install', :type => :class do
  context 'on Debian' do
    let :facts do
      {
        :osfamily => 'Debian',
      }
    end

    it { should contain_couchpotato__install }

    it do
      should contain_vcsrepo('couchpotato').with(
        :ensure => 'latest',
        :provider => 'git',
      )
    end

    it do
      should contain_file('/etc/init.d/couchpotato').with(
        :ensure => 'present',
        :source => '/couchpotato/init/ubuntu',
        :mode => '0755',
        :require => 'Vcsrepo[couchpotato]',
      )
    end

  end
end


text:
package org.apereo.cas.ticket.registry;

import org.apereo.cas.ticket.Ticket;
import org.infinispan.Cache;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * This is {@link InfinispanTicketRegistry}. Infinispan is a distributed in-memory key/value data store with optional schema.
 * It offers advanced functionality such as transactions, events, querying and distributed processing.
 * See http://infinispan.org/features/ for more info.
 *
 * @author Misagh Moayyed
 * @since 4.2.0
 */
public class InfinispanTicketRegistry extends AbstractTicketRegistry {

    private Cache cache;

    /**
     * Instantiates a new Infinispan ticket registry.
     */
    public InfinispanTicketRegistry() {
    }

    @Override
    public void updateTicket(final Ticket ticket) {
        this.cache.put(ticket.getId(), ticket);
    }

    /**
     * Add a ticket to the registry. Ticket storage is based on the ticket id.
     *
     * @param ticketToAdd The ticket we wish to add to the cache.
     */
    @Override
    public void addTicket(final Ticket ticketToAdd) {
        final Ticket ticket = encodeTicket(ticketToAdd);
        this.cache.put(ticket.getId(), ticket,
                ticket.getExpirationPolicy().getTimeToLive(), TimeUnit.SECONDS,
                ticket.getExpirationPolicy().getTimeToIdle(), TimeUnit.SECONDS);
    }

    /**
     * Retrieve a ticket from the registry.
     *
     * @param ticketId the id of the ticket we wish to retrieve
     * @return the requested ticket.
     */
    @Override
    public Ticket getTicket(final String ticketId) {
        final String encTicketId = encodeTicketId(ticketId);
        if (ticketId == null) {
            return null;
        }
        final Ticket ticket = Ticket.class.cast(cache.get(encTicketId));
        return ticket;
    }

    @Override
    public boolean deleteSingleTicket(final String ticketId) {
        this.cache.evict(ticketId);
        return getTicket(ticketId) == null;
    }

    /**
     *
     * Retrieve all tickets from the registry.
     *
     * Note! Usage of this method can be computational and I/O intensive and should not be used for other than
     * debugging.
     *
     * @return collection of tickets currently stored in the registry. Tickets
     *         might or might not be valid i.e. expired.
     */
    @Override
    public Collection<Ticket> getTickets() {
        return decodeTickets(this.cache.values());
    }

    public void setCache(final Cache<String, Ticket> cache) {
        this.cache = cache;
    }
}


text:
package org.apache.spark.sql.profiler

import java.lang.{StringBuilder => JavaStringBuilder}
import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.util
import java.util.Comparator

import scala.collection.mutable.ArrayBuffer

import org.apache.carbondata.common.logging.LogServiceFactory
import org.apache.carbondata.core.stats.TaskStatistics
import org.apache.carbondata.core.util.CarbonUtil

/**
 * the util of profiler logger
 */
private[profiler] object ProfilerLogger {

  val LOGGER = LogServiceFactory.getLogService(this.getClass.getCanonicalName)

  lazy val simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")

  // format timestamp value
  def format(time: Long): String = this.synchronized {
    if (time < 0) {
      ""
    } else {
      val timestamp = new Timestamp(time)
      simpleDateFormat.format(timestamp)
    }
  }

  def logStatementSummary(statementId: Long, messages: ArrayBuffer[ProfilerMessage]): Unit = {
    LOGGER.info(new StatementSummary(statementId, messages).toString)
  }

  def logExecutionSummary(executionId: Long, messages: ArrayBuffer[ProfilerMessage]): Unit = {
    LOGGER.info(new ExecutionSummary(executionId, messages).toString)
  }
}

/**
 * summarize the statement information
 */
private[profiler] class StatementSummary(
    statementId: Long,
    messages: ArrayBuffer[ProfilerMessage]
) {

  private var sqlText: String = ""

  private var isCommand = false

  private var startTime: Long = -1

  private var parserEnd: Long = -1

  private var analyzerEnd: Long = -1

  private var optimizerStart: Long = -1

  private var optimizerEnd: Long = -1

  private var optimizerTaken: Long = -1

  private var endTime: Long = -1

  // summarize the messages
  messages.foreach {
    case sqlStart: SQLStart =>
      sqlText = sqlStart.sqlText.trim
      isCommand = sqlStart.isCommand
      startTime = sqlStart.startTime
      parserEnd = sqlStart.parseEnd
      analyzerEnd = sqlStart.analyzerEnd
      endTime = sqlStart.endTime
    case optimizer: Optimizer =>
      optimizerTaken = optimizer.timeTaken
      optimizerStart = optimizer.startTime
      optimizerEnd = optimizerStart + optimizerTaken
  }

  private def totalTaken: Long = endTime - startTime

  private def parserTaken: Long = parserEnd - startTime

  private def analyzerTaken: Long = analyzerEnd - parserEnd

  private def parserToOptimizer: Long = optimizerEnd - startTime

  private def commandTaken: Long = endTime - analyzerEnd

  override def toString: String = {
    if (isCommand) {
      buildForComand()
    } else {
      buildForQuery()
    }
  }

  /**
   * for example
   * [statement id]: 1
   * [sql text]:
   * +-----------------------------------------------------------+
   * |CREATE TABLE carbon_table(                                 |
   * | shortField SHORT,                                         |
   * | intField INT,                                             |
   * | bigintField LONG,                                         |
   * | doubleField DOUBLE,                                       |
   * | stringField STRING,                                       |
   * | timestampField TIMESTAMP,                                 |
   * | decimalField DECIMAL(18,2),                               |
   * | dateField DATE,                                           |
   * | charField CHAR(5),                                        |
   * | floatField FLOAT                                          |
   * | )                                                         |
   * | STORED AS carbondata                                      |
   * +-----------------------------------------------------------+
   * [start time]: 2018-03-22 17:12:18.310
   * [driver side total taken]: 1255 ms
   *   |__ 1.parser taken: 203 ms
   *   |__ 2.analyzer taken: 1 ms
   *   |__ 3.execution taken: 1051 ms
   *   |__ ...
   */
  private def buildForComand(): String = {
    val builder = new JavaStringBuilder(1000)
    builder.append(s"\n[statement id]: ${ statementId }")
    builder.append(s"\n[sql text]:\n")
    CarbonUtil.logTable(builder, sqlText, "")
    builder.append(s"\n[start time]: ${ ProfilerLogger.format(startTime) }\n")
    builder.append(s"[driver side total taken]: $totalTaken ms\n")
    builder.append(s"  |__ 1.parser taken: $parserTaken ms\n")
    builder.append(s"  |__ 2.analyzer taken: $analyzerTaken ms\n")
    builder.append(s"  |__ 3.execution taken: $commandTaken ms")
    builder.toString
  }

  /**
   * for example
   * [statement id]: 4
   * [sql text]:
   * +--------------------------------------------------+
   * |SELECT charField, stringField, intField           |
   * | FROM carbon_table                                |
   * | WHERE stringfield = 'spark' AND decimalField > 40|
   * +--------------------------------------------------+
   * [start time]: 2018-03-22 17:12:22.001
   * [driver side total taken]: 476ms
   * |__ 1.parser taken: 82 ms
   * |__ 2.analyzer taken: 195 ms
   * |__ 3.(149ms)
   * |__ 4.carbon optimizer taken: 50 ms
   *       end time: 2018-03-22 17:12:22.477
   */
  private def buildForQuery(): String = {
    val builder = new JavaStringBuilder(1000)
    builder.append(s"\n[statement id]: ${ statementId }")
    builder.append(s"\n[sql text]:\n")
    CarbonUtil.logTable(builder, sqlText, "")
    builder.append(s"\n[start time]: ${ ProfilerLogger.format(startTime) }\n")
    builder.append(s"[driver side total taken]: ${ parserToOptimizer }ms\n")
    builder.append(s"  |__ 1.parser taken: $parserTaken ms\n")
    builder.append(s"  |__ 2.analyzer taken: $analyzerTaken ms\n")
    builder.append(s"  |__ 3.(${ optimizerStart - analyzerEnd }ms)\n")
    builder.append(s"  |__ 4.carbon optimizer taken: $optimizerTaken ms\n")
    builder.append(s"        end time: ${ ProfilerLogger.format(optimizerEnd) }")
    builder.toString
  }
}

/**
 * summarize the execution information
 */
private[profiler] class ExecutionSummary(
    executionId: Long,
    messages: ArrayBuffer[ProfilerMessage]
) {

  private var sqlPlan: String = ""

  private var startTime: Long = -1

  private var endTime: Long = -1

  private val partitions = new util.ArrayList[GetPartition]()

  private val tasks = new util.ArrayList[TaskStatistics]()

  // summarize the messages
  messages.foreach {
    case start: ExecutionStart =>
      sqlPlan = start.plan
      startTime = start.startTime
    case end: ExecutionEnd =>
      endTime = end.endTime
    case partition: GetPartition =>
      partitions.add(partition)
    case task: QueryTaskEnd =>
      tasks.add(new TaskStatistics(task.queryId, task.values, task.size, task.files))
  }

  private def totalTaken: Long = endTime - startTime

  /**
   * for example
   * (prepare inputFormat 55ms)~(getSplits 90ms)~(distributeSplits 4ms)~(3ms)
   */
  private def detail(p: GetPartition, builder: JavaStringBuilder): Unit = {
    builder.append("(prepare inputFormat ").append(p.getSplitsStart - p.startTime).append("ms)~")
    builder.append("(getSplits ").append(p.getSplitsEnd - p.getSplitsStart).append("ms)~")
    val gap1 = p.distributeStart - p.getSplitsEnd
    if (gap1 > 0) {
      builder.append("(").append(gap1).append("ms)~")
    }
    builder.append("(distributeSplits ").append(p.distributeEnd - p.distributeStart).append("ms)")
    val gap2 = p.endTime - p.distributeEnd
    if (gap2 > 0) {
      builder.append("~(").append(gap2).append("ms)")
    }
  }

  private def printGetPartitionTable(builder: JavaStringBuilder, indent: String): Unit = {
    util.Collections.sort(partitions)
    for (rowIndex <- 0 until partitions.size()) {
      val partition = partitions.get(rowIndex)
      val content = new JavaStringBuilder()
      content.append("query_id: ").append(partition.queryId).append("\n")
        .append("table_name: ").append(partition.tableName).append("\n")
        .append("table_path: ").append(partition.tablePath).append("\n")
        .append("start_time: ").append(ProfilerLogger.format(partition.startTime)).append("\n")
      // total time
      content.append("total_time: ").append(partition.endTime - partition.startTime).append("ms")
      content.append(" [")
      detail(partition, content)
      content.append("]\n")
      content.append("valid_segment_num: ").append(partition.numSegments).append("\n")
        .append("stream_segment_num: ").append(partition.numStreamSegments).append("\n")
        .append("hit_data_block: ").append(partition.numBlocks).append("\n")
        .append("spark_partition_num: ").append(partition.numOfPartitions).append("\n")
        .append("pushed_filter: ").append(partition.filter).append("\n")
        .append("pushed_projection: ").append(partition.projection)
      if (rowIndex > 0) {
        builder.append("\n")
      }
      CarbonUtil.logTable(builder, content.toString, indent)
    }
  }

  private def printStatisticTable(builder: JavaStringBuilder, indent: String): Unit = {
    util.Collections.sort(tasks, comparator)
    TaskStatistics.printStatisticTable(tasks, builder, indent)
  }

  private def printInputFiles(builder: JavaStringBuilder, indent: String): Unit = {
    for (taskIndex <- 0 until tasks.size()) {
      val task = tasks.get(taskIndex)
      val content = new JavaStringBuilder()
      content.append("query_id: ").append(task.getQueryId).append("\n")
        .append("task_id: ").append(task.getValues()(1)).append("\n")
        .append("total_size: ").append(task.getFileSize).append("Byte\n")
        .append("file_list: ")
      task.getFiles.foreach { file =>
        content.append("\n  Segment_").append(file)
      }
      if (taskIndex > 0) {
        builder.append("\n")
      }
      CarbonUtil.logTable(builder, content.toString, indent)
    }
  }

  // use to sort tasks
  private lazy val comparator = new Comparator[TaskStatistics]() {
    override def compare(o1: TaskStatistics,
        o2: TaskStatistics) = {
      val result = o1.getQueryId.compareTo(o2.getQueryId())
      if (result != 0) {
        result
      } else {
        val task = o1.getValues()(1) - o2.getValues()(1)
        if (task > 0) {
          1
        } else if (task < 0) {
          -1
        } else {
          0
        }
      }
    }
  }

  // scalastyle:off
  /**
   * for example
   * [execution id]: 0
   * [start time]: 2018-03-22 17:12:22.608
   * [executor side total taken]: 845 ms
   *   |_1.getPartition
   *     +------------------------------------------------------------------------------------------------------------------+
   *     |query_id: 23737310772188                                                                                |
   *     |table_name: default.carbon_table                                                                                |
   *     |table_path: /carbondata/examples/spark/target/store/default/carbon_table                                         |
   *     |start_time: 2018-03-22 17:12:23.141                                                                               |
   *     |total_time: 152ms [(prepare inputFormat 55ms)~(getSplits 90ms)~(distributeSplits 4ms)~(3ms)]                      |
   *     |valid_segment_num: 1                                                                                |
   *     |stream_segment_num: 1                                                                                |
   *     |hit_data_block: 1                                                                                |
   *     |spark_partition_num: 1                                                                                |
   *     |pushed_filter: (((stringfield <> null and decimalfield <> null) and stringfield = spark) and decimalfield > 40.00)|
   *     |pushed_projection: charfield,stringfield,intfield                                                                 |
   *     +------------------------------------------------------------------------------------------------------------------+
   *   |_2.task statistics
   *     +--------------+-------+-----------------------+----------+----------------+--------------------+----------------+--------------+---------------+---------------+---------------+-----------+-------------+-----------+-----------+
   *     |query_id      |task_id|start_time             |total_time|load_blocks_time|load_dictionary_time|carbon_scan_time|carbon_IO_time|scan_blocks_num|total_blocklets|valid_blocklets|total_pages|scanned_pages|valid_pages|result_size|
   *     +--------------+-------+-----------------------+----------+----------------+--------------------+----------------+--------------+---------------+---------------+---------------+-----------+-------------+-----------+-----------+
   *     |23737310772188|      0|2018-03-22 17:12:23.334|     106ms|             3ms|                 0ms|            -1ms|          -1ms|              1|              1|              1|          0|            1|          1|          3|
   *     +--------------+-------+-----------------------+----------+----------------+--------------------+----------------+--------------+---------------+---------------+---------------+-----------+-------------+-----------+-----------+
   *   |_3.input files for each task
   *     +--------------------------------------------------------+
   *     |query_id: 23737310772188                                |
   *     |task_id: 0                                              |
   *     |total_size: 2717Byte                                    |
   *     |file_list:                                              |
   *     |  Segment_0/part-0-0_batchno0-0-1521709939969.carbondata|
   *     +--------------------------------------------------------+
   * [sql plan]:
   * +----------+
   * | ...      |
   * +----------+
   */
  // scalastyle:on
  override def toString: String = {
    val builder = new JavaStringBuilder(1000)
    builder.append(s"\n[execution id]: ${ executionId }\n")
    builder.append(s"[start time]: ${ ProfilerLogger.format(startTime) }\n")
    builder.append(s"[executor side total taken]: $totalTaken ms")
    builder.append(s"\n  |_1.getPartition\n")
    printGetPartitionTable(builder, "    ")
    builder.append(s"\n  |_2.task statistics\n")
    printStatisticTable(builder, "    ")
    builder.append(s"\n  |_3.input files for each task\n")
    printInputFiles(builder, "    ")
    builder.append(s"\n[sql plan]:\n")
    CarbonUtil.logTable(builder, sqlPlan, "")
    builder.toString
  }
}


text:
var frisby   = require('frisby');
var datatest = require('./data');
var util     = require('util');
var url      = require('url');

module.exports = {
  runTalkTests : runTalkTests
}

function runTalkTests(userAccessToken, talks_uri) {
  testCreateTalkFailsIfNotLoggedIn(talks_uri);
  testCreateTalkFailsWithIncorrectData(userAccessToken, talks_uri);
}

function testCreateTalkFailsIfNotLoggedIn(talks_uri)
{
  frisby.create('Create talk fails if not logged in')
    .post(
      talks_uri,
      {},
      {json: true}
    )
    .afterJSON(function(result) {
      expect(result[0]).toContain("You must be logged in");
    })
    .expectStatus(401) // fails as no user token
    .toss();
}

function testCreateTalkFailsWithIncorrectData(access_token, talks_uri) {
  frisby.create('Create talk fails with missing name')
      .post(
      talks_uri,
      {},
      {json : true, headers : {'Authorization' : 'oauth ' + access_token}}
  )
      .expectStatus(400)
      .afterJSON(function (result) {
        expect(result[0]).toContain("The talk title field is required");
      })
      .toss();

    frisby.create('Create talk fails with missing description')
        .post(
        talks_uri,
        {'talk_title' : 'talk_title'},
        {json : true, headers : {'Authorization' : 'oauth ' + access_token}}
    )
        .expectStatus(400)
        .afterJSON(function (result) {
            expect(result[0]).toContain("The talk description field is required");
        })
        .toss();

    frisby.create('Create talk fails with missing date and time')
        .post(
        talks_uri,
        {
            'talk_title' : 'talk_title',
            'talk_description' : 'talk-description',
        },
        {json : true, headers : {'Authorization' : 'oauth ' + access_token}}
    )
        .expectStatus(400)
        .afterJSON(function (result) {
            expect(result[0]).toContain("Please give the date and time of the talk");
        })
        .toss();

    frisby.create('Create talk works with minimum fields')
        .post(
            talks_uri,
            {
                'talk_title' : 'talk_title',
                'talk_description' : 'talk-description',
                'start_date' : (new Date()).toISOString()
            },
            {json : true, headers : {'Authorization' : 'oauth ' + access_token}}
        )
        .expectStatus(201)
        .expectHeaderContains('Location', '/talks/')
        .toss();

    frisby.create('Create talk with Escaped title')
        .post(
            talks_uri,
            {
                "talk_title" : "Frisby \"test ' Ölrücklaufstoßdämpfer",
                "talk_description" : "'Ölrücklaufstoßdämpfer\"",
                "start_date" : (new Date()).toISOString(),
            },
            {json: true, headers: {json: true, 'Authorization' : 'oauth ' + access_token, 'Content-type': 'application/json'}}
        )
        .expectStatus(201) // Created as it is automatically approved
        .expectHeaderContains("Location", "/talks/")
        .after(function(err, res, body) {
            if(res.statusCode == 201) {
                // We have an event, we can test it!
                var event_uri = res.headers.location;
                frisby.create('Get Talkwith EscapedTitle')
                    .get(event_uri)
                    .expectStatus(200) // Created as it is automatically approved
                    .expectJSON("talks.?", {
                        "talk_title" : "Frisby \"test ' Ölrücklaufstoßdämpfer",
                        "talk_description" : "'Ölrücklaufstoßdämpfer\""
                    })
                    .toss();
            }
        })
        .toss();
}


text:
/**
 * In this file the different environments are declared. For safety reasons, the credentials are in secret.json
 * secret.json is not commited to the .git directory
 * Authentification is set to SSH Keys, so you need to have your public key on the server!
 *
 * TODO: maybe add database options to the environments for syncing options ?
 */

'use strict';

var basePath = 'build/';

module.exports = {

	// example secret.json:
	/* ------------------------------------------------------
	{

		"server": {
			"production": {
				"host": "domain.com",
				"user": "admin",
				"path": "/var/www/domain.com/"
			},
			"staging": {
				"host": "domain.com",
				"user": "admin",
				"path": "/var/www/domain.com/"
			},
			"testing": {
				"host": "testing.com",
				"user": "testuser",
				"path": "/var/www/testing.com/"
			},
			"development": {
				"host": "dev.domain.com",
				"user": "admin",
				"path": "/var/www/development.domain.com/"
			}
		}

	}

	------------------------------------------------------ */

	production: {
		host: '<%= secret.server.production.host %>',
		port: 22,
		username: '<%= secret.server.production.user %>',
		path: '<%= secret.server.production.path %>',
		agent: process.env.SSH_AUTH_SOCK,
		showProgress: true,
		srcBasePath: basePath
	},
	staging: {
		host: '<%= secret.server.staging.host %>',
		port: 22,
		username: '<%= secret.server.staging.user %>',
		path: '<%= secret.server.staging.path %>',
		agent: process.env.SSH_AUTH_SOCK,
		showProgress: true,
		srcBasePath: basePath
	},
	testing: {
		host: '<%= secret.server.testing.host %>',
		port: 22,
		username: '<%= secret.server.testing.user %>',
		path: '<%= secret.server.testing.path %>',
		agent: process.env.SSH_AUTH_SOCK,
		showProgress: true,
		srcBasePath: basePath
	},
	development: {
		host: '<%= secret.server.development.host %>',
		port: 22,
		username: '<%= secret.server.development.user %>',
		path: '<%= secret.server.development.path %>',
		agent: process.env.SSH_AUTH_SOCK,
		showProgress: true,
		srcBasePath: basePath
	}

};


text:
Perform a rolling update of the given ReplicationController.

### Synopsis

Perform a rolling update of the given ReplicationController.

Replaces the specified controller with new controller, updating one pod at a time to use the
new PodTemplate. The new-controller.json must specify the same namespace as the
existing controller and overwrite at least one (common) label in its replicaSelector.

```
kubectl rolling-update OLD_CONTROLLER_NAME -f NEW_CONTROLLER_SPEC
```

### Examples

```
// Update pods of frontend-v1 using new controller data in frontend-v2.json.
$ kubectl rolling-update frontend-v1 -f frontend-v2.json

// Update pods of frontend-v1 using JSON data passed into stdin.
$ cat frontend-v2.json | kubectl rolling-update frontend-v1 -f -
```

### Options

```
  -f, --filename="": Filename or URL to file to use to create the new controller.
  -h, --help=false: help for rolling-update
      --poll-interval="3s": Time delay between polling controller status after update. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
      --timeout="5m0s": Max time to wait for a controller to update before giving up. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
      --update-period="1m0s": Time to wait between updating pods. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
```

### Options inherrited from parent commands

```
      --alsologtostderr=false: log to standard error as well as files
      --api-version="": The API version to use when talking to the server
  -a, --auth-path="": Path to the auth info file. If missing, prompt the user. Only used if using https.
      --certificate-authority="": Path to a cert. file for the certificate authority.
      --client-certificate="": Path to a client key file for TLS.
      --client-key="": Path to a client key file for TLS.
      --cluster="": The name of the kubeconfig cluster to use
      --context="": The name of the kubeconfig context to use
      --insecure-skip-tls-verify=false: If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure.
      --kubeconfig="": Path to the kubeconfig file to use for CLI requests.
      --log_backtrace_at=:0: when logging hits line file:N, emit a stack trace
      --log_dir=: If non-empty, write log files in this directory
      --log_flush_frequency=5s: Maximum number of seconds between log flushes
      --logtostderr=true: log to standard error instead of files
      --match-server-version=false: Require server version to match client version
      --namespace="": If present, the namespace scope for this CLI request.
      --password="": Password for basic authentication to the API server.
  -s, --server="": The address and port of the Kubernetes API server
      --stderrthreshold=2: logs at or above this threshold go to stderr
      --token="": Bearer token for authentication to the API server.
      --user="": The name of the kubeconfig user to use
      --username="": Username for basic authentication to the API server.
      --v=0: log level for V logs
      --validate=false: If true, use a schema to validate the input before sending it
      --vmodule=: comma-separated list of pattern=N settings for file-filtered logging
```

### SEE ALSO
* [kubectl](kubectl.md)	 - kubectl controls the Kubernetes cluster manager

###### Auto generated by spf13/cobra at 2015-04-16 17:04:37.38985117 +0000 UTC


text:
require 'spec_helper'
module Recommendation
    class ProductBuyCountSpec
        describe "ProductBuyCount" do

            context ".generate product buy count (no user scenario)" do
                it "should not create product buy count if there are no users" do
                    ProductBuyCount.generate()
                    ProductBuyCount.count().should eql(0)
                end
            end

            context ".generate product buy count (one user scenario)" do
                it "should not create product buy count if there are no purchases" do
                    user = FactoryGirl.create(:user)
                    create_search_behavior(1111,true, user.id)
                    ProductBuyCount.generate()
                    ProductBuyCount.count().should eql(0)
                end

                it "should create only one product buy count when there is one purchase" do
                    user = FactoryGirl.create(:user)
                    create_search_and_purchase_behavior(1111, 1, user.id)
                    ProductBuyCount.generate()
                    ProductBuyCount.count().should eql(1)
                    product_buy_count = ProductBuyCount.find(:first)
                    assert_product_buy_count(product_buy_count,1111,user.id,1)
                end

                it "should create product buy counts when there are many purchases of a single product" do
                    user = FactoryGirl.create(:user)
                    create_search_and_purchase_behavior(1111, 3, user.id)
                    ProductBuyCount.generate()
                    ProductBuyCount.count().should eql(1)
                    product_buy_count = ProductBuyCount.find(:first)
                    assert_product_buy_count(product_buy_count,1111,user.id,3)
                end

                it "should create product buy counts when there are many purchases across products" do
                    user = FactoryGirl.create(:user)
                    create_search_and_purchase_behavior(1111, 3, user.id)
                    create_search_and_purchase_behavior(2222, 2, user.id)
                    ProductBuyCount.generate()
                    ProductBuyCount.count().should eql(2)
                    product_buy_count = ProductBuyCount.find(:all)
                    assert_product_buy_count(product_buy_count[0], 1111, user.id, 3)
                    assert_product_buy_count(product_buy_count[1], 2222, user.id, 2)
                end

            end

            context ".generate product buy count (multiple user scenario)" do
                it "should not create product buy count if there are no purchases" do
                    user1 = FactoryGirl.create(:user)
                    user2 = FactoryGirl.create(:user)
                    create_search_behavior(1111,true, user1.id)
                    create_search_behavior(1122,true, user2.id)
                    ProductBuyCount.generate()
                    ProductBuyCount.count().should eql(0)
                end

                it "should not create product buy count for the users with no behaviors" do
                    user1 = FactoryGirl.create(:user)
                    user2 = FactoryGirl.create(:user)
                    create_search_and_purchase_behavior(1111, 1, user1.id)
                    ProductBuyCount.generate()
                    ProductBuyCount.count().should eql(1)
                    product_buy_count = ProductBuyCount.find(:first)
                    assert_product_buy_count(product_buy_count, 1111, user1.id, 1)
                end

                it "should create product buy count if a single product is purchased by many users" do
                    user1 = FactoryGirl.create(:user)
                    user2 = FactoryGirl.create(:user)
                    create_search_and_purchase_behavior(1111, 1, user1.id)
                    create_search_and_purchase_behavior(1111, 1, user2.id)
                    ProductBuyCount.generate()
                    ProductBuyCount.count().should eql(2)
                    product_buy_count = ProductBuyCount.find(:all)
                    assert_product_buy_count(product_buy_count[0], 1111, user1.id, 1)
                    assert_product_buy_count(product_buy_count[1], 1111, user2.id, 1)
                end

                it "should create product buy count if mutiple products are purchased by many users" do
                    user1 = FactoryGirl.create(:user)
                    user2 = FactoryGirl.create(:user)

                    create_search_and_purchase_behavior(1111, 2, user1.id)
                    create_search_and_purchase_behavior(2222, 3, user1.id)

                    create_search_and_purchase_behavior(1111, 1, user2.id)
                    create_search_and_purchase_behavior(3333, 2, user2.id)
                    ProductBuyCount.generate()
                    ProductBuyCount.count().should eql(4)
                    product_buy_count = ProductBuyCount.find(:all)
                    assert_product_buy_count(product_buy_count[0], 1111, user1.id, 2)
                    assert_product_buy_count(product_buy_count[1], 2222, user1.id, 3)
                    assert_product_buy_count(product_buy_count[2], 1111, user2.id, 1)
                    assert_product_buy_count(product_buy_count[3], 3333, user2.id, 2)
                end

            end

            private
            def assert_product_buy_count(product_buy_count, product_id, user_id, purchase_count)
                product_buy_count.product_id.should eql(product_id)
                product_buy_count.user_id.should eql(user_id)
                product_buy_count.count.should eql(purchase_count)

            end
            def create_search_and_purchase_behavior(product_id,number_of_behaviors,user_id)
                number_of_behaviors.times do |index|
                    create_search_behavior(product_id,true, user_id)
                    create_purchase_behavior(product_id,index + rand() , user_id)
                end
            end
            def create_search_behavior(product, is_available, user)
                FactoryGirl.create(:search_behavior, product: product, is_available: is_available, user_id: user)
            end

            def create_purchase_behavior(product, order, user)
                FactoryGirl.create(:purchase_behavior, :parameters => "{\"products\": [#{product}], \"order\": #{order} }", :user_id => user)
            end
        end
    end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.tensorics.core.tensorbacked (tensorics-core API)</title>
<meta name="date" content="2019-07-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.tensorics.core.tensorbacked

Interfaces

Tensorbacked

Classes

AbstractTensorbacked

OngoingTensorbackedCompletion

TensorbackedBuilder

TensorbackedInternals

Tensorbackeds


text:
#include <Memory/Stack/StackAllocator.hpp>
#include <Memory/AllocationHeaderBuilder.hpp>
#include <memory>

namespace Doremi
{
    namespace Utilities
    {
        namespace Memory
        {
            StackAllocator::StackAllocator() : m_top(nullptr) {}

            void StackAllocator::Initialize(const size_t& p_memorySize)
            {
                // Allocate the memory to use, the stackallocator does not use a global alignment.
                MemoryAllocator::Initialize(p_memorySize, 0);
                Clear();
            }

            void* StackAllocator::AllocateAligned(const size_t& p_memorySize, const uint8_t& p_alignment)
            {
                if(p_alignment % 2 != 0)
                {
                    // TODO logging
                    throw std::runtime_error("Alignment must be a tuple of 2.");
                }
                if(p_alignment == 0)
                {
                    // TODO logging
                    throw std::runtime_error("Alignment must be larger than 1.");
                }

                // Compute the desired memorysize
                const size_t expandedSize = p_memorySize + p_alignment;

                // Fetch the unaligned data.
                void* rawAdress = AllocateUnaligned(expandedSize);

                // Compute adjustment
                const uint8_t adjustment = ComputeAdjustment(rawAdress, p_alignment);

                // Final adress
                void* alignedAdress = reinterpret_cast<void*>(reinterpret_cast<size_t>(rawAdress) + adjustment);

                // Set adjustment metadata
                AllocationHeaderBuilder::SetAdjustment(alignedAdress, adjustment);

                return alignedAdress;
            }

            void* StackAllocator::AllocateUnaligned(const size_t& p_newMemorySize)
            {
                if(m_occupiedMemory + p_newMemorySize < m_totalMemory)
                {
                    void* returnAdress = m_top;
                    m_top = reinterpret_cast<void*>(reinterpret_cast<size_t>(m_top) + p_newMemorySize);

                    // Update the currently occupied data information
                    m_occupiedMemory += p_newMemorySize;

                    return returnAdress;
                }
                else
                {
                    throw std::runtime_error("Error allocating - Not enough memory left in this stack.");
                    // TODORT maybe allocate dynamically instead?
                    //
                    // TODORT log
                }
            }

            void StackAllocator::Clear()
            {
                m_top = GetAdressStartAligned();
                m_occupiedMemory = 0;
            }

            void StackAllocator::FreeToMarker(const MemoryMarker& p_marker)
            {
                if(p_marker.VerifyManager(this))
                {
                    void* adress = p_marker.GetMarkerAdress();
                    if(reinterpret_cast<size_t>(adress) > reinterpret_cast<size_t>(m_top))
                    {
                        // Compute adjustment
                        const uint8_t adjustment = AllocationHeaderBuilder::GetAdjustment(adress);

                        // Compute the new top of the stack
                        m_top = reinterpret_cast<void*>(reinterpret_cast<size_t>(adress) - adjustment);

                        // Compute the new total available data
                        m_occupiedMemory = reinterpret_cast<size_t>(m_top) - reinterpret_cast<size_t>(GetAdressStartAligned());
                    }
                    else
                    { /* The marker is no longer valid, it points to memory that has already been released. */
                    }
                }
                else
                {
                    // TODO logging
                    throw std::runtime_error("Wrong marker used.");
                }
            }

            MemoryMarker StackAllocator::GetMarker() { return MemoryMarker(m_top, this); }
        }
    }
}


text:
  {% assign thumb = site.featimg | replace: '.jpg', '' %}
  {% assign imgSrc = site.media_folder | prepend: site.baseurl | replace: '//', '/' %}
  {% assign imgSrc = imgSrc | append: '/covers/' | append: thumb | append: '.jpg' %}
  {% assign imgHeight = '' %}

  {% if page.permalink == '/' %}
    {% assign imgHeight = 'logo-image-home' %}
  {% endif %}


text:
//
//  SCBuyerToolBar.h
//  SCGoJD
//
//  Created by mac on 15/9/27.
//  Copyright (c) 2015年 mac. All rights reserved.
//  用户购买收藏的工具栏

#import <UIKit/UIKit.h>

@class SCBuyerToolBar;
@class SCMyProductItem;

@protocol SCBuyerToolBarDelegate <NSObject>

@optional

- (void)toolBar:(SCBuyerToolBar *)toolBar didClickButtonAtIndex:(NSUInteger)index;

@end

@interface SCBuyerToolBar : UIView

@property (nonatomic, weak) id <SCBuyerToolBarDelegate> delegate;
/**
 *   反映顾客与商品关系的数据模型
 */
@property (nonatomic, strong) SCMyProductItem *item;

@end


text:
<?php

class Todolist extends DbTodolist
{
  public function __construct($id=null) {
    parent::__construct($id);
  }
}


text:
Error message when server returns undefined error.

<div class="definition">
    String, default = 'AJAX error. See console for more details.'
</div>

If you do not like default message, you are welcome to define your own.

<textarea class="javascript">
$('#form').w2form({
    name          : 'form',
    header        : 'Form Header',
    msgAJAXerrror : 'Uncaught AJAX error',
    fields: [
        { name: 'first_name', type: 'text', required: true },
        { name: 'last_name', type: 'text', required: true },
        { name: 'email', type: 'email' }
    ],
    record: {
        first_name    : 'John',
        last_name     : 'Doe',
        email         : 'jdoe@email.com'
    },
    actions: {
        "save": function () { this.validate(); },
        "reset": function () { this.clear(); }
    }
});
</textarea>


text:
package com.facebook.buck.cli;

import static com.facebook.buck.jvm.java.JavaTest.COMPILED_TESTS_LIBRARY_FLAVOR;
import static org.junit.Assert.assertEquals;

import com.facebook.buck.android.AndroidBinaryBuilder;
import com.facebook.buck.android.AndroidLibraryBuilder;
import com.facebook.buck.core.config.FakeBuckConfig;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.model.targetgraph.TargetGraph;
import com.facebook.buck.core.model.targetgraph.TargetGraphFactory;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.core.sourcepath.FakeSourcePath;
import com.facebook.buck.jvm.java.JavaBinaryRuleBuilder;
import com.facebook.buck.jvm.java.JavaLibraryBuilder;
import com.facebook.buck.jvm.java.JavaTestBuilder;
import com.facebook.buck.jvm.java.KeystoreBuilder;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.util.json.ObjectMappers;
import com.facebook.buck.versions.VersionedAliasBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.SortedSet;
import org.junit.Before;
import org.junit.Test;

public class AuditClasspathCommandTest {

  private TestConsole console;
  private AuditClasspathCommand auditClasspathCommand;
  private CommandRunnerParams params;

  @Before
  public void setUp() throws IOException, InterruptedException {
    console = new TestConsole();
    auditClasspathCommand = new AuditClasspathCommand();
    params =
        CommandRunnerParamsForTesting.builder()
            .setConsole(console)
            .setToolchainProvider(AndroidBinaryBuilder.createToolchainProviderForAndroidBinary())
            .build();
  }

  @Test
  public void testClassPathOutput() throws Exception {
    // Test that no output is created.
    auditClasspathCommand.printClasspath(
        params, TargetGraphFactory.newInstance(ImmutableSet.of()), ImmutableSet.of());
    assertEquals("", console.getTextWrittenToStdOut());
    assertEquals("", console.getTextWrittenToStdErr());

    // Add build rules such that all implementations of HasClasspathEntries are tested.
    BuildTarget javaLibraryTarget = BuildTargetFactory.newInstance("//:test-java-library");
    BuildTarget testJavaTarget = BuildTargetFactory.newInstance("//:project-tests");
    BuildTarget androidLibraryTarget = BuildTargetFactory.newInstance("//:test-android-library");
    BuildTarget keystoreTarget = BuildTargetFactory.newInstance("//:keystore");
    BuildTarget testAndroidTarget = BuildTargetFactory.newInstance("//:test-android-binary");

    TargetNode<?> javaLibraryNode =
        JavaLibraryBuilder.createBuilder(javaLibraryTarget)
            .addSrc(Paths.get("src/com/facebook/TestJavaLibrary.java"))
            .addTest(testJavaTarget)
            .build();
    TargetNode<?> androidLibraryNode =
        AndroidLibraryBuilder.createBuilder(androidLibraryTarget)
            .addSrc(Paths.get("src/com/facebook/TestAndroidLibrary.java"))
            .addDep(javaLibraryTarget)
            .build();
    TargetNode<?> keystoreNode =
        KeystoreBuilder.createBuilder(keystoreTarget)
            .setStore(FakeSourcePath.of("debug.keystore"))
            .setProperties(FakeSourcePath.of("keystore.properties"))
            .build();
    TargetNode<?> testAndroidNode =
        AndroidBinaryBuilder.createBuilder(testAndroidTarget)
            .setManifest(FakeSourcePath.of("AndroidManifest.xml"))
            .setKeystore(keystoreTarget)
            .setOriginalDeps(ImmutableSortedSet.of(androidLibraryTarget, javaLibraryTarget))
            .build();
    TargetNode<?> testJavaNode =
        JavaTestBuilder.createBuilder(testJavaTarget)
            .addDep(javaLibraryTarget)
            .addSrc(Paths.get("src/com/facebook/test/ProjectTests.java"))
            .build();

    TargetGraph targetGraph =
        TargetGraphFactory.newInstance(
            ImmutableSet.of(
                javaLibraryNode, androidLibraryNode, keystoreNode, testAndroidNode, testJavaNode));
    auditClasspathCommand.printClasspath(params, targetGraph, ImmutableSet.of());

    // Still empty.
    assertEquals("", console.getTextWrittenToStdOut());
    assertEquals("", console.getTextWrittenToStdErr());

    // Request the top build target. This will test the following:
    // - paths don't appear multiple times when dependencies are referenced multiple times.
    // - dependencies are walked
    // - independent targets in the same BUCK file are not included in the output
    auditClasspathCommand.printClasspath(params, targetGraph, ImmutableSet.of(testAndroidTarget));

    Path root = javaLibraryTarget.getUnflavoredBuildTarget().getCellPath();
    SortedSet<String> expectedPaths =
        Sets.newTreeSet(
            Arrays.asList(
                root.resolve(
                        BuildTargetPaths.getGenPath(
                                params.getCell().getFilesystem(),
                                androidLibraryTarget,
                                "lib__%s__output")
                            .resolve(androidLibraryTarget.getShortName() + ".jar"))
                    .toString(),
                root.resolve(
                        BuildTargetPaths.getGenPath(
                                params.getCell().getFilesystem(),
                                javaLibraryTarget,
                                "lib__%s__output")
                            .resolve(javaLibraryTarget.getShortName() + ".jar"))
                    .toString()));
    String expectedClasspath =
        String.join(System.lineSeparator(), expectedPaths) + System.lineSeparator();

    assertEquals(expectedClasspath, console.getTextWrittenToStdOut());
    assertEquals("", console.getTextWrittenToStdErr());

    // Add independent test target. This will test:
    // - the union of the classpath is output.
    // - all rules have implemented HasClasspathEntries.
    // Note that the output streams are reset.
    setUp();
    auditClasspathCommand.printClasspath(
        params,
        TargetGraphFactory.newInstance(
            ImmutableSet.of(
                javaLibraryNode, androidLibraryNode, keystoreNode, testAndroidNode, testJavaNode)),
        ImmutableSet.of(
            testAndroidTarget, javaLibraryTarget, androidLibraryTarget, testJavaTarget));

    BuildTarget testJavaCompiledJar = testJavaTarget.withFlavors(COMPILED_TESTS_LIBRARY_FLAVOR);

    expectedPaths.add(
        root.resolve(
                BuildTargetPaths.getGenPath(
                        params.getCell().getFilesystem(), testJavaCompiledJar, "lib__%s__output")
                    .resolve(testJavaCompiledJar.getShortNameAndFlavorPostfix() + ".jar"))
            .toString());
    expectedClasspath = String.join(System.lineSeparator(), expectedPaths) + System.lineSeparator();
    assertEquals(expectedClasspath, console.getTextWrittenToStdOut());
    assertEquals("", console.getTextWrittenToStdErr());
  }

  private static final String EXPECTED_JSON =
      Joiner.on("")
          .join(
              "{",
              "\"//:test-android-library\":",
              "[",
              "%s,",
              "%s",
              "],",
              "\"//:test-java-library\":",
              "[",
              "%s",
              "]",
              "}");

  @Test
  public void testJsonClassPathOutput() throws Exception {
    // Build a DependencyGraph of build rules manually.

    BuildTarget javaTarget = BuildTargetFactory.newInstance("//:test-java-library");
    TargetNode<?> javaNode =
        JavaLibraryBuilder.createBuilder(javaTarget)
            .addSrc(Paths.get("src/com/facebook/TestJavaLibrary.java"))
            .build();

    BuildTarget androidTarget = BuildTargetFactory.newInstance("//:test-android-library");
    TargetNode<?> androidNode =
        AndroidLibraryBuilder.createBuilder(androidTarget)
            .addSrc(Paths.get("src/com/facebook/TestAndroidLibrary.java"))
            .addDep(javaTarget)
            .build();

    auditClasspathCommand.printJsonClasspath(
        params,
        TargetGraphFactory.newInstance(ImmutableSet.of(androidNode, javaNode)),
        ImmutableSet.of(androidTarget, javaTarget));

    Path root = javaTarget.getCellPath();
    ObjectMapper objectMapper = ObjectMappers.legacyCreate();
    String expected =
        String.format(
            EXPECTED_JSON,
            objectMapper.valueToTree(
                root.resolve(
                    BuildTargetPaths.getGenPath(
                            params.getCell().getFilesystem(), javaTarget, "lib__%s__output")
                        .resolve(javaTarget.getShortName() + ".jar"))),
            objectMapper.valueToTree(
                root.resolve(
                    BuildTargetPaths.getGenPath(
                            params.getCell().getFilesystem(), androidTarget, "lib__%s__output")
                        .resolve(androidTarget.getShortName() + ".jar"))),
            objectMapper.valueToTree(
                root.resolve(
                    BuildTargetPaths.getGenPath(
                            params.getCell().getFilesystem(), javaTarget, "lib__%s__output")
                        .resolve(javaTarget.getShortName() + ".jar"))));
    assertEquals(expected, console.getTextWrittenToStdOut());

    assertEquals("", console.getTextWrittenToStdErr());
  }

  @Test
  public void testClassPathWithVersions() throws Exception {

    // Build the test target graph.
    TargetNode<?> javaLibrary =
        JavaLibraryBuilder.createBuilder(BuildTargetFactory.newInstance("//:test-java-library"))
            .addSrc(Paths.get("src/com/facebook/TestJavaLibrary.java"))
            .build();
    TargetNode<?> androidLibrary =
        JavaLibraryBuilder.createBuilder(BuildTargetFactory.newInstance("//:test-android-library"))
            .addSrc(Paths.get("src/com/facebook/TestAndroidLibrary.java"))
            .addDep(javaLibrary.getBuildTarget())
            .build();
    TargetNode<?> version =
        new VersionedAliasBuilder(BuildTargetFactory.newInstance("//:version"))
            .setVersions("1.0", "//:test-android-library")
            .build();
    TargetNode<?> binary =
        new JavaBinaryRuleBuilder(BuildTargetFactory.newInstance("//:rule"))
            .setDeps(ImmutableSortedSet.of(version.getBuildTarget()))
            .build();
    TargetGraph targetGraph =
        TargetGraphFactory.newInstance(javaLibrary, androidLibrary, version, binary);

    // Run the command.
    auditClasspathCommand.printClasspath(
        params.withBuckConfig(
            FakeBuckConfig.builder()
                .setSections(ImmutableMap.of("build", ImmutableMap.of("versions", "true")))
                .build()),
        targetGraph,
        ImmutableSet.of(androidLibrary.getBuildTarget(), javaLibrary.getBuildTarget()));

    // Verify output.
    Path root = javaLibrary.getBuildTarget().getUnflavoredBuildTarget().getCellPath();
    ImmutableSortedSet<String> expectedPaths =
        ImmutableSortedSet.of(
            root.resolve(
                    BuildTargetPaths.getGenPath(
                            params.getCell().getFilesystem(),
                            androidLibrary.getBuildTarget(),
                            "lib__%s__output")
                        .resolve(androidLibrary.getBuildTarget().getShortName() + ".jar"))
                .toString(),
            root.resolve(
                    BuildTargetPaths.getGenPath(
                            params.getCell().getFilesystem(),
                            javaLibrary.getBuildTarget(),
                            "lib__%s__output")
                        .resolve(javaLibrary.getBuildTarget().getShortName() + ".jar"))
                .toString());
    String expectedClasspath =
        String.join(System.lineSeparator(), expectedPaths) + System.lineSeparator();
    assertEquals(expectedClasspath, console.getTextWrittenToStdOut());
    assertEquals("", console.getTextWrittenToStdErr());
  }

  @Test
  public void testJsonClassPathWithVersions() throws Exception {

    // Build the test target graph.
    TargetNode<?> javaLibrary =
        JavaLibraryBuilder.createBuilder(BuildTargetFactory.newInstance("//:test-java-library"))
            .addSrc(Paths.get("src/com/facebook/TestJavaLibrary.java"))
            .build();
    TargetNode<?> androidLibrary =
        JavaLibraryBuilder.createBuilder(BuildTargetFactory.newInstance("//:test-android-library"))
            .addSrc(Paths.get("src/com/facebook/TestAndroidLibrary.java"))
            .addDep(javaLibrary.getBuildTarget())
            .build();
    TargetNode<?> version =
        new VersionedAliasBuilder(BuildTargetFactory.newInstance("//:version"))
            .setVersions("1.0", "//:test-android-library")
            .build();
    TargetNode<?> binary =
        new JavaBinaryRuleBuilder(BuildTargetFactory.newInstance("//:rule"))
            .setDeps(ImmutableSortedSet.of(version.getBuildTarget()))
            .build();
    TargetGraph targetGraph =
        TargetGraphFactory.newInstance(javaLibrary, androidLibrary, version, binary);

    // Run the command.
    auditClasspathCommand.printJsonClasspath(
        params.withBuckConfig(
            FakeBuckConfig.builder()
                .setSections(ImmutableMap.of("build", ImmutableMap.of("versions", "true")))
                .build()),
        targetGraph,
        ImmutableSet.of(androidLibrary.getBuildTarget(), javaLibrary.getBuildTarget()));

    // Verify output.
    Path root = javaLibrary.getBuildTarget().getCellPath();
    ObjectMapper objectMapper = ObjectMappers.legacyCreate();
    String expected =
        String.format(
            EXPECTED_JSON,
            objectMapper.valueToTree(
                root.resolve(
                    BuildTargetPaths.getGenPath(
                            params.getCell().getFilesystem(),
                            javaLibrary.getBuildTarget(),
                            "lib__%s__output")
                        .resolve(javaLibrary.getBuildTarget().getShortName() + ".jar"))),
            objectMapper.valueToTree(
                root.resolve(
                    BuildTargetPaths.getGenPath(
                            params.getCell().getFilesystem(),
                            androidLibrary.getBuildTarget(),
                            "lib__%s__output")
                        .resolve(androidLibrary.getBuildTarget().getShortName() + ".jar"))),
            objectMapper.valueToTree(
                root.resolve(
                    BuildTargetPaths.getGenPath(
                            params.getCell().getFilesystem(),
                            javaLibrary.getBuildTarget(),
                            "lib__%s__output")
                        .resolve(javaLibrary.getBuildTarget().getShortName() + ".jar"))));
    assertEquals(expected, console.getTextWrittenToStdOut());
    assertEquals("", console.getTextWrittenToStdErr());
  }
}