text:
package com.gemstone.gemfire.cache30;

import com.company.app.DBLoader;
import com.gemstone.gemfire.cache.*;
import com.gemstone.gemfire.cache.util.BridgeServer;
import com.gemstone.gemfire.cache.util.Gateway;
import com.gemstone.gemfire.cache.util.GatewayHub;
import com.gemstone.gemfire.cache.util.GatewayQueueAttributes;
import com.gemstone.gemfire.internal.AvailablePort;
import com.gemstone.gemfire.internal.cache.DistributedRegion;
import com.gemstone.gemfire.internal.cache.xmlcache.*;

import dunit.Host;
import dunit.DistributedTestCase;
import dunit.VM;

import java.io.*;
import java.util.*;

/**
 * Tests the declarative caching functionality introduced in GemFire
 * 5.0 (i.e. congo1). Don't be confused by the 45 in my name :-)
 *
 * @author Darrel Schneider
 * @since 5.0
 */
public class CacheXml45Test extends CacheXml41Test {

  ////////  Constructors

  public CacheXml45Test(String name) {
    super(name);
  }

  ////////  Helper methods

  protected String getGemFireVersion() {
    return CacheXml.VERSION_5_0;
  }

  ////////  Test methods

  public void setBridgeAttributes(BridgeServer bridge1)
  {
    super.setBridgeAttributes(bridge1);
    bridge1.setMaxConnections(100);
  }

  public void testDataPolicy() throws CacheException {
    CacheCreation cache = new CacheCreation();

    {
      RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
      attrs.setDataPolicy(DataPolicy.NORMAL);
      cache.createRegion("rootNORMAL", attrs);
    }
    {
      RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
      attrs.setDataPolicy(DataPolicy.NORMAL);
      attrs.setSubscriptionAttributes(new SubscriptionAttributes(InterestPolicy.ALL));
      cache.createRegion("rootNORMAL_ALL", attrs);
    }
    {
      RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
      attrs.setMirrorType(MirrorType.KEYS_VALUES);
      cache.createRegion("rootREPLICATE", attrs);
    }
    {
      RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
      attrs.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
      cache.createRegion("rootPERSISTENT_REPLICATE", attrs);
    }
    {
      RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
      attrs.setDataPolicy(DataPolicy.EMPTY);
      cache.createRegion("rootEMPTY", attrs);
    }
    {
      RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
      attrs.setDataPolicy(DataPolicy.EMPTY);
      attrs.setSubscriptionAttributes(new SubscriptionAttributes(InterestPolicy.ALL));
      cache.createRegion("rootEMPTY_ALL", attrs);
    }

    testXml(cache);
  }

  /**
   * These properties, if any, will be added to the properties used for getSystem calls
   */
  protected Properties xmlProps = null;

  public Properties getDistributedSystemProperties() {
    Properties props = super.getDistributedSystemProperties();
    if (this.xmlProps != null) {
      for (Iterator iter = this.xmlProps.entrySet().iterator();
           iter.hasNext(); ) {
        Map.Entry entry = (Map.Entry) iter.next();
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();
        props.setProperty(key, value);
      }
    }
    return props;
  }

  /**
   * Test xml support of MembershipAttributes.
   */
  public void testMembershipAttributes() throws Exception {
    final String MY_ROLES = "Foo, Bip, BAM";
    final String[][] roles = new String[][] {{"Foo"}, {"Bip", "BAM"}};

    final LossAction[] policies = (LossAction[])
      LossAction.VALUES.toArray(
      new LossAction[LossAction.VALUES.size()]);

    final ResumptionAction[] actions = (ResumptionAction[])
      ResumptionAction.VALUES.toArray(
      new ResumptionAction[ResumptionAction.VALUES.size()]);

    CacheCreation cache = new CacheCreation();

    // for each policy, try each action and each role...
    for (int policy = 0; policy < policies.length; policy++) {
      for (int action = 0; action < actions.length; action++) {
        for (int role = 0; role < roles.length; role++) {
          String[] theRoles = roles[role];
          LossAction thePolicy = policies[policy];
          ResumptionAction theAction = actions[action];

          //if (theRoles.length == 0 && (thePolicy != LossAction.NONE || theAction != ResumptionAction.NONE

          RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
          MembershipAttributes ra = new MembershipAttributes(
              theRoles, thePolicy, theAction);
          attrs.setMembershipAttributes(ra);
          String region = "rootMEMBERSHIP_ATTRIBUTES_" +
                          policy + "_" + action + "_" + role;
          cache.createRegion(region, attrs);
        }
      }
    }

    {
      // make our system play the roles used by this test so the create regions
      // will not think the a required role is missing
      Properties config = new Properties();
      config.setProperty("roles", MY_ROLES);
      this.xmlProps = config;
    }
    DistributedRegion.ignoreReconnect = true;
    try {
      testXml(cache);
    } finally {
      this.xmlProps = null;
      try {
        tearDown2();
      } finally {
        DistributedRegion.ignoreReconnect = false;
      }
    }
  }

  /**
   * Tests multiple cache listeners on one region
   * @since 5.0
   */
  public void testMultipleCacheListener() throws CacheException {
    CacheCreation cache = new CacheCreation();
    RegionAttributesCreation attrs = new RegionAttributesCreation(cache);

    CacheListener l1 = new MyTestCacheListener();
    CacheListener l2 = new MySecondTestCacheListener();
    attrs.addCacheListener(l1);
    attrs.addCacheListener(l2);

    cache.createRegion("root", attrs);

    testXml(cache);
    {
      Cache c = getCache();
      Region r = c.getRegion("root");
      assertEquals(Arrays.asList(new CacheListener[]{l1, l2}), Arrays.asList(r.getAttributes().getCacheListeners()));
      AttributesMutator am = r.getAttributesMutator();
      am.removeCacheListener(l2);
      assertEquals(Arrays.asList(new CacheListener[]{l1}), Arrays.asList(r.getAttributes().getCacheListeners()));
      am.removeCacheListener(l1);
      assertEquals(Arrays.asList(new CacheListener[]{}), Arrays.asList(r.getAttributes().getCacheListeners()));
      am.addCacheListener(l1);
      assertEquals(Arrays.asList(new CacheListener[]{l1}), Arrays.asList(r.getAttributes().getCacheListeners()));
      am.addCacheListener(l1);
      assertEquals(Arrays.asList(new CacheListener[]{l1}), Arrays.asList(r.getAttributes().getCacheListeners()));
      am.addCacheListener(l2);
      assertEquals(Arrays.asList(new CacheListener[]{l1,l2}), Arrays.asList(r.getAttributes().getCacheListeners()));
      am.removeCacheListener(l1);
      assertEquals(Arrays.asList(new CacheListener[]{l2}), Arrays.asList(r.getAttributes().getCacheListeners()));
      am.removeCacheListener(l1);
      assertEquals(Arrays.asList(new CacheListener[]{l2}), Arrays.asList(r.getAttributes().getCacheListeners()));
      am.initCacheListeners(new CacheListener[]{l1,l2});
      assertEquals(Arrays.asList(new CacheListener[]{l1,l2}), Arrays.asList(r.getAttributes().getCacheListeners()));
    }
  }

  /**
   * A CacheListener that is
   * Declarable, but not Declarable2.
   */
  public static class MySecondTestCacheListener
    extends TestCacheListener implements Declarable {

    public void init(Properties props) { }

    public boolean equals(Object o) {
      return o instanceof MySecondTestCacheListener;
    }
  }

  public void testHeapLRUEviction() throws Exception {
    final String name = getUniqueName();
    beginCacheXml();
    AttributesFactory factory = new AttributesFactory();
    factory.setScope(Scope.LOCAL);
    EvictionAttributes ev = EvictionAttributes.createLRUHeapAttributes(null, EvictionAction.OVERFLOW_TO_DISK);
    factory.setEvictionAttributes(ev);
//    RegionAttributes atts = factory.create();
    createRegion(name, factory.create());
    finishCacheXml(getUniqueName(), getGemFireVersion());
    Region r = getRootRegion().getSubregion(name);

    EvictionAttributes hlea = r.getAttributes().getEvictionAttributes();
    assertEquals(EvictionAction.OVERFLOW_TO_DISK, hlea.getAction());
  }

  /**
   * Tests multiple transaction listeners
   * @since 5.0
   */
  public void testMultipleTXListener() throws CacheException {
    CacheCreation cache = new CacheCreation();
    CacheTransactionManagerCreation txMgrCreation = new CacheTransactionManagerCreation();
    TransactionListener l1 = new MyTestTransactionListener();
    TransactionListener l2 = new MySecondTestTransactionListener();
    txMgrCreation.addListener(l1);
    txMgrCreation.addListener(l2);
    cache.addCacheTransactionManagerCreation(txMgrCreation);
    testXml(cache);
    {
      CacheTransactionManager tm = getCache().getCacheTransactionManager();
      assertEquals(Arrays.asList(new TransactionListener[]{l1, l2}), Arrays.asList(tm.getListeners()));
      tm.removeListener(l2);
      assertEquals(Arrays.asList(new TransactionListener[]{l1}), Arrays.asList(tm.getListeners()));
      tm.removeListener(l1);
      assertEquals(Arrays.asList(new TransactionListener[]{}), Arrays.asList(tm.getListeners()));
      tm.addListener(l1);
      assertEquals(Arrays.asList(new TransactionListener[]{l1}), Arrays.asList(tm.getListeners()));
      tm.addListener(l1);
      assertEquals(Arrays.asList(new TransactionListener[]{l1}), Arrays.asList(tm.getListeners()));
      tm.addListener(l2);
      assertEquals(Arrays.asList(new TransactionListener[]{l1,l2}), Arrays.asList(tm.getListeners()));
      tm.removeListener(l1);
      assertEquals(Arrays.asList(new TransactionListener[]{l2}), Arrays.asList(tm.getListeners()));
      tm.removeListener(l1);
      assertEquals(Arrays.asList(new TransactionListener[]{l2}), Arrays.asList(tm.getListeners()));
      tm.initListeners(new TransactionListener[]{l1,l2});
      assertEquals(Arrays.asList(new TransactionListener[]{l1,l2}), Arrays.asList(tm.getListeners()));
    }
  }

  /**
   * A TransactionListener that is
   * Declarable, but not Declarable2.
   */
  public static class MySecondTestTransactionListener
    extends TestTransactionListener implements Declarable {

    public void init(Properties props) { }

    public boolean equals(Object o) {
      return o instanceof MySecondTestTransactionListener;
    }
  }

  /**
   * Test GatewayHub / Gateway creation
   * @since 5.0
   */
  public void testGatewayHub() throws CacheException {
    CacheCreation cache = new CacheCreation();
    int HUB_PORT = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    int PORT1 = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    int PORT2 = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
    // Create GatewayHub
    GatewayHub hub = cache.setGatewayHub("US", HUB_PORT);
    hub.setSocketBufferSize(65536);
    hub.setMaximumTimeBetweenPings(30000);

    // Create Gateway and Endpoints
    Gateway gateway = hub.addGateway("EU");
    gateway.setSocketBufferSize(65536);
    gateway.addEndpoint("EU-1", DistributedTestCase.getIPLiteral(), PORT1);
    gateway.addEndpoint("EU-2", DistributedTestCase.getIPLiteral(), PORT2);

    // Create GatewayQueueAttributes
    GatewayQueueAttributes queueAttributes = gateway.getQueueAttributes();
    File overflowDirectory = new File(getName());
    overflowDirectory.mkdir();
    queueAttributes.setOverflowDirectory(overflowDirectory.getAbsolutePath());
    queueAttributes.setMaximumQueueMemory(200);
    queueAttributes.setBatchSize(500);
    queueAttributes.setBatchTimeInterval(100);
    queueAttributes.setBatchConflation(true);
    queueAttributes.setEnablePersistence(true);
    // Create cache
    testXml(cache);
    // Test the GatewayHub creation
    Cache c = getCache();
    List hubs = c.getGatewayHubs();
    GatewayHub createdHub = (GatewayHub)hubs.get(0);
    assertTrue(createdHub != null);

    // Test the created GatewayHub
    assertEquals("US", createdHub.getId());
    assertEquals(HUB_PORT, createdHub.getPort());
    assertEquals(65536, createdHub.getSocketBufferSize());
    //assertEquals(30000, createdHub.getMaximumTimeBetweenPings());

    // Test the created Gateway
    Gateway createdGateway = createdHub.getGateways().get(0);
    assertNotNull(createdGateway);

    assertEquals("EU", createdGateway.getId());
    assertEquals(65536, createdGateway.getSocketBufferSize());

    // Test the endpoints
    List endpoints = createdGateway.getEndpoints();
    assertEquals(2, endpoints.size());
    for (Iterator i = endpoints.iterator(); i.hasNext(); ) {
      Gateway.Endpoint endpoint = (Gateway.Endpoint) i.next();
      if (endpoint.getId().equals("EU-1")) {
        assertEquals(DistributedTestCase.getIPLiteral(), endpoint.getHost());
        assertEquals(PORT1, endpoint.getPort());
      } else if (endpoint.getId().equals("EU-2")) {
        assertEquals(DistributedTestCase.getIPLiteral(), endpoint.getHost());
        assertEquals(PORT2, endpoint.getPort());
      } else {
        fail("Expected an endpoint with id EU-1 or EU-2 but got one with id " + endpoint.getId());
      }
    }

    // Test the queue attributes
    GatewayQueueAttributes createdQueueAttributes = createdGateway.getQueueAttributes();
    assertEquals(overflowDirectory.getAbsolutePath(), createdQueueAttributes.getOverflowDirectory());
    assertEquals(200, createdQueueAttributes.getMaximumQueueMemory());
    assertEquals(500, createdQueueAttributes.getBatchSize());
    assertEquals(100, createdQueueAttributes.getBatchTimeInterval());
    assertEquals(true, createdQueueAttributes.getBatchConflation());
    assertEquals(true, createdQueueAttributes.getEnablePersistence());
    //Asif: Destroy the secret region used by High availability RegionQueue
    String rq= new StringBuffer(createdGateway.getGatewayHubId()).append('_').append(createdGateway.getId()).append("_EVENT_QUEUE").toString();
    Region wbcl = c.getRegion(rq);
    if(wbcl != null) {
      wbcl.localDestroyRegion();
    }
  }

  /**
   * Tests that a region created with a named attributes has the correct
   * attributes.
   */
  public void testPartitionedRegionXML() throws CacheException
  {
    setXmlFile(findFile("partitionedRegion.xml"));
    final String regionName = "pRoot";

    Cache cache = getCache();
    Region region = cache.getRegion(regionName);
    assertNotNull(region);

    Host host = Host.getHost(0);
    final VM vm0 = host.getVM(0);
    final VM vm1 = host.getVM(1);

    CacheSerializableRunnable init = new CacheSerializableRunnable("initUsingPartitionedRegionXML") {
      public void run2() throws CacheException
      {
        final Cache cache;
        try {
          CacheXml30Test.lonerDistributedSystem = false;
          cache = getCache();
        }
        finally {
          CacheXml30Test.lonerDistributedSystem = true;
        }
        Region region = cache.getRegion(regionName);
        assertNotNull(region);
        RegionAttributes attrs = region.getAttributes();
        assertNotNull(attrs.getPartitionAttributes());

        PartitionAttributes pa = attrs.getPartitionAttributes();
        // assertNull(pa.getCacheWriter());
        assertEquals(pa.getRedundantCopies(), 1);
        assertEquals(pa.getGlobalProperties().getProperty(
            PartitionAttributesFactory.GLOBAL_MAX_MEMORY_PROPERTY), "96");
        assertEquals(pa.getLocalProperties().getProperty(
            PartitionAttributesFactory.LOCAL_MAX_MEMORY_PROPERTY), "32");
      }
    };

    init.run2();
    vm0.invoke(init);
    vm1.invoke(init);
    vm0.invoke(new CacheSerializableRunnable("putUsingPartitionedRegionXML1") {
      public void run2() throws CacheException
      {
        final String val = "prValue0";
        final Integer key = new Integer(10);
        Cache cache = getCache();
        Region region = cache.getRegion(regionName);
        assertNotNull(region);
        region.put(key, val);
        assertEquals(val, region.get(key));
      }
    });
    vm1.invoke(new CacheSerializableRunnable("putUsingPartitionedRegionXML2") {
      public void run2() throws CacheException
      {
        final String val = "prValue1";
        final Integer key = new Integer(14);
        Cache cache = getCache();
        Region region = cache.getRegion(regionName);
        assertNotNull(region);
        region.put(key, val);
        assertEquals(val, region.get(key));
      }
    });
  }

  /**
   * Tests that a region created with a named attributes has the correct
   * attributes.
   *
   */
  public void testPartitionedRegionInstantiation() throws CacheException
  {
    CacheCreation cache = new CacheCreation();
    RegionAttributesCreation attrs = new RegionAttributesCreation(cache);

    Properties gp = new Properties();
    gp.setProperty(PartitionAttributesFactory.GLOBAL_MAX_MEMORY_PROPERTY, "2");
    gp.setProperty(PartitionAttributesFactory.GLOBAL_MAX_BUCKETS_PROPERTY, "17");
    Properties lp = new Properties();
    lp.setProperty(PartitionAttributesFactory.LOCAL_MAX_MEMORY_PROPERTY, "4");
    PartitionAttributesFactory paf = new PartitionAttributesFactory();

//    paf.setEntryTimeToLive(
//        new ExpirationAttributes(10, ExpirationAction.DESTROY)).setCacheLoader(
    paf.setLocalProperties(lp).setGlobalProperties(gp);
    attrs.setCacheLoader(new DBLoader());
    attrs.setPartitionAttributes(paf.create());
    cache.createRegion("pRoot", attrs);

    testXml(cache);
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <name>CMIS</name>

  <groupId>org.cmis</groupId>
  <artifactId>CMIS</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>org.apache.chemistry.opencmis</groupId>
      <artifactId>chemistry-opencmis-client-impl</artifactId>
      <version>0.10.0</version>
    </dependency>
  </dependencies>
</project>

redpajama_set_name: RedPajamaGithub


text:
#import <StoreKitUI/SKUIStorePageSection.h>

#import "SKUIMenuViewControllerDelegate-Protocol.h"
#import "SKUIPopupMenuDelegate-Protocol.h"
#import "SKUISortDataRequestDelegate-Protocol.h"
#import "UIPickerViewDataSource-Protocol.h"
#import "UIPickerViewDelegate-Protocol.h"
#import "UIPopoverControllerDelegate-Protocol.h"

@class NSMutableIndexSet, SKUIFocusedTouchGestureRecognizer, SKUIMenuPageComponent, SKUIMenuViewController, SKUIPickerWrapperView, SKUIPillsControl, SKUIPopupMenuHeaderView, UIPopoverController, UIView;

@interface SKUIMenuPageSection : SKUIStorePageSection <SKUIMenuViewControllerDelegate, SKUIPopupMenuDelegate, SKUISortDataRequestDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UIPopoverControllerDelegate>
{
    SKUIPillsControl *_pillsControl;
    SKUIMenuViewController *_moreListMenuViewController;
    UIPopoverController *_moreListPopoverController;
    SKUIFocusedTouchGestureRecognizer *_pickerDismissGestureRecognizer;
    SKUIPickerWrapperView *_pickerWrapper;
    UIView *_pickerBackgroundView;
    _Bool _pinned;
    SKUIPopupMenuHeaderView *_popupHeaderView;
    long long _selectedIndex;
    NSMutableIndexSet *_sortRequestIndexSet;
}

- (void).cxx_destruct;
- (void)_showPopoverController;
- (void)_showPickerView;
- (void)_showMoreList;
- (void)_setSelectedIndex:(long long)arg1;
- (id)_popupHeaderView;
- (id)_pillsControl;
- (void)_loadSortDataIfNecessaryForMenuIndex:(long long)arg1 reason:(long long)arg2;
- (id)_contentChildView;
- (void)_pillAction:(id)arg1;
- (void)_dismissPickerViewAction:(id)arg1;
- (void)popoverControllerDidDismissPopover:(id)arg1;
- (id)pickerView:(id)arg1 titleForRow:(long long)arg2 forComponent:(long long)arg3;
- (void)pickerView:(id)arg1 didSelectRow:(long long)arg2 inComponent:(long long)arg3;
- (long long)pickerView:(id)arg1 numberOfRowsInComponent:(long long)arg2;
- (long long)numberOfComponentsInPickerView:(id)arg1;
- (void)sortDataRequest:(id)arg1 didFinishWithLockups:(id)arg2;
- (void)popupMenuHeader:(id)arg1 didSelectMenuItemAtIndex:(long long)arg2;
- (void)menuViewController:(id)arg1 didSelectItemAtIndex:(long long)arg2;
- (void)willAppearInContext:(id)arg1;
- (void)restorePinnedHeaderView:(id)arg1;
- (id)popPinnedHeaderView;
- (long long)numberOfCells;
- (void)collectionViewWillApplyLayoutAttributes:(id)arg1;
- (struct CGSize)cellSizeForIndexPath:(id)arg1;
- (id)cellForIndexPath:(id)arg1;
- (void)dealloc;
- (id)initWithPageComponent:(id)arg1;

// Remaining properties
@property(readonly, nonatomic) SKUIMenuPageComponent *pageComponent; // @dynamic pageComponent;

@end


text:
#include "pg_bulkload.h"

#include <unistd.h>
#include <fcntl.h>

#include "access/heapam.h"
#include "catalog/pg_type.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "utils/memutils.h"

#include "binary.h"
#include "logger.h"
#include "pg_profile.h"
#include "pg_strutil.h"
#include "storage/fd.h"
#include "writer.h"

#ifndef UINT16_MAX
#define UINT16_MAX             (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX             (4294967295U)
#endif

/**
 * @brief The number of records write at one time
 */
#define WRITE_LINE_NUM	100

/**
 * @brief output a binary format file
 */
typedef struct BinaryWriter
{
	Writer	base;

	int		bin_fd;			/**< File descriptor of binary file to output */
	int		ctl_fd;			/**< File descriptor of control file to output */
	size_t	rec_len;		/**< One record length */
	char   *buffer;			/**< record buffer to keep output data */
	int		used_rec_cnt;	/**< # of used records in buffer */
	int		nfield;			/**< number of fields */
	Field  *fields;			/**< array of field descriptor */
	Datum  *values;
	bool   *nulls;
} BinaryWriter;

static void	BinaryWriterInit(BinaryWriter *self);
static void	BinaryWriterInsert(BinaryWriter *self, HeapTuple tuple);
static WriterResult	BinaryWriterClose(BinaryWriter *self, bool onError);
static bool	BinaryWriterParam(BinaryWriter *self, const char *keyword, char *value);
static void	BinaryWriterDumpParams(BinaryWriter *self);
static int	BinaryWriterSendQuery(BinaryWriter *self, PGconn *conn, char *queueName, char *logfile, bool verbose);

/* Signature of static functions */
static int	open_output_file(char *fname, char *filetype, bool check);
static void	close_output_file(int *fd, char *filetype);
static HeapTuple BinaryWriterCheckerTuple(TupleChecker *self, HeapTuple tuple, int *parsing_field);

/* ========================================================================
 * Implementation
 * ========================================================================*/

/**
 * @brief Create a new BinaryWriter
 */
Writer *
CreateBinaryWriter(void *opt)
{
	BinaryWriter	   *self;

	self = palloc0(sizeof(BinaryWriter));
	self->base.init = (WriterInitProc) BinaryWriterInit;
	self->base.insert = (WriterInsertProc) BinaryWriterInsert;
	self->base.close = (WriterCloseProc) BinaryWriterClose;
	self->base.param = (WriterParamProc) BinaryWriterParam;
	self->base.dumpParams = (WriterDumpParamsProc) BinaryWriterDumpParams;
	self->base.sendQuery = (WriterSendQueryProc) BinaryWriterSendQuery;
	self->bin_fd = -1;
	self->ctl_fd = -1;

	return (Writer *) self;
}

/**
 * @brief Initialize a BinaryWriter
 */
static void
BinaryWriterInit(BinaryWriter *self)
{
	char		path[MAXPGPATH];
	TupleDesc	tupdesc;
	int			i;
	bool		need_check = false;

	Assert(self->base.truncate == false);

	/* exist check of output file */
	self->bin_fd = open_output_file(self->base.output,
									"binary output file", true);
	snprintf(path, MAXPGPATH, "%s.ctl", self->base.output);
	self->ctl_fd = open_output_file(path, "sample control file", true);

	/* create TupleDesc */
	tupdesc = CreateTemplateTupleDesc(self->nfield, false);
	for (i = 0; i < self->nfield; i++)
	{
		TupleDescInitEntry(tupdesc, i + 1, "out col", self->fields[i].typeid,
						   -1, 0);
		self->rec_len += self->fields[i].len;

		if (self->fields[i].nulllen == 0 ||
			self->fields[i].typeid == CSTRINGOID ||
			(self->fields[i].typeid == INT4OID && self->fields[i].len == 2) ||
			(self->fields[i].typeid == INT8OID && self->fields[i].len == 4) )
			need_check = true;
	}

	self->base.desc = tupdesc;

	self->base.tchecker = CreateTupleChecker(tupdesc);
	if (need_check)
	{
		self->base.tchecker->checker =
						(CheckerTupleProc) BinaryWriterCheckerTuple;
		self->base.tchecker->opt = self->fields;
	}
	else
		self->base.tchecker->checker = (CheckerTupleProc) CoercionCheckerTuple;

	self->buffer = palloc(self->rec_len * WRITE_LINE_NUM);
	self->used_rec_cnt = 0;

	self->values = (Datum *) palloc(self->nfield * sizeof(Datum));
	self->nulls = (bool *) palloc(self->nfield * sizeof(bool));

	self->base.context = AllocSetContextCreate(
							CurrentMemoryContext,
							"BinaryWriter",
							ALLOCSET_DEFAULT_MINSIZE,
							ALLOCSET_DEFAULT_INITSIZE,
							ALLOCSET_DEFAULT_MAXSIZE);
}

static void
BinaryWriterInsert(BinaryWriter *self, HeapTuple tuple)
{
	int		i;
	char   *col;

	col = self->buffer + (self->rec_len * self->used_rec_cnt);

	/* Break down the tuple into fields */
	heap_deform_tuple(tuple, self->base.desc, self->values, self->nulls);

	for (i = 0; i < self->nfield; i++)
	{
		Field  *field = self->fields + i;

		if (!self->nulls[i])
			field->write(col, field->len, self->values[i], self->nulls[i]);
		else
			field->write(col, field->len, PointerGetDatum(field->nullif), field->nulllen);

		col += field->len;
	}

	/* open file */
	if (self->bin_fd == -1)
	{
		char	path[MAXPGPATH];

		self->bin_fd = open_output_file(self->base.output,
										"binary output file", false);
		snprintf(path, MAXPGPATH, "%s.ctl", self->base.output);
		self->ctl_fd = open_output_file(path, "sample control file", false);
	}

	self->used_rec_cnt++;

	if (self->used_rec_cnt >= WRITE_LINE_NUM)
	{
		int	len = self->rec_len * self->used_rec_cnt;

		if (write(self->bin_fd, self->buffer, len) != len)
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not write to binary output file: %m")));

		self->used_rec_cnt = 0;
	}

	BULKLOAD_PROFILE(&prof_writer_table);
}

/*
 * Clean up BinaryWriter
 */
static WriterResult
BinaryWriterClose(BinaryWriter *self, bool onError)
{
	WriterResult	ret = { 0 };

	Assert(self != NULL);

	if (self->used_rec_cnt > 0)
	{
		int	len = self->rec_len * self->used_rec_cnt;

		if (write(self->bin_fd, self->buffer, len) != len)
			ereport(WARNING,
					(errcode_for_file_access(),
					 errmsg("could not write to binary output file: %m")));

		self->used_rec_cnt = 0;
	}

	/* create sample of control file */
	if (self->base.count > 0)
	{
		char		   *filepath;
		char		   *filename;
		char		   *extension;
		StringInfoData	buf;

		filepath = self->base.output;

		/* remove extension of outfile */
		filename = strrchr(self->base.output, '/');
		Assert(filename);
		filename++;
		filename = pstrdup(filename);
		extension = strrchr(filename, '.');
		if (extension && filename < extension)
			*extension = '\0';

		initStringInfo(&buf);
		appendStringInfo(&buf, "INPUT = %s\n", filepath);
		appendStringInfo(&buf, "OUTPUT = %s\n", filename);
		appendStringInfo(&buf, "LOGFILE = %s.log\n", filepath);
		appendStringInfo(&buf, "PARSE_BADFILE = %s.prs\n", filepath);
		appendStringInfo(&buf, "DUPLICATE_BADFILE = %s.dup\n", filepath);
		appendStringInfoString(&buf,
							   "PARSE_ERRORS = INFINITE\n"
							   "DUPLICATE_ERRORS = 0\n"
							   "ON_DUPLICATE_KEEP = NEW\n"
							   "SKIP = 0\n"
							   "LIMIT = INFINITE\n"
							   "CHECK_CONSTRAINTS = NO\n"
							   "MULTI_PROCESS = YES\n"
							   "VERBOSE = NO\n"
							   "TRUNCATE = NO\n"
							   "WRITER = DIRECT\n"
							   "TYPE = BINARY\n");
		BinaryDumpParams(self->fields, self->nfield, &buf, "COL");
		appendStringInfo(&buf, "# ENCODING = %s\n", GetDatabaseEncodingName());

		if (write(self->ctl_fd, buf.data, buf.len) != buf.len)
			ereport(WARNING,
					(errcode_for_file_access(),
					 errmsg("could not write to sample control file: %m")));

		pfree(filename);
		pfree(buf.data);
	}

	close_output_file(&self->bin_fd, "binary output file");
	close_output_file(&self->ctl_fd, "sample control file");

	if (self->base.output)
		pfree(self->base.output);
	self->base.output = NULL;

	if (self->buffer)
		pfree(self->buffer);
	self->buffer = NULL;

	if (self->values)
		pfree(self->values);
	self->values = NULL;

	if (self->nulls)
		pfree(self->nulls);
	self->nulls = NULL;

	if (self->fields)
		pfree(self->fields);
	self->fields = NULL;

	if (!onError)
		MemoryContextDelete(self->base.context);

	ret.num_dup_new = 0;
	ret.num_dup_old = 0;

	return ret;
}

static bool
BinaryWriterParam(BinaryWriter *self, const char *keyword, char *value)
{
	if (CompareKeyword(keyword, "CHECK_CONSTRAINTS") ||
		CompareKeyword(keyword, "FORCE_NOT_NULL"))
	{
		ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						errmsg("does not support parameter \"%s\" in \"WRITER = BINARY\"", keyword)));
	}
	else if (CompareKeyword(keyword, "TABLE") ||
			 CompareKeyword(keyword, "OUTPUT"))
	{
		if (strlen(value) + strlen(".ctl") >= MAXPGPATH)
			ereport(ERROR,
					(errcode(ERRCODE_INTERNAL_ERROR),
					 errmsg("binary output file name is too long")));

		if (!is_absolute_path(value))
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("relative path not allowed for OUTPUT: %s", value)));

		/* must be the super user if write to file */
		if (!superuser())
			ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("must be superuser to use pg_bulkload to a file")));

		ASSERT_ONCE(self->base.output == NULL);
		self->base.output = pstrdup(value);
	}
	else if (CompareKeyword(keyword, "OUT_COL"))
	{
		BinaryParam(&self->fields, &self->nfield, value, false, true);
	}
	else
		return false;	/* unknown parameter */

	return true;
}

static void
BinaryWriterDumpParams(BinaryWriter *self)
{
	StringInfoData	buf;

	initStringInfo(&buf);
	appendStringInfoString(&buf, "WRITER = BINARY\n");

	BinaryDumpParams(self->fields, self->nfield, &buf, "OUT_COL");

	LoggerLog(INFO, buf.data, 0);
	pfree(buf.data);
}

static int
BinaryWriterSendQuery(BinaryWriter *self, PGconn *conn, char *queueName, char *logfile, bool verbose)
{
	int				i;
	int				nparam;
	const char	  **params;
	StringInfoData	buf;
	int				offset;
	int				result;

	nparam = self->nfield + 4;
	params = palloc0(sizeof(char *) * nparam);

	/* async query send */
	params[0] = queueName;
	params[1] = self->base.output;
	params[2] = logfile;
	params[3] = verbose ? "true" : "no";

	initStringInfo(&buf);
	appendStringInfoString(&buf,
		"SELECT * FROM pg_bulkload(ARRAY["
		"'TYPE=TUPLE',"
		"'INPUT=' || $1,"
		"'WRITER=BINARY',"
		"'OUTPUT=' || $2,"
		"'LOGFILE=' || $3,"
		"'VERBOSE=' || $4");

	offset = 0;
	for (i = 0 ; i < self->nfield; i++)
	{
		StringInfoData	param_buf;

		appendStringInfo(&buf, ",'OUT_COL=' || $%d", i + 4 + 1);

		initStringInfo(&param_buf);
		offset = BinaryDumpParam(self->fields + i, &param_buf, offset);
		params[i + 4] = param_buf.data;
	}

	appendStringInfoString(&buf, "])");

	result = PQsendQueryParams(conn, buf.data, nparam, NULL, params, NULL, NULL, 0);

	pfree(params);
	pfree(buf.data);

	return result;
}

/*
 * Open the output file and returns its descriptor.
 */
static int
open_output_file(char *fname, char *filetype, bool check)
{
	int	fd = -1;

	fd = BasicOpenFile(fname, O_WRONLY | O_CREAT | O_EXCL | PG_BINARY,
					   S_IRUSR | S_IWUSR);
	if (fd == -1)
		ereport(ERROR, (errcode_for_file_access(),
						errmsg("could not open %s: %m", filetype)));

	if (check)
	{
		close_output_file(&fd, filetype);
		unlink(fname);
	}

	return fd;
}

/**
 * Flush and close the output file.
 */
static void
close_output_file(int *fd, char *filetype)
{
	if (*fd == -1)
		return;

	if (pg_fsync(*fd) != 0)
		ereport(WARNING, (errcode_for_file_access(),
				errmsg("could not fsync %s: %m", filetype)));

	if (close(*fd) != 0)
		ereport(WARNING, (errcode_for_file_access(),
				errmsg("could not close %s: %m", filetype)));

	*fd = -1;
}

static HeapTuple
BinaryWriterCheckerTuple(TupleChecker *self, HeapTuple tuple, int *parsing_field)
{
	TupleDesc	desc = self->targetDesc;
	Field	   *fields = self->opt;
	int		i;

	if (self->status == NEED_COERCION_CHECK)
		UpdateTupleCheckStatus(self, tuple);

	if (self->status == NO_COERCION)
		heap_deform_tuple(tuple, desc, self->values, self->nulls);
	else
	{
		CoercionDeformTuple(self, tuple, parsing_field);
		tuple = heap_form_tuple(self->targetDesc, self->values, self->nulls);
	}

	for (i = 0; i < desc->natts; i++)
	{
		*parsing_field = i + 1;	/* 1 origin */

		if (self->nulls[i])
		{
			if (fields[i].nulllen == 0)
				ereport(ERROR,
						(errcode(ERRCODE_NOT_NULL_VIOLATION),
						 errmsg("null value violates not-null constraint")));

			continue;
		}

		switch (fields[i].typeid)
		{
			case CSTRINGOID:
				if (strlen(DatumGetCString(self->values[i])) > fields[i].len)
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
							 errmsg("value too long for type character(%d)", fields[i].len)));
				break;
			case INT4OID:
				if (fields[i].len == sizeof(uint16))
				{
					int32	value = DatumGetInt32(self->values[i]);

					if (value < 0 || value > UINT16_MAX)
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
							 errmsg("value \"%d\" is out of range for type unsigned smallint", value)));
				}
				break;
			case INT8OID:
				if (fields[i].len == sizeof(uint32))
				{
					int64	value = DatumGetInt64(self->values[i]);

					if (value < 0 || value > UINT32_MAX)
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
							 errmsg("value \"" int64_FMT "\" is out of range for type unsigned integer", value)));
				}
				break;
		}
	}

	*parsing_field = -1;

	return tuple;
}


text:
import angular from 'angular';

import Controller from './FormSubmitController';
import LoginModalDialogController from './LoginModalDialogController';

export default angular
  .module('app.user.formSubmitController', [])
  .component('formSubmit', Controller)
  .controller('loginModalDialogController', LoginModalDialogController);


text:
wordpress_id: 374
title: Happy Mother's Day Mom!
wordpress_url: http://spaetzel.com/PermaLink,guid,100.aspx
layout: post
---
So, these photos are a touch late, but I needed to put them up.

        These are the flowers that I got my Mom for Mother's day (She actually did get them
        on time)

        Hope you like the pics.


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

namespace corsairs.core.worldgen.biomes
{
    public class Marsh : TemperateLand
    {
        public override int MaxDrainage
        {
            get
            {
                return 20;
            }
        }

        public override int MinDrainage
        {
            get
            {
                return 10;
            }
        }

        public override char DebugSymbol
        {
            get { return 'm'; }
        }
    }
}


text:
Web-based recruitment system with interfaces both for applicants and recruiters. Part of a assignment in a course at KTH Royal Institute of Technology.

![Screenshot](screenshots/screenshot.png "Screenshot")

## How to run

Run the project from inside NetBeans or other IDE that has integrated support for Glassfish server

## Documentation

- Arhitectural document can be found in the folder "report"
- JavaDoc at target/site/apidocs/index.html

## Author

Kim Hammar, Alexander Lundh, Marcel Mattsson

## Copyright and license

The MIT License (MIT)

Copyright (c) 2015 Kim Hammar, Alexander Lundh, Marcel Mattsson


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

Provides an API for developing applets for the Logitech G19 LCD Keyboard, and similar devices.

Related Documentation

For examples and documentation, see:

README file

HelloWorld example using G19-style colour screen

HelloWorld example using G15-sytle monochrome screen

Example showing the use of asynchronous events

@since 2010-04-10


text:
using System;
using Gry.ArcGis.NetStGeometry.Geometry;
using Gry.ArcGis.NetStGeometry.Geometry.Base;
using Oracle.DataAccess.Types;

namespace Gry.ArcGis.NetStGeometry.Oracle
{
    /// <summary>
    /// Oracle parameter type representing an Oracle UDT object of type SDE.ST_GEOMETRY, read using SDE.ST_GEOMFROMTEXT() function.
    /// The is the same as EsriStGeometryType class, but the when reading with another function, the same type cannot be used for different OracleCustomTypeMapping attributes.
    /// Therefore, we have to define a diferent type here.
    /// Will be used when reading an Esri ST_Geometry object in Oracle, only using SDE.ST_GEOMFROMTEXT() function.
    /// </summary>
    [Serializable]
    [OracleCustomTypeMapping("SDE.ST_GEOMFROMTEXT")]
    public class EsriStGeomFromTextType : OracleCustomTypeBase<EsriStGeomFromTextType>, IEsriStGeometryType
    {
        private IStGeometry _geometry;

        #region IEsriStGeometryType Members

        [OracleObjectMapping("ENTITY")]
        public int Entity { get; set; }
        [OracleObjectMapping("NUMPTS")]
        public int NumPts { get; set; }
        [OracleObjectMapping("MINX")]
        public decimal MinX { get; set; }
        [OracleObjectMapping("MINY")]
        public decimal MinY { get; set; }
        [OracleObjectMapping("MAXX")]
        public decimal MaxX { get; set; }
        [OracleObjectMapping("MAXY")]
        public decimal MaxY { get; set; }
        [OracleObjectMapping("MINZ")]
        public decimal? MinZ { get; set; }
        [OracleObjectMapping("MAXZ")]
        public decimal? MaxZ { get; set; }
        [OracleObjectMapping("MINM")]
        public decimal? MinM { get; set; }
        [OracleObjectMapping("MAXM")]
        public decimal? MaxM { get; set; }
        [OracleObjectMapping("AREA")]
        public decimal Area { get; set; }
        [OracleObjectMapping("LEN")]
        public decimal Len { get; set; }
        [OracleObjectMapping("SRID")]
        public int Srid { get; set; }
        [OracleObjectMapping("POINTS")]
        public byte[] Points { get; set; }

        public IStGeometry Geometry
        {
            get { return _geometry; }
            set
            {
                _geometry = value;
                EsrIStGeometryTypeHelper.CalculateOtherValuesFromGeometry(this);
            }
        }

        #endregion

        protected override void MapFromCustomObject()
        {
            EsrIStGeometryTypeHelper.MapFromCustomObject(this);
        }

        protected override void MapToCustomObject()
        {
            EsrIStGeometryTypeHelper.MapToCustomObject(this);
        }
    }
}


text:
<?php

namespace KingdomHall\UserBundle\Controller;

use FOS\UserBundle\Controller\ProfileController as FOSProfileController;
use KingdomHall\UserBundle\Entity\User;
use Symfony\Component\HttpFoundation\Request;

class ProfileController extends FOSProfileController
{
    public function editAction()
    {
        $user = new User();
        $userId = $this->container->get('request')->get('userId');

        if ($userId) {
            $user = $this->container->get('doctrine.orm.entity_manager')->getRepository('KingdomHallUserBundle:User')->find($userId);
        } else {
            $user = $this->container->get('kingdomhall.user_manager')->createUser();
            $user->setEnabled(true);
        }

        $form = $this->container->get('fos_user.profile.form');
        $formHandler = $this->container->get('fos_user.profile.form.handler');

        $process = $formHandler->process($user);

        return $this->container->get('templating')->renderResponse(
            'FOSUserBundle:Profile:edit.html.'.$this->container->getParameter('fos_user.template.engine'),
            array(
                'form' => $form->createView(),
                'user' => $user,
            )
        );

    }
}


text:
package c99.parser;

import c99.Constant;
import c99.ExtAttr;
import c99.ISourceRange;
import c99.SourceRange;

import java.util.ArrayList;

@Deprecated
public abstract class Trees
{
public static class Tree extends SourceRange
{
  public Tree ( ISourceRange rng )
  {
    super( rng );
  }
} // class

public static class TreeList extends ArrayList<Tree>
{
}

public static class TExtAttr extends Tree
{
  public final ExtAttr extAttr;

  public TExtAttr ( final ISourceRange rng, final ExtAttr extAttr )
  {
    super(rng);
    this.extAttr = extAttr;
  }
}

public static class TExtAttrList extends ArrayList<TExtAttr>
{
}

public static class TIntNumber extends Tree
{
  public final Constant.IntC value;

  public TIntNumber ( final ISourceRange rng, final Constant.IntC value )
  {
    super(rng);
    this.value = value;
  }
}

}


text:
//! \file fbxdocumentinfo.h
#ifndef _FBXSDK_SCENE_DOCUMENT_INFO_H_
#define _FBXSDK_SCENE_DOCUMENT_INFO_H_

#include <fbxsdk/fbxsdk_def.h>

#include <fbxsdk/core/fbxobject.h>

#include <fbxsdk/fbxsdk_nsbegin.h>

class FbxThumbnail;

/** This class contains scene thumbnails and user-defined summary data.
  */
class FBXSDK_DLL FbxDocumentInfo : public FbxObject
{
	FBXSDK_OBJECT_DECLARE(FbxDocumentInfo, FbxObject);

public:
	/**
	* \name Public properties
	*/
	//@{
		/** This property contains the last saved URL.
		  *
		  * To retrieve the value of this property, use LastSavedUrl.Get().
		  * To set the value of this property, use LastSavedUrl.Set(FbxString).
		  *
		  * The default value is empty.
		  */
		FbxPropertyT<FbxString> LastSavedUrl;

		/** This property contains the URL.
		  *
		  * To retrieve the value of this property, use Url.Get().
		  * To set the value of this property, use Url.Set(FbxString).
		  *
		  * The default value is empty.
		  */
		FbxPropertyT<FbxString> Url;

		/** Parent property for all properties related to creation. These properties
		  * should be set once when the file is created, and you should not change them
		  * during subsequent save or reload operations.
		  * The default properties are listed below, but application vendors can add new
		  * properties under this parent property.
		  */
		FbxProperty Original;

		/** This property contains the name of the original application vendor.
		  *
		  * To retrieve the value of this property, use Original_ApplicationVendor.Get().
		  * To set the value of this property, use Original_ApplicationVendor.Set(FbxString).
		  *
		  * The default value is empty.
		  */
		FbxPropertyT<FbxString> Original_ApplicationVendor;

		/** This property contains the original application name.
		  *
		  * To retrieve the value of this property, use Original_ApplicationName.Get().
		  * To set the value of this property, use Original_ApplicationName.Set(FbxString).
		  *
		  * The default value is empty.
		  */
		FbxPropertyT<FbxString> Original_ApplicationName;

		/** This property contains the version of the original application.
		  *
		  * To retrieve the value of this property, use Original_ApplicationVersion.Get().
		  * To set the value of this property, use Original_ApplicationVersion.Set(FbxString).
		  *
		  * The default value is empty.
		  */
		FbxPropertyT<FbxString> Original_ApplicationVersion;

		/** This property contains the original file name.
		  *
		  * To retrieve the value of this property, use Original_FileName.Get().
		  * To set the value of this property, use Original_FileName.Set(FbxString).
		  *
		  * The default value is empty.
		  */
		FbxPropertyT<FbxString> Original_FileName;

		/** This property contains the original date and time.
		  *
		  * To retrieve the value of this property, use Original_DateTime_GMT.Get().
		  * To set the value of this property, use Original_DateTime_GMT.Set(FbxString).
		  *
		  * The default value is 0.
		  * \remarks                The date/time should use GMT time format.
		  */
		FbxPropertyT<FbxDateTime> Original_DateTime_GMT;

		/** The parent property for all last saved-related properties.
		  * These properties update every time a file is saved.
		  * The default properties are below, but application vendors can add new
		  * properties under this parent property.
		  * The file creator must set both the original and last saved properties.
		  */
		FbxProperty LastSaved;

		/** This property contains the last saved application vendor.
		  *
		  * To retrieve the value of this property, use LastSaved_ApplicationVendor.Get().
		  * To set the value of this property, use LastSaved_ApplicationVendor.Set(FbxString).
		  *
		  * The default value is empty.
		  */
		FbxPropertyT<FbxString> LastSaved_ApplicationVendor;

		/** This property contains the last saved application name.
		  *
		  * To retrieve the value of this property, use LastSaved_ApplicationName.Get().
		  * To set the value of this property, use LastSaved_ApplicationName.Set(FbxString).
		  *
		  * The default value is empty.
		  */
		FbxPropertyT<FbxString> LastSaved_ApplicationName;

		/** This property contains the last saved application version.
		  *
		  * To retrieve the value of this property, use LastSaved_ApplicationVersion.Get().
		  * To set the value of this property, use LastSaved_ApplicationVersion.Set(FbxString).
		  *
		  * The default value is empty.
		  */
		FbxPropertyT<FbxString> LastSaved_ApplicationVersion;

		/** This property contains the last saved date and time.
		  *
		  * To retrieve the value of this property, use LastSaved_DateTime_GMT.Get().
		  * To set the value of this property, use LastSaved_DateTime_GMT.Set(FbxString).
		  *
		  * The default value is 0.
		  *
		  * \remarks The date/time should use GMT time format.
		  */
		FbxPropertyT<FbxDateTime> LastSaved_DateTime_GMT;

		/** This property points at the ".fbm" folder that is created when
		  * reading a FBX file that has embedded data. The embedded data
		  * is not saved in the FBX file.
		  *
		  * The default value is empty.
		  */
		FbxPropertyT<FbxString> EmbeddedUrl;
	//@}

	/** \name User-defined summary data.
	  * These are user-completed fields that identify or classify the files.
	  */
	//@{
		FbxString mTitle;		//! Title.
		FbxString mSubject;		//! Subject.
		FbxString mAuthor;		//! Author
		FbxString mKeywords;	//! Keywords.
		FbxString mRevision;	//! Revision.
		FbxString mComment;		//! Comment.
	//@}

	/**
	  * \name Scene Thumbnail.
	  */
	//@{
		/** Returns the thumbnail for the scene.
		  * \return                 Pointer to the thumbnail.
		  */
		FbxThumbnail* GetSceneThumbnail();

		/** Sets the thumbnail for the scene.
		  * \param pSceneThumbnail  Pointer to the thumbnail.
		  */
		void SetSceneThumbnail(FbxThumbnail* pSceneThumbnail);
	//@}

	/** Clears the content.
	  * Resets all the strings to an empty string and clears
	  * the pointer to the thumbnail.
	  */
	void Clear();

/*****************************************************************************************************************************
** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! **
*****************************************************************************************************************************/
#ifndef DOXYGEN_SHOULD_SKIP_THIS
	virtual FbxObject& Copy(const FbxObject& pObject);

protected:
	virtual void Destruct(bool pRecursive);
	virtual void ConstructProperties(bool pForceSet);

    FbxPropertyT<FbxReference> SceneThumbnail;
#endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/
};

#include <fbxsdk/fbxsdk_nsend.h>

#endif /* _FBXSDK_SCENE_DOCUMENT_INFO_H_ */


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require 'pp'

describe "synchronous calls" do
  # To test sets, you have to have a local snmpd running with write permissions
  context "version 1" do
    it "get should succeed" do
      Net::SNMP::Session.open(:peername => "test.net-snmp.org", :community => "demopublic" ) do |sess|
        result = sess.get("sysDescr.0")
        result.varbinds.first.value.should eql("test.net-snmp.org")
      end
    end

    it "multiple calls within session should succeed" do
      Net::SNMP::Session.open(:peername => "test.net-snmp.org", :community => "demopublic" ) do |sess|
        result = sess.get("sysDescr.0")
        result.varbinds.first.value.should eql("test.net-snmp.org")
        second = sess.get("sysName.0")
        second.varbinds.first.value.should eql("test.net-snmp.org")
      end
    end
    it "get should succeed with multiple oids" do
      Net::SNMP::Session.open(:peername => "test.net-snmp.org", :community => 'demopublic' ) do |sess|
        result = sess.get(["sysDescr.0", "sysName.0"])
        result.varbinds[0].value.should eql("test.net-snmp.org")
        result.varbinds[1].value.should eql("test.net-snmp.org")
      end
    end

    it "set should succeed" do
      Net::SNMP::Session.open(:peername => '127.0.0.1', :version => 1, :community => 'private') do |sess|
        result = sess.set([['sysContact.0', Net::SNMP::Constants::ASN_OCTET_STR, 'yomama']])
        result.varbinds.first.value.should match(/yomama/)
        result.should_not be_error
      end
    end

    it "getnext should succeed" do
      Net::SNMP::Session.open(:peername => "test.net-snmp.org", :community => "demopublic" ) do |sess|
        result = sess.get_next(["sysUpTimeInstance.0"])
        result.varbinds.first.oid.oid.should eql("1.3.6.1.2.1.1.4.0")
        result.varbinds.first.value.should match(/Net-SNMP Coders/)
      end
    end

    it "getbulk should succeed" do
      Net::SNMP::Session.open(:peername => "test.net-snmp.org" , :version => '2c', :community => 'demopublic') do |sess|
        result = sess.get_bulk(["sysContact.0"], :max_repetitions => 10)
        result.varbinds.first.oid.name.should eql("1.3.6.1.2.1.1.5.0")
        result.varbinds.first.value.should eql("test.net-snmp.org")
      end
    end

    it "getbulk should succeed with multiple oids" do
      Net::SNMP::Session.open(:peername => "localhost" , :version => '2c', :community => 'public') do |sess|
        result = sess.get_bulk(["ifInOctets", 'ifOutOctets', 'ifInErrors', 'ifOutErrors'], :max_repeaters =>10)
        result.varbinds.size.should eql(40)
      end
    end

    it "get should return error with invalid oid" do
      Net::SNMP::Session.open(:peername => "test.net-snmp.org", :community => "demopublic" ) do |sess|
        result = sess.get(["XXXsysDescr.0"])  #misspelled
        result.should be_error
      end
    end

    it "get_table should work" do
      #pending "not yet implemented"
      session = Net::SNMP::Session.open(:peername => "localhost", :version => '1')
      table = session.table("ifEntry")
      table['1']['ifIndex'].should eql(1)
      table['2']['ifIndex'].should eql(2)
    end

    it "walk should work" do
      #pending "not yet implemented"
      session = Net::SNMP::Session.open(:peername => 'test.net-snmp.org', :version => 1, :community => 'demopublic')
      results = session.walk("system")
      results['1.3.6.1.2.1.1.1.0'].should match(/test.net-snmp.org/)
    end

    it "walk should work with multiple oids" do
      Net::SNMP::Session.open(:peername => 'localhost', :version => 1) do |sess|
        sess.walk(['system', 'ifTable']) do |results|
          #pp results
          results['1.3.6.1.2.1.1.1.0'].should match(/Darwin/)
          results['1.3.6.1.2.1.2.2.1.1.2'].should eql(2)
          results.size.should eql(208)
        end
      end
    end

    it "get_columns should work" do
      Net::SNMP::Session.open(:peername => 'localhost') do |sess|
        table = sess.columns(['ifIndex', 'ifDescr', 'ifType'])
        table['1']['ifIndex'].should eql(1)
        table['2']['ifDescr'].should eql('gif0')
      end
    end

    it "get a value with oid type should work" do
      Net::SNMP::Session.open(:peername => 'test.net-snmp.org', :community => 'demopublic') do |sess|
        res = sess.get("sysORID.1")
        res.varbinds.first.value.to_s.should eql('1.3.6.1.6.3.1')
      end
    end
  end

  context "version 2" do

  end

  context "version 3" do
    it "should get using snmpv3" do
      #pending
      Net::SNMP::Session.open(:peername => 'test.net-snmp.org', :version => 3, :username => 'MD5User', :security_level => Net::SNMP::Constants::SNMP_SEC_LEVEL_AUTHNOPRIV, :auth_protocol => :md5, :password => 'The Net-SNMP Demo Password') do |sess|
        result = sess.get("sysDescr.0")
        result.varbinds.first.value.should eql('test.net-snmp.org')
      end
    end
    it "should set using snmpv3" do
      pending
      Net::SNMP::Session.open(:peername => '127.0.0.1', :version => 3, :username => 'myuser', :auth_protocol => :sha1, :password => '0x1234') do |sess|
        result = sess.set([["sysDescr.0", Net::SNMP::Constants::ASN_OCTET_STR, 'yomama']])
        result.varbinds.first.value.should match(/Darwin/)
      end
    end

    it "should get using authpriv" do
      Net::SNMP::Session.open(:peername => '127.0.0.1', :version => 3, :username => 'mixtli', :security_level => Net::SNMP::Constants::SNMP_SEC_LEVEL_AUTHPRIV, :auth_protocol => :md5, :priv_protocol => :des, :auth_password => 'testauth', :priv_password => 'testpass') do |sess|
        result = sess.get("sysDescr.0")
        result.varbinds.first.value.should match(/xenu/)
      end
    end
  end
end


text:
using namespace std;

int main() {

  const int SCREEN_WIDTH = 800;
  const int SCREEN_HEIGHT = 600;

  if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    cout << "SDL init failed." << endl;
    return 1;
  }

  SDL_Window *window = SDL_CreateWindow(
    "Basic SDL Graphics",
    SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
    SCREEN_WIDTH, SCREEN_HEIGHT,
    SDL_WINDOW_SHOWN
  );

  if (window == NULL) {
    cout << "Could not create window: " << SDL_GetError() << endl;
    SDL_Quit();
    return 2;
  }

  SDL_Renderer *renderer = SDL_CreateRenderer(
    window, -1,
    SDL_RENDERER_PRESENTVSYNC
  );

  SDL_Texture *texture = SDL_CreateTexture(
    renderer, SDL_PIXELFORMAT_RGBA8888,
    SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT
  );

  if (renderer == NULL) {
    cout << "Could not create renderer" << endl;
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 3;
  }

  if (texture == NULL) {
    cout << "Could not create texture" << endl;
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 4;
  }

  Uint32 *buffer = new Uint32[SCREEN_WIDTH * SCREEN_HEIGHT];

  memset(buffer, 0, SCREEN_WIDTH * SCREEN_HEIGHT * sizeof(Uint32));

  Uint32 current_rgba = 0;
  for(int x = 0; x < SCREEN_WIDTH; ++x) {
    for(int y = 0; y <  SCREEN_HEIGHT; ++y) {
      buffer[x * SCREEN_HEIGHT + y] = current_rgba;
      current_rgba = 1.0 * SCREEN_WIDTH/SCREEN_HEIGHT * current_rgba + 0x01;
    }
  }

  SDL_UpdateTexture(texture, NULL, buffer, SCREEN_WIDTH * sizeof(Uint32));
  SDL_RenderClear(renderer);
  SDL_RenderCopy(renderer, texture, NULL, NULL);
  SDL_RenderPresent(renderer);

  bool quit = false;

  SDL_Event event;

  while (!quit) {
    while (SDL_PollEvent(&event)) {
      if (event.type == SDL_QUIT) {
        quit = true;
      }
    }
  }

  delete [] buffer;
  SDL_DestroyRenderer(renderer);
  SDL_DestroyTexture(texture);
  SDL_DestroyWindow(window);
  SDL_Quit();

  return 0;
}


text:
'use strict';

angular.module('angularPassportApp')
    .controller('RoomCtrl', function ($scope, $http, socket) {
        $scope.publisher;
        $scope.streams;
        $scope.session;
        $scope.sharingMyScreen = false;
        $scope.screenBig = true;
        $scope.shareURL = window.location.href;
        $scope.screenPublisher;
        $scope.screenPublisherProps = {
            name: "screen",
            style:{nameDisplayMode:"off"},
            publishAudio: false,
            constraints: {
                video: {
                    mandatory: {
                        chromeMediaSource: "screen",
                        maxWidth: screen.width,
                        minWidth: screen.width,
                        maxHeight: screen.height,
                        minHeight: screen.height,
                        maxFrameRate: 7,
                        minFrameRate: 7
                    },
                    optional: []
                },
                audio: false
            },
            mirror: false,
            width: screen.width,
            height: screen.height,
            aspectRatio: screen.width / screen.height
        };

        $scope.notMine = function(stream) {
            return stream.connection.connectionId != $scope.session.connection.connectionId;
        };

        $scope.shareScreen = function() {
            if (!$scope.sharingMyScreen) {
                $scope.sharingMyScreen = true;
            }
        };

        $scope.hideScreen = function() {
            if ($scope.sharingMyScreen) {
                $scope.sharingMyScreen = false;
            }
        };

        // It's a bit weird to handle changes in size at this level. Really this should be
        // in the Subscriber Directive but I'm trying not to pollute the generic
        // Subscriber Directive
        $scope.$on("changeSize", function (event) {
            if (event.targetScope.stream.oth_large === undefined) {
                // If we're a screen we default to large otherwise we default to small
                event.targetScope.stream.oth_large = event.targetScope.stream.name !== "screen";
            } else {
                event.targetScope.stream.oth_large = !event.targetScope.stream.oth_large;
            }
            setTimeout(function () {
                event.targetScope.$emit("layout");
            }, 10);
        });

        $scope.$on("changeScreenSize", function (event) {
            $scope.screenBig = !$scope.screenBig;
            setTimeout(function () {
                event.targetScope.$emit("layout");
            }, 10);
        });

        //All rooms controller
        $http.get('videochat/rooms').
        success(function(data, status, headers, config) {
          $scope.rooms = data;
        });
        //All rooms controller

        //text chat controller
        socket.on('init', function (data) {
          $scope.name = data.name;
          $scope.users = data.users;
        });

        socket.on('send:message', function (message) {
          $scope.messages.push(message);
        });

        socket.on('change:name', function (data) {
          changeName(data.oldName, data.newName);
        });

        socket.on('user:join', function (data) {
          $scope.messages.push({
            user: 'chatroom',
            text: 'User ' + data.name + ' has joined.'
          });
          $scope.users.push(data.name);
        });

        // add a message to the conversation when a user disconnects or leaves the room
        socket.on('user:left', function (data) {
          $scope.messages.push({
            user: 'chatroom',
            text: 'User ' + data.name + ' has left.'
          });
          var i, user;
          for (i = 0; i < $scope.users.length; i++) {
            user = $scope.users[i];
            if (user === data.name) {
              $scope.users.splice(i, 1);
              break;
            }
          }
        });

        // Private helpers
        // ===============

        var changeName = function (oldName, newName) {
          // rename user in list of users
          var i;
          for (i = 0; i < $scope.users.length; i++) {
            if ($scope.users[i] === oldName) {
              $scope.users[i] = newName;
            }
          }

          $scope.messages.push({
            user: 'chatroom',
            text: 'User ' + oldName + ' is now known as ' + newName + '.'
          });
        }

        // Methods published to the scope
        // ==============================

        $scope.changeName = function () {
          if($scope.name != '') {
            socket.emit('change:name', {
              name: $scope.newName
            }, function (result) {
              if (!result) {
                alert('There was an error changing your name');
              } else {

                changeName($scope.name, $scope.newName);

                $scope.name = $scope.newName;
                $scope.newName = '';
              }
            });
          }
        };

        $scope.messages = [];

        $scope.sendMessage = function () {
          if($scope.message != '') {
            socket.emit('send:message', {
              message: $scope.message
            });

            $scope.messages.push({
              user: $scope.name,
              text: $scope.message
            });
          }

          $scope.message = '';
        };
        //text chat controller

    });


text:
//
//  PPScanningDelegate.h
//  PhotoPayFramework
//
//  Created by Jura on 09/03/15.
//  Copyright (c) 2015 MicroBlink Ltd. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "PPOverlayViewController.h"
#import "PPScanningViewController.h"
#import "PPMetadata.h"

@class PPDetectorResult;

NS_ASSUME_NONNULL_BEGIN

/**
 * Protocol for obtaining scanning results
 */
@protocol PPScanningDelegate <NSObject>
@required

/**
 * Scanning library requested authorization for Camera access from the user, but the user declined it.
 * This case means scanning cannot be performed, because accessing camera images is now allowed.
 *
 * In this callback you have the chance to handle this case and present some kind of a message to the user on top
 * of scanningViewController.
 *
 *  @param scanningViewController Scanning view controller which was responsible for scanning
 */
- (void)scanningViewControllerUnauthorizedCamera:(UIViewController<PPScanningViewController> *)scanningViewController;

/**
 * Scanning library found an error. The error object is returned and contains
 * description of the error, in a specified language. Do your error handling here.
 *
 * Currently, only one situation can result with this callback being called:
 * - Using camera session resulted with AVCaptureSessionRuntimeErrorNotification notification
 *
 * The best way to handle this is to Log the error (GA, Crashlytics, Flurry) and let the user continue
 * using the app.
 *
 *  @param scanningViewController Scanning view controller which was responsible for scanning
 *  @param error                  Error object describing the error
 */
- (void)scanningViewController:(UIViewController<PPScanningViewController> *)scanningViewController didFindError:(NSError *)error;

/**
 * Scanning library was closed, usually by the user pressing close button and cancelling the scan
 *
 *  @param scanningViewController Scanning view controller responsible for scanning
 */
- (void)scanningViewControllerDidClose:(UIViewController<PPScanningViewController> *)scanningViewController;

/**
 * Scanning library did output scanning results (array of PPRecognizerResult objects). Do your next steps here.
 *
 * Depending on how you want to treat the result, you might want to
 * dismiss the scanningViewController here.
 *
 * This method is the default way for getting access to results of scanning.
 *
 * Note:
 * - there may be 0, 1, or more than one scanning results.
 * - each scanning result belongs to a common PPRecognizerResult type
 * - handle different types differently
 *
 *  @param scanningViewController scanningViewController Scanning view controller responsible for scanning
 *  @param results                Array of results returned by the scanner
 *
 * @see PPRecognizerResult
 */
- (void)scanningViewController:(nullable UIViewController<PPScanningViewController> *)scanningViewController
              didOutputResults:(NSArray<PPRecognizerResult *> *)results;

@optional

/**
 * Scanning library found an invalid license key.
 *
 * This can happen in two situations:
 *   1) Completely invalid license key was used (either it's not set, or it's garbage, or it expired)
 *   2) License key is in fact valid, but the features you're using aren't enabled by the license key
 *
 * If you don't implement this method, the SDK will present an UIAlertView with error and call your
 *
 * This is intended for you to easily spot the issue as soon as possible.
 *
 * If you implement this method, you have a chance to handle the situation. However, scanning won't work
 * without a valid license key!
 *
 *  @param scanningViewController Scanning view controller which was responsible for scanning
 *  @param error                  Error object describing the error
 */
- (void)scanningViewController:(UIViewController<PPScanningViewController> *)scanningViewController
    invalidLicenseKeyWithError:(NSError *)error;

/**
 * Called when Scanning library will display help. This can happen when the user presses
 * help button on scanning UI, or on first run of the application
 *
 *  @param scanningViewController scanningViewController Scanning view controller responsible for scanning
 */
- (void)scanningViewControllerWillPresentHelp:(UIViewController<PPScanningViewController> *)scanningViewController;

/**
 * Called when Scanning library requires the display of more info view
 *
 *  @param scanningViewController scanningViewController Scanning view controller responsible for scanning
 */
- (void)scanningViewControllerDidRequestMoreInfo:(UIViewController<PPScanningViewController> *)scanningViewController;

/**
 * Called when Scanning library starts detection of objects.
 * Detection cycle happens before recognition cycle and it attempts to find the location of specific object on an image.
 * Since detection and recognition are two separate events, it is possible for detection to be successful while recognition can fail (not
 * vice versa).
 *
 *  @param scanningViewController scanningViewController Scanning view controller responsible for scanning
 */
- (void)scanningViewControllerDidStartDetection:(UIViewController<PPScanningViewController> *)scanningViewController;

/**
 * Called when Scanning library finishes detection of objects.
 * Detection cycle happens before recognition cycle and it attempts to find the location of specific object on an image.
 * Since detection and recognition are two separate events, it is possible for detection to be successful while recognition can fail (not
 * vice versa).
 *
 * Returned PPDetectorResult object is an abstract class. Concrete classes (such as PPQuadDetectorResult) contain information about detected
 * object (i.e. location on the screen).
 *
 *  @param scanningViewController scanningViewController Scanning view controller responsible for scanning
 *  @param result result of object detection containing information of detection (i.e. location)
 */
- (void)scanningViewController:(UIViewController<PPScanningViewController> *)scanningViewController
    didFinishDetectionWithResult:(PPDetectorResult *)result;

/**
 * Called when Scanning library starts recognition cycle. Recognition cycle happens after successful detection cycle.
 *
 *  @param scanningViewController scanningViewController Scanning view controller responsible for scanning
 */
- (void)scanningViewControllerDidStartRecognition:(UIViewController<PPScanningViewController> *)scanningViewController;

- (void)scanningViewController:(UIViewController<PPScanningViewController> *)scanninvViewController
            didObtainOcrResult:(PPOcrLayout *)ocrResult
                withResultName:(NSString *)resultName;

/**
 * Called when coordinator obtaines metadata information
 *
 *  @param scanningViewController scanningViewController Scanning view controller responsible for scanning
 *  @param metadata               obtained metadata
 */
- (void)scanningViewController:(nullable UIViewController<PPScanningViewController> *)scanningViewController
             didOutputMetadata:(PPMetadata *)metadata;

@end

NS_ASSUME_NONNULL_END


text:
import os
from setuptools import setup, find_packages
version = '0.1.0'
README = os.path.join(os.path.dirname(__file__), 'README.md')
long_description = open(README).read()
setup(name='django-apiserver',
      version=version,
      description=("An API generation framework for Django."),
      long_description=long_description,
      classifiers=['Development Status :: 4 - Beta',
                   'Environment :: Web Environment',
                   'Framework :: Django',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: BSD License',
                   'Operating System :: OS Independent',
                   'Programming Language :: Python',
                   'Topic :: Software Development :: Libraries :: Python Modules',
                   'Topic :: Utilities'],
      keywords='api REST',
      author='Daniel Lindsley, Stijn Debrouwere',
      author_email='stijn@stdout.be',
      url='http://camayak.github.com/django-apiserver/',
      download_url='http://www.github.com/camayak/django-apiserver/tarball/master',
      license='BSD',
      packages=find_packages(),
      install_requires=[],
      )


text:
id: 587d7b7b367417b2b2512b14
title: Check For The Presence of an Element With indexOf()
challengeType: 1
---

## Description

Since arrays can be changed, or mutated, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, indexOf(), that allows us to quickly and easily check for the presence of an element on an array. indexOf() takes an element as a parameter, and when called, it returns the position, or index, of that element, or -1 if the element does not exist on the array.
For example:

let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];

fruits.indexOf('dates') // returns -1
fruits.indexOf('oranges') // returns 2
fruits.indexOf('pears') // returns 1, the first index at which the element exists

## Instructions

indexOf() can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, quickCheck, that takes an array and an element as arguments. Modify the function using indexOf() so that it returns true if the passed element exists on the array, and false if it does not.

## Tests

```yml
tests:
  - text: <code>quickCheck(["squash", "onions", "shallots"], "mushrooms")</code> should return <code>false</code>
    testString: assert.strictEqual(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'), false, '<code>quickCheck(["squash", "onions", "shallots"], "mushrooms")</code> should return <code>false</code>');
  - text: <code>quickCheck(["squash", "onions", "shallots"], "onions")</code> should return <code>true</code>
    testString: assert.strictEqual(quickCheck(['squash', 'onions', 'shallots'], 'onions'), true, '<code>quickCheck(["squash", "onions", "shallots"], "onions")</code> should return <code>true</code>');
  - text: <code>quickCheck([3, 5, 9, 125, 45, 2], 125)</code> should return <code>true</code>
    testString: assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true, '<code>quickCheck([3, 5, 9, 125, 45, 2], 125)</code> should return <code>true</code>');
  - text: <code>quickCheck([true, false, false], undefined)</code> should return <code>false</code>
    testString: assert.strictEqual(quickCheck([true, false, false], undefined), false, '<code>quickCheck([true, false, false], undefined)</code> should return <code>false</code>');
  - text: The <code>quickCheck</code> function should utilize the <code>indexOf()</code> method
    testString: assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1, 'The <code>quickCheck</code> function should utilize the <code>indexOf()</code> method');

```

## Challenge Seed

```js
function quickCheck(arr, elem) {
  // change code below this line

  // change code above this line
}

// change code here to test different cases:
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
```

## Solution

```js
// solution required
```


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--

 Copyright 2003 - 2017 The eFaps Team

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

-->
<ui-command xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>68e3de3d-5d76-4cfa-b2e1-fcc38e61a0cf</uuid>
    <file-application>eFapsApp-Costumers</file-application>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Costumers_OpportunityTree_Menu_Action_Edit</name>
        <access>
            <role>Costumers_Admin</role>
            <role>Costumers_Modifier</role>
        </access>
        <target>
            <form>Costumers_OpportunityForm</form>
            <execute program="org.efaps.esjp.common.uiform.Edit" />
            <trigger event="UI_ACCESSCHECK" method="check4Status"
                name="Costumers_OpportunityTree_Menu_Action_Edit.UI_ACCESSCHECK"
                program="org.efaps.esjp.admin.access.AccessCheck4UI">
                <property name="Status">Open</property>
            </trigger>
        </target>
        <property name="Target">modal</property>
        <property name="TargetMode">edit</property>
        <property name="WindowHeight">700</property>
        <property name="WindowWidth">900</property>
    </definition>
</ui-command>


text:
var _ = require('./util');

var client = require('./client');

var args = process.argv;
var node = args.shift();
var script = args.shift();
var command = args.shift();

function cliErrorHandler(err) {
  console.log('ERROR');
  console.log(err);
}

function cliResponse(promise) {
  promise.then(function(a) {
    if(_.isUndefined(a)) return console.log('Done!');
    console.log.apply(this, arguments);
  }, cliErrorHandler, function(status) {
    console.log('STATUS: ', status);
  });
}

function listServers() {
  client.servers.list().then(function(servers) {
    console.log('NAME \tHOST');
    console.log('=======\t=======');
    _.each(servers, function(server) {
      console.log(server.name+' \t'+server.host);
    });
  }, cliErrorHandler);
}

function printServer(server) {
  console.log('Name: '+server.name);
  console.log('Host: '+server.host);
}

function listInstances(serverName) {
  client.instances.list(serverName).then(function(_instances) {
    console.log('NAME \tBUILD\tSTATUS');
    console.log('=======\t=======\t=======');
    _.each(_instances, function(i, b) {
      console.log(i.name+'\t'+i.build+'\t'+i.status);
    });
  }, cliErrorHandler);
}

function printInstance(instance) {
  console.log('Name: '+instance.name);
  console.log('Build: '+instance.build);
  console.log('Status: '+instance.status);
  console.log('PID: '+instance.pid);
  console.log('Uptime: '+instance.uptime);
}

function listBuilds(serverName) {
   client.builds.list(serverName).then(function(builds) {
    console.log('ID\tSTATUS\tCOMMIT\tREFSPEC');
    console.log('=======\t=======\t=======\t=======');
    _.each(builds, function(b) {
      var ch = b.commithash ? b.commithash.substring(0,7) : '';
      console.log(b.id+'\t'+b.status+'\t'+ch+'\t'+b.refspec);
    });
  }, cliErrorHandler);
}

function printBuild(build) {
  console.log('Id: '+build.id);
  console.log('Status: '+ build.status + ' - ' + build.statusMsg);
  console.log('Repo Url: '+build.repoUrl);
  console.log('Refspec: '+build.refspec);
  console.log('Commit Hash: '+build.commithash);
}

client.start().then(function() {
  switch (command) {
    case 'config':
      var object = args.shift();
      var key = args.shift();
      var val = args.shift();
      if (!object) return console.log(_.config);
      if (!key) return console.log(_.config[object]);
      if (!val) return console.log(_.config[object][key]);
      client.configure(object, key, val);
      return;
    case 'create':
      var what = args.shift();
      switch (what) {
        case 'server':
          var name = args.shift();
          return cliResponse(client.servers.create(name));
        default:
          throw new Error('Cannot create '+what);
      }
      return cliResponse(client.servers.create());
    case 'add':
      command = args.shift();
      if(!command) throw new Error('Must specify what to add');
      switch (command) {
        case 'app':
          var name = args.shift();
          var repoUrl = args.shift();
          var deployKey = args.shift();
          if (deployKey && _.fs.existsSync(deployKey))
            deployKey = _.fs.readFileSync(deployKey, {encoding: 'utf8'});
          return cliResponse(client.apps.add(name, repoUrl, deployKey));
        case 'server':
          var name = args.shift();
          var host = args.shift();
          var key = args.shift();
          var cert = args.shift();
          if(!key) key = './'+name+'.key';
          if(!cert) cert = './'+name+'.crt';
          key = _.fs.readFileSync(key, {encoding: 'utf8'});
          cert = _.fs.readFileSync(cert, {encoding: 'utf8'});
          return cliResponse(client.servers.add(name, host, key, cert));
        default:
          throw new Error('Cannot add "'+command+'" here');
      }
    case 'server':
    case 'servers':
      serverName = args.shift();
      if(!serverName) return listServers();
      return client.servers.get(serverName).then(function(server) {
        // in the case of a "404", send them a list
        if(!server) return listServers();
        else {
          command = args.shift();
          if(!command) return printServer(server);
          switch (command) {
            case 'rename':
              var newName = args.shift();
              return cliResponse(client.servers.rename(serverName, newName));
            case 'remove':
              return cliResponse(client.servers.remove(serverName));
            case 'create':
              var type = args.shift();
              if(!type) throw new Error('Must specify what to add to this server');
              switch (type) {
                case 'build':
                  var appName = args.shift();
                  var refspec = args.shift();
                  return cliResponse(client.builds.build(serverName, appName, refspec));
                default:
                  throw new Error('Cannot add "'+type+'" to this server');
              }
            case 'builds':
            case 'build':
              var id = args.shift();
              if(!id) return listBuilds(serverName);
              else return client.builds.get(serverName, id).then(function(build) {
                command = args.shift();
                if(!command) return printBuild(build);
                switch (command) {
                  case 'remove':
                    return cliResponse(client.builds.remove(serverName, id));
                  default:
                    throw new Error('Cannot run "'+command+'" command on a build');
                }
              }, cliErrorHandler);
            case 'instances':
            case 'instance':
              var instanceName = args.shift();
              if(!instanceName) return listInstances(serverName);
              command = args.shift();
              if (command == 'set') {
                var buildId = args.shift();
                var configFile = args.shift()
                if (!configFile) configFile = './' + instanceName + '.json';
                var config = _.fs.readFileSync(configFile, {encoding: 'utf8'});
                config = JSON.parse(config);
                return cliResponse(client.instances.set(serverName, instanceName, buildId, config));
              }
              if (command == 'build') {
                var appName = args.shift();
                var refspec = args.shift();
                var configFile = args.shift()
                var config = configFile ? JSON.parse(_.fs.readFileSync(configFile, {encoding: 'utf8'})) : undefined;
                return cliResponse(client.instances.build(serverName, instanceName, appName, refspec, config));
              }
              client.instances.get(serverName, instanceName).then(function(instance) {
                if(!command) return printInstance(instance);
                switch (command) {
                  case 'remove':
                    return cliResponse(client.instances.remove(serverName, instanceName));
                  case 'config':
                    return cliResponse(client.instances.getConfig(serverName, instanceName));
                  case 'setConfig':
                    var configFile = args.shift()
                    if (!configFile) configFile = './' + instanceName + '.json';
                    var config = _.fs.readFileSync(configFile, {encoding: 'utf8'});
                    config = JSON.parse(config);
                    return cliResponse(client.instances.setConfig(serverName, instanceName, config));
                  case 'setBuild':
                    var buildId = args.shift()
                    return cliResponse(client.instances.setBuild(serverName, instanceName, buildId));
                  default:
                    throw new Error('Cannot run "'+command+'" command on an instance');
                }
              }, cliErrorHandler);
            default:
              throw new Error('Cannot run "'+command+'" on a server');
          }
        }
      }, cliErrorHandler);
    case 'app':
    case 'apps':
      appName = args.shift();
      if(!appName) return cliResponse(client.apps.list());
      return client.apps.get(appName).then(function(app) {
        // in the case of a "404", send them a list
        if(!app) return cliResponse(client.apps.list());
        else {
          command = args.shift();
          if(!command) console.log(app);
          switch (command) {
            case 'rename':
              var newName = args.shift();
              return cliResponse(client.apps.rename(appName, newName));
            case 'remove':
              return cliResponse(client.apps.remove(appName));
            default:
              throw new Error('Cannot run "'+command+'" on an app');
          }
        }
      }, cliErrorHandler);
    case 'domains':
    case 'domain':

      var domainName = args.shift();
      if(!domainName) return cliResponse(client.domains.list());
      command = args.shift();

      if(!command) return cliResponse(client.domains.get(domainName));
      else switch (command) {
        case 'records':
          command = args.shift();
          console.log('next command: ', command)
          if(!command) return cliResponse(client.domains.getRecords(domainName));
          else switch (command) {
            case 'add':
              var record = args.shift();
              var type = args.shift();
              var content = args.shift();
              var ttl = args.shift();
              console.log('adding', domainName, record, type, content, ttl )
              return cliResponse(client.domains.newRecord(domainName, record, type, content, ttl));
            default:
              throw new Error('Cannot run "'+command+'" on domain records');
          }
        default:
          throw new Error('Cannot run "'+command+'" on a domain');
      }
  }

});


text:
"use strict";
$(document).ready(function() {
    var metadata = new MetaData();
    $('#showTagBox').click(function() {
        var show = $('#showTagBox').is(':checked');
        if (show) {
            metadata.populateTags();
            $('.metaDataBox').show();
        } else {
            $('.tagPair').remove();
            $('.metaDataBox').hide();
        }
    });

    $('#searchForm .addButton').click(function(){
        metadata.addSearchParameter();
    });
    metadata.addSearchParameter();

    window.seqViewer.addUnveilListener(function(image) {
        var imageBox = $(image).parents('.imageBox');
        var mapillary_key = imageBox.find('.imageKey').val();
        metadata.imageUnveiled(mapillary_key);

        // Toggle favorite.
        $(imageBox).find('.favorite').css('cursor', 'pointer').click(function(d){
                var target = $(d.target);
                if (target.hasClass('selected')) {
                    metadata.removeFromList(mapillary_key, '--favorites');
                    target.removeClass('selected');
                } else {
                    metadata.addToList(mapillary_key, '--favorites');
                    target.addClass('selected');
                }
        });
        // Upvote + remove downvote.
        $(imageBox).find('.up').css('cursor', 'pointer').click(function(d){
                var target = $(d.target);
                if (target.hasClass('selected')) {
                    metadata.removeFromList(mapillary_key, '--upvotes');
                    target.removeClass('selected');
                } else {
                    metadata.addToList(mapillary_key, '--upvotes');
                    metadata.removeFromList(mapillary_key, '--downvotes');
                    target.addClass('selected');
                    target.parent().find('.down').removeClass('selected');
                }
        });
        // Downvote + remove upvote.
        $(imageBox).find('.down').css('cursor', 'pointer').click(function(d){
                var target = $(d.target);
                if (target.hasClass('selected')) {
                    metadata.removeFromList(mapillary_key, '--downvotes');
                    target.removeClass('selected');
                } else {
                    metadata.addToList(mapillary_key, '--downvotes');
                    metadata.removeFromList(mapillary_key, '--upvotes');
                    target.addClass('selected');
                    target.parent().find('.up').removeClass('selected');
                }
        });
    });

    $('#searchForm .searchButton').click(function(){
        var searchParameters = [];
        $(this).parent().find('.searchParam').each(function(i, searchParam){
            var key = $(searchParam).find('.key').val();
            var operator = $(searchParam).find('.operator').val();
            var value = $(searchParam).find('.value').val();
            if (key === "" || value === "") {
                return;
            }
            searchParameters.push({'key':key, 'op':operator, 'value':value});
        });

        var searchJson = JSON.stringify(searchParameters);
        $.ajax({
            type: "POST",
            url: 'http://localhost:7788/browser/api/search.py',
            data: searchJson,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
        }).done(function(imageKeys) {
            $('.searchButton').parent().find('.spinner').show();
            $('.searchButton').hide();
            window.seqViewer.showImagesByKeys(imageKeys);
        }).fail(function (){
            // TODO: Make proper error handling.
            console.log('fail');
        }).always(function(){
            $('.searchButton').parent().find('.spinner').hide();
            $('.searchButton').show();
        });
    });

});

/**
 * @param triggerFunction the function that must be called on triggering. It must accept an array
 * of the data given to the add() function.
 * A trigger function could fetch the data it is given and perhaps.
 */
function BatchTrigger(triggerFunction) {
    // Let a request be at most this number of milliseconds in the queue before triggering.
    this.triggerMS = 200;

    // When the queue gets this size, trigger no matter the time. The whole queue is triggered.
    this.triggerQueueSize = 100;

    this.triggerFunction = triggerFunction;

    this.data = [];

    this.settimeoutRunning = false;
    this.oldestDataEntry = -1;
}

BatchTrigger.prototype.trigger = function() {
    this.oldestDataEntry = -1;
    this.triggerFunction(this.data);
    this.data = [];
}

BatchTrigger.prototype.add = function(dataUnit) {
    this.data.push(dataUnit);
    if (this.oldestDataEntry < 0) {
        this.oldestDataEntry = Date.now();
    }

    this.evaluateTrigger();
}

BatchTrigger.prototype.evaluateTrigger = function() {
    if (this.data.length >= this.triggerQueueSize) {
        this.trigger();
    } else {
        this.settimeoutRunning = true;
        self = this;
        window.setTimeout(function(){
                this.settimeoutRunning = false;
                // If triggered due to another reason while we waited, skip doing it now and try later.
                if (self.oldestDataEntry >= 0 && Date.now() - self.oldestDataEntry >= self.triggerMS) {
                    self.trigger();
                } else if (! self.settimeoutRunning) {
                    self.evaluateTrigger();
                }

        }, this.triggerMS);
    }
}

function MetaData() {
    this.up = [];
    this.down = [];
    this.fav = [];

    var self = this;
    this.batchTrigger = new BatchTrigger(function(data){
        self.triggerBatchUpdate(data);
    });
}

MetaData.prototype.removeFromList = function(mapillary_key, listName) {
    this.ensureListStatus([], [mapillary_key], listName)
}

MetaData.prototype.addToList = function(mapillary_key, listName) {
    this.ensureListStatus([mapillary_key], [], listName)
}

MetaData.prototype.ensureListStatus = function(keysOnList, keysOffList, listName) {
   var listJson = JSON.stringify({'list':listName, 'on':keysOnList, 'off':keysOffList});
   var self = this;
   $.ajax({
       type: "POST",
       url: 'http://localhost:7788/browser/api/toggleList.py',
       data: listJson,
       contentType: "application/json; charset=utf-8",
       dataType: "json",
   }).done(function(status) {
       console.log("Done", status);
    }).fail(function (){
        // TODO: Make proper error handling.
        console.log('fail');
    });
}

MetaData.prototype.imageUnveiled = function(mapillary_key) {
    this.batchTrigger.add(mapillary_key);
}

MetaData.prototype.triggerBatchUpdate = function(data) {
   var listJson = JSON.stringify({'lists' : ['--favorites', '--upvotes', '--downvotes'], 'images' : data});
   var self = this;
   $.ajax({
       type: "POST",
       url: 'http://localhost:7788/browser/api/getLists.py',
       data: listJson,
       contentType: "application/json; charset=utf-8",
       dataType: "json",
   }).done(function(lists) {
       $.each(lists, function(i, keyVal){
           var action = keyVal[0];
           var key = keyVal[1];
           if (action === "--upvotes") {
               self.addUp(key);
           } else if  (action === "--downvotes") {
               self.addDown(key);
           } else if  (action === "--favorites") {
               self.addFavorite(key);
           } else {
              console.log("Not on list", key);
           }
        });
    }).fail(function (){
        // TODO: Make proper error handling.
        console.log('fail');
    });
}

MetaData.prototype.addFavorite = function(mapillary_key) {
    this.fav.push(mapillary_key);
    //.removeClass('glyphicon-heart-empty').addClass('glyphicon-heart')
    $('.imageKey[value='+mapillary_key+']').closest('.imageBox').find('.favorite').addClass('selected');
}

MetaData.prototype.addUp = function(mapillary_key) {
    this.up.push(mapillary_key);
    $('.imageKey[value='+mapillary_key+']').closest('.imageBox').find('.up').addClass('selected');
    console.log("Add up", mapillary_key);
}

MetaData.prototype.addDown = function(mapillary_key) {
    this.down.push(mapillary_key);
    $('.imageKey[value='+mapillary_key+']').closest('.imageBox').find('.down').addClass('selected');
}

MetaData.prototype.addSearchParameter = function() {
    var template = $('#searchParamTemplate');
    var searchParam = template.clone();
    searchParam.removeAttr('id');
    $('#searchForm .searchButton').before(searchParam);
}

MetaData.prototype.renderTagPair = function(key, value) {
    var keyTag = $('<input type="text" name="key" class="key">').attr('value', key);
    var valTag = $('<input type="text" name="value" class="value">').attr('value', value);
    var removeButton = $('<button type="button" class="btn btn-default glyphicon glyphicon-remove removeButton"></button>').click(function(){
        $(this).parent().remove();
    });
    return $('<div class="tagPair">').append(keyTag).append(valTag).append(removeButton);
}

MetaData.prototype.addTagPair = function(mapillary_key, tagPair) {
    $('[value="'+mapillary_key+'"]').parent().find('.saveButton').before(tagPair);
}

MetaData.prototype.populateTags = function() {
    // Get tags for all images.
    var keys = [];
    $.each($('.imageKey'), function(i, v) {
        keys[keys.length] = $(v).val();
    });

    var self = this;
    $.ajax({
        type: "POST",
        url: 'http://localhost:7788/browser/api/getTags.py',
        data: JSON.stringify(keys),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
    }).done(function(keys) {
        $.each(keys, function(i, entry){
            var mapillary_key = entry[0];
            var key = entry[1];
            var value = entry[2];
            var tagPair = self.renderTagPair(key, value);
            self.addTagPair(mapillary_key, tagPair);
        });
    }).fail(function (){
        console.log('fail');
    }).always(function(){
        // TODO: Remove spinner.
    });

}

MetaData.prototype.getTagData = function(button) {
    var tagPairs = button.parent().find('.tagPair');
    var data = {};

    $(tagPairs).each(function(i, pair){
        var key = $(pair).find('.key').val();
        var value = $(pair).find('.value').val();
        data[key] = value;
    });

    var imageKey = button.parent().find('.imageKey').val();

    return JSON.stringify({tags : data, imageKey : imageKey});
}

MetaData.prototype.buttonsAdded = function(prefix) {
    var self = this;
    $('.saveButton').click(function() {
        var button = $(this);
        var data = self.getTagData(button);
        $.ajax({
            type: "POST",
            url: 'http://localhost:7788/browser/api/saveTags.py',
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
        }).done(function() {
            $('.saveButton').parent().find('.spinner').show()
            $('.saveButton').hide()
            console.log('ok');
        }).fail(function (){
            // TODO: Make proper error handling.
            console.log('fail');
        }).always(function(){
            $('.saveButton').parent().find('.spinner').hide()
            $('.saveButton').show()
        });
    });

    $('.addButton').click(function(){
        var button = $(this);
        button.parent().find('.saveButton').before(self.renderTagPair("", ""));
    });
}


text:
package de.codescape.jira.plugins.scrumpoker.condition;

import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.plugin.webfragment.model.JiraHelper;
import com.atlassian.jira.user.ApplicationUser;
import de.codescape.jira.plugins.scrumpoker.service.ScrumPokerSessionService;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;

public class JoinScrumPokerForIssueConditionTest {

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Mock
    private ScrumPokerSessionService scrumPokerSessionService;

    @InjectMocks
    private JoinScrumPokerForIssueCondition joinScrumPokerForIssueCondition;

    @Mock
    private Issue issue;

    @Mock
    private ApplicationUser applicationUser;

    @Mock
    private JiraHelper jiraHelper;

    @Test
    public void shouldNotDisplayWhenNoActiveSessionForIssueExists() {
        when(issue.getKey()).thenReturn("KEY-1");
        when(scrumPokerSessionService.hasActiveSession(issue.getKey())).thenReturn(false);

        assertThat(joinScrumPokerForIssueCondition.shouldDisplay(applicationUser, issue, jiraHelper), is(false));
    }

    @Test
    public void shouldDisplayWhenActiveSessionForIssueExists() {
        when(issue.getKey()).thenReturn("KEY-1");
        when(scrumPokerSessionService.hasActiveSession(issue.getKey())).thenReturn(true);

        assertThat(joinScrumPokerForIssueCondition.shouldDisplay(applicationUser, issue, jiraHelper), is(true));
    }

}