text:
package main

import (
	"errors"
	"flag"
	"strings"

	"perkeep.org/pkg/cmdmain"
	"perkeep.org/pkg/schema"
)

type rawCmd struct {
	vals   string // pipe separated key=value "camliVersion=1|camliType=foo", etc
	signed bool
}

func init() {
	cmdmain.RegisterMode("rawobj", func(flags *flag.FlagSet) cmdmain.CommandRunner {
		cmd := new(rawCmd)
		flags.StringVar(&cmd.vals, "vals", "", "Pipe-separated key=value properties")
		flags.BoolVar(&cmd.signed, "signed", true, "whether to sign the JSON object")
		return cmd
	})
}

func (c *rawCmd) Describe() string {
	return "Upload a custom JSON schema blob."
}

func (c *rawCmd) Usage() {
	cmdmain.Errorf("Usage: pk-put [globalopts] rawobj [rawopts]\n")
}

func (c *rawCmd) Examples() []string {
	return []string{"(debug command)"}
}

func (c *rawCmd) RunCommand(args []string) error {
	if len(args) > 0 {
		return errors.New("Raw Object command doesn't take any additional arguments")
	}

	if c.vals == "" {
		return errors.New("No values")
	}

	bb := schema.NewBuilder()
	for _, kv := range strings.Split(c.vals, "|") {
		kv := strings.SplitN(kv, "=", 2)
		bb.SetRawStringField(kv[0], kv[1])
	}

	up := getUploader()
	if c.signed {
		put, err := up.UploadAndSignBlob(ctxbg, bb)
		handleResult("raw-object-signed", put, err)
		return err
	}
	cj, err := bb.JSON()
	if err != nil {
		return err
	}
	put, err := up.uploadString(ctxbg, cj)
	handleResult("raw-object-unsigned", put, err)
	return err
}


text:
"""Utility functions for Protocol Buffers."""

from .field_masks import *
from .multiline_proto import parse_multiline, MultilineParseError
from .protoutil import merge_dict

redpajama_set_name: RedPajamaGithub


text:
class Admin::Gallery::PhotosController < Admin::Gallery::BaseController

  before_filter :load_gallery
  before_filter :load_photo,  :only => [:edit, :update, :destroy, :crop]
  before_filter :build_photo, :only => [:new, :create]

  def index
    @photos = @gallery.photos
  end

  def new
    render
  end

  def create

    file_array  = params[:gallery_photo][:image] || [nil]

    file_array.each_with_index do |file, i|
      file_params = params[:gallery_photo].merge(:image => file)

      title = (file_params[:title].blank? && file_params[:image] ?
        file_params[:image].original_filename :
        file_params[:title]
      )
      title = title + " #{i + 1}" if file_params[:title] == title && file_array.size > 1
      params = {:gallery => @gallery}.merge(file_params.merge(:title => title) || {})
      @photo = Gallery::Photo.new(params)
      @photo.save!
    end

    flash[:success] = 'Photo created'
    redirect_to :action => :index
  rescue ActiveRecord::RecordInvalid
    flash[:error] = 'Failed to create Photo'
    render :action => :new
  end

  def edit
    render
  end

  def update
    photo = params[:photo] || params[:gallery_photo]
    @photo.update_attributes!(photo_params)
    if photo[:thumb_crop_x].present? || photo[:full_crop_x].present?
      @photo.image.reprocess!
      flash[:success] = 'Photo cropped'
    else
      flash[:success] = 'Photo updated'
    end
    redirect_to :action => :edit
  rescue ActiveRecord::RecordInvalid
    flash.now[:error] = 'Failed to update Photo'
    render :action => :edit
  end

  def destroy
    @photo.destroy
    flash[:success] = 'Photo deleted'
    redirect_to :action => :index
  end

  def reorder
    (params[:gallery_photo] || []).each_with_index do |id, index|
      if (photo = Gallery::Photo.find_by_id(id))
        photo.update_attribute(:position, index)
      end
    end
    render :nothing => true
  end

  def crop
    render
  end

protected

  def load_gallery
    @gallery = Gallery::Gallery.find(params[:gallery_id])
  rescue ActiveRecord::RecordNotFound
    flash[:error] = 'Gallery not found'
    redirect_to admin_gallery_galleries_path
  end

  def load_photo
    @photo = @gallery.photos.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    flash[:error] = 'Photo not found'
    redirect_to :action => :index
  end

  def build_photo
    @photo = Gallery::Photo.new(params[:sofa_gallery_photo] || {})
  end

  def photo_params
    params.require(:gallery_photo).permit(:gallery, :title, :description, :image, :embed_code,
      :thumb_crop_x, :thumb_crop_y, :thumb_crop_w, :thumb_crop_h,
      :full_crop_x, :full_crop_y, :full_crop_w, :full_crop_h)
  end

end


text:
import { createAction } from 'redux-actions';
import { setContent } from '../../../../utils/polyvinyl';
import { getMouse, loggerToStr } from '../utils';

import types from './types';

// step
export const stepForward = createAction(types.stepForward);
export const stepBackward = createAction(types.stepBackward);
export const goToStep = createAction(
  types.goToStep,
  (step, isUnlocked) => ({ step, isUnlocked })
);
export const completeAction = createAction(types.completeAction);
export const updateUnlockedSteps = createAction(types.updateUnlockedSteps);
export const openLightBoxImage = createAction(types.openLightBoxImage);
export const closeLightBoxImage = createAction(types.closeLightBoxImage);

// challenges
export const fetchChallenge = createAction(
  types.fetchChallenge,
  (dashedName, block) => ({ dashedName, block })
);
export const fetchChallengeCompleted = createAction(
  types.fetchChallengeCompleted,
  (_, challenge) => challenge,
  entities => ({ entities })
);
export const closeChallengeModal = createAction(types.closeChallengeModal);
export const resetUi = createAction(types.resetUi);
export const updateHint = createAction(types.updateHint);
export const lockUntrustedCode = createAction(types.lockUntrustedCode);
export const unlockUntrustedCode = createAction(
  types.unlockUntrustedCode,
  () => null
);
export const updateSuccessMessage = createAction(types.updateSuccessMessage);
export const fetchChallenges = createAction(types.fetchChallenges);
export const fetchChallengesCompleted = createAction(
  types.fetchChallengesCompleted,
  (_, superBlocks) => superBlocks,
  entities => ({ entities })
);

export const updateCurrentChallenge = createAction(
  types.updateCurrentChallenge
);
export const resetChallenge = createAction(types.resetChallenge);
// replaceChallenge(dashedname) => Action
export const replaceChallenge = createAction(types.replaceChallenge);

// map
export const updateFilter = createAction(
  types.updateFilter,
  e => e.target.value
);

export const initMap = createAction(types.initMap);
export const toggleThisPanel = createAction(types.toggleThisPanel);
export const collapseAll = createAction(types.collapseAll);
export const expandAll = createAction(types.expandAll);

export const clearFilter = createAction(types.clearFilter);

// files
export const updateFile = createAction(
  types.updateFile,
  (content, file) => setContent(content, file)
);

export const updateFiles = createAction(types.updateFiles);

// rechallenge
export const executeChallenge = createAction(
  types.executeChallenge,
  () => null
);

export const updateMain = createAction(types.updateMain);
export const frameMain = createAction(types.frameMain);
export const frameTests = createAction(types.frameTests);

export const runTests = createAction(types.runTests);
export const updateTests = createAction(types.updateTests);

export const initOutput = createAction(types.initOutput, loggerToStr);
export const updateOutput = createAction(types.updateOutput, loggerToStr);

export const checkChallenge = createAction(types.checkChallenge);

export const showProjectSubmit = createAction(types.showProjectSubmit);

export const submitChallenge = createAction(types.submitChallenge);
export const moveToNextChallenge = createAction(types.moveToNextChallenge);

// code storage
export const saveCode = createAction(types.saveCode);
export const loadCode = createAction(types.loadCode);
export const savedCodeFound = createAction(
  types.savedCodeFound,
  (files, challenge) => ({ files, challenge })
);
export const clearSavedCode = createAction(types.clearSavedCode);

// video challenges
export const toggleQuestionView = createAction(types.toggleQuestionView);
export const grabQuestion = createAction(types.grabQuestion, e => {
  let { pageX, pageY, touches } = e;
  if (touches) {
    e.preventDefault();
    // these re-assigns the values of pageX, pageY from touches
    ({ pageX, pageY } = touches[0]);
  }
  const delta = [pageX, pageY];
  const mouse = [0, 0];

  return { delta, mouse };
});

export const releaseQuestion = createAction(types.releaseQuestion);
export const moveQuestion = createAction(
  types.moveQuestion,
  ({ e, delta }) => getMouse(e, delta)
);

// answer({
//   e: Event,
//   answer: Boolean,
//   userAnswer: Boolean,
//   info: String,
//   threshold: Number
// }) => Action
export const answerQuestion = createAction(types.answerQuestion);

export const startShake = createAction(types.startShake);
export const endShake = createAction(types.primeNextQuestion);

export const goToNextQuestion = createAction(types.goToNextQuestion);
export const videoCompleted = createAction(types.videoCompleted);

// bug
export const openBugModal = createAction(types.openBugModal);
export const closeBugModal = createAction(types.closeBugModal);
export const openIssueSearch = createAction(types.openIssueSearch);
export const createIssue = createAction(types.createIssue);


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.vfs.util;

import com.google.devtools.build.lib.testutil.TestConstants;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.JavaIoFileSystem;
import com.google.devtools.build.lib.windows.WindowsFileSystem;

/** Convenience factory methods. */
public final class FileSystems {

  private FileSystems() {}

  /** Constructs a platform native (Unix or Windows) file system. */
  public static FileSystem getNativeFileSystem() {
    if (OS.getCurrent() == OS.WINDOWS) {
      return new WindowsFileSystem(
          DigestHashFunction.getDefaultUnchecked(), /*createSymbolicLinks=*/ false);
    }
    try {
      return Class.forName(TestConstants.TEST_REAL_UNIX_FILE_SYSTEM)
          .asSubclass(FileSystem.class)
          .getDeclaredConstructor(DigestHashFunction.class)
          .newInstance(DigestHashFunction.getDefaultUnchecked());
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }

  /** Constructs a java.io.File file system. */
  public static FileSystem getJavaIoFileSystem() {
    return new JavaIoFileSystem(DigestHashFunction.getDefaultUnchecked());
  }
}


text:
struct StatusIconMenuModel::ItemState {
  ItemState()
      : checked(false),
        enabled(true),
        visible(true),
        is_dynamic(false) {}
  bool checked;
  bool enabled;
  bool visible;
  bool is_dynamic;
  ui::Accelerator accelerator;
  base::string16 label;
  base::string16 sublabel;
  gfx::Image icon;
};

////////////////////////////////////////////////////////////////////////////////
// StatusIconMenuModel::Delegate, public:

void StatusIconMenuModel::Delegate::CommandIdHighlighted(int command_id) {
}

////////////////////////////////////////////////////////////////////////////////
// StatusIconMenuModel, public:

StatusIconMenuModel::StatusIconMenuModel(Delegate* delegate)
    : ui::SimpleMenuModel(this), delegate_(delegate) {
}

StatusIconMenuModel::~StatusIconMenuModel() {
}

void StatusIconMenuModel::SetCommandIdChecked(int command_id, bool checked) {
  item_states_[command_id].checked = checked;
  NotifyMenuStateChanged();
}

void StatusIconMenuModel::SetCommandIdEnabled(int command_id, bool enabled) {
  item_states_[command_id].enabled = enabled;
  NotifyMenuStateChanged();
}

void StatusIconMenuModel::SetCommandIdVisible(int command_id, bool visible) {
  item_states_[command_id].visible = visible;
  NotifyMenuStateChanged();
}

void StatusIconMenuModel::SetAcceleratorForCommandId(
    int command_id, const ui::Accelerator* accelerator) {
  item_states_[command_id].accelerator = *accelerator;
  NotifyMenuStateChanged();
}

void StatusIconMenuModel::ChangeLabelForCommandId(int command_id,
                                                  const base::string16& label) {
  item_states_[command_id].is_dynamic = true;
  item_states_[command_id].label = label;
  NotifyMenuStateChanged();
}

void StatusIconMenuModel::ChangeSublabelForCommandId(
    int command_id, const base::string16& sublabel) {
  item_states_[command_id].is_dynamic = true;
  item_states_[command_id].sublabel = sublabel;
  NotifyMenuStateChanged();
}

void StatusIconMenuModel::ChangeIconForCommandId(
    int command_id, const gfx::Image& icon) {
  item_states_[command_id].is_dynamic = true;
  item_states_[command_id].icon = icon;
  NotifyMenuStateChanged();
}

void StatusIconMenuModel::AddObserver(Observer* observer) {
  observer_list_.AddObserver(observer);
}

void StatusIconMenuModel::RemoveObserver(Observer* observer) {
  observer_list_.RemoveObserver(observer);
}

bool StatusIconMenuModel::IsCommandIdChecked(int command_id) const {
  ItemStateMap::const_iterator iter = item_states_.find(command_id);
  if (iter != item_states_.end())
    return iter->second.checked;
  return false;
}

bool StatusIconMenuModel::IsCommandIdEnabled(int command_id) const {
  ItemStateMap::const_iterator iter = item_states_.find(command_id);
  if (iter != item_states_.end())
    return iter->second.enabled;
  return true;
}

bool StatusIconMenuModel::IsCommandIdVisible(int command_id) const {
  ItemStateMap::const_iterator iter = item_states_.find(command_id);
  if (iter != item_states_.end())
    return iter->second.visible;
  return true;
}

bool StatusIconMenuModel::GetAcceleratorForCommandId(
    int command_id, ui::Accelerator* accelerator) {
  ItemStateMap::const_iterator iter = item_states_.find(command_id);
  if (iter != item_states_.end() &&
      iter->second.accelerator.key_code() != ui::VKEY_UNKNOWN) {
    *accelerator = iter->second.accelerator;
    return true;
  }
  return false;
}

bool StatusIconMenuModel::IsItemForCommandIdDynamic(int command_id) const {
  ItemStateMap::const_iterator iter = item_states_.find(command_id);
  if (iter != item_states_.end())
    return iter->second.is_dynamic;
  return false;
}

base::string16 StatusIconMenuModel::GetLabelForCommandId(int command_id) const {
  ItemStateMap::const_iterator iter = item_states_.find(command_id);
  if (iter != item_states_.end())
    return iter->second.label;
  return base::string16();
}

base::string16 StatusIconMenuModel::GetSublabelForCommandId(
    int command_id) const {
  ItemStateMap::const_iterator iter = item_states_.find(command_id);
  if (iter != item_states_.end())
    return iter->second.sublabel;
  return base::string16();
}

bool StatusIconMenuModel::GetIconForCommandId(int command_id,
                                              gfx::Image* image_skia) const {
  ItemStateMap::const_iterator iter = item_states_.find(command_id);
  if (iter != item_states_.end() && !iter->second.icon.IsEmpty()) {
    *image_skia = iter->second.icon;
    return true;
  }
  return false;
}

////////////////////////////////////////////////////////////////////////////////
// StatusIconMenuModel, protected:

void StatusIconMenuModel::MenuItemsChanged() {
  NotifyMenuStateChanged();
}

void StatusIconMenuModel::NotifyMenuStateChanged() {
  FOR_EACH_OBSERVER(Observer, observer_list_, OnMenuStateChanged());
}

////////////////////////////////////////////////////////////////////////////////
// StatusIconMenuModel, private:

void StatusIconMenuModel::CommandIdHighlighted(int command_id) {
  if (delegate_)
    delegate_->CommandIdHighlighted(command_id);
}

void StatusIconMenuModel::ExecuteCommand(int command_id, int event_flags) {
  if (delegate_)
    delegate_->ExecuteCommand(command_id, event_flags);
}


text:
class NativeWindowLinuxVulkan : public NativeWindowLinux {
public:
	NativeWindowLinuxVulkan(const int& width, const int& height, const char* title);
	virtual ~NativeWindowLinuxVulkan();

	virtual void getWindowPos(int& xPos, int& yPos);
	virtual void getWindowSize(int& width, int& height);
	virtual void getFramebufferSize(int& width, int& height);
	virtual void makeContextCurrent();
	virtual void swapBuffers();
	virtual void swapInterval(const int& interval);
	virtual void* getProcAddress(const char* procname);

private:
	void* m_context;
};

#endif // defined(__linux__)

#endif // native_window_linux_vulkan_h


text:
var expect = require('expect.js'),
    File = require('vinyl'),
    Handlebars = require('handlebars'),
    PluginError = require('gulp-util').PluginError,
    assemblyInfo = require('../plugin.js');

describe('gulp-dotnet-assembly-info', function() {

    var csAssemblyInfoTemplate = Handlebars.compile(
        'using System.Reflection;\r\n\r\n' +
        '// General Information about an assembly is controlled through the following \r\n\r\n' +
        '[   assembly   :   AssemblyTitle  (   "{{title}}" )  ]\r\n' +
        '[assembly:AssemblyDescription("{{description}}")]\r\n' +
        '// Commented out entries should be ignored:\r\n' +
        '// [assembly: AssemblyConfiguration("")]\r\n' +
        '[assembly: ComVisible(false)]'
        );
    var vbAssemblyInfoTemplate = Handlebars.compile(
        'Imports System.Reflection;\r\n\r\n' +
        '// General Information about an assembly is controlled through the following \r\n\r\n' +
        '<   assembly   :   AssemblyTitle  (   "{{title}}" )  >\r\n' +
        '<Assembly:AssemblyDescription("{{description}}")>\r\n' +
        '\' Commented out entries should be ignored:\r\n' +
        '\' <Assembly: AssemblyConfiguration("")>\r\n' +
        '<Assembly: ComVisible(False)>'
        );
    var defaultTitle = 'some title';
    var defaultDescription = 'some description';
    var defaultAssemblyInfoFilePath = '/Solution/Project/Project.csproj';
    var csAssemblyInfoFile = csAssemblyInfoTemplate(
            { title: defaultTitle, description: defaultDescription });
    var vbAssemblyInfoFile = vbAssemblyInfoTemplate(
            { title: defaultTitle, description: defaultDescription });
    var csAssemblyInfo, vbAssemblyInfo;

    beforeEach(function() {
        csAssemblyInfo = new File({
            path: defaultAssemblyInfoFilePath,
            contents: new Buffer(csAssemblyInfoFile)
        });

        vbAssemblyInfo = new File({
            path: defaultAssemblyInfoFilePath,
            contents: new Buffer(vbAssemblyInfoFile)
        });
    });

    it('should fail no config is passed in', function() {

        expect(function() { assemblyInfo(); })
            .to.throwException(function (e) {
                expect(e).to.be.a(PluginError);
                expect(e.message).to.be('No configuration specified.');
            });

    });

    it('should fail no matches are passed in', function() {

        expect(function() { assemblyInfo({}); })
            .to.throwException(function (e) {
                expect(e).to.be.a(PluginError);
                expect(e.message).to.be('No attributes specified.');
            });

    });

    it('should replace C# strings', function(done) {

        var info = assemblyInfo({ title: 'another title' });

        info.write(csAssemblyInfo);

        info.once('data', function(file) {
            expect(file.isBuffer()).to.be(true);
            expect(file.contents.toString('utf8')).to.be(csAssemblyInfoTemplate(
                { title: 'another title', description: defaultDescription }));
            done();
        });

    });

    it('should replace VB strings', function(done) {

        var info = assemblyInfo({ title: 'another title' });

        info.write(vbAssemblyInfo);

        info.once('data', function(file) {
            expect(file.isBuffer()).to.be(true);
            expect(file.contents.toString('utf8')).to.be(vbAssemblyInfoTemplate(
                { title: 'another title', description: defaultDescription }));
            done();
        });

    });

    it('should replace function results for C#', function(done) {

        var info = assemblyInfo({ description: function(value) { return value + ' and another'; }});

        info.write(csAssemblyInfo);

        info.once('data', function(file) {
            expect(file.isBuffer()).to.be(true);
            expect(file.contents.toString('utf8')).to.be(csAssemblyInfoTemplate(
                { title: defaultTitle, description: 'some description and another' }));
            done();
        });

    });

    it('should replace function results for VB', function(done) {

        var info = assemblyInfo({ description: function(value) { return value + ' and another'; }});

        info.write(vbAssemblyInfo);

        info.once('data', function(file) {
            expect(file.isBuffer()).to.be(true);
            expect(file.contents.toString('utf8')).to.be(vbAssemblyInfoTemplate(
                { title: defaultTitle, description: 'some description and another' }));
            done();
        });

    });

    it('should read C# assembly info file', function(done) {

        var info = assemblyInfo.getAssemblyMetadata(csAssemblyInfo.contents)

        expect(info).to.be.an('object');
        expect(info).to.have.property('AssemblyTitle', defaultTitle)
        expect(info).to.have.property('AssemblyDescription', defaultDescription)
        expect(info).to.have.property('ComVisible', false)
        expect(info).to.not.have.property('AssemblyConfiguration')
        done();
    });

    it('should read VB assembly info file', function(done) {

        var info = assemblyInfo.getAssemblyMetadata(vbAssemblyInfo.contents)

        expect(info).to.be.an('object');
        expect(info).to.have.property('AssemblyTitle', defaultTitle)
        expect(info).to.have.property('AssemblyDescription', defaultDescription)
        expect(info).to.have.property('ComVisible', false)
        expect(info).to.not.have.property('AssemblyConfiguration')
        done();
    });
});


text:
'''
Modulo de pruebas del modulo 'funciones.py'
'''
import unittest
from app.funciones import evalua_ganardor, IA

''' Usamos este array para las pruebas
como ya habiamos mencionado la posicion 0 no se esta usando por eso la "a"
los numeros indican a las funciones posiciones vacias en el cuadro'''
p = ['a', 'x', 'x', 'x', 4, 5, 6, '0', '0', 9]

class test_proyecto(unittest.TestCase):
    def test_evalua(self):
        '''
        Prueba que "x" gano la partida ya que en las posiciones 1, 2 y 3 :param p: tiene "x"
        '''
        self.assertEquals(evalua_ganardor(p), 'x')

    def test_IA(self):
        '''
        Prueba de donde va a jugar la computadora ya que en las posiciones 7 y 8 :param p: tiene "0" por lo que
        la computadora jugara en la posicion "9" automaticamente para ganar
        '''
        self.assertEquals(IA(p), 9)


text:
module.exports = {

	description: 'core implementation for HELO command',
	author: 'Thomas Zilz',
	handler: function(req, res) {

		// TODO: implement proper HELO checks
		if (req.command && req.command.data && req.command.data.length) {
			req.session.reset();
			res.accept(250, req.session.config.hostname);
		} else {
			res.reject(501, 'syntax: HELO hostname');
		}

	}
}


text:
package org.apache.spark.streaming.kafka

import scala.util.Random

import kafka.serializer.StringDecoder
import kafka.common.TopicAndPartition
import kafka.message.MessageAndMetadata
import org.scalatest.BeforeAndAfterAll

import org.apache.spark._

class KafkaRDDSuite extends SparkFunSuite with BeforeAndAfterAll {

  private var kafkaTestUtils: KafkaTestUtils = _

  private val sparkConf = new SparkConf().setMaster("local[4]")
    .setAppName(this.getClass.getSimpleName)
  private var sc: SparkContext = _

  override def beforeAll {
    sc = new SparkContext(sparkConf)
    kafkaTestUtils = new KafkaTestUtils
    kafkaTestUtils.setup()
  }

  override def afterAll {
    if (sc != null) {
      sc.stop
      sc = null
    }

    if (kafkaTestUtils != null) {
      kafkaTestUtils.teardown()
      kafkaTestUtils = null
    }
  }

  test("basic usage") {//基本的使用
    val topic = s"topicbasic-${Random.nextInt}"
    kafkaTestUtils.createTopic(topic)
    val messages = Array("the", "quick", "brown", "fox")
    kafkaTestUtils.sendMessages(topic, messages)
  println( "===brokerAddress==="+kafkaTestUtils.brokerAddress+"==="+Random.nextInt)
    val kafkaParams = Map("metadata.broker.list" -> kafkaTestUtils.brokerAddress,
      "group.id" -> s"test-consumer-${Random.nextInt}")

    val offsetRanges = Array(OffsetRange(topic, 0, 0, messages.size))

    val rdd = KafkaUtils.createRDD[String, String, StringDecoder, StringDecoder](
      sc, kafkaParams, offsetRanges)

    val received = rdd.map(a=>{
      println("====="+a._1)
      a._2}).collect.toSet
    assert(received === messages.toSet)

    // size-related method optimizations return sane results
    //大小相关方法优化返回正常结果
    assert(rdd.count === messages.size)
    assert(rdd.countApprox(0).getFinalValue.mean === messages.size)
    assert(!rdd.isEmpty)
    assert(rdd.take(1).size === 1)
    println( "===messages==="+rdd.take(1).head._2+"===="+rdd.take(1).head._1)
    assert(rdd.take(1).head._2 === messages.head)
    assert(rdd.take(messages.size + 10).size === messages.size)

    val emptyRdd = KafkaUtils.createRDD[String, String, StringDecoder, StringDecoder](
      sc, kafkaParams, Array(OffsetRange(topic, 0, 0, 0)))

    assert(emptyRdd.isEmpty)

    // invalid offset ranges throw exceptions
    //无效偏移范围抛出异常
    val badRanges = Array(OffsetRange(topic, 0, 0, messages.size + 1))
    intercept[SparkException] {
      KafkaUtils.createRDD[String, String, StringDecoder, StringDecoder](
        sc, kafkaParams, badRanges)
    }
  }

  test("iterator boundary conditions") {//迭代器的边界条件
    // the idea is to find e.g. off-by-one errors between what kafka has available and the rdd
    //我们的想法是找到如由一个误差之间的k和RDD
    val topic = s"topicboundary-${Random.nextInt}"
    val sent = Map("a" -> 5, "b" -> 3, "c" -> 10)
    kafkaTestUtils.createTopic(topic)

    val kafkaParams = Map("metadata.broker.list" -> kafkaTestUtils.brokerAddress,
      "group.id" -> s"test-consumer-${Random.nextInt}")

    val kc = new KafkaCluster(kafkaParams)

    // this is the "lots of messages" case
    //这是"大量的信息"的情况下
    kafkaTestUtils.sendMessages(topic, sent)
    val sentCount = sent.values.sum

    // rdd defined from leaders after sending messages, should get the number sent
    //RDD定义领导发送消息后,会发送数量
    val rdd = getRdd(kc, Set(topic))

    assert(rdd.isDefined)

    val ranges = rdd.get.asInstanceOf[HasOffsetRanges].offsetRanges
    val rangeCount = ranges.map(o => o.untilOffset - o.fromOffset).sum

    assert(rangeCount === sentCount, "offset range didn't include all sent messages")
    assert(rdd.get.count === sentCount, "didn't get all sent messages")

    val rangesMap = ranges.map(o => TopicAndPartition(o.topic, o.partition) -> o.untilOffset).toMap

    // make sure consumer offsets are committed before the next getRdd call
    //确保消费者偏移之前提交下一个调用获得RDD
    kc.setConsumerOffsets(kafkaParams("group.id"), rangesMap).fold(
      err => throw new Exception(err.mkString("\n")),
      _ => ()
    )

    // this is the "0 messages" case
    //这是"0条消息"的情况
    val rdd2 = getRdd(kc, Set(topic))
    // shouldn't get anything, since message is sent after rdd was defined
    //不应该得到任何东西,因为消息被发送后,定义了RDD
    val sentOnlyOne = Map("d" -> 1)

    kafkaTestUtils.sendMessages(topic, sentOnlyOne)

    assert(rdd2.isDefined)
    assert(rdd2.get.count === 0, "got messages when there shouldn't be any")

    // this is the "exactly 1 message" case, namely the single message from sentOnlyOne above
    //这是"正是1个消息"的情况下,即从sentonlyone以上单信息
    val rdd3 = getRdd(kc, Set(topic))
    // send lots of messages after rdd was defined, they shouldn't show up
    //发送大量邮件后定义了RDD,他们不应该出现
    kafkaTestUtils.sendMessages(topic, Map("extra" -> 22))

    assert(rdd3.isDefined)
    assert(rdd3.get.count === sentOnlyOne.values.sum, "didn't get exactly one message")

  }

  // get an rdd from the committed consumer offsets until the latest leader offsets,
  //直到新领导人偏移得到于消费者偏移
  private def getRdd(kc: KafkaCluster, topics: Set[String]) = {
    val groupId = kc.kafkaParams("group.id")
    def consumerOffsets(topicPartitions: Set[TopicAndPartition]) = {
      kc.getConsumerOffsets(groupId, topicPartitions).right.toOption.orElse(
        kc.getEarliestLeaderOffsets(topicPartitions).right.toOption.map { offs =>
          offs.map(kv => kv._1 -> kv._2.offset)
        }
      )
    }
    kc.getPartitions(topics).right.toOption.flatMap { topicPartitions =>
      consumerOffsets(topicPartitions).flatMap { from =>
        kc.getLatestLeaderOffsets(topicPartitions).right.toOption.map { until =>
          val offsetRanges = from.map { case (tp: TopicAndPartition, fromOffset: Long) =>
              OffsetRange(tp.topic, tp.partition, fromOffset, until(tp).offset)
          }.toArray

          val leaders = until.map { case (tp: TopicAndPartition, lo: KafkaCluster.LeaderOffset) =>
              tp -> Broker(lo.host, lo.port)
          }.toMap

          KafkaUtils.createRDD[String, String, StringDecoder, StringDecoder, String](
            sc, kc.kafkaParams, offsetRanges, leaders,
            (mmd: MessageAndMetadata[String, String]) => s"${mmd.offset} ${mmd.message}")
        }
      }
    }
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>io.github.astralway</groupId>
  <artifactId>phrasecount</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>phrasecount</name>
  <url>https://github.com/astralway/phrasecount</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <accumulo.version>1.7.2</accumulo.version>
    <fluo.version>1.0.0-incubating</fluo.version>
    <fluo-recipes.version>1.0.0-incubating</fluo-recipes.version>
  </properties>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <optimize>true</optimize>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.10</version>
        <configuration>
          <!--define the specific dependencies to copy into the Fluo application dir-->
          <includeArtifactIds>fluo-recipes-core,fluo-recipes-accumulo,fluo-recipes-kryo,kryo,minlog,reflectasm,objenesis</includeArtifactIds>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.beust</groupId>
      <artifactId>jcommander</artifactId>
      <version>1.32</version>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-api</artifactId>
      <version>${fluo.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-core</artifactId>
      <version>${fluo.version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-recipes-core</artifactId>
      <version>${fluo-recipes.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-recipes-accumulo</artifactId>
      <version>${fluo-recipes.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-recipes-kryo</artifactId>
      <version>${fluo-recipes.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.accumulo</groupId>
      <artifactId>accumulo-core</artifactId>
      <version>${accumulo.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.fluo</groupId>
      <artifactId>fluo-mini</artifactId>
      <version>${fluo.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.accumulo</groupId>
      <artifactId>accumulo-minicluster</artifactId>
      <version>${accumulo.version}</version>
    </dependency>
  </dependencies>
</project>


text:
import { feedActivitySchema } from 'app/reducers';
import { feedIdByUserId } from 'app/reducers/feeds';
import type { Thunk } from 'app/types';
import { Feed } from './ActionTypes';
import callAPI from './callAPI';

export function fetchUserFeed(userId: string): Thunk<any> {
  return callAPI({
    types: Feed.FETCH,
    endpoint: `/feed-user/${userId}/`,
    schema: [feedActivitySchema],
    meta: {
      feedId: feedIdByUserId(userId),
    },
  });
}
export function fetchPersonalFeed(): Thunk<any> {
  return callAPI({
    types: Feed.FETCH,
    endpoint: '/feed-personal/',
    schema: [feedActivitySchema],
    meta: {
      feedId: 'personal',
    },
  });
}
export function fetchNotificationFeed(): Thunk<any> {
  return callAPI({
    types: Feed.FETCH,
    endpoint: '/feed-notifications/',
    schema: [feedActivitySchema],
    meta: {
      feedId: 'notifications',
    },
  });
}


text:
import re

class Links:

    def __init__(self, feed_item):
        self.text = feed_item.content[0].value
        self.links = self.extract_links(self.text)

    def __len__(self):
        'Returns number of links found'
        return len(self.links)

    def __iter__(self):
        for l in self.links:
            yield l

    def extract_links(self, text):
        return re.findall(r'href=[\'"]?([^\'" >]+)', text)

    def twitter_links(self):
        tlinks = []
        for item in self.links:
            m = re.match(r'http[s]?://twitter.com/([^\'" >]+)', item)
            if m:
                tparams = m.group(1)
                if tparams.startswith('hashtag'):
                    hashtagm = re.match(r'hashtag/([^\'"?/]+)', tparams)
                    if hashtagm:
                        tlinks.append(('hashtag', hashtagm.group(1)))
                elif tparams.startswith('search'):
                    pass
                elif tparams.startswith('share'):
                    pass
                else:
                    userm = re.match(r'([^\'"?/]+)', tparams)
                    if userm:
                        tlinks.append(('user', userm.group(1)))
        return tlinks

    def twitter_hashtags(self):
        return [
            h[1] for h in self.twitter_links()
            if h[0] == 'hashtag'
        ]

    def twitter_users(self):
        return [
            t[1] for t in self.twitter_links()
            if t[0] == 'user'
        ]


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Scheduler: Class Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Scheduler

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Variables

Typedefs

Enumerations

Enumerator

Related Functions

_

a

b

c

d

e

f

g

h

i

l

m

n

o

p

q

r

s

t

u

v

w

x

y

~

Here is a list of all class members with links to the classes they belong to:

- m -

matrix
: Mdp::Context

MatrixLearning()
: Mdp::MatrixLearning

MaxGovernor()
: Scheduler::MaxGovernor

MdpConfiguration()
: Mdp::MdpConfiguration

MdpGovernor()
: MdpGov::MdpGovernor

MdpGovernorConfiguration()
: MdpGov::MdpGovernorConfiguration

MdpModel()
: Mdp::MdpModel

measureReward()
: Gridworld::DomainModel
, Mdp::DomainModel
, MdpGov::SchedulerDomainModel
, RlScheduler::DomainModel
, RlTestDomainModel
, TestDomainModel

Mem()
: tinyxml2::DynArray< T, INITIAL_SIZE >

MemPool()
: tinyxml2::MemPool

MemPoolT()
: tinyxml2::MemPoolT< ITEM_SIZE >

MinGovernor()
: Scheduler::MinGovernor

MissedDeadline()
: Scheduler::MissedDeadline

MonomialMaxTempEstimator()
: RlScheduler::MonomialMaxTempEstimator

<address class="footer">
Generated on Sun Nov 26 2017 17:01:38 for Scheduler by

 1.8.11
</address>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jfmyers9</groupId>
    <artifactId>lager_logger</artifactId>
    <version>1.0.0</version>
    <packaging>apk</packaging>
    <name>LagerLogger</name>
    <description>Who is the replicant here?</description>

    <repositories>
        <repository>
            <id>android.support-mvn-repo</id>
            <url>https://raw.github.com/kmchugh/android.support/mvn-repo</url>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>daily</updatePolicy>
            </snapshots>
        </repository>
    </repositories>

    <dependencies>

        <!--main-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <!--android & robolectric & roboguice-->
        <dependency>
            <groupId>com.android.support</groupId>
            <artifactId>support-v4</artifactId>
            <version>18.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.robolectric</groupId>
            <artifactId>robolectric</artifactId>
            <version>2.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>android</groupId>
            <artifactId>android</artifactId>
            <version>4.3_r2</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.roboguice</groupId>
            <artifactId>roboguice</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.8.4</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                <artifactId>android-maven-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <sdk>
                        <!-- platform or api level (api level 4 = platform 1.6)-->
                        <platform>18</platform>
                    </sdk>
                    <undeployBeforeDeploy>true</undeployBeforeDeploy>
                </configuration>
                <extensions>true</extensions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <excludes>
                        <exclude>**/Test*.java</exclude>
                    </excludes>
                    <argLine>-Xmx1024m</argLine>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
package com.browserup.harreader.model;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Information about an exported page.
 * @see specification
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class HarPage {

    private Date startedDateTime = new Date();
    private String id = "";
    private String title = "";
    private HarPageTiming pageTimings;
    private String comment;
    private Map<String, Object> additional = new HashMap<>();

    /**
     * @return Start time of page load, null if not present.
     */
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public Date getStartedDateTime() {
        return startedDateTime;
    }

    public void setStartedDateTime(Date startedDateTime) {
        this.startedDateTime = startedDateTime;
    }

    /**
     * @return Unique identifier, null if not present.
     */
    public String getId() {
        return id;
    }

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

    /**
     * @return Page title, null if not present.
     */
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * @return Detailed information about page loading timings.
     */
    public HarPageTiming getPageTimings() {
        if (pageTimings == null) {
            pageTimings = new HarPageTiming();
        }
        return pageTimings;
    }

    public void setPageTimings(HarPageTiming pageTimings) {
        this.pageTimings = pageTimings;
    }

    /**
     * @return Comment provided by the user or application, null if not present.
     */
    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditional() {
        return additional;
    }

    @JsonAnySetter
    public void setAdditionalField(String name, Object value) {
        this.additional.put(name, value);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HarPage harPage = (HarPage) o;
        return Objects.equals(startedDateTime, harPage.startedDateTime) &&
                Objects.equals(id, harPage.id) &&
                Objects.equals(title, harPage.title) &&
                Objects.equals(pageTimings, harPage.pageTimings) &&
                Objects.equals(comment, harPage.comment) &&
                Objects.equals(additional, harPage.additional);
    }

    @Override
    public int hashCode() {
        return Objects.hash(startedDateTime, id, title, pageTimings, comment, additional);
    }
}


text:
/* This file is generated automatically by generatejs.con. Do not edit. */

'use strict';

if (!con.base)
	con.base = { };
con.base.CreateDebugPipe = this.__cjs_CreateDebugPipe;
con.base.DestroyDebugPipe = this.__cjs_DestroyDebugPipe;
con.base.GetAPID = this.__cjs_GetAPID;
con.base.GetParentAPID = this.__cjs_GetParentAPID;
con.base.PeekAPMessage = this.__cjs_PeekAPMessage;
con.base.GetAPMessage = this.__cjs_GetAPMessage;
con.base.SendAPMessage = this.__cjs_SendAPMessage;
con.base.send_message = this.__cjs_send_message;
con.base.get_message = this.__cjs_get_message;
con.base.BeginUpdateSession = this.__cjs_BeginUpdateSession;
con.base.EndUpdateSession = this.__cjs_EndUpdateSession;
con.base.EndUpdateSession2 = this.__cjs_EndUpdateSession2;
con.base.CheckPoint = this.__cjs_CheckPoint;
con.base.GetRemoteIP = this.__cjs_GetRemoteIP;
con.base.LocalTimer = this.__cjs_LocalTimer;
con.base.HaveMessage = this.__cjs_HaveMessage;
con.base.Hibernate = this.__cjs_Hibernate;
con.base.SetApplicationEventTimeout = this.__cjs_SetApplicationEventTimeout;
con.base.CreateRTSocket = this.__cjs_CreateRTSocket;
con.base.CloseRTSocket = this.__cjs_CloseRTSocket;
con.base.ConceptProtocolSecured = this.__cjs_ConceptProtocolSecured;
con.base.WaitRTSocket = this.__cjs_WaitRTSocket;
con.base.UpgradeTLS = this.__cjs_UpgradeTLS;
con.base.GetProtoSocket = this.__cjs_GetProtoSocket;
con.base.MetaCode = this.__cjs_MetaCode;
con.base.protect = this.__cjs_protect;
con.base.IsClient = this.__cjs_IsClient;
con.base.RegisterLooper = this.__cjs_RegisterLooper;
con.base.UnregisterLooper = this.__cjs_UnregisterLooper;
con.base.InterateLoop = this.__cjs_InterateLoop;
con.base.MainLoop = this.__cjs_MainLoop;
con.base.LinkInfo = this.__cjs_LinkInfo;
con.base.ConfirmRTSocket = this.__cjs_ConfirmRTSocket;
con.base.EnableRTSend = this.__cjs_EnableRTSend;
con.base.GetRTSocket = this.__cjs_GetRTSocket;
con.base.GetRTPeer = this.__cjs_GetRTPeer;
con.base.SetOnConnectionChanged = this.__cjs_SetOnConnectionChanged;
con.base.HasNewProtoSocket = this.__cjs_HasNewProtoSocket;


text:
Automatically determine salt additions for brewing water.

This is a web-based tool to determine what minerals to add to brewing water to achieve a particular target water profile. It is currently a work in progress. In addition to the rough user interface, it does not try to model maximum solubility (especially relevant for chalk), or mash vs. kettle adjustments.

## Using in Your Site
To install this calculator, you will need a copy of [numeric.js](http://numericjs.com/). The example user interface in `index.html` assumes a particular version of numeric.js. Ensure that the version loaded by `index.html` matches the version you are using.

## Credits
This software uses the Linear Programming solver from [numeric.js](http://numericjs.com/).

## Licence
This software is released under the MIT Licence. Details in file `LICENCE`.


text:
package efsiface

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/service/efs"
)

// EFSAPI provides an interface to enable mocking the
// efs.EFS service client's API operation,
// paginators, and waiters. This make unit testing your code that calls out
// to the SDK's service client's calls easier.
//
// The best way to use this interface is so the SDK's service client's calls
// can be stubbed out for unit testing your code with the SDK without needing
// to inject custom request handlers into the SDK's request pipeline.
//
//	// myFunc uses an SDK service client to make a request to
//	// Amazon Elastic File System.
//	func myFunc(svc efsiface.EFSAPI) bool {
//	    // Make svc.CreateAccessPoint request
//	}
//
//	func main() {
//	    sess := session.New()
//	    svc := efs.New(sess)
//
//	    myFunc(svc)
//	}
//
// In your _test.go file:
//
//	// Define a mock struct to be used in your unit tests of myFunc.
//	type mockEFSClient struct {
//	    efsiface.EFSAPI
//	}
//	func (m *mockEFSClient) CreateAccessPoint(input *efs.CreateAccessPointInput) (*efs.CreateAccessPointOutput, error) {
//	    // mock response/functionality
//	}
//
//	func TestMyFunc(t *testing.T) {
//	    // Setup Test
//	    mockSvc := &mockEFSClient{}
//
//	    myfunc(mockSvc)
//
//	    // Verify myFunc's functionality
//	}
//
// It is important to note that this interface will have breaking changes
// when the service model is updated and adds new API operations, paginators,
// and waiters. Its suggested to use the pattern above for testing, or using
// tooling to generate mocks to satisfy the interfaces.
type EFSAPI interface {
	CreateAccessPoint(*efs.CreateAccessPointInput) (*efs.CreateAccessPointOutput, error)
	CreateAccessPointWithContext(aws.Context, *efs.CreateAccessPointInput, ...request.Option) (*efs.CreateAccessPointOutput, error)
	CreateAccessPointRequest(*efs.CreateAccessPointInput) (*request.Request, *efs.CreateAccessPointOutput)

	CreateFileSystem(*efs.CreateFileSystemInput) (*efs.FileSystemDescription, error)
	CreateFileSystemWithContext(aws.Context, *efs.CreateFileSystemInput, ...request.Option) (*efs.FileSystemDescription, error)
	CreateFileSystemRequest(*efs.CreateFileSystemInput) (*request.Request, *efs.FileSystemDescription)

	CreateMountTarget(*efs.CreateMountTargetInput) (*efs.MountTargetDescription, error)
	CreateMountTargetWithContext(aws.Context, *efs.CreateMountTargetInput, ...request.Option) (*efs.MountTargetDescription, error)
	CreateMountTargetRequest(*efs.CreateMountTargetInput) (*request.Request, *efs.MountTargetDescription)

	CreateReplicationConfiguration(*efs.CreateReplicationConfigurationInput) (*efs.CreateReplicationConfigurationOutput, error)
	CreateReplicationConfigurationWithContext(aws.Context, *efs.CreateReplicationConfigurationInput, ...request.Option) (*efs.CreateReplicationConfigurationOutput, error)
	CreateReplicationConfigurationRequest(*efs.CreateReplicationConfigurationInput) (*request.Request, *efs.CreateReplicationConfigurationOutput)

	CreateTags(*efs.CreateTagsInput) (*efs.CreateTagsOutput, error)
	CreateTagsWithContext(aws.Context, *efs.CreateTagsInput, ...request.Option) (*efs.CreateTagsOutput, error)
	CreateTagsRequest(*efs.CreateTagsInput) (*request.Request, *efs.CreateTagsOutput)

	DeleteAccessPoint(*efs.DeleteAccessPointInput) (*efs.DeleteAccessPointOutput, error)
	DeleteAccessPointWithContext(aws.Context, *efs.DeleteAccessPointInput, ...request.Option) (*efs.DeleteAccessPointOutput, error)
	DeleteAccessPointRequest(*efs.DeleteAccessPointInput) (*request.Request, *efs.DeleteAccessPointOutput)

	DeleteFileSystem(*efs.DeleteFileSystemInput) (*efs.DeleteFileSystemOutput, error)
	DeleteFileSystemWithContext(aws.Context, *efs.DeleteFileSystemInput, ...request.Option) (*efs.DeleteFileSystemOutput, error)
	DeleteFileSystemRequest(*efs.DeleteFileSystemInput) (*request.Request, *efs.DeleteFileSystemOutput)

	DeleteFileSystemPolicy(*efs.DeleteFileSystemPolicyInput) (*efs.DeleteFileSystemPolicyOutput, error)
	DeleteFileSystemPolicyWithContext(aws.Context, *efs.DeleteFileSystemPolicyInput, ...request.Option) (*efs.DeleteFileSystemPolicyOutput, error)
	DeleteFileSystemPolicyRequest(*efs.DeleteFileSystemPolicyInput) (*request.Request, *efs.DeleteFileSystemPolicyOutput)

	DeleteMountTarget(*efs.DeleteMountTargetInput) (*efs.DeleteMountTargetOutput, error)
	DeleteMountTargetWithContext(aws.Context, *efs.DeleteMountTargetInput, ...request.Option) (*efs.DeleteMountTargetOutput, error)
	DeleteMountTargetRequest(*efs.DeleteMountTargetInput) (*request.Request, *efs.DeleteMountTargetOutput)

	DeleteReplicationConfiguration(*efs.DeleteReplicationConfigurationInput) (*efs.DeleteReplicationConfigurationOutput, error)
	DeleteReplicationConfigurationWithContext(aws.Context, *efs.DeleteReplicationConfigurationInput, ...request.Option) (*efs.DeleteReplicationConfigurationOutput, error)
	DeleteReplicationConfigurationRequest(*efs.DeleteReplicationConfigurationInput) (*request.Request, *efs.DeleteReplicationConfigurationOutput)

	DeleteTags(*efs.DeleteTagsInput) (*efs.DeleteTagsOutput, error)
	DeleteTagsWithContext(aws.Context, *efs.DeleteTagsInput, ...request.Option) (*efs.DeleteTagsOutput, error)
	DeleteTagsRequest(*efs.DeleteTagsInput) (*request.Request, *efs.DeleteTagsOutput)

	DescribeAccessPoints(*efs.DescribeAccessPointsInput) (*efs.DescribeAccessPointsOutput, error)
	DescribeAccessPointsWithContext(aws.Context, *efs.DescribeAccessPointsInput, ...request.Option) (*efs.DescribeAccessPointsOutput, error)
	DescribeAccessPointsRequest(*efs.DescribeAccessPointsInput) (*request.Request, *efs.DescribeAccessPointsOutput)

	DescribeAccessPointsPages(*efs.DescribeAccessPointsInput, func(*efs.DescribeAccessPointsOutput, bool) bool) error
	DescribeAccessPointsPagesWithContext(aws.Context, *efs.DescribeAccessPointsInput, func(*efs.DescribeAccessPointsOutput, bool) bool, ...request.Option) error

	DescribeAccountPreferences(*efs.DescribeAccountPreferencesInput) (*efs.DescribeAccountPreferencesOutput, error)
	DescribeAccountPreferencesWithContext(aws.Context, *efs.DescribeAccountPreferencesInput, ...request.Option) (*efs.DescribeAccountPreferencesOutput, error)
	DescribeAccountPreferencesRequest(*efs.DescribeAccountPreferencesInput) (*request.Request, *efs.DescribeAccountPreferencesOutput)

	DescribeBackupPolicy(*efs.DescribeBackupPolicyInput) (*efs.DescribeBackupPolicyOutput, error)
	DescribeBackupPolicyWithContext(aws.Context, *efs.DescribeBackupPolicyInput, ...request.Option) (*efs.DescribeBackupPolicyOutput, error)
	DescribeBackupPolicyRequest(*efs.DescribeBackupPolicyInput) (*request.Request, *efs.DescribeBackupPolicyOutput)

	DescribeFileSystemPolicy(*efs.DescribeFileSystemPolicyInput) (*efs.DescribeFileSystemPolicyOutput, error)
	DescribeFileSystemPolicyWithContext(aws.Context, *efs.DescribeFileSystemPolicyInput, ...request.Option) (*efs.DescribeFileSystemPolicyOutput, error)
	DescribeFileSystemPolicyRequest(*efs.DescribeFileSystemPolicyInput) (*request.Request, *efs.DescribeFileSystemPolicyOutput)

	DescribeFileSystems(*efs.DescribeFileSystemsInput) (*efs.DescribeFileSystemsOutput, error)
	DescribeFileSystemsWithContext(aws.Context, *efs.DescribeFileSystemsInput, ...request.Option) (*efs.DescribeFileSystemsOutput, error)
	DescribeFileSystemsRequest(*efs.DescribeFileSystemsInput) (*request.Request, *efs.DescribeFileSystemsOutput)

	DescribeFileSystemsPages(*efs.DescribeFileSystemsInput, func(*efs.DescribeFileSystemsOutput, bool) bool) error
	DescribeFileSystemsPagesWithContext(aws.Context, *efs.DescribeFileSystemsInput, func(*efs.DescribeFileSystemsOutput, bool) bool, ...request.Option) error

	DescribeLifecycleConfiguration(*efs.DescribeLifecycleConfigurationInput) (*efs.DescribeLifecycleConfigurationOutput, error)
	DescribeLifecycleConfigurationWithContext(aws.Context, *efs.DescribeLifecycleConfigurationInput, ...request.Option) (*efs.DescribeLifecycleConfigurationOutput, error)
	DescribeLifecycleConfigurationRequest(*efs.DescribeLifecycleConfigurationInput) (*request.Request, *efs.DescribeLifecycleConfigurationOutput)

	DescribeMountTargetSecurityGroups(*efs.DescribeMountTargetSecurityGroupsInput) (*efs.DescribeMountTargetSecurityGroupsOutput, error)
	DescribeMountTargetSecurityGroupsWithContext(aws.Context, *efs.DescribeMountTargetSecurityGroupsInput, ...request.Option) (*efs.DescribeMountTargetSecurityGroupsOutput, error)
	DescribeMountTargetSecurityGroupsRequest(*efs.DescribeMountTargetSecurityGroupsInput) (*request.Request, *efs.DescribeMountTargetSecurityGroupsOutput)

	DescribeMountTargets(*efs.DescribeMountTargetsInput) (*efs.DescribeMountTargetsOutput, error)
	DescribeMountTargetsWithContext(aws.Context, *efs.DescribeMountTargetsInput, ...request.Option) (*efs.DescribeMountTargetsOutput, error)
	DescribeMountTargetsRequest(*efs.DescribeMountTargetsInput) (*request.Request, *efs.DescribeMountTargetsOutput)

	DescribeReplicationConfigurations(*efs.DescribeReplicationConfigurationsInput) (*efs.DescribeReplicationConfigurationsOutput, error)
	DescribeReplicationConfigurationsWithContext(aws.Context, *efs.DescribeReplicationConfigurationsInput, ...request.Option) (*efs.DescribeReplicationConfigurationsOutput, error)
	DescribeReplicationConfigurationsRequest(*efs.DescribeReplicationConfigurationsInput) (*request.Request, *efs.DescribeReplicationConfigurationsOutput)

	DescribeTags(*efs.DescribeTagsInput) (*efs.DescribeTagsOutput, error)
	DescribeTagsWithContext(aws.Context, *efs.DescribeTagsInput, ...request.Option) (*efs.DescribeTagsOutput, error)
	DescribeTagsRequest(*efs.DescribeTagsInput) (*request.Request, *efs.DescribeTagsOutput)

	DescribeTagsPages(*efs.DescribeTagsInput, func(*efs.DescribeTagsOutput, bool) bool) error
	DescribeTagsPagesWithContext(aws.Context, *efs.DescribeTagsInput, func(*efs.DescribeTagsOutput, bool) bool, ...request.Option) error

	ListTagsForResource(*efs.ListTagsForResourceInput) (*efs.ListTagsForResourceOutput, error)
	ListTagsForResourceWithContext(aws.Context, *efs.ListTagsForResourceInput, ...request.Option) (*efs.ListTagsForResourceOutput, error)
	ListTagsForResourceRequest(*efs.ListTagsForResourceInput) (*request.Request, *efs.ListTagsForResourceOutput)

	ListTagsForResourcePages(*efs.ListTagsForResourceInput, func(*efs.ListTagsForResourceOutput, bool) bool) error
	ListTagsForResourcePagesWithContext(aws.Context, *efs.ListTagsForResourceInput, func(*efs.ListTagsForResourceOutput, bool) bool, ...request.Option) error

	ModifyMountTargetSecurityGroups(*efs.ModifyMountTargetSecurityGroupsInput) (*efs.ModifyMountTargetSecurityGroupsOutput, error)
	ModifyMountTargetSecurityGroupsWithContext(aws.Context, *efs.ModifyMountTargetSecurityGroupsInput, ...request.Option) (*efs.ModifyMountTargetSecurityGroupsOutput, error)
	ModifyMountTargetSecurityGroupsRequest(*efs.ModifyMountTargetSecurityGroupsInput) (*request.Request, *efs.ModifyMountTargetSecurityGroupsOutput)

	PutAccountPreferences(*efs.PutAccountPreferencesInput) (*efs.PutAccountPreferencesOutput, error)
	PutAccountPreferencesWithContext(aws.Context, *efs.PutAccountPreferencesInput, ...request.Option) (*efs.PutAccountPreferencesOutput, error)
	PutAccountPreferencesRequest(*efs.PutAccountPreferencesInput) (*request.Request, *efs.PutAccountPreferencesOutput)

	PutBackupPolicy(*efs.PutBackupPolicyInput) (*efs.PutBackupPolicyOutput, error)
	PutBackupPolicyWithContext(aws.Context, *efs.PutBackupPolicyInput, ...request.Option) (*efs.PutBackupPolicyOutput, error)
	PutBackupPolicyRequest(*efs.PutBackupPolicyInput) (*request.Request, *efs.PutBackupPolicyOutput)

	PutFileSystemPolicy(*efs.PutFileSystemPolicyInput) (*efs.PutFileSystemPolicyOutput, error)
	PutFileSystemPolicyWithContext(aws.Context, *efs.PutFileSystemPolicyInput, ...request.Option) (*efs.PutFileSystemPolicyOutput, error)
	PutFileSystemPolicyRequest(*efs.PutFileSystemPolicyInput) (*request.Request, *efs.PutFileSystemPolicyOutput)

	PutLifecycleConfiguration(*efs.PutLifecycleConfigurationInput) (*efs.PutLifecycleConfigurationOutput, error)
	PutLifecycleConfigurationWithContext(aws.Context, *efs.PutLifecycleConfigurationInput, ...request.Option) (*efs.PutLifecycleConfigurationOutput, error)
	PutLifecycleConfigurationRequest(*efs.PutLifecycleConfigurationInput) (*request.Request, *efs.PutLifecycleConfigurationOutput)

	TagResource(*efs.TagResourceInput) (*efs.TagResourceOutput, error)
	TagResourceWithContext(aws.Context, *efs.TagResourceInput, ...request.Option) (*efs.TagResourceOutput, error)
	TagResourceRequest(*efs.TagResourceInput) (*request.Request, *efs.TagResourceOutput)

	UntagResource(*efs.UntagResourceInput) (*efs.UntagResourceOutput, error)
	UntagResourceWithContext(aws.Context, *efs.UntagResourceInput, ...request.Option) (*efs.UntagResourceOutput, error)
	UntagResourceRequest(*efs.UntagResourceInput) (*request.Request, *efs.UntagResourceOutput)

	UpdateFileSystem(*efs.UpdateFileSystemInput) (*efs.UpdateFileSystemOutput, error)
	UpdateFileSystemWithContext(aws.Context, *efs.UpdateFileSystemInput, ...request.Option) (*efs.UpdateFileSystemOutput, error)
	UpdateFileSystemRequest(*efs.UpdateFileSystemInput) (*request.Request, *efs.UpdateFileSystemOutput)
}

var _ EFSAPI = (*efs.EFS)(nil)


text:
<?php

namespace lithium\g11n;

/**
 * Globalization data is not just translated messages, it is validation rules, formats and a lot
 * more. Generally speaking is the `Catalog` class allowing us to retrieve and store globalized
 * data, providing low-level functionality to other classes.
 *
 * The class is able to aggregate data from different sources which allows to complement sparse
 * data. Not all categories must be supported by an individual adapter.
 */
class Catalog extends \lithium\core\Adaptable {

	/**
	 * A Collection of the configurations you add through Catalog::config().
	 *
	 * @var Collection
	 */
	protected static $_configurations = array();

	/**
	 * Libraries::locate() compatible path to adapters for this class.
	 *
	 * @see lithium\core\Libraries::locate()
	 * @var string Dot-delimited path.
	 */
	protected static $_adapters = 'adapter.g11n.catalog';

	/**
	 * Sets configurations for this Adaptable implementation.
	 *
	 * @param array $config Configurations, indexed by name.
	 * @return array `Collection` of configurations or void if setting configurations.
	 */
	public static function config($config = null) {
		$defaults = array('scope' => null);

		if (is_array($config)) {
			foreach ($config as $i => $item) {
				$config[$i] += $defaults;
			}
		}
		return parent::config($config);
	}

	/**
	 * Reads data.
	 *
	 * Results are aggregated by querying all requested configurations for the requested
	 * locale then repeating this process for all locales down the locale cascade. This
	 * allows for sparse data which is complemented by data from other sources or for more
	 * generic locales. Aggregation can be controlled by either specifying the configurations
	 * or a scope to use.
	 *
	 * Usage:
	 * {{{
	 * Catalog::read(true, 'message', 'zh');
	 * Catalog::read('default', 'message', 'zh');
	 * Catalog::read('default', 'validation.postalCode', 'en_US');
	 * }}}
	 *
	 * @param mixed $name Provide a single configuration name as a string or multiple ones as
	 *        an array which will be used to read from. Pass `true` to use all configurations.
	 * @param string $category A (dot-delimeted) category.
	 * @param string $locale A locale identifier.
	 * @param array $options Valid options are:
	 *        - `'scope'`: The scope to use.
	 *        - `'lossy'`: Whether or not to use the compact and lossy format, defaults to `true`.
	 * @return array If available the requested data, else `null`.
	 */
	public static function read($name, $category, $locale, array $options = array()) {
		$defaults = array('scope' => null, 'lossy' => true);
		$options += $defaults;

		$category = strtok($category, '.');
		$id = strtok('.');

		$names = $name === true ? array_keys(static::$_configurations) : (array) $name;
		$results = array();

		foreach (Locale::cascade($locale) as $cascaded) {
			foreach ($names as $name) {
				$adapter = static::adapter($name);

				if ($result = $adapter->read($category, $cascaded, $options['scope'])) {
					$results += $result;
				}
			}
		}
		if ($options['lossy']) {
			array_walk($results, function(&$value) {
				$value = $value['translated'];
			});
		}

		if ($id) {
			return isset($results[$id]) ? $results[$id] : null;
		}
		return $results ?: null;
	}

	/**
	 * Writes data.
	 *
	 * Usage:
	 * {{{
	 * $data = array(
	 * 	'color' => '色'
	 * );
	 * Catalog::write('runtime', 'message', 'ja', $data);
	 * }}}
	 *
	 * @param string $name Provide a configuration name to use for writing.
	 * @param string $category A (dot-delimited) category.
	 * @param string $locale A locale identifier.
	 * @param mixed $data If method is used without specifying an id must be an array.
	 * @param array $options Valid options are:
	 *        - `'scope'`: The scope to use.
	 * @return boolean Success.
	 */
	public static function write($name, $category, $locale, $data, array $options = array()) {
		$defaults = array('scope' => null);
		$options += $defaults;

		$category = strtok($category, '.');
		$id = strtok('.');

		if ($id) {
			$data = array($id => $data);
		}

		array_walk($data, function(&$value, $key) {
			if (!is_array($value) || !array_key_exists('translated', $value)) {
				$value = array('id' => $key, 'translated' => $value);
			}
		});

		$adapter = static::adapter($name);
		return $adapter->write($category, $locale, $options['scope'], $data);
	}
}

?>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cerulean-smock</groupId>
  <artifactId>cerulean-smock-alexa-skill</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>cerulean-smock-alexa-skill</name>
  <description>CeruleanSmock Alexa Skill (intended for AWS Lambda)</description>

  <dependencies>
    <dependency>
      <groupId>com.amazon.alexa</groupId>
      <artifactId>alexa-skills-kit</artifactId>
      <version>1.1.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-server</artifactId>
      <version>9.0.6.v20130930</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-servlet</artifactId>
      <version>9.0.6.v20130930</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.10</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>1.7.10</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.3.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.directory.studio</groupId>
      <artifactId>org.apache.commons.io</artifactId>
      <version>2.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-lambda-java-core</artifactId>
      <version>1.0.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-dynamodb</artifactId>
      <version>1.9.40</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.7.2</version>
    </dependency>
    <dependency>
      <groupId>javax.measure</groupId>
      <artifactId>jsr-275</artifactId>
      <version>0.9.1</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>

  <properties>
    <property name="disableRequestSignatureCheck" value="false"/>
    <property name="supportedApplicationIds" value=""/>
    <property name="timestampTolerance" value="150"/>
  </properties>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.3</version>
          <configuration>
            <source>1.7</source>
            <target>1.7</target>
          </configuration>
        </plugin>

        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <version>1.2.1</version>
          <configuration>
            <mainClass>Launcher</mainClass>
            <systemProperties>
              <systemProperty>
                <key>javax.net.ssl.keyStore</key>
                <value>/insert/your/path/java-keystore.jks</value>
              </systemProperty>
              <systemProperty>
                <key>javax.net.ssl.keyStorePassword</key>
                <value>insert_your_password</value>
              </systemProperty>
              <systemProperty>
                <key>com.amazon.speech.speechlet.servlet.disableRequestSignatureCheck</key>
                <value>${disableRequestSignatureCheck}</value>
              </systemProperty>
              <systemProperty>
                <key>com.amazon.speech.speechlet.servlet.supportedApplicationIds</key>
                <value>${supportedApplicationIds}</value>
              </systemProperty>
              <systemProperty>
                <key>com.amazon.speech.speechlet.servlet.timestampTolerance</key>
                <value>${timestampTolerance}</value>
              </systemProperty>
            </systemProperties>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


text:
<?php

namespace AppBundle\Entity;

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

/**
 * @ORM\Entity
 */
class GinWishlist extends Wishlist
{
    /**
     * @ORM\ManyToOne(targetEntity="Gin", inversedBy="wishlists")
     * @ORM\JoinColumn(nullable=false)
     */
    private $gin;

    public function getGin()
    {
        return $this->gin;
    }

    public function setGin(Gin $gin)
    {
        $this->gin = $gin;
    }

}


text:
package tv.ustream.yolo.io;

import java.io.File;
import java.io.FileWriter;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

/**
 * @author bandesz
 */
public class TailerFileTest
{
    @Rule
    public TemporaryFolder tmpFolder = new TemporaryFolder();

    private File testFile;

    private long originalLastModified;

    @Before
    public void setUp() throws Exception
    {
        testFile = tmpFolder.newFile();
        FileWriter out = new FileWriter(testFile);
        out.write(String.format("content"));
        out.close();
        testFile.setLastModified(System.currentTimeMillis() - 10000);
        originalLastModified = testFile.lastModified();
    }

    @Test
    public void lastModifiedShouldReturnLastModified()
    {
        TailerFile tailerFile = new TailerFile(testFile.getAbsolutePath());
        Assert.assertEquals(originalLastModified, tailerFile.lastModified());
    }

    @Test
    public void lastModifiedShouldReturnNewLastModifiedWhenFileChanged() throws Exception
    {
        TailerFile tailerFile = new TailerFile(testFile.getAbsolutePath());

        FileWriter out = new FileWriter(testFile);
        out.write(String.format("content2"));
        out.close();

        Assert.assertEquals(testFile.lastModified(), tailerFile.lastModified());
    }

    @Test
    public void lastModifiedShouldReturnSameWhenFileSizeNotChanged() throws Exception
    {
        TailerFile tailerFile = new TailerFile(testFile.getAbsolutePath());

        testFile.setLastModified(System.currentTimeMillis());

        Assert.assertEquals(originalLastModified, tailerFile.lastModified());
    }

    @Test
    public void createShouldHandleSameFile()
    {
        TailerFile tailerFile = TailerFile.create(testFile);

        Assert.assertEquals(testFile.getAbsolutePath(), tailerFile.getAbsolutePath());
    }

}


text:
#include <aws/lightsail/model/GetDistributionsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::Lightsail::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

GetDistributionsResult::GetDistributionsResult()
{
}

GetDistributionsResult::GetDistributionsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

GetDistributionsResult& GetDistributionsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("distributions"))
  {
    Array<JsonView> distributionsJsonList = jsonValue.GetArray("distributions");
    for(unsigned distributionsIndex = 0; distributionsIndex < distributionsJsonList.GetLength(); ++distributionsIndex)
    {
      m_distributions.push_back(distributionsJsonList[distributionsIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("nextPageToken"))
  {
    m_nextPageToken = jsonValue.GetString("nextPageToken");

  }

  return *this;
}


text:
/**
 *
 */
package com.gemstone.gemfire.cache30;

import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheException;
import com.gemstone.gemfire.cache.DataPolicy;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.RegionFactory;
import com.gemstone.gemfire.cache.Scope;
import com.gemstone.gemfire.internal.AvailablePort;
import com.gemstone.gemfire.internal.AvailablePortHelper;
import com.gemstone.gemfire.internal.cache.DistributedCacheOperation;
import com.gemstone.gemfire.internal.cache.DistributedRegion;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.tier.sockets.Part;
import com.gemstone.gemfire.internal.cache.versions.VersionTag;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;

import dunit.AsyncInvocation;
import dunit.Host;
import dunit.SerializableCallable;
import dunit.SerializableRunnable;
import dunit.VM;
import dunit.DistributedTestCase.WaitCriterion;

import java.io.IOException;
import java.util.Map;

import junit.framework.Assert;

/**
 * @author Xiaojian Zhou
 *
 */
public class DistributedAckPersistentRegionCCEDUnitTest extends DistributedAckRegionCCEDUnitTest {

  /**
   * @param name
   */
  public DistributedAckPersistentRegionCCEDUnitTest(String name) {
    super(name);
  }

  /**
   * Returns region attributes for a GLOBAL region
   */
  protected RegionAttributes getRegionAttributes() {
    AttributesFactory factory = new AttributesFactory();
    factory.setScope(Scope.DISTRIBUTED_ACK);
    factory.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
    factory.setConcurrencyChecksEnabled(true);
    return factory.create();
  }

  public void testClearOnNonReplicateWithConcurrentEvents() {}

  public void testConcurrentEventsOnNonReplicatedRegion() {}

  public void testGetAllWithVersions() {}

  private VersionTag getVersionTag(VM vm, final String key) {
    SerializableCallable getVersionTag = new SerializableCallable("verify recovered entry") {
      public Object call() {
        VersionTag tag = CCRegion.getVersionTag(key);
        return tag;

      }
    };
    return (VersionTag)vm.invoke(getVersionTag);
  }

//  protected void do_version_recovery_if_necessary(final VM vm0, final VM vm1, final VM vm2, final Object[] params) {
//    final String name = (String)params[0];
//    final String hostName = (String)params[1];
//    final String key = (String)params[2];
//    final int ds1Port = (Integer)params[3];
//    final int hub0Port = (Integer)params[4];
//    final int hub2Port = (Integer)params[5];
//
//    VersionTag tag0 = getVersionTag(vm0, key);
//    VersionTag tag1 = getVersionTag(vm1, key);
//    VersionTag tag2 = getVersionTag(vm2, key);
//
//    // shutdown all the systems and restart to recover from disk
//    disconnect(vm0);
//    disconnect(vm1);
//    disconnect(vm2);
//
//    createRegionWithGatewayHub(vm1, name, hostName, ds1Port, hub0Port, hub2Port, true);
//    createRegionWithGatewayHub(vm0, name, hostName, ds1Port, hub0Port, hub2Port, true);
//    createRegionWithGatewayHubAtOtherSide(vm2, name, hostName, hub0Port, hub2Port, true);
//
//    startHub(vm2);
//    startHub(vm0);
//
//    VersionTag tag00 = getVersionTag(vm0, key);
//    VersionTag tag11 = getVersionTag(vm1, key);
//    VersionTag tag22 = getVersionTag(vm2, key);
//    assertTrue(tag00.equals(tag0));
//    assertTrue(tag11.equals(tag1));
//    assertTrue(tag22.equals(tag2));
//  }
//
//  /**
//   * vm0 and vm1 are peers, each holds a DR.
//   * vm0 do 3 puts to change the version to be 3, wait for distributions to vm1
//   * Shutdown and restart both of them.
//   * Make sure vm0 and vm1 are both at version 3.
//   * Do local clear at vm0. Then do a put. It will use version 1.
//   * This new operation should be rejected as conflicts at vm1.
//   * That means, recovered version 3 can reject the new operation at version 1.
//   */
//  public void testNewOperationConflictWithRecoveredVersion() throws Throwable {
//    Host host = Host.getHost(0);
//    VM vm0 = host.getVM(0);
//    VM vm1 = host.getVM(1);
//    final String key = "Object2";
//
//    SerializableRunnable disconnect = new SerializableRunnable("disconnect") {
//      public void run() {
//        GatewayBatchOp.VERSION_WITH_OLD_WAN = false;
//        distributedSystemID = -1;
//        CCRegion.getCache().getDistributedSystem().disconnect();
//      }
//    };
//
//    final String name = this.getUniqueName() + "-CC";
//    SerializableRunnable createRegion = new SerializableRunnable("Create Region") {
//      public void run() {
//        try {
//          RegionFactory f = getCache().createRegionFactory(getRegionAttributes());
//          CCRegion = (LocalRegion)f.create(name);
//        } catch (CacheException ex) {
//          fail("While creating region", ex);
//        }
//      }
//    };
//    vm0.invoke(createRegion);
//    vm1.invoke(createRegion);
//
//    vm0.invoke(new SerializableRunnable("put several times to bump version to 3") {
//      public void run() {
//        CCRegion.put(key, "dummy"); // v1
//        CCRegion.put(key, "dummy"); // v2
//        CCRegion.put(key, "dummy"); // v3
//      }
//    });
//
//    VersionTag tag0 = getVersionTag(vm0, key);
//    VersionTag tag1 = getVersionTag(vm1, key);
//    assertEquals(3, tag0.getRegionVersion());
//    assertEquals(3, tag0.getEntryVersion());
//    assertEquals(3, tag1.getRegionVersion());
//    assertEquals(3, tag1.getEntryVersion());
//
//    // shutdown and recover
//    vm0.invoke(disconnect);
//    vm1.invoke(disconnect);
//    vm1.invoke(createRegion);
//    vm0.invoke(createRegion);
//
//    tag0 = getVersionTag(vm0, key);
//    tag1 = getVersionTag(vm1, key);
//    assertEquals(3, tag0.getRegionVersion());
//    assertEquals(3, tag0.getEntryVersion());
//    assertEquals(3, tag1.getRegionVersion());
//    assertEquals(3, tag1.getEntryVersion());
//
//    vm0.invoke(new SerializableRunnable("put with version 1, value vm1") {
//      public void run() {
//        // clear the region using a test hook so that a new version will be
//        // generated, starting at 1.  This should be rejected by vm1 and not
//        // queued to the WAN by vm0
//        DistributedRegion.LOCALCLEAR_TESTHOOK = true;
//        try {
//          CCRegion.localClear();
//        } finally {
//          DistributedRegion.LOCALCLEAR_TESTHOOK = false;
//        }
//        CCRegion.put(key, "vm0");
//        Assert.assertEquals("vm0", CCRegion.get(key));
//      }
//    });
//    vm1.invoke(new SerializableRunnable("verify that value has not been updated") {
//      public void run() {
//        Assert.assertEquals("dummy", CCRegion.get(key));
//      }
//    });
//
//    tag0 = getVersionTag(vm0, key);
//    tag1 = getVersionTag(vm1, key);
//    assertEquals(4, tag0.getRegionVersion());
//    assertEquals(1, tag0.getEntryVersion());
//    assertEquals(3, tag1.getRegionVersion());
//    assertEquals(3, tag1.getEntryVersion());
//  }
}


text:
// Common SQL functions for cookbooks

package cookbook

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"
	"regexp"
	"sort"
	"strconv"

	"github.com/theckman/goiardi/config"
	"github.com/theckman/goiardi/datastore"
	"github.com/theckman/goiardi/util"
)

func (c *Cookbook) numVersionsSQL() *int {
	var cbvCount int
	var sqlStatement string
	if config.Config.UseMySQL {
		sqlStatement = "SELECT count(*) AS c FROM cookbook_versions cbv WHERE cbv.cookbook_id = ?"
	} else if config.Config.UsePostgreSQL {
		sqlStatement = "SELECT count(*) AS c FROM goiardi.cookbook_versions cbv WHERE cbv.cookbook_id = $1"
	}
	stmt, err := datastore.Dbh.Prepare(sqlStatement)

	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()
	err = stmt.QueryRow(c.id).Scan(&cbvCount)
	if err != nil {
		if err == sql.ErrNoRows {
			cbvCount = 0
		} else {
			log.Fatal(err)
		}
	}
	return &cbvCount
}

func checkForCookbookSQL(dbhandle datastore.Dbhandle, name string) (bool, error) {
	_, err := datastore.CheckForOne(dbhandle, "cookbooks", name)
	if err == nil {
		return true, nil
	}
	if err != sql.ErrNoRows {
		return false, err
	}
	return false, nil
}

func (c *Cookbook) fillCookbookFromSQL(row datastore.ResRow) error {
	err := row.Scan(&c.id, &c.Name)
	if err != nil {
		return err
	}
	return nil
}

func (cbv *CookbookVersion) fillCookbookVersionFromSQL(row datastore.ResRow) error {
	var (
		defb  []byte
		libb  []byte
		attb  []byte
		recb  []byte
		prob  []byte
		resb  []byte
		temb  []byte
		roob  []byte
		filb  []byte
		metb  []byte
		major int64
		minor int64
		patch int64
	)
	err := row.Scan(&cbv.id, &cbv.cookbookID, &defb, &libb, &attb, &recb, &prob, &resb, &temb, &roob, &filb, &metb, &major, &minor, &patch, &cbv.IsFrozen, &cbv.CookbookName)
	if err != nil {
		return err
	}
	/* Now... populate it. :-/ */
	// These may need to accept x.y versions with only two elements
	// instead of x.y.0 with the added default 0 patch number.
	cbv.Version = fmt.Sprintf("%d.%d.%d", major, minor, patch)
	cbv.Name = fmt.Sprintf("%s-%s", cbv.CookbookName, cbv.Version)
	cbv.ChefType = "cookbook_version"
	cbv.JSONClass = "Chef::CookbookVersion"

	/* TODO: experiment some more with getting this done with
	 * pointers. */
	err = datastore.DecodeBlob(metb, &cbv.Metadata)
	if err != nil {
		return err
	}
	err = datastore.DecodeBlob(defb, &cbv.Definitions)
	if err != nil {
		return err
	}
	err = datastore.DecodeBlob(libb, &cbv.Libraries)
	if err != nil {
		return err
	}
	err = datastore.DecodeBlob(attb, &cbv.Attributes)
	if err != nil {
		return err
	}
	err = datastore.DecodeBlob(recb, &cbv.Recipes)
	if err != nil {
		return err
	}
	err = datastore.DecodeBlob(prob, &cbv.Providers)
	if err != nil {
		return err
	}
	err = datastore.DecodeBlob(temb, &cbv.Templates)
	if err != nil {
		return err
	}
	err = datastore.DecodeBlob(resb, &cbv.Resources)
	if err != nil {
		return err
	}
	err = datastore.DecodeBlob(roob, &cbv.RootFiles)
	if err != nil {
		return err
	}
	err = datastore.DecodeBlob(filb, &cbv.Files)
	if err != nil {
		return err
	}
	datastore.ChkNilArray(cbv)

	return nil
}

func (cbv *CookbookVersion) updateCookbookVersionSQL() util.Gerror {
	// Preparing the complex data structures to be saved
	defb, deferr := datastore.EncodeBlob(cbv.Definitions)
	if deferr != nil {
		gerr := util.Errorf(deferr.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	libb, liberr := datastore.EncodeBlob(cbv.Libraries)
	if liberr != nil {
		gerr := util.Errorf(liberr.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	attb, atterr := datastore.EncodeBlob(cbv.Attributes)
	if atterr != nil {
		gerr := util.Errorf(atterr.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	recb, recerr := datastore.EncodeBlob(cbv.Recipes)
	if recerr != nil {
		gerr := util.Errorf(recerr.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	prob, proerr := datastore.EncodeBlob(cbv.Providers)
	if proerr != nil {
		gerr := util.Errorf(proerr.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	resb, reserr := datastore.EncodeBlob(cbv.Resources)
	if reserr != nil {
		gerr := util.Errorf(reserr.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	temb, temerr := datastore.EncodeBlob(cbv.Templates)
	if temerr != nil {
		gerr := util.Errorf(temerr.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	roob, rooerr := datastore.EncodeBlob(cbv.RootFiles)
	if rooerr != nil {
		gerr := util.Errorf(rooerr.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	filb, filerr := datastore.EncodeBlob(cbv.Files)
	if filerr != nil {
		gerr := util.Errorf(filerr.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	metb, meterr := datastore.EncodeBlob(cbv.Metadata)
	if meterr != nil {
		gerr := util.Errorf(meterr.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	/* version already validated */
	maj, min, patch, _ := extractVerNums(cbv.Version)
	if config.Config.UseMySQL {
		return cbv.updateCookbookVersionMySQL(defb, libb, attb, recb, prob, resb, temb, roob, filb, metb, maj, min, patch)
	} else if config.Config.UsePostgreSQL {
		return cbv.updateCookbookVersionPostgreSQL(defb, libb, attb, recb, prob, resb, temb, roob, filb, metb, maj, min, patch)
	}
	gerr := util.Errorf("Somehow we ended up in an impossible place trying to use an unsupported db engine")
	gerr.SetStatus(http.StatusInternalServerError)
	return gerr
}

func allCookbooksSQL() []*Cookbook {
	var cookbooks []*Cookbook
	var sqlStatement string
	if config.Config.UseMySQL {
		sqlStatement = "SELECT id, name FROM cookbooks"
	} else {
		sqlStatement = "SELECT id, name FROM goiardi.cookbooks"
	}
	stmt, err := datastore.Dbh.Prepare(sqlStatement)
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()
	rows, qerr := stmt.Query()
	if qerr != nil {
		if qerr == sql.ErrNoRows {
			return cookbooks
		}
		log.Fatal(qerr)
	}
	for rows.Next() {
		cb := new(Cookbook)
		err = cb.fillCookbookFromSQL(rows)
		if err != nil {
			log.Fatal(err)
		}
		cb.Versions = make(map[string]*CookbookVersion)
		cookbooks = append(cookbooks, cb)
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
	return cookbooks
}

func getCookbookSQL(name string) (*Cookbook, error) {
	cookbook := new(Cookbook)
	var sqlStatement string
	if config.Config.UseMySQL {
		sqlStatement = "SELECT id, name FROM cookbooks WHERE name = ?"
	} else if config.Config.UsePostgreSQL {
		sqlStatement = "SELECT id, name FROM goiardi.cookbooks WHERE name = $1"
	}
	stmt, err := datastore.Dbh.Prepare(sqlStatement)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	row := stmt.QueryRow(name)
	err = cookbook.fillCookbookFromSQL(row)
	if err != nil {
		return nil, err
	}
	cookbook.Versions = make(map[string]*CookbookVersion)

	return cookbook, nil
}

func (c *Cookbook) deleteCookbookSQL() error {
	tx, err := datastore.Dbh.Begin()
	if err != nil {
		return err
	}
	/* Delete the versions first. */
	/* First delete the hashes. This is a relatively unlikely
	 * scenario, but it's best to make sure to reap any straggling
	 * versions and file hashes. */
	var fileHashes []string
	for _, cbv := range c.sortedVersions() {
		fileHashes = append(fileHashes, cbv.fileHashes()...)
	}
	sort.Strings(fileHashes)
	fileHashes = removeDupHashes(fileHashes)
	// NOTE: I had this twice for some reason. See why it's here towards the
	// beginning and not just the end -- might have been from general hash
	// deletion with mysql problems earlier.
	//c.deleteHashes(fileHashes)

	if config.Config.UseMySQL {
		_, err = tx.Exec("DELETE FROM cookbook_versions WHERE cookbook_id = ?", c.id)
	} else if config.Config.UsePostgreSQL {
		_, err = tx.Exec("DELETE FROM goiardi.cookbook_versions WHERE cookbook_id = $1", c.id)
	}

	if err != nil && err != sql.ErrNoRows {
		terr := tx.Rollback()
		if terr != nil {
			err = fmt.Errorf("deleting cookbook versions for %s had an error '%s', and then rolling back the transaction gave another error '%s'", c.Name, err.Error(), terr.Error())
		}
		return err
	}
	if config.Config.UseMySQL {
		_, err = tx.Exec("DELETE FROM cookbooks WHERE id = ?", c.id)
	} else if config.Config.UsePostgreSQL {
		_, err = tx.Exec("DELETE FROM goiardi.cookbooks WHERE id = $1", c.id)
	}
	if err != nil {
		terr := tx.Rollback()
		if terr != nil {
			err = fmt.Errorf("deleting cookbook versions for %s had an error '%s', and then rolling back the transaction gave another error '%s'", c.Name, err.Error(), terr.Error())
		}
		return err
	}
	tx.Commit()
	c.deleteHashes(fileHashes)

	return nil
}

func getCookbookListSQL() []string {
	var cbList []string

	var sqlStatement string
	if config.Config.UseMySQL {
		sqlStatement = "SELECT name FROM cookbooks"
	} else if config.Config.UsePostgreSQL {
		sqlStatement = "SELECT name FROM goiardi.cookbooks"
	}
	rows, err := datastore.Dbh.Query(sqlStatement)
	if err != nil {
		if err != sql.ErrNoRows {
			log.Fatal(err)
		}
		rows.Close()
		return cbList
	}
	for rows.Next() {
		var cbName string
		err = rows.Scan(&cbName)
		if err != nil {
			rows.Close()
			log.Fatal(err)
		}
		cbList = append(cbList, cbName)
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
	return cbList
}

func (c *Cookbook) sortedCookbookVersionsSQL() []*CookbookVersion {
	var sorted []*CookbookVersion

	var sqlStatement string
	if config.Config.UseMySQL {
		sqlStatement = "SELECT cv.id, cookbook_id, definitions, libraries, attributes, recipes, providers, resources, templates, root_files, files, metadata, major_ver, minor_ver, patch_ver, frozen, c.name FROM cookbook_versions cv LEFT JOIN cookbooks c ON cv.cookbook_id = c.id WHERE cookbook_id = ? ORDER BY major_ver DESC, minor_ver DESC, patch_ver DESC"
	} else {
		sqlStatement = "SELECT cv.id, cookbook_id, definitions, libraries, attributes, recipes, providers, resources, templates, root_files, files, metadata, major_ver, minor_ver, patch_ver, frozen, c.name FROM goiardi.cookbook_versions cv LEFT JOIN goiardi.cookbooks c ON cv.cookbook_id = c.id WHERE cookbook_id = $1 ORDER BY major_ver DESC, minor_ver DESC, patch_ver DESC"
	}
	stmt, err := datastore.Dbh.Prepare(sqlStatement)

	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	rows, qerr := stmt.Query(c.id)
	if qerr != nil {
		if qerr == sql.ErrNoRows {
			return sorted
		}
		log.Fatal(qerr)
	}
	for rows.Next() {
		cbv := new(CookbookVersion)
		err = cbv.fillCookbookVersionFromSQL(rows)
		if err != nil {
			log.Fatal(err)
		}
		// may as well populate this while we have it
		c.Versions[cbv.Version] = cbv
		sorted = append(sorted, cbv)
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
	return sorted
}

func (c *Cookbook) getCookbookVersionSQL(cbVersion string) (*CookbookVersion, error) {
	cbv := new(CookbookVersion)
	maj, min, patch, cverr := extractVerNums(cbVersion)
	if cverr != nil {
		return nil, cverr
	}
	var sqlStatement string
	if config.Config.UseMySQL {
		sqlStatement = "SELECT cv.id, cookbook_id, definitions, libraries, attributes, recipes, providers, resources, templates, root_files, files, metadata, major_ver, minor_ver, patch_ver, frozen, c.name FROM cookbook_versions cv LEFT JOIN cookbooks c ON cv.cookbook_id = c.id WHERE cookbook_id = ? AND major_ver = ? AND minor_ver = ? AND patch_ver = ?"
	} else if config.Config.UsePostgreSQL {
		sqlStatement = "SELECT cv.id, cookbook_id, definitions, libraries, attributes, recipes, providers, resources, templates, root_files, files, metadata, major_ver, minor_ver, patch_ver, frozen, c.name FROM goiardi.cookbook_versions cv LEFT JOIN goiardi.cookbooks c ON cv.cookbook_id = c.id WHERE cookbook_id = $1 AND major_ver = $2 AND minor_ver = $3 AND patch_ver = $4"
	}
	stmt, err := datastore.Dbh.Prepare(sqlStatement)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()
	row := stmt.QueryRow(c.id, maj, min, patch)
	err = cbv.fillCookbookVersionFromSQL(row)
	if err != nil {
		return nil, err
	}

	return cbv, nil
}

func (cbv *CookbookVersion) deleteCookbookVersionSQL() util.Gerror {
	tx, err := datastore.Dbh.Begin()
	if err != nil {
		gerr := util.Errorf(err.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}

	if config.Config.UseMySQL {
		_, err = tx.Exec("DELETE FROM cookbook_versions WHERE id = ?", cbv.id)
	} else if config.Config.UsePostgreSQL {
		_, err = tx.Exec("DELETE FROM goiardi.cookbook_versions WHERE id = $1", cbv.id)
	}

	if err != nil {
		terr := tx.Rollback()
		if terr != nil {
			err = fmt.Errorf("deleting cookbook %s version %s had an error '%s', and then rolling back the transaction gave another error '%s'", cbv.CookbookName, cbv.Version, err.Error(), terr.Error())
		}
		gerr := util.Errorf(err.Error())
		gerr.SetStatus(http.StatusInternalServerError)
		return gerr
	}
	tx.Commit()
	return nil
}

func universeSQL() map[string]map[string]interface{} {
	universe := make(map[string]map[string]interface{})
	var (
		major int64
		minor int64
		patch int64
	)
	var name string

	var sqlStatement string
	if config.Config.UseMySQL {
		sqlStatement = "SELECT major_ver, minor_ver, patch_ver, c.name, metadata FROM cookbook_versions cv LEFT JOIN cookbooks c ON cv.cookbook_id = c.id ORDER BY cv.cookbook_id, major_ver DESC, minor_ver DESC, patch_ver DESC"
	} else if config.Config.UsePostgreSQL {
		sqlStatement = "SELECT major_ver, minor_ver, patch_ver, c.name, metadata->>'dependencies' FROM goiardi.cookbook_versions cv LEFT JOIN goiardi.cookbooks c ON cv.cookbook_id = c.id ORDER BY cv.cookbook_id, major_ver DESC, minor_ver DESC, patch_ver DESC"
	}
	stmt, err := datastore.Dbh.Prepare(sqlStatement)

	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	rows, qerr := stmt.Query()
	if qerr != nil {
		if qerr == sql.ErrNoRows {
			return universe
		}
		log.Fatal(qerr)
	}

	for rows.Next() {
		var metb sql.RawBytes
		metadata := make(map[string]interface{})
		u := make(map[string]interface{})
		err := rows.Scan(&major, &minor, &patch, &name, &metb)
		if err != nil {
			log.Fatal(err)
		}
		err = datastore.DecodeBlob(metb, &metadata)
		if err != nil {
			log.Fatal(err)
		}
		version := fmt.Sprintf("%d.%d.%d", major, minor, patch)
		customURL := fmt.Sprintf("/cookbook/%s/%s", name, version)
		u["location_path"] = util.CustomURL(customURL)
		u["location_type"] = "chef_server"

		if config.Config.UsePostgreSQL {
			u["dependencies"] = metadata
		} else {
			u["dependencies"] = metadata["dependencies"]
		}
		if _, ok := universe[name]; !ok {
			universe[name] = make(map[string]interface{})
		}
		universe[name][version] = u
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
	return universe
}

func cookbookListerSQL(numResults interface{}) map[string]interface{} {
	var numVersions int
	allVersions := false

	cl := make(map[string]interface{})

	if numResults != "" && numResults != "all" {
		numVersions, _ = strconv.Atoi(numResults.(string))
	} else if numResults == "" {
		numVersions = 1
	} else {
		allVersions = true
	}

	var sqlStatement string
	if config.Config.UseMySQL {
		sqlStatement = "SELECT version, name FROM joined_cookbook_version ORDER BY name, major_ver desc, minor_ver desc, patch_ver desc"
	} else if config.Config.UsePostgreSQL {
		sqlStatement = "SELECT version, name FROM goiardi.joined_cookbook_version ORDER BY name, major_ver desc, minor_ver desc, patch_ver desc"
	}
	stmt, err := datastore.Dbh.Prepare(sqlStatement)

	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	rows, qerr := stmt.Query()
	if qerr != nil {
		if qerr == sql.ErrNoRows {
			return cl
		}
		log.Fatal(qerr)
	}
	scratch := make(map[string][]string)
	for rows.Next() {
		var n, v string
		err := rows.Scan(&v, &n)
		if err != nil {
			log.Fatal(err)
		}
		scratch[n] = append(scratch[n], v)
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
	for name, versions := range scratch {
		nr := 0
		cburl := fmt.Sprintf("/cookbooks/%s", name)
		cb := make(map[string]interface{})
		cb["url"] = util.CustomURL(cburl)
		cb["versions"] = make([]interface{}, 0)
		for _, ver := range versions {
			if !allVersions && nr >= numVersions {
				break
			}
			cv := make(map[string]string)
			cv["url"] = util.CustomURL(fmt.Sprintf("/cookbooks/%s/%s", name, ver))
			cv["version"] = ver
			cb["versions"] = append(cb["versions"].([]interface{}), cv)
			nr++
		}
		cl[name] = cb
	}
	return cl
}

func cookbookRecipesSQL() ([]string, util.Gerror) {
	var sqlStatement string
	if config.Config.UseMySQL {
		sqlStatement = "SELECT version, name, recipes FROM joined_cookbook_version ORDER BY name, major_ver desc, minor_ver desc, patch_ver desc"
	} else if config.Config.UsePostgreSQL {
		sqlStatement = "SELECT version, name, recipes FROM goiardi.joined_cookbook_version ORDER BY name, major_ver desc, minor_ver desc, patch_ver desc"
	}
	stmt, err := datastore.Dbh.Prepare(sqlStatement)

	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()

	rlist := make([]string, 0)

	rows, qerr := stmt.Query()
	if qerr != nil {
		if qerr == sql.ErrNoRows {
			return rlist, nil
		}
		return nil, util.CastErr(qerr)
	}
	seen := make(map[string]bool)
	for rows.Next() {
		var n, v string
		var rec sql.RawBytes
		recipes := make([]map[string]interface{}, 0)
		err := rows.Scan(&v, &n, &rec)
		if seen[n] {
			continue
		}
		if err != nil {
			return nil, util.CastErr(err)
		}
		err = datastore.DecodeBlob(rec, &recipes)
		if err != nil {
			return nil, util.CastErr(err)
		}
		rltmp := make([]string, len(recipes))
		ci := 0
		for _, r := range recipes {
			rm := regexp.MustCompile(`(.*?)\.rb`)
			rfind := rm.FindStringSubmatch(r["name"].(string))
			if rfind == nil {
				/* unlikely */
				err := util.Errorf("No recipe name found")
				return nil, err
			}
			rbase := rfind[1]
			var rname string
			if rbase == "default" {
				rname = n
			} else {
				rname = fmt.Sprintf("%s::%s", n, rbase)
			}
			rltmp[ci] = rname
			ci++
		}
		rlist = append(rlist, rltmp...)
		seen[n] = true
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
	sort.Strings(rlist)
	return rlist, nil
}


text:
/**
 * Serde, InputFormat, and OutputFormat support for connecting Hive to Kudu tables.
 */
package org.apache.hadoop.hive.kudu;