text:
namespace peloton {
namespace test {

class StatsTests : public PelotonTest {};

// Launch the aggregator thread manually
void LaunchAggregator(int64_t stat_interval) {
  settings::SettingsManager::SetInt(settings::SettingId::stats_mode,
                                    static_cast<int>(StatsType::ENABLE));

  auto &aggregator =
      peloton::stats::StatsAggregator::GetInstance(stat_interval);
  aggregator.GetAggregatedStats().ResetQueryCount();
  aggregator.ShutdownAggregator();
  aggregator.LaunchAggregator();
}

// Force a final aggregation
void ForceFinalAggregation(int64_t stat_interval) {
  auto &aggregator =
      peloton::stats::StatsAggregator::GetInstance(stat_interval);
  int64_t interval_cnt = 0;
  double alpha = 0;
  double weighted_avg_throughput = 0;
  aggregator.Aggregate(interval_cnt, alpha, weighted_avg_throughput);
}

void TransactionTest(storage::Database *database, storage::DataTable *table,
                     UNUSED_ATTRIBUTE uint64_t thread_itr) {
  uint64_t thread_id = TestingHarness::GetInstance().GetThreadId();
  auto tile_group_id = table->GetTileGroup(0)->GetTileGroupId();
  auto index_metadata = table->GetIndex(0)->GetMetadata();
  auto db_oid = database->GetOid();
  auto context = stats::BackendStatsContext::GetInstance();
  auto stmt = TestingStatsUtil::GetInsertStmt();

  for (oid_t txn_itr = 1; txn_itr <= NUM_ITERATION; txn_itr++) {
    context->InitQueryMetric(stmt, nullptr);

    if (thread_id % 2 == 0) {
      std::chrono::microseconds sleep_time(1);
      std::this_thread::sleep_for(sleep_time);
    }

    // Record table stat
    for (int i = 0; i < NUM_TABLE_READ; i++) {
      context->IncrementTableReads(tile_group_id);
    }
    for (int i = 0; i < NUM_TABLE_UPDATE; i++) {
      context->IncrementTableUpdates(tile_group_id);
    }
    for (int i = 0; i < NUM_TABLE_INSERT; i++) {
      context->IncrementTableInserts(tile_group_id);
    }
    for (int i = 0; i < NUM_TABLE_DELETE; i++) {
      context->IncrementTableDeletes(tile_group_id);
    }

    // Record index stat
    context->IncrementIndexReads(NUM_INDEX_READ, index_metadata);
    context->IncrementIndexDeletes(NUM_INDEX_DELETE, index_metadata);
    for (int i = 0; i < NUM_INDEX_INSERT; i++) {
      context->IncrementIndexInserts(index_metadata);
    }

    // Record database stat
    for (int i = 0; i < NUM_DB_COMMIT; i++) {
      context->GetOnGoingQueryMetric()->GetQueryLatency().RecordLatency();
      context->IncrementTxnCommitted(db_oid);
    }
    for (int i = 0; i < NUM_DB_ABORT; i++) {
      context->IncrementTxnAborted(db_oid);
    }
  }
}

TEST_F(StatsTests, MultiThreadStatsTest) {
  auto catalog = catalog::Catalog::GetInstance();
  catalog->Bootstrap();

  // Launch aggregator thread
  int64_t aggregate_interval = 100;
  LaunchAggregator(aggregate_interval);
  auto &aggregator = stats::StatsAggregator::GetInstance();

  // Create database, table and index
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  auto id_column = catalog::Column(
      type::TypeId::INTEGER, type::Type::GetTypeSize(type::TypeId::INTEGER),
      "dept_id", true);
  auto name_column =
      catalog::Column(type::TypeId::VARCHAR, 32, "dept_name", false);

  std::unique_ptr<catalog::Schema> table_schema(
      new catalog::Schema({id_column, name_column}));
  catalog->CreateDatabase(txn, "emp_db");
  catalog::Catalog::GetInstance()->CreateTable(txn,
                                               "emp_db",
                                               DEFAULT_SCHEMA_NAME,
                                               std::move(table_schema),
                                               "department_table",
                                               false);

  // Create multiple stat worker threads
  int num_threads = 8;
  storage::Database *database =
      catalog->GetDatabaseWithName(txn, "emp_db");
  storage::DataTable *table = catalog->GetTableWithName(txn,
                                                  "emp_db",
                                                  DEFAULT_SCHEMA_NAME,
                                                  "department_table");

  catalog->AddPrimaryKeyConstraint(txn,
                                   database->GetOid(),
                                   table->GetOid(),
                                   {0},
                                   "con_primary");

  txn_manager.CommitTransaction(txn);
  LaunchParallelTest(num_threads, TransactionTest, database, table);
  // Wait for aggregation to finish
  std::chrono::microseconds sleep_time(aggregate_interval * 2 * 1000);
  std::this_thread::sleep_for(sleep_time);
  aggregator.ShutdownAggregator();
  // Force a final aggregation
  ForceFinalAggregation(aggregate_interval);

  // Check query metrics
  auto &aggregated_stats = aggregator.GetAggregatedStats();
  ASSERT_EQ(aggregated_stats.GetQueryCount(), num_threads * NUM_ITERATION);

  // Check database metrics
  oid_t db_oid = database->GetOid();
  LOG_TRACE("db_oid is %u", db_oid);
  auto db_metric = aggregated_stats.GetDatabaseMetric(db_oid);
  ASSERT_GT(db_metric->GetTxnCommitted().GetCounter(),
            num_threads * NUM_ITERATION * NUM_DB_COMMIT);
  ASSERT_EQ(db_metric->GetTxnAborted().GetCounter(),
            num_threads * NUM_ITERATION * NUM_DB_ABORT);

  // Check table metrics
  auto table_oid = table->GetOid();
  auto table_metric = aggregated_stats.GetTableMetric(db_oid, table_oid);
  auto table_access = table_metric->GetTableAccess();
  ASSERT_EQ(table_access.GetReads(),
            num_threads * NUM_ITERATION * NUM_TABLE_READ);
  ASSERT_EQ(table_access.GetUpdates(),
            num_threads * NUM_ITERATION * NUM_TABLE_UPDATE);
  ASSERT_EQ(table_access.GetDeletes(),
            num_threads * NUM_ITERATION * NUM_TABLE_DELETE);
  ASSERT_EQ(table_access.GetInserts(),
            num_threads * NUM_ITERATION * NUM_TABLE_INSERT);

  // Check index metrics
  auto index_oid = table->GetIndex(0)->GetOid();
  auto index_metric =
      aggregated_stats.GetIndexMetric(db_oid, table_oid, index_oid);
  auto index_access = index_metric->GetIndexAccess();
  ASSERT_EQ(index_access.GetReads(),
            num_threads * NUM_ITERATION * NUM_INDEX_READ);
  ASSERT_EQ(index_access.GetDeletes(),
            num_threads * NUM_ITERATION * NUM_INDEX_DELETE);
  ASSERT_EQ(index_access.GetInserts(),
            num_threads * NUM_ITERATION * NUM_INDEX_INSERT);

  txn = txn_manager.BeginTransaction();
  catalog->DropDatabaseWithName(txn, "emp_db");
  txn_manager.CommitTransaction(txn);
}
//
// TEST_F(StatsTests, PerThreadStatsTest) {
//  FLAGS_stats_mode = STATS_TYPE_ENABLE;
//
//  // Register to StatsAggregator
//  auto &aggregator = peloton::stats::StatsAggregator::GetInstance(1000000);
//
//  // int tuple_count = 10;
//  int tups_per_tile_group = 100;
//  int num_rows = 10;
//
//  // Create a table and wrap it in logical tiles
//  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
//  auto txn = txn_manager.BeginTransaction();
//  std::unique_ptr<storage::DataTable> data_table(
//      TestingExecutorUtil::CreateTable(tups_per_tile_group, true));
//
//  // Ensure that the tile group is as expected.
//  const catalog::Schema *schema = data_table->GetSchema();
//  PELOTON_ASSERT(schema->GetColumnCount() == 4);
//
//  // Insert tuples into tile_group.
//  std::vector<ItemPointer> tuple_slot_ids;
//
//  for (int rowid = 0; rowid < num_rows; rowid++) {
//    int populate_value = rowid;
//
//    storage::Tuple tuple = TestingStatsUtil::PopulateTuple(
//        schema, TestingExecutorUtil::PopulatedValue(populate_value, 0),
//        TestingExecutorUtil::PopulatedValue(populate_value, 1),
//        TestingExecutorUtil::PopulatedValue(populate_value, 2),
//        TestingExecutorUtil::PopulatedValue(populate_value, 3));
//
//    std::unique_ptr<const planner::ProjectInfo> project_info{
//        TestingTransactionUtil::MakeProjectInfoFromTuple(&tuple)};
//
//    // Insert
//    planner::InsertPlan node(data_table.get(), std::move(project_info));
//    std::unique_ptr<executor::ExecutorContext> context(
//        new executor::ExecutorContext(txn));
//    executor::InsertExecutor executor(&node, context.get());
//    executor.Execute();
//  }
//  txn_manager.CommitTransaction(txn);
//  oid_t database_id = data_table->GetDatabaseOid();
//  oid_t table_id = data_table->GetOid();
//
//  // Check: # transactions committed = 1, # table inserts = 10
//  int64_t txn_commited = stats::BackendStatsContext::GetInstance()
//                             ->GetDatabaseMetric(database_id)
//                             ->GetTxnCommitted()
//                             .GetCounter();
//  int64_t inserts = stats::BackendStatsContext::GetInstance()
//                        ->GetTableMetric(database_id, table_id)
//                        ->GetTableAccess()
//                        .GetInserts();
//  EXPECT_EQ(1, txn_commited);
//  EXPECT_EQ(num_rows, inserts);
//
//  // Read every other tuple
//  txn = txn_manager.BeginTransaction();
//  for (int i = 0; i < num_rows; i += 2) {
//    int result;
//    TestingTransactionUtil::ExecuteRead(
//        txn, data_table.get(), TestingExecutorUtil::PopulatedValue(i, 0),
//        result);
//  }
//  txn_manager.CommitTransaction(txn);
//
//  // Check: # transactions committed = 2, # inserts = 10, # reads = 5
//  txn_commited = stats::BackendStatsContext::GetInstance()
//                     ->GetDatabaseMetric(database_id)
//                     ->GetTxnCommitted()
//                     .GetCounter();
//  inserts = stats::BackendStatsContext::GetInstance()
//                ->GetTableMetric(database_id, table_id)
//                ->GetTableAccess()
//                .GetInserts();
//  int64_t reads = stats::BackendStatsContext::GetInstance()
//                      ->GetTableMetric(database_id, table_id)
//                      ->GetTableAccess()
//                      .GetReads();
//  EXPECT_EQ(2, txn_commited);
//  EXPECT_EQ(num_rows, inserts);
//  EXPECT_EQ(5, reads);
//
//  // Do a single read and abort
//  txn = txn_manager.BeginTransaction();
//  int result;
//  TestingTransactionUtil::ExecuteRead(
//      txn, data_table.get(), TestingExecutorUtil::PopulatedValue(0, 0),
//      result);
//  txn_manager.AbortTransaction(txn);
//
//  // Check: # txns committed = 2, # txns aborted = 1, # reads = 6
//  txn_commited = stats::BackendStatsContext::GetInstance()
//                     ->GetDatabaseMetric(database_id)
//                     ->GetTxnCommitted()
//                     .GetCounter();
//  int64_t txn_aborted = stats::BackendStatsContext::GetInstance()
//                            ->GetDatabaseMetric(database_id)
//                            ->GetTxnAborted()
//                            .GetCounter();
//  reads = stats::BackendStatsContext::GetInstance()
//              ->GetTableMetric(database_id, table_id)
//              ->GetTableAccess()
//              .GetReads();
//  EXPECT_EQ(2, txn_commited);
//  EXPECT_EQ(1, txn_aborted);
//  EXPECT_EQ(6, reads);
//
//  // Read and update the first tuple
//  txn = txn_manager.BeginTransaction();
//  TestingTransactionUtil::ExecuteUpdate(txn, data_table.get(), 0, 2);
//  txn_manager.CommitTransaction(txn);
//
//  // Check: # txns committed = 3, # updates = 1, # reads = 7
//  txn_commited = stats::BackendStatsContext::GetInstance()
//                     ->GetDatabaseMetric(database_id)
//                     ->GetTxnCommitted()
//                     .GetCounter();
//  reads = stats::BackendStatsContext::GetInstance()
//              ->GetTableMetric(database_id, table_id)
//              ->GetTableAccess()
//              .GetReads();
//  int64_t updates = stats::BackendStatsContext::GetInstance()
//                        ->GetTableMetric(database_id, table_id)
//                        ->GetTableAccess()
//                        .GetUpdates();
//  EXPECT_EQ(3, txn_commited);
//  EXPECT_EQ(7, reads);
//  EXPECT_EQ(1, updates);
//
//  // Delete the 6th tuple and read the 1st tuple
//  txn = txn_manager.BeginTransaction();
//  TestingTransactionUtil::ExecuteDelete(txn, data_table.get(),
//                                      TestingExecutorUtil::PopulatedValue(5,
//                                      0));
//  LOG_TRACE("before read");
//  TestingTransactionUtil::ExecuteRead(
//      txn, data_table.get(), TestingExecutorUtil::PopulatedValue(1, 0),
//      result);
//  txn_manager.CommitTransaction(txn);
//
//  // Check: # txns committed = 4, # deletes = 1, # reads = 8
//  txn_commited = stats::BackendStatsContext::GetInstance()
//                     ->GetDatabaseMetric(database_id)
//                     ->GetTxnCommitted()
//                     .GetCounter();
//  reads = stats::BackendStatsContext::GetInstance()
//              ->GetTableMetric(database_id, table_id)
//              ->GetTableAccess()
//              .GetReads();
//  int64_t deletes = stats::BackendStatsContext::GetInstance()
//                        ->GetTableMetric(database_id, table_id)
//                        ->GetTableAccess()
//                        .GetDeletes();
//  EXPECT_EQ(4, txn_commited);
//  EXPECT_EQ(9, reads);
//  EXPECT_EQ(1, deletes);
//
//  aggregator.ShutdownAggregator();
//}
//
// TEST_F(StatsTests, PerQueryStatsTest) {
//  int64_t aggregate_interval = 1000;
//  LaunchAggregator(aggregate_interval);
//  auto &aggregator = stats::StatsAggregator::GetInstance();
//  auto &traffic_cop = traffic_cop::TrafficCop::GetInstance();
//
//  // Create a table first
//  auto catalog = catalog::Catalog::GetInstance();
//  catalog->CreateDatabase("emp_db", nullptr);
//  TestingStatsUtil::CreateTable();
//
//  // Default database should include 4 metrics tables and the test table
//  EXPECT_EQ(catalog::Catalog::GetInstance()
//                ->GetDatabaseWithName(CATALOG_DATABASE_NAME)
//                ->GetTableCount(),
//            6);
//  LOG_TRACE("Table created!");
//
//  auto backend_context = stats::BackendStatsContext::GetInstance();
//  // Get a query param object
//  std::shared_ptr<uchar> type_buf;
//  std::shared_ptr<uchar> format_buf;
//  std::shared_ptr<uchar> val_buf;
//  auto query_params =
//      TestingStatsUtil::GetQueryParams(type_buf, format_buf, val_buf);
//
//  // Inserting a tuple end-to-end
//  auto statement = TestingStatsUtil::GetInsertStmt();
//  // Initialize the query metric, with prep stmt parameters
//  backend_context->InitQueryMetric(statement, query_params);
//
//  // Execute insert
//  std::vector<type::Value> params;
//  std::vector<ResultValue> result;
//  std::vector<int> result_format(statement->GetTupleDescriptor().size(), 0);
//  executor::ExecutionResult status = traffic_cop.ExecuteHelper(
//      statement->GetPlanTree().get(), params, result, result_format);
//  LOG_TRACE("Statement executed. Result: %s",
//            ResultTypeToString(status.m_result).c_str());
//  LOG_TRACE("Tuple inserted!");
//
//  // Now Updating end-to-end
//  statement = TestingStatsUtil::GetUpdateStmt();
//  // Initialize the query metric
//  backend_context->InitQueryMetric(statement, nullptr);
//
//  // Execute update
//  params.clear();
//  result.clear();
//  result_format =
//      std::move(std::vector<int>(statement->GetTupleDescriptor().size(), 0));
//  status = traffic_cop.ExecuteHelper(statement->GetPlanTree().get(),
//                                            params, result, result_format);
//  LOG_TRACE("Statement executed. Result: %s",
//            ResultTypeToString(status.m_result).c_str());
//  LOG_TRACE("Tuple updated!");
//
//  // Deleting end-to-end
//  statement = std::move(TestingStatsUtil::GetDeleteStmt());
//  // Initialize the query metric
//  backend_context->InitQueryMetric(statement, nullptr);
//
//  // Execute delete
//  params.clear();
//  result.clear();
//  result_format =
//      std::move(std::vector<int>(statement->GetTupleDescriptor().size(), 0));
//  status = traffic_cop.ExecuteHelper(statement->GetPlanTree().get(),
//                                            params, result, result_format);
//  LOG_TRACE("Statement executed. Result: %s",
//            ResultTypeToString(status.m_result).c_str());
//  LOG_TRACE("Tuple deleted!");
//
//  // Wait for aggregation to finish
//  std::chrono::microseconds sleep_time(aggregate_interval * 2 * 1000);
//  std::this_thread::sleep_for(sleep_time);
//  aggregator.ShutdownAggregator();
//  ForceFinalAggregation(aggregate_interval);
//
//  EXPECT_EQ(aggregator.GetAggregatedStats().GetQueryCount(), 3);
//
//  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
//  auto txn = txn_manager.BeginTransaction();
//  catalog->DropDatabaseWithName("emp_db", txn);
//  txn_manager.CommitTransaction(txn);
//}
}  // namespace test
}  // namespace peloton


text:
<?php

namespace Amadeus\Client\Struct\Queue;

use Amadeus\Client\RequestOptions\Queue\SearchCriteriaOpt;

/**
 * Class SearchCriteria
 *
 * @package Amadeus\Client\Struct\Queue
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class SearchCriteria
{
    /**
     * @var SearchOption
     */
    public $searchOption;

    /**
     * @var Dates[]
     */
    public $dates = [];

    /**
     * SearchCriteria constructor.
     *
     * @param SearchCriteriaOpt $opt
     */
    public function __construct(SearchCriteriaOpt $opt)
    {
        $this->searchOption = new SearchOption($opt->type);

        if ($opt->start instanceof \DateTime && $opt->end instanceof \DateTime) {
            $this->dates[] = new Dates($opt->start, $opt->end);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/// <summary>
/// Author: Lele Feng
/// </summary>

using UnityEngine;
using System.Collections;

public class ColorPicker : MonoBehaviour {

	public BoxCollider pickerCollider;

	private bool m_grab;
	private Camera m_camera;
	private Texture2D m_screenRenderTexture;
	private static Texture2D m_staticRectTexture;
	private static GUIStyle m_staticRectStyle;

	private static Vector3 m_pixelPosition = Vector3.zero;
	private Color m_pickedColor = Color.white;

	void Awake() {
		// Get the Camera component
		m_camera = GetComponent<Camera>();
		if (m_camera == null) {
			Debug.LogError("You need to dray this script to a camera!");
			return;
		}

		// Attach a BoxCollider to this camera
		// In order to receive mouse events
		if (pickerCollider == null) {
			pickerCollider = gameObject.AddComponent<BoxCollider>();
			// Make sure the collider is in the camera's frustum
			pickerCollider.center = Vector3.zero;
			pickerCollider.center += m_camera.transform.worldToLocalMatrix.MultiplyVector(m_camera.transform.forward) * (m_camera.nearClipPlane + 0.2f);
			pickerCollider.size = new Vector3(Screen.width, Screen.height, 0.1f);
		}
	}

	// Draw the color we picked
	public static void GUIDrawRect( Rect position, Color color )
	{
		if( m_staticRectTexture == null )
		{
			m_staticRectTexture = new Texture2D(1, 1);
		}

		if( m_staticRectStyle == null )
		{
			m_staticRectStyle = new GUIStyle();
		}

		m_staticRectTexture.SetPixel(0, 0, color);
		m_staticRectTexture.Apply();

		m_staticRectStyle.normal.background = m_staticRectTexture;

		GUI.Box(position, GUIContent.none, m_staticRectStyle);
	}

	// OnPostRender is called after a camera has finished rendering the scene.
	// This message is sent to all scripts attached to the camera.
	// Use it to grab the screen
	// Note: grabing is a expensive operation
	void OnPostRender() {
		if (m_grab) {
			m_screenRenderTexture = new Texture2D(Screen.width, Screen.height);
			m_screenRenderTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
			m_screenRenderTexture.Apply();
			m_pickedColor = m_screenRenderTexture.GetPixel(Mathf.FloorToInt(m_pixelPosition.x), Mathf.FloorToInt(m_pixelPosition.y));
			m_grab = false;
		}
	}

	void OnMouseDown() {
		m_grab = true;
		// Record the mouse position to pick pixel
		m_pixelPosition = Input.mousePosition;
	}

	void OnGUI() {
		GUI.Box(new Rect(0, 0, 120, 200), "Color Picker");
		GUIDrawRect(new Rect(20, 30, 80, 80), m_pickedColor);
		GUI.Label(new Rect(10, 120, 100, 20), "R: " + System.Math.Round((double)m_pickedColor.r, 4) + "\t(" + Mathf.FloorToInt(m_pickedColor.r * 255)+ ")");
		GUI.Label(new Rect(10, 140, 100, 20), "G: " + System.Math.Round((double)m_pickedColor.g, 4) + "\t(" + Mathf.FloorToInt(m_pickedColor.g * 255)+ ")");
		GUI.Label(new Rect(10, 160, 100, 20), "B: " + System.Math.Round((double)m_pickedColor.b, 4) + "\t(" + Mathf.FloorToInt(m_pickedColor.b * 255)+ ")");
		GUI.Label(new Rect(10, 180, 100, 20), "A: " + System.Math.Round((double)m_pickedColor.a, 4) + "\t(" + Mathf.FloorToInt(m_pickedColor.a * 255)+ ")");
	}
}


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/prdf/common/framework/resolution/iipResolution.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 1996,2014              */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

// Module Description **************************************************
//
// Description: PRD resolution definition
//
// End Module Description **********************************************

//----------------------------------------------------------------------
//  Includes
//----------------------------------------------------------------------
#define iipResolution_C

#include <iipconst.h>
#include <CcAutoDeletePointer.h>
#include <iipSystem.h>
#include <prdfGlobal.H>
//#include <iipCalloutMap.h>
#include <iipCalloutResolution.h>
#include <iipstep.h>
#include <iipCaptureData.h>
#include <iipServiceDataCollector.h>
#include <iipErrorRegister.h>
#include <iipEregResolution.h>
#include <iipsdbug.h>
#include <iipResolutionList.h>
#include <iipCallAttnResolution.h>
#include <iipTerminateResolution.h>
#include <iipAnalyzeChipResolution.h>
#include <xspprdTryResolution.h>
#include <iipchip.h>
#include <prdfCalloutConnected.H>
#include <prdfAnalyzeConnected.H>
#include <prdfPlatServices.H>
#undef iipResolution_C

namespace PRDF
{

using namespace PlatServices;

//----------------------------------------------------------------------
//  User Types
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Constants
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Macros
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Internal Function Prototypes
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Global Variables
//----------------------------------------------------------------------

//---------------------------------------------------------------------
// Resolution Member Function Specifications
//---------------------------------------------------------------------
Resolution::~Resolution() {}

//---------------------------------------------------------------------
// EregResolution Member Function Specifications
//---------------------------------------------------------------------

int32_t EregResolution::Resolve( STEP_CODE_DATA_STRUCT & io_data )
{
    int32_t rc = PRD_INTERNAL_CODE_ERROR;
    if( errorRegister != NULL )
    {
        rc = errorRegister->Analyze( io_data );
    }
    return rc;
}

//---------------------------------------------------------------------
// CalloutResolution Member Function Specifications
// using MruValues (xspiiCallout.h)
//---------------------------------------------------------------------

int32_t CalloutResolution::Resolve( STEP_CODE_DATA_STRUCT & io_serviceData )
{
    /*
    This resolution is only needed when we callout self.So during RuleChip
    creation,we create CalloutResolution passing NULL as target value.In Resolve
    function when we need to update SDC with target to be called out we get it
    from Service Data Collector.It is because target currently under analysis is
    the target that needs to be called out here.By instantiating Callout
    resolution with just priority info and NULL target , we are able to reduce
    CalloutResolution objects to one per priority instead of one per target per
    priority.So,this reduction in number of resolution objects shall eventually
    reduce memory utilization.
    */

    if ( PRDcalloutData::TYPE_TARGET == xMruCallout.getType() )
    {
        PRDcallout l_targetCallout( ServiceDataCollector::getTargetAnalyzed() );
        io_serviceData.service_data->SetCallout( l_targetCallout, xPriority );
    }
    else
    {
        io_serviceData.service_data->SetCallout( xMruCallout,xPriority );
    }

    return(SUCCESS);
}

//--------------------------------------------------------------------
// ResolutionList Member Functions
//--------------------------------------------------------------------

int32_t ResolutionList::Resolve( STEP_CODE_DATA_STRUCT & io_serviceData )
{
    int32_t rc = SUCCESS;
    for(std::vector<void *>::iterator iter = resolutionList.begin();
        iter != resolutionList.end();
        ++iter)
    {
        Resolution * r = (Resolution *) *iter;
        rc = r->Resolve( io_serviceData );
        if( rc != SUCCESS ) break;
    }
    return(rc);
}

//--------------------------------------------------------------------
// ThresholdResolution Member Functions
//--------------------------------------------------------------------

//int32_t ThresholdResolution::Resolve(STEP_CODE_DATA_STRUCT & error)
//{
//  ++count;
//  error.service_data->SetHits((uint16_t)count);
//  error.service_data->SetThreshold((uint16_t)threshold);
//  if((count >= threshold) || (error.service_data->IsFlooding()))
//  {
//    error.service_data->SetThresholdMaskId(maskId);  // threshold, degraded YES
//  }
//  int32_t rc = SUCCESS;
//  if(xRes != NULL) rc = xRes->Resolve(error);
//  return rc;
//}

//--------------------------------------------------------------------
// Call all chips raising attention as reported by sp sysdebug area
//--------------------------------------------------------------------
int32_t CallAttnResolution::Resolve( STEP_CODE_DATA_STRUCT & io_serviceData )
{
    int32_t rc = NO_DOMAINS_AT_ATTENTION;
    SYSTEM_DEBUG_CLASS systemDebug;

    ErrorSignature * signature =
                        io_serviceData.service_data->GetErrorSignature();
    signature->clear();
    signature->setChipId(0xffffffff);

    systemDebug.CalloutThoseAtAttention( io_serviceData );

    signature->setErrCode((uint16_t)NO_PRD_ANALYSIS);

    return(rc);
}

// ********************************************************************

int32_t TerminateResolution::Resolve( STEP_CODE_DATA_STRUCT & io_serviceData )
{
    io_serviceData.service_data->SetTerminate();
    return(SUCCESS);
}

// ********************************************************************

int32_t AnalyzeChipResolution::Resolve( STEP_CODE_DATA_STRUCT & io_serviceData )
{
    // mk442956 a
    return xChip.Analyze( io_serviceData,
                          io_serviceData.service_data->GetCauseAttentionType() );
}

// ********************************************************************

int32_t TryResolution::Resolve( STEP_CODE_DATA_STRUCT & io_serviceData )
{
    // Save the current error signature
    ErrorSignature * es = io_serviceData.service_data->GetErrorSignature();
    ErrorSignature temp = *es;
    // Try the tryResolution
    int32_t rc = xTryResolution->Resolve( io_serviceData  );
    if ( (SUCCESS != rc) && (PRD_NO_CLEAR_FIR_BITS != rc) ) // if it didn't work
    {
        // Restore signature
        *es = temp;
        // Call the default signature
        rc = xDefaultResolution->Resolve( io_serviceData );
    }
    return rc;
}

int32_t CalloutConnected::Resolve( STEP_CODE_DATA_STRUCT & io_serviceData )
{
    using namespace TARGETING;

    TargetHandle_t sourceTrgt  = ServiceDataCollector::getTargetAnalyzed();
    TargetHandle_t connTrgt    = NULL;
    TargetHandle_t srcEndPoint = NULL;

    if(TYPE_NA == iv_peerConnType)
    {
        TargetHandleList list = getConnected( sourceTrgt, iv_targetType );

        if ( 0xffffffff == iv_idx )
        {
            if ( 0 < list.size() )
                connTrgt = list[0];
        }
        else
        {
            for (TargetHandleList::iterator i = list.begin();
                 i != list.end();
                 i++)
            {
                if ( iv_idx == getTargetPosition(*i) )
                {
                    connTrgt = *i;
                    break;
                }
            }
        }
    }
    else
    {
        srcEndPoint = getConnectedChild( sourceTrgt, iv_peerConnType, iv_idx );

        if ( NULL != srcEndPoint )
            connTrgt = getConnectedPeerTarget( srcEndPoint );
    }

    if ( NULL != connTrgt )
        io_serviceData.service_data->SetCallout( connTrgt, iv_priority );
    else
    {
        if ( NULL != iv_altResolution )
            iv_altResolution->Resolve( io_serviceData );
        else
        {
            PRDF_ERR( "[CalloutConnected::Resolve] No connected chip found:"
                      " sourceTrgt=0x%08x, iv_peerConnType=0x%x",
                        getHuid(sourceTrgt), iv_peerConnType);

            io_serviceData.service_data->SetCallout( sourceTrgt );
        }
    }

    return SUCCESS;
}

//--------------------------------------------------------------------
// AnalyzeConnected Member Functions
//--------------------------------------------------------------------
int32_t AnalyzeConnected::Resolve( STEP_CODE_DATA_STRUCT & io_serviceData )
{
    using namespace TARGETING;

    TargetHandle_t sourceTrgt = ServiceDataCollector::getTargetAnalyzed();
    TargetHandle_t connTrgt   = NULL;

    TargetHandleList list = getConnected( sourceTrgt, iv_targetType );

    if ( 0xffffffff == iv_idx )
    {
        if ( 0 < list.size() )
            connTrgt = list[0];
    }
    else
    {
        for (TargetHandleList::iterator i = list.begin(); i != list.end(); i++)
        {
            if ( iv_idx == getTargetPosition(*i) )
            {
                connTrgt = *i;
                break;
            }
        }
    }

    // If valid chip found, look up in global system container.
    CHIP_CLASS * connChip = NULL;
    if ( NULL != connTrgt )
    {
        connChip = systemPtr->GetChip( connTrgt );
    }

    // Analyze chip.
    if ( NULL != connChip )
        return connChip->Analyze( io_serviceData,
                        io_serviceData.service_data->GetCauseAttentionType() );
    else
        return PRD_UNRESOLVED_CHIP_CONNECTION;
}

} // end namespace PRDF


text:
namespace Forum.Data.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class Initial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.PostAnswers",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        Content = c.String(),
                        AnsweredOn = c.DateTime(nullable: false),
                        PostId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.Posts", t => t.PostId, cascadeDelete: true)
                .Index(t => t.PostId);

            CreateTable(
                "dbo.Posts",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        Title = c.String(),
                        Content = c.String(),
                        PostType = c.Int(nullable: false),
                        CreatedOn = c.DateTime(nullable: false),
                        CategoryId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.Categories", t => t.CategoryId, cascadeDelete: true)
                .Index(t => t.CategoryId);

            CreateTable(
                "dbo.Categories",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                        ParentCategoryId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.Categories", t => t.ParentCategoryId)
                .Index(t => t.ParentCategoryId);

            CreateTable(
                "dbo.Tags",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        Text = c.String(),
                    })
                .PrimaryKey(t => t.Id);

            CreateTable(
                "dbo.TagPosts",
                c => new
                    {
                        Tag_Id = c.Int(nullable: false),
                        Post_Id = c.Int(nullable: false),
                    })
                .PrimaryKey(t => new { t.Tag_Id, t.Post_Id })
                .ForeignKey("dbo.Tags", t => t.Tag_Id, cascadeDelete: true)
                .ForeignKey("dbo.Posts", t => t.Post_Id, cascadeDelete: true)
                .Index(t => t.Tag_Id)
                .Index(t => t.Post_Id);

        }

        public override void Down()
        {
            DropForeignKey("dbo.TagPosts", "Post_Id", "dbo.Posts");
            DropForeignKey("dbo.TagPosts", "Tag_Id", "dbo.Tags");
            DropForeignKey("dbo.Posts", "CategoryId", "dbo.Categories");
            DropForeignKey("dbo.Categories", "ParentCategoryId", "dbo.Categories");
            DropForeignKey("dbo.PostAnswers", "PostId", "dbo.Posts");
            DropIndex("dbo.TagPosts", new[] { "Post_Id" });
            DropIndex("dbo.TagPosts", new[] { "Tag_Id" });
            DropIndex("dbo.Categories", new[] { "ParentCategoryId" });
            DropIndex("dbo.Posts", new[] { "CategoryId" });
            DropIndex("dbo.PostAnswers", new[] { "PostId" });
            DropTable("dbo.TagPosts");
            DropTable("dbo.Tags");
            DropTable("dbo.Categories");
            DropTable("dbo.Posts");
            DropTable("dbo.PostAnswers");
        }
    }
}


text:
package org.appenders.log4j2.elasticsearch;

import org.appenders.log4j2.elasticsearch.failover.FailedItemSource;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class NoopFailoverPolicyPluginTest {

    @Test
    public void minimalBuilderTest() {

        // given
        final NoopFailoverPolicyPlugin.Builder builder = NoopFailoverPolicyPlugin.newBuilder();

        // when
        final FailoverPolicy failoverPolicy = builder.build();

        // then
        assertNotNull(failoverPolicy);

    }

    @Test
    public void deliverFailedItemSourceDelegatesToGenericAPI() {

        // given
        final NoopFailoverPolicyPlugin.Builder builder = NoopFailoverPolicyPlugin.newBuilder();
        final FailoverPolicy<Object> failoverPolicy = spy(builder.build());

        final FailedItemSource<Object> failedItemSource = mock(FailedItemSource.class);

        final ItemSource itemSource = mock(ItemSource.class);
        when(failedItemSource.getSource()).thenReturn(itemSource);

        // when
        failoverPolicy.deliver(failedItemSource);

        // then
        verify(failoverPolicy).deliver(itemSource);

    }

}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>留学生综合服务与管理系统</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <link rel="stylesheet" href="styles/flat-ui/css/vendor/bootstrap/css/bootstrap.min.css"/>
        <link rel="stylesheet" href="styles/flat-ui/css/flat-ui.min.css"/>
        <link href="images/favicon.ico" rel="shortcut icon" />
        <link rel="stylesheet" href="styles/artDialog.css"/>
        <link rel="stylesheet" href="styles/app.css"/>

正在加载中...


text:
/*
 * Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.EC2.Model
{
    /// <summary>
    /// Describes an import instance task.
    /// </summary>
    public partial class ImportInstanceTaskDetails
    {
        private string _description;
        private string _instanceId;
        private PlatformValues _platform;
        private List<ImportInstanceVolumeDetailItem> _volumes = new List<ImportInstanceVolumeDetailItem>();

        /// <summary>
        /// Gets and sets the property Description.
        /// <para>
        /// A description of the task.
        /// </para>
        /// </summary>
        public string Description
        {
            get { return this._description; }
            set { this._description = value; }
        }

        // Check to see if Description property is set
        internal bool IsSetDescription()
        {
            return this._description != null;
        }

        /// <summary>
        /// Gets and sets the property InstanceId.
        /// <para>
        /// The ID of the instance.
        /// </para>
        /// </summary>
        public string InstanceId
        {
            get { return this._instanceId; }
            set { this._instanceId = value; }
        }

        // Check to see if InstanceId property is set
        internal bool IsSetInstanceId()
        {
            return this._instanceId != null;
        }

        /// <summary>
        /// Gets and sets the property Platform.
        /// <para>
        /// The instance operating system.
        /// </para>
        /// </summary>
        public PlatformValues Platform
        {
            get { return this._platform; }
            set { this._platform = value; }
        }

        // Check to see if Platform property is set
        internal bool IsSetPlatform()
        {
            return this._platform != null;
        }

        /// <summary>
        /// Gets and sets the property Volumes.
        /// <para>
        /// One or more volumes.
        /// </para>
        /// </summary>
        public List<ImportInstanceVolumeDetailItem> Volumes
        {
            get { return this._volumes; }
            set { this._volumes = value; }
        }

        // Check to see if Volumes property is set
        internal bool IsSetVolumes()
        {
            return this._volumes != null && this._volumes.Count > 0;
        }

    }
}


text:
require 'test/support/fake_request'
require 'test/support/fake_response'

class FakeSinatraCall

  # Mimic's the context that is accessible in a Sinatra' route. Should provide
  # any methods needed to replace using an actual Sinatra app.

  attr_accessor :request, :response, :params, :logger, :router, :session
  attr_accessor :settings

  def initialize(settings = nil)
    @request         = FakeRequest.new
    @response        = FakeResponse.new
    @session         = @request.session
    @params          = @request.params
    @logger          = Deas::NullLogger.new
    @router          = Deas::Router.new
    @template_source = Deas::NullTemplateSource.new

    @content_type = nil
    @status       = 200
    @headers      = {}

    @settings = OpenStruct.new(settings || {})
  end

  def call(env)
    [@response.status, @response.headers, [@response.body]]
  end

  def halt(*args)
    throw :halt, args
  end

  def redirect(*args)
    halt 302, { 'Location' => args[0] }
  end

  def content_type(*args)
    return @content_type if args.empty?
    opts, value = [
      args.last.kind_of?(Hash) ? args.pop : {},
      args.last
    ]
    opts_value = opts.keys.map{ |k| "#{k}=#{opts[k]}" }.join(';')
    @content_type = [value, opts_value].reject{ |v| v.to_s.empty? }.join(';')
  end

  def status(*args)
    return @status if args.empty?
    @status = args.last
  end

  def headers(*args)
    return @headers if args.empty?
    @headers = args.last
  end

  def send_file(file_path, opts, &block)
    if block
      SendFileArgs.new(file_path, opts, block.call)
    else
      SendFileArgs.new(file_path, opts, nil)
    end
  end
  SendFileArgs = Struct.new(:file_path, :options, :block_call_result)

end


text:
@interface JavaUtilDuplicateFormatFlagsException : JavaUtilIllegalFormatException {
}

- (instancetype)initWithNSString:(NSString *)f;

- (NSString *)getFlags;

- (NSString *)getMessage;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaUtilDuplicateFormatFlagsException)

CF_EXTERN_C_BEGIN

J2OBJC_STATIC_FIELD_GETTER(JavaUtilDuplicateFormatFlagsException, serialVersionUID, jlong)
CF_EXTERN_C_END

J2OBJC_TYPE_LITERAL_HEADER(JavaUtilDuplicateFormatFlagsException)

#endif // _JavaUtilDuplicateFormatFlagsException_H_


text:
\hypertarget{classpkg__commands_1_1InventoryCommand}{\section{pkg\-\_\-commands.\-Inventory\-Command Class Reference}
\label{classpkg__commands_1_1InventoryCommand}\index{pkg\-\_\-commands.\-Inventory\-Command@{pkg\-\_\-commands.\-Inventory\-Command}}
}

class \hyperlink{classpkg__commands_1_1InventoryCommand}{Inventory\-Command} used to print the player's inventory

Inheritance diagram for pkg\-\_\-commands.\-Inventory\-Command\-:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=254pt]{classpkg__commands_1_1InventoryCommand__inherit__graph}
\end{center}
\end{figure}

Collaboration diagram for pkg\-\_\-commands.\-Inventory\-Command\-:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=254pt]{classpkg__commands_1_1InventoryCommand__coll__graph}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{classpkg__commands_1_1InventoryCommand_a4ca959fe6979e5ca2a79a0596803533d}{Inventory\-Command} ()
\begin{DoxyCompactList}\small\item\em Constructor for \hyperlink{classpkg__commands_1_1InventoryCommand}{Inventory\-Command}. \end{DoxyCompactList}\item
boolean \hyperlink{classpkg__commands_1_1InventoryCommand_a16ce9e3db461ecb7c4a50d2bdef65022}{execute} (\hyperlink{classpkg__world_1_1Player}{Player} player)
\begin{DoxyCompactList}\small\item\em Save the inventory into the message field. \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}

\subsection{Detailed Description}
class \hyperlink{classpkg__commands_1_1InventoryCommand}{Inventory\-Command} used to print the player's inventory

\begin{DoxyAuthor}{Author}
Rémi Nicole
\end{DoxyAuthor}

Definition at line \hyperlink{InventoryCommand_8java_source_l00009}{9} of file \hyperlink{InventoryCommand_8java_source}{Inventory\-Command.\-java}.

\subsection{Constructor \& Destructor Documentation}
\hypertarget{classpkg__commands_1_1InventoryCommand_a4ca959fe6979e5ca2a79a0596803533d}{\index{pkg\-\_\-commands\-::\-Inventory\-Command@{pkg\-\_\-commands\-::\-Inventory\-Command}!Inventory\-Command@{Inventory\-Command}}
\index{Inventory\-Command@{Inventory\-Command}!pkg_commands::InventoryCommand@{pkg\-\_\-commands\-::\-Inventory\-Command}}
\subsubsection[{Inventory\-Command}]{\setlength{\rightskip}{0pt plus 5cm}pkg\-\_\-commands.\-Inventory\-Command.\-Inventory\-Command (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}}\label{classpkg__commands_1_1InventoryCommand_a4ca959fe6979e5ca2a79a0596803533d}

Constructor for \hyperlink{classpkg__commands_1_1InventoryCommand}{Inventory\-Command}.

Definition at line \hyperlink{InventoryCommand_8java_source_l00014}{14} of file \hyperlink{InventoryCommand_8java_source}{Inventory\-Command.\-java}.

\begin{DoxyCode}
00014                              \{
00015
00016     \}
\end{DoxyCode}

\subsection{Member Function Documentation}
\hypertarget{classpkg__commands_1_1InventoryCommand_a16ce9e3db461ecb7c4a50d2bdef65022}{\index{pkg\-\_\-commands\-::\-Inventory\-Command@{pkg\-\_\-commands\-::\-Inventory\-Command}!execute@{execute}}
\index{execute@{execute}!pkg_commands::InventoryCommand@{pkg\-\_\-commands\-::\-Inventory\-Command}}
\subsubsection[{execute}]{\setlength{\rightskip}{0pt plus 5cm}boolean pkg\-\_\-commands.\-Inventory\-Command.\-execute (
\begin{DoxyParamCaption}
\item[{{\bf Player}}]{player}
\end{DoxyParamCaption}
)}}\label{classpkg__commands_1_1InventoryCommand_a16ce9e3db461ecb7c4a50d2bdef65022}

Save the inventory into the message field.

\begin{DoxyParams}{Parameters}
{\em player} & The player that called this command \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
False because it is not the quit command
\end{DoxyReturn}

Definition at line \hyperlink{InventoryCommand_8java_source_l00023}{23} of file \hyperlink{InventoryCommand_8java_source}{Inventory\-Command.\-java}.

References \hyperlink{Player_8java_source_l00229}{pkg\-\_\-world.\-Player.\-get\-Inventory()}, and \hyperlink{Command_8java_source_l00089}{pkg\-\_\-commands.\-Command.\-set\-Message()}.

\begin{DoxyCode}
00023                                           \{
00024         \hyperlink{classpkg__commands_1_1Command_ae210ff216fe908b111ba1c988a963d13}{setMessage}(player.getInventory());
00025         \textcolor{keywordflow}{return} \textcolor{keyword}{false};
00026     \}
\end{DoxyCode}

Here is the call graph for this function\-:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=350pt]{classpkg__commands_1_1InventoryCommand_a16ce9e3db461ecb7c4a50d2bdef65022_cgraph}
\end{center}
\end{figure}

The documentation for this class was generated from the following file\-:\begin{DoxyCompactItemize}
\item
pkg\-\_\-commands/\hyperlink{InventoryCommand_8java}{Inventory\-Command.\-java}\end{DoxyCompactItemize}


text:
package org.gridkit.jvmtool.stacktrace;

import java.io.DataOutput;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

public class DataBuffer implements DataOutput {

    private byte[] buffer = new byte[512];
    private int size = 0;
    private java.io.DataOutputStream dos;

    public DataBuffer() {
        dos = new java.io.DataOutputStream(new StreamStub());
    }

    public void unloadTo(DataOutput out) throws IOException {
        out.write(buffer, 0, size);
        size = 0;
    }

    @Override
    public void write(int b) throws IOException {
        dos.write(b);
    }

    @Override
    public void write(byte[] b) throws IOException {
        dos.write(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        dos.write(b, off, len);
    }

    @Override
    public void writeBoolean(boolean v) throws IOException {
        dos.writeBoolean(v);
    }

    @Override
    public void writeByte(int v) throws IOException {
        dos.writeByte(v);
    }

    @Override
    public void writeShort(int v) throws IOException {
        dos.writeShort(v);
    }

    @Override
    public void writeChar(int v) throws IOException {
        dos.writeChar(v);
    }

    @Override
    public void writeInt(int v) throws IOException {
        dos.writeInt(v);
    }

    @Override
    public void writeLong(long v) throws IOException {
        dos.writeLong(v);
    }

    @Override
    public void writeFloat(float v) throws IOException {
        dos.writeFloat(v);
    }

    @Override
    public void writeDouble(double v) throws IOException {
        dos.writeDouble(v);
    }

    @Override
    public void writeBytes(String s) throws IOException {
        dos.writeBytes(s);
    }

    @Override
    public void writeChars(String s) throws IOException {
        dos.writeChars(s);
    }

    @Override
    public void writeUTF(String s) throws IOException {
        dos.writeUTF(s);
    }

    private class StreamStub extends OutputStream {

        @Override
        public void write(int b) throws IOException {
            ensureSize(size + 1);
            buffer[size] = (byte) b;
            size++;
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            ensureSize(size + len);
            System.arraycopy(b, off, buffer, size, len);
            size += len;
        }

        private void ensureSize(int size) {
            while (buffer.length < size) {
                buffer = Arrays.copyOf(buffer, 2 * buffer.length);
            }
        }
    }
}


text:
sudo apt-get update -y && sudo apt-get upgrade -y
sudo apt-get install -y php php-mysql libapache2-mod-php7.0


text:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');

require_once("config.php");

if(!isConnected() || !isadmin()){
    header('Location: index.php');
};

$q=$bdd->query("SELECT * FROM faq ORDER BY id asc");
?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Interface d'administration - M'Effleure La Muse</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/simple-sidebar.css" rel="stylesheet">
    <link href="css/custom.css" rel="stylesheet">

                        M'Effleure La Muse

                    Gestion des questions

                    Gestion page d'accueil

                    Gestion des utilisateurs

                    Gestion des questions

                    Déconnexion

Gestion de la foire aux questions

                        Ajouter une nouvelle question

Questions en ligne actuellement

                    <button class="btn btn-default btn-xs btn-filter"> Filtrer</button>

                        <input type="text" class="form-control" placeholder="ID" disabled>
                        <input type="text" class="form-control" placeholder="Question" disabled>
                        <input type="text" class="form-control" placeholder="Réponse" disabled>
                        <input type="text" class="form-control" placeholder="Catégorie" disabled>
                        <input type="text" class="form-control" placeholder="Modification" disabled>
                        <input type="text" class="form-control" placeholder="Suppression" disabled>

                    <?php while($question = $q-> fetch()) {
                    echo("
");
                        echo("".$question['id']."	");
                        echo("".$question['question']."	");
                        echo("".$question['reponse']."	");
                        echo("".$question['categorie']."	");
                        echo("Modifier cette question");
                        echo("Supprimer cette question");
                    echo("
");
                    } ?>

                        Deconnexion


text:
/*
* (C) 1999-2010,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/pubkey.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/bigint.h>
#include <botan/pk_ops.h>
#include <botan/internal/ct_utils.h>
#include <botan/rng.h>

namespace Botan {

secure_vector<uint8_t> PK_Decryptor::decrypt(const uint8_t in[], size_t length) const
   {
   uint8_t valid_mask = 0;

   secure_vector<uint8_t> decoded = do_decrypt(valid_mask, in, length);

   if(valid_mask == 0)
      throw Decoding_Error("Invalid public key ciphertext, cannot decrypt");

   return decoded;
   }

secure_vector<uint8_t>
PK_Decryptor::decrypt_or_random(const uint8_t in[],
                                size_t length,
                                size_t expected_pt_len,
                                RandomNumberGenerator& rng,
                                const uint8_t required_content_bytes[],
                                const uint8_t required_content_offsets[],
                                size_t required_contents_length) const
   {
   const secure_vector<uint8_t> fake_pms = rng.random_vec(expected_pt_len);

   uint8_t valid_mask = 0;
   secure_vector<uint8_t> decoded = do_decrypt(valid_mask, in, length);

   valid_mask &= CT::is_equal(decoded.size(), expected_pt_len);

   decoded.resize(expected_pt_len);

   for(size_t i = 0; i != required_contents_length; ++i)
      {
      /*
      These values are chosen by the application and for TLS are constants,
      so this early failure via assert is fine since we know 0,1 < 48

      If there is a protocol that has content checks on the key where
      the expected offsets are controllable by the attacker this could
      still leak.

      Alternately could always reduce the offset modulo the length?
      */

      const uint8_t exp = required_content_bytes[i];
      const uint8_t off = required_content_offsets[i];

      BOTAN_ASSERT(off < expected_pt_len, "Offset in range of plaintext");

      valid_mask &= CT::is_equal(decoded[off], exp);
      }

   CT::conditional_copy_mem(valid_mask,
                            /*output*/decoded.data(),
                            /*from0*/decoded.data(),
                            /*from1*/fake_pms.data(),
                            expected_pt_len);

   return decoded;
   }

secure_vector<uint8_t>
PK_Decryptor::decrypt_or_random(const uint8_t in[],
                                size_t length,
                                size_t expected_pt_len,
                                RandomNumberGenerator& rng) const
   {
   return decrypt_or_random(in, length, expected_pt_len, rng,
                            nullptr, nullptr, 0);
   }

PK_Encryptor_EME::PK_Encryptor_EME(const Public_Key& key,
                                   RandomNumberGenerator& rng,
                                   const std::string& padding,
                                   const std::string& provider)
   {
   m_op = key.create_encryption_op(rng, padding, provider);
   if(!m_op)
      throw Invalid_Argument("Key type " + key.algo_name() + " does not support encryption");
   }

PK_Encryptor_EME::~PK_Encryptor_EME() { /* for unique_ptr */ }

std::vector<uint8_t>
PK_Encryptor_EME::enc(const uint8_t in[], size_t length, RandomNumberGenerator& rng) const
   {
   return unlock(m_op->encrypt(in, length, rng));
   }

size_t PK_Encryptor_EME::maximum_input_size() const
   {
   return m_op->max_input_bits() / 8;
   }

PK_Decryptor_EME::PK_Decryptor_EME(const Private_Key& key,
                                   RandomNumberGenerator& rng,
                                   const std::string& padding,
                                   const std::string& provider)
   {
   m_op = key.create_decryption_op(rng, padding, provider);
   if(!m_op)
      throw Invalid_Argument("Key type " + key.algo_name() + " does not support decryption");
   }

PK_Decryptor_EME::~PK_Decryptor_EME() { /* for unique_ptr */ }

secure_vector<uint8_t> PK_Decryptor_EME::do_decrypt(uint8_t& valid_mask,
                                                 const uint8_t in[], size_t in_len) const
   {
   return m_op->decrypt(valid_mask, in, in_len);
   }

PK_KEM_Encryptor::PK_KEM_Encryptor(const Public_Key& key,
                                   RandomNumberGenerator& rng,
                                   const std::string& param,
                                   const std::string& provider)
   {
   m_op = key.create_kem_encryption_op(rng, param, provider);
   if(!m_op)
      throw Invalid_Argument("Key type " + key.algo_name() + " does not support KEM encryption");
   }

PK_KEM_Encryptor::~PK_KEM_Encryptor() { /* for unique_ptr */ }

void PK_KEM_Encryptor::encrypt(secure_vector<uint8_t>& out_encapsulated_key,
                               secure_vector<uint8_t>& out_shared_key,
                               size_t desired_shared_key_len,
                               Botan::RandomNumberGenerator& rng,
                               const uint8_t salt[],
                               size_t salt_len)
   {
   m_op->kem_encrypt(out_encapsulated_key,
                     out_shared_key,
                     desired_shared_key_len,
                     rng,
                     salt,
                     salt_len);
   }

PK_KEM_Decryptor::PK_KEM_Decryptor(const Private_Key& key,
                                   RandomNumberGenerator& rng,
                                   const std::string& param,
                                   const std::string& provider)
   {
   m_op = key.create_kem_decryption_op(rng, param, provider);
   if(!m_op)
      throw Invalid_Argument("Key type " + key.algo_name() + " does not support KEM decryption");
   }

PK_KEM_Decryptor::~PK_KEM_Decryptor() { /* for unique_ptr */ }

secure_vector<uint8_t> PK_KEM_Decryptor::decrypt(const uint8_t encap_key[],
                                              size_t encap_key_len,
                                              size_t desired_shared_key_len,
                                              const uint8_t salt[],
                                              size_t salt_len)
   {
   return m_op->kem_decrypt(encap_key, encap_key_len,
                            desired_shared_key_len,
                            salt, salt_len);
   }

PK_Key_Agreement::PK_Key_Agreement(const Private_Key& key,
                                   RandomNumberGenerator& rng,
                                   const std::string& kdf,
                                   const std::string& provider)
   {
   m_op = key.create_key_agreement_op(rng, kdf, provider);
   if(!m_op)
      throw Invalid_Argument("Key type " + key.algo_name() + " does not support key agreement");
   }

PK_Key_Agreement::~PK_Key_Agreement() { /* for unique_ptr */ }

PK_Key_Agreement& PK_Key_Agreement::operator=(PK_Key_Agreement&& other)
   {
   if(this != &other)
      {
      m_op = std::move(other.m_op);
      }
   return (*this);
   }

PK_Key_Agreement::PK_Key_Agreement(PK_Key_Agreement&& other) :
   m_op(std::move(other.m_op))
   {}

SymmetricKey PK_Key_Agreement::derive_key(size_t key_len,
                                          const uint8_t in[], size_t in_len,
                                          const uint8_t salt[],
                                          size_t salt_len) const
   {
   return m_op->agree(key_len, in, in_len, salt, salt_len);
   }

PK_Signer::PK_Signer(const Private_Key& key,
                     RandomNumberGenerator& rng,
                     const std::string& emsa,
                     Signature_Format format,
                     const std::string& provider)
   {
   m_op = key.create_signature_op(rng, emsa, provider);
   if(!m_op)
      throw Invalid_Argument("Key type " + key.algo_name() + " does not support signature generation");
   m_sig_format = format;
   m_parts = key.message_parts();
   m_part_size = key.message_part_size();
   }

PK_Signer::~PK_Signer() { /* for unique_ptr */ }

void PK_Signer::update(const uint8_t in[], size_t length)
   {
   m_op->update(in, length);
   }

std::vector<uint8_t> PK_Signer::signature(RandomNumberGenerator& rng)
   {
   const std::vector<uint8_t> sig = unlock(m_op->sign(rng));

   if(m_sig_format == IEEE_1363)
      {
      return sig;
      }
   else if(m_sig_format == DER_SEQUENCE)
      {
      if(sig.size() % m_parts != 0 || sig.size() != m_parts * m_part_size)
         throw Internal_Error("PK_Signer: DER signature sizes unexpected, cannot encode");

      std::vector<BigInt> sig_parts(m_parts);
      for(size_t i = 0; i != sig_parts.size(); ++i)
         sig_parts[i].binary_decode(&sig[m_part_size*i], m_part_size);

      return DER_Encoder()
         .start_cons(SEQUENCE)
         .encode_list(sig_parts)
         .end_cons()
         .get_contents_unlocked();
      }
   else
      throw Internal_Error("PK_Signer: Invalid signature format enum");
   }

PK_Verifier::PK_Verifier(const Public_Key& key,
                         const std::string& emsa,
                         Signature_Format format,
                         const std::string& provider)
   {
   m_op = key.create_verification_op(emsa, provider);
   if(!m_op)
      throw Invalid_Argument("Key type " + key.algo_name() + " does not support signature verification");
   m_sig_format = format;
   m_parts = key.message_parts();
   m_part_size = key.message_part_size();
   }

PK_Verifier::~PK_Verifier() { /* for unique_ptr */ }

void PK_Verifier::set_input_format(Signature_Format format)
   {
   if(format != IEEE_1363 && m_parts == 1)
      throw Invalid_Argument("PK_Verifier: This algorithm does not support DER encoding");
   m_sig_format = format;
   }

bool PK_Verifier::verify_message(const uint8_t msg[], size_t msg_length,
                                 const uint8_t sig[], size_t sig_length)
   {
   update(msg, msg_length);
   return check_signature(sig, sig_length);
   }

void PK_Verifier::update(const uint8_t in[], size_t length)
   {
   m_op->update(in, length);
   }

bool PK_Verifier::check_signature(const uint8_t sig[], size_t length)
   {
   try {
      if(m_sig_format == IEEE_1363)
         {
         return m_op->is_valid_signature(sig, length);
         }
      else if(m_sig_format == DER_SEQUENCE)
         {
         std::vector<uint8_t> real_sig;
         BER_Decoder decoder(sig, length);
         BER_Decoder ber_sig = decoder.start_cons(SEQUENCE);

         size_t count = 0;
         while(ber_sig.more_items())
            {
            BigInt sig_part;
            ber_sig.decode(sig_part);
            real_sig += BigInt::encode_1363(sig_part, m_part_size);
            ++count;
            }

         if(count != m_parts)
            throw Decoding_Error("PK_Verifier: signature size invalid");

         return m_op->is_valid_signature(real_sig.data(), real_sig.size());
         }
      else
         throw Internal_Error("PK_Verifier: Invalid signature format enum");
      }
   catch(Invalid_Argument&) { return false; }
   }

}


text:
import logging
import os
import time
from os import listdir

import openerp
from openerp import http
from openerp.http import request
from openerp.tools.translate import _

_logger = logging.getLogger(__name__)

index_template = """
<!DOCTYPE HTML>

        <title>Odoo's PosBox</title>

Your PosBox is up and running

        The PosBox is an hardware adapter that allows you to use
        receipt printers and barcode scanners with Odoo's Point of
        Sale, version 8.0 or later. You can start an online free trial,
        or download and install it yourself.

        For more information on how to setup the Point of Sale with
        the PosBox, please refer to the manual

        To see the status of the connected hardware, please refer
        to the hardware status page

        The PosBox software installed on this posbox is version 6,
        the posbox version number is independent from Odoo. You can upgrade
        the software on the upgrade page

For any other question, please contact the Odoo support at support@odoo.com

"""

class PosboxHomepage(openerp.addons.web.controllers.main.Home):
    @http.route('/', type='http', auth='none', website=True)
    def index(self):
        #return request.render('hw_posbox_homepage.index',mimetype='text/html')
        return index_template


text:
<?php

//create all possible Zend_Db_Tables

class Users extends Zend_Db_Table_Abstract {
    protected $_name = 'users';
}

//Master model
class Admin extends MyModel {
    function getClass($cname){
        switch ($cname) {
            case 'Users':
                return new Users();
            case 'DJs':
                return new DJs();
            default:
                return false;

        }
    }
    function getUser($id){
        return $this->getObject('Users', $id);
    }
    function getUserByUsername($username){
        $users = $this->findRowByColumn($username, 'username');
        if(!$users){
            return false;
        }
        return $users[0];
    }
    function updateUser($data){
	    $id = $this->updateObject('Users', $data);
	    return $id;
    }

    function findUsersByName($search_term){
		$class = new Users();
		$db = $class->getAdapter();
		//uses fulltext search for quick and dirty magic search
		$sql = "    SELECT *,
		                MATCH(username,email,name_last, name_first, dj_name, dj_email) AGAINST(? IN BOOLEAN MODE) AS score
		                FROM users
		            WHERE MATCH(username,email,name_last, name_first, dj_name, dj_email) AGAINST(? IN BOOLEAN MODE)
		            ORDER BY score DESC
		        ";
		$stmt = $db->query($sql, array($search_term.'*', $search_term.'*'));
		$rows = $stmt->fetchAll();

		/*
		$where = '';
		$where .= $db->quoteInto('username LIKE ?', '%'.$search_term.'%');
		$where .= $db->quoteInto(' OR name_last LIKE ?', '%'.$search_term.'%');
		$where .= $db->quoteInto(' OR name_first LIKE ?', '%'.$search_term.'%');
		$order = array('name_last', 'name_first');
		$rows = $class->fetchAll($where,$order); */

		return $rows;

	}
	function findRowByColumn($value, $column){

		$table = new Users();

		$where = $table->getAdapter()->quoteInto($column . ' = ?', $value);

		$rows = $table->fetchAll($where);

		if(!$rows){
		    return false;
	    }
		$rows = $rows->toArray();
		return $rows;
	}
    function getAllUsers(){ //returns an array of all the users
        $table = new Users();
        $rows = $table->fetchAll(null, 'id');
        return $rows->toArray();
    }
    function getAllDJs(){ //returns an array of all the djs
        $table = new Users();
        $rows = $table->fetchAll(null, 'dj_name');
        return $rows->toArray();
    }
	function getAllDJInfo(){ //returns an array of all the djs with each dj indexed by their id
        $table = new Users();
        $rows = $table->fetchAll(null, 'dj_name')->toArray();
        $new_array = array();
		foreach($rows as $row){
			$new_array[$row['id']] = $row;
		}
		return $new_array;
    }

}


text:
import { Component, OnInit, ViewChild } from '@angular/core';

import { Country } from '../bll/country';
import { CountryService } from '../services/country.service';
import { Order } from '../bll/order';
import { Company } from '../bll/company';
import { Person } from '../bll/person';
import { GlobalFunctionsService } from '../services/global-functions.service';
import { Router } from '@angular/router';
import { CanComponentDeactivate } from '../validation.guard';
import { PostalCodeService } from '../services/postalcode.service';
import { environment } from '../../environments/environment';

@Component({
  moduleId: module.id,
  selector: 'fo-contactinfo',
  templateUrl: './contactinfo.component.html',
  providers: [CountryService, PostalCodeService]
})

export class ContactinfoComponent implements OnInit, CanComponentDeactivate {

  countries: Country[];
  seatsAvailable = 0;
  formDeactivationCheck = false;

  order: Order = new Order();

  @ViewChild('contactForm') form;

  constructor(private countryService: CountryService,
              private globalFunctionsService: GlobalFunctionsService,
              private postalCodeService: PostalCodeService,
              private router: Router) {
    this.globalFunctionsService.showBasket(true);
    this.globalFunctionsService.showTabs(true);
  }

  getCountries(): void {
    this.countryService.getCountries().then(countries => this.countries = countries);
  }

  toggleSelf(): void {
    this.globalFunctionsService.updateStudentCount((this.order.Students ? this.order.Students.length : 0) + (this.order.FirstStudentIsContact ? 1 : 0));
  }

  toggleStudents(): void {
    if (this.order.MultipleStudents) {
      const student = new Person();
      student.CountryId = 'NL';
      this.order.Students = [student];
      this.globalFunctionsService.updateStudentCount(this.order.Students.length + (this.order.FirstStudentIsContact ? 1 : 0));
    } else {
      this.order.Students = [];
      this.globalFunctionsService.updateStudentCount(this.order.Students.length + (this.order.FirstStudentIsContact ? 1 : 0));
    }
  }

  addStudent(): void {
    if ((this.seatsAvailable - (this.order.Students.length + (this.order.FirstStudentIsContact ? 1 : 0))) > 0 && environment.clientCode !== 'gt') {
      const student = new Person();
      student.CountryId = 'NL';
      this.order.Students.push(student);

      this.globalFunctionsService.updateStudentCount(this.order.Students.length + (this.order.FirstStudentIsContact ? 1 : 0));
    }
  }

  removeStudent(student: Person): void {
    this.order.Students = this.order.Students.filter(s => s !== student);
    this.order.MultipleStudents = this.order.Students.length > 0;

    this.globalFunctionsService.updateStudentCount(this.order.Students.length + (this.order.FirstStudentIsContact ? 1 : 0));
  }

  saveInfo(isValid: boolean): void {
    if (isValid) {
      this.globalFunctionsService.updateOrder(this.order);
      this.globalFunctionsService.enableTabs(3);

      // Redirect
      // TODO: Animate
      window.scrollTo(0, 0);
      this.router.navigate(['payment'], {queryParamsHandling: 'merge'});
    }
  }

  previousTab(): void {
    // Redirect
    // TODO: Animate
    window.scrollTo(0, 0);
    this.router.navigate(['courses'], {queryParamsHandling: 'merge'});
  }

  ngOnInit(): void {
    this.order = this.globalFunctionsService.getOrder();
    if (!this.order) {
      // Initial Values
      this.order = new Order();
      this.order.OrderType = environment.clientCode === 'gt' ? 'Company' : 'Private';
      this.order.ContactPerson = new Person();
      this.order.ContactPerson.CountryId = 'NL';
      this.order.Company = new Company();
      this.order.Company.CountryId = 'NL';
      this.order.InvoicePerson = new Person();
      this.order.InvoicePerson.CountryId = 'NL';
      this.order.InvoiceCompany = new Company();
      this.order.InvoiceCompany.CountryId = 'NL';
      this.order.Students = [];

      // Update Storage
      this.globalFunctionsService.updateOrder(this.order);
    }

    this.getCountries();

    // Available Seats
    this.seatsAvailable = this.globalFunctionsService.getSelectedCourse().AvailableSeats;
  }

  canDeactivate(): boolean {
    this.formDeactivationCheck = true;
    return this.form.valid && (this.order.FirstStudentIsContact || this.order.MultipleStudents);
  }

  getAddress(): void {
    this.postalCodeService.getAddress(this.order.ContactPerson.PostalCode, this.order.ContactPerson.AddressNumber)
      .then(address => {
        this.order.ContactPerson.Address = address.Street;
        this.order.ContactPerson.City = address.City;
      })
      .catch(() => {
        // Ignore Errors.
      });
  }

  getStudentAddress(student: Person): void {
    this.postalCodeService.getAddress(student.PostalCode, student.AddressNumber)
      .then(address => {
        student.Address = address.Street;
        student.City = address.City;
      })
      .catch(() => {
        // Ignore Errors.
      });
  }
}


text:
package ru.job4j.List;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class SimpleLinkedList<E> implements Iterable<E> {
    private Node head;
    private int index = 0;
    private int length;

    public int getLength() { return this.length; }

    public void setLength(int length) { this.length = length; }

    public void setHead(Node head) { this.head = head; }

    public void add(E value){
        Node node = new Node();
        node.setValue(value);
        node.setNext(null);
      if(head == null){
          head = node;
          length = 1;
      } else {
          Node temp = head;
          while(temp.getNext() != null){
              temp = temp.getNext();
          }
          temp.setNext(node);
          length++;
      }
    }

    public E getValue(int index){
        Node node = head;
        for(int i = 0; i < index; i++){
            node = node.getNext();
        }
        return (E)node.getValue();
    }
    public Node getNode(int index){
        Node node = head;
        for(int i = 0; i < index; i++){
            node = node.getNext();
        }
        return node;
    }
    public boolean hasCycle(Node first){
        boolean result = false;
        Node node1 = first;
        Node node2 = first;
        while(node1.getNext() != null && node2.getNext()!= null && node2.getNext().getNext() != null){
            node1 = node1.getNext();
            node2 = node2.getNext().getNext();
            if(node1.equals(node2)){
                result = true;
                break;
            }
        }
        return result;
    }
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            @Override
            public boolean hasNext() {
                return index < length;
            }

            @Override
            public E next() {
                if(this.hasNext()){
                    return getValue(index++);
                } else {
                    throw new NoSuchElementException();
                }

            }
        };
    }
}


text:
describe('kargo adapter tests', function () {
  const expect = require('chai').expect;
  const assert = require('chai').assert;
  const adapter = require('modules/kargoBidAdapter');
  const bidmanager = require('src/bidmanager');
  const bidfactory = require('src/bidfactory');
  const adloader = require('src/adloader');
  const CONSTANTS = require('src/constants.json');

  var sandbox, params, krakenParams, adUnits, bidFactorySpy, addBidResponseSpy, bodyAppendSpy, cookies = [], localStorageItems = [];

  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    addBidResponseSpy = sandbox.stub(bidmanager, 'addBidResponse');
    bodyAppendSpy = sandbox.stub(document.body, 'appendChild');
    simulateBidFactory();
    simulateAdLoader();

    params = {
      timeout: 200,
      requestId: 'f4cf851b-665a-43d7-b22c-33c8fdebe577',
      bids: [
        {
          params: {
            placementId: 'foo'
          },
          placementCode: 1
        },
        {
          params: {
            placementId: 'bar'
          },
          placementCode: 2
        }
      ]
    };

    adUnits = {
      foo: {
        receivedTracker: 'fake-tracker-1',
        cpm: 3,
        adm: '

',
        width: 320,
        height: 50
      },
      bar: {
        cpm: 2.5,
        adm: '

',
        width: 300,
        height: 250
      }
    }
  });

  afterEach(() => {
    sandbox.restore();

    for (let cookie of cookies) {
      removeCookie(cookie);
    }

    for (let localStorageItem of localStorageItems) {
      localStorage.removeItem(localStorageItem);
    }

    cookies.length = 0;
    localStorageItems.length = 0;
  });

  function setCookie(cname, cvalue, exdays = 1) {
    _setCookie(cname, cvalue, exdays);
    cookies.push(cname);
  }

  function removeCookie(cname) {
    _setCookie(cname, '', -1);
  }

  function _setCookie(cname, cvalue, exdays = 1) {
    var d = new Date(),
      expires;

    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    expires = `expires=${d.toUTCString()}`;
    document.cookie = `${cname}=${cvalue};${expires};path=/`;
  }

  function setLocalStorageItem(name, val) {
    localStorage.setItem(name, val);
    localStorageItems.push(name);
  }

  function simulateAdLoader() {
    sandbox.stub(adloader, 'loadScript', (url) => {
      window.pbjs.kargo_prebid_f4cf851b_665a_43d7_b22c_33c8fdebe577(adUnits);
      krakenParams = JSON.parse(decodeURIComponent(url.match(/\?json=(.*)&cb=/)[1]));
    });
  }

  function simulateNoLocalStorage() {
    return sandbox.stub(localStorage, 'getItem').throws();
  }

  function simulateBidFactory() {
    bidFactorySpy = sandbox.stub(bidfactory, 'createBid').withArgs(CONSTANTS.STATUS.GOOD);

    bidFactorySpy.onCall(0).returns({
      statusMessage: 'Bid available',
      adId: '12dd646671a959'
    });

    bidFactorySpy.onCall(1).returns({
      statusMessage: 'Bid available',
      adId: '33f07659bdaf94'
    });
  }

  function initializeKruxUser() {
    setLocalStorageItem('kxkar_user', 'rsgr9pnij');
  }

  function initializeKruxSegments() {
    setLocalStorageItem('kxkar_segs', 'qv9v984dy,rpx2gy365,qrd5u4axv,rnub9nmtd,reha00jnu');
  }

  function initializeKrgUid() {
    setCookie('krg_uid', '%7B%22v%22%3A%7B%22userId%22%3A%225f108831-302d-11e7-bf6b-4595acd3bf6c%22%2C%22clientId%22%3A%222410d8f2-c111-4811-88a5-7b5e190e475f%22%2C%22optOut%22%3Afalse%7D%7D');
  }

  function initializeKrgCrb() {
    setCookie('krg_crb', '%7B%22v%22%3A%22eyJzeW5jSWRzIjp7IjIiOiI4MmZhMjU1NS01OTY5LTQ2MTQtYjRjZS00ZGNmMTA4MGU5ZjkiLCIxNiI6IlZveElrOEFvSnowQUFFZENleUFBQUFDMiY1MDIiLCIyMyI6ImQyYTg1NWE1LTFiMWMtNDMwMC05NDBlLWE3MDhmYTFmMWJkZSIsIjI0IjoiVm94SWs4QW9KejBBQUVkQ2V5QUFBQUMyJjUwMiIsIjI1IjoiNWVlMjQxMzgtNWUwMy00YjlkLWE5NTMtMzhlODMzZjI4NDlmIiwiMl84MCI6ImQyYTg1NWE1LTFiMWMtNDMwMC05NDBlLWE3MDhmYTFmMWJkZSIsIjJfOTMiOiI1ZWUyNDEzOC01ZTAzLTRiOWQtYTk1My0zOGU4MzNmMjg0OWYifSwiZXhwaXJlVGltZSI6MTQ5NzQ0OTM4MjY2OCwibGFzdFN5bmNlZEF0IjoxNDk3MzYyOTc5MDEyfQ%3D%3D%22%7D');
  }

  function initializeInvalidKrgUid() {
    setCookie('krg_uid', 'invalid-krg-uid');
  }

  function initializeInvalidKrgCrbType1() {
    setCookie('krg_crb', 'invalid-krg-crb');
  }

  function initializeInvalidKrgCrbType2() {
    setCookie('krg_crb', '%7B%22v%22%3A%22%26%26%26%26%26%26%22%7D');
  }

  function initializeInvalidKrgCrbType3() {
    setCookie('krg_crb', '%7B%22v%22%3A%22Ly8v%22%7D');
  }

  function initializeEmptyKrgUid() {
    setCookie('krg_uid', '%7B%7D');
  }

  function initializeEmptyKrgCrb() {
    setCookie('krg_crb', '%7B%22v%22%3A%22eyJleHBpcmVUaW1lIjoxNDk3NDQ5MzgyNjY4LCJsYXN0U3luY2VkQXQiOjE0OTczNjI5NzkwMTJ9%22%7D');
  }

  function getExpectedKrakenParams(excludeUserIds, excludeKrux) {
    var base = {
      timeout: 200,
      currency: 'USD',
      cpmGranularity: 1,
      cpmRange: {
        floor: 0,
        ceil: 20
      },
      adSlotIds: [
        'foo',
        'bar'
      ],
      userIDs: {
        kargoID: '5f108831-302d-11e7-bf6b-4595acd3bf6c',
        clientID: '2410d8f2-c111-4811-88a5-7b5e190e475f',
        crbIDs: {
          2: '82fa2555-5969-4614-b4ce-4dcf1080e9f9',
          16: 'VoxIk8AoJz0AAEdCeyAAAAC2&502',
          23: 'd2a855a5-1b1c-4300-940e-a708fa1f1bde',
          24: 'VoxIk8AoJz0AAEdCeyAAAAC2&502',
          25: '5ee24138-5e03-4b9d-a953-38e833f2849f',
          '2_80': 'd2a855a5-1b1c-4300-940e-a708fa1f1bde',
          '2_93': '5ee24138-5e03-4b9d-a953-38e833f2849f'
        },
        optOut: false
      },
      krux: {
        userID: 'rsgr9pnij',
        segments: [
          'qv9v984dy',
          'rpx2gy365',
          'qrd5u4axv',
          'rnub9nmtd',
          'reha00jnu'
        ]
      },
      pageURL: window.location.href
    };

    if (excludeUserIds === true) {
      base.userIDs = {
        crbIDs: {}
      };
    } else if (excludeUserIds) {
      if (excludeUserIds.uid) {
        delete base.userIDs.kargoID;
        delete base.userIDs.clientID;
        delete base.userIDs.optOut;
      }

      if (excludeUserIds.crb) {
        base.userIDs.crbIDs = {};
      }
    }

    if (excludeKrux) {
      base.krux = {
        userID: null,
        segments: []
      };
    }

    return base;
  }

  function getExpectedFirstBid() {
    return {
      'bidderCode': 'kargo',
      'width': 320,
      'height': 50,
      'statusMessage': 'Bid available',
      'adId': '12dd646671a959',
      'cpm': 3,
      'ad': '

'
    };
  }

  function getExpectedSecondBid() {
    return {
      'bidderCode': 'kargo',
      'width': 300,
      'height': 250,
      'statusMessage': 'Bid available',
      'adId': '33f07659bdaf94',
      'cpm': 2.5,
      'ad': '

'
    };
  }

  function generalAssertions() {
    assert(bidFactorySpy.calledTwice);

    assert(addBidResponseSpy.getCall(0).calledWithExactly(1, sinon.match(getExpectedFirstBid())));
    assert(addBidResponseSpy.getCall(1).calledWithExactly(2, sinon.match(getExpectedSecondBid())));
    assert(addBidResponseSpy.calledTwice);

    var trackerEl = bodyAppendSpy.getCall(0).args[0];
    assert(trackerEl instanceof HTMLImageElement);
    assert(trackerEl.src === `${window.location.origin}/fake-tracker-1`);
    assert(bodyAppendSpy.calledOnce);
  }

  it('works when all params and cookies are correctly set', function() {
    initializeKruxUser();
    initializeKruxSegments();
    initializeKrgUid();
    initializeKrgCrb();

    adapter().callBids(params);

    generalAssertions();
    expect(krakenParams).to.deep.equal(getExpectedKrakenParams());
  });

  it('gracefully handles nothing being set', function() {
    adapter().callBids(params);

    generalAssertions();
    expect(krakenParams).to.deep.equal(getExpectedKrakenParams(true, true));
  });

  it('gracefully handles browsers without localStorage', function() {
    simulateNoLocalStorage();
    initializeKrgUid();
    initializeKrgCrb();

    adapter().callBids(params);

    generalAssertions();
    expect(krakenParams).to.deep.equal(getExpectedKrakenParams(false, true));
  });

  it('handles empty yet valid Kargo CRBs and UIDs', function() {
    initializeKruxUser();
    initializeKruxSegments();
    initializeEmptyKrgUid();
    initializeEmptyKrgCrb();

    adapter().callBids(params);

    generalAssertions();
    expect(krakenParams).to.deep.equal(getExpectedKrakenParams(true));
  });

  it('handles broken Kargo UIDs', function() {
    initializeKruxUser();
    initializeKruxSegments();
    initializeInvalidKrgUid();
    initializeKrgCrb();

    adapter().callBids(params);

    generalAssertions();
    expect(krakenParams).to.deep.equal(getExpectedKrakenParams({uid: true}));
  });

  it('handles broken Kargo CRBs where top level JSON is invalid', function() {
    initializeKruxUser();
    initializeKruxSegments();
    initializeKrgUid();
    initializeInvalidKrgCrbType1();

    adapter().callBids(params);

    generalAssertions();
    expect(krakenParams).to.deep.equal(getExpectedKrakenParams({crb: true}));
  });

  it('handles broken Kargo CRBs where inner base 64 is invalid', function() {
    initializeKruxUser();
    initializeKruxSegments();
    initializeKrgUid();
    initializeInvalidKrgCrbType2();

    adapter().callBids(params);

    generalAssertions();
    expect(krakenParams).to.deep.equal(getExpectedKrakenParams({crb: true}));
  });

  it('handles broken Kargo CRBs where inner JSON is invalid', function() {
    initializeKruxUser();
    initializeKruxSegments();
    initializeKrgUid();
    initializeInvalidKrgCrbType3();

    adapter().callBids(params);

    generalAssertions();
    expect(krakenParams).to.deep.equal(getExpectedKrakenParams({crb: true}));
  });
});


text:
@interface HelloWorldLayer : CCLayer
{
    CCSprite * back;
}

// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;

@end


text:
package aws

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"sort"
	"strconv"
	"strings"

	"github.com/hashicorp/go-cleanhttp"
	"github.com/hashicorp/terraform/helper/schema"
)

type dataSourceAwsIPRangesResult struct {
	CreateDate string
	Prefixes   []dataSourceAwsIPRangesPrefix
	SyncToken  string
}

type dataSourceAwsIPRangesPrefix struct {
	IpPrefix string `json:"ip_prefix"`
	Region   string
	Service  string
}

func dataSourceAwsIPRanges() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsIPRangesRead,

		Schema: map[string]*schema.Schema{
			"cidr_blocks": {
				Type:     schema.TypeList,
				Computed: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
			},
			"create_date": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"regions": {
				Type:     schema.TypeSet,
				Elem:     &schema.Schema{Type: schema.TypeString},
				Optional: true,
			},
			"services": {
				Type:     schema.TypeSet,
				Required: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
			},
			"sync_token": {
				Type:     schema.TypeInt,
				Computed: true,
			},
		},
	}
}

func dataSourceAwsIPRangesRead(d *schema.ResourceData, meta interface{}) error {

	conn := cleanhttp.DefaultClient()

	log.Printf("[DEBUG] Reading IP ranges")

	res, err := conn.Get("https://ip-ranges.amazonaws.com/ip-ranges.json")

	if err != nil {
		return fmt.Errorf("Error listing IP ranges: %s", err)
	}

	defer res.Body.Close()

	data, err := ioutil.ReadAll(res.Body)

	if err != nil {
		return fmt.Errorf("Error reading response body: %s", err)
	}

	result := new(dataSourceAwsIPRangesResult)

	if err := json.Unmarshal(data, result); err != nil {
		return fmt.Errorf("Error parsing result: %s", err)
	}

	if err := d.Set("create_date", result.CreateDate); err != nil {
		return fmt.Errorf("Error setting create date: %s", err)
	}

	syncToken, err := strconv.Atoi(result.SyncToken)

	if err != nil {
		return fmt.Errorf("Error while converting sync token: %s", err)
	}

	d.SetId(result.SyncToken)

	if err := d.Set("sync_token", syncToken); err != nil {
		return fmt.Errorf("Error setting sync token: %s", err)
	}

	get := func(key string) *schema.Set {

		set := d.Get(key).(*schema.Set)

		for _, e := range set.List() {

			s := e.(string)

			set.Remove(s)
			set.Add(strings.ToLower(s))

		}

		return set

	}

	var (
		regions        = get("regions")
		services       = get("services")
		noRegionFilter = regions.Len() == 0
		prefixes       []string
	)

	for _, e := range result.Prefixes {

		var (
			matchRegion  = noRegionFilter || regions.Contains(strings.ToLower(e.Region))
			matchService = services.Contains(strings.ToLower(e.Service))
		)

		if matchRegion && matchService {
			prefixes = append(prefixes, e.IpPrefix)
		}

	}

	if len(prefixes) == 0 {
		return fmt.Errorf(" No IP ranges result from filters")
	}

	sort.Strings(prefixes)

	if err := d.Set("cidr_blocks", prefixes); err != nil {
		return fmt.Errorf("Error setting ip ranges: %s", err)
	}

	return nil

}


text:
namespace gandiva {

/// \brief Utility class for converting sql date patterns to internal date patterns.
class GANDIVA_EXPORT DateUtils {
 public:
  static Status ToInternalFormat(const std::string& format,
                                 std::shared_ptr<std::string>* internal_format);

 private:
  using date_format_converter = std::unordered_map<std::string, std::string>;

  static date_format_converter sql_date_format_to_boost_map_;

  static date_format_converter InitMap();

  static std::vector<std::string> GetMatches(std::string pattern, bool exactMatch);

  static std::vector<std::string> GetPotentialMatches(const std::string& pattern);

  static std::vector<std::string> GetExactMatches(const std::string& pattern);
};

namespace internal {

/// \brief Returns seconds since the UNIX epoch
static inline bool ParseTimestamp(const char* buf, const char* format,
                                  bool ignoreTimeInDay, int64_t* out) {
#if defined(_MSC_VER)
  static std::locale lc_all(setlocale(LC_ALL, NULLPTR));
  std::istringstream stream(buf);
  stream.imbue(lc_all);

  // TODO: date::parse fails parsing when the hour value is 0.
  // eg.1886-12-01 00:00:00
  arrow_vendored::date::sys_seconds seconds;
  if (ignoreTimeInDay) {
    arrow_vendored::date::sys_days days;
    stream >> arrow_vendored::date::parse(format, days);
    if (stream.fail()) {
      return false;
    }
    seconds = days;
  } else {
    stream >> arrow_vendored::date::parse(format, seconds);
    if (stream.fail()) {
      return false;
    }
  }
  auto seconds_in_epoch = seconds.time_since_epoch().count();
  *out = seconds_in_epoch;
  return true;
#else
  struct tm result;
  char* ret = strptime(buf, format, &result);
  if (ret == NULLPTR) {
    return false;
  }
  // ignore the time part
  arrow_vendored::date::sys_seconds secs =
      arrow_vendored::date::sys_days(arrow_vendored::date::year(result.tm_year + 1900) /
                                     (result.tm_mon + 1) / result.tm_mday);
  if (!ignoreTimeInDay) {
    secs += (std::chrono::hours(result.tm_hour) + std::chrono::minutes(result.tm_min) +
             std::chrono::seconds(result.tm_sec));
  }
  *out = secs.time_since_epoch().count();
  return true;
#endif
}

}  // namespace internal
}  // namespace gandiva

#endif  // TO_DATE_HELPER_H


text:
<?php

// Gamserver overview. Displays a range of gameservers as set by the MAXRANGE constant in the configuration.
//
// GET VARIABLES:
//		offset -- Gameserver offset modifier of the overview.
//		search -- Search term modifier of the overview
//
// SESSION VARIABLES:
// 		user_name	-- Currently logged in user. Used for information on the current gameserver.
// 		user_id		-- Unique identifier of the currently logged in user. Stored in the new gameserver data.
//		user_level	-- Security level of the currently logged in user. Used for permissions.

require_once($_SERVER["DOCUMENT_ROOT"] . "/../private/config.php");

require_once(HELPERS_PATH . "/Utility.php");
require_once(HELPERS_PATH . "/Gameserver.php");

// Make sure that the logged in user has access rights.
if (isset($_SESSION['user_level'])) {
	if($_SESSION['user_level'] < 3) {
		header($_SERVER["SERVER_PROTOCOL"] ." 403 Access Denied", true, 403);
		include_once($_SERVER["DOCUMENT_ROOT"] . "/errors/403.php");
		die();
	}

} else {
	header($_SERVER["SERVER_PROTOCOL"] ." 403 Access Denied", true, 403);
	include_once($_SERVER["DOCUMENT_ROOT"] . "/errors/403.php");
	die();
}

// Retrieve GET variables and set defaults.
$offset = $_GET['offset'] ?? 0;
$search = $_GET['search'] ?? "";

// Retrieve all games ervers from the database. TODO: Change to ranged retrieve.
$gameservers = Gameserver::retrieveAll();
$count = Gameserver::retrieveCount();
$range = count($gameservers);

?>

<!DOCTYPE html>

    <title>Hivecom - Game Servers Overview</title>
    <?php include_once(TEMPLATES_PATH . "/core/head.php");?>
	<link rel="stylesheet" href="/static/css/font-awesome.min.css">

        <?php include_once(TEMPLATES_PATH . "/core/menu.php");?>

                Game Servers Overview

				- Site manager panel -

				<?php if($count && $range) :

				echo "
- Displaying $range of $count results -
";

				// Iterate over each gameserver and display a new information header with buttons.
				foreach ($gameservers as $gameserver) {
					$uid = $gameserver[Gameserver::SQL_UNIQUE_ID_INDEX];
					$game = $gameserver[Gameserver::SQL_GAME_INDEX];
					$title = $gameserver[Gameserver::SQL_TITLE_INDEX];
					$hidden = $gameserver[Gameserver::SQL_HIDDEN_INDEX];

					echo '

';

					// Add the game image if it exists in the game image directory.
					if(!$hidden){
						if (file_exists(STATIC_PATH . "/logos/". Utility::slug($game) . '.png')) {
							echo sprintf('', Utility::slug($game));
						}
					} else echo ' ';

					echo "
							$title

							Edit Server
							Delete Server

GAME: $game / UID: $uid

						";
				}

				?>

					<a class="button <?php if($range <= MAXRESULT) echo "disabled"; ?>" style="width:100px" href="/user/manage/gameserver/overview?offset=<?php echo $offset - $range; ?>"><

					Create a new gameserver

					<a class="button <?php if($range + $offset <= $count) echo "disabled"; ?>" style="width:100px" href="/user/manage/gameserver/create">>

				<?php else : ?>

There are currently no game servers

					Create a new game server

				<?php endif; ?>

		<?php include_once(TEMPLATES_PATH. "/core/footer.php");?>


text:
require "spec_helper"
require "json"

begin
  require "webrick"
rescue LoadError
  # nop
end
require "evil-proxy"
require "evil-proxy/async"

describe ProxyFetcher::Client do
  before :all do
    ProxyFetcher.configure do |config|
      config.provider = :xroxy
      config.client_timeout = 5
      config.logger = ProxyFetcher::NullLogger.new
    end

    quiet = ENV.key?("LOG_MITM") ? ENV["LOG_MITM"] == "false" : true

    @server = EvilProxy::MITMProxyServer.new Port: 3128, Quiet: quiet
    @server.start
  end

  after :all do
    @server.shutdown
  end

  let(:local_proxy) { ProxyFetcher::Proxy.new(addr: "127.0.0.1", port: 3128, type: "HTTP, HTTPS") }

  # Use local proxy server in order to avoid side effects, non-working proxies, etc
  before :each do
    ProxyFetcher::Client::ProxiesRegistry.manager.instance_variable_set(:'@proxies', [local_proxy])
    allow_any_instance_of(ProxyFetcher::Providers::Base).to receive(:fetch_proxies).and_return([local_proxy])
  end

  context "GET request with the valid proxy" do
    it "successfully returns page content for HTTP" do
      content = ProxyFetcher::Client.get("http://httpbin.org/get")

      expect(content).not_to be_empty
    end

    # TODO: oh this SSL / MITM proxies ....
    xit "successfully returns page content for HTTPS" do
      content = ProxyFetcher::Client.get("https://httpbin.org/get")

      expect(content).not_to be_empty
    end

    it "successfully returns page content using custom proxy" do
      content = ProxyFetcher::Client.get("http://httpbin.org/get", options: { proxy: local_proxy })

      expect(content).not_to be_empty
    end
  end

  context "POST request with the valid proxy" do
    it "successfully returns page content for HTTP" do
      headers = {
        "X-Proxy-Fetcher-Version" => ProxyFetcher::VERSION::STRING
      }

      content = ProxyFetcher::Client.post(
        "http://httpbin.org/post",
        { param: "value" },
        headers: headers
      )

      expect(content).not_to be_empty

      json = JSON.parse(content)

      expect(json["headers"]["X-Proxy-Fetcher-Version"]).to eq(ProxyFetcher::VERSION::STRING)
      expect(json["headers"]["User-Agent"]).to eq(ProxyFetcher.config.user_agent)
    end
  end

  # TODO: EvilProxy incompatible with latest Ruby/Webrick
  # @see https://github.com/bbtfr/evil-proxy/issues/10
  if Gem::Version.new(RUBY_VERSION) < Gem::Version.new("2.6")
    context "PUT request with the valid proxy" do
      it "successfully returns page content for HTTP" do
        content = ProxyFetcher::Client.put("http://httpbin.org/put", "param=PutValue")

        expect(content).not_to be_empty

        json = JSON.parse(content)

        expect(json["form"]["param"]).to eq("PutValue")
      end
    end

    context "PATCH request with the valid proxy" do
      it "successfully returns page content for HTTP" do
        content = ProxyFetcher::Client.patch("http://httpbin.org/patch", param: "value")

        expect(content).not_to be_empty

        json = JSON.parse(content)

        expect(json["form"]["param"]).to eq("value")
      end
    end
  end

  context "DELETE request with the valid proxy" do
    it "successfully returns page content for HTTP" do
      content = ProxyFetcher::Client.delete("http://httpbin.org/delete")

      expect(content).not_to be_empty
    end
  end

  context "HEAD request with the valid proxy" do
    it "successfully works" do
      content = ProxyFetcher::Client.head("http://httpbin.org")

      expect(content).to be_empty
    end
  end

  context "retries" do
    it "raises an error when reaches max retries limit" do
      allow(ProxyFetcher::Client::Request).to receive(:execute).and_raise(StandardError)

      expect { ProxyFetcher::Client.get("http://httpbin.org", options: { max_retries: 10 }) }
        .to raise_error(ProxyFetcher::Exceptions::MaximumRetriesReached)
    end

    xit "raises an error when http request returns an error" do
      allow_any_instance_of(HTTP::Client).to receive(:get).and_return(StandardError.new)

      expect { ProxyFetcher::Client.get("http://httpbin.org") }
        .to raise_error(ProxyFetcher::Exceptions::MaximumRetriesReached)
    end

    it "refreshes proxy lists if no proxy found" do
      allow(ProxyFetcher::Manager.new).to receive(:proxies).and_return([])

      expect { ProxyFetcher::Client.get("http://httpbin.org") }
        .not_to raise_error
    end
  end

  xcontext "redirects" do
    it "follows redirect when present" do
      content = ProxyFetcher::Client.get("http://httpbin.org/absolute-redirect/2")

      expect(content).not_to be_empty
    end

    it "raises an error when reaches max redirects limit" do
      expect { ProxyFetcher::Client.get("http://httpbin.org/absolute-redirect/11") }
        .to raise_error(ProxyFetcher::Exceptions::MaximumRedirectsReached)
    end
  end
end


text:
package de.plushnikov.intellij.plugin.inspection;

import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.codeInspection.defUse.DefUseInspection;
import org.jetbrains.annotations.Nullable;

public class DefUseInspectionTest extends LombokInspectionTest {
  @Override
  protected String getBasePath() {
    return super.getBasePath() + "/" + TEST_DATA_INSPECTION_DIRECTORY + "/diverse";
  }

  @Nullable
  @Override
  protected InspectionProfileEntry getInspection() {
    return new DefUseInspection();
  }

  public void testIssue633() {
    doTest();
  }
}


text:
package tw.com.mitake.sms;

public enum ConnectionResult {
    OK(1), FAIL(2), EXCEPTION(3);

    private int code;

    public int getCode() {
        return code;
    }

    ConnectionResult(int code) {
        this.code = code;
    }

    public static ConnectionResult findByKey(int code) {
        for (ConnectionResult e : values()) {
            if (e.code == code) {
                return e;
            }
        }

        return null;
    }

}