text:
package libgogo

//
// Stack data structure
//
type Stack struct {
    baseAddress uint64; //Where the stack starts
    itemCount uint64; //How many items there currently are on the stack
    capacity uint64; //How many items there can be max. (not to be changed from outside the library)
};

//
// Initializes the given stack
//
func InitializeStack(uninitializedStack *Stack) {
    uninitializedStack.baseAddress = Alloc(16 * 8); //Allocate 16 items by default
    uninitializedStack.capacity = 16;
    uninitializedStack.itemCount = 0; //Reset item count (to zero)
}

//
// Pushes an item onto the given stack, increasing its capacity if required
//
func Push(stack *Stack, value uint64) {
    var newAddress uint64;
    if (stack.capacity == stack.itemCount) { //Grow stack if its capacity doesn't suffice to push another item
        newAddress = Alloc(stack.capacity * 2 * 8); //Double the capacity
        CopyMem(stack.baseAddress, newAddress, stack.capacity * 8); //Copy old stack items
        stack.baseAddress = newAddress; //Set new address as base address
        stack.capacity = stack.capacity * 2; //Update (increase) capacity
    }
    newAddress = ToUint64FromUint64Ptr(&value);
    CopyMem(newAddress, stack.baseAddress + 8 * stack.itemCount, 8); //Push the new value by copying its value into the memory of the corresponding stack item
    stack.itemCount = stack.itemCount + 1; //Update item count
}

//
// Takes and returns an item from the given stack
// Note that this function call fails if there are no items on the stack, e.g. the stack is empty
//
func Pop(stack *Stack) uint64 {
    var returnValue uint64;
    returnValue = Peek(stack); //Peek in order to get the last value from the stack
    stack.itemCount = stack.itemCount - 1; //Update (decrease) item count
    return returnValue; //Return value taken from stack
}

//
// Returns the topmost item of a given stack without removing/taking it
// Note that this function call fails if there are no items on the stack, e.g. the stack is empty
//
func Peek(stack *Stack) uint64 {
    var returnValue uint64;
    var temp uint64;
    if (stack.itemCount == 0) { //Check if there is an item on the stack
        ExitError("Tried to Peek() from an empty stack", 126);
    }
    temp = ToUint64FromUint64Ptr(&returnValue);
    CopyMem(stack.baseAddress + (stack.itemCount - 1) * 8, temp, 8); //Copy the last value from the stack (e.g. its corresponding memory) into the return variable
    return returnValue; //Return peeked value
}

//
// Returns the number of items on the given stack
//
func GetStackItemCount(stack *Stack) uint64 {
    return stack.itemCount;
}

//
// Returns the current capacity of the given stack
//
func GetStackCapacity(stack *Stack) uint64 {
    return stack.capacity;
}


text:
<?php
class Events extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->helper('date');
		$this->load->helper('loadview');
		$this->load->library('email');
		$this->load->model('events_model');
	}

	public function showList()
	{
		$data['title'] = 'Events';
		$data['actlnk_events'] = ' class="gcf-active"';
		$data['pagemsg'] = $this->session->flashdata('pagemsg');

		$data['allevents'] = $this->events_model->getAllevents();

		load_view_admin('events/listevents', $data, 'pages_nav');
	}

	public function viewEvent($id)
	{
		$data['title'] = 'Events';
		$data['actlnk_events'] = ' class="gcf-active"';
		$data['id'] = $id;

		$data['event'] = $this->events_model->getEvent($id);

		load_view_admin('events/viewevent', $data, 'pages_nav');
	}

	public function addEvent()
	{
		$this->load->helper('form');

		if ($this->input->post()) {
			$this->load->library('form_validation');
			$this->load->library('upload');

			$this->form_validation->set_rules('eventcontent', 'Content', 'trim|required|max_length[500]');

			if ($this->form_validation->run() === true) {
				$upload_error = array();
				$video_filename = '';
				$photo_filename = '';

				$config['file_ext_tolower'] = true;
				$config['encrypt_name'] = true;

				if ($_FILES['eventvideo']['name'] != '' && $_FILES['eventvideo']['size'] > 0) {
					$config['upload_path'] = './'.EVENTFILES_PATH.'v/';
					$config['allowed_types'] = 'mp4|ogg';

					$this->upload->initialize($config);

					if (!$this->upload->do_upload('eventvideo')) {
						$data['upload_error']['eventvideo'] = $this->upload->display_errors('- ', '');
					} else {
						$video_filename = $this->upload->data('file_name');
					}
				}

				if ($_FILES['eventphoto']['name'] != '' && $_FILES['eventphoto']['size'] > 0) {
					$config['upload_path'] = './'.EVENTFILES_PATH.'p/';
					$config['allowed_types'] = 'jpg|png|gif';

					$this->upload->initialize($config);

					if (!$this->upload->do_upload('eventphoto')) {
						$data['upload_error']['eventphoto'] = $this->upload->display_errors('- ', '');
					} else {
						$photo_filename = $this->upload->data('file_name');
					}
				}

				if (empty($data['upload_error'])) {
					$event_data = array(
						'event_date' => $this->input->post('eventdate'),
						'event_content' => $this->input->post('eventcontent'),
						'event_video' => $video_filename,
						'event_photo' => $photo_filename,
						'date_added' => date('Y-m-d H:i:s'),
						'added_by' => $this->session->userdata('adminuser')
					);

					$this->events_model->saveEvent($event_data);

					$this->session->set_flashdata('pagemsg', '
An event has been successfully added.
');

					redirect('admin/pages/events');
				} else {
					$data['pagemsg'] = '
'.implode($upload_error).'
';
				}
			} else {
				$data['pagemsg'] = '
'.validation_errors().'
';
			}
		}

		$data['title'] = 'Add Event';
		$data['actlnk_events'] = ' class="gcf-active"';

		load_view_admin('events/addevent', $data, 'pages_nav');
	}

	public function editEvent($id)
	{
		$this->load->helper('form');

		$data['event'] = $this->events_model->getEvent($id);

		if ($this->input->post()) {
			$this->load->library('form_validation');
			$this->load->library('upload');

			$this->form_validation->set_rules('eventcontent', 'Content', 'trim|required|max_length[500]');

			if ($this->form_validation->run() === true) {
				$upload_error = array();
				$photo_filename = $data['event']['event_photo'];
				$video_filename = $data['event']['event_video'];

				$config['file_ext_tolower'] = true;
				$config['encrypt_name'] = true;

				if (isset($_FILES['eventphoto'])) {
					if ($_FILES['eventphoto']['name'] != '' && $_FILES['eventphoto']['size'] > 0) {
						$config['upload_path'] = './'.EVENTFILES_PATH.'p/';
						$config['allowed_types'] = 'jpg|png|gif';

						$this->upload->initialize($config);

						if (!$this->upload->do_upload('eventphoto')) {
							$data['upload_error']['eventphoto'] = $this->upload->display_errors('- ', '');
						} else {
							unlink(EVENTFILES_PATH.'p/'.$photo_filename);
							$photo_filename = $this->upload->data('file_name');
						}
					}
				}

				if (isset($_FILES['eventvideo'])) {
					if ($_FILES['eventvideo']['name'] != '' && $_FILES['eventvideo']['size'] > 0) {
						$config['upload_path'] = './'.EVENTFILES_PATH.'v/';
						$config['allowed_types'] = 'mp4|ogg';

						$this->upload->initialize($config);

						if (!$this->upload->do_upload('eventvideo')) {
							$data['upload_error']['eventvideo'] = $this->upload->display_errors('- ', '');
						} else {
							unlink(EVENTFILES_PATH.'v/'.$video_filename);
							$video_filename = $this->upload->data('file_name');
						}
					}
				}

				if (empty($data['upload_error'])) {
					$event_data = array(
						'event_date' => $this->input->post('eventdate'),
						'event_content' => $this->input->post('eventcontent'),
						'event_video' => $video_filename,
						'event_photo' => $photo_filename,
						'date_updated' => date('Y-m-d H:i:s'),
						'updated_by' => $this->session->userdata('adminuser')
					);

					$this->events_model->updateEvent($id, $event_data);

					$this->session->set_flashdata('pagemsg', '
An event has been successfully updated.
');

					redirect('admin/pages/events');
				}
			} else {
				$data['pagemsg'] = '
'.validation_errors().'
';
			}
		}

		$data['title'] = 'Edit Event';
		$data['actlnk_events'] = ' class="gcf-active"';
		$data['id'] = $id;

		load_view_admin('events/editevent', $data, 'pages_nav');
	}

	public function removeEvent($id)
	{
		$event_data = $this->events_model->getEvent($id);

		$this->events_model->deleteEvent($id);

		if (!empty($event_data['event_photo'])) {
			unlink(EVENTFILES_PATH.'p/'.$event_data['event_photo']);
		}

		if (!empty($event_data['event_video'])) {
			unlink(EVENTFILES_PATH.'v/'.$event_data['event_video']);
		}

		$this->session->set_flashdata('pagemsg', '
An event has been successfully deleted.
');

		redirect('admin/pages/events');
	}

	public function removeFile()
	{
		$return['success'] = 'false';

		if ($id = $this->input->post('eid')) {
			$event_data = $this->events_model->getEvent($id);
			$eventfile = './'.EVENTFILES_PATH;

			if ($this->input->post('ephoto') == '1') {
				$data = array('event_photo' => '');
				$eventfile .= 'p/'.$event_data['event_photo'];
			}

			if ($this->input->post('evideo') == '1') {
				$data = array('event_video' => '');
				$eventfile .= 'v/'.$event_data['event_video'];
			}

			$this->events_model->updateEvent($id, $data);
			unlink($eventfile);
			$return['success'] = 'true';
		}

		echo json_encode($return);
	}
}

redpajama_set_name: RedPajamaGithub


text:
class AddDescriptionLanguageToAttachments < ActiveRecord::Migration[5.0]
  def change
    add_column :attachments, :language, :string
    add_column :attachments, :description, :text
  end
end


text:
package com.ontology2.telepath.sumUsage;

import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.theories.suppliers.TestedOn;

import java.io.IOException;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class TestMapper {
    private SumUsageMapper mapper;
    private Mapper<Text,Text,Text,FloatWritable>.Context context;

    @Before
    public void setup() {
        mapper=new SumUsageMapper();
        context=mock(Mapper.Context.class);

    }

    @Test
    public void aSimpleCase() throws IOException, InterruptedException {
        mapper.map(new Text("<http://example.com/yfi>"),new Text("0.7"),context);
        verify(context).write(new Text("<http://example.com/yfi>"),new FloatWritable(0.7F));
    }
}


text:
namespace OryolTools {

//------------------------------------------------------------------------------
void
CmdLineArgs::AddString(const char* name, const char* desc, const char* defaultVal) {
    assert(name && desc && defaultVal);
    assert(!this->HasArg(name));

    Arg arg;
    arg.type = Arg::String;
    arg.name = name;
    arg.desc = desc;
    arg.stringValue = defaultVal;
    this->args.push_back(arg);
}

//------------------------------------------------------------------------------
void
CmdLineArgs::AddBool(const char* name, const char* desc) {
    assert(name && desc);
    assert(!this->HasArg(name));

    Arg arg;
    arg.type = Arg::Bool;
    arg.name = name;
    arg.desc = desc;
    arg.boolValue = false;
    this->args.push_back(arg);
}

//------------------------------------------------------------------------------
int
CmdLineArgs::findArg(const char* name) const {
    assert(name);
    int i = 0;
    for (const auto& arg : this->args) {
        if (arg.name == name) {
            return i;
        }
        i++;
    }
    return -1;
}

//------------------------------------------------------------------------------
bool
CmdLineArgs::HasArg(const char* name) const {
    assert(name);
    int i = this->findArg(name);
    if (-1 != i) {
        switch (this->args[i].type) {
            case Arg::String:   return !this->args[i].stringValue.empty();
            case Arg::Bool:     return this->args[i].boolValue;
            default:            return false;
        }
    }
    return false;
}

//------------------------------------------------------------------------------
std::string
CmdLineArgs::GetString(const char* name) const {
    assert(name);
    int i = this->findArg(name);
    if (i != -1) {
        if (this->args[i].type == Arg::String) {
            return this->args[i].stringValue;
        }
        else {
            Log::Fatal("CmdLineArgs::GetString(%s): arg has not been declared as string!\n", name);
        }
    }
    else {
        Log::Fatal("CmdLineArgs::GetString(%s): arg not found!\n", name);
    }
    return "";
}

//------------------------------------------------------------------------------
bool
CmdLineArgs::GetBool(const char* name) const {
    assert(name);
    int i = this->findArg(name);
    if (i != -1) {
        if (this->args[i].type == Arg::Bool) {
            return this->args[i].boolValue;
        }
        else {
            Log::Fatal("CmdLineArgs::GetBool(%s): arg has not been declared as bool!\n", name);
        }
    }
    else {
        Log::Fatal("CmdLienArgs::GetBool(%s): arg '%s' not found!\n", name);
    }
    return false;
}

//------------------------------------------------------------------------------
void
CmdLineArgs::ShowHelp() const {
    for (const auto& arg : this->args) {
        Log::Info("%s\t\t-- %s\n", arg.name.c_str(), arg.desc.c_str());
    }
}

//------------------------------------------------------------------------------
bool
CmdLineArgs::Parse(int argc, const char** argv) {
    for (int i = 1; i < argc; i++) {
        const char* curArgName = argv[i];
        bool foundArg = false;
        for (auto& arg : this->args) {
            if (arg.name == curArgName) {
                if (arg.type == Arg::String) {
                    if (++i < argc) {
                        arg.stringValue = argv[i];
                        if (arg.stringValue[0] == '-') {
                            Log::Warn("CmdLineArgs::Parse(): expected arg string after '%s', got '%s'\n", curArgName, argv[i]);
                            return false;
                        }
                        foundArg = true;
                        break;
                    }
                    else {
                        Log::Warn("CmdLineArgs::Parse(): expected arg string after '%s', got nothing\n", curArgName);
                        return false;
                    }
                }
                else {
                    assert(arg.type == Arg::Bool);
                    arg.boolValue = true;
                    foundArg = true;
                    break;
                }
            }
        }
        if (!foundArg) {
            Log::Warn("CmdLineArgs::Parse(): unknown arg '%s'\n", curArgName);
            return false;
        }
    }
    return true;
}

} // namespace OryolTools


text:
ES5Harness.registerTest({
    id: "15.2.3.5-4-246",

    path: "TestCases/chapter15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-246.js",

    description: "Object.create - one property in 'Properties' is a String object that uses Object's [[Get]] method to access the 'get' property (8.10.5 step 7.a)",

    test: function testcase() {
        var strObj = new String("abc");

        strObj.get = function () {
            return "VerifyStringObject";
        };

        var newObj = Object.create({}, {
            prop: strObj
        });

        return newObj.prop === "VerifyStringObject";
    },

    precondition: function prereq() {
        return fnExists(Object.create);
    }
});


text:
namespace net {

namespace test {

ClosingDelegate::ClosingDelegate(
    const base::WeakPtr<SpdyStream>& stream) : stream_(stream) {
  DCHECK(stream_);
}

ClosingDelegate::~ClosingDelegate() = default;

void ClosingDelegate::OnHeadersSent() {}

void ClosingDelegate::OnEarlyHintsReceived(
    const spdy::Http2HeaderBlock& headers) {}

void ClosingDelegate::OnHeadersReceived(
    const spdy::Http2HeaderBlock& response_headers,
    const spdy::Http2HeaderBlock* pushed_request_headers) {}

void ClosingDelegate::OnDataReceived(std::unique_ptr<SpdyBuffer> buffer) {}

void ClosingDelegate::OnDataSent() {}

void ClosingDelegate::OnTrailers(const spdy::Http2HeaderBlock& trailers) {}

void ClosingDelegate::OnClose(int status) {
  DCHECK(stream_);
  stream_->Close();
  // The |stream_| may still be alive (if it is our delegate).
}

bool ClosingDelegate::CanGreaseFrameType() const {
  return false;
}

NetLogSource ClosingDelegate::source_dependency() const {
  return NetLogSource();
}

StreamDelegateBase::StreamDelegateBase(
    const base::WeakPtr<SpdyStream>& stream)
    : stream_(stream),
      stream_id_(0),
      send_headers_completed_(false) {
}

StreamDelegateBase::~StreamDelegateBase() = default;

void StreamDelegateBase::OnHeadersSent() {
  stream_id_ = stream_->stream_id();
  EXPECT_NE(stream_id_, 0u);
  send_headers_completed_ = true;
}

void StreamDelegateBase::OnEarlyHintsReceived(
    const spdy::Http2HeaderBlock& headers) {
  EXPECT_EQ(stream_->type() != SPDY_PUSH_STREAM, send_headers_completed_);
  early_hints_.push_back(headers.Clone());
}

void StreamDelegateBase::OnHeadersReceived(
    const spdy::Http2HeaderBlock& response_headers,
    const spdy::Http2HeaderBlock* pushed_request_headers) {
  EXPECT_EQ(stream_->type() != SPDY_PUSH_STREAM, send_headers_completed_);
  response_headers_ = response_headers.Clone();
}

void StreamDelegateBase::OnDataReceived(std::unique_ptr<SpdyBuffer> buffer) {
  if (buffer)
    received_data_queue_.Enqueue(std::move(buffer));
}

void StreamDelegateBase::OnDataSent() {}

void StreamDelegateBase::OnTrailers(const spdy::Http2HeaderBlock& trailers) {}

void StreamDelegateBase::OnClose(int status) {
  if (!stream_.get())
    return;
  stream_id_ = stream_->stream_id();
  stream_->GetLoadTimingInfo(&load_timing_info_);
  stream_.reset();
  callback_.callback().Run(status);
}

bool StreamDelegateBase::CanGreaseFrameType() const {
  return false;
}

NetLogSource StreamDelegateBase::source_dependency() const {
  return NetLogSource();
}

int StreamDelegateBase::WaitForClose() {
  int result = callback_.WaitForResult();
  EXPECT_TRUE(!stream_.get());
  return result;
}

std::string StreamDelegateBase::TakeReceivedData() {
  size_t len = received_data_queue_.GetTotalSize();
  std::string received_data(len, '\0');
  if (len > 0) {
    EXPECT_EQ(len, received_data_queue_.Dequeue(std::data(received_data), len));
  }
  return received_data;
}

std::string StreamDelegateBase::GetResponseHeaderValue(
    const std::string& name) const {
  spdy::Http2HeaderBlock::const_iterator it = response_headers_.find(name);
  return (it == response_headers_.end()) ? std::string()
                                         : std::string(it->second);
}

const LoadTimingInfo& StreamDelegateBase::GetLoadTimingInfo() {
  DCHECK(StreamIsClosed());
  return load_timing_info_;
}

StreamDelegateDoNothing::StreamDelegateDoNothing(
    const base::WeakPtr<SpdyStream>& stream)
    : StreamDelegateBase(stream) {}

StreamDelegateDoNothing::~StreamDelegateDoNothing() = default;

StreamDelegateConsumeData::StreamDelegateConsumeData(
    const base::WeakPtr<SpdyStream>& stream)
    : StreamDelegateBase(stream) {}

StreamDelegateConsumeData::~StreamDelegateConsumeData() = default;

void StreamDelegateConsumeData::OnDataReceived(
    std::unique_ptr<SpdyBuffer> buffer) {
  buffer->Consume(buffer->GetRemainingSize());
}

StreamDelegateSendImmediate::StreamDelegateSendImmediate(
    const base::WeakPtr<SpdyStream>& stream,
    base::StringPiece data)
    : StreamDelegateBase(stream), data_(data) {}

StreamDelegateSendImmediate::~StreamDelegateSendImmediate() = default;

void StreamDelegateSendImmediate::OnHeadersReceived(
    const spdy::Http2HeaderBlock& response_headers,
    const spdy::Http2HeaderBlock* pushed_request_headers) {
  StreamDelegateBase::OnHeadersReceived(response_headers,
                                        pushed_request_headers);
  if (data_.data()) {
    scoped_refptr<StringIOBuffer> buf =
        base::MakeRefCounted<StringIOBuffer>(std::string(data_));
    stream()->SendData(buf.get(), buf->size(), MORE_DATA_TO_SEND);
  }
}

StreamDelegateWithBody::StreamDelegateWithBody(
    const base::WeakPtr<SpdyStream>& stream,
    base::StringPiece data)
    : StreamDelegateBase(stream),
      buf_(base::MakeRefCounted<StringIOBuffer>(std::string(data))) {}

StreamDelegateWithBody::~StreamDelegateWithBody() = default;

void StreamDelegateWithBody::OnHeadersSent() {
  StreamDelegateBase::OnHeadersSent();
  stream()->SendData(buf_.get(), buf_->size(), NO_MORE_DATA_TO_SEND);
}

StreamDelegateCloseOnHeaders::StreamDelegateCloseOnHeaders(
    const base::WeakPtr<SpdyStream>& stream)
    : StreamDelegateBase(stream) {
}

StreamDelegateCloseOnHeaders::~StreamDelegateCloseOnHeaders() = default;

void StreamDelegateCloseOnHeaders::OnHeadersReceived(
    const spdy::Http2HeaderBlock& response_headers,
    const spdy::Http2HeaderBlock* pushed_request_headers) {
  stream()->Cancel(ERR_ABORTED);
}

StreamDelegateDetectEOF::StreamDelegateDetectEOF(
    const base::WeakPtr<SpdyStream>& stream)
    : StreamDelegateBase(stream) {}

StreamDelegateDetectEOF::~StreamDelegateDetectEOF() = default;

void StreamDelegateDetectEOF::OnDataReceived(
    std::unique_ptr<SpdyBuffer> buffer) {
  if (!buffer)
    eof_detected_ = true;
}

}  // namespace test

}  // namespace net


text:
Merge sort: http://en.wikipedia.org/wiki/Merge_sort
Cascade merge sort
Oscillating merge sort
Polyphase merge sort
Strand sort


text:
package org.opencv.img_hash;

import org.opencv.core.Algorithm;
import org.opencv.core.Mat;

// C++: class ImgHashBase
//javadoc: ImgHashBase

public class ImgHashBase extends Algorithm {

    protected ImgHashBase(long addr) { super(addr); }

    // internal usage only
    public static ImgHashBase __fromPtr__(long addr) { return new ImgHashBase(addr); }

    //
    // C++:  double compare(Mat hashOne, Mat hashTwo)
    //

    //javadoc: ImgHashBase::compare(hashOne, hashTwo)
    public  double compare(Mat hashOne, Mat hashTwo)
    {

        double retVal = compare_0(nativeObj, hashOne.nativeObj, hashTwo.nativeObj);

        return retVal;
    }

    //
    // C++:  void compute(Mat inputArr, Mat& outputArr)
    //

    //javadoc: ImgHashBase::compute(inputArr, outputArr)
    public  void compute(Mat inputArr, Mat outputArr)
    {

        compute_0(nativeObj, inputArr.nativeObj, outputArr.nativeObj);

        return;
    }

    @Override
    protected void finalize() throws Throwable {
        delete(nativeObj);
    }

    // C++:  double compare(Mat hashOne, Mat hashTwo)
    private static native double compare_0(long nativeObj, long hashOne_nativeObj, long hashTwo_nativeObj);

    // C++:  void compute(Mat inputArr, Mat& outputArr)
    private static native void compute_0(long nativeObj, long inputArr_nativeObj, long outputArr_nativeObj);

    // native support for java finalize()
    private static native void delete(long nativeObj);

}


text:
import * as Mocha from 'mocha';
import { expect } from 'chai';
import { Math } from '../Math';

describe('Math', function () {
    it('Success', function () {
        var math = new Math();
        expect(math.sum(1, 2)).to.equal(3);
    });

    it('Arrow function will work too', () => {
        var math = new Math();
        expect(math.sum(1, 2)).to.equal(0);
    });
});


text:
package cercleSportif;

import java.util.Vector;

public class Discipline {

	private Vector<Moniteur> moniteurs;
	private Federation federation;
	private Vector<Cours> cours;

	private String nom;
	private String description;

	public Discipline(String nom) {
		this.nom = nom;
	}
	public Discipline(String nom, String description) {
		this.nom = nom;
		this.description = description;
	}

	public String getNom() {
		return nom;
	}
	public void setNom(String nom) {
		this.nom = nom;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public Federation getFederation() {
		return federation;
	}
	public void setFederation(Federation federation) {
		this.federation = federation;
	}

}


text:
package org.wso2.carbon.apimgt.common.gateway.graphql;

import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class GraphQLSchemaDefinitionTest {
    @Test
    public void testSubscriptionAvailability() throws Exception {
        String graphqlDirPath = "definitions" + File.separator + "graphql" + File.separator;
        String relativePath = graphqlDirPath + "schema_with_subscriptions.graphql";
        String schema = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath),
                StandardCharsets.UTF_8);
        Assert.assertTrue(GraphQLSchemaDefinitionUtil.isSubscriptionAvailable(schema));
        relativePath = graphqlDirPath + "schema_without_subscriptions.graphql";
        schema = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath),
                StandardCharsets.UTF_8);
        Assert.assertFalse(GraphQLSchemaDefinitionUtil.isSubscriptionAvailable(schema));
    }

    @Test
    public void testSubscriptionAvailabilityWithoutDefaultOperationNames() throws Exception {
        String graphqlDirPath = "definitions" + File.separator + "graphql" + File.separator;
        String relativePath = graphqlDirPath + "schema_with_subscriptions_without_default_operation_names.graphql";
        String schema = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath));
        Assert.assertTrue(GraphQLSchemaDefinitionUtil.isSubscriptionAvailable(schema));
        relativePath = graphqlDirPath + "schema_without_subscriptions.graphql";
        schema = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath));
        Assert.assertFalse(GraphQLSchemaDefinitionUtil.isSubscriptionAvailable(schema));
    }
}


text:
package org.apache.flink.test.streaming.runtime;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringEncoder;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.file.sink.FileSink;
import org.apache.flink.connector.file.src.FileSource;
import org.apache.flink.connector.file.src.reader.TextLineInputFormat;
import org.apache.flink.runtime.jobgraph.IntermediateDataSetID;
import org.apache.flink.runtime.minicluster.RpcServiceSharing;
import org.apache.flink.runtime.scheduler.ClusterDatasetCorruptedException;
import org.apache.flink.runtime.testutils.MiniClusterResourceConfiguration;
import org.apache.flink.streaming.api.datastream.CachedDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.transformations.CacheTransformation;
import org.apache.flink.streaming.util.TestStreamEnvironment;
import org.apache.flink.test.util.AbstractTestBase;
import org.apache.flink.test.util.MiniClusterWithClientResource;
import org.apache.flink.util.AbstractID;
import org.apache.flink.util.CloseableIterator;
import org.apache.flink.util.CollectionUtil;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;

/** Test datastream cache. */
@Disabled
public class CacheITCase extends AbstractTestBase {

    private StreamExecutionEnvironment env;
    private MiniClusterWithClientResource miniClusterWithClientResource;

    @BeforeEach
    void setUp() throws Exception {

        final Configuration configuration = new Configuration();
        miniClusterWithClientResource =
                new MiniClusterWithClientResource(
                        new MiniClusterResourceConfiguration.Builder()
                                .setConfiguration(configuration)
                                .setNumberTaskManagers(1)
                                .setNumberSlotsPerTaskManager(8)
                                .setRpcServiceSharing(RpcServiceSharing.DEDICATED)
                                .withHaLeadershipControl()
                                .build());
        miniClusterWithClientResource.before();

        env = new TestStreamEnvironment(miniClusterWithClientResource.getMiniCluster(), 8);
        env.setRuntimeMode(RuntimeExecutionMode.BATCH);
    }

    @AfterEach
    void tearDown() {
        miniClusterWithClientResource.after();
    }

    @Test
    void testCacheProduceAndConsume(@TempDir java.nio.file.Path tmpDir) throws Exception {
        File file = prepareTestData(tmpDir);

        FileSource<String> source =
                FileSource.forRecordStreamFormat(
                                new TextLineInputFormat(),
                                new org.apache.flink.core.fs.Path(file.getPath()))
                        .build();
        final CachedDataStream<Integer> cachedDataStream =
                env.fromSource(source, WatermarkStrategy.noWatermarks(), "source")
                        .map(i -> Integer.parseInt(i) + 1)
                        .cache();

        try (CloseableIterator<Integer> resultIterator = cachedDataStream.executeAndCollect()) {
            List<Integer> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(2, 3, 4);
        }

        assertThat(file.delete()).isTrue();

        try (CloseableIterator<Integer> resultIterator = cachedDataStream.executeAndCollect()) {
            List<Integer> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(2, 3, 4);
        }
    }

    @Test
    void testInvalidateCache(@TempDir java.nio.file.Path tmpDir) throws Exception {
        File file = prepareTestData(tmpDir);

        FileSource<String> source =
                FileSource.forRecordStreamFormat(
                                new TextLineInputFormat(),
                                new org.apache.flink.core.fs.Path(file.getPath()))
                        .build();

        final CachedDataStream<Integer> cachedDataStream =
                env.fromSource(source, WatermarkStrategy.noWatermarks(), "source")
                        .map(i -> Integer.parseInt(i) + 1)
                        .cache();

        try (CloseableIterator<Integer> resultIterator = cachedDataStream.executeAndCollect()) {
            List<Integer> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(2, 3, 4);
        }

        assertThat(file.delete()).isTrue();

        try (CloseableIterator<Integer> resultIterator = cachedDataStream.executeAndCollect()) {
            List<Integer> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(2, 3, 4);
        }

        cachedDataStream.invalidate();

        // overwrite the content of the source file
        try (FileWriter writer = new FileWriter(file)) {
            writer.write("4\n5\n6\n");
        }

        // after cache is invalidated it should re-read from source file with the updated content
        try (CloseableIterator<Integer> resultIterator = cachedDataStream.executeAndCollect()) {
            List<Integer> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(5, 6, 7);
        }
    }

    @Test
    void testBatchProduceCacheStreamConsume(@TempDir java.nio.file.Path tmpDir) throws Exception {

        File file = prepareTestData(tmpDir);

        FileSource<String> source =
                FileSource.forRecordStreamFormat(
                                new TextLineInputFormat(),
                                new org.apache.flink.core.fs.Path(file.getPath()))
                        .build();
        final CachedDataStream<Integer> cachedDataStream =
                env.fromSource(source, WatermarkStrategy.noWatermarks(), "source")
                        .map(Integer::parseInt)
                        .map(i -> i + 1)
                        .cache();

        try (CloseableIterator<Integer> resultIterator = cachedDataStream.executeAndCollect()) {
            List<Integer> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(2, 3, 4);
        }

        assertThat(file.delete()).isTrue();

        env.setRuntimeMode(RuntimeExecutionMode.STREAMING);
        try (CloseableIterator<Integer> resultIterator =
                cachedDataStream.map(i -> i + 1).executeAndCollect()) {
            List<Integer> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(3, 4, 5);
        }
    }

    @Test
    void testCacheProduceAndConsumeWithDifferentPartitioner() throws Exception {

        final DataStreamSource<Tuple2<Integer, Integer>> ds =
                env.fromElements(new Tuple2<>(1, 1), new Tuple2<>(2, 1), new Tuple2<>(2, 1));

        final CachedDataStream<Tuple2<Integer, Integer>> cacheSource = ds.cache();
        SingleOutputStreamOperator<Tuple2<Integer, Integer>> result =
                cacheSource.keyBy(v -> v.f0).reduce((v1, v2) -> new Tuple2<>(v1.f0, v1.f1 + v2.f1));

        try (CloseableIterator<Tuple2<Integer, Integer>> resultIterator =
                result.executeAndCollect()) {
            List<Tuple2<Integer, Integer>> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(new Tuple2<>(1, 1), new Tuple2<>(2, 2));
        }

        result =
                cacheSource.keyBy(t -> t.f1).reduce((v1, v2) -> new Tuple2<>(v1.f0 + v2.f0, v1.f1));

        try (CloseableIterator<Tuple2<Integer, Integer>> resultIterator =
                result.executeAndCollect()) {
            List<Tuple2<Integer, Integer>> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(new Tuple2<>(5, 1));
        }
    }

    @Test
    void testCacheSideOutput() throws Exception {
        OutputTag<Integer> tag = new OutputTag<Integer>("2") {};
        final DataStreamSource<Tuple2<Integer, Integer>> ds =
                env.fromElements(new Tuple2<>(1, 1), new Tuple2<>(2, 1), new Tuple2<>(2, 2));

        final SingleOutputStreamOperator<Integer> processed =
                ds.process(
                        new ProcessFunction<Tuple2<Integer, Integer>, Integer>() {
                            @Override
                            public void processElement(
                                    Tuple2<Integer, Integer> v,
                                    ProcessFunction<Tuple2<Integer, Integer>, Integer>.Context ctx,
                                    Collector<Integer> out) {
                                if (v.f0 == 2) {
                                    ctx.output(tag, v.f1);
                                    return;
                                }
                                out.collect(v.f1);
                            }
                        });

        final CachedDataStream<Integer> cachedSideOutput = processed.getSideOutput(tag).cache();

        try (CloseableIterator<Integer> resultIterator = cachedSideOutput.executeAndCollect()) {
            List<Integer> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(1, 2);
        }

        try (CloseableIterator<Integer> resultIterator = cachedSideOutput.executeAndCollect()) {
            List<Integer> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(1, 2);
        }
    }

    @Test
    void testRetryOnCorruptedClusterDataset(@TempDir java.nio.file.Path tmpDir) throws Exception {
        File file = prepareTestData(tmpDir);

        FileSource<String> source =
                FileSource.forRecordStreamFormat(
                                new TextLineInputFormat(),
                                new org.apache.flink.core.fs.Path(file.getPath()))
                        .build();
        final CachedDataStream<Integer> cachedDataStream =
                env.fromSource(source, WatermarkStrategy.noWatermarks(), "source")
                        .map(i -> Integer.parseInt(i) + 1)
                        .cache();

        try (CloseableIterator<Integer> resultIterator = cachedDataStream.executeAndCollect()) {
            List<Integer> results = CollectionUtil.iteratorToList(resultIterator);
            assertThat(results).containsExactlyInAnyOrder(2, 3, 4);
        }

        final AbstractID datasetId =
                ((CacheTransformation<Integer>) cachedDataStream.getTransformation())
                        .getDatasetId();

        assertThat(file.delete()).isTrue();
        // overwrite the content of the source file
        try (FileWriter writer = new FileWriter(file)) {
            writer.write("4\n5\n6\n");
        }

        final File outputFile = new File(tmpDir.toFile(), UUID.randomUUID().toString());
        cachedDataStream
                .flatMap(
                        (FlatMapFunction<Integer, Integer>)
                                (value, out) -> {
                                    if (value < 5) {
                                        // Simulate ClusterDatasetCorruptedException.
                                        throw new ClusterDatasetCorruptedException(
                                                null,
                                                Collections.singletonList(
                                                        new IntermediateDataSetID(datasetId)));
                                    }
                                    out.collect(value);
                                })
                .returns(Integer.class)
                .sinkTo(
                        FileSink.forRowFormat(
                                        new org.apache.flink.core.fs.Path(outputFile.getPath()),
                                        new SimpleStringEncoder<Integer>())
                                .build());
        env.execute();
        assertThat(getFileContext(outputFile)).containsExactlyInAnyOrder("5", "6", "7");
    }

    private static List<String> getFileContext(File directory) throws IOException {
        List<String> res = new ArrayList<>();

        final Collection<File> filesInBucket = FileUtils.listFiles(directory, null, true);
        for (File file : filesInBucket) {
            res.addAll(Arrays.asList(FileUtils.readFileToString(file).split("\n")));
        }

        return res;
    }

    private File prepareTestData(Path tmpDir) throws IOException {
        final File datafile = new File(tmpDir.toFile(), UUID.randomUUID().toString());
        try (FileWriter writer = new FileWriter(datafile)) {
            writer.write("1\n2\n3\n");
        }
        return datafile;
    }
}


text:
package org.tensorflow.framework;

public final class TensorDescriptionProtos {
  private TensorDescriptionProtos() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_tensorflow_TensorDescription_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_tensorflow_TensorDescription_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n\030tensor_description.proto\022\ntensorflow\032%" +
      "tensorflow/core/framework/types.proto\032,t" +
      "ensorflow/core/framework/tensor_shape.pr" +
      "oto\0326tensorflow/core/framework/allocatio" +
      "n_description.proto\"\250\001\n\021TensorDescriptio" +
      "n\022#\n\005dtype\030\001 \001(\0162\024.tensorflow.DataType\022+" +
      "\n\005shape\030\002 \001(\0132\034.tensorflow.TensorShapePr" +
      "oto\022A\n\026allocation_description\030\004 \001(\0132!.te" +
      "nsorflow.AllocationDescriptionB8\n\030org.te" +
      "nsorflow.frameworkB\027TensorDescriptionPro",
      "tosP\001\370\001\001b\006proto3"
    };
    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
        new com.google.protobuf.Descriptors.FileDescriptor.    InternalDescriptorAssigner() {
          public com.google.protobuf.ExtensionRegistry assignDescriptors(
              com.google.protobuf.Descriptors.FileDescriptor root) {
            descriptor = root;
            return null;
          }
        };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
          org.tensorflow.framework.TypesProtos.getDescriptor(),
          org.tensorflow.framework.TensorShapeProtos.getDescriptor(),
          org.tensorflow.framework.AllocationDescriptionProtos.getDescriptor(),
        }, assigner);
    internal_static_tensorflow_TensorDescription_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_tensorflow_TensorDescription_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_tensorflow_TensorDescription_descriptor,
        new java.lang.String[] { "Dtype", "Shape", "AllocationDescription", });
    org.tensorflow.framework.TypesProtos.getDescriptor();
    org.tensorflow.framework.TensorShapeProtos.getDescriptor();
    org.tensorflow.framework.AllocationDescriptionProtos.getDescriptor();
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
package Final;

import org.junit.Test;

import java.util.LinkedList;

import static org.junit.Assert.*;

/**
 * Made for problem 10
 */
public class TestTrieMap {
    @Test
    public void testTrie() {
        TrieMap trie = new TrieMap();
        trie.addWord("Java");
        trie.addWord("JavaOne");
        trie.addWord("JavaTwo");
        trie.addWord("JavaThree");
        trie.addWord("JavaFour");
        trie.addWord("JavaFive");
        trie.addWord("burden");
        trie.addWord("burger");
        trie.addWord("burp");
        trie.addWord("burper");
        assertTrue(trie.contains("Java"));
    }

    @Test
    public void testAdd() {
        TrieMap trie = new TrieMap();
        trie.addWord("Java");
        trie.addWord("Java");
        trie.addWord("Java");
        trie.addWord("Java");
        trie.addWord("Hello");
        LinkedList<TrieMap.TrieNode> l = trie.getAllWords(trie.root);
        assertEquals(1, l.get(0).count);
        assertEquals(4, l.get(1).count);
    }

    @Test
    public void testContains() {
        TrieMap trie = new TrieMap();
        trie.addWord("Java");
        trie.addWord("kartik");
        trie.addWord("hello");
        assertTrue(trie.contains("hello"));
        assertFalse(trie.contains("nah"));
    }

    public static boolean testCount(TrieMap t){
        LinkedList<TrieMap.TrieNode> words = t.getAllWords(t.root);
        for(TrieMap.TrieNode node : words){
            if ( node.count < 5){
            return false;
            }
        }
        return true;

    }

    public static void main(String[] args) {
        TrieMap t = new TrieMap();
        t.addWord("hello");
        t.addWord("kartik");
        t.addWord("Java");
        t.addWord("kartik");
        t.addWord("kartik");
        t.addWord("kartik");
        t.addWord("kartik");
        t.addWord("kartik");
        testCount(t);
    }
}


text:
<?php

class CrudCode extends CCodeModel
{
	public $model;
	public $controller;
	public $baseControllerClass='Controller';

	private $_modelClass;
	private $_table;

	public function rules()
	{
		return array_merge(parent::rules(), array(
			array('model, controller', 'filter', 'filter'=>'trim'),
			array('model, controller, baseControllerClass', 'required'),
			array('model', 'match', 'pattern'=>'/^\w+[\w+\\.]*$/', 'message'=>'{attribute} should only contain word characters and dots.'),
			array('controller', 'match', 'pattern'=>'/^\w+[\w+\\/]*$/', 'message'=>'{attribute} should only contain word characters and slashes.'),
			array('baseControllerClass', 'match', 'pattern'=>'/^[a-zA-Z_]\w*$/', 'message'=>'{attribute} should only contain word characters.'),
			array('baseControllerClass', 'validateReservedWord', 'skipOnError'=>true),
			array('model', 'validateModel'),
			array('baseControllerClass', 'sticky'),
		));
	}

	public function attributeLabels()
	{
		return array_merge(parent::attributeLabels(), array(
			'model'=>'Model Class',
			'controller'=>'Controller ID',
			'baseControllerClass'=>'Base Controller Class',
		));
	}

	public function requiredTemplates()
	{
		return array(
			'controller.php',
		);
	}

	public function init()
	{
		if(Yii::app()->db===null)
			throw new CHttpException(500,'An active "db" connection is required to run this generator.');
		parent::init();
	}

	public function successMessage()
	{
		$link=CHtml::link('try it now', Yii::app()->createUrl($this->controller), array('target'=>'_blank'));
		return "The controller has been generated successfully. You may $link.";
	}

	public function validateModel($attribute,$params)
	{
		if($this->hasErrors('model'))
			return;
		$class=@Yii::import($this->model,true);
		if(!is_string($class) || !$this->classExists($class))
			$this->addError('model', "Class '{$this->model}' does not exist or has syntax error.");
		else if(!is_subclass_of($class,'CActiveRecord'))
			$this->addError('model', "'{$this->model}' must extend from CActiveRecord.");
		else
		{
			$table=CActiveRecord::model($class)->tableSchema;
			if($table->primaryKey===null)
				$this->addError('model',"Table '{$table->name}' does not have a primary key.");
			else if(is_array($table->primaryKey))
				$this->addError('model',"Table '{$table->name}' has a composite primary key which is not supported by crud generator.");
			else
			{
				$this->_modelClass=$class;
				$this->_table=$table;
			}
		}
	}

	public function prepare()
	{
		$this->files=array();
		$templatePath=$this->templatePath;
		$controllerTemplateFile=$templatePath.DIRECTORY_SEPARATOR.'controller.php';

		$this->files[]=new CCodeFile(
			$this->controllerFile,
			$this->render($controllerTemplateFile)
		);

		$files=scandir($templatePath);
		foreach($files as $file)
		{
			if(is_file($templatePath.'/'.$file) && CFileHelper::getExtension($file)==='php' && $file!=='controller.php')
			{
				$this->files[]=new CCodeFile(
					$this->viewPath.DIRECTORY_SEPARATOR.$file,
					$this->render($templatePath.'/'.$file)
				);
			}
		}
	}

	public function getModelClass()
	{
		return $this->_modelClass;
	}

	public function getControllerClass()
	{
		if(($pos=strrpos($this->controller,'/'))!==false)
			return ucfirst(substr($this->controller,$pos+1)).'Controller';
		else
			return ucfirst($this->controller).'Controller';
	}

	public function getModule()
	{
		if(($pos=strpos($this->controller,'/'))!==false)
		{
			$id=substr($this->controller,0,$pos);
			if(($module=Yii::app()->getModule($id))!==null)
				return $module;
		}
		return Yii::app();
	}

	public function getControllerID()
	{
		if($this->getModule()!==Yii::app())
			$id=substr($this->controller,strpos($this->controller,'/')+1);
		else
			$id=$this->controller;
		if(($pos=strrpos($id,'/'))!==false)
			$id[$pos+1]=strtolower($id[$pos+1]);
		else
			$id[0]=strtolower($id[0]);
		return $id;
	}

	public function getUniqueControllerID()
	{
		$id=$this->controller;
		if(($pos=strrpos($id,'/'))!==false)
			$id[$pos+1]=strtolower($id[$pos+1]);
		else
			$id[0]=strtolower($id[0]);
		return $id;
	}

	public function getControllerFile()
	{
		$module=$this->getModule();
		$id=$this->getControllerID();
		if(($pos=strrpos($id,'/'))!==false)
			$id[$pos+1]=strtoupper($id[$pos+1]);
		else
			$id[0]=strtoupper($id[0]);
		return $module->getControllerPath().'/'.$id.'Controller.php';
	}

	public function getViewPath()
	{
		return $this->getModule()->getViewPath().'/'.$this->getControllerID();
	}

	public function getTableSchema()
	{
		return $this->_table;
	}

	public function generateInputLabel($modelClass,$column)
	{
		return "CHtml::activeLabelEx(\$model,'{$column->name}')";
	}

	public function generateInputField($modelClass,$column)
	{
		if($column->type==='boolean')
			return "CHtml::activeCheckBox(\$model,'{$column->name}')";
		else if(stripos($column->dbType,'text')!==false)
			return "CHtml::activeTextArea(\$model,'{$column->name}',array('rows'=>6, 'cols'=>50))";
		else
		{
			if(preg_match('/^(password|pass|passwd|passcode)$/i',$column->name))
				$inputField='activePasswordField';
			else
				$inputField='activeTextField';

			if($column->type!=='string' || $column->size===null)
				return "CHtml::{$inputField}(\$model,'{$column->name}')";
			else
			{
				if(($size=$maxLength=$column->size)>60)
					$size=60;
				return "CHtml::{$inputField}(\$model,'{$column->name}',array('size'=>$size,'maxlength'=>$maxLength))";
			}
		}
	}

	public function generateActiveLabel($modelClass,$column)
	{
		return "\$form->labelEx(\$model,'{$column->name}')";
	}

	public function generateActiveField($modelClass,$column)
	{
		if($column->type==='boolean')
			return "\$form->checkBox(\$model,'{$column->name}')";
		else if(stripos($column->dbType,'text')!==false)
			return "\$form->textArea(\$model,'{$column->name}',array('class'=>'ckeditor', 'id'=>'editor1', 'rows'=>10, 'cols'=>80))";
		else if(stripos($column->dbType,'time')!==false || stripos($column->dbType,'data')!==false)
			return "\$form->textField(\$model,'{$column->name}',array('id'=>'{$column->name}', 'readonly'=>'readonly', 'onclick'=>\"return showCalendar('{$column->name}','%Y-%m-%d',false,false,'{$column->name}');\"))";
		else if(stripos($column->dbType,'enum')!==false)
                {
                        preg_match_all('/\'([\w_]+)\'/i', $column->dbType, $matchesEnum);
                        $data = 'array(';
                        foreach($matchesEnum[1] as $val)
                        {
                            $data .= "'$val'=>'" . $val . "',";
                        }
                        $data .= ")";

			return "\$form->radioButtonList(\$model,'{$column->name}', $data, array('class'=>'radio'))";
                }
                else
		{
			if(preg_match('/^(password|pass|passwd|passcode)$/i',$column->name))
                        {
				$inputField='passwordField';
                        }
			elseif(preg_match('/^(\w+_)?(cat_id|cat|parent_id)$/i',$column->name,$matches))
                        {
                                if(preg_match('/^parent_id$/i',$column->name))
                                {
                                    $prefix = preg_replace('/^(\w+)?category$/i', '${1}',$this->modelClass);
                                }
                                else
                                {
                                    $prefix = isset($matches[1]) && !empty($matches[1]) ? preg_replace('/_$/i','',$matches[1]): '';
                                }
				return "\$form->dropDownList(\$model,'{$column->name}',\${$prefix}Categorys)";
			}
			elseif(preg_match('/(file|img|image|photo)$/i',$column->name))
                        {
				return "\$form->fileField(\$model,'{$column->name}')";
			}
			else
				$inputField='textField';

                        if($column->size >= 255)
                        {
                            return "\$form->textArea(\$model,'{$column->name}')";
                        }
			elseif($column->type!=='string' || $column->size===null)
				return "\$form->{$inputField}(\$model,'{$column->name}')";
			else
			{
				if(($size=$maxLength=$column->size)>60) $size=60;
				return "\$form->{$inputField}(\$model,'{$column->name}',array('size'=>$size,'maxlength'=>$maxLength))";
			}
		}
	}

	public function guessNameColumn($columns)
	{
		foreach($columns as $column)
		{
			if(!strcasecmp($column->name,'name'))
				return $column->name;
		}
		foreach($columns as $column)
		{
			if(!strcasecmp($column->name,'title'))
				return $column->name;
		}
		foreach($columns as $column)
		{
			if($column->isPrimaryKey)
				return $column->name;
		}
		return 'id';
	}
}


text:
@interface JLYMethodSwizzling : NSObject

void SwizzlingMethod(Class c, SEL origSEL, SEL newSEL);

@end


text:
using System;
using System.Collections.Generic;
using System.Text;
using wojilu.Web.Mvc;
using wojilu.Members.Sites.Domain;

namespace wojilu.Web.Controller.Users.Admin.Friends {

    public class LayoutController : ControllerBase{

        public override void Layout() {
            set( "f.ListLink", to( new FriendController().List, 0 ) );
            set( "f.FollowingLink", to( new FriendController().FollowingList ) );
            set( "f.MoreLink", to( new FriendController().More ) );
            set( "f.SearchLink", to( new FriendController().Search ) );
            set( "f.InviteLink", to( new InviteController().Index ) );
            set( "f.Rank", Link.To( Site.Instance, new wojilu.Web.Controller.Users.MainController().Rank ) );
        }

    }

}


text:
.class Lcom/android/server/am/TaskPersister$1;
.super Ljava/lang/Object;
.source "TaskPersister.java"

# interfaces
.implements Ljava/util/Comparator;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/am/TaskPersister;->restoreTasksForUserLocked(ILandroid/util/SparseBooleanArray;)Ljava/util/List;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Ljava/util/Comparator",
        "<",
        "Lcom/android/server/am/TaskRecord;",
        ">;"
    }
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/am/TaskPersister;

# direct methods
.method constructor <init>(Lcom/android/server/am/TaskPersister;)V
    .locals 0

    iput-object p1, p0, Lcom/android/server/am/TaskPersister$1;->this$0:Lcom/android/server/am/TaskPersister;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public compare(Lcom/android/server/am/TaskRecord;Lcom/android/server/am/TaskRecord;)I
    .locals 8

    const-wide/16 v6, 0x0

    iget-wide v2, p2, Lcom/android/server/am/TaskRecord;->mLastTimeMoved:J

    iget-wide v4, p1, Lcom/android/server/am/TaskRecord;->mLastTimeMoved:J

    sub-long v0, v2, v4

    cmp-long v2, v0, v6

    if-gez v2, :cond_0

    const/4 v2, -0x1

    return v2

    :cond_0
    cmp-long v2, v0, v6

    if-lez v2, :cond_1

    const/4 v2, 0x1

    return v2

    :cond_1
    const/4 v2, 0x0

    return v2
.end method

.method public bridge synthetic compare(Ljava/lang/Object;Ljava/lang/Object;)I
    .locals 1

    check-cast p1, Lcom/android/server/am/TaskRecord;

    check-cast p2, Lcom/android/server/am/TaskRecord;

    invoke-virtual {p0, p1, p2}, Lcom/android/server/am/TaskPersister$1;->compare(Lcom/android/server/am/TaskRecord;Lcom/android/server/am/TaskRecord;)I

    move-result v0

    return v0
.end method


text:
require 'bio-ucsc'
describe "Bio::Ucsc::HgFixed_GnfHumanAtlas2MedianRatio" do

  describe "#find_by_name" do
    context 'given "1007_s_at"' do
      it 'returns (r.expScores =~ /\A1\.230/)' do
        Bio::Ucsc::HgFixed::DBConnection.default
        Bio::Ucsc::HgFixed::DBConnection.connect
        r = Bio::Ucsc::HgFixed::GnfHumanAtlas2MedianRatio.find_by_name("1007_s_at")
        r.expScores.should =~ /\A1\.230/
      end
    end
  end

end


text:
package horizon

import (
	"github.com/jojopoper/horizon/db"
	"github.com/jojopoper/horizon/render/hal"
)

// OrderBookShowAction renders a account summary found by its address.
type OrderBookShowAction struct {
	Action
	Query    db.OrderBookSummaryQuery
	Record   db.OrderBookSummaryRecord
	Resource OrderBookSummaryResource
}

// LoadQuery sets action.Query from the request params
func (action *OrderBookShowAction) LoadQuery() {
	params := action.GetOrderBook()

	action.Query = db.OrderBookSummaryQuery{
		SqlQuery:      action.App.CoreQuery(),
		SellingType:   params.SellingType,
		SellingIssuer: params.SellingIssuer,
		SellingCode:   params.SellingCode,
		BuyingType:    params.BuyingType,
		BuyingIssuer:  params.BuyingIssuer,
		BuyingCode:    params.BuyingCode,
	}

	return
}

// LoadRecord populates action.Record
func (action *OrderBookShowAction) LoadRecord() {
	action.Err = db.Select(action.Ctx, action.Query, &action.Record)
}

// LoadResource populates action.Record
func (action *OrderBookShowAction) LoadResource() {
	action.Resource, action.Err = NewOrderBookSummaryResource(action.Query, action.Record)
}

// JSON is a method for actions.JSON
func (action *OrderBookShowAction) JSON() {
	action.Do(action.LoadQuery, action.LoadRecord, action.LoadResource)

	action.Do(func() {
		hal.Render(action.W, action.Resource)
	})
}


text:
Template.CaseStudies.rendered = function(){

};


text:
'use strict'

const BB = require('bluebird')

module.exports = function (child, hasExitCode = false) {
  return BB.fromNode(function (cb) {
    child.on('error', cb)
    child.on(hasExitCode ? 'close' : 'end', function (exitCode) {
      if (exitCode === undefined || exitCode === 0) {
        cb()
      } else {
        let err = new Error('exited with error code: ' + exitCode)
        cb(err)
      }
    })
  })
}


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "wishList".
 *
 * @property integer $id
 * @property integer $content
 * @property integer $wishedBy
 *
 * @property Content $content0
 * @property User $wishedBy0
 */
class WishList extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'wishList';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['content', 'wishedBy'], 'required'],
            [['content', 'wishedBy'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'content' => 'Content',
            'wishedBy' => 'Wished By',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getContent0()
    {
        return $this->hasOne(Content::className(), ['id' => 'content']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getWishedBy0()
    {
        return $this->hasOne(User::className(), ['id' => 'wishedBy']);
    }
}


text:
<?php

namespace Kdyby\RabbitMq;

use PhpAmqpLib\Connection\AMQPConnection;

/**
 * @author Alvaro Videla <videlalvaro@gmail.com>
 * @author Filip Procházka <filip@prochazka.su>
 */
class AnonymousConsumer extends Consumer
{

	public function __construct(AMQPConnection $conn)
	{
		parent::__construct($conn);

		$this->setQueueOptions(array(
			'name' => '',
			'passive' => false,
			'durable' => false,
			'exclusive' => true,
			'autoDelete' => true,
			'nowait' => false,
			'arguments' => null,
			'ticket' => null
		));
	}

}


text:
module.exports = {
  // See https://github.com/Polymer/web-component-tester/blob/master/runner/config.js#L47-54
  activeBrowsers: [],
  plugins: {
    local: true
  },
  root: '.'
};


text:
/**
 * Module dependencies
 */

var _ = require('@sailshq/lodash');
var flaverr = require('flaverr');
var Err = require('../../../errors');

/**
 * Policies hook
 * @param  {SailsApp} sails
 */
module.exports = function(sails) {

  /**
   * Expose `policies` hook definition
   */
  var policyHookDef = {

    defaults: {

      // Default policy mappings (allow all)
      policies: { }
    },

    configure: function () {
      this.middleware || (this.middleware = { });
    },

    /**
     * Initialize is fired first thing when the hook is loaded
     *
     * @api public
     */
    initialize: function(cb) {

      var self = this;

      // Grab policies config & policy modules and trigger callback
      self.loadMiddleware(function (err) {
        if (err) { return cb(err); }

        sails.log.silly('Finished loading policy middleware functions.  Preparing to bind policies based on config...');
        try {
          self.bindPolicies();
        } catch (e) { return cb(e); }

        return cb();
      });

    },

    /**
     * Wipe everything and (re)load middleware from policies
     * (policies.js config is already loaded at this point)
     *
     * @api private
     */
    loadMiddleware: function(cb) {

      var self = this;

      // Load policy modules from disk.
      sails.log.silly('Loading policy modules from app...');
      sails.modules.loadPolicies(function modulesLoaded (err, modules) {
        if (err) { return cb(err); }

        // Add the loaded policies to our internal dictionary.
        _.extend(self.middleware, modules);

        // If any policies were specified when loading Sails, add those on
        // top of the ones loaded from disk.
        if (sails.config.policies && sails.config.policies.moduleDefinitions) {
          _.extend(self.middleware, sails.config.policies.moduleDefinitions);
        }

        // Validate that all policies are functions.
        try {
          _.each(_.keys(self.middleware), function(policyName) {
            // If we find a bad'n, bail out.
            if (!_.isFunction(sails.hooks.policies.middleware[policyName])) {
              throw flaverr({ name: 'userError', code: 'E_INVALID_POLICY' }, new Error('Failed loading invalid policy `' + policyName + '` (expected a function, but got a `' + typeof(sails.hooks.policies.middleware[policyName]) + '`)' ));
            }
          });
        } catch (e) {
          return cb(e);
        }

        // Set the _middlewareType property on each policy.
        _.each(self.middleware, function(policyFn, policyName) {
          policyFn._middlewareType = 'POLICY: '+policyName;
        });

        return cb();
      });
    },

    /**
     * Curry the policy chains into the appropriate controller functions
     *
     * @api private
     */
    bindPolicies: function() {

      // Build / normalize policy config
      this.mapping = this.buildPolicyMap();

      // Register action middleware for each item in the map
      _.each(this.mapping, function(policies, targets) {
        sails.registerActionMiddleware(policies, targets);
      });

      // Emit event to let other hooks know we're ready to go
      sails.log.silly('Policy-controller bindings complete!');
      sails.emit('hook:policies:bound');
    },

    /**
     * Build normalized, hook-internal representation of policy mapping
     * by performing a non-destructive parse of `sails.config.policies`
     *
     * @returns {Object} mapping
     * @api private
     */
    buildPolicyMap: function () {

      // Loop through the keys looking for the old-style "controller-based" policy config,
      // and if we find it then expand it out to the new style.
      _.each(_.without(_.keys(sails.config.policies), 'moduleDefinitions'), function(key) {

        // Is this a plain dictionary, e.g. UserController: { '*': true } ?
        if (_.isPlainObject(sails.config.policies[key])) {

          // Get the controller name by stripping off the (optional) trailing "Controller"
          var controller = key.replace(/Controller$/,'').toLowerCase();

          // For each item (i.e. action) in the dictionary, add an entry to the config.
          _.each(_.keys(sails.config.policies[key]), function(action) {

            // Get the policies to attach to this action.
            var policies = sails.config.policies[key][action];

            // Add the target/policies mapping to sails.config.policies
            sails.config.policies[controller + '/' + action.toLowerCase()] = policies;
          });

          // Remove the deprecated config key.
          delete sails.config.policies[key];

        }

        // Make sure all standalone action glob keys are lowercased.
        else if (key !== key.toLowerCase()) {

          sails.config.policies[key.toLowerCase()] = sails.config.policies[key];
          delete sails.config.policies[key];

        }

      });

      // Sort the policy keys alphabetically, ensuring that more restrictive
      // keys (e.g. user/foo) come after less restrictive (e.g. user/*).
      // Ignore `moduleDefinitions` since it is a special key used to allow
      // programmatic setting of policy functions.
      var actionsToProtect = _.without(_.keys(sails.config.policies), 'moduleDefinitions').sort();

      // Declare a "never allow" function to use when a policy of `false` is encountered.
      var neverAllow = function neverAllow (req, res) {
        return res.forbidden();
      };
      neverAllow._middlewareType = 'POLICY: false (neverAllow)';

      // Declare a "never allow" function to use when a policy of `false` is encountered.
      var alwaysAllow = function alwaysAllow (req, res, next) {
        return next();
      };
      alwaysAllow._middlewareType = 'POLICY: true (alwaysAllow)';

      // Loop through the keys and create the map.
      var mapping = _.reduce(actionsToProtect, function (memo, target, index) {

        // Allow bald `true` and `false` policies by wrapping them in an array.
        if (sails.config.policies[target] === true || sails.config.policies[target] === false) {
          sails.config.policies[target] = [sails.config.policies[target]];
        }

        // Make sure policies are contained in an array.
        if (!_.isArray(sails.config.policies[target])) {
          sails.config.policies[target] = [sails.config.policies[target]];
        }

        // Get the policies the user wants to add to this set of actions.
        // Note the use of _.compact to transform [undefined] into [].
        var policies = _.compact(_.map(sails.config.policies[target], function(policy) {
          // If the policy is `true`, make sure it's the only one for this target.
          if (policy === true) {
            if (sails.config.policies[target].length > 1) {
              throw flaverr({ name: 'userError', code: 'E_INVALID_POLICY_CONFIG' }, new Error('Invalid policy setting for `' + target + '`: if `true` is specified, it must be the only policy in the array.'));
            }
            // Map `true` to  the "always allow" policy.
            return alwaysAllow;
          }
          // If the policy is `false`, make sure it's the only one for this target.
          if (policy === false) {
            if (sails.config.policies[target].length > 1) {
              throw flaverr({ name: 'userError', code: 'E_INVALID_POLICY_CONFIG' }, new Error('Invalid policy setting for `' + target + '`: if `false` is specified, it must be the only policy in the array.'));
            }
            // Map `false` to  the "never allow" policy.
            return neverAllow;
          }
          // If the policy is a string, make sure it corresponds to one of the policies we loaded.
          if (_.isString(policy)) {
            if (!sails.hooks.policies.middleware[policy.toLowerCase()]) {
              throw flaverr({ name: 'userError', code: 'E_INVALID_POLICY_CONFIG' }, new Error('Invalid policy setting for `' + target + '`: `' + policy + '` does not correspond to any of the loaded policies.'));
            }
            return sails.hooks.policies.middleware[policy.toLowerCase()];
          }
          // If the policy is a function, return it.
          if (_.isFunction(policy)) {
            policy._middlewareType = 'POLICY: ' + (policy.name || 'anonymous');
            return policy;
          }
          // Otherwise just bail.
          throw flaverr({ name: 'userError', code: 'E_INVALID_POLICY_CONFIG' }, new Error('Invalid policy setting for `' + target + '`: a policy must be a string, a function or `false`.'));

        }));

        // Start an array of targets that this set of policies will be applied to or ignored for.
        var allowDenyList = [target];

        // If this is the global target, loop through the rest of the targets and exclude them
        // from this one.  We may change this behavior / make it optional in the future,
        // but for now policies are NOT cumulative.
        if (target === '*') {
          (function() {
            for (var i = index + 1; i < actionsToProtect.length; i++) {
              var nextTarget = actionsToProtect[i];
              allowDenyList.push('!' + nextTarget);
            }
          })();
        }

        // If this target is a wildcard, then any other target that matches it will
        // override it.  We may change this behavior / make it optional in the future,
        // but for now policies are NOT cumulative.
        else if (target.slice(-2) === '/*') {
          (function() {
            // Get a version of the target without the /*
            var nakedTarget = target.slice(0,-2);
            // Get a version of the target without the .
            var slashTarget = target.slice(0,-1);
            // If we already bound a policy to the naked target, then flag that the
            // current policy should _not_ be applied to it.
            if (memo[nakedTarget]) {
              allowDenyList.push('!' + nakedTarget);
            }
            // Now run through the rest of the targets in the list, and if any of them
            // start with the "slashTarget", make sure this policy does _not_ apply to them.
            // So if our target is `user/foo/*`, and we see `user/foo/bar` in the list,
            // we will add that to the blacklist for this policy.
            for (var i = index + 1; i < actionsToProtect.length; i++) {
              var nextTarget = actionsToProtect[i];
              if (nextTarget.indexOf(slashTarget) === 0) {
                allowDenyList.push('!' + nextTarget);
              }
              // As soon as we find a non-matching target, we're done (because they're
              // arranged in alphabetical order).
              else {
                break;
              }
            }
          })();
        }

        // Transform the allow/deny list into a comma-delimited string that can be
        // understood by `registerActionMiddleware`.
        memo[allowDenyList.join(',')] = policies;

        return memo;

      }, {});

      return mapping;
    },

  };

  /**
   * Bind `route:typeUnknown` event handler in order to support
   * the `policy: '...` route option.
   *
   * > This allows for manually mapping policies directly on top
   * > of explicit routes; e.g. in `config/routes.js`
   */
  sails.on('route:typeUnknown', function bindDirectlyToRoute (event) {

    // Only pay attention to delegated route events
    // if `policy` is declared in event.target
    if ( !event.target || !event.target.policy ) {
      return;
    }

    var policyId = event.target.policy.toLowerCase();

    // Policy doesn't exist
    if (!sails.hooks.policies.middleware[policyId] ) {
      var routeAddrToDisplay = event.verb ? event.verb+' '+event.path : event.path;
      Err.fatal.__UnknownPolicy__ (policyId, routeAddrToDisplay, sails.config.paths.policies);
      // ^^That begins terminating the process.
      return;
    }//-•

    // Bind policy function to route.
    // Make sure to merge the target and options together, so that route options like `skipRegex`
    // are still applied to requests before running the policy.
    var fn = sails.hooks.policies.middleware[policyId];
    sails.router.bind(event.path, fn, event.verb, _.merge(event.options, event.target));
  });

  return policyHookDef;
};


text:
Create, view, share and delete Google Sheets owned by your [Google Service Account](https://cloud.google.com/iam/docs/understanding-service-accounts) through this command-line tool

## The Problem
There is no UI to create spreadsheets (or any Drive documents) via your [Google Service Account](https://cloud.google.com/iam/docs/understanding-service-accounts) account. If you want to do this, you have to create them programmatically. In other words, you have to write a script... *or*... You can use **sheets-service**, i.e. the tool in this repo!

## The Solution
**sheets-service** is a command-line script that lets you create, view, share and delete Google Sheets owned by your Google Service Account.

## Why would I ever want this?
The [Google Sheets API](https://developers.google.com/sheets/api/reference/rest/) is a little silly. It is designed so that it is easy to do the following:
- User goes to your website
- User logs into your website using Google OAuth2
- User is now authenticated to update  a spreadsheet that the *user* owns

But it's pretty unusual that you'd want this behavior.

If you want your backend to interact with a spreadsheet, it's far more likely that you'd want your data to save to one single Google Sheets spreadsheet that *you* own, such as a sign-up form. In other words, you'd want something like this:
- User goes to your website
- User fills out form and submits it
- *Your* spreadsheet is populated with their submitted information

In order to do this, you have the following choices:
- **Option 1.** Use [sheetsu.com](http://sheetsu.com), which is easy-to-use but kind of [alarmingly expensive](https://sheetsu.com/pricing) *(Not a criticism! Kudos to the maker of Sheetsu; you get that money!)*
- **Option 2.** Create a [Google Service Account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount) (GSA), which is like a new, invisible user that's tied to your application, whose data you can maniuplate without requiring user login.

To elaborate on **Option 2**,
1. You would create your sign-up spreadsheet using your Google Service Account (GSA). Note that the spreadsheet will be owned by this invisible user, not by a "real" Gmail account.
2. Share the spreadsheet made by your GSA with your Gmail account (or with whatever account(s) you want to control your spreadsheet)
3. In your NodeJS server, use the Google Sheets API to read and write to this spreadsheet without needing to generate an OAuth2 token for your user.

Success, right?!

**EXCEPT:** See original problem statement. There's no UI for creating spreadsheets using your GSA account... that is, until now! Use the **sheets-service** script for a command-line interface to your GSA account's spreadsheets.

## Installation

1. Clone this repository
```
git clone https://github.com/vrk/sheets-service.git
```

2. Install dependencies
```
npm install
```

3. Create a Google Service Account
You can skip this if you have one already. Otherwise, go to the [Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts/serviceaccounts-zero) section of the Google Developer Console and follow the wizard to create your new Google Service Account. You may need to create a new project to associate with this account.

4. Download your private key JSON file
You should see your new Google Service Account in the [Service Accounts](https://console.cloud.google.com/iam-admin/serviceaccounts/serviceaccounts-zero) menu for your project. Under "Options" on the right side of the table, click the 3-dot menu for your GSA account, and click "Create key". Create your private key in JSON format.

5. Move your private key to `./lib/privateSettings.json`
The **sheets-service** script will look for your private key JSON file in `./lib/privateSettings.json`, so move your private key .json file to the `lib/` directory of your cloned repo, and rename it to `privateSettings.json`

Now you should be ready to use the script!

## Usage
Once you have finished installation, you can run the script via:
```
npm start
```

or

```
node sheets-service.js
```

From there, the tool should be pretty self-explanitory.

## Questions, bugs, etc?
[File an issue](https://github.com/vrk/sheets-service/issues) in the tracker.


text:
package com.codingchili.core.context;

import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.*;
import org.junit.runner.RunWith;

import com.codingchili.core.configuration.Environment;
import com.codingchili.core.configuration.exception.NoServicesConfiguredForBlock;
import com.codingchili.core.configuration.exception.RemoteBlockNotConfiguredException;

import static com.codingchili.core.configuration.CoreStrings.getNoServicesConfiguredForBlock;
import static com.codingchili.core.context.LaunchContextMock.*;

/**
 * Tests for the launcher context.
 */
@RunWith(VertxUnitRunner.class)
public class LaunchContextTest {
    private static LaunchContext context;

    @BeforeClass
    public static void setUp() {
        context = new LaunchContextMock(new String[]{});
    }

    @Test
    public void testGetBlock() throws CoreException {
        Assert.assertTrue(context.service(BLOCK_1).contains(SERVICE_1));
        Assert.assertTrue(context.service(BLOCK_2).contains(SERVICE_2));
    }

    @Test
    public void testGetHostBlock() throws CoreException {
        Assert.assertTrue(context.service(HOST_1).contains(SERVICE_1));
        Assert.assertTrue(context.service(HOST_2).contains(SERVICE_1));
    }

    @Test
    public void testGetMissingBlock() throws CoreException {
        try {
            Assert.assertTrue(context.service(BLOCK_NULL).isEmpty());
        } catch (NoServicesConfiguredForBlock e) {
            Assert.assertTrue(e.getMessage().contains(BLOCK_NULL));
        }
    }

    @Test
    public void testGetMissingHost() throws CoreException {
        try {
            context.service(HOST_3).contains(SERVICE_1);
        } catch (RemoteBlockNotConfiguredException e) {
            Assert.assertTrue(e.getMessage().contains(HOST_3));
            Assert.assertTrue(e.getMessage().contains(BLOCK_NULL));
        }
    }

    @Test
    public void testGetEmptyBlockThrows(TestContext test) throws CoreException {
        try {
            context.service(BLOCK_EMPTY);
            test.fail("Should throw exception when block is empty.");
        } catch (NoServicesConfiguredForBlock e) {
            test.assertEquals(getNoServicesConfiguredForBlock(BLOCK_EMPTY), e.getMessage());
        }
    }

    @Test
    public void testGetDefaultBlockWhenNoArgs(TestContext test) throws CoreException {
        try {
            context.services();
        } catch (NoServicesConfiguredForBlock e) {
            test.assertTrue(e.getMessage().contains(BLOCK_DEFAULT));
        }
    }

    @Test
    public void testGetRemoteBlockByHostname(TestContext test) throws CoreException {
        if (Environment.hostname().isPresent()) {
            test.assertTrue(context.service(Environment.hostname().get()).contains(SERVICE_2));
        }
    }

    @Test
    public void testGetRemoteBlockByIP(TestContext test) throws CoreException {
        if (Environment.addresses().size() > 0) {
            test.assertTrue(context.service(INTERFACE_ADDRESS).contains(SERVICE_2));
        }
    }
}