text:
package com.google.android.exoplayer2.source;

import static com.google.android.exoplayer2.util.Assertions.checkNotNull;

import android.net.Uri;
import android.os.Looper;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.drm.DefaultDrmSessionManagerProvider;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.DrmSessionManagerProvider;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.Extractor;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.upstream.Allocator;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultLoadErrorHandlingPolicy;
import com.google.android.exoplayer2.upstream.LoadErrorHandlingPolicy;
import com.google.android.exoplayer2.upstream.TransferListener;
import com.google.errorprone.annotations.CanIgnoreReturnValue;

/**
 * Provides one period that loads data from a {@link Uri} and extracted using an {@link Extractor}.
 *
 *
If the possible input stream container formats are known, pass a factory that instantiates
 * extractors for them to the constructor. Otherwise, pass a {@link DefaultExtractorsFactory} to use
 * the default extractors. When reading a new stream, the first {@link Extractor} in the array of
 * extractors created by the factory that returns {@code true} from {@link Extractor#sniff} will be
 * used to extract samples from the input stream.
 *
 *
Note that the built-in extractor for FLV streams does not support seeking.
 */
public final class ProgressiveMediaSource extends BaseMediaSource
    implements ProgressiveMediaPeriod.Listener {

  /** Factory for {@link ProgressiveMediaSource}s. */
  @SuppressWarnings("deprecation") // Implement deprecated type for backwards compatibility.
  public static final class Factory implements MediaSourceFactory {

    private final DataSource.Factory dataSourceFactory;

    private ProgressiveMediaExtractor.Factory progressiveMediaExtractorFactory;
    private DrmSessionManagerProvider drmSessionManagerProvider;
    private LoadErrorHandlingPolicy loadErrorHandlingPolicy;
    private int continueLoadingCheckIntervalBytes;
    @Nullable private String customCacheKey;
    @Nullable private Object tag;

    /**
     * Creates a new factory for {@link ProgressiveMediaSource}s.
     *
     *
The factory will use the following default components:
     *
     *

     *
{@link DefaultExtractorsFactory}
     *
{@link DefaultDrmSessionManagerProvider}
     *
{@link DefaultLoadErrorHandlingPolicy}
     *

     *
     * @param dataSourceFactory A factory for {@linkplain DataSource data sources} to read the
     *     media.
     */
    public Factory(DataSource.Factory dataSourceFactory) {
      this(dataSourceFactory, new DefaultExtractorsFactory());
    }

    /**
     * Equivalent to {@link #Factory(DataSource.Factory, ProgressiveMediaExtractor.Factory) new
     * Factory(dataSourceFactory, () -> new BundledExtractorsAdapter(extractorsFactory)}.
     *
     *
The factory will use the following default components:
     *
     *

     *
{@link DefaultDrmSessionManagerProvider}
     *
{@link DefaultLoadErrorHandlingPolicy}
     *

     *
     * @param dataSourceFactory A factory for {@linkplain DataSource data sources} to read the
     *     media.
     * @param extractorsFactory A factory for the {@linkplain Extractor extractors} used to extract
     *     the media from its container.
     */
    public Factory(DataSource.Factory dataSourceFactory, ExtractorsFactory extractorsFactory) {
      this(dataSourceFactory, playerId -> new BundledExtractorsAdapter(extractorsFactory));
    }

    /**
     * Creates a new factory for {@link ProgressiveMediaSource}s.
     *
     *
The factory will use the following default components:
     *
     *

     *
{@link DefaultDrmSessionManagerProvider}
     *
{@link DefaultLoadErrorHandlingPolicy}
     *

     *
     * @param dataSourceFactory A factory for {@linkplain DataSource data sources} to read the
     *     media.
     * @param progressiveMediaExtractorFactory A factory for the {@link ProgressiveMediaExtractor}
     *     to extract the media from its container.
     */
    public Factory(
        DataSource.Factory dataSourceFactory,
        ProgressiveMediaExtractor.Factory progressiveMediaExtractorFactory) {
      this(
          dataSourceFactory,
          progressiveMediaExtractorFactory,
          new DefaultDrmSessionManagerProvider(),
          new DefaultLoadErrorHandlingPolicy(),
          DEFAULT_LOADING_CHECK_INTERVAL_BYTES);
    }

    /**
     * Creates a new factory for {@link ProgressiveMediaSource}s.
     *
     * @param dataSourceFactory A factory for {@linkplain DataSource data sources} to read the
     *     media.
     * @param progressiveMediaExtractorFactory A factory for the {@link ProgressiveMediaExtractor}
     *     to extract media from its container.
     * @param drmSessionManagerProvider A provider to obtain a {@link DrmSessionManager} for a
     *     {@link MediaItem}.
     * @param loadErrorHandlingPolicy A policy to handle load error.
     * @param continueLoadingCheckIntervalBytes The number of bytes that should be loaded between
     *     each invocation of {@link
     *     MediaPeriod.Callback#onContinueLoadingRequested(SequenceableLoader)}.
     */
    public Factory(
        DataSource.Factory dataSourceFactory,
        ProgressiveMediaExtractor.Factory progressiveMediaExtractorFactory,
        DrmSessionManagerProvider drmSessionManagerProvider,
        LoadErrorHandlingPolicy loadErrorHandlingPolicy,
        int continueLoadingCheckIntervalBytes) {
      this.dataSourceFactory = dataSourceFactory;
      this.progressiveMediaExtractorFactory = progressiveMediaExtractorFactory;
      this.drmSessionManagerProvider = drmSessionManagerProvider;
      this.loadErrorHandlingPolicy = loadErrorHandlingPolicy;
      this.continueLoadingCheckIntervalBytes = continueLoadingCheckIntervalBytes;
    }

    @CanIgnoreReturnValue
    @Override
    public Factory setLoadErrorHandlingPolicy(LoadErrorHandlingPolicy loadErrorHandlingPolicy) {
      this.loadErrorHandlingPolicy =
          checkNotNull(
              loadErrorHandlingPolicy,
              "MediaSource.Factory#setLoadErrorHandlingPolicy no longer handles null by"
                  + " instantiating a new DefaultLoadErrorHandlingPolicy. Explicitly construct and"
                  + " pass an instance in order to retain the old behavior.");
      return this;
    }

    /**
     * Sets the number of bytes that should be loaded between each invocation of {@link
     * MediaPeriod.Callback#onContinueLoadingRequested(SequenceableLoader)}. The default value is
     * {@link #DEFAULT_LOADING_CHECK_INTERVAL_BYTES}.
     *
     * @param continueLoadingCheckIntervalBytes The number of bytes that should be loaded between
     *     each invocation of {@link
     *     MediaPeriod.Callback#onContinueLoadingRequested(SequenceableLoader)}.
     * @return This factory, for convenience.
     */
    @CanIgnoreReturnValue
    public Factory setContinueLoadingCheckIntervalBytes(int continueLoadingCheckIntervalBytes) {
      this.continueLoadingCheckIntervalBytes = continueLoadingCheckIntervalBytes;
      return this;
    }

    @CanIgnoreReturnValue
    @Override
    public Factory setDrmSessionManagerProvider(
        DrmSessionManagerProvider drmSessionManagerProvider) {
      this.drmSessionManagerProvider =
          checkNotNull(
              drmSessionManagerProvider,
              "MediaSource.Factory#setDrmSessionManagerProvider no longer handles null by"
                  + " instantiating a new DefaultDrmSessionManagerProvider. Explicitly construct"
                  + " and pass an instance in order to retain the old behavior.");
      return this;
    }

    /**
     * Returns a new {@link ProgressiveMediaSource} using the current parameters.
     *
     * @param mediaItem The {@link MediaItem}.
     * @return The new {@link ProgressiveMediaSource}.
     * @throws NullPointerException if {@link MediaItem#localConfiguration} is {@code null}.
     */
    @Override
    public ProgressiveMediaSource createMediaSource(MediaItem mediaItem) {
      checkNotNull(mediaItem.localConfiguration);
      boolean needsTag = mediaItem.localConfiguration.tag == null && tag != null;
      boolean needsCustomCacheKey =
          mediaItem.localConfiguration.customCacheKey == null && customCacheKey != null;
      if (needsTag && needsCustomCacheKey) {
        mediaItem = mediaItem.buildUpon().setTag(tag).setCustomCacheKey(customCacheKey).build();
      } else if (needsTag) {
        mediaItem = mediaItem.buildUpon().setTag(tag).build();
      } else if (needsCustomCacheKey) {
        mediaItem = mediaItem.buildUpon().setCustomCacheKey(customCacheKey).build();
      }
      return new ProgressiveMediaSource(
          mediaItem,
          dataSourceFactory,
          progressiveMediaExtractorFactory,
          drmSessionManagerProvider.get(mediaItem),
          loadErrorHandlingPolicy,
          continueLoadingCheckIntervalBytes);
    }

    @Override
    public @C.ContentType int[] getSupportedTypes() {
      return new int[] {C.CONTENT_TYPE_OTHER};
    }
  }

  /**
   * The default number of bytes that should be loaded between each each invocation of {@link
   * MediaPeriod.Callback#onContinueLoadingRequested(SequenceableLoader)}.
   */
  public static final int DEFAULT_LOADING_CHECK_INTERVAL_BYTES = 1024 * 1024;

  private final MediaItem mediaItem;
  private final MediaItem.LocalConfiguration localConfiguration;
  private final DataSource.Factory dataSourceFactory;
  private final ProgressiveMediaExtractor.Factory progressiveMediaExtractorFactory;
  private final DrmSessionManager drmSessionManager;
  private final LoadErrorHandlingPolicy loadableLoadErrorHandlingPolicy;
  private final int continueLoadingCheckIntervalBytes;

  private boolean timelineIsPlaceholder;
  private long timelineDurationUs;
  private boolean timelineIsSeekable;
  private boolean timelineIsLive;
  @Nullable private TransferListener transferListener;

  private ProgressiveMediaSource(
      MediaItem mediaItem,
      DataSource.Factory dataSourceFactory,
      ProgressiveMediaExtractor.Factory progressiveMediaExtractorFactory,
      DrmSessionManager drmSessionManager,
      LoadErrorHandlingPolicy loadableLoadErrorHandlingPolicy,
      int continueLoadingCheckIntervalBytes) {
    this.localConfiguration = checkNotNull(mediaItem.localConfiguration);
    this.mediaItem = mediaItem;
    this.dataSourceFactory = dataSourceFactory;
    this.progressiveMediaExtractorFactory = progressiveMediaExtractorFactory;
    this.drmSessionManager = drmSessionManager;
    this.loadableLoadErrorHandlingPolicy = loadableLoadErrorHandlingPolicy;
    this.continueLoadingCheckIntervalBytes = continueLoadingCheckIntervalBytes;
    this.timelineIsPlaceholder = true;
    this.timelineDurationUs = C.TIME_UNSET;
  }

  @Override
  public MediaItem getMediaItem() {
    return mediaItem;
  }

  @Override
  protected void prepareSourceInternal(@Nullable TransferListener mediaTransferListener) {
    transferListener = mediaTransferListener;
    drmSessionManager.prepare();
    drmSessionManager.setPlayer(
        /* playbackLooper= */ checkNotNull(Looper.myLooper()), getPlayerId());
    notifySourceInfoRefreshed();
  }

  @Override
  public void maybeThrowSourceInfoRefreshError() {
    // Do nothing.
  }

  @Override
  public MediaPeriod createPeriod(MediaPeriodId id, Allocator allocator, long startPositionUs) {
    DataSource dataSource = dataSourceFactory.createDataSource();
    if (transferListener != null) {
      dataSource.addTransferListener(transferListener);
    }
    return new ProgressiveMediaPeriod(
        localConfiguration.uri,
        dataSource,
        progressiveMediaExtractorFactory.createProgressiveMediaExtractor(getPlayerId()),
        drmSessionManager,
        createDrmEventDispatcher(id),
        loadableLoadErrorHandlingPolicy,
        createEventDispatcher(id),
        this,
        allocator,
        localConfiguration.customCacheKey,
        continueLoadingCheckIntervalBytes);
  }

  @Override
  public void releasePeriod(MediaPeriod mediaPeriod) {
    ((ProgressiveMediaPeriod) mediaPeriod).release();
  }

  @Override
  protected void releaseSourceInternal() {
    drmSessionManager.release();
  }

  // ProgressiveMediaPeriod.Listener implementation.

  @Override
  public void onSourceInfoRefreshed(long durationUs, boolean isSeekable, boolean isLive) {
    // If we already have the duration from a previous source info refresh, use it.
    durationUs = durationUs == C.TIME_UNSET ? timelineDurationUs : durationUs;
    if (!timelineIsPlaceholder
        && timelineDurationUs == durationUs
        && timelineIsSeekable == isSeekable
        && timelineIsLive == isLive) {
      // Suppress no-op source info changes.
      return;
    }
    timelineDurationUs = durationUs;
    timelineIsSeekable = isSeekable;
    timelineIsLive = isLive;
    timelineIsPlaceholder = false;
    notifySourceInfoRefreshed();
  }

  // Internal methods.

  private void notifySourceInfoRefreshed() {
    // TODO: Split up isDynamic into multiple fields to indicate which values may change. Then
    // indicate that the duration may change until it's known. See [internal: b/69703223].
    Timeline timeline =
        new SinglePeriodTimeline(
            timelineDurationUs,
            timelineIsSeekable,
            /* isDynamic= */ false,
            /* useLiveConfiguration= */ timelineIsLive,
            /* manifest= */ null,
            mediaItem);
    if (timelineIsPlaceholder) {
      // TODO: Actually prepare the extractors during preparation so that we don't need a
      // placeholder. See https://github.com/google/ExoPlayer/issues/4727.
      timeline =
          new ForwardingTimeline(timeline) {
            @Override
            public Window getWindow(
                int windowIndex, Window window, long defaultPositionProjectionUs) {
              super.getWindow(windowIndex, window, defaultPositionProjectionUs);
              window.isPlaceholder = true;
              return window;
            }

            @Override
            public Period getPeriod(int periodIndex, Period period, boolean setIds) {
              super.getPeriod(periodIndex, period, setIds);
              period.isPlaceholder = true;
              return period;
            }
          };
    }
    refreshSourceInfo(timeline);
  }
}


text:
using System;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Securities;

namespace QuantConnect.Tests.Common.Securities
{
    [TestFixture]
    public class ImmediateSettlementModelTests
    {
        private static readonly DateTime Noon = new DateTime(2014, 6, 24, 12, 0, 0);
        private static readonly TimeKeeper TimeKeeper = new TimeKeeper(Noon.ConvertToUtc(TimeZones.NewYork), new[] { TimeZones.NewYork });

        [Test]
        public void FundsAreSettledImmediately()
        {
            var securities = new SecurityManager(TimeKeeper);
            var transactions = new SecurityTransactionManager(null, securities);
            var portfolio = new SecurityPortfolioManager(securities, transactions);
            var model = new ImmediateSettlementModel();
            var config = CreateTradeBarConfig();
            var security = new Security(
                SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(),
                config,
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
            );

            portfolio.SetCash(1000);
            Assert.AreEqual(1000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            var timeUtc = Noon.ConvertToUtc(TimeZones.NewYork);
            model.ApplyFunds(portfolio, security, timeUtc, Currencies.USD, 1000);

            Assert.AreEqual(2000, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            model.ApplyFunds(portfolio, security, timeUtc, Currencies.USD, -500);

            Assert.AreEqual(1500, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);

            model.ApplyFunds(portfolio, security, timeUtc, Currencies.USD, 1000);

            Assert.AreEqual(2500, portfolio.Cash);
            Assert.AreEqual(0, portfolio.UnsettledCash);
        }

        private SubscriptionDataConfig CreateTradeBarConfig()
        {
            return new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Provides a UPNP discovery method that mimics Hue hubs."""
import threading
import socket
import logging
import select

from aiohttp import web

from homeassistant import core
from homeassistant.components.http import HomeAssistantView

_LOGGER = logging.getLogger(__name__)

class DescriptionXmlView(HomeAssistantView):
    """Handles requests for the description.xml file."""

    url = '/description.xml'
    name = 'description:xml'
    requires_auth = False

    def __init__(self, config):
        """Initialize the instance of the view."""
        self.config = config

    @core.callback
    def get(self, request):
        """Handle a GET request."""
        xml_template = """<?xml version="1.0" encoding="UTF-8" ?>
<root xmlns="urn:schemas-upnp-org:device-1-0">
<specVersion>
<major>1</major>
<minor>0</minor>
</specVersion>
<URLBase>http://{0}:{1}/</URLBase>
<device>
<deviceType>urn:schemas-upnp-org:device:Basic:1</deviceType>
<friendlyName>HASS Bridge ({0})</friendlyName>
<manufacturer>Royal Philips Electronics</manufacturer>
<manufacturerURL>http://www.philips.com</manufacturerURL>
<modelDescription>Philips hue Personal Wireless Lighting</modelDescription>
<modelName>Philips hue bridge 2015</modelName>
<modelNumber>BSB002</modelNumber>
<modelURL>http://www.meethue.com</modelURL>
<serialNumber>1234</serialNumber>
<UDN>uuid:2f402f80-da50-11e1-9b23-001788255acc</UDN>
</device>
</root>
"""

        resp_text = xml_template.format(
            self.config.advertise_ip, self.config.advertise_port)

        return web.Response(text=resp_text, content_type='text/xml')

class UPNPResponderThread(threading.Thread):
    """Handle responding to UPNP/SSDP discovery requests."""

    _interrupted = False

    def __init__(self, host_ip_addr, listen_port, upnp_bind_multicast,
                 advertise_ip, advertise_port):
        """Initialize the class."""
        threading.Thread.__init__(self)

        self.host_ip_addr = host_ip_addr
        self.listen_port = listen_port
        self.upnp_bind_multicast = upnp_bind_multicast

        # Note that the double newline at the end of
        # this string is required per the SSDP spec
        resp_template = """HTTP/1.1 200 OK
CACHE-CONTROL: max-age=60
EXT:
LOCATION: http://{0}:{1}/description.xml
SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1
hue-bridgeid: 1234
ST: urn:schemas-upnp-org:device:basic:1
USN: uuid:Socket-1_0-221438K0100073::urn:schemas-upnp-org:device:basic:1

"""

        self.upnp_response = resp_template.format(
            advertise_ip, advertise_port).replace("\n", "\r\n") \
                                         .encode('utf-8')

    def run(self):
        """Run the server."""
        # Listen for UDP port 1900 packets sent to SSDP multicast address
        ssdp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ssdp_socket.setblocking(False)

        # Required for receiving multicast
        ssdp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        ssdp_socket.setsockopt(
            socket.SOL_IP,
            socket.IP_MULTICAST_IF,
            socket.inet_aton(self.host_ip_addr))

        ssdp_socket.setsockopt(
            socket.SOL_IP,
            socket.IP_ADD_MEMBERSHIP,
            socket.inet_aton("239.255.255.250") +
            socket.inet_aton(self.host_ip_addr))

        if self.upnp_bind_multicast:
            ssdp_socket.bind(("", 1900))
        else:
            ssdp_socket.bind((self.host_ip_addr, 1900))

        while True:
            if self._interrupted:
                clean_socket_close(ssdp_socket)
                return

            try:
                read, _, _ = select.select(
                    [ssdp_socket], [],
                    [ssdp_socket], 2)

                if ssdp_socket in read:
                    data, addr = ssdp_socket.recvfrom(1024)
                else:
                    # most likely the timeout, so check for interrupt
                    continue
            except socket.error as ex:
                if self._interrupted:
                    clean_socket_close(ssdp_socket)
                    return

                _LOGGER.error("UPNP Responder socket exception occurred: %s",
                              ex.__str__)
                # without the following continue, a second exception occurs
                # because the data object has not been initialized
                continue

            if "M-SEARCH" in data.decode('utf-8', errors='ignore'):
                # SSDP M-SEARCH method received, respond to it with our info
                resp_socket = socket.socket(
                    socket.AF_INET, socket.SOCK_DGRAM)

                resp_socket.sendto(self.upnp_response, addr)
                resp_socket.close()

    def stop(self):
        """Stop the server."""
        # Request for server
        self._interrupted = True
        self.join()

def clean_socket_close(sock):
    """Close a socket connection and logs its closure."""
    _LOGGER.info("UPNP responder shutting down.")

    sock.close()


text:
// flowlint ambiguous-object-type:error

'use strict';

const {parse} = require('graphql');
const {Parser, convertASTDocuments} = require('relay-compiler');

import type {Fragment, Root, Schema} from 'relay-compiler';

function parseGraphQLText(
  schema: Schema,
  text: string,
): {
  definitions: $ReadOnlyArray<Fragment | Root>,
  schema: Schema,
  ...
} {
  const ast = parse(text);
  const extendedSchema = schema.extend(ast);
  const definitions = convertASTDocuments(
    extendedSchema,
    [ast],
    Parser.transform.bind(Parser),
  );
  return {
    definitions,
    schema: extendedSchema,
  };
}

module.exports = parseGraphQLText;


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  include ImageUploadConcern
  include BadgeConcern

  @stream_issues = Issue.package_stream_issues

  protect_from_forgery with: :null_session
end


text:
package diff

import (
	"fmt"
	"reflect"
	"strings"
	"testing"
)

func TestDiff(t *testing.T) {
	tests := []struct {
		desc   string
		A, B   []string
		chunks []Chunk
	}{
		{
			desc: "constitution",
			A: []string{
				"We the People of the United States, in Order to form a more perfect Union,",
				"establish Justice, insure domestic Tranquility, provide for the common defence,",
				"and secure the Blessings of Liberty to ourselves",
				"and our Posterity, do ordain and establish this Constitution for the United",
				"States of America.",
			},
			B: []string{
				"We the People of the United States, in Order to form a more perfect Union,",
				"establish Justice, insure domestic Tranquility, provide for the common defence,",
				"promote the general Welfare, and secure the Blessings of Liberty to ourselves",
				"and our Posterity, do ordain and establish this Constitution for the United",
				"States of America.",
			},
			chunks: []Chunk{
				0: {
					Equal: []string{
						"We the People of the United States, in Order to form a more perfect Union,",
						"establish Justice, insure domestic Tranquility, provide for the common defence,",
					},
				},
				1: {
					Deleted: []string{
						"and secure the Blessings of Liberty to ourselves",
					},
				},
				2: {
					Added: []string{
						"promote the general Welfare, and secure the Blessings of Liberty to ourselves",
					},
					Equal: []string{
						"and our Posterity, do ordain and establish this Constitution for the United",
						"States of America.",
					},
				},
			},
		},
	}

	for _, test := range tests {
		got := DiffChunks(test.A, test.B)
		if got, want := len(got), len(test.chunks); got != want {
			t.Errorf("%s: edit distance = %v, want %v", test.desc, got-1, want-1)
			continue
		}
		for i := range got {
			got, want := got[i], test.chunks[i]
			if got, want := got.Added, want.Added; !reflect.DeepEqual(got, want) {
				t.Errorf("%s[%d]: Added = %v, want %v", test.desc, i, got, want)
			}
			if got, want := got.Deleted, want.Deleted; !reflect.DeepEqual(got, want) {
				t.Errorf("%s[%d]: Deleted = %v, want %v", test.desc, i, got, want)
			}
			if got, want := got.Equal, want.Equal; !reflect.DeepEqual(got, want) {
				t.Errorf("%s[%d]: Equal = %v, want %v", test.desc, i, got, want)
			}
		}
	}
}

func ExampleDiff() {
	constitution := strings.TrimSpace(`
We the People of the United States, in Order to form a more perfect Union,
establish Justice, insure domestic Tranquility, provide for the common defence,
promote the general Welfare, and secure the Blessings of Liberty to ourselves
and our Posterity, do ordain and establish this Constitution for the United
States of America.
`)

	got := strings.TrimSpace(`
:wq
We the People of the United States, in Order to form a more perfect Union,
establish Justice, insure domestic Tranquility, provide for the common defence,
and secure the Blessings of Liberty to ourselves
and our Posterity, do ordain and establish this Constitution for the United
States of America.
`)

	fmt.Println(Diff(got, constitution))

	// Output:
	// -:wq
	//  We the People of the United States, in Order to form a more perfect Union,
	//  establish Justice, insure domestic Tranquility, provide for the common defence,
	// -and secure the Blessings of Liberty to ourselves
	// +promote the general Welfare, and secure the Blessings of Liberty to ourselves
	//  and our Posterity, do ordain and establish this Constitution for the United
	//  States of America.
}

func TestDiffPath(t *testing.T) {
	cases := [][3]string{
		{"/home/user/path", "/home/user/notpath", "/home/user/{path -> notpath}"},
		{"/home/user/path", "/home/nobody/path", "/home/{user -> nobody}/path"},
		{"/home/user/path", "/home/nobody/notpath", "/home/{user/path -> nobody/notpath}"},
		{"/home", "/home/user/path", "/home -> /home/user/path"},
	}

	for _, c := range cases {
		r := Path(c[0], c[1])
		if r != c[2] {
			t.Fatalf("Expected diff of %s and %s to be %s was %s", c[0], c[1], c[2], r)
		}
	}
}


text:
<!DOCTYPE html>

	<title>
		BERKSHIRE HATHAWAY
	</title>

BERKSHIRE HATHAWAY INC. 3555 Farnam Street Omaha, NE 68131 Official Home Page

A Message from Warren E. Buffett

New Release Updated July 1, 2014

Annual & Interim Reports Updated May 2 2014

Warren Buffett's Letters to Berkshire Shareholders Updated March 1, 2015

Link to SEC Filings

Charlie Munger's Letters to Wesco Shareholders

Corporate Governance

Annual Meeting Information

Links to Berkshire Subsidiary Companies

Comparative Rights and Relative Prices of Class A and B Stock Updated January 20, 2010

Owner's Manual To view the Owner's Manual you may use Adobe Acrobat® Reader® software. Click here to download. Updated March 1, 2014

Order Berkshire Activewear On-line

Letters from Warren E. Buffett Regarding Pledges to Make Gifts of Berkshire StockUpdated August 30, 2012

  FOR A FREE CAR INSURANCE RATE QUOTE THAT COULD SAVE YOU SUBSTANTIAL MONEY

   If you have any comments about our WEB page, you can either write us at the address shown above or e-mail us at  berkshire@berkshirehathaway.com. However, due to the limited number of personnel in our corporate office, we are unable to provide a direct response.

  Legal Disclaimer

  Copyright © 1978-2016 Berkshire Hathaway Inc.


text:
package co.cask.cdap.examples.countrandom;

import co.cask.cdap.api.annotation.HashPartition;
import co.cask.cdap.api.annotation.ProcessInput;
import co.cask.cdap.api.annotation.UseDataSet;
import co.cask.cdap.api.dataset.lib.KeyValueTable;
import co.cask.cdap.api.flow.flowlet.AbstractFlowlet;

/**
 * Number Counter Flowlet {@code NumberCounter}.
 */
public class NumberCounter extends AbstractFlowlet {

  @UseDataSet(CountRandom.TABLE_NAME)
  KeyValueTable counters;

  @ProcessInput
  @HashPartition("n")
  public void process(Integer number) {
    counters.increment(number.toString().getBytes(), 1L);
  }
}


text:
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader(
  'Content-Type',
  'application/x-www-form-urlencoded; charset=UTF-8'
);
request.send(data);


text:
<html>
<body>
Contains all the readers of JT Files. This reader can read a JTheque file and return a JTFile. We can extract data from
this JTFile into the application.
</body>
</html>


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

#include "content/browser/private_aggregation/private_aggregation_host.h"

#include <iterator>
#include <utility>
#include <vector>

#include "base/callback.h"
#include "base/check.h"
#include "base/guid.h"
#include "base/rand_util.h"
#include "base/ranges/algorithm.h"
#include "base/time/time.h"
#include "base/values.h"
#include "content/browser/aggregation_service/aggregatable_report.h"
#include "content/browser/private_aggregation/private_aggregation_budget_key.h"
#include "content/common/aggregatable_report.mojom.h"
#include "content/common/private_aggregation_host.mojom.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_client.h"
#include "mojo/public/cpp/bindings/message.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "services/network/public/cpp/is_potentially_trustworthy.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/origin.h"

namespace content {

namespace {

// Helper to add a random delay to reports being sent. This delay is picked
// uniformly at random from the range [10 minutes, 1 hour).
// TODO(alexmt): Consider making this configurable for easier testing.
base::Time GetScheduledReportTime(base::Time report_issued_time) {
  return report_issued_time + base::Minutes(10) +
         base::RandDouble() * base::Minutes(50);
}

}  // namespace

struct PrivateAggregationHost::ReceiverContext {
  url::Origin worklet_origin;
  url::Origin top_frame_origin;
  PrivateAggregationBudgetKey::Api api_for_budgeting;
};

PrivateAggregationHost::PrivateAggregationHost(
    base::RepeatingCallback<void(AggregatableReportRequest,
                                 PrivateAggregationBudgetKey)>
        on_report_request_received,
    BrowserContext* browser_context)
    : on_report_request_received_(std::move(on_report_request_received)),
      browser_context_(*browser_context) {
  DCHECK(!on_report_request_received_.is_null());
}

PrivateAggregationHost::~PrivateAggregationHost() = default;

bool PrivateAggregationHost::BindNewReceiver(
    url::Origin worklet_origin,
    url::Origin top_frame_origin,
    PrivateAggregationBudgetKey::Api api_for_budgeting,
    mojo::PendingReceiver<mojom::PrivateAggregationHost> pending_receiver) {
  if (!network::IsOriginPotentiallyTrustworthy(worklet_origin)) {
    // Let the pending receiver be destroyed as it goes out of scope so none of
    // its requests are processed.
    return false;
  }
  receiver_set_.Add(
      this, std::move(pending_receiver),
      ReceiverContext{.worklet_origin = std::move(worklet_origin),
                      .top_frame_origin = std::move(top_frame_origin),
                      .api_for_budgeting = api_for_budgeting});
  return true;
}

void PrivateAggregationHost::SendHistogramReport(
    std::vector<mojom::AggregatableReportHistogramContributionPtr>
        contribution_ptrs,
    mojom::AggregationServiceMode aggregation_mode,
    mojom::DebugModeDetailsPtr debug_mode_details) {
  // TODO(alexmt): Consider updating or making a FeatureParam.
  static constexpr char kFledgeReportingPath[] =
      "/.well-known/private-aggregation/report-fledge";
  static constexpr char kSharedStorageReportingPath[] =
      "/.well-known/private-aggregation/report-shared-storage";

  const url::Origin& reporting_origin =
      receiver_set_.current_context().worklet_origin;
  DCHECK(network::IsOriginPotentiallyTrustworthy(reporting_origin));

  if (!GetContentClient()->browser()->IsPrivateAggregationAllowed(
          &*browser_context_, receiver_set_.current_context().top_frame_origin,
          reporting_origin)) {
    return;
  }

  // Null pointers should fail mojo validation.
  DCHECK(base::ranges::none_of(
      contribution_ptrs,
      [](const mojom::AggregatableReportHistogramContributionPtr&
             contribution_ptr) { return contribution_ptr.is_null(); }));
  DCHECK(!debug_mode_details.is_null());

  if (contribution_ptrs.size() > kMaxNumberOfContributions) {
    // TODO(crbug.com/1323324): Add histograms for monitoring failures here,
    // possibly broken out by failure reason.
    mojo::ReportBadMessage("Too many contributions");
    return;
  }

  std::vector<mojom::AggregatableReportHistogramContribution> contributions;
  contributions.reserve(contribution_ptrs.size());
  base::ranges::transform(
      contribution_ptrs, std::back_inserter(contributions),
      [](const mojom::AggregatableReportHistogramContributionPtr&
             contribution_ptr) { return std::move(*contribution_ptr); });

  AggregationServicePayloadContents payload_contents(
      AggregationServicePayloadContents::Operation::kHistogram,
      std::move(contributions), aggregation_mode);

  base::Time now = base::Time::Now();

  AggregatableReportSharedInfo shared_info(
      /*scheduled_report_time=*/GetScheduledReportTime(
          /*report_issued_time=*/now),
      /*report_id=*/base::GUID::GenerateRandomV4(), reporting_origin,
      debug_mode_details->is_enabled
          ? AggregatableReportSharedInfo::DebugMode::kEnabled
          : AggregatableReportSharedInfo::DebugMode::kDisabled,
      /*additional_fields=*/base::Value::Dict(),
      /*api_version=*/kApiReportVersion,
      /*api_identifier=*/kApiIdentifier);

  std::string reporting_path;
  switch (receiver_set_.current_context().api_for_budgeting) {
    case PrivateAggregationBudgetKey::Api::kFledge:
      reporting_path = kFledgeReportingPath;
      break;
    case PrivateAggregationBudgetKey::Api::kSharedStorage:
      reporting_path = kSharedStorageReportingPath;
      break;
  }

  absl::optional<uint64_t> debug_key;
  if (!debug_mode_details->debug_key.is_null()) {
    if (!debug_mode_details->is_enabled) {
      mojo::ReportBadMessage("Debug key present but debug mode is not enabled");
      return;
    }
    debug_key = debug_mode_details->debug_key->value;
  }

  absl::optional<AggregatableReportRequest> report_request =
      AggregatableReportRequest::Create(std::move(payload_contents),
                                        std::move(shared_info),
                                        std::move(reporting_path), debug_key);
  if (!report_request.has_value()) {
    // TODO(crbug.com/1323324): Add histograms for monitoring failures here,
    // possibly broken out by failure reason.
    mojo::ReportBadMessage("Invalid report request parameters");
    return;
  }

  absl::optional<PrivateAggregationBudgetKey> budget_key =
      PrivateAggregationBudgetKey::Create(
          /*origin=*/reporting_origin, /*api_invocation_time=*/now,
          /*api=*/receiver_set_.current_context().api_for_budgeting);

  // The origin should be potentially trustworthy.
  DCHECK(budget_key.has_value());

  on_report_request_received_.Run(std::move(report_request.value()),
                                  std::move(budget_key.value()));
}

}  // namespace content


text:
<?php

namespace {

from('Hoa')

/**
 * \Hoa\Praspel\Exception\Compiler
 */
-> import('Praspel.Exception.Compiler')

/**
 * \Hoa\Visitor\Visit
 */
-> import('Visitor.Visit');

}

namespace Hoa\Praspel\Visitor {

/**
 * Class \Hoa\Praspel\Visitor\Praspel.
 *
 * Compile the model to Praspel code.
 *
 * @author     Ivan Enderlin <ivan.enderlin@hoa-project.net>
 * @copyright  Copyright © 2007-2014 Ivan Enderlin.
 * @license    New BSD License
 */

class Praspel implements \Hoa\Visitor\Visit {

    /**
     * Visit an element.
     *
     * @access  public
     * @param   \Hoa\Visitor\Element  $element    Element to visit.
     * @param   mixed                 &$handle    Handle (reference).
     * @param   mixed                 $eldnah     Handle (not reference).
     * @return  mixed
     */
    public function visit ( \Hoa\Visitor\Element $element,
                            &$handle = null, $eldnah = null ) {

        $out = null;

        // Hoa\Praspel.

        if($element instanceof \Hoa\Praspel\Model\Specification) {

            $oout = array();

            foreach($element::getAllowedClauses() as $clause)
                if(true === $element->clauseExists($clause))
                    $oout[] = $element->getClause($clause)->accept(
                        $this,
                        $handle,
                        $eldnah
                    );

            $out = implode("\n", $oout);
        }
        elseif($element instanceof \Hoa\Praspel\Model\Is) {

            $out = '@is ' . $element->getPropertyName() . ';';
        }
        elseif($element instanceof \Hoa\Praspel\Model\Declaration) {

            $clause = $element->getName();
            $out    = '@' . $clause;
            $oout   = array();

            foreach($element->getLocalVariables() as $name => $var)
                $oout[] = ' ' . $var->accept($this, $handle, $eldnah);

            foreach($element->getPredicates() as $predicate)
                $oout[] = ' \pred(\'' . $predicate . '\')';

            $out .= implode(' and', $oout) . ';';
        }
        elseif($element instanceof \Hoa\Praspel\Model\Variable) {

            $name = $element->getName();

            if(true === $element->isLocal())
                $out = 'let ';

            $out .= $name;

            if(null === $alias = $element->getAlias())
                $out .= ': ' .
                        $element->getDomains()->accept($this, $handle, $eldnah);
            else
                $out .= ' domainof ' . $alias;

            $constraints = $element->getConstraints();

            if(isset($constraints['is']))
                $out .= ' and ' . $name . ' is ' .
                        implode(', ', $constraints['is']);

            if(isset($constraints['contains']))
                foreach($constraints['contains'] as $contains)
                    $out .= ' and ' . $name . ' contains ' .
                            $contains->accept($this, $handle, $eldnah);

            if(isset($constraints['key']))
                foreach($constraints['key'] as $pairs)
                    $out .= ' and ' . $name . '[' .
                            $pairs[0]->accept($this, $handle, $eldnah) .
                            ']: ' . $pairs[1]->accept($this, $handle, $eldnah);
        }
        elseif($element instanceof \Hoa\Praspel\Model\Throwable) {

            $oout = array();

            foreach($element as $identifier) {

                $exception = $element[$identifier];

                if(true === $exception->isDisjointed())
                    continue;

                $line = ' ' . $exception->getInstanceName() . ' ' .
                        $identifier;

                foreach((array) $exception->getDisjunction() as $_identifier) {

                    $_exception = $element[$_identifier];
                    $line      .= ' or ' . $_exception->getInstanceName() . ' ' .
                                  $_identifier;
                }

                if(null !== $with = $exception->getWith()) {

                    $line .= ' with ';
                    $liine = array();

                    foreach($with as $var)
                        $liine[] = $var->accept($this, $handle, $eldnah);

                    foreach($with->getPredicates() as $predicate)
                        $liine[] = '\pred(\'' . $predicate . '\')';

                    $line .= implode(' and ', $liine);
                }

                $oout[] = $line;
            }

            $out = '@throwable' . implode(' or', $oout) . ';';
        }
        elseif($element instanceof \Hoa\Praspel\Model\DefaultBehavior) {

            $out  = '@default {' . "\n";
            $oout = array();

            foreach($element::getAllowedClauses() as $clause)
                if(true === $element->clauseExists($clause))
                    $oout[] = '    ' . str_replace(
                        "\n",
                        "\n" . '    ',
                        $element->getClause($clause)->accept(
                            $this,
                            $handle,
                            $eldnah
                        )
                    );

            $out .= implode("\n", $oout) . "\n" . '}';
        }
        elseif($element instanceof \Hoa\Praspel\Model\Behavior) {

            $out  = '@behavior ' . $element->getIdentifier() . ' {' . "\n";
            $oout = array();

            foreach($element::getAllowedClauses() as $clause)
                if(true === $element->clauseExists($clause))
                    $oout[] = '    ' . str_replace(
                        "\n",
                        "\n" . '    ',
                        $element->getClause($clause)->accept(
                            $this,
                            $handle,
                            $eldnah
                        )
                    );

            $out .= implode("\n", $oout) . "\n" . '}';

        }
        elseif($element instanceof \Hoa\Praspel\Model\Description) {

            $oout = array();

            foreach($element as $example)
                $oout[] = '@description \'' .
                          preg_replace('#(?<!\\\)\'#', '\\\'', $example) .
                          '\';';

            $out = implode("\n", $oout);
        }
        elseif($element instanceof \Hoa\Praspel\Model\Collection)
            foreach($element as $el)
                $out .= $el->accept($this, $handle, $eldnah);

        // Hoa\Realdom.

        elseif($element instanceof \Hoa\Realdom\Disjunction) {

            $realdoms = $element->getUnflattenedRealdoms();

            if(!empty($realdoms)) {

                $oout = array();

                foreach($realdoms as $realdom)
                    $oout[] = $realdom->accept($this, $handle, $eldnah);

                $out .= implode(' or ', $oout);
            }
        }
        elseif($element instanceof \Hoa\Realdom) {

            if($element instanceof \Hoa\Realdom\IRealdom\Constant)
                $out .= $element->getConstantRepresentation();
            else {

                $oout = array();

                foreach($element->getArguments() as $argument)
                    $oout[] = $argument->accept($this, $handle, $eldnah);

                $out .= $element->getName() . '(' . implode(', ', $oout) . ')';
            }
        }
        elseif($element instanceof \Hoa\Realdom\Crate\Constant) {

            $praspel  = $element->getPraspelRepresentation();
            $out     .= $praspel();
        }
        elseif($element instanceof \Hoa\Realdom\Crate\Variable) {

            $out .= $element->getVariable()->getName();
        }

        else
            throw new \Hoa\Praspel\Exception\Compiler(
                '%s is not yet implemented.', 0, get_class($element));

        return $out;
    }
}

}


text:
using System.IO;
using System.Windows.Forms;

// Reading DOOM WAD files
// https://www.cyotek.com/blog/reading-doom-wad-files

// Writing DOOM WAD files
// https://www.cyotek.com/blog/writing-doom-wad-files

// Copyright © 2020 Cyotek Ltd. All Rights Reserved.

// This work is licensed under the MIT License.
// See LICENSE.TXT for the full text

// Found this example useful?
// https://www.paypal.me/cyotek

namespace Cyotek.Demo
{
  internal static class FileDialogHelper
  {
    #region Public Methods

    public static string GetFolderName(string description)
    {
      return FileDialogHelper.GetFolderName(description, string.Empty);
    }

    public static string GetFolderName(string description, string selectedPath)
    {
      using (FolderBrowserDialog dialog = new FolderBrowserDialog
      {
        Description = description,
        ShowNewFolderButton = true,
        SelectedPath = selectedPath
      })
      {
        return dialog.ShowDialog() == DialogResult.OK
          ? dialog.SelectedPath
          : null;
      }
    }

    public static string GetNextFileName(string path, string baseName)
    {
      string fileName;
      string name;
      string ext;
      int index;

      name = Path.GetFileNameWithoutExtension(baseName);
      ext = Path.GetExtension(baseName);
      index = 0;

      do
      {
        index++;
        fileName = Path.Combine(path, string.Format("{0}-{2}{1}", name, ext, index));
      } while (File.Exists(fileName));

      return fileName;
    }

    public static string GetOpenFileName(string title, string filter, string defaultExtension)
    {
      return FileDialogHelper.GetFileName<OpenFileDialog>(title, filter, defaultExtension, string.Empty);
    }

    public static string GetOpenFileName(string title, string filter, string defaultExtension, string defaultFileName)
    {
      return FileDialogHelper.GetFileName<OpenFileDialog>(title, filter, defaultExtension, defaultFileName);
    }

    public static string GetSaveFileName(string title, string filter, string defaultExtension)
    {
      return FileDialogHelper.GetFileName<SaveFileDialog>(title, filter, defaultExtension, string.Empty);
    }

    public static string GetSaveFileName(string title, string filter, string defaultExtension, string defaultFileName)
    {
      return FileDialogHelper.GetFileName<SaveFileDialog>(title, filter, defaultExtension, defaultFileName);
    }

    #endregion Public Methods

    #region Private Methods

    private static string GetFileName<T>(string title, string filter, string defaultExtension, string defaultFileName)
      where T : FileDialog, new()
    {
      using (T dialog = new T
      {
        Title = title,
        DefaultExt = defaultExtension,
        Filter = filter,
        FileName = defaultFileName
      })
      {
        return dialog.ShowDialog() == DialogResult.OK
          ? dialog.FileName
          : null;
      }
    }

    #endregion Private Methods
  }
}


text:
package metrics

import (
	"context"

	"go.chromium.org/luci/common/tsmon/distribution"
	"go.chromium.org/luci/common/tsmon/field"
	"go.chromium.org/luci/common/tsmon/metric"
	"go.chromium.org/luci/common/tsmon/types"
)

var (
	creationTime = metric.NewCumulativeDistribution(
		"gce/instances/times/creation",
		"Time between GCE Provider configuring an instance and GCE reporting it as created.",
		&types.MetricMetadata{Units: types.Seconds},
		distribution.GeometricBucketer(1.1, 100),
		field.String("prefix"),
		field.String("project"),
		field.String("zone"),
	)

	connectionTime = metric.NewCumulativeDistribution(
		"gce/instances/times/connection",
		"Time between GCE reporting an instance as created and Swarming reporting it as connected.",
		&types.MetricMetadata{Units: types.Seconds},
		distribution.GeometricBucketer(1.1, 100),
		field.String("prefix"),
		field.String("project"),
		field.String("server"),
		field.String("zone"),
	)
)

// ReportCreationTime sets GCE instance creation time metric.
func ReportCreationTime(c context.Context, secs float64, prefix, project, zone string) {
	creationTime.Add(c, secs, prefix, project, zone)
}

// ReportConnectionTime sets GCE instance creation time metric.
func ReportConnectionTime(c context.Context, secs float64, prefix, project, server, zone string) {
	connectionTime.Add(c, secs, prefix, project, server, zone)
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using bv.winclient.Layout;
using eidss.model.Schema;

namespace eidss.winclient.Lab
{
    public partial class LabTestAmendmentHistoryPanel : eidss.winclient.Schema.BaseGroupPanel_LabTestAmendment
    {
        public LabTestAmendmentHistoryPanel()
        {
            InitializeComponent();
            EditByDoubleClick = false;
            TopPanelVisible = false;
            //таблица не редактируется
            Grid.GridView.OptionsBehavior.Editable = false;
            Grid.GridView.OptionsBehavior.ReadOnly = true;
            Grid.GridView.OptionsView.ShowGroupPanel = false;

        }
        private void BindOldResult()
        {
            LabTestAmendment history = null;
            if (DataSource != null && DataSource.Count > 0)
                history = DataSource[0] as LabTestAmendment;
            if (history != null)
                Core.LookupBinder.BindTextEdit(txtOldResult, history, "strOldTestResult");
            else
                txtOldResult.DataBindings.Clear();

        }
        public override ILayout GetLayout()
        {
            return ParentLayout ??
                   (ParentLayout = this.CreateLayoutSimple(BusinessObject, Caption, FormID, Icon));
        }
        public override void LoadData(ref object id, int? hAcode = null)
        {
            base.LoadData(ref id,hAcode);
            BindOldResult();
        }
    }

}


text:
module WelcomeHelper

  def favorite_theme
    return nil unless user_signed_in?
    return nil unless current_user.preference.present?
    return current_user.preference.theme
  end
end


text:
package com.db4o.ext;

/**
 * db4o-specific exception.

 * This exception is thrown when the object container required for
 * the current operation was closed or failed to open.
 * @see com.db4o.Db4o#openFile
 * @see com.db4o.ObjectContainer#close
 */
public class DatabaseClosedException extends Db4oFatalException {

}


text:
#ifndef GRPC_TRANSCODING_PREFIX_WRITER_H_
#define GRPC_TRANSCODING_PREFIX_WRITER_H_

#include <string>
#include <vector>

#include "google/protobuf/stubs/stringpiece.h"
#include "google/protobuf/util/internal/object_writer.h"

namespace google {
namespace api_manager {

namespace transcoding {

// PrefixWriter is helper ObjectWriter implementation that for each incoming
// object
//  1) writes the given prefix path by starting objects to the output
//     ObjectWriter,
//  2) forwards the writer events for a single object,
//  3) unwinds the prefix, by closing objects in the reverse order.
//
// E.g.
//
//  PrefixWriter pw("A.B.C", out);
//  pw.StartObject("Root");
//  ...
//  pw.RenderString("x", "value");
//  ...
//  pw.EndObject("Root");
//
// is equivalent to
//
//  out.StartObject("Root");
//  out.StartObject("A");
//  out.StartObject("B");
//  out.StartObject("C");
//  ...
//  pw.RenderString("x", "value");
//  ...
//  out.EndObject("C");
//  out.EndObject("B");
//  out.EndObject("A");
//  out.EndObject("Root");
//
class PrefixWriter : public google::protobuf::util::converter::ObjectWriter {
 public:
  // prefix is a '.' delimited prefix path to be added
  PrefixWriter(const std::string& prefix,
               google::protobuf::util::converter::ObjectWriter* ow);

  // ObjectWriter methods.
  PrefixWriter* StartObject(google::protobuf::StringPiece name);
  PrefixWriter* EndObject();
  PrefixWriter* StartList(google::protobuf::StringPiece name);
  PrefixWriter* EndList();
  PrefixWriter* RenderBool(google::protobuf::StringPiece name, bool value);
  PrefixWriter* RenderInt32(google::protobuf::StringPiece name,
                            google::protobuf::int32 value);
  PrefixWriter* RenderUint32(google::protobuf::StringPiece name,
                             google::protobuf::uint32 value);
  PrefixWriter* RenderInt64(google::protobuf::StringPiece name,
                            google::protobuf::int64 value);
  PrefixWriter* RenderUint64(google::protobuf::StringPiece name,
                             google::protobuf::uint64 value);
  PrefixWriter* RenderDouble(google::protobuf::StringPiece name, double value);
  PrefixWriter* RenderFloat(google::protobuf::StringPiece name, float value);
  PrefixWriter* RenderString(google::protobuf::StringPiece name,
                             google::protobuf::StringPiece value);
  PrefixWriter* RenderBytes(google::protobuf::StringPiece name,
                            google::protobuf::StringPiece value);
  PrefixWriter* RenderNull(google::protobuf::StringPiece name);

 private:
  // Helper method to start the prefix and return the name to use for the value.
  google::protobuf::StringPiece StartPrefix(google::protobuf::StringPiece name);

  // Helper method to end the prefix.
  void EndPrefix();

  // The path prefix if the HTTP body maps to a nested message in the proto.
  std::vector<std::string> prefix_;

  // Tracks the depth within the output, so we know when to write the prefix
  // and when to close it off.
  int non_actionable_depth_;

  // The output object writer to forward the writer events.
  google::protobuf::util::converter::ObjectWriter* writer_;

  PrefixWriter(const PrefixWriter&) = delete;
  PrefixWriter& operator=(const PrefixWriter&) = delete;
};

}  // namespace transcoding

}  // namespace api_manager
}  // namespace google

#endif  // API_MANAGER_TRANSCODING_PREFIX_WRITER_H_


text:
using System.Web.Http;
using App.Infrastructure;
using App.Infrastructure.Web;
using MileageStats.Domain.Handlers;

namespace App.Server.Vehicle.FillUps
{
    public class GetFillUpsController : ApiController
    {
        readonly GetFillupsForVehicle getFillupsForVehicle;

        public GetFillUpsController(GetFillupsForVehicle getFillupsForVehicle)
        {
            this.getFillupsForVehicle = getFillupsForVehicle;
        }

        public object GetFillUps(int vehicleId)
        {
            var fillUps = getFillupsForVehicle.Execute(vehicleId);
            return new Page("Vehicles/FillUps/init")
            {
                Title = "Fill ups",
                MasterPage = Url.Resource<GetVehicleMasterPageController>(),
                Data = new
                {
                    fillUps,
                    add = Url.Post<GetFillUpsController>()
                }
            };
        }
    }
}


text:
package org.eclipse.php.internal.core.search;

import org.eclipse.dltk.core.IMethod;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.IType;
import org.eclipse.dltk.core.ModelException;
import org.eclipse.dltk.internal.core.AbstractSourceModule;
import org.eclipse.php.internal.core.CoreMessages;
import org.eclipse.php.internal.core.ast.nodes.*;

public class IncludeOccurrencesFinder extends AbstractOccurrencesFinder {

	private static final String INCLUDE_POINT_OF = CoreMessages
			.getString("IncludeOccurrencesFinder.0"); //$NON-NLS-1$
	public static final String ID = "RequireFinder"; //$NON-NLS-1$
	private IModelElement source;
	private IBinding binding;
	private Include includeNode;
	private IType[] types;
	private IMethod[] methods;

	/**
	 * @param root
	 *            the AST root
	 * @param node
	 *            the selected node
	 * @return returns a message if there is a problem
	 */
	public String initialize(Program root, ASTNode node) {
		fASTRoot = root;

		this.includeNode = getIncludeExpression(node);
		if (this.includeNode != null) {
			binding = includeNode.resolveBinding();
			if (binding == null) {
				return null;
			}
			source = binding.getPHPElement();
			if (source != null) {
				AbstractSourceModule module = (AbstractSourceModule) source;
				try {
					this.types = module.getTypes();
					this.methods = module.getMethods();
					return null;
				} catch (ModelException e) {
					fDescription = "MethodExitsFinder_occurrence_exit_description"; //$NON-NLS-1$
					return fDescription;
				}
			}

		}
		fDescription = "MethodExitsFinder_occurrence_exit_description"; //$NON-NLS-1$
		return fDescription;
	}

	private final Include getIncludeExpression(ASTNode node) {
		boolean isInclude = (node != null && node.getType() == ASTNode.INCLUDE);
		if (isInclude) {
			return (Include) node;
		}
		ASTNode parent = ASTNodes.getParent(node, Include.class);
		return (parent != null && parent.getType() == ASTNode.INCLUDE) ? (Include) parent
				: null;
	}

	protected void findOccurrences() {
		if (source == null) {
			return;
		}
		fDescription = Messages.format(INCLUDE_POINT_OF, this.source
				.getElementName());
		getASTRoot().accept(this);
		int offset = includeNode.getStart();
		int length = includeNode.getLength();
		fResult.add(new OccurrenceLocation(offset, length,
				getOccurrenceType(null), fDescription));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @seeorg.eclipse.php.internal.ui.search.AbstractOccurrencesFinder#
	 * getOccurrenceReadWriteType
	 * (org.eclipse.php.internal.core.ast.nodes.ASTNode)
	 */
	protected int getOccurrenceType(ASTNode node) {
		return IOccurrencesFinder.K_OCCURRENCE;
	}

	public String getElementName() {
		return binding.getName();
	}

	public String getID() {
		return ID;
	}

	public String getJobLabel() {
		return "RncludeFinder_job_label"; //$NON-NLS-1$
	}

	public int getSearchKind() {
		return IOccurrencesFinder.K_EXIT_POINT_OCCURRENCE;
	}

	public String getUnformattedPluralLabel() {
		return "IncludeFinder_label_plural"; //$NON-NLS-1$
	}

	public String getUnformattedSingularLabel() {
		return "IncludeFinder_label_singular"; //$NON-NLS-1$
	}

	@Override
	public boolean visit(ClassName className) {
		Expression className2 = className.getName();
		if (className2.getType() == ASTNode.IDENTIFIER) {
			Identifier id = (Identifier) className2;
			String name = id.getName();
			for (IType type : types) {
				if (type.getElementName().equals(name))
					fResult.add(new OccurrenceLocation(className.getStart(),
							className.getLength(), getOccurrenceType(null),
							fDescription));
			}
		}
		return false;
	}

	@Override
	public boolean visit(Identifier className) {
		final StructuralPropertyDescriptor location = className
				.getLocationInParent();
		if (location == ClassDeclaration.SUPER_CLASS_PROPERTY
				|| location == ClassDeclaration.INTERFACES_PROPERTY
				|| location == StaticMethodInvocation.CLASS_NAME_PROPERTY
				|| location == FormalParameter.PARAMETER_TYPE_PROPERTY) {
			String name = className.getName();
			for (IType type : types) {
				if (type.getElementName().equals(name))
					fResult.add(new OccurrenceLocation(className.getStart(),
							className.getLength(), getOccurrenceType(null),
							fDescription));
			}
		}
		return false;
	}

	@Override
	public boolean visit(FunctionInvocation functionInvocation) {
		Expression functionName2 = functionInvocation.getFunctionName()
				.getName();
		if (functionName2.getType() == ASTNode.IDENTIFIER) {
			Identifier id = (Identifier) functionName2;
			String name = id.getName();
			for (IMethod method : methods) {
				if (method.getElementName().equals(name))
					fResult.add(new OccurrenceLocation(functionInvocation
							.getStart(), functionInvocation.getLength(),
							getOccurrenceType(null), fDescription));
			}
		}
		return true;
	}
}


text:
<config>
  <maxchars>10000</maxchars>
  <maxrows>500</maxrows>
  <timeout>5</timeout>
  <memory>100</memory>
  <permission>admin</permission>
</config>


text:
/**
 * @file Board config file
 */

#include <device.h>
#include <init.h>

#include <nanokernel.h>

#include "soc.h"

#ifdef CONFIG_UART_STELLARIS
#include <uart.h>

#define RCGC1 (*((volatile uint32_t *)0x400FE104))

#define RCGC1_UART0_EN 0x00000001
#define RCGC1_UART1_EN 0x00000002
#define RCGC1_UART2_EN 0x00000004

static int uart_stellaris_init(struct device *dev)
{
#ifdef CONFIG_UART_STELLARIS_PORT_0
	RCGC1 |= RCGC1_UART0_EN;
#endif

#ifdef CONFIG_UART_STELLARIS_PORT_1
	RCGC1 |= RCGC1_UART1_EN;
#endif

#ifdef CONFIG_UART_STELLARIS_PORT_2
	RCGC1 |= RCGC1_UART2_EN;
#endif

	return 0;
}

SYS_INIT(uart_stellaris_init, PRIMARY, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);

#endif /* CONFIG_UART_STELLARIS */


text:
package com.hilton.vulcan;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class TabsFragment extends Fragment {
    protected static final String TAG = TabsFragment.class.getName();
    private static final String PREFS = "default_prefs";
    private static final String CURRENT_TAB = "current_tab";
    private Tab[] mTabs = new Tab[] {
            new Tab("Tab 1", "Home", R.drawable.home, R.id.tab1),
            new Tab("Tab 2", "Bookmarks", R.drawable.favorite_bookmark, R.id.tab2),
            new Tab("Tab 3", "Favorites", R.drawable.star, R.id.tab3),
            new Tab("Tab 4", "Users", R.drawable.user, R.id.tab4),
            new Tab("Tab 5", "Bastkets", R.drawable.shopping_basket, R.id.tab5)
    };

    private TabHost mTabHost;
    private LayoutInflater mFactory;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mFactory = LayoutInflater.from(activity);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        saveCurrentTab();
    }

    private void saveCurrentTab() {
        SharedPreferences sp = getActivity().getSharedPreferences(PREFS,
                Context.MODE_PRIVATE);
        Editor ed = sp.edit();
        ed.putInt(CURRENT_TAB, mTabHost.getCurrentTab());
        ed.commit();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.tabs, container, false);
        mTabHost = (TabHost) root.findViewById(android.R.id.tabhost);
        setupTabs(mTabHost);
        restoreCurrentTab();
        return root;
    }

    private void restoreCurrentTab() {
        SharedPreferences sp = getActivity().getSharedPreferences(PREFS,
                Context.MODE_PRIVATE);
        final int current = sp.getInt(CURRENT_TAB, 0);
        mTabHost.setCurrentTab(current);
    }

    private void setupTabs(final TabHost tabHost) {
        tabHost.setup();
        for (final Tab tab : mTabs) {
            TabSpec spec = createTab(tabHost, tab);
            tabHost.addTab(spec);
            attachFragment(tab);
        }
        tabHost.setOnTabChangedListener(new OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                Log.e(TAG, "which is showing ? tab id " + tabId);
            }
        });
    }

    private void attachFragment(final Tab tab) {
        Fragment frag = new FragmentTab();
        Bundle args = new Bundle();
        args.putString(FragmentTab.EXTRA_TITLE, tab.mTitle);
        frag.setArguments(args);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(tab.mStub, frag, tab.mTag);
        ft.commit();
    }

    private TabSpec createTab(final TabHost tabHost, final Tab tab) {
        TabSpec spec = tabHost.newTabSpec(tab.mTag);
        View indicator = mFactory.inflate(R.layout.tab_indicator, null,
                false);
        ImageView icon = (ImageView) indicator.findViewById(R.id.tab_icon);
        icon.setImageResource(tab.mIcon);
        TextView title = (TextView) indicator.findViewById(R.id.tab_title);
        title.setText(tab.mTitle);
        spec.setIndicator(indicator);
        spec.setContent(tab.mStub);
        return spec;
    }

    private class Tab {
        public String mTag;
        public String mTitle;
        public int mIcon;
        public int mStub;

        public Tab(final String tag, String title, int icon, int stub) {
            mTag = tag;
            mTitle = title;
            mIcon = icon;
            mStub = stub;
        }

        @Override
        public String toString() {
            return "[tag " + mTag + "]";
        }
    }
}


text:
require 'rspec'
require_relative '../lib/imperium'
require_relative 'spec_helper'

describe Engine::Area do

  it 'should not accept invalid coordinates/size' do
    top_point = Engine::Point.new(5,7)
    area = Engine::Area.new(top_point, 10, 15)
    expect(area.top_point).to be == top_point
    expect(area.width).to be == 10
    expect(area.height).to be == 15

    another_point = Engine::Point.new(15, 25)
    area.top_point = another_point
    expect(area.top_point).to be == another_point

    area.width = 27
    expect(area.width).to be == 27

    area.height = 36
    expect(area.height).to be == 36

    expect { area.top_point = nil }.to raise_error ArgumentError
    expect { area.width = -10 }.to raise_error ArgumentError
    expect { area.width = nil }.to raise_error ArgumentError
    expect { area.height = -10 }.to raise_error ArgumentError
    expect { area.height = nil }.to raise_error ArgumentError

    expect { Engine::Area.new(top_point, -10, 15) }.to raise_error ArgumentError
    expect { Engine::Area.new(top_point, 10, -15) }.to raise_error ArgumentError
    expect { Engine::Area.new(top_point, nil, 15) }.to raise_error ArgumentError
    expect { Engine::Area.new(top_point, 10, nil) }.to raise_error ArgumentError
    expect { Engine::Area.new(nil, 10, 15) }.to raise_error ArgumentError
    expect { Engine::Area.new(Array.new, 10, 15) }.to raise_error ArgumentError
  end

  it 'correctly shows included points' do
    top_point = Engine::Point.new(2,2)
    area = Engine::Area.new(top_point, 10, 15)

    included_point1 = Engine::Point.new(2,2)
    included_point2 = Engine::Point.new(2,17)
    included_point3 = Engine::Point.new(12,2)
    included_point4 = Engine::Point.new(12,17)
    included_point5 = Engine::Point.new(5,5)
    included_point6 = Engine::Point.new(3,2)
    included_point7 = Engine::Point.new(10,10)
    excluded_point1 = Engine::Point.new(1,1)
    excluded_point2 = Engine::Point.new(1,10)
    excluded_point3 = Engine::Point.new(10,1)
    excluded_point4 = Engine::Point.new(13,5)
    excluded_point5 = Engine::Point.new(5,18)

    expect { area.includes?(nil) }.to raise_error ArgumentError
    expect { area.includes?(Array.new) }.to raise_error ArgumentError

    expect(area.includes?(included_point1)).to be true
    expect(area.includes?(included_point2)).to be true
    expect(area.includes?(included_point3)).to be true
    expect(area.includes?(included_point4)).to be true
    expect(area.includes?(included_point5)).to be true
    expect(area.includes?(included_point6)).to be true
    expect(area.includes?(included_point7)).to be true
    expect(area.includes?(excluded_point1)).to be false
    expect(area.includes?(excluded_point2)).to be false
    expect(area.includes?(excluded_point3)).to be false
    expect(area.includes?(excluded_point4)).to be false
    expect(area.includes?(excluded_point5)).to be false
  end
end


text:
module.exports = {
  description: 'Generates a view unit test.',
  locals: function() {
    var blueprint = this.lookupBlueprint('view-test');
    return blueprint.locals.apply(blueprint, arguments);
  }
};


text:
/* eslint-disable radix, no-plusplus */
import JsSHA from 'jssha/src/sha3'
import BaseN from '../lib/BaseN'
import { generateAlphabet } from '../lib/BaseNHelpers'

function getHMAC(hashedKey, info) {
  const sha3Hmac = new JsSHA('SHA3-512', 'TEXT')
  sha3Hmac.setHMACKey(hashedKey, 'TEXT')

  sha3Hmac.update(`${info.domain$}-${info.username$}_${info.salt$}`)

  return sha3Hmac.getHMAC('HEX')
}

function hash(info) {
  const sha3 = new JsSHA('SHA3-512', 'TEXT', { numRounds: info.itCount$ })
  sha3.update(info.password$)
  return sha3.getHash('HEX')
}

function mapKeyToCharset(pwd, len, charset) {
  const key = new BaseN(generateAlphabet(charset)).encodeString(pwd)

  if (key.length < len) {
    window.alert('出问题了,请联系作者:)')
  }

  return key.slice(0, len)
}

export function generate(info) {
  const hashedKey = hash(info)
  const hmac = getHMAC(hashedKey, info)
  return mapKeyToCharset(hmac, info.passOutLen$, info.charset$)
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quick Reference</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Spirit 2.59">
<link rel="up" href="../lex.html" title="Lex - Writing Lexical Analyzers">
<link rel="prev" href="abstracts/lexer_static_model.html" title="The Static Lexer Model">
<link rel="next" href="quick_reference/common_notation.html" title="Common Notation">

Home
Libraries
People
FAQ
More

Quick Reference

Common
        Notation

Primitive Lexer
        Components

Semantic
        Actions

Phoenix

Supported Regular
        Expressions

        This quick reference section is provided for convenience. You can use this
        section as a sort of a "cheat-sheet" on the most commonly used
        Lex components. It is not intended to be complete, but should give you an
        easy way to recall a particular component without having to dig through pages
        and pages of reference documentation.

Copyright © 2001-2011 Joel de Guzman, Hartmut Kaiser

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package libvirt

/*
#cgo pkg-config: libvirt
#include <libvirt/libvirt.h>
#include <libvirt/virterror.h>
#include <stdlib.h>
#include <string.h>
*/
import "C"

import (
	"fmt"
	"unsafe"
)

type typedParamsFieldInfo struct {
	set *bool
	i   *int
	ui  *uint
	l   *int64
	ul  *uint64
	b   *bool
	d   *float64
	s   *string
	sl  *[]string
}

func typedParamsUnpackLen(cparams *C.virTypedParameter, nparams int, infomap map[string]typedParamsFieldInfo) (uint, error) {
	count := uint(0)
	for i := 0; i < nparams; i++ {
		var cparam *C.virTypedParameter
		cparam = (*C.virTypedParameter)(unsafe.Pointer(uintptr(unsafe.Pointer(cparams)) + unsafe.Sizeof(*cparam)*uintptr(i)))
		name := C.GoString((*C.char)(unsafe.Pointer(&cparam.field)))
		info, ok := infomap[name]
		if !ok {
			// Ignore unknown keys so that we don't break if
			// run against a newer libvirt that returns more
			// parameters than we currently have code to
			// consume
			continue
		}
		switch cparam._type {
		case C.VIR_TYPED_PARAM_INT:
			if info.i == nil {
				return 0, fmt.Errorf("field %s expects an int", name)
			}
			*info.i = int(*(*C.int)(unsafe.Pointer(&cparam.value)))
			*info.set = true
		case C.VIR_TYPED_PARAM_UINT:
			if info.ui == nil {
				return 0, fmt.Errorf("field %s expects a uint", name)
			}
			*info.ui = uint(*(*C.uint)(unsafe.Pointer(&cparam.value)))
			*info.set = true
		case C.VIR_TYPED_PARAM_LLONG:
			if info.l == nil {
				return 0, fmt.Errorf("field %s expects an int64", name)
			}
			*info.l = int64(*(*C.longlong)(unsafe.Pointer(&cparam.value)))
			*info.set = true
		case C.VIR_TYPED_PARAM_ULLONG:
			if info.ul == nil {
				return 0, fmt.Errorf("field %s expects a uint64", name)
			}
			*info.ul = uint64(*(*C.ulonglong)(unsafe.Pointer(&cparam.value)))
			*info.set = true
		case C.VIR_TYPED_PARAM_DOUBLE:
			if info.d == nil {
				return 0, fmt.Errorf("field %s expects a float64", name)
			}
			*info.d = float64(*(*C.double)(unsafe.Pointer(&cparam.value)))
			*info.set = true
		case C.VIR_TYPED_PARAM_BOOLEAN:
			if info.b == nil {
				return 0, fmt.Errorf("field %s expects a bool", name)
			}
			*info.b = *(*C.char)(unsafe.Pointer(&cparam.value)) == 1
			*info.set = true
		case C.VIR_TYPED_PARAM_STRING:
			if info.s != nil {
				*info.s = C.GoString(*(**C.char)(unsafe.Pointer(&cparam.value)))
				*info.set = true
			} else if info.sl != nil {
				*info.sl = append(*info.sl, C.GoString(*(**C.char)(unsafe.Pointer(&cparam.value))))
				*info.set = true
			} else {
				return 0, fmt.Errorf("field %s expects a string/string list", name)
			}
		}
		count++
	}

	return count, nil
}

func typedParamsUnpack(cparams []C.virTypedParameter, infomap map[string]typedParamsFieldInfo) (uint, error) {
	return typedParamsUnpackLen(&cparams[0], len(cparams), infomap)
}

func typedParamsPackLen(cparams *C.virTypedParameter, nparams int, infomap map[string]typedParamsFieldInfo) error {
	stringOffsets := make(map[string]uint)

	for i := 0; i < nparams; i++ {
		var cparam *C.virTypedParameter
		cparam = (*C.virTypedParameter)(unsafe.Pointer(uintptr(unsafe.Pointer(cparams)) + unsafe.Sizeof(*cparam)*uintptr(i)))
		name := C.GoString((*C.char)(unsafe.Pointer(&cparam.field)))
		info, ok := infomap[name]
		if !ok {
			// Ignore unknown keys so that we don't break if
			// run against a newer libvirt that returns more
			// parameters than we currently have code to
			// consume
			continue
		}
		if !*info.set {
			continue
		}
		switch cparam._type {
		case C.VIR_TYPED_PARAM_INT:
			if info.i == nil {
				return fmt.Errorf("field %s expects an int", name)
			}
			*(*C.int)(unsafe.Pointer(&cparam.value)) = C.int(*info.i)
		case C.VIR_TYPED_PARAM_UINT:
			if info.ui == nil {
				return fmt.Errorf("field %s expects a uint", name)
			}
			*(*C.uint)(unsafe.Pointer(&cparam.value)) = C.uint(*info.ui)
		case C.VIR_TYPED_PARAM_LLONG:
			if info.l == nil {
				return fmt.Errorf("field %s expects an int64", name)
			}
			*(*C.longlong)(unsafe.Pointer(&cparam.value)) = C.longlong(*info.l)
		case C.VIR_TYPED_PARAM_ULLONG:
			if info.ul == nil {
				return fmt.Errorf("field %s expects a uint64", name)
			}
			*(*C.ulonglong)(unsafe.Pointer(&cparam.value)) = C.ulonglong(*info.ul)
		case C.VIR_TYPED_PARAM_DOUBLE:
			if info.d == nil {
				return fmt.Errorf("field %s expects a float64", name)
			}
			*(*C.double)(unsafe.Pointer(&cparam.value)) = C.double(*info.d)
		case C.VIR_TYPED_PARAM_BOOLEAN:
			if info.b == nil {
				return fmt.Errorf("field %s expects a bool", name)
			}
			if *info.b {
				*(*C.char)(unsafe.Pointer(&cparam.value)) = 1
			} else {
				*(*C.char)(unsafe.Pointer(&cparam.value)) = 0
			}
		case C.VIR_TYPED_PARAM_STRING:
			if info.s != nil {
				*(**C.char)(unsafe.Pointer(&cparam.value)) = C.CString(*info.s)
			} else if info.sl != nil {
				count := stringOffsets[name]
				*(**C.char)(unsafe.Pointer(&cparam.value)) = C.CString((*info.sl)[count])
				stringOffsets[name] = count + 1
			} else {
				return fmt.Errorf("field %s expects a string", name)
			}
		}
	}

	return nil
}

func typedParamsPack(cparams []C.virTypedParameter, infomap map[string]typedParamsFieldInfo) error {
	return typedParamsPackLen(&cparams[0], len(cparams), infomap)
}

func typedParamsPackNew(infomap map[string]typedParamsFieldInfo) (*[]C.virTypedParameter, error) {
	nparams := 0
	for _, value := range infomap {
		if !*value.set {
			continue
		}

		if value.sl != nil {
			nparams += len(*value.sl)
		} else {
			nparams++
		}
	}

	cparams := make([]C.virTypedParameter, nparams)
	nparams = 0
	for key, value := range infomap {
		if !*value.set {
			continue
		}

		cfield := C.CString(key)
		defer C.free(unsafe.Pointer(cfield))
		clen := len(key) + 1
		if clen > C.VIR_TYPED_PARAM_FIELD_LENGTH {
			clen = C.VIR_TYPED_PARAM_FIELD_LENGTH
		}
		if value.sl != nil {
			for i := 0; i < len(*value.sl); i++ {
				cparam := &cparams[nparams]
				cparam._type = C.VIR_TYPED_PARAM_STRING
				C.memcpy(unsafe.Pointer(&cparam.field[0]), unsafe.Pointer(cfield), C.size_t(clen))
				nparams++
			}
		} else {
			cparam := &cparams[nparams]
			if value.i != nil {
				cparam._type = C.VIR_TYPED_PARAM_INT
			} else if value.ui != nil {
				cparam._type = C.VIR_TYPED_PARAM_UINT
			} else if value.l != nil {
				cparam._type = C.VIR_TYPED_PARAM_LLONG
			} else if value.ul != nil {
				cparam._type = C.VIR_TYPED_PARAM_ULLONG
			} else if value.b != nil {
				cparam._type = C.VIR_TYPED_PARAM_BOOLEAN
			} else if value.d != nil {
				cparam._type = C.VIR_TYPED_PARAM_DOUBLE
			} else if value.s != nil {
				cparam._type = C.VIR_TYPED_PARAM_STRING
			}
			C.memcpy(unsafe.Pointer(&cparam.field[0]), unsafe.Pointer(cfield), C.size_t(clen))
			nparams++
		}
	}

	err := typedParamsPack(cparams, infomap)
	if err != nil {
		C.virTypedParamsClear((*C.virTypedParameter)(unsafe.Pointer(&cparams[0])), C.int(nparams))
		return nil, err
	}
	return &cparams, nil
}


text:
var stdout = require('stdout-stream')
var multistream = require('multistream')
var eos = require('end-of-stream')

module.exports = function(dat, opts, cb) {
  if (!opts) opts = {}
  if (!opts.f && !opts.json) opts.json = true

  var readStream = dat.createReadStream(opts)

  if (opts.live) {
    var changes = dat.createChangesReadStream({
      since: dat.storage.change,
      data: true,
      decode: true,
      live: true
    })

    var format = through.obj(function(data, enc, cb) {
      cb(null, data.value)
    })

    readStream = multistream([readStream, pump(changes, format, ldj.serialize())])
  }

  readStream.pipe(stdout)
  eos(readStream, cb)
}


text:
#ifndef _ACTIVEMQ_CMSUTIL_PRODUCERCALLBACK_H_
#define _ACTIVEMQ_CMSUTIL_PRODUCERCALLBACK_H_

#include <activemq/util/Config.h>

namespace cms {
    class Session;
    class MessageProducer;
}
namespace activemq {
namespace cmsutil {

    /**
     * Callback for sending a message to a CMS destination.
     */
    class AMQCPP_API ProducerCallback {
    public:

        virtual ~ProducerCallback();

        /**
         * Execute an action given a session and producer.
         *
         * @param session
         *          the CMS Session
         * @param producer
         *          the CMS Producer
         *
         * @throws cms::CMSException if thrown by CMS API methods
         */
        virtual void doInCms(cms::Session* session, cms::MessageProducer* producer) = 0;

    };

}}

#endif /*_ACTIVEMQ_CMSUTIL_PRODUCERCALLBACK_H_*/


text:
package example;

import xmlparser.XmlParser;
import xmlparser.annotations.XmlAttribute;

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

import static xmlparser.XmlParser.newXmlParser;

public class PrettyPrint {

    public static class Pojo {
        public Map<String, Field> map = new HashMap<>();
    }
    public static class Field {
        @XmlAttribute
        public String attribute;
    }

    public static void main(final String... args) {
        // Pretty printing is actually the default
        final XmlParser parser = newXmlParser().shouldPrettyPrint().build();
        final Field field = new Field();
        field.attribute = "value";
        final Pojo pojo = new Pojo();
        pojo.map.put("key", field);
        System.out.println(parser.toXml(pojo));
    }

}


text:
using UnityEngine;
using System.Collections;

class DisplayUtils
{
    public static Vector2 GetFrustumSizeAtZ(float z, Camera camera)
    {
        float distance = Mathf.Abs(camera.transform.position.z) - z;
        var frustumHeight = 2.0f * distance * Mathf.Tan(camera.fieldOfView * 0.5f * Mathf.Deg2Rad);
        var frustumWidth = frustumHeight * camera.aspect;
        return new Vector2(frustumWidth, frustumHeight);
    }
}


text: Chicken Coop Door Controller using an arduino.


text:
export class ForceDirectedGraphNode{
    node: number;
    name: string;
    group: number;
    x?: number;
    y?: number;
    fixed?: boolean;
}


text:
package com.thinkaurelius.titan.blueprints.process.traversal.strategy;

import com.thinkaurelius.titan.blueprints.InMemoryGraphProvider;
import com.thinkaurelius.titan.core.TitanGraph;
import org.apache.tinkerpop.gremlin.GraphProviderClass;
import org.junit.runner.RunWith;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
@RunWith(TitanStrategySuite.class)
@GraphProviderClass(provider = InMemoryGraphProvider.class, graph = TitanGraph.class)
public class TitanStrategyTest {
}


text:
* Update to fable-babel-plugins 2.3.0

### 2.1.8

* Add `silent` option

### 2.1.7

* Enable different compiler implementations

### 2.1.6

* Add back possibility to connect to TCP port

### 2.1.5

* Update fable-babel-plugins dependency

### 2.1.4

* Add babelOptions.filename, since it is needed by other Babel plugins @SirUppyPancakes

### 2.1.3

* Accept fable-compiler 2.2.x dependency

### 2.1.2

* Add webpack >= 4.23.0 as peerDependency

### 2.1.1

* Fix #1523: Mark files with inlined functions as dependencies

### 2.1.0

* Release _stablish_ version

### 2.1.0-beta-007

* Use fable-babel-plugins package

### 2.1.0-beta-006

* Use fable-compiler package

### 2.1.0-beta-005

* Make fable-compiler-dotnet a peerDependency

### 2.1.0-beta-004

* Minor refactoring and update README

### 2.1.0-beta-003

* Fix detection of Webpack watch mode

### 2.1.0-beta-002

* Pin minor version of fable-compiler-dotnet

### 2.1.0-beta-001

* Add fable-compiler-dotnet dependency for standalone compilation

### 2.0.0

* Fable 2

### 2.0.0-beta-001

* Compatibility with Babel 7

### 2.0.0-alpha-003

* Fable 2 alpha

### 1.1.6

* Ignore dependencies

### 1.1.5

* Make dependencies an opt-out with `extra.ignoreDependencies`

### 1.1.4

* Add dependencies for files other than .fsproj

### 1.1.3

* Don't add dependencies to Webpack by default

### 1.1.2

* Update README

### 1.1.0

* Validate options
* Remove cache

### 1.0.7

* Don't cache errored files

### 1.0.6

* Update README

### 1.0.5

* Fix cache option

### 1.0.4

* Fix sourcemap generation

### 1.0.3

* Fix #988: Print relative path of compiled files (PR #994)

### 1.0.2

* Less verbose output and cache capabilities

### 1.0.0

* Don't check fable-core version

### 1.0.0-narumi-912

* Fix detection of `FABLE_SERVER_PORT`

### 1.0.0-narumi-911

* Check `FABLE_SERVER_PORT` environmental variable


text:
---
uid: SolidEdgePart.SweptCutout.IsAttributeSetPresent(System.String)
summary:
remarks:
example: [*content]
---
[!code-vb[Main](..\snippets\SolidEdgePart.SweptCutout.IsAttributeSetPresent.vb]
[!code-csharp[Main](..\snippets\SolidEdgePart.SweptCutout.IsAttributeSetPresent.cs]


text:
package com.ljd.news.data.repository;

import com.ljd.news.data.entity.mapper.NewsEntityDataMapper;
import com.ljd.news.data.net.RetrofitServiceFactory;
import com.ljd.news.domain.UpdateApk;
import com.ljd.news.domain.repository.NewsRepository;

import javax.inject.Inject;
import javax.inject.Singleton;

import okhttp3.ResponseBody;
import rx.Observable;

@Singleton
public class NewsDataRepository implements NewsRepository {

    private final NewsEntityDataMapper newsEntityDataMapper;
    private final RetrofitServiceFactory retrofitServiceFactory;

    @Inject
    public NewsDataRepository(RetrofitServiceFactory retrofitServiceFactory,
                              NewsEntityDataMapper newsEntityDataMapper) {
        this.retrofitServiceFactory = retrofitServiceFactory;
        this.newsEntityDataMapper = newsEntityDataMapper;
    }

    @Override
    public Observable<UpdateApk> checkApkUpdate() {
        return retrofitServiceFactory.getNewsService().checkUpdateApk()
                .map(updateApkEntity -> newsEntityDataMapper.transform(updateApkEntity));
    }

    @Override
    public Observable<ResponseBody> downloadNewsApk() {
        return retrofitServiceFactory.getNewsService().downloadApk();
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.batchai.models;

import com.azure.core.management.Region;
import com.azure.core.util.Context;
import com.azure.resourcemanager.batchai.fluent.models.WorkspaceInner;
import java.time.OffsetDateTime;
import java.util.Map;

/** An immutable client-side representation of Workspace. */
public interface Workspace {
    /**
     * Gets the id property: Fully qualified resource Id for the resource.
     *
     * @return the id value.
     */
    String id();

    /**
     * Gets the name property: The name of the resource.
     *
     * @return the name value.
     */
    String name();

    /**
     * Gets the type property: The type of the resource.
     *
     * @return the type value.
     */
    String type();

    /**
     * Gets the location property: The geo-location where the resource lives.
     *
     * @return the location value.
     */
    String location();

    /**
     * Gets the tags property: Resource tags.
     *
     * @return the tags value.
     */
    Map<String, String> tags();

    /**
     * Gets the creationTime property: Time when the Workspace was created.
     *
     * @return the creationTime value.
     */
    OffsetDateTime creationTime();

    /**
     * Gets the provisioningState property: The provisioned state of the Workspace.
     *
     * @return the provisioningState value.
     */
    ProvisioningState provisioningState();

    /**
     * Gets the provisioningStateTransitionTime property: The time at which the workspace entered its current
     * provisioning state.
     *
     * @return the provisioningStateTransitionTime value.
     */
    OffsetDateTime provisioningStateTransitionTime();

    /**
     * Gets the region of the resource.
     *
     * @return the region of the resource.
     */
    Region region();

    /**
     * Gets the name of the resource region.
     *
     * @return the name of the resource region.
     */
    String regionName();

    /**
     * Gets the inner com.azure.resourcemanager.batchai.fluent.models.WorkspaceInner object.
     *
     * @return the inner object.
     */
    WorkspaceInner innerModel();

    /** The entirety of the Workspace definition. */
    interface Definition
        extends DefinitionStages.Blank,
            DefinitionStages.WithLocation,
            DefinitionStages.WithResourceGroup,
            DefinitionStages.WithCreate {
    }
    /** The Workspace definition stages. */
    interface DefinitionStages {
        /** The first stage of the Workspace definition. */
        interface Blank extends WithLocation {
        }
        /** The stage of the Workspace definition allowing to specify location. */
        interface WithLocation {
            /**
             * Specifies the region for the resource.
             *
             * @param location The region in which to create the Workspace.
             * @return the next definition stage.
             */
            WithResourceGroup withRegion(Region location);

            /**
             * Specifies the region for the resource.
             *
             * @param location The region in which to create the Workspace.
             * @return the next definition stage.
             */
            WithResourceGroup withRegion(String location);
        }
        /** The stage of the Workspace definition allowing to specify parent resource. */
        interface WithResourceGroup {
            /**
             * Specifies resourceGroupName.
             *
             * @param resourceGroupName Name of the resource group to which the resource belongs.
             * @return the next definition stage.
             */
            WithCreate withExistingResourceGroup(String resourceGroupName);
        }
        /**
         * The stage of the Workspace definition which contains all the minimum required properties for the resource to
         * be created, but also allows for any other optional properties to be specified.
         */
        interface WithCreate extends DefinitionStages.WithTags {
            /**
             * Executes the create request.
             *
             * @return the created resource.
             */
            Workspace create();

            /**
             * Executes the create request.
             *
             * @param context The context to associate with this operation.
             * @return the created resource.
             */
            Workspace create(Context context);
        }
        /** The stage of the Workspace definition allowing to specify tags. */
        interface WithTags {
            /**
             * Specifies the tags property: The user specified tags associated with the Workspace..
             *
             * @param tags The user specified tags associated with the Workspace.
             * @return the next definition stage.
             */
            WithCreate withTags(Map<String, String> tags);
        }
    }
    /**
     * Begins update for the Workspace resource.
     *
     * @return the stage of resource update.
     */
    Workspace.Update update();

    /** The template for Workspace update. */
    interface Update extends UpdateStages.WithTags {
        /**
         * Executes the update request.
         *
         * @return the updated resource.
         */
        Workspace apply();

        /**
         * Executes the update request.
         *
         * @param context The context to associate with this operation.
         * @return the updated resource.
         */
        Workspace apply(Context context);
    }
    /** The Workspace update stages. */
    interface UpdateStages {
        /** The stage of the Workspace update allowing to specify tags. */
        interface WithTags {
            /**
             * Specifies the tags property: The user specified tags associated with the Workspace..
             *
             * @param tags The user specified tags associated with the Workspace.
             * @return the next definition stage.
             */
            Update withTags(Map<String, String> tags);
        }
    }
    /**
     * Refreshes the resource to sync with Azure.
     *
     * @return the refreshed resource.
     */
    Workspace refresh();

    /**
     * Refreshes the resource to sync with Azure.
     *
     * @param context The context to associate with this operation.
     * @return the refreshed resource.
     */
    Workspace refresh(Context context);
}


text:
package org.ballerinalang.containers.docker;

import org.ballerinalang.containers.Constants;
import org.ballerinalang.containers.docker.exception.BallerinaDockerClientException;
import org.ballerinalang.containers.docker.impl.DefaultBallerinaDockerClient;
import org.ballerinalang.containers.docker.utils.TestUtils;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * Unit tests to cover scenarios related to package based Docker image manipulation.
 */
public class DefaultBallerinaDockerClientPackageBasedTest {

    private BallerinaDockerClient dockerClient;
    private List<String> createdImages = new ArrayList<>();

    @BeforeMethod
    public void setUp() {
        this.dockerClient = new DefaultBallerinaDockerClient();
    }

    @Test
    public void testSuccessfulCreateServiceImage()
            throws IOException, InterruptedException, BallerinaDockerClientException {

        String serviceName = "TestService1";
        String imageName = serviceName.toLowerCase();
        List<Path> packagePaths = TestUtils.getTestServiceAsPathList();

        String result = dockerClient.createServiceImage(serviceName, null, packagePaths, null, null);
        createdImages.add(imageName);

        Assert.assertTrue((result != null) && (result.equals(imageName
                + ":" + Constants.IMAGE_VERSION_LATEST)), "Docker image creation failed.");
    }

    @Test
    public void testSuccessfulCreateFunctionImage()
            throws IOException, InterruptedException, BallerinaDockerClientException {

        String serviceName = "TestFunction1";
        String imageName = serviceName.toLowerCase();
        List<Path> packagePaths = TestUtils.getTestFunctionAsPathList();

        String result = dockerClient.createMainImage(serviceName, null, packagePaths, null, null);
        createdImages.add(imageName);

        Assert.assertTrue((result != null) && (result.equals(imageName
                + ":" + Constants.IMAGE_VERSION_LATEST)), "Docker image creation failed.");
    }

    @Test(expectedExceptions = {BallerinaDockerClientException.class})
    public void testFailedImageCreationWrongArchiveForMain()
            throws IOException, InterruptedException, BallerinaDockerClientException {
        String serviceName = "TestService1";
        List<Path> packagePaths = TestUtils.getTestServiceAsPathList();
        dockerClient.createMainImage(serviceName, null, packagePaths, null, null);
    }

    @Test(expectedExceptions = {BallerinaDockerClientException.class})
    public void testFailedImageCreationWrongArchiveForService()
            throws IOException, InterruptedException, BallerinaDockerClientException {
        String serviceName = "TestFunction1";
        List<Path> packagePaths = TestUtils.getTestFunctionAsPathList();
        dockerClient.createServiceImage(serviceName, null, packagePaths, null, null);
    }

    @AfterMethod
    public void tearDown() {
        for (String imageName : createdImages) {
            TestUtils.deleteDockerImage(imageName);
        }

        createdImages = new ArrayList<>();
    }
}


text:
ghc-man-completion
==================


text:
package psidev.psi.mi.jami.model.impl;

import junit.framework.Assert;
import org.junit.Test;
import psidev.psi.mi.jami.model.AllostericEffectorType;
import psidev.psi.mi.jami.model.MoleculeEffector;
import psidev.psi.mi.jami.utils.InteractorUtils;
import psidev.psi.mi.jami.utils.comparator.participant.DefaultModelledEntityComparator;

/**
 * Unit tester for DefaultMoleculeEffector
 *
 * @author Marine Dumousseau (marine@ebi.ac.uk)
 * @version $Id$
 * @since
30/05/13

 */

public class DefaultMoleculeEffectorTest {

    @Test
    public void test_create_molecule_effector(){

        MoleculeEffector effector = new DefaultMoleculeEffector(new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor()));

        Assert.assertEquals(AllostericEffectorType.molecule, effector.getEffectorType());
        Assert.assertTrue(DefaultModelledEntityComparator.areEquals(new DefaultModelledParticipant(InteractorUtils.createUnknownBasicInteractor()), effector.getMolecule(), true));
    }

    @Test(expected=IllegalArgumentException.class)
    public void test_molecule_effector_molecule_null() throws Exception {
        MoleculeEffector effector = new DefaultMoleculeEffector(null);
    }
}


text:
class String
  def camelcase(*separators)
    case separators.first
      when Symbol, TrueClass, FalseClass, NilClass
        first_letter = separators.shift
    end

    separators = ['_'] if separators.empty?

    str = self.dup

    separators.each do |s|
      str = str.gsub(/(?:#{s}+)([a-z])/){ $1.upcase }
    end

    case first_letter
      when :upper, true
        str = str.gsub(/(\A|\s)([a-z])/){ $1 + $2.upcase }
      when :lower, false
        str = str.gsub(/(\A|\s)([A-Z])/){ $1 + $2.downcase }
    end

    str
  end

  def upper_camelcase(*separators)
    camelcase(:upper, *separators)
  end

  def lower_camelcase(*separators)
    camelcase(:lower, *separators)
  end

end