text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/renderers/decrypting_renderer.h"

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "media/base/demuxer_stream.h"
#include "media/base/media_util.h"
#include "media/base/mock_filters.h"
#include "media/base/test_helpers.h"
#include "media/filters/decrypting_media_resource.h"
#include "testing/gmock/include/gmock/gmock.h"

using ::base::test::RunCallback;
using ::base::test::RunOnceCallback;
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Invoke;
using ::testing::Return;
using ::testing::ReturnPointee;
using ::testing::StrictMock;

namespace media {

class CdmContext;
class DemuxerStream;
class MediaLog;

class DecryptingRendererTest : public testing::Test {
 public:
  DecryptingRendererTest() {
    auto renderer = std::make_unique<StrictMock<MockRenderer>>();
    renderer_ = renderer.get();
    decrypting_renderer_ = std::make_unique<DecryptingRenderer>(
        std::move(renderer), &null_media_log_,
        task_environment_.GetMainThreadTaskRunner());

    EXPECT_CALL(cdm_context_, RegisterEventCB(_)).Times(AnyNumber());
    EXPECT_CALL(cdm_context_, GetDecryptor())
        .WillRepeatedly(Return(&decryptor_));
    EXPECT_CALL(decryptor_, CanAlwaysDecrypt())
        .WillRepeatedly(ReturnPointee(&use_aes_decryptor_));
    EXPECT_CALL(decryptor_, CancelDecrypt(_)).Times(AnyNumber());
    EXPECT_CALL(media_resource_, GetAllStreams())
        .WillRepeatedly(Invoke(this, &DecryptingRendererTest::GetAllStreams));
    EXPECT_CALL(media_resource_, GetType())
        .WillRepeatedly(Return(MediaResource::STREAM));
  }

  ~DecryptingRendererTest() override {
    // Ensure that the DecryptingRenderer is destructed before other objects
    // that it internally references but does not own.
    decrypting_renderer_.reset();
  }

  void AddStream(DemuxerStream::Type type, bool encrypted) {
    streams_.push_back(CreateMockDemuxerStream(type, encrypted));
  }

  void UseAesDecryptor(bool use_aes_decryptor) {
    use_aes_decryptor_ = use_aes_decryptor;
  }

  std::vector<DemuxerStream*> GetAllStreams() {
    std::vector<DemuxerStream*> streams;

    for (auto& stream : streams_) {
      streams.push_back(stream.get());
    }

    return streams;
  }

 protected:
  // Invoking InitializeRenderer(false) will cause the initialization of the
  // DecryptingRenderer to halt and an error will be propagated to the media
  // pipeline.
  void InitializeDecryptingRendererWithFalse() {
    decrypting_renderer_->InitializeRenderer(false);
  }

  bool use_aes_decryptor_ = false;
  base::test::TaskEnvironment task_environment_;
  base::MockCallback<Renderer::CdmAttachedCB> set_cdm_cb_;
  base::MockOnceCallback<void(PipelineStatus)> renderer_init_cb_;
  NullMediaLog null_media_log_;
  StrictMock<MockCdmContext> cdm_context_;
  StrictMock<MockDecryptor> decryptor_;
  StrictMock<MockMediaResource> media_resource_;
  StrictMock<MockRendererClient> renderer_client_;
  raw_ptr<StrictMock<MockRenderer>> renderer_;
  std::unique_ptr<DecryptingRenderer> decrypting_renderer_;
  std::vector<std::unique_ptr<StrictMock<MockDemuxerStream>>> streams_;
};

TEST_F(DecryptingRendererTest, ClearStreams_NoCdm) {
  AddStream(DemuxerStream::AUDIO, /* encrypted = */ false);
  AddStream(DemuxerStream::VIDEO, /* encrypted = */ false);

  EXPECT_CALL(*renderer_, OnInitialize(_, _, _))
      .WillOnce(RunOnceCallback<2>(PIPELINE_OK));
  EXPECT_CALL(renderer_init_cb_, Run(HasStatusCode(PIPELINE_OK)));

  decrypting_renderer_->Initialize(&media_resource_, &renderer_client_,
                                   renderer_init_cb_.Get());
  task_environment_.RunUntilIdle();

  EXPECT_FALSE(decrypting_renderer_->HasDecryptingMediaResourceForTesting());
}

TEST_F(DecryptingRendererTest, ClearStreams_AesDecryptor) {
  AddStream(DemuxerStream::AUDIO, /* encrypted = */ false);
  AddStream(DemuxerStream::VIDEO, /* encrypted = */ false);
  UseAesDecryptor(true);

  EXPECT_CALL(*renderer_, OnInitialize(_, _, _))
      .WillOnce(RunOnceCallback<2>(PIPELINE_OK));
  EXPECT_CALL(set_cdm_cb_, Run(true));
  EXPECT_CALL(renderer_init_cb_, Run(HasStatusCode(PIPELINE_OK)));

  decrypting_renderer_->SetCdm(&cdm_context_, set_cdm_cb_.Get());
  decrypting_renderer_->Initialize(&media_resource_, &renderer_client_,
                                   renderer_init_cb_.Get());
  task_environment_.RunUntilIdle();

  EXPECT_TRUE(decrypting_renderer_->HasDecryptingMediaResourceForTesting());
}

TEST_F(DecryptingRendererTest, ClearStreams_OtherCdm) {
  AddStream(DemuxerStream::AUDIO, /* encrypted = */ false);
  AddStream(DemuxerStream::VIDEO, /* encrypted = */ false);

  EXPECT_CALL(*renderer_, OnInitialize(_, _, _))
      .WillOnce(RunOnceCallback<2>(PIPELINE_OK));
  EXPECT_CALL(*renderer_, OnSetCdm(_, _)).WillOnce(RunOnceCallback<1>(true));
  EXPECT_CALL(renderer_init_cb_, Run(HasStatusCode(PIPELINE_OK)));
  EXPECT_CALL(set_cdm_cb_, Run(true));

  decrypting_renderer_->Initialize(&media_resource_, &renderer_client_,
                                   renderer_init_cb_.Get());
  decrypting_renderer_->SetCdm(&cdm_context_, set_cdm_cb_.Get());
  task_environment_.RunUntilIdle();

  EXPECT_FALSE(decrypting_renderer_->HasDecryptingMediaResourceForTesting());
}

TEST_F(DecryptingRendererTest, EncryptedStreams_NoCdm) {
  AddStream(DemuxerStream::AUDIO, /* encrypted = */ true);
  AddStream(DemuxerStream::VIDEO, /* encrypted = */ true);

  decrypting_renderer_->Initialize(&media_resource_, &renderer_client_,
                                   renderer_init_cb_.Get());
  task_environment_.RunUntilIdle();

  EXPECT_FALSE(decrypting_renderer_->HasDecryptingMediaResourceForTesting());
}

TEST_F(DecryptingRendererTest, EncryptedStreams_AesDecryptor) {
  AddStream(DemuxerStream::AUDIO, /* encrypted = */ true);
  AddStream(DemuxerStream::VIDEO, /* encrypted = */ true);
  UseAesDecryptor(true);

  EXPECT_CALL(*renderer_, OnInitialize(_, _, _))
      .WillOnce(RunOnceCallback<2>(PIPELINE_OK));
  EXPECT_CALL(renderer_init_cb_, Run(HasStatusCode(PIPELINE_OK)));
  EXPECT_CALL(set_cdm_cb_, Run(true));

  decrypting_renderer_->Initialize(&media_resource_, &renderer_client_,
                                   renderer_init_cb_.Get());
  decrypting_renderer_->SetCdm(&cdm_context_, set_cdm_cb_.Get());
  task_environment_.RunUntilIdle();

  EXPECT_TRUE(decrypting_renderer_->HasDecryptingMediaResourceForTesting());
}

TEST_F(DecryptingRendererTest, EncryptedStreams_OtherCdm) {
  AddStream(DemuxerStream::AUDIO, /* encrypted = */ true);
  AddStream(DemuxerStream::VIDEO, /* encrypted = */ true);

  EXPECT_CALL(*renderer_, OnInitialize(_, _, _))
      .WillOnce(RunOnceCallback<2>(PIPELINE_OK));
  EXPECT_CALL(*renderer_, OnSetCdm(_, _)).WillOnce(RunOnceCallback<1>(true));
  EXPECT_CALL(renderer_init_cb_, Run(HasStatusCode(PIPELINE_OK)));
  EXPECT_CALL(set_cdm_cb_, Run(true));

  decrypting_renderer_->Initialize(&media_resource_, &renderer_client_,
                                   renderer_init_cb_.Get());
  decrypting_renderer_->SetCdm(&cdm_context_, set_cdm_cb_.Get());
  task_environment_.RunUntilIdle();

  EXPECT_FALSE(decrypting_renderer_->HasDecryptingMediaResourceForTesting());
}

TEST_F(DecryptingRendererTest, EncryptedStreams_AesDecryptor_CdmSetBeforeInit) {
  AddStream(DemuxerStream::AUDIO, /* encrypted = */ true);
  AddStream(DemuxerStream::VIDEO, /* encrypted = */ true);
  UseAesDecryptor(true);

  EXPECT_CALL(*renderer_, OnInitialize(_, _, _))
      .WillOnce(RunOnceCallback<2>(PIPELINE_OK));
  EXPECT_CALL(renderer_init_cb_, Run(HasStatusCode(PIPELINE_OK)));
  EXPECT_CALL(set_cdm_cb_, Run(true));

  decrypting_renderer_->SetCdm(&cdm_context_, set_cdm_cb_.Get());
  decrypting_renderer_->Initialize(&media_resource_, &renderer_client_,
                                   renderer_init_cb_.Get());
  task_environment_.RunUntilIdle();

  EXPECT_TRUE(decrypting_renderer_->HasDecryptingMediaResourceForTesting());
}

TEST_F(DecryptingRendererTest, EncryptedStreams_OtherCdm_CdmSetBeforeInit) {
  AddStream(DemuxerStream::AUDIO, /* encrypted = */ true);
  AddStream(DemuxerStream::VIDEO, /* encrypted = */ true);

  EXPECT_CALL(*renderer_, OnInitialize(_, _, _))
      .WillOnce(RunOnceCallback<2>(PIPELINE_OK));
  EXPECT_CALL(*renderer_, OnSetCdm(_, _)).WillOnce(RunOnceCallback<1>(true));
  EXPECT_CALL(renderer_init_cb_, Run(HasStatusCode(PIPELINE_OK)));
  EXPECT_CALL(set_cdm_cb_, Run(true));

  decrypting_renderer_->SetCdm(&cdm_context_, set_cdm_cb_.Get());
  decrypting_renderer_->Initialize(&media_resource_, &renderer_client_,
                                   renderer_init_cb_.Get());
  task_environment_.RunUntilIdle();

  EXPECT_FALSE(decrypting_renderer_->HasDecryptingMediaResourceForTesting());
}

TEST_F(DecryptingRendererTest, EncryptedAndClearStream_OtherCdm) {
  AddStream(DemuxerStream::AUDIO, /* encrypted = */ false);
  AddStream(DemuxerStream::VIDEO, /* encrypted = */ true);

  EXPECT_CALL(*renderer_, OnInitialize(_, _, _))
      .WillOnce(RunOnceCallback<2>(PIPELINE_OK));
  EXPECT_CALL(*renderer_, OnSetCdm(_, _)).WillOnce(RunOnceCallback<1>(true));
  EXPECT_CALL(renderer_init_cb_, Run(HasStatusCode(PIPELINE_OK)));
  EXPECT_CALL(set_cdm_cb_, Run(true));

  decrypting_renderer_->Initialize(&media_resource_, &renderer_client_,
                                   renderer_init_cb_.Get());
  decrypting_renderer_->SetCdm(&cdm_context_, set_cdm_cb_.Get());
  task_environment_.RunUntilIdle();

  EXPECT_FALSE(decrypting_renderer_->HasDecryptingMediaResourceForTesting());
}

TEST_F(DecryptingRendererTest, DecryptingMediaResourceInitFails) {
  AddStream(DemuxerStream::AUDIO, /* encrypted = */ false);
  AddStream(DemuxerStream::VIDEO, /* encrypted = */ true);
  UseAesDecryptor(true);

  EXPECT_CALL(renderer_init_cb_,
              Run(HasStatusCode(PIPELINE_ERROR_INITIALIZATION_FAILED)));

  decrypting_renderer_->Initialize(&media_resource_, &renderer_client_,
                                   renderer_init_cb_.Get());
  task_environment_.RunUntilIdle();

  // Cause a PIPELINE_ERROR_INITIALIZATION_FAILED error to be passed as a
  // parameter to the initialization callback.
  InitializeDecryptingRendererWithFalse();
}

}  // namespace media


text:
require 'spec_helper_acceptance'

describe 'puppet5 class' do
  context 'should work with no errors' do
    it 'when configuring puppet5 without parameters' do
      pp = <<-EOS
        class { 'puppet5': }
      EOS

      apply_manifest(pp, :catch_failures => true) do |r|
        expect(r.stderr).not_to match(/error/i)
        expect(r.exit_code).to eq(2)
      end

      apply_manifest(pp, :catch_failures => true) do |r|
        expect(r.stderr).not_to eq(/error/i)
        expect(r.exit_code).to be_zero
      end
    end

    describe package('puppet-agent') do
      it { is_expected.to be_installed }
    end

    describe service('puppet') do
      it { should be_enabled }
      it { should be_running }
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
import readExpression from '../../../readExpression';
import { STRING_LITERAL, BRACKETED, INFIX_OPERATOR } from '../../../../../config/types';
import {
  escapeSequencePattern,
  lineContinuationPattern
} from './stringLiteral/makeQuotedStringMatcher';

// Match one or more characters until: ", ', or \
const stringMiddlePattern = /^[^`"\\\$]+?(?:(?=[`"\\\$]))/;

const escapes = /[\r\n\t\b\f]/g;
function getString(literal) {
  return JSON.parse(`"${literal.replace(escapes, escapeChar)}"`);
}

function escapeChar(c) {
  switch (c) {
    case '\n':
      return '\\n';
    case '\r':
      return '\\r';
    case '\t':
      return '\\t';
    case '\b':
      return '\\b';
    case '\f':
      return '\\f';
  }
}

export default function readTemplateStringLiteral(parser) {
  if (!parser.matchString('`')) return null;

  let literal = '';
  let done = false;
  let next;
  const parts = [];

  while (!done) {
    next =
      parser.matchPattern(stringMiddlePattern) ||
      parser.matchPattern(escapeSequencePattern) ||
      parser.matchString('$') ||
      parser.matchString('"');
    if (next) {
      if (next === `"`) {
        literal += `\\"`;
      } else if (next === '\\`') {
        literal += '`';
      } else if (next === '$') {
        if (parser.matchString('{')) {
          parts.push({ t: STRING_LITERAL, v: getString(literal) });
          literal = '';

          parser.sp();
          const expr = readExpression(parser);

          if (!expr) parser.error('Expected valid expression');

          parts.push({ t: BRACKETED, x: expr });

          parser.sp();
          if (!parser.matchString('}'))
            parser.error(`Expected closing '}' after interpolated expression`);
        } else {
          literal += '$';
        }
      } else {
        literal += next;
      }
    } else {
      next = parser.matchPattern(lineContinuationPattern);
      if (next) {
        // convert \(newline-like) into a \u escape, which is allowed in JSON
        literal += '\\u' + ('000' + next.charCodeAt(1).toString(16)).slice(-4);
      } else {
        done = true;
      }
    }
  }

  if (literal.length) parts.push({ t: STRING_LITERAL, v: getString(literal) });

  if (!parser.matchString('`')) parser.error("Expected closing '`'");

  if (!parts.length) {
    // empty string literal
    return { t: STRING_LITERAL, v: '' };
  } else if (parts.length === 1) {
    return parts[0];
  } else {
    let result = parts.pop();
    let part;

    while ((part = parts.pop())) {
      result = {
        t: INFIX_OPERATOR,
        s: '+',
        o: [part, result]
      };
    }

    return {
      t: BRACKETED,
      x: result
    };
  }
}


text:
$userId = id --user
if ($userId -ne "0"){
    throw "This script should be executed from the root"
}

$daemon_json_path = '/etc/docker/daemon.json'
if (Test-Path $daemon_json_path)
{
    $daemon_json = Get-Content $daemon_json_path -raw | ConvertFrom-Json
}
else
{
    $daemon_json = New-Object PSObject
}

$requires
if (! [bool]($daemon_json.PSobject.Properties.name -match "hosts"))
{
    $daemon_json | Add-Member "hosts" ("fd://", "tcp://0.0.0.0")
    $requires_daemon_json_change = $true
}
else
{
    $requires_daemon_json_change = $true
    foreach ($hst in $daemon_json.hosts)
    {
        if ($hst -eq "tcp://0.0.0.0")
        {
            $requires_daemon_json_change = $false
            break
        }
    }

    $daemon_json.hosts = $daemon_json.hosts + "tcp://0.0.0.0"
}

if ($requires_daemon_json_change)
{
    $daemon_json | ConvertTo-Json -Depth 100  | set-content $daemon_json_path
}

$rootPath = [System.IO.Path]::GetFullPath((split-path $SCRIPT:MyInvocation.MyCommand.Path -parent))

# Making temporary copy for samba-member dist files
cp -rf $rootPath/open-docker-remote-access-dist /tmp/open-docker-remote-access-dist

# Changing root for dist files
chown root:root -R /tmp/open-docker-remote-access-dist

# Moving dist files to the target place
cp -rf /tmp/open-docker-remote-access-dist/* /
rm -r /tmp/open-docker-remote-access-dist

systemctl daemon-reload

service docker restart


text:
import { Entity } from "../../../../../src/decorator/entity/Entity"
import { PrimaryGeneratedColumn } from "../../../../../src/decorator/columns/PrimaryGeneratedColumn"
import { Column } from "../../../../../src/decorator/columns/Column"

@Entity()
export class PostDefaultValues {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column({ default: "hello post" })
    text: string

    @Column({ default: true })
    isActive: boolean

    @Column({ default: () => "CURRENT_TIMESTAMP" })
    addDate: Date

    @Column({ default: 0 })
    views: number

    @Column({ nullable: true })
    description: string
}


text:
<?php
    include_once('../Configuration.inc.php');

	if (!$Page->Prefix)
		$Page->Prefix = '../';

	include_once('./Security.inc.php');
	include_once($Page->Prefix.'ajfwk/GetParameters.inc.php');
	include_once($Page->Prefix.'ajfwk/Database.inc.php');
	include_once($Page->Prefix.'ajfwk/PostParameters.inc.php');
	include_once($Page->Prefix.'ajfwk/Session.inc.php');
	include_once($Page->Prefix.'ajfwk/Errors.inc.php');
	include_once($Page->Prefix.'ajfwk/Validations.inc.php');
	include_once($Page->Prefix.'ajfwk/Pages.inc.php');

	if (empty($IdTipo))
		ErrorAdd('Debe ingresar Tipo de Propiedad');
	if (empty($IdMoneda))
		ErrorAdd('Debe ingresar Moneda');
	if (empty($Operacion))
		ErrorAdd('Debe ingresar Operacion');
	if (empty($IdZona))
		ErrorAdd('Debe ingresar Zona');
	if (empty($IdInmobiliaria))
		ErrorAdd('Debe ingresar Inmobiliaria');
	$Metros += 0;
	$Lote += 0;
	$Ambientes += 0;
	$Dormitorios += 0;
	$Banios += 0;
	$Toilettes += 0;
	$Plantas += 0;
	$IdTipo += 0;
	$Precio += 0;
	$IdMoneda += 0;
	$Operacion += 0;
	$IdZona += 0;
	$IdInmobiliaria += 0;
	$IdAgente += 0;

	DbConnect();
	DbTransactionBegin();

	if (ErrorHas()) {
		DbDisconnect();
		include('PropiedadForm.php');
		exit;
	}

	if (empty($Id))
		$sql = "Insert";
	else
		$sql = "Update";

	$sql .= " $Cfg[SqlPrefix]propiedades set
		Nombre = '$Nombre' ,
		Domicilio = '$Domicilio' ,
		Metros = '$Metros' ,
		Lote = '$Lote' ,
		Ambientes = '$Ambientes' ,
		Dormitorios = '$Dormitorios' ,
		Banios = '$Banios' ,
		Toilettes = '$Toilettes' ,
		Plantas = '$Plantas' ,
		IdTipo = $IdTipo ,
		Descripcion = '$Descripcion' ,
		Precio = '$Precio' ,
		IdMoneda = $IdMoneda ,
		Operacion = '$Operacion' ,
		IdZona = $IdZona ,
		IdInmobiliaria = $IdInmobiliaria ,
		IdAgente = $IdAgente ,
		Notas = '$Notas' ,
		Habilitada = '$Habilitada' ,
		AceptaComentarios = '$AceptaComentarios' 		";

	if (empty($Id))
	{
	}
	else
	{
	}

	if (!empty($Id))
		$sql .= " where Id=$Id";

	DbExecuteUpdate($sql);

    $dberror = DbLastSqlError();

    if ($dberror) {
        DbTransactionRollback();
        DbDisconnect();
        echo $dberror;
    }

	DbTransactionCommit();
	DbDisconnect();

	$Link = SessionGet("PropiedadLink");
	SessionRemove("PropiedadLink");

	PageAbsoluteRedirect($Link);
	exit;
?>


text:
using System;

namespace Planet.Dashboard.GitHubEventProcessor
{
	internal class WebHookTriggerAttribute : Attribute
	{
	}
}


text:
class CDateTime
{
public:
	CDateTime();
	CDateTime(unsigned __int64 ticks);
public:
	operator unsigned __int64() const;
public:
	static CDateTime UtcNow();
private:
	unsigned __int64 m_ticks;
private:
	friend bool operator < (const CDateTime& first, const CDateTime& second);
	friend bool operator > (const CDateTime& first, const CDateTime& second);
	friend bool operator <= (const CDateTime& first, const CDateTime& second);
	friend bool operator >= (const CDateTime& first, const CDateTime& second);
	friend bool operator == (const CDateTime& first, const CDateTime& second);
	friend bool operator != (const CDateTime& first, const CDateTime& second);
private:
	friend bool operator < (const __int32 first, const CDateTime& second);
	friend bool operator > (const __int32 first, const CDateTime& second);
	friend bool operator <= (const __int32 first, const CDateTime& second);
	friend bool operator >= (const __int32 first, const CDateTime& second);
	friend bool operator == (const __int32 first, const CDateTime& second);
	friend bool operator != (const __int32 first, const CDateTime& second);
private:
	friend bool operator < (const CDateTime& first, const __int32 second);
	friend bool operator > (const CDateTime& first, const __int32 second);
	friend bool operator <= (const CDateTime& first, const __int32 second);
	friend bool operator >= (const CDateTime& first, const __int32 second);
	friend bool operator == (const CDateTime& first, const __int32 second);
	friend bool operator != (const CDateTime& first, const __int32 second);
};

inline CDateTime::operator unsigned __int64 () const
{
	return m_ticks;
}
inline CDateTime::CDateTime() : m_ticks()
{
}
inline CDateTime::CDateTime(unsigned __int64 ticks) : m_ticks(ticks)
{
}
// CDateTime <-> CDateTime
inline bool operator < (const CDateTime& first, const CDateTime& second)
{
	return (first.m_ticks < second.m_ticks);
}
inline bool operator > (const CDateTime& first, const CDateTime& second)
{
	return (first.m_ticks > second.m_ticks);
}
inline bool operator <= (const CDateTime& first, const CDateTime& second)
{
	return (first.m_ticks <= second.m_ticks);
}
inline bool operator >= (const CDateTime& first, const CDateTime& second)
{
	return (first.m_ticks >= second.m_ticks);
}
inline bool operator == (const CDateTime& first, const CDateTime& second)
{
	return (first.m_ticks == second.m_ticks);
}
inline bool operator != (const CDateTime& first, const CDateTime& second)
{
	return (first.m_ticks != second.m_ticks);
}
// __int32 <-> CDateTime
inline bool operator < (const __int32 first, const CDateTime& second)
{
	return (first < second.m_ticks);
}
inline bool operator > (const __int32 first, const CDateTime& second)
{
	return (first > second.m_ticks);
}
inline bool operator <= (const __int32 first, const CDateTime& second)
{
	return (first <= second.m_ticks);
}
inline bool operator >= (const __int32 first, const CDateTime& second)
{
	return (first >= second.m_ticks);
}
inline bool operator == (const __int32 first, const CDateTime& second)
{
	return (first == second.m_ticks);
}
inline bool operator != (const __int32 first, const CDateTime& second)
{
	return (first != second.m_ticks);
}
// CDateTime <-> __int32
inline bool operator < (const CDateTime& first, const __int32 second)
{
	return (first.m_ticks < second);
}
inline bool operator > (const CDateTime& first, const __int32 second)
{
	return (first.m_ticks > second);
}
inline bool operator <= (const CDateTime& first, const __int32 second)
{
	return (first.m_ticks <= second);
}
inline bool operator >= (const CDateTime& first, const __int32 second)
{
	return (first.m_ticks >= second);
}
inline bool operator == (const CDateTime& first, const __int32 second)
{
	return (first.m_ticks == second);
}
inline bool operator != (const CDateTime& first, const __int32 second)
{
	return (first.m_ticks != second);
}
#include <sys/timeb.h>
inline CDateTime CDateTime::UtcNow()
{
	timeb time;
	ftime(&time);
	unsigned __int64 result = time.time * 1000 + time.millitm;
	return result;
}
#endif


text:
execute_process (
                  COMMAND git log --pretty=format:"%H %ct" -n 1
                  WORKING_DIRECTORY .
                  OUTPUT_VARIABLE GIT_PRETTYCHANGESET
                )

#
# Ask git for the current changeset (and date), no quotes
#

execute_process (
                  COMMAND git log --pretty=format:%H -n 1
                  WORKING_DIRECTORY .
                  OUTPUT_VARIABLE GIT_CHANGESET
                )

execute_process (
                  COMMAND git log --pretty=format:%ct -n 1
                  WORKING_DIRECTORY .
                  OUTPUT_VARIABLE GIT_DATE
                )
#
# Get the current git tag
#
execute_process (
                  COMMAND git describe --tags
                  WORKING_DIRECTORY .
                  OUTPUT_VARIABLE GIT_TAG
                )

execute_process (
                  COMMAND git describe --tags
                  WORKING_DIRECTORY .
                  OUTPUT_VARIABLE GIT_PRETTYTAG
                  OUTPUT_STRIP_TRAILING_WHITESPACE
                )

#
# Get the current branch
#
execute_process (
                  COMMAND git rev-parse --abbrev-ref HEAD
                  WORKING_DIRECTORY .
                  OUTPUT_VARIABLE GIT_BRANCH
                )

#
# Get the git status as well, so we know if there is uncommitted
# files present.
#

execute_process (
                  COMMAND git status
                  WORKING_DIRECTORY .
                  OUTPUT_VARIABLE GIT_STATUS
                )

#
# And then grab the full log entry.
#

execute_process (
                  COMMAND git log -n 1
                  WORKING_DIRECTORY .
                  OUTPUT_VARIABLE GIT_LOG
                )

#
# Reform the changeset into a #define.
#

# deal with tagless repo
if ("${GIT_PRETTYTAG}" STREQUAL "")
    set(GIT_PRETTYTAG "NOTAG")
endif()

set(DESIRED_CHANGESET_HEADER "#define REVISION_CHANGESET ${GIT_PRETTYCHANGESET}")
set(DESIRED_VERSION_HEADER "#define REVISION_TAG \"${GIT_PRETTYTAG}\"")

#
# Look for the output header.
#

set(OUTPUT_HEADER "${BASE_DIRECTORY}/changeset.h")

#
# Before we write out anything, let's ensure that it has changed. Read
# in the current header.
#

if(EXISTS ${OUTPUT_HEADER})

    file(READ ${OUTPUT_HEADER} PRESENT_CHANGESET_HEADER LIMIT 1024)

else()

    set(PRESENT_CHANGESET_HEADER "")

endif()

#
# If the two files do not match, then overwrite the existing file.
#

if(NOT PRESENT_CHANGESET_HEADER STREQUAL DESIRED_CHANGESET_HEADER)

    message("-- New changeset was pushed, updating changeset information in the pheatherstation binary.")

    file(WRITE ${OUTPUT_HEADER} "${DESIRED_CHANGESET_HEADER}")
    file(APPEND ${OUTPUT_HEADER} "\n${DESIRED_VERSION_HEADER}")

    #
    # Additionally, write the changeset information out to a file in the
    # configuration directory, so it is compressed and trackable.
    #

    set(OUTPUT_CONFIG "${BASE_DIRECTORY}/output/repository_status.txt")

    file(WRITE ${OUTPUT_CONFIG} "${GIT_LOG}\n${GIT_STATUS}")

endif()


text:
// Copyright 2007-2013 Chris Patterson
//
// 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.
namespace MassTransit.TestFramework.Courier
{
    using System;
    using System.Threading.Tasks;
    using MassTransit.Courier;

    public class NastyFaultyActivity :
        Activity<FaultyArguments, FaultyLog>
    {
        public Task<ExecutionResult> Execute(ExecuteContext<FaultyArguments> context)
        {
            Console.WriteLine("NastyFaultyActivity: Execute");
            Console.WriteLine("NastyFaultyActivity: About to blow this up!");

            throw new InvalidOperationException("Things that make you go boom!");
        }

        public async Task<CompensationResult> Compensate(CompensateContext<FaultyLog> context)
        {
            return context.Compensated();
        }
    }
}


text:
package net.poczone.blobstorage.shared;

import java.util.Date;

public class Blob {
	private String path;
	private String mimeType;
	private byte[] data;
	private boolean exists;
	private Date lastMod;

	public Blob(String path, String mimeType, byte[] data) {
		this.path = path;
		this.mimeType = mimeType;
		this.data = data;
		this.exists = true;
		this.lastMod = new Date();
	}

	public Blob(String path, String mimeType, byte[] data, boolean exists,
			Date lastMod) {
		this.path = path;
		this.mimeType = mimeType;
		this.data = data;
		this.exists = exists;
		this.lastMod = lastMod;
	}

	public String getPath() {
		return path;
	}

	public String getMimeType() {
		return mimeType;
	}

	public byte[] getData() {
		if (data == null) {
			data = new byte[0];
		}
		return data;
	}

	public Date getLastMod() {
		return lastMod;
	}

	public boolean exists() {
		return exists;
	}

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


text:
Implementation for a functional-first arithmetic mathmatics library in Python, freeing end-developers from being forced to use Python's builtin operators.

Power to the developer.


text:
namespace Skeleton.Web.Logging.Serilog.Enrichers
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Text;
    using global::Serilog.Core;
    using global::Serilog.Events;
    using Murmur;

    [ExcludeFromCodeCoverage]
    public class MessageTemplateHashEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var bytes = Encoding.UTF8.GetBytes(logEvent.MessageTemplate.Text);

            var hash = MurmurHash.Create32().ComputeHash(bytes);
            var numericHash = BitConverter.ToUInt32(hash, 0);

            logEvent.AddPropertyIfAbsent(
                propertyFactory.CreateProperty("MessageTemplateHash", numericHash.ToString("x8"))
            );
        }
    }
}


text:
namespace java.nio.file
{
    public partial interface DirectoryStream<T> : global::java.io.Closeable, global::java.lang.Iterable<T>
    {
        global::java.util.Iterator<T> iterator();
    }
}


text:
from datetime import date
from mock import patch, Mock
from nose.tools import raises, assert_equals, assert_true
from telapi_helper.rest.resources import Recordings
from tools import create_mock_json

BASE_URI = "https://api.telapi.com/2010-04-01/Accounts/AC123"
ACCOUNT_SID = "AC123"
AUTH = (ACCOUNT_SID, "token")

RE_SID = "RE19e96a31ed59a5733d2c1c1c69a83a28"

recordings = Recordings(BASE_URI, AUTH)

@patch("telapi_helper.rest.resources.make_telapi_request")
def test_paging(mock):
    resp = create_mock_json("tests/resources/recordings_list.json")
    mock.return_value = resp

    uri = "{}/Recordings".format(BASE_URI)
    recordings.list(call_sid="CA123", before=date(2010,12,5))
    exp_params = {'CallSid': 'CA123', 'DateCreated<': '2010-12-05'}

    mock.assert_called_with("GET", uri, params=exp_params, auth=AUTH)

@patch("telapi_helper.rest.resources.make_telapi_request")
def test_get(mock):
    resp = create_mock_json("tests/resources/recordings_instance.json")
    mock.return_value = resp

    uri = "{}/Recordings/{}".format(BASE_URI, RE_SID)
    r = recordings.get(RE_SID)

    mock.assert_called_with("GET", uri, auth=AUTH)

    truri = "{}/Recordings/{}/Transcriptions".format(BASE_URI, RE_SID)
    assert_equals(r.transcriptions.uri, truri)

@patch("telapi_helper.rest.resources.make_telapi_request")
def test_get(mock):
    resp = create_mock_json("tests/resources/recordings_instance.json")
    resp.status_code = 204
    mock.return_value = resp

    uri = "{}/Recordings/{}".format(BASE_URI, RE_SID)
    r = recordings.delete(RE_SID)

    mock.assert_called_with("DELETE", uri, auth=AUTH)
    assert_true(r)

@raises(AttributeError)
def test_create():
    recordings.create

@raises(AttributeError)
def test_update():
    recordings.update


text:
using System;
using LibGit2Sharp.Core;
using LibGit2Sharp.Handlers;

namespace LibGit2Sharp
{
    /// <summary>
    ///   Class to handle the mapping between libgit2 git_transfer_progress_callback function and
    ///   a corresponding <see cref = "TransferProgressHandler" />. Generates a delegate that
    ///   wraps the <see cref = "TransferProgressHandler" /> delegate with a delegate that matches
    ///   the git_transfer_progress_callback signature.
    /// </summary>
    internal class TransferCallbacks
    {
        /// <summary>
        ///   Managed delegate to be called in response to a git_transfer_progress_callback callback from libgit2.
        /// </summary>
        private readonly TransferProgressHandler onTransferProgress;

        /// <summary>
        ///   Constructor to set up the native callback given managed delegate.
        /// </summary>
        /// <param name="onTransferProgress">The <see cref="TransferProgressHandler"/> delegate that the git_transfer_progress_callback will call.</param>
        private TransferCallbacks(TransferProgressHandler onTransferProgress)
        {
            this.onTransferProgress = onTransferProgress;
        }

        /// <summary>
        ///   Generates a delegate that matches the native git_transfer_progress_callback function's signature and wraps the <see cref = "TransferProgressHandler" /> delegate.
        /// </summary>
        /// <param name="onTransferProgress">The <see cref = "TransferProgressHandler" /> delegate to call in responde to a the native git_transfer_progress_callback callback.</param>
        /// <returns>A delegate method with a signature that matches git_transfer_progress_callback.</returns>
        internal static NativeMethods.git_transfer_progress_callback GenerateCallback(TransferProgressHandler onTransferProgress)
        {
            if (onTransferProgress == null)
            {
                return null;
            }

            return new TransferCallbacks(onTransferProgress).OnGitTransferProgress;
        }

        /// <summary>
        ///   The delegate with the signature that matches the native git_transfer_progress_callback function's signature.
        /// </summary>
        /// <param name="progress"><see cref = "GitTransferProgress" /> structure containing progress information.</param>
        /// <param name="payload">Payload data.</param>
        private void OnGitTransferProgress(ref GitTransferProgress progress, IntPtr payload)
        {
            onTransferProgress(new TransferProgress(progress));
        }
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
	    android:id="@+id/edittext"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"

	    android:hint="@string/hint"
	    android:inputType="text" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edittext"
        android:text="@string/button" />
    <!--  <CheckBox
        android:id="@+id/csrftoken"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:text="@string/csrf" />-->
   <!--   <ScrollView
         android:layout_width="wrap_content"
   		 android:layout_height="wrap_content"
   		 android:layout_below="@+id/csrftoken">
	    <TextView
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:id="@+id/textView1"
			android:text="@string/hello_world" />
    </ScrollView>-->
	<ListView
      	android:id="@+id/listView1"
      	android:layout_height="fill_parent"
      	android:layout_width="fill_parent"
      	android:layout_below="@+id/button1"/>

</RelativeLayout>


text:
using System;
using Microsoft.EntityFrameworkCore.Migrations;

namespace ArragroCMS.BusinessLayer.Data.EFCore.Migrations.ArragroCms.SQL
{
    public partial class FlatContent : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(@"
UPDATE ""UrlRoutes""
   SET ""UrlRouteTypeId"" = (SELECT ""UrlRouteTypeId"" FROM ""UrlRouteTypes"" WHERE ""Name"" = 'Page')
 WHERE ""UrlRouteTypeId"" = (SELECT ""UrlRouteTypeId"" FROM ""UrlRouteTypes"" WHERE ""Name"" = 'Post')");

            migrationBuilder.DropIndex(
                name: "IX_Contents_ParentContentId",
                table: "Contents");

            migrationBuilder.DeleteData(
                table: "UrlRouteTypes",
                keyColumn: "UrlRouteTypeId",
                keyValue: 3);

            migrationBuilder.DropColumn(
                name: "Ordinal",
                table: "Contents");

            migrationBuilder.DropColumn(
                name: "ParentContentId",
                table: "Contents");

            migrationBuilder.UpdateData(
                table: "UrlRouteTypes",
                keyColumn: "UrlRouteTypeId",
                keyValue: 2,
                column: "Name",
                value: "Content");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<int>(
                name: "Ordinal",
                table: "Contents",
                nullable: false,
                defaultValue: 0);

            migrationBuilder.AddColumn<Guid>(
                name: "ParentContentId",
                table: "Contents",
                nullable: true);

            migrationBuilder.UpdateData(
                table: "UrlRouteTypes",
                keyColumn: "UrlRouteTypeId",
                keyValue: 2,
                column: "Name",
                value: "Page");

            migrationBuilder.InsertData(
                table: "UrlRouteTypes",
                columns: new[] { "UrlRouteTypeId", "Name", "UrlRouteTypes" },
                values: new object[] { 3, "Post", 1 });

            migrationBuilder.CreateIndex(
                name: "IX_Contents_ParentContentId",
                table: "Contents",
                column: "ParentContentId");
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
SoyMsgBundle (Soy Complete)
</TITLE>

<META NAME="date" CONTENT="2010-07-21">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.google.template.soy.msgs

Interface SoyMsgBundle

All Superinterfaces:
Iterable<SoyMsg>

All Known Implementing Classes:
SoyMsgBundleImpl

public interface SoyMsgBundle
extends Iterable<SoyMsg>

Represents a full set of messages in some language/locale.

Field Summary

static SoyMsgBundle
EMPTY

          Null object for SoyMsgBundle.

Method Summary

 String
getLocaleString()

          Gets the language/locale string of this bundle of messages.

 SoyMsg
getMsg(long msgId)

          Retrieves a message by its unique message id.

 int
getNumMsgs()

          Gets the number of messages in this bundle.

 Iterator<SoyMsg>
iterator()

          Returns an iterator over all the messages.

Field Detail

EMPTY

static final SoyMsgBundle EMPTY

Null object for SoyMsgBundle.

Method Detail

getLocaleString

String getLocaleString()

Gets the language/locale string of this bundle of messages.

Returns:
The language/locale string of the messages provided by this bundle.

getMsg

SoyMsg getMsg(long msgId)

Retrieves a message by its unique message id.

Parameters:
msgId - The message id of the message to retrieve.

Returns:
The corresponding message, or null if not found.

getNumMsgs

int getNumMsgs()

Gets the number of messages in this bundle.

Returns:
The number of messages in this bundle.

iterator

Iterator<SoyMsg> iterator()

Returns an iterator over all the messages.

Specified by:
iterator in interface Iterable<SoyMsg>

Returns:
An iterator over all the messages.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                © 2009 Google -
                Privacy Policy -
                Terms and Conditions -
                About Google


text:
"""Class to perform random over-sampling."""
from __future__ import print_function
from __future__ import division

import numpy as np

from collections import Counter

from sklearn.utils import check_random_state

from ..base import BaseMulticlassSampler

class RandomOverSampler(BaseMulticlassSampler):

    """Class to perform random over-sampling.

    Object to over-sample the minority class(es) by picking samples at random
    with replacement.

    Parameters
    ----------
    ratio : str or float, optional (default='auto')
        If 'auto', the ratio will be defined automatically to balance
        the dataset. Otherwise, the ratio is defined as the number
        of samples in the minority class over the the number of samples
        in the majority class.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by np.random.

    Attributes
    ----------
    min_c_ : str or int
        The identifier of the minority class.

    max_c_ : str or int
        The identifier of the majority class.

    stats_c_ : dict of str/int : int
        A dictionary in which the number of occurences of each class is
        reported.

    X_shape_ : tuple of int
        Shape of the data `X` during fitting.

    Notes
    -----
    Supports multiple classes.

    Examples
    --------

    >>> from collections import Counter
    >>> from sklearn.datasets import make_classification
    >>> from imblearn.over_sampling import RandomOverSampler
    >>> X, y = make_classification(n_classes=2, class_sep=2, weights=[0.1, 0.9],
    ...                            n_informative=3, n_redundant=1, flip_y=0,
    ...                            n_features=20, n_clusters_per_class=1,
    ...                            n_samples=1000, random_state=10)
    >>> print('Original dataset shape {}'.format(Counter(y)))
    Original dataset shape Counter({1: 900, 0: 100})
    >>> ros = RandomOverSampler(random_state=42)
    >>> X_res, y_res = ros.fit_sample(X, y)
    >>> print('Resampled dataset shape {}'.format(Counter(y_res)))
    Resampled dataset shape Counter({0: 900, 1: 900})

    """

    def __init__(self,
                 ratio='auto',
                 random_state=None):

        super(RandomOverSampler, self).__init__(ratio=ratio)
        self.random_state = random_state

    def _sample(self, X, y):
        """Resample the dataset.

        Parameters
        ----------
        X : ndarray, shape (n_samples, n_features)
            Matrix containing the data which have to be sampled.

        y : ndarray, shape (n_samples, )
            Corresponding label for each sample in X.

        Returns
        -------
        X_resampled : ndarray, shape (n_samples_new, n_features)
            The array containing the resampled data.

        y_resampled : ndarray, shape (n_samples_new)
            The corresponding label of `X_resampled`

        """

        # Keep the samples from the majority class
        X_resampled = X[y == self.maj_c_]
        y_resampled = y[y == self.maj_c_]

        # Loop over the other classes over picking at random
        for key in self.stats_c_.keys():

            # If this is the majority class, skip it
            if key == self.maj_c_:
                continue

            # Define the number of sample to create
            if self.ratio == 'auto':
                num_samples = int(self.stats_c_[self.maj_c_] -
                                  self.stats_c_[key])
            else:
                num_samples = int((self.ratio * self.stats_c_[self.maj_c_]) -
                                  self.stats_c_[key])

            # Pick some elements at random
            random_state = check_random_state(self.random_state)
            indx = random_state.randint(low=0, high=self.stats_c_[key],
                                        size=num_samples)

            # Concatenate to the majority class
            X_resampled = np.concatenate((X_resampled,
                                          X[y == key],
                                          X[y == key][indx]),
                                         axis=0)

            y_resampled = np.concatenate((y_resampled,
                                          y[y == key],
                                          y[y == key][indx]), axis=0)

        self.logger.info('Over-sampling performed: %s', Counter(
            y_resampled))

        return X_resampled, y_resampled


text:
package es.upv.i3m.grycap.im.auth.credentials;

public enum ServiceProvider {

  //@formatter:off
  INFRASTRUCTURE_MANAGER("im","InfrastructureManager"),
  VMRC("vmrc","VMRC"),
  DUMMY("dummy","Dummy"),
  OPENNEBULA("one","OpenNebula"),
  EC2("ec2","EC2"),
  FOG_BOW("fog","FogBow"),
  OPENSTACK("ost","OpenStack"),
  OCCI("occi","OCCI"),
  DOCKER("docker","Docker"),
  GCE("gce","GCE"),
  AZURE("azure","Azure"),
  KUBERNETES("kub","Kubernetes");
  //@formatter:on

  private final String id;
  private final String type;

  private ServiceProvider(final String id, final String type) {
    this.id = id;
    this.type = type;
  }

  public final String getId() {
    return id;
  }

  public final String getType() {
    return type;
  }

}


text:
package com.github.skjolber.nfc.external.hceclient;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.cardemulation.CardEmulation;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.github.skjolber.nfc.util.Broadcast;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * Activity for this app to echo the HCE service using internal NFC.
 *
 */

public class HceActivity extends DialogActivity {

	private static String TAG = HceActivity.class.getName();

	private static final Map<Class, Integer> services;

	static {
		services = new HashMap<>();
		services.put(EchoHostApduService.class, R.xml.echoservice);
		services.put(HelloHostApduService.class, R.xml.helloservice);
	}

	private boolean receiving = false;
	private CardEmulation cardEmulation;

	private final BroadcastReceiver hostCardEmulationBroadcastReceiver = new BroadcastReceiver() {

		public void onReceive(Context context, final Intent intent) {

			String action = intent.getAction();

			if (Broadcast.HOST_CARD_EMULATION_ACTION_PROCESS_COMMAND_ADPU.equals(action)) {
				final byte[] command = intent.getByteArrayExtra(Broadcast.HOST_CARD_EMULATION_EXTRA_COMMAND);
				final byte[] response = intent.getByteArrayExtra(Broadcast.HOST_CARD_EMULATION_EXTRA_RESPONSE);
				runOnUiThread(new Runnable() {
					public void run() {
						TextView textView = (TextView) findViewById(R.id.text);

						textView.setText(textView.getText() + " <- " + EchoHostApduService.toHexString(command) + "\n -> " + EchoHostApduService.toHexString(response) + "\n");
					}
				});
			} else if (Broadcast.HOST_CARD_EMULATION_ACTION_DEACTIVATED.equals(action)) {

				runOnUiThread(new Runnable() {
					public void run() {
						TextView textView = (TextView) findViewById(R.id.text);

						textView.setText(textView.getText() + "Deactivated (tag lost or IsoDep.close() called)" + "\n");
					}
				});
			} else if ("android.intent.action.MAIN".equals(action)) {
				// ignore
			} else throw new IllegalArgumentException("Unexpected action " + action);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

		setContentView(R.layout.activity_main);

		cardEmulation = CardEmulation.getInstance(NfcAdapter.getDefaultAdapter(this));

		for (Map.Entry<Class, Integer> entry : services.entrySet()) {
			String aid = Utils.parseAid(this, entry.getValue());

			if (!cardEmulation.isDefaultServiceForAid(new ComponentName(this, entry.getKey()), aid)) {
				Log.d(TAG, "This application is NOT the preferred service for aid " + aid);
			} else {
				Log.d(TAG, "This application is the preferred service for aid " + aid);
			}
		}

		enableBroadcast();

		showHelpfulDialog();

		Intent intent = getIntent();

		hostCardEmulationBroadcastReceiver.onReceive(this, getIntent());
	}

	private void showHelpfulDialog() {
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(R.string.dialogTitle);
		alert.setMessage(R.string.dialogMessage);

		alert.setNegativeButton(R.string.dialogClose, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

				return;
			}
		});

		final AlertDialog dialog = alert.create();

		dialog.setCanceledOnTouchOutside(true);
		dialog.setCancelable(true); // back button

		show(dialog);
	}

	@Override
	protected void onResume() {
		super.onResume();

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

		// note: this will only work for a single HCE service
		for (Map.Entry<Class, Integer> entry : services.entrySet()) {
			boolean preferred = prefs.getBoolean(PreferencesActivity.PREFERENCE_HOST_CARD_EMULATION_PREFERENCE + "_" + entry.getKey().getSimpleName(), true);

			if(preferred) {
				if (cardEmulation.setPreferredService(this, new ComponentName(this, entry.getKey()))) {
					Log.d(TAG, "Set " + entry.getKey().getName() + " to be the preferred HCE service for this activity");
				} else {
					Log.w(TAG, "Unable to set " + entry.getKey().getName() + " to be the preferred HCE service for this activity");
				}
			}
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

		if(cardEmulation.unsetPreferredService(this)) {
			Log.d(TAG, "Unset preferred service for " + getClass().getName());
		} else {
			Log.d(TAG, "Unable to unset preferred service for " + getClass().getName());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void enableBroadcast() {
		if (!receiving) {
			IntentFilter serviceFilter = new IntentFilter();
			serviceFilter.addAction(Broadcast.HOST_CARD_EMULATION_ACTION_PROCESS_COMMAND_ADPU);
			serviceFilter.addAction(Broadcast.HOST_CARD_EMULATION_ACTION_DEACTIVATED);
			registerReceiver(hostCardEmulationBroadcastReceiver, serviceFilter);

			receiving = true;
		}
	}

	public void disableBroadcast() {
		if (receiving) {
			unregisterReceiver(hostCardEmulationBroadcastReceiver);

			receiving = false;
		}
	}

	public void showHelp(View view) {
		String url = "https://developer.android.com/guide/topics/connectivity/nfc/hce.html#ScreenOffBehavior";
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setData(Uri.parse(url));
		startActivity(i);
	}

	public void clear(View view) {
		TextView textView = (TextView) findViewById(R.id.text);
		textView.setText("");
	}

	@Override
	protected void onDestroy() {
		disableBroadcast();

		super.onDestroy();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

			case R.id.menu_server: {
				Intent intent = new Intent(this, HceInvokerActivity.class);
				startActivity(intent);
				return true;
			}
			case R.id.action_preferences: {
				Intent intent = new Intent(this, PreferencesActivity.class);
				startActivity(intent);
				return true;
			}

			default:
				return super.onOptionsItemSelected(item);
		}

	}

}


text:
(function() {
	angular
		.module("app")
		.directive('contenteditable', [ContentEditableDirective])

	function ContentEditableDirective($compile) {
		return {
			restrict: 'A',
			require: "?ngModel",
			link: function (scope, element, attrs, ngModel) {
				if (!ngModel) return; // do nothing if no ng-model

			    ngModel.$render = function() {
			    	element.html(ngModel.$viewValue || '');
			    };

			    element.on('blur keyup change', function() {
			    	scope.$evalAsync(read);
			    });
			    read();

		    	function read() {
				    var html = element.html();
				    if ( attrs.stripBr && html == '<br>' ) {
				    	html = '';
				    }

				    ngModel.$setViewValue(html);
			    }
			}
		}
	}
})()


text:
A simple Common Lisp interface to the Brønnøysund register of norwegian corporations.

Connects to the brreg api via http, parses the json result and returns desired field.

Usage:
* (get-org-name "974760673")
* (get-org-address "974760673")
* (get-org-postnummer "974760673")
* (get-org-poststed "974760673")


text:
// Copyright 2013 Trimble Inc. All Rights Reserved.

/**
 * @file
 * @brief Interfaces for SUOpeningRef.
 */
#ifndef SKETCHUP_MODEL_OPENING_H_
#define SKETCHUP_MODEL_OPENING_H_

#include <SketchUpAPI/common.h>
#include <SketchUpAPI/geometry.h>
#include <SketchUpAPI/model/defs.h>
#include <SketchUpAPI/model/component_instance.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
@struct SUOpeningRef
@brief  References an opening object, which is a hole in a face created by an
        attached component instance or group.
@since SketchUp 2014, API 2.0

*/

/**
@brief Retrieves the number of points of an opening.
@since SketchUp 2014, API 2.0
@param[in]  opening The opening object.
@param[out] count   The number of points.
@related SUOpeningRef
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if opening is not a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if count is NULL
*/
SU_RESULT SUOpeningGetNumPoints(SUOpeningRef opening, size_t* count);

/**
@brief Retrieves the points of an opening object.
@since SketchUp 2014, API 2.0
@param[in]  opening  The opening object.
@param[in]  len      The number of points to retrieve.
@param[out] points   The points retrieved.
@param[out] count    The number of points retrieved.
@related SUOpeningRef
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if opening is not a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if points or count is NULL
*/
SU_RESULT SUOpeningGetPoints(SUOpeningRef opening, size_t len,
                             struct SUPoint3D points[], size_t* count);

/**
@brief Release an opening object.
@since SketchUp 2014, API 2.0
@param[in]  opening  The opening object.
@related SUOpeningRef
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if opening is not a valid object
- \ref SU_ERROR_NULL_POINTER_INPUT if points or count is NULL
*/
SU_RESULT SUOpeningRelease(SUOpeningRef *opening);

#ifdef __cplusplus
}  // extern "C" {
#endif

#endif  // SKETCHUP_MODEL_OPENING_H_


text:
<?php

declare(strict_types=1);

use ast\Node;
use Phan\AST\ContextNode;
use Phan\AST\UnionTypeVisitor;
use Phan\Exception\CodeBaseException;
use Phan\Language\Element\FunctionInterface;
use Phan\PluginV3;
use Phan\PluginV3\PluginAwarePostAnalysisVisitor;
use Phan\PluginV3\PostAnalyzeNodeCapability;

/**
 * A plugin that checks if calls to a function or method pass in arguments in a suspicious order.
 * E.g. calling `function example($offset, $count)` as `example($count, $offset)`
 */
class SuspiciousParamOrderPlugin extends PluginV3 implements PostAnalyzeNodeCapability
{
    /**
     * @return string - name of PluginAwarePostAnalysisVisitor subclass
     */
    public static function getPostAnalyzeNodeVisitorClassName(): string
    {
        return SuspiciousParamOrderVisitor::class;
    }
}

/**
 * Checks for invocations of functions/methods where the return value should be used.
 * Also, gathers statistics on how often those functions/methods are used.
 */
class SuspiciousParamOrderVisitor extends PluginAwarePostAnalysisVisitor
{
    // phpcs:disable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase
    // this is deliberate for issue names
    private const SuspiciousParamOrderInternal = 'PhanPluginSuspiciousParamOrderInternal';
    private const SuspiciousParamOrder = 'PhanPluginSuspiciousParamOrder';
    private const SuspiciousParamPosition = 'PhanPluginSuspiciousParamPosition';
    private const SuspiciousParamPositionInternal = 'PhanPluginSuspiciousParamPositionInternal';
    // phpcs:enable Generic.NamingConventions.UpperCaseConstantName.ClassConstantNotUpperCase

    /**
     * @param Node $node a node of type AST_CALL
     * @override
     */
    public function visitCall(Node $node): void
    {
        $args = $node->children['args']->children;
        if (count($args) < 1) {
            // Can't have a suspicious param order/position if there are no params
            return;
        }
        $expression = $node->children['expr'];
        try {
            $function_list_generator = (new ContextNode(
                $this->code_base,
                $this->context,
                $expression
            ))->getFunctionFromNode();

            foreach ($function_list_generator as $function) {
                // @phan-suppress-next-line PhanPartialTypeMismatchArgument
                $this->checkCall($function, $args, $node);
            }
        } catch (CodeBaseException $_) {
        }
    }

    /**
     * @param Node|string|int|float|null $arg_node
     */
    private static function extractName($arg_node): ?string
    {
        if (!$arg_node instanceof Node) {
            return null;
        }
        switch ($arg_node->kind) {
            case ast\AST_VAR:
                $name = $arg_node->children['name'];
                break;
                /*
            case ast\AST_CONST:
                $name = $arg_node->children['name']->children['name'];
                break;
                 */
            case ast\AST_PROP:
            case ast\AST_STATIC_PROP:
                $name = $arg_node->children['prop'];
                break;
            case ast\AST_METHOD_CALL:
            case ast\AST_STATIC_CALL:
                $name = $arg_node->children['method'];
                break;
            case ast\AST_CALL:
                $name = $arg_node->children['expr'];
                break;
            default:
                return null;
        }
        return is_string($name) ? $name : null;
    }

    /**
     * Returns a distance in the range 0..1, inclusive.
     *
     * A distance of 0 means they are similar (e.g. foo and getFoo()),
     * and 1 means there are no letters in common (bar and foo)
     */
    private static function computeDistance(string $a, string $b): float
    {
        $la = strlen($a);
        $lb = strlen($b);
        return (levenshtein($a, $b) - abs($la - $lb)) / max(1, min($la, $lb));
    }

    /**
     * @param list<Node|string|int|float> $args
     */
    private function checkCall(FunctionInterface $function, array $args, Node $node): void
    {
        $arg_names = [];
        foreach ($args as $i => $arg_node) {
            $name = self::extractName($arg_node);
            if (!is_string($name)) {
                continue;
            }
            $arg_names[$i] = strtolower($name);
        }
        if (count($arg_names) < 2) {
            if (count($arg_names) === 1) {
                $this->checkMovedArg($function, $args, $node, $arg_names);
            }
            return;
        }
        $parameters = $function->getParameterList();
        $parameter_names = [];
        foreach ($arg_names as $i => $_) {
            if (!isset($parameters[$i])) {
                unset($arg_names[$i]);
                continue;
            }
            $parameter_names[$i] = strtolower($parameters[$i]->getName());
        }
        if (count($arg_names) < 2) {
            // $arg_names and $parameter_names have the same keys
            $this->checkMovedArg($function, $args, $node, $arg_names);
            return;
        }
        $best_destination_map = [];
        foreach ($arg_names as $i => $name) {
            // To even be considered, the distance metric must be less than 60% (100% would have nothing in common)
            $best_distance = min(
                0.6,
                self::computeDistance($name, $parameter_names[$i])
            );
            $best_destination = null;
            // echo "Distances for $name to $parameter_names[$i] is $best_distance\n";

            foreach ($parameter_names as $j => $parameter_name_j) {
                if ($j === $i) {
                    continue;
                }
                $d_swap_j = self::computeDistance($name, $parameter_name_j);
                // echo "Distances for $name to $parameter_name_j is $d_swap_j\n";
                if ($d_swap_j < $best_distance) {
                    $best_destination = $j;
                    $best_distance = $d_swap_j;
                }
            }
            if ($best_destination !== null) {
                $best_destination_map[$i] = $best_destination;
            }
        }
        if (count($best_destination_map) < 2) {
            $this->checkMovedArg($function, $args, $node, $arg_names);
            return;
        }
        $places_set = [];
        foreach (self::findCycles($best_destination_map) as $cycle) {
            // To reduce false positives, don't warn unless we know the parameter $j would be compatible with what was used at $i
            foreach ($cycle as $array_index => $i) {
                $j = $cycle[($array_index + 1) % count($cycle)];
                $type = UnionTypeVisitor::unionTypeFromNode($this->code_base, $this->context, $args[$i]);
                // echo "Checking if $type can cast to $parameters[$j]\n";
                if (!$type->asExpandedTypes($this->code_base)->canCastToUnionType($parameters[$j]->getUnionType())) {
                    continue 2;
                }
            }
            foreach ($cycle as $i) {
                $places_set[$i] = true;
            }
            $arg_details = implode(' and ', array_map(static function (int $i) use ($args): string {
                return self::extractName($args[$i]) ?? 'unknown';
            }, $cycle));
            $param_details = implode(' and ', array_map(static function (int $i) use ($parameters): string {
                $param = $parameters[$i];
                return '#' . ($i + 1) . ' (' . trim($param->getUnionType() . ' $' . $param->getName()) . ')';
            }, $cycle));
            if ($function->isPHPInternal()) {
                $this->emitPluginIssue(
                    $this->code_base,
                    clone($this->context)->withLineNumberStart($node->lineno),
                    self::SuspiciousParamOrderInternal,
                    'Suspicious order for arguments named {DETAILS} - These are being passed to parameters {DETAILS} of {FUNCTION}',
                    [
                        $arg_details,
                        $param_details,
                        $function->getRepresentationForIssue(true),
                    ]
                );
            } else {
                $this->emitPluginIssue(
                    $this->code_base,
                    clone($this->context)->withLineNumberStart($node->lineno),
                    self::SuspiciousParamOrder,
                    'Suspicious order for arguments named {DETAILS} - These are being passed to parameters {DETAILS} of {FUNCTION} defined at {FILE}:{LINE}',
                    [
                        $arg_details,
                        $param_details,
                        $function->getRepresentationForIssue(true),
                        $function->getContext()->getFile(),
                        $function->getContext()->getLineNumberStart(),
                    ]
                );
            }
        }
        $this->checkMovedArg($function, $args, $node, $arg_names, $places_set);
    }

    /**
     * @param FunctionInterface $function the function being called
     * @param list<Node|string|int|float> $args
     * @param Node $node
     * @param associative-array<int,string> $arg_names
     * @param associative-array<int,true> $places_set the places that were already warned about being transposed.
     */
    private function checkMovedArg(FunctionInterface $function, array $args, Node $node, array $arg_names, array $places_set = []): void
    {
        $real_parameters = $function->getRealParameterList();
        $parameters = $function->getParameterList();
        /** @var associative-array<string,?int> maps lowercase param names to their unique index, or null */
        $parameter_names = [];
        foreach ($real_parameters as $i => $param) {
            if (isset($places_set[$i])) {
                continue;
            }
            $name_key = str_replace('_', '', strtolower($param->getName()));
            if (array_key_exists($name_key, $parameter_names)) {
                $parameter_names[$name_key] = null;
            } else {
                $parameter_names[$name_key] = $i;
            }
        }
        foreach ($arg_names as $i => $name) {
            $other_i = $parameter_names[str_replace('_', '', strtolower($name))] ?? null;
            if ($other_i === null || $other_i === $i) {
                continue;
            }
            $real_param = $real_parameters[$other_i];
            if ($real_param->isVariadic()) {
                // Skip warning about signatures such as var_dump($var, ...$args) or array_unshift($values, $arg, $arg2)
                //
                // NOTE: For internal functions, some functions such as implode() have alternate signatures where the real parameter is in a different place,
                // which is why this checks both $real_param and $param
                //
                // For user-defined functions, alternates are not supported.
                continue;
            }
            $param = $parameters[$other_i] ?? null;
            if ($param && $param->getName() === $real_param->getName()) {
                if ($param->isVariadic()) {
                    continue;
                }
                $real_param = $param;
            }
            $real_param_details = '#' . ($other_i + 1) . ' (' . trim($real_param->getUnionType() . ' $' . $real_param->getName()) . ')';
            $arg_details = self::extractName($args[$i]) ?? 'unknown';
            if ($function->isPHPInternal()) {
                $this->emitPluginIssue(
                    $this->code_base,
                    (clone($this->context))->withLineNumberStart($args[$i]->lineno ?? $node->lineno),
                    self::SuspiciousParamPositionInternal,
                    'Suspicious order for argument {DETAILS} - This is getting passed to parameter {DETAILS} of {FUNCTION}',
                    [
                        $arg_details,
                        $real_param_details,
                        $function->getRepresentationForIssue(true),
                    ]
                );
            } else {
                $this->emitPluginIssue(
                    $this->code_base,
                    clone($this->context)->withLineNumberStart($args[$i]->lineno ?? $node->lineno),
                    self::SuspiciousParamPosition,
                    'Suspicious order for argument {DETAILS} - This is getting passed to parameter {DETAILS} of {FUNCTION} defined at {FILE}:{LINE}',
                    [
                        $arg_details,
                        $real_param_details,
                        $function->getRepresentationForIssue(true),
                        $function->getContext()->getFile(),
                        $function->getContext()->getLineNumberStart(),
                    ]
                );
            }
        }
    }

    /**
     * @param list<int> $values
     * @return list<int> the same values of the cycle, rearranged to start with the smallest value.
     */
    private static function normalizeCycle(array $values, int $next): array
    {
        $pos = array_search($next, $values, true);
        $values = array_slice($values, $pos ?: 0);
        $min_pos = 0;
        foreach ($values as $i => $value) {
            if ($value < $values[$min_pos]) {
                $min_pos = $values[$i];
            }
        }
        return array_merge(array_slice($values, $min_pos), array_slice($values, 0, $min_pos));
    }

    /**
     * Given [1 => 2, 2 => 3, 3 => 1, 4 => 5, 5 => 6, 6 => 5]], return [[1,2,3],[5,6]]
     * @param array<int,int> $destination_map
     * @return array<int,array<int,int>>
     */
    public static function findCycles(array $destination_map): array
    {
        $result = [];
        while (count($destination_map) > 0) {
            reset($destination_map);
            $key = (int) key($destination_map);
            $values = [];
            while (count($destination_map) > 0) {
                $values[] = $key;
                $next = $destination_map[$key];
                unset($destination_map[$key]);
                if (in_array($next, $values, true)) {
                    $values = self::normalizeCycle($values, $next);
                    if (count($values) >= 2) {
                        $result[] = $values;
                    }
                    $values = [];
                    break;
                }
                if (!isset($destination_map[$next])) {
                    break;
                }
                $key = $next;
            }
        }
        return $result;
    }

    /**
     * @param Node $node a node of type AST_NULLSAFE_METHOD_CALL
     * @override
     */
    public function visitNullsafeMethodCall(Node $node): void
    {
        $this->visitMethodCall($node);
    }

    /**
     * @param Node $node a node of type AST_METHOD_CALL
     * @override
     */
    public function visitMethodCall(Node $node): void
    {
        $args = $node->children['args']->children;
        if (count($args) < 1) {
            // Can't have a suspicious param order/position if there are no params
            return;
        }

        $method_name = $node->children['method'];

        if (!\is_string($method_name)) {
            return;
        }
        try {
            $method = (new ContextNode(
                $this->code_base,
                $this->context,
                $node
            ))->getMethod($method_name, false, true);
        } catch (Exception $_) {
            return;
        }
        // @phan-suppress-next-line PhanPartialTypeMismatchArgument
        $this->checkCall($method, $args, $node);
    }

    /**
     * @param Node $node a node of type AST_STATIC_CALL
     * @override
     */
    public function visitStaticCall(Node $node): void
    {
        $args = $node->children['args']->children;
        if (count($args) < 1) {
            // Can't have a suspicious param order/position if there are no params
            return;
        }

        $method_name = $node->children['method'];

        if (!\is_string($method_name)) {
            return;
        }
        try {
            $method = (new ContextNode(
                $this->code_base,
                $this->context,
                $node
            ))->getMethod($method_name, true, true);
        } catch (Exception $_) {
            return;
        }
        // @phan-suppress-next-line PhanPartialTypeMismatchArgument
        $this->checkCall($method, $args, $node);
    }
}

// Every plugin needs to return an instance of itself at the
// end of the file in which it's defined.
return new SuspiciousParamOrderPlugin();


text:
The folder contains a repository of tasks (missions) in Malmo.
- MalmoMissionTable_CurrentTasks_2016_06_14.pdf: a description of the tasks.
- *.xml: All missions are .xml files.

To explore the sample missions, see Python_Examples/sample_missions_loader.py.


text:
create table FORM_TEMPLATE(
        ID BIGINT NOT NULL,
	TYPE INT,
	NAME VARCHAR(200),
	CONTENT VARCHAR(2000),
        CONSTRAINT PK_FORM_TEMPLATE PRIMARY KEY(ID)
) ENGINE=INNODB CHARSET=UTF8;


text:
package com.facebook.buck.event;

import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonValue;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

import org.immutables.value.Value;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * An implementation of {@link BuckEvent}s used for gathering performance statistics. These are
 * only intended to be used with the trace viewer and should not be used to communicate
 * information between parts of the system.
 */
public abstract class SimplePerfEvent extends AbstractBuckEvent {

  public SimplePerfEvent(EventKey eventKey) {
    super(eventKey);
  }

  public enum Type {
    STARTED("Started"),
    UPDATED("Updated"),
    FINISHED("Finished"),
    ;

    private String value;

    public String getValue() {
      return value;
    }

    Type(String value) {
      this.value = value;
    }
  }

  /**
   * @return event identifier.
   */
  public abstract PerfEventId getEventId();

  /**
   * @return event type.
   */
  public abstract Type getEventType();

  /**
   * @return information associated with the event.
   */
  public abstract ImmutableMap<String, Object> getEventInfo();

  /**
   * Prefer using {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}
   * when possible.
   *
   * Create an event that indicates the start of a particular operation.
   *
   * @param perfEventId identifier of the operation (Upload, CacheFetch, Parse, etc..).
   * @param info Any additional information to be saved with the event. This will be serialized and
   *             potentially sent over the wire, so please keep this small.
   * @return an object that should be used to create the corresponding update and finished event.
   */
  public static Started started(
      PerfEventId perfEventId,
      ImmutableMap<String, Object> info) {
    return new StartedImpl(perfEventId, info);
  }

  /**
   * Convenience wrapper around {@link SimplePerfEvent#started(PerfEventId, ImmutableMap)}.
   *
   * @param perfEventId identifier of the operation (Upload, CacheFetch, Parse, etc..).
   * @return an object that should be used to create the corresponding update and finished event.
   */
  public static Started started(PerfEventId perfEventId) {
    return started(perfEventId, ImmutableMap.of());
  }

  /**
   * Convenience wrapper around {@link SimplePerfEvent#started(PerfEventId, ImmutableMap)}.
   *
   * @param perfEventId identifier of the operation (Upload, CacheFetch, Parse, etc..).
   * @param k1 name of the value to be stored with the event.
   * @param v1 value to be stored. This will be serialized and potentially sent over the wire,
   *           so please keep this small.
   * @return an object that should be used to create the corresponding update and finished event.
   */
  public static Started started(PerfEventId perfEventId, String k1, Object v1) {
    return started(perfEventId, ImmutableMap.of(k1, v1));
  }

  /**
   * Convenience wrapper around {@link SimplePerfEvent#started(PerfEventId, ImmutableMap)}.
   *
   * @param perfEventId identifier of the operation (Upload, CacheFetch, Parse, etc..).
   * @param k1 name of the value to be stored with the event.
   * @param v1 value to be stored. This will be serialized and potentially sent over the wire,
   *           so please keep this small.
   * @param k2 name of the value to be stored with the event.
   * @param v2 value to be stored. This will be serialized and potentially sent over the wire,
   *           so please keep this small.
   * @return an object that should be used to create the corresponding update and finished event.
   */
  public static Started started(
      PerfEventId perfEventId,
      String k1,
      Object v1,
      String k2,
      Object v2) {
    return started(perfEventId, ImmutableMap.of(k1, v1, k2, v2));
  }

  /**
   * Creates a scope within which the measured operation takes place.
   *
   * <pre>
   * try (perfEvent = SimplePerfEvent.scope(bus, PerfEventId.of("BurnCpu"))) {
   *   int bitsFlopped = 0;
   *   for (int i = 0; i < 1000; i++) {
   *     bitsFlopped += invokeExpensiveOp();
   *     if (bitsFlopped % 100 == 0) {
   *       // Some of these events are of special interest.
   *       perfEvent.update("noFlopIteration", i);
   *     }
   *   }
   *   perfEvent.appendFinishedInfo("totalBitsFlopped", bitsFlopped);
   * }
   * </pre>
   *
   * @param bus the {@link BuckEventBus} to post update and finished events to.
   * @param perfEventId identifier of the operation (Upload, CacheFetch, Parse, etc..).
   * @param info Any additional information to be saved with the event. This will be serialized and
   *             potentially sent over the wire, so please keep this small.
   * @return an AutoCloseable which will send the finished event as soon as control flow exits
   * the scope.
   */
  public static Scope scope(
      BuckEventBus bus,
      PerfEventId perfEventId,
      ImmutableMap<String, Object> info) {
    StartedImpl started = new StartedImpl(perfEventId, info);
    bus.post(started);
    return new SimplePerfEventScope(bus, started);
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scope(
      BuckEventBus bus,
      PerfEventId perfEventId) {
    return scope(bus, perfEventId, ImmutableMap.of());
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scope(
      BuckEventBus bus,
      PerfEventId perfEventId,
      String k1,
      Object v1) {
    return scope(bus, perfEventId, ImmutableMap.of(k1, v1));
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scope(
      BuckEventBus bus,
      PerfEventId perfEventId,
      String k1,
      Object v1,
      String k2,
      Object v2) {
    return scope(bus, perfEventId, ImmutableMap.of(k1, v1, k2, v2));
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scope(
      Optional<BuckEventBus> bus,
      PerfEventId perfEventId,
      ImmutableMap<String, Object> info) {
    if (bus.isPresent()) {
      return scope(bus.get(), perfEventId, info);
    } else {
      return new NoopScope();
    }
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scope(
      Optional<BuckEventBus> bus,
      PerfEventId perfEventId) {
    return scope(bus, perfEventId, ImmutableMap.of());
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scope(
      Optional<BuckEventBus> bus,
      PerfEventId perfEventId,
      String k,
      Object v) {
    return scope(bus, perfEventId, ImmutableMap.of(k, v));
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scope(
      Optional<BuckEventBus> bus,
      PerfEventId perfEventId,
      String k,
      Object v,
      String k2,
      Object v2) {
    return scope(bus, perfEventId, ImmutableMap.of(k, v, k2, v2));
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scope(BuckEventBus bus, String perfEventName) {
    return scope(bus, PerfEventId.of(perfEventName), ImmutableMap.<String, Object>of());
  }

  /**
   * Like {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}, but doesn't post
   * the events if the duration of the scope is below a certain threshold.
   * NOTE: The events are buffered before being posted. The longer they are buffered, the more
   * likely any logging code will be confused. Ideally the threshold should not exceed 100ms.
   *
   *
   * @param bus the {@link BuckEventBus} to post update and finished events to.
   * @param perfEventId identifier of the operation (Upload, CacheFetch, Parse, etc..).
   * @param info Any additional information to be saved with the event. This will be serialized and
   *             potentially sent over the wire, so please keep this small.
   * @param minimumTime the scope must take at least this long for the event to be posted.
   * @param timeUnit time unit for minimumTime.
   * @return an AutoCloseable which will send the finished event as soon as control flow exits
   * the scope.
   */
  public static Scope scopeIgnoringShortEvents(
      BuckEventBus bus,
      PerfEventId perfEventId,
      ImmutableMap<String, Object> info,
      Scope parentScope,
      long minimumTime,
      TimeUnit timeUnit) {
    if (minimumTime == 0) {
      return scope(bus, perfEventId, info);
    }
    StartedImpl started = new StartedImpl(perfEventId, info);
    bus.timestamp(started);
    return new MinimumTimePerfEventScope(bus, started, parentScope, timeUnit.toNanos(minimumTime));
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scopeIgnoringShortEvents(
      BuckEventBus bus,
      PerfEventId perfEventId,
      Scope parentScope,
      long minimumTime,
      TimeUnit timeUnit) {
    return scopeIgnoringShortEvents(
        bus,
        perfEventId,
        ImmutableMap.of(),
        parentScope,
        minimumTime,
        timeUnit);
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scopeIgnoringShortEvents(
      BuckEventBus bus,
      PerfEventId perfEventId,
      String k1,
      Object v1,
      Scope parentScope,
      long minimumTime,
      TimeUnit timeUnit) {
    return scopeIgnoringShortEvents(
        bus,
        perfEventId,
        ImmutableMap.of(k1, v1),
        parentScope,
        minimumTime,
        timeUnit);
  }

  /**
   * Convenience wrapper for {@link SimplePerfEvent#scope(BuckEventBus, PerfEventId, ImmutableMap)}.
   */
  public static Scope scopeIgnoringShortEvents(
      BuckEventBus bus,
      PerfEventId perfEventId,
      String k1,
      Object v1,
      String k2,
      Object v2,
      Scope parentScope,
      long minimumTime,
      TimeUnit timeUnit) {
    return scopeIgnoringShortEvents(
        bus,
        perfEventId,
        ImmutableMap.of(k1, v1, k2, v2),
        parentScope,
        minimumTime,
        timeUnit);
  }

  /**
   * Represents the scope within which a particular performance operation is taking place.
   */
  public interface Scope extends AutoCloseable {
    /**
     * Creates and sends an event which indicates an update in state of the scope. Every invocation
     * creates and sends a new event.
     * @param info Any additional information to be saved with the event. This will be serialized
     *             and potentially sent over the wire, so please keep this small.
     */
    void update(ImmutableMap<String, Object> info);

    /**
     * Convenience wrapper for {@link Scope#update(ImmutableMap)}.
     */
    void update(String k1, Object v1);

    /**
     * Convenience wrapper for {@link Scope#update(ImmutableMap)}.
     */
    void update(String k1, Object v1, String k2, Object v2);

    /**
     * Appends information to the finished event which will be sent when control exits the scope.
     * @param k1 name of the value to be stored with the event.
     * @param v1 value to be stored. This will be serialized and potentially sent over the wire,
     *           so please keep this small.
     */
    void appendFinishedInfo(String k1, Object v1);

    /**
     * Increments a counter that will be appended to the finished event.
     */
    void incrementFinishedCounter(String key, long increment);

    @Override
    void close();
  }

  public interface Started extends BuckEvent {
    /**
     * Creates a new event which indicates an update to the performance data being gathered.
     *
     * @param info Any additional information to be saved with the event. This will be serialized
     *             and potentially sent over the wire, so please keep this small.
     * @return An event which should be posted to the {@link BuckEventBus}.
     */
    BuckEvent createUpdateEvent(ImmutableMap<String, Object> info);

    /**
     * Convenience wrapper for
     * {@link Started#createUpdateEvent(String, Object)}.
     */
    BuckEvent createUpdateEvent(String k1, Object v1);

    /**
     * Convenience wrapper for
     * {@link Started#createUpdateEvent(String, Object)}.
     */
    BuckEvent createUpdateEvent(String k1, Object v1, String k2, Object v2);

    /**
     * Creates a new event which indicates the end of a performance event.
     *
     * @param info Any additional information to be saved with the event. This will be serialized
     *             and potentially sent over the wire, so please keep this small.
     * @return An event which should be posted to the {@link BuckEventBus}.
     */
    BuckEvent createFinishedEvent(ImmutableMap<String, Object> info);

    /**
     * Convenience wrapper for
     * {@link Started#createFinishedEvent(String, Object)}.
     */
    BuckEvent createFinishedEvent();

    /**
     * Convenience wrapper for
     * {@link Started#createFinishedEvent(String, Object)}.
     */
    BuckEvent createFinishedEvent(String k1, Object v1);

    /**
     * Convenience wrapper for
     * {@link Started#createFinishedEvent(String, Object)}.
     */
    BuckEvent createFinishedEvent(String k1, Object v1, String k2, Object v2);
  }

  @Value.Immutable
  @BuckStyleImmutable
  /**
   * This is an identifier for the various performance event names in use in the system. Should
   * be CamelCase (first letter capitalized).
   */
  abstract static class AbstractPerfEventId {
    @JsonValue
    @Value.Parameter
    public abstract String getValue();

    @Value.Check
    protected void nameIsNotEmpty() {
      Preconditions.checkArgument(!getValue().isEmpty());
    }
  }

  private static class NoopScope implements AutoCloseable, Scope {
    @Override
    public void update(ImmutableMap<String, Object> info) {
    }

    @Override
    public void update(String k1, Object v1) {
    }

    @Override
    public void update(String k1, Object v1, String k2, Object v2) {
    }

    @Override
    public void appendFinishedInfo(String k1, Object v1) {
    }

    @Override
    public void incrementFinishedCounter(String key, long increment) {
    }

    @Override
    public void close() {
    }
  }

  private static class SimplePerfEventScope implements AutoCloseable, Scope {
    protected BuckEventBus bus;
    protected StartedImpl started;
    protected ConcurrentMap<String, AtomicLong> finishedCounters;
    protected ImmutableMap.Builder<String, Object> finishedInfoBuilder;

    public SimplePerfEventScope(
        BuckEventBus bus,
        StartedImpl started) {
      this.bus = bus;
      this.started = started;
      this.finishedCounters = new ConcurrentHashMap<>();
      this.finishedInfoBuilder = ImmutableMap.builder();
    }

    @Override
    public void update(ImmutableMap<String, Object> info) {
      bus.post(new Updated(started, info));
    }

    @Override
    public void update(String k1, Object v1) {
      update(ImmutableMap.of(k1, v1));
    }

    @Override
    public void update(String k1, Object v1, String k2, Object v2) {
      update(ImmutableMap.of(k1, v1, k2, v2));
    }

    @Override
    public void appendFinishedInfo(String key, Object value) {
      finishedInfoBuilder.put(key, value);
    }

    @Override
    public void incrementFinishedCounter(String key, long delta) {
      AtomicLong count = finishedCounters.get(key);
      if (count == null) {
        finishedCounters.putIfAbsent(key, new AtomicLong(0));
        count = finishedCounters.get(key);
      }
      count.addAndGet(delta);
    }

    protected Finished createFinishedEvent() {
      finishedInfoBuilder.putAll(
          Maps.transformValues(
              finishedCounters,
              AtomicLong::get));
      return new Finished(started, finishedInfoBuilder.build());
    }

    @Override
    public void close() {
      bus.post(createFinishedEvent());
    }
  }

  private static class MinimumTimePerfEventScope extends SimplePerfEventScope {
    private final long minimumDurationNanos;
    private final Scope parentScope;
    private final List<AbstractChainablePerfEvent> events;

    public MinimumTimePerfEventScope(
        BuckEventBus bus,
        StartedImpl started,
        Scope parentScope,
        long minimumDurationNanos) {
      super(bus, started);
      this.minimumDurationNanos = minimumDurationNanos;
      this.parentScope = parentScope;
      this.events = new ArrayList<>();
      this.events.add(started);
    }

    @Override
    public void update(ImmutableMap<String, Object> info) {
      Updated event = new Updated(started, info);
      bus.timestamp(event);
      events.add(event);
    }

    @Override
    public void close() {
      Finished finished = createFinishedEvent();
      bus.timestamp(finished);
      events.add(finished);

      long delta = finished.getNanoTime() - started.getNanoTime();
      if (delta >= minimumDurationNanos) {
        for (AbstractChainablePerfEvent event : events) {
          bus.postWithoutConfiguring(event);
        }
      } else {
        parentScope.incrementFinishedCounter(
            started.getEventId().getValue() + "_accumulated_duration_ns", delta);
        parentScope.incrementFinishedCounter(
            started.getEventId().getValue() + "_accumulated_count", 1);
      }
    }
  }

  /**
   * Common implementation for the Started/Updated/Finished events.
   */
  private abstract static class AbstractChainablePerfEvent extends SimplePerfEvent {
    private PerfEventId perfEventId;
    private Type perfEventType;
    private ImmutableMap<String, Object> info;

    public AbstractChainablePerfEvent(
        EventKey eventKey,
        PerfEventId perfEventId,
        Type perfEventType,
        ImmutableMap<String, Object> info) {
      super(eventKey);
      this.perfEventId = perfEventId;
      this.perfEventType = perfEventType;
      this.info = info;
    }

    @Override
    public PerfEventId getEventId() {
      return perfEventId;
    }

    @Override
    public Type getEventType() {
      return perfEventType;
    }

    @Override
    public ImmutableMap<String, Object> getEventInfo() {
      return info;
    }

    @Override
    protected String getValueString() {
      return Joiner.on(',').withKeyValueSeparator(":").join(info);
    }

    @Override
    public String getEventName() {
      return new StringBuilder("PerfEvent")
          .append(perfEventId.getValue())
          .append(perfEventType.getValue())
          .toString();
    }

    @Override
    public int hashCode() {
      return Objects.hashCode(super.hashCode(), perfEventId, perfEventType, info);
    }

    @Override
    public boolean equals(Object o) {
      if (!super.equals(o)) {
        return false;
      }

      AbstractChainablePerfEvent other = (AbstractChainablePerfEvent) o;
      return other.perfEventId.equals(perfEventId) &&
          other.info.equals(info) &&
          other.perfEventType.equals(perfEventType);
    }
  }

  private static class StartedImpl extends AbstractChainablePerfEvent implements Started {
    private boolean isChainFinished = false;

    /**
     * @return whether creating new events off of this chain is allowed.
     */
    @JsonIgnore
    public boolean isChainFinished() {
      return isChainFinished;
    }

    /**
     * Called to indicate that the chain should not allow any further events.
     */
    public void markChainFinished() {
      isChainFinished = true;
    }

    @Override
    public BuckEvent createUpdateEvent(ImmutableMap<String, Object> info) {
      Preconditions.checkState(!isChainFinished());
      return new Updated(this, info);
    }

    @Override
    public BuckEvent createUpdateEvent(String k1, Object v1) {
      Preconditions.checkState(!isChainFinished());
      return createUpdateEvent(ImmutableMap.of(k1, v1));
    }

    @Override
    public BuckEvent createUpdateEvent(String k1, Object v1, String k2, Object v2) {
      Preconditions.checkState(!isChainFinished());
      return createUpdateEvent(ImmutableMap.of(k1, v1, k2, v2));
    }

    @Override
    public BuckEvent createFinishedEvent(ImmutableMap<String, Object> info) {
      Preconditions.checkState(!isChainFinished());
      return new Finished(this, info);
    }

    @Override
    public BuckEvent createFinishedEvent() {
      Preconditions.checkState(!isChainFinished());
      return createFinishedEvent(ImmutableMap.of());
    }

    @Override
    public BuckEvent createFinishedEvent(String k1, Object v1) {
      Preconditions.checkState(!isChainFinished());
      return createFinishedEvent(ImmutableMap.of(k1, v1));
    }

    @Override
    public BuckEvent createFinishedEvent(String k1, Object v1, String k2, Object v2) {
      Preconditions.checkState(!isChainFinished());
      return createFinishedEvent(ImmutableMap.of(k1, v1, k2, v2));
    }

    public StartedImpl(PerfEventId perfEventId, ImmutableMap<String, Object> info) {
      super(EventKey.unique(), perfEventId, Type.STARTED, info);
    }
  }

  private static class Updated extends AbstractChainablePerfEvent {

    public Updated(StartedImpl started, ImmutableMap<String, Object> updateInfo) {
      super(started.getEventKey(), started.getEventId(), Type.UPDATED, updateInfo);
    }
  }

  private static class Finished extends AbstractChainablePerfEvent {

    public Finished(StartedImpl started, ImmutableMap<String, Object> finishedInfo) {
      super(started.getEventKey(), started.getEventId(), Type.FINISHED, finishedInfo);
      started.markChainFinished();
    }
  }
}


text:
package org.apache.felix.ipojo.extender.internal.queue.pref;

import static org.mockito.Mockito.when;

import java.util.Hashtable;

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.osgi.framework.Bundle;

import junit.framework.TestCase;

/**
 * Checks the selection of the job processing preference from the bundle manifest.
 */
public class HeaderPreferenceSelectionTestCase extends TestCase {

    public static final String HEADER = "Header";

    @Mock
    private Bundle m_bundle;

    @Override
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    public void testMissingHeader() throws Exception {
        Hashtable<String, String> headers = new Hashtable<String, String>();
        when(m_bundle.getHeaders()).thenReturn(headers);
        HeaderPreferenceSelection selection = new HeaderPreferenceSelection(HEADER);
        assertEquals(Preference.DEFAULT, selection.select(m_bundle));
    }

    public void testUnrecognizedHeader() throws Exception {
        Hashtable<String, String> headers = new Hashtable<String, String>();
        headers.put(HEADER, "invalid");
        when(m_bundle.getHeaders()).thenReturn(headers);
        HeaderPreferenceSelection selection = new HeaderPreferenceSelection(HEADER);
        assertEquals(Preference.DEFAULT, selection.select(m_bundle));
    }

    public void testSyncHeader() throws Exception {
        Hashtable<String, String> headers = new Hashtable<String, String>();
        // We should ignore case
        headers.put(HEADER, "SyNc");
        when(m_bundle.getHeaders()).thenReturn(headers);
        HeaderPreferenceSelection selection = new HeaderPreferenceSelection(HEADER);
        assertEquals(Preference.SYNC, selection.select(m_bundle));
    }

    public void testAsyncHeader() throws Exception {
        Hashtable<String, String> headers = new Hashtable<String, String>();
        // We should ignore case
        headers.put(HEADER, "aSyNc");
        when(m_bundle.getHeaders()).thenReturn(headers);
        HeaderPreferenceSelection selection = new HeaderPreferenceSelection(HEADER);
        assertEquals(Preference.ASYNC, selection.select(m_bundle));
    }
}