text:
using views::ColumnSet;
using views::GridLayout;

namespace {

// Minimum width of the the bubble.
const int kMinBubbleWidth = 300;
// Minimum width of the the textfield.
const int kMinTextfieldWidth = 200;
// Size of the icon.
const int kIconSize = extension_misc::EXTENSION_ICON_MEDIUM;

ExtensionService* GetExtensionService(Profile* profile) {
  return extensions::ExtensionSystem::Get(profile)->extension_service();
}

}  // namespace

BookmarkAppBubbleView* BookmarkAppBubbleView::bookmark_app_bubble_ = NULL;

BookmarkAppBubbleView::~BookmarkAppBubbleView() {
}

// static
void BookmarkAppBubbleView::ShowBubble(views::View* anchor_view,
                                       Profile* profile,
                                       const WebApplicationInfo& web_app_info,
                                       const std::string& extension_id) {
  if (bookmark_app_bubble_ != NULL)
    return;

  bookmark_app_bubble_ = new BookmarkAppBubbleView(
      anchor_view, profile, web_app_info, extension_id);
  views::BubbleDelegateView::CreateBubble(bookmark_app_bubble_)->Show();
  // Select the entire title textfield contents when the bubble is first shown.
  bookmark_app_bubble_->title_tf_->SelectAll(true);
  bookmark_app_bubble_->SetArrowPaintType(views::BubbleBorder::PAINT_NONE);
}

BookmarkAppBubbleView::BookmarkAppBubbleView(
    views::View* anchor_view,
    Profile* profile,
    const WebApplicationInfo& web_app_info,
    const std::string& extension_id)
    : BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_RIGHT),
      profile_(profile),
      web_app_info_(web_app_info),
      extension_id_(extension_id),
      add_button_(NULL),
      cancel_button_(NULL),
      open_as_tab_checkbox_(NULL),
      title_tf_(NULL),
      remove_app_(true),
      app_icon_loader_(new extensions::AppIconLoaderImpl(profile,
                                                         kIconSize,
                                                         this)) {
  const SkColor background_color = GetNativeTheme()->GetSystemColor(
      ui::NativeTheme::kColorId_DialogBackground);
  set_arrow(views::BubbleBorder::TOP_CENTER);
  set_color(background_color);
  set_background(views::Background::CreateSolidBackground(background_color));
  set_margins(gfx::Insets(views::kPanelVertMargin, 0, 0, 0));
}

void BookmarkAppBubbleView::Init() {
  views::Label* title_label = new views::Label(
      l10n_util::GetStringUTF16(IDS_BOOKMARK_APP_BUBBLE_TITLE));
  ui::ResourceBundle* rb = &ui::ResourceBundle::GetSharedInstance();
  title_label->SetFontList(rb->GetFontList(ui::ResourceBundle::MediumFont));
  title_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);

  add_button_ =
      new views::LabelButton(this, l10n_util::GetStringUTF16(IDS_ADD));
  add_button_->SetStyle(views::Button::STYLE_BUTTON);
  add_button_->SetIsDefault(true);

  cancel_button_ =
      new views::LabelButton(this, l10n_util::GetStringUTF16(IDS_CANCEL));
  cancel_button_->SetStyle(views::Button::STYLE_BUTTON);

  GridLayout* layout = new GridLayout(this);
  SetLayoutManager(layout);

  // Column sets used in the layout of the bubble.
  enum ColumnSetID {
    TITLE_COLUMN_SET_ID,
    TITLE_TEXT_COLUMN_SET_ID,
    CONTENT_COLUMN_SET_ID
  };

  // The column layout used for the title and checkbox.
  ColumnSet* cs = layout->AddColumnSet(TITLE_COLUMN_SET_ID);
  cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
  cs->AddColumn(
      GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0);
  cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);

  // The column layout used for the icon and text box.
  cs = layout->AddColumnSet(TITLE_TEXT_COLUMN_SET_ID);
  cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
  cs->AddColumn(GridLayout::LEADING,
                GridLayout::CENTER,
                0,
                GridLayout::USE_PREF,
                0,
                0);
  cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
  cs->AddColumn(GridLayout::FILL,
                GridLayout::CENTER,
                1,
                GridLayout::USE_PREF,
                0,
                kMinTextfieldWidth);
  cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);

  // The column layout used for the row with buttons.
  cs = layout->AddColumnSet(CONTENT_COLUMN_SET_ID);
  cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);
  cs->AddColumn(
      GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0);
  cs->AddPaddingColumn(1, views::kUnrelatedControlHorizontalSpacing);
  cs->AddColumn(
      GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0);
  cs->AddPaddingColumn(0, views::kRelatedButtonHSpacing);
  cs->AddColumn(
      GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0);
  cs->AddPaddingColumn(0, views::kButtonHEdgeMarginNew);

  layout->StartRow(0, TITLE_COLUMN_SET_ID);
  layout->AddView(title_label);
  layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);

  const extensions::Extension* extension =
      extensions::ExtensionRegistry::Get(profile_)->GetExtensionById(
          extension_id_, extensions::ExtensionRegistry::EVERYTHING);

  layout->StartRow(0, TITLE_TEXT_COLUMN_SET_ID);
  icon_image_view_ = new views::ImageView();
  icon_image_view_->SetImageSize(gfx::Size(kIconSize, kIconSize));
  layout->AddView(icon_image_view_);
  app_icon_loader_->FetchImage(extension_id_);

  title_tf_ = new views::Textfield();
  title_tf_->SetText(extension ? base::UTF8ToUTF16(extension->name())
                               : web_app_info_.title);
  layout->AddView(title_tf_);
  layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);

  layout->StartRow(0, CONTENT_COLUMN_SET_ID);
  open_as_tab_checkbox_ = new views::Checkbox(
      l10n_util::GetStringUTF16(IDS_BOOKMARK_APP_BUBBLE_OPEN_AS_TAB));
  open_as_tab_checkbox_->SetChecked(
      profile_->GetPrefs()->GetInteger(
          extensions::pref_names::kBookmarkAppCreationLaunchType) ==
              extensions::LAUNCH_TYPE_REGULAR);
  layout->AddView(open_as_tab_checkbox_);
  layout->AddView(add_button_);
  layout->AddView(cancel_button_);
  layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);

  AddAccelerator(ui::Accelerator(ui::VKEY_RETURN, ui::EF_NONE));
}

views::View* BookmarkAppBubbleView::GetInitiallyFocusedView() {
  return title_tf_;
}

void BookmarkAppBubbleView::WindowClosing() {
  // We have to reset |bookmark_app_bubble_| here, not in our destructor,
  // because we'll be destroyed asynchronously and the shown state will be
  // checked before then.
  DCHECK_EQ(bookmark_app_bubble_, this);
  bookmark_app_bubble_ = NULL;

  if (remove_app_) {
    GetExtensionService(profile_)
        ->UninstallExtension(extension_id_,
                             extensions::UNINSTALL_REASON_INSTALL_CANCELED,
                             base::Bind(&base::DoNothing),
                             NULL);
  } else {
    ApplyEdits();
  }
}

bool BookmarkAppBubbleView::AcceleratorPressed(
    const ui::Accelerator& accelerator) {
  if (accelerator.key_code() == ui::VKEY_RETURN) {
    HandleButtonPressed(add_button_);
  }

  return BubbleDelegateView::AcceleratorPressed(accelerator);
}

gfx::Size BookmarkAppBubbleView::GetMinimumSize() const {
  gfx::Size size(views::BubbleDelegateView::GetPreferredSize());
  size.SetToMax(gfx::Size(kMinBubbleWidth, 0));
  return size;
}

void BookmarkAppBubbleView::ButtonPressed(views::Button* sender,
                                          const ui::Event& event) {
  HandleButtonPressed(sender);
}

void BookmarkAppBubbleView::SetAppImage(const std::string& id,
                                        const gfx::ImageSkia& image) {
  DCHECK_EQ(extension_id_, id);
  icon_image_view_->SetImage(image);
}

void BookmarkAppBubbleView::HandleButtonPressed(views::Button* sender) {
  // Unset |remove_app_| so we don't delete the bookmark after the window
  // closes.
  if (sender == add_button_)
    remove_app_ = false;

  GetWidget()->Close();
}

void BookmarkAppBubbleView::ApplyEdits() {
  // Set the launch type based on the checkbox.
  extensions::LaunchType launch_type = open_as_tab_checkbox_->checked()
      ? extensions::LAUNCH_TYPE_REGULAR
      : extensions::LAUNCH_TYPE_WINDOW;
  profile_->GetPrefs()->SetInteger(
          extensions::pref_names::kBookmarkAppCreationLaunchType, launch_type);
  extensions::SetLaunchType(GetExtensionService(profile_),
                            extension_id_,
                            launch_type);

  const extensions::Extension* extension =
      extensions::ExtensionRegistry::Get(profile_)->GetExtensionById(
          extension_id_, extensions::ExtensionRegistry::EVERYTHING);

  if (!extension)
    return;

  if (base::UTF8ToUTF16(extension->name()) != title_tf_->text()) {
    // Reinstall the app with an updated name.
    WebApplicationInfo install_info(web_app_info_);
    install_info.title = title_tf_->text();

    // This will asynchronously reload the extension, causing the Extension*
    // we have to be destroyed. The extension ID will stay the same so that is
    // used later on to highlight the app.
    extensions::CreateOrUpdateBookmarkApp(GetExtensionService(profile_),
                                          &install_info);
  }

  // As the extension could be destroyed after this point, set it to null to
  // prevent anyone trying to use it in future.
  extension = nullptr;

  // Show the newly installed app in the app launcher or chrome://apps. Don't
  // do this on ash, as the icon will have been added to the shelf.
  chrome::HostDesktopType desktop =
      chrome::GetHostDesktopTypeForNativeWindow(GetWidget()->GetNativeWindow());
  if (desktop == chrome::HOST_DESKTOP_TYPE_ASH)
    return;

  Profile* current_profile = profile_->GetOriginalProfile();
  if (IsAppLauncherEnabled()) {
    AppListService::Get(desktop)
        ->ShowForAppInstall(current_profile, extension_id_, false);
    return;
  }

  chrome::NavigateParams params(current_profile,
                                GURL(chrome::kChromeUIAppsURL),
                                ui::PAGE_TRANSITION_LINK);
  params.disposition = NEW_FOREGROUND_TAB;
  chrome::Navigate(&params);

  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_APP_INSTALLED_TO_NTP,
      content::Source<content::WebContents>(params.target_contents),
      content::Details<const std::string>(&extension_id_));
}


text:
ECHO Run the OSM Ion Regulation Activity classifier

PAUSE

python OSM_QSAR.py --classify osm --load ION_META --epoch 40 --train 0 --clean

redpajama_set_name: RedPajamaGithub


text:
# partial-loads-ok and undef-value-errors necessary to ignore
# spurious (and eminently ignorable) warnings from the ruby
# interpreter
VALGRIND_BASIC_OPTS = "--num-callers=50 --error-limit=no --partial-loads-ok=yes --undef-value-errors=no"

class NokogiriTestTask < Rake::TestTask
  def initialize *args
    super
    %w[ ext lib bin test ].each do |dir|
      self.libs << dir
    end
    self.test_files = FileList['test/**/test_*.rb'] +
      FileList['test/**/*_test.rb']
    self.verbose = "verbose"
    self.warning = true
  end
end

desc "run test suite under valgrind with basic ruby options"
NokogiriTestTask.new('test:valgrind').extend(Module.new {
  def ruby *args
    run_with_env "valgrind #{VALGRIND_BASIC_OPTS} #{RUBY} #{args.join(' ')} test/test_nokogiri.rb --verbose=verbose"
  end
})

desc "run test suite under valgrind with memory-fill ruby options"
NokogiriTestTask.new('test:valgrind_mem').extend(Module.new {
  def ruby *args
    run_with_env "valgrind #{VALGRIND_BASIC_OPTS} --freelist-vol=100000000 --malloc-fill=6D --free-fill=66 #{RUBY} #{args.join(' ')} test/test_nokogiri.rb --verbose=verbose"
  end
})

desc "run test suite under valgrind with memory-zero ruby options"
NokogiriTestTask.new('test:valgrind_mem0').extend(Module.new {
  def ruby *args
    run_with_env "valgrind #{VALGRIND_BASIC_OPTS} --freelist-vol=100000000 --malloc-fill=00 --free-fill=00 #{RUBY} #{args.join(' ')} test/test_nokogiri.rb --verbose=verbose"
  end
})

desc "run test suite under gdb"
NokogiriTestTask.new('test:gdb').extend(Module.new {
  def ruby *args
    run_with_env "gdb --args #{RUBY} #{args.join(' ')}"
  end
})

desc "test coverage"
NokogiriTestTask.new('test:coverage').extend(Module.new {
  def ruby *args
    rm_rf "coverage"
    run_with_env "rcov -x Library -I lib:ext:test #{args.join(' ')}"
  end
})

desc "run test suite with verbose output"
NokogiriTestTask.new('test:verbose').extend(Module.new {
  def ruby *args
    run_with_env "#{RUBY} #{args.join(' ')} test/test_nokogiri.rb --verbose=verbose"
  end
})

def run_with_env(cmd)
  cmd = "LD_LIBRARY_PATH='#{ENV['LD_LIBRARY_PATH']}' #{cmd}"
  puts "=> #{cmd}"
  system cmd
end

namespace :test do
  desc "run test suite with aggressive GC"
  task :gc => :build do
    ENV['NOKOGIRI_GC'] = "true"
    Rake::Task["test"].invoke
  end

  desc "find call-seq in the rdoc"
  task :rdoc_call_seq => 'docs' do
    Dir['doc/**/*.html'].each { |docfile|
      next if docfile =~ /\.src/
      puts "FAIL: #{docfile}" if File.read(docfile) =~ /call-seq/
    }
  end

  desc "find all undocumented things"
  task :rdoc => 'docs' do
    base = File.expand_path(File.join(File.dirname(__FILE__), '..', 'doc'))
    require 'test/unit'
    test = Class.new(Test::Unit::TestCase)
    Dir["#{base}/**/*.html"].each { |docfile|
      test.class_eval(<<-eotest)
        def test_#{docfile.sub("#{base}/", '').gsub(/[\/\.-]/, '_')}
          assert_no_match(
            /Not documented/,
            File.read('#{docfile}'),
            '#{docfile} has undocumented things'
          )
        end
      eotest
    }
  end

  desc "Test against multiple versions of libxml2 (MULTIXML2_DIR=directory)"
  task :multixml2 do
    MULTI_XML = File.join(ENV['HOME'], '.multixml2')
    unless File.exists?(MULTI_XML)
      %w{ versions install build }.each { |x|
        FileUtils.mkdir_p(File.join(MULTI_XML, x))
      }
      Dir.chdir File.join(MULTI_XML, 'versions') do
        require 'net/ftp'
        ftp = Net::FTP.new('xmlsoft.org')
        ftp.login('anonymous', 'anonymous')
        ftp.chdir('libxml2')
        ftp.list('libxml2-2.*.tar.gz').each do |x|
          file = x[/[^\s]*$/]
          puts "Downloading #{file}"
          ftp.getbinaryfile(file)
        end
      end
    end

    # Build any libxml2 versions in $HOME/.multixml2/versions that
    # haven't been built yet
    Dir[File.join(MULTI_XML, 'versions','*.tar.gz')].each do |f|
      filename = File.basename(f, '.tar.gz')

      install_dir = File.join(MULTI_XML, 'install', filename)
      next if File.exists?(install_dir)

      Dir.chdir File.join(MULTI_XML, 'versions') do
        system "tar zxvf #{f} -C #{File.join(MULTI_XML, 'build')}"
      end

      Dir.chdir File.join(MULTI_XML, 'build', filename) do
        system "./configure --prefix=#{install_dir}"
        system "make && make install"
      end
    end

    test_results = {}
    libxslt = Dir[File.join(MULTI_XML, 'install', 'libxslt*')].first

    directories = ENV['MULTIXML2_DIR'] ? [ENV['MULTIXML2_DIR']] : Dir[File.join(MULTI_XML, 'install', '*')]
    directories.sort.reverse.each do |xml2_version|
      next unless xml2_version =~ /libxml2/
      extopts = "--with-xml2-include=#{xml2_version}/include/libxml2 --with-xml2-lib=#{xml2_version}/lib --with-xslt-dir=#{libxslt}"
      cmd = "#{$0} clean test EXTOPTS='#{extopts}' LD_LIBRARY_PATH='#{xml2_version}/lib'"

      version = File.basename(xml2_version)
      result = system(cmd)
      test_results[version] = {
        :result => result,
        :cmd    => cmd
      }
    end
    test_results.sort_by { |k,v| k }.each do |k,v|
      passed = v[:result]
      puts "#{k}: #{passed ? 'PASS' : 'FAIL'}"
      puts "repro: #{v[:cmd]}" unless passed
    end
  end
end


text:
module Pione
  module Command
    # `PioneLogFormat` is a command that converts PIONE raw log into XES or
    # other formats.
    class PioneLogFormat < BasicCommand
      #
      # basic informations
      #

      define(:name, "format")
      define(:desc, "Convert PIONE raw log into XES or other formats")

      #
      # arguments
      #

      argument PioneLogArgument.log_location

      #
      # options
      #

      option_pre(:prepare_model) do |item|
        item.process do
          model[:trace_types] = []
          model[:agent_types] = []
        end
      end

      option CommonOption.color
      option CommonOption.debug

      option(:trace_types) do |item|
        item.type = :string
        item.long = "--trace-type"
        item.arg  = "NAME"
        item.desc = 'Output only the trace type: "agent", "rule", or "task"'

        item.process {|val| model[:trace_types] << val}
      end

      option(:agent_types) do |item|
        item.type = :string
        item.arg  = "NAME"
        item.long = "--agent-type"
        item.desc = 'Output only the agent type: "task_worker", "input_generator", ...'

        item.process {|val| model[:agent_types] << val}
      end

      option(:format) do |item|
        item.type  = :symbol_downcase
        item.range = [:xes, :json, :xml]
        item.long  = "--format"
        item.arg   = "NAME"
        item.desc  = 'Set format type'
        item.init  = :xes
      end

      option(:log_id) do |item|
        item.type = :string
        item.long = "--log-id"
        item.arg  = "ID"
        item.desc = "Target log ID"
      end

      #
      # command lifecycle: setup phase
      #

      phase(:setup) do |seq|
        seq << :trace_filters
        seq << :formatter
        seq << :raw_log
      end

      setup(:trace_filters) do |item|
        item.desc = "Setup trace filters"

        item.assign(:trace_filters) do
          Array.new
        end

        # agent filters
        item.process do
          test(model[:trace_types].include?("agent"))

          if model[:agent_types].empty?
            model[:trace_filters] << Proc.new do |trace|
              trace.attributes.include?(XES.string("pione:traceType", "agent_activity"))
            end
          else
            model[:trace_filters] << Proc.new do |trace|
              trace.attributes.include?(XES.string("pione:traceType", "agent_activity")) and
                model[:agent_types].include?(trace.events.first.org_resource)
            end
          end
        end

        # rule filters
        item.process do
          test(model[:trace_types].include?("rule"))

          model[:trace_filters] << Proc.new do |trace|
            trace.attributes.include?(XES.string("pione:traceType", "rule_process"))
          end
        end

        # task filters
        item.process do
          test(model[:trace_types].include?("task"))

          model[:trace_filters] << Proc.new do |trace|
            trace.attributes.include?(XES.string("pione:traceType", "task_process"))
          end
        end
      end

      setup(:formatter) do |item|
        item.desc = "Setup formatter"

        item.assign(:formatter) do
          if Log::ProcessLog.known?(model[:format])
            Log::ProcessLog[model[:format]]
          else
            cmd.abort("Unknown format: %s" % model[:format])
          end
        end
      end

      setup(:raw_log) do |item|
        item.desc = "Read raw log table"

        item.assign(:raw_log_table) do
          model[:formatter].read(model[:log_location])
        end

        item.assign(:log_id) do
          test(not(model[:log_id]))
          model[:raw_log_table].keys.sort.last
        end
      end

      #
      # command lifecycle: execution phase
      #

      phase(:execution) do |item|
        item << :format_log
      end

      execution(:format_log) do |item|
        item.desc = "Format log file from the event log"

        item.process do
          puts(model[:raw_log_table][model[:log_id]].format(model[:trace_filters]))
        end
      end
    end

    PioneLog.define_subcommand("format", PioneLogFormat)
  end
end


text:
package gudusoft.gsqlparser.sql2xml.model;

import org.simpleframework.xml.Element;

public class with_or_without_data
{

	@Element(required = false)
	private without_data without_data;

	@Element(required = false)
	private with_data with_data;

	public without_data getWithout_data( )
	{
		return without_data;
	}

	public void setWithout_data( without_data without_data )
	{
		this.without_data = without_data;
	}

	public with_data getWith_data( )
	{
		return with_data;
	}

	public void setWith_data( with_data with_data )
	{
		this.with_data = with_data;
	}

}


text:
package com.googlecode.bpmn_simulator.bpmn.model.choreography.activities;

public class ChoreographyTask
		extends AbstractChoreographyActivity {

	public ChoreographyTask(final String id, final String name) {
		super(id, name);
	}

}


text:
//         ATMEL Microcontroller Software Support  -  Colorado Springs, CO -
// ----------------------------------------------------------------------------
// DISCLAIMER:  THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
// DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ----------------------------------------------------------------------------

/** \file
 *  \brief  Declarations and Prototypes for AES132 Helper Functions
 *  \author Tuwuh Sarwoprasojo, Atmel Bali Team
 *  \date   June 12, 2013
 */

/** \mainpage AES132 Helper Functions
 * The AES132 Helper Functions provides implementation of host-side functions for AES132.
 * This includes aes132crypt_* functions which perform AES-CCM and nonce calculation.
 *
 * The AES132 nonce is implemented as a structure aes132h_nonce_s.
 * The structure member "value" contains concatenation of 12-byte "Nonce" and 1-byte "MacCount". MacCount can be accessed in value[12].
 * The value of MacCount is reset to 0 by nonce calculation function upon success. MacCount is incremented prior to any computation performed.
 * Nonce validity is stored in "valid" structure member. A TRUE indicates that the nonce is valid, a FALSE indicates that it is invalid.
 * "valid" is set to TRUE by nonce calculation function upon success.
 * After 255 calculations (MacCount has reached maximum value), "valid" is set to FALSE by any function using it.
 *
 * ManufacturingID is defined as a AES132_MANUFACTURING_ID macro in the header file.
 * User must set this macro definition according to the content of ManufacturingID register in the particular ATAES132 configuration memory (address 0xF02B-0xF02C, MSByte is in 0xF02B).
 *
 * There are 6 public functions:
 * -# Nonce generation, aes132h_nonce()
 * -# CountValue conversion (decode 4-byte CountValue to integer counts), aes132h_decode_count_value()
 * -# Counter personalization (encode integer counts to 8-byte Counter field), aes132h_encode_counter_field()
 * -# FirstBlock and SecondBlock builder, aes132h_build_auth_block()
 * -# MAC computation and data encryption, aes132h_mac_compute_encrypt()
 * -# MAC checking and data decryption, aes132h_mac_check_decrypt()
 *
 * Please refer to each function documentation for details.
 */

#ifndef AES132_HELPER_H_
#define AES132_HELPER_H_

#include <stdint.h>
#include "utility.h"
//-------------------
// Macro definitions
//-------------------
#ifndef TRUE
	#define TRUE (1==1)
#endif

#ifndef FALSE
	#define FALSE (0==1)
#endif

#ifndef AES132_FUNCTION_RETCODE_BAD_PARAM
	#define AES132_FUNCTION_RETCODE_BAD_PARAM      ((uint8_t) (0xE2))
#endif

#ifndef AES132_MANUFACTURING_ID
	#define AES132_MANUFACTURING_ID                (0x00EE)
#endif

#ifndef AES132_COUNTER_MAX
	#define AES132_COUNTER_MAX                     (2097151)
#endif

//! Additional macro definitions for use with aes132 library
// --- Address ---
// User memory
#define AES132_USER_ZONE_ADDR(n)      ((uint16_t) (0x0000 + ((n) << 8)))

// Command memory
//   has been defined in aes132.h

// Configuration memory
#define AES132_SERIAL_NUM_ADDR        ((uint16_t) 0xF000)
#define AES132_MANUFACTURING_ID_ADDR  ((uint16_t) 0xF02B)
#define AES132_LOCK_KEYS_ADDR         ((uint16_t) 0xF020)
#define AES132_LOCK_SMALL_ADDR        ((uint16_t) 0xF021)
#define AES132_LOCK_CONFIG_ADDR       ((uint16_t) 0xF022)

#define AES132_KEY_CONFIG_ADDR(n)     ((uint16_t) (0xF080 + ((n) << 2)))
#define AES132_ZONE_CONFIG_ADDR(n)    ((uint16_t) (0xF0C0 + ((n) << 2)))
#define AES132_COUNTER_CONFIG_ADDR(n) ((uint16_t) (0xF060 + ((n) << 1)))
#define AES132_COUNTER_ADDR(n)        ((uint16_t) (0xF100 + ((n) << 3)))

#define AES132_SMALL_ZONE_ADDR        ((uint16_t) (0xF1E0))

// Key memory
#define AES132_KEY_ADDR(n)            ((uint16_t) (0xF200 + ((n) << 4)))

// --- Length ---
#define AES132_USER_ZONE_LENGTH          (256)
#define AES132_SERIAL_NUM_LENGTH         (8)
#define AES132_MANUFACTURING_ID_LENGTH   (2)
#define AES132_KEY_CONFIG_LENGTH         (4)
#define AES132_ZONE_CONFIG_LENGTH        (4)
#define AES132_COUNTER_CONFIG_LENGTH     (2)
#define AES132_COUNTER_LENGTH            (8)
#define AES132_KEY_LENGTH                (16)

#define AES132_MAC_LENGTH                (16)

// --- Bit positions ---
// KeyConfig Byte #0
#define AES132_KEY_CONFIG_EXTERNAL_CRYPTO     (1 << 0)
#define AES132_KEY_CONFIG_INBOUND_AUTH        (1 << 1)
#define AES132_KEY_CONFIG_RANDOM_NONCE        (1 << 2)
#define AES132_KEY_CONFIG_LEGACY_OK           (1 << 3)
#define AES132_KEY_CONFIG_AUTH_KEY            (1 << 4)
#define AES132_KEY_CONFIG_CHILD               (1 << 5)
#define AES132_KEY_CONFIG_PARENT              (1 << 6)
#define AES132_KEY_CONFIG_CHANGE_KEYS         (1 << 7)

// KeyConfig Byte #1
#define AES132_KEY_CONFIG_COUNTER_LIMIT       (1 << 0)
#define AES132_KEY_CONFIG_CHILD_MAC           (1 << 1)
#define AES132_KEY_CONFIG_AUTH_OUT            (1 << 2)
#define AES132_KEY_CONFIG_AUTH_OUT_HOLD       (1 << 3)
#define AES132_KEY_CONFIG_IMPORT_OK           (1 << 4)
#define AES132_KEY_CONFIG_EXPORT_AUTH         (1 << 5)
#define AES132_KEY_CONFIG_TRANSFER_OK         (1 << 6)
#define AES132_KEY_CONFIG_AUTH_COMPUTE        (1 << 7)

// CounterConfig Byte #0
#define AES132_COUNTER_CONFIG_INCREMENT_OK    (1 << 0)
#define AES132_COUNTER_CONFIG_REQUIRE_MAC     (1 << 1)

// ZoneConfig Byte #0
#define AES132_ZONE_CONFIG_AUTH_READ          (1 << 0)
#define AES132_ZONE_CONFIG_AUTH_WRITE         (1 << 1)
#define AES132_ZONE_CONFIG_ENC_READ           (1 << 2)
#define AES132_ZONE_CONFIG_ENC_WRITE          (1 << 3)
#define AES132_ZONE_CONFIG_WRITE_MODE_4       (1 << 4)
#define AES132_ZONE_CONFIG_WRITE_MODE_5       (1 << 5)
#define AES132_ZONE_CONFIG_USE_SERIAL         (1 << 6)
#define AES132_ZONE_CONFIG_USE_SMALL          (1 << 7)
// ZoneConfig Byte #2
#define AES132_ZONE_CONFIG_VOLATILE_TRANSFER_OK          (1 << 0)
// VolUsage Byte #0
#define AES132_VOL_USAGE_AUTH_OK              (1 << 0)
#define AES132_VOL_USAGE_ENCRYPT_OK_1         (1 << 1)
#define AES132_VOL_USAGE_ENCRYPT_OK_2         (1 << 2)
#define AES132_VOL_USAGE_DECRYPT_OK           (1 << 3)
#define AES132_VOL_USAGE_RANDOM_NONCE         (1 << 4)
#define AES132_VOL_USAGE_AUTH_COMPUTE         (1 << 5)
#define AES132_VOL_USAGE_LEGACY_OK            (1 << 6)
#define AES132_VOL_USAGE_EXPORT_OK            (1 << 7)

// VolUsage Byte #1
#define AES132_VOL_USAGE_WRITE_COMPUTE        (1 << 0)
#define AES132_VOL_USAGE_DEC_READ             (1 << 1)

// AuthUsage
#define AES132_AUTH_USAGE_READ_OK             (1 << 0)
#define AES132_AUTH_USAGE_WRITE_OK            (1 << 1)
#define AES132_AUTH_USAGE_KEY_USE             (1 << 2)

// MacFlag
#define AES132_MAC_FLAG_RANDOM                (1 << 0)
#define AES132_MAC_FLAG_INPUT                 (1 << 1)

// Info Register
#define AES132_INFO_MACCOUNT				0x0000
#define AES132_INFO_AUTH_STATUS				0x0005
#define AES132_INFO_DEVICENUMBER			0x0006
#define AES132_INFO_CHIPSTATE				0x000C

// Locks
#define AES132_LOCK_SMALLZONE	(0x00)
#define AES132_LOCK_KEYMEMORY	(0x01)
#define AES132_LOCK_CONFIG		(0x02)
#define AES132_LOCK_ZONECONFIG	(0x03)

//----------------------
// Structures for nonce
//----------------------
/** \struct aes132h_nonce_s
 *  \brief Implementation of AES132 nonce.
 *  \var aes132h_nonce_s::value
 *       \brief 13-byte array, concatenation of 12-byte "Nonce" and 1-byte "MacCount".
 *              MacCount can be accessed in value[12].
 *  \var aes132h_nonce_s::valid
 *       \brief 1-byte flag, indicating nonce validity. Possible value: TRUE or FALSE.
 *  \var aes132h_nonce_s::random
 *       \brief 1-byte flag, indicating whether the nonce is generated from random number.
 *              Possible value: TRUE or FALSE.
 */
struct aes132h_nonce_s {
	uint8_t value[13];
	uint8_t valid;
	uint8_t random;
};

//----------------------------------------
// Structures for input/output parameters
//----------------------------------------
/** \struct aes132crypt_in_out
 *  \brief Input/output parameters for function aes132crypt_generate_encrypt() and aes132crypt_decrypt_verify().
 *  \var aes132crypt_in_out::nonce
 *       \brief Pointer to 13-byte nonce for AES-CCM. For AES132, this is 12-byte Nonce concatenated with 1-byte MacCount.
 *  \var aes132crypt_in_out::associated_data
 *       \brief Pointer to associated data for AES-CCM calculation. For AES132, this is used in all commands. In the AES132 datasheet this is described as "authenticate-only data".
 *  \var aes132crypt_in_out::alen_bytes
 *       \brief Length of associated data, in bytes. For AES132, depending on mode used in the command, this can be 16 or 32.
 *  \var aes132crypt_in_out::key
 *       \brief Pointer to 16-byte key used in AES cipher.
 *  \var aes132crypt_in_out::payload
 *       \brief Pointer to payload for AES-CCM calculation. For AES132, this is used in commands requiring encryption. In the AES132 datasheet this is described as "cleartext data". It can be set to NULL if not used (plen_bytes = 0).
 *              This is input for aes132crypt_generate_encrypt(), and output for aes132crypt_decrypt_verify()
 *  \var aes132crypt_in_out::plen_bytes
 *       \brief Length of payload, in bytes. For AES132, depending on the command, this can be between 0 to 32.
 *  \var aes132crypt_in_out::auth_value
 *       \brief Pointer to 16-byte authentication value. In AES132 datasheet this is described as "input integrity MAC".
 *              This is output for aes132crypt_generate_encrypt(), and input for aes132crypt_decrypt_verify()
 *  \var aes132crypt_in_out::ciphertext
 *       \brief Pointer to ciphertext output. For AES132, this can be 16 or 32 bytes. Caller must provide enough space.
 *              This is output for aes132crypt_generate_encrypt(), and input for aes132crypt_decrypt_verify()
 */
struct aes132crypt_in_out {
	uint8_t *nonce;
	uint8_t *associated_data;
	uint8_t alen_bytes;
	uint8_t *key;
	uint8_t *payload;
	uint8_t plen_bytes;
	uint8_t *auth_value;
	uint8_t *ciphertext;
};

/** \struct aes132crypt_ctr_block_in_out
 *  \brief Input/output parameters for function aes132crypt_generate_encrypt().
 *  \var aes132crypt_ctr_block_in_out::auth_value_in
 *       \brief Pointer to 16-byte input authentication value (MAC).
 *  \var aes132crypt_ctr_block_in_out::data_in
 *       \brief Pointer to input data to be encrypted/decrypted.
 *  \var aes132crypt_ctr_block_in_out::plen_bytes
 *       \brief Length of the data (payload), in bytes.
 *  \var aes132crypt_ctr_block_in_out::nonce
 *       \brief Pointer to 13-byte nonce (called N in NIST Special Publication 800-38C).
 *  \var aes132crypt_ctr_block_in_out::key
 *       \brief Pointer to 16-byte key (called K in NIST Special Publication 800-38C).
 *  \var aes132crypt_ctr_block_in_out::auth_value_out
 *       \brief Pointer to 16-byte output authentication value (MAC).
 *  \var aes132crypt_ctr_block_in_out::data_out
 *       \brief Pointer to encrypted/decrypted data.
 */
struct aes132crypt_ctr_block_in_out {
	uint8_t *auth_value_in;
	uint8_t *data_in;
	uint8_t plen_bytes;
	uint8_t *nonce;
	uint8_t *key;
	uint8_t *auth_value_out;
	uint8_t *data_out;
};

/** \struct aes132crypt_nonce_in_out
 *  \brief Input/output parameters for function aes132crypt_nonce().
 *  \var aes132crypt_nonce_in_out::data_in
 *       \brief Pointer to 16-byte input message to cipher, in datasheet stated as block A.
 *  \var aes132crypt_nonce_in_out::key"
 *       \brief Pointer to 16-byte key, in datasheet stated as block B.
 *  \var aes132crypt_nonce_in_out::data_out"
 *       \brief Pointer to 16-byte output.
 */
struct aes132crypt_nonce_in_out {
	uint8_t *data_in;
	uint8_t *key;
	uint8_t *data_out;
};

/** \struct aes132h_nonce_in_out
 *  \brief Input/output parameters for function aes132h_nonce().
 *  \var aes132h_nonce_in_out::mode
 *       \brief [in]  8-bit integer, Mode argument used in ATAES132 Nonce command.
 *                    If Bit 0 = 1b, generates a random nonce based on in_seed and random,
 *                    if bit 0 = 0b, stores in_seed as the nonce.
 *  \var aes132h_nonce_in_out::in_seed
 *       \brief [in]  Pointer to 12-byte input seed chosen by application.
 *  \var aes132h_nonce_in_out::random
 *       \brief [in]  Pointer to 16-byte random number generated from the device (if used).
 *  \var aes132h_nonce_in_out::nonce
 *       \brief [out] Pointer to aes132h_nonce_s struct, as output for the resulting nonce.
 */
struct aes132h_nonce_in_out {
	uint8_t mode;
	uint8_t *in_seed;
	uint8_t *random;
	struct aes132h_nonce_s *nonce;
};

/** \struct aes132h_build_auth_block_in_out
 *  \brief Input/output parameters for function aes132h_build_auth_block().
 *  \var aes132h_build_auth_block_in_out::host_opcode
 *       \brief [in]  8-bit integer host Opcode to send the FirstBlock/SecondBlock to (e.g. AuthCompute, KeyExport).
 *  \var aes132h_build_auth_block_in_out::opcode
 *       \brief [in]  8-bit integer Opcode argument to be assembled into FirstBlock (e.g. Auth, KeyLoad).
 *  \var aes132h_build_auth_block_in_out::mode
 *       \brief [in]  8-bit integer Mode argument to be assembled into FirstBlock.
 *  \var aes132h_build_auth_block_in_out::param1
 *       \brief [in]  16-bit integer Param1 argument to be assembled into FirstBlock.
 *  \var aes132h_build_auth_block_in_out::param2
 *       \brief [in]  16-bit integer Param2 argument to be assembled into FirstBlock.
 *  \var aes132h_build_auth_block_in_out::count_value
 *       \brief [in]  Pointer to 4-byte CountValue to be assembled into FirstBlock. Only used for Counter opcode.
 *  \var aes132h_build_auth_block_in_out::usage_counter
 *       \brief [in]  Pointer to usage counter value to be assembled into SecondBlock, if specified by mode parameter.
 *  \var aes132h_build_auth_block_in_out::serial_num
 *       \brief [in]  Pointer to SerialNum[0:7], to be assembled into SecondBlock, if specified by mode parameter.
 *  \var aes132h_build_auth_block_in_out::small_zone
 *       \brief [in]  Pointer to SmallZone[0:3], to be assembled into SecondBlock, if specified by mode parameter.
 *  \var aes132h_build_auth_block_in_out::random
 *       \brief [in]  8-bit integer for Random flag. 0x01 if using random nonce, 0x00 if using inbound nonce.
 *  \var aes132h_build_auth_block_in_out::first_block
 *       \brief [out] Pointer to 6- or 11-byte FirstBlock output.
 *  \var aes132h_build_auth_block_in_out::second_block
 *       \brief [out] Pointer to 16-byte SecondBlock output, if used.
 */
struct aes132h_build_auth_block_in_out {
	uint8_t host_opcode;
	uint8_t opcode;
	uint8_t mode;
	uint16_t param1;
	uint16_t param2;
	uint8_t *count_value;
	uint8_t *usage_counter;
	uint8_t *serial_num;
	uint8_t *small_zone;
	uint8_t random;
	uint8_t *first_block;
	uint8_t *second_block;
};

/** \struct aes132h_in_out
 *  \brief Input/output parameters for function aes132h_mac_compute_encrypt() and aes132h_mac_check_decrypt().
 *  \var aes132h_in_out::opcode
 *       \brief [in]     8-bit integer Opcode argument used in ATAES132 command.
 *  \var aes132h_in_out::mode
 *       \brief [in]     8-bit integer Mode argument used in ATAES132 command.
 *  \var aes132h_in_out::param1
 *       \brief [in]     16-bit integer Param1 argument used in ATAES132 command.
 *  \var aes132h_in_out::param2
 *       \brief [in]     16-bit integer Param2 argument used in ATAES132 command.
 *                       For EncWrite and Decrypt, this is the Count field, representing number of bytes to encrypt.
 *  \var aes132h_in_out::count_value
 *       \brief [in]     Pointer to 4-byte CountValue. Only used for Counter opcode.
 *  \var aes132h_in_out::usage_counter
 *       \brief [in]     Pointer to usage counter value to be used in second authenticate-only block.
 *  \var aes132h_in_out::serial_num
 *       \brief [in]     Pointer to SerialNum[0:7], to be used in second authenticate-only block.
 *  \var aes132h_in_out::small_zone
 *       \brief [in]     Pointer to SmallZone[0:3], to be used in second authenticate-only block.
 *  \var aes132h_in_out::key
 *       \brief [in]     Pointer to 16-byte key used to calculate the MAC.
 *  \var aes132h_in_out::nonce
 *       \brief [in,out] Pointer to aes132h_nonce_s structure.
 *  \var aes132h_in_out::in_mac
 *       \brief [in]     Pointer to 16-byte input MAC to be checked by the function.
 *  \var aes132h_in_out::out_mac
 *       \brief [out]    Pointer to 16-byte output MAC generated by the function.
 *  \var aes132h_in_out::in_data
 *       \brief [in]     Pointer to input data to be encrypted, or decrypted.
 *                       Not used for Auth and Counter command.
 *  \var aes132h_in_out::out_data
 *       \brief [out]    Pointer to 16- or 32-byte encrypted output data; or pointer to decrypted output data.
 *                       Not used for Auth and Counter command.
 */
struct aes132h_in_out {
	uint8_t opcode;
	uint8_t mode;
	uint16_t param1;
	uint16_t param2;
	uint8_t *count_value;
	uint8_t *usage_counter;
	uint8_t *serial_num;
	uint8_t *small_zone;
	uint8_t *key;
	struct aes132h_nonce_s *nonce;
	uint8_t *in_mac;
	uint8_t *out_mac;
	uint8_t *in_data;
	uint8_t *out_data;
};

 struct aes132a_details {
	 uint8_t serial_number[8];
	 uint8_t lot_history[8];
	 uint8_t enc_read_size;
	 uint8_t enc_write_size;
	 uint8_t ee_page_size;
	 uint8_t device_number;
	 uint8_t lock_keys;
	 uint8_t lock_small;
	 uint8_t lock_config;
	 uint8_t manufacturing_id[2];
	 uint8_t i2c_address;
	 uint8_t chip_config;
	 uint8_t small_zone[4];
 };

//---------------------
// Function prototypes
//---------------------
uint8_t aes132h_nonce(struct aes132h_nonce_in_out *param);
uint8_t aes132h_decode_count_value(uint8_t *count_value, uint32_t *count_integer);
uint8_t aes132h_encode_counter_field(uint32_t count_integer, uint8_t *counter_field);
uint8_t aes132h_build_auth_block(struct aes132h_build_auth_block_in_out *param);
uint8_t aes132h_mac_compute_encrypt(struct aes132h_in_out *param);
uint8_t aes132h_mac_check_decrypt(struct aes132h_in_out *param);

void aes_print_buffer(uint8_t *buff, uint8_t size);
void aes_print_rc(int ret_value);
void aes132_print_zone_addresses(void);

#endif //AES132_HELPER_H_


text:
HashVTT
========

### HashVTT is a virtual tabletop for playing tabletop RPG's. It's called HashVTT because it was created to play RPG's with [Hashbang](http://hashbang.sh/#!) users.

### Current Version - 0.0.1

## Requirements for server
* Lua 5.2
* LuaRocks 2.2.0
* LuaSocket 2.0.2 (luarocks install luasocket)
* Copas 1.1.1 (luarocks install copas)

## Requirements for client
[LÖVE](https://love2d.org/)

## Communication
```
irc.hashbang.sh/6697 #!, #!social, #!rpg
```

## Contributing
1. Join the "#!rpg" channel on the Hashbang network, mentioned in Communication
2. Mention what you want to do, and wait for a response
3. Begin hacking, then submit a [pull request](https://help.github.com/articles/using-pull-requests/)

## Running the server
```
cd server/
lua server.lua port
```

## Running the client
```
cd client/
love . ip port username
```

### What about built packages?
There are none yet.

#### Note: LÖVE runs on Windows, Mac, and Linux, which means that the client will forever be supported by all of them.

## License
See LICENSE


text:
require 'test_helper'

describe OrderDetail::TransferDomain do
  describe :as_json do
    subject { order_detail.as_json }

    let(:order_detail) { build :transfer_domain_order_detail }

    let(:expected_json) {
      {
        type: 'transfer_domain',
        price: 15.00,
        domain: 'domain.ph',
        registrant_handle: 'contact',
        object: nil
      }
    }

    specify { subject.must_equal expected_json }
  end

  describe :complete! do
    subject { create :transfer_domain_order_detail }

    let(:domain) { create :domain }
    let(:saved_domain) { Domain.named(domain.full_name) }
    let(:latest_ledger_entry) { subject.order.partner.ledgers.last }

    before do
      domain

      subject.complete!
    end

    specify { subject.registrant_handle.wont_be_empty }
    specify { subject.complete?.must_equal true }
    specify { subject.product.must_equal saved_domain.product }

    specify { saved_domain.partner.must_equal subject.order.partner }

    specify { latest_ledger_entry.activity_type.must_equal 'use' }
    specify { latest_ledger_entry.amount.must_equal -15.00.money }
  end

  describe :build do
    subject { OrderDetail::TransferDomain.build params, nil }

    let(:params) {
      {
      }
    }

    specify { subject.period.must_equal 0 }
  end
end


text:
module Stamp
  class Translator

    # Full list of time zone abbreviations from
    # http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations
    TIME_ZONE_ABBREVIATIONS = %w{
        ACDT ACST ACT ADT AEDT AEST AFT AKDT AKST AMST AMT ART AST AWDT AWST AZOST AZT
        BDT BIOT BIT BOT BRT BST BTTCAT CCT CDT CEDT CEST CET CHADT CHAST CHOT ChST CHUT
        CIST CIT CKT CLST CLT COST COT CST CT CVT CWST CXT DAVT DDUT DFT EASST EAST EAT
        ECT EDT EEDT EEST EET EGST EGT EIT EST FET FJT FKST FKT FNT GALT GAMT GET GFT
        GILT GIT GMT GST GYT HADT HAEC HAST HKT HMT HOVT HST ICT IDT IOT IRDT IRKT IRST
        IST JST KGT KOST KRAT KST LHST LINT MAGT MART MAWT MDT MET MEST MHT MIST MIT MMT
        MSK MST MUT MVT MYT NCT NDT NFT NPT NST NT NUT NZDT NZST OMST ORAT PDT PET PETT
        PGT PHOT PHT PKT PMDT PMST PONT PST RET ROTT SAKT SAMT SAST SBT SCT SGT SLT SRT
        SST SYOT TAHT THA TFT TJT TKT TLT TMT TOT TVT UCT ULAT UTC UYST UYT UZT VET VLAT
        VOLT VOST VUT WAKT WAST WAT WEDT WEST WET WST YAKT YEKT
      }

    TIMEZONE_REGEXP        = /^(#{TIME_ZONE_ABBREVIATIONS.join('|')})$/
    MONTHNAMES_REGEXP      = /^(#{Date::MONTHNAMES.compact.join('|')})$/i
    ABBR_MONTHNAMES_REGEXP = /^(#{Date::ABBR_MONTHNAMES.compact.join('|')})$/i
    DAYNAMES_REGEXP        = /^(#{Date::DAYNAMES.join('|')})$/i
    ABBR_DAYNAMES_REGEXP   = /^(#{Date::ABBR_DAYNAMES.join('|')})$/i

    ONE_DIGIT_REGEXP       = /^\d{1}$/
    TWO_DIGIT_REGEXP       = /^\d{2}$/
    FOUR_DIGIT_REGEXP      = /^\d{4}$/

    TIME_REGEXP            = /(\d{1,2})(:)(\d{2})(\s*)(:)?(\d{2})?(\s*)?([ap]m)?/i

    MERIDIAN_LOWER_REGEXP  = /^(a|p)m$/
    MERIDIAN_UPPER_REGEXP  = /^(A|P)M$/

    ORDINAL_DAY_REGEXP     = /^(\d{1,2})(st|nd|rd|th)$/

    # Disambiguate based on value
    OBVIOUS_YEARS          = 60..99
    OBVIOUS_MONTHS         = 12
    OBVIOUS_DAYS           = 13..31
    OBVIOUS_24_HOUR        = 13..23

    TWO_DIGIT_YEAR_EMITTER  = Emitters::TwoDigit.new(:year) { |year| year % 100 }
    TWO_DIGIT_MONTH_EMITTER = Emitters::TwoDigit.new(:month)
    TWO_DIGIT_DAY_EMITTER   = Emitters::TwoDigit.new(:day)
    HOUR_TO_12_HOUR         = lambda { |h| ((h - 1) % 12) + 1 }

    OBVIOUS_DATE_MAP = {
      OBVIOUS_YEARS  => TWO_DIGIT_YEAR_EMITTER,
      OBVIOUS_MONTHS => TWO_DIGIT_MONTH_EMITTER,
      OBVIOUS_DAYS   => TWO_DIGIT_DAY_EMITTER
    }

    TWO_DIGIT_DATE_SUCCESSION = {
      :month => TWO_DIGIT_DAY_EMITTER,
      :day   => TWO_DIGIT_YEAR_EMITTER,
      :year  => TWO_DIGIT_MONTH_EMITTER
    }

    TWO_DIGIT_TIME_SUCCESSION = {
      :hour => Emitters::TwoDigit.new(:min),
      :min  => Emitters::TwoDigit.new(:sec)
    }

    def translate(example)
      # extract any substrings that look like times, like "23:59" or "8:37 am"
      before, time_example, after = example.partition(TIME_REGEXP)

      # build emitters from the example date
      emitters = Emitters::Composite.new
      emitters << build_emitters(before.split(/\b/)) do |token, previous_part|
        date_emitter(token, previous_part)
      end

      # build emitters from the example time
      unless time_example.empty?
        time_parts = time_example.scan(TIME_REGEXP).first
        emitters << build_emitters(time_parts) do |token, previous_part|
          time_emitter(token, previous_part)
        end
      end

      # recursively process any remaining text
      emitters << translate(after) unless after.empty?
      emitters
    end

    # Transforms tokens that look like date/time parts to emitter objects.
    def build_emitters(tokens)
      previous_part = nil
      tokens.map do |token|
        emitter = yield(token, previous_part)
        previous_part = emitter.field unless emitter.nil?

        emitter || Emitters::String.new(token)
      end
    end

    def time_emitter(token, previous_part)
      case token
      when MERIDIAN_LOWER_REGEXP
        Emitters::AmPm.new

      when MERIDIAN_UPPER_REGEXP
        Emitters::AmPm.new { |v| v.upcase }

      when TWO_DIGIT_REGEXP
        TWO_DIGIT_TIME_SUCCESSION[previous_part] ||
          case token.to_i
          when OBVIOUS_24_HOUR
            # 24-hour clock
            Emitters::TwoDigit.new(:hour)
          else
            # 12-hour clock with leading zero
            Emitters::TwoDigit.new(:hour, &HOUR_TO_12_HOUR)
          end

      when ONE_DIGIT_REGEXP
        # 12-hour clock without leading zero
        Emitters::Delegate.new(:hour, &HOUR_TO_12_HOUR)
      end
    end

    def date_emitter(token, previous_part)
      case token
      when MONTHNAMES_REGEXP
        Emitters::Lookup.new(:month, Date::MONTHNAMES)

      when ABBR_MONTHNAMES_REGEXP
        Emitters::Lookup.new(:month, Date::ABBR_MONTHNAMES)

      when DAYNAMES_REGEXP
        Emitters::Lookup.new(:wday, Date::DAYNAMES)

      when ABBR_DAYNAMES_REGEXP
        Emitters::Lookup.new(:wday, Date::ABBR_DAYNAMES)

      when TIMEZONE_REGEXP
        Emitters::Delegate.new(:zone)

      when FOUR_DIGIT_REGEXP
        Emitters::Delegate.new(:year)

      when ORDINAL_DAY_REGEXP
        Emitters::Ordinal.new(:day)

      when TWO_DIGIT_REGEXP
        value = token.to_i

        obvious_mappings =
          OBVIOUS_DATE_MAP.reject { |k,v| v.field == previous_part }

        obvious_directive = obvious_mappings.find do |range, directive|
          break directive if range === value
        end

        # if the intent isn't obvious based on the example value, try to
        # disambiguate based on context
        obvious_directive ||
          TWO_DIGIT_DATE_SUCCESSION[previous_part] ||
          TWO_DIGIT_MONTH_EMITTER

      when ONE_DIGIT_REGEXP
        Emitters::Delegate.new(:day)
      end
    end

  end
end


text:
namespace ash {

// There are five classes of accelerators in Ash:
//
// Ash (OS) reserved:
// * Neither packaged apps nor web pages can cancel.
// * For example, power button.
// * See kReservedActions below.
//
// Ash (OS) preferred:
// * Fullscreen window can consume, but normal window can't.
// * For example, Alt-Tab window cycling.
// * See kPreferredActions below.
//
// Chrome OS system keys:
// * For legacy reasons, v1 apps can process and cancel. Otherwise handled
//   directly by Ash.
// * Brightness, volume control, etc.
// * See IsSystemKey() in ash/accelerators/accelerator_filter.cc.
//
// Browser reserved:
// * Packaged apps can cancel but web pages cannot.
// * For example, browser back and forward from first-row function keys.
// * See IsReservedCommandOrKey() in
//   chrome/browser/ui/browser_command_controller.cc.
//
// Browser non-reserved:
// * Both packaged apps and web pages can cancel.
// * For example, selecting tabs by number with Ctrl-1 to Ctrl-9.
// * See kAcceleratorMap in chrome/browser/ui/views/accelerator_table.cc.
//
// In particular, there is not an accelerator processing pass for Ash after
// the browser gets the accelerator.  See crbug.com/285308 for details.
//
// There are also various restrictions on accelerators allowed at the login
// screen, when running in "forced app mode" (like a kiosk), etc. See the
// various kActionsAllowed* below.
//
// Please put if/def sections at the end of the bare section and keep the list
// within each section in alphabetical order.
enum AcceleratorAction {
  CYCLE_BACKWARD_MRU,
  CYCLE_FORWARD_MRU,
  DEBUG_PRINT_LAYER_HIERARCHY,
  DEBUG_PRINT_VIEW_HIERARCHY,
  DEBUG_PRINT_WINDOW_HIERARCHY,
  DEBUG_TOGGLE_ROOT_WINDOW_FULL_SCREEN,
  DEBUG_TOGGLE_DESKTOP_BACKGROUND_MODE,
  DEBUG_TOGGLE_DEVICE_SCALE_FACTOR,
  DEBUG_TOGGLE_SHOW_DEBUG_BORDERS,
  DEBUG_TOGGLE_SHOW_FPS_COUNTER,
  DEBUG_TOGGLE_SHOW_PAINT_RECTS,
  EXIT,
  FOCUS_NEXT_PANE,
  FOCUS_PREVIOUS_PANE,
  FOCUS_SHELF,
  LAUNCH_APP_0,
  LAUNCH_APP_1,
  LAUNCH_APP_2,
  LAUNCH_APP_3,
  LAUNCH_APP_4,
  LAUNCH_APP_5,
  LAUNCH_APP_6,
  LAUNCH_APP_7,
  LAUNCH_LAST_APP,
  MAGNIFY_SCREEN_ZOOM_IN,
  MAGNIFY_SCREEN_ZOOM_OUT,
  MEDIA_NEXT_TRACK,
  MEDIA_PLAY_PAUSE,
  MEDIA_PREV_TRACK,
  NEW_INCOGNITO_WINDOW,
  NEW_TAB,
  NEW_WINDOW,
  NEXT_IME,
  OPEN_FEEDBACK_PAGE,
  PREVIOUS_IME,
  PRINT_UI_HIERARCHIES,
  RESTORE_TAB,
  ROTATE_SCREEN,
  ROTATE_WINDOW,
  SCALE_UI_DOWN,
  SCALE_UI_RESET,
  SCALE_UI_UP,
  SHOW_KEYBOARD_OVERLAY,
  SHOW_MESSAGE_CENTER_BUBBLE,
  SHOW_SYSTEM_TRAY_BUBBLE,
  SHOW_TASK_MANAGER,
  SWITCH_IME,  // Switch to another IME depending on the accelerator.
  TAKE_PARTIAL_SCREENSHOT,
  TAKE_SCREENSHOT,
  TOGGLE_APP_LIST,
  TOGGLE_FULLSCREEN,
  TOGGLE_MAXIMIZED,
  TOGGLE_OVERVIEW,
  WINDOW_MINIMIZE,
  WINDOW_POSITION_CENTER,
  WINDOW_CYCLE_SNAP_DOCK_LEFT,
  WINDOW_CYCLE_SNAP_DOCK_RIGHT,
#if defined(OS_CHROMEOS)
  BRIGHTNESS_DOWN,
  BRIGHTNESS_UP,
  DEBUG_ADD_REMOVE_DISPLAY,
  DEBUG_TOGGLE_TOUCH_PAD,
  DEBUG_TOGGLE_TOUCH_SCREEN,
  DEBUG_TOGGLE_UNIFIED_DESKTOP,
  DISABLE_CAPS_LOCK,
  DISABLE_GPU_WATCHDOG,
  KEYBOARD_BRIGHTNESS_DOWN,
  KEYBOARD_BRIGHTNESS_UP,
  LOCK_PRESSED,
  LOCK_RELEASED,
  LOCK_SCREEN,
  OPEN_CROSH,
  OPEN_FILE_MANAGER,
  OPEN_GET_HELP,
  POWER_PRESSED,
  POWER_RELEASED,
  SILENCE_SPOKEN_FEEDBACK,
  SWAP_PRIMARY_DISPLAY,
  SWITCH_TO_NEXT_USER,
  SWITCH_TO_PREVIOUS_USER,
  TOGGLE_CAPS_LOCK,
  TOGGLE_MIRROR_MODE,
  TOGGLE_SPOKEN_FEEDBACK,
  TOGGLE_TOUCH_VIEW_TESTING,
  TOGGLE_WIFI,
  TOUCH_HUD_CLEAR,
  TOUCH_HUD_MODE_CHANGE,
  TOUCH_HUD_PROJECTION_TOGGLE,
  VOLUME_DOWN,
  VOLUME_MUTE,
  VOLUME_UP,
#else
  DUMMY_FOR_RESERVED,
#endif
};

struct AcceleratorData {
  bool trigger_on_press;
  ui::KeyboardCode keycode;
  int modifiers;
  AcceleratorAction action;
};

// Gathers the needed data to handle deprecated accelerators.
struct DeprecatedAcceleratorData {
  // The action that has deprecated accelerators.
  AcceleratorAction action;

  // The name of the UMA histogram that will be used to measure the deprecated
  // v.s. new accelerator usage.
  const char* uma_histogram_name;

  // The ID of the localized notification message to show to users informing
  // them about the deprecation.
  int notification_message_id;

  // The ID of the localized old deprecated shortcut key.
  int old_shortcut_id;

  // The ID of the localized new shortcut key.
  int new_shortcut_id;

  // Specifies whether the deprecated accelerator is still enabled to do its
  // associated action.
  bool deprecated_enabled;
};

// This will be used for the UMA stats to measure the how many users are using
// the old v.s. new accelerators.
enum DeprecatedAcceleratorUsage {
  DEPRECATED_USED = 0,     // The deprecated accelerator is used.
  NEW_USED,                // The new accelerator is used.
  DEPRECATED_USAGE_COUNT,  // Maximum value of this enum for histogram use.
};

// Accelerators handled by AcceleratorController.
ASH_EXPORT extern const AcceleratorData kAcceleratorData[];
ASH_EXPORT extern const size_t kAcceleratorDataLength;

#if defined(OS_CHROMEOS)
// The list of the deprecated accelerators.
ASH_EXPORT extern const AcceleratorData kDeprecatedAccelerators[];
ASH_EXPORT extern const size_t kDeprecatedAcceleratorsLength;

// The list of the actions with deprecated accelerators and the needed data to
// handle them.
ASH_EXPORT extern const DeprecatedAcceleratorData kDeprecatedAcceleratorsData[];
ASH_EXPORT extern const size_t kDeprecatedAcceleratorsDataLength;
#endif  // defined(OS_CHROMEOS)

// Debug accelerators. Debug accelerators are only enabled when the "Debugging
// keyboard shortcuts" flag (--ash-debug-shortcuts) is enabled. Debug actions
// are always run (similar to reserved actions).
ASH_EXPORT extern const AcceleratorData kDebugAcceleratorData[];
ASH_EXPORT extern const size_t kDebugAcceleratorDataLength;

// Actions that should be handled very early in Ash unless the current target
// window is full-screen.
ASH_EXPORT extern const AcceleratorAction kPreferredActions[];
ASH_EXPORT extern const size_t kPreferredActionsLength;

// Actions that are always handled in Ash.
ASH_EXPORT extern const AcceleratorAction kReservedActions[];
ASH_EXPORT extern const size_t kReservedActionsLength;

// Actions allowed while user is not signed in or screen is locked.
ASH_EXPORT extern const AcceleratorAction kActionsAllowedAtLoginOrLockScreen[];
ASH_EXPORT extern const size_t kActionsAllowedAtLoginOrLockScreenLength;

// Actions allowed while screen is locked (in addition to
// kActionsAllowedAtLoginOrLockScreen).
ASH_EXPORT extern const AcceleratorAction kActionsAllowedAtLockScreen[];
ASH_EXPORT extern const size_t kActionsAllowedAtLockScreenLength;

// Actions allowed while a modal window is up.
ASH_EXPORT extern const AcceleratorAction kActionsAllowedAtModalWindow[];
ASH_EXPORT extern const size_t kActionsAllowedAtModalWindowLength;

// Actions which will not be repeated while holding an accelerator key.
ASH_EXPORT extern const AcceleratorAction kNonrepeatableActions[];
ASH_EXPORT extern const size_t kNonrepeatableActionsLength;

// Actions allowed in app mode.
ASH_EXPORT extern const AcceleratorAction kActionsAllowedInAppMode[];
ASH_EXPORT extern const size_t kActionsAllowedInAppModeLength;

// Actions that require at least 1 window.
ASH_EXPORT extern const AcceleratorAction kActionsNeedingWindow[];
ASH_EXPORT extern const size_t kActionsNeedingWindowLength;

// Actions that can be performed while keeping the menu open.
ASH_EXPORT extern const AcceleratorAction kActionsKeepingMenuOpen[];
ASH_EXPORT extern const size_t kActionsKeepingMenuOpenLength;

}  // namespace ash

#endif  // ASH_ACCELERATORS_ACCELERATOR_TABLE_H_


text: puts 'Use spec/jspec.rb to alter anything you like, provide routes, browsers, etc'


text:
var Joi = require('joi');
var User = require('../models/user');

/**
 * Responds to POST /login and logs the user in, well, soon.
 */
exports.login = {
  handler: function (request, reply) {

    // In the version with Travelogue and Mongoose this was all handled by Passport (hence we retrieved
    // Passport and inserted the request and reply variables).
    User.authenticate()(request.payload.email, request.payload.password, function (err, user, passwordError) {

      // There has been an error, do something with it. I just print it to console for demo purposes.
      if (err) {
        console.error(err);
        return reply.redirect('/login');
      }

      // Something went wrong with the login process, could be any of:
      // https://github.com/saintedlama/passport-local-mongoose#error-messages
      if (passwordError) {
        // For now, just show the error and login form
        console.log(passwordError);
        return reply.view('login', {
          errorMessage: passwordError.message,
        });
      }

      // If the authentication failed user will be false. If it's not false, we store the user
      // in our session and redirect the user to the hideout
      if (user) {
        request.auth.session.set(user);
        return reply.redirect('/batmanshideout');
      }

      return reply.redirect('/login');

    });
  }
};

/**
 * Responds to GET /logout and logs out the user
 */
exports.logout = {
  auth: 'session',
  handler: function (request, reply) {
    request.auth.session.clear();
    reply().redirect('/');
  }
};

/**
 * Responds to POST /register and creates a new user.
 */
exports.register = {
  validate: {
    payload: {
      email: Joi.string().email().required(),
      password: Joi.string().required()
    }
  },
  handler: function(request, reply) {

    // Create a new user, this is the place where you add firstName, lastName etc.
    // Just don't forget to add them to the validator above.
    var newUser = new User({
      email: request.payload.email
    });

    // The register function has been added by passport-local-mongoose and takes as first parameter
    // the user object, as second the password it has to hash and finally a callback with user info.
    User.register(newUser, request.payload.password, function(err, user) {

      // Return error if present
      if (err) {
        return reply(err);
      }

      console.log('registered');
      return reply.redirect('/login');
    });
  }
};


text:
package routes

import (
	//	"fmt"
	"net/http"
	"os"
	"strconv"
	//	"strings"

	"go-little-blog/models"
	"go-little-blog/utils"

	"github.com/go-martini/martini"
	//	"github.com/martini-contrib/auth"
	"github.com/martini-contrib/render"
)

var (
	Pathposts    string // папка в которой нах-ся посты блога
	Pathhtml     string // папка в которой нах-ся обычные html страницы блога
	Pathtemplate string //  папка в которой нах-ся шаблоны
	Kolpost      int    // кол-во постов (сообщений) на главной странице блога
	Tekpost      int    // номер сообщения с которого начинается сообщения на странице
)

//-----------END вспомогательная функция которую надо будет удалить со временем

func IndexHandler(rr render.Render, w http.ResponseWriter, r *http.Request) {
	var pp models.Post
	p := make([]models.Post, 0)
	namefs := utils.Getlistfileindirectory(Pathposts)
	tnamefs := namefs
	vsegopost := len(namefs)
	if len(namefs) != 0 {
		namefs = utils.SorttoDown(namefs)
		if Kolpost > len(namefs) {
			tnamefs = namefs[:]
		} else {
			tnamefs = namefs[:Kolpost]
		}

		for _, namef := range tnamefs {
			pp.GetPostfromFileMd(Pathposts + string(os.PathSeparator) + namef)
			if !pp.GetDraft() { // не отражаются черновики
				p = append(p, pp)
			}
		}
	} else {
		p = append(p, models.Post{Id: "ПОСТОВ НЕТ", Title: "ЭТОТ БЛОГ ПУСТ. ПРИХОДИТЕ ПОЗЖЕ ;)", ContentText: ""})
	}

	rr.HTML(200, "index", &models.PagePost{TitlePage: "Блог проектов kaefik", Posts: p, Postright: vsegopost - Kolpost})
}

// посты блога
func PostsHandler(rr render.Render, w http.ResponseWriter, r *http.Request, params martini.Params) {
}

// посты блога
func HtmlHandler(rr render.Render, w http.ResponseWriter, r *http.Request, params martini.Params) {
	namefs := utils.Getlistfileindirectory(Pathhtml)
	if len(namefs) != 0 {
		for _, v := range namefs {
			if v == params["namepage"] {
				// ? сделать чтобы загружался страница из папки pathhtmlts
				//				rr.HTML(200, "news")
			}
		}
	}
	rr.Redirect("/")
}

// просмотр посты блога
func ViewHandler(rr render.Render, w http.ResponseWriter, r *http.Request, params martini.Params) {
	var pp models.Post
	p := make([]models.Post, 0)
	numpost, _ := strconv.Atoi(params["numpost"])
	namefs := utils.Getlistfileindirectory(Pathposts)
	namefs = utils.SorttoUp(namefs)
	tnamefs := namefs
	vsegopost := len(namefs)

	if numpost <= 0 {
		numpost = len(namefs)
	}

	if numpost >= len(namefs) {
		if Kolpost > len(namefs) {
			tnamefs = namefs[:]
		} else {
			tnamefs = namefs[len(namefs)-Kolpost:]
		}

		if len(namefs) != 0 {
			for k := len(tnamefs) - 1; k >= 0; k-- {
				namef := tnamefs[k]
				pp.GetPostfromFileMd(Pathposts + string(os.PathSeparator) + namef)
				p = append(p, pp)
			}
		} else {
			p = append(p, models.Post{Id: "ПОСТОВ НЕТ", Title: "ЭТОТ БЛОГ ПУСТ. ПРИХОДИТЕ ПОЗЖЕ ;)", ContentText: ""})
		}
		rr.HTML(200, "view", &models.PagePost{TitlePage: "Блог проектов kaefik", Posts: p, Postright: vsegopost - Kolpost})
		return
	}
	if len(namefs) != 0 {
		kk := numpost - Kolpost
		if kk <= 0 {
			kk = 0
		} else {
			kk = numpost - Kolpost // - 1
		}
		tnamefs := namefs[kk:numpost]

		if len(namefs) != 0 {
			for k := len(tnamefs) - 1; k >= 0; k-- {
				namef := tnamefs[k]
				pp.GetPostfromFileMd(Pathposts + string(os.PathSeparator) + namef)
				p = append(p, pp)
			}
		}
	} else {
		rr.Redirect("/")
		return
	}
	rr.HTML(200, "view", &models.PagePost{TitlePage: "Блог проектов kaefik", Posts: p, Postleft: numpost + Kolpost, Postright: numpost - Kolpost})
}


text:
<?php

use App\Services\ImageStorage;
use Faker\Provider\Base;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class FakerPostUrl extends Base
{
    /**
     * Return a Post URL.
     *
     * @return string
     */
    public function post_url()
    {
        $uploadPath = $this->generator->file(storage_path('fixtures'));
        $upload = new UploadedFile(
            $uploadPath,
            basename($uploadPath),
            'image/jpeg',
        );

        return app(ImageStorage::class)->put(
            $this->generator->unique()->randomNumber(5),
            $upload,
        );
    }
}


text:
package br.com.sailboat.canoe.dialog;

import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.WindowManager;

import br.com.sailboat.canoe.R;
import br.com.sailboat.canoe.base.BaseDialogFragment;

public class ProgressDialog extends BaseDialogFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCancelable(false);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.dlg_progress, null);
        return buildDialog(view);
    }

    private Dialog buildDialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);

        Dialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        return dialog;
    }

}


text:
<?php

$localDirectory = dirname(__FILE__);
require_once($localDirectory . "/../src/phcollect.php");

class PhListTests extends PHPUnit_Framework_TestCase{

    public function testPhListIsInstantiable(){
        $errorThrown = false;

        try{
            new PhList();
        } catch (Exception $e) {
            $errorThrown = true;
        }

        $this->assertEquals($errorThrown, false);
    }

    public function testPhListInstanceHasToArrayMethod(){
        $testList = new PhList();

        $this->assertEquals(method_exists($testList, "toArray"), true);
    }

    public function testPhListIsInstantiableWithASingleValue(){
        $testList = new PhList("test value 1");
        $this->assertEquals($testList->length(), 1);
    }

    public function testPhListIsInstantiableWithMultipleValues(){
        $testList = new PhList("1", "2", "3");
        $this->assertEquals($testList->length(), 3);
    }

    public function testPhListHasAddMethod(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $this->assertEquals(true, method_exists($testList, "add"));
    }

    public function testPhListAddMethodInsertsValue(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $testList->add(2, 9);

        $this->assertEquals(9, $testList->nth(2));
    }

    public function testPhListHasContainsMethod(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $this->assertEquals(true, method_exists($testList, "contains"));
    }

    public function testPhListHasClearMethod(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $this->assertEquals(true, method_exists($testList, "clear"));
    }

    public function testPhListClearEmptiesList(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $testList->clear();

        $this->assertEquals(0, $testList->length());
    }

    public function testPhListContainsReturnsTrueIfValueExists(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $this->assertEquals(true, $testList->contains(3));
    }

    public function testPhListContainsReturnsFalseIfValueDoesNotExist(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $this->assertEquals(false, $testList->contains(6));
    }

    public function testPhListHasDeleteMethod(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $this->assertEquals(true, method_exists($testList, "delete"));
    }

    public function testPhListDeleteRemovesCorrectValue(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $testList->delete(2);

        $this->assertEquals(4, $testList->nth(2));
    }

    public function testPhListHasIndexOfMethod(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $this->assertEquals(true, method_exists($testList, "indexOf"));
    }

    public function testPhListIndexOfReturnsIndexOfExistingElement(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $this->assertEquals(1, $testList->indexOf(2));
    }

    public function testPhListIndexOfReturnsFalseIfElementDoesNotExist(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $this->assertEquals(false, $testList->indexOf(6));
    }

    public function testPhListHasIsEmptyMethod(){
        $testList = new PhList();

        $this->assertEquals(true, method_exists($testList, "isEmpty"));
    }

    public function testPhListIsEmptyReturnsTrueIfListIsEmpty(){
        $testList = new PhList();

        $this->assertEquals(true, $testList->isEmpty());
    }

    public function testPhListIsEmptyReturnsFalsIfListIsNotEmpty(){
        $testList = new PhList(1, 2, 3, 4, 5);

        $this->assertEquals(false, $testList->isEmpty());
    }

    public function testPushAddsValueToEndOfList(){
        $testList = new PhList(1, 2);
        $testList->push(3);

        $this->assertEquals($testList->last(), 3);
    }

    public function testPushThrowsErrorIfNoValueIsProvided(){
        $testList = new PhList(1, 2);
        $exceptionThrown = false;

        try{
            $testList->push();
        } catch (Exception $e){
            $exceptionThrown = true;
        }

        $this->assertEquals($exceptionThrown, true);
    }

    public function testPopReturnsLastElementOfList(){
        $testList = new PhList(1, 2, 3, 4);

        $this->assertEquals($testList->pop(), 4);
    }

    public function testPopRemovesLastElementOfList(){
        $testList = new PhList(1, 2, 3, 4);
        $testList->pop();

        //These asserts verify that the element int 4 was correctly removed
        $this->assertEquals($testList->last(), 3);
        $this->assertEquals($testList->length(), 3);
    }

    public function testShiftReturnsFirstElementOfList(){
        $testList = new PhList(1, 2, 3, 4);
        $this->assertEquals($testList->shift(), 1);
    }

    public function testShiftRemovesFirstElementOfList(){
        $testList = new PhList(1, 2, 3, 4);
        $testList->shift();

        $this->assertEquals($testList->first(), 2);
        $this->assertEquals($testList->length(), 3);
    }

    public function testSliceReturnsNewListInstance(){
        $testList = new PhList(1, 2, 3, 4);
        $newList = $testList->slice(1);
        $this->assertEquals(get_class($newList), "PhList");
    }

    public function testSliceReturnsListSlicedAtOffset(){
        $testList = new PhList(1, 2, 3, 4);
        $newList = $testList->slice(1);

        $this->assertEquals($newList->first(), 2);
        $this->assertEquals($newList->length(), 3);
    }

    public function testSliceReturnsListSliceThatEndsAtLength(){
        $testList = new PhList(1, 2, 3, 4);
        $newList = $testList->slice(1, 2);

        $this->assertEquals($newList->first(), 2);
        $this->assertEquals($newList->last(), 3);
    }

    public function testSortSortsAList(){
        $testList = new PhList(2, 5, 1, 9, 6, 4);
        $expectedSet = array(1, 2, 4, 5, 6, 9);

        $testList->sort();
        $this->assertEquals($testList->toArray(), $expectedSet);
    }

    public function testSortSortsAListWithAPassedComparator(){
        $testList = new PhList(2, 9, 1, 5, 6, 4);
        $expectedSet = array(2, 4, 6, 1, 5, 9);

        $testList->sort(function($a, $b){
            $direction = 0;

            if($a % 2 === 0 && $b % 2 !== 0){
                $direction = -1;
            } else if($a % 2 !== 0 && $b % 2 === 0){
                $direction = 1;
            }

            if($direction === 0 && $a > $b){
                $direction = 1;
            } else if($direction === 0 && $a < $b){
                $direction = -1;
            }

            return $direction;
        });

        $this->assertEquals($testList->toArray(), $expectedSet);
    }

    public function testUnionReturnsAList(){
        $testList = new PhList(1, 2, 3);
        $returnedValue = $testList->union();

        $this->assertEquals("PhList", get_class($returnedValue));
    }

    public function testUnionReturnsUnionOfListAndArrays(){
        $testList = new PhList(1, 2, 3);
        $returnedValue = $testList->union(array(2, 3, 4), array(5, 1, 3));

        $this->assertEquals("1, 2, 3, 4, 5", implode(", ", $returnedValue->toArray()));
    }

    public function testUnionAcceptsLists(){
        $testList = new PhList(1, 2, 3);
        $list1 = new PhList(2, 3, 4);
        $list2 = new PhList(5, 3, 1);

        $result = $testList->union($list1, $list2);

        $this->assertEquals("1, 2, 3, 4, 5", implode(", ", $result->toArray()));
    }

    public function testIntersectReturnsAList(){
        $testList = new PhList(1, 2, 3);
        $returnedValue = $testList->intersect();

        $this->assertEquals("PhList", get_class($returnedValue));
    }

    public function testIntersectReturnsIntersectionOfListAndArrays(){
        $testList = new PhList(1, 2, 3);
        $returnedValue = $testList->intersect(array(2, 3, 4), array(5, 1, 3));

        $this->assertEquals("3", implode(", ", $returnedValue->toArray()));
    }

    public function testUIntersectAcceptsLists(){
        $testList = new PhList(1, 2, 3);
        $list1 = new PhList(2, 3, 4);
        $list2 = new PhList(5, 3, 1);

        $result = $testList->intersect($list1, $list2);

        $this->assertEquals("3", implode(", ", $result->toArray()));
    }

    public function testPhListActionsAreChainable(){
        $testList = new PhList(4, 2, 1, 3);
        $finalOutput = $testList->sort()
                                ->map(function($value){
                                    return $value * 5;
                                })
                                ->push(5)
                                ->slice(1, 3)
                                ->rest()
                                ->last();
        $this->assertEquals($finalOutput, 20);
    }

}

?>


text:
package com.google.guiceberry;

import com.google.common.testing.TearDown;
import com.google.common.testing.junit3.TearDownTestCase;
import com.google.inject.AbstractModule;

/**
 * @author Luiz-Otavio "Z" Zorzella
 */
public class DefaultEnvSelectorTest extends TearDownTestCase {

  private static final class MyEnvOne extends AbstractModule {
    @Override
    protected void configure() {
      install(new GuiceBerryModule());
    }
  }
  private static final class MyEnvTwo extends AbstractModule {
    @Override
    protected void configure() {
      install(new GuiceBerryModule());
    }
  }

  public void testOverride() {
    assertFalse(DefaultEnvSelector.isOverridden(MyEnvOne.class));
    assertEquals(null, DefaultEnvSelector.getOverride(MyEnvOne.class.getName()));
    GuiceBerryEnvSelector envSelector = DefaultEnvSelector.of(MyEnvOne.class);
    assertEquals(MyEnvOne.class, envSelector.guiceBerryEnvToUse(null));

    override();

    assertTrue(DefaultEnvSelector.isOverridden(MyEnvOne.class));
    assertEquals(MyEnvTwo.class, DefaultEnvSelector.getOverride(MyEnvOne.class.getName()));
    envSelector = DefaultEnvSelector.of(MyEnvOne.class);
    assertEquals(MyEnvTwo.class, envSelector.guiceBerryEnvToUse(null));
  }

  private void override() {
    addTearDown(new TearDown() {

      public void tearDown() throws Exception {
        DefaultEnvSelector.clearOverride(MyEnvOne.class);
      }
    });
    DefaultEnvSelector.override(MyEnvOne.class, MyEnvTwo.class);
  }

  public void testThatTryingToOverrideASecondTimeThrows() {
    override();
    try {
      override();
      fail("Trying to override the same env a second time should throw");
    } catch (IllegalArgumentException expected) {
      assertEquals(String.format(
        "The GuiceBerry Env '%s' is already overridden by '%s'.",
          MyEnvOne.class.getName(), MyEnvTwo.class.getName()),
          expected.getMessage());
    }
  }
}


text:
dataset_destination_path = '/Users/seb/Desktop/mpas_flat_earth_prober'
source_filename = '/Volumes/Kitware/Data/DataExploration/Data/MPAS/data/flat_n_primal/LON_LAT_NLAYER-primal_%d_0.vtu'
# dataset_destination_path = '/Volumes/KSW-Data/mpas_flat_earth_prober-raw'
# source_filename          = '/Volumes/KSW-Data/Data/DataExploration/Data/MPAS/data/flat_n_primal/LON_LAT_NLAYER-primal_%d_0.vtu'

all_time_serie = range(50, 5151, 50)
quick_time_serie = range(100, 5151, 200)
single_time_serie = [ 50 ]

time_serie = quick_time_serie

sampling_arrays = ['temperature', 'salinity']
sampling_size   = [ 500, 250, 30 ]
sampling_bounds = [ -3.2, 3.2,
                    -1.3, 1.5,
                    -3.0, 0.0 ]

# -----------------------------------------------------------------------------

from paraview import simple
from paraview.web.dataset_builder import *

# -----------------------------------------------------------------------------
# Pipeline creation
# -----------------------------------------------------------------------------

reader = simple.XMLUnstructuredGridReader(FileName = source_filename % time_serie[0], CellArrayStatus = sampling_arrays)
dataCleanUp  = simple.Threshold(Input = reader, Scalars = ['CELLS', 'temperature'], ThresholdRange = [-1000.0, 50.0])

# -----------------------------------------------------------------------------
# Data Generation
# -----------------------------------------------------------------------------

dpdsb = DataProberDataSetBuilder(dataCleanUp, dataset_destination_path, sampling_size, sampling_arrays, sampling_bounds)

# Add time information
dpdsb.getDataHandler().registerArgument(priority=1, name='time', values=time_serie, ui='slider', loop='modulo')

# Explore dataset
dpdsb.start()
for time in dpdsb.getDataHandler().time:
    reader.FileName = source_filename % time
    dpdsb.writeData()
dpdsb.stop()


text:
Cam RPC App
===========

Django app that implements the WebCam RPC functionality of my home-control framework.

The API is based completely on HTTP GET requests,
with commands mapped to URI's and parameters passed into commands as URL query strings.

App Description
---------------

This app allows taking webcam snapshots remotely via the snapshot API.

Cam RPC App API Documentation
-----------------------------

### `snapshot/` URL

The snapshot URL is used to take a webcam snapshot.

There are no parameters for this command.

If successful, the command returns the snapshot taken in the HTTP Response (use the content-type to determine the image type).

If the snapshot failed, the response will be a JSON string with an error message.

App Configuration
-----------------

The app uses the Django DB to store configuration,
so the configuration is managed via Django admin interface.

For taking snapshots, the app will iterate over available `WebCam` records in the app table (ordered by the priority defined for each record),
and try to take a snapshot with the settings defined by the record,
until a successful snapshot is taken, which is then returned.

The settings:

* `name`: A name for this record. For convenience.
* `priority`: A positive integer representing the record priority. Lower numbers are used before higher numbers.
* `webcam_source`: A string denoting the webcam source to use for snapshots.
  * In Windows, this should be the device number passed to `VideoCapture.Device` (converted to int of course).
  * In Linux, this should be the path of the `gst-launch` executable.
  * In all platforms, if the field is a path to an existing image file, the file will be returned instead of a live snapshot. If the field is a path to an existing directory, a random file from the directory will be selected (and returned if it's an image).
  * Default value is "0" in Windows (for the first webcam device), and "gst-launch-0.10" is Linux.
* `snapshot_file`: A full path to the file to hold the temporary snapshot taken. Leave blank (default) to use a randomly generated temporary file. The web server will need write access to this path.

App Requirements
----------------

- Windows: [VideoCapture](http://videocapture.sourceforge.net/)
- Linux: [GStreamer](http://gstreamer.freedesktop.org/) gst-launch program.


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace FCT.LLC.BusinessService.Entities
{
    [Table("tblStandardNotificationList")]
    public partial class tblStandardNotificationList
    {
        public tblStandardNotificationList()
        {
            tblEmailTemplateLists = new HashSet<tblEmailTemplateList>();
        }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int StandardNotificationID { get; set; }

        [Required]
        [StringLength(100)]
        public string StandardNotificationName { get; set; }

        [StringLength(50)]
        public string GlobalizationKey { get; set; }

        [Required]
        [StringLength(50)]
        public string Recipient { get; set; }

        public bool IsHighPriority { get; set; }

        public bool Active { get; set; }

        public bool IsOptional { get; set; }

        public virtual ICollection<tblEmailTemplateList> tblEmailTemplateLists { get; set; }
    }
}


text:
from django import forms
#from codemirror2.widgets import CodeMirrorEditor
from jssor.models import Slide

class JssorAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(JssorAdminForm, self).__init__(*args, **kwargs)
    class Meta:
        model = Slide
        exclude = ('created','edited')


text:
package io.github.jonestimd.swing.validation;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import io.github.jonestimd.mockito.Matchers;
import io.github.jonestimd.swing.validation.ValidationTracker.ValidationChangeHandler;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class ValidationTrackerTest {
    private static final String REQUIRED_MESSAGE = "required";
    private final JPanel panel = new JPanel();
    @Mock
    private ValidationChangeHandler handler;
    private InOrder inOrder;

    @Before
    public void setup() throws Exception {
        ValidationTracker.install(handler, panel);
        inOrder = inOrder(handler);
    }

    @Test
    public void trackValidationMessages() throws Exception {
        ValidatedTextField field = new ValidatedTextField(new RequiredValidator(REQUIRED_MESSAGE));
        inOrder.verify(handler).validationChanged(Matchers.isEmpty());

        panel.add(field);
        inOrder.verify(handler).validationChanged(Matchers.containsOnly(REQUIRED_MESSAGE));

        field.setText("something");
        inOrder.verify(handler).validationChanged(Matchers.isEmpty());

        panel.remove(field);
        field.setText("something");
        inOrder.verify(handler).validationChanged(Matchers.isEmpty());
    }

    @Test
    public void trackAddedComponents() throws Exception {
        ValidatedTextField field = new ValidatedTextField(new RequiredValidator(REQUIRED_MESSAGE));
        inOrder.verify(handler).validationChanged(Matchers.isEmpty());

        panel.add(field);
        inOrder.verify(handler).validationChanged(Matchers.containsOnly(REQUIRED_MESSAGE));

        field.setText("text");
        inOrder.verify(handler).validationChanged(Matchers.isEmpty());

        field.setText("");
        inOrder.verify(handler).validationChanged(Matchers.containsOnly(REQUIRED_MESSAGE));

        panel.remove(field);
        inOrder.verify(handler).validationChanged(Matchers.isEmpty());
    }

    @Test
    public void ignoreValidationOnHiddenComponent() throws Exception {
        ValidatedTextField field = new ValidatedTextField(new RequiredValidator(REQUIRED_MESSAGE));
        panel.add(field);
        JFrame frame = new JFrame("JUnit test");
        SwingUtilities.invokeAndWait(() -> {
            frame.getContentPane().add(panel);
            frame.pack();
            frame.setVisible(true);
        });

        SwingUtilities.invokeAndWait(() -> field.setVisible(false));

        inOrder.verify(handler).validationChanged(Matchers.containsOnly(REQUIRED_MESSAGE));
        inOrder.verify(handler).validationChanged(Matchers.isEmpty());
        frame.dispose();
    }

    @Test
    public void trackNestedAddedComponents() throws Exception {
        ValidatedTextField field = new ValidatedTextField(new RequiredValidator(REQUIRED_MESSAGE));
        inOrder.verify(handler).validationChanged(Matchers.isEmpty());

        JPanel nested = new JPanel();
        nested.add(field);
        panel.add(nested);
        inOrder.verify(handler).validationChanged(Matchers.containsOnly(REQUIRED_MESSAGE));

        field.setText("text");
        inOrder.verify(handler).validationChanged(Matchers.isEmpty());

        field.setText("");
        inOrder.verify(handler).validationChanged(Matchers.containsOnly(REQUIRED_MESSAGE));

        panel.remove(nested);
        inOrder.verify(handler).validationChanged(Matchers.isEmpty());
    }
}


text:
use strict;
use warnings;

ENCODING INVALID => {
  diagram    => 'MR=0',
  extensions => 'NONE',
  exceptions => 'UNCATEGORIZED',
  categories => 'NONE',
  metadata   => 'isa=NONE',
  tags       => 'page=INVALID',
};

T['INVALID   ', 'NONE ', 'INVALID' , ''];

1;


text:
function(test)

  return()
  path_package_source()
  ans(path_source)

  events_track(
    project_on_begin_load
    project_on_load
    project_on_package_load
    project_on_packages_loaded
  )
  ans(tracker)

  ## event handler protocols all events fired
  ### load default non existing project

  ## arrange
  project_open()
  ans(project)

  ## act
  assign(success = project.load("pr0"))

  ## assert
  assert(success)
  assert(NOT EXISTS "${test_dir}/pr0")
  assertf({project.project_dir} STREQUAL "${test_dir}/pr0")
  assertf({project.config_dir} STREQUAL "${test_dir}/pr0/.cps")
  assertf({project.content_dir} STREQUAL "${test_dir}/pr0")
  assertf({project.dependency_dir} STREQUAL "${test_dir}/pr0/packages")

  ### load non existing project with custom config

  ## arrange
  project_open()
  ans(project)

  events_track(
    project_on_begin_load
    project_on_load
    project_on_package_load
    project_on_packages_loaded
  )
  ans(tracker)
  ## act
  assign(success = project.load("pr1"
    "{
      config_dir:'custom_config_dir',
      dependency_dir:'custom_package_dir',
      content_dir:'custom_content_dir'
    }"))

  ## assert
  assert(success)
  assert(NOT EXISTS "${test_dir}/pr1")
  assertf({project.project_dir} STREQUAL "${test_dir}/pr1")
  assertf({project.dependency_dir} STREQUAL "${test_dir}/pr1/custom_package_dir")
  assertf({project.config_dir} STREQUAL "${test_dir}/pr1/custom_config_dir")
  assertf({project.content_dir} STREQUAL "${test_dir}/pr1/custom_content_dir")
  assertf({project.local.directory} STREQUAL "${test_dir}/pr1/custom_package_dir")

  assertf({tracker.event_ids} CONTAINS project_on_begin_load)
  assertf({tracker.event_ids} CONTAINS project_on_load)

  ### load existing project with default layout with installed packages

  events_track(
    project_on_begin_load
    project_on_load
    project_on_package_load
    project_on_packages_loaded
  )
  ans(tracker)
  ## arrange
  fwrite_data("pkg1/package.cmake" "{id:'mypkg',version:'0.0.0',includes:'**'}" --json)
  managed_package_source("project" "${test_dir}/pr2/packages")
  ans(managed_source)

  assign(success = managed_source.push(${path_source} pkg1))
  project_open()
  ans(project)

  ## act
  assign(success = project.load("pr2"))

  ## assert
  assert(success)
  assertf({project.project_dir} STREQUAL "${test_dir}/pr2")
  assertf({project.local.directory} STREQUAL "${test_dir}/pr2/packages")

  assertf({tracker.event_ids} CONTAINS project_on_begin_load)
  assertf({tracker.event_ids} CONTAINS project_on_load)
  assertf({tracker.event_ids} CONTAINS project_on_package_load)
  assertf({tracker.event_ids} CONTAINS project_on_packages_loaded)

endfunction()