text:
#  Kotlin Starter

 [![version][release-svg]][release-url] [![changelog][cl-svg]][cl-url] [![build][travis-svg]][travis-url] [![api-doc][apidoc-svg]][apidoc-url] [![gitter][gitter-svg]][gitter-url] [![license][license-svg]][license-url] [![kotlin][kotlin-svg]][kotlin-url]

 A starter template for my [kotlin][kotlin-url] projects using [Gradle Kotlin DSL][kotlin-dsl]!

### Download

* Binary

   [![Download][release-svg]][download-url]

   > After download, make sure to set the execute permission (`chmod +x @project@`).

   > Windows users can run the `executable jar` - [![Download][execjar-svg]][execjar-url].

### Build

* Source

    ```ruby
     $ git clone https://github.com/sureshg/@project@
     $ cd @project@
     $ ./gradlew makeExecutable -q
    ```
    > The binary would be located at `build/libs/@project@`

    Inorder to build a new version, change `appVersion` in the [gradle.properties](gradle.properties) or pass it to `./gradlew -q -PappVersion=@version@`

* API Doc

    > The API docs would be generated under the [docs](docs), which can be published as [GitHub Pages][github-pages]

    ```ruby
     $ cd @project@
     $ ./gradlew dokka
    ```

* Github Release

    > In order to publish the `@project@` binary to Github, generate [Github Access token][github-token]

    ```ruby
     $ export GITHUB_TOKEN=<token>
     $ cd @project@
     $ ./gradlew prepareRelease
     $ ./gradlew githubRelease -q
    ```

    The latest release is [![version][release-svg]][release-url]

### Usage

* Help

    ```ruby
    $ @project@ --help
    ```

### Examples

* Generating [AOT type-safe accessors][kotlin-dsl-aot-doc] in kotlin,

    ```bash
    $ ./gradlew kotlinDslAccessorsSnapshot
    ```

* Other Tasks

    ```bash
    # Run the main class.
    $ ./gradlew clean :run

    # Display project dependency
    $ ./gradlew dependencyInsight --dependency kotlin-stdlib  --configuration compile
    $ ./gradlew dependencies

    # See task tree for build task
    $ ./gradlew :build :taskTree
    ```

#### Kotlin Build Script Compilation

[Script compilation][kotlin-slack-thread] happens in 4 steps:

 - Extract `buildscript` block, compile it against parent project
   classpath (up to `buildSrc`), evaluate it against current project.
 - Extract `plugins` block,  compile it against the same classpath as
   the previous step, evaluate it against current project.
 - MAGIC (generate Kotlin code based on information contributed by previous steps).
 - Compile whole script against classpath contributed by previous steps.

-----------------
**Require [Java 8 or later][java-download]

[apidoc-url]: https://sureshg.github.io/@project@/
[apidoc-svg]: https://img.shields.io/badge/api--doc-latest-ff69b4.svg?style=flat-square

[cl-url]: @changelogUrl@
[cl-svg]: https://img.shields.io/badge/change--log-@versionBadge@-blue.svg?style=flat-square

[release-url]: https://github.com/sureshg/@project@/releases/latest
[download-url]: https://github.com/sureshg/@project@/releases/download/@version@/@project@
[release-svg]: https://img.shields.io/github/release/sureshg/@project@.svg?style=flat-square

[execjar-url]: https://github.com/sureshg/@project@/releases/download/@version@/@project@.jar
[execjar-svg]: https://img.shields.io/badge/exec--jar-@versionBadge@-00BCD4.svg?style=flat-square

[license-url]: https://github.com/sureshg/@project@/blob/master/LICENSE
[license-svg]: https://img.shields.io/github/license/sureshg/@project@.svg?style=flat-square

[travis-url]: https://travis-ci.org/sureshg/@project@/builds
[travis-svg]: https://img.shields.io/travis/sureshg/@project@.svg?style=flat-square

[codecov-url]: https://codecov.io/gh/sureshg/@project@
[codecov-svg]: https://img.shields.io/codecov/c/github/sureshg/@project@.svg?style=flat-square

[coverall-url]: https://coveralls.io/github/sureshg/@project@?branch=master
[coverall-svg]: https://img.shields.io/coveralls/sureshg/@project@.svg?style=flat-square

[total-dl-url]: https://github.com/sureshg/@project@/releases
[total-dl-svg]: https://img.shields.io/github/downloads/sureshg/@project@/total.svg?style=flat-square

[gitter-url]: https://gitter.im/sureshg/@project@
[gitter-svg]: https://img.shields.io/gitter/room/sureshg/@project@.svg

[kotlin-url]: https://kotlinlang.org/
[kotlin-svg]: https://img.shields.io/badge/kotlin-@kotlinBadge@-green.svg?style=flat-square

[kotlin-dsl]: https://github.com/gradle/kotlin-dsl
[kotlin-dsl-aot-doc]: https://github.com/gradle/kotlin-dsl/releases/tag/v0.8.0

[kotlin-slack-thread]: https://kotlinlang.slack.com/archives/gradle/p1488489798002208
[maven-google-mirror]: https://maven-central.storage.googleapis.com
[java-download]: http://www.oracle.com/technetwork/java/javase/downloads/index.html

[github-token]: https://github.com/settings/tokens
[github-pages]: https://pages.github.com/
[github-pages-pub]: https://help.github.com/articles/configuring-a-publishing-source-for-github-pages/


text:
<?php

namespace RectorPrefix20210615;

if (\class_exists('Swift_Attachment')) {
    return;
}
class Swift_Attachment
{
    /**
     * @param string $string
     * @return string
     */
    public static function fromPath($string)
    {
        $string = (string) $string;
        return 'foo';
    }
}
\class_alias('Swift_Attachment', 'Swift_Attachment', \false);

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace TijsVerkoyen\UitDatabank\Entities\Event\Calendar\WeekScheme;

class Tuesday extends Day {

}


text:
from .device import Device
from .pathpoints import BasePathpoint, pathpoint_from_functions


text:
using WebKit::WebAutofillClient;

namespace {

const SkColor kBorderColor = SkColorSetARGB(0xFF, 0xC7, 0xCA, 0xCE);
const SkColor kHoveredBackgroundColor = SkColorSetARGB(0xFF, 0xCD, 0xCD, 0xCD);
const SkColor kItemTextColor = SkColorSetARGB(0xFF, 0x7F, 0x7F, 0x7F);
const SkColor kPopupBackground = SkColorSetARGB(0xFF, 0xFF, 0xFF, 0xFF);
const SkColor kValueTextColor = SkColorSetARGB(0xFF, 0x00, 0x00, 0x00);

}  // namespace

namespace autofill {

AutofillPopupViewViews::AutofillPopupViewViews(
    AutofillPopupController* controller, views::Widget* observing_widget)
    : controller_(controller),
      observing_widget_(observing_widget) {}

AutofillPopupViewViews::~AutofillPopupViewViews() {
  if (controller_) {
    controller_->ViewDestroyed();

    HideInternal();
  }
}

void AutofillPopupViewViews::Hide() {
  // The controller is no longer valid after it hides us.
  controller_ = NULL;

  HideInternal();

  if (GetWidget()) {
    // Don't call CloseNow() because some of the functions higher up the stack
    // assume the the widget is still valid after this point.
    // http://crbug.com/229224
    // NOTE: This deletes |this|.
    GetWidget()->Close();
  } else {
    delete this;
  }
}

void AutofillPopupViewViews::OnPaint(gfx::Canvas* canvas) {
  if (!controller_)
    return;

  canvas->DrawColor(kPopupBackground);
  OnPaintBorder(canvas);

  for (size_t i = 0; i < controller_->names().size(); ++i) {
    gfx::Rect line_rect = controller_->GetRowBounds(i);

    if (controller_->identifiers()[i] ==
            WebAutofillClient::MenuItemIDSeparator) {
      canvas->DrawRect(line_rect, kItemTextColor);
    } else {
      DrawAutofillEntry(canvas, i, line_rect);
    }
  }
}

void AutofillPopupViewViews::OnMouseCaptureLost() {
  if (controller_)
    controller_->MouseExitedPopup();
}

bool AutofillPopupViewViews::OnMouseDragged(const ui::MouseEvent& event) {
  if (!controller_)
    return false;

  if (HitTestPoint(event.location())) {
    controller_->MouseHovered(event.x(), event.y());

    // We must return true in order to get future OnMouseDragged and
    // OnMouseReleased events.
    return true;
  }

  // If we move off of the popup, we lose the selection.
  controller_->MouseExitedPopup();
  return false;
}

void AutofillPopupViewViews::OnMouseExited(const ui::MouseEvent& event) {
  if (controller_)
    controller_->MouseExitedPopup();
}

void AutofillPopupViewViews::OnMouseMoved(const ui::MouseEvent& event) {
  if (controller_)
    controller_->MouseHovered(event.x(), event.y());
}

bool AutofillPopupViewViews::OnMousePressed(const ui::MouseEvent& event) {
  // We must return true in order to get the OnMouseReleased event later.
  return true;
}

void AutofillPopupViewViews::OnMouseReleased(const ui::MouseEvent& event) {
  if (!controller_)
    return;

  // We only care about the left click.
  if (event.IsOnlyLeftMouseButton() &&
      HitTestPoint(event.location()))
    controller_->MouseClicked(event.x(), event.y());
}

void AutofillPopupViewViews::OnWidgetBoundsChanged(
    views::Widget* widget,
    const gfx::Rect& new_bounds) {
  controller_->Hide();
}

void AutofillPopupViewViews::Show() {
  if (!GetWidget()) {
    observing_widget_->AddObserver(this);

    // The widget is destroyed by the corresponding NativeWidget, so we use
    // a weak pointer to hold the reference and don't have to worry about
    // deletion.
    views::Widget* widget = new views::Widget;
    views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
    params.delegate = this;
    params.parent = controller_->container_view();
    widget->Init(params);
    widget->SetContentsView(this);
  }

  set_border(views::Border::CreateSolidBorder(kBorderThickness, kBorderColor));

  UpdateBoundsAndRedrawPopup();
  GetWidget()->Show();
}

void AutofillPopupViewViews::InvalidateRow(size_t row) {
  SchedulePaintInRect(controller_->GetRowBounds(row));
}

void AutofillPopupViewViews::UpdateBoundsAndRedrawPopup() {
  GetWidget()->SetBounds(controller_->popup_bounds());
  SchedulePaint();
}

void AutofillPopupViewViews::HideInternal() {
  AutofillPopupView::Hide();

  observing_widget_->RemoveObserver(this);
}

void AutofillPopupViewViews::DrawAutofillEntry(gfx::Canvas* canvas,
                                               int index,
                                               const gfx::Rect& entry_rect) {
  if (controller_->selected_line() == index)
    canvas->FillRect(entry_rect, kHoveredBackgroundColor);

  bool is_rtl = base::i18n::IsRTL();
  int value_text_width = controller_->GetNameFontForRow(index).GetStringWidth(
      controller_->names()[index]);
  int value_content_x = is_rtl ?
      entry_rect.width() - value_text_width - kEndPadding : kEndPadding;

  canvas->DrawStringInt(
      controller_->names()[index],
      controller_->GetNameFontForRow(index),
      kValueTextColor,
      value_content_x,
      entry_rect.y(),
      canvas->GetStringWidth(controller_->names()[index],
                             controller_->GetNameFontForRow(index)),
      entry_rect.height(),
      gfx::Canvas::TEXT_ALIGN_CENTER);

  // Use this to figure out where all the other Autofill items should be placed.
  int x_align_left = is_rtl ? kEndPadding : entry_rect.width() - kEndPadding;

  // Draw the Autofill icon, if one exists
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  int row_height = controller_->GetRowBounds(index).height();
  if (!controller_->icons()[index].empty()) {
    int icon = controller_->GetIconResourceID(controller_->icons()[index]);
    DCHECK_NE(-1, icon);
    int icon_y = entry_rect.y() + (row_height - kAutofillIconHeight) / 2;

    x_align_left += is_rtl ? 0 : -kAutofillIconWidth;

    canvas->DrawImageInt(*rb.GetImageSkiaNamed(icon), x_align_left, icon_y);

    x_align_left += is_rtl ? kAutofillIconWidth + kIconPadding : -kIconPadding;
  }

  // Draw the name text.
  if (!is_rtl) {
    x_align_left -= canvas->GetStringWidth(controller_->subtexts()[index],
                                           controller_->subtext_font());
  }

  canvas->DrawStringInt(
      controller_->subtexts()[index],
      controller_->subtext_font(),
      kItemTextColor,
      x_align_left + kEndPadding,
      entry_rect.y(),
      canvas->GetStringWidth(controller_->subtexts()[index],
                             controller_->subtext_font()),
      entry_rect.height(),
      gfx::Canvas::TEXT_ALIGN_CENTER);
}

AutofillPopupView* AutofillPopupView::Create(
    AutofillPopupController* controller) {
  views::Widget* observing_widget =
      views::Widget::GetTopLevelWidgetForNativeView(
          controller->container_view());

  // If the top level widget can't be found, cancel the popup since we can't
  // fully set it up.
  if (!observing_widget)
    return NULL;

  return new AutofillPopupViewViews(controller, observing_widget);
}

}  // namespace autofill


text:
from rrb3 import *
from random import randint

rr = RRB3(12, 12) # Battery voltage 12V, motor 12V

T = 20  # 20 seconds to extend

extended = False

try:
	while True:
		if rr.get_distance() < 20:
			if extended:  # if extended retract and vice versa
				print("retracting")
				rr.set_led1(True)  # LED 1 on
				rr.reverse(T, 1.0)
				rr.set_led1(False)
				extended = False
			else:
				print("extending")
				rr.set_led2(True)
				rr.forward(T, 1.0)
				rr.set_led2(False)
				extended = True
			print("done")
finally:
	rr.cleanup() # Set all GPIO pins to safe input state


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Dicom.IO;
using Dicom.IO.Buffer;

namespace Dicom.Imaging {
	/// <summary>
	/// DICOM Pixel Data abstract class for reading and writing DICOM images pixel data according to the specified transfer syntax
	/// </summary>
	public abstract class DicomPixelData {
		/// <summary>
		/// Initialize new instance of <seealso cref="DicomPixelData"/> using passed <paramref name="dataset"/>
		/// </summary>
		/// <param name="dataset"></param>
		protected DicomPixelData(DicomDataset dataset) {
			Dataset = dataset;
			Syntax = dataset.InternalTransferSyntax;
		}

		/// <summary>
		/// Dicom Dataset
		/// </summary>
		public DicomDataset Dataset {
			get;
			private set;
		}

		/// <summary>
		/// The transfer syntax used to encode the DICOM iamge pixel data
		/// </summary>
		public DicomTransferSyntax Syntax {
			get;
			private set;
		}

		/// <summary>
		/// DICOM image width (columns) in pixels
		/// </summary>
		public ushort Width {
			get { return Dataset.Get<ushort>(DicomTag.Columns); }
			set { Dataset.Add(new DicomUnsignedShort(DicomTag.Columns, value)); }
		}

		/// <summary>
		/// DICOM image height (rows) in pixels
		/// </summary>
		public ushort Height {
			get { return Dataset.Get<ushort>(DicomTag.Rows); }
			set { Dataset.Add(new DicomUnsignedShort(DicomTag.Rows, value)); }
		}

		/// <summary>
		/// DICOM image Number of frames. This value usually equals 1 for single frame images
		/// </summary>
		public int NumberOfFrames {
			get { return Dataset.Get<ushort>(DicomTag.NumberOfFrames, 0, 1); }
			set { Dataset.Add(new DicomIntegerString(DicomTag.NumberOfFrames, value)); }
		}

		/// <summary>
		/// Return new instance of <seealso cref="BitDepth"/> using dataset information
		/// </summary>
		public BitDepth BitDepth {
			get {
				return new BitDepth(BitsAllocated, BitsStored, HighBit, PixelRepresentation == PixelRepresentation.Signed);
			}
		}

		/// <summary>
		/// Number of bits allocated per pixel sample (0028,0100)
		/// </summary>
		public ushort BitsAllocated {
			get { return Dataset.Get<ushort>(DicomTag.BitsAllocated); }
			set { Dataset.Add(new DicomUnsignedShort(DicomTag.BitsAllocated, value)); }
		}

		/// <summary>
		/// Number of bits stored per pixel sample (0028,0101)
		/// </summary>
		public ushort BitsStored {
			get { return Dataset.Get<ushort>(DicomTag.BitsStored); }
			set { Dataset.Add(new DicomUnsignedShort(DicomTag.BitsStored, value)); }
		}

		/// <summary>
		/// Index of the most signficant bit (MSB) of pixel sample(0028,0102)
		/// </summary>
		public ushort HighBit {
			get { return Dataset.Get<ushort>(DicomTag.HighBit); }
			set { Dataset.Add(new DicomUnsignedShort(DicomTag.HighBit, value)); }
		}

		/// <summary>
		/// Number of samples per pixel (0028,0002), usually 1 for grayscale and 3 for color (RGB and YBR)
		/// </summary>
		public ushort SamplesPerPixel {
			get { return Dataset.Get<ushort>(DicomTag.SamplesPerPixel, 0, 1); }
			set { Dataset.Add(new DicomUnsignedShort(DicomTag.SamplesPerPixel, value)); }
		}

		/// <summary>
		/// Pixel Representation (0028,0103) represents signed/unsigned data of the pixel samples
		/// </summary>
		public PixelRepresentation PixelRepresentation {
			get { return Dataset.Get<PixelRepresentation>(DicomTag.PixelRepresentation); }
			set { Dataset.Add(new DicomUnsignedShort(DicomTag.PixelRepresentation, (ushort)value)); }
		}

		/// <summary>
		/// Planar Configuration (0028,0006) indicates whether the color pixel data are sent color-by-plane
		/// or color-by-pixel
		/// </summary>
		public PlanarConfiguration PlanarConfiguration {
			get { return Dataset.Get<PlanarConfiguration>(DicomTag.PlanarConfiguration); }
			set { Dataset.Add(new DicomUnsignedShort(DicomTag.PlanarConfiguration, (ushort)value)); }
		}

		/// <summary>
		/// Photometric Interpretation
		/// </summary>
		public PhotometricInterpretation PhotometricInterpretation {
			get { return Dataset.Get<PhotometricInterpretation>(DicomTag.PhotometricInterpretation); }
			set { Dataset.Add(new DicomCodeString(DicomTag.PhotometricInterpretation, value.Value)); }
		}

		/// <summary>
		/// Lossy image compression (0028,2110), returns true if stored value is "01"
		/// </summary>
		public bool IsLossy {
			get { return Dataset.Get<string>(DicomTag.LossyImageCompression, "00") == "01"; }
		}

		/// <summary>
		/// Lossy image compression method (0028,2114)
		/// </summary>
		public string LossyCompressionMethod {
			get { return Dataset.Get<string>(DicomTag.LossyImageCompressionMethod); }
		}

		/// <summary>
		/// Lossy image compression ration (0028,2112)
		/// </summary>
		public decimal LossyCompressionRatio {
			get { return Dataset.Get<decimal>(DicomTag.LossyImageCompressionRatio); }
		}

		/// <summary>
		/// Number of bytes allocated per pixel sample
		/// </summary>
		public int BytesAllocated {
			get {
				int bytes = BitsAllocated / 8;
				if ((BitsAllocated % 8) > 0)
					bytes++;
				return bytes;
			}
		}

		/// <summary>
		/// Uncompressed frame size in bytes
		/// </summary>
		public int UncompressedFrameSize {
			get {
				if (BitsAllocated == 1) {
					var bytes = (Width * Height) / 8;
					if (((Width * Height) % 8) > 0)
						bytes++;
					return bytes;
				}
				return BytesAllocated * SamplesPerPixel * Width * Height;
			}
		}
		/// <summary>
		/// Plaette color LUT, valid for PALETTE COLOR <seealso cref="PhotometricInterpretation"/>
		/// </summary>
		public Color32[] PaletteColorLUT {
			get { return GetPaletteColorLUT(); }
			set { throw new NotImplementedException(); }
		}

		/// <summary>
		/// Extracts the palette color LUT from DICOM dataset, valid for PALETTE COLOR <seealso cref="PhotometricInterpretation"/>
		/// </summary>
		/// <returns>Palette color LUT</returns>
		/// <exception cref="DicomImagingException">Invalid photometric interpretation or plaette color lUT missing from database</exception>
		private Color32[] GetPaletteColorLUT() {
			if (PhotometricInterpretation != PhotometricInterpretation.PaletteColor)
				throw new DicomImagingException("Attempted to get Palette Color LUT from image with invalid photometric interpretation.");

			if (!Dataset.Contains(DicomTag.RedPaletteColorLookupTableDescriptor))
				throw new DicomImagingException("Palette Color LUT missing from dataset.");

			int size = Dataset.Get<int>(DicomTag.RedPaletteColorLookupTableDescriptor, 0);
			int first = Dataset.Get<int>(DicomTag.RedPaletteColorLookupTableDescriptor, 1);
			int bits = Dataset.Get<int>(DicomTag.RedPaletteColorLookupTableDescriptor, 2);

			var r = Dataset.Get<byte[]>(DicomTag.RedPaletteColorLookupTableData);
			var g = Dataset.Get<byte[]>(DicomTag.GreenPaletteColorLookupTableData);
			var b = Dataset.Get<byte[]>(DicomTag.BluePaletteColorLookupTableData);

            // If the LUT size is 0, that means it's 65536 in size.
            if (size == 0)
                size = 65536;

            var lut = new Color32[size];

			if (r.Length == size) {
				// 8-bit LUT entries
				for (int i = 0; i < size; i++)
					lut[i] = new Color32(0xff, r[i], g[i], b[i]);
			} else {
				// 16-bit LUT entries... we only support 8-bit until someone can find a sample image with a 16-bit palette

				// 8-bit entries with 16-bits allocated
				int offset = 0;

				// 16-bit entries with 8-bits stored
				if (bits == 16)
					offset = 1;

				for (int i = 0; i < size; i++, offset += 2)
					lut[i] = new Color32(0xff, r[offset], g[offset], b[offset]);
			}

			return lut;
		}

		/// <summary>
		/// Abstract GetFrame method to extract specific frame byte buffer <paramref name="frame"/> dataset
		/// </summary>
		/// <param name="frame">Frame index</param>
		/// <returns>Frame byte buffer</returns>
		public abstract IByteBuffer GetFrame(int frame);

		/// <summary>
		/// Abstract AddFrame method to add new frame into dataset pixel dataset. new frame will be appended to existing frames
		/// </summary>
		/// <param name="data">Frame byte buffer</param>
		public abstract void AddFrame(IByteBuffer data);

		/// <summary>
		/// A factory method to initialize new instance of <seealso cref="DicomPixelData"/> implementation either
		/// <seealso cref="OtherWordPixelData"/>, <seealso cref="OtherBytePixelData"/>, or <seealso cref="EncapsulatedPixelData"/>
		/// </summary>
		/// <param name="dataset">Source DICOM Dataset</param>
		/// <param name="newPixelData">true if new <seealso cref="DicomPixelData"/>will be created for current dataset,
		/// false to read <seealso cref="DicomPixelData"/> from <paramref name="dataset"/>.
		/// Default is false (read)</param>
		/// <returns>New instance of DicomPixelData</returns>
		public static DicomPixelData Create(DicomDataset dataset, bool newPixelData = false) {
			var syntax = dataset.InternalTransferSyntax;

			if (newPixelData) {
				if (syntax == DicomTransferSyntax.ImplicitVRLittleEndian)
					return new OtherWordPixelData(dataset, true);

				if (syntax.IsEncapsulated)
					return new EncapsulatedPixelData(dataset, true);

				if (dataset.Get<ushort>(DicomTag.BitsAllocated) == 16)
					return new OtherWordPixelData(dataset, true);
				else
					return new OtherBytePixelData(dataset, true);
			} else {
				var item = dataset.Get<DicomItem>(DicomTag.PixelData);
				if (item == null)
					throw new DicomImagingException("DICOM dataset is missing pixel data element.");

				if (item is DicomOtherByte)
					return new OtherBytePixelData(dataset, false);
				if (item is DicomOtherWord)
					return new OtherWordPixelData(dataset, false);
				if (item is DicomOtherByteFragment || item is DicomOtherWordFragment)
					return new EncapsulatedPixelData(dataset, false);

				throw new DicomImagingException("Unexpected or unhandled pixel data element type: {0}", item.GetType());
			}
		}

		/// <summary>
		/// Other Byte (OB) implementation of <seealso cref="DicomPixelData"/>
		/// </summary>
		private class OtherBytePixelData : DicomPixelData {
			/// <summary>
			/// Initialize new instance of OtherBytePixelData
			/// </summary>
			/// <param name="dataset">The source dataset to extract from or create new pixel data for</param>
			/// <param name="newPixelData">True to create new pixel data, false to read pixel data</param>
			public OtherBytePixelData(DicomDataset dataset, bool newPixelData) : base(dataset) {
				if (newPixelData) {
					NumberOfFrames = 0;
					Element = new DicomOtherByte(DicomTag.PixelData, new CompositeByteBuffer());
					Dataset.Add(Element);
				} else
					Element = dataset.Get<DicomOtherByte>(DicomTag.PixelData);
			}

			/// <summary>
			/// The pixel data other byte (OB) element
			/// </summary>
			public DicomOtherByte Element {
				get;
				private set;
			}
			public override IByteBuffer GetFrame(int frame) {
                if (frame < 0 || frame >= NumberOfFrames)
                    throw new IndexOutOfRangeException("Requested frame out of range!");

				int offset = UncompressedFrameSize * frame;
				return new RangeByteBuffer(Element.Buffer, (uint)offset, (uint)UncompressedFrameSize);
			}

			public override void AddFrame(IByteBuffer data) {
				if (!(Element.Buffer is CompositeByteBuffer))
					throw new DicomImagingException("Expected pixel data element to have a CompositeByteBuffer");

				CompositeByteBuffer buffer = Element.Buffer as CompositeByteBuffer;
				buffer.Buffers.Add(data);

				NumberOfFrames++;
			}
		}

		/// <summary>
		/// Other Word (OW) implementation of <seealso cref="DicomPixelData"/>
		/// </summary>
		private class OtherWordPixelData : DicomPixelData {
			/// <summary>
			/// Initialize new instance of OtherWordPixelData
			/// </summary>
			/// <param name="dataset">The source dataset to extract from or create new pixel data for</param>
			/// <param name="newPixelData">True to create new pixel data, false to read pixel data</param>
			public OtherWordPixelData(DicomDataset dataset, bool newPixelData) : base(dataset) {
				if (newPixelData) {
					NumberOfFrames = 0;
					Element = new DicomOtherWord(DicomTag.PixelData, new CompositeByteBuffer());
					Dataset.Add(Element);
				} else
					Element = dataset.Get<DicomOtherWord>(DicomTag.PixelData);
			}

			/// <summary>
			/// The pixel data other word (OW) element
			/// </summary>
			public DicomOtherWord Element {
				get;
				private set;
			}

			public override IByteBuffer GetFrame(int frame) {
                if (frame < 0 || frame >= NumberOfFrames)
                    throw new IndexOutOfRangeException("Requested frame out of range!");

				int offset = UncompressedFrameSize * frame;
				IByteBuffer buffer = new RangeByteBuffer(Element.Buffer, (uint)offset, (uint)UncompressedFrameSize);

				// mainly for GE Private Implicit VR Little Endian
				if (Syntax.SwapPixelData)
					buffer = new SwapByteBuffer(buffer, 2);

				return buffer;
			}

			public override void AddFrame(IByteBuffer data) {
				if (!(Element.Buffer is CompositeByteBuffer))
					throw new DicomImagingException("Expected pixel data element to have a CompositeByteBuffer.");

				CompositeByteBuffer buffer = Element.Buffer as CompositeByteBuffer;
				if (BytesAllocated == 1)
					data = new SwapByteBuffer(data , 2);
				buffer.Buffers.Add(data);

				NumberOfFrames++;
			}
		}

		/// <summary>
		/// Other Byte Fragment implementation of <seealso cref="DicomPixelData"/>, used for handling encapsulated (compressed)
		/// pixel data
		/// </summary>
		private class EncapsulatedPixelData : DicomPixelData {
			/// <summary>
			/// Initialize new instance of EncapsulatedPixelData
			/// </summary>
			/// <param name="dataset">The source dataset to extract from or create new pixel data for</param>
			/// <param name="newPixelData">True to create new pixel data, false to read pixel data</param>
			public EncapsulatedPixelData(DicomDataset dataset, bool newPixelData) : base(dataset) {
				if (newPixelData) {
					NumberOfFrames = 0;
					Element = new DicomOtherByteFragment(DicomTag.PixelData);
					Dataset.Add(Element);
				} else
					Element = dataset.Get<DicomFragmentSequence>(DicomTag.PixelData);
			}

			/// <summary>
			/// The pixel data framgent sequence element
			/// </summary>
			public DicomFragmentSequence Element {
				get;
				private set;
			}

			public override IByteBuffer GetFrame(int frame) {
                if (frame < 0 || frame >= NumberOfFrames)
                    throw new IndexOutOfRangeException("Requested frame out of range!");

                IByteBuffer buffer = null;

				if (NumberOfFrames == 1) {
					if (Element.Fragments.Count == 1)
						buffer = Element.Fragments[0];
					else
						buffer = new CompositeByteBuffer(Element.Fragments.ToArray());
				}
				else if (Element.Fragments.Count == NumberOfFrames)
					buffer = Element.Fragments[frame];
				else if (Element.OffsetTable.Count == NumberOfFrames) {
					uint start = Element.OffsetTable[frame];
					uint stop = (Element.OffsetTable.Count == (frame + 1)) ? uint.MaxValue : Element.OffsetTable[frame + 1];

					var composite = new CompositeByteBuffer();

					uint pos = 0;
					int frag = 0;

					while (pos < start && frag < Element.Fragments.Count) {
						pos += 8;
						pos += Element.Fragments[frag].Size;
						frag++;
					}

					if (pos != start)
						throw new DicomImagingException("Fragment start position does not match offset table.");

					while (pos < stop && frag < Element.Fragments.Count) {
						composite.Buffers.Add(Element.Fragments[frag]);

						pos += 8;
						pos += Element.Fragments[frag].Size;
						frag++;
					}

					if (pos < stop && stop != uint.MaxValue)
						throw new DicomImagingException("Image frame truncated while reading fragments from offset table.");

					buffer = composite;
				}
				else
					throw new DicomImagingException("Support for multi-frame images with varying fragment sizes and no offset table has not been implemented.");

				// mainly for GE Private Implicit VR Little Endian
				if (!Syntax.IsEncapsulated && BitsAllocated == 16 && Syntax.SwapPixelData)
					buffer = new SwapByteBuffer(buffer, 2);

				return EndianByteBuffer.Create(buffer, Syntax.Endian, BytesAllocated);
			}

			public override void AddFrame(IByteBuffer data) {
				NumberOfFrames++;

				long pos = Element.Fragments.Sum(x => (long)x.Size + 8);
				if (pos < uint.MaxValue) {
					Element.OffsetTable.Add((uint)pos);
				} else {
					// do not create an offset table for very large datasets
					Element.OffsetTable.Clear();
				}

				data = EndianByteBuffer.Create(data, Syntax.Endian, BytesAllocated);
				Element.Fragments.Add(data);
			}
		}
	}
}


text:
package com.android.aft.AFAppManager.model;

import java.util.ArrayList;

public class ApplicationBuildInfo {

    public String name;
    public String revision;
    public String directory;

    public ArrayList<DeliveryInfo> mDeliveries = new ArrayList<DeliveryInfo>();

    public void addDelevery(DeliveryInfo d) {
        mDeliveries.add(d);
    }

}


text:
package org.springframework.boot.actuate.autoconfigure.metrics.export.humio;

import java.util.Collections;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link HumioPropertiesConfigAdapter}.
 *
 * @author Andy Wilkinson
 */
class HumioPropertiesConfigAdapterTests {

	@Test
	void whenApiTokenIsSetAdapterApiTokenReturnsIt() {
		HumioProperties properties = new HumioProperties();
		properties.setApiToken("ABC123");
		assertThat(new HumioPropertiesConfigAdapter(properties).apiToken()).isEqualTo("ABC123");
	}

	@Test
	void whenPropertiesRepositoryIsSetAdapterRepositoryReturnsIt() {
		HumioProperties properties = new HumioProperties();
		properties.setRepository("test");
		assertThat(new HumioPropertiesConfigAdapter(properties).repository()).isEqualTo("test");
	}

	@Test
	void whenPropertiesTagsIsSetAdapterTagsReturnsIt() {
		HumioProperties properties = new HumioProperties();
		properties.setTags(Collections.singletonMap("name", "test"));
		assertThat(new HumioPropertiesConfigAdapter(properties).tags())
				.isEqualTo(Collections.singletonMap("name", "test"));
	}

	@Test
	void whenPropertiesUriIsSetAdapterUriReturnsIt() {
		HumioProperties properties = new HumioProperties();
		properties.setUri("https://humio.example.com");
		assertThat(new HumioPropertiesConfigAdapter(properties).uri()).isEqualTo("https://humio.example.com");
	}

}


text:
//
//  HMDropdownView.m
//  HMMeiTuanHD19
//
//  Created by heima on 16/9/14.
//  Copyright © 2016年 heima. All rights reserved.
//

#import "HMDropdownView.h"
#import "HMCategoryModel.h"
#import "XDLDistrictModel.h"
#import "HMDropdownLeftTableViewCell.h"
#import "HMDropdownRightTableViewCell.h"
#import "XDLConst.h"

@interface HMDropdownView ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *leftTableView;
@property (weak, nonatomic) IBOutlet UITableView *rightTableView;

//分类的左边选中模型
@property (nonatomic, strong) HMCategoryModel *selectCategoryLeftModel;

@property (nonatomic, strong) XDLDistrictModel *selectDistrictModel;

@end

@implementation HMDropdownView

/** 提供类方法, 快速创建View*/
+ (instancetype)dropdownView
{
    UINib *nib = [UINib nibWithNibName:@"HMDropdownView" bundle:nil];
    return [nib instantiateWithOwner:nil options:nil][0];
}

-(void)setDistrictArray:(NSArray *)districtArray{

    _districtArray = districtArray;
    [self.leftTableView reloadData];

    self.selectDistrictModel = nil;
    [self.rightTableView reloadData];
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    //view默认的autoresizingMask是有值得. 因此, 当发生压缩/放大时, 视图也会发生响应的效果
    //iPad分辨率很大, 768 * 1024, popover默认320 * 480 . 当大的视图放到小的视图中, 就会压缩
    //关闭这个属性, 就可以保证不变
    self.autoresizingMask = UIViewAutoresizingNone;
}

#pragma mark - 表视图的数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(self.categoryArray.count){

        if (tableView == self.leftTableView) {
        return self.categoryArray.count;
    } else {
        //为了显示右边数据 --> 需要先知道左边选中了谁 --> 实现表格的选中方法, 记录左边的数据
        return  self.selectCategoryLeftModel.subcategories.count;
        }
    }else{
        if (tableView == self.leftTableView) {
            return self.districtArray.count;
        } else {
            //为了显示右边数据 --> 需要先知道左边选中了谁 --> 实现表格的选中方法, 记录左边的数据
            return  self.selectDistrictModel.subdistricts.count;
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if(self.categoryArray.count){

        if (tableView == self.leftTableView) {
        //左边表格
        HMDropdownLeftTableViewCell *cell = [HMDropdownLeftTableViewCell dropdownLeftTableViewCellWithTableView:tableView];

        //1. 显示Label数据
        HMCategoryModel *categoryModel = self.categoryArray[indexPath.row];
        cell.textLabel.text = categoryModel.name;
        //2. 显示Image数据
        cell.imageView.image = [UIImage imageNamed:categoryModel.icon];
        //3. 设置cell的附属视图
        if (categoryModel.subcategories.count == 0) {
            cell.accessoryType = UITableViewCellAccessoryNone;
        } else {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        return cell;
    } else {
        //右边表格
        HMDropdownRightTableViewCell *cell = [HMDropdownRightTableViewCell dropdownRightTableViewCellWithTableView:tableView];
        // 为了显示右边的数据  --> 需要知道左边选中了谁 --> tableView的选中方法中记录
        NSArray *categoryArray = self.selectCategoryLeftModel.subcategories;
        cell.textLabel.text = categoryArray[indexPath.row];
        return cell;
        }
    }else{
        if (tableView == self.leftTableView) {
            //左边表格
            HMDropdownLeftTableViewCell *cell = [HMDropdownLeftTableViewCell dropdownLeftTableViewCellWithTableView:tableView];
            //1. 显示Label数据
            XDLDistrictModel *districtModel = self.districtArray[indexPath.row];
            cell.textLabel.text = districtModel.name;
            //3. 设置cell的附属视图
            if (districtModel.subdistricts.count == 0) {
                cell.accessoryType = UITableViewCellAccessoryNone;
            } else {
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
            return cell;
        } else {
            //右边表格
            HMDropdownRightTableViewCell *cell = [HMDropdownRightTableViewCell dropdownRightTableViewCellWithTableView:tableView];
            // 为了显示右边的数据  --> 需要知道左边选中了谁 --> tableView的选中方法中记录
            NSArray *subDistrictArray = self.selectDistrictModel.subdistricts;
            cell.textLabel.text = subDistrictArray[indexPath.row];
            return cell;
        }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.categoryArray){
        if (tableView == self.leftTableView) {
        //1. 记录左边选中的模型
            self.selectCategoryLeftModel = self.categoryArray[indexPath.row];
            if(self.selectCategoryLeftModel.subcategories.count == 0){
                [XDLNotificationCenter postNotificationName:XDLCategoryDidChangeNotifacation object:nil userInfo:@{XDLCategoryModelKey: self.selectCategoryLeftModel}];
            }
        //2. 刷新右边数据
            //    [self.rightTableView reloadData];
        }else{
                [XDLNotificationCenter postNotificationName:XDLCategoryDidChangeNotifacation object:nil userInfo:@{XDLCategoryModelKey: self.selectCategoryLeftModel, XDLCategorySubtitleKey: self.selectCategoryLeftModel.subcategories[indexPath.row]}];
        }
    }else{
        if (tableView == self.leftTableView) {
            //1. 记录左边选中的模型
          self.selectDistrictModel = self.districtArray[indexPath.row];
            if(self.selectDistrictModel.subdistricts.count == 0){
                [XDLNotificationCenter postNotificationName:XDLDistrictDidChangeNotifacation object:nil userInfo:@{XDLDistrictModelKey: self.selectDistrictModel}];
            }
        }else{
            [XDLNotificationCenter postNotificationName:XDLDistrictDidChangeNotifacation object:nil userInfo:@{XDLDistrictModelKey:self.selectDistrictModel, XDLDistrictSubtitleKey:self.selectDistrictModel.subdistricts[indexPath.row]}];
        }
    }
    //2. 刷新右边数据
    [self.rightTableView reloadData];
}
@end


text:
/*
 * SubSonic - http://subsonicproject.com
 *
 * The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
*/

using System;
using System.IO;

namespace SubSonic.Sugar
{
    /// <summary>
    /// Summary for the Files class
    /// </summary>
    public static class Files
    {
        /// <summary>
        /// Read a text file and obtain it's contents.
        /// </summary>
        /// <param name="absolutePath">The complete file path to write to.</param>
        /// <returns>String containing the content of the file.</returns>
        public static string GetFileText(string absolutePath)
        {
            using(StreamReader sr = new StreamReader(absolutePath))
                return sr.ReadToEnd();
        }

        /// <summary>
        /// Creates or opens a file for writing and writes text to it.
        /// </summary>
        /// <param name="absolutePath">The complete file path to write to.</param>
        /// <param name="fileText">A String containing text to be written to the file.</param>
        public static void CreateToFile(string absolutePath, string fileText)
        {
            using(StreamWriter sw = File.CreateText(absolutePath))
                sw.Write(fileText);
        }

        /// <summary>
        /// Update text within a file by replacing a substring within the file.
        /// </summary>
        /// <param name="absolutePath">The complete file path to write to.</param>
        /// <param name="lookFor">A String to be replaced.</param>
        /// <param name="replaceWith">A String to replace all occurrences of lookFor.</param>
        public static void UpdateFileText(string absolutePath, string lookFor, string replaceWith)
        {
            string newText = GetFileText(absolutePath).Replace(lookFor, replaceWith);
            WriteToFile(absolutePath, newText);
        }

        /// <summary>
        /// Writes out a string to a file.
        /// </summary>
        /// <param name="absolutePath">The complete file path to write to.</param>
        /// <param name="fileText">A String containing text to be written to the file.</param>
        public static void WriteToFile(string absolutePath, string fileText)
        {
            using(StreamWriter sw = new StreamWriter(absolutePath, false))
                sw.Write(fileText);
        }

        /// <summary>
        /// Display bytes as a suitable unit of measurement.
        /// </summary>
        /// <remarks>
        /// Uses 1024^x for the units as used by memory and file sizing. Do not use in
        /// telecommunications where 1000^x is the norm.
        /// </remarks>
        /// <param name="bytes">Number of bytes to display.</param>
        /// <returns>A String formatted with the number of bytes and suitable unit of measurement.</returns>
        public static string FromByteCount(long bytes)
        {
            const decimal kilobyte = 1024m;
            const decimal megabyte = kilobyte * 1024;
            const decimal gigabyte = megabyte * 1024;

            if(bytes > gigabyte)
                return String.Format("{0:0.00} GB", bytes / gigabyte);
            if(bytes > megabyte)
                return String.Format("{0:0.00} MB", bytes / megabyte);
            if(bytes > kilobyte)
                return String.Format("{0:0.00} KB", bytes / kilobyte);
            return String.Format("{0} B", bytes);
        }
    }
}


text:
require 'spec_helper'

describe Spree::Author do
  context "validation" do
    let(:author) { build :author }

    it "should be valid with valid attributes" do
      expect(author).to be_valid
    end

    it "should not be valid without first_name" do
      author.first_name = nil
      expect(author).not_to be_valid
    end

    it "should not be valid without last_name" do
      author.last_name = nil
      expect(author).not_to be_valid
    end

    it "should not be valid without bio" do
      author.bio = nil
      expect(author).not_to be_valid
    end

    it "should not be valid withoud seo_description" do
      author.seo_description = nil
      expect(author).not_to be_valid
    end

    it "should have an unique permalink" do
      another_author = create(:author)
      expect(author).to be_valid
      expect(author.permalink).to eq('eugenio-montale-1')
    end
  end

  context "permalink" do
    let(:author) { create :author }

    context "when created" do
      it "should be composed with first_name-last_name format" do
        expect(author.permalink).to eq("eugenio-montale")
      end
    end

    context "when edited" do
      it "should be updated" do
        author.update_attributes(permalink: "luigi-pirandello")
        expect(author.permalink).to eq("luigi-pirandello")
      end
    end
  end

  context "Seo Fields" do
    let(:author) { create :author }
    context "Seo Slug" do
      it "should have a seo_slug" do
        expect(author).to respond_to(:seo_slug)
      end
      it "should be the same as permalink" do
        expect(author.seo_slug).to eq(author.permalink)
      end
    end
    context "Seo Description" do
      it "should have a seo_description" do
        expect(author).to respond_to(:seo_description)
      end
    end
    context "Seo Title" do
      it "should have a seo_title" do
        expect(author).to respond_to(:seo_title)
      end
      it "should contain the full name" do
        expect(author.seo_title).to match(Regexp.new(author.full_name))
      end
    end
  end
end


text:
---
uid: SolidEdgeAssembly.AdjustablePart.SetAdjustables(System.Int32,System.Array@,System.Array@)
summary:
remarks:
syntax:
    parameters:
    - id: AsmVariables
      description: Specifies the assembly variables.
    - id: NumberOfEntries
      description: Specifies the number of entries in the output arrays.
    - id: PartVariables
      description: Specifies the part variables.
---


text:
require 'logger'
require 'flipper/adapters/instrumented'
require 'flipper/instrumentation/log_subscriber'

RSpec.describe Flipper::Instrumentation::LogSubscriber do
  let(:adapter) do
    memory = Flipper::Adapters::Memory.new
    Flipper::Adapters::Instrumented.new(memory, instrumenter: ActiveSupport::Notifications)
  end
  let(:flipper) do
    Flipper.new(adapter, instrumenter: ActiveSupport::Notifications)
  end

  before do
    Flipper.register(:admins) do |thing|
      thing.respond_to?(:admin?) && thing.admin?
    end

    @io = StringIO.new
    logger = Logger.new(@io)
    logger.formatter = proc { |_severity, _datetime, _progname, msg| "#{msg}\n" }
    described_class.logger = logger
  end

  after do
    described_class.logger = nil
  end

  let(:log) { @io.string }

  context 'feature enabled checks' do
    before do
      clear_logs
      flipper[:search].enabled?
    end

    it 'logs feature calls with result after operation' do
      feature_line = find_line('Flipper feature(search) enabled? false')
      expect(feature_line).to include('[ thing=nil ]')
    end

    it 'logs adapter calls' do
      adapter_line = find_line('Flipper feature(search) adapter(memory) get')
      expect(adapter_line).to include('[ result={')
      expect(adapter_line).to include('} ]')
    end
  end

  context 'feature enabled checks with a thing' do
    let(:user) { Flipper::Types::Actor.new(Flipper::Actor.new('1')) }

    before do
      clear_logs
      flipper[:search].enabled?(user)
    end

    it 'logs thing for feature' do
      feature_line = find_line('Flipper feature(search) enabled?')
      expect(feature_line).to include(user.inspect)
    end
  end

  context 'changing feature enabled state' do
    let(:user) { Flipper::Types::Actor.new(Flipper::Actor.new('1')) }

    before do
      clear_logs
      flipper[:search].enable(user)
    end

    it 'logs feature calls with result in brackets' do
      feature_line = find_line('Flipper feature(search) enable true')
      expect(feature_line).to include("[ thing=#{user.inspect} gate_name=actor ]")
    end

    it 'logs adapter value' do
      adapter_line = find_line('Flipper feature(search) adapter(memory) enable')
      expect(adapter_line).to include('[ result=')
    end
  end

  context 'getting all the features from the adapter' do
    before do
      clear_logs
      flipper.features
    end

    it 'logs adapter calls' do
      adapter_line = find_line('Flipper adapter(memory) features')
      expect(adapter_line).to include('[ result=')
    end
  end

  def find_line(str)
    regex = /#{Regexp.escape(str)}/
    lines = log.split("\n")
    lines.detect { |line| line =~ regex } ||
      raise("Could not find line matching #{str.inspect} in #{lines.inspect}")
  end

  def clear_logs
    @io.string = ''
  end
end


text:
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

describe Admin::FlagTypesController do
  fixtures :users

  before do
    login_as :smurf
  end

  def mock_flag_type(stubs={})
    @mock_flag_type ||= mock_model(FlagType, stubs)
  end

  describe "responding to GET index" do

    it "should expose all flag_types as @flag_types" do
      FlagType.should_receive(:find).with(:all).and_return([mock_flag_type])
      get :index
      assigns[:flag_types].should == [mock_flag_type]
    end

    describe "with mime type of xml" do

      it "should render all flag_types as xml" do
        request.env["HTTP_ACCEPT"] = "application/xml"
        FlagType.should_receive(:find).with(:all).and_return(flag_types = mock("Array of FlagTypes"))
        flag_types.should_receive(:to_xml).and_return("generated XML")
        get :index
        response.body.should == "generated XML"
      end

    end

  end

  describe "responding to GET show" do

    it "should expose the requested flag_type as @flag_type" do
      FlagType.should_receive(:find).with("37").and_return(mock_flag_type)
      get :show, :id => "37"
      assigns[:flag_type].should equal(mock_flag_type)
    end

    describe "with mime type of xml" do

      it "should render the requested flag_type as xml" do
        request.env["HTTP_ACCEPT"] = "application/xml"
        FlagType.should_receive(:find).with("37").and_return(mock_flag_type)
        mock_flag_type.should_receive(:to_xml).and_return("generated XML")
        get :show, :id => "37"
        response.body.should == "generated XML"
      end

    end

  end

  describe "responding to GET new" do

    it "should expose a new flag_type as @flag_type" do
      FlagType.should_receive(:new).and_return(mock_flag_type)
      get :new
      assigns[:flag_type].should equal(mock_flag_type)
    end

  end

  describe "responding to GET edit" do

    it "should expose the requested flag_type as @flag_type" do
      FlagType.should_receive(:find).with("37").and_return(mock_flag_type)
      get :edit, :id => "37"
      assigns[:flag_type].should equal(mock_flag_type)
    end

  end

  describe "responding to POST create" do

    describe "with valid params" do

      it "should expose a newly created flag_type as @flag_type" do
        FlagType.should_receive(:new).with({'these' => 'params'}).and_return(mock_flag_type(:save => true))
        post :create, :flag_type => {:these => 'params'}
        assigns(:flag_type).should equal(mock_flag_type)
      end

      it "should redirect to the created flag_type" do
        FlagType.stub!(:new).and_return(mock_flag_type(:save => true))
        post :create, :flag_type => {}
        response.should redirect_to(admin_flag_type_url(mock_flag_type))
      end

    end

    describe "with invalid params" do

      it "should expose a newly created but unsaved flag_type as @flag_type" do
        FlagType.stub!(:new).with({'these' => 'params'}).and_return(mock_flag_type(:save => false))
        post :create, :flag_type => {:these => 'params'}
        assigns(:flag_type).should equal(mock_flag_type)
      end

      it "should re-render the 'new' template" do
        FlagType.stub!(:new).and_return(mock_flag_type(:save => false))
        post :create, :flag_type => {}
        response.should render_template('new')
      end

    end

  end

  describe "responding to PUT udpate" do

    describe "with valid params" do

      it "should update the requested flag_type" do
        FlagType.should_receive(:find).with("37").and_return(mock_flag_type)
        mock_flag_type.should_receive(:update_attributes).with({'these' => 'params'})
        put :update, :id => "37", :flag_type => {:these => 'params'}
      end

      it "should expose the requested flag_type as @flag_type" do
        FlagType.stub!(:find).and_return(mock_flag_type(:update_attributes => true))
        put :update, :id => "1"
        assigns(:flag_type).should equal(mock_flag_type)
      end

      it "should redirect to the flag_type" do
        FlagType.stub!(:find).and_return(mock_flag_type(:update_attributes => true))
        put :update, :id => "1"
        response.should redirect_to(admin_flag_type_url(mock_flag_type))
      end

    end

    describe "with invalid params" do

      it "should update the requested flag_type" do
        FlagType.should_receive(:find).with("37").and_return(mock_flag_type)
        mock_flag_type.should_receive(:update_attributes).with({'these' => 'params'})
        put :update, :id => "37", :flag_type => {:these => 'params'}
      end

      it "should expose the flag_type as @flag_type" do
        FlagType.stub!(:find).and_return(mock_flag_type(:update_attributes => false))
        put :update, :id => "1"
        assigns(:flag_type).should equal(mock_flag_type)
      end

      it "should re-render the 'edit' template" do
        FlagType.stub!(:find).and_return(mock_flag_type(:update_attributes => false))
        put :update, :id => "1"
        response.should render_template('edit')
      end

    end

  end

  describe "responding to DELETE destroy" do

    it "should destroy the requested flag_type" do
      FlagType.should_receive(:find).with("37").and_return(mock_flag_type)
      mock_flag_type.should_receive(:destroy)
      delete :destroy, :id => "37"
    end

    it "should redirect to the flag_types list" do
      FlagType.stub!(:find).and_return(mock_flag_type(:destroy => true))
      delete :destroy, :id => "1"
      response.should redirect_to(admin_flag_types_url)
    end

  end

end


text:
skywater-pdk related GitHub Actions
===================================

.. image:: https://img.shields.io/github/license/google/skywater-pdk-actions
   :alt: GitHub license - Apache 2.0
   :target: https://github.com/google/skywater-pdk-actions

.. image:: https://img.shields.io/github/v/tag/google/skywater-pdk-actions?include_prereleases&sort=semver
   :alt: Latest GitHub tag (including pre-releases)
   :target: https://gitHub.com/google/skywater-pdk-actions/commit/

.. image:: https://img.shields.io/github/commits-since/google/skywater-pdk-actions/|TAG_VERSION|
   :alt: GitHub commits since latest release (|TAG_VERSION|)
   :target: https://gitHub.com/google/skywater-pdk-actions/commit/

This repository contains the GitHub actions uses with the
`Google skywater-pdk <https://github.com/google/skywater-pdk>`__ and
`related modules <https://github.com/google?q=skywater-pdk&type=&language=>`__.

.. image:: https://github.com/google/skywater-pdk/raw/master/docs/_static/skywater-pdk-logo.png
   :alt: Google + SkyWater Logo Image
   :align: center
   :target: https://github.com/google/skywater-pdk
   :width: 80%

Actions
=======

Modules Related
---------------

```modules-pr-backporter`` <./modules-pr-backporter>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``modules-pr-backporter`` action is used on the
`SkyWater modules <https://github.com/google?q=skywater-pdk-libs>`__
(such as the
`standard cells <https://github.com/google?q=skywater-pdk-libs-sky130_fd_sc>`__)
to enable automatic backporting of pull requests to older released
versions.

```modules-roller`` <./modules-roller>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``modules-roller`` action is used by
`the primary SkyWater PDK repo <https://github.com/google/skywater-pdk>`__
to automatically generate pull requests which update the GitHub submodules when
new changes are added to them.

CI Related
----------

-  TODO

Resources
=========

The latest SkyWater SKY130 PDK design resources can be viewed at the following locations:

* `On Github @ google/skywater-pdk <https://github.com/google/skywater-pdk>`_
* `Google CodeSearch interface @ https://cs.opensource.google/skywater-pdk <https://cs.opensource.google/skywater-pdk>`_
* `foss-eda-tools.googlesource.com/skywater-pdk <https://foss-eda-tools.googlesource.com/skywater-pdk/>`_

.. include:: docs/license.rst


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace Consul
{
    public sealed class WebClient : IWebClient
    {
        const string AllServicesUrl = "v1/catalog/services";
        const string RegisterServiceUrl = "v1/agent/service/register";
        const string UnregisterAgentServiceUrlTemplate = "v1/agent/service/deregister/{0}";
        const string CatalogDeregisterUrl = "v1/catalog/deregister";

        const string KeyValueUrlTemplate = "v1/kv/{0}";

        private HttpClient NetClient { get; set; }
        public Uri Host { get; private set; }

        public WebClient( string host )
        {
            Host = new Uri( host );
            NetClient = new HttpClient()
            {
                BaseAddress = Host
            };
        }

        public void Dispose()
        {
            Dispose( true );
            GC.SuppressFinalize( this );
        }

        private bool _disposed = false;
        private void Dispose( bool disposing )
        {
            if( _disposed ) return;
            if( NetClient != null )
            {
                NetClient.Dispose();
            }
            _disposed = true;
        }

        public async Task<bool> IsHostReachableAsync()
        {
            try
            {
                var response = await NetClient.GetAsync( Host );
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        //HTTP GET localhost:8500/v1/catalog/services
        public async Task<OperationResult<ServiceDefinitionOutput[]>> ReadServicesInCatalogAsync( string dc )
        {
            var url = AllServicesUrl;
            if( !string.IsNullOrWhiteSpace( dc ) )
            {
                url += string.Format( "?dc={0}", dc );
            }
            return await ReadServicesInCatalogInternalAsync( url );
        }

        //HTTP GET localhost:8500/v1/catalog/services?wait=10m&index={index}
        public async Task<OperationResult<ServiceDefinitionOutput[]>> BlockingReadServicesInCatalogAsync( string dc, int latestIndex )
        {
            var url = AllServicesUrl;
            if( !string.IsNullOrWhiteSpace( dc ) )
            {
                url += string.Format( "?dc={0}&wait=10m&index={1}", dc, latestIndex );
            }
            else
            {
                url += string.Format( "?wait=10m&index={0}", latestIndex );
            }

            return await ReadServicesInCatalogInternalAsync( url );
        }

        private async Task<OperationResult<ServiceDefinitionOutput[]>> ReadServicesInCatalogInternalAsync( string url )
        {
            var response = await NetClient.GetAsync( url );
            var json = await response.Content.ReadAsStringAsync();

            //the keys are the names of the services, so we need to use a JObject here.
            JObject jobject = JObject.Parse( json );
            var serviceNames = jobject.Properties().Select( p => p.Name ).ToList();

            List<ServiceDefinitionOutput> servicesList = new List<ServiceDefinitionOutput>();
            foreach( var serviceName in serviceNames )
            {
                servicesList.AddRange( await ReadServicesByNameAsync( serviceName ) );
            }

            int index = response.Headers.GetValue<int>( "X-Consul-Index" );

            return new OperationResult<ServiceDefinitionOutput[]>( servicesList.ToArray() )
            {
                ConsulIndex = index,
            };
        }

        //HTTP POST localhost:8500/v1/agent/service/register
        //{
        //  "id": "redis1",
        //  "name": "redis",
        //  "port": 8000,
        //  "tags": [ "master", "v1" ],
        //  "check": {
        //    "script": "/usr/local/bin/check_redis.py",
        //    "interval": "10s"
        //  }
        //}
        public async Task<bool> RegisterServiceAsync( ServiceDefinition service )
        {
            var response = await NetClient.PostJsonContentAsync( RegisterServiceUrl, service );
            return response.IsSuccessStatusCode;
        }

        //HTTP GET localhost:8500/v1/agent/service/deregister/{serviceName}
        public async Task<bool> UnregisterServiceAsync( string serviceId )
        {
            ServiceDefinitionOutput existingService = await ReadServiceByIdAsync( serviceId );
            if( existingService == null )
            {
                return false;
            }

            //http://www.consul.io/docs/agent/http.html#_v1_agent_service_deregister_lt_serviceID_gt_
            //this is not a bug, documentation says unregister should be perfomed via HTTP GET

            if( LocalMachine.IsLocalIP( existingService.Address ) )
            {
                //service is local, deregister via agent
                var url = string.Format( UnregisterAgentServiceUrlTemplate, serviceId );
                var response = await NetClient.GetAsync( url );
                return response.IsSuccessStatusCode;
            }
            else
            {
                //service is not on the local machine, unregister it via the catalog endpoint
                var response = await NetClient.PutJsonContentAsync( CatalogDeregisterUrl, new
                    {
                        Datacenter = Settings.DC1,
                        Node = existingService.Node,
                        ServiceID = existingService.ServiceId,
                    } );
                return response.IsSuccessStatusCode;
            }
        }

        public async Task<ServiceDefinitionOutput> ReadServiceByIdAsync( string serviceId )
        {
            OperationResult<ServiceDefinitionOutput[]> readServicesResult = await ReadServicesInCatalogAsync( null );

            var allServices = readServicesResult.Value;
            var match = allServices.Where( s => s.ServiceId == serviceId ).FirstOrDefault();
            return match;
        }

        const string ReadCatalogServiceUrlTemplate = "v1/catalog/service/{0}";
        const string ReadAgentServiceUrlTemplate = "v1/agent/service/{0}";

        //HTTP GET localhost:8500/v1/catalog/service/{serviceName}
        public async Task<ServiceDefinitionOutput[]> ReadServicesByNameAsync( string serviceName )
        {
            var url = string.Format( ReadCatalogServiceUrlTemplate, serviceName );
            var response = await NetClient.GetAsync( url );
            if( response.IsSuccessStatusCode )
            {
                return await response.DeserializeJsonAsync<ServiceDefinitionOutput[]>();
            }
            else
            {
                //could not find a service at the catalog path, look again with the agent path:
                url = string.Format( ReadCatalogServiceUrlTemplate, serviceName );
                response = await NetClient.GetAsync( url );
                return await response.DeserializeJsonAsync<ServiceDefinitionOutput[]>();
            }
        }

        public async Task<bool> CreateKeyAsync( string key, string value )
        {
            var request = new HttpRequestMessage( HttpMethod.Put, string.Format( KeyValueUrlTemplate, key ) );
            request.Content = new StringContent( value );
            var response = await NetClient.SendAsync( request );
            return response.IsSuccessStatusCode;
        }

        public async Task<ValueEntry[]> ReadKeyAsync( string key )
        {
            var url = string.Format( KeyValueUrlTemplate, key );
            var response = await NetClient.GetAsync( url );
            return await response.DeserializeJsonAsync<ValueEntry[]>();
        }

        public async Task<string> ReadKeySimpleAsync( string key )
        {
            ValueEntry[] values = await ReadKeyAsync( key );
            if( values == null ) return null;
            return values[ 0 ].GetDecodedValue();
        }

        public async Task<bool> DeleteKeyAsync( string key )
        {
            var request = new HttpRequestMessage( HttpMethod.Delete, string.Format( KeyValueUrlTemplate, key ) );
            var response = await NetClient.SendAsync( request );
            return response.IsSuccessStatusCode;
        }

        public async Task<bool> DeleteNodeAsync( string node, string dataCenter )
        {
            var response = await NetClient.PutJsonContentAsync( CatalogDeregisterUrl, new
            {
                DataCenter = dataCenter,
                Node = node,
            } );
            return response.IsSuccessStatusCode;
        }
    }
}


text:
<?php
class ViewLookupWizardField extends ViewControl
{
	public $nLookupType;
	public $lookupTable;
	public $displayFieldName;
	public $linkFieldName;
	public $linkAndDisplaySame;
	public $pSet;
	public $lookupPSet;
	public $cipherer;
	public $lookupQueryObj;
	public $displayFieldIndex;
	public $LookupSQL;
	public $resolvedLookupValues = array();
	public $resolvedLinkLookupValues = array();
	public $linkFieldIndex;

	public $localControlsContainer;

	public function ViewLookupWizardField($field, $container, $pageObject)
	{
		parent::ViewControl($field, $container, $pageObject);

		$this->nLookupType = null;
		$this->lookupTable = "";
		$this->displayFieldName = "";
		$this->linkFieldName = "";
		$this->linkAndDisplaySame = false;
		$this->lookupPSet = null;
		$this->cipherer = null;
		$this->lookupQueryObj = null;
		$this->displayFieldIndex = 0;
		$this->linkFieldIndex = 1;
		$this->LookupSQL = "";

		if($this->container->pSet->getEditFormat($field) != EDIT_FORMAT_LOOKUP_WIZARD)
		{
			$this->pSet = new ProjectSettings($this->container->pSet->_table,
				$this->container->pSet->getPageTypeByFieldEditFormat($field, EDIT_FORMAT_LOOKUP_WIZARD));
		}
		else
			$this->pSet = $this->container->pSet;

		$this->nLookupType = $this->pSet->getLookupType($this->field);
		$this->lookupTable = $this->pSet->getLookupTable($this->field);
		$this->displayFieldName = $this->pSet->getDisplayField($this->field);
		$this->linkFieldName = $this->pSet->getLinkField($this->field);
		$this->linkAndDisplaySame = $this->displayFieldName == $this->linkFieldName;
		if($this->nLookupType == LT_QUERY){
			$this->lookupPSet = new ProjectSettings($this->lookupTable, $this->container->pageType);
			$this->cipherer = new RunnerCipherer($this->lookupTable);
			$this->lookupQueryObj = $this->lookupPSet->getSQLQuery()->CloneObject();
			if($this->pSet->getCustomDisplay($this->field))
				$this->lookupQueryObj->AddCustomExpression($this->displayFieldName, $this->lookupPSet, $this->pSet->_table, $this->field);
			$this->lookupQueryObj->ReplaceFieldsWithDummies($this->lookupPSet->getBinaryFieldsIndices());
			$lookupIndexes = GetLookupFieldsIndexes($this->pSet, $this->field);
			$this->displayFieldIndex = $lookupIndexes["displayFieldIndex"];
			$this->linkFieldIndex = $lookupIndexes["linkFieldIndex"];
		}else{
			$this->cipherer = new RunnerCipherer($this->pSet->_table);
			$this->LookupSQL = "SELECT ";
			$this->LookupSQL.= $this->pSet->getLWDisplayField($this->field).", ".$this->pSet->getLWLinkField($this->field);
			$this->LookupSQL.= " FROM ".AddTableWrappers($this->pSet->getLookupTable($this->field))." WHERE ";
		}

		$this->localControlsContainer = new ViewControlsContainer($this->pSet, $this->container->pageType, $pageObject);
		$this->localControlsContainer->isLocal = true;
	}

	public function showDBValue(&$data, $keylink)
	{
		global $conn, $strTableName;
		$value = $data[$this->field];
		if(!strlen($value))
			return "";

		$where = "";
		$out = "";
		$lookupvalue = $value;
		$iquery = "field=".runner_htmlspecialchars(rawurlencode($this->field)).$keylink;

		$where = GetLWWhere($this->field, $this->pSet->getEditPageType());
		if($this->pSet->multiSelect($this->field))
		{
			$arr = splitvalues($value);
			$numeric = true;
			$type = $this->pSet->getLWLinkFieldType($this->field);
			if(!$type)
			{
				foreach($arr as $val)
					if(strlen($val) && !is_numeric($val))
					{
						$numeric=false;
						break;
					}
			}
			else
				$numeric = !NeedQuotes($type);
			$in = "";
			foreach($arr as $val)
			{
				if($numeric && !strlen($val))
					continue;
				if(strlen($in))
					$in.= ",";
				if($numeric)
					$in.= ($val+0);
				else
					$in.= db_prepare_string($this->cipherer->EncryptField($this->nLookupType == LT_QUERY ? $this->linkFieldName : $this->field, $val));
			}
			if(strlen($in))
			{

				if( count($this->resolvedLookupValues[$value]) )
				{
					$lookupArr = $this->resolvedLookupValues[$value];
					$lookupLinksResolutionArr = $this->resolvedLinkLookupValues[$value];
				}
				else
				{
					if($this->nLookupType == LT_QUERY){
						$inWhere = GetFullFieldName($this->linkFieldName, $this->lookupTable, false)." in (".$in.")";
						if(strlen($where))
							$inWhere.=" and (".$where.")";
						$LookupSQL = $this->lookupQueryObj->toSql(whereAdd($this->lookupQueryObj->m_where->toSql($this->lookupQueryObj), $inWhere));
					}else{
						$LookupSQL = $this->LookupSQL.$this->pSet->getLWLinkField($this->field)." in (".$in.")";
						if(strlen($where))
							$LookupSQL.=" and (".$where.")";
					}
					LogInfo($LookupSQL);
					$rsLookup = db_query($LookupSQL,$conn);
					$found = false;
					$lookupArrTmp = array();
					$lookupLinksResolutionArr = array();
					$lookupArr = array();
					while($lookuprow=db_fetch_numarray($rsLookup))
					{
						$displayValue = $lookuprow[$this->displayFieldIndex];
						$lookupArrTmp[] = $displayValue;
						$lookupLinksResolutionArr[$displayValue] = $lookuprow[$this->linkFieldIndex];
					}
					$lookupArr = array_unique($lookupArrTmp);
					if( count($lookupArr) )
					{
						$this->resolvedLookupValues[$value] = $lookupArr;
						 $this->resolvedLinkLookupValues[$value] = $lookupLinksResolutionArr;
					}
				}
				$localData = $data;
				foreach($lookupArr as $lookupvalue)
				{
					if($found)
						$out.= ",";
					$found = true;
					$this->localControlsContainer->linkFieldValues[$this->field] = $data[$this->field];
					$this->localControlsContainer->originlinkValues[$this->field] = $lookupLinksResolutionArr[ $lookupvalue ];
					if($this->pSet->getViewFormat($this->field) != "Custom"){
						$localData[$this->field] = $lookupvalue;
					}
					$outVal = $this->localControlsContainer->showDBValue($this->field, $localData, $keylink, $lookupvalue);
					$out.= $this->nLookupType == LT_QUERY || $this->linkAndDisplaySame ?
						$this->cipherer->DecryptField($this->nLookupType == LT_QUERY ? $this->displayFieldName : $this->field, $outVal) : $outVal;
				}
				return $out;
			}
		}
		else
		{
			$found = false;
			if( isset($this->resolvedLookupValues[$value]) )
			{
				$lookupvalue = $this->resolvedLookupValues[$value];
				$found = true;
			}
			else
			{
				$strdata = $this->cipherer->MakeDBValue($this->nLookupType == LT_QUERY ? $this->linkFieldName : $this->field, $value, "", "", true);
				if($this->nLookupType == LT_QUERY){
					$strWhere = GetFullFieldName($this->linkFieldName, $this->lookupTable, false)." = " . $strdata;
					if(strlen($where))
						$strWhere.= " and (".$where.")";
					$LookupSQL = $this->lookupQueryObj->toSql(whereAdd($this->lookupQueryObj->m_where->toSql($this->lookupQueryObj), $strWhere));
				}else{
					$strWhere = $this->pSet->getLWLinkField($this->field)." = " . $strdata;
					if(strlen($where))
						$strWhere.= " and (".$where.")";
					$LookupSQL = $this->LookupSQL.$strWhere;
				}
				LogInfo($LookupSQL);
				$rsLookup = db_query($LookupSQL,$conn);
				if($lookuprow = db_fetch_numarray($rsLookup)){
					$lookupvalue = $lookuprow[$this->displayFieldIndex];
					$this->resolvedLookupValues[$value] = $lookupvalue;
					$found = true;
				}
			}
		}
		if(!$out){
			if($found && ($this->nLookupType == LT_QUERY || $this->linkAndDisplaySame)){
				$lookupvalue = $this->cipherer->DecryptField($this->nLookupType == LT_QUERY ? $this->displayFieldName : $this->field, $lookupvalue);
			}
			$localData = $data;
			$this->localControlsContainer->linkFieldValues[$this->field] = $data[$this->field];
			if($this->pSet->getViewFormat($this->field) != "Custom"){
				$localData[$this->field] = $lookupvalue;
			}
			$out = $this->localControlsContainer->showDBValue($this->field, $localData, $keylink, $lookupvalue);
		}
		return $out;
	}
}
?>


text:
package com.mauriciotogneri.dry.compiler.syntactic.nodes;

import com.mauriciotogneri.dry.compiler.lexical.Token;
import com.mauriciotogneri.dry.compiler.syntactic.TreeNode;

public class AssignmentNode extends ExpressionBinaryNode
{
    public AssignmentNode(Token token, TreeNode definition, TreeNode expression)
    {
        super(token, definition, expression);
    }

    @Override
    public String sourceCode()
    {
        return String.format("%s = %s", left.sourceCode(), right.sourceCode());
    }
}


text:
package org.dependencytrack.notification.publisher;

import alpine.logging.Logger;
import alpine.notification.Notification;
import alpine.notification.NotificationLevel;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import javax.json.JsonObject;
import java.io.PrintStream;

public class ConsolePublisher implements Publisher {

    private static final Logger LOGGER = Logger.getLogger(ConsolePublisher.class);
    private static final PebbleEngine ENGINE = new PebbleEngine.Builder().newLineTrimming(false).build();
    private static final PebbleTemplate TEMPLATE = ENGINE.getTemplate("templates/notification/publisher/console.peb");

    public void inform(final Notification notification, final JsonObject config) {
        final String content = prepareTemplate(notification, TEMPLATE);
        if (content == null) {
            LOGGER.warn("A template was not found. Skipping notification");
            return;
        }
        final PrintStream ps;
        if (notification.getLevel() == NotificationLevel.ERROR) {
            ps = System.err;
        } else {
            ps = System.out;
        }
        ps.println(content);
    }
}


text:
package access.solution.local;
//import access.solution.local.*;
public class Foreign {
	public static void main(String[] args){
		PackagedClass pc = new PackagedClass();
	}
}


text:
import java.io.IOException;

import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.mapred.lib.LongSumReducer;
import org.apache.hadoop.util.*;

public class TemperatureDistribution extends Configured implements Tool {

  static class TemperatureCountMapper extends MapReduceBase
    implements Mapper<LongWritable, Text, IntWritable, LongWritable> {

    private static final LongWritable ONE = new LongWritable(1);
    private NcdcRecordParser parser = new NcdcRecordParser();

    public void map(LongWritable key, Text value,
        OutputCollector<IntWritable, LongWritable> output, Reporter reporter)
        throws IOException {

      parser.parse(value);
      if (parser.isValidTemperature()) {
        output.collect(new IntWritable(parser.getAirTemperature() / 10), ONE);
      }
    }
  }

  @Override
  public int run(String[] args) throws IOException {
    JobConf conf = JobBuilder.parseInputAndOutput(this, getConf(), args);
    if (conf == null) {
      return -1;
    }

    conf.setMapperClass(TemperatureCountMapper.class);
    conf.setCombinerClass(LongSumReducer.class);
    conf.setReducerClass(LongSumReducer.class);
    conf.setOutputKeyClass(IntWritable.class);
    conf.setOutputValueClass(LongWritable.class);

    JobClient.runJob(conf);
    return 0;
  }

  public static void main(String[] args) throws Exception {
    int exitCode = ToolRunner.run(new TemperatureDistribution(), args);
    System.exit(exitCode);
  }
}


text:
package org.apache.camel.component.jms;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import javax.jms.ConnectionFactory;
import javax.jms.ExceptionListener;
import javax.jms.Session;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.LoggingLevel;
import org.apache.camel.impl.DefaultComponent;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.spi.HeaderFilterStrategyAware;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.task.TaskExecutor;
import org.springframework.jms.connection.JmsTransactionManager;
import org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter;
import org.springframework.jms.core.JmsOperations;
import org.springframework.jms.listener.AbstractMessageListenerContainer;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.destination.DestinationResolver;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.util.ErrorHandler;

import static org.apache.camel.util.ObjectHelper.removeStartingCharacters;

/**
 * A JMS Component
 *
 * @version
 */
public class JmsComponent extends DefaultComponent implements ApplicationContextAware, HeaderFilterStrategyAware {

    private static final String KEY_FORMAT_STRATEGY_PARAM = "jmsKeyFormatStrategy";
    private JmsConfiguration configuration;
    private ApplicationContext applicationContext;
    private QueueBrowseStrategy queueBrowseStrategy;
    private HeaderFilterStrategy headerFilterStrategy = new JmsHeaderFilterStrategy();
    private ExecutorService asyncStartStopExecutorService;
    private MessageListenerContainerFactory messageListenerContainerFactory;

    public JmsComponent() {
    }

    public JmsComponent(CamelContext context) {
        super(context);
    }

    public JmsComponent(JmsConfiguration configuration) {
        this.configuration = configuration;
    }

    /**
     * Static builder method
     */
    public static JmsComponent jmsComponent() {
        return new JmsComponent();
    }

    /**
     * Static builder method
     */
    public static JmsComponent jmsComponent(JmsConfiguration configuration) {
        return new JmsComponent(configuration);
    }

    /**
     * Static builder method
     */
    public static JmsComponent jmsComponent(ConnectionFactory connectionFactory) {
        return jmsComponent(new JmsConfiguration(connectionFactory));
    }

    /**
     * Static builder method
     */
    public static JmsComponent jmsComponentClientAcknowledge(ConnectionFactory connectionFactory) {
        JmsConfiguration template = new JmsConfiguration(connectionFactory);
        template.setAcknowledgementMode(Session.CLIENT_ACKNOWLEDGE);
        return jmsComponent(template);
    }

    /**
     * Static builder method
     */
    public static JmsComponent jmsComponentAutoAcknowledge(ConnectionFactory connectionFactory) {
        JmsConfiguration template = new JmsConfiguration(connectionFactory);
        template.setAcknowledgementMode(Session.AUTO_ACKNOWLEDGE);
        return jmsComponent(template);
    }

    public static JmsComponent jmsComponentTransacted(ConnectionFactory connectionFactory) {
        JmsTransactionManager transactionManager = new JmsTransactionManager();
        transactionManager.setConnectionFactory(connectionFactory);
        return jmsComponentTransacted(connectionFactory, transactionManager);
    }

    @SuppressWarnings("deprecation")
    public static JmsComponent jmsComponentTransacted(ConnectionFactory connectionFactory,
                                                      PlatformTransactionManager transactionManager) {
        JmsConfiguration template = new JmsConfiguration(connectionFactory);
        template.setTransactionManager(transactionManager);
        template.setTransacted(true);
        template.setTransactedInOut(true);
        return jmsComponent(template);
    }

    // Properties
    // -------------------------------------------------------------------------

    public JmsConfiguration getConfiguration() {
        if (configuration == null) {
            configuration = createConfiguration();

            // If we are being configured with spring...
            if (applicationContext != null) {
                Map<String, ConnectionFactory> beansOfTypeConnectionFactory = applicationContext.getBeansOfType(ConnectionFactory.class);
                if (!beansOfTypeConnectionFactory.isEmpty()) {
                    ConnectionFactory cf = beansOfTypeConnectionFactory.values().iterator().next();
                    configuration.setConnectionFactory(cf);
                }
                Map<String, DestinationResolver> beansOfTypeDestinationResolver = applicationContext.getBeansOfType(DestinationResolver.class);
                if (!beansOfTypeDestinationResolver.isEmpty()) {
                    DestinationResolver destinationResolver = beansOfTypeDestinationResolver.values().iterator().next();
                    configuration.setDestinationResolver(destinationResolver);
                }
            }
        }
        return configuration;
    }

    /**
     * Sets the JMS configuration
     *
     * @param configuration the configuration to use by default for endpoints
     */
    public void setConfiguration(JmsConfiguration configuration) {
        this.configuration = configuration;
    }

    public void setAcceptMessagesWhileStopping(boolean acceptMessagesWhileStopping) {
        getConfiguration().setAcceptMessagesWhileStopping(acceptMessagesWhileStopping);
    }

    public void setAcknowledgementMode(int consumerAcknowledgementMode) {
        getConfiguration().setAcknowledgementMode(consumerAcknowledgementMode);
    }

    public void setEagerLoadingOfProperties(boolean eagerLoadingOfProperties) {
        getConfiguration().setEagerLoadingOfProperties(eagerLoadingOfProperties);
    }

    public void setAcknowledgementModeName(String consumerAcknowledgementMode) {
        getConfiguration().setAcknowledgementModeName(consumerAcknowledgementMode);
    }

    public void setAutoStartup(boolean autoStartup) {
        getConfiguration().setAutoStartup(autoStartup);
    }

    public void setCacheLevel(int cacheLevel) {
        getConfiguration().setCacheLevel(cacheLevel);
    }

    public void setCacheLevelName(String cacheName) {
        getConfiguration().setCacheLevelName(cacheName);
    }

    public void setReplyToCacheLevelName(String cacheName) {
        getConfiguration().setReplyToCacheLevelName(cacheName);
    }

    public void setClientId(String consumerClientId) {
        getConfiguration().setClientId(consumerClientId);
    }

    public void setConcurrentConsumers(int concurrentConsumers) {
        getConfiguration().setConcurrentConsumers(concurrentConsumers);
    }

    public void setConnectionFactory(ConnectionFactory connectionFactory) {
        getConfiguration().setConnectionFactory(connectionFactory);
    }

    public void setDeliveryPersistent(boolean deliveryPersistent) {
        getConfiguration().setDeliveryPersistent(deliveryPersistent);
    }

    public void setDurableSubscriptionName(String durableSubscriptionName) {
        getConfiguration().setDurableSubscriptionName(durableSubscriptionName);
    }

    public void setExceptionListener(ExceptionListener exceptionListener) {
        getConfiguration().setExceptionListener(exceptionListener);
    }

    public void setErrorHandler(ErrorHandler errorHandler) {
        getConfiguration().setErrorHandler(errorHandler);
    }

    public void setErrorHandlerLoggingLevel(LoggingLevel errorHandlerLoggingLevel) {
        getConfiguration().setErrorHandlerLoggingLevel(errorHandlerLoggingLevel);
    }

    public void setErrorHandlerLogStackTrace(boolean errorHandlerLogStackTrace) {
        getConfiguration().setErrorHandlerLogStackTrace(errorHandlerLogStackTrace);
    }

    public void setExplicitQosEnabled(boolean explicitQosEnabled) {
        getConfiguration().setExplicitQosEnabled(explicitQosEnabled);
    }

    public void setExposeListenerSession(boolean exposeListenerSession) {
        getConfiguration().setExposeListenerSession(exposeListenerSession);
    }

    public void setIdleTaskExecutionLimit(int idleTaskExecutionLimit) {
        getConfiguration().setIdleTaskExecutionLimit(idleTaskExecutionLimit);
    }

    public void setIdleConsumerLimit(int idleConsumerLimit) {
        getConfiguration().setIdleConsumerLimit(idleConsumerLimit);
    }

    public void setMaxConcurrentConsumers(int maxConcurrentConsumers) {
        getConfiguration().setMaxConcurrentConsumers(maxConcurrentConsumers);
    }

    public void setMaxMessagesPerTask(int maxMessagesPerTask) {
        getConfiguration().setMaxMessagesPerTask(maxMessagesPerTask);
    }

    public void setMessageConverter(MessageConverter messageConverter) {
        getConfiguration().setMessageConverter(messageConverter);
    }

    public void setMapJmsMessage(boolean mapJmsMessage) {
        getConfiguration().setMapJmsMessage(mapJmsMessage);
    }

    public void setMessageIdEnabled(boolean messageIdEnabled) {
        getConfiguration().setMessageIdEnabled(messageIdEnabled);
    }

    public void setMessageTimestampEnabled(boolean messageTimestampEnabled) {
        getConfiguration().setMessageTimestampEnabled(messageTimestampEnabled);
    }

    public void setAlwaysCopyMessage(boolean alwaysCopyMessage) {
        getConfiguration().setAlwaysCopyMessage(alwaysCopyMessage);
    }

    public void setUseMessageIDAsCorrelationID(boolean useMessageIDAsCorrelationID) {
        getConfiguration().setUseMessageIDAsCorrelationID(useMessageIDAsCorrelationID);
    }

    public void setPriority(int priority) {
        getConfiguration().setPriority(priority);
    }

    public void setPubSubNoLocal(boolean pubSubNoLocal) {
        getConfiguration().setPubSubNoLocal(pubSubNoLocal);
    }

    public void setReceiveTimeout(long receiveTimeout) {
        getConfiguration().setReceiveTimeout(receiveTimeout);
    }

    public void setRecoveryInterval(long recoveryInterval) {
        getConfiguration().setRecoveryInterval(recoveryInterval);
    }

    @Deprecated
    public void setSubscriptionDurable(boolean subscriptionDurable) {
        getConfiguration().setSubscriptionDurable(subscriptionDurable);
    }

    public void setTaskExecutor(TaskExecutor taskExecutor) {
        getConfiguration().setTaskExecutor(taskExecutor);
    }

    public void setTimeToLive(long timeToLive) {
        getConfiguration().setTimeToLive(timeToLive);
    }

    public void setTransacted(boolean consumerTransacted) {
        getConfiguration().setTransacted(consumerTransacted);
    }

    public void setLazyCreateTransactionManager(boolean lazyCreating) {
        getConfiguration().setLazyCreateTransactionManager(lazyCreating);
    }

    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        getConfiguration().setTransactionManager(transactionManager);
    }

    public void setTransactionName(String transactionName) {
        getConfiguration().setTransactionName(transactionName);
    }

    public void setTransactionTimeout(int transactionTimeout) {
        getConfiguration().setTransactionTimeout(transactionTimeout);
    }

    public void setTestConnectionOnStartup(boolean testConnectionOnStartup) {
        getConfiguration().setTestConnectionOnStartup(testConnectionOnStartup);
    }

    public void setAsyncStartListener(boolean asyncStartListener) {
        getConfiguration().setAsyncStartListener(asyncStartListener);
    }

    public void setAsyncStopListener(boolean asyncStopListener) {
        getConfiguration().setAsyncStopListener(asyncStopListener);
    }

    public void setForceSendOriginalMessage(boolean forceSendOriginalMessage) {
        getConfiguration().setForceSendOriginalMessage(forceSendOriginalMessage);
    }

    public void setRequestTimeout(long requestTimeout) {
        getConfiguration().setRequestTimeout(requestTimeout);
    }

    public void setRequestTimeoutCheckerInterval(long requestTimeoutCheckerInterval) {
        getConfiguration().setRequestTimeoutCheckerInterval(requestTimeoutCheckerInterval);
    }

    public void setTransferExchange(boolean transferExchange) {
        getConfiguration().setTransferExchange(transferExchange);
    }

    public void setTransferException(boolean transferException) {
        getConfiguration().setTransferException(transferException);
    }

    public void setJmsOperations(JmsOperations jmsOperations) {
        getConfiguration().setJmsOperations(jmsOperations);
    }

    public void setDestinationResolver(DestinationResolver destinationResolver) {
        getConfiguration().setDestinationResolver(destinationResolver);
    }

    public void setReplyToType(ReplyToType replyToType) {
        getConfiguration().setReplyToType(replyToType);
    }

    public void setPreserveMessageQos(boolean preserveMessageQos) {
        getConfiguration().setPreserveMessageQos(preserveMessageQos);
    }

    public void setAsyncConsumer(boolean asyncConsumer) {
        getConfiguration().setAsyncConsumer(asyncConsumer);
    }

    public void setAllowNullBody(boolean allowNullBody) {
        getConfiguration().setAllowNullBody(allowNullBody);
    }

    public void setIncludeSentJMSMessageID(boolean includeSentJMSMessageID) {
        getConfiguration().setIncludeSentJMSMessageID(includeSentJMSMessageID);
    }

    public void setDefaultTaskExecutorType(DefaultTaskExecutorType type) {
        getConfiguration().setDefaultTaskExecutorType(type);
    }

    public void setJmsKeyFormatStrategy(JmsKeyFormatStrategy jmsKeyFormatStrategy) {
        getConfiguration().setJmsKeyFormatStrategy(jmsKeyFormatStrategy);
    }

    public void setJmsKeyFormatStrategy(String jmsKeyFormatStrategyName) {
        // allow to configure a standard by its name, which is simpler
        JmsKeyFormatStrategy strategy = resolveStandardJmsKeyFormatStrategy(jmsKeyFormatStrategyName);
        if (strategy == null) {
            throw new IllegalArgumentException("JmsKeyFormatStrategy with name " + jmsKeyFormatStrategyName + " is not a standard supported name");
        } else {
            getConfiguration().setJmsKeyFormatStrategy(strategy);
        }
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public QueueBrowseStrategy getQueueBrowseStrategy() {
        if (queueBrowseStrategy == null) {
            queueBrowseStrategy = new DefaultQueueBrowseStrategy();
        }
        return queueBrowseStrategy;
    }

    public void setQueueBrowseStrategy(QueueBrowseStrategy queueBrowseStrategy) {
        this.queueBrowseStrategy = queueBrowseStrategy;
    }

    public HeaderFilterStrategy getHeaderFilterStrategy() {
        return headerFilterStrategy;
    }

    public void setHeaderFilterStrategy(HeaderFilterStrategy strategy) {
        this.headerFilterStrategy = strategy;
    }

    // Implementation methods
    // -------------------------------------------------------------------------

    @Override
    protected void doShutdown() throws Exception {
        if (asyncStartStopExecutorService != null) {
            getCamelContext().getExecutorServiceManager().shutdownNow(asyncStartStopExecutorService);
            asyncStartStopExecutorService = null;
        }
        super.doShutdown();
    }

    protected synchronized ExecutorService getAsyncStartStopExecutorService() {
        if (asyncStartStopExecutorService == null) {
            // use a cached thread pool for async start tasks as they can run for a while, and we need a dedicated thread
            // for each task, and the thread pool will shrink when no more tasks running
            asyncStartStopExecutorService = getCamelContext().getExecutorServiceManager().newCachedThreadPool(this, "AsyncStartStopListener");
        }
        return asyncStartStopExecutorService;
    }

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
        throws Exception {

        boolean pubSubDomain = false;
        boolean tempDestination = false;
        if (remaining.startsWith(JmsConfiguration.QUEUE_PREFIX)) {
            pubSubDomain = false;
            remaining = removeStartingCharacters(remaining.substring(JmsConfiguration.QUEUE_PREFIX.length()), '/');
        } else if (remaining.startsWith(JmsConfiguration.TOPIC_PREFIX)) {
            pubSubDomain = true;
            remaining = removeStartingCharacters(remaining.substring(JmsConfiguration.TOPIC_PREFIX.length()), '/');
        } else if (remaining.startsWith(JmsConfiguration.TEMP_QUEUE_PREFIX)) {
            pubSubDomain = false;
            tempDestination = true;
            remaining = removeStartingCharacters(remaining.substring(JmsConfiguration.TEMP_QUEUE_PREFIX.length()), '/');
        } else if (remaining.startsWith(JmsConfiguration.TEMP_TOPIC_PREFIX)) {
            pubSubDomain = true;
            tempDestination = true;
            remaining = removeStartingCharacters(remaining.substring(JmsConfiguration.TEMP_TOPIC_PREFIX.length()), '/');
        }

        final String subject = convertPathToActualDestination(remaining, parameters);

        // lets make sure we copy the configuration as each endpoint can
        // customize its own version
        JmsConfiguration newConfiguration = getConfiguration().copy();
        JmsEndpoint endpoint;
        if (pubSubDomain) {
            if (tempDestination) {
                endpoint = new JmsTemporaryTopicEndpoint(uri, this, subject, newConfiguration);
            } else {
                endpoint = new JmsEndpoint(uri, this, subject, pubSubDomain, newConfiguration);
            }
        } else {
            QueueBrowseStrategy strategy = getQueueBrowseStrategy();
            if (tempDestination) {
                endpoint = new JmsTemporaryQueueEndpoint(uri, this, subject, newConfiguration, strategy);
            } else {
                endpoint = new JmsQueueEndpoint(uri, this, subject, newConfiguration, strategy);
            }
        }

        // resolve any custom connection factory first
        ConnectionFactory cf = resolveAndRemoveReferenceParameter(parameters, "connectionFactory", ConnectionFactory.class);
        if (cf != null) {
            endpoint.getConfiguration().setConnectionFactory(cf);
        }

        String username = getAndRemoveParameter(parameters, "username", String.class);
        String password = getAndRemoveParameter(parameters, "password", String.class);
        if (username != null && password != null) {
            cf = endpoint.getConfiguration().getConnectionFactory();
            UserCredentialsConnectionFactoryAdapter ucfa = new UserCredentialsConnectionFactoryAdapter();
            ucfa.setTargetConnectionFactory(cf);
            ucfa.setPassword(password);
            ucfa.setUsername(username);
            endpoint.getConfiguration().setConnectionFactory(ucfa);
        } else {
            if (username != null || password != null) {
                // exclude the the saturation of username and password are all empty
                throw new IllegalArgumentException("The JmsComponent's username or password is null");
            }
        }

        // jms header strategy
        String strategyVal = getAndRemoveParameter(parameters, KEY_FORMAT_STRATEGY_PARAM, String.class);
        JmsKeyFormatStrategy strategy = resolveStandardJmsKeyFormatStrategy(strategyVal);
        if (strategy != null) {
            endpoint.setJmsKeyFormatStrategy(strategy);
        } else {
            // its not a standard, but a reference
            parameters.put(KEY_FORMAT_STRATEGY_PARAM, strategyVal);
            endpoint.setJmsKeyFormatStrategy(resolveAndRemoveReferenceParameter(
                    parameters, KEY_FORMAT_STRATEGY_PARAM, JmsKeyFormatStrategy.class));
        }

        messageListenerContainerFactory = resolveAndRemoveReferenceParameter(parameters,
                "messageListenerContainerFactoryRef", MessageListenerContainerFactory.class);
        if (messageListenerContainerFactory != null) {
            endpoint.setMessageListenerContainerFactory(messageListenerContainerFactory);
        }

        setProperties(endpoint.getConfiguration(), parameters);
        endpoint.setHeaderFilterStrategy(getHeaderFilterStrategy());

        return endpoint;
    }

    /**
     * Resolves the standard supported {@link JmsKeyFormatStrategy} by a name which can be:
     *

     *
default - to use the default strategy

     *
passthrough - to use the passthrough strategy

     *

     *
     * @param name  the name
     * @return the strategy, or <tt>null</tt> if not a standard name.
     */
    private static JmsKeyFormatStrategy resolveStandardJmsKeyFormatStrategy(String name) {
        if ("default".equalsIgnoreCase(name)) {
            return new DefaultJmsKeyFormatStrategy();
        } else if ("passthrough".equalsIgnoreCase(name)) {
            return new PassThroughJmsKeyFormatStrategy();
        } else {
            return null;
        }
    }

    /**
     * A strategy method allowing the URI destination to be translated into the
     * actual JMS destination name (say by looking up in JNDI or something)
     */
    protected String convertPathToActualDestination(String path, Map<String, Object> parameters) {
        return path;
    }

    /**
     * Factory method to create the default configuration instance
     *
     * @return a newly created configuration object which can then be further
     *         customized
     */
    protected JmsConfiguration createConfiguration() {
        return new JmsConfiguration();
    }

}


text:
var semafor = require('../dist/')();
semafor.fail("This is an error");
semafor.warn("This is a warning");
semafor.ok("This is success");
semafor.log("This is sparta");