text:
<!DOCTYPE html>

		<meta charset="utf-8"/>
		<title>WallRide</title>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MsTestToXunitConverter.xUnit
{
    class TestClass
    {
        public void TestDoesNotContain()
        {
            //No idea what xunit is talking about
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace java {
  namespace lang {
    class String;
    class Class;
  }
}
template<class T> class JArray;

namespace org {
  namespace apache {
    namespace lucene {
      namespace index {

        class OrdTermState : public ::org::apache::lucene::index::TermState {
        public:
          enum {
            mid_init$_54c6a166,
            mid_copyFrom_d506ca07,
            mid_toString_14c7b5c5,
            max_mid
          };

          enum {
            fid_ord,
            max_fid
          };

          static ::java::lang::Class *class$;
          static jmethodID *mids$;
          static jfieldID *fids$;
          static bool live$;
          static jclass initializeClass(bool);

          explicit OrdTermState(jobject obj) : ::org::apache::lucene::index::TermState(obj) {
            if (obj != NULL)
              env->getClass(initializeClass);
          }
          OrdTermState(const OrdTermState& obj) : ::org::apache::lucene::index::TermState(obj) {}

          jlong _get_ord() const;
          void _set_ord(jlong) const;

          OrdTermState();

          void copyFrom(const ::org::apache::lucene::index::TermState &) const;
          ::java::lang::String toString() const;
        };
      }
    }
  }
}

#include <Python.h>

namespace org {
  namespace apache {
    namespace lucene {
      namespace index {
        extern PyTypeObject PY_TYPE(OrdTermState);

        class t_OrdTermState {
        public:
          PyObject_HEAD
          OrdTermState object;
          static PyObject *wrap_Object(const OrdTermState&);
          static PyObject *wrap_jobject(const jobject&);
          static void install(PyObject *module);
          static void initialize(PyObject *module);
        };
      }
    }
  }
}

#endif


text:
package io.druid.server.coordinator;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.MapMaker;
import com.metamx.common.concurrent.ScheduledExecutorFactory;
import io.druid.client.DruidServer;
import io.druid.client.ImmutableDruidServer;
import io.druid.client.SingleServerInventoryView;
import io.druid.curator.discovery.NoopServiceAnnouncer;
import io.druid.curator.inventory.InventoryManagerConfig;
import io.druid.metadata.MetadataSegmentManager;
import io.druid.server.DruidNode;
import io.druid.server.coordination.DruidServerMetadata;
import io.druid.server.initialization.ZkPathsConfig;
import io.druid.server.metrics.NoopServiceEmitter;
import io.druid.timeline.DataSegment;
import org.apache.curator.framework.CuratorFramework;
import org.easymock.EasyMock;
import org.joda.time.Duration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.ConcurrentMap;

/**
 */
public class DruidCoordinatorTest
{
  private DruidCoordinator coordinator;
  private CuratorFramework curator;
  private LoadQueueTaskMaster taskMaster;
  private MetadataSegmentManager databaseSegmentManager;
  private SingleServerInventoryView serverInventoryView;
  private ScheduledExecutorFactory scheduledExecutorFactory;
  private DruidServer druidServer;
  private DruidServer druidServer2;
  private DataSegment segment;
  private ConcurrentMap<String, LoadQueuePeon> loadManagementPeons;
  private LoadQueuePeon loadQueuePeon;

  @Before
  public void setUp() throws Exception
  {
    druidServer = EasyMock.createMock(DruidServer.class);
    druidServer2 = EasyMock.createMock(DruidServer.class);
    segment = EasyMock.createNiceMock(DataSegment.class);
    loadQueuePeon = EasyMock.createNiceMock(LoadQueuePeon.class);
    loadManagementPeons = new MapMaker().makeMap();
    serverInventoryView = EasyMock.createMock(SingleServerInventoryView.class);

    databaseSegmentManager = EasyMock.createNiceMock(MetadataSegmentManager.class);
    EasyMock.replay(databaseSegmentManager);

    scheduledExecutorFactory = EasyMock.createNiceMock(ScheduledExecutorFactory.class);
    EasyMock.replay(scheduledExecutorFactory);

    coordinator = new DruidCoordinator(
        new DruidCoordinatorConfig()
        {
          @Override
          public Duration getCoordinatorStartDelay()
          {
            return null;
          }

          @Override
          public Duration getCoordinatorPeriod()
          {
            return null;
          }

          @Override
          public Duration getCoordinatorIndexingPeriod()
          {
            return null;
          }
        },
        new ZkPathsConfig()
        {

          @Override
          public String getBase()
          {
            return "";
          }
        },
        null,
        databaseSegmentManager,
        serverInventoryView,
        null,
        curator,
        new NoopServiceEmitter(),
        scheduledExecutorFactory,
        null,
        taskMaster,
        new NoopServiceAnnouncer(),
        new DruidNode("hey", "what", 1234),
        loadManagementPeons
    );
  }

  @After
  public void tearDown() throws Exception
  {
    EasyMock.verify(druidServer);
    EasyMock.verify(druidServer2);
    EasyMock.verify(loadQueuePeon);
    EasyMock.verify(serverInventoryView);
  }

  @Test
  public void testMoveSegment() throws Exception
  {
    EasyMock.expect(druidServer.toImmutableDruidServer()).andReturn(
        new ImmutableDruidServer(
            new DruidServerMetadata("from", null, 5L, null, null, 0),
            1L,
            null,
            ImmutableMap.of("dummySegment", segment)
        )
    ).atLeastOnce();
    EasyMock.replay(druidServer);

    EasyMock.expect(druidServer2.toImmutableDruidServer()).andReturn(
        new ImmutableDruidServer(
            new DruidServerMetadata("to", null, 5L, null, null, 0),
            1L,
            null,
            ImmutableMap.of("dummySegment2", segment)
        )
    ).atLeastOnce();
    EasyMock.replay(druidServer2);

    loadManagementPeons.put("from", loadQueuePeon);
    loadManagementPeons.put("to", loadQueuePeon);

    EasyMock.expect(loadQueuePeon.getLoadQueueSize()).andReturn(new Long(1));
    EasyMock.replay(loadQueuePeon);

    EasyMock.expect(serverInventoryView.getInventoryManagerConfig()).andReturn(
        new InventoryManagerConfig()
        {
          @Override
          public String getContainerPath()
          {
            return "";
          }

          @Override
          public String getInventoryPath()
          {
            return "";
          }
        }
    );
    EasyMock.replay(serverInventoryView);

    coordinator.moveSegment(
        druidServer.toImmutableDruidServer(),
        druidServer2.toImmutableDruidServer(),
        "dummySegment", null
    );
  }
}


text:
namespace
{
using ByteVector = std::vector<uint8_t>;

decltype(auto) GetForest()
{
  auto tree1 = tree_node::MakeTreeNode<complex::ComplexSerdes::Ids>({1, 2, 3});
  auto node11 = tree_node::MakeTreeNode<complex::ComplexSerdes::Ids>({11, 12, 13});
  tree_node::Link(tree_node::MakeTreeNode<complex::ComplexSerdes::Ids>({111}), node11);
  tree_node::Link(tree_node::MakeTreeNode<complex::ComplexSerdes::Ids>({112, 113}), node11);
  tree_node::Link(tree_node::MakeTreeNode<complex::ComplexSerdes::Ids>({114}), node11);
  tree_node::Link(node11, tree1);
  tree_node::Link(tree_node::MakeTreeNode<complex::ComplexSerdes::Ids>({6, 7}), tree1);

  auto tree2 = tree_node::MakeTreeNode<complex::ComplexSerdes::Ids>({9});
  tree_node::Link(tree_node::MakeTreeNode<complex::ComplexSerdes::Ids>({21, 22, 23}), tree2);
  tree_node::Link(tree_node::MakeTreeNode<complex::ComplexSerdes::Ids>({24, 25}), tree2);

  tree_node::Forest<complex::ComplexSerdes::Ids> forest;
  forest.Append(tree1);
  forest.Append(tree2);
  return forest;
}

UNIT_TEST(Complex_SerdesV0)
{
  auto const expectedForest = GetForest();
  ByteVector buffer;
  {
    MemWriter<decltype(buffer)> writer(buffer);
    WriterSink<decltype(writer)> sink(writer);
    complex::ComplexSerdes::Serialize(sink, complex::ComplexSerdes::Version::V0, expectedForest);
  }
  {
    MemReader reader(buffer.data(), buffer.size());
    ReaderSource<decltype(reader)> src(reader);
    tree_node::Forest<complex::ComplexSerdes::Ids> forest;
    complex::ComplexSerdes::Deserialize(src, complex::ComplexSerdes::Version::V0, forest);
    TEST_EQUAL(forest, expectedForest, ());
  }
}

UNIT_TEST(Complex_Serdes)
{
  auto const expectedForest = GetForest();
  ByteVector buffer;
  {
    MemWriter<decltype(buffer)> writer(buffer);
    WriterSink<decltype(writer)> sink(writer);
    complex::ComplexSerdes::Serialize(sink, expectedForest);
  }
  {
    MemReader reader(buffer.data(), buffer.size());
    tree_node::Forest<complex::ComplexSerdes::Ids> forest;
    complex::ComplexSerdes::Deserialize(reader, forest);
    TEST_EQUAL(forest, expectedForest, ());
  }
}
}  // namespace


text:
use std::fs::File;
use std::path::PathBuf;
use std::io::Read;
use crypto::sha2::Sha224;
use crypto::digest::Digest;
use super::Error;

/// A private trait Hashable (with Sha224 only)
pub trait Hashable {
    /// Hash (with sha224) to result in a String or io::Error
    fn hash(&self) -> Result<String,Error>;
}

impl Hashable for Vec<u8> {
    fn hash(&self) -> Result<String, Error> {
        // Start the hash
        let mut hash = Box::new(Sha224::new());

        // Add the content
        hash.input( &*self );

        // Get the result
        Ok(hash.result_str())
    }
}

impl Hashable for PathBuf {
    fn hash(&self) -> Result<String, Error> {
        // Start the hash
        let mut hash = Box::new(Sha224::new());

        // Open the file
        let mut file =
            File::open(self)
                .map_err(|e| { (e, "Cannot open content file for hashing") } )?;

        // Digest 4096 bytes at a time
        let mut buf: [u8; 4096] = [0_u8; 4096];
        loop {
            let count = file.read(&mut buf)
                .map_err(|e| { (e, "Unable to read file to hash") } )?;
            if count==0 { return Ok(hash.result_str()); }
            hash.input(&buf[..count]); // Add to hash input
        }
    }
}


text:
import redis

keyStringPrefix = 'i_'
keyFormat = '{0}_{1}'
currentDatabaseIdKey = 'currentDatabaseId'

websiteInfoRedisDB = redis.StrictRedis( '127.0.0.1', 6379 )

def getNewDatabaseId():
  key = keyFormat.format( keyStringPrefix, currentDatabaseIdKey )
  result = websiteInfoRedisDB.get( key )
  if result == None or result == '':#FIXME: which one is it ? None or '' ?
    result = '0'

  websiteInfoRedisDB.set( key, int( result ) + 1 )

  return result


text:
package org.apache.ibatis.submitted.associationtest;

public class Car {
  private int id;
  private String type;
  private Engine engine;
  private Brakes brakes;

  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getType() {
    return type;
  }
  public void setType(String type) {
    this.type = type;
  }
  public Engine getEngine() {
    return engine;
  }
  public void setEngine(Engine engine) {
    this.engine = engine;
  }
  public Brakes getBrakes() {
    return brakes;
  }
  public void setBrakes(Brakes brakes) {
    this.brakes = brakes;
  }

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="typeRepresentationStrategy" class="org.springframework.data.neo4j.support.typerepresentation.SubReferenceNodeTypeRepresentationStrategy">
        <constructor-arg ref="graphDatabaseService"/>
        <constructor-arg ref="graphEntityInstantiator" />
    </bean>

</beans>


text:
package main

import (
	"bytes"
	"os"
	"path/filepath"
	"testing"

	"gopkg.in/check.v1"

	"github.com/tsuru/tsuru-client/tsuru/admin"
	"github.com/tsuru/tsuru-client/tsuru/client"
	"github.com/tsuru/tsuru/cmd"
	"github.com/tsuru/tsuru/exec/exectest"
)

type S struct{}

func (s *S) SetUpSuite(c *check.C) {
	os.Setenv("TSURU_TARGET", "http://localhost:8080")
	os.Setenv("TSURU_TOKEN", "sometoken")
}

func (s *S) TearDownSuite(c *check.C) {
	os.Unsetenv("TSURU_TARGET")
	os.Unsetenv("TSURU_TOKEN")
}

var _ = check.Suite(&S{})
var manager *cmd.Manager

func Test(t *testing.T) { check.TestingT(t) }

func (s *S) SetUpTest(c *check.C) {
	var stdout, stderr bytes.Buffer
	manager = cmd.NewManagerPanicExiter("glb", "1.0.0", "Supported-Tsuru", &stdout, &stderr, os.Stdin, nil)
}

func (s *S) TestCommandsFromBaseManagerAreRegistered(c *check.C) {
	baseManager := cmd.BuildBaseManagerPanicExiter("tsuru", version, header, nil)
	manager = buildManager("tsuru")
	for name, instance := range baseManager.Commands {
		command, ok := manager.Commands[name]
		c.Assert(ok, check.Equals, true)
		c.Assert(command, check.FitsTypeOf, instance)
	}
}

func (s *S) TestAppCreateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	create, ok := manager.Commands["app-create"]
	c.Assert(ok, check.Equals, true)
	c.Assert(create, check.FitsTypeOf, &client.AppCreate{})
}

func (s *S) TestAppRemoveIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	remove, ok := manager.Commands["app-remove"]
	c.Assert(ok, check.Equals, true)
	c.Assert(remove, check.FitsTypeOf, &client.AppRemove{})
}

func (s *S) TestAppListIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["app-list"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &client.AppList{})
}

func (s *S) TestAppGrantIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	grant, ok := manager.Commands["app-grant"]
	c.Assert(ok, check.Equals, true)
	c.Assert(grant, check.FitsTypeOf, &client.AppGrant{})
}

func (s *S) TestAppRevokeIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	grant, ok := manager.Commands["app-revoke"]
	c.Assert(ok, check.Equals, true)
	c.Assert(grant, check.FitsTypeOf, &client.AppRevoke{})
}

func (s *S) TestAppLogIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	log, ok := manager.Commands["app-log"]
	c.Assert(ok, check.Equals, true)
	c.Assert(log, check.FitsTypeOf, &client.AppLog{})
}

func (s *S) TestAppRunIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	run, ok := manager.Commands["app-run"]
	c.Assert(ok, check.Equals, true)
	c.Assert(run, check.FitsTypeOf, &client.AppRun{})
}

func (s *S) TestAppRestartIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	restart, ok := manager.Commands["app-restart"]
	c.Assert(ok, check.Equals, true)
	c.Assert(restart, check.FitsTypeOf, &client.AppRestart{})
}

func (s *S) TestEnvGetIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	get, ok := manager.Commands["env-get"]
	c.Assert(ok, check.Equals, true)
	c.Assert(get, check.FitsTypeOf, &client.EnvGet{})
}

func (s *S) TestEnvSetIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	set, ok := manager.Commands["env-set"]
	c.Assert(ok, check.Equals, true)
	c.Assert(set, check.FitsTypeOf, &client.EnvSet{})
}

func (s *S) TestEnvUnsetIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	unset, ok := manager.Commands["env-unset"]
	c.Assert(ok, check.Equals, true)
	c.Assert(unset, check.FitsTypeOf, &client.EnvUnset{})
}

func (s *S) TestServiceListIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["service-list"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, client.ServiceList{})
}

func (s *S) TestServiceUpdateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	add, ok := manager.Commands["service-update"]
	c.Assert(ok, check.Equals, true)
	c.Assert(add, check.FitsTypeOf, &admin.ServiceUpdate{})
}

func (s *S) TestServiceInstanceUpdateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	add, ok := manager.Commands["service-instance-update"]
	c.Assert(ok, check.Equals, true)
	c.Assert(add, check.FitsTypeOf, &client.ServiceInstanceUpdate{})
}

func (s *S) TestServiceInstanceAddIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	add, ok := manager.Commands["service-instance-add"]
	c.Assert(ok, check.Equals, true)
	c.Assert(add, check.FitsTypeOf, &client.ServiceInstanceAdd{})
}

func (s *S) TestServiceInstanceRemoveIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	remove, ok := manager.Commands["service-instance-remove"]
	c.Assert(ok, check.Equals, true)
	c.Assert(remove, check.FitsTypeOf, &client.ServiceInstanceRemove{})
}

func (s *S) TestServiceInstanceBindIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	bind, ok := manager.Commands["service-instance-bind"]
	c.Assert(ok, check.Equals, true)
	c.Assert(bind, check.FitsTypeOf, &client.ServiceInstanceBind{})
}

func (s *S) TestServiceInstanceUnbindIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	unbind, ok := manager.Commands["service-instance-unbind"]
	c.Assert(ok, check.Equals, true)
	c.Assert(unbind, check.FitsTypeOf, &client.ServiceInstanceUnbind{})
}

func (s *S) TestServiceInstanceInfoIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	info, ok := manager.Commands["service-instance-info"]
	c.Assert(ok, check.Equals, true)
	c.Assert(info, check.FitsTypeOf, client.ServiceInstanceInfo{})
}

func (s *S) TestServiceInfoIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	info, ok := manager.Commands["service-info"]
	c.Assert(ok, check.Equals, true)
	c.Assert(info, check.FitsTypeOf, &client.ServiceInfo{})
}

func (s *S) TestAppInfoIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["app-info"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &client.AppInfo{})
}

func (s *S) TestUnitAddIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	addunit, ok := manager.Commands["unit-add"]
	c.Assert(ok, check.Equals, true)
	c.Assert(addunit, check.FitsTypeOf, &client.UnitAdd{})
}

func (s *S) TestUnitRemoveIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	rmunit, ok := manager.Commands["unit-remove"]
	c.Assert(ok, check.Equals, true)
	c.Assert(rmunit, check.FitsTypeOf, &client.UnitRemove{})
}

func (s *S) TestUnitSetIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	rmunit, ok := manager.Commands["unit-set"]
	c.Assert(ok, check.Equals, true)
	c.Assert(rmunit, check.FitsTypeOf, &client.UnitSet{})
}

func (s *S) TestCNameAddIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	cname, ok := manager.Commands["cname-add"]
	c.Assert(ok, check.Equals, true)
	c.Assert(cname, check.FitsTypeOf, &client.CnameAdd{})
}

func (s *S) TestCNameRemoveIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	cname, ok := manager.Commands["cname-remove"]
	c.Assert(ok, check.Equals, true)
	c.Assert(cname, check.FitsTypeOf, &client.CnameRemove{})
}

func (s *S) TestPlatformListIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	plat, ok := manager.Commands["platform-list"]
	c.Assert(ok, check.Equals, true)
	c.Assert(plat, check.FitsTypeOf, &admin.PlatformList{})
}
func (s *S) TestPlatformAddIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	plat, ok := manager.Commands["platform-add"]
	c.Assert(ok, check.Equals, true)
	c.Assert(plat, check.FitsTypeOf, &admin.PlatformAdd{})
}

func (s *S) TestAppSwapIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	cmd, ok := manager.Commands["app-swap"]
	c.Assert(ok, check.Equals, true)
	c.Assert(cmd, check.FitsTypeOf, &client.AppSwap{})
}

func (s *S) TestAppStartIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	start, ok := manager.Commands["app-start"]
	c.Assert(ok, check.Equals, true)
	c.Assert(start, check.FitsTypeOf, &client.AppStart{})
}

func (s *S) TestPluginInstallIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	command, ok := manager.Commands["plugin-install"]
	c.Assert(ok, check.Equals, true)
	c.Assert(command, check.FitsTypeOf, &client.PluginInstall{})
}

func (s *S) TestPluginRemoveIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	command, ok := manager.Commands["plugin-remove"]
	c.Assert(ok, check.Equals, true)
	c.Assert(command, check.FitsTypeOf, &client.PluginRemove{})
}

func (s *S) TestPluginListIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	command, ok := manager.Commands["plugin-list"]
	c.Assert(ok, check.Equals, true)
	c.Assert(command, check.FitsTypeOf, &client.PluginList{})
}

func (s *S) TestPluginBundleIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	command, ok := manager.Commands["plugin-bundle"]
	c.Assert(ok, check.Equals, true)
	c.Assert(command, check.FitsTypeOf, &client.PluginBundle{})
}

func (s *S) TestPluginLookup(c *check.C) {
	// Kids, do not try this at $HOME
	defer os.Setenv("HOME", os.Getenv("HOME"))
	tempHome, _ := filepath.Abs("client/testdata")
	os.Setenv("HOME", tempHome)

	fexec := exectest.FakeExecutor{}
	client.Execut = &fexec
	defer func() {
		client.Execut = nil
	}()
	manager = buildManager("tsuru")
	manager.Run([]string{"myplugin"})
	pluginPath := cmd.JoinWithUserDir(".tsuru", "plugins", "myplugin")
	c.Assert(fexec.ExecutedCmd(pluginPath, []string{}), check.Equals, true)
}

func (s *S) TestAppStopIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	stop, ok := manager.Commands["app-stop"]
	c.Assert(ok, check.Equals, true)
	c.Assert(stop, check.FitsTypeOf, &client.AppStop{})
}

func (s *S) TestAppDeployIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	deployCmd, ok := manager.Commands["app-deploy"]
	c.Assert(ok, check.Equals, true)
	c.Assert(deployCmd, check.FitsTypeOf, &client.AppDeploy{})
}

func (s *S) TestAppDeployRollbackIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	deployRollbackCmd, ok := manager.Commands["app-deploy-rollback"]
	c.Assert(ok, check.Equals, true)
	c.Assert(deployRollbackCmd, check.FitsTypeOf, &client.AppDeployRollback{})
}

func (s *S) TestAppDeployRollbackUpdateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	deployRollbackUpdateCmd, ok := manager.Commands["app-deploy-rollback-update"]
	c.Assert(ok, check.Equals, true)
	c.Assert(deployRollbackUpdateCmd, check.FitsTypeOf, &client.AppDeployRollbackUpdate{})
}

func (s *S) TestPlanListRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["plan-list"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &client.PlanList{})
}

func (s *S) TestChangePasswordIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	chpass, ok := manager.Commands["change-password"]
	c.Assert(ok, check.Equals, true)
	c.Assert(chpass, check.FitsTypeOf, &client.ChangePassword{})
}

func (s *S) TestResetPasswordIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	reset, ok := manager.Commands["reset-password"]
	c.Assert(ok, check.Equals, true)
	c.Assert(reset, check.FitsTypeOf, &client.ResetPassword{})
}

func (s *S) TestUserRemoveIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	rmUser, ok := manager.Commands["user-remove"]
	c.Assert(ok, check.Equals, true)
	c.Assert(rmUser, check.FitsTypeOf, &client.UserRemove{})
}

func (s *S) TestUserListIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	rmUser, ok := manager.Commands["user-list"]
	c.Assert(ok, check.Equals, true)
	c.Assert(rmUser, check.FitsTypeOf, &client.ListUsers{})
}

func (s *S) TestTeamRemoveIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	rmTeam, ok := manager.Commands["team-remove"]
	c.Assert(ok, check.Equals, true)
	c.Assert(rmTeam, check.FitsTypeOf, &client.TeamRemove{})
}

func (s *S) TestUserCreateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	user, ok := manager.Commands["user-create"]
	c.Assert(ok, check.Equals, true)
	c.Assert(user, check.FitsTypeOf, &client.UserCreate{})
}

func (s *S) TestTeamCreateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	create, ok := manager.Commands["team-create"]
	c.Assert(ok, check.Equals, true)
	c.Assert(create, check.FitsTypeOf, &client.TeamCreate{})
}

func (s *S) TestTeamListIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["team-list"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &client.TeamList{})
}

func (s *S) TestTeamInfoIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["team-info"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &client.TeamInfo{})
}

func (s *S) TestPoolListIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["pool-list"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &client.PoolList{})
}

func (s *S) TestAppUpdateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	change, ok := manager.Commands["app-update"]
	c.Assert(ok, check.Equals, true)
	c.Assert(change, check.FitsTypeOf, &client.AppUpdate{})
}

func (s *S) TestNodeAddIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	change, ok := manager.Commands["node-add"]
	c.Assert(ok, check.Equals, true)
	c.Assert(change, check.FitsTypeOf, &admin.AddNodeCmd{})
}

func (s *S) TestNodeRemoveIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	change, ok := manager.Commands["node-remove"]
	c.Assert(ok, check.Equals, true)
	c.Assert(change, check.FitsTypeOf, &admin.RemoveNodeCmd{})
}

func (s *S) TestNodeUpdateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	change, ok := manager.Commands["node-update"]
	c.Assert(ok, check.Equals, true)
	c.Assert(change, check.FitsTypeOf, &admin.UpdateNodeCmd{})
}

func (s *S) TestNodeListIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	change, ok := manager.Commands["node-list"]
	c.Assert(ok, check.Equals, true)
	c.Assert(change, check.FitsTypeOf, &admin.ListNodesCmd{})
}

func (s *S) TestNodeHealingInfoIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	change, ok := manager.Commands["node-healing-info"]
	c.Assert(ok, check.Equals, true)
	c.Assert(change, check.FitsTypeOf, &admin.GetNodeHealingConfigCmd{})
}

func (s *S) TestNodeHealingUpdateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	change, ok := manager.Commands["node-healing-update"]
	c.Assert(ok, check.Equals, true)
	c.Assert(change, check.FitsTypeOf, &admin.SetNodeHealingConfigCmd{})
}

func (s *S) TestNodeHealingDeleteIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	change, ok := manager.Commands["node-healing-delete"]
	c.Assert(ok, check.Equals, true)
	c.Assert(change, check.FitsTypeOf, &admin.DeleteNodeHealingConfigCmd{})
}

func (s *S) TestNodeRebalanceIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	change, ok := manager.Commands["node-rebalance"]
	c.Assert(ok, check.Equals, true)
	c.Assert(change, check.FitsTypeOf, &admin.RebalanceNodeCmd{})
}

func (s *S) TestServiceCreateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["service-create"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &admin.ServiceCreate{})
}

func (s *S) TestServiceDestroyIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["service-destroy"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &admin.ServiceDestroy{})
}

func (s *S) TestServiceDocGetIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["service-doc-get"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &admin.ServiceDocGet{})
}

func (s *S) TestServiceDocAddIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["service-doc-add"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &admin.ServiceDocAdd{})
}

func (s *S) TestServiceTemplateIsRegistered(c *check.C) {
	manager = buildManager("tsuru")
	list, ok := manager.Commands["service-template"]
	c.Assert(ok, check.Equals, true)
	c.Assert(list, check.FitsTypeOf, &admin.ServiceTemplate{})
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/networksecurity/v1beta1/client_tls_policy.proto

namespace Google\Cloud\NetworkSecurity\V1beta1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Request used by the DeleteClientTlsPolicy method.
 *
 * Generated from protobuf message google.cloud.networksecurity.v1beta1.DeleteClientTlsPolicyRequest
 */
class DeleteClientTlsPolicyRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. A name of the ClientTlsPolicy to delete. Must be in
     * the format `projects/*/locations/{location}/clientTlsPolicies/*`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $name = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. A name of the ClientTlsPolicy to delete. Must be in
     *           the format `projects/*/locations/{location}/clientTlsPolicies/*`.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Networksecurity\V1Beta1\ClientTlsPolicy::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. A name of the ClientTlsPolicy to delete. Must be in
     * the format `projects/*/locations/{location}/clientTlsPolicies/*`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. A name of the ClientTlsPolicy to delete. Must be in
     * the format `projects/*/locations/{location}/clientTlsPolicies/*`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

}


text:
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.events.ScriptContextAdapter;
import com.teamdev.jxbrowser.chromium.events.ScriptContextEvent;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;

/**
 * The sample demonstrates how to register and use ScriptContextListener to execute
 * custom JavaScript code before any other JavaScript on the loaded web page is executed.
 * Use this approach for injecting your custom JavaScript code when it's necessary.
 */
public class ScriptContextListenerSample {
    public static void main(String[] args) {
        Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addScriptContextListener(new ScriptContextAdapter() {
            @Override
            public void onScriptContextCreated(ScriptContextEvent event) {
                Browser browser = event.getBrowser();
                // Access and modify document.title property before any other
                // JavaScript on the loaded web page has been executed.
                JSValue document = browser.executeJavaScriptAndReturnValue("document");
                document.asObject().setProperty("title", "My title");
            }
        });

        browser.loadURL("http://google.com");
    }
}


text:
<?php

namespace Google\AdsApi\Dfp\v201702;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class NumberValue extends \Google\AdsApi\Dfp\v201702\Value
{

    /**
     * @var string $value
     */
    protected $value = null;

    /**
     * @param string $value
     */
    public function __construct($value = null)
    {
      $this->value = $value;
    }

    /**
     * @return string
     */
    public function getValue()
    {
      return $this->value;
    }

    /**
     * @param string $value
     * @return \Google\AdsApi\Dfp\v201702\NumberValue
     */
    public function setValue($value)
    {
      $this->value = $value;
      return $this;
    }

}


text:
({{ _("Welcome! We think you'll like it here") }}.)

{{ _("Your organization has been migrated from zulip.com to zulipchat.com! New service, same great conversation. We just need you to do one last thing.") }}

{{ _("Accept the Zulip terms of service") }}


text:
 #include "Object.h"
 #include "../exception.h"
 #include <iostream>
 #include <new>
 #include <stdlib.h>

 using namespace std;

bool svmObjectIsDead(Object &obj){
   return (obj.init.byte1 != OBJECT_ALIVE);
}

bool svmObjectHasInstance(Object &obj, int instance){
   return (obj.instanceData.byte1 == instance);
}

void svmInitHeapObject(Object &obj, int _typedef_, u1 objsz_t, int gc_status){
  if(!svmObjectIsDead(obj))
        return;

  obj.init.byte1 = OBJECT_ALIVE;
  obj.instanceData.byte1 = _typedef_;
  obj.instanceData.byte2 = gc_status;

  if(_typedef_ == TYPEDEF_GENERIC){
   obj.obj = new (nothrow) DataObject[1];

   if(obj.obj == nullptr)
      Exception("Object could not be created.", "OutOfMemoryError");
  }
  if(_typedef_ == TYPEDEF_STRING){
   obj.obj = new (nothrow) DataObject[1];
   obj.obj->strobj = new (nothrow) StringObject[1];
   obj.obj->strobj->array = new (nothrow) ArrayObject[1];

   if(obj.obj == nullptr || obj.obj->strobj == nullptr
      || obj.obj->strobj->array == nullptr)
       Exception("String object could not be created.", "OutOfMemoryError");
  }
  if(_typedef_ == TYPEDEF_GENERIC_ARRAY) {
   obj.obj = new (nothrow) DataObject[1];
   obj.obj->arrayobj = new (nothrow) ArrayObject[1];

   if(obj.obj == nullptr || obj.obj->arrayobj == nullptr)
       Exception("Array object could not be created.", "OutOfMemoryError");

   obj.obj->arrayobj->length = objsz_t.byte1;
   obj.obj->arrayobj->generic = (double*)malloc(objsz_t.byte1);

   if(obj.obj->arrayobj->generic == NULL)
       Exception("Array object could not be created.", "OutOfMemoryError");
  }
  if(_typedef_ == TYPEDEF_STRING_ARRAY) {
   obj.obj = new (nothrow) DataObject[1];
   obj.obj->arrayobj = new (nothrow) ArrayObject[1];

   if(obj.obj == nullptr || obj.obj->arrayobj == nullptr)
       Exception("String array object could not be created.", "OutOfMemoryError");

   obj.obj->arrayobj->length = objsz_t.byte1;
   obj.obj->arrayobj->strobj = (StringObject*)malloc(objsz_t.byte1);

   if(obj.obj->arrayobj->strobj == NULL)
       Exception("String array object could not be created.", "OutOfMemoryError");

   for(long i = 0; i < objsz_t.byte1; i++){ // initalize all strings
      obj.obj->arrayobj->strobj[i].array = new (nothrow) ArrayObject[1];

      if(obj.obj->arrayobj->strobj[i].array == nullptr)
        Exception("String array object could not be created.", "OutOfMemoryError");
   }

  }

  obj.size_t.byte1 = objsz_t.byte1;
}

long jmpLocation(Method &m){
    return m.ref.byte2;
}

long returnLocation(Method &m){
    return m.ref.byte1;
}

void svmSetGenericValue(Object &obj, double value){
    if(svmObjectIsDead(obj))
      Exception("Object was not initalized.", "DeadObjectException");

    obj.obj->generic = value;
}

double svmGetGenericValue(Object &obj){
    if(svmObjectIsDead(obj))
      Exception("Object was not initalized.", "DeadObjectException");

    return obj.obj->generic;
}

long __typedef(Object &obj){
    return obj.instanceData.byte1;
}

long __gcstatus(Object &obj){
    return obj.instanceData.byte2;
}

bool isObjArray(Object &obj){
    return (__typedef(obj) == TYPEDEF_GENERIC_ARRAY || __typedef(obj) == TYPEDEF_STRING_ARRAY);
}

void freeObj(Object &obj){
    if(!svmObjectIsDead(obj))
       return;

    free(obj.obj);
    obj.instanceData.byte2 = GC_IDLE;
    obj.size_t.byte1 = 0;
    obj.instanceData.byte1 = 0;
    obj.init.byte1 = OBJECT_DEAD;
}

// We perform a shallow delete
void svmDumpObject(Object &obj){
  gc_objc++;
  obj.size_t.byte1 = 0;
  obj.instanceData.byte1 = 0;
  obj.init.byte1 = OBJECT_DEAD;
  obj.instanceData.byte2 = GC_DIRTY;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;
using Newtonsoft.Json;

namespace MadcowModel
{
  public interface IBusinessEntity
  {
    int ID { get; set; }
  }

  public abstract class BusinessEntityBase: IBusinessEntity
  {
    public BusinessEntityBase()
    {
      ID = 0;
    }
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
  }

  public class WorkoutSet
  {
    [JsonConstructor]
    public WorkoutSet(int targetReps = 5, float weight = 0)
    {
      this.targetReps = targetReps;
      this.weight = weight;
    }

    public WorkoutSet(WorkoutSet other)
    {
      this.targetReps = other.targetReps;
      this.weight = other.weight;
    }
    public static int undoneRep = -1;

    // how many reps in this set
    public int completedReps = undoneRep;
    public int targetReps = 5;
    public float weight = 0;
  }

  public class WorkoutMovement
  {
    public enum Type
    {
      squat,
      benchPress,
      overheadPress,
      row,
      deadlift
    }
    public Type type = Type.squat;
    public List<WorkoutSet> sets = new List<WorkoutSet>();

    [JsonConstructor]
    public WorkoutMovement(Type type = Type.squat)
    {
      this.type = type;
    }
  }

  public class Workout: BusinessEntityBase
  {
    public enum Type
    {
      A,
      B,
      C
    }

    public List<WorkoutMovement> movements = new List<WorkoutMovement>();
    public Type type;
    public DateTime createdDate = DateTime.Now;

    [JsonConstructor]
    public Workout(Workout.Type type = Type.A)
    {
      this.type = type;
    }

    // helper

    [JsonIgnore]
    public WorkoutMovement squat
    {
      get
      {
        return getMovement(WorkoutMovement.Type.squat);
      }
    }

    [JsonIgnore]
    public WorkoutMovement benchPress
    {
      get
      {
        return getMovement(WorkoutMovement.Type.benchPress);
      }
    }

    [JsonIgnore]
    public WorkoutMovement row
    {
      get
      {
        return getMovement(WorkoutMovement.Type.row);
      }
    }

    [JsonIgnore]
    public WorkoutMovement overheadPress
    {
      get
      {
        return getMovement(WorkoutMovement.Type.overheadPress);
      }
    }

    [JsonIgnore]
    public WorkoutMovement deadlift
    {
      get
      {
        return getMovement(WorkoutMovement.Type.deadlift);
      }
    }

    private WorkoutMovement getMovement(WorkoutMovement.Type movementType)
    {
      foreach(var m in movements)
      {
        if (m.type == movementType)
        {
          return m;
        }
      }
      return null;
    }

  }

  public class WeightStatus
  {
    public enum WeightType
    {
      pound,
      kilogram
    }

    // lb or kg?
    public WeightType type = WeightType.pound;
    public float body = 0;
    public float squat = 0;
    public float benchPress = 0;
    public float overheadPress = 0;
    public float row = 0;
    public float deadlift = 0;
  }
}


text:
<?php
namespace tests\Repository\CompositeKey;

use PDO;
use PHPUnit_Framework_TestCase;
use tests\Utils\Composite\FixtureCompositeKey;
use WScore\Repository\Repo;

class GenericRepoTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var PDO
     */
    private $pdo;

    /**
     * @var Repo
     */
    private $repo;

    public function setup()
    {
        $this->pdo = new PDO('sqlite::memory:');
        $fixture = new FixtureCompositeKey($this->pdo);
        $fixture->createTables();
        $fixture->insertData();
        $this->repo = new Repo($this->pdo);
    }

    public function test0()
    {
        $fees = $this->repo->getRepository('fees', ['year', 'type', 'code']);
        $fee2016 = $fees->find(['year' => 2016]);
        $this->assertCount(4, $fee2016);
        foreach($fee2016 as $f) {
            $this->assertEquals(2016, $f->get('year'));
        }
    }

    /**
     * @test
     */
    public function findByKey_works_for_composite_keys()
    {
        $members = $this->repo->getRepository('members', ['type', 'code']);
        $main    = $members->findByKey(['type' => 1, 'code' => 100]);
        $this->assertEquals('Main Member', $main->get('name'));
    }

}


text:
package edu.gatech.gtri.typesafeconfigextensions.jndi;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigParseOptions;

import static edu.gatech.gtri.typesafeconfigextensions.internal.Check.checkNotNull;
import static edu.gatech.gtri.typesafeconfigextensions.jndi.JndiContexts.noContext;

final class NoContext extends BaseContext {

    private final OptionalJndiOriginDescription originDescription;
    private final ConfigParseOptions parseOptions;

    NoContext(
        OptionalJndiOriginDescription originDescription,
        ConfigParseOptions parseOptions
    ) {
        this.originDescription = checkNotNull(originDescription);
        this.parseOptions = checkNotNull(parseOptions);
    }

    @Override
    public JndiContext getContext(String path) {
        return noContext();
    }

    @Override
    public Config toConfig() {

        if (originDescription.isPresent()) {
            return ConfigFactory.empty(originDescription.get());
        }

        {
            String str = parseOptions.getOriginDescription();

            if (str != null) {
                return ConfigFactory.empty(str);
            }
        }

        return ConfigFactory.empty();
    }

    @Override
    public JndiContext
    withOriginDescription(OptionalJndiOriginDescription originDescription) {

        return new NoContext(
            checkNotNull(originDescription),
            parseOptions
        );
    }

    @Override
    public JndiContext withParseOptions(ConfigParseOptions parseOptions) {

        return new NoContext(
            originDescription,
            checkNotNull(parseOptions)
        );
    }
}


text:
Register

        <form ng-submit="submit()" name="register" class="form-horizontal" novalidate autocomplete="off">

              <fieldset>
                <legend>Personal Info</legend>

                <input name="firstName" ng-model="newUser.firstName" required type="text" placeholder="First Name" ng-minlength="3" ng-maxLength="20" />

The first name field is required

First name must be at least 3 characters long

First name must be no more than 20 characters long

                <input name="lastName" ng-model="newUser.lastName" required type="text" placeholder="Last Name" ng-minlength="3" ng-maxLength="20" />

The last name field is required

Last name must be at least 3 characters long

Last name must be no more than 20 characters long

                <input name="email" ng-model="newUser.email" required ng-pattern="/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i" type="email" placeholder="Email" />

The email field is required

Please enter a valid email address

                    <input class="checkbox-inline" type="checkbox" ng-model="newUser.isDriver" name="isDriver" id="is-driver" />I am a driver

              </fieldset>

              <fieldset>
                <legend>Account Info</legend>

                <input name="username" ng-model="newUser.username" required type="text" placeholder="Username" ng-minlength="4" ng-maxlength="15" />

The username field is required

Username must be at least 4 characters long

Username must be no more than 15 characters long

                <input name="password" ng-model="newUser.password" required type="password" placeholder="Password" ng-minlength="6" ng-maxlength="30" />

The password field is required

Password must be at least 6 characters long

Password must be no more than 30 characters long

                <input name="confirmPassword" ng-model="newUser.confirmPassword" required type="password" placeholder="Confirm Password" validate-equals='newUser.password' />

The confirm password field is required

Passwords do not match

                  <input name="carModel" ng-model="newUser.carModel" ng-required="newUser.isDriver" type="text" placeholder="Car Make/Model" ng-minlength="3" ng-maxlength="30" />

You must specify car make/model

Car make/model name must be at least 3 characters long

Car make/model name must be no more than 30 characters long

              </fieldset>

          <input ng-disabled="register.$invalid" type="submit" value="Submit" class="btn btn-success btn-sm" />
        </form>


text:
package io.getlime.push.errorhandling;

import io.getlime.core.rest.model.base.entity.Error;

/**
 * Web service communication error.
 *
 * @author Roman Strobl, roman.strobl@wultra.com
 */
public class WebServiceError extends Error {

    /**
     * Error code class.
     */
    public static class Code extends Error.Code {

        /**
         * Error code value.
         */
        public static final String ERROR_PA_SERVER_COMM = "ERROR_PA_SERVER_COMM";

        /**
         * Default constructor.
         */
        public Code() {
        }
    }
}


text:
package io.github.zwieback.relef.services;

import io.github.zwieback.relef.services.HeadersBuilder.Headers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners
public class HeadersBuilderTest {

    private static final String KEY = "key";
    private static final String VALUE = "value";

    @Test
    public void test_build_without_headers_should_be_empty() {
        Headers headers = HeadersBuilder.create().build();
        assertThat(headers).isEmpty();
    }

    @Test
    public void test_build_with_headers_should_not_be_empty() {
        Headers headers = HeadersBuilder.create().add(KEY, VALUE).build();
        assertThat(headers).containsExactly(entry(KEY, VALUE));
    }
}


text:
package org.apache.carbondata.datamap.bloom;

import java.io.IOException;
import java.util.List;

import org.apache.carbondata.common.annotations.InterfaceAudience;
import org.apache.carbondata.core.datamap.Segment;
import org.apache.carbondata.core.datastore.block.SegmentProperties;
import org.apache.carbondata.core.metadata.datatype.DataTypes;
import org.apache.carbondata.core.metadata.schema.table.column.CarbonColumn;
import org.apache.carbondata.core.util.ByteUtil;
import org.apache.carbondata.core.util.CarbonUtil;
import org.apache.carbondata.core.util.DataTypeUtil;

/**
 * BloomDataMap is constructed in CG level (blocklet level).
 * For each indexed column, a bloom filter is constructed to indicate whether a value
 * belongs to this blocklet. Bloom filter of blocklet that belongs to same block will
 * be written to one index file suffixed with .bloomindex. So the number
 * of bloom index file will be equal to that of the blocks.
 */
@InterfaceAudience.Internal
public class BloomDataMapWriter extends AbstractBloomDataMapWriter {

  BloomDataMapWriter(String tablePath, String dataMapName, List<CarbonColumn> indexColumns,
      Segment segment, String shardName, SegmentProperties segmentProperties,
      int bloomFilterSize, double bloomFilterFpp, boolean compressBloom)
      throws IOException {
    super(tablePath, dataMapName, indexColumns, segment, shardName, segmentProperties,
        bloomFilterSize, bloomFilterFpp, compressBloom);
  }

  protected byte[] convertNonDictionaryValue(int indexColIdx, Object value) {
    if (DataTypes.VARCHAR == indexColumns.get(indexColIdx).getDataType()) {
      return DataConvertUtil.getRawBytesForVarchar((byte[]) value);
    } else if (DataTypeUtil.isPrimitiveColumn(indexColumns.get(indexColIdx).getDataType())) {
      // get bytes for the original value of the no dictionary column
      return CarbonUtil.getValueAsBytes(indexColumns.get(indexColIdx).getDataType(), value);
    } else {
      return DataConvertUtil.getRawBytes((byte[]) value);
    }
  }

  @Override
  protected byte[] convertDictionaryValue(int indexColIdx, Object value) {
    // input value from onPageAdded in load process is byte[]

    // for dict columns including dictionary and date columns decode value to get the surrogate key
    int surrogateKey = CarbonUtil.getSurrogateInternal((byte[]) value, 0,
        ByteUtil.dateBytesSize());
    // store the dictionary key in bloom
    return CarbonUtil.getValueAsBytes(DataTypes.INT, surrogateKey);
  }
}


text:
Webapp to facilitate humans playing as the robots in RoboRally.  Will hand out cards, resolve play order, and keep track of various stats.

## Running

### Debian Linux

Install NodeJS (I've been running 4.2.6, I'm guessing any recent version will do)

    $ curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
    $ sudo apt-get install nodejs
Install the crazy pile of modules required to run webpack + babel (Last count for me was 165M in node_modules)

    $ npm install
Build frontend

    $ npm run build
Install perl modules required for backend

    $ sudo apt-get install libanyevent-perl libdata-uuid-perl libfile-slurp-perl libjson-perl libjson-xs-perl liblist-moreutils-perl libmojolicious-perl libtest-deep-perl
Go

    $ ./cyborg-rally
Browse to http://localhost:3000/

### Windows
Install NodeJS via the [Windows installer](http://nodejs.org/#download) from http://nodejs.org

    npm install
Build frontend

    npm run build
Download and install [Strawberry perl](http://strawberryperl.com/)

    cpan Mojolicious::Lite EV AnyEvent JSON JSON:XS Data::UUID List::MoreUtils Test::Deep
Go

    perl cyborg-rally
Browse to http://localhost:3000/

## Development

Run webpack in watch mode

    npm run watch
Run development server (optional, if you intend to modify files there)

    morbo cyborg-rally

Run your editor of choice

Use whatever developer tools you are comfortable in your browser.  Note: react has React Developer Tools for Chrome and Firefox.  I reccommend installing the extension.  In chrome, it often shows up under >> because it is the far right tab in developer tools.

The page is purposely very talky because I haven't taken the time to figure out web tests for react.  There are plenty of tests for the backend, but none for the UI.

If you want to run the backend tests: ```prove -l```

## Documentation

All documentation will be markdown files in the [lib](lib) and [js](js) directories covering the backend api and React frontend respectively.


text:
if( !("ui" in hello) ){
	hello.ui = {};
}

hello.ui.filePicker = function(options, callback){

	var prefix = 'fp-',
		win = window,
		doc = window.document,
		x,
		i=0;

	// Sanitize input vars
	if(typeof(options)==='function'){
		callback = options;
		options = {};
	}

	var main_el = create('div', {'class':prefix + "main"});
		var head_el = create('div', {'class':prefix + "head"}, main_el);
			var path_el = create('div', {'class':prefix + "path"}, head_el);
				var upload_btn = create('button', {'class':prefix + "upload_btn", "text":'Upload'}, path_el);
		var center_el = create('div', {'class':prefix + "center"}, main_el );
			var nav_el = create('div', {'class':prefix + "nav"}, center_el);
			var body_el = create('div', {'class':prefix + "body"}, center_el);
				var select_el = create('ul', {'class':prefix + "local", id:prefix + "local"}, body_el);
				var camera_el = create('div', {'class':prefix + "camera",id:prefix + "camera"}, body_el);
					var video_el = create('video', {'autoplay':true}, camera_el);
					var snap_btn = create('button', {}, camera_el);
		var footer_el = create('div', {'class':prefix + "footer"}, main_el);
			var info_el = create('span', {'class':prefix + "info", 'text':'none'}, footer_el);
			var done_el = create('button', {'class':prefix + "button", 'text':'Done'}, footer_el);
			var cancel_el = create('button', {'class':prefix + "cancel", 'text':'Cancel'}, footer_el);

	var frame_el;

	// Container
	if(!options.element){

		frame_el = options.element = create('div', {'class':prefix+"container"}, document.body);
		addEvent( options.element, 'click', function(e){
			if(e.target===options.element){
				close();
			}
		});
	}

	options.element.appendChild(main_el);

	var global_counter = 0,
		ref = [],
		current_bucket = select_el,
		current_network = null,
		current_folder = "local",
		upl; // Upload input file

	// Add Provider buttons
	var services = {
		"local" : "Local Computer"
	};

	var networks = hello.init();
	for(x in networks) if(networks.hasOwnProperty(x)&&"id" in networks[x]){
		switch(x){
			case "google":
				services[x + ":/me/files"] = "Drive";
				services[x + ":/me/albums"] = "Picasa";
			break;
			case "windows":
				services[x + ":/me/files"] = "SkyDrive";
			break;
			default:
				services[x + ":/me/files"] = x.replace(/^\w/, ucword );
		}
	}

	// Camera?
	// Does this browser support WebRTC?
	if(!win.navigator.getUserMedia){
		win.navigator.getUserMedia = (win.navigator.webkitGetUserMedia || win.navigator.mozGetUserMedia || win.navigator.msGetUserMedia);
	}

	// URL?
	if(!window.URL){
		window.URL = window.webkitURL;
	}

	if(window.URL && win.navigator.getUserMedia){
		services["camera"] = "Camera";
	}

	for(x in services){if(services.hasOwnProperty(x)){

		var btn = create('button', {
			'data-path' : x,
			'name' : x.match(/:/) ? services[x] : '',
			'html' : services[x],
		}, nav_el);

		if(x.indexOf(":")>-1){
			btn.className = x.replace(/\:.*$/,'');
		}
	}}

	// Add Control to all buttons
	var btns = nav_el.children;
	for(i=0;i<btns.length;i++){
		btns[i].onclick = selectBucket;
	}

	function selectBucket(){
		if(this.className.indexOf(prefix+"selected")===-1){
			this.className += ' '+prefix+"selected";
		}

		if(this.getAttribute('data-path') !== "local"){
			upload_btn.style.display = 'none';
		}
		else{
			upload_btn.style.display = 'inline-block';
		}

		for(var i=0;i<btns.length;i++){
			if(btns[i]!==this){
				btns[i].className = btns[i].className.replace(prefix+"selected", '');
			}
		}
		getBucket(this.getAttribute('data-path'), this.getAttribute('name'));
	}

	// Trigger first button
	btns[0].onclick();

	//
	// Buttons
	//
	info_el.onclick = function(){
		btns[0].onclick();
	};

	// Trigger upload into the current path
	addEvent(upload_btn, 'click', function(){

		// insert a form control and trigger the native picker
		if(!upl){
			upl = doc.createElement('input');
			upl.type='file';
			upl.multiple=true;

			var frm = doc.createElement('form');
			frm.style.opacity = 0;
			frm.style.position = 'absolute';
			frm.style.left = '-2000px';
			frm.style.top = 0;
			frm.appendChild(upl);

			doc.body.appendChild(frm);

			// listen to the onchange event
			// This will carry with it a reference to the file which the user has selected
			upl.addEventListener('change', function(e){
				if(!(e.target&&e.target.files)){
					return;
				}

				// Pass to our custom function for reading the file
				uploadFileList(e.target.files);
			},false);

		}

		// Create and Fire a mouse click event
		var clickEvent = doc.createEvent ("MouseEvent");
		clickEvent.initMouseEvent ("click", true, true, window, 0,
			event.screenX, event.screenY, event.clientX, event.clientY,
			event.ctrlKey, event.altKey, event.shiftKey, event.metaKey,
			0, null);

		// Lets ensure we are focussed on the element for which we are triggering the click event
		upl.focus();
		upl.dispatchEvent(clickEvent);
	});

	// Click
	cancel_el.onclick = function(){
		// Deselect all the selected
		for(var i=0;i<ref.length;i++){
			// set to false
			ref[i].toggleSelect(false);
		}

		close();

		callback({
			cancelled : true,
			files : []
		});
	};

	done_el.onclick = function(){

		var r = {files:[]};
		// Find all the selected elements
		for(var i=0;i<ref.length;i++){
			// set to true
			if(ref[i].selected){
				r.files.push(ref[i].item);
			}
		}
		// Close
		close();

		callback(r);
	};

	if(camera_el){
		var video_el = camera_el.getElementsByTagName('video')[0],
			snap_el = video_el.nextSibling;
		addEvent( video_el, 'click', function(){
			win.navigator.getUserMedia({video:true}, function(stream){
				// Create Object
				video_el.src = win.URL ? win.URL.createObjectURL(stream) : stream;
			}, function(e){
				console.log(e);
			});
		});

		addEvent(snap_el, 'click', function(){
			var blob = elementToBlob(video_el, "snapshot.png");
			// Create a new fileRef
			var pointer = new fileRef({
				name : "snapshot.png",
				type : blob.type,
				file : blob
			}, current_network, snap_el, true);
//			}, current_network, current_bucket, true);

			ref.push( pointer );

			readFile(blob, function(dataURL){

				// Update list
				pointer.update({
					picture : dataURL,
					thumbnail : dataURL
				});
			});
		});
	}

	//
	// DRAG and DROP
	//

	// stop FireFox from replacing the whole page with the file.
	main_el.ondragover = function () { main_el.className=prefix+"dragover"; return false; };
	main_el.ondragend = main_el.ondragleave = function () { main_el.className=""; return false; };

	// Add drop handler
	main_el.ondrop = function (e) {
		main_el.className="";
		e.preventDefault();
		e = e || window.event;
		var files = (e.files || e.dataTransfer.files);
		if(files){
			uploadFileList(files);
		}
	};

	// Creates a new Div if one doesn't exist already and loads the resource into the page
	function getBucket(path, name, parent){

		// Does it already exist?
		var id = prefix + path.replace(/\W/g,''),
			tab = doc.getElementById(id),
			label = doc.getElementById("label"+id);

		// Network
		var network = path.replace(/\:.*/, '');

		// Set current path
		if(!label&&name){
			label = doc.createElement('a');
			label.innerHTML = name;
			label.id = "label"+id;
			if(parent){
				label.setAttribute('data-parent', parent);
			}
			label.onclick = function(){
				getBucket(path, name, parent);
			};
			path_el.appendChild(label);
		}

		if(!tab){

			// create a new tab
			tab = doc.createElement('ul');
			tab.id = id;
			tab.innerHTML = "";
			body_el.appendChild(tab);

			// Remove loading
			var span = tab.getElementsByTagName('span')[0];

			// Login
			hello.login(network, function(auth){

				if(!auth||auth.error){
					span.setAttribute('data-message', "Signin failed, try again");
					span.setAttribute('data-animate', false);
					span.onclick = function(){
						tab.parentNode.removeChild(tab);
						getBucket(path, name, parent);
					};
					return;
				}

				span.setAttribute('data-message', "Loading files");

				// API
				hello.api(path, function(r){
					span.parentNode.removeChild(span);

					// Add files to the tab
					for(var i=0;i<r.data.length;i++){
						ref.push( new fileRef(r.data[i], network, tab) );
					}
				});
			});

		}

		// Hide the others
		// LISTS
		var a = body_el.children;
		for(var i=0;i=0;--i){
			if(parent&&a[i].id === "label"+parent){
				//parent = a[i].getAttribute('data-parent');
				a[i].style.display = "inline-block";
			}
			else if(a[i].id === "label"+id){
				a[i].style.display = "inline-block";
			}
			else{
				a[i].style.display = "none";
			}
		}

		// Update global
		current_folder = path;

		current_bucket = tab;

		current_network = network;

		// show this
		tab.style.display = 'block';

		// Update the upload btn
		upload_btn.innerHTML = name?"Upload to " + name.replace(/^[a-z]/,function(r){return r.toUpperCase();}):'Upload';
	}

	//
	// Each item is stored as a fileRef instance in the ref array
	// This function controls the element which it is applied upon.
	// Controlling when the elements update for generated content
	//
	function fileRef(item, network, bucket, selected){

		this.els = [];
		this.selected = false;

		this.item = {};

		// Item contents change
		this.update = function(item){
			if(!item){
				return this.item;
			}
			else {
				// Merge the two together
				this.item = hello.utils.merge(this.item, item);
			}

			// Loop through the elements and update their content
			for(var i=0;i<this.els.length;i++){
				this.els[i].getElementsByTagName('span')[0].innerHTML = this.item.name;
				if(this.item.thumbnail){
					this.els[i].getElementsByTagName('img')[0].src = this.item.thumbnail;
				}
			}
		};

		// Create an element in the given bucket,
		// adding on click event handlers
		this.create = function(bucket){
			var item = this.item;
			var self = this;
			var el = doc.createElement('li');
			el.title = item.name;
			el.innerHTML = ""
							+""+(item.name||'')+"";
			el.onclick = function(){
				// Is this a folder?
				if(item.type==='folder'||item.type==='album'){
					getBucket(network+":"+(item.files?item.files:item.id+"/files"), item.name, bucket.id );
				}
				else {
					// Toggle selected
					self.toggleSelect();
				}
			};
			// Add to bucket
			bucket.appendChild(el);

			// Add to local store
			this.els.push(el);

			return el;
		};

		this.toggleSelect = function(bool){

			if(bool===this.selected){
				// nothing
				return;
			}
			// else change

			// toggle
			this.selected = !this.selected;

			// Selected
			if(this.selected){
				// Does the element exist within the local bucket
				var local = false;
				for(i=0;i<this.els.length;i++){
					if( this.els[i].parentNode === select_el ){
						local=true;
						break;
					}
				}
				if(!local){
					// create it
					this.create(select_el);
				}
			}

			// Loop through the elements and update their content
			for(i=0;i<this.els.length;i++){
				this.els[i].className = this.selected ? "select" : "";
			}

			// get the number of selected items in ref and update
			info_el.innerHTML = ( this.selected ? ++global_counter : --global_counter );
		};

		// Create the initial element
		this.update(item);
		this.create(bucket);

		// if this is selected
		if(selected){
			this.toggleSelect();
		}
	}

	// Upload file list
	// Take all the photos in the FileList and create items with them
	function uploadFileList(files){

		// FileList
		if(!("FileList" in window) || (files instanceof File) || (files instanceof Blob)){
			// Make an Array
			files = [files];
		}

		var max = 20, len = files.length;
		if(len>max){
			var bool = confirm("You man only upload "+max+" files at a time");
			if(!bool){
				return;
			}
			len = max;
		}

		// Loop through the array and place the items on the page
		for(var i=0;i<len;i++){
			createRef(files[i]);
		}
	}

	// Do we upload them to the endpoint? Or load them into the page?
	function createRef(file){

		// Create a new fileRef
		var pointer = new fileRef({
			name : file.name,
			type : file.type,
			file : file
		}, current_network, current_bucket, true);

		ref.push( pointer );

		if(current_folder==="local"){
			readFile(file, function(dataURL){

				// Update list
				pointer.update({
					thumbnail : dataURL,
					picture : dataURL
				});
			});
		}
		else{
			// Upload the files to the current directory
			hello.api(current_folder, "post", {file: file}, function(r){
				// Once the files have been successfully upload lets update the pointer
				pointer.update({
					id : r.id,
					thumbnail : r.source,
					picture : r.source
				});
			});
		}
	}

	// readFile
	// Perform one operation at a time, to get a nice gradule load
	function readFile(file, callback){

		// Run this sequentially
		sync(function(){
			// Create a new FileReader Object
			var reader = new FileReader();

			// Set an onload handler because we load files into it Asynchronously
			reader.onload = function(e){

				// Print onto Canvas
				callback( this.result );

				// Run the next one;
				sync();
			};

			reader.readAsDataURL(file);
		});
	}

	// Function
	// Load
	var sync_list = [];
	function sync(func){
		if(func){
			// Add to the end
			sync_list.push(func);
		}
		else{
			// remove first one
			sync_list.shift();
		}
		if(sync_list.length===1||(sync_list.length>0&&!func)){
			// Remove it and run it.
			sync_list[0]();
		}
	}

	function elementToBlob(o,name,type){

		// Create a canvas tag
		// is canvas
		if(o instanceof win.HTMLVideoElement){
			var c = doc.createElement('canvas'),
				ctx = c.getContext('2d');
			c.width = parseInt(video_el.width||640, 10);
			c.height = parseInt(video_el.height||480, 10);

			ctx.drawImage(o, 0, 0, c.width, c.height);
			o = c;

			type = "image/jpeg";
		}

		// is canvas
		if(o instanceof win.HTMLCanvasElement){
			// turn into DataURL
			o = o.toDataURL(type||'image/png');
			name = name || "Canvas";
		}

		var binary;

		if(typeof(o)==='string'&&o.match(/^data\:/)){
			name = name || "DataURI";
			binary = atob(o.split(',')[1]);
			type = o.slice(o.indexOf(':')+1, o.indexOf(';') );
		}

		// Does the browser support the native Blob interface and Typed Arrays'?
		if("Blob" in window && "Uint8Array" in window){
			// convert the item to a native Blob object.
			var a = [];
			for(var i = 0; i < binary.length; i++) {
				a.push(binary.charCodeAt(i));
			}
			return new Blob([new Uint8Array(a)], {type: type});
		}
		else {
			throw "Cannot create blob";
		}
	}

	function close(){
		// is this a popup?
		win.close();

		var container = frame_el || main_el;

		// Hide the DOM element
		if(container&&container.parentNode){
			container.parentNode.removeChild(container);
		}
	}

	function addEvent(obj, eventName, listener) { //function to add event
		if (obj.addEventListener) {
			obj.addEventListener(eventName, listener, false);
		} else {
			obj.attachEvent("on" + eventName, listener);
		}
	}
	function remEvent(obj, eventName, listener) { //function to add event
		if (obj.removeEventListener) {
			obj.removeEventListener(eventName, listener);
		} else {
			obj.detachEvent("on" + eventName, listener);
		}
	}

	function create(type,attr,parent){
		var el = doc.createElement(type);
		for(var x in attr){
			if(x==='text'||x==='html'){
				el.innerHTML = attr[x];
			}
			else{
				el.setAttribute(x,attr[x]);
			}
		}
		if(parent){
			parent.appendChild(el);
		}
		return el;
	}

	function ucword(m){
		return m.toUpperCase();
	}

	addEvent(doc, "keydown", function self(e){
		if(e.keyCode===27){
			cancel_el.onclick();
			remEvent(doc, "keydown", self);
		}
		else if (e.keyCode === 13){
			done_el.onclick();
			remEvent(doc, "keydown", self);
		}
	});
}


text:
namespace Yoox.CampoCalcolato
{
    using System;
    using System.Data.Entity;
    using System.Linq;

    public class MyDbContext : DbContext
    {
        public MyDbContext()
            : base("name=MyConnectionString")
        {
        }

        public override int SaveChanges()
        {
            var selectedEntityList = ChangeTracker.Entries()
                                    .Where(x => x.Entity is INeedToCalculateSomething &&
                                    (x.State == EntityState.Added || x.State == EntityState.Modified));

            foreach(var entity in selectedEntityList)
            {
                var myEntity = (INeedToCalculateSomething)entity.Entity;
                myEntity.CalculateIt();
            }

            return base.SaveChanges();
        }

        public virtual DbSet<Ordine> Ordini { get; set; }
        public virtual DbSet<RigaOrdine> RigheOrdine { get; set; }
    }
}


text:
int main(int, char**)
{
  static_assert(std::is_nothrow_default_constructible<std::mutex>::value, "");
  std::mutex m;
  ((void)m);
  return 0;
}


text:
<!DOCTYPE html
  PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>DEMO_trabeculae_compression</title><meta name="generator" content="MATLAB 8.5"><link rel="schema.DC" href="http://purl.org/dc/elements/1.1/"><meta name="DC.date" content="2015-09-15"><meta name="DC.source" content="DEMO_FEBio_trabeculae_compression.m">

DEMO_trabeculae_compression

This demonstration shows the creation of a trabacular structure model derived from a triply periodic equation. The structure is meshed using tetrahedral elements and subjected to compression.

Contents

DEFINING GEOMETRY

DEFINE SMESH STRUCT FOR MESHING

MESH MODEL USING TETGEN

SET UP BOUNDARY CONDITIONS

CONSTRUCTING FEB MODEL

SAVING .FEB FILE

RUNNING FEBIO JOB

IMPORTING NODAL DISPLACEMENT RESULTS

CREATING NODE SET IN DEFORMED STATE

clear; close all; clc;

Plot settings

fontSize=15;
faceAlpha1=1;
faceAlpha2=0.5;
edgeColor=0.25*ones(1,3);
edgeWidth=1;
markerSize1=25;
boneColor=[1 0.8 0.7]*0.7;

path names

filePath=mfilename('fullpath');
savePath=fullfile(fileparts(filePath),'data','temp');

DEFINING GEOMETRY

The trabecular structure is here simulated using isosurfaces on the the "Gyroid triply periodic surface" function.

%Get periodic surface
n=25;
isoLevel=0.6; %Iso-surface level
[X,Y,Z]=meshgrid(linspace(-1.95*pi,1.95*pi,n));
V=[X(:) Y(:) Z(:)];
[R,~]=euler2DCM([0.25*pi 0.25*pi 0.25*pi]);
V=(R*V')';
S=triplyPeriodicMinimal(V(:,1),V(:,2),V(:,3),'g');
S=reshape(S,size(X));
[Fi,Vi] = isosurface(X,Y,Z,S,isoLevel); %main isosurface
Fi=fliplr(Fi); %Flip so normal faces outward
[Fc,Vc] = isocaps(X,Y,Z,S,isoLevel); %Caps to close the shape
Fc=fliplr(Fc); %Flip so normal faces outward

%Join model segments
V=[Vi;Vc];
F=[Fi;Fc+size(Vi,1)];

%Find top and bottom face sets
[Nc]=patchNormal(Fc,Vc);
logicTop_Fc=Nc(:,3)>0.5;
logicTop=[false(size(Fi,1),1);logicTop_Fc];

[Nc]=patchNormal(Fc,Vc);
logicBottom_Fc=Nc(:,3)<-0.5;
logicBottom=[false(size(Fi,1),1);logicBottom_Fc];

%Merge nodes
[~,ind1,ind2]=unique(pround(V,5),'rows');
V=V(ind1,:);
F=ind2(F);

%Smoothen surface mesh (isosurface does not yield high quality mesh)
indRigid=F(size(Fi,1)+1:end,:);
indRigid=unique(indRigid(:));
cPar.n=50;
cPar.RigidConstraints=indRigid; %Boundary nodes are held on to
cPar.Method='tHC';
[~,IND_V]=patchIND(F,V,2);
[V]=patchSmooth(F,V,IND_V,cPar);

cFigure;
title('Gyroid derived model of trabecular structure','FontSize',fontSize);
xlabel('X','FontSize',fontSize);ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize); hold on;
patch('Faces',F,'Vertices',V,'FaceColor',boneColor,'edgeColor',edgeColor,'lineWidth',edgeWidth,'FaceAlpha',1);
patch('Faces',F(logicTop,:),'Vertices',V,'FaceColor','none','EdgeColor','r','lineWidth',edgeWidth,'FaceAlpha',1);
patch('Faces',F(logicBottom,:),'Vertices',V,'FaceColor','none','EdgeColor','b','lineWidth',edgeWidth,'FaceAlpha',1);
% plotV(V(indRigid,:),'k.','MarkerSize',markerSize1);
axis equal; view(3); axis tight; axis vis3d; grid on;
set(gca,'FontSize',fontSize);
camlight headlight;

Prepare for meshing by finding interior point

[~,indInner]=max(S(:)); %Due to isosurface spec. we can use this
V_in_1=[X(indInner) Y(indInner) Z(indInner)];

faceBoundaryMarker=ones(size(F,1),1);
faceBoundaryMarker(logicTop)=2;
faceBoundaryMarker(logicBottom)=3;

cFigure;
title('Inner point visualization','FontSize',fontSize);
xlabel('X','FontSize',fontSize);ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize); hold on;
patch('Faces',F,'Vertices',V,'FaceColor',boneColor,'edgeColor','none','FaceAlpha',0.5);
plotV(V_in_1,'r.','MarkerSize',markerSize1);

axis equal; view(3); axis tight; axis vis3d; grid on;
set(gca,'FontSize',fontSize);
camlight headlight;
drawnow;

DEFINE SMESH STRUCT FOR MESHING

stringOpt='-pq1.2AaYQ';
modelNameEnd='tempModel';
modelName=fullfile(savePath,modelNameEnd);
smeshName=[modelName,'.smesh'];

smeshStruct.stringOpt=stringOpt;
smeshStruct.Faces=F;
smeshStruct.Nodes=V;
smeshStruct.holePoints=[];
smeshStruct.faceBoundaryMarker=faceBoundaryMarker; %Face boundary markers
smeshStruct.regionPoints=V_in_1; %region points
smeshStruct.regionA=[0.5];
smeshStruct.minRegionMarker=2; %Minimum region marker
smeshStruct.smeshName=smeshName;

MESH MODEL USING TETGEN

[meshOutput]=runTetGenSmesh(smeshStruct);
%runTetView(meshOutput.loadNameStruct.loadName_ele);

% Accessing the model element and patch data
FT=meshOutput.faces;
Fb=meshOutput.facesBoundary;
Cb=meshOutput.boundaryMarker;
VT=meshOutput.nodes;
C=meshOutput.faceMaterialID;
E=meshOutput.elements;
elementMaterialIndices=meshOutput.elementMaterialID;

Warning: runTetGenSmesh has been renamed to runTetGen. runTetGenSmesh will be
removed in future releases.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--- TETGEN Tetrahedral meshing --- 15-Sep-2015 20:33:25
Warning: smeshStruct.smeshName input will be replaced by smeshStruct.modelName
in future releases!

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--- Writing SMESH file --- 15-Sep-2015 20:33:25
Warning: smeshStruct.smeshName input will be replaced by smeshStruct.modelName
in future releases!
----> Adding node field
----> Adding facet field
----> Adding holes specification
----> Adding region specification
--- Done --- 15-Sep-2015 20:33:25
--- Running TetGen to mesh input boundary--- 15-Sep-2015 20:33:25
Opening D:\MATLAB\GIBBON\trunk\lib_ext\tetGen\tempFiles\tempModel.smesh.
--- Done --- 15-Sep-2015 20:33:26

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--- Importing TetGen files --- 15-Sep-2015 20:33:26
--- Done --- 15-Sep-2015 20:33:26

SET UP BOUNDARY CONDITIONS

%List of nodes to fix
bcFixList=Fb(Cb==3,:);
bcFixList=unique(bcFixList(:));

%List of nodes to prescribe displacement for
bcPrescribeList=Fb(Cb==2,:);
bcPrescribeList=unique(bcPrescribeList(:));

%Define displacement magnitudes
displacementMagnitude=[0 0 -1.5];

%Plot model boundaries
hf1=cFigure;
title('Model boundaries and BC nodes','FontSize',fontSize);
xlabel('X','FontSize',fontSize); ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize); hold on;
hps=patch('Faces',Fb,'Vertices',VT,'FaceColor','flat','CData',Cb,'lineWidth',edgeWidth,'edgeColor',edgeColor,'FaceAlpha',faceAlpha1);
plotV(VT(bcPrescribeList,:),'k.','MarkerSize',markerSize1);
plotV(VT(bcFixList,:),'k.','MarkerSize',markerSize1);
view(3); axis tight;  axis equal;  grid on;
set(gca,'FontSize',fontSize);
cMap=[boneColor;[1 0 0]; [0 1 0]];
colormap(cMap);
camlight headlight;
drawnow;

CONSTRUCTING FEB MODEL

FEB_struct.febio_spec.version='2.0';
FEB_struct.Module.Type='solid';

% Defining file names
FEB_struct.run_filename=[modelName,'.feb']; %FEB file name
FEB_struct.run_logname=[modelName,'.txt']; %FEBio log file name

febMatID=elementMaterialIndices;
febMatID(elementMaterialIndices==-2)=1;

%Creating FEB_struct
FEB_struct.Geometry.Nodes=VT;
FEB_struct.Geometry.Elements={E}; %The element sets
FEB_struct.Geometry.ElementType={'tet4'}; %The element types
FEB_struct.Geometry.ElementMat={febMatID};
FEB_struct.Geometry.ElementsPartName={'Trabeculae'};

% DEFINING MATERIALS
c1=1e-3;
k=c1*1e3;
FEB_struct.Materials{1}.Type='Mooney-Rivlin';
FEB_struct.Materials{1}.Name='cube_mat';
FEB_struct.Materials{1}.Properties={'c1','c2','k'};
FEB_struct.Materials{1}.Values={c1,0,k};

%Control section
FEB_struct.Control.AnalysisType='static';
FEB_struct.Control.Properties={'time_steps','step_size',...
    'max_refs','max_ups',...
    'dtol','etol','rtol','lstol'};
FEB_struct.Control.Values={20,0.05,...
    25,0,...
    0.001,0.01,0,0.9};
FEB_struct.Control.TimeStepperProperties={'dtmin','dtmax','max_retries','opt_iter','aggressiveness'};
FEB_struct.Control.TimeStepperValues={1e-4,0.05,5,10,1};

%Defining node sets
FEB_struct.Geometry.NodeSet{1}.Set=bcFixList;
FEB_struct.Geometry.NodeSet{1}.Name='bcFixList';
FEB_struct.Geometry.NodeSet{2}.Set=bcPrescribeList;
FEB_struct.Geometry.NodeSet{2}.Name='bcPrescribeList';

%Adding BC information
FEB_struct.Boundary.Fix{1}.bc='x';
FEB_struct.Boundary.Fix{1}.SetName=FEB_struct.Geometry.NodeSet{1}.Name;
FEB_struct.Boundary.Fix{2}.bc='y';
FEB_struct.Boundary.Fix{2}.SetName=FEB_struct.Geometry.NodeSet{1}.Name;
FEB_struct.Boundary.Fix{3}.bc='z';
FEB_struct.Boundary.Fix{3}.SetName=FEB_struct.Geometry.NodeSet{1}.Name;

FEB_struct.Boundary.Prescribe{1}.SetName=FEB_struct.Geometry.NodeSet{2}.Name;
FEB_struct.Boundary.Prescribe{1}.Scale=displacementMagnitude(1);
FEB_struct.Boundary.Prescribe{1}.bc='x';
FEB_struct.Boundary.Prescribe{1}.lc=1;
FEB_struct.Boundary.Prescribe{1}.Type='relative';
FEB_struct.Boundary.Prescribe{2}.SetName=FEB_struct.Geometry.NodeSet{2}.Name;
FEB_struct.Boundary.Prescribe{2}.Scale=displacementMagnitude(2);
FEB_struct.Boundary.Prescribe{2}.bc='y';
FEB_struct.Boundary.Prescribe{2}.lc=1;
FEB_struct.Boundary.Prescribe{2}.Type='relative';
FEB_struct.Boundary.Prescribe{3}.SetName=FEB_struct.Geometry.NodeSet{2}.Name;
FEB_struct.Boundary.Prescribe{3}.Scale=displacementMagnitude(3);
FEB_struct.Boundary.Prescribe{3}.bc='z';
FEB_struct.Boundary.Prescribe{3}.lc=1;
FEB_struct.Boundary.Prescribe{3}.Type='relative';

%Load curves
FEB_struct.LoadData.LoadCurves.id=1;
FEB_struct.LoadData.LoadCurves.type={'linear'};
FEB_struct.LoadData.LoadCurves.loadPoints={[0 0;1 1;]};

%Adding output requests
FEB_struct.Output.VarTypes={'displacement','stress','relative volume'};

%Specify log file output
run_node_output_name=[modelNameEnd,'_node_out.txt'];
FEB_struct.run_output_names={run_node_output_name};
FEB_struct.output_types={'node_data'};
FEB_struct.data_types={'ux;uy;uz'};

SAVING .FEB FILE

FEB_struct.disp_opt=0; %Display waitbars option
febStruct2febFile(FEB_struct);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--- Writing FEBio XML object --- 15-Sep-2015 20:33:27
Adding Module level
Adding Control level
Adding Globals level
Adding Material level
Adding Geometry level
----> Adding node field
----> Adding element field
----> Adding tet4 element entries....
----> Adding NodeSet field
Adding Boundary level
----> Defining fix type boundary conditions
----> Defining prescribe type boundary conditions
Adding LoadData level
----> Defining load curves
Adding Output level
----> Adding plotfile field
----> Adding logfile field
Writing .feb file
--- Done --- 15-Sep-2015 20:33:30

RUNNING FEBIO JOB

% FEBioRunStruct.FEBioPath='C:\Program Files\febio2-2.2.6\bin\FEBio2.exe';
FEBioRunStruct.run_filename=FEB_struct.run_filename;
FEBioRunStruct.run_logname=FEB_struct.run_logname;
FEBioRunStruct.disp_on=1;
FEBioRunStruct.disp_log_on=1;
FEBioRunStruct.runMode='external';%'internal';
FEBioRunStruct.t_check=0.25; %Time for checking log file (dont set too small)
FEBioRunStruct.maxtpi=1e99; %Max analysis time
FEBioRunStruct.maxLogCheckTime=3; %Max log file checking time

[runFlag]=runMonitorFEBio(FEBioRunStruct);%START FEBio NOW!!!!!!!!

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--- STARTING FEBIO JOB --- 15-Sep-2015 20:33:30
Waiting for log file...
Proceeding to check log file...15-Sep-2015 20:33:31
------- converged at time : 0.05
------- converged at time : 0.1
------- converged at time : 0.15
------- converged at time : 0.2
------- converged at time : 0.25
------- converged at time : 0.3
------- converged at time : 0.35
------- converged at time : 0.4
------- converged at time : 0.45
------- converged at time : 0.5
------- converged at time : 0.55
------- converged at time : 0.6
------- converged at time : 0.65
------- converged at time : 0.7
------- converged at time : 0.75
------- converged at time : 0.8
------- converged at time : 0.85
------- converged at time : 0.9
------- converged at time : 0.95
------- converged at time : 1
--- Done --- 15-Sep-2015 20:33:48

IMPORTING NODAL DISPLACEMENT RESULTS

Importing nodal displacements from a log file

 fName=fullfile(savePath,FEB_struct.run_output_names{1});
[~, N_disp_mat,~]=importFEBio_logfile(fName); %Nodal displacements

DN=N_disp_mat(:,2:end,end); %Final nodal displacements

CREATING NODE SET IN DEFORMED STATE

VT_def=VT+DN;
DN_magnitude=sqrt(sum(DN.^2,2));

Plotting the deformed model

[CF]=vertexToFaceMeasure(F,DN_magnitude);

hf1=cFigure;
title('The deformed model','FontSize',fontSize);
xlabel('X','FontSize',fontSize); ylabel('Y','FontSize',fontSize); zlabel('Z','FontSize',fontSize); hold on;

hps=patch('Faces',F,'Vertices',VT_def,'FaceColor','flat','CData',CF,'lineWidth',edgeWidth,'edgeColor',edgeColor,'FaceAlpha',faceAlpha1);

view(3); axis tight;  axis equal;  grid on;
colormap jet; colorbar;
camlight headlight;
set(gca,'FontSize',fontSize);
drawnow;

GIBBON www.gibboncode.org

Kevin Mattheus Moerman, gibbon.toolbox@gmail.com

Published with MATLAB® R2015a


text:
package org.organicdesign.fp.collections;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.organicdesign.fp.FunctionUtils;

import java.util.Arrays;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

import static org.junit.Assert.*;
import static org.organicdesign.fp.StaticImports.vec;
import static org.organicdesign.fp.testUtils.EqualsContract.equalsDistinctHashCode;
import static org.organicdesign.fp.testUtils.EqualsContract.equalsSameHashCode;

@RunWith(JUnit4.class)
public class PersistentTreeSetTest {

    public static final Comparator<String> STR_LEN_COMP = (a, b) -> a.length() - b.length();

    @Test public void javaBug() {
        // This illustrates the bug in java
        SortedSet<String> ss = new TreeSet<>(STR_LEN_COMP);
        ss.add("bye");
        ss.add("hello");

        SortedSet<String> ss2 = new TreeSet<>();
        ss2.add("bye");
        ss2.add("12345");

        // Uses comparator.compare(a, b) == 0 to define equality.  This is good.
        assertNotEquals(ss2, ss);

        // Doesn't care that the order is different.  This is the bug!
        assertEquals(ss, ss2);

        // Because ordering is a critical component of SortedSets, they should not be compared to Sets.
        // Yet TreeSet TreeSet inherits .equals() from AbstractSet, which doesn't care about comparators
        // or ordering.  It relies on size() and containsAll(). containsAll() calls TreeSet.contains()
        // which effectively uses its comparator.compare(a,b) == 0 instead of equals.  TreeSet.contains()
        // is correct, because the comparator rules all the other operations on this TreeSet.
        // Mixing equals() with it would muddy the waters.
        //
        // The best fix would be for TreeSet to implement equals() to take into account ordering.
        // So the subtle issue here is that ordering (whether the comparator returns positive or negative)
        // doesn't matter.  But equality is still determined by whether or not the comparator returns 0.  Not by a
        // call to equals().  That is incredibly weird.  I don't even know what to do about that.
    }

    @Test public void assocAndGet() {
        PersistentTreeSet<String> s1 = PersistentTreeSet.empty();
        assertTrue(s1.isEmpty());

        PersistentTreeSet<String> s2 = s1.put("one");
        assertFalse(s2.isEmpty());

        // Prove m1 unchanged
        assertEquals(0, s1.size());
        assertFalse(s1.contains("one"));

        // Show m2 correct.
        assertEquals(1, s2.size());

        assertTrue(s2.contains("one"));
        assertFalse(s2.contains("two"));

        //noinspection EqualsWithItself
        assertTrue(s1.equals(s1));

        //noinspection EqualsWithItself
        assertTrue(s2.equals(s2));
        assertNotEquals(s1.hashCode(), s2.hashCode());
        assertFalse(s1.equals(s2));
        assertFalse(s2.equals(s1));

        PersistentTreeSet<Integer> s3 = PersistentTreeSet.<Integer>empty().put(1).put(2).put(3);

        assertEquals(3, s3.size());
        assertTrue(s3.contains(1));
        assertTrue(s3.contains(2));
        assertTrue(s3.contains(3));
        assertFalse(s3.contains(4));

        assertArrayEquals(new Integer[]{1, 2, 3}, s3.toArray());

        assertArrayEquals(new Integer[]{1, 2, 3},
                          PersistentTreeSet.<Integer>empty().put(3).put(2).put(1).toArray());
    }

    @Test public void disjoin() {
        PersistentTreeSet<String> s1 = PersistentTreeSet.empty();
        assertTrue(s1.isEmpty());

        PersistentTreeSet<String> s2 = s1.put("one");
        assertFalse(s2.isEmpty());

        PersistentTreeSet<String> s3 = s1.without("one");
        assertEquals(0, s3.size());
        assertTrue(s3.isEmpty());
        assertEquals(s1.hashCode(), s3.hashCode());
        assertTrue(s1.equals(s3));
        assertTrue(s3.equals(s1));

        PersistentTreeSet<String> s4 = s2.without("two");
        assertEquals(1, s4.size());
        assertEquals(s2.hashCode(), s4.hashCode());
        assertTrue(s2.equals(s4));
        assertTrue(s4.equals(s2));
    }

    @Test public void ordering() {
        PersistentTreeSet<Integer> s1 = PersistentTreeSet.of(Arrays.asList(5, 2, 4, 1, 3));
        assertEquals(5, s1.size());
        assertEquals(Integer.valueOf(1), s1.first());
        assertEquals(Integer.valueOf(5), s1.last());
        assertArrayEquals(new Integer[]{1, 2, 3, 4, 5},
                          s1.toArray());

        assertArrayEquals(new Integer[] {1,2,3,4,5},
                          s1.subSet(Integer.MIN_VALUE, Integer.MAX_VALUE).toArray());

        assertArrayEquals(new Integer[] {1,2,3,4,5},
                          s1.subSet(-99, 99).toArray());

        assertArrayEquals(new Integer[]{1, 2, 3, 4, 5},
                          s1.subSet(1, 6).toArray());

        assertArrayEquals(new Integer[]{1, 2, 3, 4},
                          s1.subSet(1, 5).toArray());

        assertArrayEquals(new Integer[]{2, 3, 4, 5},
                          s1.subSet(2, 6).toArray());

        assertArrayEquals(new Integer[]{3},
                          s1.subSet(3, 4).toArray());

        assertArrayEquals(new Integer[0],
                          s1.subSet(3, 3).toArray());

        assertNull(s1.comparator());

        PersistentTreeSet<String> s2 = PersistentTreeSet.ofComp(STR_LEN_COMP,
                                                                Arrays.asList("hello", "an", "work", "b", "the"));
        assertEquals(STR_LEN_COMP, s2.comparator());
        assertEquals(5, s2.size());
        assertEquals("b", s2.first());
        assertEquals("hello", s2.last());

        assertEquals(STR_LEN_COMP, s2.subSet("", "                 ").comparator());

        assertArrayEquals(new String[]{"b", "an", "the", "work", "hello"},
                          s2.toArray());

        assertArrayEquals(new String[]{"b", "an", "the", "work", "hello"},
                          s2.subSet("", "                 ").toArray());

        assertArrayEquals(new String[] {"b", "an", "the", "work", "hello"},
                          s2.subSet("", "._._._").toArray());

        assertArrayEquals(new String[]{"b", "an", "the", "work", "hello"},
                          s2.subSet("z", "aaaaaa").toArray());

        assertEquals(STR_LEN_COMP, s2.subSet("a", "four").comparator());

        assertArrayEquals(new String[]{"b", "an", "the"},
                          s2.subSet("a", "four").toArray());

        assertArrayEquals(new String[] {"an", "the", "work", "hello"},
                          s2.subSet("UH", "SLDFKJS").toArray());

        assertArrayEquals(new String[] {"the"},
                          s2.subSet("THE", "JUNK").toArray());

        assertArrayEquals(new String[0],
                          s2.subSet("the", "the").toArray());

        assertEquals(STR_LEN_COMP, s2.comparator());
    }

    @Test public void equality() {
        PersistentTreeSet<String> s1 = PersistentTreeSet.of(Arrays.asList("hello", "an", "work", "b", "the"));

        SortedSet<String> ss1 = new TreeSet<>();
        ss1.add("the");
        ss1.add("b");
        ss1.add("work");
        ss1.add("an");
        ss1.add("hello");
        equalsDistinctHashCode(s1, ss1, FunctionUtils.unmodSortedSet(ss1),
                               PersistentTreeSet.of(Arrays.asList("hello", "an", "work", "the")));

        // Really, you need to read the JavaDoc for PersistentTreeSet.equals() to understand the bizarre notion of
        // equality being checked here.
        equalsDistinctHashCode(s1, ss1, FunctionUtils.unmodSortedSet(ss1),
                               PersistentTreeSet.ofComp(STR_LEN_COMP,
                                                        Arrays.asList("helloz", "an", "work", "b", "the")));

        PersistentTreeSet<String> s2 = PersistentTreeSet.ofComp(STR_LEN_COMP,
                                                                Arrays.asList("hello", "an", "work", "b", "the"));

        // This illustrates the bug in java
        SortedSet<String> ss = new TreeSet<>(STR_LEN_COMP);
        ss.add("the");
        ss.add("b");
        ss.add("work");
        ss.add("an");
        ss.add("hello");
//
//        SortedSet<String> ss2 = new TreeSet<>();
//        ss2.add("the");
//        ss2.add("b");
//        ss2.add("work");
//        ss2.add("an");
//        ss2.add("Hello");
//
//        // Yeah, totally bizarre.  Doesn't care that the order is different.
//        assertEquals(ss, ss2);
//        assertEquals(ss2, ss);
//
//
        equalsDistinctHashCode(s2, ss, FunctionUtils.unmodSortedSet(ss),
                               PersistentTreeSet.ofComp(STR_LEN_COMP,
                                                        Arrays.asList("helloz", "an", "work", "the")));

//        assertEquals(s2, yadda);
//        assertEquals(ss, yadda);
//        assertEquals(unmodSortedSet(ss), yadda);
//
//        assertNotEquals(yadda, s2);
//        assertNotEquals(yadda, ss);
//        assertNotEquals(yadda, unmodSortedSet(ss));

        equalsDistinctHashCode(s2, ss, FunctionUtils.unmodSortedSet(ss),
                               PersistentTreeSet.of(Arrays.asList("an", "helloz", "work", "b", "the")));

        equalsSameHashCode(s2,
                           PersistentTreeSet.ofComp(STR_LEN_COMP,
                                                    vec("an", "hello", "work", "the")).put("b"),
                           PersistentTreeSet.ofComp(STR_LEN_COMP,
                                                    vec("an", "b", "work")).put("hello").put("the"),
                           PersistentTreeSet.of(vec("an", "hello", "work", "b", "the")));

    }

    // TODO: Finish this!
    @Test public void testToString() {
        PersistentTreeSet<String> s2 = PersistentTreeSet.ofComp(STR_LEN_COMP);

        assertEquals("PersistentTreeSet(b,an,the,work,hello)",
                     s2.put("hello").put("an").put("work").put("b").put("the").toString());
    }

}


text:
@implementation TKTumblr

@synthesize delegate, email, password, currentPost, currentElementName, requestedPost, currentTumblelog;

- (id)initWithEmail:(NSString *)theEmail andPassword:(NSString *)thePassword
{
    if ((self = [super init]) != nil) {
        self.email = theEmail;
        self.password = thePassword;
        self.currentTumblelog = nil;
        self.currentPost = nil;
        self.currentElementName = nil;
        self.requestedPost = nil;
    }
    return self;
}

- (TKPost *)postWithID:(NSNumber *)thePostID andDomain:(NSString *)theDomain
{
    TKTumblrReadRequest *theReadRequest = [[TKTumblrReadRequest alloc] initWithPostID:thePostID andDomain:theDomain];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:[theReadRequest endpoint]];
    id previousDelegate = [self delegate];
    [self setDelegate:self];
    [parser setDelegate:self];
    [parser parse];
    [self setDelegate:previousDelegate];

    TKPost *thePost = nil;

    if (requestedPost) {
        thePost = [self requestedPost];
        [self setRequestedPost:nil];
    }

    return thePost;
}

- (void)postsWithReadRequest:(TKTumblrReadRequest *)theReadRequest
{
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:[theReadRequest endpoint]];
    [parser setDelegate:self];
    [parser parse];
}

- (BOOL)uploadPost:(TKPost *)thePost
{
    return [self uploadPost:thePost withDomain:nil];
}

- (BOOL)uploadPost:(TKPost *)thePost withDomain:(NSString *)theDomain
{
    NSMutableDictionary *postDict = (NSMutableDictionary *)[self attributesAsDictionary];

    if (theDomain)
        [postDict setObject:theDomain forKey:@"group"];

    [postDict addEntriesFromDictionary:[thePost attributesAsDictionary]];

    NSData *postBody = [postDict multipartMIMEData];
    NSMutableURLRequest *theURLRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://www.tumblr.com/api/write"]];

    [theURLRequest setHTTPMethod:@"POST"];
    [theURLRequest setValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"];
    [theURLRequest setValue:[NSString stringWithFormat:@"%d", [postBody length]] forHTTPHeaderField:@"Content-Length"];
    [theURLRequest setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", [NSString MIMEBoundary]] forHTTPHeaderField:@"Content-Type"];
    [theURLRequest setHTTPBody:postBody];

    if (delegate && [delegate respondsToSelector:@selector(tumblrWillUploadPost:withDomain:)]) {
        [delegate tumblrWillUploadPost:thePost withDomain:theDomain];
    }

    NSError *error = nil;
    NSHTTPURLResponse *theURLResponse = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:theURLRequest
                                                 returningResponse:&theURLResponse
                                                             error:&error];

    // Release the request before we can enter some potentially dangerous
    // code path.

    // Bail out quickly if NSURLConnection populated error.
    if (([theURLResponse statusCode] != TKTumblrCreated)) {
        if (delegate && [delegate respondsToSelector:@selector(tumblrDidFailToUploadPost:withDomain:returnCode:)]) {
            [delegate tumblrDidFailToUploadPost:thePost
                                     withDomain:theDomain
                                     returnCode:(TKTumblrResponseReturnCode)[theURLResponse statusCode]];
        }
        return NO;
    }

    // The following code will only execute when we get a TKTumblrCreated response, so it's
    // safe to assume that responseData will have only the postID of the post we created.
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *postID = [formatter numberFromString:[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]];

    if (delegate && [delegate respondsToSelector:@selector(tumblrDidUploadPost:withDomain:postID:)]) {
        [delegate tumblrDidUploadPost:thePost withDomain:theDomain postID:postID];
    }

    return YES;
}

- (NSDictionary *)attributesAsDictionary
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                 email, @"email",
                                 password, @"password",
                                 nil];
    return dict;
}

- (NSArray *)tumblelogs
{
    NSString *theURLString = [NSString stringWithFormat:@"https://www.tumblr.com/api/authenticate?email=%@&password=%@",
                              [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                              [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURL *theURL = [NSURL URLWithString:theURLString];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:theURL];
    [parser setDelegate:self];
    [parser parse];

    return nil;
}

#pragma mark NSXMLParserDelegate

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    self.currentElementName = elementName;

    if ([elementName isEqualToString:@"post"]) {
        self.currentPost = [TKPost postWithAttributes:attributeDict];
    }
    else if ([elementName isEqualToString:@"tumblelog"]) {
        self.currentTumblelog = [TKTumblelog tumblelogWithAttributes:attributeDict];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"post"]) {
        if (currentPost != nil) {
            if (delegate && [delegate respondsToSelector:@selector(tumblrDidReceivePost:withDomain:)]) {
                [delegate tumblrDidReceivePost:currentPost withDomain:@""];
            }
        }
        self.currentPost = nil;
    }
    else if ([elementName isEqualToString:@"tumblelog"]) {
        if (currentTumblelog != nil) {
            if (delegate && [delegate respondsToSelector:@selector(tumblrDidReceiveTumblelog:)]) {
                [delegate tumblrDidReceiveTumblelog:currentTumblelog];
            }
        }
        self.currentTumblelog = nil;
    }
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    static NSDictionary *elementToSelectorDict = nil;

    if (!elementToSelectorDict) {
        elementToSelectorDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                 @"appendToText:", @"text",
                                 @"appendToCaption:",@"caption",
                                 @"appendToPlayer:", @"player",
                                 @"appendToBody:", @"body",
                                 @"setURLWithString:", @"url",
                                 nil];
    }

    NSString *key = [[currentElementName componentsSeparatedByString:@"-"] lastObject];
    SEL selector = NSSelectorFromString([elementToSelectorDict objectForKey:key]);
    if (selector) {
        [currentPost performSelector:selector withObject:string];
    }
}

#pragma clang diagnostic pop

#pragma mark TKTumblrDelegate

- (void)tumblrDidReceivePost:(TKPost *)thePost withDomain:(NSString *)theDomain
{
    [self setRequestedPost:thePost];
}

@end