text:
package ui

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	_ "net/http/pprof" // Comment this line to disable pprof endpoint.
	"path/filepath"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/log/level"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/common/route"
)

func serveAsset(w http.ResponseWriter, req *http.Request, fp string, logger log.Logger) {
	info, err := AssetInfo(fp)
	if err != nil {
		level.Warn(logger).Log("msg", "Could not get file", "err", err)
		w.WriteHeader(http.StatusNotFound)
		return
	}
	file, err := Asset(fp)
	if err != nil {
		if err != io.EOF {
			level.Warn(logger).Log("msg", "Could not get file", "file", fp, "err", err)
		}
		w.WriteHeader(http.StatusNotFound)
		return
	}

	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	http.ServeContent(w, req, info.Name(), info.ModTime(), bytes.NewReader(file))
}

// Register registers handlers to serve files for the web interface.
func Register(r *route.Router, reloadCh chan<- chan error, logger log.Logger) {
	ihf := prometheus.InstrumentHandlerFunc

	r.Get("/metrics", prometheus.Handler().ServeHTTP)

	r.Get("/", ihf("index", func(w http.ResponseWriter, req *http.Request) {
		serveAsset(w, req, "ui/app/index.html", logger)
	}))

	r.Get("/script.js", ihf("app", func(w http.ResponseWriter, req *http.Request) {
		serveAsset(w, req, "ui/app/script.js", logger)
	}))

	r.Get("/favicon.ico", ihf("app", func(w http.ResponseWriter, req *http.Request) {
		serveAsset(w, req, "ui/app/favicon.ico", logger)
	}))

	r.Get("/lib/*filepath", ihf("lib_files",
		func(w http.ResponseWriter, req *http.Request) {
			fp := route.Param(req.Context(), "filepath")
			serveAsset(w, req, filepath.Join("ui/app/lib", fp), logger)
		},
	))

	r.Post("/-/reload", func(w http.ResponseWriter, req *http.Request) {
		errc := make(chan error)
		defer close(errc)

		reloadCh <- errc
		if err := <-errc; err != nil {
			http.Error(w, fmt.Sprintf("failed to reload config: %s", err), http.StatusInternalServerError)
		}
	})

	r.Get("/-/healthy", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "OK")
	})
	r.Get("/-/ready", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "OK")
	})

	r.Get("/debug/*subpath", http.DefaultServeMux.ServeHTTP)
	r.Post("/debug/*subpath", http.DefaultServeMux.ServeHTTP)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Ovs.Hotel.Ui.Controllers
{
    public class MessageController : Controller
    {
        // GET: Message
        public ActionResult UserCredentialsNotValid()
        {
            return View();
        }

        public ActionResult AgentCredentialsNotValid()
        {
            return View();
        }

        public ActionResult UserNotLoggedIn()
        {
            return View();
        }
        public ActionResult DisplayOptionsNotFound()
        {
            return View();
        }
        public ActionResult BrowserNotSupported()
        {
            return View();
        }
        public ActionResult LegacyError()
        {
            return View();
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'gm_hash_wrapper/version'
require 'gm_hash_wrapper/hash_wrapper'
require 'gm_hash_wrapper/strict_hash_wrapper'

module GmHashWrapper
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

-->

<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

    <string name="home" msgid="7658288663002113681">"Inici"</string>
    <string name="uid_name" msgid="7820867637514617527">"Aplicacions principals d\'Android"</string>
    <string name="folder_name" msgid="7371454440695724752"></string>
    <string name="wallpaper_instructions" msgid="563973358787555519">"Estableix el fons de pantalla"</string>

    <plurals name="number_of_items_selected">
        <item msgid="7464587177007785408" quantity="zero">"Seleccionats: %1$d"</item>
        <item msgid="142482526010824029" quantity="one">"Seleccionats: %1$d"</item>
        <item msgid="1418352074806573570" quantity="other">"Seleccionats: %1$d"</item>
    </plurals>

    <string name="wallpaper_accessibility_name" msgid="1655953108132967972">"Fons de pantalla %1$d de %2$d"</string>
    <string name="announce_selection" msgid="8338254712932127413">"S\'ha seleccionat <xliff:g id="LABEL">%1$s</xliff:g>"</string>
    <string name="wallpaper_delete" msgid="8095005658756613921">"Suprimeix"</string>
    <string name="pick_image" msgid="1272073934062909527">"Selecciona una imatge"</string>
    <string name="pick_wallpaper" msgid="8179698221502010609">"Fons de pantalla"</string>
    <string name="crop_wallpaper" msgid="8334345984491368009">"Retalla el fons de pantalla"</string>
    <string name="activity_not_found" msgid="8071924732094499514">"L\'aplicació no s\'ha instal·lat."</string>
    <string name="widgets_tab_label" msgid="2921133187116603919">"Widgets"</string>
    <string name="widget_adder" msgid="3201040140710381657">"Widgets"</string>
    <string name="long_press_widget_to_add" msgid="7699152356777458215">"Mantén premut un widget per triar-lo."</string>
    <string name="market" msgid="2619650989819296998">"Compra"</string>
    <string name="widget_dims_format" msgid="2370757736025621599">"%1$d × %2$d"</string>
    <string name="external_drop_widget_error" msgid="3165821058322217155">"No s\'ha pogut deixar anar l\'element a Inici."</string>
    <string name="external_drop_widget_pick_title" msgid="3486317258037690630">"Tria el widget que vulguis crear"</string>
    <string name="rename_folder_label" msgid="3727762225964550653">"Nom de la carpeta"</string>
    <string name="rename_folder_title" msgid="3771389277707820891">"Canvi de nom de la carpeta"</string>
    <string name="rename_action" msgid="5559600076028658757">"D\'acord"</string>
    <string name="cancel_action" msgid="7009134900002915310">"Cancel·la"</string>
    <string name="menu_item_add_item" msgid="1264911265836810421">"Afegir a la pantalla d\'inici"</string>
    <string name="group_applications" msgid="3797214114206693605">"Aplicacions"</string>
    <string name="group_shortcuts" msgid="6012256992764410535">"Dreceres"</string>
    <string name="group_widgets" msgid="1569030723286851002">"Widgets"</string>
    <string name="completely_out_of_space" msgid="6106288382070760318">"No queda espai a les pantalles d\'inici."</string>
    <string name="out_of_space" msgid="4691004494942118364">"Ja no queda espai en aquesta pantalla d\'inici."</string>
    <string name="hotseat_out_of_space" msgid="9139760413395605841">"No queda espai al hotseat."</string>
    <string name="invalid_hotseat_item" msgid="1211534262129849507">"Aquest widget és massa gran per al hotseat."</string>
    <string name="shortcut_installed" msgid="1701742129426969556">"S\'ha creat la drecera \"<xliff:g id="NAME">%s</xliff:g>\"."</string>
    <string name="shortcut_uninstalled" msgid="8176767991305701821">"S\'ha suprimit la drecera \"<xliff:g id="NAME">%s</xliff:g>\"."</string>
    <string name="shortcut_duplicate" msgid="9167217446062498127">"La drecera \"<xliff:g id="NAME">%s</xliff:g>\" ja existeix."</string>
    <string name="title_select_shortcut" msgid="6680642571148153868">"Tria d\'una drecera"</string>
    <string name="title_select_application" msgid="3280812711670683644">"Tria d\'una aplicació"</string>
    <string name="all_apps_button_label" msgid="9110807029020582876">"Aplicacions"</string>
    <string name="all_apps_home_button_label" msgid="252062713717058851">"Inici"</string>
    <string name="delete_zone_label_workspace" msgid="4009607676751398685">"Suprimeix"</string>
    <string name="delete_zone_label_all_apps" msgid="8083826390278958980">"Desinstal·la"</string>
    <string name="delete_target_label" msgid="1822697352535677073">"Suprimeix"</string>
    <string name="delete_target_uninstall_label" msgid="5100785476250872595">"Desinstal·la"</string>
    <string name="info_target_label" msgid="8053346143994679532">"Informació de l\'aplicació"</string>
    <string name="accessibility_search_button" msgid="1628520399424565142">"Cerca"</string>
    <string name="accessibility_voice_search_button" msgid="4637324840434406584">"Cerca per veu"</string>
    <string name="accessibility_all_apps_button" msgid="2603132375383800483">"Aplicacions"</string>
    <string name="accessibility_delete_button" msgid="6466114477993744621">"Suprimeix"</string>
    <string name="delete_zone_label_all_apps_system_app" msgid="449755632749610895">"Desinstal·la l\'actualització"</string>
    <string name="cab_menu_delete_app" msgid="7435191475867183689">"Desinstal·la l\'aplicació"</string>
    <string name="cab_menu_app_info" msgid="8593722221450362342">"Detalls de l\'aplicació"</string>
    <string name="cab_app_selection_text" msgid="374688303047985416">"1 aplicació seleccionada"</string>
    <string name="cab_widget_selection_text" msgid="1833458597831541241">"1 widget seleccionat"</string>
    <string name="cab_folder_selection_text" msgid="7999992513806132118">"1 carpeta seleccionada"</string>
    <string name="cab_shortcut_selection_text" msgid="2103811025667946450">"1 drecera seleccionada"</string>
    <string name="permlab_install_shortcut" msgid="5632423390354674437">"instal·la dreceres"</string>
    <string name="permdesc_install_shortcut" msgid="923466509822011139">"Permet que una aplicació afegeixi dreceres sense la intervenció de l\'usuari."</string>
    <string name="permlab_uninstall_shortcut" msgid="864595034498083837">"desinstal·la dreceres"</string>
    <string name="permdesc_uninstall_shortcut" msgid="5134129545001836849">"Permet que l\'aplicació suprimeixi dreceres sense la intervenció de l\'usuari."</string>
    <string name="permlab_read_settings" msgid="1941457408239617576">"llegeix la configuració i les dreceres de la pantalla d\'inici"</string>
    <string name="permdesc_read_settings" msgid="5833423719057558387">"Permet que l\'aplicació llegeixi la configuració i les dreceres de la pantalla d\'inici."</string>
    <string name="permlab_write_settings" msgid="3574213698004620587">"escriu la configuració i les dreceres de la pantalla d\'inici"</string>
    <string name="permdesc_write_settings" msgid="5440712911516509985">"Permet que l\'aplicació canviï la configuració i les dreceres de la pantalla d\'inici."</string>
    <string name="gadget_error_text" msgid="6081085226050792095">"S\'ha produït un problema en carregar el widget"</string>
    <string name="uninstall_system_app_text" msgid="4172046090762920660">"Aquesta aplicació és una aplicació del sistema i no es pot desinstal·lar."</string>
    <string name="folder_hint_text" msgid="6617836969016293992">"Carpeta sense nom"</string>
    <string name="workspace_description_format" msgid="2950174241104043327">"Pantalla d\'inici %1$d"</string>
    <string name="default_scroll_format" msgid="7475544710230993317">"Pàgina %1$d de %2$d"</string>
    <string name="workspace_scroll_format" msgid="8458889198184077399">"Pantalla d\'inici %1$d de %2$d"</string>
    <string name="apps_customize_apps_scroll_format" msgid="370005296147130238">"Pàgina d\'aplicacions %1$d de %2$d"</string>
    <string name="apps_customize_widgets_scroll_format" msgid="3106209519974971521">"Pàgina de widgets %1$d de %2$d"</string>
    <string name="folder_opened" msgid="94695026776264709">"S\'ha obert la carpeta, <xliff:g id="WIDTH">%1$d</xliff:g> per <xliff:g id="HEIGHT">%2$d</xliff:g>"</string>
    <string name="folder_tap_to_close" msgid="1884479294466410023">"Toca per tancar la carpeta"</string>
    <string name="folder_tap_to_rename" msgid="9191075570492871147">"Toca per desar el canvi de nom"</string>
    <string name="folder_closed" msgid="4100806530910930934">"Carpeta tancada"</string>
    <string name="folder_renamed" msgid="1794088362165669656">"S\'ha canviat el nom de la carpeta a <xliff:g id="NAME">%1$s</xliff:g>"</string>
    <string name="folder_name_format" msgid="6629239338071103179">"Carpeta: <xliff:g id="NAME">%1$s</xliff:g>"</string>
    <string name="widget_button_text" msgid="2880537293434387943">"Widgets"</string>
    <string name="wallpaper_button_text" msgid="8404103075899945851">"Fons de pantalla"</string>
    <string name="settings_button_text" msgid="8119458837558863227">"Configuració"</string>
    <string name="application_copyright">Copyright \\u00A9 2015 Phonemetra</string>
    <string name="sort_button_text">Ordena</string>
    <string name="filter_button_text">Filtre</string>
    <string name="default_screen_button_text">Pantalla predeterminada</string>
    <string name="transition_effect_button_text">Efecte desplaçament</string>
    <string name="sort_mode_title">Títol</string>
    <string name="sort_mode_launch_count">Vegades executat</string>
    <string name="sort_mode_install_time">Hora d\'instal·lació</string>
    <string name="scrolling_page_outlines">Vores de la pàgina</string>
    <string name="scrolling_fade_adjacent">Esvaeix els costats de les pàgines</string>
    <string name="wallpaper_scroll">Desplaça el fons de pantalla</string>
    <string name="preferences_title">Configuració</string>
    <string name="preferences_application_title">App</string>
    <string name="preferences_interface_homescreen_title">Pantalla d\'inici</string>
    <string name="preferences_interface_homescreen_search_title">Barra de cerca</string>
    <string name="preferences_interface_homescreen_search_summary">Mostra sempre la barra de cerca a la  part superior de la pantalla</string>
    <string name="preferences_interface_homescreen_general_hide_icon_labels_title">Amaga les etiquetes de les icones</string>
    <string name="preferences_interface_homescreen_general_hide_icon_labels_summary">Amaga les etiquetes de les icones de la pantalla d\'inici</string>
    <string name="preferences_interface_drawer_title">Calaix</string>
    <string name="preferences_interface_drawer_summary">Calaix d\'apps i widgets</string>
    <string name="preferences_interface_drawer_apps_category">Apps</string>
    <string name="preferences_interface_drawer_hidden_apps_title">Apps amagades</string>
    <string name="preferences_interface_drawer_hidden_apps_summary">Amaga les apps del calaix</string>
    <string name="preferences_interface_drawer_hidden_apps_shortcuts_title">Treu les dreceres</string>
    <string name="preferences_interface_drawer_hidden_apps_shortcuts_summary">Treu les dreceres de les apps amagades de la pantalla d\'inici</string>
    <string name="preferences_interface_drawer_hidden_apps_widgets_title">Treu els widgets</string>
    <string name="preferences_interface_drawer_hidden_apps_widgets_summary">Treu els widgets de les apps amagades de la pantalla d\'inici</string>
    <string name="preferences_interface_drawer_hide_icon_labels_title">Amaga les etiquetes de les icones</string>
    <string name="preferences_interface_drawer_hide_icon_labels_summary">Amaga les etiquetes de les icones al calaix</string>
    <string name="preferences_interface_dock_title">Barra d\'aplicacions</string>
    <string name="preferences_interface_general_title">General</string>
    <string name="preferences_interface_general_icons_category">Icones</string>
    <string name="preferences_interface_general_icons_large_title">Icones més grans</string>
    <string name="preferences_interface_general_icons_large_summary">Utilitza icones d\'aplicació extra grans a la pantalla d\'inici i al calaix</string>
    <string name="preferences_interface_general_icons_text_style_title">Estil del tipus de lletra del text</string>
    <string name="preferences_interface_general_icons_text_style_summary">Variant i estil del tipus de lletra pel text de les icones</string>
    <string name="menu_hidden_apps_delete">Reinicia</string>
    <string name="hidden_apps_title">Apps amagades</string>
    <string name="launcher_settings">CONFIGURACIÓ DEL LLANÇADOR</string>
    <string name="home_screen_settings">CONFIGURACIÓ DE LA PANTALLA D\'INICI</string>
    <string name="drawer_settings">CONFIGURACIÓ DEL CALAIX</string>
    <string name="scroll_effect_text">Efecte desplaçament</string>
    <string name="drawer_sorting_text">Mode d\'ordenació</string>
    <string name="home_screen_search_text">Barra de cerca</string>
    <string name="larger_icons_text">Icones grans</string>
    <string name="hide_icon_labels">Amaga les etiquetes de les icones</string>
    <string name="setting_state_on">SÍ</string>
    <string name="setting_state_off">NO</string>
    <string name="themes_button_text">Temes</string>

</resources>


text:
module PgSearch
  class Railtie < Rails::Railtie
    rake_tasks do
      load "pg_search/tasks.rb"
    end

    generators do
      require "pg_search/migration/multisearch_generator"
      require "pg_search/migration/dmetaphone_generator"
      require "pg_search/migration/associated_against_generator"
    end
  end
end


text:
HERE = File.expand_path(File.dirname(__FILE__)) + '/'

require 'rake'
require 'rake/clean'
require 'rake/testtask'
require HERE+'rakefile_helper'

include RakefileHelpers

# Load default configuration, for now
DEFAULT_CONFIG_FILE = 'gcc_32.yml'
configure_toolchain(DEFAULT_CONFIG_FILE)

task :unit do
  run_tests get_unit_test_files
end

desc "Generate test summary"
task :summary do
  report_summary
end

desc "Build and test Unity"
task :all => [:clean, :unit, :summary]
task :default => [:clobber, :all]
task :ci => [:default]
task :cruise => [:default]

desc "Load configuration"
task :config, :config_file do |t, args|
  configure_toolchain(args[:config_file])
end


text:
namespace quic {
namespace test {

MockRandom::MockRandom() : base_(0xDEADBEEF), increment_(0) {}

MockRandom::MockRandom(uint32_t base) : base_(base), increment_(0) {}

void MockRandom::RandBytes(void* data, size_t len) {
  memset(data, increment_ + static_cast<uint8_t>('r'), len);
}

uint64_t MockRandom::RandUint64() {
  return base_ + increment_;
}

void MockRandom::ChangeValue() {
  increment_++;
}

}  // namespace test
}  // namespace quic


text:
require 'spec_helper'

require 'chef/osc_user'
require 'tempfile'

describe Chef::OscUser do
  before(:each) do
    @user = Chef::OscUser.new
  end

  describe "initialize" do
    it "should be a Chef::OscUser" do
      expect(@user).to be_a_kind_of(Chef::OscUser)
    end
  end

  describe "name" do
    it "should let you set the name to a string" do
      expect(@user.name("ops_master")).to eq("ops_master")
    end

    it "should return the current name" do
      @user.name "ops_master"
      expect(@user.name).to eq("ops_master")
    end

    # It is not feasible to check all invalid characters.  Here are a few
    # that we probably care about.
    it "should not accept invalid characters" do
      # capital letters
      expect { @user.name "Bar" }.to raise_error(ArgumentError)
      # slashes
      expect { @user.name "foo/bar" }.to raise_error(ArgumentError)
      # ?
      expect { @user.name "foo?" }.to raise_error(ArgumentError)
      # &
      expect { @user.name "foo&" }.to raise_error(ArgumentError)
    end

    it "should not accept spaces" do
      expect { @user.name "ops master" }.to raise_error(ArgumentError)
    end

    it "should throw an ArgumentError if you feed it anything but a string" do
      expect { @user.name Hash.new }.to raise_error(ArgumentError)
    end
  end

  describe "admin" do
    it "should let you set the admin bit" do
      expect(@user.admin(true)).to eq(true)
    end

    it "should return the current admin value" do
      @user.admin true
      expect(@user.admin).to eq(true)
    end

    it "should default to false" do
      expect(@user.admin).to eq(false)
    end

    it "should throw an ArgumentError if you feed it anything but true or false" do
      expect { @user.name Hash.new }.to raise_error(ArgumentError)
    end
  end

  describe "public_key" do
    it "should let you set the public key" do
      expect(@user.public_key("super public")).to eq("super public")
    end

    it "should return the current public key" do
      @user.public_key("super public")
      expect(@user.public_key).to eq("super public")
    end

    it "should throw an ArgumentError if you feed it something lame" do
      expect { @user.public_key Hash.new }.to raise_error(ArgumentError)
    end
  end

  describe "private_key" do
    it "should let you set the private key" do
      expect(@user.private_key("super private")).to eq("super private")
    end

    it "should return the private key" do
      @user.private_key("super private")
      expect(@user.private_key).to eq("super private")
    end

    it "should throw an ArgumentError if you feed it something lame" do
      expect { @user.private_key Hash.new }.to raise_error(ArgumentError)
    end
  end

  describe "when serializing to JSON" do
    before(:each) do
      @user.name("black")
      @user.public_key("crowes")
      @json = @user.to_json
    end

    it "serializes as a JSON object" do
      expect(@json).to match(/^\{.+\}$/)
    end

    it "includes the name value" do
      expect(@json).to include(%q{"name":"black"})
    end

    it "includes the public key value" do
      expect(@json).to include(%{"public_key":"crowes"})
    end

    it "includes the 'admin' flag" do
      expect(@json).to include(%q{"admin":false})
    end

    it "includes the private key when present" do
      @user.private_key("monkeypants")
      expect(@user.to_json).to include(%q{"private_key":"monkeypants"})
    end

    it "does not include the private key if not present" do
      expect(@json).not_to include("private_key")
    end

    it "includes the password if present" do
      @user.password "password"
      expect(@user.to_json).to include(%q{"password":"password"})
    end

    it "does not include the password if not present" do
      expect(@json).not_to include("password")
    end

    include_examples "to_json equivalent to Chef::JSONCompat.to_json" do
      let(:jsonable) { @user }
    end
  end

  describe "when deserializing from JSON" do
    before(:each) do
      user = { "name" => "mr_spinks",
        "public_key" => "turtles",
        "private_key" => "pandas",
        "password" => "password",
        "admin" => true }
      @user = Chef::OscUser.from_json(Chef::JSONCompat.to_json(user))
    end

    it "should deserialize to a Chef::OscUser object" do
      expect(@user).to be_a_kind_of(Chef::OscUser)
    end

    it "preserves the name" do
      expect(@user.name).to eq("mr_spinks")
    end

    it "preserves the public key" do
      expect(@user.public_key).to eq("turtles")
    end

    it "preserves the admin status" do
      expect(@user.admin).to be_truthy
    end

    it "includes the private key if present" do
      expect(@user.private_key).to eq("pandas")
    end

    it "includes the password if present" do
      expect(@user.password).to eq("password")
    end

  end

  describe "API Interactions" do
    before (:each) do
      @user = Chef::OscUser.new
      @user.name "foobar"
      @http_client = double("Chef::REST mock")
      allow(Chef::REST).to receive(:new).and_return(@http_client)
    end

    describe "list" do
      before(:each) do
        Chef::Config[:chef_server_url] = "http://www.example.com"
        @osc_response = { "admin" => "http://www.example.com/users/admin"}
        @ohc_response = [ { "user" => { "username" => "admin" }} ]
        allow(Chef::OscUser).to receive(:load).with("admin").and_return(@user)
        @osc_inflated_response = { "admin" => @user }
      end

      it "lists all clients on an OSC server" do
        allow(@http_client).to receive(:get_rest).with("users").and_return(@osc_response)
        expect(Chef::OscUser.list).to eq(@osc_response)
      end

      it "inflate all clients on an OSC server" do
        allow(@http_client).to receive(:get_rest).with("users").and_return(@osc_response)
        expect(Chef::OscUser.list(true)).to eq(@osc_inflated_response)
      end

      it "lists all clients on an OHC/OPC server" do
        allow(@http_client).to receive(:get_rest).with("users").and_return(@ohc_response)
        # We expect that Chef::OscUser.list will give a consistent response
        # so OHC API responses should be transformed to OSC-style output.
        expect(Chef::OscUser.list).to eq(@osc_response)
      end

      it "inflate all clients on an OHC/OPC server" do
        allow(@http_client).to receive(:get_rest).with("users").and_return(@ohc_response)
        expect(Chef::OscUser.list(true)).to eq(@osc_inflated_response)
      end
    end

    describe "create" do
      it "creates a new user via the API" do
        @user.password "password"
        expect(@http_client).to receive(:post_rest).with("users", {:name => "foobar", :admin => false, :password => "password"}).and_return({})
        @user.create
      end
    end

    describe "read" do
      it "loads a named user from the API" do
        expect(@http_client).to receive(:get_rest).with("users/foobar").and_return({"name" => "foobar", "admin" => true, "public_key" => "pubkey"})
        user = Chef::OscUser.load("foobar")
        expect(user.name).to eq("foobar")
        expect(user.admin).to eq(true)
        expect(user.public_key).to eq("pubkey")
      end
    end

    describe "update" do
      it "updates an existing user on via the API" do
        expect(@http_client).to receive(:put_rest).with("users/foobar", {:name => "foobar", :admin => false}).and_return({})
        @user.update
      end
    end

    describe "destroy" do
      it "deletes the specified user via the API" do
        expect(@http_client).to receive(:delete_rest).with("users/foobar")
        @user.destroy
      end
    end
  end
end


text:
require 'rails_helper'

RSpec.describe PostTag, type: :model do
  it { should belong_to(:post) }
  it { should belong_to(:tag) }
end


text:
typedef struct _material{
	int startIndex;
	int endIndex;
	int materialIndex;

	struct _material *next;
} material_t;

typedef struct _mesh {
	int vertexCount;
	int indexCount;
	float *vertices;
	int *indices;

	// a material will be set for a range of indices [a, b] so
	// the vertex data must be assembled with that in mind.

	// \/\/\/
	// or make multiple meshes with a single material

	material_t *materials;
} mesh_t;

typedef struct _model {
	mesh_t *mesh;
	void *animation_data;
} model_t;


text:
include (ExternalProject)

set(GRPC_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/grpc/src/grpc/include)
set(GRPC_URL https://github.com/grpc/grpc.git)
set(GRPC_BUILD ${CMAKE_CURRENT_BINARY_DIR}/grpc/src/grpc)
set(GRPC_TAG 781fd6f6ea03645a520cd5c675da67ab61f87e4b)

if(WIN32)
  set(grpc_STATIC_LIBRARIES
      ${CMAKE_CURRENT_BINARY_DIR}/grpc/src/grpc/Release/grpc++_unsecure.lib
      ${CMAKE_CURRENT_BINARY_DIR}/grpc/src/grpc/Release/grpc_unsecure.lib
      ${CMAKE_CURRENT_BINARY_DIR}/grpc/src/grpc/Release/gpr.lib)
else()
  set(grpc_STATIC_LIBRARIES
      ${CMAKE_CURRENT_BINARY_DIR}/grpc/src/grpc/libgrpc++_unsecure.a
      ${CMAKE_CURRENT_BINARY_DIR}/grpc/src/grpc/libgrpc_unsecure.a
      ${CMAKE_CURRENT_BINARY_DIR}/grpc/src/grpc/libgpr.a
      ${CMAKE_CURRENT_BINARY_DIR}/grpc/src/grpc/third_party/cares/libcares.a)
endif()

ExternalProject_Add(grpc
    PREFIX grpc
    DEPENDS protobuf zlib
    GIT_REPOSITORY ${GRPC_URL}
    GIT_TAG ${GRPC_TAG}
    DOWNLOAD_DIR "${DOWNLOAD_LOCATION}"
    BUILD_IN_SOURCE 1
    # TODO(jhseu): Remove this PATCH_COMMAND once grpc removes the dependency
    # on "grpc" from the "grpc++_unsecure" rule.
    PATCH_COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/patches/grpc/CMakeLists.txt ${GRPC_BUILD}
    BUILD_COMMAND ${CMAKE_COMMAND} --build . --config Release --target grpc++_unsecure
    COMMAND ${CMAKE_COMMAND} --build . --config Release --target grpc_cpp_plugin
    INSTALL_COMMAND ""
    CMAKE_CACHE_ARGS
        -DCMAKE_BUILD_TYPE:STRING=Release
        -DCMAKE_VERBOSE_MAKEFILE:BOOL=OFF
        -DPROTOBUF_INCLUDE_DIRS:STRING=${PROTOBUF_INCLUDE_DIRS}
        -DPROTOBUF_LIBRARIES:STRING=${protobuf_STATIC_LIBRARIES}
        -DZLIB_ROOT:STRING=${ZLIB_INSTALL}
	-DgRPC_SSL_PROVIDER:STRING=NONE
)

# grpc/src/core/ext/census/tracing.c depends on the existence of openssl/rand.h.
ExternalProject_Add_Step(grpc copy_rand
    COMMAND ${CMAKE_COMMAND} -E copy
    ${CMAKE_SOURCE_DIR}/patches/grpc/rand.h ${GRPC_BUILD}/include/openssl/rand.h
    DEPENDEES patch
    DEPENDERS build
)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.resources.generated;

import com.azure.core.util.Context;

/** Samples for Changes List. */
public final class ChangesListSamples {
    /*
     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2022-05-01/examples/ListChanges.json
     */
    /**
     * Sample code: ListChanges.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void listChanges(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .genericResources()
            .manager()
            .resourceChangeClient()
            .getChanges()
            .list("resourceGroup1", "resourceProvider1", "resourceType1", "resourceName1", null, null, Context.NONE);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Lichenologist 5(5-6): 454 (1973)

#### Original name
Hypogymnia tavaresii D. Hawksw. & P. James

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace MelloWeb
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseDefaultFiles();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            routes.MapRoute(
               name: "Default",
               template: "{*anything}", //Catch-all
               defaults: new { controller = "Home", action = "Index" }
             ));
        }
    }
}


text:
package org.onosproject.ui.topo;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.onosproject.net.Device;
import org.onosproject.net.Element;
import org.onosproject.net.Host;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.host.HostService;
import org.onosproject.ui.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import static com.google.common.base.Strings.isNullOrEmpty;
import static org.onosproject.net.DeviceId.deviceId;
import static org.onosproject.net.HostId.hostId;

/**
 * Encapsulates a selection of devices and/or hosts from the topology view.
 */
public class NodeSelection {

    private static final Logger log =
            LoggerFactory.getLogger(NodeSelection.class);

    private static final String IDS = "ids";
    private static final String HOVER = "hover";

    private final DeviceService deviceService;
    private final HostService hostService;

    private final Set<String> ids;
    private final String hover;

    private final Set<Device> devices = new HashSet<>();
    private final Set<Host> hosts = new HashSet<>();
    private Element hovered;

    /**
     * Creates a node selection entity, from the given payload, using the
     * supplied device and host services. Note that if a device or host was
     * hovered over by the mouse, it is available via {@link #hovered()}.
     *
     * @param payload message payload
     * @param deviceService device service
     * @param hostService host service
     */
    public NodeSelection(ObjectNode payload,
                         DeviceService deviceService,
                         HostService hostService) {
        this.deviceService = deviceService;
        this.hostService = hostService;

        ids = extractIds(payload);
        hover = extractHover(payload);

        // start by extracting the hovered element if any
        if (isNullOrEmpty(hover)) {
            hovered = null;
        } else {
            setHoveredElement();
        }

        // now go find the devices and hosts that are in the selection list
        Set<String> unmatched = findDevices(ids);
        unmatched = findHosts(unmatched);
        if (unmatched.size() > 0) {
            log.debug("Skipping unmatched IDs {}", unmatched);
        }

    }

    /**
     * Returns a view of the selected devices (hover not included).
     *
     * @return selected devices
     */
    public Set<Device> devices() {
        return Collections.unmodifiableSet(devices);
    }

    /**
     * Returns a view of the selected devices, including the hovered device
     * if there was one.
     *
     * @return selected (plus hovered) devices
     */
    public Set<Device> devicesWithHover() {
        Set<Device> withHover;
        if (hovered != null && hovered instanceof Device) {
            withHover = new HashSet<>(devices);
            withHover.add((Device) hovered);
        } else {
            withHover = devices;
        }
        return Collections.unmodifiableSet(withHover);
    }

    /**
     * Returns a view of the selected hosts (hover not included).
     *
     * @return selected hosts
     */
    public Set<Host> hosts() {
        return Collections.unmodifiableSet(hosts);
    }

    /**
     * Returns a view of the selected hosts, including the hovered host
     * if thee was one.
     *
     * @return selected (plus hovered) hosts
     */
    public Set<Host> hostsWithHover() {
        Set<Host> withHover;
        if (hovered != null && hovered instanceof Host) {
            withHover = new HashSet<>(hosts);
            withHover.add((Host) hovered);
        } else {
            withHover = hosts;
        }
        return Collections.unmodifiableSet(withHover);
    }

    /**
     * Returns the element (host or device) over which the mouse was hovering,
     * or null.
     *
     * @return element hovered over
     */
    public Element hovered() {
        return hovered;
    }

    /**
     * Returns true if nothing is selected.
     *
     * @return true if nothing selected
     */
    public boolean none() {
        return devices().size() == 0 && hosts().size() == 0;
    }

    @Override
    public String toString() {
        return "NodeSelection{" +
                "ids=" + ids +
                ", hover='" + hover + '\'' +
                ", #devices=" + devices.size() +
                ", #hosts=" + hosts.size() +
                '}';
    }

    // == helper methods

    private Set<String> extractIds(ObjectNode payload) {
        ArrayNode array = (ArrayNode) payload.path(IDS);
        if (array == null || array.size() == 0) {
            return Collections.emptySet();
        }

        Set<String> ids = new HashSet<>();
        for (JsonNode node : array) {
            ids.add(node.asText());
        }
        return ids;
    }

    private String extractHover(ObjectNode payload) {
        return JsonUtils.string(payload, HOVER);
    }

    private void setHoveredElement() {
        Set<String> unmatched;
        unmatched = new HashSet<>();
        unmatched.add(hover);
        unmatched = findDevices(unmatched);
        if (devices.size() == 1) {
            hovered = devices.iterator().next();
            devices.clear();
        } else {
            unmatched = findHosts(unmatched);
            if (hosts.size() == 1) {
                hovered = hosts.iterator().next();
                hosts.clear();
            } else {
                hovered = null;
                log.debug("Skipping unmatched HOVER {}", unmatched);
            }
        }
    }

    private Set<String> findDevices(Set<String> ids) {
        Set<String> unmatched = new HashSet<>();
        Device device;

        for (String id : ids) {
            try {
                device = deviceService.getDevice(deviceId(id));
                if (device != null) {
                    devices.add(device);
                } else {
                    unmatched.add(id);
                }
            } catch (Exception e) {
                unmatched.add(id);
            }
        }
        return unmatched;
    }

    private Set<String> findHosts(Set<String> ids) {
        Set<String> unmatched = new HashSet<>();
        Host host;

        for (String id : ids) {
            try {
                host = hostService.getHost(hostId(id));
                if (host != null) {
                    hosts.add(host);
                } else {
                    unmatched.add(id);
                }
            } catch (Exception e) {
                unmatched.add(id);
            }
        }
        return unmatched;
    }
}


text:
package japgolly.scalajs.benchmark.gui

import japgolly.scalajs.benchmark.gui.CssSettings._
import japgolly.univeq.UnivEq

object Styles extends StyleSheet.Inline {
  import dsl._

  val enabled = Domain.boolean.map(Enabled.when)
  val validity = Domain.boolean.map(Valid.when)

//  val cssReset = style(scalacss.ext.CssReset.normaliseCss)

  object Suite {

    val suiteName = style(
      fontSize(2 em),
      margin.vertical(0.8 em))

    val suiteDesc = style(
      maxWidth(90 %%),
      boxSizing.borderBox,
      marginBottom(1.5 em),
      padding(0.8 ex),
      border(solid, 1.px, black),
      backgroundColor(c"#d7ebff"),
      unsafeChild("code")(
        backgroundColor(c"#eee"),
        padding(1 px, 3 px),
        margin.horizontal(2 px),
        border(solid, 1 px, c"#bbb")))

    private val anyHeader = mixin(
      backgroundColor(c"#eee"))

    private val settingsCell = mixin(
      border(solid, 1.px, black),
      padding.vertical(1 ex))

    val settingsTable = style(
      borderCollapse.collapse,
      marginBottom(1 em))

    val settingsTableHeader = style(
      settingsCell,
      lineHeight(1.25 em),
      textAlign.right,
      padding.horizontal(2 ex),
      anyHeader)

    val settingsTableData = style(
      settingsCell,
      padding.horizontal(1 ex),
      textAlign.left)

    val settingsTableBm = style(
      display.block)

    val settingsTableBmLabel = style(
      fontWeight.normal,
      paddingLeft(0.3 ex))

    val etaRow = style(
      marginBottom(1 em),
    )

    val allBMsCheckbox = style(
      display.block,
      paddingBottom(0.3 em),
      marginBottom(0.3 em),
      borderBottom(1 px, solid, c"#ccc"),
    )

    val resultTable = style(
      borderCollapse.collapse)

    private val resultCell = mixin(
      border(solid, 1.px, black))

    val resultHeader = style(
      anyHeader,
      resultCell,
      textAlign.center,
      padding(v = 0.5 ex, h = 1 ex))

    val resultHeaderScore = style(
      resultHeader,
      minWidth(12 ex))

    val resultData = style(
      resultCell,
      padding(v = 0.2 ex, h = 1 ex))

    val preparing = style(
      color(c"#33c"))

    val running = style(
      color(c"#d40000"))

    val numericResult = style(
      textAlign.right,
      fontFamily :=! "monospace")

    def paramInt = numericResult

    val paramBool = style(
      textAlign.center)

    val paramEnumLabel = style(
      settingsTableBmLabel,
      display.block)

    val startButton = style(
      &.disabled(color(c"#aaa")))

    val runningRow = style(
      marginBottom(1 ex))

    val abortButton = style(
      marginLeft(2 ex))

    val doneRow = style(
      color(c"#060"),
      runningRow)

    def resetButton = abortButton

    val resultFormatRow = style(
      marginTop(.25 em),
      marginBottom(.75 em))

    val resultFormat = style(
      cursor.pointer,
      marginLeft(1.5 ex))

    private def graphWidth = 640 px

    val graphContainer = style(
      marginTop(3 em),
      // padding(1 em),
      // border(solid, 1 px, c"#d4d4d4"),
      width(graphWidth))

    val graphHeader = style(
      width(graphWidth),
      textAlign.center,
      color(c"#555"),
      fontFamily :=! "sans-serif",
      fontSize(0.9 em))

    val graph = style(
      width(graphWidth),
      height(720 px))

    import ReactChart._
    def graphInner(d: ScalaBarData): ScalaBarData = {
      /*
      // Using this totally-not-a-quick-hack effect will colour graph bars according to their value, green ↔ red
      import ReactChart.RGB
      import ReactChart.ColourByValue
      import ReactChart.ColourByValue.scaleFn
      val graphFX = Some(ColourByValue(
        fill = Some(scaleFn(RGB(32,255,32), RGB(255,32,32))),
        stroke = Some(scaleFn(RGB(0,92,0), RGB(92,0,0)))))
       */

      def styleDataset(d: ScalaDataset): ScalaDataset =
        d.copy(
          fillColor       = "#FFC870",
          strokeColor     = "#FFC870",
          highlightFill   = "#FDB45C",
          highlightStroke = "#FDB45C")

      d.copy(datasets = d.datasets.map(styleDataset))
    }
  }

  // ===================================================================================================================

  object Editors {

    val inputText = styleF(validity)(v => styleS(
      v match {
        case Valid   => styleS()
        case Invalid => styleS(
          outline.none,
          border(solid, 1 px, red),
          backgroundColor(c"#fff6f6"))
      }
    ))

    val engineOptionCnt = style(width(6.4 ex))
    val engineOptionDur = style(width(10.4 ex))
  }

  // ===================================================================================================================

  object TextOutput {

    val pre = style(
      border(solid, 1 px, c"#222"),
      color(c"#222"),
      backgroundColor(c"#ebfaff"),
      padding(1 ex),
      maxHeight :=! "calc(28em + 1ex)",
      overflow.auto,
      position.relative, // this block is the anchor to the buttons
    )

    val hiddenTextArea = style(
      position.absolute,
      zIndex(-1),
      opacity(0),
    )

    val buttons = style(
      position.absolute,
      top(`0`),
      right(`0`),
      display.flex,
      flexDirection.column,
      alignItems.flexEnd,
    )
  }

  // ===================================================================================================================

  object Menu {

    val topNav = style(
      width(100 %%),
      boxSizing.borderBox,
      padding(v = 1 ex, h = 2 ex),
      backgroundColor(c"#eee"))

    val topNavBreadcrumbSep = style(
      color(c"#888"),
      margin.horizontal(1 ex))

    val folder = style(
      marginTop(0.6 em),
      marginBottom(0.3 em))

    val folderUL = style(
      marginBottom(1.2 em))

    val folderLI = style(
      marginBottom(0.3 em))
  }

  // ===================================================================================================================

  object BatchMode {

    sealed trait Status {
      import Status._

      final def merge(s: Status): Status =
        (this, s) match {
          case (Disabled, x) => x
          case (x, Disabled) => x

          case (Done, x@(Pending | Preparing | Running | Incomplete | Done)) => x
          case (x@(Pending | Preparing | Running | Incomplete), Done) => x

          case (Pending, x@(Pending | Preparing | Running)) => x
          case (x@(Preparing | Running), Pending) => x

          case (Pending, Incomplete) => Incomplete
          case (Incomplete, Pending) => Incomplete

          case (Incomplete, x@(Incomplete | Preparing | Running)) => x
          case (x@(Preparing | Running), Incomplete) => x

          // These cases shouldn't happen in practice
          case (Running, Running | Preparing) => Running
          case (Preparing, Running)           => Running
          case (Preparing, Preparing)         => Preparing
        }
    }

    object Status {
      case object Disabled   extends Status
      case object Pending    extends Status
      case object Incomplete extends Status
      case object Preparing  extends Status
      case object Running    extends Status
      case object Done       extends Status

      val domain = Domain.ofValues[Status](
        Disabled,
        Pending,
        Incomplete,
        Preparing,
        Running,
        Done,
      )

      implicit def univEq: UnivEq[Status] = UnivEq.derive
    }

    private val menuSharedUL = styleS(
      lineHeight(1.5 em),
      listStyleType := "none")

    val root = style(
      display.flex)

    val controlsSection = style(
      paddingRight(4.8 rem))

    val controlTable = style(
      borderCollapse.collapse)

    def controlKey   = Suite.settingsTableHeader
    def controlValue = Suite.settingsTableData

    val controlFormat = style(
      lineHeight(1.5 em))

    def controlSaveMech = controlFormat

    val controlButtonRow = style(
      marginTop(2 em),
      textAlign.center)

    val controlButton = style(
      fontSize(120 %%),
      padding(0.4 em, 2 ex))

    val controlDownloadPrepButton = style(
      padding(0.4 em, 2 ex))

    val menuRootUL = style(
      menuSharedUL,
      paddingInlineStart(`0`))

    val menuUL = style(
      menuSharedUL,
      paddingInlineStart(3.6 ex))

    val menuLI = styleF(enabled)(e => styleS(
      mixinIf(e is Disabled)(color(c"#ccc"))))

    val runningItem = styleF(Status.domain)(s => styleS(
      display.inlineBlock,
      s match {
        case Status.Disabled   => styleS()
        case Status.Pending    => styleS()
        case Status.Incomplete => styleS(color(c"#7db2e8"))
        case Status.Preparing  => styleS(color(c"#ef9d06"), &.before(content.string("➜ ")))
        case Status.Running    => styleS(color(c"#ef9d06"), &.before(content.string("➜ ")))
        case Status.Done       => styleS(color(c"#008800"), &.before(content.string("✓ ")))
      }
    ))
  }

  // ===================================================================================================================

  initInnerObjects(
    Suite.resultTable,
    Editors.inputText(Valid),
    BatchMode.menuUL,
    Menu.topNav,
    TextOutput.pre,
  )
}


text:
<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Eventsadmin extends CI_Model
{

    public $table = 'events';
    /*public $table2 = 'event_info';*/

    public function get_by_id($id)
    {
        $this->db->from($this->table);
        $this->db->where('id', $id);
        $query = $this->db->get();
		$q = $query->row();
		$q->date = date("d/m/Y",strtotime($q->date));
		return $q;
    }

    function listEvents()
    {

	//select your colum as new column name wich is converted as str ot date

	 $this->db->where('date <>', '');
	 $this->db->order_by('date','ASC');
	 $q = $this->db->get('events')->result();

	 $this->db->where('date =', '');
	 $this->db->order_by('view_rank','ASC');
	 $q2 = $this->db->get('events')->result();

	 $q3=array_merge($q,$q2);

	 return $q3;
    }

    /*function getEventinfo()
    {

        $query = $this->db->get('event_info');
        return $query->row();
    }*/

    public function createEvent($data)
    {
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }

    public function event_update($where, $data)
    {
        $this->db->update($this->table, $data, $where);
        return $this->db->affected_rows();
    }
    /*public function event_info_update($data)
    {
        $this->db->update($this->table2, $data, "id = 1");
        return $this->db->affected_rows();
    }*/

    public function delete_by_id($id)
    {
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }
}


text:
/*  This is a container component. Notice it does not contain any JSX,
    nor does it import React. This component is **only** responsible for
    wiring in the actions and state necessary to render a presentational
    component - in this case, the counter:   */

import { connect } from 'react-redux'
import { toggleSideBar, navigate } from '../../../shared/components/Navigation/redux/actions';
import { bindActionCreators } from 'redux';

import { ProfileView } from '../views';
import CoreLayout from '../../../shared/layouts/CoreLayout';
import { callAPI } from '../../../shared';
import { updateUserProfile } from '../../../shared/redux/user/actions.js';

import {leaveGuild} from '../redux/actions.js';

function mapDispatchToProps(dispatch) {

    return {

        toggleSideBar: () => dispatch(toggleSideBar()),
        navigate: (newRoute = "/") => {
            dispatch(navigate(newRoute))
        },
        callAPI: (url, method) => {
            return dispatch(callAPI(url, method));
        },
        updateUserProfile: bindActionCreators(updateUserProfile, dispatch),
        leaveGuild: bindActionCreators(leaveGuild, dispatch)
    }
}

const mapStateToProps = (state) => ({
    state: state,
    user: state.shared.user
})

var ProfileContainer = connect(mapStateToProps, mapDispatchToProps)(ProfileView);

const ProfileRoute = {
    path: '/profile',
    component: CoreLayout,
    indexRoute: { component: ProfileContainer }
}

export { ProfileRoute }

export default ProfileContainer


text:
project_id = attribute('project_id', description:'GCP project id')
location = attribute("location", description:'GCP location')
sa_name = attribute("prometheus_sa_name")
k8s_ns = attribute("prometheus_k8s_ns")
k8s_sa = attribute("prometheus_k8s_sa")

control 'prometheus-1' do
  impact 1.0

  title 'Ensure service account and IAM binding exists'

  tag platform: "GCP"
  tag category: 'Service'
  tag resource: "Prometheus"
  tag effort: 0.2

  describe google_service_account(project: project_id, name: sa_name) do
    it { should exist }
    its('display_name') { should cmp 'prometheus' }
  end

  describe google_project_iam_binding(project: project_id, role: "roles/compute.instanceAdmin.v1") do
    it { should exist }
    its('members') { should include 'serviceAccount:' + sa_name}
  end

  # How test that ?
  # describe google_service_account_iam_binding(project: project_id, role: "roles/iam.workloadIdentityUser") do
  #   it { should exist }
  #   its('members') { should include 'serviceAccount:' + project_id + ".svc.id.goog[" + k8s_ns + "/" + k8s_sa + "]"}
  # end

end


text:
import socket

import config
import h264decode

import common.AirPlayHandler
import mirror.Packet
import mirror.Cryptor

class MirrorService(common.AirPlayHandler.FPLYHandler):
	protocol_version = "HTTP/1.1"
	decoder_cls = h264decode.Decoder

	def do_GET(self):
		if self.path == "/stream.xml" and self.checkAuth():
			self.sendCapabilities()

	def do_POST(self):
		common.AirPlayHandler.FPLYHandler.do_POST(self)
		if self.path == "/stream":
			self.receiveStream()

	def receiveStream(self):
		self.streamInfo = self.readPlist()
		if 'param1' in self.streamInfo and 'param2' in self.streamInfo:
			aesKey = self.fply.decrypt(self.streamInfo['param1'])
			aesIV = self.streamInfo['param2']
			self.cryptor = mirror.Cryptor.Cryptor(aesKey, aesIV)
		else:
			self.log_message("Client doesn't want to encrypt stream. Skipping AES")
			self.cryptor = mirror.Cryptor.EchoCryptor()

		self.frameSinks = []
		self.log_message("Get Stream info: %r", self.streamInfo)
		self.log_message("Switching to stream packet mode")
		self.handle_one_request = self.parseStreamPacket

	def closeConnection(self):
		self.log_message("Closing connection")
		self.close_connection = 1
		self.frameSinks = []

	def parseStreamPacket(self):
		try:
			packet = mirror.Packet.Packet(self.rfile)
		except IOError:
			return self.closeConnection() # TODO: Really?
		except EOFError:
			return self.closeConnection()
		except socket.timeout, e:
			self.log_error("Request timed out: %r", e)
			return self.closeConnection()
		self.handlePacket(packet)

	def handlePacket(self, packet):
		if packet.payloadType == mirror.Packet.TYPE_VIDEO:
			decryptedH264Packet = self.cryptor.decrypt(packet.data)
			frame = self.decoder.decodeFrame(decryptedH264Packet)
			if frame:
				for sink in self.frameSinks:
					sink.handle(frame, packet.timestamp)

		elif packet.payloadType == mirror.Packet.TYPE_CODECDATA:
			self.decoder = self.decoder_cls(packet.data)
			self.frameSinks = [cls(self.streamInfo, self.clientName) \
									for cls in config.selectedSinks]

	def sendCapabilities(self):
		self.log_message("Sending capabilities")
		self.clientName = self.headers.getheader('X-Apple-Client-Name')
		self.clientProtocolVersion = self.headers.getheader('X-Apple-ProtocolVersion')
		self.sendPList(config.default_capabilities)


text:
// The MIT License(MIT)
//
// Copyright(c) 2015-2017 Ripcord Software Ltd
//
// 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.

using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;

using Xunit;
using Moq;

using RipcordSoftware.HttpWebClient;

namespace HttpWebClient.UnitTests
{
    [ExcludeFromCodeCoverage]
    public class TestHttpWebClientChunkedResponseStream
    {
        private const string TestChunkedText = "16\r\nhello worldhello world\r\nB\r\nhello world\r\n0\r\n\r\n";
        private static readonly byte[] _textChunkedBytes = Encoding.ASCII.GetBytes(TestChunkedText);

        [Fact]
        public void TestInitializedHttpWebClientChunkedResponseStream()
        {
            var socket = new MemoryStreamSocket();
            var memStream = new MemoryStream();

            using (var responseStream = new HttpWebClientResponseStream(socket, memStream))
            {
                using (var stream = new HttpWebClientChunkedResponseStream(responseStream))
                {
                    Assert.True(stream.CanRead);
                    Assert.False(stream.CanWrite);
                    Assert.False(stream.CanSeek);
                    Assert.False(stream.CanTimeout);
                    Assert.Equal(0, stream.Length);
                    Assert.Equal(0, stream.Position);
                    Assert.Equal(0, stream.Available);
                    Assert.Equal(0, stream.SocketAvailable);
                    Assert.Equal(0, stream.BufferAvailable);
                    Assert.Equal(0, stream.Read(new byte[256], 0, 256));
                    Assert.Equal(-1, stream.ReadByte());
                    Assert.Equal(0, stream.SocketReceive(new byte[256], 0, 256));

                    Assert.Throws<NotImplementedException>(() => stream.Seek(100, SeekOrigin.End));
                    Assert.Throws<NotImplementedException>(() => stream.SetLength(1024));
                    Assert.Throws<NotImplementedException>(() => stream.Write(new byte[256], 0, 256));
                    Assert.Throws<NotImplementedException>(() => { stream.Position = 1024; });
                }
            }
        }

        [Fact]
        public void TestHttpWebClientChunkedResponseStreamRead()
        {
            var socket = new MemoryStreamSocket();
            var memStream = new MemoryStream(_textChunkedBytes);

            using (var responseStream = new HttpWebClientResponseStream(socket, memStream))
            {
                using (var stream = new HttpWebClientChunkedResponseStream(responseStream))
                {
                    Assert.Equal(0, stream.Length);
                    Assert.Equal(0, stream.Position);
                    Assert.Equal(_textChunkedBytes.Length, stream.Available);
                    Assert.Equal(0, stream.SocketAvailable);
                    Assert.Equal(_textChunkedBytes.Length, stream.BufferAvailable);
                    Assert.Equal(22, stream.Read(new byte[256], 0, 256));
                    Assert.Equal(11, stream.Read(new byte[256], 0, 256));
                    Assert.Equal(-1, stream.ReadByte());
                    Assert.Equal(0, stream.SocketReceive(new byte[256], 0, 256));
                }
            }
        }
    }
}


text:
require 'spec_helper'

describe Admin::TagsController do
  let!(:blog) { create(:blog) }
  let!(:user) { create(:user, login: 'henri', profile: create(:profile_admin)) }

  before { request.session = { user: user.id } }

  describe 'index' do
    before(:each) { get :index }
    it { expect(response).to redirect_to(action: 'new') }
  end

  context "with a tag" do
    let(:tag) { create(:tag) }

    describe 'edit' do
      before(:each) { get :edit, id: tag.id }

      it { expect(response).to be_success }
      it { expect(response).to render_template('new') }
      it { expect(assigns(:tag)).to be_valid }
    end

    describe 'destroy' do
      context "with a get" do
        before(:each) { get :destroy, id: tag.id }

        it { expect(response).to be_success }
        it { expect(response).to render_template('destroy') }
        it { expect(assigns(:record)).to be_valid }

        context "with view" do
          render_views
          it { expect(response.body).to have_selector("form[action='/admin/tags/destroy/#{tag.id}'][method='post']") }
        end
      end

      context "with a post" do
        before(:each) { post :destroy, id: tag.id, tag: {display_name: 'Foo Bar'}}
        it { expect(response).to redirect_to(action: 'index') }
        it { expect(Tag.count).to eq(0) }
      end
    end

    describe 'update' do
      before(:each) { post :edit, id: tag.id, tag: {display_name: 'Foo Bar'} }
      it { expect(response).to be_success }
      it { expect(tag.reload.name).to eq('foo-bar') }
      it { expect(tag.reload.display_name).to eq('Foo Bar') }
      it { expect(Redirect.count).to eq(1) }
      it { expect(Redirect.first.to_path).to eq('/tag/foo-bar') }
    end
  end
end


text:
<?php

// Bootstrap
try {
    // Step 1: init autoloader

    $autoloadFiles = [__DIR__ . '/../vendor/autoload.php',
                           __DIR__ . '/../../../autoload.php'];

    $found = false;
    foreach ($autoloadFiles as $autoloadFile) {
        if (file_exists($autoloadFile)) {
            $found = true;
            require_once $autoloadFile;
            break;
        }
    }
    if (!$found) {
        throw new \Exception('Cannot find composer vendor autoload, run composer update');
    }
} catch (\Exception $e) {
    echo $e->getMessage() . "\n";
    exit(1);
}

$cli = new Symfony\Component\Console\Application('pjb-server console', '2.0.0');
$cli->setCatchExceptions(true);

$commandRepo = new \PjbServer\Tools\Console\CommandRepository();

$cli->addCommands($commandRepo->getRegisteredCommands());

// helpers
$helpers = [
    'question' => new Symfony\Component\Console\Helper\QuestionHelper(),
];
foreach ($helpers as $name => $helper) {
    $cli->getHelperSet()->set($helper, $name);
}

$cli->run();


text:
<?php

namespace Omnipay\Vindicia\Message;

use Omnipay\Common\Exception\InvalidCreditCardException;
use Omnipay\Common\Message\ResponseInterface;
use Omnipay\Vindicia\TestableSoapClient;
use Omnipay\Vindicia\VindiciaItemBag;
use Omnipay\Vindicia\AttributeBag;
use Omnipay\Vindicia\NameValue;
use Omnipay\Vindicia\PriceBag;
use Omnipay\Common\Exception\InvalidRequestException;
use PaymentGatewayLogger\Event\Constants;
use PaymentGatewayLogger\Event\ErrorEvent;
use PaymentGatewayLogger\Event\RequestEvent;
use PaymentGatewayLogger\Event\ResponseEvent;
use SoapFault;
use stdClass;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request as HttpRequest;
use Guzzle\Http\ClientInterface;
use InvalidArgumentException;
use Omnipay\Common\CreditCard;
use Omnipay\Vindicia\NonStrippingCreditCard;

/**
 * Vindicia Abstract Request
 */
abstract class AbstractRequest extends \Omnipay\Common\Message\AbstractRequest
{
    /**
     * True if this is the update version of a request rather than the create
     * version. (They're essentially the same but some validation logic is
     * slightly different.
     *
     * @var bool
     */
    protected $isUpdate;

    /**
     * @var EventDispatcherInterface|null
     */
    protected $eventDispatcher;

    const API_VERSION = '18.0';
    const LIVE_ENDPOINT = 'https://soap.vindicia.com';
    const TEST_ENDPOINT = 'https://soap.staging.us-west.vindicia.com';

    const VINDICIA_EXPIRATION_DATE_FORMAT = 'Ym';

    /**
     * Object names used in the Vindicia API
     */
    /**
     * @var string
     */
    protected static $TRANSACTION_OBJECT = 'Transaction';
    /**
     * @var string
     */
    protected static $SUBSCRIPTION_OBJECT = 'AutoBill';
    /**
     * @var string
     */
    protected static $CUSTOMER_OBJECT = 'Account';
    /**
     * @var string
     */
    protected static $PAYMENT_METHOD_OBJECT = 'PaymentMethod';
    /**
     * @var string
     */
    protected static $REFUND_OBJECT = 'Refund';
    /**
     * @var string
     */
    protected static $CHARGEBACK_OBJECT = 'Chargeback';
    /**
     * @var string
     */
    protected static $PLAN_OBJECT = 'BillingPlan';
    /**
     * @var string
     */
    protected static $PRODUCT_OBJECT = 'Product';
    /**
     * @var string
     */
    protected static $WEB_SESSION_OBJECT = 'WebSession';

    /**
     * Default amount of time to wait for connection or response, in seconds
     *
     * @var int
     */
    const DEFAULT_TIMEOUT = 120;

    /**
     * Default tax classification for products.
     *
     * @var string
     */
    const DEFAULT_TAX_CLASSIFICATION = 'TaxExempt';

    /**
     * Payment method types
     *
     * @var string
     */
    const PAYMENT_METHOD_PAYPAL = 'PayPal';
    const PAYMENT_METHOD_APPLE_PAY = 'ApplePay';
    const PAYMENT_METHOD_CREDIT_CARD = 'CreditCard';

    /**
     * If chargeback probability from risk scoring is greater than this,
     * the transaction will fail. By default, every transaction will
     * succeed.
     *
     * @var int
     */
    const DEFAULT_MIN_CHARGEBACK_PROBABILITY = 100;

    /**
     * The class to use for the response.
     *
     * @var string
     */
    protected static $RESPONSE_CLASS = '\Omnipay\Vindicia\Message\Response';

    /**
     * Create a new Request
     *
     * @param ClientInterface $httpClient  A Guzzle client to make API calls with
     * @param HttpRequest     $httpRequest A Symfony HTTP request object
     * @param bool            $isUpdate    True if this is an update request rather than a create (default false)
     */
    public function __construct(ClientInterface $httpClient, HttpRequest $httpRequest, $isUpdate = false)
    {
        parent::__construct($httpClient, $httpRequest);

        $this->isUpdate = $isUpdate;

        // Used to fire events before and after executing a request.
        $this->eventDispatcher = $httpClient->getEventDispatcher();
    }

    /**
     * Initialize request with parameters.
     * For new products, the default tax classification is Tax Exempt
     *
     * @param array<string, mixed> $parameters
     * @return static
     */
    public function initialize(array $parameters = array())
    {
        if (!array_key_exists('timeout', $parameters)) {
            $parameters['timeout'] = self::DEFAULT_TIMEOUT;
        }
        if (!$this->isUpdate() && !array_key_exists('taxClassification', $parameters)) {
            $parameters['taxClassification'] = self::DEFAULT_TAX_CLASSIFICATION;
        }

        parent::initialize($parameters);

        return $this;
    }

    /**
     * @return null|string
     */
    public function getUsername()
    {
        return $this->getParameter('username');
    }

    /**
     * @param string $value
     * @return static
     */
    public function setUsername($value)
    {
        return $this->setParameter('username', $value);
    }

    /**
     * @return null|string
     */
    public function getPassword()
    {
        return $this->getParameter('password');
    }

    /**
     * @param string $value
     * @return static
     */
    public function setPassword($value)
    {
        return $this->setParameter('password', $value);
    }

    /**
     * @return null|string
     */
    public function getIp()
    {
        return $this->getParameter('ip');
    }

    /**
     * @return static
     */
    public function setIp($value)
    {
        return $this->setParameter('ip', $value);
    }

    /**
     * @return null|string
     */
    public function getCustomerId()
    {
        return $this->getParameter('customerId');
    }

    /**
     * @return static
     */
    public function setCustomerId($value)
    {
        return $this->setParameter('customerId', $value);
    }

    /**
     * @return null|string
     */
    public function getCustomerReference()
    {
        return $this->getParameter('customerReference');
    }

    /**
     * @return static
     */
    public function setCustomerReference($value)
    {
        return $this->setParameter('customerReference', $value);
    }

    /**
     * Gets the customer's name
     *
     * @return null|string
     */
    public function getName()
    {
        return $this->getParameter('name');
    }

    /**
     * Sets the customer's name
     *
     * @param string $value
     * @return static
     */
    public function setName($value)
    {
        return $this->setParameter('name', $value);
    }

    /**
     * Gets the customer's email
     *
     * @return null|string
     */
    public function getEmail()
    {
        return $this->getParameter('email');
    }

    /**
     * Sets the customer's email
     *
     * @param string $value
     * @return static
     */
    public function setEmail($value)
    {
        return $this->setParameter('email', $value);
    }

    /**
     * @return null|string
     */
    public function getRefundId()
    {
        return $this->getParameter('refundId');
    }

    /**
     * @return static
     */
    public function setRefundId($value)
    {
        return $this->setParameter('refundId', $value);
    }

    /**
     * @return null|string
     */
    public function getPaymentMethodId()
    {
        return $this->getParameter('paymentMethodId');
    }

    /**
     * @return static
     */
    public function setPaymentMethodId($value)
    {
        return $this->setParameter('paymentMethodId', $value);
    }

    /**
     * @return null|string
     */
    public function getPaymentMethodReference()
    {
        return $this->getParameter('paymentMethodReference');
    }

    /**
     * @return static
     */
    public function setPaymentMethodReference($value)
    {
        return $this->setParameter('paymentMethodReference', $value);
    }

    /**
     * @return null|string
     */
    public function getTaxClassification()
    {
        return $this->getParameter('taxClassification');
    }

    /**
     * @return null|string
     */
    public function getSubscriptionId()
    {
        return $this->getParameter('subscriptionId');
    }

    /**
     * @return static
     */
    public function setSubscriptionId($value)
    {
        return $this->setParameter('subscriptionId', $value);
    }

    /**
     * @return null|string
     */
    public function getSubscriptionReference()
    {
        return $this->getParameter('subscriptionReference');
    }

    /**
     * @return static
     */
    public function setSubscriptionReference($value)
    {
        return $this->setParameter('subscriptionReference', $value);
    }

    /**
     * @return null|string
     */
    public function getPlanId()
    {
        return $this->getParameter('planId');
    }

    /**
     * @return static
     */
    public function setPlanId($value)
    {
        return $this->setParameter('planId', $value);
    }

    /**
     * @return null|string
     */
    public function getPlanReference()
    {
        return $this->getParameter('planReference');
    }

    /**
     * @return static
     */
    public function setPlanReference($value)
    {
        return $this->setParameter('planReference', $value);
    }

    /**
     * @return null|string
     */
    public function getProductId()
    {
        return $this->getParameter('productId');
    }

    /**
     * @return int
     */
    public function getQuantity()
    {
        return $this->getParameter('quantity');
    }

    /**
     * @return static
     */
    public function setQuantity($value)
    {
        return $this->setParameter('quantity', $value);
    }

    /**
     * @return static
     */
    public function setProductId($value)
    {
        return $this->setParameter('productId', $value);
    }

    /**
     * @return null|string
     */
    public function getProductReference()
    {
        return $this->getParameter('productReference');
    }

    /**
     * @return static
     */
    public function setProductReference($value)
    {
        return $this->setParameter('productReference', $value);
    }

    /**
     * Returns the invoice reference
     *
     * @return null|string
     */
    public function getInvoiceReference()
    {
        return $this->getParameter('invoiceReference');
    }

    /**
     * Sets the invoice reference
     *
     * @param string $value
     * @return static
     */
    public function setInvoiceReference($value)
    {
        return $this->setParameter('invoiceReference', $value);
    }

    /**
     * @return static
     */
    public function setTaxClassification($value)
    {
        return $this->setParameter('taxClassification', $value);
    }

    /**
     * Set the items in this order
     *
     * @param VindiciaItemBag|array $items
     * @return static
     */
    public function setItems($items)
    {
        if ($items && !$items instanceof VindiciaItemBag) {
            $items = new VindiciaItemBag($items);
        }

        return $this->setParameter('items', $items);
    }

    /**
     * A list of attributes
     *
     * @return AttributeBag|null
     */
    public function getAttributes()
    {
        return $this->getParameter('attributes');
    }

    /**
     * Set the attributes in this order
     *
     * @param AttributeBag|array $attributes
     * @return static
     */
    public function setAttributes($attributes)
    {
        if ($attributes && !$attributes instanceof AttributeBag) {
            $attributes = new AttributeBag($attributes);
        }

        return $this->setParameter('attributes', $attributes);
    }

    /**
     * Get amount of time to wait for connection or response, in seconds
     *
     * @return null|int
     */
    public function getTimeout()
    {
        return $this->getParameter('timeout');
    }

    /**
     * Set amount of time to wait for connection or response, in seconds
     *
     * @param int $value
     * @return static
     */
    public function setTimeout($value)
    {
        return $this->setParameter('timeout', $value);
    }

    /**
     * Get the billing day
     *
     * @return null|int
     */
    public function getBillingDay()
    {
        return $this->getParameter('billingDay');
    }

    /**
     * Set the billing day
     *
     * @param int $value
     * @return static
     */
    public function setBillingDay($value)
    {
        return $this->setParameter('billingDay', $value);
    }

    /**
     * Get the start time.
     *
     * @return null|string
     */
    public function getStartTime()
    {
        return $this->getParameter('startTime');
    }

    /**
     * Set the start time. Takes a date/timestamp string, such as
     * "2016-06-02T12:30:00-04:00" (June 2, 2016 @ 12:30 PM, GMT - 4 hours)
     * Use varies depending on request. May be used to specify the start time
     * of a subscription or a range of objects to fetch.
     *
     * @param string $value
     * @return static
     */
    public function setStartTime($value)
    {
        return $this->setParameter('startTime', $value);
    }

    /**
     * Get the end time.
     *
     * @return null|string
     */
    public function getEndTime()
    {
        return $this->getParameter('endTime');
    }

    /**
     * Set the end time. Takes a date/timestamp string, such as
     * "2016-06-02T12:30:00-04:00" (June 2, 2016 @ 12:30 PM, GMT - 4 hours)
     * Used to specify the end time of a range of objects to fetch.
     *
     * @param string $value
     * @return static
     */
    public function setEndTime($value)
    {
        return $this->setParameter('endTime', $value);
    }

    /**
     * Gets the description shown on the customers billing statement from the bank
     *
     * @return null|string
     */
    public function getStatementDescriptor()
    {
        return $this->getParameter('statementDescriptor');
    }

    /**
     * Sets the description shown on the customers billing statement from the bank
     * This field's value and its format are constrained by your payment processor;
     * consult with Vindicia Client Services before setting the value.
     *
     * @param string $value
     * @return static
     */
    public function setStatementDescriptor($value)
    {
        return $this->setParameter('statementDescriptor', $value);
    }

    /**
     * Get the redirect url that the customer will be sent to after
     * HOA completes.
     *
     * @return null|string
     */
    public function getReturnUrl()
    {
        /**
         * @var null|string
         */
        return parent::getReturnUrl();
    }

    /**
     * Set the redirect url that the customer will be sent to after
     * HOA or a PayPal purchase completes.
     *
     * @param string $value
     * @return static
     */
    public function setReturnUrl($value)
    {
        /**
         * @var static
         */
        return parent::setReturnUrl($value);
    }

    /**
     * Get minimum chargeback probability.
     * If chargeback probability from risk scoring is greater than the
     * this value, the transaction will fail. If the value is 100,
     * all transactions will succeed.
     *
     * @return null|int
     */
    public function getMinChargebackProbability()
    {
        return $this->getParameter('minChargebackProbability');
    }

    /**
     * Set minimum chargeback probability.
     * If chargeback probability from risk scoring is greater than the
     * set value, the transaction will fail. If the value is 100,
     * all transactions will succeed.
     *
     * @param int $value
     * @return static
     */
    public function setMinChargebackProbability($value)
    {
        return $this->setParameter('minChargebackProbability', $value);
    }

    /**
     * Get the redirect url that will be used in the case of a cancel from PayPal's site.
     *
     * @return null|string
     */
    public function getCancelUrl()
    {
        /**
         * @var null|string
         */
        return parent::getCancelUrl();
    }

    /**
     * Set the redirect url that will be used in the case of a cancel from PayPal's site.
     *
     * @param string $value
     * @return static
     */
    public function setCancelUrl($value)
    {
        /**
         * @var static
         */
        return parent::setCancelUrl($value);
    }
    /**
     * Gets whether PayPal redirected the customer to your success page. If false, they
     * were redirected to the error page.
     *
     * @return null|bool
     */
    public function getSuccess()
    {
        return $this->getParameter('success');
    }

    /**
     * Sets whether PayPal redirected the customer to your success page. Set to false
     * if they were redirected to the error page.
     *
     * @param bool $value
     * @return static
     */
    public function setSuccess($value)
    {
        return $this->setParameter('success', $value);
    }

    /**
     * Gets the identifier generated by the gateway to represent the underlying
     * PayPal transaction.
     *
     * @return null|string
     */
    public function getPayPalTransactionReference()
    {
        return $this->getParameter('payPalTransactionReference');
    }

    /**
     * Sets the identifier generated by the gateway to represent the underlying
     * PayPal transaction.
     *
     * @param string $value
     * @return static
     */
    public function setPayPalTransactionReference($value)
    {
        return $this->setParameter('payPalTransactionReference', $value);
    }

    /**
     * A list of prices (currency and amount)
     *
     * @return null|PriceBag|null
     */
    public function getPrices()
    {
        return $this->getParameter('prices');
    }

    /**
     * Set the prices (currency and amount)
     * If you only need a price for one currency, you can also use setAmount and setCurrency.
     *
     * @param PriceBag|array $prices
     * @return static
     * @throws InvalidPriceBagException if multiple prices have the same currency
     */
    public function setPrices($prices)
    {
        if ($prices && !$prices instanceof PriceBag) {
            $prices = new PriceBag($prices);
        }

        return $this->setParameter('prices', $prices);
    }

    /**
     * Redefining to correct return type
     *
     * @return null|\Omnipay\Common\CreditCard
     */
    public function getCard()
    {
        /**
         * @var null|\Omnipay\Common\CreditCard
         */
        return parent::getCard();
    }

    /**
     * Redefining to correct return type
     *
     * @return null|bool
     */
    public function getTestMode()
    {
        /**
         * @var null|bool
         */
        return parent::getTestMode();
    }

    /**
     * Redefining to correct return type
     *
     * @return null|string
     */
    public function getAmount()
    {
        /**
         * @var null|string
         */
        return parent::getAmount();
    }

    /**
     * Redefining to correct return type
     *
     * @return null|string
     */
    public function getCurrency()
    {
        /**
         * @var null|string
         */
        return parent::getCurrency();
    }

    /**
     * Redefining to correct return type
     *
     * @return null|string
     */
    public function getDescription()
    {
        /**
         * @var null|string
         */
        return parent::getDescription();
    }

    /**
     * Redefining to correct return type
     *
     * @return null|string
     */
    public function getTransactionId()
    {
        /**
         * @var null|string
         */
        return parent::getTransactionId();
    }

    /**
     * Redefining to correct return type
     *
     * @return null|string
     */
    public function getTransactionReference()
    {
        /**
         * @var null|string
         */
        return parent::getTransactionReference();
    }

    /**
     * Gets the ApplePayPaymentToken received from the parsed ApplePayPayment object.
     *
     * @return array|null
     */
    public function getApplePayToken()
    {
        return $this->getParameter('applePayToken');
    }

    /**
     * The object type on which the API call will be made
     *
     * @return string
     */
    abstract protected function getObject();

    /**
     * The name of the function to be called in Vindicia's API
     *
     * @return string
     */
    abstract protected function getFunction();

    /**
     * @return string
     */
    final protected function getEndpoint()
    {
        return ($this->getTestMode() === false ? self::LIVE_ENDPOINT : self::TEST_ENDPOINT)
               . '/'
               . self::API_VERSION
               . '/'
               . $this->getObject()
               . '.wsdl';
    }

    /**
     * @param array $data
     *
     * @return ResponseInterface
     * @throws SoapFault
     */
    public function sendData($data)
    {
        $originalWsdlCacheEnabled = ini_get('soap.wsdl_cache_enabled');
        $originalWsdlCacheTtl = ini_get('soap.wsdl_cache_ttl');
        $originalSocketTimeout = ini_get('default_socket_timeout');
        ini_set('soap.wsdl_cache_enabled', 1);
        ini_set('soap.wsdl_cache_ttl', 3600);
        $timeout = $this->getTimeout();
        if ($timeout !== null) {
            ini_set('default_socket_timeout', $timeout);
        }

        $data['srd'] = '';

        $auth = new stdClass();
        $auth->version = self::API_VERSION;
        $auth->login = $this->getUsername();
        $auth->password = $this->getPassword();
        $auth->evid = null;
        $auth->userAgent = null;
        $data['auth'] = $auth;

        $action = $data['action'];
        unset($data['action']);

        $params = array();
        $params['parameters'] = $data;

        if ($this->eventDispatcher) {
            // Log the request before it is sent.
            $this->eventDispatcher->dispatch(Constants::OMNIPAY_REQUEST_BEFORE_SEND, new RequestEvent($this));
        }

        try {
            $client = new TestableSoapClient(
                $this->getEndpoint(),
                array(
                    'style'              => SOAP_DOCUMENT,
                    'use'                => SOAP_LITERAL,
                    'connection_timeout' => $timeout,
                    'trace'              => true,
                    'features'           => SOAP_SINGLE_ELEMENT_ARRAYS,
                    'location'           => ($this->getTestMode() === false ? self::LIVE_ENDPOINT : self::TEST_ENDPOINT)
                                            . '/v'
                                            . self::API_VERSION
                                            . '/soap.pl'
                )
            );
            $response = $client->__soapCall($action, $params);
        } catch (SoapFault $exception) {
            if ($this->eventDispatcher) {
                // Log any errors.
                $this->eventDispatcher->dispatch(
                    Constants::OMNIPAY_REQUEST_ERROR,
                    new ErrorEvent($exception, $this)
                );
            }

            throw $exception;
        }
        // reset to how they were before
        ini_set('soap.wsdl_cache_enabled', $originalWsdlCacheEnabled);
        ini_set('soap.wsdl_cache_ttl', $originalWsdlCacheTtl);
        ini_set('default_socket_timeout', $originalSocketTimeout);

        $this->response = new static::$RESPONSE_CLASS($this, $response);
        if ($this->eventDispatcher) {
            // Log successful request responses.
            $this->eventDispatcher->dispatch(Constants::OMNIPAY_RESPONSE_SUCCESS, new ResponseEvent($this->response));
        }

        return $this->response;
    }

    /**
     * Overriding to provide a more precise return type
     * @return Response
     */
    public function send()
    {
        /**
         * @var Response
         */
        return parent::send();
    }

    /**
     * Returns true if this is an update call, false if it's a create call
     *
     * @return bool
     */
    protected function isUpdate()
    {
        return $this->isUpdate;
    }

    /**
     * Helper function to make a Vindicia transaction object.
     * Set $validateCard to false to skip card validation.
     *
     * @param string $paymentMethodType default null
     *
     * @return stdClass
     * @throws InvalidRequestException
     * @throws InvalidCreditCardException If unable to build the payment method specified by $paymentMethodType.
     */
    protected function buildTransaction($paymentMethodType = null)
    {
        $account = new stdClass();
        // doesn't work if account isn't created, id must be passed in :-(
        $account->merchantAccountId = $this->getCustomerId();
        $account->VID = $this->getCustomerReference();
        $account->name = $this->getName();
        $account->emailAddress = $this->getEmail();

        $amount = $this->getAmount();
        $transactionItems = array();
        $items = $this->getItems();

        if (!empty($items)) {
            $totalPriceOfItems = '0';
            foreach ($items as $i => $item) {
                $item->validate();

                $transactionItem = new stdClass();
                $transactionItem->name = $item->getName();
                $transactionItem->price = $item->getPrice();
                $transactionItem->quantity = $item->getQuantity();
                $transactionItem->indexNumber = $i + 1; // vindicia index numbers start at 1
                $transactionItem->itemType = 'Purchase';
                $transactionItem->taxClassification = $item->getTaxClassification() ?: $this->getTaxClassification();
                $transactionItem->sku = $item->getSku();
                $transactionItem->nameValues = array(
                    new NameValue('description', $item->getDescription())
                );

                $transactionItems[] = $transactionItem;

                // strval to avoid floating point error
                $totalPriceOfItems = strval($totalPriceOfItems + $transactionItem->price * $transactionItem->quantity);
            }

            if ($amount && floatval($amount) !== floatval($totalPriceOfItems)) {
                throw new InvalidRequestException('Sum of item prices not equal to set amount.');
            }
        } elseif ($amount) {
            $transactionItem = new stdClass();
            $transactionItem->name = 'Item'; // generic name since the name field is required
            $transactionItem->price = $amount;
            $transactionItem->quantity = 1;
            $transactionItem->indexNumber = 1;
            $transactionItem->itemType = 'Purchase';
            $transactionItem->taxClassification = $this->getTaxClassification();
            $transactionItem->sku = 0;

            $transactionItems[] = $transactionItem;
        }

        $card = $this->getCard();

        $transaction = new stdClass();
        $transaction->account = $account;
        $transaction->currency = $this->getCurrency();
        $transaction->merchantTransactionId = $this->getTransactionId();
        if ($paymentMethodType !== null) {
            $transaction->sourcePaymentMethod = $this->buildPaymentMethod($paymentMethodType);
        }
        $transaction->transactionItems = $transactionItems;
        $transaction->billingStatementIdentifier = $this->getStatementDescriptor();
        $transaction->sourceIp = $this->getIp();
        if ($card !== null) {
            $transaction->shippingAddress = $this->buildAddress($card);
        }

        $attributes = $this->getAttributes();
        if ($attributes) {
            $transaction->nameValues = $this->buildNameValues($attributes);
        }

        return $transaction;
    }

    /**
     * Helper function to make a Vindicia payment method object.
     * Set $addAttributes to true if the request attributes should be added to the payment
     * method
     *
     * @param string|null $paymentMethodType (self::PAYMENT_METHOD_CREDIT_CARD, self::PAYMENT_METHOD_PAYPAL,
     *                                        self::PAYMENT_METHOD_APPLE_PAY,
     *                                        null autodetects or sets nothing if no specifying data provided)
     * @param bool $addAttributes default false
     *
     * @return stdClass
     * @throws InvalidArgumentException if $paymentMethodType is not supported
     * @throws InvalidCreditCardException
     * @psalm-suppress PossiblyInvalidArrayOffset for applePayToken object
     * @psalm-suppress PossiblyNullArrayAccess for applePayToken object
     */
    protected function buildPaymentMethod($paymentMethodType, $addAttributes = false)
    {
        $paymentMethod = new stdClass();
        $paymentMethod->merchantPaymentMethodId = $this->getPaymentMethodId();
        $paymentMethod->VID = $this->getPaymentMethodReference();
        $paymentMethod->active = true;
        $paymentMethod->currency = $this->getCurrency();

        $card = $this->getCard();

        if ($paymentMethodType === self::PAYMENT_METHOD_CREDIT_CARD
            || ($paymentMethodType === null && $card)
        ) {
            if ($card) {
                // if we're adding a new credit card, the whole thing needs to be provided
                if (!$this->isUpdate()) {
                    $card->validate();
                }

                $creditCard = new stdClass();
                $creditCard->account = $card->getNumber();
                $creditCard->expirationDate = $card->getExpiryDate(self::VINDICIA_EXPIRATION_DATE_FORMAT);

                $paymentMethod->creditCard = $creditCard;
            }

            // never change the type on an update
            if (!$this->isUpdate()) {
                $paymentMethod->type = self::PAYMENT_METHOD_CREDIT_CARD;
            }
        } elseif ($paymentMethodType === self::PAYMENT_METHOD_PAYPAL
                  || ($paymentMethodType === null && $this->getReturnUrl())
        ) {
            $paypal = new stdClass();
            $paypal->cancelUrl = $this->getCancelUrl();
            $paypal->returnUrl = $this->getReturnUrl();
            $paypal->requestReferenceId = true;

            $paymentMethod->paypal = $paypal;

            // never change the type on an update
            if (!$this->isUpdate()) {
                $paymentMethod->type = self::PAYMENT_METHOD_PAYPAL;
            }
        } elseif ($paymentMethodType === self::PAYMENT_METHOD_APPLE_PAY && $card) {
            // $card parameter is needed for successful authorization.
            $applePay = new stdClass();

            // 'applePayToken' is validated to ensure it's set before reaching here.
            $token = $this->getApplePayToken();
            $applePay->paymentInstrumentName = $token['paymentMethod']['displayName'];
            $applePay->paymentNetwork = $token['paymentMethod']['network'];
            $applePay->transactionIdentifier = $token['transactionIdentifier'];
            // Vindicia expects the paymentData to be a string
            $applePay->paymentData = json_encode($token['paymentData']);

            $paymentMethod->applePay = $applePay;

            // never change the type on an update
            if (!$this->isUpdate()) {
                $paymentMethod->type = self::PAYMENT_METHOD_APPLE_PAY;
            }
        } elseif ($paymentMethodType !== null) {
            throw new InvalidArgumentException('Unknown payment method type.');
        }

        $attributes = $this->getAttributes();
        if ($attributes && $addAttributes) {
            $paymentMethod->nameValues = $this->buildNameValues($attributes);
        }

        if ($card !== null) {
            $paymentMethod->accountHolderName = $card->getName();
            $paymentMethod->billingAddress = $this->buildAddress($card);

            if ($card->getCvv()) {
                if (!isset($paymentMethod->nameValues)) {
                    $paymentMethod->nameValues = array();
                }
                $paymentMethod->nameValues[] = new NameValue('CVN', $card->getCvv());
            }
        }

        return $paymentMethod;
    }

    /**
     * Helper function to make a Vindicia address
     *
     * @param CreditCard $card
     * @return stdClass
     */
    protected function buildAddress(CreditCard $card)
    {
        $address = new stdClass();
        $address->addr1 = $card->getAddress1();
        $address->addr2 = $card->getAddress2();
        $address->city = $card->getCity();
        $address->country = $card->getCountry();
        $address->district = $card->getState();
        $address->name = $card->getName();
        $address->postalCode = $card->getPostcode();

        return $address;
    }

    /**
     * Helper function to make an array of name values from a bag of attributes
     *
     * @param AttributeBag $attributes
     * @return array of NameValue
     */
    protected function buildNameValues(AttributeBag $attributes)
    {
        $nameValues = array();
        foreach ($attributes as $attribute) {
            $nameValues[] = new NameValue($attribute->getName(), $attribute->getValue());
        }

        return $nameValues;
    }

    /**
     * Builds the value for Vindicia's prices field
     *
     * @return array of stdClass
     * @throws InvalidRequestException
     */
    protected function makePricesForVindicia()
    {
        $prices = $this->getPrices();
        $amount = $this->getAmount();
        $currency = $this->getCurrency();
        if (!empty($prices) && (isset($amount) || isset($currency))) {
            throw new InvalidRequestException(
                'The amount and currency parameters cannot be set if the prices parameter is set.'
            );
        }

        $vindiciaPrices = array();
        if (!empty($prices)) {
            foreach ($prices as $price) {
                $vindiciaPrice = new stdClass();
                $vindiciaPrice->amount = $price->getAmount();
                $vindiciaPrice->currency = $price->getCurrency();
                $vindiciaPrices[] = $vindiciaPrice;
            }
        } else {
            if (isset($amount)) {
                $price = new stdClass();
                $price->amount = $amount;
                $price->currency = $currency;
                $vindiciaPrices[] = $price;
            }
        }

        return $vindiciaPrices;
    }

    /**
     * This method is only overriden to provide type hinting for static type checking
     * by PSALM.
     * This is necessary because Omnipay\Common\AbstractRequest::setParameter says it
     * returns AbstractRequest instead of static.
     *
     * @return static
     */
    protected function setParameter($key, $value)
    {
        /**
         * @var static
         */
        return parent::setParameter($key, $value);
    }

    /**
     * Get data for request
     *
     * @return array<string, mixed>
     */
    abstract public function getData();

    /**
     * Redefining to tell psalm it's variadic
     *
     * @return bool
     * @psalm-variadic
     */
    public function validate()
    {
        return call_user_func_array('parent::validate', func_get_args());
    }
}


text:
class EvtAbsExternalGen {

public:

  EvtAbsExternalGen() {};
  virtual ~EvtAbsExternalGen() {};

  virtual bool doDecay(EvtParticle* theMother) = 0;
  virtual void initialise() = 0;

protected:

private:

};

#endif


text:
package com.swfarm.biz.ebay.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.chain.bo.SaleChannel;
import com.swfarm.biz.chain.srv.ChainService;
import com.swfarm.biz.ebay.bo.BlockedBuyerRecord;
import com.swfarm.biz.ebay.bo.EbayCaseStatus;
import com.swfarm.biz.ebay.bo.EbayFeedbackProcessSteps;
import com.swfarm.biz.ebay.dto.SearchBlockedBuyerRecordCriteria;
import com.swfarm.biz.ebay.srv.EbayService;
import com.swfarm.pub.framework.PaginationSupport;

public class ShowBlockedBuyerRecordsController extends AbstractController{

	private ChainService chainService;

	private EbayService ebayService;

	public void setChainService(ChainService chainService) {
		this.chainService = chainService;
	}

	public void setEbayService(EbayService ebayService) {
		this.ebayService = ebayService;
	}

	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		SearchBlockedBuyerRecordCriteria criteria = (SearchBlockedBuyerRecordCriteria) req.getAttribute("criteria");
		String startIndexStr = req.getParameter("startIndex");
		int startIndex = 0;
		int pageSize = 50;
		if (StringUtils.isNotEmpty(startIndexStr)) {
			startIndex = new Integer(startIndexStr).intValue();
		} else {
			String pageStr = req.getParameter("page");
			if (StringUtils.isNotEmpty(pageStr)) {
				startIndex = PaginationSupport.getPageStartIndex(new Integer(
						pageStr), pageSize);
			}
		}
		Map dataMap = new HashMap();
		PaginationSupport pagination = null;
		if (criteria != null) {
			pagination = this.ebayService.searchBlockedBuyerRecords(
					criteria, pageSize, startIndex);
		} else {
			pagination = this.ebayService.findBlockedBuyerRecords(pageSize,
					startIndex);
		}
		int page = pagination.getPage(startIndex);
		int[] pageRange = pagination.getPageRange(page);
		dataMap.put("pagination", pagination);
		dataMap.put("currentPage", page);
		dataMap.put("pageRange", pageRange);
		List<String> blockedReasonList = new ArrayList<String>();
		blockedReasonList.add(BlockedBuyerRecord.LEAVE_NEGATIVE_FEEDBACK);
		blockedReasonList.add(BlockedBuyerRecord.OPEN_CASE);
		dataMap.put("blockedReasonList", blockedReasonList);
		List<SaleChannel> saleChannelList = this.chainService.findSaleChannels();
		List SaleChannelNames = new ArrayList();
		for (SaleChannel saleChannel : saleChannelList) {
			SaleChannelNames.add(saleChannel.getName());
		}
		dataMap.put("saleChannelList", SaleChannelNames);
		dataMap.put("ebayFeedbackProcessSteps",
				EbayFeedbackProcessSteps.getSteps());
		EbayCaseStatus[] ebayCaseStatusArr = EbayCaseStatus.values();
		List ebayCaseStatusList = new ArrayList();
		for (int i = 0; i < ebayCaseStatusArr.length; i++) {
			EbayCaseStatus ebayCaseStatus = ebayCaseStatusArr[i];
			ebayCaseStatusList.add(new String[] { ebayCaseStatus.name(),
					ebayCaseStatus.getDesc() });
		}
		dataMap.put("ebayCaseStatusList", ebayCaseStatusList);
		return new ModelAndView("ebay/blockedbuyerrecords", dataMap);
	}

}