text:
(function () {
    // jshint newcap: false
    this.LivePlayerSupportLevelRestartableTest = AsyncTestCase("LivePlayerSupportLevelRestartableTest");

    this.LivePlayerSupportLevelRestartableTest.prototype.setUp = function () {
        this.sandbox = sinon.sandbox.create();
    };

    this.LivePlayerSupportLevelRestartableTest.prototype.tearDown = function () {
        this.sandbox.restore();
    };

    var config = {"modules":{"base":"antie/devices/browserdevice","modifiers":["antie/devices/mediaplayer/html5"]}, "input":{"map":{}},"layouts":[{"width":960,"height":540,"module":"fixtures/layouts/default","classes":["browserdevice540p"]}],"deviceConfigurationKey":"devices-html5-1"};
    var configWithForceBeginPlaybackToEndOfWindowAsTrue = {"modules":{"base":"antie/devices/browserdevice","modifiers":["antie/devices/mediaplayer/html5"]}, "input":{"map":{}},"layouts":[{"width":960,"height":540,"module":"fixtures/layouts/default","classes":["browserdevice540p"]}],"deviceConfigurationKey":"devices-html5-1","streaming":{"overrides":{"forceBeginPlaybackToEndOfWindow":true}}};
    var configWithForceBeginPlaybackToEndOfWindowAsFalse = {"modules":{"base":"antie/devices/browserdevice","modifiers":["antie/devices/mediaplayer/html5"]}, "input":{"map":{}},"layouts":[{"width":960,"height":540,"module":"fixtures/layouts/default","classes":["browserdevice540p"]}],"deviceConfigurationKey":"devices-html5-1","streaming":{"overrides":{"forceBeginPlaybackToEndOfWindow":false}}};

    this.LivePlayerSupportLevelRestartableTest.prototype.testGetLiveSupportReturnsRestartableWithSupportLevelRestartable = function (queue) {
        expectAsserts(1);

        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function(application, MediaPlayer, Device) {

            var device = new Device(antie.framework.deviceConfiguration);
            var liveSupportLevel = device.getLiveSupport();

            assertEquals("restartable", liveSupportLevel);
        });
    };

    var testFunctionsInLivePlayerCallMediaPlayerFunctions = function(action, expectedArgCount) {
        return function (queue) {
            expectAsserts(2);
            queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function(application, MediaPlayer, Device) {
                var device = new Device(antie.framework.deviceConfiguration);
                var livePlayer = device.getLivePlayer();
                var mediaPlayerFuncStub = this.sandbox.stub();
                device.getMediaPlayer()[action] = mediaPlayerFuncStub;
                livePlayer[action]();
                assert(mediaPlayerFuncStub.calledOnce);
                assertEquals(expectedArgCount, mediaPlayerFuncStub.getCall(0).args.length);
            }, config);
        };
    };

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerBeginPlaybackCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('beginPlayback', 0);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerBeginPlaybackFromCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('beginPlaybackFrom', 1);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerSetSourceCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('setSource', 3);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerStopCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('stop', 0);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerResetCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('reset', 0);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerGetStateCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('getState', 0);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerGetSourceCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('getSource', 0);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerGetMimeTypeCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('getMimeType', 0);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerAddEventCallbackCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('addEventCallback', 2);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerRemoveEventCallbackCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('removeEventCallback', 2);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerRemoveAllEventCallbacksCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('removeAllEventCallbacks', 0);

    this.LivePlayerSupportLevelRestartableTest.prototype.testLivePlayerGetPlayerElementCallsFunctionInMediaPlayer = testFunctionsInLivePlayerCallMediaPlayerFunctions('getPlayerElement', 0);

    this.LivePlayerSupportLevelRestartableTest.prototype.testSeekableMediaPlayerFunctionsNotDefinedInRestartableLive = function (queue) {
        expectAsserts(5);

        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function(application, MediaPlayer, Device) {

            var device = new Device(antie.framework.deviceConfiguration);
            var livePlayer = device.getLivePlayer();

            assertUndefined(livePlayer.playFrom);
            assertUndefined(livePlayer.pause);
            assertUndefined(livePlayer.resume);
            assertUndefined(livePlayer.getCurrentTime);
            assertUndefined(livePlayer.getSeekableRange);
        });
    };

    this.LivePlayerSupportLevelRestartableTest.prototype.testGetStateReturnsState = function (queue) {
        expectAsserts(1);
        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function(application, MediaPlayer, Device) {
            var device = new Device(antie.framework.deviceConfiguration);
            var livePlayer = device.getLivePlayer();
            assertEquals("EMPTY", livePlayer.getState());
        }, config);
    };

    this.LivePlayerSupportLevelRestartableTest.prototype.testGetSourceReturnsSource = function (queue) {
        expectAsserts(1);
        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function(application, MediaPlayer, Device) {
            var device = new Device(antie.framework.deviceConfiguration);
            var livePlayer = device.getLivePlayer();

            this.sandbox.stub(livePlayer._mediaPlayer, 'getSource').returns("http://test.mp4");

            assertEquals("http://test.mp4", livePlayer.getSource());
        }, config);
    };

    this.LivePlayerSupportLevelRestartableTest.prototype.testGetMimeTypeReturnsMimeType = function (queue) {
        expectAsserts(1);
        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function(application, MediaPlayer, Device) {
            var device = new Device(antie.framework.deviceConfiguration);
            var livePlayer = device.getLivePlayer();

            this.sandbox.stub(livePlayer._mediaPlayer, 'getMimeType').returns("video/mp4");

            assertEquals("video/mp4", livePlayer.getMimeType());
        }, config);
    };

    this.LivePlayerSupportLevelRestartableTest.prototype.testMediaTypeIsMutatedToLive = function(queue) {
        expectAsserts(4);
        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function (application, MediaPlayer, Device) {
            var device = new Device(antie.framework.deviceConfiguration);
            var livePlayer = device.getLivePlayer();

            this.sandbox.stub(livePlayer._mediaPlayer, 'setSource');

            livePlayer.setSource(MediaPlayer.TYPE.VIDEO, "", "");
            assert(livePlayer._mediaPlayer.setSource.calledWith(MediaPlayer.TYPE.LIVE_VIDEO));

            livePlayer.setSource(MediaPlayer.TYPE.AUDIO, "", "");
            assert(livePlayer._mediaPlayer.setSource.calledWith(MediaPlayer.TYPE.LIVE_AUDIO));

            livePlayer.setSource(MediaPlayer.TYPE.LIVE_VIDEO, "", "");
            assert(livePlayer._mediaPlayer.setSource.calledWith(MediaPlayer.TYPE.LIVE_VIDEO));

            livePlayer.setSource(MediaPlayer.TYPE.LIVE_AUDIO, "", "");
            assert(livePlayer._mediaPlayer.setSource.calledWith(MediaPlayer.TYPE.LIVE_AUDIO));
        }, config);
    };

    this.LivePlayerSupportLevelRestartableTest.prototype.testGetPlayerElementReturnsPlayerElement = function (queue) {
        expectAsserts(1);
        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function (application, MediaPlayer, Device) {
            var device = new Device(antie.framework.deviceConfiguration);
            var livePlayer = device.getLivePlayer();
            var playerElement = "player element";

            this.sandbox.stub(livePlayer._mediaPlayer, 'getPlayerElement').returns(playerElement);

            assertEquals(playerElement, livePlayer.getPlayerElement());
        }, config);
    };

    this.LivePlayerSupportLevelRestartableTest.prototype.testBeginPlaybackFromIsCalledWithInfinityIfForceBeginPlaybackToEndOfWindowIsTrue = function (queue) {
        expectAsserts(2);
        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function (application, MediaPlayer, Device) {
            var device = new Device(antie.framework.deviceConfiguration);
            var livePlayer = device.getLivePlayer();

            livePlayer._mediaPlayer.beginPlayback = this.sandbox.stub();
            livePlayer._mediaPlayer.beginPlaybackFrom = this.sandbox.stub();

            livePlayer.beginPlayback();
            assert(livePlayer._mediaPlayer.beginPlaybackFrom.calledWith(Infinity));
            assert(livePlayer._mediaPlayer.beginPlayback.notCalled);
        }, configWithForceBeginPlaybackToEndOfWindowAsTrue);
    };

    this.LivePlayerSupportLevelRestartableTest.prototype.testBeginPlaybackIsCalledIfForceBeginPlaybackToEndOfWindowIsFalse = function (queue) {
        expectAsserts(2);
        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function (application, MediaPlayer, Device) {
            var device = new Device(antie.framework.deviceConfiguration);
            var livePlayer = device.getLivePlayer();

            livePlayer._mediaPlayer.beginPlayback = this.sandbox.stub();
            livePlayer._mediaPlayer.beginPlaybackFrom = this.sandbox.stub();

            livePlayer.beginPlayback();
            assert(livePlayer._mediaPlayer.beginPlayback.called);
            assert(livePlayer._mediaPlayer.beginPlaybackFrom.notCalled);
        }, configWithForceBeginPlaybackToEndOfWindowAsFalse);
    };

    this.LivePlayerSupportLevelRestartableTest.prototype.testBeginPlaybackIsCalledIfForceBeginPlaybackToEndOfWindowIsNotPresent = function (queue) {
        expectAsserts(2);
        queuedApplicationInit(queue, 'lib/mockapplication', ["antie/devices/mediaplayer/mediaplayer", "antie/devices/device", "antie/devices/mediaplayer/live/restartable"], function (application, MediaPlayer, Device) {
            var device = new Device(antie.framework.deviceConfiguration);
            var livePlayer = device.getLivePlayer();

            livePlayer._mediaPlayer.beginPlayback = this.sandbox.stub();
            livePlayer._mediaPlayer.beginPlaybackFrom = this.sandbox.stub();

            livePlayer.beginPlayback();
            assert(livePlayer._mediaPlayer.beginPlayback.called);
            assert(livePlayer._mediaPlayer.beginPlaybackFrom.notCalled);
        }, config);
    };
})();


text:
require 'optparse'
require 'google/ads/google_ads'
require 'date'

def add_affiliate_location_extensions(
  customer_id,
  chain_id,
  campaign_id,
  should_delete_existing_feeds)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  if should_delete_existing_feeds
    delete_location_extension_feeds(client, customer_id)
  end

  feed_resource_name = create_affiliate_location_extension_feed(
    client,
    customer_id,
    chain_id,
  )

  # After the completion of the feed creation operation above the added feed
  # will not be available for usage in a campaign feed until the feed mapping
  # is created. We then need to wait for the feed mapping to be created.
  feed_mapping = wait_for_feed_to_be_ready(
    client,
    customer_id,
    feed_resource_name,
  )

  create_campaign_feed(
    client,
    customer_id,
    campaign_id,
    feed_mapping,
    feed_resource_name,
    chain_id,
  )
end

# Deletes the existing location extension feeds.
def delete_location_extension_feeds(client, customer_id)
  # To delete a location extension feed, you need to
  # 1. Delete the customer feed so that the location extensions from the feed
  #    stop serving.
  # 2. Delete the feed so that Google Ads will no longer sync from the Business
  #    Profile account.
  customer_feeds = get_location_extension_customer_feeds(client, customer_id)
  unless customer_feeds.empty?
    # Optional: You may also want to delete the campaign and ad group feeds.
    remove_customer_feeds(client, customer_id, customer_feeds)
  end
  feeds = get_location_extension_feeds(client, customer_id)
  unless feeds.empty?
    remove_feeds(client, customer_id, customer_feeds)
  end
end

# Gets the existing location extension customer feeds.
def get_location_extension_customer_feeds(client, customer_id)
  customer_feeds = []

  # Creates the query. A location extension customer feed can be identified
  # by filtering for placeholder_types as LOCATION (location extension feeds) or
  # placeholder_types as AFFILIATE_LOCATION (affiliate location extension feeds).
  query = <<~QUERY
    SELECT customer_feed.resource_name
    FROM customer_feed
    WHERE customer_feed.placeholder_types CONTAINS ANY(LOCATION, AFFILIATE_LOCATION)
    AND customer_feed.status = ENABLED
  QUERY

  # Issues a search stream request.
  responses = client.service.google_ads.search_stream(
    customer_id: customer_id,
    query: query,
  )

  # Iterates over all rows in all messages to collect the results.
  responses.each do |response|
    response.results.each do |row|
      customer_feeds << row.customer_feed
    end
  end

  customer_feeds
end

# Removes the customer feeds.
def remove_customer_feeds(client, customer_id, customer_feeds)
  operations = []

  customer_feeds.each do |customer_feed|
    operations << client.operation.remove_resource.customer_feed(
      customer_feed.resource_name)
  end

  # Issues a mutate request to remove the customer feeds.
  client.service.customer_feed.mutate_customer_feeds(customer_id, operations)
end

# Gets the existing location extension feeds.
def get_location_extension_feeds(client, customer_id)
  feeds = []

  # Creates the query.
  query = <<~QUERY
    SELECT feed.resource_name
    FROM feed
    WHERE feed.status = ENABLED
    AND feed.origin = USER
  QUERY

  # Issues a search stream request.
  responses = client.service.google_ads.search_stream(
    customer_id: customer_id,
    query: query,
  )

  # Iterates over all rows in all messages to collect the results.
  responses.each do |response|
    response.results.each do |row|
      feeds << row.feed
    end
  end

  feeds
end

# Removes the feeds.
def remove_feeds(client, customer_id, feeds)
  operations = []

  feeds.each do |feed|
    operations << client.operation.remove_resource.feed(feed.resource_name)
  end

  # Issues a mutate request to remove the feeds.
  client.service.feed.mutate_feeds(customer_id, operations)
end

# Creates the affiliate location extension feed.
# [START add_affiliate_location_extensions]
def create_affiliate_location_extension_feed(client, customer_id, chain_id)
  # Creates a feed that will sync to retail addresses for a given retail
  # chain ID.
  # Do not add feed attributes, Google Ads will add them automatically because
  # this will be a system generated feed.
  operation = client.operation.create_resource.feed do |feed|
    feed.name = "Affiliate Location Extension feed ##{(Time.new.to_f * 1000).to_i}"
    feed.affiliate_location_feed_data = client.resource.affiliate_location_feed_data do |data|
      data.chain_ids << chain_id
      data.relationship_type = :GENERAL_RETAILER
    end
    # Since this feed's contents will be managed by Google, you must set its
    # origin to GOOGLE.
    feed.origin = :GOOGLE
  end

  # Issues a mutate request to add the feed and prints some information.
  response = client.service.feed.mutate_feeds(
    customer_id: customer_id,
    operations: [operation],
  )

  feed_resource_name = response.results.first.resource_name
  puts "Affiliate location extension feed created with resource name: #{feed_resource_name}"

  feed_resource_name
end
# [END add_affiliate_location_extensions]

# Waits for the affiliate location extension feed to be ready. An exponential
# back-off policy with a maximum number of attempts is used to poll the server.
# [START add_affiliate_location_extensions_2]
def wait_for_feed_to_be_ready(client, customer_id, feed_resource_name)
  number_of_attempts = 0

  while number_of_attempts < MAX_FEEDMAPPING_RETRIEVAL_ATTEMPTS
    # Once you create a feed, Google's servers will setup the feed by creating
    # feed attributes and feed mapping. Once the feed mapping is created, it is
    # ready to be used for creating customer feed.
    # This process is asynchronous, so we wait until the feed mapping is
    # created, performing exponential backoff.
    feed_mapping = get_affiliated_location_extension_feed_mapping(
      client, customer_id, feed_resource_name)

    if feed_mapping.nil?
      number_of_attempts += 1
      sleep_seconds = POLL_FREQUENCY_SECONDS * (2 ** number_of_attempts)
      puts "Checked #{number_of_attempts} time(s). Feed is not ready yet. " \
        "Waiting #{sleep_seconds} seconds before trying again."
      sleep sleep_seconds
    else
      puts "Feed #{feed_resource_name} is now ready."
      return feed_mapping
    end
  end

  raise "The affiliate location feed mapping is still not ready after " \
    "#{MAX_FEEDMAPPING_RETRIEVAL_ATTEMPTS} attempt(s)."
end
# [END add_affiliate_location_extensions_2]

# Gets the affiliate location extension feed mapping.
# [START add_affiliate_location_extensions_1]
def get_affiliated_location_extension_feed_mapping(
  client,
  customer_id,
  feed_resource_name)
  # Creates a query that retrieves the feed mapping.
  query = <<~QUERY
    SELECT feed_mapping.resource_name,
           feed_mapping.attribute_field_mappings,
           feed_mapping.status
    FROM feed_mapping
    WHERE feed_mapping.feed = '#{feed_resource_name}'
    AND feed_mapping.status = ENABLED
    AND feed_mapping.placeholder_type = AFFILIATE_LOCATION
    LIMIT 1
  QUERY

  # Issues a search request
  responses = client.service.google_ads.search(
    customer_id: customer_id,
    query: query,
    return_total_results_count: true,
  )

  response = responses.page.response
  response.total_results_count == 1 ? response.results.first.feed_mapping : nil
end
# [END add_affiliate_location_extensions_1]

# Creates the campaign feed.
# [START add_affiliate_location_extensions_3]
def create_campaign_feed(
  client,
  customer_id,
  campaign_id,
  feed_mapping,
  feed_resource_name,
  chain_id)
  matching_function = "IN(FeedAttribute[#{feed_resource_name.split('/')[3]}, " \
    "#{get_attribute_id_for_chain_id(feed_mapping)}], #{chain_id})"

  # Adds a campaign feed that associates the feed with this campaign for the
  # AFFILIATE_LOCATION placeholder type.
  operation = client.operation.create_resource.campaign_feed do |cf|
    cf.feed = feed_resource_name
    cf.placeholder_types << :AFFILIATE_LOCATION
    cf.matching_function = client.resource.matching_function do |m|
      m.function_string = matching_function
    end
    cf.campaign = client.path.campaign(customer_id, campaign_id)
  end

  # Issues a mutate request to add the campaign feed and prints some information.
  response = client.service.campaign_feed.mutate_campaign_feeds(
    customer_id: customer_id,
    operations: [operation],
  )
  puts "Campaign feed created with resource name: " \
    "#{response.results.first.resource_name}"
end
# [END add_affiliate_location_extensions_3]

# Gets the feed attribute ID for the retail chain ID.
# [START add_affiliate_location_extensions_4]
def get_attribute_id_for_chain_id(feed_mapping)
  feed_mapping.attribute_field_mappings.each do |fm|
    if fm.affiliate_location_field == :CHAIN_ID
      return fm.feed_attribute_id
    end
  end

  raise "Affiliate location feed mapping isn't setup correctly."
end
# [END add_affiliate_location_extensions_4]

if __FILE__ == $0
  POLL_FREQUENCY_SECONDS = 5
  MAX_FEEDMAPPING_RETRIEVAL_ATTEMPTS = 10

  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
  options[:chain_id] = 'INSERT_CHAIN_ID_HERE'
  options[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE'
  options[:should_delete_existing_feeds] = false

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.on('-N', '--chain-id CHAIN-ID', String, 'Chain ID') do |v|
      options[:chain_id] = v
    end

    opts.on('-c', '--campaign-id CAMPAIGN-ID', String, 'Campaign ID') do |v|
      options[:campaign_id] = v
    end

    opts.on('-D', '--should-delete-existing-feeds SHOULD-DELETE-EXISTING-FEEDS',
      TrueClass, 'Should delete existing feeds') do |v|
      options[:should_delete_existing_feeds] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    add_affiliate_location_extensions(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:chain_id).to_i,
      options.fetch(:campaign_id),
      options[:should_delete_existing_feeds])
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
    raise
  end
end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace KafkaNet.Common
{
    /// <summary>
    /// Provides Big Endian conversion extensions to required types for the Kafka protocol.
    /// </summary>
    public static class Extensions
    {
        public static byte[] ToIntSizedBytes(this string value)
        {
            if (string.IsNullOrEmpty(value)) return (-1).ToBytes();

            return value.Length.ToBytes()
                        .Concat(value.ToBytes())
                        .ToArray();
        }

        public static byte[] ToInt16SizedBytes(this string value)
        {
            if (string.IsNullOrEmpty(value)) return (-1).ToBytes();

            return ((Int16)value.Length).ToBytes()
                        .Concat(value.ToBytes())
                        .ToArray();
        }

        public static byte[] ToInt32PrefixedBytes(this byte[] value)
        {
            if (value == null) return (-1).ToBytes();

            return value.Length.ToBytes()
                        .Concat(value)
                        .ToArray();
        }

        public static string ToUtf8String(this byte[] value)
        {
            if (value == null) return string.Empty;

            return Encoding.UTF8.GetString(value);
        }

        public static KafkaDataPayload ToPayload(this byte[] data)
        {
            return new KafkaDataPayload {Buffer = data};
        }

        public static byte[] ToBytes(this string value)
        {
            if (string.IsNullOrEmpty(value)) return (-1).ToBytes();

            //UTF8 is array of bytes, no endianness
            return Encoding.UTF8.GetBytes(value);
        }

        public static byte[] ToBytes(this Int16 value)
        {
            return BitConverter.GetBytes(value).Reverse().ToArray();
        }

        public static byte[] ToBytes(this Int32 value)
        {
            return BitConverter.GetBytes(value).Reverse().ToArray();
        }

        public static byte[] ToBytes(this Int64 value)
        {
            return BitConverter.GetBytes(value).Reverse().ToArray();
        }

        public static byte[] ToBytes(this float value)
        {
            return BitConverter.GetBytes(value).Reverse().ToArray();
        }

        public static byte[] ToBytes(this double value)
        {
            return BitConverter.GetBytes(value).Reverse().ToArray();
        }

        public static byte[] ToBytes(this char value)
        {
            return BitConverter.GetBytes(value).Reverse().ToArray();
        }

        public static byte[] ToBytes(this bool value)
        {
            return BitConverter.GetBytes(value).Reverse().ToArray();
        }

        public static Int32 ToInt32(this byte[] value)
        {
            return BitConverter.ToInt32(value.Reverse().ToArray(), 0);
        }

        /// <summary>
        /// Execute an await task while monitoring a given cancellation token.  Use with non-cancelable async operations.
        /// </summary>
        /// <remarks>
        /// This extension method will only cancel the await and not the actual IO operation.  The status of the IO opperation will still
        /// need to be considered after the operation is cancelled.
        /// See <see cref="http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx"/>
        /// </remarks>
        public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<bool>();

            var cancelRegistration = cancellationToken.Register(source => ((TaskCompletionSource<bool>) source).TrySetResult(true), tcs);

            using (cancelRegistration)
            {
                if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false))
                {
                    throw new OperationCanceledException(cancellationToken);
                }
            }

            return await task.ConfigureAwait(false);
        }

        /// <summary>
        /// Execute an await task while monitoring a given cancellation token.  Use with non-cancelable async operations.
        /// </summary>
        /// <remarks>
        /// This extension method will only cancel the await and not the actual IO operation.  The status of the IO opperation will still
        /// need to be considered after the operation is cancelled.
        /// See <see cref="http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx"/>
        /// </remarks>
        public static async Task WithCancellation(this Task task, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<bool>();

            var cancelRegistration = cancellationToken.Register(source => ((TaskCompletionSource<bool>)source).TrySetResult(true), tcs);

            using (cancelRegistration)
            {
                if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false))
                {
                    throw new OperationCanceledException(cancellationToken);
                }
            }
        }

        /// <summary>
        /// Returns true if <see cref="WaitHandle"/> before timeout expires./>
        /// </summary>
        /// <param name="handle">The handle whose signal triggers the task to be completed.</param>
        /// <param name="timeout">The timespan to wait before returning false</param>
        /// <returns>The task returns true if the handle is signaled before the timeout has expired.</returns>
        /// <remarks>
        /// Original code from: http://blog.nerdbank.net/2011/07/c-await-for-waithandle.html
        /// There is a (brief) time delay between when the handle is signaled and when the task is marked as completed.
        /// </remarks>
        public static Task<bool> WaitAsync(this WaitHandle handle, TimeSpan timeout)
        {
            Contract.Requires<ArgumentNullException>(handle != null);
            Contract.Ensures(Contract.Result<Task>() != null);

            var tcs = new TaskCompletionSource<bool>();
            var localVariableInitLock = new object();
            lock (localVariableInitLock)
            {
                RegisteredWaitHandle callbackHandle = null;
                callbackHandle = ThreadPool.RegisterWaitForSingleObject(
                    handle,
                    (state, timedOut) =>
                    {
                        tcs.TrySetResult(!timedOut);

                        // We take a lock here to make sure the outer method has completed setting the local variable callbackHandle.
                        lock (localVariableInitLock)
                        {
                            if (callbackHandle!= null) callbackHandle.Unregister(null);
                        }
                    },
                    state: null,
                    millisecondsTimeOutInterval: (long)timeout.TotalMilliseconds,
                    executeOnlyOnce: true);
            }

            return tcs.Task;
        }

        /// <summary>
        /// Mainly used for testing, allows waiting on a single task without throwing exceptions.
        /// </summary>
        public static void SafeWait(this Task source, TimeSpan timeout)
        {
            try
            {
                source.Wait(timeout);
            }
            catch
            {
                //ignore an exception that happens in this source
            }
        }

        /// <summary>
        /// Splits a collection into given batch sizes and returns as an enumerable of batches.
        /// </summary>
        public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> collection, int batchSize)
        {
            var nextbatch = new List<T>(batchSize);
            foreach (T item in collection)
            {
                nextbatch.Add(item);
                if (nextbatch.Count == batchSize)
                {
                    yield return nextbatch;
                    nextbatch = new List<T>(batchSize);
                }
            }
            if (nextbatch.Count > 0)
                yield return nextbatch;
        }

        /// <summary>
        /// Extracts a concrete exception out of a Continue with result.
        /// </summary>
        public static Exception ExtractException(this Task task)
        {
            if (task.IsFaulted == false) return null;
            if (task.Exception != null)
                return task.Exception.Flatten();

            return new ApplicationException("Unknown exception occured.");
        }
    }
}


text:
using System;

//Problem 7. Sum of 5 Numbers
//• Write a program that enters 5 numbers (given in a single line,
//separated by a space), calculates and prints their sum.

//Examples:
//numbers                     sum
//1 2 3 4 5                   15
//10 10 10 10 10              50
//1.5 3.14 8.2 -1 0           11.84

class Sum_of_5_Numbers
{
    static void Main()
    {
        Console.Write("Enter 5 numbers, separated by space character: ");
        string input = Console.ReadLine();
        string[] numbers = input.Split(' ');
        double sum = 0;

        for (int i = 0; i < numbers.Length; i++)
        {
            sum += int.Parse(numbers[i]);
        }

        Console.WriteLine("Sum is: " + sum);
    }
}


text:
Ananta
======

AWS Lambda packaging library and tools

Requirements
------------

- Python 2.7
- pip (to run commands)
- boto3 (to run commands)

Usage
-----

0. Install
^^^^^^^^^^

.. code-block:: sh

   $ pip install git+https://github.com/attakei/ananta.git
   $ pip install -e .

1. Decorate to lambda function
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

   from ananta import lamnda_function

   @lamnda_function(FunctionName='my_lambda_func', Role='arn:aws:::your:lambda:exec:role')
   def my_lambda_function(event, context):
       do_it()

2. Build zip package to use for AWS
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: bash

   $ ananta build
   $ ls -l
   ... package.zip ...

3. Deploy to AWS Lambda
^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: bash

   $ ananta upload -p package.zip


text:
<!DOCTYPE html>

	<title>GitHub LightHouse</title>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta http-equiv="Content-Type" content="text/html">
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0, maximum-scale=1, minimum-scale=1, minimal-ui">
	<meta name="msvalidate.01" content="29D6D5708B52ED032B2828FDE769F73F">
	<link rel="stylesheet" href="./public/css/app.css" media="screen">
</script>


text:
//******************************************************************************************************************************************************************************************//
// Public Domain                                                                                //
//                                                                                //
// Written by Peter O. in 2014.                                                                                //
//                                                                                //
// Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/                                                                                //
//                                                                                //
// If you like this, you should donate to Peter O. at: http://peteroupc.github.io/                                                                                //
//******************************************************************************************************************************************************************************************//
using System;
using System.Collections.Generic;
using System.Text;

namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor
{
  /// Includes options to control how CBOR objects are converted
  /// to JSON.
  public sealed class JSONOptions {
    /// Specifies how JSON numbers are converted to CBOR when
    /// decoding JSON.
    public enum ConversionMode {
       /// JSON numbers are decoded to CBOR using the full precision
       /// given in the JSON text. This may involve numbers being converted to
       /// arbitrary-precision integers or decimal numbers, where
       /// appropriate.
       Full,

       /// JSON numbers are decoded to CBOR as their closest-rounded
       /// approximation as 64-bit binary floating-point numbers. (In some
       /// cases, numbers extremely close to zero may underflow to positive or
       /// negative zero, and numbers of extremely large magnitude may
       /// overflow to infinity.).
       Double,

       /// A JSON number is decoded to CBOR either as a CBOR integer
       /// (major type 0 or 1) if the JSON number represents an integer at
       /// least -(2^53)+1 and less than 2^53, or as their closest-rounded
       /// approximation as 64-bit binary floating-point numbers otherwise.
       /// For example, the JSON number 0.99999999999999999999999999999999999
       /// is not an integer, so it's converted to its closest floating-point
       /// approximation, namely 1.0. (In some cases, numbers extremely close
       /// to zero may underflow to positive or negative zero, and numbers of
       /// extremely large magnitude may overflow to infinity.).
       IntOrFloat,

       /// A JSON number is decoded to CBOR either as a CBOR integer
       /// (major type 0 or 1) if the number's closest-rounded approximation
       /// as a 64-bit binary floating-point number represents an integer at
       /// least -(2^53)+1 and less than 2^53, or as that approximation
       /// otherwise. For example, the JSON number
       /// 0.99999999999999999999999999999999999 is the integer 1 when rounded
       /// to its closest floating-point approximation (1.0), so it's
       /// converted to the CBOR integer 1 (major type 0). (In some cases,
       /// numbers extremely close to zero may underflow to zero, and numbers
       /// of extremely large magnitude may overflow to infinity.).
       IntOrFloatFromDouble,

       /// JSON numbers are decoded to CBOR as their closest-rounded
       /// approximation to an IEEE 854 decimal128 value, using the rules for
       /// the EDecimal form of that approximation as given in the
       /// <c>CBORObject.FromObject(EDecimal)</c> method.
       Decimal128,
    }

    /// Initializes a new instance of the
    /// <see cref='PeterO.Cbor.JSONOptions'/> class with default
    /// options.
    public JSONOptions() : this(String.Empty) {
    }

    /// Initializes a new instance of the
    /// <see cref='PeterO.Cbor.JSONOptions'/> class with the given value
    /// for the Base64Padding option.
    /// <param name='base64Padding'>Whether padding is included when
    /// writing data in base64url or traditional base64 format to
    /// JSON.</param>
    [Obsolete("Use the string constructor instead.")]
    public JSONOptions(bool base64Padding)
      : this("base64Padding=" + (base64Padding ? "1" : "0")) {
    }

    /// Initializes a new instance of the
    /// <see cref='PeterO.Cbor.JSONOptions'/> class with the given values
    /// for the options.
    /// <param name='base64Padding'>Whether padding is included when
    /// writing data in base64url or traditional base64 format to
    /// JSON.</param>
    /// <param name='replaceSurrogates'>Whether surrogate code points not
    /// part of a surrogate pair (which consists of two consecutive
    /// <c>char</c> s forming one Unicode code point) are each replaced
    /// with a replacement character (U+FFFD). The default is false; an
    /// exception is thrown when such code points are encountered.</param>
#pragma warning disable CS0618
    [Obsolete("Use the string constructor instead.")]
    public JSONOptions(bool base64Padding, bool replaceSurrogates)
      : this("base64Padding=" + (base64Padding ? "1" : "0") +
           ";replacesurrogates=" + (replaceSurrogates ? "1" : "0")) {
    }

    /// Initializes a new instance of the
    /// <see cref='PeterO.Cbor.JSONOptions'/> class.
    /// <param name='paramString'>A string setting forth the options to
    /// use. This is a semicolon-separated list of options, each of which
    /// has a key and a value separated by an equal sign ("="). Whitespace
    /// and line separators are not allowed to appear between the
    /// semicolons or between the equal signs, nor may the string begin or
    /// end with whitespace. The string can be empty, but cannot be null.
    /// The following is an example of this parameter:
    /// <c>base64padding=false;replacesurrogates=true</c>. The key can be
    /// any one of the following where the letters can be any combination
    /// of basic upper-case and/or basic lower-case letters:
    /// <c>base64padding</c>, <c>replacesurrogates</c>,
    /// <c>allowduplicatekeys</c>, <c>preservenegativezero</c>,
    /// <c>numberconversion</c>. Other keys are ignored. (Keys are
    /// compared using a basic case-insensitive comparison, in which two
    /// strings are equal if they match after converting the basic
    /// upper-case letters A to Z (U+0041 to U+005A) in both strings to
    /// basic lower-case letters.) If two or more key/value pairs have
    /// equal keys (in a basic case-insensitive comparison), the value
    /// given for the last such key is used. The first four keys just given
    /// can have a value of <c>1</c>, <c>true</c>, <c>yes</c>, or
    /// <c>on</c> (where the letters can be any combination of basic
    /// upper-case and/or basic lower-case letters), which means true, and
    /// any other value meaning false. The last key,
    /// <c>numberconversion</c>, can have a value of any name given in the
    /// <c>JSONOptions.ConversionMode</c> enumeration (where the letters
    /// can be any combination of basic upper-case and/or basic lower-case
    /// letters), and any other value is unrecognized. (If the
    /// <c>numberconversion</c> key is not given, its value is treated as
    /// <c>full</c>. If that key is given, but has an unrecognized value,
    /// an exception is thrown.) For example, <c>base64padding=Yes</c> and
    /// <c>base64padding=1</c> both set the <c>Base64Padding</c> property
    /// to true, and <c>numberconversion=double</c> sets the
    /// <c>NumberConversion</c> property to <c>ConversionMode.Double</c>
    /// .</param>
    /// <exception cref='ArgumentNullException'>The parameter <paramref
    /// name='paramString'/> is null. In the future, this class may allow
    /// other keys to store other kinds of values, not just true or
    /// false.</exception>
    /// <exception cref='ArgumentException'>An unrecognized value for
    /// <c>numberconversion</c> was given.</exception>
    public JSONOptions(string paramString) {
      if (paramString == null) {
        throw new ArgumentNullException(nameof(paramString));
      }
      var parser = new OptionsParser(paramString);
      this.PreserveNegativeZero = parser.GetBoolean(
        "preservenegativezero",
        true);
      this.AllowDuplicateKeys = parser.GetBoolean(
        "allowduplicatekeys",
        false);
      this.Base64Padding = parser.GetBoolean("base64padding", true);
      this.ReplaceSurrogates = parser.GetBoolean(
        "replacesurrogates",
        false);
      this.NumberConversion = ToNumberConversion(parser.GetLCString(
        "numberconversion",
        null));
    }

    /// Gets the values of this options object's properties in
    /// text form.
    /// <returns>A text string containing the values of this options
    /// object's properties. The format of the string is the same as the
    /// one described in the String constructor for this class.</returns>
    public override string ToString() {
      return new StringBuilder()
        .Append("base64padding=").Append(this.Base64Padding ? "true" : "false")
        .Append(";replacesurrogates=")
        .Append(this.ReplaceSurrogates ? "true" : "false")
        .Append(this.PreserveNegativeZero ? "true" : "false")
        .Append(";numberconversion=").Append(this.FromNumberConversion())
        .Append(";allowduplicatekeys=")
        .Append(this.AllowDuplicateKeys ? "true" : "false")
        .ToString();
    }

    /// The default options for converting CBOR objects to
    /// JSON.
    public static readonly JSONOptions Default = new JSONOptions();

    /// Gets a value indicating whether the Base64Padding property
    /// is true. This property has no effect; in previous versions, this
    /// property meant that padding was written out when writing base64url
    /// or traditional base64 to JSON.
    /// <value>A value indicating whether the Base64Padding property is
    /// true.</value>
    [Obsolete("This property now has no effect. This library now includes " +
"\u0020necessary padding when writing traditional base64 to JSON and" +
"\u0020includes no padding when writing base64url to JSON, in " +
"\u0020accordance with the revision of the CBOR specification.")]
    public bool Base64Padding {
      get;
      private set;
    }

    private string FromNumberConversion() {
      ConversionMode kind = this.NumberConversion;
      if (kind == ConversionMode.Full) {
        return "full";
      }
      if (kind == ConversionMode.Double) {
        return "double";
      }
      if (kind == ConversionMode.Decimal128) {
        return "decimal128";
      }
      if (kind == ConversionMode.IntOrFloat) {
        return "intorfloat";
      }
      return (kind == ConversionMode.IntOrFloatFromDouble) ?
"intorfloatfromdouble" : "full";
    }

    private static ConversionMode ToNumberConversion(string str) {
      if (str != null) {
        if (str.Equals("full", StringComparison.Ordinal)) {
          return ConversionMode.Full;
        }
        if (str.Equals("double", StringComparison.Ordinal)) {
          return ConversionMode.Double;
        }
        if (str.Equals("decimal128", StringComparison.Ordinal)) {
          return ConversionMode.Decimal128;
        }
        if (str.Equals("intorfloat", StringComparison.Ordinal)) {
          return ConversionMode.IntOrFloat;
        }
        if (str.Equals("intorfloatfromdouble", StringComparison.Ordinal)) {
          return ConversionMode.IntOrFloatFromDouble;
        }
      } else {
        return ConversionMode.Full;
      }
      throw new ArgumentException("Unrecognized conversion mode");
    }

    /// Gets a value indicating whether the JSON decoder should
    /// preserve the distinction between positive zero and negative zero
    /// when the decoder decodes JSON to a floating-point number format
    /// that makes this distinction. For a value of <c>false</c>, if the
    /// result of parsing a JSON string would be a floating-point negative
    /// zero, that result is a positive zero instead. (Note that this
    /// property has no effect for conversion kind
    /// <c>IntOrFloatFromDouble</c>, where floating-point zeros are not
    /// possible.).
    /// <value>A value indicating whether to preserve the distinction
    /// between positive zero and negative zero when decoding JSON. The
    /// default is true.</value>
    public bool PreserveNegativeZero {
      get;
      private set;
    }

    /// Gets a value indicating how JSON numbers are decoded to
    /// CBOR.
    /// <value>A value indicating how JSON numbers are decoded to CBOR. The
    /// default is <c>ConversionMode.Full</c>.</value>
    public ConversionMode NumberConversion {
      get;
      private set;
    }

    /// Gets a value indicating whether to allow duplicate keys
    /// when reading JSON. Used only when decoding JSON. If this property
    /// is <c>true</c> and a JSON object has two or more values with the
    /// same key, the last value of that key set forth in the JSON object
    /// is taken.
    /// <value>A value indicating whether to allow duplicate keys when
    /// reading JSON. The default is false.</value>
    public bool AllowDuplicateKeys {
      get;
      private set;
    }

    /// Gets a value indicating whether surrogate code points not
    /// part of a surrogate pair (which consists of two consecutive
    /// <c>char</c> s forming one Unicode code point) are each replaced
    /// with a replacement character (U+FFFD). If false, an exception is
    /// thrown when such code points are encountered.
    /// <value>True, if surrogate code points not part of a surrogate pair
    /// are each replaced with a replacement character, or false if an
    /// exception is thrown when such code points are encountered. The
    /// default is false.</value>
    public bool ReplaceSurrogates {
      get;
      private set;
    }
  }
}


text:
/*
© 2017 Altavant Technologies Inc.
Web: http://www.altavant.com
*/

namespace Altavant.Fusion.Layouting
{
	using System;
	using System.Collections.Generic;
	using Fusion.Utils;
	using Fusion.Layouting.Data;

	internal class Selector : Element, ISelector
	{
		private class Features
		{
			private Selector _selector;
			private Width _width;
			private Height _height;
			private Alignment _alignment;
			private Borders _borders;
			private Spacings _spacings;
			private Paddings _paddings;
			private Background _background;
			private Foreground _foreground;
			private bool? _stretch;
			private Visibility? _visibility;
			private int? _selectedIndex;

			public Features(Selector selector)
			{
				_selector = selector;
			}

			public Width Width
			{
				get
				{
					if (_width == null)
						_width = (Width)_selector.GetFeature(Element.Feature.Width);

					return _width;
				}
			}

			public Height Height
			{
				get
				{
					if (_height == null)
						_height = (Height)_selector.GetFeature(Element.Feature.Height);

					return _height;
				}
			}

			public Alignment Alignment
			{
				get
				{
					if (_alignment == null)
						_alignment = (Alignment)_selector.GetFeature(Element.Feature.Alignment);

					return _alignment;
				}
			}

			public Borders Borders
			{
				get
				{
					if (_borders == null)
						_borders = (Borders)_selector.GetFeature(Element.Feature.Borders);

					return _borders;
				}
			}

			public Spacings Spacings
			{
				get
				{
					if (_spacings == null)
						_spacings = (Spacings)_selector.GetFeature(Element.Feature.Spacings);

					return _spacings;
				}
			}

			public Paddings Paddings
			{
				get
				{
					if (_paddings == null)
						_paddings = (Paddings)_selector.GetFeature(Element.Feature.Paddings);

					return _paddings;
				}
			}

			public Background Background
			{
				get
				{
					if (_background == null)
						_background = (Background)_selector.GetFeature(Element.Feature.Background);

					return _background;
				}
			}

			public Foreground Foreground
			{
				get
				{
					if (_foreground == null)
						_foreground = (Foreground)_selector.GetFeature(Element.Feature.Foreground);

					return _foreground;
				}
			}

			public bool Stretch
			{
				get
				{
					if (_stretch == null)
						_stretch = (bool?)_selector.GetFeature(Element.Feature.Stretch);

					return _stretch.Value;
				}
			}

			public Visibility Visibility
			{
				get
				{
					if (_visibility == null)
						_visibility = (Visibility?)_selector.GetFeature(Element.Feature.Visibility);

					return _visibility.Value;
				}
			}

			public int SelectedIndex
			{
				get
				{
					if (_selectedIndex == null)
						_selectedIndex = (int?)_selector.GetFeature(Element.Feature.SelectedIndex);

					return _selectedIndex.Value;
				}
			}

			public void Reset(Feature feature)
			{
				switch (feature)
				{
					case Feature.Width:
						_width = null;

						break;

					case Feature.Height:
						_height = null;

						break;

					case Feature.Alignment:
						_alignment = null;

						break;

					case Feature.Borders:
						_borders = null;

						break;

					case Feature.Spacings:
						_spacings = null;

						break;

					case Feature.Paddings:
						_paddings = null;

						break;

					case Feature.Background:
						_background = null;

						break;

					case Feature.Foreground:
						_foreground = null;

						break;

					case Feature.Stretch:
						_stretch = null;

						break;

					case Feature.Visibility:
						_visibility = null;

						break;

					case Feature.SelectedIndex:
						_selectedIndex = null;

						break;
				}
			}

			public void Reset()
			{
				_width = null;
				_height = null;
				_alignment = null;
				_borders = null;
				_spacings = null;
				_paddings = null;
				_background = null;
				_foreground = null;
				_stretch = null;
				_visibility = null;
				_selectedIndex = null;
			}
		}

		private Width _width;
		private Height _height;
		private Alignment _alignment;
		private Borders _borders;
		private Spacings _spacings;
		private Paddings _paddings;
		private Background _background;
		private Foreground _foreground;
		private bool _stretch;
		private Visibility _visibility;
		private ElementCollection _content;
		private List<string> _prefixes;
		private int _prefixIndex;
		private int _selectedIndex;
		private Features _features;
		private Dictionary<string, Element> _ids;

		public Selector(Layout layout, Element parent)
			: base(layout, parent)
		{
			_width = Width.Default;
			_height = Height.Default;
			_alignment = Alignment.Default;
			_borders = Borders.Default;
			_spacings = Spacings.Default;
			_paddings = Paddings.Default;
			_background = Background.Default;
			_foreground = Foreground.Default;
			_stretch = true;
			_visibility = Visibility.Visible;
			_content = new ElementCollection();
			_prefixes = new List<string>();
			_prefixIndex = -1;
			_selectedIndex = -1;
			_features = new Features(this);
		}

		public override ElementType Type
		{
			get
			{
				return ElementType.Selector;
			}
		}

		public Width Width
		{
			get
			{
				if (_width == Width.Default)
					_width = new Width();

				return _features.Width;
			}
			set
			{
				if (value != null)
					_width = value;
				else
					_width = Width.Default;

				_features.Reset(Feature.Width);
			}
		}

		public Height Height
		{
			get
			{
				if (_height == Height.Default)
					_height = new Height();

				return _features.Height;
			}
			set
			{
				if (value != null)
					_height = value;
				else
					_height = Height.Default;

				_features.Reset(Feature.Height);
			}
		}

		public Alignment Alignment
		{
			get
			{
				if (_alignment == Alignment.Default)
					_alignment = new Alignment();

				return _features.Alignment;
			}
			set
			{
				if (value != null)
					_alignment = value;
				else
					_alignment = Alignment.Default;

				_features.Reset(Feature.Alignment);
			}
		}

		public Borders Borders
		{
			get
			{
				if (_borders == Borders.Default)
					_borders = new Borders();

				return _features.Borders;
			}
			set
			{
				if (value != null)
					_borders = value;
				else
					_borders = Borders.Default;

				_features.Reset(Feature.Borders);
			}
		}

		public Spacings Spacings
		{
			get
			{
				if (_spacings == Spacings.Default)
					_spacings = new Spacings();

				return _features.Spacings;
			}
			set
			{
				if (value != null)
					_spacings = value;
				else
					_spacings = Spacings.Default;

				_features.Reset(Feature.Spacings);
			}
		}

		public Paddings Paddings
		{
			get
			{
				if (_paddings == Paddings.Default)
					_paddings = new Paddings();

				return _features.Paddings;
			}
			set
			{
				if (value != null)
					_paddings = value;
				else
					_paddings = Paddings.Default;

				_features.Reset(Feature.Paddings);
			}
		}

		public Background Background
		{
			get
			{
				if (_background == Background.Default)
					_background = new Background();

				return _features.Background;
			}
			set
			{
				if (value != null)
					_background = value;
				else
					_background = Background.Default;

				_features.Reset(Feature.Background);
			}
		}

		public Foreground Foreground
		{
			get
			{
				if (_foreground == Foreground.Default)
					_foreground = new Foreground();

				return _features.Foreground;
			}
			set
			{
				if (value != null)
					_foreground = value;
				else
					_foreground = Foreground.Default;

				_features.Reset(Feature.Foreground);
			}
		}

		public bool Stretch
		{
			get
			{
				return _features.Stretch;
			}
			set
			{
				_stretch = value;

				_features.Reset(Feature.Stretch);
			}
		}

		public Visibility Visibility
		{
			get
			{
				return _features.Visibility;
			}
			set
			{
				_visibility = value;

				_features.Reset(Feature.Visibility);
			}
		}

		public int SelectedIndex
		{
			get
			{
				return _features.SelectedIndex;
			}
			set
			{
				if (_selectedIndex != value)
				{
					if (_selectedIndex >= 0)
					{
						string prefix = _prefixes[_selectedIndex];

						RemoveIdsFromLayout(prefix);
					}

					_selectedIndex = value;

					if (_selectedIndex >= 0)
					{
						string prefix = _prefixes[_selectedIndex];

						AddIdsToLayout(prefix);
					}

					_features.Reset(Feature.SelectedIndex);
				}
			}
		}

		public ElementCollection Content
		{
			get
			{
				return _content;
			}
		}

		public Dictionary<string, Element> Ids
		{
			get
			{
				if (_ids == null)
					_ids = new Dictionary<string, Element>(10);

				return _ids;
			}
		}

		public IElement SelectedElement
		{
			get
			{
				return GetSelected();
			}
		}

		private Element GetSelected()
		{
			int selectedIndex = _features.SelectedIndex;

			if ((selectedIndex < 0) || (selectedIndex >= _content.Count))
				return null;

			return _content[selectedIndex];
		}

		public override object GetFeature(Feature feature)
		{
			switch (feature)
			{
				case Feature.Width:
					return DataBinding.Evaluate(this, "Width", DataContext, _width);

				case Feature.Height:
					return DataBinding.Evaluate(this, "Height", DataContext, _height);

				case Feature.Alignment:
					return DataBinding.Evaluate(this, "Alignment", DataContext, _alignment);

				case Feature.Borders:
					return DataBinding.Evaluate(this, "Borders", DataContext, _borders);

				case Feature.Spacings:
					return DataBinding.Evaluate(this, "Spacings", DataContext, _spacings);

				case Feature.Paddings:
					return DataBinding.Evaluate(this, "Paddings", DataContext, _paddings);

				case Feature.Background:
					return DataBinding.Evaluate(this, "Background", DataContext, _background);

				case Feature.Foreground:
					return DataBinding.Evaluate(this, "Foreground", DataContext, _foreground);

				case Feature.Stretch:
					return DataBinding.Evaluate(this, "Stretch", DataContext, _stretch);

				case Feature.Visibility:
					return DataBinding.Evaluate(this, "Visibility", DataContext, _visibility);

				case Feature.SelectedIndex:
					return DataBinding.Evaluate(this, "SelectedIndex", DataContext, _selectedIndex);
			}

			return null;
		}

		protected override void ResetFeatures()
		{
			_features.Reset();
		}

		public Text.ICaption AddCaption()
		{
			Text.Caption caption = new Text.Caption(_layout, this);

			AddElement(caption);

			return caption;
		}

		public Text.IText AddText()
		{
			Text.Text text = new Text.Text(_layout, this);

			AddElement(text);

			return text;
		}

		public IImage AddImage()
		{
			Image img = new Image(_layout, this);

			AddElement(img);

			return img;
		}

		public IImage AddImage(Fusion.Graphics.Image image)
		{
			Image img = new Image(_layout, this, image);

			AddElement(img);

			return img;
		}

		public IShape AddShape()
		{
			Shape shp = new Shape(_layout, this);

			AddElement(shp);

			return shp;
		}

		public IShape AddShape(Fusion.Shape.Shape shape)
		{
			Shape shp = new Shape(_layout, this, shape);

			AddElement(shp);

			return shp;
		}

		public IGroup AddGroup()
		{
			Group group = new Group(_layout, this);

			AddElement(group);

			return group;
		}

		public IContour AddContour()
		{
			Contour contour = new Contour(_layout, this);

			AddElement(contour);

			return contour;
		}

		public ISelector AddSelector()
		{
			Selector selector = new Selector(_layout, this);

			AddElement(selector);

			return selector;
		}

		public IRule AddRule()
		{
			Rule rule = new Rule(_layout, this);

			AddElement(rule);

			return rule;
		}

		public IStack AddStack()
		{
			Stack stack = new Stack(_layout, this);

			AddElement(stack);

			return stack;
		}

		public IBand AddBand()
		{
			Band band = new Band(_layout, this);

			AddElement(band);

			return band;
		}

		public Grid.IGrid AddGrid()
		{
			Grid.Grid grid = new Grid.Grid(_layout, this);

			AddElement(grid);

			return grid;
		}

		public Slot.ISlot AddSlot()
		{
			Slot.Slot slot = new Slot.Slot(_layout, this);

			AddElement(slot);

			return slot;
		}

		public List.IList AddList()
		{
			List.List list = new List.List(_layout, this);

			AddElement(list);

			return list;
		}

		public Repeater.IRepeater AddRepeater()
		{
			Repeater.Repeater repeater = new Repeater.Repeater(_layout, this);

			AddElement(repeater);

			return repeater;
		}

		public IPlace AddPlace()
		{
			Place place = new Place(_layout, this);

			AddElement(place);

			return place;
		}

		public ISite AddSite()
		{
			Site site = new Site(_layout, this);

			AddElement(site);

			return site;
		}

		public ICanvas AddCanvas()
		{
			Canvas canvas = new Canvas(_layout, this);

			AddElement(canvas);

			return canvas;
		}

		public IPlaceholder AddPlaceholder()
		{
			Placeholder placeholder = new Placeholder(_layout, this);

			AddElement(placeholder);

			return placeholder;
		}

		private void AddElement(Element element)
		{
			string prefix = PushPrefix();

			element.Prefix = prefix;

			_content.Add(element);

			PopPrefix();
		}

		private void RemoveElement(Element element)
		{
			_content.Remove(element);
		}

		private void AddIdsToLayout(string prefix)
		{
			if (_ids == null)
				return;

			Dictionary<string, Element> ids = _layout.Ids;

			foreach (var pair in _ids)
			{
				string id = pair.Key;

				if (id.StartsWith(prefix, StringComparison.Ordinal))
				{
					int pos = prefix.Length;

					id = id.Substring(pos, id.Length - pos);

					if (!ids.ContainsKey(id))
						ids.Add(id, pair.Value);
				}
			}
		}

		private void RemoveIdsFromLayout(string prefix)
		{
			if (_ids == null)
				return;

			Dictionary<string, Element> ids = _layout.Ids;

			foreach (var pair in _ids)
			{
				string id = pair.Key;

				if (id.StartsWith(prefix, StringComparison.Ordinal))
				{
					int pos = prefix.Length;

					id = id.Substring(pos, id.Length - pos);

					if (ids.ContainsKey(id))
						ids.Remove(id);
				}
			}
		}

		private string PushPrefix()
		{
			_prefixIndex++;

			string prefix = string.Format("{0}.", _prefixIndex);

			_prefixes.Add(prefix);

			_layout.Prefix.Push(prefix);

			return prefix;
		}

		private void PopPrefix()
		{
			_layout.Prefix.Pop();
		}

		public void Clear()
		{
			_content.Clear();

			if (_selectedIndex >= 0)
			{
				string prefix = _prefixes[_selectedIndex];

				RemoveIdsFromLayout(prefix);
			}

			_prefixes.Clear();

			if (_ids != null)
				_ids.Clear();
		}

		public void Remove(IElement element)
		{
			int index = _content.IndexOf((Element)element);

			if (index >= 0)
			{
				if (index == _selectedIndex)
				{
					string prefix = _prefixes[index];

					RemoveIdsFromLayout(prefix);
				}

				_prefixes.RemoveAt(index);

				RemoveElement((Element)element);
			}
		}

		public IElement Find(Predicate<IElement> match)
		{
			foreach (Element element in _content)
			{
				if (match(element))
					return element;
			}

			return null;
		}

		public IElement Find(Func<IElement, int, bool> match)
		{
			int i = 0;

			foreach (Element element in _content)
			{
				if (match(element, i))
					return element;

				i++;
			}

			return null;
		}

		public List<IElement> Select(Predicate<IElement> match)
		{
			System.Collections.Generic.List<IElement> list = new List<IElement>();

			Perform(match, element => list.Add(element));

			return list;
		}

		public List<IElement> Select(Func<IElement, int, bool> match)
		{
			System.Collections.Generic.List<IElement> list = new List<IElement>();

			Perform(match, element => list.Add(element));

			return list;
		}

		public void Perform(Predicate<IElement> match, Action<IElement> action)
		{
			foreach (Element element in _content)
			{
				if (match(element))
					action(element);
			}
		}

		public void Perform(Func<IElement, int, bool> match, Action<IElement> action)
		{
			int i = 0;

			foreach (Element element in _content)
			{
				if (match(element, i))
					action(element);

				i++;
			}
		}

		protected override void MeasureImpl(Fusion.Graphics.IGraphics graphics, Fusion.Graphics.Size size)
		{
			_features.Reset();

			float width = 0F;

			switch (_features.Width.Type)
			{
				case WidthType.Default:
					width = size.Width - _features.Spacings.Start - _features.Spacings.End;

					break;

				case WidthType.Direct:
					width = ((DirectWidth)_features.Width).Value;

					break;

				case WidthType.Relative:
					width = (size.Width - _features.Spacings.Start - _features.Spacings.End) * ((RelativeWidth)_features.Width).Value / 100F;

					width = Utils.Round(width, _layout.RenderingScale);

					Fusion.Graphics.Constraint constraint = ((RelativeWidth)_features.Width).Constraint;

					if (constraint != null)
						width = constraint.Apply(width);

					break;
			}

			if (width < 0F)
				width = 0F;

			float height = 0F;

			switch (_features.Height.Type)
			{
				case HeightType.Default:
					height = size.Height - _features.Spacings.Top - _features.Spacings.Bottom;

					break;

				case HeightType.Direct:
					height = ((DirectHeight)_features.Height).Value;

					break;

				case HeightType.Relative:
				{
					height = (size.Height - _features.Spacings.Top - _features.Spacings.Bottom) * ((RelativeHeight)_features.Height).Value / 100F;

					height = Utils.Round(height, _layout.RenderingScale);

					Fusion.Graphics.Constraint constraint = ((RelativeHeight)_features.Height).Constraint;

					if (constraint != null)
						height = constraint.Apply(height);

					break;
				}

				case HeightType.Aspect:
				{
					height = width * ((AspectHeight)_features.Height).Value / 100F;

					height = Utils.Round(height, _layout.RenderingScale);

					Fusion.Graphics.Constraint constraint = ((AspectHeight)_features.Height).Constraint;

					if (constraint != null)
						height = constraint.Apply(height);

					break;
				}
			}

			if (height < 0F)
				height = 0F;

			Fusion.Graphics.Rectangle scene = Element.MakeScene(0F, 0F, width, height, _features.Borders, _features.Paddings);

			float dh = height - scene.Height;

			Element.NormalizeScene(scene);

			Fusion.Graphics.Size sz = new Fusion.Graphics.Size(scene.Width, scene.Height);

			Element element = GetSelected();

			bool align = false;

			float h = 0F;

			if (element != null)
			{
				Visibility? visibility = (Visibility?)element.GetFeature(Element.Feature.Visibility);

				if ((visibility == null) || (visibility.Value != Visibility.Gone))
				{
					h = element.Measure(graphics, sz).Height;

					Spacings spacings = (Spacings)element.GetFeature(Feature.Spacings);

					if (spacings != null)
						h += spacings.Top + spacings.Bottom;

					align = true;
				}
			}

			h += dh;

			if (_features.Stretch && ((_features.Height.Type == HeightType.Default) || (height < h)))
				height = h;

			scene.Height = height - dh;

			_size = new Fusion.Graphics.Size(width, height);

			if (align)
				Element.Align(element, _features.Alignment, scene, _layout.RenderingScale);
		}

		public override void Draw(Fusion.Graphics.IGraphics graphics, Fusion.Graphics.Point offset, Fusion.Graphics.Zone zone)
		{
			if (_features.Visibility != Visibility.Visible)
				return;

			if ((_size.Width <= 0F) || (_size.Height <= 0F))
				return;

			_features.Reset();

			float x = _pos.X + offset.X;
			float y = _pos.Y + offset.Y;

			offset = new Fusion.Graphics.Point(x, y);

			graphics.SaveState();

			Element.ClipBounds(graphics, x, y, _size.Width, _size.Height, _features.Borders);

			Element.DrawBackground(this, graphics, x, y, _size.Width, _size.Height, _features.Background);

			Element element = GetSelected();

			if (element != null)
			{
				if ((zone == null) || zone.Intersects(y + element.Pos.Y, element.Size.Height))
				{
					Visibility? visibility = (Visibility?)element.GetFeature(Element.Feature.Visibility);

					if ((visibility == null) || (visibility.Value != Visibility.Gone))
					{
						if (element.Angle != 0F)
						{
							graphics.SaveState();

							graphics.Rotate(x + element.Pos.X, y + element.Pos.Y, element.Angle);

							element.Draw(graphics, offset, zone);

							graphics.RestoreState();
						}
						else
						{
							element.Draw(graphics, offset, zone);
						}
					}
				}
			}

			Element.DrawForeground(this, graphics, x, y, _size.Width, _size.Height, _features.Foreground);

			Element.DrawBorders(graphics, x, y, _size.Width, _size.Height, _features.Borders);

			graphics.RestoreState();
		}

		public override void Reset()
		{
			SelectedIndex = -1;

			foreach (Element element in _content)
			{
				element.Reset();
			}

			base.Reset();
		}

		public override void Release()
		{
			foreach (Element element in _content)
			{
				element.Release();
			}

			_width = null;
			_height = null;
			_alignment = null;
			_borders = null;
			_spacings = null;
			_paddings = null;
			_background = null;
			_foreground = null;
			_content = null;
			_features = null;

			base.Release();
		}

		public override Element Clone(Element parent)
		{
			Selector group = new Selector(_layout, parent);

			CloneImpl(group);

			return group;
		}

		protected override void CloneImpl(Element clone)
		{
			Selector selector = (Selector)clone;

			selector.Width = _width;
			selector.Height = _height;
			selector.Alignment = _alignment;
			selector.Borders = _borders;
			selector.Spacings = _spacings;
			selector.Paddings = _paddings;
			selector.Background = _background;
			selector.Foreground = _foreground;
			selector.Stretch = _stretch;
			selector.Visibility = _visibility;
			selector.SelectedIndex = _selectedIndex;

			foreach (Element element in _content)
			{
				selector.Content.Add(element.Clone(selector));
			}

			base.CloneImpl(clone);
		}
	}
}


text:
using System;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace LongPolling.Shared
{
    [AttributeUsage(AttributeTargets.Class)]
    public class WorkerThreadPoolBehaviorAttribute : Attribute, IContractBehavior
    {
        private static WorkerThreadPoolSynchronizer synchronizer = new WorkerThreadPoolSynchronizer();

        void IContractBehavior.AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        void IContractBehavior.ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
        }

        void IContractBehavior.ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        {
            dispatchRuntime.SynchronizationContext = synchronizer;
        }

        void IContractBehavior.Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
        {
        }

    }
}


text:
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _

from .utils import format_name, even_chunker
from libya_elections.abstract import AbstractTimestampModel
from libya_elections.libya_bread import ElectionFormatterMixin, RegistrationCenterFormatterMixin
from libya_elections.constants import MALE, FEMALE, UNISEX
from register.models import RegistrationCenter
from voting.models import Election

def station_distributor(roll):
    """Given a list of Citizens (voters at a center), evenly distribute them into stations by
    gender.

    Return a list of unsaved Station instances. Each station has the gender and number attributes
    populated. Station numbers start at 1 and are unique within the center.

    This is the factory function for Station instances. You should get all of your Stations from
    here rather than calling the Station ctor directly (test code excepted of course).

    The registrants (Citizens) in roll have a new field 'registrant_number' that's unique
    within the center. It also starts counting at 1.

    This function usually creates a unisex station if either gender has less than UNISEX_TRIGGER
    voters. See complex rules in inline comments. In unisex centers, men are listed first.
    """
    # group by gender
    grouped = {FEMALE: [], MALE: []}
    for voter in roll:
        grouped[voter.gender].append(voter)

    # stations contains 2 lists, each list contains Station instances
    stations = {FEMALE: [], MALE: []}
    # Counter for registrant number. Each registrant in a center gets a unique number; they do
    # *not* repeat across male/female/unisex stations.
    registrant_number = 1

    # chunk into stations
    for gender in (MALE, FEMALE):
        num_reg = len(grouped[gender])
        num_chunks = ((num_reg - 1) // settings.ROLLGEN_REGISTRANTS_PER_STATION_MAX) + 1
        # 550 -> 1, 551 -> 2

        for chunk in even_chunker(grouped[gender], num_chunks):
            station_roll = chunk
            for voter in station_roll:
                voter.registrant_number = registrant_number
                registrant_number += 1

            station = Station(gender=gender)
            station.roll = station_roll
            stations[gender].append(station)

    # Below a certain threshold of registrants at a station, we want to combine the last male &
    # female stations into a single unisex station. This sounds simple, but there's a lot of cases
    # to consider. Fortunately, the code above does a nice job distributing registrants and will not
    # create underused stations unless it has no other choice. (e.g. If there are 560 male
    # registrants, it creates two stations of 280 registrants each rather than one with 550 and
    # another with 10. Similarly, if there are only 40 male registrants, it smart enough to leave
    # them in one station rather than splitting them into two stations of 20 each.)
    #
    # You can see how it's chunking with this code:
    #   print('  males: ' + ','.join([str(len(station['roll'])) for station in stations[MALE]]))
    #   print('females: ' + ','.join([str(len(station['roll'])) for station in stations[FEMALE]]))
    #
    # Given the above, there are 9 cases to consider --
    #
    #    1. n_males registered == 0         AND n_females registered == 0
    #    2. n_males registered == 0         AND n_females registered > 0 and < 25
    #    3. n_males registered == 0         AND n_females registered >= 25
    #    4. n_males registered > 0 and < 25 AND n_females registered == 0
    #    5. n_males registered > 0 and < 25 AND n_females registered > 0 and < 25
    #    6. n_males registered > 0 and < 25 AND n_females registered >= 25
    #    7. n_males registered >= 25        AND n_females registered == 0
    #    8. n_males registered >= 25        AND n_females registered > 0 and < 25
    #    9. n_males registered >= 25        AND n_females registered >= 25
    #
    # Fortunately, in the first case we can't create a unisex station (no voters at all, which I'm
    # not even sure this code will ever see), and in any case where there are no voters of a given
    # gender (cases 1, 2, 3, 4, and 7), then creating a unisex station doesn't consolidate stations
    # anyway, so there's no point to doing it.
    # Case 9 is the "normal" case that doesn't require creation of a unisex station.
    # Therefore, only cases 5, 6, and 8 require a unisex station.

    # Note that the requirements document Polling Planning Rules eng 20140526 0900.docx says,
    # "There may not be more than one uni-sex station per centre."
    unisex_station = None

    if (not stations[MALE]) or (not stations[FEMALE]):
        # Cases 1, 2, 3, 4, and 7 from above ==> nothing to do.
        pass
    else:
        n_males = len(grouped[MALE])
        n_females = len(grouped[FEMALE])

        if (n_males < settings.ROLLGEN_UNISEX_TRIGGER) or \
           (n_females < settings.ROLLGEN_UNISEX_TRIGGER):
            # Cases 5, 6, and 8 from above. One or both of these is too small and will have to be
            # combined with the other to create a unisex station.
            # There's a potential small bug here where the two stations being combined may create
            # a unisex station that has > REGISTRANTS_PER_STATION_MAX voters. We've decided to let
            # it slide on the grounds that (a) it's not likely to happen, (b) the consequences are
            # small if it does happen, and (c) it's difficult to fix.
            # ref: https://github.com/hnec-vr/roll-generator/issues/98
            if n_females < settings.ROLLGEN_UNISEX_TRIGGER:
                # This handles both cases 5 and 8.
                big_gender = MALE
                little_gender = FEMALE
            else:
                # Case 6.
                big_gender = FEMALE
                little_gender = MALE

            roll_men = stations[MALE][-1].roll
            roll_women = stations[FEMALE][-1].roll
            unisex_station = stations[big_gender].pop(-1)
            unisex_station.gender = UNISEX
            # In the roll of a unisex station, "Men will always be listed first."
            # ref: Polling Planning Rules eng 20140118 2020
            unisex_station.roll = roll_men + roll_women
            stations[little_gender] = []
        # else:
            # Case 9 ==> nothing to do.

    stations = stations[MALE] + stations[FEMALE]

    if unisex_station:
        stations.append(unisex_station)

    # Assign a unique number to each station. Station numbers do *not* duplicate between
    # male/female/unisex stations.
    for station_number, station in enumerate(stations):
        station.number = station_number + 1

    return stations

class Station(ElectionFormatterMixin, RegistrationCenterFormatterMixin, AbstractTimestampModel):
    """A voting station. These should only be created through station_distributor().

    Each station has a roll attribute that's not stored in the database. The roll is a list of
    people assigned to vote at that station. Populating the roll attribute triggers populating
    other attributes, specifically: n_registrants, first_voter_name, first_voter_number,
    last_voter_name, and last_voter_number.

    The only attributes that users of this class should populate are election, center, number,
    gender, and roll. (The other attributes would be read-only properties if Django models allowed
    such a thing.) And in practice, number, gender and roll are populated by the
    function station_distributor() (q.v.).
    """
    election = models.ForeignKey(Election, verbose_name=_('election'),
                                 on_delete=models.CASCADE)
    center = models.ForeignKey(RegistrationCenter, verbose_name=_('registration center'),
                               on_delete=models.CASCADE)
    number = models.PositiveSmallIntegerField(_('number'))
    gender = models.PositiveSmallIntegerField(_('gender'))
    n_registrants = models.IntegerField(_('number of registrants'))
    first_voter_name = models.CharField(_('first voter name'), max_length=255)
    first_voter_number = models.IntegerField(_('first voter number'))
    last_voter_name = models.CharField(_('last voter name'), max_length=255)
    last_voter_number = models.IntegerField(_('last voter number'))

    # Voter roll is accessed through a property and is not stored in the database.
    _roll = []

    @property
    def roll(self):
        return self._roll

    @roll.setter
    def roll(self, voter_roll):
        """Sets voter roll. See class docstring for details."""
        self._roll = voter_roll
        self.n_registrants = len(voter_roll)
        self.first_voter_name = format_name(self.first_voter)
        self.first_voter_number = self.first_voter.registrant_number
        self.last_voter_name = format_name(self.last_voter)
        self.last_voter_number = self.last_voter.registrant_number

    @property
    def first_voter(self):
        return self._roll[0] if self._roll else None

    @property
    def last_voter(self):
        return self._roll[-1] if self._roll else None

    class Meta:
        verbose_name = _("station")
        verbose_name_plural = _("stations")
        ordering = ('center__center_id', 'number', )
        unique_together = ('election', 'center', 'number', )
        permissions = [
            ("browse_station", "Can list stations"),
            ("read_station", "Can read a station"),
        ]

    def __str__(self):
        # While debugging, it's possible that the center might not yet be set when this is invoked.
        center_id = self.center.center_id if self.center_id else "[None]"
        return "Center {}, Station {}".format(center_id, self.number)


text:
package lee;

import org.hibernate.Transaction;
import org.hibernate.Session;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import org.crazyit.app.domain.*;

public class HqlQuery
{
	public static void main(String[] args)throws Exception
	{
		HqlQuery mgr = new HqlQuery();
		mgr.findByNamedQuery();
		HibernateUtil.sessionFactory.close();
	}
private void findByNamedQuery()
	throws Exception
{
	//´ò¿ªHibernateµÄSessionºÍÊÂÎñ
	Session sess = HibernateUtil.currentSession();
	Transaction tx = sess.beginTransaction();
	System.out.println("===Ö´ÐÐÃüÃû²éѯ===");
	//Ö´ÐÐÃüÃû²éѯ
	List pl = sess.getNamedQuery("myNamedQuery")
		//¸ù¾ÝHQLÓï¾äÀï²ÎÊýË÷ÒýΪ²ÎÊý¸³Öµ
		.setInteger(0 , 20)
		.list();
	//µü´úÊä³ö²éѯµÃµ½µÄÿ¸öPerson¶ÔÏó
	for (Iterator pit = pl.iterator() ; pit.hasNext(); )
	{
		Person p = ( Person )pit.next();
		System.out.println(p.getName());
	}
	//Ìá½»ÊÂÎñ¡¢¹Ø±ÕSession
	tx.commit();
	HibernateUtil.closeSession();
}
}


text:
namespace ui {

TextInputState::TextInputState()
    : type(TEXT_INPUT_TYPE_NONE),
      flags(TEXT_INPUT_FLAG_NONE),
      selection_start(0),
      selection_end(0),
      composition_start(0),
      composition_end(0),
      can_compose_inline(false) {}

TextInputState::TextInputState(TextInputType type,
                               int flags,
                               const std::string& text,
                               int selection_start,
                               int selection_end,
                               int composition_start,
                               int composition_end,
                               bool can_compose_inline)
    : type(type),
      flags(flags),
      text(text),
      selection_start(selection_start),
      selection_end(selection_end),
      composition_start(composition_start),
      composition_end(composition_end),
      can_compose_inline(can_compose_inline) {}

TextInputState::TextInputState(const TextInputState& other) = default;

bool TextInputState::operator==(const TextInputState& other) const {
  return type == other.type &&
         flags == other.flags &&
         text == other.text &&
         selection_start == other.selection_start &&
         selection_end == other.selection_end &&
         composition_start == other.composition_start &&
         composition_end == other.composition_end &&
         can_compose_inline == other.can_compose_inline;
}

}  // namespace ui


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FSL.eBook.RWP.DesignPatterns.FlyweightChapter
{
    public class FlyweightController : Controller
    {
        public ActionResult Index(int id = 100)
        {
            int[] tagsIds = new[] { 10, 20, 30, 50, 100, 150, 200, 250, 260, 270, 300, 350, 400, 500, 600, 700, 1000, 1050, 1200 };
            var factory = new ControlFactory();
            var rnd = new Random();
            int item = 0;
            while (item <= id)
            {
                Control control = null;
                var tag = Tags.Text;
                int tagId = tagsIds[rnd.Next(0, tagsIds.Length)];
                if (tagId >= 0 && tagId <= 100)
                {
                    tag = Tags.Button;
                }
                if (tagId >= 101 && tagId <= 300)
                {
                    tag = Tags.Radio;
                }
                control = factory.GetControl(tag);
                item++;
            }

            return Content("Flyweight");
        }
    }
}


text:
package org.terracotta.statistics;

import java.io.Serializable;
import java.time.Instant;

/**
 * @author cdennis
 */
public class Sample<T extends Serializable> implements Serializable {

  private static final long serialVersionUID = 1L;

  private final long timestamp;
  private final T sample;

  public Sample(long timestamp, T sample) {
    this.sample = sample;
    this.timestamp = timestamp;
  }

  public T getSample() {
    return sample;
  }

  /**
   * @return The sample time in milliseconds
   */
  public long getTimestamp() {
    return timestamp;
  }

  @Override
  public String toString() {
    return getSample() + " @ " + Instant.ofEpochMilli(getTimestamp());
  }

}


text:
rawr-website
============

Final project for Comp 553

This is a website built using the WAMP arcitechture as the final project for Comp-553 (WWW class).

Basic template is up. Follow similar format of what I've done for adding any additonal static pages. I've just come up with a few off the top of my head. I'm not attached to them :) Feel free to move the order of the links around.

Please make a new branch for your work off master so we don't lose any progress!

git checkout -b 'branchname'

^^ use this to checkout out a new branch replacing 'branchname' with some text, no "" necessary!

I find the git bash is most useful for this since we're not on macs -_-

Make sure to have the WAMP server installed and place the files under the www directory.

Helpful commands:

git pull
--use this to update your branch, so if two people are working on same branch and one does a commit the other needs to do a pull to get the new changes.

git status
--checks what files you've modified, deleted, added

git branch
--gives you a list of branches you've downloaded

git checkout 'branchname'
--use this to checkout someone elses branch, replacing 'branchname' entirely with the branch you want, as well as to switch branches. to create a new branch use this option: -b ( git checkout -b "the_name_of_the_branch_you_want" ) NO SPACES or you'll want to die

git add 'filename'
--use this after running at git status to add one file at a time to be commited. use: git add -A, to add all files at once

git commit -m "your message"
--use this after adding all the files you want committed. This just commits to your local machine. Make sure to run the command below to push to our github repo!. Here the "" are needed. Please provide a brief meaningful message of what you updated.

git push origin head
--use this after commiting to push all your changes to the repo!

This is the gist of it. I have a lot more knowledge if you get stuck but this should be good for now :D


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
DobCollection
</TITLE>

<META NAME="date" CONTENT="2013-04-05">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

se.js.jesdob

Class DobCollection

java.lang.Object
  se.js.jesdob.DobCollection

All Implemented Interfaces:
java.lang.Iterable<IDob>, IDobCollection

public class DobCollection
extends java.lang.Object
implements IDobCollection, java.lang.Iterable<IDob>

A DobCollection is a collection containing one or more IDobs (dynamic objects).
 It is possible to add objects to a collection, and to remove objects from
 a collection.

 It is possible to get IDobs from the collection, by index, or by searching a specific attribute and value.
 You can also filter the DobCollection by using a IDobQuery-object.
 This will make the IDob-object act more like a database.

 DobCollections can be exported to text as json-format, xml-format or dob-format. They can
 then be saved to files and read as dynamic objects when they are needed.

Constructor Summary

DobCollection()

          Parameterless constructor.

DobCollection(IDob... dobs)

          Constructor.

DobCollection(java.lang.String... dobsData)

          Constructor.

Method Summary

 IDobCollection
add(IDob... dobs)

          Adds one or more dobs to the dob collection.

 IDobCollection
add(IDobCollection dobCollection)

          Adds the content of a dob collection to a dob collection.

 IDobCollection
add(java.lang.String... dobsData)

          Adds one or more dobs from dob data-strings.

 IDobCollection
clear()

          Removes all data from the DobCollection

 IDobCollection
filter(IDobQuery query)

          Applies a filter on this DobCollection and returns the filtered version.

 IDob
get(int index)

          Returns a Dob from a specific index in the collection.

 IDob
get(java.lang.String attribute,
    java.lang.String value)

          Returns the first dob in the collection where a specific attribute has
 a specific value.

 IDobCollection
getAll(java.lang.String attribute,
       java.lang.String value)

          Returns a new DobCollection containing all Dobs which have a particular
 value for a particular attribute.

 boolean
isEmpty()

          Returns true or false, depending on if the collection is empty or not.

 java.util.Iterator<IDob>
iterator()

          Returns an iterator used for iterating Dobs in the DobCollection.

 boolean
remove(java.lang.String attr,
       java.lang.String value)

          Removes all dobs where a specific attribute has a specific value.

 int
size()

          Returns the number of dobs in the collection.

 java.lang.String
toDob()

          Returns the content of the collection, in dob-format.

 java.lang.String
toJson()

          Returns the content of the collection, in json-format.

 java.util.List<IDob>
toList()

          Returns a new list with dobs from the collection.

 java.lang.String
toXml()

          Returns the content of the collection, in xml-format.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DobCollection

public DobCollection()

Parameterless constructor.

DobCollection

public DobCollection(IDob... dobs)

Constructor. Creates a new collection filled with a list of attached dobs.

Parameters:
dobs - The dobs we want to fill our collection with.

DobCollection

public DobCollection(java.lang.String... dobsData)

Constructor. Creates a new collection filled with dobs created from
 string list with dob data.

Parameters:
dobsData - This dob data will be converted to dob, and added to the new collection.

Method Detail

add

public IDobCollection add(IDob... dobs)

Adds one or more dobs to the dob collection.

Specified by:
add in interface IDobCollection

Parameters:
dobs - The dobs that should be added to the collection.

Returns:
The DobCollection object, to enable chaining.

add

public IDobCollection add(IDobCollection dobCollection)

Adds the content of a dob collection to a dob collection.

Specified by:
add in interface IDobCollection

Parameters:
dobCollection - The DobCollection we want to add the content from.

Returns:
The DobCollection object, to enable chaining.

add

public IDobCollection add(java.lang.String... dobsData)

Adds one or more dobs from dob data-strings. The dob data-strings will
 be converted to dobs and added to the collection.

Specified by:
add in interface IDobCollection

Parameters:
dobsData - The dob data we want to convert to dobs and add to the collection.

Returns:
The DobCollection object, to enable chaining.

remove

public boolean remove(java.lang.String attr,
                      java.lang.String value)

Removes all dobs where a specific attribute has a specific value. Returns
 true if any objects were removed, and false if no objects were removed.

Specified by:
remove in interface IDobCollection

Parameters:
attr - The attribute we want to check for.
value - The value we want to check for.

Returns:
If any object were removed from the collection.

get

public IDob get(int index)

Returns a Dob from a specific index in the collection.

Specified by:
get in interface IDobCollection

Parameters:
index - A specific Dob index of the collection.

Returns:
The Dob from the specific index in the collection.

size

public int size()

Returns the number of dobs in the collection.

Specified by:
size in interface IDobCollection

Returns:
The number of dobs in the collection.

isEmpty

public boolean isEmpty()

Returns true or false, depending on if the collection is empty or not.

Specified by:
isEmpty in interface IDobCollection

Returns:
True or false, depending on if the collection is empty or not.

toList

public java.util.List<IDob> toList()

Returns a new list with dobs from the collection.

Specified by:
toList in interface IDobCollection

Returns:
A new list with dobs from the collection.

toJson

public java.lang.String toJson()

Returns the content of the collection, in json-format.

Specified by:
toJson in interface IDobCollection

Returns:
The content of the collection, in json-format.

toDob

public java.lang.String toDob()

Returns the content of the collection, in dob-format.

Specified by:
toDob in interface IDobCollection

Returns:
The content of the collection, in dob-format.

toXml

public java.lang.String toXml()

Returns the content of the collection, in xml-format.

Specified by:
toXml in interface IDobCollection

Returns:
The content of the collection, in xml-format.

get

public IDob get(java.lang.String attribute,
                java.lang.String value)

Returns the first dob in the collection where a specific attribute has
 a specific value. If no such object exists in the collection, this method
 will return null.

Specified by:
get in interface IDobCollection

Parameters:
attribute - The specific attribute.
value - The specific value.

Returns:
A dob object where the specified attribute matches the specified value.

getAll

public IDobCollection getAll(java.lang.String attribute,
                             java.lang.String value)

Returns a new DobCollection containing all Dobs which have a particular
 value for a particular attribute. If no such Dobs exists, an empty collection
 will be returned.

Specified by:
getAll in interface IDobCollection

Parameters:
attribute - The specific attribute.
value - The specific value.

Returns:
A new Dob collection containing all Dobs matching the search criterias.

filter

public IDobCollection filter(IDobQuery query)

Applies a filter on this DobCollection and returns the filtered version.
 The filtering is done is by the applied IDobQuery object.

Specified by:
filter in interface IDobCollection

Parameters:
query - The query we want to use for filtering the collection.

Returns:
The new collection, produced by filtering the original collection.

clear

public IDobCollection clear()

Removes all data from the DobCollection

Specified by:
clear in interface IDobCollection

Returns:
The DobCollection, to enable chaining.

iterator

public java.util.Iterator<IDob> iterator()

Returns an iterator used for iterating Dobs in the DobCollection.

Specified by:
iterator in interface java.lang.Iterable<IDob>

Returns:
a new iterator used for iterating Dobs in the DobCollection.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD