text:
NSString* kDefaultCSSPath = @"extThree20CSSStyle.bundle/stylesheets/default.css";

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation TTDefaultCSSStyleSheet

@synthesize styleSheet = _styleSheet;

///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)init {
	self = [super init];
  if (self) {
    [[NSNotificationCenter defaultCenter]
     addObserver: self
     selector: @selector(didReceiveMemoryWarning:)
     name: UIApplicationDidReceiveMemoryWarningNotification
     object: nil];

    _styleSheet = [[TTCSSStyleSheet alloc] init];

    BOOL loadedSuccessfully = [_styleSheet
                               loadFromFilename:TTPathForBundleResource(kDefaultCSSPath)];

    // Test if load succesfully.
    if (!loadedSuccessfully) {
        [NSException raise:NSInternalInconsistencyException
                    format:@"%@ fail to load the Default CSS file. "
                           @"It's very likely that you forgot to add the extThree20CSSStyle.bundle "
                           @"to your project. If you didn't, ensure that it's being copied in "
                           @"the 'Copy Bundle Resources' phase.", NSStringFromClass([self class])];
        return nil;
    }
  }

  return self;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc {
  [[NSNotificationCenter defaultCenter]
   removeObserver: self
   name: UIApplicationDidReceiveMemoryWarningNotification
   object: nil];

  TT_RELEASE_SAFELY(_styleSheet);
  TT_RELEASE_SAFELY(_cachedCssFiles);

  [super dealloc];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark NSNotifications

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didReceiveMemoryWarning:(void*)object {
  [self freeMemory];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)freeMemory {
  [_styleSheet freeMemory];

  [super freeMemory];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Public

///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)addStyleSheetFromDisk:(NSString*)filename ignoreCache:(BOOL)cache {

  // Check if this file is already cached, also respect if should ignore the cache.
  if (!cache && [_cachedCssFiles containsObject:filename]) {
    TTDWARNING( @"'%@' is already loaded and cached. Ignoring...", filename );
    return NO;
  }

  TTCSSStyleSheet* styleSheet = [[TTCSSStyleSheet alloc] init];

  BOOL loadedSuccessfully = [styleSheet loadFromFilename:filename];

  [_styleSheet addStyleSheet:styleSheet];

  TT_RELEASE_SAFELY(styleSheet);

  ///////////// //////// //////// //////// ////////
  // Init cache, if needed.
  if ( !_cachedCssFiles )
    _cachedCssFiles = [NSMutableSet new];

  // Cache if Loaded Successfully.
  if ( loadedSuccessfully )
    [_cachedCssFiles addObject:filename];

  return loadedSuccessfully;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)addStyleSheetFromDisk:(NSString*)filename {
  return [self addStyleSheetFromDisk:filename ignoreCache:NO];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
+ (TTDefaultCSSStyleSheet*)globalCSSStyleSheet {
  TTDASSERT([[TTStyleSheet globalStyleSheet] isKindOfClass:[TTDefaultStyleSheet class]]);
  return (TTDefaultCSSStyleSheet*)[TTStyleSheet globalStyleSheet];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
-(void)applyCssFromSelector:(NSString*)selectorName toObject:(id<TTCSSApplyProtocol>)anObject {
	// Assert that the conforms with the protocol.
	if ( ![(id)anObject conformsToProtocol:@protocol(TTCSSApplyProtocol)] )
		[NSException raise:NSInternalInconsistencyException
                format:@"'%@' must conform with the 'TTCSSApplyProtocol' protocol",
     NSStringFromClass([(id)anObject class]) ];

	// Apply retrieved rules to the object.
	[anObject applyCssRules:[self css:selectorName]];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Common styles

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)textColor {
  return [_styleSheet colorWithCssSelector: @"body"
                                  forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)highlightedTextColor {
  return [_styleSheet colorWithCssSelector: @"body"
                                  forState: UIControlStateHighlighted];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIFont*)font {
  return [_styleSheet fontWithCssSelector: @"body"
                                 forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)backgroundColor {
  return [_styleSheet backgroundColorWithCssSelector: @"body"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)navigationBarTintColor {
  return [_styleSheet backgroundColorWithCssSelector: @"navigationBar"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)toolbarTintColor {
  return [_styleSheet backgroundColorWithCssSelector: @"toolbar"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)searchBarTintColor {
  return [_styleSheet backgroundColorWithCssSelector: @"searchbar"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Tables

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)tablePlainBackgroundColor {
  return [_styleSheet backgroundColorWithCssSelector: @"table"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)tableGroupedBackgroundColor {
  return [_styleSheet backgroundColorWithCssSelector: @"groupedTable"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)searchTableBackgroundColor {
  return [_styleSheet backgroundColorWithCssSelector: @"searchTable"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)searchTableSeparatorColor {
  return [_styleSheet backgroundColorWithCssSelector: @"searchTableSeparator"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Table Items

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)linkTextColor {
  return [_styleSheet colorWithCssSelector: @".tableItemLink"
                                  forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)timestampTextColor {
  return [_styleSheet colorWithCssSelector: @".tableItemTimestamp"
                                  forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)moreLinkTextColor {
  return [_styleSheet colorWithCssSelector: @".moreButton"
                                  forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Table Headers

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)tableHeaderTextColor {
  return [_styleSheet colorWithCssSelector: @".tableHeader"
                                  forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)tableHeaderShadowColor {
  return [_styleSheet textShadowColorWithCssSelector: @".tableHeader"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGSize)tableHeaderShadowOffset {
  return [_styleSheet textShadowOffsetWithCssSelector: @".tableHeader"
                                             forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)tableHeaderTintColor {
  return [_styleSheet backgroundColorWithCssSelector: @".tableHeader"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Photo Captions

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)photoCaptionTextColor {
  return [_styleSheet colorWithCssSelector: @".photoCaption"
                                  forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)photoCaptionTextShadowColor {
  return [_styleSheet textShadowColorWithCssSelector: @".photoCaption"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGSize)photoCaptionTextShadowOffset {
  return [_styleSheet textShadowOffsetWithCssSelector: @".photoCaption"
                                             forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark DragRefreshHeader

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIFont*)tableRefreshHeaderLastUpdatedFont {
  return [_styleSheet fontWithCssSelector: @".dragRefreshHeaderLastUpdated"
                                 forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIFont*)tableRefreshHeaderStatusFont {
  return [_styleSheet fontWithCssSelector: @".dragRefreshHeaderStatusFont"
                                 forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)tableRefreshHeaderBackgroundColor {
  return [_styleSheet backgroundColorWithCssSelector: @".dragRefreshHeader"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)tableRefreshHeaderTextColor {
  return [_styleSheet colorWithCssSelector: @".dragRefreshHeader"
                                  forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIColor*)tableRefreshHeaderTextShadowColor {
  return [_styleSheet textShadowColorWithCssSelector: @".dragRefreshHeader"
                                            forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGSize)tableRefreshHeaderTextShadowOffset {
  return [_styleSheet textShadowOffsetWithCssSelector: @".dragRefreshHeader"
                                             forState: UIControlStateNormal];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
-(TTCSSRuleSet*)css:(NSString*)selector {
	return [_styleSheet css:selector];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
-(TTCSSRuleSet*)css:(NSString*)selectorName forState:(UIControlState)state {
	return [_styleSheet css:selectorName forState:state];
}

@end


text:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingFile"
			      type="log4net.Appender.FileAppender">
    <file value="..\logs\sample.publisher.log" />
    <appendToFile value="false" />

    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5p %d{hh:mm:ss} %message%newline" />
    </layout>
  </appender>

  <!-- Set root logger level to DEBUG and its only appender to Console -->
  <root>
    <level value="INFO" />
    <appender-ref ref="RollingFile" />
  </root>

  <!-- Standard MassTransit Logging Settings -->
  <logger name="MassTransit">
    <level value="INFO" />
  </logger>
</log4net>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>Pelias + Leaflet geocoding plugin</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-capable" content="yes">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.3/leaflet.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet-geocoder-mapzen/1.9.4/leaflet-geocoder-mapzen.css">

Your browser cannot display the map on this page. Try this one instead.


text:
package com.marvinformatics.formatter.java;

import com.marvinformatics.formatter.AbstractFormatterTest;

/**
 * @author marvin.froeder
 */
public class JavaFormatterTest extends AbstractFormatterTest {

	public void testDoFormatFile() throws Exception {
		doTestFormat(new JavaFormatter(), "AnyClass.java",
				"c178cea8d43d16a4741dffc9be4e1b0a2931e897");
	}

}


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

namespace LumiSoft.Net.IMAP.Server
{
    /// <summary>
    /// IMAP message info.
    /// </summary>
    public class IMAP_Message
    {
        private IMAP_MessageCollection m_pOwner       = null;
        private string                 m_ID           = "";
        private long                   m_UID          = 0;
        private DateTime               m_InternalDate = DateTime.Now;
        private long                   m_Size         = 0;
        private IMAP_MessageFlags      m_Flags        = IMAP_MessageFlags.None;

        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="onwer">Owner collection.</param>
        /// <param name="id">Message ID.</param>
        /// <param name="uid">Message IMAP UID value.</param>
        /// <param name="internalDate">Message store date.</param>
        /// <param name="size">Message size in bytes.</param>
        /// <param name="flags">Message flags.</param>
        internal IMAP_Message(IMAP_MessageCollection onwer,string id,long uid,DateTime internalDate,long size,IMAP_MessageFlags flags)
        {
            m_pOwner       = onwer;
            m_ID           = id;
            m_UID          = uid;
            m_InternalDate = internalDate;
            m_Size         = size;
            m_Flags        = flags;
        }

        #region method SetFlags

        /// <summary>
        /// Sets message flags.
        /// </summary>
        /// <param name="flags">Message flags.</param>
        internal void SetFlags(IMAP_MessageFlags flags)
        {
            m_Flags = flags;
        }

        #endregion

        #region Properties Implementation

        /// <summary>
        /// Gets message 1 based sequence number in the collection. This property is slow, use with care, never use in big for loops !
        /// </summary>
        public int SequenceNo
        {
            get{ return m_pOwner.IndexOf(this) + 1; }
        }

        /// <summary>
        /// Gets message ID.
        /// </summary>
        public string ID
        {
            get{ return m_ID; }
        }

        /// <summary>
        /// Gets message IMAP UID value.
        /// </summary>
        public long UID
        {
            get{ return m_UID; }
        }

        /// <summary>
        /// Gets message store date.
        /// </summary>
        public DateTime InternalDate
        {
            get{ return m_InternalDate; }
        }

        /// <summary>
        /// Gets message size in bytes.
        /// </summary>
        public long Size
        {
            get{ return m_Size; }
        }

        /// <summary>
        /// Gets message flags.
        /// </summary>
        public IMAP_MessageFlags Flags
        {
            get{ return m_Flags; }
        }

        /// <summary>
        /// Gets message flags string. For example: "\DELETES \SEEN".
        /// </summary>
        public string FlagsString
        {
            get{ return IMAP_Utils.MessageFlagsToString(m_Flags); }
        }

        #endregion

    }
}


text:
require "logstash/outputs/base"
require "logstash/namespace"
require "logstash/plugin_mixins/aws_config"

# This output lets you aggregate and send metric data to AWS CloudWatch
#
# #### Summary:
# This plugin is intended to be used on a logstash indexer agent (but that
# is not the only way, see below.)  In the intended scenario, one cloudwatch
# output plugin is configured, on the logstash indexer node, with just AWS API
# credentials, and possibly a region and/or a namespace.  The output looks
# for fields present in events, and when it finds them, it uses them to
# calculate aggregate statistics.  If the `metricname` option is set in this
# output, then any events which pass through it will be aggregated & sent to
# CloudWatch, but that is not recommended.  The intended use is to NOT set the
# metricname option here, and instead to add a `CW_metricname` field (and other
# fields) to only the events you want sent to CloudWatch.
#
# When events pass through this output they are queued for background
# aggregation and sending, which happens every minute by default.  The
# queue has a maximum size, and when it is full aggregated statistics will be
# sent to CloudWatch ahead of schedule. Whenever this happens a warning
# message is written to logstash's log.  If you see this you should increase
# the `queue_size` configuration option to avoid the extra API calls.  The queue
# is emptied every time we send data to CloudWatch.
#
# Note: when logstash is stopped the queue is destroyed before it can be processed.
# This is a known limitation of logstash and will hopefully be addressed in a
# future version.
#
# #### Details:
# There are two ways to configure this plugin, and they can be used in
# combination: event fields & per-output defaults
#
# Event Field configuration...
# You add fields to your events in inputs & filters and this output reads
# those fields to aggregate events.  The names of the fields read are
# configurable via the `field_*` options.
#
# Per-output defaults...
# You set universal defaults in this output plugin's configuration, and
# if an event does not have a field for that option then the default is
# used.
#
# Notice, the event fields take precedence over the per-output defaults.
#
# At a minimum events must have a "metric name" to be sent to CloudWatch.
# This can be achieved either by providing a default here OR by adding a
# `CW_metricname` field. By default, if no other configuration is provided
# besides a metric name, then events will be counted (Unit: Count, Value: 1)
# by their metric name (either a default or from their `CW_metricname` field)
#
# Other fields which can be added to events to modify the behavior of this
# plugin are, `CW_namespace`, `CW_unit`, `CW_value`, and
# `CW_dimensions`.  All of these field names are configurable in
# this output.  You can also set per-output defaults for any of them.
# See below for details.
#
# Read more about [AWS CloudWatch](http://aws.amazon.com/cloudwatch/),
# and the specific of API endpoint this output uses,
# [PutMetricData](http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_PutMetricData.html)
class LogStash::Outputs::CloudWatch < LogStash::Outputs::Base
  include LogStash::PluginMixins::AwsConfig

  config_name "cloudwatch"
  milestone 1

  # Constants
  # aggregate_key members
  DIMENSIONS = "dimensions"
  TIMESTAMP = "timestamp"
  METRIC = "metric"
  COUNT = "count"
  UNIT = "unit"
  SUM = "sum"
  MIN = "min"
  MAX = "max"
  # Units
  COUNT_UNIT = "Count"
  NONE = "None"

  # How often to send data to CloudWatch
  # This does not affect the event timestamps, events will always have their
  # actual timestamp (to-the-minute) sent to CloudWatch.
  #
  # We only call the API if there is data to send.
  #
  # See the Rufus Scheduler docs for an [explanation of allowed values](https://github.com/jmettraux/rufus-scheduler#the-time-strings-understood-by-rufus-scheduler)
  config :timeframe, :validate => :string, :default => "1m"

  # How many events to queue before forcing a call to the CloudWatch API ahead of `timeframe` schedule
  # Set this to the number of events-per-timeframe you will be sending to CloudWatch to avoid extra API calls
  config :queue_size, :validate => :number, :default => 10000

  # The default namespace to use for events which do not have a `CW_namespace` field
  config :namespace, :validate => :string, :default => "Logstash"

  # The name of the field used to set a different namespace per event
  # Note: Only one namespace can be sent to CloudWatch per API call
  # so setting different namespaces will increase the number of API calls
  # and those cost money.
  config :field_namespace, :validate => :string, :default => "CW_namespace"

  # The default metric name to use for events which do not have a `CW_metricname` field.
  # Beware: If this is provided then all events which pass through this output will be aggregated and
  # sent to CloudWatch, so use this carefully.  Furthermore, when providing this option, you
  # will probably want to also restrict events from passing through this output using event
  # type, tag, and field matching
  config :metricname, :validate => :string

  # The name of the field used to set the metric name on an event
  # The author of this plugin recommends adding this field to events in inputs &
  # filters rather than using the per-output default setting so that one output
  # plugin on your logstash indexer can serve all events (which of course had
  # fields set on your logstash shippers.)
  config :field_metricname, :validate => :string, :default => "CW_metricname"

  VALID_UNITS = ["Seconds", "Microseconds", "Milliseconds", "Bytes",
                 "Kilobytes", "Megabytes", "Gigabytes", "Terabytes",
                 "Bits", "Kilobits", "Megabits", "Gigabits", "Terabits",
                 "Percent", COUNT_UNIT, "Bytes/Second", "Kilobytes/Second",
                 "Megabytes/Second", "Gigabytes/Second", "Terabytes/Second",
                 "Bits/Second", "Kilobits/Second", "Megabits/Second",
                 "Gigabits/Second", "Terabits/Second", "Count/Second", NONE]

  # The default unit to use for events which do not have a `CW_unit` field
  # If you set this option you should probably set the "value" option along with it
  config :unit, :validate => VALID_UNITS, :default => COUNT_UNIT

  # The name of the field used to set the unit on an event metric
  config :field_unit, :validate => :string, :default => "CW_unit"

  # The default value to use for events which do not have a `CW_value` field
  # If provided, this must be a string which can be converted to a float, for example...
  #     "1", "2.34", ".5", and "0.67"
  # If you set this option you should probably set the `unit` option along with it
  config :value, :validate => :string, :default => "1"

  # The name of the field used to set the value (float) on an event metric
  config :field_value, :validate => :string, :default => "CW_value"

  # The default dimensions [ name, value, ... ] to use for events which do not have a `CW_dimensions` field
  config :dimensions, :validate => :hash

  # The name of the field used to set the dimensions on an event metric
  # The field named here, if present in an event, must have an array of
  # one or more key & value pairs, for example...
  #     add_field => [ "CW_dimensions", "Environment", "CW_dimensions", "prod" ]
  # or, equivalently...
  #     add_field => [ "CW_dimensions", "Environment" ]
  #     add_field => [ "CW_dimensions", "prod" ]
  config :field_dimensions, :validate => :string, :default => "CW_dimensions"

  public
  def aws_service_endpoint(region)
    return {
        :cloud_watch_endpoint => "monitoring.#{region}.amazonaws.com"
    }
  end

  public
  def register
    require "thread"
    require "rufus/scheduler"
    require "aws"

    @cw = AWS::CloudWatch.new(aws_options_hash)

    @event_queue = SizedQueue.new(@queue_size)
    @scheduler = Rufus::Scheduler.start_new
    @job = @scheduler.every @timeframe do
      @logger.info("Scheduler Activated")
      publish(aggregate({}))
    end
  end # def register

  public
  def receive(event)
    return unless output?(event)

    if event == LogStash::SHUTDOWN
      job.trigger()
      job.unschedule()
      @logger.info("CloudWatch aggregator thread shutdown.")
      finished
      return
    end

    return unless (event[@field_metricname] || @metricname)

    if (@event_queue.length >= @event_queue.max)
      @job.trigger
      @logger.warn("Posted to AWS CloudWatch ahead of schedule.  If you see this often, consider increasing the cloudwatch queue_size option.")
    end

    @logger.info("Queueing event", :event => event)
    @event_queue << event
  end # def receive

  private
  def publish(aggregates)
    aggregates.each do |namespace, data|
      @logger.info("Namespace, data: ", :namespace => namespace, :data => data)
      metric_data = []
      data.each do |aggregate_key, stats|
        new_data = {
            :metric_name => aggregate_key[METRIC],
            :timestamp => aggregate_key[TIMESTAMP],
            :unit => aggregate_key[UNIT],
            :statistic_values => {
                :sample_count => stats[COUNT],
                :sum => stats[SUM],
                :minimum => stats[MIN],
                :maximum => stats[MAX],
            }
        }
        dims = aggregate_key[DIMENSIONS]
        if (dims.is_a?(Array) && dims.length > 0 && (dims.length % 2) == 0)
          new_data[:dimensions] = Array.new
          i = 0
          while (i < dims.length)
            new_data[:dimensions] << {:name => dims[i], :value => dims[i+1]}
            i += 2
          end
        end
        metric_data << new_data
      end # data.each

      begin
        @cw.put_metric_data(
            :namespace => namespace,
            :metric_data => metric_data
        )
        @logger.info("Sent data to AWS CloudWatch OK", :namespace => namespace, :metric_data => metric_data)
      rescue Exception => e
        @logger.warn("Failed to send to AWS CloudWatch", :exception => e, :namespace => namespace, :metric_data => metric_data)
        break
      end
    end # aggregates.each
    return aggregates
  end# def publish

  private
  def aggregate(aggregates)
    @logger.info("QUEUE SIZE ", :queuesize => @event_queue.size)
    while !@event_queue.empty? do
      begin
        count(aggregates, @event_queue.pop(true))
      rescue Exception => e
        @logger.warn("Exception!  Breaking count loop", :exception => e)
        break
      end
    end
    return aggregates
  end # def aggregate

  private
  def count(aggregates, event)
    # If the event doesn't declare a namespace, use the default
    fnamespace = field(event, @field_namespace)
    namespace = (fnamespace ? fnamespace : event.sprintf(@namespace))

    funit = field(event, @field_unit)
    unit = (funit ? funit : event.sprintf(@unit))

    fvalue = field(event, @field_value)
    value = (fvalue ? fvalue : event.sprintf(@value))

    # We may get to this point with valid Units but missing value.  Send zeros.
    val = (!value) ? 0.0 : value.to_f

    # Event provides exactly one (but not both) of value or unit
    if ( (fvalue == nil) ^ (funit == nil) )
      @logger.warn("Likely config error: event has one of #{@field_value} or #{@field_unit} fields but not both.", :event => event)
    end

    # If Unit is still not set or is invalid warn about misconfiguration & use NONE
    if (!VALID_UNITS.include?(unit))
      unit = NONE
      @logger.warn("Likely config error: invalid or missing Units (#{unit.to_s}), using '#{NONE}' instead", :event => event)
    end

    if (!aggregates[namespace])
      aggregates[namespace] = {}
    end

    dims = event[@field_dimensions]
    if (dims) # event provides dimensions
              # validate the structure
      if (!dims.is_a?(Array) || dims.length == 0 || (dims.length % 2) != 0)
        @logger.warn("Likely config error: CloudWatch dimensions field (#{dims.to_s}) found which is not a positive- & even-length array.  Ignoring it.", :event => event)
        dims = nil
      end
              # Best case, we get here and exit the conditional because dims...
              # - is an array
              # - with positive length
              # - and an even number of elements
    elsif (@dimensions.is_a?(Hash)) # event did not provide dimensions, but the output has been configured with a default
      dims = @dimensions.flatten.map{|d| event.sprintf(d)} # into the kind of array described just above
    else
      dims = nil
    end

    fmetric = field(event, @field_metricname)
    aggregate_key = {
        METRIC => (fmetric ? fmetric : event.sprintf(@metricname)),
        DIMENSIONS => dims,
        UNIT => unit,
        TIMESTAMP => event.sprintf("%{+YYYY-MM-dd'T'HH:mm:00Z}")
    }

    if (!aggregates[namespace][aggregate_key])
      aggregates[namespace][aggregate_key] = {}
    end

    if (!aggregates[namespace][aggregate_key][MAX] || val > aggregates[namespace][aggregate_key][MAX])
      aggregates[namespace][aggregate_key][MAX] = val
    end

    if (!aggregates[namespace][aggregate_key][MIN] || val < aggregates[namespace][aggregate_key][MIN])
      aggregates[namespace][aggregate_key][MIN] = val
    end

    if (!aggregates[namespace][aggregate_key][COUNT])
      aggregates[namespace][aggregate_key][COUNT] = 1
    else
      aggregates[namespace][aggregate_key][COUNT] += 1
    end

    if (!aggregates[namespace][aggregate_key][SUM])
      aggregates[namespace][aggregate_key][SUM] = val
    else
      aggregates[namespace][aggregate_key][SUM] += val
    end
  end # def count

  private
  def field(event, fieldname)
    if !event[fieldname]
      return nil
    else
      if event[fieldname].is_a?(Array)
        return event[fieldname][0]
      else
        return event[fieldname]
      end
    end
  end # def field

end # class LogStash::Outputs::CloudWatch


text:
<?php

namespace MainBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichImageType;

class PublicationEType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('description',TextareaType::class)->add('imageFile',VichImageType::class)->add('Section',ChoiceType::class,array(

            'choices'=>array(
                "camping"=>"camping", "escalade"=>"escalade","Spéléologie"=>"Spéléologie","Alpinisme"=>"Alpinisme",
                "plongée"=>"plongée",   "chasse"=>"chasse","pêche"=>"pêche"
            )))->add('Publier',SubmitType::class)        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'MainBundle\Entity\PublicationE'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'mainbundle_publicatione';
    }

}


text:
<!DOCTYPE html>

		<title>three.js / examples</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

three.js / examples

				<input type="text" id="filterInput" placeholder="Type to filter" autocorrect="off" autocapitalize="off" spellcheck="false"/>
				x


text:
stegosaurus
===========

Simple steganography tool.


text:
OWASP Enterprise Security API for ColdFusion/CFML (ESAPI4CF)
=
This project is part of the Open Web Application Security Project (OWASP) Enterprise Security API (ESAPI) project. For details, please see http://www.owasp.org/index.php/ESAPI.

Copyright (c) 2011 - The OWASP Foundation

The ESAPI is published by OWASP under the BSD license. You should read and accept the LICENSE before you use, modify, and/or redistribute this software.

ABOUT
-
ESAPI (The OWASP Enterprise Security API) is a free, open source, web application security control library that makes it easier for programmers to write lower-risk applications. The ESAPI libraries are designed to make it easier for programmers to retrofit security into existing applications. The ESAPI libraries also serve as a solid foundation for new development. Allowing for language-specific differences, all OWASP ESAPI versions have the same basic design:
- **There is a set of security control interfaces.** They define for example types of parameters that are passed to types of security controls.
- **There is a reference implementation for each security control.** The logic is not organization‐specific and the logic is not application‐specific. An example: string‐based input validation.
- **There are optionally your own implementations for each security control.** There may be application logic contained in these classes which may be developed by or for your organization. An example: enterprise authentication.

This project source code is licensed under the BSD license, which is very permissive and about as close to public domain as is possible. The project documentation is licensed under the Creative Commons license. You can use or modify ESAPI however you want, even include it in commercial products.

GETTING STARTED
-
Adding ESAPI4CF to your CF application is very simple and even more so now in v2 and can be accomplished with just a few lines of code.

To get started, generate a new random master key and master salt using <localhost>/esapi4cf/utilities/secretKeyGenerator.cfm.

Now we will initialize ESAPI inside your onApplicationStart() method...
```
application.ESAPI = new org.owasp.esapi.ESAPI({
	"Encryptor": {
		"MasterKey": "my generated master key",
		"MasterSalt": "my generated master salt"
	}
});
```
Some features of ESAPI require access to the HTTP request and HTTP response, so register them with ESAPI in your onRequestStart() method...
```
application.ESAPI.httpUtilities().setCurrentHTTP(getPageContext().getRequest(), getPageContext().getResponse());
```
Now your set! You will now have access to ESAPI and all of its modules.

**Some examples:**

Want an application specific logger to log data audits and event statuses to:
```
var logger = application.ESAPI.getLogger(application.name & "-Logger");
logger.info(logger.SECURITY_AUDIT, "Data changed!");
```
Want to authenticate and persist a user across requests:
```
application.ESAPI.authenticator().login();
```

Want to see if the current user is logged in:
```
application.ESAPI.authenticator().getCurrentUser().isLoggedIn();
```
Or you can see if the current user is anonymous (not logged in):
```
application.ESAPI.authenticator().getCurrentUser().isAnonymous();
```

Want to change the current user password:
```
application.ESAPI.authenticator().getCurrentUser().changePassword(currentPassword, newPassword, confirmNewPassword);
```

Want to see if the current user has a permission:
```
application.ESAPI.accessController().isAuthorizedForData(action="edit", data=yourData);
```

Want to encode output to prevent cross-site scripting (XSS):
```
application.ESAPI.encoder().encodeForHTML(input);
```

Want to use Anti-Samy to cleanse rich text input so malicious markup does not get into your application:
```
application.ESAPI.validator().getValidSafeHTML(context="myContext", input=myRichTextValue, maxLength=65536, allowNull=true);
```

Want to encrypt a string:
```
application.ESAPI.encryptor().encryptString(value);
```
Or a shortcut to encrypt an entire query string:
```
application.ESAPI.httpUtilities().encryptQueryString(qs);
```

And this is only a fraction of what ESAPI4CF can do to make your web application more secure and it can do it much easier than any other library out there!

EXTENSIBILITY
-
All ESAPI4CF modules can be extended so you can add your own features or override the default implementations.  If, for example, you find that you want implement your own password complexity rules, you can extend the Authenticator implementation and override the **verifyPasswordStrength** method with your own.  Then you simply need to tell ESAPI to use your Authenticator implementation instead of the default.  You do this in your onApplicationStart right after the ESAPI initialization.
```
application.ESAPI = new org.owasp.esapi.ESAPI({
	"ESAPI": {
		"Authenticator": "CFCpathToMyAuthenticatorInstance",
	}
});
```

You no longer need to extended the Authenitcator or AccessController in order to hook ESAPI into your DB model.  As of v2 you can now accomplish this without extending by the use the the ESAPIAdaptor.  The Adaptor simply needs to implement the org.owasp.esapi.Adapter interface.

Or use the provided ESAPI interfaces to create your own implementation entirely.  The choice is yours!

All of the error and log messages generated by ESAPI4CF are resource bundled.  This means the user messages can be customized without altering the code.  This also means you can translate the user messages to any language you wish.

DOCUMENTATION
-
Compatibility information, setup, tutorials, API reference, and links to latest download are available here:

http://damonmiller.github.io/esapi4cf/

RELEASE NOTES
-
Information on bug fixes and improvements for each release are available here:

https://github.com/damonmiller/esapi4cf/releases

ISSUES
-
You can find known issues or report new issues here:

https://github.com/damonmiller/esapi4cf/issues


text:
package com.kodekutters.ripple.wallet

import com.kodekutters.ripple.protocol._
import play.api.libs.json._
import scala.collection.mutable

// just a test

final case class RippleWallet(secret_key: String) {

  var account_data: Option[Account_data] = None
  val trust_lines = new mutable.ListBuffer[Trust_line]()
  val offers = new mutable.ListBuffer[Offer]()
  val ious = new mutable.ListBuffer[Account_data]()
  val receive_currencies = new mutable.ListBuffer[String]()
  val send_currencies = new mutable.ListBuffer[String]()
  val transaction = new mutable.ListBuffer[Transaction]()

}

object RippleWallet {

  val rwReads: Reads[RippleWallet] = new Reads[RippleWallet] {
    def reads(json: JsValue) = Json.format[RippleWallet].reads(json)
  }

//(
  //  (JsPath \ "secret_key").read[String]
   //   (JsPath \ "account_data").read[Account_data] and
    //  (JsPath \ "trust_lines").read[mutable.ListBuffer[Trust_line]] and
    //  (JsPath \ "offers").read[mutable.ListBuffer[Offer]] and
    //  (JsPath \ "ious").read[mutable.ListBuffer[Account_data]]
   // )(RippleWallet.apply _)

  val rwWrites = new Writes[RippleWallet] {
    def writes(rw: RippleWallet) = Json.obj(
      "account_data" -> rw.account_data,
      "trust_lines" -> rw.trust_lines,
      "offers" -> rw.offers,
      "ious" -> rw.ious)
  }

  implicit val fmt: Format[RippleWallet] = Format(rwReads, rwWrites)
}


text:
FROM jupyter/base-notebook:latest as jupyter

FROM insighttoolkit/itksoftwareguide-bin:latest as itksoftwareguide
MAINTAINER Matt McCormick <matt.mccormick@kitware.com>

RUN apt-get update && apt-get install -y \
  bash-completion \
  liquidprompt \
  sudo

# Import Jupyter configuration and binaries

# Configure environment
ENV CONDA_DIR=/opt/conda \
    SHELL=/bin/bash \
    NB_USER=jovyan \
    NB_UID=1000 \
    NB_GID=100 \
    LC_ALL=en_US.UTF-8 \
    LANG=en_US.UTF-8 \
    LANGUAGE=en_US.UTF-8
ENV PATH=$CONDA_DIR/bin:$PATH \
    HOME=/home/$NB_USER
COPY --from=jupyter /usr/local/bin/fix-permissions /usr/local/bin/
# Create jovyan user with UID=1000 and in the 'users' group
# and make sure these dirs are writable by the `users` group.
RUN useradd -m -s /bin/bash -N -u $NB_UID $NB_USER && \
    mkdir -p $CONDA_DIR && \
    chown $NB_USER:$NB_GID $CONDA_DIR && \
    fix-permissions $HOME && \
    fix-permissions $CONDA_DIR

COPY --from=jupyter /usr/local/bin/tini /usr/local/bin/
COPY --from=jupyter /opt/conda /opt/conda
COPY --from=jupyter /usr/local/bin/start.sh /usr/local/bin/
COPY --from=jupyter /usr/local/bin/start-notebook.sh /usr/local/bin/
COPY --from=jupyter /usr/local/bin/start-singleuser.sh  /usr/local/bin/
COPY --from=jupyter /etc/jupyter/jupyter_notebook_config.py /etc/jupyter/
RUN fix-permissions /etc/jupyter/
RUN fix-permissions /ITKSoftwareGuide
RUN fix-permissions /ITKSoftwareGuide-build && \
  chown -R $NB_USER:$NB_GID /ITKSoftwareGuide-build

RUN /usr/bin/liquidprompt_activate

EXPOSE 8888
WORKDIR /

# Configure container startup
ENTRYPOINT ["tini", "--"]
CMD ["start.sh", "jupyter", "lab"]

USER $NB_USER


text:
// Copyright (C) 2011 Vicente J. Botet Escriba
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// <boost/thread/locks.hpp>

// template <class Mutex> class shared_lock;

// Mutex *mutex() const;

#include <boost/thread/lock_types.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/detail/lightweight_test.hpp>

boost::shared_mutex m;

int main()
{
  boost::shared_lock<boost::shared_mutex> lk0;
  BOOST_TEST(lk0.mutex() == 0);
  boost::shared_lock<boost::shared_mutex> lk1(m);
  BOOST_TEST(lk1.mutex() == &m);
  lk1.unlock();
  BOOST_TEST(lk1.mutex() == &m);

  return boost::report_errors();
}


text:
import copy
from concurrent.futures import ThreadPoolExecutor

from health_check.conf import HEALTH_CHECK
from health_check.exceptions import ServiceWarning
from health_check.plugins import plugin_dir

class CheckMixin:
    _errors = None
    _plugins = None

    @property
    def errors(self):
        if not self._errors:
            self._errors = self.run_check()
        return self._errors

    @property
    def plugins(self):
        if not self._plugins:
            self._plugins = sorted(
                (
                    plugin_class(**copy.deepcopy(options))
                    for plugin_class, options in plugin_dir._registry
                ),
                key=lambda plugin: plugin.identifier(),
            )
        return self._plugins

    def run_check(self):
        errors = []

        def _run(plugin):
            plugin.run_check()
            try:
                return plugin
            finally:
                from django.db import connections

                connections.close_all()

        with ThreadPoolExecutor(max_workers=len(self.plugins) or 1) as executor:
            for plugin in executor.map(_run, self.plugins):
                if plugin.critical_service:
                    if not HEALTH_CHECK["WARNINGS_AS_ERRORS"]:
                        errors.extend(
                            e
                            for e in plugin.errors
                            if not isinstance(e, ServiceWarning)
                        )
                    else:
                        errors.extend(plugin.errors)

        return errors


text:
<?xml version="1.0" encoding="utf-8"?>
<com.gvillani.pinnedlist.PinnedListLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/pinned_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:pin_text_color="@color/colorAccent"
    app:type="image"
    app:pin_vertical_position="center">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.AppBarLayout>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="16dp"/>

</com.gvillani.pinnedlist.PinnedListLayout>


text:
<?php

namespace LastFmApi\Lib;

/**
 * Allows access to the sqlite database using a standard database class
 */
class Sqlite extends \Sqlite3
{
    /**
     * Stores the error details
     * @var array
     */
    public $error;

    /**
     * Method which runs queries. Returns a class on success and false on error
     * @param string $sql The SQL query to run
     * @return class
     * @uses lastfmApiDatabase_result
     */
    function query($sql)
    {
        return new SqliteResult(parent::query($sql));
    }

}


text:
package flavors

import (
	"github.com/gophercloud/gophercloud"
	"github.com/gophercloud/gophercloud/pagination"
)

// GetResult temporarily holds the response from a Get call.
type GetResult struct {
	gophercloud.Result
}

// Extract provides access to the individual Flavor returned by the Get function.
func (r GetResult) Extract() (*Flavor, error) {
	var s struct {
		Flavor *Flavor `json:"flavor"`
	}
	err := r.ExtractInto(&s)
	return s.Flavor, err
}

// Flavor records represent (virtual) hardware configurations for server resources in a region.
type Flavor struct {
	// The flavor's unique identifier.
	ID int `json:"id"`

	// The RAM capacity for the flavor.
	RAM int `json:"ram"`

	// The Name field provides a human-readable moniker for the flavor.
	Name string `json:"name"`

	// Links to access the flavor.
	Links []gophercloud.Link
}

// FlavorPage contains a single page of the response from a List call.
type FlavorPage struct {
	pagination.LinkedPageBase
}

// IsEmpty determines if a page contains any results.
func (page FlavorPage) IsEmpty() (bool, error) {
	flavors, err := ExtractFlavors(page)
	return len(flavors) == 0, err
}

// NextPageURL uses the response's embedded link reference to navigate to the next page of results.
func (page FlavorPage) NextPageURL() (string, error) {
	var s struct {
		Links []gophercloud.Link `json:"flavors_links"`
	}
	err := page.ExtractInto(&s)
	if err != nil {
		return "", err
	}
	return gophercloud.ExtractNextURL(s.Links)
}

// ExtractFlavors provides access to the list of flavors in a page acquired from the List operation.
func ExtractFlavors(r pagination.Page) ([]Flavor, error) {
	var s struct {
		Flavors []Flavor `json:"flavors"`
	}
	err := (r.(FlavorPage)).ExtractInto(&s)
	return s.Flavors, err
}


text:
{% extends 'intro/base.html' %}

{% block title %}Privacy Policy{% endblock %}

{% block content %}

Privacy Policy

[TODO]

{% endblock %}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import cms.models.fields
import djangocms_text_ckeditor.fields

class Migration(migrations.Migration):

    dependencies = [
        ('cms', '0013_urlconfrevision'),
        ('contenttypes', '0002_remove_content_type_name'),
        ('filer', '0002_auto_20150606_2003'),
        ('myshop', '0002_add_i18n'),
    ]

    operations = [
        migrations.CreateModel(
            name='OperatingSystem',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=50, verbose_name='Name')),
            ],
        ),
        migrations.CreateModel(
            name='Product',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created at')),
                ('updated_at', models.DateTimeField(auto_now=True, verbose_name='Updated at')),
                ('active', models.BooleanField(default=True, help_text='Is this product publicly visible.', verbose_name='Active')),
                ('product_name', models.CharField(max_length=255, verbose_name='Product Name')),
                ('slug', models.SlugField(unique=True, verbose_name='Slug')),
                ('order', models.PositiveIntegerField(verbose_name='Sort by', db_index=True)),
            ],
            options={
                'ordering': ('order',),
            },
        ),
        migrations.CreateModel(
            name='ProductTranslation',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('language_code', models.CharField(max_length=15, verbose_name='Language', db_index=True)),
                ('description', djangocms_text_ckeditor.fields.HTMLField(help_text='Description for the list view of products.', verbose_name='Description')),
            ],
        ),
        migrations.CreateModel(
            name='SmartPhone',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('product_code', models.CharField(unique=True, max_length=255, verbose_name='Product code')),
                ('unit_price', models.DecimalField(default='0', help_text='Net price for this product', max_digits=30, decimal_places=3)),
                ('storage', models.PositiveIntegerField(help_text='Internal storage in MB', verbose_name='Internal Storage')),
            ],
        ),
        migrations.AlterUniqueTogether(
            name='smartcardtranslation',
            unique_together=set([]),
        ),
        migrations.RemoveField(
            model_name='smartcardtranslation',
            name='master',
        ),
        migrations.AlterModelOptions(
            name='smartcard',
            options={'verbose_name': 'Smart Card', 'verbose_name_plural': 'Smart Cards'},
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='active',
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='cms_pages',
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='created_at',
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='id',
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='images',
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='manufacturer',
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='order',
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='polymorphic_ctype',
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='product_name',
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='slug',
        ),
        migrations.RemoveField(
            model_name='smartcard',
            name='updated_at',
        ),
        migrations.AlterField(
            model_name='cartitem',
            name='product',
            field=models.ForeignKey(to='myshop.Product'),
        ),
        migrations.AlterField(
            model_name='orderitem',
            name='product',
            field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, verbose_name='Product', blank=True, to='myshop.Product', null=True),
        ),
        migrations.AlterField(
            model_name='productimage',
            name='product',
            field=models.ForeignKey(to='myshop.Product'),
        ),
        migrations.AlterField(
            model_name='productpage',
            name='product',
            field=models.ForeignKey(to='myshop.Product'),
        ),
        migrations.CreateModel(
            name='Commodity',
            fields=[
                ('product_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='myshop.Product')),
                ('unit_price', models.DecimalField(default='0', help_text='Net price for this product', max_digits=30, decimal_places=3)),
                ('product_code', models.CharField(unique=True, max_length=255, verbose_name='Product code')),
                ('placeholder', cms.models.fields.PlaceholderField(slotname='Commodity Details', editable=False, to='cms.Placeholder', null=True)),
            ],
            options={
                'verbose_name': 'Commodity',
                'verbose_name_plural': 'Commodities',
            },
            bases=('myshop.product',),
        ),
        migrations.CreateModel(
            name='SmartPhoneModel',
            fields=[
                ('product_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='myshop.Product')),
                ('battery_type', models.PositiveSmallIntegerField(verbose_name='Battery type', choices=[(1, 'Lithium Polymer (Li-Poly)'), (2, 'Lithium Ion (Li-Ion)')])),
                ('battery_capacity', models.PositiveIntegerField(help_text='Battery capacity in mAh', verbose_name='Capacity')),
                ('ram_storage', models.PositiveIntegerField(help_text='RAM storage in MB', verbose_name='RAM')),
                ('wifi_connectivity', models.PositiveIntegerField(help_text='WiFi Connectivity', verbose_name='WiFi', choices=[(1, '802.11 b/g/n')])),
                ('bluetooth', models.PositiveIntegerField(help_text='Bluetooth Connectivity', verbose_name='Bluetooth', choices=[(1, 'Bluetooth 4.0')])),
                ('gps', models.BooleanField(default=False, help_text='GPS integrated', verbose_name='GPS')),
                ('width', models.DecimalField(help_text='Width in mm', verbose_name='Width', max_digits=4, decimal_places=1)),
                ('height', models.DecimalField(help_text='Height in mm', verbose_name='Height', max_digits=4, decimal_places=1)),
                ('weight', models.DecimalField(help_text='Weight in gram', verbose_name='Weight', max_digits=5, decimal_places=1)),
                ('screen_size', models.DecimalField(help_text='Diagonal screen size in inch', verbose_name='Screen size', max_digits=4, decimal_places=2)),
                ('operating_system', models.ForeignKey(verbose_name='Operating System', to='myshop.OperatingSystem')),
            ],
            options={
                'verbose_name': 'Smart Phone',
                'verbose_name_plural': 'Smart Phones',
            },
            bases=('myshop.product',),
        ),
        migrations.DeleteModel(
            name='SmartCardTranslation',
        ),
        migrations.AddField(
            model_name='producttranslation',
            name='master',
            field=models.ForeignKey(related_name='translations', to='myshop.Product', null=True),
        ),
        migrations.AddField(
            model_name='product',
            name='cms_pages',
            field=models.ManyToManyField(help_text='Choose list view this product shall appear on.', to='cms.Page', through='myshop.ProductPage'),
        ),
        migrations.AddField(
            model_name='product',
            name='images',
            field=models.ManyToManyField(to='filer.Image', through='myshop.ProductImage'),
        ),
        migrations.AddField(
            model_name='product',
            name='manufacturer',
            field=models.ForeignKey(verbose_name='Manufacturer', to='myshop.Manufacturer'),
        ),
        migrations.AddField(
            model_name='product',
            name='polymorphic_ctype',
            field=models.ForeignKey(related_name='polymorphic_myshop.product_set+', editable=False, to='contenttypes.ContentType', null=True),
        ),
        migrations.AddField(
            model_name='smartcard',
            name='product_ptr',
            field=models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, default=None, serialize=False, to='myshop.Product'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='smartphone',
            name='product',
            field=models.ForeignKey(verbose_name='Smart-Phone Model', to='myshop.SmartPhoneModel'),
        ),
        migrations.AlterUniqueTogether(
            name='producttranslation',
            unique_together=set([('language_code', 'master')]),
        ),
    ]


text:
package example.aggregation;

import peersim.core.*;
import peersim.config.FastConfig;
import peersim.vector.SingleValueHolder;
import peersim.cdsim.CDProtocol;

/**
 * This class provides an implementation for the averaging function in the
 * aggregation framework. When a pair of nodes interact, their values are
 * averaged. The class subclasses {@link SingleValueHolder} in
 * order to provide a consistent access to the averaging variable value.
 *
 * Note that this class does not override the clone method, because it does
 * not have any state other than what is inherited from
 * {@link SingleValueHolder}.
 *
 * @author Alberto Montresor
 * @version $Revision: 1.11 $
 */
public class AverageFunction extends SingleValueHolder implements CDProtocol {
    /**
     * Creates a new {@link example.aggregation.AverageFunction} protocol
     * instance.
     *
     * @param prefix
     *            the component prefix declared in the configuration file.
     */
    public AverageFunction(String prefix) {
        super(prefix);
    }

    /**
     * Using an underlying {@link Linkable} protocol choses a neighbor and
     * performs a variance reduction step.
     *
     * @param node
     *            the node on which this component is run.
     * @param protocolID
     *            the id of this protocol in the protocol array.
     */
    public void nextCycle(Node node, int protocolID) {
        int linkableID = FastConfig.getLinkable(protocolID);
        Linkable linkable = (Linkable) node.getProtocol(linkableID);
        if (linkable.degree() > 0) {
            Node peer = linkable.getNeighbor(CommonState.r.nextInt(linkable
                    .degree()));

            // Failure handling
            if (!peer.isUp())
                return;

            System.out.println(node.getID()+" gossiped to "+peer.getID());
            AverageFunction neighbor = (AverageFunction) peer
                    .getProtocol(protocolID);
            double mean = (this.value + neighbor.value) / 2;
            this.value = mean;
            neighbor.value = mean;
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using ExtensionsCore;
using System.Net.Http.Formatting;

namespace FlowplaneExtensions.Controllers.api
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class Api_ProcessController : ApiController
    {
        [HttpPost]
        [AllowAnonymous]
        public IAssignees GetAssignees(FormDataCollection formData)
        {
            return new Models.api.Process.Details().GetAssignees(formData);
        }

        [HttpPost]
        [AllowAnonymous]
        public IWorkspaces GetWorkSpaces(FormDataCollection formData)
        {
            return new Models.api.Process.Details().GetWorkSpaces(formData);
        }

        [HttpPost]
        [AllowAnonymous]
        public IProjects GetProjects(FormDataCollection formData)
        {
            return new Models.api.Process.Details().GetProjects(formData);
        }

        [HttpPost]
        [AllowAnonymous]
        public ITasks GetTasks(FormDataCollection formData)
        {
            return new Models.api.Process.Details().GetTasks(formData);
        }

        //[HttpPost]
        //[AllowAnonymous]
        //public ITree GetFolders(FormDataCollection formData)
        //{
        //    return new Models.api.Process.Details().GetFolders(formData);
        //}
    }
}


text:
class Api::V1::Auth::RegistrationsController < Devise::RegistrationsController
  include ::Concerns::DeviseRedirectionPaths

  def build_resource sign_up_params
    self.resource = Registration.new sign_up_params
  end

end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 2: 681 (1924)

#### Original name
Mellitiosporiopsis violacea Rehm

### Remarks
null


text:
<?php
/**
 * This file contains the EE_Register_Admin_Page class that implements EEI_Plugin_API.
 * @package      Event Espresso
 * @subpackage helpers
 * @since           4.3.0
 */
if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');

/**
 * Use this to register or deregister an EE Admin Page.
 *
 * @package        Event Espresso
 * @subpackage  plugin api, admin
 * @since            4.3.0
 * @author          Darren Ethier
 */
class EE_Register_Admin_Page implements EEI_Plugin_API {

    /**
     * Holds registered EE_Admin_Pages
     * @var array
     */
    protected static $_ee_admin_page_registry = array();

    /**
     * The purpose of this method is to provide an easy way for addons to register their admin pages (using the EE Admin Page loader system).
     *
     * @since 4.3.0
     *
	 * @param  string $page_basename 	This string represents the basename of the Admin Page init.
	 *                                                        		The init file must use this basename in its name and class (i.e. {page_basename}_Admin_Page_Init.core.php).
     * @param  array  $config  {              An array of configuration options that will be used in different circumstances
	 *
	 *		@type  string $page_path             This is the path where the registered admin pages reside ( used to setup autoloaders).
	 *
	 * 	}
     * @return void
     */
    public static function register( $page_basename = NULL, $config = array() ) {

		// check that an admin_page has not already been registered with that name
		if ( isset(self::$_ee_admin_page_registry[ $page_basename ] )) {
			throw new EE_Error( sprintf( __( 'An Admin Page with the name "%s" has already been registered and each Admin Page requires a unique name.', 'event_espresso' ), $page_basename ));
		}

		// required fields MUST be present, so let's make sure they are.
		if ( empty( $page_basename ) || ! is_array( $config ) || empty( $config['page_path'] )) {
			throw new EE_Error( __( 'In order to register an Admin Page with EE_Register_Admin_Page::register(), you must include the "page_basename" (the class name of the page), and an array containing the following keys: "page_path" (the path where the registered admin pages reside)', 'event_espresso' ));
		}

		//make sure we don't register twice
		if( isset( self::$_ee_admin_page_registry[ $page_basename ] ) ){
			return;
		}

		if ( ! did_action( 'AHEE__EE_System__load_espresso_addons' ) || did_action( 'AHEE__EE_Admin__loaded' )) {
            EE_Error::doing_it_wrong(
				__METHOD__,
				sprintf(
					__('An attempt was made to register "%s" as an EE Admin page has failed because it was not registered at the correct time.  Please use the "AHEE__EE_Admin__loaded" hook to register Admin pages.','event_espresso'),
					$page_basename
				),
				'4.3'
			);
        }

        //add incoming stuff to our registry property
        self::$_ee_admin_page_registry[ $page_basename ] = array(
            'page_path' => $config['page_path'],
            'config' => $config
            );

       //add filters

       add_filter('FHEE__EE_Admin_Page_Loader___get_installed_pages__installed_refs', array( 'EE_Register_Admin_Page', 'set_page_basename' ), 10 );
       add_filter('FHEE__EEH_Autoloader__load_admin_core', array( 'EE_Register_Admin_Page', 'set_page_path' ), 10 );

    }

    /**
     * This deregisters a EE_Admin page that is already registered.  Note, this MUST be loaded after the
     * page being deregistered is loaded.
     *
     * @since    4.3.0
     *
     * @param  string $page_basename Use whatever string was used to register the admin page.
     * @return  void
     */
    public static function deregister( $page_basename = NULL ) {
    	if ( !empty( self::$_ee_admin_page_registry[$page_basename] ) )
    		unset( self::$_ee_admin_page_registry[$page_basename] );
    }

	/**
	 * set_page_basename
	 *
	 * @param $installed_refs
	 * @return mixed
	 */
	public static function set_page_basename( $installed_refs ) {
		if ( ! empty( self::$_ee_admin_page_registry )) {
			foreach ( self::$_ee_admin_page_registry as $basename => $args ) {
				$installed_refs[ $basename ] = $args['page_path'];
			}
		}
        return $installed_refs;
    }

	/**
	 * set_page_path
	 *
	 * @param $paths
	 * @return mixed
	 */
	public static function set_page_path( $paths ) {
        foreach ( self::$_ee_admin_page_registry as $basename => $args ) {
            $paths[ $basename ] = $args['page_path'];
        }
        return $paths;
    }
}


text:
import warnings
from django.apps import AppConfig, apps
from django.core.exceptions import MultipleObjectsReturned
from django.utils.datastructures import OrderedSet
from django.utils.translation import get_language

from fluent_pages import appsettings
from fluent_pages.models import UrlNode
from fluent_pages.models.managers import UrlNodeQuerySet

from polymorphic.models import PolymorphicModel

from mptt.models import MPTTModel

from . import monkey_patches
from .managers import PublishingQuerySet, PublishingPolymorphicManager, \
    PublishingUrlNodeManager, UrlNodeQuerySetWithPublishingFeatures, \
    _queryset_iterator
from .models import PublishingModel
from .middleware import is_draft_request_context, \
    override_draft_request_context

def monkey_patch_override_method(klass):
    """
    Override a class method with a new version of the same name. The original
    method implementation is made available within the override method as
    `_original_<METHOD_NAME>`.
    """
    def perform_override(override_fn):
        fn_name = override_fn.__name__
        original_fn_name = '_original_' + fn_name
        # Override class method, if it hasn't already been done
        if not hasattr(klass, original_fn_name):
            original_fn = getattr(klass, fn_name)
            setattr(klass, original_fn_name, original_fn)
            setattr(klass, fn_name, override_fn)
    return perform_override

def monkey_patch_override_instance_method(instance):
    """
    Override an instance method with a new version of the same name. The
    original method implementation is made available within the override method
    as `_original_<METHOD_NAME>`.
    """
    def perform_override(override_fn):
        fn_name = override_fn.__name__
        original_fn_name = '_original_' + fn_name
        # Override instance method, if it hasn't already been done
        if not hasattr(instance, original_fn_name):
            original_fn = getattr(instance, fn_name)
            setattr(instance, original_fn_name, original_fn)
            bound_override_fn = override_fn.__get__(instance)
            setattr(instance, fn_name, bound_override_fn)
    return perform_override

class AppConfig(AppConfig):
    # Name of package where `apps` module is located
    name = '.'.join(__name__.split('.')[:-1])

    def __init__(self, *args, **kwargs):
        self.label = self.name.replace('.', '_')
        super(AppConfig, self).__init__(*args, **kwargs)

    def ready(self):
        # Ensure everything below is only ever run once
        # TODO This check is necessary for Django 1.7 events tests, why?
        if getattr(AppConfig, 'has_run_ready', False):
            return
        AppConfig.has_run_ready = True

        monkey_patches.APPLY_patch_urlnodeadminform_clean_for_publishable_items()
        monkey_patches.APPLY_patch_django_17_collector_collect()
        monkey_patches.APPLY_patch_django_18_get_candidate_relations_to_delete()

        # Monkey-patch `UrlNodeQuerySet.published` to avoid filtering out draft
        # items when we are in a draft request context when the special-case
        # `for_user` parameter is supplied. The original only avoids this
        # filtering for logged-in staff users, but we need to avoid it for
        # other cases like when a specially "signed" draft URL is shared.
        @monkey_patch_override_method(UrlNodeQuerySet)
        def published(self, for_user=None):
            if for_user is not None and is_draft_request_context():
                return self._single_site()
            else:
                return self._original_published(for_user=for_user)

        @monkey_patch_override_method(UrlNodeQuerySet)
        def iterator(self):
            return _queryset_iterator(self)

        # Monkey-patch `UrlNodeQuerySet.get_for_path` to add filtering by
        # publishing status.
        @monkey_patch_override_method(UrlNodeQuerySet)
        def get_for_path(self, path, language_code=None):
            """
            Return the UrlNode for the given path.
            The path is expected to start with an initial slash.

            Raises UrlNode.DoesNotExist when the item is not found.
            """
            if language_code is None:
                language_code = self._language or get_language()

            # Don't normalize slashes, expect the URLs to be sane.
            qs = self._single_site().filter(
                translations___cached_url=path,
                translations__language_code=language_code,
            )

            matches = _filter_candidates_by_published_status(qs)
            return _get_first_routable(
                matches, self.model, path, language_code,
                enforce_single_result=True)

        # Monkey-patch `UrlNodeQuerySet.best_match_for_path` to add filtering
        # by publishing status.
        @monkey_patch_override_method(UrlNodeQuerySet)
        def best_match_for_path(self, path, language_code=None):
            if language_code is None:
                language_code = self._language or get_language()

            # Based on FeinCMS:
            paths = self._split_path_levels(path)

            qs = self._single_site() \
                .filter(translations___cached_url__in=paths,
                        translations__language_code=language_code) \
                .extra(select={'_url_length': 'LENGTH(_cached_url)'}) \
                .order_by('-level', '-_url_length')  # / and /news/ is both level 0

            matches = _filter_candidates_by_published_status(qs)
            return _get_first_routable(
                matches, self.model, path, language_code,
                enforce_single_result=False)

        def _filter_candidates_by_published_status(candidates):
            # Filter candidate results by published status, using
            # instance attributes instead of queryset filtering to
            # handle unpublishable and ICEKit publishing-enabled items.
            objs = OrderedSet()  # preserve order & remove dupes
            if is_draft_request_context():
                for candidate in candidates:
                    # Keep candidates that are publishable draft copies, or
                    # that are not publishable (i.e. they don't have the
                    # `is_draft` attribute at all)
                    if getattr(candidate, 'is_draft', True):
                        objs.add(candidate)
                    # Also keep candidates where we have the published copy and
                    # can exchange to get the draft copy with an identical URL
                    elif hasattr(candidate, 'get_draft'):
                        draft_copy = candidate.get_draft()
                        if draft_copy.get_absolute_url() == \
                                candidate.get_absolute_url():
                            objs.add(draft_copy)
            else:
                for candidate in candidates:
                    # Keep candidates that are published, or that are not
                    # publishable (i.e. they don't have the `is_published`
                    # attribute)
                    if getattr(candidate, 'is_published', True):
                        # Skip candidates that are not within any publication
                        # date restrictions
                        if (hasattr(candidate, 'is_within_publication_dates')
                            and not candidate.is_within_publication_dates()
                        ):
                            pass
                        else:
                            objs.add(candidate)
            # Convert `OrderedSet` to a list which supports `len`, see
            # https://code.djangoproject.com/ticket/25093
            return list(objs)

        def _get_first_routable(item_list, model, path, language_code,
                                enforce_single_result=False):
            """
            Return the first item in the given list of routable items.

            Raise `DoesNotExist` if the list is empty.

            Raise `MultipleObjectsReturned` if the list contains multiple
            objects and the `enforce_single_result` argument is set.
            """
            request_context_desc = \
                'published' if is_draft_request_context() else 'draft'
            # Check for invalid multiple results if requested
            if enforce_single_result and len(item_list) > 1:
                raise model.MultipleObjectsReturned(
                    u"Multiple {0} {1} found for the path '{2}'"
                    .format(request_context_desc, model.__name__, path))
            # Get first result; error if none are available
            try:
                obj = item_list[0]
                # Explicitly set language for object.
                obj.set_current_language(language_code)
                return obj
            except IndexError:
                raise model.DoesNotExist(
                    u"No {0} {1} found for the path '{2}'"
                    .format(request_context_desc, model.__name__, path))

        # Monkey-patch method overrides for classes where we must do so to
        # avoid our custom versions from getting clobbered by versions higher
        # up the inheritance hierarchy.
        for model in apps.get_models():

            # Monkey-patch the queryset class used by any model descriptors
            # that represent relationships to publishable items, including
            # our own and `UrlNode`s notions of publishing, so that we can
            # exchange draft items for their corresponding published copies
            # when `published()` is invoked on these relationships.
            try:
                # Django 1.8+
                field_names = [f.name for f in model._meta.get_fields()]
            except AttributeError:
                # Django < 1.8
                field_names = model._meta.get_all_field_names()
            for field_name in field_names:
                try:
                    descriptor = getattr(model, field_name)
                except AttributeError:
                    continue
                # We are only interested in descriptors for related item
                # relationships, which we recognise by the presence of
                # `related_manager_cls`.
                if not hasattr(descriptor, 'related_manager_cls'):
                    continue
                manager_cls = descriptor.related_manager_cls
                # Different item relationships keep the queryset class we need
                # to patch in different places: grab the class and remember the
                # attribute name wherever that class is.
                try:
                    qs_class = manager_cls.queryset_class
                except AttributeError:
                    qs_class = manager_cls._queryset_class

                # If queryset is a descendent of our own `PublishingQuerySet`
                # we only need to enable the exchange mechanism so it will
                # happen by default
                if issubclass(qs_class, PublishingQuerySet):
                    qs_class.exchange_on_published = True
                # If the queryset is not based on `PublishingQuerySet` but is
                # a `UrlNodeQuerySet` we replace that QS class with our own
                # customised version that overrides the `published()` method.
                elif issubclass(qs_class, UrlNodeQuerySet):
                    descriptor.related_manager_cls = manager_cls.from_queryset(
                        UrlNodeQuerySetWithPublishingFeatures)
                    # Override published method on manager as well, so our
                    # queryset's implementation of `published()` is used
                    descriptor.related_manager_cls.published = \
                        lambda self, **kwargs: self.all().published(**kwargs)

            # Skip any models that don't have publishing features
            if not issubclass(model, PublishingModel):
                continue

            ##############################################################
            # Override `publishing_draft` 1-to-1 queryset traversal to avoid
            # wrapping the draft copy result in `DraftItemBoobyTrap`
            # TODO Get this to actually work...

            # @monkey_patch_override_instance_method(model.publishing_draft)
            # def get_queryset(self, **kwargs):
            #     with override_draft_request_context(True):
            #         return self._original_get_queryset(**kwargs)

            ##############################################################

            def _contribute_if_not_subclass(attr, cls):
                if hasattr(model, attr):
                    val = getattr(model, attr)
                    if isinstance(val, cls):
                        # the attribute is already an instance of the class
                        # we want.
                        return
                    else:
                        warnings.warn(
                            u"`{0}` manager {1} on model {2} does not "
                            u"subclass `{3}`. Monkey-patching.".format(
                                attr,
                                type(val),
                                model,
                                cls
                            )
                        )
                cls().contribute_to_class(model, attr)

            if issubclass(model, PolymorphicModel) \
                    and not issubclass(model, UrlNode):

                _contribute_if_not_subclass('objects', PublishingPolymorphicManager)
                _contribute_if_not_subclass('_default_manager', PublishingPolymorphicManager)

            if issubclass(model, UrlNode):
                _contribute_if_not_subclass('objects', PublishingUrlNodeManager)
                _contribute_if_not_subclass('_default_manager', PublishingUrlNodeManager)

                @monkey_patch_override_method(model)
                def _make_slug_unique(self, translation):
                    """
                    Custom make slug unique checked.
                    :param self: The object to which the slug is or will be
                    associated.
                    :param translation: The particular translation of the slug.
                    :return: None
                    """
                    # Short-circuit processing of newly-published items that do
                    # not yet have a relationship to the corresponding draft.
                    # This avoids triggering `UrlNode._update_descendant_urls`
                    # when it will break because we are saving a partially-
                    # complete published item.
                    if self.is_published:
                        try:
                            self.publishing_draft
                        except type(self).publishing_draft.RelatedObjectDoesNotExist:
                            return

                    original_slug = translation.slug
                    count = 1
                    while True:
                        exclude_kwargs = {
                            'pk__in': [],
                        }
                        if self:
                            exclude_kwargs['pk__in'].append(self.pk)

                        if self.publishing_linked_id:
                            exclude_kwargs['pk__in'].append(self.publishing_linked_id)

                        url_nodes = UrlNode.objects.filter(
                            parent=self.parent_id,
                            translations__slug=translation.slug,
                            translations__language_code=translation.language_code
                        ).exclude(**exclude_kwargs).non_polymorphic()

                        if appsettings.FLUENT_PAGES_FILTER_SITE_ID:
                            url_nodes = url_nodes.parent_site(self.parent_site_id)

                        if not url_nodes.exists():
                            break

                        count += 1
                        translation.slug = '%s-%d' % (original_slug, count)

            if issubclass(model, MPTTModel):

                @monkey_patch_override_method(model)
                def get_root(self):
                    """
                    Replace default implementation of `mptt.models.MPTTModel.get_root`
                    with a version that returns the root of either published or draft
                    items, as appropriate for this item.

                    In other words: return the published root if this item is
                    published; return the draft root if this item is a draft.
                    """
                    if self.is_root_node() \
                            and type(self) == self._tree_manager.tree_model:
                        return self

                    root_qs = self._tree_manager._mptt_filter(
                        tree_id=self._mpttfield('tree_id'),
                        parent=None,
                    )
                    # Try normal approach first, in case it works
                    try:
                        return root_qs.get()
                    except MultipleObjectsReturned:
                        # Nope, we got both draft and published copies as root
                        pass

                    # Sort out this mess manually by grabbing the first root candidate
                    # and converting it to draft or published copy as appropriate.
                    if self.is_draft:
                        return root_qs.first().get_draft()
                    else:
                        return root_qs.first().get_published()

                @monkey_patch_override_method(model)
                def get_descendants(self, include_self=False, ignore_publish_status=False):
                    """
                    Replace `mptt.models.MPTTModel.get_descendants` with a version that
                    returns only draft or published copy descendants, as appopriate.
                    """
                    qs = self._original_get_descendants(include_self=include_self)
                    if not ignore_publish_status:
                        return type(self).objects.filter(
                            pk__in=qs.values_list('pk', flat=True),
                            publishing_is_draft=self.publishing_is_draft)
                    return qs

                @monkey_patch_override_method(model)
                def get_ancestors(self, ascending=False, include_self=False,
                                  ignore_publish_status=False):
                    """
                    Replace `mptt.models.MPTTModel.get_ancestors` with a version that
                    returns only draft or published copy ancestors, as appopriate.
                    """
                    qs = self._original_get_ancestors(
                        ascending=ascending, include_self=include_self)
                    if not ignore_publish_status:
                        return type(self).objects.filter(
                            pk__in=qs.values_list('pk', flat=True),
                            publishing_is_draft=self.publishing_is_draft)
                    return qs