text:
// -*- mode: c++; c-basic-offset: 4 -*-

#include <click/config.h>
#include <click/router.hh>
#include "fromhost.hh"
#include <click/args.hh>
#include <click/error.hh>
#include <click/straccum.hh>
#include <click/standard/scheduleinfo.hh>
#include <clicknet/ip6.h>

#include <click/cxxprotect.h>
CLICK_CXX_PROTECT
#include <asm/types.h>
#include <asm/uaccess.h>
#include <linux/ip.h>
#include <linux/inetdevice.h>
#include <linux/if_arp.h>
#include <linux/etherdevice.h>
#include <net/route.h>
#include <net/dst.h>
#include <net/inet_common.h>
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 24)
# include <net/net_namespace.h>
#endif
CLICK_CXX_UNPROTECT
#include <click/cxxunprotect.h>

#if HAVE_LINUX_INET_CTL_SOCK_CREATE
# define click_inet_ioctl(sock, dev, cmd, arg)	inet_ioctl((sock), (cmd), (arg))
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
# define click_inet_ioctl(sock, dev, cmd, arg)	devinet_ioctl(dev_net(dev), (cmd), (arg))
#else
# define click_inet_ioctl(sock, dev, cmd, arg)	devinet_ioctl((cmd), (arg))
#endif

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
# define click_dev_ioctl(dev, cmd, arg)		dev_ioctl(dev_net(dev), (cmd), (arg))
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 24)
# define click_dev_ioctl(dev, cmd, arg)		dev_ioctl(&init_net, (cmd), (arg))
#else
# define click_dev_ioctl(dev, cmd, arg)		dev_ioctl((cmd), (arg))
#endif

#ifndef NETDEV_TX_OK
# define NETDEV_TX_OK		0
# define NETDEV_TX_BUSY		1
#endif

extern "C" {
static int fl_open(net_device *);
static int fl_close(net_device *);
static void fl_wakeup(Timer *, void *);
}

FromHost *FromHost::configuring = 0;
static AnyDeviceMap fromlinux_map;

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 32)
static struct net_device_ops fromhost_netdev_ops;
# define netdev_op(dev, opname)		(dev)->netdev_ops->ndo_##opname
#else
# define netdev_op(dev, opname)		(dev)->opname
#endif

void
FromHost::static_initialize()
{
    fromlinux_map.initialize();
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 32)
    fromhost_netdev_ops.ndo_open = fl_open;
    fromhost_netdev_ops.ndo_stop = fl_close;
    fromhost_netdev_ops.ndo_start_xmit = fl_tx;
    fromhost_netdev_ops.ndo_set_mac_address = eth_mac_addr;
#endif
}

FromHost::FromHost()
    : _macaddr((const unsigned char *)"\000\001\002\003\004\005"),
      _task(this), _wakeup_timer(fl_wakeup, this),
      _drops(0), _ninvalid(0)
{
    _head = _tail = 0;
    _capacity = 100;
    _q.lgq = 0;
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 32)
    memset(&_stats, 0, sizeof(_stats));
#endif
}

FromHost::~FromHost()
{
}

void *FromHost::cast(const char *name)
{
    if (strcmp(name, "Storage") == 0)
	return (Storage *)this;
    else if (strcmp(name, "FromHost") == 0)
	return (Element *)this;
    else
	return 0;
}

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)
extern "C" {
static void fromhost_inet_setup(struct net_device *dev)
{
    dev->type = ARPHRD_NONE;
    dev->hard_header_len = 0;
    dev->addr_len = 0;
    dev->mtu = 1500;
    dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
}
}
#endif

net_device *
FromHost::new_device(const char *name)
{
    read_lock(&dev_base_lock);
    void (*setup)(struct net_device *) = (_macaddr ? ether_setup : fromhost_inet_setup);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)
    net_device *dev = alloc_netdev(0, name, setup);
#else
    int errcode;
    net_device *dev = dev_alloc(name, &errcode);
#endif
    read_unlock(&dev_base_lock);
    if (!dev)
	return 0;

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 32)
    dev->netdev_ops = &fromhost_netdev_ops;
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)
    dev->open = fl_open;
    dev->stop = fl_close;
    dev->hard_start_xmit = fl_tx;
    dev->get_stats = fl_stats;
#else
    setup(dev);
#endif
    dev->mtu = _mtu;
    dev->tx_queue_len = 0;
    dev->ifindex = -1;
    return dev;
}

int
FromHost::configure(Vector<String> &conf, ErrorHandler *errh)
{
    String type;
    int mtu = 1500;
    _destaddr = IPAddress();
    _destmask = IPAddress();
    _clear_anno = true;

    if (Args(conf, this, errh)
	.read_mp("DEVNAME", _devname)
	.read_p("PREFIX", IPPrefixArg(), _destaddr, _destmask)
	.read("TYPE", WordArg(), type)
	.read("ETHER", _macaddr)
	.read("MTU", mtu)
	.read("CAPACITY", _capacity)
	.read("CLEAR_ANNO", _clear_anno)
	.complete() < 0)
	return -1;

    // check for duplicate element
    if (_devname.length() > IFNAMSIZ - 1)
	return errh->error("device name '%s' too long", _devname.c_str());
    void *&used = router()->force_attachment("FromHost_" + _devname);
    if (used)
	return errh->error("duplicate FromHost for device '%s'", _devname.c_str());
    used = this;

    _mtu = mtu;
    // check for existing device
    _dev = AnyDevice::get_by_name(_devname.c_str());
    if (_dev) {
	if (netdev_op(_dev, open) != fl_open) {
	    dev_put(_dev);
	    _dev = 0;
	    return errh->error("device '%s' already exists", _devname.c_str());
	} else {
	    fromlinux_map.insert(this, false);
	    return 0;
	}
    }

    // set type
    if (type == "IP")
	_macaddr = EtherAddress();
    else if (type != "ETHER" && type != "")
	return errh->error("bad TYPE");

    // set up queue
    if (_capacity < 1)
	_capacity = 1;
    if (_capacity > smq_size)
	if (!(_q.lgq = new Packet *[_capacity + 1]))
	    return errh->error("out of memory!");

    // if not found, create new device
    int res;
    _dev = new_device(_devname.c_str());
    if (!_dev)
	return errh->error("out of memory registering device '%s'", _devname.c_str());
    else {
	// in Linux < 2.6.32 register_netdev calls copy_rtnl_link_stats which
	// requires valid net_device_stats structure, so remember which
	// FromHost we're configuring (configure is serialized)
	dev_hold(_dev);
	configuring = this;
	res = register_netdev(_dev);
	configuring = 0;
	if (res == 0)
	    fromlinux_map.insert(this, false);
	else {
	    dev_put(_dev);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)
	    free_netdev(_dev);
#else
	    kfree(_dev);
#endif
	    _dev = 0;
	    return errh->error("error %d registering device '%s'", res, _devname.c_str());
	}
    }

    return 0;
}

int
FromHost::set_device_addresses(ErrorHandler *errh)
{
    int res = 0;
    struct ifreq ifr;
    strncpy(ifr.ifr_name, _dev->name, IFNAMSIZ);
    struct sockaddr_in *sin = (struct sockaddr_in *)&ifr.ifr_addr;
    mm_segment_t oldfs;

    if (_macaddr) {
	ifr.ifr_hwaddr.sa_family = _dev->type;
	memcpy(ifr.ifr_hwaddr.sa_data, _macaddr.data(), 6);
#if HAVE_LINUX_DEV_IOCTL
	oldfs = get_fs();
	set_fs(get_ds());
	res = click_dev_ioctl(_dev, SIOCSIFHWADDR, &ifr);
	set_fs(oldfs);
#else
	rtnl_lock();
	res = dev_set_mac_address(_dev, &ifr.ifr_hwaddr);
	rtnl_unlock();
#endif
	if (res)
	    errh->error("error %d setting hardware address for device '%s'",
			res, _devname.c_str());
    }

    if (_destaddr) {
#if HAVE_LINUX_DEVINET_IOCTL || HAVE_LINUX_INET_CTL_SOCK_CREATE
        sin->sin_family = AF_INET;
        sin->sin_addr = _destaddr;
# if HAVE_LINUX_INET_CTL_SOCK_CREATE
	struct socket *sock = kmalloc(sizeof(struct socket), GFP_KERNEL);
	sock->sk = 0;
	if (res >= 0 && (res = inet_ctl_sock_create(&sock->sk, AF_INET, SOCK_RAW, IPPROTO_TCP, dev_net(_dev))) != 0) {
	    errh->error("error %d creating control socket for device '%s'", res, _devname.c_str());
	    res = -1;
	}
# endif
	oldfs = get_fs();
	set_fs(get_ds());
        if (res >= 0 && (res = click_inet_ioctl(sock, _dev, SIOCSIFADDR, &ifr)) < 0)
            errh->error("error %d setting address for device '%s'", res, _devname.c_str());

        sin->sin_addr = _destmask;
        if (res >= 0 && (res = click_inet_ioctl(sock, _dev, SIOCSIFNETMASK, &ifr)) < 0)
            errh->error("error %d setting netmask for device '%s'", res, _devname.c_str());
	set_fs(oldfs);
# if HAVE_LINUX_INET_CTL_SOCK_CREATE
	inet_ctl_sock_destroy(sock->sk);
	kfree(sock);
# endif
#else
	res = errh->error("cannot set IP address for FromHost devices on this kernel");
#endif
    }

    return res;
}

static int
dev_updown(net_device *dev, int up, ErrorHandler *errh)
{
    struct ifreq ifr;
    strncpy(ifr.ifr_name, dev->name, IFNAMSIZ);
    uint32_t flags = IFF_UP | IFF_RUNNING;
    int res = -EINVAL;

#if HAVE_LINUX_DEV_IOCTL
    mm_segment_t oldfs = get_fs();
    set_fs(get_ds());

    (void) click_dev_ioctl(dev, SIOCGIFFLAGS, &ifr);
    ifr.ifr_flags = (up > 0 ? ifr.ifr_flags | flags : ifr.ifr_flags & ~flags);
    res = click_dev_ioctl(dev, SIOCSIFFLAGS, &ifr);
    set_fs(oldfs);
#else
    rtnl_lock();
    res = dev_change_flags(dev, dev->flags | IFF_UP);
    rtnl_unlock();
#endif

    if (res < 0 && errh)
	errh->error("error %d bringing %s device '%s'", res, (up > 0 ? "up" : "down"), dev->name);
    return res;
}

int
FromHost::initialize(ErrorHandler *errh)
{
    ScheduleInfo::initialize_task(this, &_task, _dev != 0, errh);
    _nonfull_signal = Notifier::downstream_full_signal(this, 0, &_task);
    if (_dev->flags & IFF_UP) {
	_wakeup_timer.initialize(this);
	_wakeup_timer.schedule_now();
	return 0;
    } else if (set_device_addresses(errh) < 0)
	return -1;
    else
	return dev_updown(_dev, 1, errh);
}

void
FromHost::cleanup(CleanupStage)
{
    fromlinux_map.remove(this, false);

    Packet * volatile *q = queue();
    while (_head != _tail) {
	Packet *p = q[_head];
	p->kill();
	_head = next_i(_head);
    }
    if (_capacity > smq_size)
	delete[] _q.lgq;
    _capacity = 1;
    _head = _tail = 0;

    if (_dev) {
	dev_put(_dev);
	unsigned long lock_flags;
	fromlinux_map.lock(false, lock_flags);
	if (fromlinux_map.lookup(_dev, 0))
	    // do not free device if it is in use
	    _dev = 0;
	fromlinux_map.unlock(false, lock_flags);
	if (_dev) {
	    if (_dev->flags & IFF_UP)
		dev_updown(_dev, -1, 0);
	    unregister_netdev(_dev);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0)
	    free_netdev(_dev);
#else
	    kfree(_dev);
#endif
	    _dev = 0;
	}
    }
}

/*
 * Device callbacks
 */

extern "C" {
static int
fl_open(net_device *dev)
{
    netif_start_queue(dev);
    return 0;
}

static int
fl_close(net_device *dev)
{
    netif_stop_queue(dev);
    return 0;
}

static void
fl_wakeup(Timer *, void *thunk)
{
    FromHost *fl = (FromHost *)thunk;
    PrefixErrorHandler errh(ErrorHandler::default_handler(), fl->declaration() + ": ");
    net_device *dev = fl->device();

    if (dev->flags & IFF_UP)
	dev_updown(dev, -1, &errh);

    fl->set_device_addresses(&errh);

    dev_updown(dev, 1, &errh);
}

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 32)
net_device_stats *
FromHost::fl_stats(net_device *dev)
{
    unsigned long lock_flags;
    fromlinux_map.lock(false, lock_flags);
    FromHost *fl = (FromHost *) fromlinux_map.lookup(dev, 0);
    if (!fl)
	fl = (FromHost *) fromlinux_map.lookup_unknown(dev, 0);
    if (!fl && configuring && configuring->device() == dev)
	fl = configuring;
    net_device_stats *stats = (fl ? fl->stats() : 0);
    fromlinux_map.unlock(false, lock_flags);
    return stats;
}
#endif
}

int
FromHost::fl_tx(struct sk_buff *skb, net_device *dev)
{
    /* 8.May.2003 - Doug and company had crashes with FromHost configurations.
         We eventually figured out this was because fl_tx was called at
         interrupt time -- at bottom-half time, to be exact -- and then pushed
         a packet through the configuration. Whoops: if Click was interrupted,
         and during the bottom-half FromHost emitted a packet into Click,
         DISASTER -- we assume that, when running single-threaded, at most one
         Click thread is active at a time; so there were race conditions,
         particularly with the task list. The solution is a queue in
         FromHost. fl_tx puts a packet onto the queue, a regular Click Task
         takes the packet off the queue. */
    int ret;
    unsigned long lock_flags;
    fromlinux_map.lock(false, lock_flags);
    if (FromHost *fl = (FromHost *)fromlinux_map.lookup(dev, 0)) {
	Storage::index_type next = fl->next_i(fl->_tail);
	if (likely(next != fl->_head)) {
	    Packet * volatile *q = fl->queue();

	    // skb->dst may be set since the packet came from Linux.  Since
	    // Click doesn't use dst, clear it now.
#if HAVE_SKB_DST_DROP
	    skb_dst_drop(skb);
#else
	    if (skb->dst) {
		dst_release(skb->dst);
		skb->dst = 0;
	    }
#endif

	    Packet *p = Packet::make(skb);
	    p->timestamp_anno().assign_now();
	    if (fl->_clear_anno)
		p->clear_annotations(false);
	    fl->stats()->tx_packets++;
	    fl->stats()->tx_bytes += p->length();
	    fl->_task.reschedule();
	    q[fl->_tail] = p;
	    packet_memory_barrier(q[fl->_tail], fl->_tail);
	    fl->_tail = next;
	    ret = NETDEV_TX_OK;
	} else {
	    fl->_drops++;
	    ret = NETDEV_TX_BUSY;	// Linux will free the packet.
	}
    } else
	ret = -1;
    fromlinux_map.unlock(false, lock_flags);
    return ret;
}

bool
FromHost::run_task(Task *)
{
    if (!_nonfull_signal)
	return false;

    if (likely(!empty())) {
	Packet * volatile *q = queue();
	Packet *p = q[_head];
	packet_memory_barrier(q[_head], _head);
	_head = next_i(_head);

	// Convenience for TYPE IP: set the IP header and destination address.
	if (_dev->type == ARPHRD_NONE && p->length() >= 1) {
	    const click_ip *iph = (const click_ip *) p->data();
	    if (iph->ip_v == 4) {
		if (iph->ip_hl >= 5
		    && ntohs(iph->ip_len) >= (iph->ip_hl << 2)
		    && reinterpret_cast<const uint8_t *>(iph) + (iph->ip_hl << 2) <= p->end_data()) {
		    p->set_ip_header(iph, iph->ip_hl << 2);
		    p->set_dst_ip_anno(iph->ip_dst);
		} else
		    goto bad;
	    } else if (iph->ip_v == 6) {
		if (reinterpret_cast<const uint8_t *>(iph) + sizeof(click_ip6) <= p->end_data())
		    p->set_ip6_header(reinterpret_cast<const click_ip6 *>(iph));
		else
		    goto bad;
	    } else {
	      bad:
	        _ninvalid++;
		checked_output_push(1, p);
		goto done;
	    }
	}

	output(0).push(p);

      done:
	if (!empty())
	    _task.fast_reschedule();
	return true;
    } else
	return false;
}

String
FromHost::read_handler(Element *e, void *)
{
    FromHost *fh = (FromHost *) e;
    return String(fh->size());
}

void
FromHost::add_handlers()
{
    add_task_handlers(&_task);
    add_read_handler("length", read_handler, h_length);
    add_data_handlers("capacity", Handler::OP_READ, &_capacity);
    add_data_handlers("drops", Handler::OP_READ, &_drops);
}

ELEMENT_REQUIRES(AnyDevice linuxmodule)
EXPORT_ELEMENT(FromHost)


text:
#include "cpl_string.h"
#include "cpl_conv.h"
#include "cpl_multiproc.h"
#include "gdal_version.h"
#include "gdal.h"
#include "vrtdataset.h"
#include "commonutils.h"

#include <algorithm>

CPL_CVSID("$Id: gdalenhance.cpp f007ad4c08eba374ffefc0cdcacf8c820ed9e422 2018-07-16 10:39:27 +0200 Even Rouault $")

static int
ComputeEqualizationLUTs( GDALDatasetH hDataset,  int nLUTBins,
                         double **ppadfScaleMin, double **padfScaleMax,
                         int ***ppapanLUTs, GDALProgressFunc pfnProgress );

static CPLErr EnhancerCallback( void *hCBData,
                                int nXOff, int nYOff, int nXSize, int nYSize,
                                void *pData );

typedef struct {
    GDALRasterBand *poSrcBand;
    GDALDataType    eWrkType;
    double          dfScaleMin;
    double          dfScaleMax;
    int             nLUTBins;
    const int      *panLUT;
} EnhanceCBInfo;

/* ******************************************************************** */
/*                               Usage()                                */
/* ******************************************************************** */

static void Usage()

{
    printf( "Usage: gdalenhance [--help-general]\n"
            "       [-of format] [-co \"NAME=VALUE\"]*\n"
            "       [-ot {Byte/Int16/UInt16/UInt32/Int32/Float32/Float64/\n"
            "             CInt16/CInt32/CFloat32/CFloat64}]\n"
//            "       [-src_scale[_n] src_min src_max]\n"
//            "       [-dst_scale[_n] dst_min dst_max]\n"
//            "       [-lutbins count]\n"
//            "       [-s_nodata[_n] value]\n"
//            "       [-stddev multiplier]\n"
            "       [-equalize]\n"
            "       [-config filename]\n"
            "       src_dataset dst_dataset\n\n" );
    printf( "%s\n\n", GDALVersionInfo( "--version" ) );
    exit( 1 );
}

/************************************************************************/
/*                             ProxyMain()                              */
/************************************************************************/

MAIN_START(argc, argv)

{
    GDALDatasetH        hDataset, hOutDS;
    int                 i;
    const char          *pszSource=nullptr, *pszDest=nullptr, *pszFormat = nullptr;
    GDALDriverH         hDriver = nullptr;
    GDALDataType        eOutputType = GDT_Unknown;
    char                **papszCreateOptions = nullptr;
    GDALProgressFunc    pfnProgress = GDALTermProgress;
    int                 nLUTBins = 256;
    const char         *pszMethod = "minmax";
//    double              dfStdDevMult = 0.0;
    double             *padfScaleMin = nullptr;
    double             *padfScaleMax = nullptr;
    int               **papanLUTs = nullptr;
    int                 iBand;
    const char         *pszConfigFile = nullptr;

    /* Check strict compilation and runtime library version as we use C++ API */
    if (! GDAL_CHECK_VERSION(argv[0]))
        exit(1);
/* -------------------------------------------------------------------- */
/*      Register standard GDAL drivers, and process generic GDAL        */
/*      command options.                                                */
/* -------------------------------------------------------------------- */
    GDALAllRegister();
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );
    if( argc < 1 )
        exit( -argc );

/* -------------------------------------------------------------------- */
/*      Handle command line arguments.                                  */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( i < argc-1 && (EQUAL(argv[i],"-of") || EQUAL(argv[i],"-f")) )
        {
            pszFormat = argv[++i];
        }

        else if( i < argc-1 && EQUAL(argv[i],"-ot") )
        {
            int iType;

            for( iType = 1; iType < GDT_TypeCount; iType++ )
            {
                if( GDALGetDataTypeName(static_cast<GDALDataType>(iType)) != nullptr
                    && EQUAL(GDALGetDataTypeName(static_cast<GDALDataType>(iType)),
                             argv[i+1]) )
                {
                    eOutputType = static_cast<GDALDataType>(iType);
                }
            }

            if( eOutputType == GDT_Unknown )
            {
                printf( "Unknown output pixel type: %s\n", argv[i+1] );
                Usage();
            }
            i++;
        }

        else if( STARTS_WITH_CI(argv[i], "-s_nodata") )
        {
            // TODO
            i += 1;
        }

        else if( i < argc-1 && EQUAL(argv[i],"-co") )
        {
            papszCreateOptions = CSLAddString( papszCreateOptions, argv[++i] );
        }

        else if( i < argc-1 && STARTS_WITH_CI(argv[i], "-src_scale") )
        {
            // TODO
            i += 2;
        }

        else if( i < argc-2 && STARTS_WITH_CI(argv[i], "-dst_scale") )
        {
            // TODO
            i += 2;
        }

        else if( i < argc-1 && EQUAL(argv[i],"-config") )
        {
            pszConfigFile = argv[++i];
        }

        else if( EQUAL(argv[i],"-equalize") )
        {
            pszMethod = "equalize";
        }

        else if( EQUAL(argv[i],"-quiet") )
        {
            pfnProgress = GDALDummyProgress;
        }

        else if( argv[i][0] == '-' )
        {
            printf( "Option %s incomplete, or not recognised.\n\n",
                    argv[i] );
            Usage();
        }
        else if( pszSource == nullptr )
        {
            pszSource = argv[i];
        }
        else if( pszDest == nullptr )
        {
            pszDest = argv[i];
        }

        else
        {
            printf( "Too many command options.\n\n" );
            Usage();
        }
    }

    if( pszSource == nullptr )
    {
        Usage();
    }

/* -------------------------------------------------------------------- */
/*      Attempt to open source file.                                    */
/* -------------------------------------------------------------------- */

    hDataset = GDALOpenShared( pszSource, GA_ReadOnly );

    if( hDataset == nullptr )
    {
        fprintf( stderr,
                 "GDALOpen failed - %d\n%s\n",
                 CPLGetLastErrorNo(), CPLGetLastErrorMsg() );
        GDALDestroyDriverManager();
        exit( 1 );
    }

    int nBandCount = GDALGetRasterCount(hDataset);

/* -------------------------------------------------------------------- */
/*      Find the output driver.                                         */
/* -------------------------------------------------------------------- */
    CPLString osFormat;
    if( pszFormat == nullptr && pszDest != nullptr )
    {
        osFormat = GetOutputDriverForRaster(pszDest);
        if( osFormat.empty() )
        {
            GDALDestroyDriverManager();
            exit( 1 );
        }
    }
    else if( pszFormat != nullptr )
    {
        osFormat = pszFormat;
    }

    if( !osFormat.empty() )
    {
        hDriver = GDALGetDriverByName( osFormat );
        if( hDriver == nullptr )
        {
            int iDr;

            printf( "Output driver `%s' not recognised.\n", osFormat.c_str() );
            printf( "The following format drivers are configured and support output:\n" );
            for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
            {
                hDriver = GDALGetDriver(iDr);

                if( GDALGetMetadataItem( hDriver, GDAL_DCAP_RASTER, nullptr) != nullptr &&
                    (GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, nullptr ) != nullptr
                    || GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATECOPY, nullptr ) != nullptr) )
                {
                    printf( "  %s: %s\n",
                            GDALGetDriverShortName( hDriver  ),
                            GDALGetDriverLongName( hDriver ) );
                }
            }
            printf( "\n" );
            Usage();
        }
    }

/* -------------------------------------------------------------------- */
/*      If histogram equalization is requested, do it now.              */
/* -------------------------------------------------------------------- */
    if( EQUAL(pszMethod,"equalize") )
    {
        ComputeEqualizationLUTs( hDataset, nLUTBins,
                                 &padfScaleMin, &padfScaleMax,
                                 &papanLUTs, pfnProgress );
    }

/* -------------------------------------------------------------------- */
/*      If we have a config file, assume it is for input and read       */
/*      it.                                                             */
/* -------------------------------------------------------------------- */
    else if( pszConfigFile != nullptr )
    {
        char **papszLines = CSLLoad( pszConfigFile );
        if( CSLCount(papszLines) == 0 )
            exit( 1 );

        if( CSLCount(papszLines) != nBandCount )
        {
            fprintf( stderr, "Did not get %d lines in config file as expected.\n", nBandCount );
            exit( 1 );
        }

        padfScaleMin =
            static_cast<double *>(CPLCalloc(nBandCount,sizeof(double)));
        padfScaleMax =
            static_cast<double *>(CPLCalloc(nBandCount,sizeof(double)));

        for( iBand = 0; iBand < nBandCount; iBand++ )
        {
            int iLUT;
            char **papszTokens = CSLTokenizeString( papszLines[iBand] );

            if( CSLCount(papszTokens) < 3
                || atoi(papszTokens[0]) != iBand+1 )
            {
                fprintf( stderr, "Line %d seems to be corrupt.\n", iBand+1 );
                exit( 1 );
            }

            // Process scale min/max

            padfScaleMin[iBand] = CPLAtof(papszTokens[1]);
            padfScaleMax[iBand] = CPLAtof(papszTokens[2]);

            if( CSLCount(papszTokens) == 3 )
                continue;

            // process lut
            if( papanLUTs == nullptr )
            {
                nLUTBins = CSLCount(papszTokens) - 3;
                papanLUTs =
                    static_cast<int **>(CPLCalloc(sizeof(int*), nBandCount));
            }

            papanLUTs[iBand] =
                static_cast<int *>(CPLCalloc(nLUTBins, sizeof(int)));

            for( iLUT = 0; iLUT < nLUTBins; iLUT++ )
                papanLUTs[iBand][iLUT] = atoi(papszTokens[iLUT+3]);

            CSLDestroy( papszTokens );
        }
    }

/* -------------------------------------------------------------------- */
/*      If there is no destination, just report the scaling values      */
/*      and luts.                                                       */
/* -------------------------------------------------------------------- */
    if( pszDest == nullptr )
    {
        FILE *fpConfig = stdout;
        if( pszConfigFile )
            fpConfig = fopen( pszConfigFile, "w" );

        for( iBand = 0; iBand < nBandCount; iBand++ )
        {
            fprintf( fpConfig, "%d:Band ", iBand+1 );
            if( padfScaleMin != nullptr )
                fprintf( fpConfig, "%g:ScaleMin %g:ScaleMax ",
                         padfScaleMin[iBand], padfScaleMax[iBand] );

            if( papanLUTs )
            {
                int iLUT;

                for( iLUT = 0; iLUT < nLUTBins; iLUT++ )
                    fprintf( fpConfig, "%d ", papanLUTs[iBand][iLUT] );
            }
            fprintf( fpConfig, "\n" );
        }

        if( pszConfigFile )
            fclose( fpConfig );

        exit( 0 );
    }

    if (padfScaleMin == nullptr || padfScaleMax == nullptr)
    {
        fprintf( stderr, "-equalize or -config filename command line options must be specified.\n");
        exit(1);
    }

/* ==================================================================== */
/*      Create a virtual dataset.                                       */
/* ==================================================================== */
    EnhanceCBInfo *pasEInfo = static_cast<EnhanceCBInfo *>(
        CPLCalloc(nBandCount, sizeof(EnhanceCBInfo)));

/* -------------------------------------------------------------------- */
/*      Make a virtual clone.                                           */
/* -------------------------------------------------------------------- */
    VRTDataset *poVDS =
        new VRTDataset(GDALGetRasterXSize(hDataset),
                       GDALGetRasterYSize(hDataset));

    if( GDALGetGCPCount(hDataset) == 0 )
    {
        double adfGeoTransform[6];

        const char *pszProjection = GDALGetProjectionRef(hDataset);
        if( pszProjection != nullptr && strlen(pszProjection) > 0 )
            poVDS->SetProjection( pszProjection );

        if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None )
            poVDS->SetGeoTransform( adfGeoTransform );
    }
    else
    {
        poVDS->SetGCPs( GDALGetGCPCount(hDataset),
                        GDALGetGCPs(hDataset),
                        GDALGetGCPProjection( hDataset ) );
    }

    poVDS->SetMetadata( static_cast<GDALDataset*>(hDataset)->GetMetadata() );

    for( iBand = 0; iBand < nBandCount; iBand++ )
    {
        VRTSourcedRasterBand   *poVRTBand;
        GDALRasterBand  *poSrcBand;
        GDALDataType    eBandType;

        poSrcBand = static_cast<GDALDataset*>(hDataset)->GetRasterBand(iBand+1);

/* -------------------------------------------------------------------- */
/*      Select output data type to match source.                        */
/* -------------------------------------------------------------------- */
        if( eOutputType == GDT_Unknown )
            eBandType = GDT_Byte;
        else
            eBandType = eOutputType;

/* -------------------------------------------------------------------- */
/*      Create this band.                                               */
/* -------------------------------------------------------------------- */
        poVDS->AddBand( eBandType, nullptr );
        poVRTBand = cpl::down_cast<VRTSourcedRasterBand *>(poVDS->GetRasterBand( iBand+1 ));

/* -------------------------------------------------------------------- */
/*      Create a function based source with info on how to apply the    */
/*      enhancement.                                                    */
/* -------------------------------------------------------------------- */
        pasEInfo[iBand].poSrcBand = poSrcBand;
        pasEInfo[iBand].eWrkType = eBandType;
        pasEInfo[iBand].dfScaleMin = padfScaleMin[iBand];
        pasEInfo[iBand].dfScaleMax = padfScaleMax[iBand];
        pasEInfo[iBand].nLUTBins = nLUTBins;

        if( papanLUTs )
            pasEInfo[iBand].panLUT = papanLUTs[iBand];

        poVRTBand->AddFuncSource( EnhancerCallback, pasEInfo + iBand );

/* -------------------------------------------------------------------- */
/*      copy over some other information of interest.                   */
/* -------------------------------------------------------------------- */
        poVRTBand->CopyCommonInfoFrom( poSrcBand );
    }

/* -------------------------------------------------------------------- */
/*      Write to the output file using CopyCreate().                    */
/* -------------------------------------------------------------------- */
    hOutDS = GDALCreateCopy( hDriver, pszDest, static_cast<GDALDatasetH>(poVDS),
                             FALSE, papszCreateOptions,
                             pfnProgress, nullptr );
    if( hOutDS != nullptr )
        GDALClose( hOutDS );

    GDALClose(poVDS);

    GDALClose(hDataset);

/* -------------------------------------------------------------------- */
/*      Cleanup and exit.                                               */
/* -------------------------------------------------------------------- */
    GDALDumpOpenDatasets( stderr );
    GDALDestroyDriverManager();
    CSLDestroy( argv );
    CSLDestroy( papszCreateOptions );

    exit( 0 );
}
MAIN_END

/************************************************************************/
/*                      ComputeEqualizationLUTs()                       */
/*                                                                      */
/*      Get an image histogram, and compute equalization luts from      */
/*      it.                                                             */
/************************************************************************/

static int
ComputeEqualizationLUTs( GDALDatasetH hDataset, int nLUTBins,
                         double **ppadfScaleMin, double **ppadfScaleMax,
                         int ***ppapanLUTs,
                         GDALProgressFunc pfnProgress )

{
    int iBand;
    int nBandCount = GDALGetRasterCount(hDataset);
    int nHistSize = 0;
    GUIntBig *panHistogram = nullptr;

    // For now we always compute min/max
    *ppadfScaleMin =
        static_cast<double *>(CPLCalloc(sizeof(double), nBandCount));
    *ppadfScaleMax =
        static_cast<double *>(CPLCalloc(sizeof(double), nBandCount));

    *ppapanLUTs = static_cast<int **>(CPLCalloc(sizeof(int *), nBandCount));

/* ==================================================================== */
/*      Process all bands.                                              */
/* ==================================================================== */
    for( iBand = 0; iBand < nBandCount; iBand++ )
    {
        GDALRasterBandH hBand = GDALGetRasterBand( hDataset, iBand+1 );
        CPLErr eErr;

/* -------------------------------------------------------------------- */
/*      Get a reasonable histogram.                                     */
/* -------------------------------------------------------------------- */
        eErr =
            GDALGetDefaultHistogramEx( hBand,
                                     *ppadfScaleMin + iBand,
                                     *ppadfScaleMax + iBand,
                                     &nHistSize, &panHistogram,
                                     TRUE, pfnProgress, nullptr );

        if( eErr != CE_None )
            return FALSE;

        panHistogram[0] = 0; // zero out extremes (nodata, etc)
        panHistogram[nHistSize-1] = 0;

/* -------------------------------------------------------------------- */
/*      Total histogram count, and build cumulative histogram.          */
/*      We take care to use big integers as there may be more than 4    */
/*      Gigapixels.                                                     */
/* -------------------------------------------------------------------- */
        GUIntBig *panCumHist =
            static_cast<GUIntBig *>(CPLCalloc(sizeof(GUIntBig), nHistSize));
        GUIntBig nTotal = 0;
        int iHist;

        for( iHist = 0; iHist < nHistSize; iHist++ )
        {
            panCumHist[iHist] = nTotal + panHistogram[iHist]/2;
            nTotal += panHistogram[iHist];
        }

        CPLFree( panHistogram );

        if( nTotal == 0 )
        {
            CPLError( CE_Warning, CPLE_AppDefined,
                      "Zero value entries in histogram, results will not be meaningful." );
            nTotal = 1;
        }

/* -------------------------------------------------------------------- */
/*      Now compute a LUT from the cumulative histogram.                */
/* -------------------------------------------------------------------- */
        int *panLUT = static_cast<int *>(CPLCalloc(sizeof(int), nLUTBins));
        int iLUT;

        for( iLUT = 0; iLUT < nLUTBins; iLUT++ )
        {
            iHist = (iLUT * nHistSize) / nLUTBins;
            int nValue =
                static_cast<int>((panCumHist[iHist] * nLUTBins) / nTotal);

            panLUT[iLUT] = std::max(0, std::min(nLUTBins - 1, nValue));
        }

        (*ppapanLUTs)[iBand] = panLUT;
    }

    return TRUE;
}

/************************************************************************/
/*                          EnhancerCallback()                          */
/*                                                                      */
/*      This is the VRT callback that actually does the image rescaling.*/
/************************************************************************/

static CPLErr EnhancerCallback( void *hCBData,
                                int nXOff, int nYOff, int nXSize, int nYSize,
                                void *pData )

{
    const EnhanceCBInfo *psEInfo = static_cast<const EnhanceCBInfo *>(hCBData);

    if( psEInfo->eWrkType != GDT_Byte )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Currently gdalenhance only supports Byte output." );
        exit( 2 );
    }

    GByte *pabyOutImage = static_cast<GByte *>(pData);
    CPLErr eErr;
    float *pafSrcImage =
        static_cast<float *>(CPLCalloc(sizeof(float), nXSize * nYSize));

    eErr = psEInfo->poSrcBand->
        RasterIO( GF_Read, nXOff, nYOff, nXSize, nYSize,
                  pafSrcImage, nXSize, nYSize, GDT_Float32, 0, 0, nullptr );

    if( eErr != CE_None )
    {
        CPLFree( pafSrcImage );
        return eErr;
    }

    int nPixelCount = nXSize * nYSize;
    int iPixel;
    int bHaveNoData;
    float fNoData = static_cast<float>(psEInfo->poSrcBand->GetNoDataValue( &bHaveNoData ));
    double dfScale =
        psEInfo->nLUTBins / (psEInfo->dfScaleMax - psEInfo->dfScaleMin);

    for( iPixel = 0; iPixel < nPixelCount; iPixel++ )
    {
        if( bHaveNoData && pafSrcImage[iPixel] == fNoData )
        {
            pabyOutImage[iPixel] = static_cast<GByte>(fNoData);
            continue;
        }

        int iBin = static_cast<int>(
            (pafSrcImage[iPixel] - psEInfo->dfScaleMin) * dfScale);
        iBin = std::max(0, std::min(psEInfo->nLUTBins - 1, iBin));

        if( psEInfo->panLUT )
            pabyOutImage[iPixel] = static_cast<GByte>(psEInfo->panLUT[iBin]);
        else
            pabyOutImage[iPixel] = static_cast<GByte>(iBin);
    }

    CPLFree( pafSrcImage );

    return CE_None;
}

redpajama_set_name: RedPajamaGithub


text:
#import "UICollectionViewCell.h"

@class NSString, UIColor, UILabel, UIView;

@interface SKUIGallerySwooshCollectionViewCell : UICollectionViewCell
{
    UIView *_contentChildView;
    UIColor *_titleColor;
    UILabel *_titleLabel;
}

@property(retain, nonatomic) UIView *contentChildView; // @synthesize contentChildView=_contentChildView;
- (void).cxx_destruct;
- (void)layoutSubviews;
@property(copy, nonatomic) NSString *title;
- (void)setColoringWithColorScheme:(id)arg1;

@end


text:
define([
        "core/framework/Tundra",
        "core/asset/IAsset"
    ], function(Tundra, IAsset) {

var AnimationProviderAsset = IAsset.$extend(
/** @lends AnimationProviderAsset.prototype */
{
    __classvars__ :
    {
        /**
            @static
            @readonly
            @memberof AnimationProviderAsset
            @enum {Number}
        */
        Type:
        {
            SkinnedMesh: 0,
            KeyFrame: 1
        }
    },

    /**
        Animation provider asset interface

        @extends IAsset
        @constructs
        @param {String} name Unique name of the asset, usually this is the asset reference.
        @param {String} type Asset type.
    */
    __init__ : function(name, type, animationType)
    {
        this.$super(name, type);
        this.providesAnimations = true;
        this.animationHierarchy = {};
        this.animationType = animationType;
    },

    /**
        Returns available animation names for this skeleton.
        @return {Array} List of strings.
    */
    getAvailableAnimations : function()
    {
        return Object.keys(this.animationHierarchy);
    },

    /**
        Returns if animation is available in this skeleton.
        @return {Boolean}
    */
    hasAnimation : function(name)
    {
        return (this.animationHierarchy[name] !== undefined);
    },

    getAnimation : function(name)
    {
        if (!this.isAttached())
        {
            this.log.error("Cannot get animation, skeleton", this.name, "not attached.");
            return null;
        }

        var animation = this.animationHierarchy[name];
        if (animation === undefined)
        {
            this.log.error("Could not find animation", name, "for playback in", this.name, ". See getAvailableAnimations() for available animation names.");
            return null;
        }
        return animation;
    }
});

return AnimationProviderAsset;

}); // require js


text:
<?php

namespace Smath\VentasBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Pedido
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Pedido
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fechaCreacion", type="datetime")
     */
    private $fechaCreacion;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Auth\UserBundle\Entity\User",cascade={"persist"})
     * @ORM\JoinColumn(name="usuario", referencedColumnName="id")
     */
    private $usuario;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Smath\ClienteBundle\Entity\Cliente",cascade={"persist"})
     * @ORM\JoinColumn(name="cliente", referencedColumnName="id")
     */
    private $cliente;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Smath\ClienteBundle\Entity\PuntoVenta",cascade={"persist"})
     * @ORM\JoinColumn(name="puntoVenta", referencedColumnName="id")
     */
    private $puntoVenta;

    /**
     * @ORM\ManyToOne(targetEntity="Smath\CalendarioVisitaBundle\Entity\CalendarioVisita",cascade={"persist"})
     * @ORM\JoinColumn(name="calendarioVisita", referencedColumnName="id")
     */
    private $calendarioVisita;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fechaEntrega", type="datetime")
     */
    private $fechaEntrega;

    /**
     * @var boolean
     *
     * @ORM\Column(name="estado", type="boolean")
     */
    private $estado;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set fechaCreacion
     *
     * @param \DateTime $fechaCreacion
     * @return Pedido
     */
    public function setFechaCreacion($fechaCreacion)
    {
        $this->fechaCreacion = $fechaCreacion;

        return $this;
    }

    /**
     * Get fechaCreacion
     *
     * @return \DateTime
     */
    public function getFechaCreacion()
    {
        return $this->fechaCreacion;
    }

    /**
     * Set usuario
     *
     * @param integer $usuario
     * @return Pedido
     */
    public function setUsuario($usuario)
    {
        $this->usuario = $usuario;

        return $this;
    }

    /**
     * Get usuario
     *
     * @return integer
     */
    public function getUsuario()
    {
        return $this->usuario;
    }

    /**
     * Set cliente
     *
     * @param integer $cliente
     * @return Pedido
     */
    public function setCliente($cliente)
    {
        $this->cliente = $cliente;

        return $this;
    }

    /**
     * Get cliente
     *
     * @return integer
     */
    public function getCliente()
    {
        return $this->cliente;
    }

    /**
     * Set fechaEntrega
     *
     * @param \DateTime $fechaEntrega
     * @return Pedido
     */
    public function setFechaEntrega($fechaEntrega)
    {
        $this->fechaEntrega = $fechaEntrega;

        return $this;
    }

    /**
     * Get fechaEntrega
     *
     * @return \DateTime
     */
    public function getFechaEntrega()
    {
        return $this->fechaEntrega;
    }

    /**
     * Set puntoVenta
     *
     * @param \Smath\ClienteBundle\Entity\PuntoVenta $puntoVenta
     * @return Pedido
     */
    public function setPuntoVenta(\Smath\ClienteBundle\Entity\PuntoVenta $puntoVenta = null)
    {
        $this->puntoVenta = $puntoVenta;

        return $this;
    }

    /**
     * Get puntoVenta
     *
     * @return \Smath\ClienteBundle\Entity\PuntoVenta
     */
    public function getPuntoVenta()
    {
        return $this->puntoVenta;
    }

    /**
     * Set calendarioVisita
     *
     * @param \Smath\CalendarioVisitaBundle\Entity\CalendarioVisita $calendarioVisita
     * @return Pedido
     */
    public function setCalendarioVisita(\Smath\CalendarioVisitaBundle\Entity\CalendarioVisita $calendarioVisita = null)
    {
        $this->calendarioVisita = $calendarioVisita;

        return $this;
    }

    /**
     * Get calendarioVisita
     *
     * @return \Smath\CalendarioVisitaBundle\Entity\CalendarioVisita
     */
    public function getCalendarioVisita()
    {
        return $this->calendarioVisita;
    }

    /**
     * Set estado
     *
     * @param boolean $estado
     * @return Pedido
     */
    public function setEstado($estado)
    {
        $this->estado = $estado;

        return $this;
    }

    /**
     * Get estado
     *
     * @return boolean
     */
    public function getEstado()
    {
        return $this->estado;
    }

    /**
     *
     * @return string
     */
    public function __toString()
    {
        // hack
        return "$this->id";
    }
}


text:
package com.reyansh.audio.audioplayer.free.NowPlaying;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.reyansh.audio.audioplayer.free.Adapters.NowPlayingBottomBarAdapter;
import com.reyansh.audio.audioplayer.free.Common;
import com.reyansh.audio.audioplayer.free.Models.Song;
import com.reyansh.audio.audioplayer.free.R;
import com.reyansh.audio.audioplayer.free.Utils.Constants;
import com.reyansh.audio.audioplayer.free.Utils.PreferencesHelper;
import com.reyansh.audio.audioplayer.free.Utils.TypefaceHelper;

import java.util.ArrayList;

/**
 * Created by REYANSH on 7/31/2017.
 */

public class NowPlayingBottomBarFragment extends Fragment {

    private View mView;
    private FloatingActionButton mFloatingActionButton;
    private RelativeLayout mRelativeLayout;
    private SeekBar mSeekBar;
    private TextView mDurationTextView;
    private Common mApp;
    private Handler mHandler;
    SeekBar.OnSeekBarChangeListener mOnSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (mApp.isServiceRunning()) {
                try {
                    long currentSongDuration = mApp.getService().getMediaPlayer().getDuration();
                    seekBar.setMax((int) currentSongDuration);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            mHandler.removeCallbacks(seekbarUpdateRunnable);
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            int seekBarPosition = seekBar.getProgress();
            if (mApp.isServiceRunning()) {
                mApp.getService().getMediaPlayer().seekTo(seekBarPosition);
                mHandler.post(seekbarUpdateRunnable);
            } else {
                PreferencesHelper.getInstance().put(PreferencesHelper.Key.SONG_CURRENT_SEEK_DURATION, seekBarPosition);
                mDurationTextView.setText(Common.convertMillisToMinsSecs(mSeekBar.getProgress()));
            }
        }
    };
    /**
     * Create a new Runnable to update the seekbar and time every 100ms.
     */
    public Runnable seekbarUpdateRunnable = new Runnable() {

        public void run() {
            try {
                long currentPosition = mApp.getService().getMediaPlayer().getCurrentPosition();
                int currentPositionInSecs = (int) currentPosition;
                mSeekBar.setProgress(currentPositionInSecs);
                mDurationTextView.setText(Common.convertMillisToMinsSecs(mSeekBar.getProgress()));
                if (mApp.isServiceRunning()) {
                    if (mApp.getService().getMediaPlayer().isPlaying()) {
                        mHandler.postDelayed(seekbarUpdateRunnable, 1000);
                    } else {
                        mHandler.removeCallbacks(seekbarUpdateRunnable);
                    }
                } else {
                    mHandler.removeCallbacks(seekbarUpdateRunnable);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    private RecyclerView mRecyclerView;
    private NowPlayingBottomBarAdapter mNowPlayingBottomBarAdapter;
    private ArrayList<Song> songs;

    /**
     * Update UI when track completes it self and goes to next one
     */

    BroadcastReceiver mUpdateUIReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.hasExtra(Constants.ACTION_PLAY_PAUSE)) {
                if (mApp.isServiceRunning())
                    if (mApp.getService().getMediaPlayer().isPlaying()) {
                        mFloatingActionButton.setImageResource(R.drawable.pause);
                    } else {
                        mFloatingActionButton.setImageResource(R.drawable.play);
                    }
            } else {
                updateUI();
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_bottom_bar, container, false);
        mApp = (Common) getActivity().getApplicationContext();
        mView.setVisibility(View.GONE);

        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        mNowPlayingBottomBarAdapter = new NowPlayingBottomBarAdapter(this);
        mRecyclerView.setAdapter(mNowPlayingBottomBarAdapter);
        SnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(mRecyclerView);
        mDurationTextView = (TextView) mView.findViewById(R.id.duration_text);
        mDurationTextView.setTypeface(TypefaceHelper.getTypeface(Common.getInstance(), TypefaceHelper.FUTURA_BOLD));

        mSeekBar = (SeekBar) mView.findViewById(R.id.seek_bar);
        mSeekBar.setOnSeekBarChangeListener(mOnSeekBarChangeListener);

        try {
            mSeekBar.setThumb(ContextCompat.getDrawable(Common.getInstance(), R.drawable.transparent_drawable));
        } catch (Exception e) {
            e.printStackTrace();
        }

        mHandler = new Handler();

        mFloatingActionButton = (FloatingActionButton) mView.findViewById(R.id.fab);
        mRelativeLayout = (RelativeLayout) mView.findViewById(R.id.main_background);
        updateUI();
        mFloatingActionButton.setOnClickListener(v -> {
            mApp.getPlayBackStarter().playPauseFromBottomBar();

            try {
                setSeekbarDuration(mApp.getService().getMediaPlayer().getDuration());
            } catch (NullPointerException e) {
                e.printStackTrace();
                mFloatingActionButton.setImageResource(R.drawable.play);
            }

        });
        mRelativeLayout.setOnClickListener(v -> {

        });

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                    int newPosition = linearLayoutManager.findFirstCompletelyVisibleItemPosition();
                    int oldPosition;
                    if (mApp.isServiceRunning()) {
                        oldPosition = mApp.getService().getCurrentSongIndex();
                    } else {
                        oldPosition = PreferencesHelper.getInstance().getInt(PreferencesHelper.Key.CURRENT_SONG_POSITION);
                    }
                    if (newPosition != -1)
                        if (mApp.isServiceRunning() && newPosition != oldPosition) {
                            PreferencesHelper.getInstance().put(PreferencesHelper.Key.SONG_CURRENT_SEEK_DURATION, 0);
                            mApp.getService().setSelectedSong(newPosition);
                        } else if (oldPosition != newPosition) {
                            PreferencesHelper.getInstance().put(PreferencesHelper.Key.SONG_CURRENT_SEEK_DURATION, 0);
                            mApp.getPlayBackStarter().playSongs(songs, newPosition);
                        }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    public void onStart() {
        super.onStart();
        getActivity().registerReceiver((mUpdateUIReceiver), new IntentFilter(Constants.ACTION_UPDATE_NOW_PLAYING_UI));
    }

    @Override
    public void onStop() {
        super.onStop();
        getActivity().unregisterReceiver((mUpdateUIReceiver));
    }

    private void updateUI() {

        if (mApp.isServiceRunning()) {
            mNowPlayingBottomBarAdapter.updateData(mApp.getService().getSongList());
            if (mApp.isServiceRunning()) {
                if (mApp.getService().getMediaPlayer().isPlaying()) {
                    mFloatingActionButton.setImageResource(R.drawable.pause);
                } else {
                    mFloatingActionButton.setImageResource(R.drawable.play);
                }
            }

            mView.setVisibility(View.VISIBLE);
            try {
                setSeekbarDuration(mApp.getService().getMediaPlayer().getDuration());
            } catch (Exception e) {
                e.printStackTrace();
            }
            mRecyclerView.scrollToPosition(mApp.getService().getCurrentSongIndex());
        } else {
            new AsyncTask<Void, Void, Void>() {
                int position;
                int seekPosition;

                @Override
                protected Void doInBackground(Void... params) {
                    songs = mApp.getDBAccessHelper().getQueue();
                    position = PreferencesHelper.getInstance().getInt(PreferencesHelper.Key.CURRENT_SONG_POSITION, 0);
                    seekPosition = PreferencesHelper.getInstance().getInt(PreferencesHelper.Key.SONG_CURRENT_SEEK_DURATION, 0);
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
                    if (songs.size() > 0) {
                        mNowPlayingBottomBarAdapter.updateData(songs);
                        mSeekBar.setMax(PreferencesHelper.getInstance().getInt(PreferencesHelper.Key.SONG_TOTAL_SEEK_DURATION, 0));
                        mSeekBar.setProgress(seekPosition);
                        mRecyclerView.scrollToPosition(position);
                        mDurationTextView.setText(Common.convertMillisToMinsSecs(mSeekBar.getProgress()));
                        mView.setVisibility(View.VISIBLE);
                    } else {
                        mView.setVisibility(View.GONE);
                    }
                }
            }.execute();
        }
    }

    private void setSeekbarDuration(int duration) {
        mSeekBar.setMax(duration);
        mSeekBar.setProgress(mApp.getService().getMediaPlayer().getCurrentPosition());
        mHandler.postDelayed(seekbarUpdateRunnable, 1000);
        mDurationTextView.setText(Common.convertMillisToMinsSecs(mSeekBar.getProgress()));
    }
}


text:
"""
Backwards-compatible support for include()-ing the model-based
activation workflow's URLconf.

The new location for that URLconf is
registration.backends.model_activation.urls. Using include() with
registration.backends.default.urls will raise deprecation warnings,
and support for it will be removed in a future release.

"""

import warnings

warnings.warn(
    "registration.backends.default.urls is deprecated; "
    "use registration.backends.model_activation.urls instead.",
    DeprecationWarning
)

from registration.backends.model_activation import urls as model_urls

urlpatterns = model_urls.urlpatterns


text:
<?php

interface b2c_order_extends_interface
{
    /**
     * 订单支付完后对订单的扩展操作
     * @param mixed sdf payment array
     * @param mixed sdf of order change array
     * @return null
     */
    public function order_pay_extends($sdf, &$sdf_order=array());
}


text:
/**
 * @jsx React.DOM
 */

// Swipe gestures in React!

// Create some utility classes.
function Vector(x, y) {
  this.x = x;
  this.y = y;
}

// TODO: we could pool these in the future maybe, so
// create them with a helper function.
function vector(x, y) {
  return new Vector(x, y);
}

function SwipingEvent(offset, time, swiping) {
  this.offset = offset;
  this.time = time;
  this.swiping = swiping;
}

function swipingEvent(offset, time) {
  return new SwipingEvent(offset, time);
}

function SwipedEvent(velocity) {
  this.velocity = velocity;
}

function swipedEvent(velocity) {
  return new SwipedEvent(velocity);
}

// We can avoid a square root by doing the comparison
// within the function.
function isDistanceGreaterThan(v1, v2, d) {
  // http://jsperf.com/pow-vs-mul
  var xd = (v2.x - v1.x);
  var yd = (v2.y - v1.y);
  return xd * xd + yd * yd > d * d;
}

// We need to know the difference between a tap and a
// swipe; we define a swipe by moving at least 2px
// throughout its lifetime.
var MIN_SWIPE_DISTANCE = 2;

var SwipeTarget = React.createClass({
  getInitialState: function() {
    return {
      lastTouchPos: null,
      lastTouchVelocity: null,
      lastTouchTime: null,
      touchStartPos: null,
      swiping: false
    };
  },

  handleTouchStart: function(e) {
    var touch = e.targetTouches[0];

    if (this.props.onStartGesturing) {
      this.props.onStartGesturing();
    }

    this.setState({
      lastTouchPos: vector(touch.screenX, touch.screenY),
      lastTouchVelocity: vector(0, 0),
      lastTouchTime: Date.now(),
      // Create a second vector here because we mutate
      // the first one to save GC
      touchStartPos: vector(touch.screenX, touch.screenY),
      swiping: false
    });

    // We return false from all touch handlers so the
    // browser doesn't scroll.
    return false;
  },

  handleTouchMove: function(e) {
    var touch = e.targetTouches[0];
    var time = Date.now();
    var timeDelta = time - this.state.lastTouchTime;
    var offsetX = touch.screenX - this.state.lastTouchPos.x;
    var offsetY = touch.screenY - this.state.lastTouchPos.y;

    // If the swipe has ever moved 2px from the origin, we
    // are doing a swipe gesture.
    var swiping = this.state.swiping || isDistanceGreaterThan(
      this.state.lastTouchPos,
      this.state.touchStartPos,
      MIN_SWIPE_DISTANCE
    );

    if (this.props.onSwiping && swiping) {
      this.props.onSwiping(swipingEvent(vector(offsetX, offsetY), timeDelta, swiping));
    }

    // Reuse the last obj for less GCs, even though
    // mutating state is bad form in React. This is a
    // hot path and we know what we're doing.
    var lastTouchVelocity = this.state.lastTouchVelocity;
    lastTouchVelocity.x = offsetX / timeDelta;
    lastTouchVelocity.y = offsetY / timeDelta;

    var lastTouchPos = this.state.lastTouchPos;
    // TODO: I think these numbers are incorrect on Android
    lastTouchPos.x = touch.screenX;
    lastTouchPos.y = touch.screenY;

    this.setState({
      lastTouchPos: lastTouchPos,
      lastTouchVelocity: lastTouchVelocity,
      lastTouchTime: time,
      swiping: swiping
    });

    // Again, return false so the browser doesn't get it.
    return false;
  },

  handleTouchEnd: function(e) {
    if (this.props.onStopGesturing) {
      this.props.onStopGesturing(this.state.swiping);
    }

    // TODO: is it possible the velocity has changed since
    // the last move event? Like if the user swipes, holds,
    // and then lets go?
    if (this.props.onSwiped && this.state.swiping) {
      this.props.onSwiped(swipedEvent(this.state.lastTouchVelocity));
    }
    return false;
  },

  render: function() {
    // Area of improvement: make it work for mouse events.
    return this.transferPropsTo(
      <div
          onTouchStart={this.handleTouchStart}
          onTouchEnd={this.handleTouchEnd}
          onTouchMove={this.handleTouchMove}>
        {this.props.children}
      </div>
    );
  }
});

// Need this to get happy touch events in React. By the way
// this example uses a custom build of React which injects
// TapEventPlugin, which is needed if you ever want
// onTouchTap. It is not included by default in React today
React.initializeTouchEvents(true);

window.SwipeTarget = SwipeTarget;


text:
package net.fhtagn.orientation.orientation.sensors;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;

import net.fhtagn.orientation.orientation.math.IO;
import net.fhtagn.orientation.orientation.math.Mat3;
import net.fhtagn.orientation.orientation.math.Quaternion;

// An orientation tracker that uses Android's ROTATION_VECTOR sensor which should rely on
// sensor fusion
public class RotVectorOrientationTracker extends OrientationTracker {
  private Sensor rotVectorSensor;
  private String debugText = "";

  public RotVectorOrientationTracker(SensorManager sm) {
    rotVectorSensor = sm.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
  }

  public void reset() {}

  public String getDebugText() {
    return debugText;
  }

  // Must be call in owner Activity.onResume()
  @Override
  public void onResume(SensorManager sm) {
    sm.registerListener(this, rotVectorSensor,
        SensorManager.SENSOR_DELAY_GAME);
  }

  // Must be call in owner Activity.onPause()
  @Override
  public void onPause(SensorManager sm) {
    sm.unregisterListener(this);
  }

  private void update(float[] rotationVector) {
    float[] M = new float[9];
    SensorManager.getRotationMatrixFromVector(M, rotationVector);

    final Mat3 mat = Mat3.fromRowMajorArray(M);
    setOrientation(Quaternion.fromMatrix(mat));
  }

  public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
      final float [] rotationVector = event.values.clone();

      debugText = "rotV : " + IO.vectorToString(rotationVector) + "\n";
      synchronized (this) {
        update(rotationVector);
      }

      debugText += "rot matrix :\n" + getOrientation().toMatrix();
      float[] mat44 = new float[16];
      getOrientation().toMatrix().toColumnMajorArray(mat44);
      debugText += "44 rot :\n" + IO.matrixToString(mat44);
      // Log.i(TAG, debugText);
    }
  }
}


text:
/* Generated By:JJTree: Do not edit this line. MQLIDENTIFICATIONVARIABLE.java Version 4.1 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=true,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=MQL,NODE_EXTENDS=,NODE_FACTORY= */
package ed.db.mql.nodes;

import ed.db.mql.SimpleNode;
import ed.db.mql.MQL;
import ed.db.mql.Token;

public class MQLIDENTIFICATIONVARIABLE extends SimpleNode {
  public MQLIDENTIFICATIONVARIABLE(int id) {
    super(id);
  }

  public MQLIDENTIFICATIONVARIABLE(MQL p, int id) {
    super(p, id);
  }
}
/* JavaCC - OriginalChecksum=0e674f865846fb4e3936330cacf3106f (do not edit this line) */


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _bag = require('../bag');

var _bag2 = _interopRequireDefault(_bag);

var _message = require('./message');

var _message2 = _interopRequireDefault(_message);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var url = require('url');

/**
 * Http Request
 *
 * Contains information about request
 */
var Request = function (_Message) {
  _inherits(Request, _Message);

  /**
   * Constructor
   */
  function Request() {
    _classCallCheck(this, Request);

    var _this = _possibleConstructorReturn(this, (Request.__proto__ || Object.getPrototypeOf(Request)).call(this));

    _this.setMethod(Request.METHOD_GET);
    _this.setUri(new _bag2.default());
    _this.setQuery(new _bag2.default());
    _this.setServer(new _bag2.default());
    _this.setClient(new _bag2.default());
    return _this;
  }

  /**
   * Get request's method (GET|POST|PUT|PATCH|DELETE|OPTIONS)
   * @returns {string}
   */

  _createClass(Request, [{
    key: 'getMethod',
    value: function getMethod() {
      return this._method;
    }

    /**
     * Set request's method
     * @param {!string} method
     */

  }, {
    key: 'setMethod',
    value: function setMethod(method) {
      this._method = method;
    }

    /**
     * Get URI
     * @returns {Bag}
     */

  }, {
    key: 'getUri',
    value: function getUri() {
      return this._uri;
    }

    /**
     * Set URI
     * @param {!string|Bag|Object} uri
     */

  }, {
    key: 'setUri',
    value: function setUri(uri) {
      if (uri instanceof _bag2.default) {
        this._uri = uri;
      } else if ((typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) === 'object') {
        this._uri = new _bag2.default(uri);
      } else if (typeof uri === 'string') {
        var info = url.parse(uri, true);
        this._uri = new _bag2.default({
          protocol: info.protocol,
          host: info.hostname,
          port: parseInt(info.port),
          path: info.pathname,
          hash: info.hash,
          href: info.href,
          search: info.search
        });
        this.setQuery(info.query);
      } else {
        throw new Error('The request\'s URI must be an instance of Bag, an object or a string.');
      }
    }

    /**
     * Get request's query
     * @returns {Bag}
     */

  }, {
    key: 'getQuery',
    value: function getQuery() {
      return this._query;
    }

    /**
     * Set request's query
     * @param {Bag|Object|string} query
     */

  }, {
    key: 'setQuery',
    value: function setQuery(query) {
      if (query instanceof _bag2.default) {
        this._query = query;
      } else if ((typeof query === 'undefined' ? 'undefined' : _typeof(query)) === 'object') {
        this._query = new _bag2.default(query);
      } else if (typeof query === 'string') {
        this._query = new _bag2.default(url.parse(query, true).query);
      } else {
        throw new Error('The query of request must be either a string, an instance of Bag or an object.');
      }
    }

    /**
     * Return server's information
     * @returns {Bag}
     */

  }, {
    key: 'getServer',
    value: function getServer() {
      return this._server;
    }

    /**
     * Set server's information
     * @param {Bag|Object} [server={}]
     */

  }, {
    key: 'setServer',
    value: function setServer() {
      var server = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      if (server instanceof _bag2.default) {
        this._server = server;
      } else if ((typeof server === 'undefined' ? 'undefined' : _typeof(server)) === 'object') {
        this._server = new _bag2.default(server);
      } else {
        throw new Error('The request\'s server information must be either an instance of Bag or an object.');
      }
    }

    /**
     * Return client's information
     * @returns {Bag}
     */

  }, {
    key: 'getClient',
    value: function getClient() {
      return this._client;
    }

    /**
     * Set client's information
     * @param {Bag|Object} [client={}]
     */

  }, {
    key: 'setClient',
    value: function setClient() {
      var client = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      if (client instanceof _bag2.default) {
        this._client = client;
      } else if ((typeof client === 'undefined' ? 'undefined' : _typeof(client)) === 'object') {
        this._client = new _bag2.default(client);
      } else {
        throw new Error('The request\'s client information must be either an instance of Bag or an object.');
      }
    }

    /**
     * Create an instance of Request from a specific resource
     * @param {!Object} resource Original resource, it should be an instance of http.IncomingMessage
     * @returns {Request}
     */

  }], [{
    key: 'from',
    value: function from(resource) {
      if (resource === null || (typeof resource === 'undefined' ? 'undefined' : _typeof(resource)) !== 'object') {
        throw new Error('The resource of request must be an object.');
      }

      var request = new Request();
      this._setUpMethod(request, resource);
      this._setUpHeader(request, resource);
      this._setUpUri(request, resource);
      this._setUpServer(request, resource);
      this._setUpClient(request, resource);

      return request;
    }

    /**
     * Set up header from resource
     * @param {!Request} request
     * @param {!Object} resource
     * @private
     */

  }, {
    key: '_setUpHeader',
    value: function _setUpHeader(request, resource) {
      if (resource.rawHeaders !== undefined) {
        for (var i = 0; i < resource.rawHeaders.length; i++) {
          request.getHeader().set(resource.rawHeaders[i], resource.rawHeaders[++i]);
        }
      }
    }

    /**
     * Setup URI from resource's url
     * @param {!Request} request
     * @param {!Object} resource
     * @private
     */

  }, {
    key: '_setUpUri',
    value: function _setUpUri(request, resource) {
      if (resource.url !== undefined) {
        request.setUri(resource.url);
      }
    }

    /**
     * Set up method of request
     * @param {!Request} request
     * @param {!Object} resource
     * @private
     */

  }, {
    key: '_setUpMethod',
    value: function _setUpMethod(request, resource) {
      if (resource.method !== undefined) {
        request.setMethod(resource.method);
      }
    }

    /**
     * Set up information about request's server
     * @param {!Request} request
     * @param {!Object} resource
     * @private
     */

  }, {
    key: '_setUpServer',
    value: function _setUpServer(request, resource) {
      if (resource.connection !== undefined) {
        var connection = resource.connection;
        request.getClient().set(Request.SERVER_HOST, connection.address().address);
        request.getClient().set(Request.SERVER_PORT, connection.address().port);
        request.getClient().set(Request.ADDRESS_FAMILY, connection.address().family);
        request.getClient().set(Request.LOCAL_HOST, connection.localAddress);
        request.getClient().set(Request.LOCAL_PORT, connection.localPort);
      }
    }

    /**
     * Set up information about request's client source
     * @param {!Request} request
     * @param {!Object} resource
     * @private
     */

  }, {
    key: '_setUpClient',
    value: function _setUpClient(request, resource) {
      if (resource.connection !== undefined) {
        var connection = resource.connection;
        request.getClient().set(Request.CLIENT_HOST, connection.remoteAddress);
        request.getClient().set(Request.CLIENT_PORT, connection.remotePort);
        request.getClient().set(Request.ADDRESS_FAMILY, connection.remoteFamily);
      }
    }
  }]);

  return Request;
}(_message2.default);

exports.default = Request;

Request.METHOD_GET = 'GET';
Request.METHOD_POST = 'POST';
Request.METHOD_PUT = 'PUT';
Request.METHOD_PATCH = 'PATCH';
Request.METHOD_DELETE = 'DELETE';
Request.METHOD_HEAD = 'HEAD';
Request.METHOD_OPTION = 'OPTION';

Request.DEFAULT_METHOD = 'GET';
Request.DEFAULT_PATH = '/';

Request.ADDRESS_FAMILY = 'family';
Request.ADDRESS_HOST = 'host';
Request.ADDRESS_PORT = 'port';
Request.SERVER_HOST = Request.ADDRESS_HOST;
Request.SERVER_PORT = Request.ADDRESS_PORT;
Request.CLIENT_HOST = Request.ADDRESS_HOST;
Request.CLIENT_PORT = Request.ADDRESS_PORT;
Request.LOCAL_HOST = Request.ADDRESS_HOST;
Request.LOCAL_PORT = Request.ADDRESS_PORT;
Request.URI_PROTOCOL = 'protocol';
Request.URI_HOST = 'host';
Request.URI_PORT = 'port';
Request.URI_PATH = 'path';
Request.URI_HASH = 'hash';


text:
'use strict';

var assert = require('assert');
var should = require('should');
var matter = require('gray-matter');
var utils = require('parser-utils');
var consolidate = require('consolidate');
var _ = require('lodash');

var Template = require('..');
var template = new Template();

describe('.parse()', function () {
  before(function () {
    template = new Template();

    template.parser('md', function (file) {
      _.merge(file, utils.extendFile(file));
      _.merge(file, matter(file.content));
    });
  });

  describe('.parseSync()', function () {
    describe('when the `.render()` method is called:', function () {
      it('should run the parser stack for the given template before passing it to render:', function () {
        template.engine('md', consolidate.handlebars);

        template
          .parserSync('md', function a(file, value, key) {
            file.locals.author = 'Brian Woodward';
          })
          .parserSync('md', function b(file, value, key) {
            file.locals.author = file.locals.author.toUpperCase();
          })

        var file = {path: 'fixture.md', content: '<title>{{author}}</title>', author: 'Jon Schlinkert'};

        template.render(file, function (err, content) {
          if (err) console.log(err);
          content.should.equal('<title>BRIAN WOODWARD</title>');
        });
      });
    });

    describe('.parse()', function () {
      describe('when a file extension is provided:', function () {
        it('should run a parser stack based on file extension:', function () {
          template
            .parserSync('a', function (file, value, key) {
              file.content = 'abc-' + file.content;
            })
            .parserSync('a', function (file, value, key) {
              file.content = file.content.toUpperCase();
            })
            .parserSync('a', function (file, value, key) {
              file.content = file.content.replace(/(.)/g, '$1 ')
            });

          template.getParsers('a', true).length.should.equal(3);

          var result = template.parseSync({ext: 'a', content: 'xyz'});
          result.should.have.property('content', 'A B C - X Y Z ');
        });
      });
    });
  });
});


text:
{% extends "cheddar/base.html" %}
{% block content %}
Welcome,
{% if user.last_name %}
 {{ user.first_name }} {{ user.last_name }}
{% else %}
 {{ user.username }}
{% endif %}

{% if tracks %}
You are an admin for the following tracks:

{% for track in tracks %}
{{track.name}}

{% endfor %}
{% else %}
You are not (yet) a track admin.
{% endif %}
{% endblock %}


text: {{+partials.standard_apps_article article:intros.manifest/description/}}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nim;

import java.util.Random;
import javax.swing.JOptionPane;

/**
 *
 * @author stefan987
 */
public class Player {

    private String name;

    public Player(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public static int getTurn() {
        return new Random().nextInt(3) + 1;
    }

    //@return returns the total blocks
    public int doTurn(int tBlocks) {
        int totalBlocks = tBlocks;
        JOptionPane.showMessageDialog(null, name + ", it is your turn.");
        String input = JOptionPane.showInputDialog("How many blocks do you choose?");
        while (!NimRunner.isInputANumber(input)) {
            input = JOptionPane.showInputDialog("Please enter a valid number. Now, how many blocks do you choose?");
        }
        int playerChoice = Integer.parseInt(input);

        if (playerChoice <= (totalBlocks / 2)) {
            totalBlocks -= playerChoice;
            JOptionPane.showMessageDialog(null, "There are now " + totalBlocks + " blocks");
        } else {
            JOptionPane.showMessageDialog(null, "You must choose 1/2 or less of the blocks!\n"
                    + "Please try again.");
        }
        return totalBlocks;
    }
}


text:
<bill session="115" type="s" number="1926" updated="2017-10-13T13:30:17Z">
  <state datetime="2017-10-05">REFERRED</state>
  <status>
    <introduced datetime="2017-10-05"/>
  </status>
  <introduced datetime="2017-10-05"/>
  <titles>
    <title type="short" as="introduced">Saint Francis Dam Disaster National Memorial Act</title>
    <title type="short" as="introduced">Saint Francis Dam Disaster National Memorial Act</title>
    <title type="official" as="introduced">A bill to provide for the establishment of a national memorial and national monument to commemorate those killed by the collapse of the Saint Francis Dam on March 12, 1928, and for other purposes.</title>
    <title type="display">Saint Francis Dam Disaster National Memorial Act</title>
  </titles>
  <sponsor bioguide_id="H001075"/>
  <cosponsors>
    <cosponsor bioguide_id="F000062" joined="2017-10-05"/>
  </cosponsors>
  <actions>
    <action datetime="2017-10-05">
      <text>Introduced in Senate</text>
    </action>
    <action datetime="2017-10-05" state="REFERRED">
      <text>Read twice and referred to the Committee on Energy and Natural Resources.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="SSEG" name="Senate Energy and Natural Resources" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects/>
  <amendments/>
  <committee-reports/>
</bill>


text: https://github.com/guardian/scribe-plugin-sanitizer via globals


text:
<Template name="invoice_ticket">

        {{ i18n 'invoiceCard.name' }}
        {{ i18n 'invoiceCard.invoiceNumber' }}
        {{ i18n 'invoiceCard.paymentOption' }}
        {{ i18n 'invoiceCard.state' }}
        {{ i18n 'invoiceCard.dates.createdAt' }}
        {{ i18n 'invoiceCard.amount' }}
        {{ i18n 'invoiceCard.yenReceived' }}
        {{ i18n 'invoiceCard.satoshisExpected' }}
        {{ i18n 'invoiceCard.satoshisReceived' }}

        {{ ticket.buyerFullName }}
        {{ ticket.invoiceNumber }}
        {{ ticket.paymentOption }}

        {{ formatDate ticket.createdAt }}
        {{ formatCurrency 'USD' ticket.usdRequested }}
        {{ formatCurrency 'YEN' ticket.yenReceived }}
        {{ formatCurrency 'BTC' (satoshisToBtc ticket.satoshisExpected) }}
        {{ formatCurrency 'BTC' (satoshisToBtc ticket.satoshisReceived) }}

</Template>


text:
function getIPAddresses() {

    var ipAddresses = [];

    var interfaces = require('os').networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                ipAddresses.push(alias.address);
            }
        }
    }

    return ipAddresses;
}

exports.get = getIPAddresses;


text:
{{'label.anchor.products' | translate}} /

{{'label.anchor.savingproducts' | translate}} /

{{savingproduct.name}}

            {{'label.button.edit' | translate}}

		<legend>{{savingproduct.name}}</legend>

					{{'label.heading.details' | translate}}

				{{'label.heading.description' | translate}}
				{{savingproduct.description}}

				{{'label.heading.shortname' | translate}} :
				{{savingproduct.shortName}}

{{'label.heading.items' | translate}}

				{{'label.heading.currency' | translate}}
				{{savingproduct.currency.name}}

				{{'label.heading.decimalplaces' | translate}}
				{{savingproduct.currency.decimalPlaces}}

				{{'label.heading.currencyinmultiplesof' | translate}}
				{{savingproduct.currency.inMultiplesOf}}

				{{'label.heading.nominalannualinterestrate' | translate}}
				{{savingproduct.nominalAnnualInterestRate}}

				{{'label.heading.interestcompoundingperiod' | translate}}
				{{savingproduct.interestCompoundingPeriodType.value}}

				{{'label.heading.interestpostingperiod' | translate}}
				{{savingproduct.interestPostingPeriodType.value}}

				{{'label.heading.interestcalculatedusing' | translate}}
				{{savingproduct.interestCalculationType.value}}

				{{'label.heading.daysinyears' | translate}}
				{{savingproduct.interestCalculationDaysInYearType.value}}

{{'label.heading.settings' | translate}}

				{{'label.heading.minimumopeningbalance' | translate}}
				{{savingproduct.minRequiredOpeningBalance}}

				{{'label.heading.lockinPeriodFrequency' | translate}}
				{{savingproduct.lockinPeriodFrequency}} {{savingproduct.lockinPeriodFrequencyType.value}}

				{{'label.heading.withdrawalfeefotransfers' | translate}}
				{{savingproduct.withdrawalFeeForTransfers}}

			    {{'label.heading.charges' | translate}}

			    {{'label.heading.name' | translate}}
			    {{'label.heading.type' | translate}}
			    {{'label.heading.amount' | translate}}
			    {{'label.heading.collectedon' | translate}}

			    {{charge.name}}
			    {{charge.chargeCalculationType.value}}
			    {{charge.amount}}
			    {{charge.chargeTimeType.value}}

{{'label.heading.accounting' | translate}}	{{'label.none' | translate}}

							{{'label.heading.savingsreference' | translate}}({{'label.heading.assets' | translate}})
							{{savingproduct.accountingMappings.savingsReferenceAccount.name}}

							{{'label.heading.savingscontrol' | translate}}({{'label.heading.liabilities' | translate}})
							{{savingproduct.accountingMappings.savingsControlAccount.name}}

							{{'label.heading.transfersinsuspenpense' | translate}}({{'label.heading.liabilities' | translate}})
							{{savingproduct.accountingMappings.transfersInSuspenseAccount.name}}

							{{'label.heading.interestonsavings' | translate}}({{'label.heading.expenses' | translate}})
							{{savingproduct.accountingMappings.interestOnSavingsAccount.name}}

							{{'label.heading.incomefromfee' | translate}}({{'label.heading.income' | translate}})
							{{savingproduct.accountingMappings.incomeFromFeeAccount.name}}

							{{'label.heading.incomefrompenalties' | translate}}({{'label.heading.income' | translate}})
							{{savingproduct.accountingMappings.incomeFromPenaltyAccount.name}}

								{{'label.heading.advancedaccountingrules' | translate}}

{{'label.heading.configurefundsourcesforpaymentchannels' | translate}}

				            {{'label.heading.paymenttype' | translate}}
				            {{'label.heading.fundsource' | translate}}

				            {{paymentChannel.paymentType.name}}
                			{{paymentChannel.fundSourceAccount.name}}

			                {{'label.heading.feestospecificincome' | translate}}

			                {{'label.heading.fees' | translate}}
			                {{'label.heading.incomeaccount' | translate}}

			                {{feeToIncomeAccount.charge.name}}
			                {{feeToIncomeAccount.incomeAccount.name}}

			                {{'label.heading.penaltiesspecifictoincomeacc' | translate}}

			                {{'label.heading.penalty' | translate}}
			                {{'label.heading.incomeaccount' | translate}}

			                {{penaltyToIncomeAccount.charge.name}}
			                {{penaltyToIncomeAccount.incomeAccount.name}}

					{{'label.button.top' | translate}}


text:
/**
 * Module dependencies.
 */
var express = require('express');
var proxy = require('../../index'); // require('http-proxy-middleware');

/**
 * Configure proxy middleware
 */
var wsProxy = proxy('/', {
                target: 'http://echo.websocket.org',
                // pathRewrite: {
                //  '^/websocket' : '/socket',          // rewrite path.
                //  '^/removepath' : ''                 // remove path.
                // },
                changeOrigin: true,                     // for vhosted sites, changes host header to match to target's host
                ws: true,                               // enable websocket proxy
                logLevel: 'debug'
            });

var app = express();
app.use('/', express.static(__dirname));                // demo page
app.use(wsProxy);                                       // add the proxy to express

var server = app.listen(3000);
server.on('upgrade', wsProxy.upgrade);                  // optional: upgrade externally

console.log('[DEMO] Server: listening on port 3000');
console.log('[DEMO] Opening: http://localhost:3000');

require('opn')('http://localhost:3000');

/**
 * Example:
 * Open http://localhost:3000 in WebSocket compatible browser.
 * In browser console:
 * 1. `var socket = new WebSocket('ws://localhost:3000');`          // create new WebSocket
 * 2. `socket.onmessage = function (msg) {console.log(msg)};`       // listen to socket messages
 * 3. `socket.send('hello world');`                                 // send message
 * >  {data: "hello world"}                                         // server should echo back your message.
 **/


text:
require 'spec_helper'

RSpec.describe Wirecard::Callback do
  let(:fingerprinter) { Wirecard::Fingerprint::Sha512.new(params, implicit_fingerprint_order) }
  let(:params) { { 'parameterKey1' => 'parameterValue1',
                   'parameterKey2' => 'parameterValue2' }.merge!(additional_params) }
  let(:additional_params) { {} }
  let(:implicit_fingerprint_order) { nil }

  describe '#fingerprinted_params' do
    subject { fingerprinter.fingerprinted_params }

    context 'when no implicit_fingerprint_order is given' do
      let(:implicit_fingerprint_order) { nil }

      it { is_expected.to eq params.merge({
        "requestFingerprint" => "5b158abcb10055cc9a700a871676559b5444cd9b9e7d6aebb9ae2783dd1230bdb46b6c2db1bbefe816757762b281aa44fbc7b73dcfad115d9d276582e04f603b",
        "requestFingerprintOrder" => "parameterKey1,parameterKey2,requestFingerprintOrder,secret"
      }) }
    end

    context 'when implicit_fingerprint_order is set' do
      let(:implicit_fingerprint_order) { ['parameterKey2', 'parameterKey1', 'secret'] }

      it { is_expected.to eq params.merge({
        "requestFingerprint" => "8c558d1efb1fdbb768c92774c622e0b38b6fe1ff0c63ee37513a1bfa138df33c868962acf1e255fb0513adfd23019343412d092e1e3fdfe3ba178bd91e5d9216"
      }) }
    end
  end

  describe '#request_fingerprint_order' do
    subject { fingerprinter.send(:request_fingerprint_order) }

    it { is_expected.to eq 'parameterKey1,parameterKey2,requestFingerprintOrder,secret' }
  end

  describe '#fingerprint_string' do
    subject { fingerprinter.send(:fingerprint_string) }

    context 'when no implicit_fingerprint_order is given' do
      let(:implicit_fingerprint_order) { nil }

      context 'when requestFingerprintOrder is set within parameters' do
        let(:additional_params) { {'requestFingerprintOrder' => 'parameterKey1,parameterKey2,requestFingerprintOrder,secret'} }

        it { is_expected.to eq 'parameterValue1parameterValue2parameterKey1,parameterKey2,requestFingerprintOrder,secretB8AKTPWBRMNBV455FG6M2DANE99WU2' }
      end

      context 'when responseFingerprintOrder is set within parameters' do
        let(:additional_params) { {'responseFingerprintOrder' => 'parameterKey2,parameterKey1,secret,responseFingerprintOrder'} }

        it { is_expected.to eq 'parameterValue2parameterValue1B8AKTPWBRMNBV455FG6M2DANE99WU2parameterKey2,parameterKey1,secret,responseFingerprintOrder' }
      end

      context 'when no order is given in the params' do
        it { expect{ subject }.to raise_error(Wirecard::Fingerprint::NoFingerprintOrderGivenError) }
      end
    end

    context 'when implicit_fingerprint_order is set' do
      let(:implicit_fingerprint_order) { ['parameterKey2', 'parameterKey1', 'secret'] }

      it { is_expected.to eq 'parameterValue2parameterValue1B8AKTPWBRMNBV455FG6M2DANE99WU2' }
    end

  end

end


text:
{% extends "layout.html" %}

{% block page_title %} Admin | Page list {% endblock %}

{% block head %}
    {% include "includes/head.html" %}
    {% include "includes/scripts.html" %}
{% endblock %}

{% block proposition_header %}
    {% include "includes/propositional_navigation_admin.html" %}
{% endblock %}

{% block content %}

        {% include "admin/page-list/condition-list.html" %}

Epilepsy awake

question

                        IF 1 →

                        IF 2 →

{% endblock %}


text:
These settings apply only when `--ruby` is specified on the command line.

``` yaml $(ruby)
ruby:
  package-name: azure_mgmt_devtestlabs
  package-version: "0.16.0"
  azure-arm: true
```

### Ruby multi-api

``` yaml $(ruby) && $(multiapi)
batch:
  - tag: package-2016-05
```

### Tag: package-2016-05 and ruby

These settings apply only when `--tag=package-2016-05 --ruby` is specified on the command line.
Please also specify `--ruby-sdks-folder=<path to the root directory of your azure-sdk-for-ruby clone>`.

``` yaml $(tag) == 'package-2016-05' && $(ruby)
namespace: "Azure::DevTestLabs::Mgmt::V2016_05_15"
output-folder: $(ruby-sdks-folder)/management/azure_mgmt_devtestlabs/lib
```


text:
#import <iWorkImport/TSPObject.h>

#import "TSKModel-Protocol.h"
#import "TSSPreset-Protocol.h"
#import "TSSStyleClient-Protocol.h"

@class NSString, TSTTableStyleNetwork;

// Not exported
@interface TSTTableStylePreset : TSPObject <TSSPreset, TSSStyleClient, TSKModel>
{
    unsigned long long mIndex;
    TSTTableStyleNetwork *mStyleNetwork;
}

- (void)replaceReferencedStylesUsingBlock:(id)arg1;
- (id)referencedStyles;
- (void)saveToArchiver:(id)arg1;
- (void)saveToArchive:(struct TableStylePresetArchive *)arg1 archiver:(id)arg2;
- (id)initFromUnarchiver:(id)arg1;
- (void)drawSwatchInRect:(struct CGRect)arg1 inContext:(struct CGContext *)arg2;
- (id)styleNetworkInStylesheet:(id)arg1;
- (id)swatchImage;
@property(readonly, nonatomic) NSString *presetKind;
- (_Bool)isThemeEquivalent:(id)arg1;
- (unsigned long long)hash;
- (_Bool)isEqual:(id)arg1;
- (void)dealloc;
- (id)initWithContext:(id)arg1;
- (id)initWithStyleNetwork:(id)arg1 index:(unsigned long long)arg2;
- (id)p_documentRoot;
@property(copy, nonatomic) TSTTableStyleNetwork *styleNetwork;
@property(nonatomic) unsigned long long index;

@end


text:
#pragma once

#include "core/types.h"
#include "util/string.h"
#include "core/sysfunc.h"

//------------------------------------------------------------------------------
namespace Win32
{
class Win32Guid
{
public:
    /// override new operator
    void* operator new(size_t s);
    /// override delete operator
    void operator delete(void* ptr);

    /// constructor
    Win32Guid();
    /// copy constructor
    Win32Guid(const Win32Guid& rhs);
    /// construct from raw binary data as returned by AsBinary()
    Win32Guid(const unsigned char* ptr, SizeT size);
    /// assignement operator
    void operator=(const Win32Guid& rhs);
    /// assignment operator from string
    void operator=(const Util::String& rhs);
    /// equality operator
    bool operator==(const Win32Guid& rhs) const;
    /// inequlality operator
    bool operator!=(const Win32Guid& rhs) const;
    /// less-then operator
    bool operator<(const Win32Guid& rhs) const;
    /// less-or-equal operator
    bool operator<=(const Win32Guid& rhs) const;
    /// greater-then operator
    bool operator>(const Win32Guid& rhs) const;
    /// greater-or-equal operator
    bool operator>=(const Win32Guid& rhs) const;
    /// return true if the contained guid is valid (not NIL)
    bool IsValid() const;
    /// generate a new guid
    void Generate();
    /// construct from string representation
    static Win32Guid FromString(const Util::String& str);
    /// construct from binary representation
    static Win32Guid FromBinary(const unsigned char* ptr, SizeT numBytes);
    /// get as string
    Util::String AsString() const;
    /// get pointer to binary data
    SizeT AsBinary(const unsigned char*& outPtr) const;
    /// return the size of the binary representation in bytes
    static SizeT BinarySize();
    /// get a hash code (compatible with Util::HashTable)
    IndexT HashCode() const;

private:
    UUID uuid;
};

//------------------------------------------------------------------------------
/**
*/
__forceinline void*
Win32Guid::operator new(size_t size)
{
    #if NEBULA3_DEBUG
    n_assert(size == sizeof(Win32Guid));
    #endif

    #if NEBULA3_OBJECTS_USE_MEMORYPOOL
        return Memory::ObjectPoolAllocator->Alloc(size);
    #else
        return Memory::Alloc(Memory::ObjectHeap, size);
    #endif
}

//------------------------------------------------------------------------------
/**
*/
__forceinline void
Win32Guid::operator delete(void* ptr)
{
    #if NEBULA3_OBJECTS_USE_MEMORYPOOL
        return Memory::ObjectPoolAllocator->Free(ptr, sizeof(Win32Guid));
    #else
        return Memory::Free(Memory::ObjectHeap, ptr);
    #endif
}

//------------------------------------------------------------------------------
/**
*/
inline
Win32Guid::Win32Guid()
{
    Memory::Clear(&(this->uuid), sizeof(this->uuid));
}

//------------------------------------------------------------------------------
/**
*/
inline
Win32Guid::Win32Guid(const Win32Guid& rhs)
{
    this->uuid = rhs.uuid;
}

//------------------------------------------------------------------------------
/**
*/
inline
Win32Guid::Win32Guid(const unsigned char* ptr, SizeT size)
{
    n_assert((0 != ptr) && (size == sizeof(UUID)));
    Memory::Copy(ptr, &this->uuid, sizeof(UUID));
}

//------------------------------------------------------------------------------
/**
*/
inline SizeT
Win32Guid::BinarySize()
{
    return sizeof(UUID);
}

} // namespace Win32
//------------------------------------------------------------------------------