text:
CM2_Comp_Miscellaneous::CM2_Comp_Miscellaneous(const CM2& M2Object)
	: m_HasMisc(false)
	, m_M2Object(M2Object)
{
}

CM2_Comp_Miscellaneous::~CM2_Comp_Miscellaneous()
{
}

void CM2_Comp_Miscellaneous::Load(const SM2_Header& M2Header, const std::shared_ptr<IByteBuffer>& File)
{
	// Attachments
	if (M2Header.attachments.size > 0)
	{
		const SM2_Attachment* m2Attachments = (const SM2_Attachment*)(File->getData() + M2Header.attachments.offset);
		for (uint32 i = 0; i < M2Header.attachments.size; i++)
			m_Attachments.push_back(MakeShared(CM2_Part_Attachment, m_M2Object, File, m2Attachments[i]));

		// Animated
		m_HasMisc = true;
	}

	// Attachments Lookup
	if (M2Header.attachmentLookup.size > 0)
	{
		const int16* m2AttachmentsLookup = (const int16*)(File->getData() + M2Header.attachmentLookup.offset);
		for (uint32 i = 0; i < M2Header.attachmentLookup.size; i++)
		{
			m_AttachmentsLookup.push_back(m2AttachmentsLookup[i]);
		}
	}

	// Events
	if (M2Header.events.size > 0)
	{
		const SM2_Event* m2Events = (const SM2_Event*)(File->getData() + M2Header.events.offset);
		for (uint32 i = 0; i < M2Header.events.size; i++)
			m_Events.push_back(MakeShared(CM2_Part_Event, m_M2Object, File, m2Events[i]));

		// Animated
		m_HasMisc = true;
	}

	// Lights
	if (M2Header.lights.size > 0)
	{
		const SM2_Light* m2Lights = (const SM2_Light*)(File->getData() + M2Header.lights.offset);
		for (uint32 i = 0; i < M2Header.lights.size; i++)
			m_Lights.push_back(MakeShared(CM2_Part_Light, m_M2Object, File, m2Lights[i]));

		// Animated
		m_HasMisc = true;
	}

	// Cameras
	if (M2Header.cameras.size > 0)
	{
		const SM2_Camera* m2Cameras = (const SM2_Camera*)(File->getData() + M2Header.cameras.offset);
		for (uint32 i = 0; i < M2Header.cameras.size; i++)
			m_Cameras.push_back(MakeShared(CM2_Part_Camera, m_M2Object, File, m2Cameras[i]));

		// Animated
		m_HasMisc = true;
	}

	// Cameras Lookup
	if (M2Header.camerasLookup.size > 0)
	{
		const int16* m2CamerasLookup = (const int16*)(File->getData() + M2Header.camerasLookup.offset);
		for (uint32 i = 0; i < M2Header.camerasLookup.size; i++)
			m_CamerasLookup.push_back(m2CamerasLookup[i]);
	}

#if 0
	// Ribbons
	if (M2Header.ribbon_emitters.size > 0)
	{
		const SM2_RibbonEmitter* m2Ribbons = (const SM2_RibbonEmitter*)(File->getData() + M2Header.ribbon_emitters.offset);
		for (uint32 i = 0; i < M2Header.ribbon_emitters.size; i++)
		{
			std::shared_ptr<CM2_Part_RibbonEmitters> ribbon = std::make_shared<CM2_Part_RibbonEmitters>(m_M2Object, File, m2Ribbons[i]);
			m_RibbonEmitters.push_back(ribbon);
		}

		// Animated
		m_HasMisc = true;
	}
#endif

	// Particle systems
	if (M2Header.particle_emitters.size > 0)
	{
		const SM2_Particle* m2ParticleSystems = (const SM2_Particle*)(File->getData() + M2Header.particle_emitters.offset);
		for (uint32 i = 0; i < M2Header.particle_emitters.size; i++)
		{
			m_ParticleSystems.push_back(MakeShared(CM2_Part_ParticleSystem, m_M2Object, File, m2ParticleSystems[i]));
		}

		// Animated
		m_HasMisc = true;
	}
}

bool CM2_Comp_Miscellaneous::isAttachmentExists(EM2_AttachmentPoint Index) const
{
	if (static_cast<uint32>(Index) >= static_cast<uint32>(m_AttachmentsLookup.size()))
		return false;
	int16 newIndex = getAttachmentLookup(static_cast<uint32>(Index));
	return (newIndex != -1) && (newIndex < static_cast<int16>(m_Attachments.size()));
}

std::shared_ptr<const CM2_Part_Attachment> CM2_Comp_Miscellaneous::getAttachment(EM2_AttachmentPoint Index) const
{
	int16 directIndex = getAttachmentLookup(static_cast<uint32>(Index));
	if (directIndex == -1)
		return nullptr;
	return getAttachmentDirect(directIndex);
}

int16 CM2_Comp_Miscellaneous::getAttachmentLookup(uint32 Index) const
{
	if (Index >= static_cast<uint32>(m_AttachmentsLookup.size()))
		throw CException("CM2_Comp_Miscellaneous::getAttachmentLookup: lookup index out of bounds. %d of %d.", Index, m_AttachmentsLookup.size());
	return m_AttachmentsLookup[Index];
}

std::shared_ptr<const CM2_Part_Attachment> CM2_Comp_Miscellaneous::getAttachmentDirect(int16 Index) const
{
	if (Index >= static_cast<int16>(m_Attachments.size()))
		throw CException("CM2_Comp_Miscellaneous::getAttachmentDirect: direct index out of bounds. %d of %d.", Index, m_Attachments.size());
	return (m_Attachments[Index]);
}

std::shared_ptr<const CM2_Part_Event> CM2_Comp_Miscellaneous::getEventDirect(uint32 Index) const
{
	if (Index >= static_cast<int16>(m_Events.size()))
		throw CException("CM2_Comp_Miscellaneous::getEventDirect: direct index out of bounds.");
	return m_Events[Index];
}

std::shared_ptr<const CM2_Part_Light> CM2_Comp_Miscellaneous::getLightDirect(uint32 Index) const
{
	if (Index >= static_cast<int16>(m_Lights.size()))
		throw CException("CM2_Comp_Miscellaneous::getLightDirect: direct index out of bounds.");

	return m_Lights[Index];
}

const std::vector<std::shared_ptr<CM2_Part_Light>>& CM2_Comp_Miscellaneous::GetLightsDirectArray() const
{
	return m_Lights;
}

std::shared_ptr<const CM2_Part_Camera> CM2_Comp_Miscellaneous::getCamera(uint32 Index) const
{
	int16 directIndex = getCameraLookup(Index);
	if (directIndex == -1)
		return nullptr;

	if (directIndex >= static_cast<int16>(m_Cameras.size()))
		throw CException("CM2_Comp_Miscellaneous::getCamera: direct index out of bounds.");

	return m_Cameras[directIndex];
}

int16 CM2_Comp_Miscellaneous::getCameraLookup(uint32 Index) const
{
	if (Index >= static_cast<uint32>(m_CamerasLookup.size()))
		throw CException("CM2_Comp_Miscellaneous::getCameraLookup: lookup index out of bounds.");
	return m_CamerasLookup[Index];
}

std::shared_ptr<const CM2_Part_Camera> CM2_Comp_Miscellaneous::getCameraDirect(int16 Index) const
{
	if (Index >= static_cast<int16>(m_Cameras.size()))
		throw CException("CM2_Comp_Miscellaneous::getCameraDirect: direct index out of bounds.");
	return m_Cameras[Index];
}

const std::vector<std::shared_ptr<CM2_Part_ParticleSystem>>& CM2_Comp_Miscellaneous::GetParticles() const
{
	return m_ParticleSystems;
}


text:
var TwitterCldr = require('../../../lib/assets/javascripts/twitter_cldr/en.js');
var fs = require('fs');

var BIDI_TEST_PATH = __dirname + '/classpath_bidi_test.txt';
var DIRECTIONS = [null, "LTR", "RTL"];

expand_bitset_str = function(bitset) {
  var padded_str = ("0000" + parseInt(bitset).toString(2)).slice(-3);
  var result = [], idx;

  for (idx in padded_str) {
    result.push(padded_str[idx] == "1");
  }

  return result.reverse();
};

describe("Bidi", function() {
  it("should pass the derived tests in classpath_bidi_test.txt", function() {
    var data = fs.readFileSync(BIDI_TEST_PATH, "ASCII").split("\n");

    var expected_level_data = [];
    var expected_reorder_data = [];
    var num_failed = 0;
    var num_succeeded = 0;

    var input_bitset, input, bitset, result_list, bitset_arr, index, check;
    var types, bidi, passed, idx, level, levels, level_idx, string_arr, i;
    var position, positions, pos_idx, line_idx, cur_line, first_char;

    for (line_idx in data) {
      cur_line = data[line_idx].trim();
      first_char = cur_line[0];

      switch (first_char) {
        case "#":
          continue;

        case "@":
          if (cur_line.indexOf("@Levels:") > -1) {
            expected_level_data = [];
            levels = cur_line.replace("@Levels:", "").trim().split(" ");
            for (level_idx in levels) { expected_level_data.push(parseInt(levels[level_idx])); }
          }

          if (cur_line.indexOf("@Reorder:") > -1) {
            expected_reorder_data = [];
            positions = cur_line.replace("@Reorder:", "").trim().split(" ");
            for (pos_idx in positions) { expected_reorder_data.push(parseInt(positions[pos_idx])); }
          }

          break;

        default:
          input_bitset = cur_line.split("; ");
          input = input_bitset[0];
          bitset = input_bitset[1];
          result_list = [];
          bitset_arr = expand_bitset_str(bitset);

          for (index in bitset_arr) {
            check = bitset_arr[index];

            if (check) {
              types = input.split(" ");
              bidi = TwitterCldr.Bidi.from_type_array(types, {direction: DIRECTIONS[index], default_direction: "LTR"});
              passed = true;

              for (idx in bidi.levels) {
                level = bidi.levels[idx];
                passed = passed && (level === expected_level_data[idx]);
              }

              string_arr = [];

              for (i = 0; i < types.length; i ++) {
                string_arr.push(i);
              }

              bidi.string_arr = string_arr;
              bidi.reorder_visually();

              for (idx in bidi.string_arr) {
                position = bidi.string_arr[idx];
                passed = passed && (position === expected_reorder_data[idx]);
              }

              if (passed) {
                num_succeeded += 1;
              } else {
                num_failed += 1;
              }
            }
          }

          break;
      }
    }

    expect(num_failed).toEqual(0);
  });

  it("should be able to reorder RTL text", function() {
    var bidi_str = TwitterCldr.Bidi.from_string("hello نزوة world", {"direction": "RTL"});
    bidi_str.reorder_visually();
    expect(bidi_str.toString()).toEqual("world ةوزن hello");
  });

  // TODO: add tests for all other methods of Bidi class
  xit("should implement all other methods properly")
});

redpajama_set_name: RedPajamaGithub


text:
package io.nats.client.impl;

import java.text.NumberFormat;

import static io.nats.client.support.NatsConstants.EMPTY_BODY;

public class MessageProtocolCreationBenchmark {
    public static void main(String args[]) throws InterruptedException {
        int warmup = 1_000_000;
        int msgCount = 50_000_000;

        System.out.printf("### Running benchmarks with %s messages.\n", NumberFormat.getInstance().format(msgCount));

        for (int j = 0; j < warmup; j++) {
            new NatsMessage("subject", "replyTo", EMPTY_BODY);
        }

        long start = System.nanoTime();
        for (int j = 0; j < msgCount; j++) {
            new NatsMessage("subject", "replyTo", EMPTY_BODY);
        }
        long end = System.nanoTime();

        System.out.printf("\n### Total time to create %s non-utf8 messages for sending was %s ms\n\t%f ns/op\n\t%s op/sec\n",
                NumberFormat.getInstance().format(msgCount),
                NumberFormat.getInstance().format((end - start) / 1_000_000L),
                ((double) (end - start)) / ((double) (msgCount)),
                NumberFormat.getInstance().format(((double)(1_000_000_000L * msgCount))/((double) (end - start))));

        start = System.nanoTime();
        for (int j = 0; j < msgCount; j++) {
            new NatsMessage("subject", "replyTo", EMPTY_BODY);
        }
        end = System.nanoTime();

        System.out.printf("\n### Total time to create %s utf8 messages for sending was %s ms\n\t%f ns/op\n\t%s op/sec\n",
                NumberFormat.getInstance().format(msgCount),
                NumberFormat.getInstance().format((end - start) / 1_000_000L),
                ((double) (end - start)) / ((double) (msgCount)),
                NumberFormat.getInstance().format(((double)(1_000_000_000L * msgCount))/((double) (end - start))));

        start = System.nanoTime();
        for (int j = 0; j < msgCount; j++) {
            new NatsMessage.ProtocolMessage(EMPTY_BODY);
        }
        end = System.nanoTime();

        System.out.printf("\n### Total time to create %s a protocol message was %s ms\n\t%f ns/op\n\t%s op/sec\n",
                NumberFormat.getInstance().format(msgCount),
                NumberFormat.getInstance().format((end - start) / 1_000_000L),
                ((double) (end - start)) / ((double) (msgCount)),
                NumberFormat.getInstance().format(((double)(1_000_000_000L * msgCount))/((double) (end - start))));
    }
}


text:
@implementation SKTextCell

-(void)setup {
    _textView = [UITextView new];
    [self addSubview:_textView];
    _textView.backgroundColor = self.backgroundColor;
    _textView.delegate = self;
    _textView.text = [self value];
    _textView.font = [UIFont systemFontOfSize:14];
}
-(void)textViewDidBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@"Your text here..."]) { // replace this w/ a better solution in the future
        textView.text = nil;
    }
}
-(void)textViewDidChange:(UITextView *)textView {
    [self setValue:_textView.text];
}
-(void)layoutSubviews {
    _textView.frame = CGRectInset(self.bounds, 10, 5);
    [super layoutSubviews];
}
-(BOOL)clicked {
    [_textView becomeFirstResponder];
    return NO;
}

@end


text:
CREATE SCHEMA osm_mosques CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
GRANT ALL PRIVILEGES ON osm_mosques.* TO 'osm_mosques'@'localhost' IDENTIFIED BY 'osm_mosques';
GRANT ALL PRIVILEGES ON osm_mosques.* TO 'osm_mosques'@'%' IDENTIFIED BY 'osm_mosques';


text:
angular.module('nnConsumerUi')
  .config(function($translateProvider) {
    $translateProvider.translations('fi', {
      'REQUIRED_FIELD': 'Pakollinen kenttä',
      'CHARACTERS_LEFT': 'Merkkiä jäljellä',
      'CHOOSE_FILE': 'Valitse tiedosto',
      'EMPTY_TEXT': 'Valitse',
      'PRINT_BUTTON': 'Tulosta valitus',
      'SEND_MAIL_BUTTON': 'Lähetä Omaan Sähköpostiisi',
      'MAIL_SENT_TEXT': 'Sähköposti lähetetty',
      'NEXT_TEXT': 'Seuraava',
      'SUMMARY_HEADING': 'Reklamaatio',
      'SUMMARY_FOOT_TEXT': 'Odotan vastaustanne kahden viikon kuluessa. Sen jälkeen minulla on mahdollisuus ottaa yhteyttä maistraattien kuluttajaneuvontaan.'
    });

    $translateProvider.translations('sv', {
      'REQUIRED_FIELD': 'Obligatoriskt fält',
      'CHARACTERS_LEFT': 'Tecken kvar',
      'CHOOSE_FILE': 'Välj fil',
      'EMPTY_TEXT': 'Välj',
      'PRINT_BUTTON': 'Skriv ut reklamation',
      'SEND_MAIL_BUTTON': 'Skicka till e-post',
      'MAIL_SENT_TEXT': 'E-post skickad',
      'NEXT_TEXT': 'Nästa',
      'SUMMARY_HEADING': 'Reklamation',
      'SUMMARY_FOOT_TEXT': 'Jag förväntar mig svar inom två veckor. Efter det kan jag kontakta maistratens konsumentrådgivning.'
    });

    $translateProvider.translations('en', {
      'REQUIRED_FIELD': 'Required field',
      'CHARACTERS_LEFT': 'Characters left',
      'CHOOSE_FILE': 'Choose file',
      'EMPTY_TEXT': 'Select',
      'PRINT_BUTTON': 'Print complaint',
      'SEND_MAIL_BUTTON': 'Send to e-mail',
      'MAIL_SENT_TEXT': 'E-mail sent',
      'NEXT_TEXT': 'Next',
      'SUMMARY_HEADING': 'Complaint',
      'SUMMARY_FOOT_TEXT': 'I await an answer within two weeks. Thereafter I may choose to contact the registry office\'s consumer advice.'
    });

    $translateProvider.preferredLanguage('fi');
    $translateProvider.useSanitizeValueStrategy(null);
  });


text:
require 'faye'
require 'json'

module Sinkdown
  module Middleware
    class Reload

      def initialize(app = nil, options = nil)
        @app = app
        @site = options[:site]
        @listeners = Hash.new
      end

      def call(env)
        if Faye::WebSocket.websocket? env
          ws = Faye::WebSocket.new env
          ws.on :open do |event|
            listener = lambda do |doc_event|
              if ws
                msg = {
                  "document" => doc_event[:document].to_json
                }
                ws.send msg.to_json
              end
            end
            @listeners[ws] = listener
            @site.watcher << listener
          end
          ws.on :close do |event|
            listener = @listeners[ws]
            if listener
              @site.watcher.remove_listener listener
            end
            @listeners.delete(ws)
            ws = nil
          end
          ws.rack_response
        else
          @app.call env
        end
      end
    end
  end
end


text:
<!DOCTYPE html>

    <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
    <title>Edit Tournament</title>

Change Tournament Name

	<form class="lift:TournamentEdit?form=post">

		The identifier: tournament (this is used for images and stuff, so will never change)

	  	The old name: Tournament

	  	The new name: <input class="tournamentNameNew"/>

	  	<input type="submit" value="Confirm"/>

    </form>


text:
package net.community.chest.convert;

import net.community.chest.lang.StringUtil;
import net.community.chest.reflect.NumberValueStringConstructor;

public abstract class NonIntegerNumberValueStringConstructor<N extends Number> extends NumberValueStringConstructor<N> {
    protected NonIntegerNumberValueStringConstructor (Class<N> prmClass, Class<N> clsClass) throws IllegalArgumentException
    {
        super(prmClass, clsClass);
    }

    public static final String    NAN_VALUE="NaN",
                                POSITIVE_INFINITY_VALUE="+*",
                                NEGATIVE_INFINITY_VALUE="-*";
    /**
     * @param inst The {@link Number} to be checked if special encoding
     * @return The {@link String} to be used - null/empty if not a special value
     */
    public abstract String convertSpecialInstance (N inst);
    /*
     * @see net.community.chest.reflect.ValueStringConstructor#convertInstance(java.lang.Object)
     */
    @Override
    public String convertInstance (N inst) throws Exception
    {
        final String    s=convertSpecialInstance(inst);
        if ((s != null) && (s.length() > 0))
            return s;

        return super.convertInstance(inst);
    }
    /**
     * Checks if the supplied {@link String} is one of the special values
     * @param s The string to be considered
     * @return The matching {@link Number} - null if not a special value
     */
    public abstract N newSpecialInstance (String s);
    /*
     * @see net.community.chest.reflect.ValueStringConstructor#newInstance(java.lang.String)
     */
    @Override
    public N newInstance (String v) throws Exception
    {
        final String    s=StringUtil.getCleanStringValue(v);
        final N            inst=newSpecialInstance(s);
        if (inst != null)
            return inst;

        return super.newInstance(s);
    }
}


text:
namespace wn {
namespace runtime {
namespace testing {

// Directly from googletest.
namespace {

// Formats a countable noun.  Depending on its quantity, either the
// singular form or the plural form is used. e.g.
//
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
// FormatCountableNoun(5, "book", "books") returns "5 books".
static std::string FormatCountableNoun(
    int count, const char* singular_form, const char* plural_form) {
  return ::testing::internal::StreamableToString(count) + " " +
         (count == 1 ? singular_form : plural_form);
}

// Formats the count of tests.
static std::string FormatTestCount(int test_count) {
  return FormatCountableNoun(test_count, "test", "tests");
}

// Formats the count of test cases.
static std::string FormatTestCaseCount(int test_case_count) {
  return FormatCountableNoun(test_case_count, "test case", "test cases");
}

// Converts a TestPartResult::Type enum to human-friendly string
// representation.  Both kNonFatalFailure and kFatalFailure are translated
// to "Failure", as the user usually doesn't care about the difference
// between the two when viewing the test result.
static const char* TestPartResultTypeToString(
    ::testing::TestPartResult::Type type) {
  switch (type) {
    case ::testing::TestPartResult::kSuccess:
      return "Success";

    case ::testing::TestPartResult::kNonFatalFailure:
    case ::testing::TestPartResult::kFatalFailure:
#ifdef _MSC_VER
      return "error: ";
#else
      return "Failure\n";
#endif
    default:
      return "Unknown result type";
  }
}

// Prints a TestPartResult to an std::string.
static std::string PrintTestPartResultToString(
    const ::testing::TestPartResult& test_part_result) {
  return (::testing::Message()
          << ::testing::internal::FormatFileLocation(
                 test_part_result.file_name(), test_part_result.line_number())
          << " " << TestPartResultTypeToString(test_part_result.type())
          << test_part_result.message())
      .GetString();
}
}  // anonymous namespace

// Try to emulate the default printer but use android logging to do it.
class AndroidUnitTestPrinter : public ::testing::TestEventListener {
public:
  AndroidUnitTestPrinter()
    : m_test_static_log(&m_console_logger, logging::log_level::max, false),
      m_test_log(m_test_static_log.log()) {}

  virtual void OnTestProgramStart(const ::testing::UnitTest&) {}
  virtual void OnEnvironmentsSetUpEnd(const ::testing::UnitTest&) {}
  virtual void OnEnvironmentsTearDownEnd(const ::testing::UnitTest&) {}
  virtual void OnTestProgramEnd(const ::testing::UnitTest&) {}

  virtual void OnTestIterationStart(
      const ::testing::UnitTest& unit_test, int iteration);
  virtual void OnEnvironmentsSetUpStart(const ::testing::UnitTest& unit_test);
  virtual void OnTestCaseStart(const ::testing::TestCase& test_case);
  virtual void OnTestStart(const ::testing::TestInfo& test_info);
  virtual void OnTestPartResult(const ::testing::TestPartResult& result);
  virtual void OnTestEnd(const ::testing::TestInfo& test_info);
  virtual void OnTestCaseEnd(const ::testing::TestCase& test_case);
  virtual void OnEnvironmentsTearDownStart(
      const ::testing::UnitTest& unit_test);
  virtual void OnTestIterationEnd(
      const ::testing::UnitTest& unit_test, int iteration);

private:
  void PrintFullTestCommentIfPresent(const ::testing::TestInfo& info);
  void PrintFailedTests(const ::testing::UnitTest& unit_test);

  wn::logging::console_logger<> m_console_logger;
  wn::logging::static_log<logging::log_level::max> m_test_static_log;
  wn::logging::log_impl<logging::log_level::max>* m_test_log;
};

static const char sTypeParamLabel[] = "TypeParam";
static const char sValueParamLabel[] = "GetParam()";

void AndroidUnitTestPrinter::PrintFullTestCommentIfPresent(
    const ::testing::TestInfo& test_info) {
  const char* const type_param = test_info.type_param();
  const char* const value_param = test_info.value_param();

  if (type_param != NULL || value_param != NULL) {
    m_test_log->log_info_flags(
        static_cast<size_t>(logging::log_flags::no_header) |
            static_cast<size_t>(logging::log_flags::no_newline),
        ", where ");
    if (type_param != NULL) {
      m_test_log->log_info_flags(
          static_cast<size_t>(logging::log_flags::no_header) |
              static_cast<size_t>(logging::log_flags::no_newline),
          sTypeParamLabel, " = ", type_param);
      if (value_param != NULL) {
        m_test_log->log_info_flags(
            static_cast<size_t>(logging::log_flags::no_header) |
                static_cast<size_t>(logging::log_flags::no_newline),
            " and ");
      }
    }
    if (value_param != NULL) {
      m_test_log->log_info_flags(
          static_cast<size_t>(logging::log_flags::no_header) |
              static_cast<size_t>(logging::log_flags::no_newline),
          sValueParamLabel, " = ", value_param);
    }
  }
}

static const char sUniversalFilter[] = "*";

void AndroidUnitTestPrinter::OnTestIterationStart(
    const ::testing::UnitTest& unit_test, int iteration) {
  if (::testing::GTEST_FLAG(repeat) != 1) {
    m_test_log->log_debug(
        "Repeating all tests (iteration ", iteration + 1, ") . . . ");
  }

  m_test_log->log_debug_flags(
      static_cast<size_t>(logging::log_flags::no_header), "");

  if (::testing::GTEST_FLAG(filter) != sUniversalFilter) {
    m_test_log->log_debug("Note: " GTEST_NAME_ " filter = ",
        ::testing::GTEST_FLAG(filter).c_str());
  }

  if (::testing::GTEST_FLAG(shuffle)) {
    m_test_log->log_debug("Note: Randomizing tests' orders with a seed of ",
        unit_test.random_seed(), " .");
  }

  m_test_log->log_info_flags(
      static_cast<size_t>(logging::log_flags::no_header) |
          static_cast<size_t>(logging::log_flags::no_newline),
      "[==========] ");
  m_test_log->log_info_flags(
      static_cast<size_t>(logging::log_flags::no_header) |
          static_cast<size_t>(logging::log_flags::no_newline),
      "Running ", FormatTestCount(unit_test.test_to_run_count()).c_str(),
      " from ",
      FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
  m_test_log->flush();
}

void AndroidUnitTestPrinter::OnEnvironmentsSetUpStart(
    const ::testing::UnitTest&) {
  m_test_log->log_info_flags(
      static_cast<size_t>(logging::log_flags::no_newline),
      "[----------] Global test environment set-up.");
  m_test_log->flush();
}

void AndroidUnitTestPrinter::OnTestCaseStart(
    const ::testing::TestCase& test_case) {
  const std::string counts =
      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
  m_test_log->log_info_flags(
      static_cast<size_t>(logging::log_flags::no_newline), "[----------] ");
  if (test_case.type_param() == NULL) {
    m_test_log->log_info_flags(
        static_cast<size_t>(logging::log_flags::no_header), counts.c_str(),
        " from ", test_case.name());
  } else {
    m_test_log->log_info_flags(
        static_cast<size_t>(logging::log_flags::no_header), counts.c_str(),
        " from ", test_case.name(), ", where ", sTypeParamLabel, " = ",
        test_case.type_param());
  }
  m_test_log->flush();
}

void AndroidUnitTestPrinter::OnTestStart(const ::testing::TestInfo& test_info) {
  m_test_log->log_info_flags(
      static_cast<size_t>(logging::log_flags::no_newline), "[ RUN      ] ");
  m_test_log->log_info_flags(static_cast<size_t>(logging::log_flags::no_header),
      test_info.test_case_name(), ".", test_info.name());
  m_test_log->flush();
}

void AndroidUnitTestPrinter::OnTestPartResult(
    const ::testing::TestPartResult& result) {
  if (result.type() == ::testing::TestPartResult::kSuccess)
    return;

  m_test_log->log_info(PrintTestPartResultToString(result).c_str());
  m_test_log->flush();
}

void AndroidUnitTestPrinter::OnTestEnd(const ::testing::TestInfo& test_info) {
  if (test_info.result()->Passed()) {
    m_test_log->log_info_flags(
        static_cast<size_t>(logging::log_flags::no_newline), "[       OK ] ");
  } else {
    m_test_log->log_error_flags(
        static_cast<size_t>(logging::log_flags::no_newline), "[  FAILED  ] ");
  }

  m_test_log->log_info_flags(
      static_cast<size_t>(logging::log_flags::no_header) |
          static_cast<size_t>(logging::log_flags::no_newline),
      test_info.test_case_name(), ".", test_info.name());

  if (test_info.result()->Failed())
    PrintFullTestCommentIfPresent(test_info);

  if (::testing::GTEST_FLAG(print_time)) {
    m_test_log->log_info_flags(
        static_cast<size_t>(logging::log_flags::no_header), " (",
        ::testing::internal::StreamableToString(
            test_info.result()->elapsed_time())
            .c_str(),
        " ms)");
  } else {
    m_test_log->log_info_flags(
        static_cast<size_t>(logging::log_flags::no_header), "");
  }
  m_test_log->flush();
}

void AndroidUnitTestPrinter::OnTestCaseEnd(
    const ::testing::TestCase& test_case) {
  if (!::testing::GTEST_FLAG(print_time))
    return;

  const std::string counts =
      FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");

  m_test_log->log_info("[----------] ", counts.c_str(), " from ",
      test_case.name(), " (",
      ::testing::internal::StreamableToString(test_case.elapsed_time()).c_str(),
      "ms total)");
  m_test_log->flush();
}

void AndroidUnitTestPrinter::OnEnvironmentsTearDownStart(
    const ::testing::UnitTest&) {
  m_test_log->log_info("[----------] Global test environment tear-down\n");
  m_test_log->flush();
}

void AndroidUnitTestPrinter::PrintFailedTests(
    const ::testing::UnitTest& unit_test) {
  const int failed_test_count = unit_test.failed_test_count();
  if (failed_test_count == 0) {
    return;
  }

  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
    const ::testing::TestCase& test_case = *unit_test.GetTestCase(i);
    if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
      continue;
    }
    for (int j = 0; j < test_case.total_test_count(); ++j) {
      const ::testing::TestInfo& test_info = *test_case.GetTestInfo(j);
      if (!test_info.should_run() || test_info.result()->Passed()) {
        continue;
      }
      m_test_log->log_error_flags(
          static_cast<size_t>(logging::log_flags::no_newline), "[  FAILED  ] ",
          test_case.name(), ".", test_info.name());
      PrintFullTestCommentIfPresent(test_info);
      m_test_log->log_error_flags(
          static_cast<size_t>(logging::log_flags::no_header), "");
    }
  }
}

void AndroidUnitTestPrinter::OnTestIterationEnd(
    const ::testing::UnitTest& unit_test, int) {
  m_test_log->log_info_flags(
      static_cast<size_t>(logging::log_flags::no_newline), "[==========] ",
      FormatTestCount(unit_test.test_to_run_count()).c_str(), " from ",
      FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str(), " ran.");

  if (::testing::GTEST_FLAG(print_time)) {
    m_test_log->log_info_flags(
        static_cast<size_t>(logging::log_flags::no_header) |
            static_cast<size_t>(logging::log_flags::no_newline),
        " (",
        ::testing::internal::StreamableToString(unit_test.elapsed_time())
            .c_str(),
        " ms total)");
  }
  m_test_log->log_info_flags(
      static_cast<size_t>(logging::log_flags::no_header), "");
  m_test_log->log_info("[  PASSED  ] ",
      FormatTestCount(unit_test.successful_test_count()).c_str(), ".");

  int num_failures = unit_test.failed_test_count();
  if (!unit_test.Passed()) {
    const int failed_test_count = unit_test.failed_test_count();
    m_test_log->log_error("[  FAILED  ] ",
        FormatTestCount(failed_test_count).c_str(), ", listed below");
    PrintFailedTests(unit_test);
    m_test_log->log_error("");
    m_test_log->log_error(
        num_failures, "FAILED ", num_failures == 1 ? "TEST" : "TESTS");
  }

  int num_disabled = unit_test.reportable_disabled_test_count();
  if (num_disabled && !::testing::GTEST_FLAG(also_run_disabled_tests)) {
    if (!num_failures) {
      m_test_log->log_info(0, "");
    }
    m_test_log->log_warning("YOU HAVE ", num_disabled, " DISABLED ",
        num_disabled == 1 ? "TEST." : "TESTS.");
  }
  m_test_log->flush();
}

void init_test_framework() {
  ::testing::TestEventListeners& listeners =
      ::testing::UnitTest::GetInstance()->listeners();
  listeners.Append(new AndroidUnitTestPrinter);
}
}  // namespace testing
}  // namespace runtime
}  // namespace wn


text:
package library

import (
	"fmt"
)

type Trainer interface {
	Train()
}

// Trainer implementor
type Athlete struct{}

func (a *Athlete) Train() {
	fmt.Println("athlete training started")
	fmt.Println("athlete training completed")
}

func Swim() {
	fmt.Println("Swimming!")
}

type CompositeSwimmerA struct {
	MyAthelete Athlete
	MySwim     *func()
}

type Swimmer interface {
	Swim()
}

type SwimmerImplementor struct{}

func (s *SwimmerImplementor) Swim() {
	fmt.Println("another swimmer[implementor] swimming!")
}

type CompositeSwimmerB struct {
	Trainer
	Swimmer
}

type Animal struct{}

func (a *Animal) Eat() {
	fmt.Println("Animal eat")
}

type Shark struct {
	Animal
	SharkSwim func()
}


text:
/*
 * Description:
 *     A greedy load balancer
 *
 * Revision history:
 *     2016-02-03, Weijie Sun, first version
 */

# pragma once

# include "server_load_balancer.h"
# include <functional>
# include <atomic>

using namespace dsn;
using namespace dsn::service;
using namespace dsn::replication;

class greedy_load_balancer
    : public dsn::dist::server_load_balancer,
      public serverlet<greedy_load_balancer>
{
public:
    greedy_load_balancer(server_state* state);
    ~greedy_load_balancer();

    virtual void run() override;
    virtual void run(global_partition_id gpid) override;
    virtual void on_config_changed(std::shared_ptr<configuration_update_request> request) override;
    virtual void on_balancer_proposal(/*in*/const balancer_proposal_request& request, /*out*/balancer_proposal_response& response) override;
    virtual void on_control_migration(/*in*/const control_balancer_migration_request& request,
                                      /*out*/control_balancer_migration_response& response) override;
private:
    bool run_lb(partition_configuration& pc);

    bool balancer_proposal_check(const balancer_proposal_request& balancer_proposal);

    void execute_balancer_proposal();
    void greedy_copy_secondary();
    void greedy_copy_primary(int total_replicas);
    void greedy_move_primary(const std::vector<dsn::rpc_address>& node_list,
                             const std::vector<int>& prev,
                             int flows);
    void greedy_balancer(int total_replicas);

    bool walk_through_primary(const dsn::rpc_address& addr, const std::function<bool (partition_configuration& pc)>& func);
    bool walk_through_partitions(const dsn::rpc_address& addr, const std::function<bool (partition_configuration& pc)>& func);

    dsn::rpc_address recommend_primary(partition_configuration& pc);
    dsn::rpc_address find_minimal_load_machine(bool primaryOnly);

    void insert_balancer_proposal_request(const global_partition_id& gpid, balancer_type type, dsn::rpc_address from, dsn::rpc_address to)
    {
        balancer_proposal_request& request = _balancer_proposals_map[gpid];
        request.gpid = gpid;
        request.type = type;
        request.from_addr= from;
        request.to_addr = to;
    }
private:
    volatile bool _is_greedy_rebalancer_enabled;

    std::unordered_map<global_partition_id, dsn::rpc_address> _primary_recommender;
    std::unordered_map<global_partition_id, balancer_proposal_request> _balancer_proposals_map;
};


text:
@import uk.gov.hmrc.bforms.models.FieldValue
@import uk.gov.hmrc.bforms.views.html.localisation
@import uk.gov.hmrc.play.views.html.helpers._

@(fieldValue: FieldValue, selections: List[String])

@localisation(fieldValue.label)

    @selections.map{ selection =>
@selection
 }


text:
require File.dirname(__FILE__) + '/../capistrano-helpers' if ! defined?(CapistranoHelpers)

CapistranoHelpers.with_configuration do

  namespace :deploy do
    desc "Install gems on the remote server using Bundler."
    task :bundler do
      run "sudo chown -Rh `whoami` #{shared_path}/vendor/bundler"
      run "cd #{release_path} && bundle install --deployment --local --path #{shared_path}/vendor/bundler --without development test"
    end
  end

  after "deploy:symlink_shared", "deploy:bundler"

end


text:
<?php
/*

	Module: Router engine - modified AltoRouter
	Version: 1.0
	Author: Anthonius, apitak(at)softpae.com

*/

class AltoRouter {

	/**
	 * @var array Array of all routes (incl. named routes).
	 */
	protected $routes = array();

	/**
	 * @var array Array of all named routes.
	 */
	protected $namedRoutes = array();

	/**
	 * @var string Can be used to ignore leading part of the Request URL (if main file lives in subdirectory of host)
	 */
	protected $basePath = '';

	/**
	 * @var array Array of default match types (regex helpers)
	 */
	protected $matchTypes = array(
		'i'  => '[0-9]++',
		'a'  => '[0-9A-Za-z]++',
		'h'  => '[0-9A-Fa-f]++',
		'*'  => '.+?',
		'**' => '.++',
		''   => '[^/\.]++'
	);

	/**
	  * Create router in one call from config.
	  *
	  * @param array $routes
	  * @param string $basePath
	  * @param array $matchTypes
	  */
	public function __construct( $routes = array(), $basePath = '', $matchTypes = array() ) {
		$this->addRoutes($routes);
		$this->setBasePath($basePath);
		$this->addMatchTypes($matchTypes);
	}

	/**
	 * Retrieves all routes.
	 * Useful if you want to process or display routes.
	 * @return array All routes.
	 */
	public function getRoutes() {
		return $this->routes;
	}

	/**
	 * Add multiple routes at once from array in the following format:
	 *
	 *   $routes = array(
	 *      array($method, $route, $target, $name)
	 *   );
	 *
	 * @param array $routes
	 * @return void
	 * @author Koen Punt
	 * @throws Exception
	 */
	public function addRoutes($routes){
		if(!is_array($routes) && !$routes instanceof Traversable) {
			throw new \Exception('Routes should be an array or an instance of Traversable');
		}
		foreach($routes as $route) {
			call_user_func_array(array($this, 'map'), $route);
		}
	}

	/**
	 * Set the base path.
	 * Useful if you are running your application from a subdirectory.
	 */
	public function setBasePath($basePath) {
		$this->basePath = $basePath;
	}

	/**
	 * Add named match types. It uses array_merge so keys can be overwritten.
	 *
	 * @param array $matchTypes The key is the name and the value is the regex.
	 */
	public function addMatchTypes($matchTypes) {
		$this->matchTypes = array_merge($this->matchTypes, $matchTypes);
	}

	/**
	 * Map a route to a target
	 *
	 * @param string $method One of 5 HTTP Methods, or a pipe-separated list of multiple HTTP Methods (GET|POST|PATCH|PUT|DELETE)
	 * @param string $route The route regex, custom regex must start with an @. You can use multiple pre-set regex filters, like [i:id]
	 * @param mixed $target The target where this route should point to. Can be anything.
	 * @param string $name Optional name of this route. Supply if you want to reverse route this url in your application.
	 * @throws Exception
	 */
	public function map($method, $route, $target, $name = null) {

		//$regex = $this->compileRoute($route);
		//$this->routes[] = array($method, $route, $target, $name, $regex);
		$this->routes[] = array($method, $route, $target, $name);

		if($name) {
			if(isset($this->namedRoutes[$name])) {
				throw new \Exception("Can not redeclare route '{$name}'");
			} else {
				$this->namedRoutes[$name] = $route;
			}

		}

		return;
	}

	/**
	 * Reversed routing
	 *
	 * Generate the URL for a named route. Replace regexes with supplied parameters
	 *
	 * @param string $routeName The name of the route.
	 * @param array @params Associative array of parameters to replace placeholders with.
	 * @return string The URL of the route with named parameters in place.
	 * @throws Exception
	 */
	public function generate($routeName, array $params = array()) {

		// Check if named route exists
		if(!isset($this->namedRoutes[$routeName])) {
			throw new \Exception("Route '{$routeName}' does not exist.");
		}

		// Replace named parameters
		$route = $this->namedRoutes[$routeName];

		// prepend base path to route url again
		$url = $this->basePath . $route;

		if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {

			foreach($matches as $match) {
				list($block, $pre, $type, $param, $optional) = $match;

				if ($pre) {
					$block = substr($block, 1);
				}

				if(isset($params[$param])) {
					$url = str_replace($block, $params[$param], $url);
				} elseif ($optional) {
					$url = str_replace($pre . $block, '', $url);
				}
			}

		}

		return $url;
	}

	/**
	 * Match a given Request Url against stored routes
	 * @param string $requestUrl
	 * @param string $requestMethod
	 * @return array|boolean Array with route information on success, false on failure (no match).
	 */
	public function match($requestUrl = null, $requestMethod = null) {

		$params = array();
		$match = false;

		// set Request Url if it isn't passed as parameter
		if($requestUrl === null) {
			$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
		}

		// strip base path from request url
		$requestUrl = substr($requestUrl, strlen($this->basePath));

		// Strip query string (?a=b) from Request Url
		if (($strpos = strpos($requestUrl, '?')) !== false) {
			$requestUrl = substr($requestUrl, 0, $strpos);
		}

		// set Request Method if it isn't passed as a parameter
		if($requestMethod === null) {
			$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
		}

		foreach($this->routes as $handler) {
			list($methods, $route, $target, $name) = $handler;
			//list($methods, $route, $target, $name, $regex) = $handler;

			$method_match = (stripos($methods, $requestMethod) !== false);

			// Method did not match, continue to next route.
			if (!$method_match) continue;

			if ($route === '*') {
				// * wildcard (matches all)
				$match = true;
			} elseif (isset($route[0]) && $route[0] === '@') {
				// @ regex delimiter
				$pattern = '`' . substr($route, 1) . '`u';
				$match = preg_match($pattern, $requestUrl, $params) === 1;
			} elseif (($position = strpos($route, '[')) === false) {
				// No params in url, do string comparison
				//$match = strcmp($requestUrl, $route) === 0;
				$match = ($requestUrl == $route);
			} else {
				// Compare longest non-param string with url
				if (strncmp($requestUrl, $route, $position) !== 0) {
					continue;
				}
				$regex = $this->compileRoute($route);
				$match = preg_match($regex, $requestUrl, $params) === 1;
			}

			if ($match) {

				if ($params) {
					foreach($params as $key => $value) {
						if(is_numeric($key)) unset($params[$key]);
					}
				}

				return array(
					'target' => $target,
					'params' => $params,
					'name' => $name
				);
			}
		}
		return false;
	}

	/**
	 * Compile the regex for a given route (EXPENSIVE)
	 */
	private function compileRoute($route) {
		if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {

			$matchTypes = $this->matchTypes;
			foreach($matches as $match) {
				list($block, $pre, $type, $param, $optional) = $match;

				if (isset($matchTypes[$type])) {
					$type = $matchTypes[$type];
				}
				if ($pre === '.') {
					$pre = '\.';
				}

				//Older versions of PCRE require the 'P' in (?P<named>)
				$pattern = '(?:'
						. ($pre !== '' ? $pre : null)
						. '('
						. ($param !== '' ? "?P<$param>" : null)
						. $type
						. '))'
						. ($optional !== '' ? '?' : null);

				$route = str_replace($block, $pattern, $route);
			}

		}
		return "`^$route$`u";
	}
}
?>


text:
define( ['jquery', 'app/ui/mediaqueries/mediaqueries', 'app/ui/infinitescroll/infinitescroll', 'app/availability/availability', 'app/util/useragent'], function ( $, MediaQueries, InfiniteScroll, Availability, UserAgent ) {

	'use strict';

	return {
		$rotator: $( '.js-rotator-listing' ),
		$search: $( '.js-listing-search' ),
		$searchButton: $( '.js-listing-search-button' ),
		$searchSubmit: $( '.js-listing-search-submit' ),
		$sort: $( '#sortInput' ),
		queries: {
			"listing-search-medium": "screen and (max-width: 639px)"
		},
		init: function () {
			InfiniteScroll.init();
			Availability.init();
			this.bindGenericListingSortInput();
			this.bindRotator();
			this.bindListForm();
			this.bindListFormButton();
			this.bindDatepickerInput();
		},
		bindGenericListingSortInput: function () {
			this.$sort.change( function () {
				location.href = $( this ).find( 'option:selected' ).data( 'href' );
			} );
		},
		bindRotator: function () {
			if ( this.$rotator ) {
				require( ['app/ui/rotator/listing'], function ( ListingRotator ) {
					$( document ).ready( function () {
						ListingRotator.init();
					} );
				} );
			}
		},
		bindDatepickerInput: function () {
			var $dateInput = $( "#CheckInDateInput" );

			if ( !$dateInput.length ) {
				return;
			}

			if ( UserAgent.isIOS() ) {
				$dateInput.attr('type', 'date');
				return;
			}

			require(['datepicker'], function() {
				$dateInput.datepicker( { dateFormat: "yy-mm-dd" } );
			});
		},
		bindListForm: function () {
			var module = this;
			if ( this.$search ) {
				MediaQueries.register( {
					queries: this.queries["listing-search-medium"],
					shouldDegrade: true,
					match: function () {
						require( ['expandcollapse'], function () {
							$( document ).ready( function () {
								module.$search.expandCollapse();
							} );
						} );
					},
					unmatch: function () {
						require( ['expandcollapse'], function () {
							$( document ).ready( function () {
								module.$search.expandCollapse( 'destroy' );
							} );
						} );
					}
				} );
			}
		},
		bindListFormButton: function () {
			this.$searchButton.on( 'click', { module: this }, function ( event ) {
				event.preventDefault();
				var module = event.data.module;
				module.$search.find( module.$searchSubmit ).trigger( 'click' );
			} );
		}
	};

} );


text:
This directory contains CQ client library to be distributed to other repos. If
you need to modify some files in this directory, please make sure that you are
changing the canonical version of the source code and not one of the copies,
which should only be updated as a whole using Glyco (when available, see
[chromium issue 489420](http://crbug.com/489420)).

The canonical version is located at `https://chrome-internal.googlesource.com/
infra/infra_internal/+/master/commit_queue/cq_client`.

To generate `cq_pb2.py` and `cq.pb.go`, please use protoc version 2.6.1:

    cd commit_queue/cq_client
    protoc cq.proto --python_out $(pwd) --go_out $(pwd)

Additionally, please make sure to use proto3-compatible syntax, e.g. no default
values, no required fields. Ideally, we should use proto3 generator already,
however alpha version thereof is still unstable.


text:
layout: post-print
title: The endless labyrinth / El laberinto infinito / O labirinto infinito
tags: [print]
categories: [print]
description: The works of Jorge Luis Borges presented here are short texts about the infinite. / Estas obras de Jorge Luis Borges tratan temas sobre el infinito. / Estas obras de Jorge Luis Borges são textos curtos sobre o infinito.
---

[EN]    [ES]    [PT]

---

**[EN]** The works of Jorge Luis Borges presented here are short texts about the infinite. His stories enact the existing tension in our human capacity to comprehend what is  spatially, chronologically, or conceptually possible. "The Garden of Forking Paths" and "The Aleph" were first published in Victoria Ocampo's cultural magazine *Sur* in the 1940s.

---

**[ES]** Estas obras de Jorge Luis Borges tratan temas sobre el infinito. Son cuentos que manifiestan la tensión existente en nuestra capacidad humana para comprender lo que es espacial, conceptual o cronológicamente posible. "El jardín de senderos que se bifurcan" y "El aleph" fueron publicados por primera vez en la revista cultural *Sur* de Victoria Ocampo en la década de 1940.

---

**[PT]** Estas obras de Jorge Luis Borges são textos curtos sobre o infinito. Estes contos manifestam a tensão existente na nossa capacidade humana para compreender o que é espacial, conceptual ou cronologicamente possível. "O Jardim dos Caminhos que se Bifurcam" e "O Aleph" foram publicados pela primeira vez na revista cultural *Sur* de Vitoria Ocampo nos anos quarenta.


text: IntlMessageFormat.__addLocaleData({locale:"to",pluralRuleFunction:function(a,t){return"other"}});


text:
require 'capybara/rspec'
require 'capybara/poltergeist'
require 'selenium-webdriver'
require 'capybara-screenshot/rspec'

Capybara.javascript_driver = ENV['JS_DRIVER'] == "selenium" ? :selenium : :poltergeist

Capybara.default_driver = :selenium if ENV['JS_DRIVER'] == "selenium"

Capybara.register_driver :poltergeist do |app|
  # inspector:true enables poltergeist debugging with page.driver.debug
  Capybara::Poltergeist::Driver.new(app, inspector: true)
end

Capybara.register_driver :selenium do |app|
  profile = Selenium::WebDriver::Firefox::Profile.new

	Capybara::Selenium::Driver.new(app, {:browser => :firefox,
	                                     :profile => ENV['DEFAULT_PROFILE'] ? 'default' : profile } )
end

# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In
# order to ease the transition to Capybara we set the default here. If you'd
# prefer to use XPath just remove this line and adjust any selectors in your
# steps to use the XPath syntax.
Capybara.default_selector = :css
Capybara.ignore_hidden_elements = true


text:
import type { Container } from "../../../Container";
import { IExternalInteractor } from "../../../Interfaces/IExternalInteractor";
export declare class Grabber implements IExternalInteractor {
    private readonly container;
    constructor(container: Container);
    isEnabled(): boolean;
    reset(): void;
    interact(): void;
}


text:
using System.Threading.Tasks;
using Orleans.Runtime;

namespace UnitTests.GrainInterfaces
{
    public interface ITestExtension : IGrainExtension
    {
        Task<string> CheckExtension_1();

        Task<string> CheckExtension_2();
    }

    public interface IGenericTestExtension<T> : IGrainExtension
    {
        Task<T> CheckExtension_1();

        Task<string> CheckExtension_2();
    }

    public interface ISimpleExtension : IGrainExtension
    {
        Task<string> CheckExtension_1();
    }

    public interface IAutoExtension : IGrainExtension
    {
        Task<string> CheckExtension();
    }
}


text:
import { ParameterModel } from './parameter.model';

export class OutputRouterModel {
    constructor(public id: number,
        public name: string,
        public settings: ParameterModel[]
    ) {
    }
}


text:
#ifndef GRPC_INTERNAL_CORE_IOMGR_ENDPOINT_PAIR_H
#define GRPC_INTERNAL_CORE_IOMGR_ENDPOINT_PAIR_H

#include "src/core/iomgr/endpoint.h"

typedef struct {
  grpc_endpoint *client;
  grpc_endpoint *server;
} grpc_endpoint_pair;

grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(size_t read_slice_size);

#endif  /* GRPC_INTERNAL_CORE_IOMGR_ENDPOINT_PAIR_H */


text:
FROM seandavi/icat:4.1.4
MAINTAINER danb@renci.org

RUN apt-get update ; apt-get upgrade -y

#set up tomcat and apache
RUN apt-get -y install openjdk-7-jdk
RUN update-java-alternatives -s java-1.7.0-openjdk-amd64

RUN mkdir /usr/share/tomcat7
RUN mkdir /usr/share/tomcat7/common
RUN mkdir /usr/share/tomcat7/common/classes
RUN mkdir /usr/share/tomcat7/server
RUN mkdir /usr/share/tomcat7/server/classes
RUN mkdir /usr/share/tomcat7/shared
RUN mkdir /usr/share/tomcat7/shared/classes

RUN apt-get -y install tomcat7 apache2
ADD ./server.xml /etc/tomcat7/server.xml
RUN mkdir /etc/idrop-web
ADD ./idrop-web-config2.groovy /etc/idrop-web/idrop-web-config2.groovy
RUN rm -rf /var/lib/tomcat7/webapps/ROOT
RUN wget -O /var/lib/tomcat7/webapps/ROOT.war http://people.renci.org/~danb/FOR_DEMOS/iDrop-Web-2/idrop-web2.war
ADD ./ajp.apache /etc/apache2/sites-available/ajp.apache.conf
RUN a2enmod proxy_ajp
RUN a2dissite 000-default
RUN a2ensite ajp.apache

ADD ./bootstrap.sh /opt/irods/bootstrap.sh
ADD ./update-idw-config.sh /opt/irods/update-idw-config.sh
ADD ./tcstart.sh /opt/irods/tcstart.sh
RUN chmod a+x /opt/irods/*.sh

# set defaults for runtime variables that will be loaded into idrop-web-config2.groovy
ENV DOCKER_PORT80=8552
ENV DOCKER_HOSTNAME=localhost

EXPOSE 80
ENTRYPOINT [ "/opt/irods/bootstrap.sh" ]


text:
package com.camnter.smartsave.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author CaMnter
 */

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface Save {

    int value() default 0;

}


text:
#ifndef __GTK_CSS_PROVIDER_H__
#define __GTK_CSS_PROVIDER_H__

#include <gio/gio.h>
#include <gtk/gtkcsssection.h>

G_BEGIN_DECLS

#define GTK_TYPE_CSS_PROVIDER         (gtk_css_provider_get_type ())
#define GTK_CSS_PROVIDER(o)           (G_TYPE_CHECK_INSTANCE_CAST ((o), GTK_TYPE_CSS_PROVIDER, GtkCssProvider))
#define GTK_CSS_PROVIDER_CLASS(c)     (G_TYPE_CHECK_CLASS_CAST    ((c), GTK_TYPE_CSS_PROVIDER, GtkCssProviderClass))
#define GTK_IS_CSS_PROVIDER(o)        (G_TYPE_CHECK_INSTANCE_TYPE ((o), GTK_TYPE_CSS_PROVIDER))
#define GTK_IS_CSS_PROVIDER_CLASS(c)  (G_TYPE_CHECK_CLASS_TYPE    ((c), GTK_TYPE_CSS_PROVIDER))
#define GTK_CSS_PROVIDER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS  ((o), GTK_TYPE_CSS_PROVIDER, GtkCssProviderClass))

/**
 * GTK_CSS_PROVIDER_ERROR:
 *
 * Domain for #GtkCssProvider errors.
 */
#define GTK_CSS_PROVIDER_ERROR (gtk_css_provider_error_quark ())

/**
 * GtkCssProviderError:
 * @GTK_CSS_PROVIDER_ERROR_FAILED: Failed.
 * @GTK_CSS_PROVIDER_ERROR_SYNTAX: Syntax error.
 * @GTK_CSS_PROVIDER_ERROR_IMPORT: Import error.
 * @GTK_CSS_PROVIDER_ERROR_NAME: Name error.
 * @GTK_CSS_PROVIDER_ERROR_DEPRECATED: Deprecation error.
 * @GTK_CSS_PROVIDER_ERROR_UNKNOWN_VALUE: Unknown value.
 *
 * Error codes for %GTK_CSS_PROVIDER_ERROR.
 */
typedef enum
{
  GTK_CSS_PROVIDER_ERROR_FAILED,
  GTK_CSS_PROVIDER_ERROR_SYNTAX,
  GTK_CSS_PROVIDER_ERROR_IMPORT,
  GTK_CSS_PROVIDER_ERROR_NAME,
  GTK_CSS_PROVIDER_ERROR_DEPRECATED,
  GTK_CSS_PROVIDER_ERROR_UNKNOWN_VALUE
} GtkCssProviderError;

GDK_AVAILABLE_IN_ALL
GQuark gtk_css_provider_error_quark (void);

typedef struct _GtkCssProvider GtkCssProvider;
typedef struct _GtkCssProviderClass GtkCssProviderClass;
typedef struct _GtkCssProviderPrivate GtkCssProviderPrivate;

struct _GtkCssProvider
{
  GObject parent_instance;
  GtkCssProviderPrivate *priv;
};

struct _GtkCssProviderClass
{
  GObjectClass parent_class;

  void (* parsing_error)                        (GtkCssProvider  *provider,
                                                 GtkCssSection   *section,
                                                 const GError *   error);

  /* Padding for future expansion */
  void (*_gtk_reserved2) (void);
  void (*_gtk_reserved3) (void);
  void (*_gtk_reserved4) (void);
};

GDK_AVAILABLE_IN_ALL
GType gtk_css_provider_get_type (void) G_GNUC_CONST;

GDK_AVAILABLE_IN_ALL
GtkCssProvider * gtk_css_provider_new (void);

GDK_AVAILABLE_IN_3_2
char *           gtk_css_provider_to_string      (GtkCssProvider  *provider);

GDK_AVAILABLE_IN_ALL
gboolean         gtk_css_provider_load_from_data (GtkCssProvider  *css_provider,
                                                  const gchar     *data,
                                                  gssize           length,
                                                  GError         **error);
GDK_AVAILABLE_IN_ALL
gboolean         gtk_css_provider_load_from_file (GtkCssProvider  *css_provider,
                                                  GFile           *file,
                                                  GError         **error);
GDK_AVAILABLE_IN_ALL
gboolean         gtk_css_provider_load_from_path (GtkCssProvider  *css_provider,
                                                  const gchar     *path,
                                                  GError         **error);

GDK_AVAILABLE_IN_3_16
void             gtk_css_provider_load_from_resource (GtkCssProvider *css_provider,
                                                      const gchar    *resource_path);

GDK_AVAILABLE_IN_ALL
GtkCssProvider * gtk_css_provider_get_default (void);

GDK_AVAILABLE_IN_ALL
GtkCssProvider * gtk_css_provider_get_named (const gchar *name,
                                             const gchar *variant);

G_END_DECLS

#endif /* __GTK_CSS_PROVIDER_H__ */


text:
package aserg.gtf.task;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.lang3.StringUtils;

import aserg.gtf.model.LogCommitInfo;
import aserg.gtf.util.LineInfo;

public class NewAliasHandler{
	List<LineInfo> fileAliases;
	public NewAliasHandler(List<LineInfo> list) {
		this.fileAliases = list;
	}
	Map<String, List<LogCommitInfo>> devUsernameMap;
	Map<String, List<LogCommitInfo>> devNameMap;

	public Map<String, LogCommitInfo> execute(String repositoryName, Map<String, LogCommitInfo> commits){
		setUsername(commits);
		devUsernameMap = new HashMap<String, List<LogCommitInfo>>();

		for (LogCommitInfo commit : commits.values()) {
			String commitUsername = commit.getUserName();
			if (!devUsernameMap.containsKey(commitUsername))
				devUsernameMap.put(commitUsername, new ArrayList<LogCommitInfo>());
			devUsernameMap.get(commitUsername).add(commit);
		}

		//Set<String> devNames = new HashSet<String>();
		devNameMap = new HashMap<String, List<LogCommitInfo>>();
		for (LogCommitInfo commit : commits.values()) {
			//devNames.add(commit.getMainName());
			String commitDevName = commit.getNormMainName();
			if (!devNameMap.containsKey(commitDevName))
				devNameMap.put(commitDevName, new ArrayList<LogCommitInfo>());
			devNameMap.get(commitDevName).add(commit);
		}
		unifyUsernameByName();
		if (fileAliases!=null)
			treatFileAlias();
		return commits;
	}

	private void setUsername(Map<String, LogCommitInfo> commits) {
		for (LogCommitInfo commit : commits.values()) {
			if (!commit.getNormMainEmail().isEmpty())
				commit.setUserName(commit.getNormMainEmail());
			else if (!commit.getMainName().isEmpty())
				commit.setUserName(commit.getNormMainName());
			else{
				System.err.println("Empty usernam in commit  " + commit.getSha());
				commit.setUserName("");
			}
		}

	}

	private void treatFileAlias() {
		for (LineInfo info : fileAliases) {
			String rep = info.getRepositoryName();
			String dev1 = info.getValues().get(0);
			String dev2 = info.getValues().get(1);
			String usernameDev1 = devNameMap.get(dev1.toUpperCase()).get(0).getUserName();
			String usernameDev2 = devNameMap.get(dev2.toUpperCase()).get(0).getUserName();

			String newUsername = usernameDev1.contains(usernameDev2)?usernameDev1: (usernameDev2.contains(usernameDev1)?usernameDev2:usernameDev1+"$$"+usernameDev2);

			for (LogCommitInfo commit : devUsernameMap.get(usernameDev1)) {
				if (!commit.getUserName().equals(usernameDev2)){
					setNewUsername(commit, newUsername);
					//commit.setUserName(newUsername);
				}

			}
			for (LogCommitInfo commit : devUsernameMap.get(usernameDev2)) {
				if (!commit.getUserName().equals(usernameDev1)){
					setNewUsername(commit, newUsername);
					//commit.setUserName(newUsername);
				}

			}

		}

	}

	private void printAliases(Map<String, List<String>> aliases) {
		for (Entry<String, List<String>> entry : aliases.entrySet()) {
			for (String alias : entry.getValue()) {
				System.out.println(entry.getKey() + ";" + alias);
			}
		}

	}

	/** Treat different names for the same e-mail case */
	private void unifyUsernameByEmail(Map<String, List<LogCommitInfo>> usernameMap) {
		for (Entry<String, List<LogCommitInfo>> entry : usernameMap.entrySet()) {
			List<String> names = getNamesList(entry.getValue());
			String newUserName = names.get(0);
			if (names.size()>1)
				newUserName = getNewName(names);
			for (LogCommitInfo commit : entry.getValue()) {
				commit.setUserName(newUserName);
			}
		}

	}

	private List<String> getNamesList(Collection<LogCommitInfo> commits) {
		HashSet<String> nameSet = new HashSet<String>();
		List<String> names =  new ArrayList<String>();
		for (LogCommitInfo commit : commits) {
			String simplifyedName = commit.getNormMainName().replace(" ", "");
			if (!nameSet.contains(simplifyedName)){
				nameSet.add(simplifyedName);
				names.add(commit.getMainName());
			}
		}
		return names;
	}

	private String getNewName(Collection<String> names) {
		String newName = "";
		for (String name : names) {
			if (!newName.isEmpty())
				newName += "**";
			newName += name;
		}
		return newName;
	}

	/** Treat similar name aliases */
	private void unifyUsernameByName() {
		for (Entry<String, List<LogCommitInfo>> entry : devNameMap.entrySet()) {
			// Avoid to group developers with empty name
			if (!entry.getKey().isEmpty()) {
				List<String> userNames = getUserNamesList(entry.getValue());
				if (userNames.size() > 1) {
					String newUsername = getNewUserName(userNames);
					for (LogCommitInfo commit : entry.getValue()) {
						setNewUsername(commit, newUsername);

						//commit.setUserName(newUsername);
					}
				}
			}
		}

	}

	private void setNewUsername(LogCommitInfo commit, String newUsername) {
		List<LogCommitInfo> listCommits = devUsernameMap.get(commit.getUserName());
		devUsernameMap.remove(commit.getUserName());
		for (LogCommitInfo commitAux : listCommits) {
			commitAux.setUserName(newUsername);
		}

		if (!devUsernameMap.containsKey(newUsername))
			devUsernameMap.put(newUsername, listCommits);
		else
			devUsernameMap.get(newUsername).addAll(listCommits);
	}

	private List<String> getUserNamesList(Collection<LogCommitInfo> commits) {
		Set<String> userNameSet = new HashSet<String>();
		for (LogCommitInfo commit : commits) {
			userNameSet.add(commit.getUserName());
		}
		return new ArrayList<String>(userNameSet);
	}

	private String getNewUserName(Collection<String> names) {
		String newName = "";
		for (String name : names) {
			if (!newName.isEmpty())
				newName += "||";
			newName += name;
		}
		return newName;
	}

	private static Map<String, List<String>> findAliases(List<String> allDevelopers, int distance, int minSize) {
		int newDistance = distance;
		List<String> copyList =  new CopyOnWriteArrayList<String>(allDevelopers);
		Map<String, List<String>> aliases =  new HashMap<String, List<String>>();
		for (String developer1 : copyList) {
			copyList.remove (developer1);
			for (String developer2 : copyList) {
				if(developer1.length()>=minSize){
					int localDistance = StringUtils.getLevenshteinDistance(convertToUTFLower(developer1), convertToUTFLower(developer2));
					if (distance == -1){
						newDistance = developer1.split(" ").length;
					}
					if (!developer1.equals(developer2) && localDistance<=newDistance){
						if(!aliases.containsKey(developer1))
							aliases.put(developer1, new ArrayList<String>());
						aliases.get(developer1).add(developer2);
						copyList.remove(developer2);
					}
				}
			}
		}
		return aliases;
	}

	private static CharSequence convertToUTFLower(String str) {
		String ret = null;
		try {
			ret = new String(str.getBytes("ISO-8859-1"), "UTF-8");
		}
		catch (java.io.UnsupportedEncodingException e) {
			return null;
		}
		return ret.toLowerCase();
	}

	private class DevIdentification{
		private String name;
		private String email;
		private String username;

		public DevIdentification(String name, String email, String username) {
			super();
			this.name = name;
			this.email = email;
			this.username = username;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getUsername() {
			return username;
		}
		public void setUsername(String username) {
			this.username = username;
		}
		public String getEmail() {
			return email;
		}
		public void setEmail(String email) {
			this.email = email;
		}

	}

}


text:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using RailDataEngine.Services.Authentication.Data;
using RailDataEngine.Services.Authentication.Entity;

namespace RailDataEngine.Services.Authentication.Migrations
{
    using System.Data.Entity.Migrations;

    internal sealed class Configuration : DbMigrationsConfiguration<AuthenticationContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(AuthenticationContext context)
        {
            var manager = new UserManager<RailDataEngineUser>(new UserStore<RailDataEngineUser>(new AuthenticationContext()));

            var user = new RailDataEngineUser
            {
                UserName = "Default",
                Email = "Default@mymail.com",
                EmailConfirmed = true
            };

            manager.Create(user, "Password12!");
        }
    }
}


text:
<?php
$this->pageTitle = Yii::app()->name . ' - Wybierz wpis portfolio';
$this->breadcrumbs = array(
    'Portfolio' => array('index'),
    'Wybierz wpis portfolio'
);
?>

    <?php
    $form = $this->beginWidget('bootstrap.widgets.BsActiveForm', array(
        'id' => 'chooseportfolio-form',
        'enableClientValidation' => true,
        'clientOptions' => [
            'validateOnSubmit' => true,
        ],
    ));
    ?>

<?php echo $form->dropDownListControlGroup($model, 'id', $portfolios); ?>

<?php echo BsHtml::submitButton('Wybierz', array('color' => BSHtml::BUTTON_COLOR_INFO)); ?>

    <?php
    $this->endWidget();
    ?>


text:
 package com.indeed.imhotep.io;

import com.google.common.io.ByteStreams;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author jsgroth
 */
public final class SubInputStream extends InputStream {
    private static final int INITIAL_BUFFER_SIZE = 65536;

    private final InputStream is;

    private byte[] bytes;
    private int currentIndex;
    private int currentBlockSize;
    private boolean done;

    public SubInputStream(InputStream is) {
        this.is = is;
        bytes = new byte[INITIAL_BUFFER_SIZE];
    }

    @Override
    public int read() throws IOException {
        if (done) return -1;

        if (currentIndex == currentBlockSize) {
            currentBlockSize = Streams.readInt(is);
            currentIndex = 0;
            if (currentBlockSize == -1) {
                throw new EOFException("unexpected end of stream");
            } else if (currentBlockSize == 0) {
                done = true;
                return -1;
            }
            if (bytes.length < currentBlockSize) {
                bytes = new byte[Math.max(currentBlockSize, bytes.length*2)];
            }
            ByteStreams.readFully(is, bytes, 0, currentBlockSize);
        }
        return bytes[currentIndex++] & 0xFF;
    }

    @Override
    public int read(byte[] b) throws IOException {
        return read(b, 0, b.length);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (done) return -1;

        int count = 0;
        while (len > 0) {
            int x = read();
            if (x == -1) {
                return count;
            }

            b[off++] = (byte)x;
            --len;
            ++count;
        }

        return count;
    }
}


text:
declare module '@salesforce/design-system-react/components/date-picker/private/calendar' {
	import React from 'react';
	type Props = {
		/**
		 * Three letter abbreviations of the days of the week, starting on Sunday.
		 */
		abbreviatedWeekDayLabels: any[] /*.isRequired*/;
		/**
		 * dateDisabled() takes a date as input argument, returns true if given date should be disabled, otherwise returns false.
		 */
		dateDisabled?: (v: any) => any;
		/**
		 * HTML id for component
		 */
		id: string /*.isRequired*/;
		/**
		 * Date used to create calendar that is displayed. This is typically the initial day focused when using the keyboard navigation. Focus will be set to this date if available.
		 */
		initialDateForCalendarRender: Date /*.isRequired*/;
		/**
		 * Makes Monday the first day of the week
		 */
		isIsoWeekday?: boolean;
		/**
		 * Triggered when the keyboard moves focus off the calendar.
		 */
		onCalendarBlur: (v: any) => any /*.isRequired*/;
		/**
		 * Displayed calendar has changed or re-rendered
		 */
		onChangeMonth: (v: any) => any /*.isRequired*/;
		/**
		 * Internal callback that will eventually trigger when the keyboard moves focus on the calendar. `{date: [Date object], formattedDate: [string]}`.
		 */
		onRequestInternalFocusDate?: (v: any) => any;
		/**
		 * Triggered when the calendar is cancelled.
		 */
		onRequestClose: (v: any) => any /*.isRequired*/;
		/**
		 * Triggered when a date on the calendar is clicked.
		 */
		onSelectDate: (v: any) => any /*.isRequired*/;
		/**
		 * Currently selected date. This should be present in the input field.
		 */
		selectedDate?: Date;
		/**
		 * Component reference / DOM node for selected day.
		 */
		selectedDateRef?: (v: any) => any;
		/**
		 * Label of shortcut to jump to today within the calendar. This is also used for assistive text on today's date.
		 */
		todayLabel: string /*.isRequired*/;
		/**
		 * For keyboard navigation. Listens for key presses on the last focusable DOM Node, the "Today" link, so that dialog focus can be trapped.
		 */
		onLastFocusableNodeKeyDown?: (v: any) => any;
		/**
		 * Callback that passes in the DOM reference of the Today `a` DOM node within this component. Primary use is to allow `focus` to be called. You should still test if the node exists, since rendering is asynchronous. `buttonRef={(component) => { if(component) console.log(component); }}`
		 */
		todayRef?: (v: any) => any;
		/**
		 * Names of the seven days of the week, starting on Sunday.
		 */
		weekDayLabels: any[] /*.isRequired*/;
	};

	function Component(props: Props): JSX.Element;
	export default Component;
}


text:
<?php

namespace OAuthTest\Unit\OAuth2\Service;

use OAuth\Common\Token\TokenInterface;
use OAuth\OAuth2\Service\Dailymotion;

class DailymotionTest extends \PHPUnit_Framework_TestCase {

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 */
	public function testConstructCorrectInterfaceWithoutCustomUri()
	{
		$service = new Dailymotion(
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
		);

		$this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\ServiceInterface', $service);
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 */
	public function testConstructCorrectInstanceWithoutCustomUri()
	{
		$service = new Dailymotion(
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
		);

		$this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service);
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 */
	public function testConstructCorrectInstanceWithCustomUri()
	{
		$service = new Dailymotion(
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface'),
			[],
			'some-url'
		);

		$this->assertInstanceOf('\\OAuth\\OAuth2\\Service\\AbstractService', $service);
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 * @covers OAuth\OAuth2\Service\Dailymotion::getAuthorizationEndpoint
	 */
	public function testGetAuthorizationEndpoint()
	{
		$service = new Dailymotion(
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
		);

		$this->assertSame('https://api.dailymotion.com/oauth/authorize', (string) $service->getAuthorizationEndpoint());
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 * @covers OAuth\OAuth2\Service\Dailymotion::getAccessTokenEndpoint
	 */
	public function testGetAccessTokenEndpoint()
	{
		$service = new Dailymotion(
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
		);

		$this->assertSame('https://api.dailymotion.com/oauth/token', (string) $service->getAccessTokenEndpoint());
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 * @covers OAuth\OAuth2\Service\Dailymotion::getAuthorizationMethod
	 */
	public function testGetAuthorizationMethod()
	{
		$token = $this->getMock('\\OAuth\\OAuth2\\Token\\TokenInterface');
		$token->expects($this->once())->method('getEndOfLife')->will($this->returnValue(TokenInterface::EOL_NEVER_EXPIRES));
		$token->expects($this->once())->method('getAccessToken')->will($this->returnValue('foo'));

		$storage = $this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface');
		$storage->expects($this->once())->method('retrieveAccessToken')->will($this->returnValue($token));

		/** @var Dailymotion|\PHPUnit_Framework_MockObject_MockObject $service */
		$service = $this->getMock('\\OAuth\\OAuth2\\Service\\Dailymotion', ['httpRequest'], [
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$storage
		]);

		$service->expects($this->once())->method('httpRequest')->will($this->returnArgument(2));

		$headers = $service->request('https://pieterhordijk.com/my/awesome/path');

		$this->assertTrue(array_key_exists('Authorization', $headers));
		$this->assertTrue(in_array('OAuth foo', $headers, TRUE));
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 * @covers OAuth\OAuth2\Service\Dailymotion::parseAccessTokenResponse
	 */
	public function testParseAccessTokenResponseThrowsExceptionOnNulledResponse()
	{
		/** @var Dailymotion|\PHPUnit_Framework_MockObject_MockObject $service */
		$service = $this->getMock('\\OAuth\\OAuth2\\Service\\Dailymotion', ['httpRequest'], [
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
		]);

		$service->expects($this->once())->method('httpRequest')->will($this->returnValue(NULL));

		$this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException');

		$service->requestAccessToken('foo');
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 * @covers OAuth\OAuth2\Service\Dailymotion::parseAccessTokenResponse
	 */
	public function testParseAccessTokenResponseThrowsExceptionOnErrorDescription()
	{
		/** @var Dailymotion|\PHPUnit_Framework_MockObject_MockObject $service */
		$service = $this->getMock('\\OAuth\\OAuth2\\Service\\Dailymotion', ['httpRequest'], [
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
		]);

		$service->expects($this->once())->method('httpRequest')->will($this->returnValue('error_description=some_error'));

		$this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException');

		$service->requestAccessToken('foo');
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 * @covers OAuth\OAuth2\Service\Dailymotion::parseAccessTokenResponse
	 */
	public function testParseAccessTokenResponseThrowsExceptionOnError()
	{
		/** @var Dailymotion|\PHPUnit_Framework_MockObject_MockObject $service */
		$service = $this->getMock('\\OAuth\\OAuth2\\Service\\Dailymotion', ['httpRequest'], [
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
		]);

		$service->expects($this->once())->method('httpRequest')->will($this->returnValue('error=some_error'));

		$this->setExpectedException('\\OAuth\\Common\\Http\\Exception\\TokenResponseException');

		$service->requestAccessToken('foo');
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 * @covers OAuth\OAuth2\Service\Dailymotion::parseAccessTokenResponse
	 */
	public function testParseAccessTokenResponseValidWithoutRefreshToken()
	{
		/** @var Dailymotion|\PHPUnit_Framework_MockObject_MockObject $service */
		$service = $this->getMock('\\OAuth\\OAuth2\\Service\\Dailymotion', ['httpRequest'], [
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
		]);

		$service->expects($this->once())->method('httpRequest')->will($this->returnValue('{"access_token":"foo","expires_in":"bar"}'));

		$this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo'));
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 * @covers OAuth\OAuth2\Service\Dailymotion::parseAccessTokenResponse
	 */
	public function testParseAccessTokenResponseValidWithRefreshToken()
	{
		/** @var Dailymotion|\PHPUnit_Framework_MockObject_MockObject $service */
		$service = $this->getMock('\\OAuth\\OAuth2\\Service\\Dailymotion', ['httpRequest'], [
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
		]);

		$service->expects($this->once())->method('httpRequest')->will($this->returnValue('{"access_token":"foo","expires_in":"bar","refresh_token":"baz"}'));

		$this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo'));
	}

	/**
	 * @covers OAuth\OAuth2\Service\Dailymotion::__construct
	 * @covers OAuth\OAuth2\Service\Dailymotion::getExtraOAuthHeaders
	 */
	public function testGetExtraOAuthHeaders()
	{
		/** @var Dailymotion|\PHPUnit_Framework_MockObject_MockObject $service */
		$service = $this->getMock('\\OAuth\\OAuth2\\Service\\Dailymotion', ['httpRequest'], [
			$this->getMock('\\OAuth\\Common\\Consumer\\CredentialsInterface'),
			$this->getMock('\\Buzz\\Browser'),
			$this->getMock('\\OAuth\\Common\\Storage\\TokenStorageInterface')
		]);

		$service->expects($this->once())->method('httpRequest')->will($this->returnCallback(function ($uri, $params,
			$extraHeaders)
		{
			\PHPUnit_Framework_Assert::assertTrue(array_key_exists('Accept', $extraHeaders));
			\PHPUnit_Framework_Assert::assertTrue(in_array('application/json', $extraHeaders, TRUE));

			return '{"access_token":"foo","expires_in":"bar"}';
		}));

		$this->assertInstanceOf('\\OAuth\\OAuth2\\Token\\StdOAuth2Token', $service->requestAccessToken('foo'));
	}
}


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Stucom Mail</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
        <link href="cssLogin.css" rel="stylesheet" type="text/css"/>

								Login

								Register

                		<form id="login-form" action="login.php" method="post" role="form" style="display: block;">

                				<input type="text" name="username" class="form-control" placeholder="Username" maxlength="10" required autofocus>

                				<input type="password" name="password" class="form-control" placeholder="Password" maxlength="200" required>

                			    	<input type="checkbox" value="remember-me"> Remember me

               							<button class="btn btn-lg btn-primary btn-block" type="submit" name="login-submit"> Sign in</button>

                		</form>
                		<form id="register-form" action="login.php" method="post" role="form" style="display: none;">

										<input type="text" name="username" id="username" class="form-control" placeholder="Username" maxlength="10" required>

										<input type="password" name="password" id="password" class="form-control" placeholder="Password" maxlength="200" required>

										<input type="password" name="confirm-password" id="confirm-password" class="form-control" placeholder="Confirm Password" maxlength="200" required>

										<input type="text" name="name" id="name" class="form-control" placeholder="Name" maxlength="20" required>

										<input type="text" name="surname" id="surname" class="form-control" placeholder="Surname" maxlength="60" required>

												<input type="submit" name="register-submit" id="register-submit" class="form-control btn btn-register" value="Register Now">

								</form>


text:
namespace Platform
{
	/// <summary>
	/// An interface for objects that can be refreshed.
	/// </summary>
	public interface IRefreshable
	{
		/// <summary>
		/// Refreshes the current object (what refresh means depends on the object).
		/// </summary>
		void Refresh();
	}
}


text:
package events

import (
	"database/sql"
	_ "database/sql"
	json2 "encoding/json"
	"errors"
	"github.com/julienschmidt/httprouter"
	_ "github.com/lib/pq"
	"mynsb-api/internal/db"
	"mynsb-api/internal/quickerrors"
	"mynsb-api/internal/util"
	"net/http"
	"strconv"
)

// RETRIEVAL FUNCTIONS

// getWithID takes an eventID and a db and queries the database for an event with the matching event ID
func getWithID(eventID int, db *sql.DB) (Event, error) {
	eventArr, err := performRequest(db, "SELECT * FROM events WHERE event_id = $1", eventID)
	return eventArr[0], err
}

// getBetween returns all events between two times
func getBetween(db *sql.DB, startStr string, endStr string) ([]Event, error) {

	start, parseErrorOne := util.ParseDate(startStr)
	end, parseErrorTwo := util.ParseDate(endStr)

	if parseErrorOne != nil || parseErrorTwo != nil {
		return []Event{}, errors.New("invalid date")
	}

	return performRequest(db, "SELECT * FROM events WHERE event_start BETWEEN $1::TIMESTAMP AND $2::TIMESTAMP", start, end)
}

// getAll returns all events currently in the database
func getAll(db *sql.DB) ([]Event, error) {
	return performRequest(db, "SELECT * FROM events")
}

// UTILITY FUNCTIONS

// performRequest takes a simple request and a string of parameters, executes the query and returns the result
func performRequest(db *sql.DB, query string, args ...interface{}) ([]Event, error) {

	rows, err := db.Query(query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var allEvents []Event

	for rows.Next() {
		// Parse data into an event object and append it to the allEvents structure
		event := Event{}
		event.ScanFrom(rows)
		allEvents = append(allEvents, event)
	}

	return allEvents, nil
}

// parseRequest takes an http request and determines what type of request they are performing
func parseRequest(r *http.Request) (string, map[string]string) {

	eventID := r.URL.Query().Get("Event_ID")
	start := r.URL.Query().Get("Start")
	end := r.URL.Query().Get("End")

	// Determine what type of request the user wants
	requestType := ""
	switch {
	case util.IsSet(start, end):
		requestType = "Range"
		break
	case util.IsSet(eventID):
		requestType = "getWithID"
		break
	default:
		requestType = "getAll"
	}

	return requestType, map[string]string{
		"eventID": eventID,
		"start": start,
		"end": end,
	}
}

// HTTP HANDLERS

// EventRetrievalHandler returns all events according to a http request
func EventRetrievalHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {

	db.Conn("student")
	defer db.DB.Close()

	requestType, params := parseRequest(r)
	var response []byte

	// Determine which function is being requested
	switch requestType {
	case "getAll":
		json, _ := getAll(db.DB)
		response, _ = json2.Marshal(json)
		break

	case "getWithID":
		// convert the eventID to an integer
		eventId, _ := strconv.Atoi(params["eventID"])
		json, _ := getWithID(eventId, db.DB)
		response, _ = json2.Marshal(json)
		break

	case "Range":
		json, _ := getBetween(db.DB, params["start"], params["end"])
		response, _ = json2.Marshal(json)
		break

	default:
		quickerrors.NotFound(w)
		return
	}

	util.HTTPResponse(200, "OK", string(response), "Result: ", w)
}


text:
from os import pardir
from os.path import abspath, join, dirname, realpath

DEFAULT_TESTS_DIR = abspath(join((dirname(realpath(__file__))), pardir, 'tests'))

del pardir, abspath, join, dirname, realpath


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>CSS Selectors :last-of-type</title>
<link rel="help" href="https://drafts.csswg.org/selectors-4/#the-last-of-type-pseudo">

Whitespace nodes should be ignored.

Thre is another child element of the same type.

There is a posterior child element of another type.

A next element of the parent should not affect.

The parent element of the same type should not affect.

A child of the next element should not affect.

The first child element of the same
type should not match.

The first child element of the same
type should not match, the last child has a case-different tag name.


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

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

namespace Amazon.SimpleEmail.Model
{
    ///
    /// Message-related information to include in the Delivery Status Notification (DSN) when
    /// an email that Amazon SES receives on your behalf bounces.
    ///
    ///
    /// <para>
    /// For information about receiving email through Amazon SES, see the Amazon
    /// SES Developer Guide.
    /// </para>
    ///
    public partial class MessageDsn
    {
        private DateTime? _arrivalDate;
        private List<ExtensionField> _extensionFields = new List<ExtensionField>();
        private string _reportingMta;

        ///
        /// Gets and sets the property ArrivalDate.
        /// <para>
        /// When the message was received by the reporting mail transfer agent (MTA), in RFC
        /// 822 date-time format.
        /// </para>
        ///
        public DateTime ArrivalDate
        {
            get { return this._arrivalDate.GetValueOrDefault(); }
            set { this._arrivalDate = value; }
        }

        // Check to see if ArrivalDate property is set
        internal bool IsSetArrivalDate()
        {
            return this._arrivalDate.HasValue;
        }

        ///
        /// Gets and sets the property ExtensionFields.
        /// <para>
        /// Additional X-headers to include in the DSN.
        /// </para>
        ///
        public List<ExtensionField> ExtensionFields
        {
            get { return this._extensionFields; }
            set { this._extensionFields = value; }
        }

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

        ///
        /// Gets and sets the property ReportingMta.
        /// <para>
        /// The reporting MTA that attempted to deliver the message, formatted as specified in
        /// RFC 3464 (mta-name-type; mta-name).
        /// The default value is dns; inbound-smtp.[region].amazonaws.com.
        /// </para>
        ///
        public string ReportingMta
        {
            get { return this._reportingMta; }
            set { this._reportingMta = value; }
        }

        // Check to see if ReportingMta property is set
        internal bool IsSetReportingMta()
        {
            return this._reportingMta != null;
        }

    }
}


text:
<?php

$data = array
  (
     'Global' => array
     (
        array
        (
           'url' =>
           'http://%GangliaWebHostName%:%GangliaWebPort%/ganglia/graph.php?c=%HDFSSlavesClusterName%&g=hdp_mon_hdfs_io_report',
           'title' => 'HDFS I/O',
           'description' => 'Bytes written to and read from HDFS, aggregated across all the DataNodes',
           'link' => 'http://%GangliaWebHostName%:%GangliaWebPort%/ganglia/?c=%NameNodeClusterName%'
        ),
        array
        (
           'url' =>
           'http://%GangliaWebHostName%:%GangliaWebPort%/ganglia/graph.php?c=%NameNodeClusterName%&g=hdp_mon_hdfs_ops_report',
           'title' => 'NameNode Operation Counts',
           'description' => 'Counts of key operations on the NameNode, to give a feel for the high-level HDFS activity pattern',
           'link' => 'http://%GangliaWebHostName%:%GangliaWebPort%/ganglia/?c=%NameNodeClusterName%'
        ),
        array
        (
           'url' =>
           'http://%GangliaWebHostName%:%GangliaWebPort%/ganglia/graph.php?c=%NameNodeClusterName%&g=hdp_mon_jvm_gc_report',
           'title' => 'NameNode: JVM Garbage Collection',
           'description' => 'Key Garbage Collection stats for the NameNode\'s JVM',
           'link' => 'http://%GangliaWebHostName%:%GangliaWebPort%/ganglia/?c=%NameNodeClusterName%'
        ),
        array
        (
           'url' =>
           'http://%GangliaWebHostName%:%GangliaWebPort%/ganglia/graph.php?c=%NameNodeClusterName%&g=hdp_mon_rpc_latency_report',
           'title' => 'NameNode: RPC Average Latencies',
           'description' => 'Average latencies for processing and queue times on the NameNode, to give a feel for potential performance bottlenecks',
           'link' => 'http://%GangliaWebHostName%:%GangliaWebPort%/ganglia/?c=%NameNodeClusterName%'
        )
     )
  );

echo json_encode($data);

?>


text:
<?php
namespace Qurel\Nodes;

class JoinSource extends Binary
{
    public function __construct($single_source, array $joinop = array())
    {
        parent::__construct($single_source, $joinop);
    }
}


text:
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * VMWare Azure specific policy Input.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType")
@JsonTypeName("InMageAzureV2")
public class InMageAzureV2PolicyInput extends PolicyProviderSpecificInput {
    /**
     * The recovery point threshold in minutes.
     */
    @JsonProperty(value = "recoveryPointThresholdInMinutes")
    private Integer recoveryPointThresholdInMinutes;

    /**
     * The duration in minutes until which the recovery points need to be
     * stored.
     */
    @JsonProperty(value = "recoveryPointHistory")
    private Integer recoveryPointHistory;

    /**
     * The crash consistent snapshot frequency (in minutes).
     */
    @JsonProperty(value = "crashConsistentFrequencyInMinutes")
    private Integer crashConsistentFrequencyInMinutes;

    /**
     * The app consistent snapshot frequency (in minutes).
     */
    @JsonProperty(value = "appConsistentFrequencyInMinutes")
    private Integer appConsistentFrequencyInMinutes;

    /**
     * A value indicating whether multi-VM sync has to be enabled. Value should
     * be 'Enabled' or 'Disabled'. Possible values include: 'Enable',
     * 'Disable'.
     */
    @JsonProperty(value = "multiVmSyncStatus", required = true)
    private SetMultiVmSyncStatus multiVmSyncStatus;

    /**
     * Get the recovery point threshold in minutes.
     *
     * @return the recoveryPointThresholdInMinutes value
     */
    public Integer recoveryPointThresholdInMinutes() {
        return this.recoveryPointThresholdInMinutes;
    }

    /**
     * Set the recovery point threshold in minutes.
     *
     * @param recoveryPointThresholdInMinutes the recoveryPointThresholdInMinutes value to set
     * @return the InMageAzureV2PolicyInput object itself.
     */
    public InMageAzureV2PolicyInput withRecoveryPointThresholdInMinutes(Integer recoveryPointThresholdInMinutes) {
        this.recoveryPointThresholdInMinutes = recoveryPointThresholdInMinutes;
        return this;
    }

    /**
     * Get the duration in minutes until which the recovery points need to be stored.
     *
     * @return the recoveryPointHistory value
     */
    public Integer recoveryPointHistory() {
        return this.recoveryPointHistory;
    }

    /**
     * Set the duration in minutes until which the recovery points need to be stored.
     *
     * @param recoveryPointHistory the recoveryPointHistory value to set
     * @return the InMageAzureV2PolicyInput object itself.
     */
    public InMageAzureV2PolicyInput withRecoveryPointHistory(Integer recoveryPointHistory) {
        this.recoveryPointHistory = recoveryPointHistory;
        return this;
    }

    /**
     * Get the crash consistent snapshot frequency (in minutes).
     *
     * @return the crashConsistentFrequencyInMinutes value
     */
    public Integer crashConsistentFrequencyInMinutes() {
        return this.crashConsistentFrequencyInMinutes;
    }

    /**
     * Set the crash consistent snapshot frequency (in minutes).
     *
     * @param crashConsistentFrequencyInMinutes the crashConsistentFrequencyInMinutes value to set
     * @return the InMageAzureV2PolicyInput object itself.
     */
    public InMageAzureV2PolicyInput withCrashConsistentFrequencyInMinutes(Integer crashConsistentFrequencyInMinutes) {
        this.crashConsistentFrequencyInMinutes = crashConsistentFrequencyInMinutes;
        return this;
    }

    /**
     * Get the app consistent snapshot frequency (in minutes).
     *
     * @return the appConsistentFrequencyInMinutes value
     */
    public Integer appConsistentFrequencyInMinutes() {
        return this.appConsistentFrequencyInMinutes;
    }

    /**
     * Set the app consistent snapshot frequency (in minutes).
     *
     * @param appConsistentFrequencyInMinutes the appConsistentFrequencyInMinutes value to set
     * @return the InMageAzureV2PolicyInput object itself.
     */
    public InMageAzureV2PolicyInput withAppConsistentFrequencyInMinutes(Integer appConsistentFrequencyInMinutes) {
        this.appConsistentFrequencyInMinutes = appConsistentFrequencyInMinutes;
        return this;
    }

    /**
     * Get a value indicating whether multi-VM sync has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values include: 'Enable', 'Disable'.
     *
     * @return the multiVmSyncStatus value
     */
    public SetMultiVmSyncStatus multiVmSyncStatus() {
        return this.multiVmSyncStatus;
    }

    /**
     * Set a value indicating whether multi-VM sync has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values include: 'Enable', 'Disable'.
     *
     * @param multiVmSyncStatus the multiVmSyncStatus value to set
     * @return the InMageAzureV2PolicyInput object itself.
     */
    public InMageAzureV2PolicyInput withMultiVmSyncStatus(SetMultiVmSyncStatus multiVmSyncStatus) {
        this.multiVmSyncStatus = multiVmSyncStatus;
        return this;
    }

}


text:
/*
 * $Id: mailsmtp_ssl.c,v 1.16 2006/12/26 13:13:25 hoa Exp $
 */

#ifdef HAVE_CONFIG_H
#	include <config.h>
#endif

#include "mailsmtp_socket.h"

#include "mailsmtp.h"

#include "mailstream_cfstream.h"
#include "connect.h"

#include <stdlib.h>
#ifdef HAVE_NETINET_IN_H
#	include <netinet/in.h>
#endif
#ifdef HAVE_UNISTD_H
#	include <unistd.h>
#endif

#define DEFAULT_SMTPS_PORT 465
#define SERVICE_NAME_SMTPS "smtps"
#define SERVICE_TYPE_TCP "tcp"

static int mailsmtp_cfssl_connect(mailsmtp * session,
                                  const char * server, uint16_t port);

int mailsmtp_ssl_connect(mailsmtp * session,
    const char * server, uint16_t port)
{
  return mailsmtp_ssl_connect_with_callback(session, server, port,
      NULL, NULL);
}

int mailsmtp_ssl_connect_with_callback(mailsmtp * session,
    const char * server, uint16_t port,
    void (* callback)(struct mailstream_ssl_context * ssl_context, void * data), void * data)
{
  int s;
  mailstream * stream;

#if HAVE_CFNETWORK
  if (mailstream_cfstream_enabled) {
    if (callback == NULL) {
      return mailsmtp_cfssl_connect(session, server, port);
    }
  }
#endif

  if (port == 0) {
    port = mail_get_service_port(SERVICE_NAME_SMTPS, SERVICE_TYPE_TCP);
    if (port == 0)
      port = DEFAULT_SMTPS_PORT;
  }

  /* Connection */

  s = mail_tcp_connect_timeout(server, port, session->smtp_timeout);
  if (s == -1)
    return MAILSMTP_ERROR_CONNECTION_REFUSED;

  stream = mailstream_ssl_open_with_callback_timeout(s, session->smtp_timeout, callback, data);
  if (stream == NULL) {
#ifdef WIN32
	closesocket(s);
#else
	close(s);
#endif
    return MAILSMTP_ERROR_SSL;
  }

  return mailsmtp_connect(session, stream);
}

static int mailsmtp_cfssl_connect_ssl_level(mailsmtp * session,
                                            const char * server, uint16_t port, int ssl_level)
{
  mailstream * stream;
  int r;

  stream = mailstream_cfstream_open_timeout(server, port, session->smtp_timeout);
  if (stream == NULL) {
    return MAILSMTP_ERROR_CONNECTION_REFUSED;
  }
  mailstream_cfstream_set_ssl_level(stream, ssl_level);
  mailstream_cfstream_set_ssl_verification_mask(stream, MAILSTREAM_CFSTREAM_SSL_NO_VERIFICATION);
  r = mailstream_cfstream_set_ssl_enabled(stream, 1);
  if (r < 0) {
    mailstream_close(stream);
    return MAILSMTP_ERROR_SSL;
  }

  return mailsmtp_connect(session, stream);
}

static int mailsmtp_cfssl_connect(mailsmtp * session,
                                  const char * server, uint16_t port)
{
    return mailsmtp_cfssl_connect_ssl_level(session, server, port, MAILSTREAM_CFSTREAM_SSL_LEVEL_NEGOCIATED_SSL);
}


text:
module WeekViewHelper

end


text:
package org.olat.system.commons.date;

import static org.junit.Assert.assertTrue;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.junit.Test;

/**
 * Initial Date: 14.12.2011 <br>
 *
 * @author lavinia
 */
public class DateUtilTest {

    @Test
    public void isMoreThanOneDayBefore() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -2);
        assertTrue(DateUtil.isMoreThanOneDayBefore(cal.getTime()));
    }

    @Test
    public void getEndDate_validDate() {
        String someDate = "10.05.14";
        String deFormattedDate = DateUtil.getEndDate(someDate, 30, Locale.GERMAN);
        System.out.println("deFormattedDate: " + deFormattedDate);
        assertTrue(deFormattedDate.equals("09.06.2014"));
    }

    @Test
    public void getEndDate_invalidDate() {
        String someDate = "noDate";
        String deFormattedDate = DateUtil.getEndDate(someDate, 30, Locale.GERMAN);
        System.out.println("deFormattedDate: " + deFormattedDate);

        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMAN);
        String today = df.format(new Date());
        assertTrue(deFormattedDate.equals(today));
    }

    @Test
    public void getRemainingDays_future() {
        String someDate = "20.03.24";
        int days = DateUtil.getRemainingDays(someDate, 3);
        System.out.println("getRemainingDays: " + days);
        assertTrue(days > 0);

        int oneDay = DateUtil.getRemainingDays(someDate, 3) - DateUtil.getRemainingDays(someDate, 2);
        assertTrue(oneDay == 1);
    }

    @Test
    public void getRemainingDays_past() {
        String someDate = "20.03.04";
        int days = DateUtil.getRemainingDays(someDate, 3);
        System.out.println("getRemainingDays: " + days);
        assertTrue(days < 0);
    }

    @Test
    public void getRemainingDays_invalidDate() {
        String someDate = "noDate";
        int days = DateUtil.getRemainingDays(someDate, 3);
        System.out.println("getRemainingDays: " + days);
        assertTrue(days == 0);
    }

    @Test
    public void getRemainingDays_emptyArgs() {
        String someDate = "";
        int days = DateUtil.getRemainingDays(someDate, 0);
        System.out.println("getRemainingDays: " + days);
        assertTrue(days == 0);
    }

}