text:
package net.tomp2p.upnp;

/**
 * Interface to defined allowed values for service state variables data types
 *
 * @author SuperBonBon
 * @version 1.0
 */
public interface StateVariableTypes {

    /**
     * Unsigned 1 Byte int. Same format as int without leading sign.
     */
    public final static String UI1 = "ui1";

    /**
     * Unsigned 2 Byte int. Same format as int without leading sign.
     */
    public final static String UI2 = "ui2";

    /**
     * Unsigned 4 Byte int. Same format as int without leading sign.
     */
    public final static String UI4 = "ui4";

    /**
     * 1 Byte int. Same format as int.
     */
    public final static String I1 = "i1";

    /**
     * 2 Byte int. Same format as int.
     */
    public final static String I2 = "i2";

    /**
     * 4 Byte int. Same format as int.
     */
    public final static String I4 = "i4";

    /**
     * Fixed point, integer number. May have leading sign. May have leading
     * zeros. (No currency symbol.) (No grouping of digits to the left of the
     * decimal, e.g., no commas.)
     */
    public final static String INT = "int";

    /**
     * 4 Byte float. Same format as float. Must be between 3.40282347E+38 to
     * 1.17549435E-38.
     */
    public final static String R4 = "r4";

    /**
     * 8 Byte float. Same format as float. Must be between -1.79769313486232E308
     * and -4.94065645841247E-324 for negative values, and between
     * 4.94065645841247E-324 and 1.79769313486232E308 for positive values, i.e.,
     * IEEE 64-bit (8-Byte) double.
     */
    public final static String R8 = "r8";

    /**
     * Same as r8.
     */
    public final static String NUMBER = "number";

    /**
     * Same as r8 but no more than 14 digits to the left of the decimal point
     * and no more than 4 to the right.
     */
    public final static String FIXED_14_4 = "fixed.14.4";

    /**
     * Floating point number. Mantissa (left of the decimal) and/or exponent may
     * have a leading sign. Mantissa and/or exponent may have leading zeros.
     * Decimal character in mantissa is a period, i.e., whole digits in mantissa
     * separated from fractional digits by period. Mantissa separated from
     * exponent by E. (No currency symbol.) (No grouping of digits in the
     * mantissa, e.g., no commas.)
     */
    public final static String FLOAT = "float";

    /**
     * Unicode string. One character long.
     */
    public final static String CHAR = "char";

    /**
     * Unicode string. No limit on length.
     */
    public final static String STRING = "string";

    /**
     * Date in a subset of ISO 8601 format without time data.
     */
    public final static String DATE = "date";

    /**
     * Date in ISO 8601 format with optional time but no time zone.
     */
    public final static String DATETIME = "dateTime";

    /**
     * Date in ISO 8601 format with optional time and optional time zone.
     */
    public final static String DATETIME_TZ = "dateTime.tz";

    /**
     * Time in a subset of ISO 8601 format with no date and no time zone.
     */
    public final static String TIME = "time";

    /**
     * Time in a subset of ISO 8601 format with optional time zone but no date.
     */
    public final static String TIME_TZ = "time.tz";

    /**
     * 0, false, or no for false; 1, true, or yes for true.
     */
    public final static String BOOLEAN = "boolean";

    /**
     * MIME-style Base64 encoded binary BLOB. Takes 3 Bytes, splits them into 4
     * parts, and maps each 6 bit piece to an octet. (3 octets are encoded as
     * 4.) No limit on size.
     */
    public final static String BIN_BASE64 = "bin.base64";

    /**
     * Hexadecimal digits representing octets. Treats each nibble as a hex digit
     * and encodes as a separate Byte. (1 octet is encoded as 2.) No limit on
     * size.
     */
    public final static String BIN_HEX = "bin.hex";

    /**
     * Universal Resource Identifier.
     */
    public final static String URI = "uri";

    /**
     * Universally Unique ID. Hexadecimal digits representing octets. Optional
     * embedded hyphens are ignored.
     */
    public final static String UUID = "uuid";

    /***/
    public final static int UI1_INT = "ui1".hashCode();

    /***/
    public final static int UI2_INT = "ui2".hashCode();

    /***/
    public final static int UI4_INT = "ui4".hashCode();

    /***/
    public final static int I1_INT = "i1".hashCode();

    /***/
    public final static int I2_INT = "i2".hashCode();

    /***/
    public final static int I4_INT = "i4".hashCode();

    /***/
    public final static int INT_INT = "int".hashCode();

    /***/
    public final static int R4_INT = "r4".hashCode();

    /***/
    public final static int R8_INT = "r8".hashCode();

    /***/
    public final static int NUMBER_INT = "number".hashCode();

    /***/
    public final static int FIXED_14_4_INT = "fixed.14.4".hashCode();

    /***/
    public final static int FLOAT_INT = "float".hashCode();

    /***/
    public final static int CHAR_INT = "char".hashCode();

    /***/
    public final static int STRING_INT = "string".hashCode();

    /***/
    public final static int DATE_INT = "date".hashCode();

    /***/
    public final static int DATETIME_INT = "dateTime".hashCode();

    /***/
    public final static int DATETIME_TZ_INT = "dateTime.tz".hashCode();

    /***/
    public final static int TIME_INT = "time".hashCode();

    /***/
    public final static int TIME_TZ_INT = "time.tz".hashCode();

    /***/
    public final static int BOOLEAN_INT = "boolean".hashCode();

    /***/
    public final static int BIN_BASE64_INT = "bin.base64".hashCode();

    /***/
    public final static int BIN_HEX_INT = "bin.hex".hashCode();

    /***/
    public final static int URI_INT = "uri".hashCode();

    /***/
    public final static int UUID_INT = "uuid".hashCode();

}


text:
{% extends 'dash_base.html' %}

{% block sidebar %}
  {% with current_sidebar="instances" %}
    {{block.super}}
  {% endwith %}
{% endblock %}

{% block page_header %}
  {% url dash_instances request.user.tenant as refresh_link %}
  {# to make searchable false, just remove it from the include statement #}
  {% include "_page_header.html" with title="Instances" refresh_link=refresh_link searchable="true" %}
{% endblock page_header %}

{% block dash_main %}
  {% if instances %}
    {% include '_instance_list.html' %}
  {% else %}

Info

There are currently no instances.  You can launch an instance from the  Images Page.

  {% endif %}
{% endblock %}

{% block footer_js %}

{% endblock footer_js %}

redpajama_set_name: RedPajamaGithub


text:
<?php
/*
 Prototype   : int filesize ( string $filename );
 Description : Returns the size of the file in bytes, or FALSE
   (and generates an error of level E_WARNING) in case of an error.
*/

$file_path = dirname(__FILE__);

echo "*** Testing filesize(): usage variations ***\n";
$filename =  $file_path."/filesize_variation3.tmp";
$file_handle = fopen($filename, "w");
fwrite($file_handle, (binary)str_repeat("Hello,World ", 1000) ); // create file of size 12000 bytes
fclose($file_handle);

echo "-- Testing filesize() after truncating the file to a new length --\n";
// truncate the file created earlier in subdir, the size of the file is 12000bytes
// truncate the same file, in the loop , each time with the decrement in size by 1200 bytes,
//  until -1200bytes size
for($size = filesize($filename); $size>=-1200; $size-=1200) {
  $file_handle = fopen($filename, "r+");
  var_dump( ftruncate($file_handle, $size) );
  fclose($file_handle);
  var_dump( filesize($filename) );
  clearstatcache();
}

echo "*** Done ***\n";
?>


text:
export DEBIAN_FRONTEND=noninteractive
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

readonly COMPOSE_VERSION=1.3.0
readonly MACHINE_VERSION=v0.3.0

readonly DOCKVIZ_VERSION=v0.2
readonly DOCKVIZ_EXE_URL=https://github.com/justone/dockviz/releases/download/$DOCKVIZ_VERSION/dockviz_linux_amd64

readonly DOCKERGEN_VERSION=0.4.0
readonly DOCKERGEN_TARBALL=docker-gen-linux-amd64-$DOCKERGEN_VERSION.tar.gz

readonly DOCKERIZE_VERSION=v0.0.2
readonly DOCKERIZE_TARBALL=dockerize-linux-amd64-$DOCKERIZE_VERSION.tar.gz

readonly CADVISOR_VERSION=0.15.1
readonly CADVISOR_EXE_URL=https://github.com/google/cadvisor/releases/download/$CADVISOR_VERSION/cadvisor

#---------------------------------------#
# fix base box
#

# disable the warning "Your environment specifies an invalid locale"
sudo touch /var/lib/cloud/instance/locale-check.skip

# update packages
sudo apt-get update
#sudo apt-get -y -q upgrade
#sudo apt-get -y -q dist-upgrade

#---------------------------------------#
# Docker-related stuff
#

# install Docker
curl -sL https://get.docker.io/ | sudo sh

# enable memory and swap accounting
sed -i -e \
  's/^GRUB_CMDLINE_LINUX=.+/GRUB_CMDLINE_LINUX="cgroup_enable=memory swapaccount=1"/' \
  /etc/default/grub
sudo update-grub

# enable UFW forwarding
sed -i -e \
  's/^DEFAULT_FORWARD_POLICY=.+/DEFAULT_FORWARD_POLICY="ACCEPT"/' \
  /etc/default/ufw
#sudo ufw reload

#
# override "insecure-registry" error for private registry to ease testing
# @see http://stackoverflow.com/a/27163607/714426
#
cat << "EOF_REGISTRY" >> /etc/default/docker

# allow Docker Remote API
DOCKER_OPTS="$DOCKER_OPTS -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock"

# allow HTTP access to private registry "registry.com"
DOCKER_OPTS="$DOCKER_OPTS --insecure-registry registry.com"
#DOCKER_OPTS="--insecure-registry 10.0.0.0/24 --insecure-registry registry.com"

EOF_REGISTRY

# install Docker Compose (was: Fig)
# @see http://docs.docker.com/compose/install/
curl -o docker-compose -L https://github.com/docker/compose/releases/download/$COMPOSE_VERSION/docker-compose-`uname -s`-`uname -m`
chmod a+x docker-compose
sudo mv docker-compose /usr/local/bin

# install Docker Machine
# @see https://docs.docker.com/machine/
curl -o docker-machine -L https://github.com/docker/machine/releases/download/$MACHINE_VERSION/docker-machine_linux-amd64
chmod a+x docker-machine
sudo mv docker-machine /usr/local/bin

# install dockviz
curl -o /usr/local/bin/dockviz -L $DOCKVIZ_EXE_URL
chmod a+x /usr/local/bin/dockviz

# install Pipework
# @see https://github.com/jpetazzo/pipework
curl -o pipework -L https://raw.githubusercontent.com/jpetazzo/pipework/master/pipework
chmod a+x pipework
sudo mv pipework /usr/local/bin

# install docker-gen
# @see https://github.com/jwilder/docker-gen
curl -o docker-gen.tar.gz -L https://github.com/jwilder/docker-gen/releases/download/$DOCKERGEN_VERSION/$DOCKERGEN_TARBALL
tar xvzf docker-gen.tar.gz
sudo chown root docker-gen
sudo chgrp root docker-gen
sudo mv docker-gen /usr/local/bin
rm *.tar.gz

# install dockerize
# @see https://github.com/jwilder/dockerize
curl -o dockerize.tar.gz -L https://github.com/jwilder/dockerize/releases/download/$DOCKERIZE_VERSION/$DOCKERIZE_TARBALL
tar xzvf dockerize.tar.gz
sudo chown root dockerize
sudo chgrp root dockerize
sudo mv dockerize /usr/local/bin
rm *.tar.gz

# install swarm
sudo docker pull swarm

# install docker-bench-security
docker pull diogomonica/docker-bench-security
cat << EOF_BENCH_SECURITY > /usr/local/bin/docker-bench-security
#!/bin/sh

exec docker run -it --label docker-bench-security \
    --net host --pid host \
    -v /var/run/docker.sock:/var/run/docker.sock \
    -v /usr/lib/systemd:/usr/lib/systemd  \
    -v /etc:/etc \
    diogomonica/docker-bench-security

EOF_BENCH_SECURITY
chmod a+x /usr/local/bin/docker-bench-security

# install cAdvisor
curl -o /usr/local/bin/cadvisor -L $CADVISOR_EXE_URL
chmod a+x /usr/local/bin/cadvisor
docker pull google/cadvisor:latest

cat << EOF_CADVISOR > /etc/init/cadvisor.conf
description "cAdvisor"

start on filesystem and started docker
stop on runlevel [!2345]

#respawn

# @see https://github.com/google/cadvisor/blob/master/docs/running.md#standalone
script

    docker rm -f cadvisor  || true

    docker run  \
        --volume=/:/rootfs:ro          \
        --volume=/var/run:/var/run:rw  \
        --volume=/sys:/sys:ro          \
        --volume=/var/lib/docker/:/var/lib/docker:ro  \
        --publish=8080:8080  \
        --detach=true    \
        --restart=always \
        --name=cadvisor  \
        google/cadvisor:latest

end script
EOF_CADVISOR

# install weave
# @see https://github.com/zettio/weave
curl -o weave -L https://github.com/zettio/weave/releases/download/latest_release/weave
sudo chmod a+x  weave
sudo chown root weave
sudo chgrp root weave
sudo mv weave /usr/local/bin
# preload images
sudo weave setup

# install Docker-Host-Tools
# @see https://github.com/William-Yeh/docker-host-tools
DOCKER_HOST_TOOLS=( docker-rm-stopped  docker-rmi-repo  docker-inspect-attr )
for item in "${DOCKER_HOST_TOOLS[@]}"; do
  curl -o /usr/local/bin/$item  -sSL https://raw.githubusercontent.com/William-Yeh/docker-host-tools/master/$item
  chmod a+x /usr/local/bin/$item
done

#
# de-duplicate ID for Swarm
# @see https://github.com/docker/swarm/issues/563
# @see https://github.com/docker/swarm/issues/362
#
rm -f /etc/docker/key.json

# clean up
sudo docker rm `sudo docker ps --no-trunc -a -q`
sudo docker rmi -f busybox
for SERVICE in "chef-client" "puppet"; do
    /usr/sbin/update-rc.d -f $SERVICE remove
    rm /etc/init.d/$SERVICE
    pkill -9 -f $SERVICE
done
sudo apt-get autoremove -y chef puppet
sudo apt-get clean
sudo rm -f \
  /var/log/messages   \
  /var/log/lastlog    \
  /var/log/auth.log   \
  /var/log/syslog     \
  /var/log/daemon.log \
  /var/log/docker.log
sudo rm -rf  \
  /var/log/chef       \
  /var/chef           \
  /var/lib/puppet

#---------------------------------------#
# Vagrant-specific settings below
#

# add 'vagrant' user to docker group
sudo usermod -aG docker vagrant

# zero out the free space to save space in the final image
sudo dd if=/dev/zero of=/EMPTY bs=1M
sudo rm -f /EMPTY

rm -f /home/vagrant/.bash_history  /var/mail/vagrant

sudo cat <<HOSTNAME > /etc/hostname
localhost
HOSTNAME

cat <<EOF  >> /home/vagrant/.bashrc
export PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] '
export LC_CTYPE=C.UTF-8
lsb_release -a
EOF


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;

using OpenMetaverse;
using log4net;
using Nini.Config;
using Mono.Addins;

using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;

namespace OpenSim.Region.CoreModules.Avatar.Profile
{
    [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BasicProfileModule")]
    public class BasicProfileModule : IProfileModule, ISharedRegionModule
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        //
        // Module vars
        //
        private List<Scene> m_Scenes = new List<Scene>();
        private bool m_Enabled = false;

        #region ISharedRegionModule

        public void Initialise(IConfigSource config)
        {
            if(config.Configs["UserProfiles"] != null)
                return;

            m_log.DebugFormat("[PROFILE MODULE]: Basic Profile Module enabled");
            m_Enabled = true;
        }

        public void AddRegion(Scene scene)
        {
            if (!m_Enabled)
                return;

            lock (m_Scenes)
            {
                if (!m_Scenes.Contains(scene))
                {
                    m_Scenes.Add(scene);
                    // Hook up events
                    scene.EventManager.OnNewClient += OnNewClient;
                    scene.RegisterModuleInterface<IProfileModule>(this);
                }
            }
        }

        public void RegionLoaded(Scene scene)
        {
            if (!m_Enabled)
                return;
        }

        public void RemoveRegion(Scene scene)
        {
            if (!m_Enabled)
                return;

            lock (m_Scenes)
            {
                m_Scenes.Remove(scene);
            }
        }

        public void PostInitialise()
        {
        }

        public void Close()
        {
        }

        public string Name
        {
            get { return "BasicProfileModule"; }
        }

        public Type ReplaceableInterface
        {
            get { return typeof(IProfileModule); }
        }

        #endregion

        /// New Client Event Handler
        private void OnNewClient(IClientAPI client)
        {
            //Profile
            client.OnRequestAvatarProperties += RequestAvatarProperties;
        }

        public void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
        {
            IScene s = remoteClient.Scene;
            if (!(s is Scene))
                return;

//            Scene scene = (Scene)s;

            string profileUrl = String.Empty;
            string aboutText = String.Empty;
            string firstLifeAboutText = String.Empty;
            UUID image = UUID.Zero;
            UUID firstLifeImage = UUID.Zero;
            UUID partner = UUID.Zero;
            uint wantMask = 0;
            string wantText = String.Empty;
            uint skillsMask = 0;
            string skillsText = String.Empty;
            string languages = String.Empty;

            UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, avatarID);

            string name = "Avatar";
            int created = 0;
            if (account != null)
            {
                name = account.FirstName + " " + account.LastName;
                created = account.Created;
            }
            Byte[] membershipType = Utils.StringToBytes(name);

            profileUrl = "No profile data";
            aboutText = string.Empty;
            firstLifeAboutText = string.Empty;
            image = UUID.Zero;
            firstLifeImage = UUID.Zero;
            partner = UUID.Zero;

            remoteClient.SendAvatarProperties(avatarID, aboutText,
                        Util.ToDateTime(created).ToString(
                                "M/d/yyyy", CultureInfo.InvariantCulture),
                        membershipType, firstLifeAboutText,
                        (uint)(0 & 0xff),
                        firstLifeImage, image, profileUrl, partner);

            //Viewer expects interest data when it asks for properties.
            remoteClient.SendAvatarInterestsReply(avatarID, wantMask, wantText,
                                                    skillsMask, skillsText, languages);
        }

    }
}


text:
get "/profile" do

  if current_session?
    @user = current_user
    logger.info @user
    erb :'users/profile'
  else
    redirect '/'
  end
end

get '/user/new' do
  erb :'users/new'
end

post '/user/new' do
  new_user = User.new(params[:user])
  if new_user.save
    session[:user_id] = new_user.id
    redirect '/questions'
  else
    @error = "You must include a unique username and email, as well as a password."
    erb :'users/new'
  end
end


text:
import gettext
import json
import sys

import eventlet
from eventlet import wsgi
from oslo.config import cfg

gettext.install('climate', unicode=1)

from climate.api.v1 import app as v1_app
from climate.api.v2 import app as v2_app
from climate.openstack.common import log as logging
from climate.utils import service as service_utils

opts = [
    cfg.IntOpt('port', default=1234,
               help='Port that will be used to listen on'),
]

api_opts = [
    cfg.BoolOpt('enable_v1_api',
                default=True,
                help='Deploy the v1 API.'),
]

LOG = logging.getLogger(__name__)
CONF = cfg.CONF
CONF.register_cli_opts(opts)
CONF.register_opts(api_opts)

CONF.import_opt('host', 'climate.config')

class VersionSelectorApplication(object):
    """Maps WSGI versioned apps and defines default WSGI app."""

    def __init__(self):
        self._status = ''
        self._response_headers = []
        self.v1 = v1_app.make_app()
        self.v2 = v2_app.make_app()

    def _append_versions_from_app(self, versions, app, environ):
        tmp_versions = app(environ, self.internal_start_response)
        if self._status.startswith("300"):
            tmp_versions = json.loads("".join(tmp_versions))
            versions['versions'].extend(tmp_versions['versions'])

    def internal_start_response(self, status, response_headers, exc_info=None):
        self._status = status
        self._response_headers = response_headers

    def __call__(self, environ, start_response):
        self._status = ''
        self._response_headers = []

        if environ['PATH_INFO'] == '/' or environ['PATH_INFO'] == '/versions':
            versions = {'versions': []}
            self._append_versions_from_app(versions, self.v1, environ)
            self._append_versions_from_app(versions, self.v2, environ)
            if len(versions['versions']):
                start_response("300 Multiple Choices",
                               [("Content-Type", "application/json")])
                return [json.dumps(versions)]
            else:
                start_response("204 No Content", [])
                return []
        else:
            if environ['PATH_INFO'].startswith('/v1'):
                return self.v1(environ, start_response)
            return self.v2(environ, start_response)

def main():
    """Entry point to start Climate API wsgi server."""
    cfg.CONF(sys.argv[1:], project='climate', prog='climate-api')
    service_utils.prepare_service(sys.argv)
    logging.setup("climate")
    if not CONF.enable_v1_api:
        app = v2_app.make_app()
    else:
        app = VersionSelectorApplication()

    wsgi.server(eventlet.listen((CONF.host, CONF.port), backlog=500), app)

if __name__ == '__main__':
    main()


text:
package org.elasticmq.actor.queue.operations

import org.elasticmq.actor.queue.{InternalMessage, QueueActorStorage}
import org.elasticmq.msg.SendMessage
import org.elasticmq.util.Logging
import org.elasticmq.{DeduplicationId, MoveDestination, MoveToDLQ}

trait MoveMessageOps extends Logging {
  this: QueueActorStorage =>

  def moveMessage(message: InternalMessage, destination: MoveDestination): Unit = {

    copyMessagesToActorRef.foreach { _ ! SendMessage(message.toNewMessageData) }

    destination match {
      case MoveToDLQ =>
        if (queueData.isFifo) {
          CommonOperations.wasRegistered(message.toNewMessageData, fifoMessagesHistory) match {
            case Some(_) => ()
            case None =>
              logger.debug(s"Moved message (${message.id}) from FIFO queue to ${queueData.name}")
              moveMessageToQueue(regenerateDeduplicationId(message))
          }
        } else {
          logger.debug(s"Moved message (${message.id}) to ${queueData.name}")
          moveMessageToQueue(message)
        }
    }
  }

  private def regenerateDeduplicationId(internalMessage: InternalMessage): InternalMessage = {
    internalMessage.copy(
      messageDeduplicationId = Some(DeduplicationId(internalMessage.id))
    )
  }

  private def moveMessageToQueue(internalMessage: InternalMessage): Unit = {
    messageQueue += internalMessage
    fifoMessagesHistory = fifoMessagesHistory.addNew(internalMessage)
  }
}


text:
using Lucene.Net.Benchmarks.ByTask.Utils;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Console = Lucene.Net.Support.SystemConsole;

namespace Lucene.Net.Benchmarks.ByTask.Feeds
{

    ///
    /// Base class for source of data for benchmarking.
    ///
    /// <remarks>
    /// Keeps track of various statistics, such as how many data items were generated,
    /// size in bytes etc.
    /// <para/>
    /// Supports the following configuration parameters:
    /// <list type="bullet">
    ///     <item><term>content.source.forever</term><description>specifies whether to generate items forever (default=true).</description></item>
    ///     <item><term>content.source.verbose</term><description>specifies whether messages should be output by the content source (default=false).</description></item>
    ///     <item><term>content.source.encoding</term><description>
    ///         specifies which encoding to use when
    ///         reading the files of that content source. Certain implementations may define
    ///         a default value if this parameter is not specified. (default=null).
    ///     </description></item>
    ///     <item><term>content.source.log.step</term><description>
    ///         specifies for how many items a
    ///         message should be logged. If set to 0 it means no logging should occur.
    ///         NOTE: if verbose is set to false, logging should not occur even if
    ///         logStep is not 0 (default=0).
    ///     </description></item>
    /// </list>
    /// </remarks>
    public abstract class ContentItemsSource : IDisposable
    {
        private long bytesCount;
        private long totalBytesCount;
        private int itemCount;
        private int totalItemCount;
        private Config config;

        private int lastPrintedNumUniqueTexts = 0;
        private long lastPrintedNumUniqueBytes = 0;
        private int printNum = 0;

        protected bool m_forever;
        protected int m_logStep;
        protected bool m_verbose;
        protected Encoding m_encoding;

        /// update count of bytes generated by this source
        protected void AddBytes(long numBytes)
        {
            lock (this)
            {
                bytesCount += numBytes;
                totalBytesCount += numBytes;
            }
        }

        /// update count of items generated by this source
        protected void AddItem()
        {
            lock (this)
            {
                ++itemCount;
                ++totalItemCount;
            }
        }

        ///
        /// A convenience method for collecting all the files of a content source from
        /// a given directory. The collected <see cref="FileInfo"/> instances are stored in the
        /// given <paramref name="files"/>.
        ///
        protected void CollectFiles(DirectoryInfo dir, IList<FileInfo> files)
        {
            CollectFilesImpl(dir, files);
            files.Sort(new FileNameComparer());
        }

        private void CollectFilesImpl(DirectoryInfo dir, IList<FileInfo> files)
        {
            foreach (var sub in dir.EnumerateDirectories())
            {
                CollectFilesImpl(sub, files);
            }

            files.AddRange(dir.GetFiles());
        }

        private class FileNameComparer : IComparer<FileInfo>
        {
            public int Compare(FileInfo x, FileInfo y)
            {
                return x.FullName.CompareToOrdinal(y.FullName);
            }
        }

        ///
        /// Returns <c>true</c> whether it's time to log a message (depending on verbose and
        /// the number of items generated).
        ///
        /// <returns></returns>
        protected bool ShouldLog()
        {
            return m_verbose && m_logStep > 0 && itemCount % m_logStep == 0;
        }

        /// Called when reading from this content source is no longer required.
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// Called when reading from this content source is no longer required.
        protected abstract void Dispose(bool disposing);

        /// Returns the number of bytes generated since last reset.
        public long BytesCount { get { return bytesCount; } }

        /// Returns the number of generated items since last reset.
        public int ItemsCount { get { return itemCount; } }

        public Config Config { get { return config; } }

        /// Returns the total number of bytes that were generated by this source.
        public long TotalBytesCount { get { return totalBytesCount; } }

        /// Returns the total number of generated items.
        public int TotalItemsCount { get { return totalItemCount; } }

        ///
        /// Resets the input for this content source, so that the test would behave as
        /// if it was just started, input-wise.
        /// <para/>
        /// NOTE: the default implementation resets the number of bytes and
        /// items generated since the last reset, so it's important to call
        /// <c>base.ResetInputs()</c> in case you override this method.
        ///
        public virtual void ResetInputs()
        {
            bytesCount = 0;
            itemCount = 0;
        }

        ///
        /// Sets the <see cref="Utils.Config"/> for this content source. If you override this
        /// method, you must call <c>base.SetConfig(config)</c>.
        ///
        /// <param name="config"></param>
        public virtual void SetConfig(Config config)
        {
            this.config = config;
            m_forever = config.Get("content.source.forever", true);
            m_logStep = config.Get("content.source.log.step", 0);
            m_verbose = config.Get("content.source.verbose", false);
            string encodingStr = config.Get("content.source.encoding", null);
            if (!string.IsNullOrWhiteSpace(encodingStr))
            {
                m_encoding = Encoding.GetEncoding(encodingStr);
            }
            else
            {
                m_encoding = Encoding.GetEncoding(0); // Default system encoding
            }
        }

        public virtual void PrintStatistics(string itemsName)
        {
            if (!m_verbose)
            {
                return;
            }
            bool print = false;
            string col = "                  ";
            StringBuilder sb = new StringBuilder();
            string newline = Environment.NewLine;
            sb.Append("------------> ").Append(GetType().GetTypeInfo().Name).Append(" statistics (").Append(printNum).Append("): ").Append(newline);
            int nut = TotalItemsCount;
            if (nut > lastPrintedNumUniqueTexts)
            {
                print = true;
                sb.Append("total count of " + itemsName + ": ").Append(Formatter.Format(0, nut, col)).Append(newline);
                lastPrintedNumUniqueTexts = nut;
            }
            long nub = TotalBytesCount;
            if (nub > lastPrintedNumUniqueBytes)
            {
                print = true;
                sb.Append("total bytes of " + itemsName + ": ").Append(Formatter.Format(0, nub, col)).Append(newline);
                lastPrintedNumUniqueBytes = nub;
            }
            if (ItemsCount > 0)
            {
                print = true;
                sb.Append("num " + itemsName + " added since last inputs reset:   ").Append(Formatter.Format(0, ItemsCount, col)).Append(newline);
                sb.Append("total bytes added for " + itemsName + " since last inputs reset: ").Append(Formatter.Format(0, BytesCount, col)).Append(newline);
            }
            if (print)
            {
                Console.WriteLine(sb.Append(newline).ToString());
                printNum++;
            }
        }
    }
}


text:
package org.hbase.async;

/**
 * Appends data to one or more columns in BigTable, creating the columns if they
 * do not exist. The {@code value} is simply concatenated with whatever is
 * already in the column. An append operation will acquire a lock on the row
 * so that all column operations are atomic with respect to writers. However
 * reads across the row are not atomic and therefore readers may see partially
 * completed operations.
 *

 * Note that the results of the append operation
 * are not returned at this time. Issue a {@see GetRequest} to fetch the results.
 *

 *
A note on passing {@code byte} arrays in argument

 * None of the method that receive a {@code byte[]} in argument will copy it.
 * For more info, please refer to the documentation of {@link HBaseRpc}.
 *
A note on passing {@code String}s in argument

 * All strings are assumed to use the platform's default charset.
 *
A note on passing {@code timestamp}s in argument

 * BigTable orders all the writes based on timestamps from {@code AppendRequest}
 * irrespective of the actual order in which they're received or stored by
 * a RegionServer.  In other words, if you send a first {@code AppendRequest}
 * with timestamp T, and then later send another one for the same table,
 * key, family and qualifier, but with timestamp T - 1, then the second
 * write will look like it was applied before the first one when you read
 * this cell back from BigTable. When manually setting timestamps, it is thus
 * strongly recommended to use real UNIX timestamps in milliseconds, e.g.
 * from {@link System#currentTimeMillis}.
 *

 * If you want to let BigTable set the timestamp on a write at the time it's
 * applied within the RegionServer, then use {@link KeyValue#TIMESTAMP_NOW}
 * as a timestamp.  The timestamp is set right before being written to the WAL
 * (Write Ahead Log).  Note however that this has a subtle consequence: if a
 * write succeeds from the server's point of view, but fails from the client's
 * point of view (maybe because the client got disconnected from the server
 * before the server could acknowledge the write), then if the client retries
 * the write it will create another version of the cell with a different
 * timestamp.
 * @since 1.7
 */
public final class AppendRequest extends BatchableRpc
  implements HBaseRpc.HasTable, HBaseRpc.HasKey, HBaseRpc.HasFamily,
             HBaseRpc.HasQualifiers, HBaseRpc.HasValues, HBaseRpc.IsEdit,
             /* legacy: */ HBaseRpc.HasQualifier, HBaseRpc.HasValue {

  /**
   * Invariants:
   *   - qualifiers.length == values.length
   *   - qualifiers.length > 0
   */
  private final byte[][] qualifiers;
  private final byte[][] values;

  /** Whether or not to return the result of the append request */
  private boolean return_result = false;

  /**
   * Constructor using current time.
   * These byte arrays will NOT be copied.
   *

   * Note: If you want to set your own timestamp, use
   * {@link #AppendRequest(byte[], byte[], byte[], byte[], byte[], long)}
   * instead.  This constructor will let the RegionServer assign the timestamp
   * to this write at the time using {@link System#currentTimeMillis} right
   * before the write is persisted to the WAL.
   * @param table The table to edit.
   * @param key The key of the row to edit in that table.
   * @param family The column family to edit in that table.
   * @param qualifier The column qualifier to edit in that family.
   * @param value The value to store.
   */
  public AppendRequest(final byte[] table,
                    final byte[] key,
                    final byte[] family,
                    final byte[] qualifier,
                    final byte[] value) {
    this(table, key, family, qualifier, value, KeyValue.TIMESTAMP_NOW);
  }

  /**
   * Constructor for multiple columns using current time.
   * These byte arrays will NOT be copied.
   *

   * Note: If you want to set your own timestamp, use
   * {@link #AppendRequest(byte[], byte[], byte[], byte[][], byte[][], long)}
   * instead.  This constructor will let the RegionServer assign the timestamp
   * to this write at the time using {@link System#currentTimeMillis} right
   * before the write is persisted to the WAL.
   * @param table The table to edit.
   * @param key The key of the row to edit in that table.
   * @param family The column family to edit in that table.
   * @param qualifiers The column qualifiers to edit in that family.
   * @param values The corresponding values to store.
   * @throws IllegalArgumentException if {@code qualifiers.length == 0}
   * or if {@code qualifiers.length != values.length}
   */
  public AppendRequest(final byte[] table,
                    final byte[] key,
                    final byte[] family,
                    final byte[][] qualifiers,
                    final byte[][] values) {
    this(table, key, family, qualifiers, values, KeyValue.TIMESTAMP_NOW, false);
  }

  /**
   * Constructor for a specific timestamp.
   * These byte arrays will NOT be copied.
   * @param table The table to edit.
   * @param key The key of the row to edit in that table.
   * @param family The column family to edit in that table.
   * @param qualifier The column qualifier to edit in that family.
   * @param value The value to store.
   * @param timestamp The timestamp to set on this edit.
   */
  public AppendRequest(final byte[] table,
                    final byte[] key,
                    final byte[] family,
                    final byte[] qualifier,
                    final byte[] value,
                    final long timestamp) {
    this(table, key, family, new byte[][] { qualifier },
        new byte[][] { value }, timestamp, false);
  }

  /**
   * Constructor for multiple columns with a specific timestamp.
   * These byte arrays will NOT be copied.
   * @param table The table to edit.
   * @param key The key of the row to edit in that table.
   * @param family The column family to edit in that table.
   * @param qualifiers The column qualifiers to edit in that family.
   * @param values The corresponding values to store.
   * @param timestamp The timestamp to set on this edit.
   * @throws IllegalArgumentException if {@code qualifiers.length == 0}
   * or if {@code qualifiers.length != values.length}
   */
  public AppendRequest(final byte[] table,
                    final byte[] key,
                    final byte[] family,
                    final byte[][] qualifiers,
                    final byte[][] values,
                    final long timestamp) {
    this(table, key, family, qualifiers, values, timestamp, false);
  }

  /**
   * Constructor from a {@link KeyValue}.
   * @param table The table to edit.
   * @param kv The {@link KeyValue} to store.
   */
  public AppendRequest(final byte[] table,
                     final KeyValue kv) {
    super(table, kv.key(), kv.family(), kv.timestamp(), RowLock.NO_LOCK);
    this.qualifiers = new byte[][] { kv.qualifier() };
    this.values = new byte[][] { kv.value() };
  }

  /** Private constructor.  */
  private AppendRequest(final byte[] table,
                     final byte[] key,
                     final byte[] family,
                     final byte[][] qualifiers,
                     final byte[][] values,
                     final long timestamp,
                     final boolean return_result) {
    super(table, key, family, timestamp, RowLock.NO_LOCK);
    KeyValue.checkFamily(family);

    if (qualifiers.length != values.length) {
      throw new IllegalArgumentException("Have " + qualifiers.length
        + " qualifiers and " + values.length + " values.  Should be equal.");
    } else if (qualifiers.length == 0) {
      throw new IllegalArgumentException("Need at least one qualifier/value.");
    }
    for (int i = 0; i < qualifiers.length; i++) {
      KeyValue.checkQualifier(qualifiers[i]);
      KeyValue.checkValue(values[i]);
    }
    this.qualifiers = qualifiers;
    this.values = values;
  }

  @Override
  public byte[] table() {
    return table;
  }

  @Override
  public byte[] key() {
    return key;
  }

  /**
   * Returns the first qualifier of the set of edits in this RPC.
   * {@inheritDoc}
   */
  @Override
  public byte[] qualifier() {
    return qualifiers[0];
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public byte[][] qualifiers() {
    return qualifiers;
  }

  /**
   * Returns the first value of the set of edits in this RPC.
   * {@inheritDoc}
   */
  @Override
  public byte[] value() {
    return values[0];
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public byte[][] values() {
    return values;
  }

  public String toString() {
    return super.toStringWithQualifiers("AppendRequest",
                                       family, qualifiers, values,
                                       ", timestamp=" + timestamp
                                       + ", lockid=" + lockid
                                       + ", durable=" + durable
                                       + ", return_result=" + return_result
                                       + ", bufferable=" + super.bufferable);
  }

  /** @param return_result Whether or not to fetch the results of the append
   * from HBase. */
  public void returnResult(boolean return_result) {
    this.return_result = return_result;
  }

  /** @return Whether or not to fetch the results of the append from HBase. */
  public boolean returnResult() {
    return return_result;
  }

}


text:
<?
defined('C5_EXECUTE') or die("Access Denied.");
class PageForbiddenController extends Concrete5_Controller_PageForbidden {}


text:
export const databaseDsn = process.env.DB || 'mysql://myapp:myapp@localhost/myapp';

// session key
export const crypto = '---- place here ----';

// passport-google config
export const GOOGLE_CLIENT_ID = '---- place here ----';
export const GOOGLE_CLIENT_SECRET = '---- place here ----';

// passport-facebook config
export const FACEBOOK_APP_ID = '---- place here ----';
export const FACEBOOK_APP_SECRET = '---- place here ----';

// passport-twitter config
export const TWITTER_CONSUMER_KEY = '---- place here ----';
export const TWITTER_CONSUMER_SECRET = '---- place here ----';

export {port, host, hostAddress} from './config.client';


text:
'use strict';

/**
 * @method InstanceSizingMixin
 * @private
 * @param {Class} SuperClass a superclass to apply the mixin too
 */
const InstanceSizingMixin = (SuperClass) => {
  /**
   * @class
   * @memberof module:CivoCloud/api
   * @augments module:CivoCloud/api.Civo
   * @see {@link https://www.civo.com/api/sizes}
   */
  const InstanceSizing = class extends SuperClass {
    /**
     * @method module:CivoCloud/api.InstanceSizing~listInstanceSizes
     * @see {@link https://www.civo.com/api/sizes#listing-available-sizes}
     * @description gets an array of the currently available instance sizes on civo cloud [GET]
     * @returns {Promise} a promise wich resolves with the instance size list or rejects with an
     * error
     * @public
     */
    listInstanceSizes() {
      return this.getRequest('sizes');
    }
  };
  return InstanceSizing;
};

module.exports = InstanceSizingMixin;


text:
#include <linux/module.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <asm/io.h>

/*
 * output data from a potentially misaligned buffer
 */
void __outsl(unsigned long addr, const void *buffer, int count)
{
	const unsigned char *buf = buffer;
	unsigned long val;

	while (count--) {
		memcpy(&val, buf, 4);
		outl(val, addr);
		buf += 4;
	}
}
EXPORT_SYMBOL(__outsl);


text:
@implementation ALinBottomToolView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (NSArray *)tools
{
    return @[@"talk_public_40x40", @"talk_private_40x40", @"talk_sendgift_40x40", @"talk_rank_40x40", @"talk_share_40x40", @"talk_close_40x40"];
}

- (void)setup
{
    CGFloat wh = 40;
    CGFloat margin = (ALinScreenWidth - wh * self.tools.count) / (self.tools.count + 1.0);
    CGFloat x = 0;
    CGFloat y = 0;
    for (int i = 0; i<self.tools.count; i++) {
        x = margin + (margin + wh) * i;
        UIImageView *toolView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, wh, wh)];
        toolView.userInteractionEnabled = YES;
        toolView.tag = i;
        toolView.image = [UIImage imageNamed:self.tools[i]];
        [toolView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click:)]];
        [self addSubview:toolView];
    }
}

- (void)click:(UITapGestureRecognizer *)tapRec
{
    if (self.clickToolBlock) {
        self.clickToolBlock(tapRec.view.tag);
    }
}
@end


text:
package io.pravega.controller.store;
import io.pravega.common.util.BitConverter;
import io.pravega.common.util.ByteArraySegment;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

import io.pravega.controller.store.stream.OperationContext;
import org.apache.commons.lang3.tuple.Pair;

/**
 * Properties of a Scope and operations that can be performed on it.
 * Identifier for a Scope is its name.
 */
public interface Scope {
    /**
     * Retrieve name of the scope.
     *
     * @return Name of the scope
     */
    String getName();

    /**
     * Create the scope.
     * @param context operation context
     * @return null on success and exception on failure.
     */
    CompletableFuture<Void> createScope(OperationContext context);

    /**
     * Delete the scope.
     *
     * @param context operation context
     * @return null on success and exception on failure.
     */
    CompletableFuture<Void> deleteScope(OperationContext context);

    /**
     * Delete the scope recursively.
     *
     * @param context operation context
     * @return null on success and exception on failure.
     */
    CompletableFuture<Void> deleteScopeRecursive(OperationContext context);

    /**
     * A paginated api on the scope to get requested number of streams from under the scope starting from the continuation token.
     *
     * @param limit maximum number of streams to return
     * @param continuationToken continuation token from where to start.
     * @param executor executor
     * @param context operation context
     * @return A future, which upon completion, will hold a pair of list of stream names and a new continuation token.
     */
    CompletableFuture<Pair<List<String>, String>> listStreams(final int limit, final String continuationToken, Executor executor,
                                                              OperationContext context);

    /**
     * A paginated api on the scope to get streams with the specified tag starting from the continuation token.
     * @param tag Stream Tag.
     * @param continuationToken Continuation token from where to start.
     * @param executor executor.
     * @param context operation context.
     * @return A fture, when upon completion, will hold a pair of list of stream names and a new continuation token.
     */
    CompletableFuture<Pair<List<String>, String>> listStreamsForTag(final String tag, final String continuationToken, Executor executor,
                                                              OperationContext context);

    /**
     * List existing streams in scopes.
     * @param context operation context
     * @return List of streams in scope
     */
    CompletableFuture<List<String>> listStreamsInScope(OperationContext context);

    /**
     * Refresh the scope object. Typically to be used to invalidate any caches.
     * This allows us reuse of scope object without having to recreate a new scope object for each new operation
     */
    void refresh();

    /**
     * A paginated api on the scope to get requested number of KeyValueTables from under the scope
     * starting from the continuation token.
     *
     * @param limit maximum number of kvtables to return
     * @param continuationToken continuation token from where to start.
     * @param context operation context
     * @param executor executor
     * @return A future, which upon completion, will hold a pair of list of kvtable names and a new continuation token.
     */
    CompletableFuture<Pair<List<String>, String>> listKeyValueTables(final int limit, final String continuationToken,
                                                                     final Executor executor, OperationContext context);

    CompletableFuture<UUID> getReaderGroupId(String rgName, OperationContext context);

    CompletableFuture<Boolean> isScopeSealed(String scopeName, OperationContext context);

    CompletableFuture<UUID> getScopeId(String scopeName, OperationContext context);

    default UUID newId() {
        return UUID.randomUUID();
    }

    default byte[] getIdInBytes(UUID id) {
        byte[] b = new byte[2 * Long.BYTES];
        BitConverter.writeUUID(new ByteArraySegment(b), id);
        return b;
    }
}


text:
package com.baoyongan.java.eg.pattern.singleton;

public class SingletonTy {
    private SingletonTy(){
        System.out.println("初始化了");
    }
    private final static SingletonTy INSTANCE=new SingletonTy();
    public static SingletonTy getInstance(){
        return INSTANCE;
    }
    public void say(String name){
        System.out.println("Hello "+name);
    }
}


text:
"""Uniform noise adapter distribution."""

import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_compression.python.distributions import helpers

__all__ = [
    "UniformNoiseAdapter",
    "NoisyMixtureSameFamily",
    "NoisyNormal",
    "NoisyLogistic",
    "NoisyLaplace",
    "NoisyNormalMixture",
    "NoisyLogisticMixture",
]

def _logsum_expbig_minus_expsmall(big, small):
  """Numerically stable evaluation of `log(exp(big) - exp(small))`.

  This assumes `small <= big` and arguments that can be broadcast against each
  other.

  Args:
    big: Floating-point `tf.Tensor`.
    small: Floating-point `tf.Tensor`.

  Returns:
    `tf.Tensor` containing the result.
  """
  with tf.name_scope("logsum_expbig_minus_expsmall"):
    return tf.math.log1p(-tf.exp(small - big)) + big

class UniformNoiseAdapter(tfp.distributions.Distribution):
  """Additive i.i.d. uniform noise adapter distribution.

  Given a base `tfp.distributions.Distribution` object, this distribution
  models the base distribution after addition of independent uniform noise.

  Effectively, the base density function is convolved with a box kernel of width
  one. The resulting density can be efficiently evaluated via the relation:
  ```
  (p * u)(x) = c(x + .5) - c(x - .5)
  ```
  where `p` and `u` are the base density and the unit-width uniform density,
  respectively, and `c` is the cumulative distribution function (CDF)
  corresponding to `p`. This is described in appendix 6.2 of the paper:

  > "Variational image compression with a scale hyperprior"

  > J. Ballé, D. Minnen, S. Singh, S. J. Hwang, N. Johnston

  > https://openreview.net/forum?id=rkcQFMZRb

  For best numerical stability, the base `Distribution` should implement both
  `cdf()` and `survival_function()` and/or their `log_*` equivalents.
  """

  def __init__(self, base, name="UniformNoiseAdapter"):
    """Initializer.

    Args:
      base: A `tfp.distributions.Distribution` object representing a
        continuous-valued random variable.
      name: String. A name for this distribution.
    """
    parameters = dict(locals())
    self._base = base
    super().__init__(
        dtype=base.dtype,
        reparameterization_type=base.reparameterization_type,
        validate_args=base.validate_args,
        allow_nan_stats=base.allow_nan_stats,
        parameters=parameters,
        name=name,
    )

  @property
  def base(self):
    """The base distribution (without uniform noise)."""
    return self._base

  def _batch_shape_tensor(self):
    return self.base.batch_shape_tensor()

  def _batch_shape(self):
    return self.base.batch_shape

  def _event_shape_tensor(self):
    return self.base.event_shape_tensor()

  def _event_shape(self):
    return self.base.event_shape

  def _sample_n(self, n, seed=None):
    with tf.name_scope("transform"):
      n = tf.convert_to_tensor(n, name="n")
      samples = self.base.sample(n, seed=seed)
      return samples + tf.random.uniform(
          tf.shape(samples), minval=-.5, maxval=.5, dtype=samples.dtype)

  def _log_prob(self, y):
    if not hasattr(self.base, "_log_cdf"):
      raise NotImplementedError(
          "`log_prob()` is not implemented unless the base distribution "
          "implements `log_cdf()`.")
    try:
      return self._log_prob_with_logsf_and_logcdf(y)
    except NotImplementedError:
      return self._log_prob_with_logcdf(y)

  def _log_prob_with_logcdf(self, y):
    return _logsum_expbig_minus_expsmall(
        self.base.log_cdf(y + .5), self.base.log_cdf(y - .5))

  def _log_prob_with_logsf_and_logcdf(self, y):
    """Compute log_prob(y) using log survival_function and cdf together."""
    # There are two options that would be equal if we had infinite precision:
    # Log[ sf(y - .5) - sf(y + .5) ]
    #   = Log[ exp{logsf(y - .5)} - exp{logsf(y + .5)} ]
    # Log[ cdf(y + .5) - cdf(y - .5) ]
    #   = Log[ exp{logcdf(y + .5)} - exp{logcdf(y - .5)} ]
    logsf_y_plus = self.base.log_survival_function(y + .5)
    logsf_y_minus = self.base.log_survival_function(y - .5)
    logcdf_y_plus = self.base.log_cdf(y + .5)
    logcdf_y_minus = self.base.log_cdf(y - .5)

    # Important:  Here we use select in a way such that no input is inf, this
    # prevents the troublesome case where the output of select can be finite,
    # but the output of grad(select) will be NaN.

    # In either case, we are doing Log[ exp{big} - exp{small} ]
    # We want to use the sf items precisely when we are on the right side of the
    # median, which occurs when logsf_y < logcdf_y.
    condition = logsf_y_plus < logcdf_y_plus
    big = tf.where(condition, logsf_y_minus, logcdf_y_plus)
    small = tf.where(condition, logsf_y_plus, logcdf_y_minus)
    return _logsum_expbig_minus_expsmall(big, small)

  def _prob(self, y):
    if not hasattr(self.base, "_cdf"):
      raise NotImplementedError(
          "`prob()` is not implemented unless the base distribution implements "
          "`cdf()`.")
    try:
      return self._prob_with_sf_and_cdf(y)
    except NotImplementedError:
      return self._prob_with_cdf(y)

  def _prob_with_cdf(self, y):
    return self.cdf(y + .5) - self.cdf(y - .5)

  def _prob_with_sf_and_cdf(self, y):
    # There are two options that would be equal if we had infinite precision:
    # sf(y - .5) - sf(y + .5)
    # cdf(y + .5) - cdf(y - .5)
    sf_y_plus = self.base.survival_function(y + .5)
    sf_y_minus = self.base.survival_function(y - .5)
    cdf_y_plus = self.base.cdf(y + .5)
    cdf_y_minus = self.base.cdf(y - .5)

    # sf_prob has greater precision iff we're on the right side of the median.
    return tf.where(
        sf_y_plus < cdf_y_plus,
        sf_y_minus - sf_y_plus, cdf_y_plus - cdf_y_minus)

  def _mean(self):
    return self.base.mean()

  def _quantization_offset(self):
    return helpers.quantization_offset(self.base)

  def _lower_tail(self, tail_mass):
    return helpers.lower_tail(self.base, tail_mass)

  def _upper_tail(self, tail_mass):
    return helpers.upper_tail(self.base, tail_mass)

  @classmethod
  def _parameter_properties(cls, dtype=tf.float32, num_classes=None):
    raise NotImplementedError(
        f"`{cls.__name__}` does not implement `_parameter_properties`.")

class NoisyMixtureSameFamily(tfp.distributions.MixtureSameFamily):
  """Mixture of distributions with additive i.i.d. uniform noise."""

  def __init__(self, mixture_distribution, components_distribution,
               name="NoisyMixtureSameFamily"):
    """Initializer, taking the same arguments as `tfpd.MixtureSameFamily`."""
    super().__init__(
        mixture_distribution=mixture_distribution,
        components_distribution=UniformNoiseAdapter(components_distribution),
        name=name,
    )
    self._base = tfp.distributions.MixtureSameFamily(
        mixture_distribution=mixture_distribution,
        components_distribution=components_distribution,
        name=name + "Base",
    )

  @property
  def base(self):
    """The base distribution (without uniform noise)."""
    return self._base

  def _batch_shape_tensor(self):
    return self.base.batch_shape_tensor()

  def _batch_shape(self):
    return self.base.batch_shape

  def _event_shape_tensor(self):
    return self.base.event_shape_tensor()

  def _event_shape(self):
    return self.base.event_shape

  def _quantization_offset(self):
    # Picks the "peakiest" of the component quantization offsets.
    offsets = helpers.quantization_offset(self.components_distribution)
    rank = self.batch_shape.rank
    transposed_offsets = tf.transpose(offsets, [rank] + list(range(rank)))
    component = tf.argmax(self.log_prob(transposed_offsets), axis=0)
    return tf.gather(offsets, component, axis=-1, batch_dims=rank)

  def _lower_tail(self, tail_mass):
    return helpers.lower_tail(self.base, tail_mass)

  def _upper_tail(self, tail_mass):
    return helpers.upper_tail(self.base, tail_mass)

  @classmethod
  def _parameter_properties(cls, dtype=tf.float32, num_classes=None):
    raise NotImplementedError(
        f"`{cls.__name__}` does not implement `_parameter_properties`.")

class NoisyNormal(UniformNoiseAdapter):
  """Gaussian distribution with additive i.i.d. uniform noise."""

  def __init__(self, name="NoisyNormal", **kwargs):
    """Initializer, taking the same arguments as `tfpd.Normal`."""
    super().__init__(tfp.distributions.Normal(**kwargs), name=name)

class NoisyLogistic(UniformNoiseAdapter):
  """Logistic distribution with additive i.i.d. uniform noise."""

  def __init__(self, name="NoisyLogistic", **kwargs):
    """Initializer, taking the same arguments as `tfpd.Logistic`."""
    super().__init__(tfp.distributions.Logistic(**kwargs), name=name)

class NoisyLaplace(UniformNoiseAdapter):
  """Laplacian distribution with additive i.i.d. uniform noise."""

  def __init__(self, name="NoisyLaplace", **kwargs):
    """Initializer, taking the same arguments as `tfpd.Laplace`."""
    super().__init__(tfp.distributions.Laplace(**kwargs), name=name)

class NoisyNormalMixture(NoisyMixtureSameFamily):
  """Mixture of normal distributions with additive i.i.d. uniform noise."""

  def __init__(self, loc, scale, weight, name="NoisyNormalMixture"):
    """Initializer.

    Args:
      loc: Location parameters of `tfpd.Normal` component distributions.
      scale: Scale parameters of `tfpd.Normal` component distributions.
      weight: `probs` parameter of `tfpd.Categorical` mixture distribution.
      name: A name for this distribution.
    """
    super().__init__(
        mixture_distribution=tfp.distributions.Categorical(probs=weight),
        components_distribution=tfp.distributions.Normal(loc=loc, scale=scale),
        name=name,
    )

class NoisyLogisticMixture(NoisyMixtureSameFamily):
  """Mixture of logistic distributions with additive i.i.d. uniform noise."""

  def __init__(self, loc, scale, weight, name="NoisyLogisticMixture"):
    """Initializer.

    Args:
      loc: Location parameters of `tfpd.Logistic` component distributions.
      scale: Scale parameters of `tfpd.Logistic` component distributions.
      weight: `probs` parameter of `tfpd.Categorical` mixture distribution.
      name: A name for this distribution.
    """
    super().__init__(
        mixture_distribution=tfp.distributions.Categorical(probs=weight),
        components_distribution=tfp.distributions.Logistic(
            loc=loc, scale=scale),
        name=name,
    )


text:
from datetime import datetime
import unittest

from django.db import models
from django.http import HttpResponse
from django.utils import simplejson

from dynamicresponse.json_response import JsonResponse

class ModelWithSerializeFields(models.Model):
    title = models.CharField('Title', max_length=200)
    text = models.TextField('Text')
    _password = models.CharField('Password', max_length=100)

    def serialize_fields(self):
        return [
            'id',
            'title'
        ]

class ModelWithoutSerializeFields(models.Model):
    title = models.CharField('Title', max_length=200)
    text = models.TextField('Text')
    _password = models.CharField('Password', max_length=100)

class JsonResponseTest(unittest.TestCase):

    def setUp(self):
        self.testObj = { 'testval': 99, 'testStr': 'Ice Cone', 'today': datetime(2012, 5, 17) }
        self.jsonres = JsonResponse(self.testObj)

        self.modelWithSerializeFields = JsonResponse(ModelWithSerializeFields(title='Hadouken',
                                                                            text='is said repeatedly in Street Fighter',
                                                                            _password='is secret'))

        self.modelbaseWithoutSerializeFields = ModelWithoutSerializeFields(title='Hadouken',
                                                                        text='is said repeatedly in Street Fighter',
                                                                        _password='is secret')

        self.modelWithoutSerializeFields = JsonResponse(self.modelbaseWithoutSerializeFields)

    def testIsInstanceOfHttpResponse(self):
        self.assertTrue(isinstance(self.jsonres, HttpResponse), 'should be an instance of HttpResponse')
        self.assertTrue(isinstance(self.modelWithSerializeFields, HttpResponse), 'should be an instance of HttpResponse')
        self.assertTrue(isinstance(self.modelWithoutSerializeFields, HttpResponse), 'should be an instance of HttpResponse')

    def testSetsCorrectMimetype(self):
        self.assertEqual(self.jsonres['Content-Type'], 'application/json; charset=utf-8')
        self.assertEqual(self.modelWithSerializeFields['Content-Type'], 'application/json; charset=utf-8')
        self.assertEqual(self.modelWithoutSerializeFields['Content-Type'], 'application/json; charset=utf-8')

    def testDictContentConvertsToJson(self):
        result = simplejson.loads(self.jsonres.content)

        for key, value in result.items():
            self.assertEqual(self.testObj.get(key).__str__(), value.__str__())

    def testModelWithSerializeFieldsConvertsToJson(self):
        to_equal = { u'id': None, u'title': u'Hadouken' }
        result = simplejson.loads(self.modelWithSerializeFields.content)

        for key, value in result.items():
            self.assertEqual(to_equal.get(key).__str__(), value.__str__())

    def testModelWithoutSerializeFieldsConvertsToJson(self):
        to_equal = { u'text': u'is said repeatedly in Street Fighter', u'title': u'Hadouken', u'id': None }
        result = simplejson.loads(self.modelWithoutSerializeFields.content)

        for key, value in result.items():
            self.assertEqual(to_equal.get(key).__str__(), value.__str__())

    def testModelsWithDynamiclyAddedFieldsConvertsToJson(self):
        to_equal = { u'text': u'is said repeatedly in Street Fighter', u'title': u'Hadouken', u'id': None, u'dummy': u'blah' }

        self.modelbaseWithoutSerializeFields.dummy = "blah"
        self.modelbaseWithoutSerializeFields._dummy = "blah"
        result = simplejson.loads(JsonResponse(self.modelbaseWithoutSerializeFields).content)

        for key, value in result.items():
            self.assertEqual(to_equal.get(key).__str__(), value.__str__())