text:
package org.apache.sling.discovery.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.discovery.base.connectors.BaseConfig;
import org.apache.sling.discovery.commons.providers.spi.base.DiscoveryLiteConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Configuration object used as a central config point for the discovery service
 * implementation
 *

 * The properties are described below under.
 */
@Component(metatype = true, label="%config.name", description="%config.description")
@Service(value = { Config.class, BaseConfig.class, DiscoveryLiteConfig.class })
public class Config implements BaseConfig, DiscoveryLiteConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /** resource used to keep instance information such as last heartbeat, properties, incoming announcements **/
    private static final String CLUSTERINSTANCES_RESOURCE = "clusterInstances";

    /** resource used to store the sync tokens as part of a topology change **/
    private static final String SYNC_TOKEN_RESOURCE = "syncTokens";

    /** resource used to store the clusterNodeIds to slingIds map **/
    private static final String ID_MAP_RESOURCE = "idMap";

    /** resource used to keep the currently established view **/
    private static final String ESTABLISHED_VIEW_RESOURCE = "establishedView";

    /** resource used to keep the previously established view **/
    private static final String PREVIOUS_VIEW_RESOURCE = "previousView";

    /** resource used to keep ongoing votings **/
    private static final String ONGOING_VOTING_RESOURCE = "ongoingVotings";

    /** Configure the timeout (in seconds) after which an instance is considered dead/crashed. */
    public static final long DEFAULT_HEARTBEAT_TIMEOUT = 120;
    @Property(longValue=DEFAULT_HEARTBEAT_TIMEOUT)
    public static final String HEARTBEAT_TIMEOUT_KEY = "heartbeatTimeout";
    protected long heartbeatTimeout = DEFAULT_HEARTBEAT_TIMEOUT;

    /** Configure the interval (in seconds) according to which the heartbeats are exchanged in the topology. */
    public static final long DEFAULT_HEARTBEAT_INTERVAL = 30;
    @Property(longValue=DEFAULT_HEARTBEAT_INTERVAL)
    public static final String HEARTBEAT_INTERVAL_KEY = "heartbeatInterval";
    protected long heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL;

    /** Configure the time (in seconds) which must be passed at minimum between sending TOPOLOGY_CHANGING/_CHANGED (avoid flooding). */
    public static final int DEFAULT_MIN_EVENT_DELAY = 3;
    @Property(intValue=DEFAULT_MIN_EVENT_DELAY)
    public static final String MIN_EVENT_DELAY_KEY = "minEventDelay";
    protected int minEventDelay = DEFAULT_MIN_EVENT_DELAY;

    /** Configure the socket connect timeout for topology connectors. */
    public static final int DEFAULT_CONNECTION_TIMEOUT = 10;
    @Property(intValue=DEFAULT_CONNECTION_TIMEOUT)
    public static final String CONNECTION_TIMEOUT_KEY = "connectionTimeout";
    private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;

    /** Configure the socket read timeout (SO_TIMEOUT) for topology connectors. */
    public static final int DEFAULT_SO_TIMEOUT = 10;
    @Property(intValue=DEFAULT_SO_TIMEOUT)
    public static final String SO_TIMEOUT_KEY = "soTimeout";
    private int soTimeout = DEFAULT_SO_TIMEOUT;

    /** Name of the repository descriptor to be taken into account for leader election:
        those instances have preference to become leader which have the corresponding descriptor value of 'false' */
    @Property
    public static final String LEADER_ELECTION_REPOSITORY_DESCRIPTOR_NAME_KEY = "leaderElectionRepositoryDescriptor";

    /**
     * Whether or not (default false) the leaderElectionRepositoryDescriptor should be inverted (if that one
     * is configured at all).
     */
    @Property(boolValue=false)
    public static final String INVERT_REPOSITORY_DESCRIPTOR_NAME_KEY = "invertRepositoryDescriptor";

    /** URLs where to join a topology, eg http://localhost:4502/libs/sling/topology/connector */
    @Property(cardinality=1024)
    public static final String TOPOLOGY_CONNECTOR_URLS_KEY = "topologyConnectorUrls";
    private URL[] topologyConnectorUrls = {null};

    /** list of ips and/or hostnames which are allowed to connect to /libs/sling/topology/connector */
    private static final String[] DEFAULT_TOPOLOGY_CONNECTOR_WHITELIST = {"localhost","127.0.0.1"};
    @Property(value={"localhost","127.0.0.1"})
    public static final String TOPOLOGY_CONNECTOR_WHITELIST_KEY = "topologyConnectorWhitelist";
    private String[] topologyConnectorWhitelist = DEFAULT_TOPOLOGY_CONNECTOR_WHITELIST;

    /** Path of resource where to keep discovery information, e.g /var/discovery/impl/ */
    private static final String DEFAULT_DISCOVERY_RESOURCE_PATH = "/var/discovery/impl/";
    @Property(value=DEFAULT_DISCOVERY_RESOURCE_PATH, propertyPrivate=true)
    public static final String DISCOVERY_RESOURCE_PATH_KEY = "discoveryResourcePath";
    private String discoveryResourcePath = DEFAULT_DISCOVERY_RESOURCE_PATH;

    /**
     * If set to true, local-loops of topology connectors are automatically stopped when detected so.
     */
    @Property(boolValue=false)
    private static final String AUTO_STOP_LOCAL_LOOP_ENABLED = "autoStopLocalLoopEnabled";

    /**
     * If set to true, request body will be gzipped - only works if counter-part accepts gzip-requests!
     */
    @Property(boolValue=false)
    private static final String GZIP_CONNECTOR_REQUESTS_ENABLED = "gzipConnectorRequestsEnabled";

    /**
     * If set to true, hmac is enabled and the white list is disabled.
     */
    @Property(boolValue=false)
    private static final String HMAC_ENABLED = "hmacEnabled";

    /**
     * If set to true, and the whitelist is disabled, messages will be encrypted.
     */
    @Property(boolValue=false)
    private static final String ENCRYPTION_ENABLED = "enableEncryption";

    /**
     * The value fo the shared key, shared amongst all instances in the same cluster.
     */
    @Property
    private static final String SHARED_KEY = "sharedKey";

    /**
     * The default lifetime of a HMAC shared key in ms. (4h)
     */
    private static final long DEFAULT_SHARED_KEY_INTERVAL = 3600*1000*4;

    @Property(longValue=DEFAULT_SHARED_KEY_INTERVAL)
    private static final String SHARED_KEY_INTERVAL = "hmacSharedKeyTTL";

    /**
     * The property for defining the backoff factor for standby (loop) connectors
     */
    @Property
    private static final String BACKOFF_STANDBY_FACTOR = "backoffStandbyFactor";
    private static final int DEFAULT_BACKOFF_STANDBY_FACTOR = 5;

    /**
     * The property for defining the maximum backoff factor for stable connectors
     */
    @Property
    private static final String BACKOFF_STABLE_FACTOR = "backoffStableFactor";
    private static final int DEFAULT_BACKOFF_STABLE_FACTOR = 5;

    /**
     * when set to true and the syncTokenService (of discovery.commons) is available,
     * then it is used
     */
    @Property(boolValue=true)
    private static final String USE_SYNC_TOKEN_SERVICE_ENABLED = "useSyncTokenService";

    private String leaderElectionRepositoryDescriptor ;

    private boolean invertRepositoryDescriptor = false; /* default: false */

    /** True when auto-stop of a local-loop is enabled. Default is false. **/
    private boolean autoStopLocalLoopEnabled;

    /**
     * True when the hmac is enabled and signing is disabled.
     */
    private boolean hmacEnabled;

    /**
     * the shared key.
     */
    private String sharedKey;

    /**
     * The key interval.
     */
    private long keyInterval;

    /**
     * true when encryption is enabled.
     */
    private boolean encryptionEnabled;

    /**
     * true when topology connector requests should be gzipped
     */
    private boolean gzipConnectorRequestsEnabled;

    /** the backoff factor to be used for standby (loop) connectors **/
    private int backoffStandbyFactor = DEFAULT_BACKOFF_STANDBY_FACTOR;

    /** the maximum backoff factor to be used for stable connectors **/
    private int backoffStableFactor = DEFAULT_BACKOFF_STABLE_FACTOR;

    /**
     * when set to true and the syncTokenService (of discovery.commons) is available,
     * then it is used.
     */
    private boolean useSyncTokenService = true;

    @Activate
    protected void activate(final Map<String, Object> properties) {
		logger.debug("activate: config activated.");
        configure(properties);
    }

    protected void configure(final Map<String, Object> properties) {
        this.heartbeatTimeout = PropertiesUtil.toLong(
                properties.get(HEARTBEAT_TIMEOUT_KEY),
                DEFAULT_HEARTBEAT_TIMEOUT);
        logger.debug("configure: heartbeatTimeout='{}'", this.heartbeatTimeout);

        this.heartbeatInterval = PropertiesUtil.toLong(
                properties.get(HEARTBEAT_INTERVAL_KEY),
                DEFAULT_HEARTBEAT_INTERVAL);
        logger.debug("configure: heartbeatInterval='{}'",
                this.heartbeatInterval);

        this.minEventDelay = PropertiesUtil.toInteger(
                properties.get(MIN_EVENT_DELAY_KEY),
                DEFAULT_MIN_EVENT_DELAY);
        logger.debug("configure: minEventDelay='{}'",
                this.minEventDelay);

        this.connectionTimeout = PropertiesUtil.toInteger(
                properties.get(CONNECTION_TIMEOUT_KEY),
                DEFAULT_CONNECTION_TIMEOUT);
        logger.debug("configure: connectionTimeout='{}'",
                this.connectionTimeout);

        this.soTimeout = PropertiesUtil.toInteger(
                properties.get(SO_TIMEOUT_KEY),
                DEFAULT_SO_TIMEOUT);
        logger.debug("configure: soTimeout='{}'",
                this.soTimeout);

        String[] topologyConnectorUrlsStr = PropertiesUtil.toStringArray(
                properties.get(TOPOLOGY_CONNECTOR_URLS_KEY), null);
        if (topologyConnectorUrlsStr!=null && topologyConnectorUrlsStr.length > 0) {
            List<URL> urls = new LinkedList<URL>();
            for (int i = 0; i < topologyConnectorUrlsStr.length; i++) {
                String anUrlStr = topologyConnectorUrlsStr[i];
                try {
                	if (anUrlStr!=null && anUrlStr.length()>0) {
	                    URL url = new URL(anUrlStr);
	                    logger.debug("configure: a topologyConnectorbUrl='{}'",
	                            url);
	                    urls.add(url);
                	}
                } catch (MalformedURLException e) {
                    logger.error("configure: could not set a topologyConnectorUrl: " + e,
                            e);
                }
            }
            if (urls.size()>0) {
                this.topologyConnectorUrls = urls.toArray(new URL[urls.size()]);
                logger.debug("configure: number of topologyConnectorUrls='{}''",
                        urls.size());
            } else {
                this.topologyConnectorUrls = null;
                logger.debug("configure: no (valid) topologyConnectorUrls configured");
            }
        } else {
            this.topologyConnectorUrls = null;
            logger.debug("configure: no (valid) topologyConnectorUrls configured");
        }
        this.topologyConnectorWhitelist = PropertiesUtil.toStringArray(
                properties.get(TOPOLOGY_CONNECTOR_WHITELIST_KEY),
                DEFAULT_TOPOLOGY_CONNECTOR_WHITELIST);
        logger.debug("configure: topologyConnectorWhitelist='{}'",
                this.topologyConnectorWhitelist);

        this.discoveryResourcePath = PropertiesUtil.toString(
                properties.get(DISCOVERY_RESOURCE_PATH_KEY),
                "");
        while(this.discoveryResourcePath.endsWith("/")) {
            this.discoveryResourcePath = this.discoveryResourcePath.substring(0,
                    this.discoveryResourcePath.length()-1);
        }
        this.discoveryResourcePath = this.discoveryResourcePath + "/";
        if (this.discoveryResourcePath==null || this.discoveryResourcePath.length()<=1) {
            // if the path is empty, or /, then use the default
            this.discoveryResourcePath = DEFAULT_DISCOVERY_RESOURCE_PATH;
        }
        logger.debug("configure: discoveryResourcePath='{}'",
                this.discoveryResourcePath);

        this.leaderElectionRepositoryDescriptor = PropertiesUtil.toString(
                properties.get(LEADER_ELECTION_REPOSITORY_DESCRIPTOR_NAME_KEY),
                null);
        logger.debug("configure: leaderElectionRepositoryDescriptor='{}'",
                this.leaderElectionRepositoryDescriptor);

        this.invertRepositoryDescriptor = PropertiesUtil.toBoolean(
                properties.get(INVERT_REPOSITORY_DESCRIPTOR_NAME_KEY),
                false /* default: false*/);
        logger.debug("configure: invertRepositoryDescriptor='{}'",
                this.invertRepositoryDescriptor);

        autoStopLocalLoopEnabled = PropertiesUtil.toBoolean(properties.get(AUTO_STOP_LOCAL_LOOP_ENABLED), false);
        gzipConnectorRequestsEnabled = PropertiesUtil.toBoolean(properties.get(GZIP_CONNECTOR_REQUESTS_ENABLED), false);

        hmacEnabled = PropertiesUtil.toBoolean(properties.get(HMAC_ENABLED), true);
        encryptionEnabled = PropertiesUtil.toBoolean(properties.get(ENCRYPTION_ENABLED), false);
        sharedKey = PropertiesUtil.toString(properties.get(SHARED_KEY), null);
        keyInterval = PropertiesUtil.toLong(SHARED_KEY_INTERVAL, DEFAULT_SHARED_KEY_INTERVAL);

        backoffStandbyFactor = PropertiesUtil.toInteger(properties.get(BACKOFF_STANDBY_FACTOR),
                DEFAULT_BACKOFF_STANDBY_FACTOR);
        backoffStableFactor = PropertiesUtil.toInteger(properties.get(BACKOFF_STABLE_FACTOR),
                DEFAULT_BACKOFF_STABLE_FACTOR);

        useSyncTokenService = PropertiesUtil.toBoolean(properties.get(USE_SYNC_TOKEN_SERVICE_ENABLED), true);
    }

    /**
     * Returns the timeout (in seconds) after which an instance or voting is considered invalid/timed out
     * @return the timeout (in seconds) after which an instance or voting is considered invalid/timed out
     */
    public long getHeartbeatTimeout() {
        return heartbeatTimeout;
    }

    /**
     * Returns the timeout (in milliseconds) after which an instance or voting is considered invalid/timed out
     * @return the timeout (in milliseconds) after which an instance or voting is considered invalid/timed out
     */
    public long getHeartbeatTimeoutMillis() {
        return getHeartbeatTimeout() * 1000;
    }

    /**
     * Returns the socket connect() timeout used by the topology connector, 0 disables the timeout
     * @return the socket connect() timeout used by the topology connector, 0 disables the timeout
     */
    public int getSocketConnectTimeout() {
        return connectionTimeout;
    }

    /**
     * Returns the socket read timeout (SO_TIMEOUT) used by the topology connector, 0 disables the timeout
     * @return the socket read timeout (SO_TIMEOUT) used by the topology connector, 0 disables the timeout
     */
    public int getSoTimeout() {
        return soTimeout;
    }

    /**
     * Returns the interval (in seconds) in which heartbeats are sent
     * @return the interval (in seconds) in which heartbeats are sent
     */
    public long getHeartbeatInterval() {
        return heartbeatInterval;
    }

    /**
     * Returns the minimum time (in seconds) between sending TOPOLOGY_CHANGING/_CHANGED events - to avoid flooding
     * @return the minimum time (in seconds) between sending TOPOLOGY_CHANGING/_CHANGED events - to avoid flooding
     */
    public int getMinEventDelay() {
        return minEventDelay;
    }

    /**
     * Returns the URLs to which to open a topology connector - or null/empty if no topology connector
     * is configured (default is null)
     * @return the URLs to which to open a topology connector - or null/empty if no topology connector
     * is configured
     */
    public URL[] getTopologyConnectorURLs() {
        return topologyConnectorUrls;
    }

    /**
     * Returns a comma separated list of hostnames and/or ip addresses which are allowed as
     * remote hosts to open connections to the topology connector servlet
     * @return a comma separated list of hostnames and/or ip addresses which are allowed as
     * remote hosts to open connections to the topology connector servlet
     */
    public String[] getTopologyConnectorWhitelist() {
        return topologyConnectorWhitelist;
    }

    public String getDiscoveryResourcePath() {
        return discoveryResourcePath;
    }

    /**
     * Returns the resource path where cluster instance informations are stored.
     * @return the resource path where cluster instance informations are stored
     */
    public String getClusterInstancesPath() {
        return getDiscoveryResourcePath() + CLUSTERINSTANCES_RESOURCE;
    }

    /**
     * Returns the resource path where the established view is stored.
     * @return the resource path where the established view is stored
     */
    public String getEstablishedViewPath() {
        return getDiscoveryResourcePath() + ESTABLISHED_VIEW_RESOURCE;
    }

    /**
     * Returns the resource path where ongoing votings are stored.
     * @return the resource path where ongoing votings are stored
     */
    public String getOngoingVotingsPath() {
        return getDiscoveryResourcePath() + ONGOING_VOTING_RESOURCE;
    }

    /**
     * Returns the resource path where the previous view is stored.
     * @return the resource path where the previous view is stored
     */
    public String getPreviousViewPath() {
        return getDiscoveryResourcePath() + PREVIOUS_VIEW_RESOURCE;
    }

    /**
     * Returns the repository descriptor key which is to be included in the
     * cluster leader election - or null.
     *

     * When set, the value (treated as a boolean) of the repository descriptor
     * is prepended to the leader election id.
     * @return the repository descriptor key which is to be included in the
     * cluster leader election - or null
     */
    public String getLeaderElectionRepositoryDescriptor() {
        return leaderElectionRepositoryDescriptor;
    }

    /**
     * Returns true when the value of the repository descriptor identified
     * via the property 'leaderElectionRepositoryDescriptor' should be
     * inverted - only applies when 'leaderElectionRepositoryDescriptor'
     * is configured of course.
     * @return true when property resulting from 'leaderElectionRepositoryDescriptor'
     * should be inverted, false if it should remain unchanged.
     */
    public boolean shouldInvertRepositoryDescriptor() {
        return invertRepositoryDescriptor;
    }

    /**
     * @return true if hmac is enabled.
     */
    public boolean isHmacEnabled() {
        return hmacEnabled;
    }

    /**
     * @return the shared key
     */
    public String getSharedKey() {
        return sharedKey;
    }

    /**
     * @return the interval of the shared key for hmac.
     */
    public long getKeyInterval() {
        return keyInterval;
    }

    /**
     * @return true if encryption is enabled.
     */
    public boolean isEncryptionEnabled() {
        return encryptionEnabled;
    }

    /**
     * @return true if requests on the topology connector should be gzipped
     * (which only works if the server accepts that.. ie discovery.impl 1.0.4+)
     */
    public boolean isGzipConnectorRequestsEnabled() {
        return gzipConnectorRequestsEnabled;
    }

    /**
     * @return true if the auto-stopping of local-loop topology connectors is enabled.
     */
    public boolean isAutoStopLocalLoopEnabled() {
        return autoStopLocalLoopEnabled;
    }

    /**
     * Returns the backoff factor to be used for standby (loop) connectors
     * @return the backoff factor to be used for standby (loop) connectors
     */
    public int getBackoffStandbyFactor() {
        return backoffStandbyFactor;
    }

    /**
     * Returns the (maximum) backoff factor to be used for stable connectors
     * @return the (maximum) backoff factor to be used for stable connectors
     */
    public int getBackoffStableFactor() {
        return backoffStableFactor;
    }

    /**
     * Returns the backoff interval for standby (loop) connectors in seconds
     * @return the backoff interval for standby (loop) connectors in seconds
     */
    public long getBackoffStandbyInterval() {
        final int factor = getBackoffStandbyFactor();
        if (factor<=1) {
            return -1;
        } else {
            return factor * getHeartbeatInterval();
        }
    }

    @Override
    public long getConnectorPingInterval() {
        return getHeartbeatInterval();
    }

    @Override
    public long getConnectorPingTimeout() {
        return getHeartbeatTimeout();
    }

    @Override
    public String getSyncTokenPath() {
        return getDiscoveryResourcePath() + SYNC_TOKEN_RESOURCE;
    }

    @Override
    public String getIdMapPath() {
        return getDiscoveryResourcePath() + ID_MAP_RESOURCE;
    }

    @Override
    public long getClusterSyncServiceTimeoutMillis() {
        return -1;
    }

    @Override
    public long getClusterSyncServiceIntervalMillis() {
        return 1000;
    }

    public boolean useSyncTokenService() {
        return useSyncTokenService;
    }

}


text:
package org.lancegatlin

object Try3a {
  case class Person(id: Int, name: String, age: Int)

  trait Schema[C] {
    class Field[A](val unapply: C => A) {
      def name: String = {
        // org.lancegatlin.Try1$PersonSchema$id$
        val name = getClass.getName
        // Try1$PersonSchema$id
        val simpleName = name.substring(name.lastIndexOf('.') + 1).dropRight(1)
        // id
        simpleName.substring(simpleName.lastIndexOf('$') + 1)
      }
        // Note: bug in this call for objects
        //getClass.getSimpleName

      override def toString = s"Field($name)"
    }
    def fields: Seq[Field[_]]
  }

  implicit object PersonSchema extends Schema[Person] {
    object id extends Field(_.id)
    object name extends Field(_.name)
    object age extends Field(_.age)
    val fields = Seq(id,name,age)
  }

  sealed trait Ast[C,A]
  case class Equals[C,A](field: Schema[C]#Field[A], ast: Ast[C,A]) extends Ast[C,A]
  case class LessThan[C,A](field: Schema[C]#Field[A], ast: Ast[C,A]) extends Ast[C,A]
  case class Value[C,A](value: A) extends Ast[C,A]
  case class And[C,A,B](ast1: Ast[C,A],ast2:Ast[C,B]) extends Ast[C,(A,B)]

  implicit class PimpMyField[C,A](val self: Schema[C]#Field[A]) extends AnyVal {
    def ===(value: A) = Equals(self,Value[C,A](value))
    def <(value: A) = LessThan(self,Value[C,A](value))
  }

  implicit class PimpMyAst[C,A](val self: Ast[C,A]) extends AnyVal {
    def and[B](other: Ast[C,B]) = And(self, other)
  }

  val ast =
  {
    import PersonSchema._
    id === 1 and name === "asdf" and age < 30
  }

  trait ToSql[A] {
    def apply(a: A) : String
  }

  implicit object toSql_Int extends ToSql[Int] {
    override def apply(a: Int): String = a.toString
  }
  implicit object toSql_String extends ToSql[String] {
    override def apply(a: String): String = s""""$a""""
  }

  trait ToSql_Tuple2[A,B] extends ToSql[(A,B)] {
    def aToSql : ToSql[A]
    def bToSql : ToSql[B]
  }

  implicit def toSql_Tuple2[A,B](implicit
    _aToSql:ToSql[A],
    _bToSql:ToSql[B]
  ) = new ToSql_Tuple2[A,B] {
    implicit def aToSql = _aToSql
    implicit def bToSql = _bToSql
    override def apply(a: (A, B)): String = ???
  }

  def astToSql[C,A](ast: Ast[C,A])(implicit outerToSql:ToSql[A]) : String = {
    val builder = new StringBuilder(256)
    def loop2[CC,AA,BB](ast: Ast[CC,(AA,BB)])(implicit toSql:ToSql_Tuple2[AA,BB]) : Unit = {
      ast match {
        case And(ast1,ast2) =>
          loop(ast1)(toSql.aToSql)
          builder.append(" AND ")
          loop(ast2)(toSql.bToSql)
        case _ => ???
      }
    }

    def loop[CC,AA](ast: Ast[CC,AA])(implicit toSql:ToSql[AA]) : Unit = {
      ast match {
        case e@Equals(field,ast1) =>
          builder
            .append(field.name)
            .append(" = ")
          loop(ast1)
        case LessThan(field,ast1) =>
          builder
            .append(field.name)
            .append(" < ")
          loop(ast1)
        case Value(value) =>
          builder.append(toSql(value))
        case a@And(ast1,ast2) =>
          // The type params on And get lost here - end up with And[Any,Any,Any]
          // They shouldn't get lost since for And, AA is (A,B) so it should be
          // possible for the compiler to pass on that info here
          loop2(a)(toSql.asInstanceOf[ToSql_Tuple2[Any,Any]])
      }
    }
    loop(ast)
    builder.result()
  }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.contrib import messages
from django.contrib.auth import login as auth_login, logout as auth_logout, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.http import is_safe_url
from django.views.generic import View

from secrets.forms import UserKeyForm
from secrets.models import SessionKey, UserKey
from utilities.forms import ConfirmationForm
from .forms import LoginForm, PasswordChangeForm, TokenForm
from .models import Token

#
# Login/logout
#

class LoginView(View):
    template_name = 'login.html'

    def get(self, request):
        form = LoginForm(request)

        return render(request, self.template_name, {
            'form': form,
        })

    def post(self, request):
        form = LoginForm(request, data=request.POST)
        if form.is_valid():

            # Determine where to direct user after successful login
            redirect_to = request.POST.get('next', '')
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = reverse('home')

            # Authenticate user
            auth_login(request, form.get_user())
            messages.info(request, "Logged in as {}.".format(request.user))

            return HttpResponseRedirect(redirect_to)

        return render(request, self.template_name, {
            'form': form,
        })

class LogoutView(View):

    def get(self, request):
        auth_logout(request)
        messages.info(request, "You have logged out.")

        return HttpResponseRedirect(reverse('home'))

#
# User profiles
#

@method_decorator(login_required, name='dispatch')
class ProfileView(View):
    template_name = 'users/profile.html'

    def get(self, request):

        return render(request, self.template_name, {
            'active_tab': 'profile',
        })

@method_decorator(login_required, name='dispatch')
class ChangePasswordView(View):
    template_name = 'users/change_password.html'

    def get(self, request):
        form = PasswordChangeForm(user=request.user)

        return render(request, self.template_name, {
            'form': form,
            'active_tab': 'change_password',
        })

    def post(self, request):
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            messages.success(request, "Your password has been changed successfully.")
            return redirect('user:profile')

        return render(request, self.template_name, {
            'form': form,
            'active_tab': 'change_password',
        })

@method_decorator(login_required, name='dispatch')
class UserKeyView(View):
    template_name = 'users/userkey.html'

    def get(self, request):
        try:
            userkey = UserKey.objects.get(user=request.user)
        except UserKey.DoesNotExist:
            userkey = None

        return render(request, self.template_name, {
            'userkey': userkey,
            'active_tab': 'userkey',
        })

class UserKeyEditView(View):
    template_name = 'users/userkey_edit.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        try:
            self.userkey = UserKey.objects.get(user=request.user)
        except UserKey.DoesNotExist:
            self.userkey = UserKey(user=request.user)

        return super(UserKeyEditView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        form = UserKeyForm(instance=self.userkey)

        return render(request, self.template_name, {
            'userkey': self.userkey,
            'form': form,
            'active_tab': 'userkey',
        })

    def post(self, request):
        form = UserKeyForm(data=request.POST, instance=self.userkey)
        if form.is_valid():
            uk = form.save(commit=False)
            uk.user = request.user
            uk.save()
            messages.success(request, "Your user key has been saved.")
            return redirect('user:userkey')

        return render(request, self.template_name, {
            'userkey': self.userkey,
            'form': form,
            'active_tab': 'userkey',
        })

@method_decorator(login_required, name='dispatch')
class SessionKeyDeleteView(LoginRequiredMixin, View):

    def get(self, request):

        sessionkey = get_object_or_404(SessionKey, userkey__user=request.user)
        form = ConfirmationForm()

        return render(request, 'users/sessionkey_delete.html', {
            'obj_type': sessionkey._meta.verbose_name,
            'form': form,
            'return_url': reverse('user:userkey'),
        })

    def post(self, request):

        sessionkey = get_object_or_404(SessionKey, userkey__user=request.user)
        form = ConfirmationForm(request.POST)
        if form.is_valid():

            # Delete session key
            sessionkey.delete()
            messages.success(request, "Session key deleted")

            # Delete cookie
            response = redirect('user:userkey')
            response.delete_cookie('session_key')

            return response

        return render(request, 'users/sessionkey_delete.html', {
            'obj_type': sessionkey._meta.verbose_name,
            'form': form,
            'return_url': reverse('user:userkey'),
        })

@method_decorator(login_required, name='dispatch')
class RecentActivityView(View):
    template_name = 'users/recent_activity.html'

    def get(self, request):

        return render(request, self.template_name, {
            'recent_activity': request.user.actions.all()[:50],
            'active_tab': 'recent_activity',
        })

#
# API tokens
#

class TokenListView(LoginRequiredMixin, View):

    def get(self, request):

        tokens = Token.objects.filter(user=request.user)

        return render(request, 'users/api_tokens.html', {
            'tokens': tokens,
            'active_tab': 'api_tokens',
        })

class TokenEditView(LoginRequiredMixin, View):

    def get(self, request, pk=None):

        if pk is not None:
            token = get_object_or_404(Token.objects.filter(user=request.user), pk=pk)
        else:
            token = Token(user=request.user)

        form = TokenForm(instance=token)

        return render(request, 'utilities/obj_edit.html', {
            'obj': token,
            'obj_type': token._meta.verbose_name,
            'form': form,
            'return_url': reverse('user:token_list'),
        })

    def post(self, request, pk=None):

        if pk is not None:
            token = get_object_or_404(Token.objects.filter(user=request.user), pk=pk)
            form = TokenForm(request.POST, instance=token)
        else:
            token = Token()
            form = TokenForm(request.POST)

        if form.is_valid():
            token = form.save(commit=False)
            token.user = request.user
            token.save()

            msg = "Modified token {}".format(token) if pk else "Created token {}".format(token)
            messages.success(request, msg)

            if '_addanother' in request.POST:
                return redirect(request.path)
            else:
                return redirect('user:token_list')

        return render(request, 'utilities/obj_edit.html', {
            'obj': token,
            'obj_type': token._meta.verbose_name,
            'form': form,
            'return_url': reverse('user:token_list'),
        })

class TokenDeleteView(LoginRequiredMixin, View):

    def get(self, request, pk):

        token = get_object_or_404(Token.objects.filter(user=request.user), pk=pk)
        initial_data = {
            'return_url': reverse('user:token_list'),
        }
        form = ConfirmationForm(initial=initial_data)

        return render(request, 'utilities/obj_delete.html', {
            'obj': token,
            'obj_type': token._meta.verbose_name,
            'form': form,
            'return_url': reverse('user:token_list'),
        })

    def post(self, request, pk):

        token = get_object_or_404(Token.objects.filter(user=request.user), pk=pk)
        form = ConfirmationForm(request.POST)
        if form.is_valid():
            token.delete()
            messages.success(request, "Token deleted")
            return redirect('user:token_list')

        return render(request, 'utilities/obj_delete.html', {
            'obj': token,
            'obj_type': token._meta.verbose_name,
            'form': form,
            'return_url': reverse('user:token_list'),
        })


text:
/**
 * CSC232 Data Structures with C++
 * Missouri State University, Fall 2017
 *
 * @file Main.cpp
 * @authors Jim Daehn <jdaehn@missouristate.edu>
 *          Your Name <yname@missouristate.edu>
 *          Partner Name <pname@missouristate.edu>
 * @brief   Entry point for this application. This is nothing more than a playground.
 */

#include <cstdlib>
#include <iostream>

int main(int argc, char **argv) {
    std::cout << "Hello, Main" << std::endl;

    return EXIT_SUCCESS;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

    <servlet>
        <servlet-name>CarbonDataSourceLookupServlet</servlet-name>
        <servlet-class>org.wso2.appserver.samples.jndi.CarbonDataSourceLookupServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CarbonDataSourceLookupServlet</servlet-name>
        <url-pattern>/jndi/carbon-datasource-lookup</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>TomcatDataSourceLookupServlet</servlet-name>
        <servlet-class>org.wso2.appserver.samples.jndi.TomcatDataSourceLookupServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TomcatDataSourceLookupServlet</servlet-name>
        <url-pattern>/jndi/tomcat-resource-lookup</url-pattern>
    </servlet-mapping>

    <!--<servlet>-->
        <!--<servlet-name>CarbonContextServlet</servlet-name>-->
        <!--<servlet-class>org.wso2.carbon.CarbonContext</servlet-class>-->
    <!--</servlet>-->
    <!--<servlet-mapping>-->
        <!--<servlet-name>CarbonContextServlet</servlet-name>-->
        <!--<url-pattern>/carbon/CarbonContext</url-pattern>-->
    <!--</servlet-mapping>-->

    <!--<servlet>-->
        <!--<servlet-name>TomcatContextServlet</servlet-name>-->
        <!--<servlet-class>org.wso2.tomcat.context.TomcatContext</servlet-class>-->
    <!--</servlet>-->
    <!--<servlet-mapping>-->
        <!--<servlet-name>TomcatContextServlet</servlet-name>-->
        <!--<url-pattern>/tomcat/tomcatcontext</url-pattern>-->
    <!--</servlet-mapping>-->

    <!--<servlet>-->
        <!--<servlet-name>WebAppContextServlet</servlet-name>-->
        <!--<servlet-class>org.wso2.webapp.WebAppContext</servlet-class>-->
    <!--</servlet>-->
    <!--<servlet-mapping>-->
        <!--<servlet-name>WebAppContextServlet</servlet-name>-->
        <!--<url-pattern>/webapp/webappContext</url-pattern>-->
    <!--</servlet-mapping>-->

    <!--<servlet>-->
        <!--<servlet-name>CatalinaTomcatContextServlet</servlet-name>-->
        <!--<servlet-class>org.wso2.tomcat.catalinatomcatcontext.CatalinaTomcatContextLink</servlet-class>-->
    <!--</servlet>-->
    <!--<servlet-mapping>-->
        <!--<servlet-name>CatalinaTomcatContextServlet</servlet-name>-->
        <!--<url-pattern>/tomcat/CatalinaTomcatContext</url-pattern>-->
    <!--</servlet-mapping>-->

    <!--<servlet>-->
        <!--<servlet-name>TestCatalinaWebAppLinkContextJNDI</servlet-name>-->
        <!--<servlet-class>org.wso2.tomcat.catalinawebappcontext.CatalinaWebAppLink</servlet-class>-->
    <!--</servlet>-->
    <!--<servlet-mapping>-->
        <!--<servlet-name>TestCatalinaWebAppLinkContextJNDI</servlet-name>-->
        <!--<url-pattern>/webapp/CatalinaWebAppTestContext</url-pattern>-->
    <!--</servlet-mapping>-->

</web-app>


text:
var onRun = function(context) {
	var doc = context.document;
	var dt = 'bond';

	@import '../controllers/genTable.js';
};


text:
package javax.swing;

/** DesktopManager objects are owned by a JDesktopPane object. They are responsible
  * for implementing L&F specific behaviors for the JDesktopPane. JInternalFrame
  * implementations should delegate specific behaviors to the DesktopManager. For
  * instance, if a JInternalFrame was asked to iconify, it should try:
  *

  *    getDesktopPane().getDesktopManager().iconifyFrame(frame);
  *

  * This delegation allows each L&F to provide custom behaviors for desktop-specific
  * actions. (For example, how and where the internal frame's icon would appear.)
  *
This class provides a policy for the various JInternalFrame methods, it is not
  * meant to be called directly rather the various JInternalFrame methods will call
  * into the DesktopManager.

  *
  * @see JDesktopPane
  * @see JInternalFrame
  * @see JInternalFrame.JDesktopIcon
  *
  * @author David Kloba
  */
public interface DesktopManager
{
    /** If possible, display this frame in an appropriate location.
      * Normally, this is not called, as the creator of the JInternalFrame
      * will add the frame to the appropriate parent.
      */
    void openFrame(JInternalFrame f);

    /** Generally, this call should remove the frame from it's parent. */
    void closeFrame(JInternalFrame f);

    /** Generally, the frame should be resized to match it's parents bounds. */
    void maximizeFrame(JInternalFrame f);
    /** Generally, this indicates that the frame should be restored to it's
      * size and position prior to a maximizeFrame() call.
      */
    void minimizeFrame(JInternalFrame f);
    /** Generally, remove this frame from it's parent and add an iconic representation. */
    void iconifyFrame(JInternalFrame f);
    /** Generally, remove any iconic representation that is present and restore the
      * frame to it's original size and location.
      */
    void deiconifyFrame(JInternalFrame f);

    /**
     * Generally, indicate that this frame has focus. This is usually called after
     * the JInternalFrame's IS_SELECTED_PROPERTY has been set to true.
     */
    void activateFrame(JInternalFrame f);

    /**
     * Generally, indicate that this frame has lost focus. This is usually called
     * after the JInternalFrame's IS_SELECTED_PROPERTY has been set to false.
     */
    void deactivateFrame(JInternalFrame f);

    /** This method is normally called when the user has indicated that
      * they will begin dragging a component around. This method should be called
      * prior to any dragFrame() calls to allow the DesktopManager to prepare any
      * necessary state. Normally f will be a JInternalFrame.
      */
    void beginDraggingFrame(JComponent f);

    /** The user has moved the frame. Calls to this method will be preceded by calls
      * to beginDraggingFrame().
      *  Normally f will be a JInternalFrame.
      */
    void dragFrame(JComponent f, int newX, int newY);
    /** This method signals the end of the dragging session. Any state maintained by
      * the DesktopManager can be removed here.  Normally f will be a JInternalFrame.
      */
    void endDraggingFrame(JComponent f);

    /** This methods is normally called when the user has indicated that
      * they will begin resizing the frame. This method should be called
      * prior to any resizeFrame() calls to allow the DesktopManager to prepare any
      * necessary state.  Normally f will be a JInternalFrame.
      */
    void beginResizingFrame(JComponent f, int direction);
    /** The user has resized the component. Calls to this method will be preceded by calls
      * to beginResizingFrame().
      *  Normally f will be a JInternalFrame.
      */
    void resizeFrame(JComponent f, int newX, int newY, int newWidth, int newHeight);
    /** This method signals the end of the resize session. Any state maintained by
      * the DesktopManager can be removed here.  Normally f will be a JInternalFrame.
      */
    void endResizingFrame(JComponent f);

    /** This is a primitive reshape method.*/
    void setBoundsForFrame(JComponent f, int newX, int newY, int newWidth, int newHeight);
}


text:
package com.metamx.tranquility.javatests;

import backtype.storm.task.IMetricsContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.metamx.common.Granularity;
import com.metamx.tranquility.beam.Beam;
import com.metamx.tranquility.beam.ClusteredBeamTuning;
import com.metamx.tranquility.druid.DruidBeams;
import com.metamx.tranquility.druid.DruidLocation;
import com.metamx.tranquility.druid.DruidRollup;
import com.metamx.tranquility.storm.BeamBolt;
import com.metamx.tranquility.storm.BeamFactory;
import com.metamx.tranquility.typeclass.JavaObjectWriter;
import com.metamx.tranquility.typeclass.Timestamper;
import com.twitter.finagle.Service;
import io.druid.granularity.QueryGranularity;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.CountAggregatorFactory;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.test.TestingCluster;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.junit.Assert;
import org.junit.Test;

import javax.ws.rs.core.MediaType;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class StormJavaApiTest
{
  private static final List<String> dimensions = ImmutableList.of("column");
  private static final List<AggregatorFactory> aggregators = ImmutableList.<AggregatorFactory>of(
      new CountAggregatorFactory(
          "cnt"
      )
  );

  public static class MyBeamFactory implements BeamFactory<Map<String, Object>>
  {
    @Override
    public Beam<Map<String, Object>> makeBeam(Map<?, ?> conf, IMetricsContext metrics)
    {
      try (
          final TestingCluster cluster = new TestingCluster(1);
          final CuratorFramework curator = CuratorFrameworkFactory.builder()
                                                                  .connectString(cluster.getConnectString())
                                                                  .retryPolicy(
                                                                      new RetryOneTime(1000)
                                                                  )
                                                                  .build()
      ) {
        cluster.start();
        curator.start();

        final String dataSource = "hey";

        final DruidBeams.Builder<Map<String, Object>> builder = DruidBeams
            .builder(
                new Timestamper<Map<String, Object>>()
                {
                  @Override
                  public DateTime timestamp(Map<String, Object> theMap)
                  {
                    return new DateTime(theMap.get("timestamp"));
                  }
                }
            )
            .curator(curator)
            .discoveryPath("/test/discovery")
            .location(
                DruidLocation.create(
                    "druid:local:indexer",
                    "druid:local:firehose:%s",
                    dataSource
                )
            )
            .rollup(DruidRollup.create(dimensions, aggregators, QueryGranularity.MINUTE))
            .tuning(
                ClusteredBeamTuning.builder()
                                   .segmentGranularity(Granularity.HOUR)
                                   .windowPeriod(new Period("PT10M"))
                                   .build()
            )
            .objectWriter(
                new JavaObjectWriter<Map<String, Object>>()
                {
                  final ObjectMapper objectMapper = new ObjectMapper();

                  @Override
                  public byte[] asBytes(Map<String, Object> obj)
                  {
                    try {
                      return objectMapper.writeValueAsBytes(obj);
                    }
                    catch (JsonProcessingException e) {
                      throw Throwables.propagate(e);
                    }
                  }

                  @Override
                  public byte[] batchAsBytes(Iterator<Map<String, Object>> objects)
                  {
                    try {
                      return objectMapper.writeValueAsBytes(ImmutableList.of(objects));
                    }
                    catch (JsonProcessingException e) {
                      throw Throwables.propagate(e);
                    }
                  }

                  @Override
                  public String contentType()
                  {
                    return MediaType.APPLICATION_JSON;
                  }
                }
            );

        final Service<List<Map<String, Object>>, Integer> service = builder.buildJavaService();
        Assert.assertNotNull(service);
        final Beam<Map<String, Object>> beam = builder.buildBeam();
        Assert.assertNotNull(beam);
        return beam;
      }
      catch (Exception e) {
        throw Throwables.propagate(e);
      }
    }
  }

  @Test
  public void testDruidBeamBoltConstruction() throws Exception
  {
    final BeamBolt<Map<String, Object>> beamBolt = new BeamBolt<>(new MyBeamFactory());

    // Ensure serializability
    final ObjectOutputStream objectOutputStream = new ObjectOutputStream(new ByteArrayOutputStream());
    objectOutputStream.writeObject(beamBolt);
    Assert.assertTrue(true);
  }
}


text:
package io.anand.play;

import java.io.IOException;
import java.util.Arrays;

public class WinterSummer {
    static public int getSummerStart(int[] T) {
        // write your code in Java SE 8

        // Given Winter always is colder than summer and they are preceeding values
        int left, marker, right;

        left = 0;
        right = T.length - 1;

        while (left <= right) {
//        System.out.println("left: " + T[left] + ", right: " + T[right]);
            // Advance to summer till we see a temparature rising
            if (T[left] <= T[right])
                left++;
            // Advance to Winter till we see a temparature dropping
            if (T[right] > T[left])
                right--;
            // If we see a temperature from right dropping than one of left, we have crossed over.
            if (T[right] < T[left])
                break;
        }
        return right + 1;
    }

    public static void main(String[] args) throws IOException {
        int num [] = {5, 1, 0, -5, 2, 3, 8, 6};
        int result = getSummerStart(num);

        System.out.println("Temperatures: " + Arrays.toString(num) + ", Summer starts at: " + result);
    }
}


text:
/**
 * Generated with Acceleo
 */
package org.wso2.developerstudio.eclipse.gmf.esb.parts.forms;

// Start of user code for imports
import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.ecore.EObject;

import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;

import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;

import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart;

import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;

import org.eclipse.emf.eef.runtime.part.impl.SectionPropertiesEditingPart;

import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;

import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;

import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable;

import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable.ReferencesTableListener;

import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableContentProvider;
import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings;

import org.eclipse.jface.viewers.ViewerFilter;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;

import org.eclipse.swt.widgets.Composite;

import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;

import org.wso2.developerstudio.eclipse.gmf.esb.parts.DefaultEndPointOutputConnectorPropertiesEditionPart;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository;

import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages;

// End of user code

/**
 *
 *
 */
public class DefaultEndPointOutputConnectorPropertiesEditionPartForm extends SectionPropertiesEditingPart implements IFormPropertiesEditionPart, DefaultEndPointOutputConnectorPropertiesEditionPart {

	protected ReferencesTable commentMediators;
	protected List<ViewerFilter> commentMediatorsBusinessFilters = new ArrayList<ViewerFilter>();
	protected List<ViewerFilter> commentMediatorsFilters = new ArrayList<ViewerFilter>();

	/**
	 * For {@link ISection} use only.
	 */
	public DefaultEndPointOutputConnectorPropertiesEditionPartForm() { super(); }

	/**
	 * Default constructor
	 * @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
	 *
	 */
	public DefaultEndPointOutputConnectorPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) {
		super(editionComponent);
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
	 *  createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit)
	 *
	 */
	public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) {
		ScrolledForm scrolledForm = widgetFactory.createScrolledForm(parent);
		Form form = scrolledForm.getForm();
		view = form.getBody();
		GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		view.setLayout(layout);
		createControls(widgetFactory, view);
		return scrolledForm;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
	 *  createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite)
	 *
	 */
	public void createControls(final FormToolkit widgetFactory, Composite view) {
		CompositionSequence defaultEndPointOutputConnectorStep = new BindingCompositionSequence(propertiesEditionComponent);
		defaultEndPointOutputConnectorStep
			.addStep(EsbViewsRepository.DefaultEndPointOutputConnector.Properties.class)
			.addStep(EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators);

		composer = new PartComposer(defaultEndPointOutputConnectorStep) {

			@Override
			public Composite addToPart(Composite parent, Object key) {
				if (key == EsbViewsRepository.DefaultEndPointOutputConnector.Properties.class) {
					return createPropertiesGroup(widgetFactory, parent);
				}
				if (key == EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators) {
					return createCommentMediatorsTableComposition(widgetFactory, parent);
				}
				return parent;
			}
		};
		composer.compose(view);
	}
	/**
	 *
	 */
	protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) {
		Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
		propertiesSection.setText(EsbMessages.DefaultEndPointOutputConnectorPropertiesEditionPart_PropertiesGroupLabel);
		GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL);
		propertiesSectionData.horizontalSpan = 3;
		propertiesSection.setLayoutData(propertiesSectionData);
		Composite propertiesGroup = widgetFactory.createComposite(propertiesSection);
		GridLayout propertiesGroupLayout = new GridLayout();
		propertiesGroupLayout.numColumns = 3;
		propertiesGroup.setLayout(propertiesGroupLayout);
		propertiesSection.setClient(propertiesGroup);
		return propertiesGroup;
	}

	/**
	 * @param container
	 *
	 */
	protected Composite createCommentMediatorsTableComposition(FormToolkit widgetFactory, Composite parent) {
		this.commentMediators = new ReferencesTable(getDescription(EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators, EsbMessages.DefaultEndPointOutputConnectorPropertiesEditionPart_CommentMediatorsLabel), new ReferencesTableListener() {
			public void handleAdd() {
				propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(DefaultEndPointOutputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.ADD, null, null));
				commentMediators.refresh();
			}
			public void handleEdit(EObject element) {
				propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(DefaultEndPointOutputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.EDIT, null, element));
				commentMediators.refresh();
			}
			public void handleMove(EObject element, int oldIndex, int newIndex) {
				propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(DefaultEndPointOutputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.MOVE, element, newIndex));
				commentMediators.refresh();
			}
			public void handleRemove(EObject element) {
				propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(DefaultEndPointOutputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.REMOVE, null, element));
				commentMediators.refresh();
			}
			public void navigateTo(EObject element) { }
		});
		for (ViewerFilter filter : this.commentMediatorsFilters) {
			this.commentMediators.addFilter(filter);
		}
		this.commentMediators.setHelpText(propertiesEditionComponent.getHelpContent(EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators, EsbViewsRepository.FORM_KIND));
		this.commentMediators.createControls(parent, widgetFactory);
		this.commentMediators.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent e) {
				if (e.item != null && e.item.getData() instanceof EObject) {
					propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(DefaultEndPointOutputConnectorPropertiesEditionPartForm.this, EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators, PropertiesEditionEvent.CHANGE, PropertiesEditionEvent.SELECTION_CHANGED, null, e.item.getData()));
				}
			}

		});
		GridData commentMediatorsData = new GridData(GridData.FILL_HORIZONTAL);
		commentMediatorsData.horizontalSpan = 3;
		this.commentMediators.setLayoutData(commentMediatorsData);
		this.commentMediators.setLowerBound(0);
		this.commentMediators.setUpperBound(-1);
		commentMediators.setID(EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators);
		commentMediators.setEEFType("eef::AdvancedTableComposition"); //$NON-NLS-1$
		// Start of user code for createCommentMediatorsTableComposition

		// End of user code
		return parent;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
	 *
	 */
	public void firePropertiesChanged(IPropertiesEditionEvent event) {
		// Start of user code for tab synchronization

		// End of user code
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.DefaultEndPointOutputConnectorPropertiesEditionPart#initCommentMediators(EObject current, EReference containingFeature, EReference feature)
	 */
	public void initCommentMediators(ReferencesTableSettings settings) {
		if (current.eResource() != null && current.eResource().getResourceSet() != null)
			this.resourceSet = current.eResource().getResourceSet();
		ReferencesTableContentProvider contentProvider = new ReferencesTableContentProvider();
		commentMediators.setContentProvider(contentProvider);
		commentMediators.setInput(settings);
		boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.DefaultEndPointOutputConnector.Properties.commentMediators);
		if (eefElementEditorReadOnlyState && commentMediators.isEnabled()) {
			commentMediators.setEnabled(false);
			commentMediators.setToolTipText(EsbMessages.DefaultEndPointOutputConnector_ReadOnly);
		} else if (!eefElementEditorReadOnlyState && !commentMediators.isEnabled()) {
			commentMediators.setEnabled(true);
		}

	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.DefaultEndPointOutputConnectorPropertiesEditionPart#updateCommentMediators()
	 *
	 */
	public void updateCommentMediators() {
	commentMediators.refresh();
}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.DefaultEndPointOutputConnectorPropertiesEditionPart#addFilterCommentMediators(ViewerFilter filter)
	 *
	 */
	public void addFilterToCommentMediators(ViewerFilter filter) {
		commentMediatorsFilters.add(filter);
		if (this.commentMediators != null) {
			this.commentMediators.addFilter(filter);
		}
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.DefaultEndPointOutputConnectorPropertiesEditionPart#addBusinessFilterCommentMediators(ViewerFilter filter)
	 *
	 */
	public void addBusinessFilterToCommentMediators(ViewerFilter filter) {
		commentMediatorsBusinessFilters.add(filter);
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.DefaultEndPointOutputConnectorPropertiesEditionPart#isContainedInCommentMediatorsTable(EObject element)
	 *
	 */
	public boolean isContainedInCommentMediatorsTable(EObject element) {
		return ((ReferencesTableSettings)commentMediators.getInput()).contains(element);
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
	 *
	 */
	public String getTitle() {
		return EsbMessages.DefaultEndPointOutputConnector_Part_Title;
	}

	// Start of user code additional methods

	// End of user code

}


text:
<?xml version="1.0"?>
<ruleset name="Jicon ruleset" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">

  <description>
    Jicon PMD ruleset for everything except tests
  </description>

  <!-- exclude tests -->
  <exclude-pattern>.*src/test/java/.*</exclude-pattern>

  <rule ref="rulesets/java/basic.xml"/>
  <rule ref="rulesets/java/strings.xml"/>
  <rule ref="rulesets/java/unusedcode.xml"/>
  <rule ref="rulesets/java/braces.xml"/>
  <rule ref="rulesets/java/imports.xml"/>
  <rule ref="rulesets/java/coupling.xml">
    <exclude name="LawOfDemeter"/>
    <exclude name="LoosePackageCoupling"/>
  </rule>
  <rule ref="rulesets/java/typeresolution.xml">
    <exclude name="UnusedImports"/>
  </rule>
  <rule ref="rulesets/java/strictexception.xml"/>
  <rule ref="rulesets/java/optimizations.xml">
    <exclude name="AvoidInstantiatingObjectsInLoops"/>
  </rule>

  <rule ref="rulesets/java/empty.xml">
    <exclude name="EmptyCatchBlock"/>
  </rule>

  <rule ref="rulesets/java/empty.xml/EmptyCatchBlock" message="Must handle exceptions">
    <priority>2</priority>
  </rule>

  <rule ref="rulesets/java/codesize.xml/ExcessiveMethodLength"/>
  <rule ref="rulesets/java/codesize.xml/ExcessiveParameterList"/>
  <rule ref="rulesets/java/codesize.xml/ExcessiveClassLength"/>
  <rule ref="rulesets/java/codesize.xml/ExcessivePublicCount"/>
  <rule ref="rulesets/java/codesize.xml/TooManyFields"/>

  <rule ref="rulesets/java/codesize.xml/CyclomaticComplexity">
    <properties>
      <property name="reportLevel" value="5"/>
    </properties>
  </rule>

  <rule ref="rulesets/java/design.xml/UseCollectionIsEmpty"/>
  <rule ref="rulesets/java/design.xml/PreserveStackTrace"/>
  <rule ref="rulesets/java/design.xml/GodClass"/>
  <rule ref="rulesets/java/design.xml/UnnecessaryLocalBeforeReturn"/>

</ruleset>


text:
	<title>Phil's WebGl Resume</title>
	<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">

	  <link href="style.css" rel="stylesheet" type="text/css">
	  <link href="menu.css" rel="stylesheet" type="text/css">

	<link rel="icon" href="../Doc3D.jpg"/>

	<canvas id="webGlCanvas" style="border: none;" class="mainView"></canvas>

	    It looks like your browser can't support this.

	    Click here to download a browser which can


text:
from datetime import timedelta
from persistent_message.models import Message, Tag
from django.test import TransactionTestCase, override_settings
from myuw.dao.term import get_comparison_datetime_with_tz
from myuw.dao.persistent_messages import BannerMessage
from myuw.test import (get_request_with_user, get_request_with_date)

def setup_db(req):
    msg = Message()
    msg.content = 'Hello World!'
    msg.begins = (
        get_comparison_datetime_with_tz(req) - timedelta(days=1))
    msg.save()
    return msg

def set_tags(msg, tag_names):
    tags = []
    for tag in tag_names:
        msg.tags.add(Tag.objects.get(name=tag))
    msg.save()
    return msg

class PersistentMessageDAOTest(TransactionTestCase):
    fixtures = ['persistent_messages.json']

    def test_tags(self):
        tags = Tag.objects.all()
        self.assertEqual(len(tags), 15)

    def test_get_message_for_all(self):
        req = get_request_with_user('none')
        bm = BannerMessage(req)
        data = bm.get_message_json()
        self.assertEqual(len(data), 2)
        self.assertEqual(data[0]["start"], "2013-04-08T07:00:01+00:00")
        self.assertEqual(data[1]["start"], "2013-04-15T07:00:01+00:00")

    def test_get_message_no_match(self):
        req = get_request_with_user('seagrad')
        Message.objects.all().delete()
        msg = setup_db(req)
        msg = set_tags(msg, ['bothell'])
        bm = BannerMessage(req)
        self.assertEqual(len(bm.get_message_json()), 0)

    def test_get_message_for_undergraduate(self):
        req = get_request_with_user('javerage')
        bm = BannerMessage(req)
        msg = setup_db(req)
        msg = set_tags(msg, ['seattle', 'undergraduate'])
        json_content = bm._to_json(msg, True)
        self.assertEqual(json_content['content'], 'Hello World!')
        self.assertEqual(json_content['level_name'], 'Info')
        self.assertEqual(json_content['start'], '2013-04-14T00:00:01-07:00')
        self.assertIsNone(json_content['end'])
        self.assertTrue(json_content['seattle'])
        self.assertTrue(json_content['undergraduate'])

        tags = msg.tags.all()
        self.assertTrue(bm._is_stud_campus_matched(tags))
        self.assertTrue(bm._student_affiliation_matched(tags))
        self.assertEqual(len(bm.get_message_json()), 3)

    def test_get_message_for_faculty(self):
        req = get_request_with_user('bill')
        bm = BannerMessage(req)
        msg = setup_db(req)
        msg = set_tags(msg, ['faculty'])
        tags = msg.tags.all()
        self.assertTrue(bm._employee_affiliation_matched(tags))
        self.assertEqual(len(bm.get_message_json()), 3)

        msg = set_tags(msg, ['seattle'])
        tags = msg.tags.all()
        self.assertTrue(bm._is_employee_campus_matched(tags))
        self.assertEqual(len(bm.get_message_json()), 3)

    def test_get_message_for_alumni(self):
        req = get_request_with_user('jalum')
        bm = BannerMessage(req)
        msg = setup_db(req)
        msg = set_tags(msg, ['alumni'])
        tags = msg.tags.all()
        self.assertTrue(bm._campus_neutral(tags))
        self.assertTrue(bm._for_alumni(tags))
        self.assertEqual(len(bm.get_message_json()), 3)

    def test_get_message_for_applicant(self):
        req = get_request_with_user('japplicant')
        bm = BannerMessage(req)
        msg = setup_db(req)
        msg = set_tags(msg, ['applicant'])
        tags = msg.tags.all()
        self.assertTrue(bm._for_applicant(tags))
        self.assertEqual(len(bm.get_message_json()), 3)


text:
<!DOCTYPE html>

	<title>Testing Overview</title>

	<link rel="stylesheet" type="text/css" href="../../../../../../../../resources/sap/ui/core/themes/sap_fiori_3/library.css">

Testing Overview

This is an overview page of various ways to test the generated app during development.

		Choose one of the access points below to launch the app as a standalone application.

index.html - start the app (with real service)

test/mockServer.html - start the app (with local mock data)

test/testsuite.qunit.html - run all the tests

test/unit/unitTests.qunit.html - run all unit tests

test/integration/opaTests.qunit.html - run all integration tests


text:
/**
 * http://notes.jetienne.com/2011/05/18/cancelRequestAnimFrame-for-paul-irish-requestAnimFrame.html
 */
window.requestAnimFrame = (function() {
  return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
    function( /* function */ callback, /* DOMElement */ element) {
      return window.setTimeout(callback, 1000 / 60);
    };
})();

window.cancelRequestAnimFrame = (function() {
  return window.cancelAnimationFrame || window.webkitCancelRequestAnimationFrame ||
    window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame ||
    window.msCancelRequestAnimationFrame || clearTimeout;
})();

//http://snipplr.com/view/13523/
//modified for speed
//http://jsperf.com/getcomputedstyle-vs-style-vs-css/8
if (!window.getComputedStyle) {
  (function() {
    var elem;

    var styleObj = {
      getPropertyValue: function getPropertyValue(prop) {
        if (prop == 'float') {
          prop = 'styleFloat';
        }
        return elem.currentStyle[prop.toUpperCase()] || null;
      }
    };

    window.getComputedStyle = function(el) {
      elem = el;
      return styleObj;
    };
  })();
}

/**
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
 */
if (!String.prototype.trim) {
  var trimRegex = /^\s+|\s+$/g;
  /* jshint -W121 */
  String.prototype.trim = function() {
    return this.replace(trimRegex, '');
  };
}


text:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        >

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<servico xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://servicos.gov.br/v3/schema ../servico.xsd">
    <nome>Emissão de Certidão Pessoa Física (Dívida Ativa da União – DAU)</nome>
    <sigla/>
    <nomes-populares/>
    <descricao>Solicitar emissão de certidão da pessoa física, exceto de contribuições previdenciárias.</descricao>
    <gratuito/>
    <solicitantes/>
    <tempo-total-estimado>
        <descricao/>
    </tempo-total-estimado>
    <etapas>
        <etapa>
            <titulo/>
            <descricao/>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao tipo="web">
                        <descricao>http://www.receita.fazenda.gov.br/Aplicacoes/ATSPO/Certidao/CndConjuntaInter/InformaNICertidao.asp?Tipo=</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/77"/>
    <segmentos-da-sociedade>
        <item>Cidadãos</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Economia e Finanças</item>
    </areas-de-interesse>
    <palavras-chave/>
    <legislacoes/>
</servico>


text:
import Map from 'core-js/es6/map'
import '../jquery.cmf_context_menu'
import 'fancytree/src/jquery.fancytree.js'
import 'fancytree/src/jquery.fancytree.dnd.js'
import 'fancytree/skin-win8/ui.fancytree.css'
import '../../css/fontawesome-style.css'

var cache = new Map();

function getPropertyFromString(name, list) {
    var isOptional = name.substr(0, 1) === '?';
    var nameWithoutPrefix = (isOptional ? name.substr(1) : name);

    if (undefined === list[nameWithoutPrefix]) {
        if (isOptional) {
            return undefined;
        }

        throw 'Attribute "' + props[prop] + '" does not exists';
    }

    return list[nameWithoutPrefix];
}

/**
 * A tree browser adapter for the Fancytree library.
 *
 * @author Wouter J <wouter@wouterj.nl>
 * @see https://github.com/mar10/fancytree
 */
export class FancytreeAdapter {
    constructor(options) {
        if (!window.jQuery || !jQuery.fn.fancytree) {
            throw 'The FancytreeAdapter requires both jQuery and the FancyTree library.';
        }

        if (!options.request) {
            throw 'The FancytreeAdapter requires a request option.';
        }

        this.requestData = options.request;
        this.rootNode = options.root_node || '/';
        this.useCache = undefined === options.use_cache ? true : options.use_cache;
        this.boundToInput = false;
        this.sortableBy = undefined == options.sortableBy ? false : options.sortableBy;

        if (options.dnd && undefined == options.dnd.enabled) {
            options.dnd.enabled = true;
        }
        var alwaysTrueFunction = () => { return true };
        this.dndOptions = jQuery.extend({
            enabled: false,
            isNodeDraggable: alwaysTrueFunction,
            nodeAcceptsDraggable: alwaysTrueFunction
        }, options.dnd);

        if (this.dndOptions.enabled && !options.request.move) {
            throw 'The move request needs to be configured when drag \'n drop is enabled, pass it using the `request.move` option.';
        }
        this.dndOptions.request = options.request.move;

        // available actions (array)
        this.actions = new Array();
        // the Fancytree instance (FancytreeTree)
        this.tree = null;
        // the tree element (jQuery)
        this.$tree = null;
        // a map of path and related keys
        this.pathKeyMap = {};
    }

    bindToElement($elem) {
        if (this.$tree) {
            throw 'Cannot bind to multiple elements.';
        }

        if (!$elem instanceof jQuery) {
            throw  'FancytreeAdapter can only be adapted to a jQuery object.';
        }

        this.$tree = $elem;
        var actions = this.actions;
        var parseUrl = function (url, node) {
            if (typeof url == 'object' && url.hasOwnProperty('data')) {
                return getPropertyFromString(url.data, node.descriptors);
            }

            if (typeof url == 'function') {
                return url(requestNode);
            }

            if (typeof url == 'string') {
                return url;
            }
        };
        var requestNodeToFancytreeNode = (requestNode) => {
            if (requestNode.length === 0) {
                return;
            }

            if ('//' == requestNode.path || '/' == requestNode.path) {
                return requestNodeToFancytreeNode(requestNode.children[Object.keys(requestNode.children)[0]]);
            }

            var refPath = requestNode.path.replace('\/', '/').replace('//', '/');
            var key = this.pathKeyMap[refPath] || "" + jQuery.ui.fancytree._nextNodeKey++;
            var fancytreeNode = {
                title: requestNode.label,
                key: key,
                children: [],
                actions: {},
                refPath: refPath,
                type: requestNode.payload_type,
                unselectable: true
            };

            this.pathKeyMap[refPath] = key;

            if (requestNode.descriptors.hasOwnProperty('icon')) {
                fancytreeNode.icon = requestNode.descriptors.icon;
            }

            if(requestNode.descriptors.hasOwnProperty('position')) {
                fancytreeNode.position = requestNode.descriptors.position;
            }

            for (let actionName in actions) {
                var action = actions[actionName];
                var url = parseUrl(action.url, requestNode);

                if (url === undefined) {
                    continue;
                }
                fancytreeNode['actions'][actionName] = { label: actionName, iconClass: action.icon, url: url };
            }

            var childrenCount = 0;
            for (name in requestNode.children) {
                if (!requestNode.children.hasOwnProperty(name)) {
                    continue;
                }

                var child = requestNodeToFancytreeNode(requestNode.children[name]);
                if (child) {
                    fancytreeNode.children.push(child);
                }
                childrenCount++;
            }

            if (0 != childrenCount) {
                fancytreeNode.folder = true;
                fancytreeNode.lazy = true;

                if (0 === fancytreeNode.children.length) {
                    fancytreeNode.children = null;
                }
            }

            return fancytreeNode;
        };

        var requestData = this.requestData;
        var useCache = this.useCache;
        var fancytreeOptions = {
            // the start data (root node + children)
            source: (useCache && cache.has(this.rootNode)) ? cache.get(this.rootNode) : requestData.load(this.rootNode),

            // lazy load the children when a node is collapsed
            lazyLoad: function (event, data) {
                var path = data.node.data.refPath;
                if (useCache && cache.has(path)) {
                    data.result = cache.get(path);
                } else {
                    var loadData = requestData.load(path);

                    if (Array.isArray(loadData)) {
                        data.result = loadData;
                    } else {
                        data.result = jQuery.extend({
                            data: {}
                        }, loadData);
                    }
                }
            },

            // transform the JSON response into a data structure that's supported by FancyTree
            postProcess: function (event, data) {
                if (data.hasOwnProperty('error') && null != data.error) {
                    data.result = {
                        // todo: maybe use a more admin friendly error message in prod?
                        error: 'An error occured while retrieving the nodes: ' + data.error
                    };

                    return;
                }

                let result = requestNodeToFancytreeNode(data.response);
                let nodeIsDuplicate = function (node, parentPath) {
                    return parentPath == node.refPath;
                };

                if (nodeIsDuplicate(result, data.node.data.refPath)) {
                    result = result.children;
                } else {
                    result = [result];
                }

                if (result.length == 1 && undefined !== result[0].folder) {
                    result[0].expanded = true;
                }

                data.result = result;
                if (useCache) {
                    cache.set(data.node.data.refPath, result);
                }
            },

            // always show the active node
            activeVisible: true
        };

        if (this.sortableBy) {
            fancytreeOptions.sortChildren = (a, b) => {
                var current = a.data[this.sortableBy];
                var next = b.data[this.sortableBy];
                if (current == next) {
                    return 0;
                } else if (current < next) {
                    return -1;
                } else  {
                    return 1;
                }
            };
        }

        if (this.dndOptions.enabled) {
            fancytreeOptions.extensions = ['dnd'];
            fancytreeOptions.dnd = {
                dragStart: (node, data) => {
                    return this.dndOptions.isNodeDraggable(node, data);
                },
                dragEnter: (node, data) => {
                    return this.dndOptions.nodeAcceptsDraggable(node, data);
                },
                dragExpand: (node, data) => {
                    return true;
                },
                dragDrop: (node, data) => {
                    let dropedNode = data.otherNode;
                    let dropedAtNode = data.node;

                    let dropNodePath = dropedNode.data.refPath;
                    let dropedAtPath = dropedAtNode.data.refPath;
                    let positionBefore = 'over' != data.hitMode && 'child' != data.hitMode;
                    let parentNode = positionBefore ? dropedAtNode.parent : dropedAtNode;
                    let parenPath = parentNode.data.refPath;
                    let targetPath = parenPath + '/' + dropNodePath.substr(1 + dropNodePath.lastIndexOf('/'));

                    let formerIcon = dropedNode.icon;

                    let moveNodeInTree = (responseData) => {
                        dropedNode.remove();
                        if (positionBefore) {
                            parentNode.children.forEach((node) => {
                            if (node.data.position >= responseData.descriptors.position) {
                                node.data.position++;
                            }
                        });
                      }
                        parentNode.addChildren(requestNodeToFancytreeNode(responseData));
                    };

                    let setIcon = (nodeToSetOn, icon) => {
                        nodeToSetOn.icon = icon;
                        dropedNode.renderTitle();
                    };

                    setIcon(dropedNode, 'fa fa-spinner fa-spin')

                    let onError = (jqxhr) => {
                        let message = 'Failed to move node';
                        let formerLabel = dropedNode.title;
                        if (jqxhr.hasOwnProperty('responseJSON') && jqxhr.responseJSON.hasOwnProperty('message')) {
                            message += ': ' + jqxhr.responseJSON.message;
                        }
                        let details = null;
                        if (jqxhr.hasOwnProperty('responseJSON')) {
                            details = jqxhr.responseJSON;
                        }
                        dropedNode._error = { message: message, details: details};
                        dropedNode.renderStatus();

                        dropedNode.title +=  '[' + message + ']';
                        dropedNode.renderTitle();

                        console.error(message);
                        setIcon(dropedNode, formerIcon);

                        setTimeout(function () {
                            dropedNode._error = null;
                            dropedNode.title = formerLabel;
                            dropedNode.renderTitle();
                            dropedNode.renderStatus();
                        }, 1000);
                    };
                    this.requestData.move(dropNodePath, targetPath).done((responseData) => {
                        if (positionBefore && this.dndOptions.reorder) {
                            this.requestData.reorder(parenPath, dropedAtPath, targetPath, data.hitMode).done((responseData) => {
                                moveNodeInTree(responseData);
                                if (fancytreeOptions.hasOwnProperty('sortChildren')) {
                                    parentNode.sortChildren(fancytreeOptions.sortChildren, true);
                                }
                                setIcon(dropedNode, formerIcon);
                          }).fail( (jqxhr) => {
                              onError(jqxhr);
                              setTimeout(() => {
                                  this.requestData.move(targetPath, dropNodePath).done((responseData) => {
                                      if (fancytreeOptions.hasOwnProperty('sortChildren')) {
                                         parentNode.sortChildren(fancytreeOptions.sortChildren, true);
                                      }
                                      setIcon(dropedNode, formerIcon);
                                  });
                              }, 1000);

                            });
                        } else {
                            dropedNode.icon = formerIcon;
                            moveNodeInTree(responseData);
                        }
                    }).fail(onError);
                }
            };
        }

        this.$tree.fancytree(fancytreeOptions);

        if (this.actions) {
            this.$tree.cmfContextMenu({
                delegate: 'span.fancytree-title',
                wrapperTemplate: '

',
                actionTemplate: '
 {{ label }}
',
                actions: function ($node) {
                    return jQuery.ui.fancytree.getNode($node).data.actions;
                }
            });
        }

        this.tree = this.$tree.fancytree('getTree');

        this.tree.getNodeByRefPath = function (refPath) {
            return this.findFirst((node) => {
                return node.data.refPath == refPath;
            });
        };

        // We do not want to do anything on activation atm.
        this.$tree.fancytree('option', 'activate', (event, data) => {
            if (!this.boundToInput) {
                data.node.setActive(false);
                data.node.setFocus(false);
            }
        });
    }

    bindToInput($input) {
        this.boundToInput = true;

        // output active node to input field
        this.$tree.fancytree('option', 'activate', (event, data) => {
            $input.val(data.node.data.refPath);
        });

        var showPath = (path) => {
            if (!this.pathKeyMap.hasOwnProperty(path)) {
                var parts = path.split('/');

                while (!this.pathKeyMap.hasOwnProperty(parts.join('/')) && parts.pop());

                if (parts.length === 0) {
                    return;
                }

                var loadedPath = parts.join('/');
                var pathsToLoad = path.substr(loadedPath.length + 1).split('/');

                pathsToLoad.forEach((pathToLoad) => {
                    this.pathKeyMap[loadedPath += '/' + pathToLoad] = "" + jQuery.ui.fancytree._nextNodeKey++;
                });
            }

            this.tree.loadKeyPath(generateKeyPath(path), function (node, status) {
                if ('ok' == status) {
                    node.setExpanded();
                    node.setActive();
                }
            });
        };
        var generateKeyPath = (path) => {
            var keyPath = '';
            var refPath = '';
            var subPaths = path.split('/');

            subPaths.forEach((subPath) => {
                if (subPath == '' || !this.pathKeyMap.hasOwnProperty(refPath += '/' + subPath)) {
                    return;
                }

                keyPath += '/' + this.pathKeyMap[refPath];
            });

            return keyPath;
        };

        // use initial input value as active node
        this.$tree.bind('fancytreeinit', function (event, data) {
            showPath($input.val());
        });

        // change active node when the value of the input field changed
        $input.on('change', function (e) {
            showPath($(this).val());
        });
    }

    addAction(name, url, icon) {
        this.actions[name] = { url: url, icon: icon };
    }

    static _resetCache() {
        cache.clear();
    }
}


text:
package edu.wpi.first.wpilibj.ultimateascent.subsystems;

import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.lib.Print;
import edu.wpi.first.wpilibj.ultimateascent.RobotMap;

/**
 *
 * @author Jeremy
 */
public class Intake extends Subsystem {

    /*
     * vvvtl7: So, I made this subsystem and its one command
     * I'm not sure exactly how to count the amount of firsbees
     *  that enter and leave the robot.
     * The best so far is this:
     *  'public static int frisbees'
     *  'if(intakeSuccess){frisbees += 1}'
     *  'if(shooterSuccess){frisbees -= 1}'
     *  'if(frisbees >= 4){don't intake)'
     */

    private Talon intakeMotor = new Talon(RobotMap.INTAKE_MOTOR);

    public void initDefaultCommand() {
        intakeMotor.set(0);
    }

    public void setIntakeMotor(double pow) {
        Print.printMessage("We seriously intook a frisbee.");
        intakeMotor.set(pow);
    }

    // vvvtl7: TODO: devise some sort of logic for counting frisbees
    protected int countFrisbees() {
        return 0;
    }
}


text:
exports.config = {
	seleniumAddress: 'http://localhost:4444/wd/hub',
	baseUrl: 'http://localhost:9999',
	rootElement: 'html',
	specs: ['test/e2e/*.spec.js'],
	allScriptsTimeout: 60000,
	chromeOnly: false,

	multiCapabilities: [{
		browserName: 'chrome'
	}, {
		browserName: 'firefox'
	}],

	jasmineNodeOpts: {
		onComplete: null,
		isVerbose: false,
		showColors: true,
		includeStackTrace: true,
		defaultTimeoutInterval: 60000
	}
};


text:
 class Mapper {
  constructor({width = 768, rowHeight = 15, numColumns = 60, buffer = 4, minHeight = 4, minWidth = 10}) {
    this.width = width;
    this.numColumns = numColumns;
    this.buffer = buffer;
    this.rowHeight = rowHeight;
    this.minHeight = minHeight;
    this.minWidth = minWidth;

    // colWidth and rowHeight include buffer
    this.colWidth = (width - (numColumns - 1) * buffer)/numColumns + buffer;
  }

  /** All sides (left, right, top, bottom) are snapped to a grid */
  px2layout({left, top, width, height}) {
    const pos = this.px2pos({left, top});
    const right = Math.ceil((this.left2px(pos.left) + width)/this.colWidth);
    const bottom = Math.ceil((this.top2px(pos.top) + height + this.buffer)/this.rowHeight);

    return {
      left: pos.left,
      top: pos.top,
      width: right - pos.left,
      height: bottom - pos.top,
    };
  }

  layout2px({left, top, width, height}) {
    return {
      left: this.left2px(left),
      top: this.top2px(top),
      width: this.width2px(width),
      height: this.height2px(height)
    };
  }

  px2pos({left, top}) {
    return {
      left: this._closestMultiple(left, this.colWidth),
      top: this._closestMultiple(top, this.rowHeight)
    };
  }

  left2px(left) {
    return left * this.colWidth;
  }

  top2px(top) {
    return top * this.rowHeight;
  }

  width2px(width) {
    return width * this.colWidth - this.buffer;
  }

  height2px(height) {
    return height * this.rowHeight -  this.buffer;
  }

  getClosestPosition(pixels) {
    return this.checkPositionConstraints(this.px2layout(pixels));
  }

  getClosestSize(pixels, axis) {
    return this.checkSizeConstraints(this.px2layout(pixels), axis);
  }

  checkPositionConstraints({width, height, left, top}) {
    // Right container
    if (left + width > this.numColumns) {
      left = this.numColumns - width;
    }

    // Left container
    if (left < 0) {
      left = 0;
    }

    // Top container
    if (top < 0) {
      top = 0;
    }

    return {
      left,
      top,
      width,
      height
    };
  }

  checkSizeConstraints({width, height, left, top}, isLeft) {
    // Right container
    if (left + width > this.numColumns) {
      width = this.numColumns - left;
    }

    if (left < 0) {
      const right = left + width;
      left = 0;
      width = right - left;
    }

    if (width < this.minWidth) {
      // If it was shrunk from the left handler, then move the leftside back
      if (isLeft) {
        left -= this.minWidth - width;
      }
      width = this.minWidth;
    }

    if (height < this.minHeight) {
      height = this.minHeight;
    }

    return {
      left, top, width, height
    };
  }

  _closestMultiple(val, divisor) {
    const result = val/divisor;
    const option1 = Math.floor(result);
    const option2 = Math.ceil(result);
    return result - option1 > option2 - result? option2 : option1;
  }
}

export default function MapperFactory() {
  return Mapper;
}


text:
var Hapi 			= require('hapi'),
    swagger         = require('../'),
    pack            = require('../package'),
	routes 			= require('./mock-routes');

var server = new Hapi.Server(3004);
server.route(routes);

// setup swagger options
var swaggerOptions = {
    basePath: 'http://localhost:3004',
    apiVersion: pack.version
};

server.pack.register(require('../'), function(err) {
	if(err){
		console.log(['error'], 'plugin "hapi-swagger" load error: ' + err)
	}else{
		console.log(['start'], 'swagger interface loaded')
		server.start(function(){
            console.log(['start'], pack.name + ' - web interface: ' + server.info.uri);
        });
	}
});


text:
"""gRPC server that places a ffmpeg task in a Google Cloud Tasks queue.

To deploy this server, an API key must be created for the FFmpeg worker service.
The key and the URL of the FFmpeg worker service are sent to Google Cloud Tasks.

This code requires a service account with the permission to enqueue tasks.
Steps on how to create this service account can be found in the link below:
https://cloud.google.com/tasks/docs/creating-http-target-tasks#sa
"""

from concurrent import futures
import os

import grpc
from google.cloud import tasks_v2
from google.protobuf import json_format

from async_worker.async_ffmpeg_worker_pb2 import AsyncFFmpegRequest
from async_worker.async_ffmpeg_worker_pb2 import AsyncFFmpegResponse
from async_worker import async_ffmpeg_worker_pb2_grpc

PROJECT = os.environ['PROJECT']
QUEUE = os.environ['QUEUE']
LOCATION = os.environ['LOCATION']
HOST = os.environ['SERVICE_IP']
API_KEY = os.environ['FFMPEG_API_KEY']
URL = f'http://{HOST}:8080/FFmpeg/transcode?key={API_KEY}'

class AsyncFFmpegServicer(async_ffmpeg_worker_pb2_grpc.AsyncFFmpegServicer):  # pylint: disable=too-few-public-methods
    """Implements AsyncFFmpeg service"""

    def transcode(self, request: AsyncFFmpegRequest,
                  context) -> AsyncFFmpegResponse:
        """Creates FFmpeg task on Google Cloud Tasks queue.

        The task contains the HTTP target to call and the payload.
        """
        client = tasks_v2.CloudTasksClient()
        parent = client.queue_path(PROJECT, LOCATION, QUEUE)
        payload = json_format.MessageToJson(request.request,
                                            preserving_proto_field_name=True)
        task = {
            'http_request': {
                'http_method': 'POST',
                'url': URL,
                'body': payload.encode()
            }
        }
        response = client.create_task(parent, task)
        return AsyncFFmpegResponse(task_name=response.name)

if __name__ == '__main__':
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    async_ffmpeg_worker_pb2_grpc.add_AsyncFFmpegServicer_to_server(
        AsyncFFmpegServicer(), server)
    server.add_insecure_port('[::]:8080')
    server.start()
    server.wait_for_termination()


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/PswGenDroid.iml" filepath="$PROJECT_DIR$/PswGenDroid.iml" group="PswGenDroid" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" group="PswGenDroid/app" />
    </modules>
  </component>
</project>


text:
// Decompiled with JetBrains decompiler
// Type: System.Fabric.Management.ServiceModel.StatelessServiceTypeType
// Assembly: System.Fabric.Management.ServiceModel, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// MVID: C6D32D4D-966E-4EA3-BD3A-F4CF14D36DBC
// Assembly location: C:\Git\ServiceFabricSdkContrib\ServiceFabricSdkContrib.MsBuild\bin\Debug\netstandard2.0\publish\runtimes\win\lib\netstandard2.0\System.Fabric.Management.ServiceModel.dll

using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Serialization;

namespace System.Fabric.Management.ServiceModel
{
  [GeneratedCode("xsd", "4.0.30319.17929")]
  [DebuggerStepThrough]
  [XmlType(Namespace = "http://schemas.microsoft.com/2011/01/fabric")]
  public class StatelessServiceTypeType : ServiceTypeType
  {
    private bool useImplicitHostField;

    public StatelessServiceTypeType()
    {
      this.useImplicitHostField = false;
    }

    [XmlAttribute]
    [DefaultValue(false)]
    public bool UseImplicitHost
    {
      get
      {
        return this.useImplicitHostField;
      }
      set
      {
        this.useImplicitHostField = value;
      }
    }
  }
}


text:
<?php
/**
 * Comment NestedSets install migration
 * Класс миграций для модуля Comment добавляющий поля
 * для использования NestedSets:
 *
 * @category YupeMigration
 * @package  yupe.modules.comment.install.migrations
 * @author   YupeTeam <team@yupe.ru>
 * @license  BSD https://raw.github.com/yupe/yupe/master/LICENSE
 * @link     http://yupe.ru
 **/
class m130704_095200_comment_nestedsets extends yupe\components\DbMigration
{
    public function safeUp()
    {
        $this->addColumn('{{comment_comment}}','level','integer DEFAULT 0');
        $this->addColumn('{{comment_comment}}','root','integer DEFAULT 0');
        $this->addColumn('{{comment_comment}}','lft','integer DEFAULT 0');
        $this->addColumn('{{comment_comment}}','rgt','integer DEFAULT 0');

        $this->createIndex('ix_{{comment_comment}}_level','{{comment_comment}}', "level", false);
        $this->createIndex('ix_{{comment_comment}}_root','{{comment_comment}}', "root", false);
        $this->createIndex('ix_{{comment_comment}}_lft','{{comment_comment}}', "lft", false);
        $this->createIndex('ix_{{comment_comment}}_rgt','{{comment_comment}}', "rgt", false);
    }

    public function safeDown()
    {
        $this->dropIndex('ix_{{comment_comment}}_level','{{comment_comment}}');
        $this->dropIndex('ix_{{comment_comment}}_root','{{comment_comment}}');
        $this->dropIndex('ix_{{comment_comment}}_lft','{{comment_comment}}');
        $this->dropIndex('ix_{{comment_comment}}_rgt','{{comment_comment}}');

        $this->dropColumn('{{comment_comment}}','level');
        $this->dropColumn('{{comment_comment}}','root');
        $this->dropColumn('{{comment_comment}}','lft');
        $this->dropColumn('{{comment_comment}}','rgt');
    }
}


text:
namespace vast {

template <>
struct access::state<null_bitstream> {
  template <typename Bitstream, typename F>
  static void call(Bitstream&& bs, F f) {
    f(bs.bits_);
  }
};

template <>
struct access::state<ewah_bitstream> {
  template <typename Bitstream, typename F>
  static void call(Bitstream&& bs, F f) {
    f(bs.num_bits_, bs.last_marker_, bs.bits_);
  }
};

} // namespace vast

#endif


text:
package cz.lbenda.dataman.db.frm;

import cz.lbenda.dataman.db.SQLQueryRows;
import cz.lbenda.dataman.db.TableDesc;
import cz.lbenda.test.JavaFXInitializer;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static org.mockito.Mockito.*;

/** Created by Lukas Benda <lbenda @ lbenda.cz> on 20.9.15. */
public class TestDataTableFrmController {

  @BeforeClass
  public void setup() throws InterruptedException {
    JavaFXInitializer.initialize();
  }

  @Test
  public void contstructor() {
    TableDesc td = mock(TableDesc.class);
    BooleanProperty dirty = new SimpleBooleanProperty(false);
    SQLQueryRows sqlRows = new SQLQueryRows();
    when(td.dirtyProperty()).thenReturn(dirty);
    when(td.getQueryRow()).thenReturn(sqlRows);
    when(td.getRows()).thenReturn(sqlRows.getRows());
    when(td.isLoaded()).thenReturn(false);

    // TableDesc td = new TableDesc("catalog", "schema", "TABLE", "table1");
    new DataTableFrmController(td);
    verify(td, times(1)).isLoaded();
    verify(td, times(1)).reloadRowsAction();
    when(td.isLoaded()).thenReturn(true);

    new DataTableFrmController(td);
    verify(td, times(2)).isLoaded();
    verify(td, times(1)).reloadRowsAction();
  }
}