text:
package com.jjf.jdbc;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;

import com.mysql.jdbc.NonRegisteringDriver;

public class JDriver extends NonRegisteringDriver implements Driver{

	static {
        try {
            java.sql.DriverManager.registerDriver(new JDriver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }

	public JDriver() throws SQLException {
		super();
	}

	@Override
    public Connection connect(String url, Properties info) throws SQLException {
        return super.connect(UrlFactory.getUrl(url, info), info);
    }

}

redpajama_set_name: RedPajamaGithub


text:
FROM tomcat:7-jre7
RUN apt-get update -y && apt-get install -y wget curl locate
RUN apt-get install -y vim
RUN mkdir /ncwms
WORKDIR /ncwms
ADD LICENCE /
ADD tomcat-users.xml /usr/local/tomcat/conf/
RUN wget http://tenet.dl.sourceforge.net/project/ncwms/ncwms/1.2/ncWMS-1.2.war
RUN cp ncWMS-1.2.war /usr/local/tomcat/webapps/ncWMS.war
RUN updatedb


text:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke.Common.Utilities;

#endregion

namespace DotNetNuke.UI.WebControls
{
    /// -----------------------------------------------------------------------------
    /// Project:    DotNetNuke
    /// Namespace:  DotNetNuke.UI.WebControls
    /// Class:      DNNMultiStateBoxColumnTemplate
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The DNNMultiStateBoxColumnTemplate provides a Template for the DNNMultiStateBoxColumn
    /// </summary>
    /// -----------------------------------------------------------------------------
    public class DNNMultiStateBoxColumnTemplate : ITemplate
    {
        private string mDataField = Null.NullString;
        private bool mEnabled = true;
        private string mEnabledField = Null.NullString;
        private string mImagePath = "";
        private ListItemType mItemType = ListItemType.Item;
        private string mSelectedStateKey = "";
        private DNNMultiStateCollection mStates;
        private string mText = "";

        public DNNMultiStateBoxColumnTemplate() : this(ListItemType.Item)
        {
        }

        public DNNMultiStateBoxColumnTemplate(ListItemType itemType)
        {
            ItemType = itemType;
        }

		/// -----------------------------------------------------------------------------
		/// <summary>
		/// Gets and sets whether the column fires a postback when the control changes
		/// </summary>
		/// <value>A Boolean</value>
		/// -----------------------------------------------------------------------------
        public bool AutoPostBack { get; set; }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets and sets the selected state of the DNNMultiStateBox (unless DataBound)
        /// </summary>
        /// <value>A Boolean</value>
        /// -----------------------------------------------------------------------------
        public string SelectedStateKey
        {
            get
            {
                return mSelectedStateKey;
            }
            set
            {
                mSelectedStateKey = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Data Field that the column should bind to
        /// </summary>
        /// <value>A String</value>
        /// -----------------------------------------------------------------------------
        public string DataField
        {
            get
            {
                return mDataField;
            }
            set
            {
                mDataField = value;
            }
        }

		/// -----------------------------------------------------------------------------
		/// <summary>
		/// Gets or sets the Design Mode of the Column
		/// </summary>
		/// <value>A Boolean</value>
		/// -----------------------------------------------------------------------------
        public bool DesignMode { get; set; }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// An flag that indicates whether the control is enabled (this is overridden if
        /// the EnabledField is set
        /// changed
        /// </summary>
        /// <value>A Boolean</value>
        /// -----------------------------------------------------------------------------
        public bool Enabled
        {
            get
            {
                return mEnabled;
            }
            set
            {
                mEnabled = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Data Field that determines whether the control is Enabled
        /// changed
        /// </summary>
        /// <value>A String</value>
        /// -----------------------------------------------------------------------------
        public string EnabledField
        {
            get
            {
                return mEnabledField;
            }
            set
            {
                mEnabledField = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The type of Template to Create
        /// </summary>
        /// <value>A String</value>
        /// -----------------------------------------------------------------------------
        public ListItemType ItemType
        {
            get
            {
                return mItemType;
            }
            set
            {
                mItemType = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Text to display in a Header Template
        /// </summary>
        /// <value>A String</value>
        /// -----------------------------------------------------------------------------
        public string Text
        {
            get
            {
                return mText;
            }
            set
            {
                mText = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets and sets the image path of the DNNMultiStateBox
        /// </summary>
        /// <value>A Boolean</value>
        /// -----------------------------------------------------------------------------
        public string ImagePath
        {
            get
            {
                return mImagePath;
            }
            set
            {
                mImagePath = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets and sets the state collection of the DNNMultiStateBox
        /// </summary>
        /// <value>A Boolean</value>
        /// -----------------------------------------------------------------------------
        public DNNMultiStateCollection States
        {
            get
            {
                if (mStates == null)
                {
                    mStates = new DNNMultiStateCollection(new DNNMultiStateBox());
                }
                return mStates;
            }
            set
            {
                mStates = value;
            }
        }

        #region ITemplate Members

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// InstantiateIn is called when the Template is instantiated by the parent control
        /// </summary>
        /// <param name="container">The container control</param>
		/// -----------------------------------------------------------------------------
        public void InstantiateIn(Control container)
        {
            if (!String.IsNullOrEmpty(Text))
            {
                container.Controls.Add(new LiteralControl(Text + "<br/>"));
            }
            if (ItemType != ListItemType.Header)
            {
                var box = new DNNMultiStateBox();
                box.AutoPostBack = AutoPostBack;
                box.ImagePath = ImagePath;
                foreach (DNNMultiState objState in States)
                {
                    box.States.Add(objState);
                }
                box.DataBinding += Item_DataBinding;
                container.Controls.Add(box);
            }
        }

        #endregion

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Called when the template item is Data Bound
        /// </summary>
        /// -----------------------------------------------------------------------------
        private void Item_DataBinding(object sender, EventArgs e)
        {
            var box = (DNNMultiStateBox) sender;
            var container = (DataGridItem) box.NamingContainer;
            if (!String.IsNullOrEmpty(DataField) && ItemType != ListItemType.Header)
            {
                if (DesignMode)
                {
                    box.SelectedStateKey = "";
                }
                else
                {
                    box.SelectedStateKey = Convert.ToString(DataBinder.Eval(container.DataItem, DataField));
                }
            }
            else
            {
                box.SelectedStateKey = SelectedStateKey;
            }
            if (!String.IsNullOrEmpty(EnabledField))
            {
                if (DesignMode)
                {
                    box.Enabled = false;
                }
                else
                {
                    box.Enabled = Convert.ToBoolean(DataBinder.Eval(container.DataItem, EnabledField));
                }
            }
            else
            {
                box.Enabled = Enabled;
            }
        }
    }
}


text:
Puppet::Type.newtype(:cloudstack_domain) do
  @doc = "Cloudstack Domain"

  ensurable

  newparam(:name, :namevar => true) do
    desc "The domain name (eg. TEST)"
  end

  newproperty(:networkdomain) do
    desc "The domainname (DNS) (eg. test.org) to use when creating VMs under this domain"
  end

  newproperty(:parent) do
    desc "The parent domain (name)"  # CONVERT TO ID
  end

  # domainid [Transfer from other Region ?]
end


text:
"use strict";
import { UseCase } from "../../src";
export class SyncNoDispatchUseCase extends UseCase {
    execute() {}
}


text:
package com.sun.nfs;

/**
 * This exception is thrown whenever an NFS error occurs.
 */
public class NfsException extends java.io.IOException {
    int error;

    /*
     * We're fortunate that NFS v2 and v3
     * share the same error codes
     */
    public static final int NFS_OK = 0;
    public static final int NFSERR_PERM = 1;
    public static final int NFSERR_NOENT = 2;
    public static final int NFSERR_IO = 5;
    public static final int NFSERR_NXIO = 6;
    public static final int NFSERR_ACCES = 13;
    public static final int NFSERR_EXIST = 17;
    public static final int NFSERR_XDEV = 18;
    public static final int NFSERR_NODEV = 19;
    public static final int NFSERR_NOTDIR = 20;
    public static final int NFSERR_ISDIR = 21;
    public static final int NFSERR_INVAL = 22;
    public static final int NFSERR_FBIG = 27;
    public static final int NFSERR_NOSPC = 28;
    public static final int NFSERR_ROFS = 30;
    public static final int NFSERR_MLINK = 31;
    public static final int NFSERR_NAMETOOLONG = 63;
    public static final int NFSERR_NOTEMPTY = 66;
    public static final int NFSERR_DQUOT = 69;
    public static final int NFSERR_STALE = 70;
    public static final int NFSERR_REMOTE = 71;
    public static final int NFSERR_BADHANDLE = 10001;
    public static final int NFSERR_NOT_SYNC = 10002;
    public static final int NFSERR_BAD_COOKIE = 10003;
    public static final int NFSERR_NOTSUPP = 10004;
    public static final int NFSERR_TOOSMALL = 10005;
    public static final int NFSERR_SERVERFAULT = 10006;
    public static final int NFSERR_BADTYPE = 10007;
    public static final int NFSERR_JUKEBOX = 10008;

    /**
     * Create a new NfsException
     *
     * @param NFS error number for this error
     */
    public NfsException(int error) {
        super("NFS error: " + error);
        this.error = error;
    }

    @Override
    public String toString() {

        switch (error) {
    case NFS_OK:
            return ("OK");
    case NFSERR_PERM:
            return ("Not owner");
    case NFSERR_NOENT:
            return ("No such file or directory");
    case NFSERR_IO:
            return ("I/O error");
    case NFSERR_NXIO:
            return ("No such device or address");
    case NFSERR_ACCES:
            return ("Permission denied");
    case NFSERR_EXIST:
            return ("File exists");
    case NFSERR_XDEV:
            return ("Attempted cross-device link");
    case NFSERR_NODEV:
            return ("No such device");
    case NFSERR_NOTDIR:
            return ("Not a directory");
    case NFSERR_ISDIR:
            return ("Is a directory");
    case NFSERR_INVAL:
            return ("Invalid argument");
    case NFSERR_FBIG:
            return ("File too large");
    case NFSERR_NOSPC:
            return ("No space left on device");
    case NFSERR_ROFS:
            return ("Read-only file system");
    case NFSERR_MLINK:
            return ("Too many links");
    case NFSERR_NAMETOOLONG:
            return ("File name too long");
    case NFSERR_NOTEMPTY:
            return ("Directory not empty");
    case NFSERR_DQUOT:
            return ("Disk quota exceeded");
    case NFSERR_STALE:
            return ("Stale NFS file handle");
    case NFSERR_REMOTE:
            return ("Too many levels of remote in path");
    case NFSERR_BADHANDLE:
            return ("Illegal NFS file handle");
    case NFSERR_NOT_SYNC:
            return ("Update sync mismatch");
    case NFSERR_BAD_COOKIE:
            return ("Readdir cookie is stale");
    case NFSERR_NOTSUPP:
            return ("Operation not supported");
    case NFSERR_TOOSMALL:
            return ("Buffer/request too small");
    case NFSERR_SERVERFAULT:
            return ("Server fault");
    case NFSERR_BADTYPE:
            return ("Bad type");
    case NFSERR_JUKEBOX:
            return ("Jukebox error: try later");
        }
        return ("Unknown NFS error: " + error);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">

What To Farm Next...

    <button onclick = "askTroll()">Ask the garden troll</button>

    <button onclick = "profit()">Profits</button>


text:
<resources>

    <!-- Farveskema for app'en - arver fra Theme.AppCompat -->
    <style name="AppTheme" parent="Theme.AppCompat">
        <!-- Farveskema / tema kan tilrettes herunder -->
<!--
        <item name="colorPrimary">#3F51B5</item>
        <item name="colorPrimaryDark">#303F9F</item>
        <item name="colorAccent">#FF4081</item>
        -->
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

</resources>


text:
// $Id: OS_NS_sys_uio.cpp 96519 2012-12-17 10:00:00Z johnnyw $

#include "ace/OS_NS_sys_uio.h"

#if !defined (ACE_HAS_INLINED_OSCALLS)
# include "ace/OS_NS_sys_uio.inl"
#endif /* ACE_HAS_INLINED_OSCALLS */

#include "ace/OS_Memory.h"
#include "ace/OS_NS_string.h"
#include "ace/OS_NS_unistd.h"

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

# if defined (ACE_LACKS_READV)

// "Fake" readv for operating systems without it.  Note that this is
// thread-safe.

ssize_t
ACE_OS::readv_emulation (ACE_HANDLE handle,
                         const iovec *iov,
                         int n)
{
  ACE_OS_TRACE ("ACE_OS::readv_emulation");

  // In case there's a single element, skip the memcpy.
  if (1 == n)
    return ACE_OS::read (handle, iov[0].iov_base, iov[0].iov_len);

  ssize_t length = 0;
  int i;

  for (i = 0; i < n; ++i)
    if (static_cast<int> (iov[i].iov_len) < 0)
      return -1;
    else
      length += iov[i].iov_len;

  char *buf;
#   if defined (ACE_HAS_ALLOCA)
  buf = (char *) alloca (length);
#   else
  ACE_NEW_RETURN (buf,
                  char[length],
                  -1);
#   endif /* !defined (ACE_HAS_ALLOCA) */

  length = ACE_OS::read (handle, buf, length);

  if (length != -1)
    {
      char *ptr = buf;
      ssize_t copyn = length;

      for (i = 0;
           i < n && copyn > 0;
           ++i)
        {
          ACE_OS::memcpy (iov[i].iov_base, ptr,
                          // iov_len is int on some platforms, size_t on others
                          copyn > (int) iov[i].iov_len
                            ? (size_t) iov[i].iov_len
                            : (size_t) copyn);
          ptr += iov[i].iov_len;
          copyn -= iov[i].iov_len;
        }
    }

#   if !defined (ACE_HAS_ALLOCA)
  delete [] buf;
#   endif /* !defined (ACE_HAS_ALLOCA) */
  return length;
}
# endif /* ACE_LACKS_READV */

# if defined (ACE_LACKS_WRITEV)

// "Fake" writev for operating systems without it.  Note that this is
// thread-safe.

ssize_t
ACE_OS::writev_emulation (ACE_HANDLE handle, const iovec *iov, int n)
{
  ACE_OS_TRACE ("ACE_OS::writev_emulation");

  // To avoid having to allocate a temporary buffer to which all of
  // the data will be copied and then written, this implementation
  // performs incremental writes.

  ssize_t bytes_sent = 0;

  for (int i = 0; i < n; ++i)
    {
      ssize_t const result =
        ACE_OS::write (handle, iov[i].iov_base, iov[i].iov_len);

      if (result == -1)
        {
          // There is a subtle difference in behaviour depending on
          // whether or not any data was sent.  If no data was sent,
          // then always return -1.  Otherwise return bytes_sent.
          // This gives the caller an opportunity to keep track of
          // bytes that have already been sent.
          if (bytes_sent > 0)
            break;
          else
            return -1;
        }
      else
        {
          bytes_sent += result;

          // Do not continue on to the next loop iteration if the
          // amount of data sent was less than the amount data given.
          // This avoids a subtle problem where "holes" in the data
          // stream would occur if partial sends of a given buffer in
          // the iovec array occured.
          if (static_cast<size_t> (result) < iov[i].iov_len)
            break;
        }
    }

  return bytes_sent;
}
# endif /* ACE_LACKS_WRITEV */

ACE_END_VERSIONED_NAMESPACE_DECL


text:
import os
import multiprocessing

PROJECT_NAME = 'one-server'
PROJ_DIR = os.path.join('/home/webapps/Projects/', PROJECT_NAME)
proc_name = PROJECT_NAME
# user = PROJECT_NAME
# group = 'webapps'
workers = multiprocessing.cpu_count() * 2 + 1
log_level = 'info'
# bind = 'unix:%s' % os.path.join(PROJ_DIR, 'tmp/gunicorn.sock')
timeout = 300
max_requests = 50
daemon = True
# pidfile = os.path.join(PROJ_DIR, 'tmp/gunicorn.pid')
# umask = 7
# tmp_upload_dir = os.path.join(PROJ_DIR, 'tmp/')
# worker_tmp_dir = os.path.join(PROJ_DIR, 'tmp/')
# raw_env = ['TMPDIR=%s' % os.path.join(PROJ_DIR, 'run/tmp/')]#,'DJANGO_SETTINGS_MODULE=config.settings.production']


text:
package com.jalotsav.jamnadasconnect;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.jalotsav.jamnadasconnect.common.AppConstants;
import com.jalotsav.jamnadasconnect.common.LogHelper;
import com.jalotsav.jamnadasconnect.navgtndrawer.NavgtnDrwrMain;

public class ActvtyMain extends Activity {

    private static final String TAG = ActvtyMain.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lo_actvty_main);

        LogHelper.printLog(AppConstants.LOGTYPE_INFO, TAG, "Welcome to Jamnadas Edu Media!");
        Handler mHndlr = new Handler();
        mHndlr.postDelayed(new Runnable() {
            @Override
            public void run() {

                int navDrwrPostn = getIntent().getIntExtra(AppConstants.PUT_EXTRA_NAVDRWER_POSTN, AppConstants.NAVDRWER_DASHBOARD);
                startActivity(new Intent(ActvtyMain.this, NavgtnDrwrMain.class)
                        .putExtra(AppConstants.PUT_EXTRA_NAVDRWER_POSTN, navDrwrPostn));
                finish();
            }
        }, 3000);
    }
}


text:
package com.intellij.openapi.vcs;

import com.intellij.lifecycle.PeriodicalTasksCloser;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vcs.changes.VcsAnnotationLocalChangesListener;
import com.intellij.openapi.vcs.history.VcsHistoryCache;
import com.intellij.openapi.vcs.impl.ContentRevisionCache;
import com.intellij.openapi.vcs.impl.VcsDescriptor;
import com.intellij.openapi.vcs.impl.VcsEnvironmentsProxyCreator;
import com.intellij.openapi.vcs.update.UpdatedFiles;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Processor;
import com.intellij.util.messages.Topic;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * Manages the version control systems used by a specific project.
 */
public abstract class ProjectLevelVcsManager {

  public static final Topic<VcsListener> VCS_CONFIGURATION_CHANGED = Topic.create("VCS configuration changed", VcsListener.class);
  public static final Topic<VcsListener> VCS_CONFIGURATION_CHANGED_IN_PLUGIN = Topic.create("VCS configuration changed in VCS plugin", VcsListener.class);

  public abstract void iterateVfUnderVcsRoot(VirtualFile file, Processor<VirtualFile> processor);

  /**
   * Returns the <code>ProjectLevelVcsManager<code> instance for the specified project.
   *
   * @param project the project for which the instance is requested.
   * @return the manager instance.
   */
  public static ProjectLevelVcsManager getInstance(Project project) {
    return PeriodicalTasksCloser.getInstance().safeGetComponent(project, ProjectLevelVcsManager.class);
  }

  /**
   * Gets the instance of the component if the project wasn't disposed. If the project was
   * disposed, throws ProcessCanceledException. Should only be used for calling from background
   * threads (for example, committed changes refresh thread).
   *
   * @param project the project for which the component instance should be retrieved.
   * @return component instance
   */
  public static ProjectLevelVcsManager getInstanceChecked(final Project project) {
    return ApplicationManager.getApplication().runReadAction(new Computable<ProjectLevelVcsManager>() {
      public ProjectLevelVcsManager compute() {
        if (project.isDisposed()) throw new ProcessCanceledException();
        return getInstance(project);
      }
    });
  }

  /**
   * Returns the list of all registered version control systems.
   *
   * @return the list of registered version control systems.
   */
  public abstract VcsDescriptor[] getAllVcss();

  /**
   * Returns the version control system with the specified name.
   *
   * @param name the name of the VCS to find.
   * @return the VCS instance, or null if none is found.
   */
  @Nullable
  public abstract AbstractVcs findVcsByName(@NonNls String name);

  @Nullable
  public abstract VcsDescriptor getDescriptor(final String name);
  /**
   * Checks if all files in the specified array are managed by the specified VCS.
   *
   * @param abstractVcs the VCS to check.
   * @param files       the files to check.
   * @return true if all files are managed by the VCS, false otherwise.
   */
  public abstract boolean checkAllFilesAreUnder(AbstractVcs abstractVcs, VirtualFile[] files);

  /**
   * Returns the VCS managing the specified file.
   *
   * @param file the file to check.
   * @return the VCS instance, or null if the file does not belong to any module or the module
   *         it belongs to is not under version control.
   */
  @Nullable
  public abstract AbstractVcs getVcsFor(@NotNull VirtualFile file);

  /**
   * Returns the VCS managing the specified file path.
   *
   * @param file the file to check.
   * @return the VCS instance, or null if the file does not belong to any module or the module
   *         it belongs to is not under version control.
   */
  @Nullable
  public abstract AbstractVcs getVcsFor(FilePath file);

  /**
   * Return the parent directory of the specified file which is mapped to a VCS.
   *
   * @param file the file for which the root is requested.
   * @return the root, or null if the specified file is not in a VCS-managed directory.
   */
  @Nullable
  public abstract VirtualFile getVcsRootFor(@Nullable VirtualFile file);

  /**
   * Return the parent directory of the specified file path which is mapped to a VCS.
   *
   * @param file the file for which the root is requested.
   * @return the root, or null if the specified file is not in a VCS-managed directory.
   */
  @Nullable
  public abstract VirtualFile getVcsRootFor(FilePath file);

  @Nullable
  public abstract VcsRoot getVcsRootObjectFor(final VirtualFile file);

  @Nullable
  public abstract VcsRoot getVcsRootObjectFor(FilePath file);

  /**
   * Checks if the specified VCS is used by any of the modules in the project.
   *
   * @param vcs the VCS to check.
   * @return true if the VCS is used by any of the modules, false otherwise
   */
  public abstract boolean checkVcsIsActive(AbstractVcs vcs);

  /**
   * Checks if the VCS with the specified name is used by any of the modules in the project.
   *
   * @param vcsName the name of the VCS to check.
   * @return true if the VCS is used by any of the modules, false otherwise
   */
  public abstract boolean checkVcsIsActive(@NonNls String vcsName);

  /**
   * Returns the list of VCSes used by at least one module in the project.
   *
   * @return the list of VCSes used in the project.
   */
  public abstract AbstractVcs[] getAllActiveVcss();

  public abstract boolean hasActiveVcss();

  public abstract boolean hasAnyMappings();

  public abstract void addMessageToConsoleWindow(String message, TextAttributes attributes);

  @NotNull
  public abstract VcsShowSettingOption getStandardOption(@NotNull VcsConfiguration.StandardOption option,
                                                         @NotNull AbstractVcs vcs);

  @NotNull
  public abstract VcsShowConfirmationOption getStandardConfirmation(@NotNull VcsConfiguration.StandardConfirmation option,
                                                                    AbstractVcs vcs);

  @NotNull
  public abstract VcsShowSettingOption getOrCreateCustomOption(@NotNull String vcsActionName,
                                                               @NotNull AbstractVcs vcs);

  public abstract void showProjectOperationInfo(final UpdatedFiles updatedFiles, String displayActionName);

  /**
   * Adds a listener for receiving notifications about changes in VCS configuration for the project.
   *
   * @param listener the listener instance.
   * @deprecated use {@link #VCS_CONFIGURATION_CHANGED} instead
   * @since 6.0
   */
  public abstract void addVcsListener(VcsListener listener);

  /**
   * Removes a listener for receiving notifications about changes in VCS configuration for the project.
   *
   * @param listener the listener instance.
   * @deprecated use {@link #VCS_CONFIGURATION_CHANGED} instead
   * @since 6.0
   */
  public abstract void removeVcsListener(VcsListener listener);

  /**
   * Marks the beginning of a background VCS operation (commit or update).
   *
   * @since 6.0
   */
  public abstract void startBackgroundVcsOperation();

  /**
   * Marks the end of a background VCS operation (commit or update).
   *
   * @since 6.0
   */
  public abstract void stopBackgroundVcsOperation();

  /**
   * Checks if a background VCS operation (commit or update) is currently in progress.
   *
   * @return true if a background operation is in progress, false otherwise.
   * @since 6.0
   */
  public abstract boolean isBackgroundVcsOperationRunning();

  public abstract List<VirtualFile> getRootsUnderVcsWithoutFiltering(final AbstractVcs vcs);
  public abstract VirtualFile[] getRootsUnderVcs(AbstractVcs vcs);

  /**
   * Also includes into list all modules under roots
   */
  public abstract List<VirtualFile> getDetailedVcsMappings(final AbstractVcs vcs);

  public abstract VirtualFile[] getAllVersionedRoots();

  @NotNull
  public abstract VcsRoot[] getAllVcsRoots();

  public abstract void updateActiveVcss();

  public abstract List<VcsDirectoryMapping> getDirectoryMappings();
  public abstract List<VcsDirectoryMapping> getDirectoryMappings(AbstractVcs vcs);

  @Nullable
  public abstract VcsDirectoryMapping getDirectoryMappingFor(FilePath path);

  /**
   * This method can be used only when initially loading the project configuration!
   */
  public abstract void setDirectoryMapping(final String path, final String activeVcsName);

  public abstract void setDirectoryMappings(final List<VcsDirectoryMapping> items);

  public abstract void iterateVcsRoot(final VirtualFile root, final Processor<FilePath> iterator);

  public abstract void iterateVcsRoot(final VirtualFile root, final Processor<FilePath> iterator,
                                      @Nullable VirtualFileFilter directoryFilter);

  @Nullable
  public abstract AbstractVcs findVersioningVcs(VirtualFile file);

  public abstract CheckoutProvider.Listener getCompositeCheckoutListener();

  public abstract VcsEventsListenerManager getVcsEventsListenerManager();
  protected abstract VcsEnvironmentsProxyCreator getProxyCreator();

  public abstract VcsHistoryCache getVcsHistoryCache();
  public abstract ContentRevisionCache getContentRevisionCache();
  public abstract boolean isFileInContent(final VirtualFile vf);

  public abstract boolean dvcsUsedInProject();

  @NotNull
  public abstract VcsAnnotationLocalChangesListener getAnnotationLocalChangesListener();
}


text:
using UnityEngine;
using System.Collections;

public class movecam : MonoBehaviour {

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
        GetComponent<Rigidbody>().velocity = new Vector3(0, GM.vertVel, 4 * GM.zVelAdj);

    }
}


text:
//
//  LXFBaseBrush.h
//  LXFDrawBoard
//
//  Created by LXF on 2017/7/6.
//  Copyright © 2017年 LXF. All rights reserved.
//
//  GitHub: https://github.com/LinXunFeng
//  简书: http://www.jianshu.com/users/31e85e7a22a2

#import <UIKit/UIKit.h>

@interface LXFBaseBrush : NSObject

/** startPoint */
@property(nonatomic, assign) CGPoint startPoint;
/** endPoint */
@property(nonatomic, assign) CGPoint endPoint;
/** lastPoint */
@property(nonatomic, assign) CGPoint lastPoint;
/** 是否有lastPoint */
@property(nonatomic, assign) BOOL hasLastPoint;
/** lineWidth */
@property(nonatomic, assign) CGFloat lineWidth;
/** 是否使用填充 */
@property(nonatomic, assign) BOOL isFill;

/** 是否连续绘制 */
@property(nonatomic, assign) BOOL keepDrawing;

// 笔刷专用绘图上下文
- (void)drawInContext:(CGContextRef)ctx;

@end


text:
SYSTEM_APPS="
BasicDreams
Books
Browser
CMWallpapers
Calculator
Calendar
Camera2
CloudPrint2
EditorsSlides
Eleven
Email
Exchange2
FitnessPrebuilt
Galaxy4
GenieWidget
GoogleEarth
Jelly
HoloSpiralWallpaper
LiveWallpapers
MagicSmokeWallpapers
Newsstand
Music
Music2
NoiseField
PhaseBeam
PhotoPhase
PhotoTable
PrebuiltExchange3Google
PrebuiltKeep
PrebuiltNewsWeather
PinyinIME
Snap
Street
Terminal
Videos
VisualizationWallpapers
"

SYSTEM_AUDIO="
VideoRecord.ogg
camera_focus.ogg
camera_click.ogg
"

if [ -z "$1" ] || [ "$1" == 'post-restore' ] ; then
  # remove apps unused apps from system partition
  for app in ${SYSTEM_APPS}; do
    rm -rf "/system/app/${app}"
    rm -rf "/system/priv-app/${app}"
  done
  # remove system sounds
  for file in ${SYSTEM_AUDIO}; do
    rm -f "/system/media/audio/ui/${file}"
  done
fi

true


text:
package com.ptycore.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

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

import org.junit.Test;

import com.ptycore.BrokenRule;
import com.ptycore.BusinessRulesException;
import com.ptycore.Identity;
import com.ptycore.lib.EmergencyContact;
import com.ptycore.lib.readonly.EmergencyContactList;

public class EmergencyContactTest {

	private int _EmergencyContactID = 6;
	private Identity _identity = null;

	@Test
	public void AddEmergencyContact() {
		System.out.println("New EmergencyContact");

		_identity = Identity.NewIdentity();
		_identity.setOperator("JUnit");
		_identity.setOperatorId(-1000);

		EmergencyContact emergencyContact = EmergencyContact.NewEmergencyContact(_identity);
		emergencyContact.setEmergencyTitle("Ambulance");
		emergencyContact.setNumber1(987654321);
		emergencyContact.setNumber2(101);
		emergencyContact.setEntity("Karuna Hospital");
		try {
			emergencyContact.SaveEmergencyContact();
		} catch (BusinessRulesException e) {
			System.out.println(e.getMessage());
			for (BrokenRule rule : e.getBrokenRules()) {
				System.out.println(rule.getDescription());
			}
		}

		assertTrue(emergencyContact.isNew());
	}

	@Test
	public void GetEmergencyContact() {
		System.out.println("Get EmergencyContact " + _EmergencyContactID);

		_identity = Identity.NewIdentity();
		_identity.setOperator("JUnit");
		_identity.setOperatorId(-1000);

		EmergencyContact emergencyContact = EmergencyContact.GetEmergencyContact(_EmergencyContactID, _identity);
		assertEquals("Pudunagaram Police Station", emergencyContact.getEntity());
	}

	@Test
	public void UpdateEmergencyContact() {
		System.out.println("Update EmergencyContact " + _EmergencyContactID);

		_identity = Identity.NewIdentity();
		_identity.setOperator("JUnit");
		_identity.setOperatorId(-1000);

		EmergencyContact emergencyContact = EmergencyContact.GetEmergencyContact(_EmergencyContactID, _identity);
		emergencyContact.setEmergencyTitle("Police Station");
		emergencyContact.setNumber1(100);
		emergencyContact.setNumber2(12345);
		emergencyContact.setEntity("Pudunagaram Police Station");
		try {
			emergencyContact.SaveEmergencyContact();
		} catch (BusinessRulesException e) {
			System.out.println(e.getMessage());
			for (BrokenRule rule : e.getBrokenRules()) {
				System.out.println(rule.getDescription());
			}
		}
		emergencyContact = EmergencyContact.GetEmergencyContact(_EmergencyContactID, _identity);
		assertEquals(100, emergencyContact.getNumber1());
	}

	@Test(timeout = 1000)
	public void GetEmergencyContactList() {
		System.out.println("Get EmergencyContact List");

		EmergencyContactList emergencyContactList = EmergencyContactList.getEmergencyContactList();
		assertEquals(6, emergencyContactList.size());
	}

	@Test(timeout = 1000)
	public void SearchEmergencyContactList() {
		System.out.println("Search EmergencyContact List");

		Map<String, String> searchItems = new HashMap<String, String>();
		String ID = "ID";
		String key = "7";
		searchItems.put(ID, key);
		searchItems.put("EmergencyTitle", "Ambulance");
		searchItems.put("Number1", "101");
		searchItems.put("Number2", "101");
		searchItems.put("Entity", "Karuna Hospital");
		searchItems.put("*", "Ambulance");

		EmergencyContactList emergencyContactList = EmergencyContactList.getEmergencyContactList(searchItems);
		assertEquals(6, emergencyContactList.size());
	}

}


text: The SoulSellerS Website


text:
PANDOC = pandoc
BEAMER_THEME = Boadilla

all:	lightning.pdf

# Create slides with pandoc
%.pdf:	%.md Makefile
	$(PANDOC) --template=default.beamer -s --slide-level=2 -t beamer -V theme:$(BEAMER_THEME) -o $@ $<

.PHONY:	all


text:
@implementation NSBundle (KDIPrivateExtensions)

+ (NSBundle *)KDI_frameworkBundle; {
    return [self bundleWithIdentifier:@"com.kosoku.ditko"] ?: [self bundleWithURL:[[self bundleForClass:DitkoClass.class].resourceURL URLByAppendingPathComponent:@"Ditko.bundle"]] ?: [self bundleWithURL:[NSBundle.mainBundle URLForResource:@"Ditko" withExtension:@"bundle"]];
}

@end


text:
package com.ebay.marketplace.resolution.v1.services;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 * 	  		Response that indicates the status of Issue Partial Refund Request. Please
 * 	  		note that this need to be invoked only if original payment was done through
 * 	  		paypal
 *
 *
 *
IssuePartialRefundResponse complex typeµÄ Java Àà¡£
 *
 *
ÒÔÏÂģʽƬ¶ÎÖ¸¶¨°üº¬ÔÚ´ËÀàÖеÄÔ¤ÆÚÄÚÈÝ¡£
 *
 *

 * <complexType name="IssuePartialRefundResponse">
 *   <complexContent>
 *     <extension base="{http://www.ebay.com/marketplace/resolution/v1/services}BaseResponse">
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "IssuePartialRefundResponse")
public class IssuePartialRefundResponse
    extends BaseResponse
{

}


text:
class DVAPI IKSkeleton
{
	std::vector<IKNode *> m_nodes;
	int numEffector;
	int numJoint;

public:
	IKSkeleton()
	{
		numEffector = 0;
		numJoint = 0;
	}
	~IKSkeleton()
	{
		clear();
	}

	void compute();
	void clear()
	{
		std::vector<IKNode *>::iterator it;
		for (it = m_nodes.begin(); it != m_nodes.end(); ++it)
			delete *it;
		m_nodes.clear();
		numEffector = 0;
		numJoint = 0;
	}
	void addNode(IKNode *node) { m_nodes.push_back(node); }
	int getNodeCount() const { return (int)m_nodes.size(); }
	IKNode *getNode(int index) const
	{
		assert(0 <= index && index < getNodeCount());
		return m_nodes[index];
	}
	IKNode *getRoot() const { return m_nodes[0]; }

	int getNumNode() const { return (numJoint + numEffector); }
	int getNumEffector() const { return numEffector; }
	int getNumJoint() const { return numJoint; }

	void setRoot(int nodeIndex)
	{
		m_nodes[nodeIndex]->setR(m_nodes[nodeIndex]->getPos());
	}
	void setNode(int nodeIndex, const TPointD &pos, IKNode::Purpose purpose)
	{
		assert(0 <= nodeIndex && nodeIndex < getNodeCount());
		m_nodes[nodeIndex]->setPos(pos);
		m_nodes[nodeIndex]->setS(pos);
		m_nodes[nodeIndex]->setPurpose(purpose);
		m_nodes[nodeIndex]->unFreeze();
		m_nodes[nodeIndex]->setIndex(nodeIndex);
	}
	void setPurpose(int nodeIndex, IKNode::Purpose purpose);
	void setParent(int nodeIndex, int parentIndex)
	{
		assert(0 <= nodeIndex && nodeIndex < getNodeCount());
		assert(0 <= parentIndex && parentIndex < getNodeCount());
		m_nodes[nodeIndex]->setParent(m_nodes[parentIndex]);
		// Setto la posizione relativa
		m_nodes[nodeIndex]->setR(m_nodes[nodeIndex]->getPos() - m_nodes[parentIndex]->getPos());
	}

	IKNode *getParent(const IKNode *node)
	{
		//assert(0<=nodeIndex && nodeIndex<getNodeCount());
		return node->getParent();
	}

private:
	void computeSkeleton(IKNode *);
};

#endif //IKSKELETON_H


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

<title>OnPrepare</title>
<meta name="date" content="2022-10-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element

com.facebook.litho.annotations

Annotation Type OnPrepare

@Retention(value=CLASS)
public @interface OnPrepare

A MountSpec can define a method annotated with OnPrepare to run code that is more
 heavy and cannot be done during OnMount or OnBind. The method is called once
 before the layout calculation is performed, and the framework can invoke it either on the UI
 thread or on a background thread.

The annotated method has a void return type and will be passed the following arguments when
 the framework invokes it:

Required:

ComponentContext

Optional annotated arguments:

Prop

TreeProp

InjectProp

State

Output

The annotation processor will validate this and other invariants in the API at build time.

OnPrepare-annotated methods can calculate values which are heavy to compute and
 pass them as inter-stage props to other methods which are performance critical, such as OnMount.

For example:

 @MountSpec
 class ExampleMountSpec {

   @OnPrepare
   static void onPrepare(
       ComponentContext c,
       @Prop String colorName,
       Output<Integer> color) {
       color.set(Color.parseColor(colorName));
   }

   @OnCreateMountContent
   static ColorDrawable onCreateMountContent(
       ComponentContext c) {
     return new ColorDrawable();
   }

   @OnMount
   static void onMount(
       ComponentContext c,
       ColorDrawable colorDrawable,
       @FromPrepare int color){
     colorDrawable.setColor(color);
   }
 }

See Also:

OnMount,
OnBind

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element


text:
/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 *    Cobweb.java
 *    Copyright (C) 2001 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.clusterers;

import weka.core.AttributeStats;
import weka.core.Capabilities;
import weka.core.Drawable;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.Capabilities.Capability;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.experiment.Stats;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Add;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;

/**

 * Class implementing the Cobweb and Classit clustering algorithms.

 *

 * Note: the application of node operators (merging, splitting etc.) in terms of ordering and priority differs (and is somewhat ambiguous) between the original Cobweb and Classit papers. This algorithm always compares the best host, adding a new leaf, merging the two best hosts, and splitting the best host when considering where to place a new instance.

 *

 * For more information see:

 *

 * D. Fisher (1987). Knowledge acquisition via incremental conceptual clustering. Machine Learning. 2(2):139-172.

 *

 * J. H. Gennari, P. Langley, D. Fisher (1990). Models of incremental concept formation. Artificial Intelligence. 40:11-61.
 *

 *

 * BibTeX:
 *

 * @article{Fisher1987,
 *    author = {D. Fisher},
 *    journal = {Machine Learning},
 *    number = {2},
 *    pages = {139-172},
 *    title = {Knowledge acquisition via incremental conceptual clustering},
 *    volume = {2},
 *    year = {1987}
 * }
 *
 * @article{Gennari1990,
 *    author = {J. H. Gennari and P. Langley and D. Fisher},
 *    journal = {Artificial Intelligence},
 *    pages = {11-61},
 *    title = {Models of incremental concept formation},
 *    volume = {40},
 *    year = {1990}
 * }
 *

 *

 *

 * Valid options are:

 *
 *
 -A <acuity>
 *  Acuity.
 *  (default=1.0)

 *
 *
 -C <cutoff>
 *  Cutoff.
 *  (default=0.002)

 *
 *
 -S <num>
 *  Random number seed.
 *  (default 42)

 *

 *
 * @author Mark Hall
 * @version $Revision: 6790 $
 * @see RandomizableClusterer
 * @see Drawable
 */
public class Cobweb
  extends RandomizableClusterer
  implements Drawable, TechnicalInformationHandler, UpdateableClusterer {

  /** for serialization */
  static final long serialVersionUID = 928406656495092318L;

  /**
   * Inner class handling node operations for Cobweb.
   *
   * @see Serializable
   */
  private class CNode
    implements Serializable, RevisionHandler {

    /** for serialization */
    static final long serialVersionUID = 3452097436933325631L;
    /**
     * Within cluster attribute statistics
     */
    private AttributeStats[] m_attStats;

    /**
     * Number of attributes
     */
    private int m_numAttributes;

    /**
     * Instances at this node
     */
    protected Instances m_clusterInstances = null;

    /**
     * Children of this node
     */
    private FastVector m_children = null;

    /**
     * Total instances at this node
     */
    private double m_totalInstances = 0.0;

    /**
     * Cluster number of this node
     */
    private int m_clusterNum = -1;

    /**
     * Creates an empty CNode instance.
     *
     * @param numAttributes the number of attributes in the data
     */
    public CNode(int numAttributes) {
      m_numAttributes = numAttributes;
    }

    /**
     * Creates a new leaf CNode instance.
     *
     * @param numAttributes the number of attributes in the data
     * @param leafInstance the instance to store at this leaf
     */
    public CNode(int numAttributes, Instance leafInstance) {
      this(numAttributes);
      if (m_clusterInstances == null) {
	m_clusterInstances = new Instances(leafInstance.dataset(), 1);
      }
      m_clusterInstances.add(leafInstance);
      updateStats(leafInstance, false);
    }

    /**
     * Adds an instance to this cluster.
     *
     * @param newInstance the instance to add
     * @throws Exception if an error occurs
     */
    protected void addInstance(Instance newInstance) throws Exception {
      // Add the instance to this cluster

      if (m_clusterInstances == null) {
	m_clusterInstances = new Instances(newInstance.dataset(), 1);
	m_clusterInstances.add(newInstance);
	updateStats(newInstance, false);
	return;
      } else if (m_children == null) {
	/* we are a leaf, so make our existing instance(s) into a child
	   and then add the new instance as a child */
	m_children = new FastVector();
	CNode tempSubCluster = new CNode(m_numAttributes,
					 m_clusterInstances.instance(0));

	//	System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +"Dumping "+m_clusterInstances.numInstances());
	for (int i = 1; i < m_clusterInstances.numInstances(); i++) {
	  tempSubCluster.m_clusterInstances.
	    add(m_clusterInstances.instance(i));
	  tempSubCluster.updateStats(m_clusterInstances.instance(i), false);
	}
	m_children = new FastVector();
	m_children.addElement(tempSubCluster);
	m_children.addElement(new CNode(m_numAttributes, newInstance));

	m_clusterInstances.add(newInstance);
	updateStats(newInstance, false);

	// here is where we check against cutoff (also check cutoff
	// in findHost)
	if (categoryUtility() < m_cutoff) {
	  //	  System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +"Cutting (leaf add) ");
	  m_children = null;
	}
	return;
      }

      // otherwise, find the best host for this instance
      CNode bestHost = findHost(newInstance, false);
      if (bestHost != null) {
	// now add to the best host
	bestHost.addInstance(newInstance);
      }
    }

    /**
     * Temporarily adds a new instance to each of this nodes children
     * in turn and computes the category utility.
     *
     * @param newInstance the new instance to evaluate
     * @return an array of category utility values---the result of considering
     * each child in turn as a host for the new instance
     * @throws Exception if an error occurs
     */
    private double[] cuScoresForChildren(Instance newInstance)
      throws Exception {
      // look for a host in existing children
      double[] categoryUtils = new double [m_children.size()];

      // look for a home for this instance in the existing children
      for (int i = 0; i < m_children.size(); i++) {
	CNode temp = (CNode) m_children.elementAt(i);
	// tentitively add the new instance to this child
	temp.updateStats(newInstance, false);
	categoryUtils[i] = categoryUtility();

	// remove the new instance from this child
	temp.updateStats(newInstance, true);
      }
      return categoryUtils;
    }

    private double cuScoreForBestTwoMerged(CNode merged,
					   CNode a, CNode b,
					   Instance newInstance)
      throws Exception {

      double mergedCU = -Double.MAX_VALUE;
      // consider merging the best and second
      // best.
      merged.m_clusterInstances = new Instances(m_clusterInstances, 1);

      merged.addChildNode(a);
      merged.addChildNode(b);
      merged.updateStats(newInstance, false); // add new instance to stats
      // remove the best and second best nodes
      m_children.removeElementAt(m_children.indexOf(a));
      m_children.removeElementAt(m_children.indexOf(b));
      m_children.addElement(merged);
      mergedCU = categoryUtility();
      // restore the status quo
      merged.updateStats(newInstance, true);
      m_children.removeElementAt(m_children.indexOf(merged));
      m_children.addElement(a);
      m_children.addElement(b);
      return mergedCU;
    }

    /**
     * Finds a host for the new instance in this nodes children. Also
     * considers merging the two best hosts and splitting the best host.
     *
     * @param newInstance the instance to find a host for
     * @param structureFrozen true if the instance is not to be added to
     * the tree and instead the best potential host is to be returned
     * @return the best host
     * @throws Exception if an error occurs
     */
    private CNode findHost(Instance newInstance,
			   boolean structureFrozen) throws Exception {

      if (!structureFrozen) {
	updateStats(newInstance, false);
      }

      // look for a host in existing children and also consider as a new leaf
      double[] categoryUtils = cuScoresForChildren(newInstance);

      // make a temporary new leaf for this instance and get CU
      CNode newLeaf = new CNode(m_numAttributes, newInstance);
      m_children.addElement(newLeaf);
      double bestHostCU = categoryUtility();
      CNode finalBestHost = newLeaf;

      // remove new leaf when seaching for best and second best nodes to
      // consider for merging and splitting
      m_children.removeElementAt(m_children.size()-1);

      // now determine the best host (and the second best)
      int best = 0;
      int secondBest = 0;
      for (int i = 0; i < categoryUtils.length; i++) {
	if (categoryUtils[i] > categoryUtils[secondBest]) {
	  if (categoryUtils[i] > categoryUtils[best]) {
	    secondBest = best;
	    best = i;
	  } else {
	    secondBest = i;
	  }
	}
      }

      CNode a = (CNode) m_children.elementAt(best);
      CNode b = (CNode) m_children.elementAt(secondBest);
      if (categoryUtils[best] > bestHostCU) {
	bestHostCU = categoryUtils[best];
	finalBestHost = a;
	//	System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +"Node is best");
      }

      if (structureFrozen) {
	if (finalBestHost == newLeaf) {
	  return null; // *this* node is the best host
	} else {
	  return finalBestHost;
	}
      }

      double mergedCU = -Double.MAX_VALUE;
      CNode merged = new CNode(m_numAttributes);
      if (a != b) {
	mergedCU = cuScoreForBestTwoMerged(merged, a, b, newInstance);

	if (mergedCU > bestHostCU) {
	  bestHostCU = mergedCU;
	  finalBestHost = merged;
	}
      }

      // Consider splitting the best
      double splitCU = -Double.MAX_VALUE;
      double splitBestChildCU = -Double.MAX_VALUE;
      double splitPlusNewLeafCU = -Double.MAX_VALUE;
      double splitPlusMergeBestTwoCU = -Double.MAX_VALUE;
      if (a.m_children != null) {
	FastVector tempChildren = new FastVector();

	for (int i = 0; i < m_children.size(); i++) {
	  CNode existingChild = (CNode)m_children.elementAt(i);
	  if (existingChild != a) {
	    tempChildren.addElement(existingChild);
	  }
	}
	for (int i = 0; i < a.m_children.size(); i++) {
	  CNode promotedChild = (CNode)a.m_children.elementAt(i);
	  tempChildren.addElement(promotedChild);
	}
	// also add the new leaf
	tempChildren.addElement(newLeaf);

	FastVector saveStatusQuo = m_children;
	m_children = tempChildren;
	splitPlusNewLeafCU = categoryUtility(); // split + new leaf
	// remove the new leaf
	tempChildren.removeElementAt(tempChildren.size()-1);
	// now look for best and second best
	categoryUtils = cuScoresForChildren(newInstance);

	// now determine the best host (and the second best)
	best = 0;
	secondBest = 0;
	for (int i = 0; i < categoryUtils.length; i++) {
	  if (categoryUtils[i] > categoryUtils[secondBest]) {
	    if (categoryUtils[i] > categoryUtils[best]) {
	      secondBest = best;
	      best = i;
	    } else {
	      secondBest = i;
	    }
	  }
	}
	CNode sa = (CNode) m_children.elementAt(best);
	CNode sb = (CNode) m_children.elementAt(secondBest);
	splitBestChildCU = categoryUtils[best];

	// now merge best and second best
	CNode mergedSplitChildren = new CNode(m_numAttributes);
	if (sa != sb) {
	  splitPlusMergeBestTwoCU =
	    cuScoreForBestTwoMerged(mergedSplitChildren, sa, sb, newInstance);
	}
	splitCU = (splitBestChildCU > splitPlusNewLeafCU) ?
	  splitBestChildCU : splitPlusNewLeafCU;
	splitCU = (splitCU > splitPlusMergeBestTwoCU) ?
	  splitCU : splitPlusMergeBestTwoCU;

	if (splitCU > bestHostCU) {
	  bestHostCU = splitCU;
	  finalBestHost = this;
	  //	  tempChildren.removeElementAt(tempChildren.size()-1);
	} else {
	  // restore the status quo
	  m_children = saveStatusQuo;
	}
      }

      if (finalBestHost != this) {
	// can commit the instance to the set of instances at this node
	m_clusterInstances.add(newInstance);
      } else {
	m_numberSplits++;
      }

      if (finalBestHost == merged) {
	m_numberMerges++;
	m_children.removeElementAt(m_children.indexOf(a));
	m_children.removeElementAt(m_children.indexOf(b));
	m_children.addElement(merged);
      }

      if (finalBestHost == newLeaf) {
	finalBestHost = new CNode(m_numAttributes);
	m_children.addElement(finalBestHost);
      }

      if (bestHostCU < m_cutoff) {
	if (finalBestHost == this) {
	  // splitting was the best, but since we are cutting all children
	  // recursion is aborted and we still need to add the instance
	  // to the set of instances at this node
	  m_clusterInstances.add(newInstance);
	}
	m_children = null;
	finalBestHost = null;
      }

      if (finalBestHost == this) {
	// splitting is still the best, so downdate the stats as
	// we'll be recursively calling on this node
	updateStats(newInstance, true);
      }

      return finalBestHost;
    }

    /**
     * Adds the supplied node as a child of this node. All of the child's
     * instances are added to this nodes instances
     *
     * @param child the child to add
     */
    protected void addChildNode(CNode child) {
      for (int i = 0; i < child.m_clusterInstances.numInstances(); i++) {
	Instance temp = child.m_clusterInstances.instance(i);
	m_clusterInstances.add(temp);
	updateStats(temp, false);
      }

      if (m_children == null) {
	m_children = new FastVector();
      }
      m_children.addElement(child);
    }

    /**
     * Computes the utility of all children with respect to this node
     *
     * @return the category utility of the children with respect to this node.
     * @throws Exception if there are no children
     */
    protected double categoryUtility() throws Exception {

      if (m_children == null) {
	throw new Exception("categoryUtility: No children!");
      }

      double totalCU = 0;

      for (int i = 0; i < m_children.size(); i++) {
	CNode child = (CNode) m_children.elementAt(i);
	totalCU += categoryUtilityChild(child);
      }

      totalCU /= (double)m_children.size();
      return totalCU;
    }

    /**
     * Computes the utility of a single child with respect to this node
     *
     * @param child the child for which to compute the utility
     * @return the utility of the child with respect to this node
     * @throws Exception if something goes wrong
     */
    protected double categoryUtilityChild(CNode child) throws Exception {

      double sum = 0;
      for (int i = 0; i < m_numAttributes; i++) {
	if (m_clusterInstances.attribute(i).isNominal()) {
	  for (int j = 0;
	       j < m_clusterInstances.attribute(i).numValues(); j++) {
	    double x = child.getProbability(i, j);
	    double y = getProbability(i, j);
	    sum += (x * x) - (y * y);
	  }
	} else {
	  // numeric attribute
	  sum += ((m_normal / child.getStandardDev(i)) -
		  (m_normal / getStandardDev(i)));

	}
      }
      return (child.m_totalInstances / m_totalInstances) * sum;
    }

    /**
     * Returns the probability of a value of a nominal attribute in this node
     *
     * @param attIndex the index of the attribute
     * @param valueIndex the index of the value of the attribute
     * @return the probability
     * @throws Exception if the requested attribute is not nominal
     */
    protected double getProbability(int attIndex, int valueIndex)
      throws Exception {

      if (!m_clusterInstances.attribute(attIndex).isNominal()) {
	throw new Exception("getProbability: attribute is not nominal");
      }

      if (m_attStats[attIndex].totalCount <= 0) {
	return 0;
      }

      return (double) m_attStats[attIndex].nominalCounts[valueIndex] /
	(double) m_attStats[attIndex].totalCount;
    }

    /**
     * Returns the standard deviation of a numeric attribute
     *
     * @param attIndex the index of the attribute
     * @return the standard deviation
     * @throws Exception if an error occurs
     */
    protected double getStandardDev(int attIndex) throws Exception {
      if (!m_clusterInstances.attribute(attIndex).isNumeric()) {
	throw new Exception("getStandardDev: attribute is not numeric");
      }

      m_attStats[attIndex].numericStats.calculateDerived();
      double stdDev = m_attStats[attIndex].numericStats.stdDev;
      if (Double.isNaN(stdDev) || Double.isInfinite(stdDev)) {
	return m_acuity;
      }

      return Math.max(m_acuity, stdDev);
    }

    /**
     * Update attribute stats using the supplied instance.
     *
     * @param updateInstance the instance for updating
     * @param delete true if the values of the supplied instance are
     * to be removed from the statistics
     */
    protected void updateStats(Instance updateInstance,
			       boolean delete) {

      if (m_attStats == null) {
	m_attStats = new AttributeStats[m_numAttributes];
	for (int i = 0; i < m_numAttributes; i++) {
	  m_attStats[i] = new AttributeStats();
	  if (m_clusterInstances.attribute(i).isNominal()) {
	    m_attStats[i].nominalCounts =
	      new int [m_clusterInstances.attribute(i).numValues()];
	  } else {
	    m_attStats[i].numericStats = new Stats();
	  }
	}
      }
      for (int i = 0; i < m_numAttributes; i++) {
	if (!updateInstance.isMissing(i)) {
	  double value = updateInstance.value(i);
	  if (m_clusterInstances.attribute(i).isNominal()) {
	    m_attStats[i].nominalCounts[(int)value] += (delete) ?
	      (-1.0 * updateInstance.weight()) :
	      updateInstance.weight();
	    m_attStats[i].totalCount += (delete) ?
	      (-1.0 * updateInstance.weight()) :
	      updateInstance.weight();
	  } else {
	    if (delete) {
	      m_attStats[i].numericStats.subtract(value,
						  updateInstance.weight());
	    } else {
	      m_attStats[i].numericStats.add(value, updateInstance.weight());
	    }
	  }
	}
      }
      m_totalInstances += (delete)
	? (-1.0 * updateInstance.weight())
	: (updateInstance.weight());
    }

    /**
     * Recursively assigns numbers to the nodes in the tree.
     *
     * @param cl_num an int[] value
     * @throws Exception if an error occurs
     */
    private void assignClusterNums(int[] cl_num) throws Exception {
      if (m_children != null && m_children.size() < 2) {
	throw new Exception("assignClusterNums: tree not built correctly!");
      }

      m_clusterNum = cl_num[0];
      cl_num[0]++;
      if (m_children != null) {
	for (int i = 0; i < m_children.size(); i++) {
	  CNode child = (CNode) m_children.elementAt(i);
	  child.assignClusterNums(cl_num);
	}
      }
    }

    /**
     * Recursively build a string representation of the Cobweb tree
     *
     * @param depth depth of this node in the tree
     * @param text holds the string representation
     */
    protected void dumpTree(int depth, StringBuffer text) {

      if (depth == 0)
	determineNumberOfClusters();

      if (m_children == null) {
	text.append("\n");
	for (int j = 0; j < depth; j++) {
	  text.append("|   ");
	}
	text.append("leaf "+m_clusterNum+" ["
		    +m_clusterInstances.numInstances()+"]");
      } else {
	for (int i = 0; i < m_children.size(); i++) {
	  text.append("\n");
	  for (int j = 0; j < depth; j++) {
	    text.append("|   ");
	  }
	  text.append("node "+m_clusterNum+" ["
		      +m_clusterInstances.numInstances()
		      +"]");
	  ((CNode) m_children.elementAt(i)).dumpTree(depth+1, text);
	}
      }
    }

    /**
     * Returns the instances at this node as a string. Appends the cluster
     * number of the child that each instance belongs to.
     *
     * @return a String value
     * @throws Exception if an error occurs
     */
    protected String dumpData() throws Exception {
      if (m_children == null) {
	return m_clusterInstances.toString();
      }

      // construct instances string with cluster numbers attached
      CNode tempNode = new CNode(m_numAttributes);
      tempNode.m_clusterInstances = new Instances(m_clusterInstances, 1);
      for (int i = 0; i < m_children.size(); i++) {
	tempNode.addChildNode((CNode)m_children.elementAt(i));
      }
      Instances tempInst = tempNode.m_clusterInstances;
      tempNode = null;

      Add af = new Add();
      af.setAttributeName("Cluster");
      String labels = "";
      for (int i = 0; i < m_children.size(); i++) {
	CNode temp = (CNode)m_children.elementAt(i);
	labels += ("C"+temp.m_clusterNum);
	if (i < m_children.size()-1) {
	  labels+=",";
	}
      }
      af.setNominalLabels(labels);
      af.setInputFormat(tempInst);
      tempInst = Filter.useFilter(tempInst, af);
      tempInst.setRelationName("Cluster "+m_clusterNum);

      int z = 0;
      for (int i = 0; i < m_children.size(); i++) {
	CNode temp = (CNode)m_children.elementAt(i);
	for (int j = 0; j < temp.m_clusterInstances.numInstances(); j++) {
	  tempInst.instance(z).setValue(m_numAttributes, (double)i);
	  z++;
	}
      }
      return tempInst.toString();
    }

    /**
     * Recursively generate the graph string for the Cobweb tree.
     *
     * @param text holds the graph string
     * @throws Exception if generation fails
     */
    protected void graphTree(StringBuffer text) throws Exception {

      text.append("N"+m_clusterNum
		  + " [label=\""+((m_children == null)
				  ? "leaf " : "node ")
		  +m_clusterNum+" "
		  +" ("+m_clusterInstances.numInstances()
		  +")\" "
		  +((m_children == null)
		    ? "shape=box style=filled " : "")
		  +(m_saveInstances
		    ? "data =\n"+dumpData() +"\n,\n"
		    : "")
		  + "]\n");
      if (m_children != null) {
	for (int i = 0; i < m_children.size(); i++) {
	  CNode temp = (CNode)m_children.elementAt(i);
	  text.append("N"+m_clusterNum
		      +"->"
		      +"N" + temp.m_clusterNum
		      + "\n");
	}

	for (int i = 0; i < m_children.size(); i++) {
	  CNode temp = (CNode)m_children.elementAt(i);
	  temp.graphTree(text);
	}
      }
    }

    /**
     * Returns the revision string.
     *
     * @return		the revision
     */
    public String getRevision() {
      return RevisionUtils.extract("$Revision: 6790 $");
    }
  }

  /**
   * Normal constant.
   */
  protected static final double m_normal = 1.0/(2 * Math.sqrt(Math.PI));

  /**
   * Acuity (minimum standard deviation).
   */
  protected double m_acuity = 1.0;

  /**
   * Cutoff (minimum category utility).
   */
  protected double m_cutoff = 0.01 * Cobweb.m_normal;

  /**
   * Holds the root of the Cobweb tree.
   */
  protected CNode m_cobwebTree = null;

  /**
   * Number of clusters (nodes in the tree). Must never be queried directly,
   * only via the method numberOfClusters(). Otherwise it's not guaranteed that
   * it contains the correct value.
   *
   * @see #numberOfClusters()
   * @see #m_numberOfClustersDetermined
   */
  protected int m_numberOfClusters = -1;

  /** whether the number of clusters was already determined */
  protected boolean m_numberOfClustersDetermined = false;

  /** the number of splits that happened */
  protected int m_numberSplits;

  /** the number of merges that happened */
  protected int m_numberMerges;

  /**
   * Output instances in graph representation of Cobweb tree (Allows
   * instances at nodes in the tree to be visualized in the Explorer).
   */
  protected boolean m_saveInstances = false;

  /**
   * default constructor
   */
  public Cobweb() {
    super();

    m_SeedDefault = 42;
    setSeed(m_SeedDefault);
  }

  /**
   * Returns a string describing this clusterer
   * @return a description of the evaluator suitable for
   * displaying in the explorer/experimenter gui
   */
  public String globalInfo() {
    return
        "Class implementing the Cobweb and Classit clustering algorithms.\n\n"
      + "Note: the application of node operators (merging, splitting etc.) in "
      + "terms of ordering and priority differs (and is somewhat ambiguous) "
      + "between the original Cobweb and Classit papers. This algorithm always "
      + "compares the best host, adding a new leaf, merging the two best hosts, "
      + "and splitting the best host when considering where to place a new "
      + "instance.\n\n"
      + "For more information see:\n\n"
      + getTechnicalInformation().toString();
  }

  /**
   * Returns an instance of a TechnicalInformation object, containing
   * detailed information about the technical background of this class,
   * e.g., paper reference or book this class is based on.
   *
   * @return the technical information about this class
   */
  public TechnicalInformation getTechnicalInformation() {
    TechnicalInformation 	result;
    TechnicalInformation 	additional;

    result = new TechnicalInformation(Type.ARTICLE);
    result.setValue(Field.AUTHOR, "D. Fisher");
    result.setValue(Field.YEAR, "1987");
    result.setValue(Field.TITLE, "Knowledge acquisition via incremental conceptual clustering");
    result.setValue(Field.JOURNAL, "Machine Learning");
    result.setValue(Field.VOLUME, "2");
    result.setValue(Field.NUMBER, "2");
    result.setValue(Field.PAGES, "139-172");

    additional = result.add(Type.ARTICLE);
    additional.setValue(Field.AUTHOR, "J. H. Gennari and P. Langley and D. Fisher");
    additional.setValue(Field.YEAR, "1990");
    additional.setValue(Field.TITLE, "Models of incremental concept formation");
    additional.setValue(Field.JOURNAL, "Artificial Intelligence");
    additional.setValue(Field.VOLUME, "40");
    additional.setValue(Field.PAGES, "11-61");

    return result;
  }

  /**
   * Returns default capabilities of the clusterer.
   *
   * @return      the capabilities of this clusterer
   */
  public Capabilities getCapabilities() {
    Capabilities result = super.getCapabilities();
    result.disableAll();
    result.enable(Capability.NO_CLASS);

    // attributes
    result.enable(Capability.NOMINAL_ATTRIBUTES);
    result.enable(Capability.NUMERIC_ATTRIBUTES);
    result.enable(Capability.DATE_ATTRIBUTES);
    result.enable(Capability.MISSING_VALUES);

    // other
    result.setMinimumNumberInstances(0);

    return result;
  }

  /**
   * Builds the clusterer.
   *
   * @param data the training instances.
   * @throws Exception if something goes wrong.
   */
  public void buildClusterer(Instances data) throws Exception {
    m_numberOfClusters = -1;
    m_cobwebTree = null;
    m_numberSplits = 0;
    m_numberMerges = 0;

    // can clusterer handle the data?
    getCapabilities().testWithFail(data);

    // randomize the instances
    data = new Instances(data);

    if (getSeed() >= 0) {
      data.randomize(new Random(getSeed()));
    }

    for (int i = 0; i < data.numInstances(); i++) {
      updateClusterer(data.instance(i));
    }

    updateFinished();
  }

  /**
   * Singals the end of the updating.
   */
  public void updateFinished() {
    determineNumberOfClusters();
  }

  /**
   * Classifies a given instance.
   *
   * @param instance the instance to be assigned to a cluster
   * @return the number of the assigned cluster as an interger
   * if the class is enumerated, otherwise the predicted value
   * @throws Exception if instance could not be classified
   * successfully
   */
  public int clusterInstance(Instance instance) throws Exception {
    CNode host = m_cobwebTree;
    CNode temp = null;

    determineNumberOfClusters();

    do {
      if (host.m_children == null) {
	temp = null;
	break;
      }

      //host.updateStats(instance, false);
      temp = host.findHost(instance, true);
      // host.updateStats(instance, true);

      if (temp != null) {
	host = temp;
      }
    } while (temp != null);

    return host.m_clusterNum;
  }

  /**
   * determines the number of clusters if necessary
   *
   * @see #m_numberOfClusters
   * @see #m_numberOfClustersDetermined
   */
  protected void determineNumberOfClusters() {
    if (    !m_numberOfClustersDetermined
	 && (m_cobwebTree != null) ) {
      int[] numClusts = new int [1];
      numClusts[0] = 0;
      try {
	m_cobwebTree.assignClusterNums(numClusts);
      }
      catch (Exception e) {
	e.printStackTrace();
	numClusts[0] = 0;
      }
      m_numberOfClusters = numClusts[0];

      m_numberOfClustersDetermined = true;
    }
  }

  /**
   * Returns the number of clusters.
   *
   * @return the number of clusters
   */
  public int numberOfClusters() {
    determineNumberOfClusters();
    return m_numberOfClusters;
  }

  /**
   * Adds an instance to the clusterer.
   *
   * @param newInstance the instance to be added
   * @throws Exception 	if something goes wrong
   */
  public void updateClusterer(Instance newInstance) throws Exception {
    m_numberOfClustersDetermined = false;

    if (m_cobwebTree == null) {
      m_cobwebTree = new CNode(newInstance.numAttributes(), newInstance);
    } else {
      m_cobwebTree.addInstance(newInstance);
    }
  }

  /**
   * Adds an instance to the Cobweb tree.
   *
   * @param newInstance the instance to be added
   * @throws Exception if something goes wrong
   * @deprecated updateClusterer(Instance) should be used instead
   * @see #updateClusterer(Instance)
   */
  public void addInstance(Instance newInstance) throws Exception {
    updateClusterer(newInstance);
  }

  /**
   * Returns an enumeration describing the available options.
   *
   * @return an enumeration of all the available options.
   **/
  public Enumeration listOptions() {
    Vector result = new Vector();

    result.addElement(new Option(
	"\tAcuity.\n"
	+"\t(default=1.0)",
	"A", 1,"-A <acuity>"));

    result.addElement(new Option(
	"\tCutoff.\n"
	+"\t(default=0.002)",
	"C", 1,"-C <cutoff>"));

    Enumeration en = super.listOptions();
    while (en.hasMoreElements())
      result.addElement(en.nextElement());

    return result.elements();
  }

  /**
   * Parses a given list of options.

   *

   * Valid options are:

   *
   *
 -A <acuity>
   *  Acuity.
   *  (default=1.0)

   *
   *
 -C <cutoff>
   *  Cutoff.
   *  (default=0.002)

   *
   *
 -S <num>
   *  Random number seed.
   *  (default 42)

   *

   *
   * @param options the list of options as an array of strings
   * @throws Exception if an option is not supported
   */
  public void setOptions(String[] options) throws Exception {
    String optionString;

    optionString = Utils.getOption('A', options);
    if (optionString.length() != 0) {
      Double temp = new Double(optionString);
      setAcuity(temp.doubleValue());
    }
    else {
      m_acuity = 1.0;
    }
    optionString = Utils.getOption('C', options);
    if (optionString.length() != 0) {
      Double temp = new Double(optionString);
      setCutoff(temp.doubleValue());
    }
    else {
      m_cutoff = 0.01 * Cobweb.m_normal;
    }

    super.setOptions(options);
  }

  /**
   * Returns the tip text for this property
   * @return tip text for this property suitable for
   * displaying in the explorer/experimenter gui
   */
  public String acuityTipText() {
    return "set the minimum standard deviation for numeric attributes";
  }

  /**
   * set the acuity.
   * @param a the acuity value
   */
  public void setAcuity(double a) {
    m_acuity = a;
  }

  /**
   * get the acuity value
   * @return the acuity
   */
  public double getAcuity() {
    return m_acuity;
  }

  /**
   * Returns the tip text for this property
   * @return tip text for this property suitable for
   * displaying in the explorer/experimenter gui
   */
  public String cutoffTipText() {
    return "set the category utility threshold by which to prune nodes";
  }

  /**
   * set the cutoff
   * @param c the cutof
   */
  public void setCutoff(double c) {
    m_cutoff = c;
  }

  /**
   * get the cutoff
   * @return the cutoff
   */
  public double getCutoff() {
    return m_cutoff;
  }

  /**
   * Returns the tip text for this property
   * @return tip text for this property suitable for
   * displaying in the explorer/experimenter gui
   */
  public String saveInstanceDataTipText() {
    return "save instance information for visualization purposes";
  }

  /**
   * Get the value of saveInstances.
   *
   * @return Value of saveInstances.
   */
  public boolean getSaveInstanceData() {

    return m_saveInstances;
  }

  /**
   * Set the value of saveInstances.
   *
   * @param newsaveInstances Value to assign to saveInstances.
   */
  public void setSaveInstanceData(boolean newsaveInstances) {

    m_saveInstances = newsaveInstances;
  }

  /**
   * Gets the current settings of Cobweb.
   *
   * @return an array of strings suitable for passing to setOptions()
   */
  public String[] getOptions() {
    int       		i;
    Vector<String>    	result;
    String[]  		options;

    result = new Vector<String>();

    result.add("-A");
    result.add("" + m_acuity);
    result.add("-C");
    result.add("" + m_cutoff);

    options = super.getOptions();
    for (i = 0; i < options.length; i++)
      result.add(options[i]);

    return result.toArray(new String[result.size()]);
  }

  /**
   * Returns a description of the clusterer as a string.
   *
   * @return a string describing the clusterer.
   */
  public String toString() {
    StringBuffer text = new StringBuffer();
    if (m_cobwebTree == null) {
      return "Cobweb hasn't been built yet!";
    }
    else {
      m_cobwebTree.dumpTree(0, text);
      return "Number of merges: "
	+ m_numberMerges+"\nNumber of splits: "
	+ m_numberSplits+"\nNumber of clusters: "
	+ numberOfClusters() +"\n"+text.toString()+"\n\n";

    }
  }

  /**
   *  Returns the type of graphs this class
   *  represents
   *  @return Drawable.TREE
   */
  public int graphType() {
      return Drawable.TREE;
  }

  /**
   * Generates the graph string of the Cobweb tree
   *
   * @return a String value
   * @throws Exception if an error occurs
   */
  public String graph() throws Exception {
    StringBuffer text = new StringBuffer();

    text.append("digraph CobwebTree {\n");
    m_cobwebTree.graphTree(text);
    text.append("}\n");
    return text.toString();
  }

  /**
   * Returns the revision string.
   *
   * @return		the revision
   */
  public String getRevision() {
    return RevisionUtils.extract("$Revision: 6790 $");
  }

  /**
   * Returns the tip text for this property
   *
   * @return            tip text for this property suitable for
   *                    displaying in the explorer/experimenter gui
   */
  public String seedTipText() {
    String result = super.seedTipText() + " Use -1 for no randomization.";

    return result;
  }

  /**
   * Main method.
   *
   * @param argv the commandline options
   */
  public static void main(String[] argv) {
    runClusterer(new Cobweb(), argv);
  }
}


text:
/****************************************************************************
	leaflet-control-home.js,

	(c) 2016, FCOO

	https://github.com/FCOO/leaflet-control-home
	https://github.com/FCOO

****************************************************************************/
;(function (L, window, document, undefined) {
  /* global L */
  'use strict';
	var protocol = window.location.protocol == 'https:' ? 'https:' : 'http:';

  L.Control.HomeButton = L.Control.extend({
    options: {
      position: 'topleft',
      href: protocol + '//' + window.location.host,
      title: 'Navigate to home page',
      className: 'leaflet-control-home',
      icon: 'leaflet-control-home-toggle'
    },
    onAdd: function (map) {
      this._map = map;
      return this._container;
    },
    initialize: function (options) {
      L.setOptions(this, options);
      //var container = L.DomUtil.create('div', 'leaflet-bar ' +
      //  this.options.className);
      var container = L.DomUtil.create('div', this.options.className);
      this._container = container;
      this._homeButton = this._createHomeButton(container);

      L.DomEvent.disableClickPropagation(container);
      return this._container;
    },
    _createHomeButton: function () {
      var link = L.DomUtil.create('a', this.options.icon,
        this._container);
      link.href = this.options.href;
      link.title = this.options.title;

      L.DomEvent
        .on(link, 'mousedown dblclick', L.DomEvent.stopPropagation);
        //.on(link, 'click', L.DomEvent.stop)
      return link;
    },
  });

  L.control.homeButton = function (options) {
    return new L.Control.HomeButton(options);
  };

  return L.Control.HomeButton;

}(L, this, document));


text:
<?php

namespace App\Http\Controllers\Opwifi\Device;
use App\Http\Controllers\Opwifi\OwCRUDController;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;

use Input;

use App\Models\OwDevConfigs;

//use App\Http\Helpers\Opwifi\DeviceConfigApply;

class ConfigController extends OwCRUDController {

	protected $viewData = array(
	);

    public function __construct()
    {
    }

    protected $limitUserId = 'mnger_id';
    protected $indexOwnModel = 'name';
    protected function newOwnModel() {
    	return new OwDevConfigs();
    }

	public function getIndex(Request $request) {
		return view("opwifi.device.config", $this->viewData);
	}

    public function getEdit(Request $request, $id) {
        $cfg = OwDevConfigs::where("id", $id)->first();
        return view("opwifi.device.config_edit", $this->viewData)->with('config', $cfg);
    }

    public function postEdit(Request $request, $id) {
        $cfg = OwDevConfigs::where("id", $id)->first();
        $cfg->update($request->all());
        return redirect()->route('opwifi::device.config');
    }
}


text:
package de.iweinzierl.easyprofiles.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

import de.inselhome.android.utils.UiUtils;
import de.iweinzierl.easyprofiles.R;
import de.iweinzierl.easyprofiles.domain.TimePeriod;

public class TimeRangeAdapter extends ListAdapter<TimePeriod> {

    public TimeRangeAdapter(Context context, List<TimePeriod> items) {
        super(context, items);
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item = inflater.inflate(R.layout.spinner_item_timerange, viewGroup, false);

        TimePeriod timePeriod = (TimePeriod) getItem(i);

        TextView period = UiUtils.getGeneric(TextView.class, item, R.id.period);
        TextView unit = UiUtils.getGeneric(TextView.class, item, R.id.unit);

        period.setText(String.valueOf(timePeriod.getPeriod()));
        unit.setText(timePeriod.getUnit().name());

        return item;
    }
}


text:
//
//  MGViewAnimation.m
//  Created by Matt Gemmell on 13/11/2006. http://mattgemmell.com/
//  Based on code by Todd Yandell http://tyandell.googlepages.com/
//  Includes bug fix by Joe Goh http://www.funkeemonk.com/funkeestory/
//

#import "MGViewAnimation.h"

@implementation MGViewAnimation

- (id)initWithViewAnimations:(NSArray*)viewAnimations
{
    if (self = [super initWithDuration:0.5 animationCurve:NSAnimationEaseInOut]) {
        [self setAnimationBlockingMode:NSAnimationNonblocking];

        _views = [[NSMutableArray alloc] initWithCapacity:[viewAnimations count]];
        _fadeViews = [[NSMutableDictionary alloc] initWithCapacity:0];
        _fadeImages = [[NSMutableDictionary alloc] initWithCapacity:0];

        [self setViewAnimations:viewAnimations];

        _continuouslyUpdatesFadingViews = YES;
        _ordersOutFadedWindows = YES;

        [self addProgressMark:1.0];
    }

    return self;
}

- (void)setViewAnimations:(NSArray *)viewAnimations
{
    // Ensure we have suitable start and end frames for every animation
    NSMutableArray *normalizedAnimations = [[NSMutableArray alloc] initWithCapacity:[viewAnimations count]];
    NSEnumerator *animationsEnum = [viewAnimations objectEnumerator];
    NSDictionary *nextAnimation;

    while (nextAnimation = [animationsEnum nextObject]) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:nextAnimation];
        id thisView;
        if ((thisView = [dict objectForKey:NSViewAnimationTargetKey])) {
            if ([thisView isKindOfClass:[NSWindow class]] || [thisView isKindOfClass:[NSView class]]) {
                [_views addObject:thisView];
                NSValue *viewFrameValue = [NSValue valueWithRect:[thisView frame]];
                if (![dict objectForKey:NSViewAnimationStartFrameKey]) {
                    [dict setObject:viewFrameValue forKey:NSViewAnimationStartFrameKey];
                }
                if (![dict objectForKey:NSViewAnimationEndFrameKey]) {
                    [dict setObject:viewFrameValue forKey:NSViewAnimationEndFrameKey];
                }
                [normalizedAnimations addObject:dict];
            }
        }
        [dict release];
    }

    _viewAnimations = normalizedAnimations; // already retained by init...: above
}

- (NSArray *)viewAnimations
{
    return _viewAnimations;
}

- (void)stopAnimation
{
    if ([self isAnimating]) {
        [super stopAnimation];
        [self setCurrentProgress:1.0];
    }
}

- (void)setCurrentProgress:(float)progress
{
    NSDisableScreenUpdates();
    [super setCurrentProgress:progress];

    NSEnumerator *viewEnum = [_views objectEnumerator];
    id nextTarget;
    NSMutableArray *superviews = [[NSMutableArray alloc] initWithCapacity:[_views count]];
    int i = 0;

    while (nextTarget = [viewEnum nextObject]) {
        NSRect newFrame = [self frameForView:(NSView *)nextTarget atProgress:[self currentValue]];
        if ([nextTarget isKindOfClass:[NSWindow class]]) {
            [(NSWindow *)nextTarget setFrame:newFrame display:YES];
        } else {
            [(NSView *)nextTarget setFrame:newFrame];
        }

        /*
         NSViewAnimationEffectKey
         An effect to apply to the animation.

         Takes a string constant specifying fade-in or fade-out effects for the target:
         NSViewAnimationFadeInEffect and NSViewAnimationFadeOutEffect. If the target is
         a view and the effect is to fade out, the view is hidden at the end. If the effect
         is to fade in an initially hidden view and the end frame is non-empty, the view is
         unhidden at the end. If the target is a window, the window is ordered in or out as
         appropriate to the effect. This property is optional.
         */
        NSString *effectKey = [[_viewAnimations objectAtIndex:i] objectForKey:NSViewAnimationEffectKey];
        BOOL fadeOut = [effectKey isEqualToString:NSViewAnimationFadeOutEffect];
        if (effectKey) {
            NSString *key = [NSString stringWithFormat:@"%d", i];
            if ([nextTarget isKindOfClass:[NSView class]]) {
                NSView *nextView = (NSView *)nextTarget;
                if (progress == 1.0) {
                    // Destroy _fadeImage and _fadeView
                    [(NSImageView *)[_fadeViews objectForKey:key] removeFromSuperview];
                    [_fadeViews removeObjectForKey:key];
                    [_fadeImages removeObjectForKey:key];

                    if (!fadeOut) {
                        [nextView setHidden:NO];
                    }
                } else if (![nextView isHidden] || ![_fadeViews objectForKey:key]) { // we always hide the view before starting a fade effect
                                                                                // Create view image for this view and NSImageView to display it
                    NSImage *thisImg = [[NSImage alloc] initWithSize:[nextView bounds].size];
                    [thisImg lockFocus];
                    // Make nextView draw itself into our image, even though it's hidden
                    [nextView drawRect:[nextView bounds]];
                    [thisImg unlockFocus];
                    [_fadeImages setObject:thisImg forKey:key];
                    [thisImg release];

                    NSImageView *imgView = [[NSImageView alloc] initWithFrame:newFrame];
                    [imgView setImageFrameStyle:NSImageFrameNone];
                    [imgView setImageScaling:NSImageScaleNone];
                    if (fadeOut) {
                        [imgView setImage:thisImg];
                    }
                    [[nextView superview] addSubview:imgView positioned:NSWindowAbove relativeTo:nextView];
                    [_fadeViews setObject:imgView forKey:key];
                    [imgView release];

                    [nextView setHidden:YES];
                } else {
                    // Create image representation of thisView
                    NSImage *thisViewImage = [[NSImage alloc] initWithSize:newFrame.size];
                    NSImage *thisImg;
                    if ([self continuouslyUpdatesFadingViews]) {
                        thisImg = [[[NSImage alloc] initWithSize:[nextView bounds].size] autorelease];
                        [thisImg lockFocus];
                        // Make nextView draw itself into our image, even though it's hidden
                        [nextView drawRect:[nextView bounds]];
                        [thisImg unlockFocus];
                        // Update stored image
                        [_fadeImages setObject:thisImg forKey:key];
                    } else {
                        thisImg = (NSImage *)[_fadeImages objectForKey:key];
                    }

                    float fraction = (fadeOut) ? 1.0 - progress : progress;
                    [thisViewImage lockFocus];
                    [thisImg compositeToPoint:NSZeroPoint operation:NSCompositingOperationSourceOver fraction:fraction];
                    [thisViewImage unlockFocus];

                    NSImageView *fadeView = (NSImageView *)[_fadeViews objectForKey:key];
                    [fadeView setImage:thisViewImage];
                    [fadeView setFrame:newFrame];
                    [thisViewImage release];
                }
            } else {
                // This is a window
                NSWindow *win = (NSWindow *)nextTarget;
                if (!fadeOut && ![win isVisible]) {
                    // Starting animation
                    [win setAlphaValue:0.0];
                    [win orderFront:nil];
                } else if (progress == 1.0 && fadeOut) {
                    // Finishing animation
                    [win setAlphaValue:0.0];
                    if ([self ordersOutFadedWindows]) {
                        [win orderOut:nil];
                    }
                } else {
                    [win setAlphaValue:(fadeOut) ? 1.0 - progress : progress];
                }
            }
        }

        if ([nextTarget isKindOfClass:[NSView class]]) {
            NSView *superview = [nextTarget superview];
            if (![superviews containsObject:superview]) {
                [superview setNeedsDisplay:YES];
                [superviews addObject:superview];
            }
        }
        i++;
    }

    viewEnum = [superviews objectEnumerator];
    NSView *superview;
    while (superview = [viewEnum nextObject]) {
        [superview displayIfNeeded];
    }
    [superviews release];
    NSEnableScreenUpdates();
}

- (void)dealloc
{
    [_fadeViews release];
    [_fadeImages release];
    [_views release];
    [_viewAnimations release];
    [super dealloc];
}

- (NSRect)frameForView:(NSView *)view atProgress:(float)progress
{
    NSRect originalRect = [self originalFrameForView:view];
    NSRect destinationRect = [self destinationFrameForView:view];

    return NSMakeRect(
          round(originalRect.origin.x + ((destinationRect.origin.x - originalRect.origin.x) * progress)),
          round(originalRect.origin.y + ((destinationRect.origin.y - originalRect.origin.y) * progress)),
          originalRect.size.width + ((destinationRect.size.width - originalRect.size.width) * progress),
          originalRect.size.height + ((destinationRect.size.height - originalRect.size.height) * progress));
}

- (NSRect)originalFrameForView:(NSView *)view
{
    NSEnumerator *infoEnum = [_viewAnimations objectEnumerator];
    NSDictionary *nextInfo;

    while (nextInfo = [infoEnum nextObject]) {
        if ([[nextInfo objectForKey:NSViewAnimationTargetKey] isEqual:view]) {
            return [[nextInfo objectForKey:NSViewAnimationStartFrameKey] rectValue];
        }
    }

    return NSZeroRect;
}

- (NSRect)destinationFrameForView:(NSView *)view
{
    NSEnumerator *infoEnum = [_viewAnimations objectEnumerator];
    NSDictionary *nextInfo;

    while (nextInfo = [infoEnum nextObject]) {
        if ([[nextInfo objectForKey:NSViewAnimationTargetKey] isEqual:view]) {
            return [[nextInfo objectForKey:NSViewAnimationEndFrameKey] rectValue];
        }
    }

    return NSZeroRect;
}

- (BOOL)continuouslyUpdatesFadingViews
{
    return _continuouslyUpdatesFadingViews;
}

- (void)setContinuouslyUpdateFadingViews:(BOOL)value
{
    _continuouslyUpdatesFadingViews = value;
}

- (BOOL)ordersOutFadedWindows
{
    return _ordersOutFadedWindows;
}

- (void)setOrdersOutFadedWindows:(BOOL)value
{
    _ordersOutFadedWindows = value;
}

@end


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
from time import time

import pandas as pd
import psutil

class Runtime(list):
    # TODO: https://docs.python.org/3/library/time.html#time.process_time
    # TODO: https://docs.python.org/3/library/time.html#time.perf_counter
    def __init__(self):
        self.starting_time = time()
        self.previous = 0
        super(Runtime, self).__init__()

    def dataframe(self):
        return pd.DataFrame(data=self, columns=['cumulative', 'incremental'])

    def record(self):
        cumulative = time() - self.starting_time
        incremental = cumulative - self.previous
        self.previous = cumulative
        self.append([cumulative, incremental])
        print('Runtime:{:0.2f} s,\t{:0.3f} s'.format(cumulative,
                                                     incremental))

class MemoryUsage(list):
    def __init__(self):
        self.process = psutil.Process(os.getpid())
        self.previous = 0
        super(MemoryUsage, self).__init__()

    def dataframe(self):
        return pd.DataFrame(data=self, columns=['memory_usage', 'differential'])

    def record(self):
        memory_usage = self.process.get_memory_info()[0] / (2 ** 20)
        differential = memory_usage - self.previous
        self.previous = memory_usage
        self.append([memory_usage, differential])
        print('Memory: {:0.2f} MB,\t{:0.8f} MB'.format(memory_usage,
                                                       differential))


text:
require 'bundler/setup'
require 'rack/cascade'
require 'firehose'

module Rack
  # Middleware that wraps rack endpoint in front of [Firehose](http://firehose.io) endpoint.
  class Firehose
    # @param [Object] app rack application to wrap
    # @param [Hash] options
    # @option options [Boolean] :allow_puts Allow PUT requests to publish content. Default false.
    def initialize(app, options = {})
      @options = {
        :allow_puts => false
      }.merge(options)

      @rack     = app
      @firehose = @options[:allow_puts] ? ::Firehose::Rack::App.new : ::Firehose::Rack::ConsumerApp.new
      @app      = Rack::Cascade.new [@rack, @firehose]

      # sinatra doesn't work with #extend
      @rack.class.send :include, DSL
    end

    def call(env)
      unless env['async.callback']
        raise ArgumentError.new "Unsupported server: missing env['async.callback']"
      end
      @app.call(env)
    end

    # This module is mixed into the rack application.
    module DSL
      # @param [String] content message to publish
      # @param [Hash] options
      # @option options [String] :to path to publish content to
      def chunk(content, options = {})
        raise ArgumentError.new ":to not specified" unless options[:to]
        @_firehose_publisher ||= ::Firehose::Publisher.new
        @_firehose_publisher.publish options[:to], content
      end
    end
  end
end


text:
/**
 * Module dependencies
 */

var nodeunit = require('../nodeunit'),
    utils = require('../utils'),
    fs = require('fs'),
    track = require('../track'),
    path = require('path'),
    AssertionError = require('../assert').AssertionError;

/**
 * Reporter info string
 */

exports.info = "Default tests reporter";

/**
 * Run all tests within each module, reporting the results to the command-line.
 *
 * @param {Array} files
 * @api public
 */

exports.run = function (files, options, callback) {

    if (!options) {
        // load default options
        var content = fs.readFileSync(
            __dirname + '/../../bin/nodeunit.json', 'utf8'
        );
        options = JSON.parse(content);
    }

    var error = function (str) {
        return options.error_prefix + str + options.error_suffix;
    };
    var ok    = function (str) {
        return options.ok_prefix + str + options.ok_suffix;
    };
    var bold  = function (str) {
        return options.bold_prefix + str + options.bold_suffix;
    };
    var assertion_message = function (str) {
        return options.assertion_prefix + str + options.assertion_suffix;
    };

    var start = new Date().getTime();
    var tracker = track.createTracker(function (tracker) {
        if (tracker.unfinished()) {
            console.log('');
            console.log(error(bold(
                'FAILURES: Undone tests (or their setups/teardowns): '
            )));
            var names = tracker.names();
            for (var i = 0; i < names.length; i += 1) {
                console.log('- ' + names[i]);
            }
            console.log('');
            console.log('To fix this, make sure all tests call test.done()');
            process.reallyExit(tracker.unfinished());
        }
    });

	var opts = {
	    testspec: options.testspec,
	    testFullSpec: options.testFullSpec,
        moduleStart: function (name) {
            console.log('\n' + bold(name));
        },
        testDone: function (name, assertions) {
            tracker.remove(name);

            if (!assertions.failures()) {
                console.log('✔ ' + name);
            }
            else {
                console.log(error('✖ ' + name) + '\n');
                assertions.forEach(function (a) {
                    if (a.failed()) {
                        a = utils.betterErrors(a);
                        if (a.error instanceof AssertionError && a.message) {
                            console.log(
                                'Assertion Message: ' +
                                assertion_message(a.message)
                            );
                        }
                        console.log(a.error.stack + '\n');
                    }
                });
            }
        },
        done: function (assertions, end) {
            var end = end || new Date().getTime();
            var duration = end - start;
            if (assertions.failures()) {
                console.log(
                    '\n' + bold(error('FAILURES: ')) + assertions.failures() +
                    '/' + assertions.length + ' assertions failed (' +
                    assertions.duration + 'ms)'
                );
            }
            else {
                console.log(
                   '\n' + bold(ok('OK: ')) + assertions.length +
                   ' assertions (' + assertions.duration + 'ms)'
                );
            }

            if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined);
        },
        testStart: function(name) {
            tracker.put(name);
        }
    };
	if (files && files.length) {
	    var paths = files.map(function (p) {
	        return path.resolve(p);
	    });
	    nodeunit.runFiles(paths, opts);
	} else {
		nodeunit.runModules(files,opts);
	}
};