text:
package msgraph

import "context"

// RoomRequestBuilder is request builder for Room
type RoomRequestBuilder struct{ BaseRequestBuilder }

// Request returns RoomRequest
func (b *RoomRequestBuilder) Request() *RoomRequest {
	return &RoomRequest{
		BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},
	}
}

// RoomRequest is request for Room
type RoomRequest struct{ BaseRequest }

// Get performs GET request for Room
func (r *RoomRequest) Get(ctx context.Context) (resObj *Room, err error) {
	var query string
	if r.query != nil {
		query = "?" + r.query.Encode()
	}
	err = r.JSONRequest(ctx, "GET", query, nil, &resObj)
	return
}

// Update performs PATCH request for Room
func (r *RoomRequest) Update(ctx context.Context, reqObj *Room) error {
	return r.JSONRequest(ctx, "PATCH", "", reqObj, nil)
}

// Delete performs DELETE request for Room
func (r *RoomRequest) Delete(ctx context.Context) error {
	return r.JSONRequest(ctx, "DELETE", "", nil, nil)
}

// RoomListRequestBuilder is request builder for RoomList
type RoomListRequestBuilder struct{ BaseRequestBuilder }

// Request returns RoomListRequest
func (b *RoomListRequestBuilder) Request() *RoomListRequest {
	return &RoomListRequest{
		BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client},
	}
}

// RoomListRequest is request for RoomList
type RoomListRequest struct{ BaseRequest }

// Get performs GET request for RoomList
func (r *RoomListRequest) Get(ctx context.Context) (resObj *RoomList, err error) {
	var query string
	if r.query != nil {
		query = "?" + r.query.Encode()
	}
	err = r.JSONRequest(ctx, "GET", query, nil, &resObj)
	return
}

// Update performs PATCH request for RoomList
func (r *RoomListRequest) Update(ctx context.Context, reqObj *RoomList) error {
	return r.JSONRequest(ctx, "PATCH", "", reqObj, nil)
}

// Delete performs DELETE request for RoomList
func (r *RoomListRequest) Delete(ctx context.Context) error {
	return r.JSONRequest(ctx, "DELETE", "", nil, nil)
}


text:
class NilClass
  WHINERS = [::Array]
  WHINERS << ::ActiveRecord::Base if defined? ::ActiveRecord

  METHOD_CLASS_MAP = Hash.new

  WHINERS.each do |klass|
    methods = klass.public_instance_methods - public_instance_methods
    class_name = klass.name
    methods.each { |method| METHOD_CLASS_MAP[method.to_sym] = class_name }
  end

  # Raises a RuntimeError when you attempt to call +id+ on +nil+.
  def id
    raise RuntimeError, "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id", caller
  end

  private
    def method_missing(method, *args, &block)
      raise_nil_warning_for METHOD_CLASS_MAP[method], method, caller
    end

    # Raises a NoMethodError when you attempt to call a method on +nil+.
    def raise_nil_warning_for(class_name = nil, selector = nil, with_caller = nil)
      message = "You have a nil object when you didn't expect it!"
      message << "\nYou might have expected an instance of #{class_name}." if class_name
      message << "\nThe error occurred while evaluating nil.#{selector}" if selector

      raise NoMethodError, message, with_caller || caller
    end
end

redpajama_set_name: RedPajamaGithub


text:
var app = new PIXI.Application();
document.body.appendChild(app.view);

// create a texture from an image path
var texture = PIXI.Texture.fromImage('required/assets/p2.jpeg');

/* create a tiling sprite ...
 * requires a texture, a width and a height
 * in WebGL the image size should preferably be a power of two
 */
var tilingSprite = new PIXI.extras.TilingSprite(
    texture,
    app.renderer.width,
    app.renderer.height
);
app.stage.addChild(tilingSprite);

var count = 0;

app.ticker.add(function() {

    count += 0.005;

    tilingSprite.tileScale.x = 2 + Math.sin(count);
    tilingSprite.tileScale.y = 2 + Math.cos(count);

    tilingSprite.tilePosition.x += 1;
    tilingSprite.tilePosition.y += 1;
});


text:
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace AspNetCoreSpa.Web.SignalR
{
    public class ShapeHub : Hub
    {
        public async Task MoveShape(int x, int y)
        {
            await Clients.Others.SendAsync("shapeMoved", x, y);
        }
    }
}


text:
IntlCalendar::isEquivalentTo() basic test
--SKIPIF--
<?php
if (!extension_loaded('intl'))
	die('skip intl extension not enabled');
--FILE--
<?php
ini_set("intl.error_level", E_WARNING);
ini_set("intl.default_locale", "nl");

$intlcal1 = IntlCalendar::createInstance('Europe/Amsterdam');
$intlcal2 = IntlCalendar::createInstance('Europe/Lisbon');
$intlcal3 = IntlCalendar::createInstance('Europe/Amsterdam', "nl_NL@calendar=islamic");
$intlcal4 = IntlCalendar::createInstance('Europe/Amsterdam');
$intlcal4->roll(IntlCalendar::FIELD_MONTH, true);

var_dump(
		"1 - 1",
		$intlcal1->isEquivalentTo($intlcal1),
		"1 - 2",
		$intlcal1->isEquivalentTo($intlcal2),
		"1 - 3",
		$intlcal1->isEquivalentTo($intlcal3),
		"1 - 4",
		$intlcal1->isEquivalentTo($intlcal4)
);

?>
==DONE==
--EXPECT--
string(5) "1 - 1"
bool(true)
string(5) "1 - 2"
bool(false)
string(5) "1 - 3"
bool(false)
string(5) "1 - 4"
bool(true)
==DONE==


text:
`hello` is a program which serves a web server on port 8080.

The package installs
- the program bin and its assets
- a service unit file for systemd
- a desktop link to open the hello homepage
- and environment variable

# run it

```sh
rm -fr build && mkdir -p build/{386,amd64}
GOOS=linux GOARCH=386 go build -o build/386/hello hello.go
GOOS=linux GOARCH=amd64 go build -o build/amd64/hello hello.go
vagrant up
vagrant ssh -c 'sudo apt-get install build-essential lintian -y'
vagrant ssh -c 'wget -q -O - --no-check-certificate https://raw.githubusercontent.com/mh-cbon/go-bin-deb/master/install.sh | sh'
vagrant ssh -c 'cd /vagrant/ && VERBOSE=* go-bin-deb generate -a 386 --version 0.0.1 -w pkg-build/386/ -o hello-386.deb'
vagrant ssh -c 'cd /vagrant/ && VERBOSE=* go-bin-deb generate -a amd64 --version 0.0.1 -w pkg-build/amd64/ -o hello-amd64.deb'
vagrant ssh -c 'cd /vagrant/ && dpkg-deb --show hello-amd64.deb'
vagrant ssh -c 'cd /vagrant/ && dpkg-deb --contents hello-amd64.deb'
vagrant ssh -c "sudo dpkg -r hello"
vagrant ssh -c "cd /vagrant/ && sudo dpkg -i hello-amd64.deb"
vagrant ssh -c "echo \$some"
vagrant ssh -c "hello -h"
vagrant ssh -c "systemctl status hello"
vagrant ssh -c "wget -q -O - http://localhost:8080/"
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KompetansetorgetXamarin.Models;
using XLabs.Forms;
using Xamarin.Forms;
using System.Collections.ObjectModel;
using KompetansetorgetXamarin.Controls;
using System.Windows.Input;
using KompetansetorgetXamarin.Controllers;
using Xamarin.Forms.Xaml;
using System.Collections.Specialized;
using KompetansetorgetXamarin.DAL;

namespace KompetansetorgetXamarin.Views
{
    public partial class CarouselOppgaver : BaseCarouselPage
    {
        VMOppgaverSettings listInit = new VMOppgaverSettings();
        //ObservableCollection<Oppgave> oppgaver = new ObservableCollection<Oppgave>();
        public ObservableCollection<Project> oppgaver = new ObservableCollection<Project>();
        /*Dictionary<string, string> filter = new Dictionary<string, string>();*/ //used in AddData;
        ICommand refreshCommand;
        string p0title = "Oppgaveforslag";
        string p1title = "Velg fagområder";
        //static public bool pullList = true;
        //string p2title = "Velg fagområder";
        //string p3title = "Velg emne";
        private bool sortDesc;

        public CarouselOppgaver()
        {
            InitializeComponent();
            sortDesc = true;
            this.Title = p0title;

            OppgaveList.SetCarouselOppgaver(this);
            OppgaveList.RefreshCommand = RefreshCommand;
            OppgaveList.IsPullToRefreshEnabled = true;

            søk.TextChanged += (sender, e) => OppgaveList.FilterOppgaver(søk.Text);
            søk.SearchButtonPressed += (sender, e) =>
            {
                OppgaveList.FilterOppgaver(søk.Text);
            };
            InitializeSelectItemEventListener();

            UpdateItemSource();
        }

        void InitializeSelectItemEventListener()
        {
            OppgaveList.ItemSelected += (sender, e) =>
            {
                Project d = (Project)e.SelectedItem;
                //var action = DisplayAlert(d.Text, d.JobTitle, "Slett varsel", "Se annonse");
                OpenAdvert(d);
            };
        }

        private async Task OpenAdvert(Project oppgave)
        {
            OppgaveList.SelectedItem = null;
            var url = oppgave.webpage;
            var type = "project";
            var WebPage = new WebPage(type, url);
            await Navigation.PushAsync(WebPage);  //opens new webpage in browser to given url
        }

        private async Task UpdateItemSource()
        {
            OppgaveList.IsRefreshing = true;
            oppgaverSettings.ItemsSource = listInit.oppgaveSettings;
            await AddData();
            OppgaveList.ItemsSource = oppgaver;   // oppgave.companies[0].name  .logo
            OppgaveList.IsRefreshing = false;
            //OppgaverEmner.ItemsSource = listInit.coursesSettings;

        }

        public ObservableCollection<Project> GetProjects()
        {
            return oppgaver;
        }

        void Sorter_OnTapped(object sender, EventArgs e)
        {
            sortDesc = !sortDesc;
            Sort();
        }

        void Sort()
        {
            if (sortDesc)
            {
                OppgaveList.ItemsSource = oppgaver
                    .OrderByDescending(x => x.published);
            }
            else
            {
                OppgaveList.ItemsSource = oppgaver
                    .OrderBy(x => x.published);
            }
            //UpdateItemSource();
            OppgaveList.IsRefreshing = false;
        }

        void SaveSettings(object sender, EventArgs e)
        {
            listInit.SaveSettings();
            this.DisplayAlert("Innstillinger lagret!", "Oppdatér for å få inn nye oppgaver.", "OK");
        }

        //void VelgEmneButton_OnTapped(object sender, EventArgs e)
        //{
        //    this.CurrentPage = this.Children[3];
        //}

        //void VelgFagområdeButton_OnTapped(object sender, EventArgs e)
        //{
        //        this.CurrentPage = this.Children[2];
        //}

        void SwipeRight(object sender, EventArgs e)
        {
            ToolbarItem tbi = (ToolbarItem)sender;
            Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
            {
                if (CurrentPage == this.Children[0])
                {
                    this.CurrentPage = this.Children[1];
                }
                else if (CurrentPage == this.Children[1])
                {
                    this.CurrentPage = this.Children[2];
                }
                else if (CurrentPage == this.Children[2])
                {
                    this.CurrentPage = this.Children[3];
                }
            });
        }

        void SwipeLeft(object sender, EventArgs e)
        {
            ToolbarItem tbi = (ToolbarItem)sender;
            Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
            {
                //if (CurrentPage == this.Children[3])
                //{
                //    this.CurrentPage = this.Children[2];
                //}
                //else if (CurrentPage == this.Children[2])
                //{
                //    this.CurrentPage = this.Children[1];
                //}
                //else
                if (CurrentPage == this.Children[1])
                {
                    this.CurrentPage = this.Children[0];
                }
            });
        }

        /// <summary>
        /// Handles refresh behaviour on button click
        /// </summary>
        void Refresh_OnTapped(object sender, EventArgs e)
        {
           ExcecuteRefreshCommand();
        }

        private ICommand RefreshCommand
        {
            get
            {
                System.Diagnostics.Debug.WriteLine("CarouselOppgaver - RefreshCommand - before refreshCommand ??");
                return refreshCommand ?? (refreshCommand = new Command(async () => await ExcecuteRefreshCommand()));
            }
        }
        /// <summary>
        /// Custom refresh to pull new data from server. If pullList is false(set in SearchListView.cs), it won't download a new list but will instead just do a regular unmodified refresh.
        /// </summary>
        async Task ExcecuteRefreshCommand()
        {
            OppgaveList.IsRefreshing = true;
            await AddData();
            Sort();
            OppgaveList.IsRefreshing = false;
        }

        //Alters title on carouselpage by contentpage
        public new event EventHandler CurrentPageChanged;
        protected override void OnCurrentPageChanged()
        {
            int prevPage = 0;
            EventHandler changed = CurrentPageChanged;
            if (changed != null)
                changed(this, EventArgs.Empty);
            if (CurrentPage == this.Children[0])
            {
                this.Title = p0title;
                listInit.SaveSettings();  //saves settings when going to p0
                ExcecuteRefreshCommand();
            }
            else if (CurrentPage == this.Children[1])
            {
                this.Title = p1title;
            }
            //add in case of more pages
            //else if (CurrentPage == this.Children[2]) {
            //    this.Title = p2title;
            //} else if (CurrentPage == this.Children[3]) {
            //    this.Title = p3title;
            //}
        }

        protected override void OnDisappearing()
        {
            listInit.SaveSettings(); //saves the settings when pressing the up button/leaving the page
        }

        //protected override bool OnBackButtonPressed() //behaviour of HARDWARE back button, not the up button.
        //{
        //    listInit.SaveSettings();
        //    if (CurrentPage.SendBackButtonPressed()) return true;
        //    return true;
        //}

        public void OnMore(object sender, EventArgs e)
        {
            var mi = ((MenuItem)sender);
            DisplayAlert("More Context Action", mi.CommandParameter + " more context action", "OK");
        }

        public void OnDelete(object sender, EventArgs e)
        {
            var mi = ((MenuItem)sender);
            DisplayAlert("Delete Context Action", mi.CommandParameter + " delete context action", "OK");
        }

        public void getFilter()
        { }

        //public Dictionary<string, string> GetCourse()
        //{
        //    foreach (Course course in listInit.coursesSettings)
        //    {
        //        object itemname = OppgaverEmner.SelectedItem;
        //        string i = itemname.ToString();

        //        if (course.name == i) {
        //            listInit.coursesFilter.Add("courses", course.id);
        //            System.Diagnostics.Debug.WriteLine("ITEMNAME TOSTRING DOES NOT WORK::::: " + i);
        //        }
        //        else
        //        {
        //            System.Diagnostics.Debug.WriteLine("ITEMNAME TOSTRING PRODUCES STRING::::: " + i);
        //        }

        //    }
        //    return listInit.coursesFilter;
        //}

        //void OnSelection(object sender, SelectedItemChangedEventArgs e)
        //{
        //    if (e.SelectedItem == null)
        //    {
        //        return; //ItemSelected is called on deselection, which results in SelectedItem being set to null
        //    }
        //    DisplayAlert("Item Selected", e.SelectedItem.ToString(), "Ok");
        //    //((ListView)sender).SelectedItem = null; //uncomment line if you want to disable the visual selection state.
        //}

        private async Task AddData()
        {
            //Dictionary<string, string> filter = new Dictionary<string, string>(); //contains only one item from each group
            //filter.Add("courses", "DAT-304");
            //filter.Add("types", "virksomhet");

            //if (pullList == false)
            //{
            //}
            //else if (pullList == true)
            //{
            ProjectsController jc = new ProjectsController();

            IEnumerable<Project> projects = await jc.GetProjectsBasedOnFilter(listInit.GetSettings(), null);
            HashSet<Project> newProjects = new HashSet<Project>(projects);
            HashSet<Project> oldProjects = new HashSet<Project>(oppgaver);
            bool sameProjects = newProjects.SetEquals(oldProjects);

            if (!sameProjects)
            {
                //OppgaveList.ItemsSource = null;
                oppgaver.Clear();
                foreach (Project project in projects)
                {
                    System.Diagnostics.Debug.WriteLine("project.title: " + project.title);
                    oppgaver.Add(project);
                }
                //OppgaveList.ItemsSource = oppgaver;
            }
            if (!Authenticater.Authorized)
            {
                GoToLogin();
            }
        }
    }
}

//TapGestureRecognizer tapGestureRecognizer = new TapGestureRecognizer();

//private static void OnOppgaveSelected(object o, ItemTappedEventArgs e)
//{
//if itemclicked.contains title X,
//var DBoppgave = database.findOppgaveWhereTitleIs(X)
//navigation.oppgavepage(passing data DBoppgave.text, DBoppgave.imageURL)
//goto StillingPage, insert text and imageURL

//}

//oppgaver.Add(new Oppgave("Universitetet i Agder","Lag en app for kompetansetorget!", defaultLogo));
//            oppgaver.Add(new Oppgave("Universitetet i Agder", "Hjelp oss med å lage en kalenderfunksjon for UiAs studenter", defaultLogo));

//private async void GetAllProjectsFromWebApi_OnClicked(object sender, EventArgs e)
//{
//    ProjectsController jc = new ProjectsController();
//    IEnumerable<Project> projects = await jc.GetProjectsBasedOnFilter();
//    if (!Authenticater.Authorized)
//    {
//        GoToLogin();
//    }
//    if (projects != null)
//    {
//        System.Diagnostics.Debug.WriteLine("GetJobsBasedOnFilter: jobs.Count(): " +
//                                           projects.Count());
//    }
//}


text:
<?php
class Kwf_Assets_Sass_WithComponentScssCompile_Component1_Component extends Kwc_Abstract
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        return $ret;
    }
}


text:
interface FeedTimeline {
  module_name: 'feed_timeline' | 'feed_contextual_post' | 'newsfeed' | 'feed_contextual_newsfeed_multi_media_liked';
}

interface FeedContextualHashtag {
  module_name: 'feed_contextual_hashtag';
  hashtag: string;
}

interface FeedContextualLocation {
  module_name: 'feed_contextual_location';
  location_id: string | number;
}

interface BaseProfile {
  username: string;
  user_id: string | number;
}

interface Profile extends BaseProfile {
  module_name: 'profile';
}

interface MediaViewProfile extends BaseProfile {
  module_name: 'media_view_profile';
}

interface VideoViewProfile extends BaseProfile {
  module_name: 'video_view_profile';
}

interface PhotoViewProfile extends BaseProfile {
  module_name: 'photo_view_profile';
}

export type LikeModuleInfoOption = (
  | FeedTimeline
  | FeedContextualHashtag
  | FeedContextualLocation
  | Profile
  | MediaViewProfile
  | VideoViewProfile
  | PhotoViewProfile
) & { [x: string]: any };

type LikeOrUnlikeBaseOptions = {
  mediaId: string;
  moduleInfo: LikeModuleInfoOption;
};

export type LikeRequestOptions = LikeOrUnlikeBaseOptions & {
  d: 1 | 0;
};

export type UnlikeRequestOptions = LikeOrUnlikeBaseOptions & {
  d?: 0;
};

export type MediaLikeOrUnlikeOptions = LikeOrUnlikeBaseOptions & {
  action: 'like' | 'unlike';
  // d - means double-tap. If you liked post by double tap then d=1. You cant unlike post by double tap
  d?: 1 | 0;
};


text:
#include "error.h"
#include <stdio.h>

#include <fiber.h>
struct rmean *rmean_error = NULL;

const char *rmean_error_strings[RMEAN_ERROR_LAST] = {
	"ERROR"
};

static struct method clienterror_methods[] = {
	make_method(&type_ClientError, "code", &ClientError::errcode),
	METHODS_SENTINEL
};
const struct type type_ClientError = make_type("ClientError", &type_Exception,
	clienterror_methods);

ClientError::ClientError(const char *file, unsigned line,
			 uint32_t errcode, ...)
	: Exception(&type_ClientError, file, line)
{
	m_errcode = errcode;
	va_list ap;
	va_start(ap, errcode);
	vsnprintf(m_errmsg, sizeof(m_errmsg),
		  tnt_errcode_desc(m_errcode), ap);
	if (rmean_error)
		rmean_collect(rmean_error, RMEAN_ERROR, 1);
	va_end(ap);
}

ClientError::ClientError(const char *file, unsigned line, const char *msg,
			 uint32_t errcode)
	: Exception(&type_ClientError, file, line)
{
	m_errcode = errcode;
	strncpy(m_errmsg, msg, sizeof(m_errmsg) - 1);
	m_errmsg[sizeof(m_errmsg) - 1] = 0;
	if (rmean_error)
		rmean_collect(rmean_error, RMEAN_ERROR, 1);
}

void
ClientError::log() const
{
	_say(S_ERROR, m_file, m_line, m_errmsg, "%s", tnt_errcode_str(m_errcode));
}

uint32_t
ClientError::get_errcode(const Exception *e)
{
	ClientError *client_error = type_cast(ClientError, e);
	if (client_error)
		return client_error->errcode();
	if (type_cast(OutOfMemory, e))
		return ER_MEMORY_ISSUE;
	return ER_PROC_LUA;
}

ErrorInjection::ErrorInjection(const char *file, unsigned line, const char *msg)
	: LoggedError(file, line, ER_INJECTION, msg)
{
	/* nothing */
}

const char *
box_error_type(const box_error_t *error)
{
	Exception *e = (Exception *) error;
	return e->type->name;
}

uint32_t
box_error_code(const box_error_t *error)
{
	Exception *e = (Exception *) error;
	return ClientError::get_errcode(e);
}

const char *
box_error_message(const box_error_t *error)
{
	Exception *e = (Exception *) error;
	return e->errmsg();
}

const box_error_t *
box_error_last(void)
{
	return (box_error_t *) diag_last_error(&fiber()->diag);
}

void
box_error_clear(void)
{
	diag_clear(&fiber()->diag);
}

int
box_error_raise(uint32_t code, const char *fmt, ...)
{
	char msg[EXCEPTION_ERRMSG_MAX];

	va_list ap;
	va_start(ap, fmt);
	vsnprintf(msg, sizeof(msg), fmt, ap);
	va_end(ap);

	tnt_error(ClientError, msg, code);
	return -1;
}


text:
module Jekyll
  module Drops
    class StaticFileDrop < Drop
      extend Forwardable
      delegate_methods   :name, :extname, :modified_time, :basename
      delegate_method_as :relative_path, :path
      delegate_method_as :type, :collection

      private delegate_method_as :data, :fallback_data
    end
  end
end


text:
/**
 * system_layer2_multithreaded_callback.cpp
 *
 * Multithreaded System implementation
 */
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <stdarg.h>
#include <string.h>
#include <syslog.h>
#include <signal.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/mman.h>
#include <sys/timerfd.h>
#include <sys/user.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <netpacket/packet.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/ethernet.h>
#include <sys/un.h>
#include <sys/eventfd.h>

#include <vector>

#include "net_interface_imp.h"
#include "enumeration.h"
#include "notification_imp.h"
#include "log_imp.h"
#include "end_station_imp.h"
#include "controller_imp.h"
#include "system_message_queue.h"
#include "system_tx_queue.h"
#include "system_layer2_multithreaded_callback.h"

namespace avdecc_lib
{

    net_interface_imp *netif_obj_in_system;
    controller_imp *controller_ref_in_system;
    system_layer2_multithreaded_callback *local_system = NULL;

    system_layer2_multithreaded_callback *system_layer2_multithreaded_callback::instance = NULL;

    size_t system_queue_tx(void *notification_id, uint32_t notification_flag, uint8_t *frame, size_t mem_buf_len)
    {
        if (local_system)
        {
            return local_system->queue_tx_frame(notification_id, notification_flag, frame, mem_buf_len);
        }
        else
        {
            return 0;
        }
    }

    system * STDCALL create_system(system::system_type type, net_interface *netif, controller *controller_obj)
    {
        local_system = new system_layer2_multithreaded_callback(netif, controller_obj);

        return local_system;
    }

    system_layer2_multithreaded_callback::system_layer2_multithreaded_callback(net_interface *netif, controller *controller_obj)
    {
        instance = this;
        netif_obj_in_system = dynamic_cast<net_interface_imp *>(netif);
        controller_ref_in_system = dynamic_cast<controller_imp *>(controller_obj);
        pipe(tx_pipe);

        wait_mgr = new cmd_wait_mgr();

        waiting_sem = (sem_t *)calloc(1, sizeof(*waiting_sem));
        if (waiting_sem)
            sem_init(waiting_sem, 0, 0);

        shutdown_sem = (sem_t *)calloc(1, sizeof(*shutdown_sem));
        if (shutdown_sem)
            sem_init(shutdown_sem, 0, 0);
    }

    system_layer2_multithreaded_callback::~system_layer2_multithreaded_callback()
    {
        free(waiting_sem);
        free(shutdown_sem);
    }

    void STDCALL system_layer2_multithreaded_callback::destroy()
    {
        if (this == local_system)
        {
            local_system = NULL;

            // Wait for controller to have finished
            if (sem_wait(shutdown_sem) != 0)
            {
                perror("sem_wait");
            }
        }

        delete this;
    }

    int system_layer2_multithreaded_callback::queue_tx_frame(
        void *notification_id,
        uint32_t notification_flag,
        uint8_t *frame,
        size_t mem_buf_len)
    {
        struct tx_data t;

        t.frame = new uint8_t[2048];
        if (!t.frame)
        {
            perror("malloc");
            exit(EXIT_FAILURE);

        }
        t.mem_buf_len = mem_buf_len;
        memcpy(t.frame, frame, mem_buf_len);
        t.notification_id = notification_id;
        t.notification_flag = notification_flag;
        write(tx_pipe[PIPE_WR], &t, sizeof(t));

        /**
         * Check for conditions that cause wait for completion.
         */
        if ( wait_mgr->primed_state() &&
             wait_mgr->match_id(notification_id) &&
             (notification_flag == CMD_WITH_NOTIFICATION))
        {
            int status = 0;

            status = wait_mgr->set_active_state();
            assert(status == 0);
            sem_wait(waiting_sem);
            resp_status_for_cmd = wait_mgr->get_completion_status();
            status = wait_mgr->set_idle_state();
            assert(status == 0);
        }

        return 0;
    }

    int STDCALL system_layer2_multithreaded_callback::set_wait_for_next_cmd(void * id)
    {
        wait_mgr->set_primed_state(id);
        return 0;
    }

    int STDCALL system_layer2_multithreaded_callback::get_last_resp_status()
    {
        return resp_status_for_cmd;
    }

    int system_layer2_multithreaded_callback::timer_start_interval(int timerfd)
    {
        struct itimerspec itimer_new;
        struct itimerspec itimer_old;
        unsigned long ns_per_ms = 1000000;
        unsigned long interval_ms = TIME_PERIOD_25_MILLISECONDS;

        memset(&itimer_new, 0, sizeof(itimer_new));
        memset(&itimer_old, 0, sizeof(itimer_old));

        itimer_new.it_interval.tv_sec = interval_ms / 1000;
        itimer_new.it_interval.tv_nsec = (interval_ms % 1000) * ns_per_ms;
        itimer_new.it_value = itimer_new.it_interval;

        return timerfd_settime(timerfd, 0, &itimer_new, &itimer_old);
    }

    int system_layer2_multithreaded_callback::fn_timer_cb(struct epoll_priv *priv)
    {
        return instance->fn_timer(priv);
    }
    int system_layer2_multithreaded_callback::fn_netif_cb(struct epoll_priv *priv)
    {
        return instance->fn_netif(priv);
    }
    int system_layer2_multithreaded_callback::fn_tx_cb(struct epoll_priv *priv)
    {
        return instance->fn_tx(priv);
    }

    int system_layer2_multithreaded_callback::fn_timer(struct epoll_priv *priv)
    {
        uint64_t timer_exp_count;
        read(priv->fd, &timer_exp_count, sizeof(timer_exp_count));

        bool notification_id_incomplete = false;

        if (wait_mgr->active_state())
        {
            if (controller_ref_in_system->is_inflight_cmd_with_notification_id(wait_mgr->get_notify_id()) ||
                controller_ref_in_system->is_active_operation_with_notification_id(wait_mgr->get_notify_id()))
                notification_id_incomplete = true;
        }

        // If waiting on a command to complete and the command was "inflight" prior to calling the
        // timer tick update (ie notification_id_incomplete == true) AND after calling the timer tick
        // update the command is no longer "inflight", timeout processing has removed it, so signal the
        // waiting app thread.
        controller_ref_in_system->time_tick_event();

        bool is_timeout_for_waiting_notify_id = wait_mgr->active_state() && notification_id_incomplete &&
                                                !controller_ref_in_system->is_inflight_cmd_with_notification_id(wait_mgr->get_notify_id()) &&
                                                !controller_ref_in_system->is_active_operation_with_notification_id(wait_mgr->get_notify_id());
        if (is_timeout_for_waiting_notify_id)
        {
            int status = wait_mgr->set_completion_status(AVDECC_LIB_STATUS_TICK_TIMEOUT);
            assert(status == 0);
            sem_post(waiting_sem);
        }

        return 0;
    }

    int system_layer2_multithreaded_callback::fn_tx(struct epoll_priv *priv)
    {
        struct tx_data t;
        int result = read(tx_pipe[PIPE_RD], &t, sizeof(t));

        if (result > 0)
        {
            log_imp_ref->post_log_msg(LOGGING_LEVEL_DEBUG, "fn_tx");
            controller_ref_in_system->tx_packet_event(
                t.notification_id,
                t.notification_flag,
                t.frame,
                t.mem_buf_len);

            delete[] t.frame;
        }

        return 0;
    }

    int system_layer2_multithreaded_callback::fn_netif(struct epoll_priv *priv)
    {
        uint16_t length = 0;
        const uint8_t *rx_frame;
        int status = 0;

        status = netif_obj_in_system->capture_frame(&rx_frame, &length);

        if (status > 0)
        {
            bool is_notification_id_valid = false;
            int rx_status = -1;
            void *notification_id = NULL;
            uint16_t operation_id = 0;
            bool is_operation_id_valid = false;

            controller_ref_in_system->rx_packet_event(notification_id,
                    is_notification_id_valid,
                    rx_frame,
                    length,
                    rx_status,
                    operation_id,
                    is_operation_id_valid);

            if (
                wait_mgr->active_state() &&
                is_notification_id_valid &&
                wait_mgr->match_id(notification_id) &&
                !controller_ref_in_system->is_inflight_cmd_with_notification_id(wait_mgr->get_notify_id()) &&
                !controller_ref_in_system->is_active_operation_with_notification_id(wait_mgr->get_notify_id())
            )
            {
                int status = wait_mgr->set_completion_status(rx_status);
                assert(status == 0);
                sem_post(waiting_sem);
            }
        }
        return 0;
    }

    int system_layer2_multithreaded_callback::prep_evt_desc(
        int fd,
        handler_fn fn,
        struct epoll_priv *priv,
        struct epoll_event *ev)
    {
        priv->fd = fd;
        priv->fn = fn;
        ev->events = EPOLLIN;
        ev->data.ptr = priv;
        return 0;
    }

    int system_layer2_multithreaded_callback::proc_poll_loop()
    {

        int epollfd;
        struct epoll_event ev, epoll_evt[POLL_COUNT];
        struct epoll_priv fd_fns[POLL_COUNT];

        epollfd = epoll_create(POLL_COUNT);

        prep_evt_desc(timerfd_create(CLOCK_MONOTONIC, 0), &system_layer2_multithreaded_callback::fn_timer_cb, &fd_fns[0],  &ev);
        epoll_ctl(epollfd, EPOLL_CTL_ADD, fd_fns[0].fd, &ev);

        prep_evt_desc(netif_obj_in_system->get_fd(), &system_layer2_multithreaded_callback::fn_netif_cb, &fd_fns[1], &ev);
        epoll_ctl(epollfd, EPOLL_CTL_ADD, fd_fns[1].fd, &ev);

        prep_evt_desc(tx_pipe[PIPE_RD], &system_layer2_multithreaded_callback::fn_tx_cb, &fd_fns[2],
                      &ev);
        epoll_ctl(epollfd, EPOLL_CTL_ADD, fd_fns[2].fd, &ev);

        fcntl(fd_fns[0].fd, F_SETFL, O_NONBLOCK);
        timer_start_interval(fd_fns[0].fd);

        do
        {
            int i, res;
            struct epoll_priv *priv;
            res = epoll_wait(epollfd, epoll_evt, POLL_COUNT, -1);

            if (local_system == NULL)
            {
                // System has been shut down
                sem_post(shutdown_sem);
                return 0;
            }

            /* exit on error */
            if (-1 == res)
                return -errno;

            for (i = 0; i < res; i++)
            {
                priv = (struct epoll_priv *)epoll_evt[i].data.ptr;
                if (priv->fn(priv) < 0)
                    return -1;
            }
        }
        while (1);
        return 0;
    }

    void * system_layer2_multithreaded_callback::thread_fn(void *param)
    {
        ((system_layer2_multithreaded_callback *)param)->proc_poll_loop();

        return 0;
    }

    int STDCALL system_layer2_multithreaded_callback::process_start()
    {
        int rc;

        rc = pthread_create(&h_thread, NULL, &system_layer2_multithreaded_callback::thread_fn, (void *)this);
        if (rc)
        {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
        return 0;
    }

    int STDCALL system_layer2_multithreaded_callback::process_close()
    {

        return 0;
    }
}


text:
package transformer

import (
	"time"

	"github.com/cloudevents/sdk-go/v2/binding"
	"github.com/cloudevents/sdk-go/v2/binding/spec"
	"github.com/cloudevents/sdk-go/v2/types"
)

var (
	// Add the cloudevents time attribute, if missing, to time.Now()
	AddTimeNow binding.Transformer = addTimeNow{}
)

type addTimeNow struct{}

func (a addTimeNow) Transform(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error {
	attr, ti := reader.GetAttribute(spec.Time)
	if ti == nil {
		return writer.SetAttribute(attr, types.Timestamp{Time: time.Now()})
	}
	return nil
}


text:
package org.zstack.test.storage.primary;

import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.cluster.ClusterInventory;
import org.zstack.header.host.HostInventory;
import org.zstack.header.message.MessageReply;
import org.zstack.header.simulator.storage.primary.SimulatorPrimaryStorageDetails;
import org.zstack.header.storage.primary.AllocatePrimaryStorageMsg;
import org.zstack.header.storage.primary.PrimaryStorageConstant;
import org.zstack.header.storage.primary.PrimaryStorageInventory;
import org.zstack.header.zone.ZoneInventory;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.BeanConstructor;
import org.zstack.test.DBUtil;
import org.zstack.utils.Utils;
import org.zstack.utils.data.SizeUnit;
import org.zstack.utils.logging.CLogger;
public class TestDefaultPrimaryStorageAllocatorStrategyFailure1 {
    CLogger logger = Utils.getLogger(TestDefaultPrimaryStorageAllocatorStrategyFailure1.class);
    Api api;
    ComponentLoader loader;
    DatabaseFacade dbf;
    CloudBus bus;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        BeanConstructor con = new BeanConstructor();
        /* This loads spring application context */
        loader = con.addXml("PortalForUnitTest.xml").addXml("Simulator.xml")
                .addXml("PrimaryStorageManager.xml").addXml("ZoneManager.xml")
                .addXml("ClusterManager.xml").addXml("HostManager.xml").addXml("ConfigurationManager.xml").addXml("AccountManager.xml").build();
        dbf = loader.getComponent(DatabaseFacade.class);
        bus = loader.getComponent(CloudBus.class);
        api = new Api();
        api.startServer();
    }

    @After
    public void tearDown() throws Exception {
        api.stopServer();
    }

    @Test
    public void test() throws ApiSenderException {
        ZoneInventory zone = api.createZones(1).get(0);
        long requiredSize = SizeUnit.GIGABYTE.toByte(10);
        SimulatorPrimaryStorageDetails sp = new SimulatorPrimaryStorageDetails();
        sp.setTotalCapacity(SizeUnit.TERABYTE.toByte(10));
        sp.setAvailableCapacity(sp.getTotalCapacity());
        sp.setUrl("nfs://simulator/primary/");
        sp.setZoneUuid(zone.getUuid());
        PrimaryStorageInventory pinv = api.createSimulatoPrimaryStorage(1, sp).get(0);
        ClusterInventory cluster = api.createClusters(1, zone.getUuid()).get(0);
        HostInventory host = api.createHost(1, cluster.getUuid()).get(0);
        /* primary storage is not attached */

        AllocatePrimaryStorageMsg msg = new AllocatePrimaryStorageMsg();
        msg.setRequiredHostUuid(host.getUuid());
        msg.setSize(requiredSize);
        msg.setServiceId(bus.makeLocalServiceId(PrimaryStorageConstant.SERVICE_ID));
        MessageReply reply = bus.call(msg);
        Assert.assertFalse(reply.isSuccess());
    }
}


text:
package com.github.plusvic.yara.external;

import org.junit.Test;

import java.util.UUID;

import static org.junit.Assert.*;

/**
 * User: pba
 * Date: 6/13/15
 * Time: 8:55 AM
 */
public class NativeExecutableTest {
    @Test(expected = IllegalArgumentException.class)
    public void testCreateNoName() {
        new NativeExecutable("");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testCreateNullName() {
        new NativeExecutable(null, NativeExecutableTest.class.getClassLoader());
    }

    @Test
    public void testCreate() {
        new NativeExecutable("yara");
    }

    @Test
    public void testLoadNotFound() {
        NativeExecutable exe = new NativeExecutable(UUID.randomUUID().toString());
        assertFalse(exe.load());
    }

    @Test
    public void testLoadYara() {
        NativeExecutable exe = new NativeExecutable("yara");
        assertTrue(exe.load());
    }

    @Test
    public void testLoadYarac() {
        NativeExecutable exe = new NativeExecutable("yarac");
        assertTrue(exe.load());
    }
}


text:
"""
byceps.services.attendance.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from __future__ import annotations
from collections import defaultdict
from typing import Iterable, Optional

from sqlalchemy import select

from ...database import db, paginate, Pagination
from ...typing import PartyID, UserID

from ..seating.dbmodels.seat import Seat as DbSeat
from ..ticketing.dbmodels.ticket import (
    Category as DbCategory,
    Ticket as DbTicket,
)
from ..user.dbmodels.user import User as DbUser
from ..user_avatar.dbmodels import AvatarSelection as DbAvatarSelection

from .transfer.models import Attendee, AttendeeTicket

def get_attendees_paginated(
    party_id: PartyID,
    page: int,
    per_page: int,
    *,
    search_term: Optional[str] = None,
) -> Pagination:
    """Return the party's ticket users with tickets and seats."""
    users_paginated = _get_users_paginated(
        party_id, page, per_page, search_term=search_term
    )
    users = users_paginated.items
    user_ids = {u.id for u in users}

    tickets = _get_tickets_for_users(party_id, user_ids)
    tickets_by_user_id = _index_tickets_by_user_id(tickets)

    attendees = list(_generate_attendees(users, tickets_by_user_id))

    users_paginated.items = attendees
    return users_paginated

def _get_users_paginated(
    party_id: PartyID,
    page: int,
    per_page: int,
    *,
    search_term: Optional[str] = None,
) -> Pagination:
    # Drop revoked tickets here already to avoid users without tickets
    # being included in the list.

    items_query = select(
        DbUser,
        db.func.lower(DbUser.screen_name).label('screen_name_lower')
    ) \
        .distinct() \
        .options(
            db.load_only(DbUser.id, DbUser.screen_name, DbUser.deleted),
            db.joinedload(DbUser.avatar_selection)
                .joinedload(DbAvatarSelection.avatar),
        ) \
        .join(DbTicket, DbTicket.used_by_id == DbUser.id) \
        .filter(DbTicket.revoked == False) \
        .join(DbCategory).filter(DbCategory.party_id == party_id) \
        .order_by('screen_name_lower')

    count_query = select(db.func.count(db.distinct(DbUser.id))) \
        .join(DbTicket, DbTicket.used_by_id == DbUser.id) \
        .filter(DbTicket.revoked == False) \
        .join(DbCategory).filter(DbCategory.party_id == party_id)

    if search_term:
        items_query = items_query \
            .filter(DbUser.screen_name.ilike(f'%{search_term}%'))
        count_query = count_query \
            .filter(DbUser.screen_name.ilike(f'%{search_term}%'))

    return paginate(
        items_query, count_query, page, per_page, scalar_result=True
    )

def _get_tickets_for_users(
    party_id: PartyID, user_ids: set[UserID]
) -> list[DbTicket]:
    return db.session \
        .query(DbTicket) \
        .options(
            db.joinedload(DbTicket.category),
            db.joinedload(DbTicket.occupied_seat)
                .joinedload(DbSeat.area),
        ) \
        .filter(DbTicket.party_id == party_id) \
        .filter(DbTicket.used_by_id.in_(user_ids)) \
        .filter(DbTicket.revoked == False) \
        .all()

def _index_tickets_by_user_id(
    tickets: Iterable[DbTicket],
) -> dict[UserID, set[DbTicket]]:
    tickets_by_user_id = defaultdict(set)
    for ticket in tickets:
        tickets_by_user_id[ticket.used_by_id].add(ticket)
    return tickets_by_user_id

def _generate_attendees(
    users: Iterable[DbUser], tickets_by_user_id: dict[UserID, set[DbTicket]]
) -> Iterable[Attendee]:
    for user in users:
        tickets = tickets_by_user_id[user.id]
        attendee_tickets = _to_attendee_tickets(tickets)
        yield Attendee(user, attendee_tickets)

def _to_attendee_tickets(tickets: Iterable[DbTicket]) -> list[AttendeeTicket]:
    attendee_tickets = [
        AttendeeTicket(t.occupied_seat, t.user_checked_in) for t in tickets
    ]
    attendee_tickets.sort(key=_get_attendee_ticket_sort_key)
    return attendee_tickets

def _get_attendee_ticket_sort_key(
    attendee_ticket: AttendeeTicket,
) -> tuple[bool, str, bool]:
    return (
        # List tickets with occupied seat first.
        attendee_ticket.seat is None,

        # Sort by seat label.
        attendee_ticket.seat.label if attendee_ticket.seat else None,

        # List checked in tickets first.
        not attendee_ticket.checked_in,
    )


text:
define([
   'esri/units',
   'esri/geometry/Extent',
   'esri/config',
   'esri/tasks/GeometryService',
   'esri/layers/ImageParameters'
], function (units, Extent, esriConfig, GeometryService, ImageParameters) {

    // url to your proxy page, must be on same machine hosting you app. See proxy folder for readme.
    esriConfig.defaults.io.proxyUrl = 'proxy/proxy.ashx';
    esriConfig.defaults.io.alwaysUseProxy = false;
    // url to your geometry server.
    esriConfig.defaults.geometryService = new GeometryService('http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer');

    //image parameters for dynamic services, set to png32 for higher quality exports.
    var imageParameters = new ImageParameters();
    imageParameters.format = 'png32';

    return {
        // used for debugging your app
        isDebug: true,

        //default mapClick mode, mapClickMode lets widgets know what mode the map is in to avoid multipult map click actions from taking place (ie identify while drawing).
        defaultMapClickMode: 'identify',
        // map options, passed to map constructor. see: https://developers.arcgis.com/javascript/jsapi/map-amd.html#map1
        mapOptions: {
            basemap: 'streets',
            center: [-96.59179687497497, 39.09596293629694],
            zoom: 5,
            sliderStyle: 'small'
        },
        // panes: {
        // 	left: {
        // 		splitter: true
        // 	},
        // 	right: {
        // 		id: 'sidebarRight',
        // 		placeAt: 'outer',
        // 		region: 'right',
        // 		splitter: true,
        // 		collapsible: true
        // 	},
        // 	bottom: {
        // 		id: 'sidebarBottom',
        // 		placeAt: 'outer',
        // 		splitter: true,
        // 		collapsible: true,
        // 		region: 'bottom'
        // 	},
        // 	top: {
        // 		id: 'sidebarTop',
        // 		placeAt: 'outer',
        // 		collapsible: true,
        // 		splitter: true,
        // 		region: 'top'
        // 	}
        // },
        // collapseButtonsPane: 'center', //center or outer

        // operationalLayers: Array of Layers to load on top of the basemap: valid 'type' options: 'dynamic', 'tiled', 'feature'.
        // The 'options' object is passed as the layers options for constructor. Title will be used in the legend only. id's must be unique and have no spaces.
        // 3 'mode' options: MODE_SNAPSHOT = 0, MODE_ONDEMAND = 1, MODE_SELECTION = 2
        operationalLayers: [{
            type: 'feature',
            url: 'http://services1.arcgis.com/g2TonOxuRkIqSOFx/arcgis/rest/services/MeetUpHomeTowns/FeatureServer/0',
            title: 'STLJS Meetup Home Towns',
            options: {
                id: 'meetupHometowns',
                opacity: 1.0,
                visible: true,
                outFields: ['*'],
                mode: 0
            },
            editorLayerInfos: {
                disableGeometryUpdate: false
            },
            legendLayerInfos: {
                exclude: false,
                layerInfo: {
                    title: 'My layer'
                }
            }
  }, {
            type: 'feature',
            url: 'http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/SanFrancisco/311Incidents/FeatureServer/0',
            title: 'San Francisco 311 Incidents',
            options: {
                id: 'sf311Incidents',
                opacity: 1.0,
                visible: true,
                outFields: ['req_type', 'req_date', 'req_time', 'address', 'district'],
                mode: 0
            }
  }, {
            type: 'dynamic',
            url: 'http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/PublicSafety/PublicSafetyOperationalLayers/MapServer',
            title: 'Louisville Public Safety',
            options: {
                id: 'louisvillePubSafety',
                opacity: 1.0,
                visible: true,
                imageParameters: imageParameters
            },
            identifyLayerInfos: {
                layerIds: [2, 4, 5, 8, 12, 21]
            },
            legendLayerInfos: {
                layerInfo: {
                    hideLayers: [21]
                }
            }
  }, {
            type: 'dynamic',
            url: 'http://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/MapServer',
            title: 'Damage Assessment',
            options: {
                id: 'DamageAssessment',
                opacity: 1.0,
                visible: true,
                imageParameters: imageParameters
            },
            legendLayerInfos: {
                exclude: true
            },
            layerControlLayerInfos: {
                swipe: true,
                metadataUrl: true,
                expanded: true
            }
  }],
        // set include:true to load. For titlePane type set position the the desired order in the sidebar
        widgets: {
            growler: {
                include: true,
                id: 'growler',
                type: 'domNode',
                path: 'gis/dijit/Growler',
                srcNodeRef: 'growlerDijit',
                options: {}
            },
            geocoder: {
                include: true,
                id: 'geocoder',
                type: 'domNode',
                path: 'gis/dijit/Geocoder',
                srcNodeRef: 'geocodeDijit',
                options: {
                    map: true,
                    mapRightClickMenu: true,
                    geocoderOptions: {
                        autoComplete: true,
                        arcgisGeocoder: {
                            placeholder: 'Enter an address or place'
                        }
                    }
                }
            },
            identify: {
                include: true,
                id: 'identify',
                type: 'titlePane',
                path: 'gis/dijit/Identify',
                title: 'Identify',
                open: false,
                position: 3,
                options: 'config/identify'
            },
            basemaps: {
                include: true,
                id: 'basemaps',
                type: 'domNode',
                path: 'gis/dijit/Basemaps',
                srcNodeRef: 'basemapsDijit',
                options: 'config/basemaps'
            },
            mapInfo: {
                include: false,
                id: 'mapInfo',
                type: 'domNode',
                path: 'gis/dijit/MapInfo',
                srcNodeRef: 'mapInfoDijit',
                options: {
                    map: true,
                    mode: 'dms',
                    firstCoord: 'y',
                    unitScale: 3,
                    showScale: true,
                    xLabel: '',
                    yLabel: '',
                    minWidth: 286
                }
            },
            scalebar: {
                include: true,
                id: 'scalebar',
                type: 'map',
                path: 'esri/dijit/Scalebar',
                options: {
                    map: true,
                    attachTo: 'bottom-left',
                    scalebarStyle: 'line',
                    scalebarUnit: 'dual'
                }
            },
            locateButton: {
                include: true,
                id: 'locateButton',
                type: 'domNode',
                path: 'gis/dijit/LocateButton',
                srcNodeRef: 'locateButton',
                options: {
                    map: true,
                    publishGPSPosition: true,
                    highlightLocation: true,
                    useTracking: true,
                    geolocationOptions: {
                        maximumAge: 0,
                        timeout: 15000,
                        enableHighAccuracy: true
                    }
                }
            },
            overviewMap: {
                include: true,
                id: 'overviewMap',
                type: 'map',
                path: 'esri/dijit/OverviewMap',
                options: {
                    map: true,
                    attachTo: 'bottom-right',
                    color: '#0000CC',
                    height: 100,
                    width: 125,
                    opacity: 0.30,
                    visible: false
                }
            },
            homeButton: {
                include: true,
                id: 'homeButton',
                type: 'domNode',
                path: 'esri/dijit/HomeButton',
                srcNodeRef: 'homeButton',
                options: {
                    map: true,
                    extent: new Extent({
                        xmin: -180,
                        ymin: -85,
                        xmax: 180,
                        ymax: 85,
                        spatialReference: {
                            wkid: 4326
                        }
                    })
                }
            },
            legend: {
                include: true,
                id: 'legend',
                type: 'titlePane',
                path: 'esri/dijit/Legend',
                title: 'Legend',
                open: false,
                position: 0,
                options: {
                    map: true,
                    legendLayerInfos: true
                }
            },
            layerControl: {
                include: true,
                id: 'layerControl',
                type: 'titlePane',
                path: 'gis/dijit/LayerControl',
                title: 'Layers',
                open: false,
                position: 0,
                options: {
                    map: true,
                    layerControlLayerInfos: true,
                    separated: true,
                    vectorReorder: true,
                    overlayReorder: true
                }
            },
            bookmarks: {
                include: true,
                id: 'bookmarks',
                type: 'titlePane',
                path: 'gis/dijit/Bookmarks',
                title: 'Bookmarks',
                open: false,
                position: 2,
                options: 'config/bookmarks'
            },
            find: {
                include: true,
                id: 'find',
                type: 'titlePane',
                canFloat: true,
                path: 'gis/dijit/Find',
                title: 'Find',
                open: false,
                position: 3,
                options: 'config/find'
            },
            draw: {
                include: true,
                id: 'draw',
                type: 'titlePane',
                canFloat: true,
                path: 'gis/dijit/Draw',
                title: 'Draw',
                open: false,
                position: 4,
                options: {
                    map: true,
                    mapClickMode: true
                }
            },
            measure: {
                include: true,
                id: 'measurement',
                type: 'titlePane',
                canFloat: true,
                path: 'gis/dijit/Measurement',
                title: 'Measurement',
                open: false,
                position: 5,
                options: {
                    map: true,
                    mapClickMode: true,
                    defaultAreaUnit: units.SQUARE_MILES,
                    defaultLengthUnit: units.MILES
                }
            },
            print: {
                include: true,
                id: 'print',
                type: 'titlePane',
                canFloat: true,
                path: 'gis/dijit/Print',
                title: 'Print',
                open: false,
                position: 6,
                options: {
                    map: true,
                    printTaskURL: 'https://utility.arcgisonline.com/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task',
                    copyrightText: 'Copyright 2014',
                    authorText: 'Me',
                    defaultTitle: 'Viewer Map',
                    defaultFormat: 'PDF',
                    defaultLayout: 'Letter ANSI A Landscape'
                }
            },
            directions: {
                include: true,
                id: 'directions',
                type: 'titlePane',
                path: 'gis/dijit/Directions',
                title: 'Directions',
                open: false,
                position: 7,
                options: {
                    map: true,
                    mapRightClickMenu: true,
                    options: {
                        routeTaskUrl: 'http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Route',
                        routeParams: {
                            directionsLanguage: 'en-US',
                            directionsLengthUnits: units.MILES
                        },
                        active: false //for 3.12, starts active by default, which we dont want as it interfears with mapClickMode
                    }
                }
            },
            editor: {
                include: true,
                id: 'editor',
                type: 'titlePane',
                path: 'gis/dijit/Editor',
                title: 'Editor',
                open: false,
                position: 8,
                options: {
                    map: true,
                    mapClickMode: true,
                    editorLayerInfos: true,
                    settings: {
                        toolbarVisible: true,
                        showAttributesOnClick: true,
                        enableUndoRedo: true,
                        createOptions: {
                            polygonDrawTools: ['freehandpolygon', 'autocomplete']
                        },
                        toolbarOptions: {
                            reshapeVisible: true,
                            cutVisible: true,
                            mergeVisible: true
                        }
                    }
                }
            },
            streetview: {
                include: true,
                id: 'streetview',
                type: 'titlePane',
                canFloat: true,
                position: 9,
                path: 'gis/dijit/StreetView',
                title: 'Google Street View',
                options: {
                    map: true,
                    mapClickMode: true,
                    mapRightClickMenu: true
                }
            },
            help: {
                include: true,
                id: 'help',
                type: 'floating',
                path: 'gis/dijit/Help',
                title: 'Help',
                options: {}
            }

        }
    };
});


text:
// Copyright (c) 2014-2018 NVIDIA Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#ifndef _VSD_H_
#define _VSD_H_

#include "common/vs_defs.h"
#include "vsd/vsd_math.h"

/*************************************************************************************
NOTE: There is no need to include this file directly.

Instead, include one or more of the specializations vs1d.h, vsd2.h, vs3d.h, or vs4d.h.

A specialization is needed in order for the code to compile.
**************************************************************************************/

/** Templated VS functions for dimension-specific implementations of the void simplex algorithm. */

/**
Support function for vsd_test_feature<D>.

This function is not defined for general D.  Specializations are defined in vs1d.h, vs2d.h, vs3d.h, and vs4d.h.

An implementation if this function must find the nearest vector (p) to an input vector (q) which solves:

	dot<D+1>(p, S[indices[i]]) = 0

for all i = 0, ... , N-1.

\param[out]	p		the solution, a (D+1)-dimensional vector.
\param[in]	q		the target, a (D+1)-dimensional vector.
\param[in]	S		an array of (D+1)-dimensional vectors, of at least the size such that each value in indices[0], ..., indices[N-1] is a valid element.
					In this algorithm we may assume that S stores a (D+1)x(D+1) array.
\param[in]	indices	stores the indices elements of the S array (equivalently, columns of the S matrix) used.
\param[in]	N		the size of the indices array.

\return the square of the determinant of the linear system solved to find p.  If 0 is returned, a solution is not found.
*/
template<uint D>
inline real
vsd_solve_feature(real p[], const real q[], const real S[][D + 1], const uint indices[], uint N);

/*
Support function for vsd_search_features<D>.

Given N_set plane equations stored in columns 0 through (N_set-1) of S, and a subset of columns of S defined by the bits in columns_test,
a solution p to the equations

	dot<D+1>(p, S[c]) = 0

for all test column indices c, is found.  If that solution also satisfies

	dot<D+1>(p, S[c]) <= 0

for all indices 0 <= c < N_set which are _not_ marked by bits in columns_test, then the solution p is valid.

Valid solutions are compared with the current solution by values stored in the measure array.  If a valid solution has better measure parameters,
then it is closer to the current solution and the current solution is copied to the output vector p along with update measure parameters,
the square determinant of the basis used to solve for p, and the columns used to calculate p.
*/
template<uint D>
inline bool
vsd_test_feature(real p[D + 1], real& p2_min, real& det_basis, uint& columns, uint columns_test, uint N_set, const real S[D + 1][D + 1], const real q[D + 1])
{
	real p_test[D + 1];	// test solution

	// Create index array
	uint indices[D];
	uint N = 0;
	for (uint j = 0; j < N_set; ++j) if (((columns_test >> j) & 1) != 0) indices[N++] = j;

	// Solve for closest point on the feature defined by indices
	const real det_basis_test = vsd_solve_feature<D>(p_test, q, S, indices, N);
	if (det_basis_test == 0) return false;

	// Don't accept a bounded solution if we have an unbounded solution already
	if (p_test[D] > p[D]) return false;

	// Make sure solution is valid (not outside the other half-spaces in S)
	for (uint j = 0; j < N_set; ++j) if ((((columns_test >> j) & 1) == 0) && dot<D + 1>(p_test, S[j]) > 0) return false;

	// If the solution isn't better than the current one, don't use it
	const real p2 = q[D] != 0 ? diff_norm_2_sq<D>(p_test, q) : -dot<D + 1>(p_test, q);
	if (p[D] == p_test[D] && p2 >= p2_min) return false;

	// Use this solution
	cpy<D + 1>(p, p_test);
	p2_min = p2;
	det_basis = det_basis_test;
	columns = columns_test;

	return true;
}

/*
Support function for vsd_update<D>.

This function is not defined for general D.  Specializations are defined in vs1d.h, vs2d.h, vs3d.h, and vs4d.h.

An implementation if this function must find the best solution p for every subset of the columns
of S, an N x (D+1) matrix with columns holding plane equations, such that

	dot<D+1>(p, S[c]) = 0

for all test column indices c, and

	dot<D+1>(p, S[c]) <= 0

for all other columns c of S.

\param[out]	columns		the columns used to find the best solution, represented as bits in an unsigned integer.
\param[out]	p			the best solution, a (D+1)-dimensional vector.
\param[out] det_basis	the determinant of the linear system solved to find p.
\param[in]	S			an array of N (D+1)-dimensional vectors representing plane equations.
\param[in]	N			the number of columns in S.
\param[in]	q			the target, a (D+1)-dimensional vector.

\return true iff a solution is found.
*/
template<uint D>
inline bool
vsd_search_features(uint& columns, real p[], real& det_basis, const real S[][D + 1], uint N, const real q[]);

/*
Support function for vsd_solve_i<D>.

Finds the closest point represented by a homogeneous (D+1)-vector p to the target (D+1)-vector q, which satisfies

	dot<D+1>(p, S[c]) <= 0

for all columns c of S, an N x (D+1) matrix with columns holding (D+1)-dimensional vectors representing plane equations.

On output, only the columns of S which held strict equality in the above equation are kept.  If no solution is found, the function returns false.

\param[out]		p			the solution, a (D+1)-dimensional vector.
\param[out]		det_basis	the determinant of the linear system solved to find p.
\param[in,out]	S			an array of N (D+1)-dimensional vectors representing plane equations.  On output, only the columns of S which lead to strict equality in the above equation are kept.
\param[in,out]	N			the number of columns in S.  On output, the number of columns of S kept.
\param[in]		q			the target, a (D+1)-dimensional vector.

\return true iff a solution is found.
*/
template<uint D>
inline bool
vsd_update(real p[], real& det_basis, real S[][D + 1], uint& N, const real q[])
{
	// Reduce problem into new plane
	real v[D];		// Householder vector
	real R[D][D];	// Reduced simplex matrix
	real qR[D];		// Reduced objective

	// Save off index of the new plane, which will serve as the original number of working planes (old planes)
	const uint N_old = N - 1;

	// Restrict solution to new plane, since it must lie there if it exists.  Using a Householder reflection which maps the new plane normal to the last coordinate axis:
	const real* h_new = S[N_old];
	const real Vnd = h_new[D - 1];
	const real sgnVnd = Vnd >= 0 ? (real)1 : -(real)1;
	cpy<D>(v, h_new);
	v[D - 1] += sgnVnd;
	const real negBeta = -1 / (1 + Vnd*sgnVnd);

	// Project all plane equations and the objective into the new plane
	const real sgnVnd_d_new = sgnVnd*h_new[D];
	for (uint n = 0; n < N_old; ++n)
	{
		madd<D>(R[n], v, negBeta*dot<D>(v, S[n]), S[n]);	// Perform the D-dimensional transformation of the normal vector
		R[n][D - 1] = S[n][D] + sgnVnd_d_new*R[n][D - 1];	// Replace Rn[D-1] with the correct plane displacement for the reduced plane in the space of the new plane (note, these won't be normalized, which is OK)
	}
	madd<D - 1>(qR, v, negBeta*dot<D>(v, q), q);
	qR[D - 1] = q[D];

	uint columns;		// Bits representing columns of S used in feature calculations
	const bool solution_found = vsd_search_features<D-1>(columns, p, det_basis, R, N_old, qR);

	// Translate p to original space
	p[D] = p[D - 1];
	p[D - 1] *= sgnVnd_d_new;
	madd<D>(p, v, negBeta*dot<D>(v, p), p);

	// If no combination of planes produces a feature, we have a void simplex
	if (!solution_found) return false;

	// ... otherwise update the simplex
	const uint N_set = N;
	N = 0;
	for (uint j = 0; j < N_set; ++j, columns >>= 1) if (columns & 1) cpy<D + 1>(S[N++], S[j]);
	cpy<D + 1>(S[N++], h_new);	// Include last column

	return true;
}

/**
Execute the void simplex algorithm (templated D).  This version exposes internal state (thus the 'i' suffix).

\param[out]	S			will be filled with the working simplex upon return.
\param[out]	N			will contain the number of columns (5-vectors) in S upon return.
\param[out]	p			will be filled with the solution upon return if the function returns 1.
\param[in]	halfspaces	the user-defined implementation of VS_Halfspace_Set.
\param[in]	q			the objective vector.  It must contain 5 reals representing a normalized projective point (q[4] == 1) or direction (q[4] == 0, |q| == 1).
\param[out]	rho			(optional) if not NULL, *rho will be set to the absolute value of the determinant of the linear system solved for the returned solution.  0 < rho <= 1.  Default is NULL.
						NOTE: a crude approximation for the condition number is (1+sqrt(1-rho))/rho.
\param[in]	tol			the requested solution accuracy, relative to the size of the output vector.
\return 1, 0, or -1.  The meaning of each value is given below.

Return values:
	 1: the halfspace set has a non-empty intersection
	 0: the halfspace set has an empty intersection
	-1: the function failed to find a result
*/
template<uint D>
inline int
vsd_solve_i(real S[D + 1][D + 1], uint& N, real p[D + 1], const VS_Halfspace_Set& halfspaces, const real q[D + 1], real* rho = nullptr, real tol = vs_default_tolerance())
{
	// Constants
	const uint max_iteration_count = 10 * D;	// Maximum allowed iterations of main loop.  If exceeded, error value (-1) is returned

	// Initialize state (the memory in S will be considered uninitialized, appropriate for N == 0)
	N = 0;
	cpy<D + 1>(p, q);

	// Using tolerance squared
	const real tol_sq = tol*tol;

	// Iterate until a stopping condition is met or the maximum number of iterations is reached
	real det_basis = 1;	// Used to approximate solution robustness
	int result = -1;
	for (uint i = 0; result < 0 && i < max_iteration_count; ++i)
	{
		const real delta = halfspaces.farthest_halfspace(S[N], p);
		if (delta <= 0 || delta*delta <= tol_sq*dot<D + 1>(p, p)) result = 1;	// Intersection found
		else if (!vsd_update<D>(p, det_basis, S, ++N, q)) result = 0;	// Void found
	}

	// If robustness is given, fill it with the absolute value of the determinant of the basis matrix
	if (rho) *rho = det_basis > 0 ? det_basis : -det_basis;

	return result;
}

/*
Execute the void simplex algorithm (templated D).  This version hides its internal state.
It also does not require a normalized objective vector q (see the requirements for q in vsd_solve_i<D>).

\param[in]		halfspaces	user-defined implementation of VS_Halfspace_Set.
\param[in,out]	q			a pointer the objective vector on input, and (if the function returns 1) the solution vector on output, if it is not NULL.
							If NULL, the objective vector will be the origin (0, ..., 0, 1).  Otherwise, it must point to D+1 reals representing a projective point (q[D] != 0) or direction (q[D] == 0).
\param[out]		rho			(optional) if not NULL, *rho will be set to the absolute value of the determinant of the linear system solved for the returned solution.  0 < rho <= 1.  Default is NULL.
							NOTE: a crude approximation for the condition number is (1+sqrt(1-rho))/rho.
\param[in]		tol			the requested solution accuracy, relative to the size of the output vector.
\return 1, 0, or -1.		The meaning of each value is given below.

Return values:
	 1: the halfspace set has a non-empty intersection
	 0: the halfspace set has an empty intersection
	-1: the function failed to find a result
*/
template<uint D>
inline int
vsd_solve(const VS_Halfspace_Set& halfspaces, real* q = nullptr, real* rho = nullptr, real tol = vs_default_tolerance())
{
	real S[D + 1][D + 1];
	real p[D + 1];
	real objective[D + 1];

	// Objective = q if it is not NULL, otherwise it is the origin represented in homogeneous coordinates
	if (q)
	{
		if (q[D] != 0) div<D + 1>(objective, q, q[D]);
		else cpy<D + 1>(objective, q);
	}
	else
	{
		zero<D + 1>(objective);
		objective[D] = 1;
	}

	uint N;
	const int result = vsd_solve_i<D>(S, N, p, halfspaces, objective, rho, tol);

	// If q is given, fill it with the solution
	if (q) cpy<D + 1>(q, p);

	return result;
}

#endif // #ifndef _VSD_H_


text:
require 'test_helper'

module Elasticsearch
  module Test
    class IngestDeletePipelineTest < ::Test::Unit::TestCase

      context "Ingest: Delete pipeline" do
        subject { FakeClient.new }

        should "require the :id argument" do
          assert_raise ArgumentError do
            subject.ingest.delete_pipeline
          end
        end

        should "perform correct request" do
          subject.expects(:perform_request).with do |method, url, params, body|
            assert_equal 'DELETE', method
            assert_equal '_ingest/pipeline/foo', url
            assert_equal Hash.new, params
            assert_nil   body
            true
          end.returns(FakeResponse.new)

          subject.ingest.delete_pipeline :id => 'foo'
        end

        should "URL-escape the ID" do
          subject.expects(:perform_request).with do |method, url, params, body|
            assert_equal '_ingest/pipeline/foo%5Ebar', url
            true
          end.returns(FakeResponse.new)

          subject.ingest.delete_pipeline :id => 'foo^bar'
        end

      end

    end
  end
end


text:
require 'spec_helper'
require 'matchers/json'

# the json-schema gem doesn't support windows
if not Puppet.features.microsoft_windows?
  NODE_SCHEMA = JSON.parse(File.read(File.join(File.dirname(__FILE__), '../../api/schemas/node.json')))

  describe "node schema" do
    it "should validate against the json meta-schema" do
      JSON::Validator.validate!(JSON_META_SCHEMA, NODE_SCHEMA)
    end
  end
end

describe Puppet::Node do
  it "should register its document type as Node" do
    PSON.registered_document_types["Node"].should equal(Puppet::Node)
  end

  describe "when managing its environment" do
    it "should use any set environment" do
      Puppet::Node.new("foo", :environment => "bar").environment.name.should == :bar
    end

    it "should support providing an actual environment instance" do
      Puppet::Node.new("foo", :environment => Puppet::Node::Environment.new(:bar)).environment.name.should == :bar
    end

    it "should determine its environment from its parameters if no environment is set" do
      Puppet::Node.new("foo", :parameters => {"environment" => :bar}).environment.name.should == :bar
    end

    it "should use the default environment if no environment is provided" do
      Puppet::Node.new("foo").environment.name.should == Puppet::Node::Environment.new.name
    end

    it "should always return an environment instance rather than a string" do
      Puppet::Node.new("foo").environment.should be_instance_of(Puppet::Node::Environment)
    end

    it "should allow the environment to be set after initialization" do
      node = Puppet::Node.new("foo")
      node.environment = :bar
      node.environment.name.should == :bar
    end

    it "should allow its environment to be set by parameters after initialization" do
      node = Puppet::Node.new("foo")
      node.parameters["environment"] = :bar
      node.environment.name.should == :bar
    end
  end

  it "can survive a round-trip through YAML" do
    facts = Puppet::Node::Facts.new("hello", "one" => "c", "two" => "b")
    node = Puppet::Node.new("hello",
                            :environment => 'kjhgrg',
                            :classes => ['erth', 'aiu'],
                            :parameters => {"hostname"=>"food"}
                           )
    new_node = Puppet::Node.convert_from('yaml', node.render('yaml'))
    new_node.environment.should == node.environment
    new_node.parameters.should == node.parameters
    new_node.classes.should == node.classes
    new_node.name.should == node.name
  end

  it "can round-trip through pson" do
    facts = Puppet::Node::Facts.new("hello", "one" => "c", "two" => "b")
    node = Puppet::Node.new("hello",
                            :environment => 'kjhgrg',
                            :classes => ['erth', 'aiu'],
                            :parameters => {"hostname"=>"food"}
                           )
    new_node = Puppet::Node.convert_from('pson', node.render('pson'))
    new_node.environment.should == node.environment
    new_node.parameters.should == node.parameters
    new_node.classes.should == node.classes
    new_node.name.should == node.name
  end

  it "validates against the node json schema", :unless => Puppet.features.microsoft_windows? do
    facts = Puppet::Node::Facts.new("hello", "one" => "c", "two" => "b")
    node = Puppet::Node.new("hello",
                            :environment => 'kjhgrg',
                            :classes => ['erth', 'aiu'],
                            :parameters => {"hostname"=>"food"}
                           )
    JSON::Validator.validate!(NODE_SCHEMA, node.to_pson)
  end

  it "when missing optional parameters validates against the node json schema", :unless => Puppet.features.microsoft_windows? do
    facts = Puppet::Node::Facts.new("hello", "one" => "c", "two" => "b")
    node = Puppet::Node.new("hello",
                            :environment => 'kjhgrg'
                           )
    JSON::Validator.validate!(NODE_SCHEMA, node.to_pson)
  end

  describe "when converting to json" do
    before do
      @node = Puppet::Node.new("mynode")
    end

    it "should provide its name" do
      @node.should set_json_attribute('name').to("mynode")
    end

    it "should produce a hash with the document_type set to 'Node'" do
      @node.should set_json_document_type_to("Node")
    end

    it "should include the classes if set" do
      @node.classes = %w{a b c}
      @node.should set_json_attribute("classes").to(%w{a b c})
    end

    it "should not include the classes if there are none" do
      @node.should_not set_json_attribute('classes')
    end

    it "should include parameters if set" do
      @node.parameters = {"a" => "b", "c" => "d"}
      @node.should set_json_attribute('parameters').to({"a" => "b", "c" => "d"})
    end

    it "should not include the parameters if there are none" do
      @node.should_not set_json_attribute('parameters')
    end

    it "should include the environment" do
      @node.environment = "production"
      @node.should set_json_attribute('environment').to('production')
    end
  end

  describe "when converting from json" do
    before do
      @node = Puppet::Node.new("mynode")
      @format = Puppet::Network::FormatHandler.format('pson')
    end

    def from_json(json)
      @format.intern(Puppet::Node, json)
    end

    it "should set its name" do
      Puppet::Node.should read_json_attribute('name').from(@node.to_pson).as("mynode")
    end

    it "should include the classes if set" do
      @node.classes = %w{a b c}
      Puppet::Node.should read_json_attribute('classes').from(@node.to_pson).as(%w{a b c})
    end

    it "should include parameters if set" do
      @node.parameters = {"a" => "b", "c" => "d"}
      Puppet::Node.should read_json_attribute('parameters').from(@node.to_pson).as({"a" => "b", "c" => "d"})
    end

    it "should include the environment" do
      @node.environment = "production"
      Puppet::Node.should read_json_attribute('environment').from(@node.to_pson).as(Puppet::Node::Environment.new(:production))
    end
  end
end

describe Puppet::Node, "when initializing" do
  before do
    @node = Puppet::Node.new("testnode")
  end

  it "should set the node name" do
    @node.name.should == "testnode"
  end

  it "should not allow nil node names" do
    proc { Puppet::Node.new(nil) }.should raise_error(ArgumentError)
  end

  it "should default to an empty parameter hash" do
    @node.parameters.should == {}
  end

  it "should default to an empty class array" do
    @node.classes.should == []
  end

  it "should note its creation time" do
    @node.time.should be_instance_of(Time)
  end

  it "should accept parameters passed in during initialization" do
    params = {"a" => "b"}
    @node = Puppet::Node.new("testing", :parameters => params)
    @node.parameters.should == params
  end

  it "should accept classes passed in during initialization" do
    classes = %w{one two}
    @node = Puppet::Node.new("testing", :classes => classes)
    @node.classes.should == classes
  end

  it "should always return classes as an array" do
    @node = Puppet::Node.new("testing", :classes => "myclass")
    @node.classes.should == ["myclass"]
  end
end

describe Puppet::Node, "when merging facts" do
  before do
    @node = Puppet::Node.new("testnode")
    Puppet::Node::Facts.indirection.stubs(:find).with(@node.name, instance_of(Hash)).returns(Puppet::Node::Facts.new(@node.name, "one" => "c", "two" => "b"))
  end

  it "should fail intelligently if it cannot find facts" do
    Puppet::Node::Facts.indirection.expects(:find).with(@node.name, instance_of(Hash)).raises "foo"
    lambda { @node.fact_merge }.should raise_error(Puppet::Error)
  end

  it "should prefer parameters already set on the node over facts from the node" do
    @node = Puppet::Node.new("testnode", :parameters => {"one" => "a"})
    @node.fact_merge
    @node.parameters["one"].should == "a"
  end

  it "should add passed parameters to the parameter list" do
    @node = Puppet::Node.new("testnode", :parameters => {"one" => "a"})
    @node.fact_merge
    @node.parameters["two"].should == "b"
  end

  it "should accept arbitrary parameters to merge into its parameters" do
    @node = Puppet::Node.new("testnode", :parameters => {"one" => "a"})
    @node.merge "two" => "three"
    @node.parameters["two"].should == "three"
  end

  it "should add the environment to the list of parameters" do
    Puppet[:environment] = "one"
    @node = Puppet::Node.new("testnode", :environment => "one")
    @node.merge "two" => "three"
    @node.parameters["environment"].should == "one"
  end

  it "should not set the environment if it is already set in the parameters" do
    Puppet[:environment] = "one"
    @node = Puppet::Node.new("testnode", :environment => "one")
    @node.merge "environment" => "two"
    @node.parameters["environment"].should == "two"
  end
end

describe Puppet::Node, "when indirecting" do
  it "should default to the 'plain' node terminus" do
    Puppet::Node.indirection.reset_terminus_class

    Puppet::Node.indirection.terminus_class.should == :plain
  end
end

describe Puppet::Node, "when generating the list of names to search through" do
  before do
    @node = Puppet::Node.new("foo.domain.com", :parameters => {"hostname" => "yay", "domain" => "domain.com"})
  end

  it "should return an array of names" do
    @node.names.should be_instance_of(Array)
  end

  describe "and the node name is fully qualified" do
    it "should contain an entry for each part of the node name" do
      @node.names.should be_include("foo.domain.com")
      @node.names.should be_include("foo.domain")
      @node.names.should be_include("foo")
    end
  end

  it "should include the node's fqdn" do
    @node.names.should be_include("yay.domain.com")
  end

  it "should combine and include the node's hostname and domain if no fqdn is available" do
    @node.names.should be_include("yay.domain.com")
  end

  it "should contain an entry for each name available by stripping a segment of the fqdn" do
    @node.parameters["fqdn"] = "foo.deep.sub.domain.com"
    @node.names.should be_include("foo.deep.sub.domain")
    @node.names.should be_include("foo.deep.sub")
  end

  describe "and :node_name is set to 'cert'" do
    before do
      Puppet[:strict_hostname_checking] = false
      Puppet[:node_name] = "cert"
    end

    it "should use the passed-in key as the first value" do
      @node.names[0].should == "foo.domain.com"
    end

    describe "and strict hostname checking is enabled" do
      it "should only use the passed-in key" do
        Puppet[:strict_hostname_checking] = true
        @node.names.should == ["foo.domain.com"]
      end
    end
  end

  describe "and :node_name is set to 'facter'" do
    before do
      Puppet[:strict_hostname_checking] = false
      Puppet[:node_name] = "facter"
    end

    it "should use the node's 'hostname' fact as the first value" do
      @node.names[0].should == "yay"
    end
  end
end