text:
namespace {

using ScopedCaptureTrace =
    media::TypedScopedAsyncTrace<media::TraceCategory::kVideoAndImageCapture>;

#if BUILDFLAG(IS_CHROMEOS_ASH)
std::unique_ptr<media::VideoCaptureJpegDecoder> CreateGpuJpegDecoder(
    scoped_refptr<base::SequencedTaskRunner> decoder_task_runner,
    media::MojoMjpegDecodeAcceleratorFactoryCB jpeg_decoder_factory_callback,
    media::VideoCaptureJpegDecoder::DecodeDoneCB decode_done_cb,
    base::RepeatingCallback<void(const std::string&)> send_log_message_cb) {
  return std::make_unique<media::ScopedVideoCaptureJpegDecoder>(
      std::make_unique<media::VideoCaptureJpegDecoderImpl>(
          jpeg_decoder_factory_callback, decoder_task_runner,
          std::move(decode_done_cb), std::move(send_log_message_cb)),
      decoder_task_runner);
}
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

void TakePhotoCallbackTrampoline(
    media::VideoCaptureDevice::TakePhotoCallback callback,
    std::unique_ptr<ScopedCaptureTrace> trace,
    media::mojom::BlobPtr blob) {
  std::move(callback).Run(std::move(blob));
}

}  // anonymous namespace

namespace video_capture {

#if BUILDFLAG(IS_CHROMEOS_ASH)
DeviceMediaToMojoAdapter::DeviceMediaToMojoAdapter(
    std::unique_ptr<media::VideoCaptureDevice> device,
    media::MojoMjpegDecodeAcceleratorFactoryCB jpeg_decoder_factory_callback,
    scoped_refptr<base::SequencedTaskRunner> jpeg_decoder_task_runner)
    : device_(std::move(device)),
      jpeg_decoder_factory_callback_(std::move(jpeg_decoder_factory_callback)),
      jpeg_decoder_task_runner_(std::move(jpeg_decoder_task_runner)) {}
#elif BUILDFLAG(IS_WIN)
DeviceMediaToMojoAdapter::DeviceMediaToMojoAdapter(
    std::unique_ptr<media::VideoCaptureDevice> device,
    media::VideoCaptureDeviceFactory* factory)
    : device_(std::move(device)),
      device_started_(false),
      dxgi_device_manager_(factory ? factory->GetDxgiDeviceManager()
                                   : nullptr) {}

#else
DeviceMediaToMojoAdapter::DeviceMediaToMojoAdapter(
    std::unique_ptr<media::VideoCaptureDevice> device)
    : device_(std::move(device)), device_started_(false) {}
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

DeviceMediaToMojoAdapter::~DeviceMediaToMojoAdapter() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (device_started_)
    device_->StopAndDeAllocate();
}

void DeviceMediaToMojoAdapter::Start(
    const media::VideoCaptureParams& requested_settings,
    mojo::PendingRemote<mojom::VideoFrameHandler>
        video_frame_handler_pending_remote) {
  DCHECK(thread_checker_.CalledOnValidThread());
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("video_and_image_capture"),
               "DeviceMediaToMojoAdapter::Start");
  mojo::Remote<mojom::VideoFrameHandler> handler_remote(
      std::move(video_frame_handler_pending_remote));
  handler_remote.set_disconnect_handler(
      base::BindOnce(&DeviceMediaToMojoAdapter::OnClientConnectionErrorOrClose,
                     weak_factory_.GetWeakPtr()));

  receiver_ =
      std::make_unique<ReceiverMojoToMediaAdapter>(std::move(handler_remote));
  auto media_receiver = std::make_unique<media::VideoFrameReceiverOnTaskRunner>(
      receiver_->GetWeakPtr(), base::ThreadTaskRunnerHandle::Get());

  if (requested_settings.buffer_type !=
          media::VideoCaptureBufferType::kSharedMemory &&
      requested_settings.buffer_type !=
          media::VideoCaptureBufferType::kGpuMemoryBuffer &&
      requested_settings.buffer_type !=
          media::VideoCaptureBufferType::kSharedMemoryViaRawFileDescriptor) {
    // Buffer types other than shared memory are not supported.
    media_receiver->OnError(
        media::VideoCaptureError::
            kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType);
    return;
  }

  scoped_refptr<media::VideoCaptureBufferPool> buffer_pool;
  {
    TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("video_and_image_capture"),
                 "CreateVideoCaptureBufferPoolImpl");
    // Create a dedicated buffer pool for the device usage session.
#if BUILDFLAG(IS_WIN)
    buffer_pool = base::MakeRefCounted<media::VideoCaptureBufferPoolImpl>(
        requested_settings.buffer_type, max_buffer_pool_buffer_count(),
        std::make_unique<media::VideoCaptureBufferTrackerFactoryWin>(
            dxgi_device_manager_));
#else
    buffer_pool = base::MakeRefCounted<media::VideoCaptureBufferPoolImpl>(
        requested_settings.buffer_type, max_buffer_pool_buffer_count());
#endif
  }

#if BUILDFLAG(IS_CHROMEOS_ASH)
  auto device_client = std::make_unique<media::VideoCaptureDeviceClient>(
      requested_settings.buffer_type, std::move(media_receiver), buffer_pool,
      base::BindRepeating(
          &CreateGpuJpegDecoder, jpeg_decoder_task_runner_,
          jpeg_decoder_factory_callback_,
          media::BindToCurrentLoop(base::BindRepeating(
              &media::VideoFrameReceiver::OnFrameReadyInBuffer,
              receiver_->GetWeakPtr())),
          media::BindToCurrentLoop(base::BindRepeating(
              &media::VideoFrameReceiver::OnLog, receiver_->GetWeakPtr()))));
#else
  auto device_client = std::make_unique<media::VideoCaptureDeviceClient>(
      requested_settings.buffer_type, std::move(media_receiver), buffer_pool);
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

  device_->AllocateAndStart(requested_settings, std::move(device_client));
  device_started_ = true;
}

void DeviceMediaToMojoAdapter::MaybeSuspend() {
  if (!device_started_)
    return;
  device_->MaybeSuspend();
}

void DeviceMediaToMojoAdapter::Resume() {
  if (!device_started_)
    return;
  device_->Resume();
}

void DeviceMediaToMojoAdapter::GetPhotoState(GetPhotoStateCallback callback) {
  media::VideoCaptureDevice::GetPhotoStateCallback scoped_callback =
      mojo::WrapCallbackWithDefaultInvokeIfNotRun(
          media::BindToCurrentLoop(std::move(callback)), nullptr);
  device_->GetPhotoState(std::move(scoped_callback));
}

void DeviceMediaToMojoAdapter::SetPhotoOptions(
    media::mojom::PhotoSettingsPtr settings,
    SetPhotoOptionsCallback callback) {
  media::mojom::ImageCapture::SetOptionsCallback scoped_callback =
      mojo::WrapCallbackWithDefaultInvokeIfNotRun(
          media::BindToCurrentLoop(std::move(callback)), false);
  device_->SetPhotoOptions(std::move(settings), std::move(scoped_callback));
}

void DeviceMediaToMojoAdapter::TakePhoto(TakePhotoCallback callback) {
  auto scoped_trace = ScopedCaptureTrace::CreateIfEnabled("TakePhoto");
  media::mojom::ImageCapture::TakePhotoCallback scoped_callback =
      mojo::WrapCallbackWithDefaultInvokeIfNotRun(
          media::BindToCurrentLoop(base::BindOnce(&TakePhotoCallbackTrampoline,
                                                  std::move(callback),
                                                  std::move(scoped_trace))),
          nullptr);
  device_->TakePhoto(std::move(scoped_callback));
}

void DeviceMediaToMojoAdapter::ProcessFeedback(
    const media::VideoCaptureFeedback& feedback) {
  // Feedback ID may not propagated by mojo interface.
  device_->OnUtilizationReport(feedback);
}

void DeviceMediaToMojoAdapter::RequestRefreshFrame() {
  device_->RequestRefreshFrame();
}

void DeviceMediaToMojoAdapter::Stop() {
  DCHECK(thread_checker_.CalledOnValidThread());
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("video_and_image_capture"),
               "DeviceMediaToMojoAdapter::Stop");
  if (!device_started_)
    return;
  device_started_ = false;
  weak_factory_.InvalidateWeakPtrs();
  device_->StopAndDeAllocate();
  // We need to post the deletion of receiver to the end of the message queue,
  // because |device_->StopAndDeAllocate()| may post messages (e.g.
  // OnBufferRetired()) to a WeakPtr to |receiver_| to this queue,
  // and we need those messages to be sent before we invalidate the WeakPtr.
  base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE,
                                                  std::move(receiver_));
}

void DeviceMediaToMojoAdapter::OnClientConnectionErrorOrClose() {
  DCHECK(thread_checker_.CalledOnValidThread());
  Stop();
}

// static
int DeviceMediaToMojoAdapter::max_buffer_pool_buffer_count() {
  return media::DeviceVideoCaptureMaxBufferPoolSize();
}

}  // namespace video_capture


text:
require 'test_helper'

class Api::SeasonsHelperTest < ActionView::TestCase
end

redpajama_set_name: RedPajamaGithub


text:
package org.jabref.model.entry;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.jabref.model.FieldChange;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.OrFields;
import org.jabref.model.entry.field.SpecialField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.StandardEntryType;

import com.google.common.collect.Sets;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class BibEntryTests {

    private BibEntry keywordEntry;
    private BibEntry emptyEntry;

    @BeforeEach
    public void setUp() {
        // Default entry for most keyword and some type tests
        keywordEntry = new BibEntry();
        keywordEntry.setType(StandardEntryType.Article);
        keywordEntry.setField(StandardField.KEYWORDS, "Foo, Bar");
        keywordEntry.setChanged(false);

        // Empty entry for some tests
        emptyEntry = new BibEntry();
        emptyEntry.setType(StandardEntryType.Article);
        emptyEntry.setChanged(false);
    }

    @Test
    public void testDefaultConstructor() {
        BibEntry entry = new BibEntry();
        assertEquals(StandardEntryType.Misc, entry.getType());
        assertNotNull(entry.getId());
        assertFalse(entry.getField(StandardField.AUTHOR).isPresent());
    }

    @Test
    public void allFieldsPresentDefault() {
        BibEntry e = new BibEntry(StandardEntryType.Article);
        e.setField(StandardField.AUTHOR, "abc");
        e.setField(StandardField.TITLE, "abc");
        e.setField(StandardField.JOURNAL, "abc");

        List<OrFields> requiredFields = new ArrayList<>();
        requiredFields.add(new OrFields(StandardField.AUTHOR));
        requiredFields.add(new OrFields(StandardField.TITLE));
        assertTrue(e.allFieldsPresent(requiredFields, null));

        requiredFields.add(new OrFields(StandardField.YEAR));
        assertFalse(e.allFieldsPresent(requiredFields, null));
    }

    @Test
    public void allFieldsPresentOr() {
        BibEntry e = new BibEntry(StandardEntryType.Article);
        e.setField(StandardField.AUTHOR, "abc");
        e.setField(StandardField.TITLE, "abc");
        e.setField(StandardField.JOURNAL, "abc");

        List<OrFields> requiredFields = new ArrayList<>();
        requiredFields.add(new OrFields(StandardField.JOURNAL, StandardField.YEAR));
        assertTrue(e.allFieldsPresent(requiredFields, null));

        requiredFields.add(new OrFields(StandardField.YEAR, StandardField.ADDRESS));
        assertFalse(e.allFieldsPresent(requiredFields, null));
    }

    @Test
    public void isNullCiteKeyThrowsNPE() {
        BibEntry e = new BibEntry(StandardEntryType.Article);
        assertThrows(NullPointerException.class, () -> e.setCiteKey(null));
    }

    @Test
    public void isEmptyCiteKey() {
        BibEntry e = new BibEntry(StandardEntryType.Article);
        assertFalse(e.hasCiteKey());

        e.setCiteKey("");
        assertFalse(e.hasCiteKey());

        e.setCiteKey("key");
        assertTrue(e.hasCiteKey());

        e.clearField(InternalField.KEY_FIELD);
        assertFalse(e.hasCiteKey());
    }

    @Test
    public void settingTypeToNullThrowsException() {
        assertThrows(NullPointerException.class, () -> keywordEntry.setType(null));
    }

    @Test
    public void getFieldOrAliasDateWithYearNumericalMonthString() {
        emptyEntry.setField(StandardField.YEAR, "2003");
        emptyEntry.setField(StandardField.MONTH, "3");
        assertEquals(Optional.of("2003-03"), emptyEntry.getFieldOrAlias(StandardField.DATE));
    }

    @Test
    public void getFieldOrAliasDateWithYearAbbreviatedMonth() {
        emptyEntry.setField(StandardField.YEAR, "2003");
        emptyEntry.setField(StandardField.MONTH, "#mar#");
        assertEquals(Optional.of("2003-03"), emptyEntry.getFieldOrAlias(StandardField.DATE));
    }

    @Test
    public void getFieldOrAliasDateWithYearAbbreviatedMonthString() {
        emptyEntry.setField(StandardField.YEAR, "2003");
        emptyEntry.setField(StandardField.MONTH, "mar");
        assertEquals(Optional.of("2003-03"), emptyEntry.getFieldOrAlias(StandardField.DATE));
    }

    @Test
    public void getFieldOrAliasDateWithOnlyYear() {
        emptyEntry.setField(StandardField.YEAR, "2003");
        assertEquals(Optional.of("2003"), emptyEntry.getFieldOrAlias(StandardField.DATE));
    }

    @Test
    public void getFieldOrAliasYearWithDateYYYY() {
        emptyEntry.setField(StandardField.DATE, "2003");
        assertEquals(Optional.of("2003"), emptyEntry.getFieldOrAlias(StandardField.YEAR));
    }

    @Test
    public void getFieldOrAliasYearWithDateYYYYMM() {
        emptyEntry.setField(StandardField.DATE, "2003-03");
        assertEquals(Optional.of("2003"), emptyEntry.getFieldOrAlias(StandardField.YEAR));
    }

    @Test
    public void getFieldOrAliasYearWithDateYYYYMMDD() {
        emptyEntry.setField(StandardField.DATE, "2003-03-30");
        assertEquals(Optional.of("2003"), emptyEntry.getFieldOrAlias(StandardField.YEAR));
    }

    @Test
    public void getFieldOrAliasMonthWithDateYYYYReturnsNull() {
        emptyEntry.setField(StandardField.DATE, "2003");
        assertEquals(Optional.empty(), emptyEntry.getFieldOrAlias(StandardField.MONTH));
    }

    @Test
    public void getFieldOrAliasMonthWithDateYYYYMM() {
        emptyEntry.setField(StandardField.DATE, "2003-03");
        assertEquals(Optional.of("#mar#"), emptyEntry.getFieldOrAlias(StandardField.MONTH));
    }

    @Test
    public void getFieldOrAliasMonthWithDateYYYYMMDD() {
        emptyEntry.setField(StandardField.DATE, "2003-03-30");
        assertEquals(Optional.of("#mar#"), emptyEntry.getFieldOrAlias(StandardField.MONTH));
    }

    @Test
    public void getFieldOrAliasLatexFreeAlreadyFreeValueIsUnchanged() {
        emptyEntry.setField(StandardField.TITLE, "A Title Without any LaTeX commands");
        assertEquals(Optional.of("A Title Without any LaTeX commands"), emptyEntry.getFieldOrAliasLatexFree(StandardField.TITLE));
    }

    @Test
    public void getFieldOrAliasLatexFreeAlreadyFreeAliasValueIsUnchanged() {
        emptyEntry.setField(StandardField.JOURNAL, "A Title Without any LaTeX commands");
        assertEquals(Optional.of("A Title Without any LaTeX commands"), emptyEntry.getFieldOrAliasLatexFree(StandardField.JOURNALTITLE));
    }

    @Test
    public void getFieldOrAliasLatexFreeBracesAreRemoved() {
        emptyEntry.setField(StandardField.TITLE, "{A Title with some {B}ra{C}es}");
        assertEquals(Optional.of("A Title with some BraCes"), emptyEntry.getFieldOrAliasLatexFree(StandardField.TITLE));
    }

    @Test
    public void getFieldOrAliasLatexFreeBracesAreRemovedFromAlias() {
        emptyEntry.setField(StandardField.JOURNAL, "{A Title with some {B}ra{C}es}");
        assertEquals(Optional.of("A Title with some BraCes"), emptyEntry.getFieldOrAliasLatexFree(StandardField.JOURNALTITLE));
    }

    @Test
    public void getFieldOrAliasLatexFreeComplexConversionInAlias() {
        emptyEntry.setField(StandardField.JOURNAL, "A 32~{mA} {$\\Sigma\\Delta$}-modulator");
        assertEquals(Optional.of("A 32 mA ΣΔ-modulator"), emptyEntry.getFieldOrAliasLatexFree(StandardField.JOURNALTITLE));
    }

    @Test
    public void setNullField() {
        assertThrows(NullPointerException.class, () -> emptyEntry.setField(null));
    }

    @Test
    public void addNullKeywordThrowsNPE() {
        assertThrows(NullPointerException.class, () -> keywordEntry.addKeyword((Keyword) null, ','));
    }

    @Test
    public void putNullKeywordListThrowsNPE() {
        assertThrows(NullPointerException.class, () -> keywordEntry.putKeywords((KeywordList) null, ','));
    }

    @Test
    public void putNullKeywordSeparatorThrowsNPE() {
        assertThrows(NullPointerException.class, () -> keywordEntry.putKeywords(Arrays.asList("A", "B"), null));
    }

    @Test
    public void testGetSeparatedKeywordsAreCorrect() {
        assertEquals(new KeywordList("Foo", "Bar"), keywordEntry.getKeywords(','));
    }

    @Test
    public void testAddKeywordIsCorrect() {
        keywordEntry.addKeyword("FooBar", ',');
        assertEquals(new KeywordList("Foo", "Bar", "FooBar"), keywordEntry.getKeywords(','));
    }

    @Test
    public void testAddKeywordHasChanged() {
        keywordEntry.addKeyword("FooBar", ',');
        assertTrue(keywordEntry.hasChanged());
    }

    @Test
    public void testAddKeywordTwiceYiedsOnlyOne() {
        keywordEntry.addKeyword("FooBar", ',');
        keywordEntry.addKeyword("FooBar", ',');
        assertEquals(new KeywordList("Foo", "Bar", "FooBar"), keywordEntry.getKeywords(','));
    }

    @Test
    public void addKeywordIsCaseSensitive() {
        keywordEntry.addKeyword("FOO", ',');
        assertEquals(new KeywordList("Foo", "Bar", "FOO"), keywordEntry.getKeywords(','));
    }

    @Test
    public void testAddKeywordWithDifferentCapitalizationChanges() {
        keywordEntry.addKeyword("FOO", ',');
        assertTrue(keywordEntry.hasChanged());
    }

    @Test
    public void testAddKeywordEmptyKeywordIsNotAdded() {
        keywordEntry.addKeyword("", ',');
        assertEquals(new KeywordList("Foo", "Bar"), keywordEntry.getKeywords(','));
    }

    @Test
    public void testAddKeywordEmptyKeywordNotChanged() {
        keywordEntry.addKeyword("", ',');
        assertFalse(keywordEntry.hasChanged());
    }

    @Test
    public void texNewBibEntryHasNoKeywords() {
        assertTrue(emptyEntry.getKeywords(',').isEmpty());
    }

    @Test
    public void texNewBibEntryHasNoKeywordsEvenAfterAddingEmptyKeyword() {
        emptyEntry.addKeyword("", ',');
        assertTrue(emptyEntry.getKeywords(',').isEmpty());
    }

    @Test
    public void texNewBibEntryAfterAddingEmptyKeywordNotChanged() {
        emptyEntry.addKeyword("", ',');
        assertFalse(emptyEntry.hasChanged());
    }

    @Test
    public void testAddKeywordsWorksAsExpected() {
        emptyEntry.addKeywords(Arrays.asList("Foo", "Bar"), ',');
        assertEquals(new KeywordList("Foo", "Bar"), emptyEntry.getKeywords(','));
    }

    @Test
    public void testPutKeywordsOverwritesOldKeywords() {
        keywordEntry.putKeywords(Arrays.asList("Yin", "Yang"), ',');
        assertEquals(new KeywordList("Yin", "Yang"), keywordEntry.getKeywords(','));
    }

    @Test
    public void testPutKeywordsHasChanged() {
        keywordEntry.putKeywords(Arrays.asList("Yin", "Yang"), ',');
        assertTrue(keywordEntry.hasChanged());
    }

    @Test
    public void testPutKeywordsPutEmpyListErasesPreviousKeywords() {
        keywordEntry.putKeywords(Collections.emptyList(), ',');
        assertTrue(keywordEntry.getKeywords(',').isEmpty());
    }

    @Test
    public void testPutKeywordsPutEmpyListHasChanged() {
        keywordEntry.putKeywords(Collections.emptyList(), ',');
        assertTrue(keywordEntry.hasChanged());
    }

    @Test
    public void testPutKeywordsPutEmpyListToEmptyBibentry() {
        emptyEntry.putKeywords(Collections.emptyList(), ',');
        assertTrue(emptyEntry.getKeywords(',').isEmpty());
    }

    @Test
    public void testPutKeywordsPutEmpyListToEmptyBibentryNotChanged() {
        emptyEntry.putKeywords(Collections.emptyList(), ',');
        assertFalse(emptyEntry.hasChanged());
    }

    @Test
    public void putKeywordsToEmptyReturnsNoChange() {
        Optional<FieldChange> change = emptyEntry.putKeywords(Collections.emptyList(), ',');
        assertEquals(Optional.empty(), change);
    }

    @Test
    public void clearKeywordsReturnsChange() {
        Optional<FieldChange> change = keywordEntry.putKeywords(Collections.emptyList(), ',');
        assertEquals(Optional.of(new FieldChange(keywordEntry, StandardField.KEYWORDS, "Foo, Bar", null)), change);
    }

    @Test
    public void changeKeywordsReturnsChange() {
        Optional<FieldChange> change = keywordEntry.putKeywords(Arrays.asList("Test", "FooTest"), ',');
        assertEquals(Optional.of(new FieldChange(keywordEntry, StandardField.KEYWORDS, "Foo, Bar", "Test, FooTest")),
                change);
    }

    @Test
    public void putKeywordsToSameReturnsNoChange() {
        Optional<FieldChange> change = keywordEntry.putKeywords(Arrays.asList("Foo", "Bar"), ',');
        assertEquals(Optional.empty(), change);
    }

    @Test
    public void getKeywordsReturnsParsedKeywordListFromKeywordsField() {
        BibEntry entry = new BibEntry();
        entry.setField(StandardField.KEYWORDS, "w1, w2a w2b, w3");
        assertEquals(new KeywordList("w1", "w2a w2b", "w3"), entry.getKeywords(','));
    }

    @Test
    public void removeKeywordsOnEntryWithoutKeywordsDoesNothing() {
        BibEntry entry = new BibEntry();
        Optional<FieldChange> change = entry.removeKeywords(SpecialField.RANKING.getKeyWords(), ',');
        assertEquals(Optional.empty(), change);
    }

    @Test
    public void removeKeywordsWithEmptyListDoesNothing() {
        keywordEntry.putKeywords(Arrays.asList("kw1", "kw2"), ',');
        Optional<FieldChange> change = keywordEntry.removeKeywords(new KeywordList(), ',');
        assertEquals(Optional.empty(), change);
    }

    @Test
    public void removeKeywordsWithNonExistingKeywordsDoesNothing() {
        keywordEntry.putKeywords(Arrays.asList("kw1", "kw2"), ',');
        Optional<FieldChange> change = keywordEntry.removeKeywords(KeywordList.parse("kw3, kw4", ','), ',');
        assertEquals(Optional.empty(), change);
        assertEquals(Sets.newHashSet("kw1", "kw2"), keywordEntry.getKeywords(',').toStringList());
    }

    @Test
    public void removeKeywordsWithExistingKeywordsRemovesThem() {
        keywordEntry.putKeywords(Arrays.asList("kw1", "kw2", "kw3"), ',');
        Optional<FieldChange> change = keywordEntry.removeKeywords(KeywordList.parse("kw1, kw2", ','), ',');
        assertTrue(change.isPresent());
        assertEquals(KeywordList.parse("kw3", ','), keywordEntry.getKeywords(','));
    }

    @Test
    public void setCiteKey() {
        BibEntry be = new BibEntry();
        assertFalse(be.hasCiteKey());
        be.setField(StandardField.AUTHOR, "Albert Einstein");
        be.setCiteKey("Einstein1931");
        assertTrue(be.hasCiteKey());
        assertEquals(Optional.of("Einstein1931"), be.getCiteKeyOptional());
        assertEquals(Optional.of("Albert Einstein"), be.getField(StandardField.AUTHOR));
        be.clearField(StandardField.AUTHOR);
        assertEquals(Optional.empty(), be.getField(StandardField.AUTHOR));
    }
}


text:
package org.apache.pulsar.admin.cli;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.Parameters;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.api.transaction.TxnID;
import org.apache.pulsar.common.util.RelativeTimeUtil;

@Parameters(commandDescription = "Operations on transactions")
public class CmdTransactions extends CmdBase {

    @Parameters(commandDescription = "Get transaction coordinator stats")
    private class GetCoordinatorStats extends CliCommand {
        @Parameter(names = {"-c", "--coordinator-id"}, description = "The coordinator id", required = false)
        private Integer coordinatorId;

        @Override
        void run() throws Exception {
            if (coordinatorId != null) {
                print(getAdmin().transactions().getCoordinatorStatsById(coordinatorId));
            } else {
                print(getAdmin().transactions().getCoordinatorStats());
            }
        }
    }

    @Parameters(commandDescription = "Get transaction buffer stats")
    private class GetTransactionBufferStats extends CliCommand {
        @Parameter(names = {"-t", "--topic"}, description = "The topic", required = true)
        private String topic;

        @Parameter(names = {"-l", "--low-water-mark"},
                description = "Whether to get information about lowWaterMarks stored in transaction buffer.")
        private boolean lowWaterMark;

        @Override
        void run() throws Exception {
            print(getAdmin().transactions().getTransactionBufferStats(topic, lowWaterMark));
        }
    }

    @Parameters(commandDescription = "Get transaction pending ack stats")
    private class GetPendingAckStats extends CliCommand {
        @Parameter(names = {"-t", "--topic"}, description = "The topic name", required = true)
        private String topic;

        @Parameter(names = {"-s", "--sub-name"}, description = "The subscription name", required = true)
        private String subName;

        @Parameter(names = {"-l", "--low-water-mark"},
                description = "Whether to get information about lowWaterMarks stored in transaction pending ack.")
        private boolean lowWaterMarks;

        @Override
        void run() throws Exception {
            print(getAdmin().transactions().getPendingAckStats(topic, subName, lowWaterMarks));
        }
    }

    @Parameters(commandDescription = "Get transaction in pending ack stats")
    private class GetTransactionInPendingAckStats extends CliCommand {
        @Parameter(names = {"-m", "--most-sig-bits"}, description = "The most sig bits", required = true)
        private int mostSigBits;

        @Parameter(names = {"-l", "--least-sig-bits"}, description = "The least sig bits", required = true)
        private long leastSigBits;

        @Parameter(names = {"-t", "--topic"}, description = "The topic name", required = true)
        private String topic;

        @Parameter(names = {"-s", "--sub-name"}, description = "The subscription name", required = true)
        private String subName;

        @Override
        void run() throws Exception {
            print(getAdmin().transactions().getTransactionInPendingAckStats(new TxnID(mostSigBits, leastSigBits),
                    topic, subName));
        }
    }

    @Parameters(commandDescription = "Get transaction in buffer stats")
    private class GetTransactionInBufferStats extends CliCommand {
        @Parameter(names = {"-m", "--most-sig-bits"}, description = "The most sig bits", required = true)
        private int mostSigBits;

        @Parameter(names = {"-l", "--least-sig-bits"}, description = "The least sig bits", required = true)
        private long leastSigBits;

        @Parameter(names = {"-t", "--topic"}, description = "The topic name", required = true)
        private String topic;

        @Override
        void run() throws Exception {
            print(getAdmin().transactions().getTransactionInBufferStats(new TxnID(mostSigBits, leastSigBits), topic));
        }
    }

    @Parameters(commandDescription = "Get transaction metadata")
    private class GetTransactionMetadata extends CliCommand {
        @Parameter(names = {"-m", "--most-sig-bits"}, description = "The most sig bits", required = true)
        private int mostSigBits;

        @Parameter(names = {"-l", "--least-sig-bits"}, description = "The least sig bits", required = true)
        private long leastSigBits;

        @Override
        void run() throws Exception {
            print(getAdmin().transactions().getTransactionMetadata(new TxnID(mostSigBits, leastSigBits)));
        }
    }

    @Parameters(commandDescription = "Get slow transactions.")
    private class GetSlowTransactions extends CliCommand {
        @Parameter(names = {"-c", "--coordinator-id"}, description = "The coordinator id", required = false)
        private Integer coordinatorId;

        @Parameter(names = { "-t", "--time" }, description = "The transaction timeout time. "
                + "(eg: 1s, 10s, 1m, 5h, 3d)", required = true)
        private String timeoutStr = "1s";

        @Override
        void run() throws Exception {
            long timeout;
            try {
                timeout = TimeUnit.SECONDS.toMillis(RelativeTimeUtil.parseRelativeTimeInSeconds(timeoutStr));
            } catch (IllegalArgumentException exception) {
                throw new ParameterException(exception.getMessage());
            }
            if (coordinatorId != null) {
                print(getAdmin().transactions().getSlowTransactionsByCoordinatorId(coordinatorId,
                        timeout, TimeUnit.MILLISECONDS));
            } else {
                print(getAdmin().transactions().getSlowTransactions(timeout, TimeUnit.MILLISECONDS));
            }
        }
    }

    @Parameters(commandDescription = "Get transaction coordinator internal stats")
    private class GetCoordinatorInternalStats extends CliCommand {
        @Parameter(names = {"-c", "--coordinator-id"}, description = "The coordinator id", required = true)
        private int coordinatorId;

        @Parameter(names = { "-m", "--metadata" }, description = "Flag to include ledger metadata")
        private boolean metadata = false;
        @Override
        void run() throws Exception {
            print(getAdmin().transactions().getCoordinatorInternalStats(coordinatorId, metadata));
        }
    }

    @Parameters(commandDescription = "Get pending ack internal stats")
    private class GetPendingAckInternalStats extends CliCommand {
        @Parameter(names = {"-t", "--topic"}, description = "Topic name", required = true)
        private String topic;

        @Parameter(names = {"-s", "--subscription-name"}, description = "Subscription name", required = true)
        private String subName;

        @Parameter(names = { "-m", "--metadata" }, description = "Flag to include ledger metadata")
        private boolean metadata = false;
        @Override
        void run() throws Exception {
            print(getAdmin().transactions().getPendingAckInternalStats(topic, subName, metadata));
        }
    }

    @Parameters(commandDescription = "Update the scale of transaction coordinators")
    private class ScaleTransactionCoordinators extends CliCommand {
        @Parameter(names = { "-r", "--replicas" }, description = "The scale of the transaction coordinators")
        private int replicas;
        @Override
        void run() throws Exception {
            getAdmin().transactions().scaleTransactionCoordinators(replicas);
        }
    }

    @Parameters(commandDescription = "Get the position stats in transaction pending ack")
    private class GetPositionStatsInPendingAck extends CliCommand {
        @Parameter(names = {"-t", "--topic"}, description = "The topic name", required = true)
        private String topic;

        @Parameter(names = {"-s", "--subscription-name"}, description = "Subscription name", required = true)
        private String subName;

        @Parameter(names = {"-l", "--ledger-id"}, description = "Ledger ID of the position", required = true)
        private Long ledgerId;

        @Parameter(names = {"-e", "--entry-id"}, description = "Entry ID of the position", required = true)
        private Long entryId;

        @Parameter(names = {"-b", "--batch-index"}, description = "Batch index of the position")
        private Integer batchIndex;

        @Override
        void run() throws Exception {
            getAdmin().transactions().getPositionStatsInPendingAck(topic, subName, ledgerId, entryId, batchIndex);
        }
    }

    public CmdTransactions(Supplier<PulsarAdmin> admin) {
        super("transactions", admin);
        jcommander.addCommand("coordinator-internal-stats", new GetCoordinatorInternalStats());
        jcommander.addCommand("pending-ack-internal-stats", new GetPendingAckInternalStats());
        jcommander.addCommand("coordinator-stats", new GetCoordinatorStats());
        jcommander.addCommand("transaction-buffer-stats", new GetTransactionBufferStats());
        jcommander.addCommand("pending-ack-stats", new GetPendingAckStats());
        jcommander.addCommand("transaction-in-buffer-stats", new GetTransactionInBufferStats());
        jcommander.addCommand("transaction-in-pending-ack-stats", new GetTransactionInPendingAckStats());
        jcommander.addCommand("transaction-metadata", new GetTransactionMetadata());
        jcommander.addCommand("slow-transactions", new GetSlowTransactions());
        jcommander.addCommand("scale-transactionCoordinators", new ScaleTransactionCoordinators());
        jcommander.addCommand("position-stats-in-pending-ack", new GetPositionStatsInPendingAck());

    }
}


text:
package ecjapp.eval.problem;

import ec.EvolutionState;
import ec.Evolve;
import ec.simple.SimpleEvolutionState;
import ec.util.Parameter;
import ec.util.ParameterDatabase;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Eric 'Siggy' Scott
 */
public class ThreadDynamicArgumentsTest {
    private final static Parameter BASE = new Parameter("base");
    private final static String OPT1 = "-opt1";
    private final static String OPT2 = "-opt2";

    private EvolutionState state;
    private ThreadDynamicArguments sut;

    public ThreadDynamicArgumentsTest() { }

    @Before
    public void setUp() {
        this.state = getFreshState();
        this.sut = new ThreadDynamicArguments();
    }

    private static EvolutionState getFreshState() {
        final EvolutionState state = new SimpleEvolutionState();
        state.parameters = getParams();
        state.output = Evolve.buildOutput();
        state.output.setThrowsErrors(true);
        return state;
    }

    private static ParameterDatabase getParams() {
        final ParameterDatabase parameters = new ParameterDatabase();
        parameters.set(BASE.push(ThreadDynamicArguments.P_OPT), OPT1);
        return parameters;
    }

    @Test
    public void testGet1() {
        System.out.println("get");
        sut.setup(state, BASE);
        final int thread = 0;
        final String expResult = String.format(" %s %s", OPT1, thread);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGet2() {
        System.out.println("get");
        sut.setup(state, BASE);
        final int thread = 100;
        final String expResult = String.format(" %s %s", OPT1, thread);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGet3() {
        System.out.println("get");
        sut.setup(state, BASE);
        final int thread = Integer.MAX_VALUE;
        final String expResult = String.format(" %s %s", OPT1, thread);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetModulo1() {
        System.out.println("get (with modulo)");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_MODULO), "5");
        sut.setup(state, BASE);
        final int thread = 0;
        final String expResult = String.format(" %s %s", OPT1, thread);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetModulo2() {
        System.out.println("get (with modulo)");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_MODULO), "5");
        sut.setup(state, BASE);
        final int thread = 4;
        final String expResult = String.format(" %s %s", OPT1, thread);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetModulo3() {
        System.out.println("get (with modulo)");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_MODULO), "5");
        sut.setup(state, BASE);
        final int thread = 5;
        final String expResult = String.format(" %s %s", OPT1, 0);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetModulo4() {
        System.out.println("get (with modulo)");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_MODULO), "5");
        sut.setup(state, BASE);
        final int thread = 15;
        final String expResult = String.format(" %s %s", OPT1, 0);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetModulo5() {
        System.out.println("get (with modulo)");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_MODULO), "5");
        sut.setup(state, BASE);
        final int thread = 100;
        final String expResult = String.format(" %s %s", OPT1, 0);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetModulo6() {
        System.out.println("get (with modulo)");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_MODULO), "5");
        sut.setup(state, BASE);
        final int thread = 156;
        final String expResult = String.format(" %s %s", OPT1, 1);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetWrapped1() {
        System.out.println("get (with wrapped dynamicArguments)");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS), "ecjapp.eval.problem.ThreadDynamicArguments");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS).push(ThreadDynamicArguments.P_OPT), OPT2);
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS).push(ThreadDynamicArguments.P_MODULO), "5");
        sut.setup(state, BASE);
        final int thread = 156;
        final String expResult = String.format(" %s %s %s %s", OPT2, 1, OPT1, thread);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetWrapped2() {
        System.out.println("get (with wrapped dynamicArguments)");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS), "ecjapp.eval.problem.ThreadDynamicArguments");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS).push(ThreadDynamicArguments.P_OPT), OPT2);
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS).push(ThreadDynamicArguments.P_MODULO), "5");
        sut.setup(state, BASE);
        final int thread = 5;
        final String expResult = String.format(" %s %s %s %s", OPT2, 0, OPT1, thread);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetWrapped3() {
        System.out.println("get (with wrapped dynamicArguments)");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS), "ecjapp.eval.problem.ThreadDynamicArguments");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS).push(ThreadDynamicArguments.P_OPT), OPT2);
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS).push(ThreadDynamicArguments.P_MODULO), "5");
        sut.setup(state, BASE);
        final int thread = 17;
        final String expResult = String.format(" %s %s %s %s", OPT2, 2, OPT1, thread);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testGetWrapped4() {
        System.out.println("get (with wrapped dynamicArguments)");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS), "ecjapp.eval.problem.ThreadDynamicArguments");
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS).push(ThreadDynamicArguments.P_OPT), OPT2);
        state.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS).push(ThreadDynamicArguments.P_MODULO), "5");
        sut.setup(state, BASE);
        final int thread = 2;
        final String expResult = String.format(" %s %s %s %s", OPT2, 2, OPT1, thread);
        String result = sut.get(state, thread);
        assertEquals(expResult, result);
    }

    @Test
    public void testEquals() {
        System.out.println("equals");

        final EvolutionState state1 = getFreshState();
        final EvolutionState state2 = getFreshState();
        state2.parameters.set(BASE.push(ThreadDynamicArguments.P_MODULO), "5");
        final EvolutionState state3 = getFreshState();
        state3.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS), "ecjapp.eval.problem.ThreadDynamicArguments");
        state3.parameters.set(BASE.push(ThreadDynamicArguments.P_DYNAMIC_ARGUMENTS).push(ThreadDynamicArguments.P_OPT), OPT2);

        sut.setup(state, BASE);
        final ThreadDynamicArguments sut1 = new ThreadDynamicArguments();
        sut1.setup(state1, BASE);
        final ThreadDynamicArguments sut2 = new ThreadDynamicArguments();
        sut2.setup(state2, BASE);
        final ThreadDynamicArguments sut3 = new ThreadDynamicArguments();
        sut3.setup(state3, BASE);

        assertTrue(sut.equals(sut));
        assertTrue(sut.equals(sut1));
        assertFalse(sut.equals(sut2));
        assertFalse(sut.equals(sut3));
        assertFalse(sut2.equals(sut));
        assertFalse(sut3.equals(sut));

        assertEquals(sut.hashCode(), sut1.hashCode());
        assertFalse(sut.hashCode() == sut2.hashCode());
        assertFalse(sut.hashCode() == sut3.hashCode());
    }
}


text:
    <input type="checkbox" {{#selected}}checked{{/selected}} name="{{ value }}">
    {{#if title}}
      {{ title }}
    {{else}}
      {{ value }}
    {{/if}}


text:
import sys
from PyQt4.QtGui import QIntValidator, QDoubleValidator, QApplication, QSizePolicy
from Orange.widgets import widget, gui
from Orange.widgets.settings import Setting
from Orange.data import Table, Domain, ContinuousVariable
import numpy as np

#try:
#    from ..tools.xoppy_calc import xoppy_doc
#except ImportError:
#    print("Error importing: xoppy_doc")
#    raise

#try:
#    from ..tools.xoppy_calc import xoppy_calc_xinpro
#except ImportError:
#    print("compute pressed.")
#    print("Error importing: xoppy_calc_xinpro")
#    raise

class OWxinpro(widget.OWWidget):
    name = "xinpro"
    id = "orange.widgets.dataxinpro"
    description = "xoppy application to compute..."
    icon = "icons/xoppy_xinpro.png"
    author = "create_widget.py"
    maintainer_email = "srio@esrf.eu"
    priority = 10
    category = ""
    keywords = ["xoppy", "xinpro"]
    outputs = [#{"name": "xoppy_data",
               # "type": np.ndarray,
               # "doc": ""},
               {"name": "xoppy_table",
                "type": Table,
                "doc": ""},
               {"name": "xoppy_specfile",
                "type": str,
                "doc": ""}]

    #inputs = [{"name": "Name",
    #           "type": type,
    #           "handler": None,
    #           "doc": ""}]

    want_main_area = False

    CRYSTAL_MATERIAL = Setting(0)
    MODE = Setting(0)
    ENERGY = Setting(8000.0)
    MILLER_INDEX_H = Setting(1)
    MILLER_INDEX_K = Setting(1)
    MILLER_INDEX_L = Setting(1)
    ASYMMETRY_ANGLE = Setting(0.0)
    THICKNESS = Setting(500.0)
    TEMPERATURE = Setting(300.0)
    NPOINTS = Setting(100)
    SCALE = Setting(0)
    XFROM = Setting(-50.0)
    XTO = Setting(50.0)

    def __init__(self):
        super().__init__()

        box0 = gui.widgetBox(self.controlArea, " ",orientation="horizontal")
        #widget buttons: compute, set defaults, help
        gui.button(box0, self, "Compute", callback=self.compute)
        gui.button(box0, self, "Defaults", callback=self.defaults)
        gui.button(box0, self, "Help", callback=self.help1)
        self.process_showers()
        box = gui.widgetBox(self.controlArea, " ",orientation="vertical")

        idx = -1

        #widget index 0
        idx += 1
        box1 = gui.widgetBox(box)
        gui.comboBox(box1, self, "CRYSTAL_MATERIAL",
                     label=self.unitLabels()[idx], addSpace=True,
                    items=['Silicon', 'Germanium', 'Diamond', 'GaAs', 'GaP', 'InAs', 'InP', 'InSb', 'SiC', 'CsF', 'KCl', 'LiF', 'NaCl', 'Graphite', 'Beryllium'],
                    valueType=int, orientation="horizontal")
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 1
        idx += 1
        box1 = gui.widgetBox(box)
        gui.comboBox(box1, self, "MODE",
                     label=self.unitLabels()[idx], addSpace=True,
                    items=['Reflectivity in Bragg case', 'Transmission in Bragg case', 'Reflectivity in Laue case', 'Transmission in Laue case'],
                    valueType=int, orientation="horizontal")
        print(" >>>>>>>>>>>>>>>>>>>> MODE: ")
        print(self.unitFlags()[idx])
        print(" >>>>>>>>>>>>>>>>>>>> MODE END: ")
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 2
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "ENERGY",
                     label=self.unitLabels()[idx], addSpace=True,
                    valueType=float, validator=QDoubleValidator())
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 3
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "MILLER_INDEX_H",
                     label=self.unitLabels()[idx], addSpace=True,
                    valueType=int, validator=QIntValidator())
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 4
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "MILLER_INDEX_K",
                     label=self.unitLabels()[idx], addSpace=True,
                    valueType=int, validator=QIntValidator())
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 5
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "MILLER_INDEX_L",
                     label=self.unitLabels()[idx], addSpace=True,
                    valueType=int, validator=QIntValidator())
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 6
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "ASYMMETRY_ANGLE",
                     label=self.unitLabels()[idx], addSpace=True,
                    valueType=float, validator=QDoubleValidator())
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 7
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "THICKNESS",
                     label=self.unitLabels()[idx], addSpace=True,
                    valueType=float, validator=QDoubleValidator())
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 8
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "TEMPERATURE",
                     label=self.unitLabels()[idx], addSpace=True,
                    valueType=float, validator=QDoubleValidator())
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 9
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "NPOINTS",
                     label=self.unitLabels()[idx], addSpace=True,
                    valueType=int, validator=QIntValidator())
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 10
        idx += 1
        box1 = gui.widgetBox(box)
        gui.comboBox(box1, self, "SCALE",
                     label=self.unitLabels()[idx], addSpace=True,
                    items=['Automatic', 'External'],
                    valueType=int, orientation="horizontal")
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 11
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "XFROM",
                     label=self.unitLabels()[idx], addSpace=True,
                    valueType=float, validator=QDoubleValidator())
        self.show_at(self.unitFlags()[idx], box1)

        #widget index 12
        idx += 1
        box1 = gui.widgetBox(box)
        gui.lineEdit(box1, self, "XTO",
                     label=self.unitLabels()[idx], addSpace=True,
                    valueType=float, validator=QDoubleValidator())
        self.show_at(self.unitFlags()[idx], box1)

        gui.rubber(self.controlArea)

    def unitLabels(self):
         return ['Crystal material: ','Calculation mode:','Energy [eV]:','Miller index H:','Miller index K:','Miller index L:','Asymmetry angle:','Crystal thickness [microns]:','Crystal temperature [K]:','Number of points: ','Angular limits: ','Theta min [arcsec]:','Theta max [arcsec]:']

    def unitFlags(self):
         return ['True','False','True','True','True','True','True','True','True','True','True','self.SCALE  ==  1','self.SCALE  ==  1']

    #def unitNames(self):
    #     return ['CRYSTAL_MATERIAL','MODE','ENERGY','MILLER_INDEX_H','MILLER_INDEX_K','MILLER_INDEX_L','ASYMMETRY_ANGLE','THICKNESS','TEMPERATURE','NPOINTS','SCALE','XFROM','XTO']

    def compute(self):
        fileName = xoppy_calc_xinpro(CRYSTAL_MATERIAL=self.CRYSTAL_MATERIAL,MODE=self.MODE,ENERGY=self.ENERGY,MILLER_INDEX_H=self.MILLER_INDEX_H,MILLER_INDEX_K=self.MILLER_INDEX_K,MILLER_INDEX_L=self.MILLER_INDEX_L,ASYMMETRY_ANGLE=self.ASYMMETRY_ANGLE,THICKNESS=self.THICKNESS,TEMPERATURE=self.TEMPERATURE,NPOINTS=self.NPOINTS,SCALE=self.SCALE,XFROM=self.XFROM,XTO=self.XTO)
        #send specfile
        self.send("xoppy_specfile",fileName)

        print("Loading file:  ",fileName)
        #load spec file with one scan, # is comment
        out = np.loadtxt(fileName)
        print("data shape: ",out.shape)
        #get labels
        txt = open(fileName).readlines()
        tmp = [ line.find("#L") for line in txt]
        itmp = np.where(np.array(tmp) != (-1))
        labels = txt[itmp[0]].replace("#L ","").split("  ")
        print("data labels: ",labels)
        #
        # build and send orange table
        #
        domain = Domain([ ContinuousVariable(i) for i in labels ])
        table = Table.from_numpy(domain, out)
        self.send("xoppy_table",table)

    def defaults(self):
         self.resetSettings()
         self.compute()
         return

    def help1(self):
        print("help pressed.")
        xoppy_doc('xinpro')

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = OWxinpro()
    w.show()
    app.exec()
    w.saveSettings()


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Craig Field / Selma, AL</location>
	<station_id>KSEM</station_id>
	<latitude>32.35</latitude>
	<longitude>-86.98333</longitude>
	<observation_time>Last Updated on Dec 24 2015, 12:30 pm CST</observation_time>
        <observation_time_rfc822>Thu, 24 Dec 2015 12:30:00 -0600</observation_time_rfc822>
	<weather>Partly Cloudy</weather>
	<temperature_string>72.0 F (22.0 C)</temperature_string>
	<temp_f>72.0</temp_f>
	<temp_c>22.0</temp_c>
	<relative_humidity>88</relative_humidity>
	<wind_string>Southeast at 8.1 MPH (7 KT)</wind_string>
	<wind_dir>Southeast</wind_dir>
	<wind_degrees>140</wind_degrees>
	<wind_mph>8.1</wind_mph>
	<wind_kt>7</wind_kt>
	<pressure_in>29.99</pressure_in>
	<dewpoint_string>68.0 F (20.0 C)</dewpoint_string>
	<dewpoint_f>68.0</dewpoint_f>
	<dewpoint_c>20.0</dewpoint_c>
	<visibility_mi>10.00</visibility_mi>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/KSEM.html</two_day_history_url>
	<icon_url_name>sct.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/KSEM.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
package org.azrul.langkuik.framework;

import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.MappedSuperclass;
import org.azrul.langkuik.system.model.user.User;

/**
 *
 * @author Azrul
 */
@MappedSuperclass
public abstract class Work<T> {

    @Enumerated(EnumType.STRING)
    @Column(name = "STATUS")
    protected T status;

    @Column(name = "PREVIOUS_STATUS")
    protected T previousStatus;

    @Column(name = "CURRENT_OWNER")
    protected User currentOwner;

    @Column(name= "PREVIOUS_MESSAGE")
    protected String previousMessage;

    protected T getStatus() {
        return status;
    }

    protected void setStatus(T status) {
        this.status = status;
    }

    protected User getCurrentOwner() {
        return currentOwner;
    }

    protected void setCurrentOwner(User currentOwner) {
        this.currentOwner = currentOwner;
    }

    public T getPreviousStatus() {
        return previousStatus;
    }

    public void setPreviousStatus(T previousStatus) {
        this.previousStatus = previousStatus;
    }

    public String getPreviousMessage() {
        return previousMessage;
    }

    public void setPreviousMessage(String previousMessage) {
        this.previousMessage = previousMessage;
    }

    public class Result{

        public Result() {
        }
        protected T nextWorklist;
        protected String message;

        public T getNextWorklist() {
            return nextWorklist;
        }

        public void setNextWorklist(T nextWorklist) {
            this.nextWorklist = nextWorklist;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public void run(){

        }
    }

}


text:
function version(self)

% Version of 19-Jul-2001 16:52:00.

% svn $Id: version.m 361 2009-07-02 15:43:20Z arango $
%=======================================================================
% Copyright (C) 1996 Dr. Charles R. Denham, ZYDECO.
%  All Rights Reserved.
%   Disclosure without written consent from the
%    copyright owner does not constitute publication.
%=======================================================================

helpdlg(help(mfilename), 'presto')


text:
class CreateArticleProducts < ActiveRecord::Migration
  def self.up
    create_table :article_products do |t|
      t.references :article
      t.references :product
      t.integer    :position
    end
  end

  def self.down
    drop_table :article_products
  end
end


text:
package com.vendor.rx;

import java.util.UUID;
import java.util.logging.Logger;

import javax.jws.WebService;

import com.vendor.model.RequestStatus;
import com.vendor.rx.model.RxDataRequest;
import com.vendor.rx.model.RxDataResponse;
import com.vendor.rx.model.RxDataStatusResponse;

/**
 *
 * @author rj
 *
 */
@WebService(endpointInterface = "com.vendor.rx.RxDataRecordsService")
public class RxDataRecordsServiceImpl implements RxDataRecordsService {

	/**
	 *
	 */
	private Logger logger = Logger.getLogger("com.vendor.rx.RxDataRecordsServiceImpl");

	@Override
	public RxDataStatusResponse checkRequestStatus(String transactionId) {
		logger.info("Received transaction ID: " + transactionId);

		RxDataStatusResponse rxDataStatusResponse = new RxDataStatusResponse();
		rxDataStatusResponse.setRequestStatus(RequestStatus.INPROGRESS);
		rxDataStatusResponse.setTransactionId(transactionId);

		return rxDataStatusResponse;
	}

	@Override
	public RxDataResponse requestRxDataRecords(RxDataRequest request) {
		logger.info("Received last name: " + request.getLastName());
		logger.info("Received government ID: " + request.getGovernmentId());

		String transactionId = UUID.randomUUID().toString();
		logger.info("Generated transaction ID: " + transactionId);

		RxDataResponse rxDataResponse = new RxDataResponse();
		rxDataResponse.setTransactionId(transactionId);
		rxDataResponse.setTransactionSuccessful(true);

		return rxDataResponse;
	}
}


text:
'use strict';
const LintError = require('./lint-error');

/**
 *
 *
 * @class TSLintError
 * @extends {LintError}
 */
class TSLintError extends LintError {
	constructor (error) {
		super({
			// 文件名
			// fileName: error.fileName,

			// TSLint无警告,错误等级全部算错误
			severity: 'error',

			// 行号
			lineNumber: error.startPosition.lineAndCharacter.line + 1,

			// 列号
			columnNumber: error.startPosition.lineAndCharacter.character + 1,

			// 错误信息
			message: error.failure,

			// 触发错误的规则
			rule: error.ruleName,

			// 源代码上下文
			source: error.rawLines,

			// 报错插件
			plugin: 'TSLint',

			// 文档
			doc: error.ruleName && `https://palantir.github.io/tslint/rules/${error.ruleName}/`,
		}, error);
	}
}

module.exports = TSLintError;


text:
CREATE TABLE user (
	id	INTEGER IDENTITY PRIMARY KEY,
	user_id		VARCHAR(30),
	user_name		VARCHAR(30),
	password	VARCHAR(30)
);


text:
namespace Merchello.Core.Persistence.Migrations.Upgrades.TargetVersionTwoThreeZero
{
	using Merchello.Core.Configuration;

	using Umbraco.Core;
	using Umbraco.Core.Logging;
	using Umbraco.Core.Persistence;
	using Umbraco.Core.Persistence.Migrations;
	using Umbraco.Core.Persistence.SqlSyntax;

	/// <summary>
	/// Migration to update the description field size in the merchAppliedPayment table
	/// </summary>
	/// <remarks>
	/// See issue http://issues.merchello.com/youtrack/issue/M-682 for details
	/// </remarks>
	/// <seealso cref="Umbraco.Core.Persistence.Migrations.MigrationBase" />
	/// <seealso cref="Merchello.Core.Persistence.Migrations.IMerchelloMigration" />
	[Migration("2.3.0", 1, MerchelloConfiguration.MerchelloMigrationName)]
	public class AlterAppliedPaymentDescriptionFieldSize : MerchelloMigrationBase, IMerchelloMigration
	{
		/// <summary>
		/// Updates the column size
		/// </summary>
		public override void Up()
		{
			var database = ApplicationContext.Current.DatabaseContext.Database;

			var databaseSchemaHelper = new DatabaseSchemaHelper(database, this.Logger, this.SqlSyntax);
			if (databaseSchemaHelper.TableExist("merchAppliedPayment"))
			{
                // Add another assertion that the field size has not already been changed to 500
                // and some other migration failed which flagged the version to 2.2.0 or earlier
			    var size = database.GetDbTableColumnSize("merchAppliedPayment", "description");

                if (size == 500) return;

                // Update the column to allow for 500 characters instead of 255 which proved too small
                Alter.Table("merchAppliedPayment").AlterColumn("description").AsString(500).NotNullable();
			}
		}

		/// <summary>
		/// Undoes the column size update
		/// </summary>
		/// <exception cref="DataLossException">Cannot downgrade from a version 2.3.0 database to a prior version, the database schema has already been modified</exception>
		public override void Down()
		{
			throw new DataLossException("Cannot downgrade from a version 2.3.0 database to a prior version, the database schema has already been modified");
		}
	}
}


text:
#ifndef WEBRTC_VIDEO_ENGINE_MAIN_TEST_AUTOTEST_INTERFACE_TB_VIDEO_CHANNEL_H_
#define WEBRTC_VIDEO_ENGINE_MAIN_TEST_AUTOTEST_INTERFACE_TB_VIDEO_CHANNEL_H_

#include "tb_interfaces.h"
class tbVideoChannel
{
public:
    tbVideoChannel(tbInterfaces& Engine, int& nrOfErrors,
                   webrtc::VideoCodecType sendCodec = webrtc::kVideoCodecVP8,
                   int width = 352, int height = 288, int frameRate = 30,
                   int startBitrate = 300);

    ~tbVideoChannel(void);

    void SetFrameSettings(int width, int height, int frameRate);

    void StartSend(const unsigned short rtpPort = 11000,
                   const char* ipAddress = "127.0.0.1");

    void StopSend();

    void StartReceive(const unsigned short rtpPort = 11000);

    void StopReceive();

    int videoChannel;
private:
    int& numberOfErrors;
    tbInterfaces& ViE;
};

#endif  // WEBRTC_VIDEO_ENGINE_MAIN_TEST_AUTOTEST_INTERFACE_TB_VIDEO_CHANNEL_H_


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.file;

import java.util.Objects;

/**
 * A regular UNIX-style user and its primary group.
 *
 * @author mpolden
 */
public class UnixUser {

    public static final UnixUser ROOT = new UnixUser("root", 0, "root", 0);

    private final String name;
    private final int uid;
    private final String group;
    private final int gid;

    public UnixUser(String name, int uid, String group, int gid) {
        this.name = name;
        this.uid = uid;
        this.group = group;
        this.gid = gid;
    }

    /** Username of this */
    public String name() { return name; }

    /** User ID of this */
    public int uid() { return uid; }

    /** Primary group of this */
    public String group() { return group; }

    /** Primary group ID of this */
    public int gid() { return gid; }

    @Override
    public String toString() {
        return "user " + name + ":" + group;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UnixUser unixUser = (UnixUser) o;
        return uid == unixUser.uid && name.equals(unixUser.name) &&
                gid == unixUser.gid && group.equals(unixUser.group);
    }

    @Override
    public int hashCode() {
        return Objects.hash(uid, name, gid, group);
    }
}


text:
package org.apache.myfaces.trinidadinternal.style.xml.parse;

import org.xml.sax.Attributes;
import org.xml.sax.SAXParseException;

import org.apache.myfaces.trinidad.logging.TrinidadLogger;

import org.apache.myfaces.trinidadinternal.share.xml.LeafNodeParser;
import org.apache.myfaces.trinidadinternal.share.xml.ParseContext;

import org.apache.myfaces.trinidadinternal.style.StyleConstants;
import org.apache.myfaces.trinidadinternal.style.xml.XMLConstants;

/**
 * NodeParser for includeProperty nodes
 * @version $Name:  $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/style/xml/parse/IncludePropertyNodeParser.java#0 $) $Date: 10-nov-2005.18:58:08 $
 */
public class IncludePropertyNodeParser extends LeafNodeParser
  implements XMLConstants, StyleConstants
{
  /**
   * Implementation of NodeParser.startElement()
   */
  @Override
  public Object getNodeValue(
    ParseContext context,
    String       namespaceURI,
    String       localName,
    Attributes   attrs
    ) throws SAXParseException
  {
    String name = attrs.getValue(NAME_ATTR);
    String selector = attrs.getValue(SELECTOR_ATTR);
    String propertyName = getRequiredAttribute(context,
                                               attrs,
                                               PROPERTY_NAME_ATTR);
    String localPropertyName = attrs.getValue(LOCAL_PROPERTY_NAME_ATTR);

    if ((name == null) && (selector == null))
    {
      _LOG.warning(_INCLUDE_PROPERTY_ID_ERROR);
      return null;
    }

    if (propertyName == null)
      return null;

    return new IncludePropertyNode(name,
                                   selector,
                                   propertyName,
                                   localPropertyName);
  }

  private static final String _INCLUDE_PROPERTY_ID_ERROR =
    "<includeProperty> element must specify a selector or name attribute";
  private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger(IncludePropertyNodeParser.class);
}


text:
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;

namespace GM
{
	[Serializable]
	public class Command
	{
		[XmlAttribute]
		public string name;
		[XmlAttribute]
		public string desc;
		[XmlAttribute]
		public string defaultArg;
	}

	[Serializable]
	[XmlRootAttribute ("Commands")]
	public class CommandArray
	{
		[XmlArrayAttribute ("Items")]
		public Command[] items = new Command[0];
	}

	public class CommandManager : MonoBehaviour
	{
		const string assetsRuntimeConsoleResourcescmdxml = "Assets/CommandManager/Resources/Commands.xml";

		[SerializeField]
		CommandArray commands = null;

		public event Action<Command, string[]> onSubmit;

		Vector2 scrollPosition = Vector2.zero;
		Vector2 scrollPositionCMD = Vector2.zero;

		bool messageUpdated = false;

		ArrayList messages = new ArrayList ();
		string inputString = string.Empty;
		bool cmdOn = false;
		bool traceOn = false;

		[ContextMenu ("SaveCommands")]
		void SaveCommands ()
		{
			XmlSerializer serializer = new XmlSerializer (typeof(CommandArray));
			TextWriter writer = new StreamWriter (assetsRuntimeConsoleResourcescmdxml);
			serializer.Serialize (writer, commands);
		}

		void LoadCommands ()
		{
			XmlSerializer serializer = new XmlSerializer (typeof(CommandArray));
			TextReader reader = new StreamReader (assetsRuntimeConsoleResourcescmdxml);
			commands = serializer.Deserialize (reader) as CommandArray;
		}

		void Start ()
		{
			Application.logMessageReceived += Application_logMessageReceived;
			LoadCommands ();
		}

		void Application_logMessageReceived (string condition, string stackTrace, LogType type)
		{
			string[] colorNames = { "red", "red", "yellow", "white", "red" };
			var msg = string.Format ("<color={0}>{1}{2}</color>", colorNames [(int)type], condition, stackTrace);
			messages.Add (msg);
			messageUpdated = true;
		}

		void Submit ()
		{
			Debug.Log (string.Format ("[CommandManager] Submit: ", inputString));
			if (inputString.StartsWith ("@")) {
				if (commands != null && commands.items != null) {
					string[] fields = inputString.Split (new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
					string cmdName = fields [0].TrimStart ('@');
					var cmd = Array.Find (commands.items, delegate(Command obj) {
						return obj.name == cmdName;
					});
					int count = fields.Length - 1;
					string[] args = new string[count];
					if (count > 0) {
						Array.ConstrainedCopy (fields, 1, args, 0, count);
					}
					if (cmd != null) {
						if (onSubmit != null) {
							onSubmit.Invoke (cmd, args);
						}
					}
				}
			}
		}

		bool TryUseReturnOrEnter ()
		{
			if (Event.current.isKey && (Event.current.keyCode == KeyCode.KeypadEnter || Event.current.keyCode == KeyCode.Return)) {
				Event.current.Use ();
				return true;
			}
			return false;
		}

		void OnGUI ()
		{
			using (var v = new GUILayout.VerticalScope (GUILayout.Width (Screen.width), GUILayout.Height (Screen.height))) {
				GUILayout.FlexibleSpace ();
				if (traceOn) {
					if (messages.Count > 0) {
						using (var v1 = new GUILayout.VerticalScope ("box")) {
							using (var s = new GUILayout.ScrollViewScope (scrollPosition)) {
								float height = 0;
								for (int i = 0; i < messages.Count; i++) {
									var msg = messages [i] as string;
									GUIContent c = new GUIContent (msg);
									GUILayout.Label (c);
									height += GUI.skin.label.CalcSize (c).y;
								}
								scrollPosition = s.scrollPosition;
								if (messageUpdated) {
									scrollPosition.y = height;
									messageUpdated = false;
								}
							}
						}
					}
				}
				if (cmdOn) {
					using (var v1 = new GUILayout.VerticalScope ("Commands", "window")) {
						using (var s = new GUILayout.ScrollViewScope (scrollPositionCMD)) {
							var style = new GUIStyle(GUI.skin.button);
							style.alignment = TextAnchor.MiddleLeft;
							for (int i = 0; i < commands.items.Length; i++) {
								var item = commands.items [i];
								var itemName = string.Format ("{0}. {1} ({2} 默认参数 {3})", i, item.name, item.desc, item.defaultArg);
								if (GUILayout.Button (itemName, style)) {
									inputString = string.Format ("@{0} {1}", item.name, item.defaultArg);
								}
							}
							scrollPositionCMD = s.scrollPosition;
						}
					}
				}
				using (var h = new GUILayout.HorizontalScope ()) {
					traceOn = GUILayout.Toggle (traceOn, "Trace", "button", GUILayout.Width (64));
					cmdOn = GUILayout.Toggle (cmdOn, "CMD", "button", GUILayout.Width (64));
					inputString = GUILayout.TextField (inputString);
					if (GUILayout.Button ("Enter", GUILayout.Width (64)) || TryUseReturnOrEnter ()) {
						if (!string.IsNullOrEmpty (inputString)) {
							Submit ();
						}
					}
				}
				GUILayout.Space (6);
			}
		}
	}
}


text:
layout: post
title: "Markup: Syntax Highlighting"
author: mmistakes
tags: [code]
---

From Michael's Rose [Minimal Mistakes](https://mmistakes.github.io/minimal-mistakes/markup-syntax-highlighting).
Syntax highlighting is a feature that displays source code, in different colors and fonts according to the category of terms. This feature facilitates writing in a structured language such as a programming language or a markup language as both structures and syntax errors are visually distinct. [Highlighting](http://en.wikipedia.org/wiki/Syntax_highlighting) does not affect the meaning of the text itself; it is intended only for human readers.

### GFM Code Blocks

GitHub Flavored Markdown [fenced code blocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/) are supported. To modify styling and highlight colors edit `/_sass/syntax.scss`.

```css
#container {
  float: left;
  margin: 0 -240px 0 0;
  width: 100%;
}
```

{% highlight scss linenos %}
.highlight {
  margin: 0;
  padding: 1em;
  font-family: $monospace;
  font-size: $type-size-7;
  line-height: 1.8;
}
{% endhighlight %}

```html
{% raw %}<nav class="pagination" role="navigation">
  {% if page.previous %}
    <a href="{{ site.url }}{{ page.previous.url }}" class="btn" title="{{ page.previous.title }}">Previous article</a>
  {% endif %}
  {% if page.next %}
    <a href="{{ site.url }}{{ page.next.url }}" class="btn" title="{{ page.next.title }}">Next article</a>
  {% endif %}
</nav><!-- /.pagination -->{% endraw %}
```

```ruby
module Jekyll
  class TagIndex < Page
    def initialize(site, base, dir, tag)
      @site = site
      @base = base
      @dir = dir
      @name = 'index.html'
      self.process(@name)
      self.read_yaml(File.join(base, '_layouts'), 'tag_index.html')
      self.data['tag'] = tag
      tag_title_prefix = site.config['tag_title_prefix'] || 'Tagged: '
      tag_title_suffix = site.config['tag_title_suffix'] || '–'
      self.data['title'] = "#{tag_title_prefix}#{tag}"
      self.data['description'] = "An archive of posts tagged #{tag}."
    end
  end
end
```

### Code Blocks in Lists

Indentation matters. Be sure the indent of the code block aligns with the first non-space character after the list item marker (e.g., `1.`). Usually this will mean indenting 3 spaces instead of 4.

1. Do step 1.
2. Now do this:

   ```ruby
   def print_hi(name)
     puts "Hi, #{name}"
   end
   print_hi('Tom')
   #=> prints 'Hi, Tom' to STDOUT.
   ```

3. Now you can do this.

### GitHub Gist Embed

An example of a Gist embed below.

<script src="https://gist.github.com/mmistakes/77c68fbb07731a456805a7b473f47841.js"></script>

### Source


text:
class RemoveScNumberOnEpisodes < ActiveRecord::Migration
  def change
    remove_index :episodes, name: 'index_episodes_on_work_id_and_sc_number'
    remove_index :episodes, :sc_number
    remove_column :episodes, :sc_number
  end
end


text:
/**
 * @file
 * Terms of service element styles.
 */

.webform-terms-of-service-details {
  border: 1px solid #ccc;
  padding: .5em 1em;
  margin: .5em 0;
}

.webform-terms-of-service-details--title {
  font-weight: bold;
}


text:
IMPORTED_RE = False

try:
    import regex
except ImportError:
    import re as regex
    IMPORTED_RE = True
    # This handling of import regex error does not really mean that
    # we are able to work without regex being installed. It means that
    # whylog can work with these python versions, which don't handle
    # regex module(like pypy, pypy3). So if you use cpython 2.5-3.5
    # please install regex module. That will improve whylog performance.

assert regex

class CompareResult(object):
    LT, EQ, GT = -1, 0, 1


text:
// Copyright (c) CodeSmith Tools, LLC. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;

namespace CodeSmith.SchemaHelper {
    /// <summary>
    /// Interface that describes the contract for an Entity.
    /// </summary>
    public interface IAssociation : ICommonEntityProperty {
        /// <summary>
        /// This is the name of the Association from the DataSource.
        /// </summary>
        string AssociationKeyName { get; }

        /// <summary>
        /// This is the unique key of the Association.
        /// </summary>
        string AssociationKey { get; }

        /// <summary>
        /// The namespace that the Association belongs in.
        /// </summary>
        string Namespace { get; }

        #region Properties

        /// <summary>
        /// Returns the association type of the first associated property.
        /// </summary>
        AssociationType AssociationType { get; }

        /// <summary>
        /// Returns the Entity.
        /// </summary>
        IEntity Entity { get; }

        /// <summary>
        /// Returns the Associated Entity.
        /// </summary>
        IEntity ForeignEntity { get; }

        /// <summary>
        /// Returns the Intermediary Entity for a Many to Many Association
        /// </summary>
        IAssociation IntermediaryAssociation { get; }

        /// <summary>
        /// Returns true if the current association was created by the parent table and not the child.
        /// </summary>
        bool IsParentEntity { get; }

        /// <summary>
        /// Returns a list of all the Properties of this Association.
        /// </summary>
        List<AssociationProperty> Properties { get; }

        /// <summary>
        /// The resolved Type Name for this Association.
        /// </summary>
        string TypeName { get; }

        /// <summary>
        /// Resolved GenericProperty for this Association.
        /// </summary>
        string GenericProperty { get; }

        /// <summary>
        /// Set name without formatting it.
        /// </summary>
        /// <param name="name"></param>
        void SetName(string name);

        /// <summary>
        /// Expands an associations name into the full name with column properties.
        /// </summary>
        void MakeUnique();

        /// <summary>
        /// The SearchCriteria for this Association.
        /// </summary>
        SearchCriteria SearchCriteria { get; set; }

        #endregion

        #region Accessibility Modifiers

        /// <summary>
        /// Controls the Access Modifier the class is defined with.
        /// </summary>
        string TypeAccess { get; }

        /// <summary>
        /// The Getter Access of the Association.
        /// </summary>
        string GetterAccess { get; }

        /// <summary>
        /// The Setter Access of the Association.
        /// </summary>
        string SetterAccess { get; }

        #endregion
    }
}


text:
import math
import random

random.seed(100) # TODO: Find a way of sharing seed

def stepGen(base, avail):
    if not (hasattr(base, '__divmod__') and hasattr(avail, '__divmod__')):
        return None
    elif base < 0 or avail < 0:
        return None
    else:
        return 0 if not avail else int(math.floor(base/avail))

def stepRange(base, n):
    if not (hasattr(base, '__divmod__') and hasattr(n, '__divmod__')):
        return None
    elif base <= n:
        return [i for i in range(base)]

    step = stepGen(base, n) or 1
    seq = [i for i in range(step-1, base, step)]

    seqLen = len(seq)
    while seqLen > n:
        randPick = random.randint(0, seqLen-2)
        seq.pop(randPick)
        seqLen = len(seq)

    return seq

def rangeSearch(sortedList, query):
    # Binary search algorithm however that returns (lowElem, highElem,)
    # where lowElem = l[low], highElem = l[high]. This helps give the range of an element
    # In the even that an item is present, lowElem = highElem = l[mid]
    low, high = 0, len(sortedList)-1
    lC = hC = None
    while low <= high:
        mid = (low + high)>>1
        if sortedList[mid] == query:
            lC = hC = mid
            break
        elif query < sortedList[mid]:
            hC = mid
            high = mid - 1
        else:
            lC = mid
            low = mid + 1

    return lC, hC

def acquireIndex(seq, query):
    sResult = rangeSearch(seq, query)
    # Greedy search
    tIndex, l = 0, len(sResult)
    while tIndex < l:
        if sResult[tIndex] is not None:
            return sResult[tIndex]
        tIndex += 1

def main():
    sRange = stepRange(10, 6)
    print('Srange', sRange)
    print(acquireIndex(sRange, 10))
    print(acquireIndex(sRange, 0))
    print(acquireIndex(sRange, 5))
    print(acquireIndex(sRange, -1))
    print(acquireIndex(sRange, 12))

if __name__ == '__main__':
    main()


text:
'''
Run the tests using testrunner.py script in the project root directory.

Usage: testrunner.py SDK_PATH TEST_PATH
Run unit tests for App Engine apps.

SDK_PATH    Path to the SDK installation
TEST_PATH   Path to package containing test modules

Options:
  -h, --help  show this help message and exit

'''
import unittest
import webapp2
import os
import webtest
from google.appengine.ext import testbed

from mock import Mock
from mock import patch

import boilerplate
from boilerplate import models
from boilerplate import routes
from boilerplate import routes as boilerplate_routes
from boilerplate import config as boilerplate_config
from boilerplate.lib import utils
from boilerplate.lib import captcha
from boilerplate.lib import i18n
from boilerplate.lib import test_helpers

# setting HTTP_HOST in extra_environ parameter for TestApp is not enough for taskqueue stub
os.environ['HTTP_HOST'] = 'localhost'

# globals
network = False

# mock Internet calls
if not network:
    i18n.get_territory_from_ip = Mock(return_value=None)

class AppTest(unittest.TestCase, test_helpers.HandlerHelpers):
    def setUp(self):

        webapp2_config = boilerplate_config.config

        # create a WSGI application.
        self.app = webapp2.WSGIApplication(config=webapp2_config)
        routes.add_routes(self.app)
        boilerplate_routes.add_routes(self.app)
        self.testapp = webtest.TestApp(self.app, extra_environ={'REMOTE_ADDR' : '127.0.0.1'})

        # activate GAE stubs
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_taskqueue_stub()
        self.testbed.init_mail_stub()
        self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME)
        self.taskqueue_stub = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME)
        self.testbed.init_user_stub()

        self.headers = {'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) Version/6.0 Safari/536.25',
                        'Accept-Language' : 'en_US'}

        # fix configuration if this is still a raw boilerplate code - required by test with mails
        if not utils.is_email_valid(self.app.config.get('contact_sender')):
            self.app.config['contact_sender'] = "noreply-testapp@example.com"
        if not utils.is_email_valid(self.app.config.get('contact_recipient')):
            self.app.config['contact_recipient'] = "support-testapp@example.com"

    def tearDown(self):
        self.testbed.deactivate()

    def test_homepage(self):
        response = self.get('/')
        self.assertIn('Congratulations on your Google App Engine Boilerplate powered page.', response)

    def test_homepage_has_no_calls_create_login_url(self):
        with patch('google.appengine.api.users.create_login_url') as create_login_url:
            self.get('/')
        self.assertEqual(0, create_login_url.call_count)

    def test_csrf_protection(self):
        self.register_activate_testuser()
        self.post('/login/',
                dict(username='testuser', password='password'), status=403)

    def test_login_from_homepage(self):
        self.register_activate_testuser()

        form = self.get_form('/', 'form_login_user')
        form['username'] = 'testuser'
        form['password'] = '123456'
        self.submit(form)
        self.assert_user_logged_in()

    def test_login_invalid_password(self):
        self.register_activate_testuser()

        form = self.get_form('/', 'form_login_user')
        form['username'] = 'testuser'
        form['password'] = 'wrongpassword'
        self.submit(form, expect_error=True, error_message='Your username or password is incorrect')
        self.assert_user_not_logged_in()

    def test_login_not_activated(self):
        self.register_testuser()

        form = self.get_form('/', 'form_login_user')
        form['username'] = 'testuser'
        form['password'] = '123456'
        self.submit(form, expect_error=True, error_message='Please check your email to activate it')
        self.assert_user_not_logged_in()

    def _login_openid(self, provider, uid, email=None):
        openid_user = Mock()
        openid_user.federated_identity.return_value = uid
        openid_user.email.return_value = email
        with patch('google.appengine.api.users.get_current_user', return_value=openid_user):
            response = self.get('/social_login/{}/complete'.format(provider), status=302)
            response = response.follow(status=200, headers=self.headers)
        return response

    def test_login_openid_add_association(self):
        response = self._login_openid('google', 'http://www.google.com/accounts/123')
        self.assert_success_message_in_response(response, 'Welcome!  You have been registered as a new user')
        self.assert_user_logged_in()

    def test_login_openid_with_email_add_association(self):
        response = self._login_openid('google', 'http://www.google.com/accounts/123', 'testuser@example.com')
        self.assert_success_message_in_response(response, 'Welcome!  You have been registered as a new user')
        self.assert_user_logged_in()
        user = models.User.query().get()
        self.assertEqual('testuser@example.com', user.email)

    def test_login_openid(self):
        user = self.register_activate_testuser()
        models.SocialUser(user=user.key, provider='google', uid='http://www.google.com/accounts/123').put()
        self._login_openid('google', uid='http://www.google.com/accounts/123')
        self.assert_user_logged_in(user_id=user.get_id())

    def test_login_twitter_no_association(self):
        response = self._test_login_twitter()
        self.assert_success_message_in_response(response, "Welcome!  You have been registered as a new user")
        self.assert_user_logged_in()

    def test_login_twitter_add_association(self):
        self.register_activate_login_testuser()
        response = self._test_login_twitter()
        self.assert_success_message_in_response(response, 'Twitter association added.')

    def test_login_twitter(self):
        user = self.register_activate_testuser()
        models.SocialUser(user=user.key, provider='twitter', uid='7588892').put()
        self._test_login_twitter()
        self.assert_user_logged_in()

    def _test_login_twitter(self):
        oauth_token = 'NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0'
        oauth_token_secret = 'veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI'
        oauth_callback_confirmed = 'true'
        oauth_verifier = 'uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY'
        user_id = '7588892'
        access_token = '{}-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4'.format(user_id)
        oauth_token_secret2 = 'PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo'
        screen_name = 'testuser'

        class Response:
            def __init__(self, content):
                self.content = content
            def readlines(self):
                return self.content.split('\n')

        urlopen = Mock(side_effect=[Response('oauth_token={}&oauth_token_secret={}&oauth_callback_confirmed=true'.
                                           format(oauth_token, oauth_token_secret, oauth_callback_confirmed)),
                                  Response('oauth_token={}&oauth_token_secret={}&user_id={}&screen_name={}'.
                                           format(access_token, oauth_token_secret2, user_id, screen_name)),
                                  Response('{"id":%s}' % user_id)])
        with patch('urllib2.urlopen', urlopen):
            response = self.get('/social_login/twitter', status=302)
            self.assertTrue(response.headers['Location'].startswith('http://api.twitter.com/oauth/authenticate?'))

            self.assertEquals(urlopen.call_count, 1)
            self.assertTrue(urlopen.call_args_list[0][0][0].
                            startswith('https://api.twitter.com/oauth/request_token?'))

            response = self.get('/social_login/twitter/complete?oauth_token={}&oauth_verifier={}'.
                                format(oauth_token, oauth_verifier), status=302)
            self.assertEquals(urlopen.call_count, 2)
            self.assertTrue(urlopen.call_args_list[1][0][0].
                            startswith('https://api.twitter.com/oauth/access_token?'))

            response = response.follow(status=200, headers=self.headers)
            return response

    def test_resend_activation_mail(self):
        self.register_testuser()

        # login with valid credentials
        form = self.get_form('/', 'form_login_user')
        form['username'] = 'testuser'
        form['password'] = '123456'
        # account is not activated
        response = self.submit(form, expect_error=True, error_message='Please check your email to activate it')
        self.assert_user_not_logged_in()
        # "lose" activation mail
        self.get_sent_messages(to='testuser@example.com')[0]

        # resend the activation mail
        response2 = response.click(description='click here').follow(status=200, headers=self.headers)
        self.assert_success_message_in_response(response2,
                "The verification email has been resent to testuser@example.com.")

        # click again should fail
        response = response.click(description='click here').follow(status=200, headers=self.headers)
        self.assert_error_message_in_response(response, 'The link is invalid.')

        message = self.get_sent_messages(to='testuser@example.com')[0]
        url = self.get_url_from_message(message, 'activation')
        response = self.get(url, status=302).follow(status=200, headers=self.headers)
        self.assert_success_message_in_response(response,
                message='Congratulations, Your account testuser has been successfully activated.')

    def test_request_with_no_user_agent_header(self):
        self.get('/', headers={'Accept-Language' : 'en_US'})

    def test_request_with_no_accept_language_header(self):
        self.get('/', headers={'User-Agent' : 'Safari'})

    def test_request_with_no_headers(self):
        self.get('/', headers=None)

    def test_edit_profile(self):
        self.get('/settings/profile', status=302) # not for anonymous
        user = self.register_activate_login_testuser()

        form = self.get_form('/settings/profile', 'form_edit_profile')
        self.assertEqual(form['username'].value, 'testuser')
        self.assertEqual(form['name'].value, '')
        self.assertEqual(form['last_name'].value, '')
        self.assertEqual(form['country'].value, '')
        self.submit(form, success_message='your settings have been saved.')

        form['username'] = 'testuser2'
        form['name'] = 'Test'
        form['last_name'] = 'User'
        form['country'] = 'US'
        self.submit(form, success_message='your settings have been saved.')
        self.assertEqual(user.username, 'testuser2')
        self.assertEqual(user.name, 'Test')
        self.assertEqual(user.last_name, 'User')
        self.assertEqual(user.country, 'US')

        self.testapp.reset()
        self.login_user('testuser2', '123456')

    def test_logout(self):
        self.register_activate_login_testuser()
        self.get('/logout/', status=302)
        self.assert_user_not_logged_in()

    def test_edit_email(self):
        user = self.register_activate_login_testuser()

        form = self.get_form('/settings/email', 'form_edit_email', expect_fields=['new_email', 'password'])
        form['new_email'] = 'invalid_email-example.com'
        form['password'] = '123456'
        self.submit(form, expect_error=True, error_message='Invalid email address.')
        form['new_email'] = 'tu@example.com'
        form['password'] = '123'
        self.submit(form, expect_error=True, error_message='Incorrect password!')
        form['password'] = '123456'
        self.submit(form, success_message='Please check your new email for confirmation')

        message_old_address = self.get_sent_messages(to='testuser@example.com', reset_mail_stub=False)[0]
        message_new_address = self.get_sent_messages(to='tu@example.com')[0]
        self.assertEqual(message_old_address.sender, self.app.config.get('contact_sender'))
        self.assertEqual(message_new_address.sender, self.app.config.get('contact_sender'))
        self.assertIn("Recently you've changed the email address", message_old_address.html.payload)
        self.assertIn("You've changed the email address", message_new_address.html.payload)

        self.assertEqual(user.email, 'testuser@example.com')

        # click confirmation link
        url = self.get_url_from_message(message_new_address, 'change-email')
        self.get(url, status=302)

        self.assertEqual(user.email, 'tu@example.com')

    def test_password_reset(self):
        self.register_activate_testuser()

        form = self.get_form('/password-reset/', 'form_reset_password',
                             expect_fields=['email_or_username', 'recaptcha_challenge_field', 'recaptcha_response_field'])
        form['email_or_username'] = 'testuser'
        with patch('boilerplate.lib.captcha.submit', return_value=captcha.RecaptchaResponse(is_valid=False)):
            self.submit(form, expect_error=True, error_message='Wrong image verification code.')
        with patch('boilerplate.lib.captcha.submit', return_value=captcha.RecaptchaResponse(is_valid=True)):
            response1 = self.submit(form, warning_message="you will receive an email from us with instructions for resetting your password.")
            form['email_or_username'] = 'user_does_not_exists'
            response2 = self.submit(form, warning_message="you will receive an email from us with instructions for resetting your password.")
            page1 = response1.body, response1.request.url
            page2 = response2.body.replace('user_does_not_exists', 'testuser'), response2.request.url
            self.assertEqual(page1, page2, "for security reasons application should respond with the same page here")

        message = self.get_sent_messages(to='testuser@example.com')[0]
        self.assertEqual(message.sender, self.app.config.get('contact_sender'))
        self.assertIn('click the link below:', message.html.payload)

        # click password reset link and submit new password
        url = self.get_url_from_message(message, 'password-reset')
        self.get(url)
        form = self.get_form(url, 'form_new_password', expect_fields=['password', 'c_password'])
        self.assert_user_not_logged_in()
        form['password'] = form['c_password'] = '456456'
        self.submit(form, success_message='Password changed successfully')

        self.testapp.reset()
        self.login_user('testuser', '456456')

    def test_edit_password(self):
        self.register_activate_login_testuser()
        form = self.get_form('/settings/password', 'form_edit_password',
                             expect_fields=['current_password', 'password', 'c_password'])
        form['current_password'] = '123456'
        form['password'] = '789789'
        form['c_password'] = '789'
        self.submit(form, expect_error=True, error_message='Passwords must match.')
        form['c_password'] = '789789'
        self.submit(form)

        self.testapp.reset()
        self.login_user('testuser', '789789')

    def test_register(self):
        self._test_register('/register/',
                    expect_fields=['username', 'name', 'last_name', 'email', 'password', 'c_password', 'country', 'tz'])

    def test_register_from_home_page(self):
        self._test_register('/',
                    expect_fields=['username', 'email', 'country', 'password', 'c_password', 'tz'])

    def _test_register(self, url, form_id='form_register', expect_fields=None):
        form = self.get_form(url, form_id, expect_fields=expect_fields)

        # TODO: check mutliple validation errors on the form
        self.submit(form, expect_error=True, error_message='This field is required.', error_field='username')
        form['username'] = 'Reguser'
        form['email'] = 'reguser@example.com'
        form['password'] = form['c_password'] = '456456'
        self.submit(form, success_message='You were successfully registered. Please check your email to activate your account')

        message = self.get_sent_messages(to='reguser@example.com')[0]
        url = self.get_url_from_message(message, 'activation')

        # try to activate account with invalid token
        response = self.get(url+'qwe', status=302).follow(status=200, headers=self.headers)
        self.assert_error_message_in_response(response, 'The link is invalid.')

        response = self.get(url, status=302).follow(status=200, headers=self.headers)
        self.assert_success_message_in_response(response,
                message='Congratulations, Your account reguser has been successfully activated.')

        # activation token has already been used
        response = self.get(url, status=302).follow(status=200, headers=self.headers)
        self.assert_error_message_in_response(response, 'The link is invalid.')

        # activated user should be auto-logged in
        self.assert_user_logged_in()

    def test_contact(self):
        form = self.get_form('/contact/', 'form_contact',
                            expect_fields=['exception', 'name', 'email', 'message'])
        form['name'] = 'Anton'
        form['email'] = 'anton@example.com'
        form['message'] = 'Hi there...'
        self.submit(form)
        message = self.get_sent_messages(to=self.app.config.get('contact_recipient'))[0]
        self.assertEqual(message.sender, self.app.config.get('contact_sender'))
        self.assertIn('Hi there...', message.html.payload)

        self.register_activate_login_testuser()
        form = self.get_form('/contact/', 'form_contact')
        self.assertEqual(form['name'].value, '')
        self.assertEqual(form['email'].value, 'testuser@example.com')
        self.assertEqual(form['message'].value, '')
        form['message'] = 'help'
        self.submit(form, expect_error=True, error_field='name')
        form['name'].value = 'Antonioni'
        self.submit(form, expect_error=False)
        message = self.get_sent_messages(to=self.app.config.get('contact_recipient'))[0]
        self.assertIn('help', message.html.payload)

class ModelTest(unittest.TestCase):
    def setUp(self):

        # activate GAE stubs
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

    def tearDown(self):
        self.testbed.deactivate()

    def test_user_token(self):
        user = models.User(name="tester", email="tester@example.com")
        user.put()
        user2 = models.User(name="tester2", email="tester2@example.com")
        user2.put()

        token = models.User.create_signup_token(user.get_id())
        self.assertTrue(models.User.validate_signup_token(user.get_id(), token))
        self.assertFalse(models.User.validate_resend_token(user.get_id(), token))
        self.assertFalse(models.User.validate_signup_token(user2.get_id(), token))

if __name__ == "__main__":
    unittest.main()


text:
package com.shcem.common;

import com.alibaba.fastjson.annotation.JSONField;

/**
 * Created by lizhihua on 2017/2/16.
 */
public class RequestData {
    String MethodName;
    String ServiceName;
    @JSONField(name = "Params")
    public String getParams() {
        return Params;
    }

    public void setParams(String params) {
        Params = params;
    }
    @JSONField(name = "MethodName")
    public String getMethodName() {
        return MethodName;
    }

    public void setMethodName(String methodName) {
        MethodName = methodName;
    }
    @JSONField(name = "ServiceName")
    public String getServiceName() {
        return ServiceName;
    }

    public void setServiceName(String serviceName) {
        ServiceName = serviceName;
    }

    String Params;

}


text:
[Compiler tutorial](http://compilers.iecc.com/crenshaw/)
[x86_64 writing to stdout](http://0xax.blogspot.com/2014/11/say-hello-to-x64-assembly-part-4.html)
[More string printing in x86_64](https://stackoverflow.com/questions/27594297/how-to-print-a-string-to-the-terminal-in-x86-64-assembly-nasm-without-syscall)

## X86_64 Referece Material
https://nickdesaulniers.github.io/blog/2014/04/18/lets-write-some-x86-64/
# Notes On Introduction
## FPC
* OSX needs the free pascal compiler which is almost equivilent to turbo pascal.
* http://www.toosquare.com/2014/07/install-pascal-on-os-x/
## Assembly language
* 68000 code is the assembly language used.
* My Macbook uses X86_64
* TODO: Translate from 68000 to X86_64
* NOTE: Giving up on containing both 68000 code and X86. I'd need to get into
        full ABST or Bytecode in order to make it actually managable.

# EBNF Of The Languages

<expression> ::= <term> [<addop> <term>]*
<term> ::= <factor>  [ <mulop> <factor> ]*
<factor> ::= (<expression>)