text:
var should          = require('should'),
    builder         = require('buffer-builder'),

    toBuilder       = require('../lib/encoded_to_buffer_builder'),
    tu              = require('./testing_utils');

describe('toBufferBuilder', function() {
    describe('#number()', function () {
        it('should encode to smallest possible', function() {
            var input = ['ulong', 0];
            var expected = tu.newBuf([0x44]);
            tu.shouldBufEql(expected, toBuilder(input));
            input = ['ulong', 123];
            expected = tu.newBuf([0x53, 123]);
            tu.shouldBufEql(expected, toBuilder(input));
            input = ['uint', 250];
            expected = tu.newBuf([0x52, 250]);
            tu.shouldBufEql(expected, toBuilder(input));
        });
    });

    describe('#variable()', function() {
        it('should encode symbols', function() {
            var input = ['symbol', 'abc'];
            var expected = tu.newBuf([0xa3, 3, 'abc']);
            tu.shouldBufEql(expected, toBuilder(input));
        })
    });

    describe('#described()', function() {
        it('should allow simple descriptors, values', function() {
            var str = 'open frame contents';
            var input = ['described', ['ulong', 0x10], str];
            var expected = tu.newBuf([0x00, 0x53, 0x10, 0xa1, str.length, str]);
            tu.shouldBufEql(expected, toBuilder(input));
        });
    });

    describe('#list()', function() {
        it('should encode simple lists', function() {
            var input = ['list', 'val1', ['int', -123]];
            var expected = tu.newBuf([0xc0, 1 + 6 + 2, 2, 0xa1, 4, 'val1', 0x54, -123]);
            tu.shouldBufEql(expected, toBuilder(input));
        });
        it('should encode empty lists', function() {
            var input = ['list'];
            var expected = tu.newBuf([0x45]);
            tu.shouldBufEql(expected, toBuilder(input));
        })
    });

    describe('#map()', function() {
        it('should encode simple maps', function() {
            var input = ['map', 'key1', ['int', -123]];
            var expected = tu.newBuf([0xc1, 1 + 6 + 2, 2, 0xa1, 4, 'key1', 0x54, -123]);
            tu.shouldBufEql(expected, toBuilder(input));
        });
        it('should encode empty maps', function() {
            var input = ['map'];
            var expected = tu.newBuf([0xc1, 0, 0]);
            tu.shouldBufEql(expected, toBuilder(input));
        })
    });

    describe('#array()', function() {
        it('should be able to encode arrays of symbols', function () {
            var input = ['array', 'symbol', 'array', 'of', 'symbols'];
            var expected = tu.newBuf([0xe0, 1 + 1 + 6 + 3 + 8, 3, 0xa3, 5, 'array', 2, 'of', 7, 'symbols']);
            tu.shouldBufEql(expected, toBuilder(input));
        });
    });
});


text:
package org.apache.ignite.internal.processors.cache.distributed.dht;

import org.apache.ignite.*;
import org.apache.ignite.cache.*;
import org.apache.ignite.cache.eviction.fifo.*;
import org.apache.ignite.cluster.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.events.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.processors.cache.distributed.near.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.spi.discovery.tcp.*;
import org.apache.ignite.spi.discovery.tcp.ipfinder.*;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*;
import org.apache.ignite.testframework.junits.common.*;

import java.util.*;
import java.util.concurrent.atomic.*;

import static org.apache.ignite.cache.CacheAtomicityMode.*;
import static org.apache.ignite.cache.CacheDistributionMode.*;
import static org.apache.ignite.cache.CacheMode.*;
import static org.apache.ignite.cache.CacheRebalanceMode.*;
import static org.apache.ignite.events.EventType.*;

/**
 * Tests for dht cache eviction.
 */
public class GridCacheDhtEvictionSelfTest extends GridCommonAbstractTest {
    /** */
    private static final int GRID_CNT = 2;

    /** */
    private TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);

    /** Default constructor. */
    public GridCacheDhtEvictionSelfTest() {
        super(false /* don't start grid. */);
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(gridName);

        TcpDiscoverySpi disco = new TcpDiscoverySpi();

        disco.setIpFinder(ipFinder);

        cfg.setDiscoverySpi(disco);

        CacheConfiguration cacheCfg = defaultCacheConfiguration();

        cacheCfg.setCacheMode(PARTITIONED);
        cacheCfg.setRebalanceMode(NONE);
        cacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
        cacheCfg.setSwapEnabled(false);
        cacheCfg.setEvictSynchronized(true);
        cacheCfg.setEvictNearSynchronized(true);
        cacheCfg.setAtomicityMode(TRANSACTIONAL);
        cacheCfg.setDistributionMode(NEAR_PARTITIONED);
        cacheCfg.setBackups(1);

        // Set eviction queue size explicitly.
        cacheCfg.setEvictMaxOverflowRatio(0);
        cacheCfg.setEvictSynchronizedKeyBufferSize(1);
        cacheCfg.setEvictionPolicy(new CacheFifoEvictionPolicy(10000));
        cacheCfg.setNearEvictionPolicy(new CacheFifoEvictionPolicy(10000));

        cfg.setCacheConfiguration(cacheCfg);

        return cfg;
    }

    /** {@inheritDoc} */
    @SuppressWarnings({"ConstantConditions"})
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        if (GRID_CNT < 2)
            throw new IgniteCheckedException("GRID_CNT must not be less than 2.");

        startGrids(GRID_CNT);
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        super.afterTestsStopped();

        stopAllGrids();
    }

    /** {@inheritDoc} */
    @SuppressWarnings({"SizeReplaceableByIsEmpty"})
    @Override protected void beforeTest() throws Exception {
        for (int i = 0; i < GRID_CNT; i++) {
            assert near(grid(i)).size() == 0;
            assert dht(grid(i)).size() == 0;

            assert near(grid(i)).isEmpty();
            assert dht(grid(i)).isEmpty();
        }
    }

    /** {@inheritDoc} */
    @SuppressWarnings({"unchecked"})
    @Override protected void afterTest() throws Exception {
        for (int i = 0; i < GRID_CNT; i++) {
            near(grid(i)).removeAll();

            assert near(grid(i)).isEmpty() : "Near cache is not empty [idx=" + i + "]";
            assert dht(grid(i)).isEmpty() : "Dht cache is not empty [idx=" + i + "]";
        }
    }

    /**
     * @param node Node.
     * @return Grid for the given node.
     */
    private Ignite grid(ClusterNode node) {
        return G.ignite(node.id());
    }

    /**
     * @param g Grid.
     * @return Near cache.
     */
    @SuppressWarnings({"unchecked"})
    private GridNearCacheAdapter<Integer, String> near(Ignite g) {
        return (GridNearCacheAdapter)((IgniteKernal)g).internalCache();
    }

    /**
     * @param g Grid.
     * @return Dht cache.
     */
    @SuppressWarnings({"unchecked", "TypeMayBeWeakened"})
    private GridDhtCacheAdapter<Integer, String> dht(Ignite g) {
        return ((GridNearCacheAdapter)((IgniteKernal)g).internalCache()).dht();
    }

    /**
     * @param key Key.
     * @return Primary node for the given key.
     */
    private Collection<ClusterNode> keyNodes(Object key) {
        return grid(0).affinity(null).mapKeyToPrimaryAndBackups(key);
    }

    /**
     * @param nodeId Node id.
     * @return Predicate for events belonging to specified node.
     */
    private IgnitePredicate<Event> nodeEvent(final UUID nodeId) {
        assert nodeId != null;

        return new P1<Event>() {
            @Override public boolean apply(Event e) {
                info("Predicate called [e.nodeId()=" + e.node().id() + ", nodeId=" + nodeId + ']');

                return e.node().id().equals(nodeId);
            }
        };
    }

    /**
     * JUnit.
     *
     * @throws Exception If failed.
     */
    @SuppressWarnings("NullArgumentToVariableArgMethod")
    public void testSingleKey() throws Exception {
        Integer key = 1;

        Collection<ClusterNode> nodes = new ArrayList<>(keyNodes(key));

        ClusterNode primary = F.first(nodes);

        assert primary != null;

        nodes.remove(primary);

        ClusterNode backup = F.first(nodes);

        assert backup != null;

        assert !F.eqNodes(primary, backup);

        info("Key primary node: " + primary.id());
        info("Key backup node: " + backup.id());

        GridNearCacheAdapter<Integer, String> nearPrimary = near(grid(primary));
        GridDhtCacheAdapter<Integer, String> dhtPrimary = dht(grid(primary));

        GridNearCacheAdapter<Integer, String> nearBackup = near(grid(backup));
        GridDhtCacheAdapter<Integer, String> dhtBackup = dht(grid(backup));

        String val = "v1";

        // Put on primary node.
        nearPrimary.put(key, val, null);

        assertEquals(val, nearPrimary.peek(key));
        assertEquals(val, dhtPrimary.peek(key));

        assertEquals(val, nearBackup.peek(key));
        assertEquals(val, dhtBackup.peek(key));

        GridDhtCacheEntry entryPrimary = (GridDhtCacheEntry)dhtPrimary.peekEx(key);
        GridDhtCacheEntry entryBackup = (GridDhtCacheEntry)dhtBackup.peekEx(key);

        assert entryPrimary != null;
        assert entryBackup != null;

        assertTrue(entryPrimary.readers().isEmpty());
        assertTrue(entryBackup.readers().isEmpty());

        IgniteFuture<Event> futBackup =
            waitForLocalEvent(grid(backup).events(), nodeEvent(backup.id()), EVT_CACHE_ENTRY_EVICTED);

        IgniteFuture<Event> futPrimary =
            waitForLocalEvent(grid(primary).events(), nodeEvent(primary.id()), EVT_CACHE_ENTRY_EVICTED);

        // Evict on primary node.
        // It should trigger dht eviction and eviction on backup node.
        grid(primary).jcache(null).localEvict(Collections.<Object>singleton(key));

        // Give 5 seconds for eviction event to occur on backup and primary node.
        futBackup.get(3000);
        futPrimary.get(3000);

        assertEquals(0, nearPrimary.size());

        assertNull(nearPrimary.peekEx(key));
        assertNull(dhtPrimary.peekEx(key));

        assertNull(nearBackup.peekEx(key));
        assertNull(dhtBackup.peekEx(key));
    }

    /**
     * JUnit.
     *
     * @throws Exception If failed.
     */
    @SuppressWarnings("NullArgumentToVariableArgMethod")
    public void testMultipleKeys() throws Exception {
        final int keyCnt = 1000;

        final Ignite primaryIgnite = grid(0);
        final Ignite backupIgnite = grid(1);

        GridNearCacheAdapter<Integer, String> nearPrimary = near(primaryIgnite);
        GridDhtCacheAdapter<Integer, String> dhtPrimary = dht(primaryIgnite);

        GridNearCacheAdapter<Integer, String> nearBackup = near(backupIgnite);
        GridDhtCacheAdapter<Integer, String> dhtBackup = dht(backupIgnite);

        Collection<Integer> keys = new ArrayList<>(keyCnt);

        for (int key = 0; keys.size() < keyCnt; key++)
            if (F.eqNodes(primaryIgnite.cluster().localNode(), F.first(keyNodes(key))))
                keys.add(key++);

        info("Test keys: " + keys);

        // Put on primary node.
        for (Integer key : keys)
            nearPrimary.put(key, "v" + key, null);

        for (Integer key : keys) {
            String val = "v" + key;

            assertEquals(val, nearPrimary.peek(key));
            assertEquals(val, dhtPrimary.peek(key));

            assertEquals(val, nearBackup.peek(key));
            assertEquals(val, dhtBackup.peek(key));
        }

        final AtomicInteger cntBackup = new AtomicInteger();

        IgniteFuture<Event> futBackup = waitForLocalEvent(backupIgnite.events(), new P1<Event>() {
            @Override public boolean apply(Event e) {
                return e.node().id().equals(backupIgnite.cluster().localNode().id()) &&
                    cntBackup.incrementAndGet() == keyCnt;
            }
        }, EVT_CACHE_ENTRY_EVICTED);

        final AtomicInteger cntPrimary = new AtomicInteger();

        IgniteFuture<Event> futPrimary = waitForLocalEvent(primaryIgnite.events(), new P1<Event>() {
            @Override public boolean apply(Event e) {
                return e.node().id().equals(primaryIgnite.cluster().localNode().id()) &&
                    cntPrimary.incrementAndGet() == keyCnt;
            }
        }, EVT_CACHE_ENTRY_EVICTED);

        // Evict on primary node.
        // Eviction of the last key should trigger queue processing.
        for (Integer key : keys)
            primaryIgnite.jcache(null).localEvict(Collections.<Object>singleton(key));

        // Give 5 seconds for eviction events to occur on backup and primary node.
        futBackup.get(3000);
        futPrimary.get(3000);

        info("nearBackupSize: " + nearBackup.size());
        info("dhtBackupSize: " + dhtBackup.size());
        info("nearPrimarySize: " + nearPrimary.size());
        info("dhtPrimarySize: " + dhtPrimary.size());

        // Check backup node first.
        for (Integer key : keys) {
            String msg = "Failed key: " + key;

            assertNull(msg, nearBackup.peek(key));
            assertNull(msg, dhtBackup.peek(key));
            assertNull(msg, nearBackup.peekEx(key));
            assertNull(msg, dhtBackup.peekEx(key));
        }

        for (Integer key : keys) {
            String msg = "Failed key: " + key;

            assertNull(msg, nearPrimary.peek(key));
            assertNull(msg, dhtPrimary.peek(key));
            assertNull(msg, nearPrimary.peekEx(key));
            assertNull(dhtPrimary.peekEx(key));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Tolk
  class ApplicationController < Tolk.config.base_controller.constantize
    include Tolk::Pagination::Methods

    helper :all
    protect_from_forgery

    cattr_accessor :authenticator
    before_action :authenticate

    def authenticate
#      self.authenticator.bind(self).call if self.authenticator && self.authenticator.respond_to?(:call)
      instance_exec(nil, &self.authenticator) if self.authenticator && self.authenticator.respond_to?(:instance_exec)
    end

    def ensure_no_primary_locale
      redirect_to tolk.locales_path if @locale.primary?
    end
  end
end


text: {{title | translate}}


text:
package org.credo.repository;

import org.credo.security.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 *
 * @author ZhaoQian
 * @date: 2014年8月3日
 */
@Repository
public interface RoleRepository extends JpaRepository<Role, Long>
{

}


text:
var express    = require('express'),
    app        = express(),
    bodyParser = require('body-parser'),
    mongoose   = require('mongoose'),
    port       = 3000,
    env        = process.env.NODE_ENV = process.env.NODE_ENV || 'development'; // production

var config = require('./server/config/config')[env];
    require('./server/config/express')(app, config);
    require('./server/config/mongoose')(config);
    require('./server/config/routes')(app);

app.listen(config.port);
console.log('server running on port ' + port);


text:
package org.ros.internal.node.topic;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ros.exception.RemoteException;
import org.ros.internal.node.client.SlaveClient;
import org.ros.internal.node.response.Response;
import org.ros.internal.node.server.NodeIdentifier;
import org.ros.internal.node.server.SlaveServer;
import org.ros.internal.node.xmlrpc.XmlRpcTimeoutException;
import org.ros.internal.transport.ProtocolDescription;
import org.ros.internal.transport.ProtocolNames;
import org.ros.node.topic.Publisher;
import org.ros.node.topic.Subscriber;

/**
 * A {@link Runnable} which is used whenever new publishers are being added to a
 * {@link DefaultSubscriber}. It takes care of registration between the {@link Subscriber}
 * and remote {@link Publisher}.
 *
 * @author damonkohler@google.com (Damon Kohler)
 */
class UpdatePublisherRunnable<MessageType> implements Runnable {

  private static final Log log = LogFactory.getLog(UpdatePublisherRunnable.class);

  private final DefaultSubscriber<MessageType> subscriber;
  private final PublisherIdentifier publisherIdentifier;
  private final NodeIdentifier nodeIdentifier;

  /**
   * @param subscriber
   * @param nodeIdentifier
   *          {@link NodeIdentifier} of the {@link Subscriber}'s
   *          {@link SlaveServer}
   * @param publisherIdentifier
   *          {@link PublisherIdentifier} of the new {@link Publisher}
   */
  public UpdatePublisherRunnable(DefaultSubscriber<MessageType> subscriber,
      NodeIdentifier nodeIdentifier, PublisherIdentifier publisherIdentifier) {
    this.subscriber = subscriber;
    this.nodeIdentifier = nodeIdentifier;
    this.publisherIdentifier = publisherIdentifier;
  }

  @Override
  public void run() {
    SlaveClient slaveClient;
    try {
      slaveClient = new SlaveClient(nodeIdentifier.getName(), publisherIdentifier.getNodeUri());
      Response<ProtocolDescription> response =
          slaveClient.requestTopic(subscriber.getTopicName(), ProtocolNames.SUPPORTED);
      // TODO(kwc): all of this logic really belongs in a protocol handler
      // registry.
      ProtocolDescription selected = response.getResult();
      if (ProtocolNames.SUPPORTED.contains(selected.getName())) {
        subscriber.addPublisher(publisherIdentifier, selected.getAddress());
      } else {
        log.error("Publisher returned unsupported protocol selection: " + response);
      }
    } catch (RemoteException e) {
      // TODO(damonkohler): Retry logic is needed at the XML-RPC layer.
      log.error(e);
    } catch (XmlRpcTimeoutException e) {
      // TODO(damonkohler): see above note re: retry
      log.error(e);
    } catch (RuntimeException e) {
      // TODO(kwc):
      // org.apache.xmlrpc.XmlRpcException/java.net.ConnectException's are
      // leaking through as java.lang.reflect.UndeclaredThrowableExceptions.
      // This is happening whenever the node attempts to connect to a stale
      // publisher (i.e. a publisher that is no longer online).
      log.error(e);
    }
  }
}


text:
package com.sao.spring.learning.session;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * Created by saoprb on 3/12/17.
 */
@Component
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix = "hibernate")
public class HibernateProperties {

    private String dialect;
    private String currentSessionContextClass;
    private Boolean showSql;

    public String getDialect() {
        return dialect;
    }

    public void setDialect(String dialect) {
        this.dialect = dialect;
    }

    public String getCurrentSessionContextClass() {
        return currentSessionContextClass;
    }

    public void setCurrentSessionContextClass(String currentSessionContextClass) {
        this.currentSessionContextClass = currentSessionContextClass;
    }

    public Boolean getShowSql() {
        return showSql;
    }

    public void setShowSql(Boolean showSql) {
        this.showSql = showSql;
    }
}


text:
package main

import (
	"fmt"
	"github.com/jasdel/harvester/internal/common"
	"github.com/jasdel/harvester/internal/queue"
	"github.com/jasdel/harvester/internal/storage"
	"log"
	"net/http"
	"time"
)

// Searches for and extracts URLs from a page. Those URLs are then queued up for recursive
// crawling with maximum depth of the passed in max level.
type Crawler struct {
	urlQueuePub queue.Publisher
	sc          *storage.Client
	maxLevel    int
}

// Creates a new instance of the Crawler. The crawler is save to be run across multiple
// go-routines.
func NewCrawler(urlQueuePub queue.Publisher, sc *storage.Client, maxLevel int) *Crawler {
	return &Crawler{
		urlQueuePub: urlQueuePub,
		sc:          sc,
		maxLevel:    maxLevel,
	}
}

// Retrieves the content of the item URL scrapes it for URLs.  Those descendant URLs
// are then either added back into the URL queue or added directly to a job's results.
// The URLs will be added to the URL queue if when the passed in item's Level is incremented
// and won't breach the Max Level of distance from the origin URL.
//
// When a crawl is complete the associated pending URL with this item will be removed,
// and a check to determine if there are anymore pending URLs for the item's Origin
// will be made. If there are no longer any pending URLs the Origin's Job URL entry
// will be marked as completed.
func (c *Crawler) Crawl(item *common.URLQueueItem) {
	startedAt := time.Now()
	urlClient := c.sc.URLClient()

	defer func() {
		// Make sure the Job is cleaned up even in if an error happens.
		if err := urlClient.DeletePending(item.JobId, item.URLId, item.OriginId); err != nil {
			log.Println("crawl: Failed to delete pending record for", item.URLId, item.OriginId)
		}
		log.Println("crawl: Finished crawling of", item.URLId, item.Level, "duration", time.Now().Sub(startedAt).String())

		// If there are no more pending entries for this origin, all jobs which contain that
		// origin which are not already complete can be marked as complete.
		if complete, err := urlClient.UpdateJobURLIfComplete(item.JobId, item.OriginId); err != nil {
			log.Println("crawl: Failed to update if Job URL is complete", item.OriginId, err)
		} else if complete {
			log.Println("crawl: Marked Job URL as complete", item.JobId, item.OriginId)
		}

	}()

	urlRec, err := c.sc.URLClient().GetURLById(item.URLId)
	if err != nil || urlRec == nil {
		log.Println("Failed to get URL record for URLId", item.URLId)
		return
	}

	mime, urls, err := Scrape(urlRec.URL, http.DefaultClient)
	if err != nil {
		log.Println("crawl: Failed to request and scrape", item.URLId, urlRec.URL, err)
		return
	}

	log.Println("crawl: Request and Scrape complete URL", item.URLId, urlRec.URL, "mime:", mime, "level", item.Level, "descendants", len(urls), "duration", time.Now().Sub(startedAt).String(), "error", err)

	// Update mime type for the URL
	if err := urlClient.MarkCrawled(item.URLId, mime); err != nil {
		log.Println("crawl: failed to add update URL's mime type", item.URLId, mime, err)
		return
	}
	// Update the local urlRec mime value so don't need to re-query for it.
	urlRec.Mime = mime

	// Only add items to the result if they are greater than the first layer
	// because the first layer is the URLs that are used to start a job,
	// so they do not make sense to be inserted into the results without a refer.
	if item.Level > 0 {
		urlClient.AddResult(item.JobId, item.ReferId, item.URLId)
	}

	if err := c.processURLDescendants(item, urls); err != nil {
		log.Println("crawl: failed to process descendants", err)
	}
}

// Iterates over the raw URLs fond on the page. These URLs will be added back into the
// URL Queue if the max level distance from the origin hasn't been reached yet. If the
// level has been reached the URLs will be just added to the Origin's Job URL result.
func (c *Crawler) processURLDescendants(referItem *common.URLQueueItem, urls []string) error {
	urlClient := c.sc.URLClient()

	for i := 0; i < len(urls); i++ {
		u := urls[i]

		kind := common.GuessURLsMime(u)
		urlRec, err := urlClient.GetOrAddURLByURL(u, kind)
		if err != nil {
			return fmt.Errorf("Failed to get or add URL", u)
		}

		// Link the descendant with the refer, Ignore errors about duplicates
		urlClient.AddLink(urlRec.Id, referItem.URLId)

		// Only process the URLs for queue, or skipping, if the max level would
		// wouldn't be reached yet.
		if referItem.Level+1 < c.maxLevel {
			if common.CanSkipMime(kind) {
				urlClient.AddResult(referItem.JobId, referItem.URLId, urlRec.Id)
			}

			q := &common.URLQueueItem{
				JobId:      referItem.JobId,
				OriginId:   referItem.OriginId,
				ReferId:    referItem.URLId,
				URLId:      urlRec.Id,
				Level:      referItem.Level + 1,
				ForceCrawl: referItem.ForceCrawl,
			}
			if err := urlClient.AddPending(referItem.JobId, urlRec.Id, q.OriginId); err != nil {
				log.Println("crawl: failed to add pending URL", err)
			}

			c.urlQueuePub.Send(q)
		} else {
			// For any URL that will not be enqueued, add it as a result instead
			urlClient.AddResult(referItem.JobId, referItem.URLId, urlRec.Id)
		}
	}

	return nil
}


text:
namespace MassTransit.PipeConfigurators
{
    using System.Collections.Generic;
    using GreenPipes;
    using Pipeline.Filters;

    public class DeadLetterPipeSpecification :
        IPipeSpecification<ReceiveContext>
    {
        readonly IPipe<ReceiveContext> _deadLetterPipe;

        public DeadLetterPipeSpecification(IPipe<ReceiveContext> deadLetterPipe)
        {
            _deadLetterPipe = deadLetterPipe;
        }

        public void Apply(IPipeBuilder<ReceiveContext> builder)
        {
            builder.AddFilter(new DeadLetterFilter(_deadLetterPipe));
        }

        public IEnumerable<ValidationResult> Validate()
        {
            if (_deadLetterPipe == null)
                yield return this.Failure("RescuePipe", "must not be null");
        }
    }
}


text:
package com.almoturg.sprog.data;

import android.util.JsonReader;
import android.util.JsonToken;

import com.almoturg.sprog.model.ParentComment;
import com.almoturg.sprog.model.Poem;
import com.almoturg.sprog.model.SprogDbHelper;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

class PoemParser {
    private JsonReader reader;
    private HashMap<String, Poem> mainpoem_links;
    private HashSet<String> read_poems;
    private HashSet<String> favorite_poems;
    private MarkdownConverter markdownConverter;

    PoemParser(InputStream in, SprogDbHelper dbHelper, MarkdownConverter markdownConverter)
            throws IOException {
        this.markdownConverter = markdownConverter;
        read_poems = dbHelper.getReadPoems();
        favorite_poems = dbHelper.getFavoritePoems();
        reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        mainpoem_links = new HashMap<>();
        reader.beginArray();
    }

    List<Poem> getPoems(int n) throws IOException {
        if (reader == null) {
            return null;
        }
        List<Poem> poems = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (!reader.hasNext()) {
                reader.close();
                reader = null;
                break;
            }
            poems.add(readPoem());
        }
        return poems;
    }

    private Poem readPoem() throws IOException {
        int gold = -1;
        int silver = -1;
        int platinum = -1;
        int score = -1;
        String content = null;
        double timestamp = -1;
        String post_title = null;
        String post_author = null;
        String post_content = null;
        String post_url = null;
        List<ParentComment> parents = null;
        String link = null;
        Poem main_poem = null;
        boolean read = false;
        boolean favorite = false;

        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            JsonToken check = reader.peek();
            if (check == JsonToken.NULL) {
                reader.skipValue();
                continue;
            }
            switch (name) {
                case "gold":
                    gold = reader.nextInt();
                    break;
                case "silver":
                    silver = reader.nextInt();
                    break;
                case "platinum":
                    platinum = reader.nextInt();
                    break;
                case "score":
                    score = reader.nextInt();
                    break;
                case "link":
                    link = reader.nextString();
                    main_poem = mainpoem_links.get(link);
                    break;
                case "orig_content":
                    content = reader.nextString().replace("^", "");
                    break;
                case "timestamp":
                    timestamp = reader.nextDouble();
                    break;
                case "submission_title":
                    post_title = reader.nextString();
                    break;
                case "submission_url":
                    post_url = reader.nextString();
                    break;
                case "submission_user":
                    post_author = formatUsername(reader.nextString());
                    break;
                case "orig_submission_content":
                    post_content = reader.nextString().replace("^", "");
                    break;
                case "parents":
                    parents = readParentCommentArray();
                    break;
                default:
                    reader.skipValue();
                    break;
            }
        }
        reader.endObject();

        CharSequence first_line;

        first_line = markdownConverter.convertMarkdown(
                content.trim().split("\n", 2)[0].trim() + "...");

        if (read_poems.contains(link)) {
            read = true;
        }
        if (favorite_poems.contains(link)) {
            favorite = true;
        }

        Poem poem = new Poem(silver, gold, platinum, score, content, first_line, timestamp,
                post_title, post_author, post_content, post_url,
                parents, link, main_poem, read, favorite);

        if (main_poem == null) {
            // add parent comments of this poem which are poems to mainpoem_links
            for (ParentComment p : poem.parents) {
                if (p.author.equalsIgnoreCase("/u/poem_for_your_sprog")) {
                    mainpoem_links.put(p.link, poem);
                }
            }
        } else {
            // if this poem is the parent of another one put it into the corresponding ParentComment
            for (ParentComment p : main_poem.parents) {
                if (p.link.equals(poem.link)) {
                    p.is_poem = poem;
                }
            }
        }
        return poem;
    }

    private List<ParentComment> readParentCommentArray() throws IOException {
        List<ParentComment> parents = new ArrayList<>();

        reader.beginArray();
        while (reader.hasNext()) {
            parents.add(readParentComment());
        }
        reader.endArray();
        return parents;
    }

    private ParentComment readParentComment() throws IOException {
        String content = null;
        String author = null;
        String link = null;

        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            JsonToken check = reader.peek();
            if (check == JsonToken.NULL) {
                reader.skipValue();
                continue;
            }
            switch (name) {
                case "author":
                    author = formatUsername(reader.nextString());
                    break;
                case "orig_body":
                    content = reader.nextString().replace("^", "");
                    break;
                case "link":
                    link = reader.nextString();
                    break;
                default:
                    reader.skipValue();
                    break;
            }
        }
        reader.endObject();
        return new ParentComment(content, author, link);
    }

    private static String formatUsername(String username) {
        username = username.replace("\\_", "_");
        if (username.equals("(deleted user)")) {
            return username;
        } else {
            return "/u/" + username;
        }
    }
}


text:
"use strict";

import React from "react";
import { AppRegistry, StyleSheet } from "react-native";

import { StackNavigator } from 'react-navigation';

import Home from "./pages/Home";
import GettingStarted from "./pages/GettingStarted";
import AboutUs from "./pages/AboutUs";
import Recommended from "./pages/Recommended";

import ActivityInfo from "./pages/ActivityInfo";

const App = StackNavigator({
    Home: {screen: Home},
    GettingStarted: {screen: GettingStarted},
    AboutUs: {screen: AboutUs},
    Recommended: {screen: Recommended},

    // Activities
    ActivityInfo: {screen: ActivityInfo}
});

AppRegistry.registerComponent("MainPage", () => App);


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.04.15 at 03:56:27 PM CEST
//

package org.eclipse.om2m.commons.resource;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.datatype.Duration;

/**
 *

 * Java class for anonymous complex type.
 *
 *

 * The following schema fragment specifies the expected content contained within
 * this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <extension base="{http://www.onem2m.org/xml/protocols}regularResource">
 *       <sequence>
 *         <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="cmdType" type="{http://www.onem2m.org/xml/protocols}cmdType"/>
 *         <element name="execReqArgs" type="{http://www.onem2m.org/xml/protocols}execReqArgsListType" minOccurs="0"/>
 *         <element name="execEnable" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
 *         <element name="execTarget" type="{http://www.onem2m.org/xml/protocols}nodeID"/>
 *         <element name="execMode" type="{http://www.onem2m.org/xml/protocols}execModeType" minOccurs="0"/>
 *         <element name="execFrequency" type="{http://www.w3.org/2001/XMLSchema}duration" minOccurs="0"/>
 *         <element name="execDelay" type="{http://www.w3.org/2001/XMLSchema}duration" minOccurs="0"/>
 *         <element name="execNumber" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/>
 *         <choice>
 *           <element name="childResource" type="{http://www.onem2m.org/xml/protocols}childResourceRef" maxOccurs="unbounded"/>
 *           <choice maxOccurs="unbounded">
 *             <element ref="{http://www.onem2m.org/xml/protocols}execInstance"/>
 *             <element ref="{http://www.onem2m.org/xml/protocols}subscription"/>
 *           </choice>
 *         </choice>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "description", "cmdType", "execReqArgs",
		"execEnable", "execTarget", "execMode", "execFrequency", "execDelay",
		"execNumber", "childResource", "execInstanceOrSubscription" })
@XmlRootElement(name = "mgmtCmd")
public class MgmtCmd extends RegularResource {

	protected String description;
	@XmlElement(required = true)
	protected BigInteger cmdType;
	protected ExecReqArgsListType execReqArgs;
	protected boolean execEnable;
	@XmlElement(required = true)
	@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
	protected String execTarget;
	protected BigInteger execMode;
	protected Duration execFrequency;
	protected Duration execDelay;
	@XmlSchemaType(name = "nonNegativeInteger")
	protected BigInteger execNumber;
	protected List<ChildResourceRef> childResource;
	@XmlElements({
			@XmlElement(name = "execInstance", namespace = "http://www.onem2m.org/xml/protocols", type = ExecInstance.class),
			@XmlElement(name = "subscription", namespace = "http://www.onem2m.org/xml/protocols", type = Subscription.class) })
	protected List<RegularResource> execInstanceOrSubscription;

	/**
	 * Gets the value of the description property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * Sets the value of the description property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setDescription(String value) {
		this.description = value;
	}

	/**
	 * Gets the value of the cmdType property.
	 *
	 * @return possible object is {@link BigInteger }
	 *
	 */
	public BigInteger getCmdType() {
		return cmdType;
	}

	/**
	 * Sets the value of the cmdType property.
	 *
	 * @param value
	 *            allowed object is {@link BigInteger }
	 *
	 */
	public void setCmdType(BigInteger value) {
		this.cmdType = value;
	}

	/**
	 * Gets the value of the execReqArgs property.
	 *
	 * @return possible object is {@link ExecReqArgsListType }
	 *
	 */
	public ExecReqArgsListType getExecReqArgs() {
		return execReqArgs;
	}

	/**
	 * Sets the value of the execReqArgs property.
	 *
	 * @param value
	 *            allowed object is {@link ExecReqArgsListType }
	 *
	 */
	public void setExecReqArgs(ExecReqArgsListType value) {
		this.execReqArgs = value;
	}

	/**
	 * Gets the value of the execEnable property.
	 *
	 */
	public boolean isExecEnable() {
		return execEnable;
	}

	/**
	 * Sets the value of the execEnable property.
	 *
	 */
	public void setExecEnable(boolean value) {
		this.execEnable = value;
	}

	/**
	 * Gets the value of the execTarget property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getExecTarget() {
		return execTarget;
	}

	/**
	 * Sets the value of the execTarget property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setExecTarget(String value) {
		this.execTarget = value;
	}

	/**
	 * Gets the value of the execMode property.
	 *
	 * @return possible object is {@link BigInteger }
	 *
	 */
	public BigInteger getExecMode() {
		return execMode;
	}

	/**
	 * Sets the value of the execMode property.
	 *
	 * @param value
	 *            allowed object is {@link BigInteger }
	 *
	 */
	public void setExecMode(BigInteger value) {
		this.execMode = value;
	}

	/**
	 * Gets the value of the execFrequency property.
	 *
	 * @return possible object is {@link Duration }
	 *
	 */
	public Duration getExecFrequency() {
		return execFrequency;
	}

	/**
	 * Sets the value of the execFrequency property.
	 *
	 * @param value
	 *            allowed object is {@link Duration }
	 *
	 */
	public void setExecFrequency(Duration value) {
		this.execFrequency = value;
	}

	/**
	 * Gets the value of the execDelay property.
	 *
	 * @return possible object is {@link Duration }
	 *
	 */
	public Duration getExecDelay() {
		return execDelay;
	}

	/**
	 * Sets the value of the execDelay property.
	 *
	 * @param value
	 *            allowed object is {@link Duration }
	 *
	 */
	public void setExecDelay(Duration value) {
		this.execDelay = value;
	}

	/**
	 * Gets the value of the execNumber property.
	 *
	 * @return possible object is {@link BigInteger }
	 *
	 */
	public BigInteger getExecNumber() {
		return execNumber;
	}

	/**
	 * Sets the value of the execNumber property.
	 *
	 * @param value
	 *            allowed object is {@link BigInteger }
	 *
	 */
	public void setExecNumber(BigInteger value) {
		this.execNumber = value;
	}

	/**
	 * Gets the value of the childResource property.
	 *
	 *

	 * This accessor method returns a reference to the live list, not a
	 * snapshot. Therefore any modification you make to the returned list will
	 * be present inside the JAXB object. This is why there is not a
	 * set method for the childResource property.
	 *
	 *

	 * For example, to add a new item, do as follows:
	 *
	 *

	 * getChildResource().add(newItem);
	 *

	 *
	 *
	 *

	 * Objects of the following type(s) are allowed in the list
	 * {@link ChildResourceRef }
	 *
	 *
	 */
	public List<ChildResourceRef> getChildResource() {
		if (childResource == null) {
			childResource = new ArrayList<ChildResourceRef>();
		}
		return this.childResource;
	}

	/**
	 * Gets the value of the execInstanceOrSubscription property.
	 *
	 *

	 * This accessor method returns a reference to the live list, not a
	 * snapshot. Therefore any modification you make to the returned list will
	 * be present inside the JAXB object. This is why there is not a
	 * set method for the execInstanceOrSubscription property.
	 *
	 *

	 * For example, to add a new item, do as follows:
	 *
	 *

	 * getExecInstanceOrSubscription().add(newItem);
	 *

	 *
	 *
	 *

	 * Objects of the following type(s) are allowed in the list
	 * {@link ExecInstance } {@link Subscription }
	 *
	 *
	 */
	public List<RegularResource> getExecInstanceOrSubscription() {
		if (execInstanceOrSubscription == null) {
			execInstanceOrSubscription = new ArrayList<RegularResource>();
		}
		return this.execInstanceOrSubscription;
	}

}


text: export default function promisify<T>(toWrap: Function, ...args: any[]): Promise<T>;


text:
package fosite

import (
	"testing"

	"github.com/pkg/errors"
	"github.com/stretchr/testify/assert"
	"golang.org/x/text/language"

	"github.com/ory/fosite/i18n"
)

func TestRFC6749Error(t *testing.T) {
	t.Run("case=wrap", func(t *testing.T) {
		orig := errors.New("hi")
		wrap := new(RFC6749Error)
		wrap.Wrap(orig)

		assert.EqualValues(t, orig.(stackTracer).StackTrace(), wrap.StackTrace())
	})

	t.Run("case=wrap_self", func(t *testing.T) {
		wrap := new(RFC6749Error)
		wrap.Wrap(wrap)

		assert.Empty(t, wrap.StackTrace())
	})
}

func TestErrorI18N(t *testing.T) {
	catalog := i18n.NewDefaultMessageCatalog([]*i18n.DefaultLocaleBundle{
		{
			LangTag: "en",
			Messages: []*i18n.DefaultMessage{
				{
					ID:               "access_denied",
					FormattedMessage: "The resource owner or authorization server denied the request.",
				},
				{
					ID:               "badRequestMethod",
					FormattedMessage: "HTTP method is '%s', expected 'POST'.",
				},
			},
		},
		{
			LangTag: "es",
			Messages: []*i18n.DefaultMessage{
				{
					ID:               "access_denied",
					FormattedMessage: "El propietario del recurso o el servidor de autorización denegó la solicitud.",
				},
				{
					ID:               "HTTP method is '%s', expected 'POST'.",
					FormattedMessage: "El método HTTP es '%s', esperado 'POST'.",
				},
				{
					ID:               "Unable to parse HTTP body, make sure to send a properly formatted form request body.",
					FormattedMessage: "No se puede analizar el cuerpo HTTP, asegúrese de enviar un cuerpo de solicitud de formulario con el formato adecuado.",
				},
				{
					ID:               "badRequestMethod",
					FormattedMessage: "El método HTTP es '%s', esperado 'POST'.",
				},
			},
		},
	})

	t.Run("case=legacy", func(t *testing.T) {
		err := ErrAccessDenied.WithLocalizer(catalog, language.Spanish).WithHintf("HTTP method is '%s', expected 'POST'.", "GET")
		assert.EqualValues(t, "El propietario del recurso o el servidor de autorización denegó la solicitud. El método HTTP es 'GET', esperado 'POST'.", err.GetDescription())
	})

	t.Run("case=unsupported_locale_legacy", func(t *testing.T) {
		err := ErrAccessDenied.WithLocalizer(catalog, language.Afrikaans).WithHintf("HTTP method is '%s', expected 'POST'.", "GET")
		assert.EqualValues(t, "The resource owner or authorization server denied the request. HTTP method is 'GET', expected 'POST'.", err.GetDescription())
	})

	t.Run("case=simple", func(t *testing.T) {
		err := ErrAccessDenied.WithLocalizer(catalog, language.Spanish).WithHintIDOrDefaultf("badRequestMethod", "HTTP method is '%s', expected 'POST'.", "GET")
		assert.EqualValues(t, "El propietario del recurso o el servidor de autorización denegó la solicitud. El método HTTP es 'GET', esperado 'POST'.", err.GetDescription())
	})

	t.Run("case=unsupported_locale", func(t *testing.T) {
		err := ErrAccessDenied.WithLocalizer(catalog, language.Afrikaans).WithHintIDOrDefaultf("badRequestMethod", "HTTP method is '%s', expected 'POST'.", "GET")
		assert.EqualValues(t, "The resource owner or authorization server denied the request. HTTP method is 'GET', expected 'POST'.", err.GetDescription())
	})
}


text:
package building.decorative;

public class Ancient_Skull {

}


text:
ObjectGraph creation functions
------------------------------

.. automodule:: refcycle.creators
   :members:


text:
package io.youi.task

class Action(action: () => Unit) extends Task {
  override def update(delta: Double, reset: Boolean): Conclusion = {
    action()
    Conclusion.Finished
  }
}

object Action {
  def apply(f: => Unit): Action = new Action(() => f)
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;

namespace Sekai.Common
{
    public class ConvertImage
    {
        public static async Task<byte[]> ConvertImagetoByte(StorageFile image)
        {
            IRandomAccessStream fileStream = await image.OpenAsync(FileAccessMode.Read);
            var reader = new DataReader(fileStream.GetInputStreamAt(0));
            await reader.LoadAsync((uint)fileStream.Size);

            var pixels = new byte[fileStream.Size];

            reader.ReadBytes(pixels);

            return pixels;

        }
    }
}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.bigquery.model;

/**
 * Model definition for TransactionInfo.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the BigQuery API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class TransactionInfo extends com.google.api.client.json.GenericJson {

  /**
   * [Output-only] // [Alpha] Id of the transaction.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String transactionId;

  /**
   * [Output-only] // [Alpha] Id of the transaction.
   * @return value or {@code null} for none
   */
  public java.lang.String getTransactionId() {
    return transactionId;
  }

  /**
   * [Output-only] // [Alpha] Id of the transaction.
   * @param transactionId transactionId or {@code null} for none
   */
  public TransactionInfo setTransactionId(java.lang.String transactionId) {
    this.transactionId = transactionId;
    return this;
  }

  @Override
  public TransactionInfo set(String fieldName, Object value) {
    return (TransactionInfo) super.set(fieldName, value);
  }

  @Override
  public TransactionInfo clone() {
    return (TransactionInfo) super.clone();
  }

}


text:
<?xml version="1.0" ?>

<container xmlns="http://www.symfony-project.org/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:zend="http://www.symfony-project.org/schema/dic/zend"
    xmlns:app="http://www.symfony-project.org/schema/dic/symfony"
    xsi:schemaLocation="http://www.symfony-project.org/schema/dic/services http://www.symfony-project.org/schema/dic/services/services-1.0.xsd
                        http://www.symfony-project.org/schema/dic/zend http://www.symfony-project.org/schema/dic/zend/zend-1.0.xsd">

    <imports>
        <import resource="config_dev.xml" />
    </imports>

    <webprofiler:config
        toolbar="false"
        intercept-redirects="false"
    />

    <app:config error_handler="false">
        <app:test />
    </app:config>

    <zend:config>
        <zend:logger priority="debug" />
    </zend:config>
</container>


text:
cask 'google-chrome' do
  version :latest
  sha256 :no_check

  url 'https://dl.google.com/chrome/mac/stable/GGRO/googlechrome.dmg'
  name 'Google Chrome'
  homepage 'https://www.google.com/chrome/'

  auto_updates true
  depends_on macos: '>= :mavericks'

  app 'Google Chrome.app'

  zap delete: [
                '~/Library/Application Support/Google/Chrome',
                '~/Library/Caches/Google/Chrome',
                '~/Library/Caches/com.google.Chrome',
                '~/Library/Caches/com.google.Keystone',
                '~/Library/Caches/com.google.Keystone.Agent',
                '~/Library/Caches/com.google.SoftwareUpdate',
                '~/Library/Google/GoogleSoftwareUpdate',
                '~/Library/Google/Google Chrome Brand.plist',
                '~/Library/LaunchAgents/com.google.keystone.agent.plist',
                '~/Library/Logs/GoogleSoftwareUpdateAgent.log',
                '~/Library/Preferences/com.google.Chrome.plist',
                '~/Library/Preferences/com.google.Keystone.Agent.plist',
                '~/Library/Saved Application State/com.google.Chrome.app.*.savedState',
                '~/Library/Saved Application State/com.google.Chrome.savedState',
                '~/Library/WebKit/com.google.Chrome',
              ],
      rmdir:  [
                '~/Library/Application Support/Google',
                '~/Library/Caches/Google',
                '~/Library/Google',
              ]
end


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

using Xamarin.Forms;

namespace decode01
{
    public class App : Application
    {
        public App()
        {
            // The root page of your application
            //MainPage = new ThermoMeterPage();
            MainPage = new NavigationPage(new StartPage());
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }

    public class StartPage : ContentPage
    {
        public StartPage()
        {
            Title = "de:code Demo App";
            Padding = 10;
            Content = new StackLayout
            {
                Children = {
                    new Button {
                        Text = "ThermoMeter",
                        Command = new Command(async () =>
                            await Navigation.PushAsync(new ThermoMeterPage()))
                    },
                    new Button {
                        Text = "ListView",
                        Command = new Command(async () =>
                            await Navigation.PushAsync(new ListViewPage()))
                    },
                    new Button{
                        Text = "Infragistics ThermoMeter",
                        Command = new Command(async () =>
                            await Navigation.PushAsync(new ThermoMeterPage2()))
                    },
                         new Button{
                        Text = "Infragistics Garicchi Room",
                        Command = new Command(async () =>
                            await Navigation.PushAsync(new Page2()))
                    },

                }
            };
        }

    }
}


text:
require "so_stub_very_test/version"
require "excon"

module SoStubVeryTest
  extend self

  class AmbiguousResponseError < StandardError; end
  class MixedNamespacesError   < StandardError; end
  class NoPathGivenError       < StandardError; end

  def namespace(path, host = nil, &block)
    validate_host(host)

    stub_paths << path
    self.stub_host = host || default_host
    yield
  ensure
    stub_paths.pop

    if stub_paths.empty?
      self.stub_host = nil
    end
  end

  Excon::HTTP_VERBS.each do |verb|
    define_method "stub_#{verb}" do |path, response = nil, host = nil, &block|
      validate_host(host)
      validate_path_given(path)

      unless is_request_options?(path) || path.is_a?(String)
        response = path
        path     = ""
      end

      if is_request_options?(path)
        request = path
        path    = request[:path]
      else
        request = {}
      end

      validate_single_response(block, response)

      if block
        response = block
      end

      path = stub_path + path
      path = replace_path_params(path)
      path = create_path_regexp(path)

      request.merge!(method: verb, path: path)

      if host = get_request_host(host)
        request[:host] = host
      end

      unless response.is_a?(Proc) || (response.is_a?(Hash) && response.has_key?(:body))
        response = { body: response }
      end

      unless SoStubVeryTest.defining_default_stubs
        SoStubVeryTest.custom_stubs << [request, response]
      end

      Excon.stub(request, response)
    end
  end

  class << self
    attr_accessor :default_host

    def clear_custom_stubs
      custom_stubs.each do |stub|
        Excon.stubs.delete stub
      end

      custom_stubs.clear
    end

    def custom_stubs
      @custom_stubs ||= []
    end

    def defining_default_stubs
      @defining_default_stubs ||= false
    end

    def register_host(name, host)
      define_method "#{name}_namespace" do |path, &block|
        namespace path, host, &block
      end

      Excon::HTTP_VERBS.each do |verb|
        define_method "#{name}_stub_#{verb}" do |path, response = nil|
          send "stub_#{verb}", path, response, host
        end
      end
    end

    def defaults(&block)
      @defining_default_stubs = true
      instance_exec &block
    ensure
      @defining_default_stubs = false
    end
  end

  private

  def create_path_regexp(path)
    Regexp.new '\A' + path + '\Z'
  end

  def default_host
    SoStubVeryTest.default_host
  end

  def get_request_host(host)
    stub_host || host || default_host
  end

  def is_request_options?(options)
    options.is_a?(Hash) && options.has_key?(:path)
  end

  def replace_path_params(path)
    path.gsub /:[^\/]+/, '[^\/]+'
  end

  def stub_host=(host)
    @stub_host = host
  end

  def stub_host
    @stub_host
  end

  def stub_path
    stub_paths.join
  end

  def stub_paths
    @stub_paths ||= []
  end

  def validate_path_given(path)
    if stub_paths.empty? && !(is_request_options?(path) || path.is_a?(String))
      raise NoPathGivenError, "Must provide a path to stub requests for"
    end
  end

  def validate_host(host)
    if stub_paths.any? && host && stub_host != host
      raise MixedNamespacesError, "Namespaces can't be mixed (#{stub_host} and #{host == nil ? "nil" : host})"
    end
  end

  def validate_single_response(block, response)
    if block && response
      raise AmbiguousResponseError, "Must provide only either a response object or a block"
    end
  end
end


text:
namespace content {

// BackgroundSyncNetworkObserverAndroid is a specialized
// BackgroundSyncNetworkObserver which is backed by a NetworkChangeNotifier
// that listens for network events even when the browser is paused, unlike the
// standard NetworkChangeNotifier. This ensures that sync events can be fired
// even when the browser is backgrounded, and other network observers are
// disabled.
class BackgroundSyncNetworkObserverAndroid
    : public BackgroundSyncNetworkObserver {
 public:
  // Creates a BackgroundSyncNetworkObserver. |network_changed_callback| is
  // called via PostMessage when the network connection changes.
  BackgroundSyncNetworkObserverAndroid(
      const base::Closure& network_changed_callback);

  ~BackgroundSyncNetworkObserverAndroid() override;

  // This class lives on the UI thread and mediates all access to the Java
  // BackgroundSyncNetworkObserver, which it creates and owns. It is in turn
  // owned by the BackgroundSyncNetworkObserverAndroid.
  class Observer : public base::RefCountedThreadSafe<
                       BackgroundSyncNetworkObserverAndroid::Observer,
                       content::BrowserThread::DeleteOnUIThread> {
   public:
    static scoped_refptr<BackgroundSyncNetworkObserverAndroid::Observer> Create(
        base::Callback<void(net::NetworkChangeNotifier::ConnectionType)>
            callback);

    static bool RegisterNetworkObserver(JNIEnv* env);

    // Called from BackgroundSyncNetworkObserver.java over JNI whenever the
    // connection type changes. This updates the current connection type seen by
    // this class and calls the |network_changed_callback| provided to the
    // constructor, on the IO thread, with the new connection type.
    void NotifyConnectionTypeChanged(
        JNIEnv* env,
        const base::android::JavaParamRef<jobject>& jcaller,
        jint new_connection_type);

   private:
    friend struct BrowserThread::DeleteOnThread<BrowserThread::UI>;
    friend class base::DeleteHelper<
        BackgroundSyncNetworkObserverAndroid::Observer>;

    Observer(base::Callback<void(net::NetworkChangeNotifier::ConnectionType)>
                 callback);
    void Init();
    ~Observer();

    // This callback is to be run on the IO thread whenever the connection type
    // changes.
    base::Callback<void(net::NetworkChangeNotifier::ConnectionType)> callback_;
    base::android::ScopedJavaGlobalRef<jobject> j_observer_;

    DISALLOW_COPY_AND_ASSIGN(Observer);
  };

 private:
  // Accessed on UI Thread
  scoped_refptr<Observer> observer_;

  base::WeakPtrFactory<BackgroundSyncNetworkObserverAndroid> weak_ptr_factory_;
};

}  // namespace content

#endif  // CONTENT_BROWSER_ANDROID_BACKGROUND_SYNC_NETWORK_OBSERVER_ANDROID_H_


text:
#ifndef _FRONTIA_SHARE_DELEGATE_H_
#define _FRONTIA_SHARE_DELEGATE_H_

#import <Foundation/Foundation.h>

/*!
 @abstract 取消分享的回调函数。
 @result
     无。
 */
typedef void(^FrontiaShareCancelCallback)();

/*!
 @abstract 分享失败的回调函数。
 @param errorCode
     错误码。
 @param errorMessage
     错误消息。
 @result
     无。
 */
typedef void(^FrontiaShareFailureCallback)(int errorCode, NSString *errorMessage);

/*!
 @abstract 单平台分享成功的回调函数。
 @param result
     认证返回的结果。
 @result
     无。
 */
typedef void(^FrontiaSingleShareResultCallback)();

/*!
 @abstract 多平台分享成功的回调函数。
 @param respones
     分享成功的平台和分享失败的平台信息。
 @result
     无。
 */
typedef void(^FrontiaMultiShareResultCallback)(NSDictionary *respones);

#endif


text: Basic HTML. Orange juice fund: 1KLoepWkHVEMksdMCsu7nc5amfTvVb2qvk


text:
{php define('MUI', true);}
{template 'common/header'}

请输入手机号,以收取验证码

				<input name="username" type="text" class="js-mobile-val" placeholder="手机号"/>

			<button class="mui-btn mui-btn-success mui-btn-block js-check-mobile" uniacid="{$_W['uniacid']}">下一步</button>

您的手机号会收到一条含有6位数字验证码的短息

				<input type="text" placeholder="请输入验证码" name="code"/>

			<button class="mui-btn mui-btn-success mui-btn-block check-verify">下一步</button>

请为你的账号设置密码,以保证下次正常登录

				<input name="password" type="password" placeholder="请设置密码"/>

				<input name="repassword" type="password" placeholder="确认新密码"/>

密码为6~16位数字或字母

			<button class="mui-btn mui-btn-success mui-btn-block resetpassword">确认</button>


text:
<?php
return array(

	/**
	 * Menu items and titles
	 */
	'thewire' => "The Wire",
	'thewire:everyone' => "Alle Wire-berichten",
	'thewire:user' => "Wire-berichten van %s",
	'thewire:friends' => "Wire-berichten van je vrienden",
	'thewire:replying' => "Antwoord op %s (@%s), die schreef",
	'thewire:thread' => "Conversatie",
	'thewire:charleft' => "karakters resterend",
	'thewire:tags' => "Wire-berichten met de tag '%s'",
	'thewire:noposts' => "Nog geen Wire-berichten",
	'item:object:thewire' => "Wire-berichten",
	'thewire:by' => 'Wire-bericht van %s',
	'thewire:previous:help' => "Bekijk vorige bericht",
	'thewire:hide:help' => "Verberg vorige bericht",

	/**
	 * The wire river
	 */
	'river:create:object:thewire' => "%s stuurde een bericht aan %s",
	'thewire:wire' => 'The Wire',

	/**
	 * Wire widget
	 */
	'thewire:widget:desc' => 'Toon je laatste Wire-berichten',
	'thewire:num' => 'Aantal items om weer te geven',
	'thewire:moreposts' => 'Meer Wire-berichten',

	/**
	 * Status messages
	 */
	'thewire:posted' => "Je bericht is succesvol geplaatst op The Wire.",
	'thewire:deleted' => "Je notitie is succesvol verwijderd.",
	'thewire:blank' => "Sorry, je moet wel iets intypen voordat we je bericht kunnen versturen!",
	'thewire:notfound' => "Sorry, we konden het gezochte Wire-bericht niet vinden.",
	'thewire:notsaved' => "Sorry, we konden je Wire-bericht niet opslaan.",
	'thewire:notdeleted' => "Sorry, we konden dit Wire-bericht niet verwijderen.",

	/**
	 * Notifications
	 */
	'thewire:notify:summary' => 'Nieuw Wire-bericht: %s',
	'thewire:notify:subject' => "Nieuw Wire-bericht van %s",
	'thewire:notify:reply' => '%s reageerde op %s op The Wire:',
	'thewire:notify:post' => '%s plaatste op The Wire:',
	'thewire:notify:footer' => "Bekijk en reageer:\n%s",

	/**
	 * Settings
	 */
	'thewire:settings:limit' => "Maximum aantal karakters voor Wire-berichten:",
	'thewire:settings:limit:none' => "Geen limiet",
);


text:
using System.Globalization;
using System.Threading;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;

namespace BenchmarkDotNet.Samples
{
    [Config(typeof(Config))]
    [ShortRunJob]
    public class IntroCultureInfo
    {
        private class Config : ManualConfig
        {
            public Config()
            {
                CultureInfo = (CultureInfo) CultureInfo.InvariantCulture.Clone();
                CultureInfo.NumberFormat.NumberDecimalSeparator = "@";
            }
        }

        [Benchmark]
        public void Foo() => Thread.Sleep(100);
    }
}


text:
<?php

namespace Tools\Controller\Component;

use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Routing\Router;
use Shim\Controller\Component\Component;
use Tools\Utility\Utility;

/**
 * A component included in every app to take care of common stuff.
 *
 * @author Mark Scherer
 * @license MIT
 */
class CommonComponent extends Component {

	/**
	 * @param \Cake\Event\Event $event
	 * @return void
	 */
	public function startup(Event $event) {
		if (Configure::read('DataPreparation.notrim')) {
			return;
		}

		$request = $this->Controller->getRequest();

		if ($this->Controller->getRequest()->getData()) {

			$newData = Utility::trimDeep($request->getData());
			foreach ($newData as $k => $v) {
				if ($request->getData($k) !== $v) {
					$request = $request->withData($k, $v);
				}
			}
		}
		if ($request->getQuery()) {
			$queryData = Utility::trimDeep($request->getQuery());
			if ($queryData !== $request->getQuery()) {
				$request = $request->withQueryParams($queryData);
			}
		}
		if ($request->getParam('pass')) {
			$passData = Utility::trimDeep($request->getParam('pass'));
			if ($passData !== $request->getParam('pass')) {
				$request = $request->withParam('pass', $passData);
			}
		}

		if ($request === $this->Controller->getRequest()) {
			return;
		}

		$this->Controller->setRequest($request);
	}

	/**
	 * Returns internal redirect only, otherwise falls back to default.
	 *
	 * Lookup order:
	 * - POST data
	 * - query string
	 * - provided default
	 *
	 * @param string|array $default
	 * @param string|array|null $data
	 * @param string $key
	 *
	 * @return string|array
	 */
	public function getSafeRedirectUrl($default, $data = null, $key = 'redirect') {
		$redirectUrl = $data ?: ($this->Controller->getRequest()->getData($key) ?: $this->Controller->getRequest()->getQuery($key));
		if ($redirectUrl && (mb_substr($redirectUrl, 0, 1) !== '/' || mb_substr($redirectUrl, 0, 2) === '//')) {
			$redirectUrl = null;
		}

		return $redirectUrl ?: $default;
	}

	/**
	 * List all direct actions of a controller
	 *
	 * @return array Actions
	 */
	public function listActions() {
		$parentClassMethods = get_class_methods(get_parent_class($this->Controller));
		$subClassMethods = get_class_methods($this->Controller);
		$classMethods = array_diff($subClassMethods, $parentClassMethods);
		foreach ($classMethods as $key => $classMethod) {
			if (mb_substr($classMethod, 0, 1) === '_') {
				unset($classMethods[$key]);
			}
		}
		return $classMethods;
	}

	/**
	 * Convenience method to check on POSTED data.
	 * Doesn't matter if it's POST, PUT or PATCH.
	 *
	 * Note that you can also use request->is(array('post', 'put', 'patch') directly.
	 *
	 * @return bool If it is of type POST/PUT/PATCH
	 */
	public function isPosted() {
		return $this->Controller->getRequest()->is(['post', 'put', 'patch']);
	}

	/**
	 * Add component just in time (inside actions - only when needed)
	 * aware of plugins and config array (if passed)
	 *
	 * @deprecated Use normal controller component loading now. Will be removed in the future.
	 * @param string $component Component
	 * @param array $config
	 * @param bool $callbacks (defaults to true)
	 * @return void
	 */
	public function loadComponent($component, array $config = [], $callbacks = true) {
		list($plugin, $componentName) = pluginSplit($component);
		$this->Controller->loadComponent($component, $config);
		if (!$callbacks) {
			return;
		}
		if (method_exists($this->Controller->{$componentName}, 'beforeFilter')) {
			$this->Controller->{$componentName}->beforeFilter(new Event('Controller.initialize', $this->Controller->{$componentName}));
		}
		if (method_exists($this->Controller->{$componentName}, 'startup')) {
			$this->Controller->{$componentName}->startup(new Event('Controller.startup', $this->Controller->{$componentName}));
		}
	}

	/**
	 * Add helper just in time (inside actions - only when needed)
	 * aware of plugins
	 *
	 * @deprecated In 3.x, but kept for easier migration for now. Will be removed in the future.
	 * @param mixed $helpers (single string or multiple array)
	 * @return void
	 */
	public function loadHelper($helpers = []) {
		$this->Controller->viewBuilder()->setHelpers((array)$helpers, true);
	}

	/**
	 * Used to get the value of a passed param.
	 *
	 * @param mixed $var
	 * @param mixed $default
	 * @return mixed
	 */
	public function getPassedParam($var, $default = null) {
		$passed = $this->Controller->getRequest()->getParam('pass');

		return isset($passed[$var]) ? $passed[$var] : $default;
	}

	/**
	 * Returns defaultUrlParams including configured prefixes.
	 *
	 * @return array URL params
	 */
	public static function defaultUrlParams() {
		$defaults = ['plugin' => false];
		$prefixes = (array)Configure::read('Routing.prefixes');
		foreach ($prefixes as $prefix) {
			$defaults[$prefix] = false;
		}
		return $defaults;
	}

	/**
	 * Returns current url (with all missing params automatically added).
	 * Necessary for Router::url() and comparison of urls to work.
	 *
	 * @param bool $asString Defaults to false = array
	 * @return mixed URL
	 */
	public function currentUrl($asString = false) {
		$action = $this->Controller->getRequest()->getParam('action');

		$passed = (array)$this->Controller->getRequest()->getParam('pass');
		$url = [
			'prefix' => $this->Controller->getRequest()->getParam('prefix'),
			'plugin' => $this->Controller->getRequest()->getParam('plugin'),
			'action' => $action,
			'controller' => $this->Controller->getRequest()->getParam('controller'),
		];
		$url = array_merge($passed, $url);

		if ($asString === true) {
			return Router::url($url);
		}
		return $url;
	}

	/**
	 * Smart Referer Redirect - will try to use an existing referer first
	 * otherwise it will use the default url
	 *
	 * @param mixed $whereTo URL
	 * @param bool $allowSelf if redirect to the same controller/action (url) is allowed
	 * @param int $status
	 * @return \Cake\Http\Response
	 */
	public function autoRedirect($whereTo, $allowSelf = false, $status = 302) {
		if ($allowSelf || $this->Controller->referer(null, true) !== $this->Controller->getRequest()->getRequestTarget()) {
			return $this->Controller->redirect($this->Controller->referer($whereTo, true), $status);
		}
		return $this->Controller->redirect($whereTo, $status);
	}

	/**
	 * Should be a 303, but:
	 * Note: Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303.
	 *
	 * TODO: change to 303 with backwards-compatibility for older browsers...
	 *
	 * @see http://en.wikipedia.org/wiki/Post/Redirect/Get
	 *
	 * @param mixed $whereTo URL
	 * @param int $status
	 * @return \Cake\Http\Response
	 */
	public function postRedirect($whereTo, $status = 302) {
		return $this->Controller->redirect($whereTo, $status);
	}

	/**
	 * Combine auto with post
	 * also allows whitelisting certain actions for autoRedirect (use Controller::$autoRedirectActions)
	 *
	 * @param mixed $whereTo URL
	 * @param bool $conditionalAutoRedirect false to skip whitelisting
	 * @param int $status
	 * @return \Cake\Http\Response
	 */
	public function autoPostRedirect($whereTo, $conditionalAutoRedirect = true, $status = 302) {
		$referer = $this->Controller->referer($whereTo, true);
		if (!$conditionalAutoRedirect && !empty($referer)) {
			return $this->postRedirect($referer, $status);
		}

		if (!empty($referer)) {
			$referer = Router::parse($referer);
		}

		if ($conditionalAutoRedirect && !empty($this->Controller->autoRedirectActions) && is_array($referer) && !empty($referer['action'])) {
			// Be sure that controller offset exists, otherwise you
			// will run into problems, if you use url rewriting.
			$refererController = null;
			if (isset($referer['controller'])) {
				$refererController = $referer['controller'];
			}
			// fixme
			if (!isset($this->Controller->autoRedirectActions)) {
				$this->Controller->autoRedirectActions = [];
			}

			foreach ($this->Controller->autoRedirectActions as $action) {
				list($controller, $action) = pluginSplit($action);
				if (!empty($controller) && $refererController !== '*' && $refererController !== $controller) {
					continue;
				}
				if (empty($controller) && $refererController !== $this->Controller->getRequest()->getParam('controller')) {
					continue;
				}
				if (!in_array($referer['action'], (array)$this->Controller->autoRedirectActions, true)) {
					continue;
				}
				return $this->autoRedirect($whereTo, true, $status);
			}
		}
		return $this->postRedirect($whereTo, $status);
	}

	/**
	 * Automatically add missing URL parts of the current URL including
	 * - querystring (especially for 3.x then)
	 * - passed params
	 *
	 * @param mixed|null $url
	 * @param int|null $status
	 * @return \Cake\Http\Response
	 */
	public function completeRedirect($url = null, $status = 302) {
		if ($url === null) {
			$url = $this->Controller->getRequest()->params;
			unset($url['pass']);
			unset($url['isAjax']);
		}
		if (is_array($url)) {
			$url += $this->Controller->getRequest()->getParam('pass');
		}
		return $this->Controller->redirect($url, $status);
	}

	/**
	 * Set headers to cache this request.
	 * Opposite of Controller::disableCache()
	 *
	 * @param int $seconds
	 * @return void
	 */
	public function forceCache($seconds = HOUR) {
		$response = $this->Controller->getResponse();

		$response = $response->withHeader('Cache-Control', 'public, max-age=' . $seconds)
			->withHeader('Last-modified', gmdate('D, j M Y H:i:s', time()) . ' GMT')
			->withHeader('Expires', gmdate('D, j M Y H:i:s', time() + $seconds) . ' GMT');

		$this->Controller->setResponse($response);
	}

	/**
	 * Referrer checking (where does the user come from)
	 * Only returns true for a valid external referrer.
	 *
	 * @param string|null $ref Referer
	 * @return bool Success
	 */
	public function isForeignReferer($ref = null) {
		if ($ref === null) {
			$ref = env('HTTP_REFERER');
		}
		if (!$ref) {
			return false;
		}
		$base = Configure::read('App.fullBaseUrl') . '/';
		if (mb_strpos($ref, $base) === 0) {
			return false;
		}
		return true;
	}

}


text:
package utils

import (
	"fmt"
	"reflect"
)

func HproseLog(fName string, params []reflect.Value, ctx interface{}) string {
	str := "invoker from " + GetIp(ctx) + "\n"
	str += "invokes the function " + fName + "\n"
	str += "parameters: "
	for _, v := range params {
		str += fmt.Sprintf("%v  ", v.Interface())
	}
	str += "\n"
	return str
}


text:
ruleName: no-duplicate-variable
description: Disallows duplicate variable declarations in the same block scope.
descriptionDetails: |-

  This rule is only useful when using the `var` keyword -
  the compiler will detect redeclarations of `let` and `const` variables.
rationale: |-

  A variable can be reassigned if necessary -
  there's no good reason to have a duplicate variable declaration.
optionsDescription: Not configurable.
options: null
optionExamples:
  - 'true'
type: functionality
optionsJSON: 'null'
layout: rule
title: 'Rule: no-duplicate-variable'
---


text:
/**
 *
 * TableHeader
 *
 */

import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

import CustomInputCheckbox from '../CustomInputCheckbox';

import styles from './styles.scss';

class TableHeader extends React.Component {
  handleChangeSort(name) {
    if (this.props.sort === name) {
      this.props.onChangeSort(`-${name}`);
    } else if (this.props.sort === `-${name}`) {
      this.props.onChangeSort(this.props.primaryKey);
    } else {
      this.props.onChangeSort(name);
    }
  }

  renderBulk = () => {
    if (this.props.enableBulkActions) {
      return (

          <CustomInputCheckbox
            entriesToDelete={this.props.entriesToDelete}
            isAll
            name="all"
            onChange={this.props.onClickSelectAll}
            value={this.props.value}
          />

      );
    }

    return null;
  }

  render() {
    // Generate headers list
    const headers = this.props.headers.map((header, i) => {
      // Define sort icon
      let icon;

      if (this.props.sort === header.name || this.props.sort === 'id' && header.name === '_id') {
        icon = <i className={`fa fa-sort-asc ${styles.iconAsc}`} />;
      } else if (this.props.sort === `-${header.name}`) {
        icon = <i className={`fa fa-sort-asc ${styles.iconDesc}`} />;
      }

      return (
         {
            if (header.sortable) {
              this.handleChangeSort(header.name);
            }
          }}
        >

            {header.label}
            {icon}

      );
    });

    // Add empty th for actions column.
    headers.push(	);

    return (

          {[this.renderBulk()].concat(headers)}

    );
  }
}

TableHeader.defaultProps = {
  enableBulkActions: true,
  value: false,
};

TableHeader.propTypes = {
  enableBulkActions: PropTypes.bool,
  entriesToDelete: PropTypes.array.isRequired,
  headers: PropTypes.array.isRequired,
  onChangeSort: PropTypes.func.isRequired,
  onClickSelectAll: PropTypes.func.isRequired,
  primaryKey: PropTypes.string.isRequired,
  sort: PropTypes.string.isRequired,
  value: PropTypes.bool,
};

export default TableHeader;


text:
@extends('gatekeeper::layouts.default')

@section('styles')
<link rel="stylesheet" href="{{asset('css/map.css')}}">
<link rel="stylesheet" href="{{asset('css/bootstrap-toggle.min.css')}}">
@stop

@section('content')
<br/>
@include('sentinel::zones.map')
@endsection

@section('scripts')
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&language=fr&libraries=drawing"></script>
<script src="{{asset('js/bootstrap-toggle.min.js')}}"></script>
<script src="{{asset('js/gmaps.min.js')}}"></script>
<script src="{{asset('js/map.js')}}"></script>
<script src="{{asset('js/fontawesome-markers.min.js')}}"></script>
<script>
	$('#toggle_drawtools').change(function() { drawtools() })
</script>
@stop


text:
Massive-Migrate is a small migrations library based on [Massive-js](https://github.com/robconery/massive-js) that can help you implement migrations for Postgres databases using Node.js.

## Installation

```bash
npm install massive-migrate --save
```

## Usage

Once installed, you can use it by calling the `runUpMigration` function of a `Migrations` instance you've created before:

```js
var massiveMigrate = require("massive-migrate");
var conn = "postgresql://postgres:postgres@localhost:5432/postgres";
var migrationsDirectory = path.join(__dirname,'/migrations');
var name = '0.1.0';
var options =  {
	connectionString : conn,
	directory : migrationsDirectory
}

massiveMigrate(options, function (err, migrations) {
    if (err) {
        return console.log('migration error', err)
    }

    migrations.runUpMigration({ name : name }, function(err) {
        if(!err) {
        	console.log('migration done');
        }
    });
});
```

Simple migrations can be a single file (like `0.1.0`-up.sql).  For situations where additional coding logic for each migration or multiple SQL migrations per `version` are required a directory can be created to hold up migrations and a `<name>-up.js` migration script.

#### Simple Migrations

The simple migration directory layout for your `migrationsDirectory` will be like:

```
├── migrations
│    └── 0.1.0-up.sql
│    └── 0.2.0-up.sql
└── app.js
```

The migration file's name can be whatever you like but must end in `-up.sql` and should contain standard postgres SQL.  An example app.js to run these migrations could look like:

```js
var massiveMigrate = require("massive-migrate");
var conn = "postgresql://postgres:postgres@localhost:5432/postgres";
var migrationsDirectory = path.join(__dirname,'/migrations');
var options =  {
	connectionString : conn,
	directory : migrationsDirectory
}

massiveMigrate(options, function () {
    migrations.runUpMigration({ name : '0.1.0' }, function(err) {
        if(err) {
            console.log("Error running migration", err);
            return;
        }
        migrations.runUpMigration({ name : '0.2.0' }, function(err) {
            if(err) {
                console.log("Error running migration", err);
                return;
            }
            console.log('Migrations successfully applied!');
        }
    });
});
```

#### Advanced Migrations

For the second case where you want more control over the migrations or additional migration files per `version` you'll create a directory to hold the SQL migration files and a script to execute them.  For example, if want to do an `up`-migration to version `0.1.0`, you must have a directory `0.1.0` in your `migrationsDirectory`.

```
├── migrations
│    └── 0.1.0
└── app.js
```

The parameter for the `up` function is an options object containing at least the name of the migration that should be run. The order of the operations to be done during the `0.1.0` `up` migration is defined in a script whose name by convention is `name` of the migration + `up.js`. Thus for the up migration `0.1.0` it is `0.1.0-up.js`.

The migration script has to reside below the `0.1.0` folder shown in the the tree above:

```
├── migrations
│    └── 0.1.0
│      └── 0.1.0-up.js
└── app.js
```

As the core idea of [Massive-js](https://github.com/robconery/massive-js) (on top of which Massive-Migrate is build) is the usage of `.SQL` files, the migrations themselve are written in `.SQL` files as well.

In our `0.1.0` `up` migration we want to create a table `customer` using the `createcustomertable.sql` file:

```SQL
BEGIN;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE IF NOT EXISTS Customer (
  ID UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  companyname1 VARCHAR(40),
  companyname2 VARCHAR(40),
  addressline1 VARCHAR(40),
  addressline2 VARCHAR(40),
  zipcode VARCHAR(10),
  city VARCHAR(40),
  salestaxidentificationnumber VARCHAR(14),
  createdat DATE DEFAULT now()
);
END;
```

We also want to create a `salutation` table using the `createsalutationtable.sql` file:

```SQL
BEGIN;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE IF NOT EXISTS salutation (
  ID UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  salutation VARCHAR(40),
  male BOOL,
  female BOOL,
  genderless BOOL,
  createdat DATE DEFAULT now()
);
END;
```

Both `.SQL` files have to be in the `up` folder below your `0.1.0` migration folder:

```
├── migrations
│    └── 0.1.0
│         ├── up
│         │    ├── createcustomertable.sql
│         │    └── createsalutationtable.sql
│         └── 0.1.0-up.js
└── app.js
```

The final piece for our migration is the implementation of the migration script named `0.1.0-up.js` which gets hooked up for the migration by Massive-Migrate:

```js
var async = require('async');

exports.up = function(db, options, callback) {
    async.parallel([
        function(cb) {
            db.createsalutationtable(function(err, result){
                if(err) {
                    console.log('up error while creating salutation table: ', err)
                }
                console.log('created salutation table', result);
                cb()
            });

        },
        function(cb) {
            db.createcustomertable(function(err, result) {
                if(err) {
                    console.log('up error while creating customer table: ', err)
                }
                console.log('created customer table', result);
                cb()
            })
        }
    ], function(err, result) {
        callback(err)
    })

};
```

If you run your application which calls the migration, you get this output:

```bash`
$ node app.js
created salutation table
created customer table
migration done
```

Your database now contains the two tables as well as a table `pgmigrations`:

```
│    id    │   name    │  scriptname  │  dateapplied  │
├──────────┼───────────┼──────────────┼───────────────┤
│  <guid>  │   0.1.0   │   0.1.0-up   │    <date>     │
```

## Running a series of migrations
If you want to run more than one migration, you can just follow the convention and provide multiple migrations, each having their folder containing the `.SQL` files and their up script.

Then you can run them in a series like this:

```js
var massiveMigrate = require("massive-migrate");
var conn = "postgresql://postgres:postgres@localhost:5432/postgres";
var migrationsDirectory = path.join(__dirname,'/migrations');
var options =  {
	connectionString : conn,
	directory : migrationsDirectory
}

massiveMigrate(options, function () {
    migrations.runUpMigration({ name : '0.1.0' }, function(err) {
        if(!err) {
          migrations.runUpMigration({ name : '0.2.0' }, function(err) {
        	  console.log('migration done');
        	}
        }
    });
});
```

## Passing custom params to the up script
If you want to pass custom params to the up script when calling the `runUpMigration` function, you can do so.

Just apply your custom params to the options object like shown with the `seedTestData` param:

```js
var massiveMigrate = require("massive-migrate");
var conn = "postgresql://postgres:postgres@localhost:5432/postgres";
var migrationsDirectory = path.join(__dirname,'/migrations');
var name = '0.1.0';
var options =  {
	connectionString : conn,
	directory : migrationsDirectory
}

massiveMigrate(options, function () {
    migrations.runUpMigration({ name : name, seedTestData : true }, function(err) {
        if(!err) {
        	console.log('migration done');
        }
    });
});
```

In your `up`-script you can simply access the `seedTestData` param via the `options` param being passed in to the `up` function:

```js
exports.up = function(db, options, callback) {
    async.parallel([
        function(cb) {
            db.createsalutationtable(function(err, result){
                if(err) {
                    console.log('up error while creating salutation table: ', err)
                }
                cb()
            });

        },
        function(cb) {
            db.createcustomertable(function(err, result) {
                if(err) {
                    console.log('up error while creating customer table: ', err)
                    cb();
                }
                else {
                    if(options.seedTestData) {
                        db.seedcustomertestdata(function(err) {
                            cb();
                        })
                    } else {
                        cb();
                    }
                }
            })
        }
    ], function(err, result) {
        callback(err)
    })
};
```

## Does a migration already exist?
If you want to know if a migration has been applied already, you can ask the migrations:

```js
var massiveMigrate = require("massive-migrate");
var conn = "postgresql://postgres:postgres@localhost:5432/postgres";
var migrationsDirectory = path.join(__dirname,'/migrations');
var name = '0.1.0';
var options =  {
	connectionString : conn,
	directory : migrationsDirectory
}

massiveMigrate(options, function () {
    migrations.hasUpMigration(name, function(err, result) {
        if(!err) {
        	console.log('migration exists', result); // true or false
        }
    });
});
```

If you're trying to run a migration that has been already applied, you'll get receive an error:

`'Migration has been applied already'`

For more details, please take a look at the tests.

## Get all applied migrations
If you need details (`id`, `name`, `scriptname` and `dateapplied`) about all applied migrations, just call the `getAppliedMigrations` function:

```js
var massiveMigrate = require("massive-migrate");
var conn = "postgresql://postgres:postgres@localhost:5432/postgres";
var migrationsDirectory = path.join(__dirname,'/migrations');
var options =  {
	connectionString : conn,
	directory : migrationsDirectory
}

massiveMigrate(options, function () {
    migrations.runUpMigration({ name : '0.1.0' }, function(err) {
        if(err) {
            console.log("Error running migration", err);
            return;
        }
        migrations.runUpMigration({ name : '0.2.0' }, function(err) {
            if(err) {
                console.log("Error running migration", err);
                return;
            }
            console.log('Migrations successfully applied!');
        }
    });
});
```

## Running the tests
You can choose two variants to run the tests: against a local Postgres installation or using Postgres in a Docker container.

Without Docker, create a local Postgres database named `postgres` with username and password `postgres`, listening on `localhost:5432`.

Then, run the tests:
```bash
npm test
```

If you want to use Docker with no local Postgres installation required, run your tests like this:

```
npm run dockerpostgres
npm test
```

## Want to help?
This project is just getting off the ground and could use some help with cleaning things up and refactoring.

If you want to contribute - we'd love it! Just open an issue to work against so you get full credit for your fork. You can open the issue first so we can discuss and you can work your fork as we go along.

If you see a bug, please be so kind as to show how it's failing, and we'll do our best to get it fixed quickly.

## License (BSD 3-Clause)

Copyright (c) 2015, PDMLab e.K.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of massive-migrate nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


text:
namespace EnergyTrading.Mdm.Contracts.Rules
{
    using EnergyTrading.Data;
    using EnergyTrading.Mdm.Contracts;
    using EnergyTrading.Mdm.Data;
    using EnergyTrading.Validation;

    public class NexusIdNoOverlappingRule<T> : Rule<EnergyTrading.Mdm.Contracts.MdmId>
        where T : class, IIdentifiable, IEntityMapping
    {
        private const string MessageTemplate = "Identifier '{0}' for system '{1}' already assigned to an entity for some part of the range {2:yyyy-MMM-dd} to {3:yyyy-MMM-dd}";
        private readonly IRepository repository;

        public NexusIdNoOverlappingRule(IRepository repository)
        {
            this.repository = repository;
        }

        public override bool IsValid(MdmId entity)
        {
            var range = new EnergyTrading.DateRange(entity.StartDate, entity.EndDate);
            var count = this.repository.FindOverlappingMappingCount<T>(entity.SystemName, entity.Identifier, range);
            if (count > 0)
            {
                Message = string.Format(MessageTemplate, entity.Identifier, entity.SystemName, range.Start, range.Finish);
                return false;
            }

            return true;
        }
    }
}


text:
<?php

if( $get_id ) $post = new post( $get_id );
else if( $post_id ) $post = new post( $post_id );
else exit;

if( $post->owner != $_SESSION['user']->idcode ) {
	include( ABSPATH . 'header.php' );

	echo '';

	app_nav();

	echo '
' . lang::$_ERRORS[28] . '
';
	//You do not have permission to edit this post.

	echo '';

	exit;
}

$type 		= $post->type;
$title 		= $post->title;
$reviewed 	= $post->reviewed;
$price 		= $post->price;
$dates 		= $post->dates;
$content 	= $post->content;
$longcontent= $post->longcontent;

$_SESSION['post-tmp'] = $post->filters;

$filename	= isset( $post->filename ) ? $post->filename : NULL;
if( isset( $filename ) && in_array( $post->type, array( 'pic', 'gen', 'adv' ) ) ) $file = $post->get_image( 'edit' );
else if( $post->type == 'aud' ) $file = $post->get_audio( 'edit' );
else if( $post->type == 'vid' ) $file = $post->get_video( 'edit' );
else $file = NULL;

$draft = ic_get_get( 'draft' );
if( !$draft ) $draft = ic_get_post( 'edit-draft' );
$submit = $draft ? t( 'publish' ) : t( 'update' );

$editid = $get_id ? $get_id : $post_id;
$edit = '
<input type="hidden" name="ms" value="' . $editid . '"/>
';
$edit .= '
<input type="hidden" name="edit-draft" value="' . $editid . '"/>
';


text:
<!DOCTYPE html>

This tests that you can set the placeholder text color.

Default style:
<input value="default">
<input value="default disabled">

::-webkit-input-placeholder:
<input class="red" value="text">
<input class="red" type="search" value="search">
<input class="red" type="text" value="password">
<input class="red" disabled value="disabled text">

::placeholder:
<input class="blue" value="text">
<input class="blue" type="search" value="search">
<input class="blue" type="text" value="password">
<input class="blue" disabled value="disabled text">

Both:
<input class="prefixed-unprefixed" value="unprefixed">
<input class="unprefixed-prefixed" value="prefixed">