text:
package org.apache.asterix.metadata.entities;

import java.util.List;

import org.apache.asterix.common.config.DatasetConfig.IndexType;
import org.apache.asterix.common.exceptions.CompilationException;
import org.apache.asterix.common.exceptions.ErrorCode;
import org.apache.asterix.common.transactions.IRecoveryManager.ResourceType;
import org.apache.asterix.metadata.MetadataCache;
import org.apache.asterix.metadata.api.IMetadataEntity;
import org.apache.asterix.om.types.ARecordType;
import org.apache.asterix.om.types.AUnionType;
import org.apache.asterix.om.types.IAType;
import org.apache.asterix.om.utils.NonTaggedFormatUtil;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.common.utils.Pair;

/**
 * Metadata describing an index.
 */
public class Index implements IMetadataEntity<Index>, Comparable<Index> {

    private static final long serialVersionUID = 1L;
    public static final int RECORD_INDICATOR = 0;

    private final String dataverseName;
    // Enforced to be unique within a dataverse.
    private final String datasetName;
    // Enforced to be unique within a dataverse, dataset combination.
    private final String indexName;
    private final IndexType indexType;
    private final List<List<String>> keyFieldNames;
    private final List<Integer> keyFieldSourceIndicators;
    private final List<IAType> keyFieldTypes;
    private final boolean overrideKeyFieldTypes;
    private final boolean isEnforced;
    private final boolean isPrimaryIndex;
    // Specific to NGRAM indexes.
    private final int gramLength;
    // Type of pending operations with respect to atomic DDL operation
    private int pendingOp;

    public Index(String dataverseName, String datasetName, String indexName, IndexType indexType,
            List<List<String>> keyFieldNames, List<Integer> keyFieldSourceIndicators, List<IAType> keyFieldTypes,
            int gramLength, boolean overrideKeyFieldTypes, boolean isEnforced, boolean isPrimaryIndex, int pendingOp) {
        this.dataverseName = dataverseName;
        this.datasetName = datasetName;
        this.indexName = indexName;
        this.indexType = indexType;
        this.keyFieldNames = keyFieldNames;
        this.keyFieldSourceIndicators = keyFieldSourceIndicators;
        this.keyFieldTypes = keyFieldTypes;
        this.gramLength = gramLength;
        this.overrideKeyFieldTypes = overrideKeyFieldTypes;
        this.isEnforced = isEnforced;
        this.isPrimaryIndex = isPrimaryIndex;
        this.pendingOp = pendingOp;
    }

    public Index(String dataverseName, String datasetName, String indexName, IndexType indexType,
            List<List<String>> keyFieldNames, List<Integer> keyFieldSourceIndicators, List<IAType> keyFieldTypes,
            boolean overrideKeyFieldTypes, boolean isEnforced, boolean isPrimaryIndex, int pendingOp) {
        this(dataverseName, datasetName, indexName, indexType, keyFieldNames, keyFieldSourceIndicators, keyFieldTypes,
                -1, overrideKeyFieldTypes, isEnforced, isPrimaryIndex, pendingOp);
    }

    public String getDataverseName() {
        return dataverseName;
    }

    public String getDatasetName() {
        return datasetName;
    }

    public String getIndexName() {
        return indexName;
    }

    public List<List<String>> getKeyFieldNames() {
        return keyFieldNames;
    }

    public List<Integer> getKeyFieldSourceIndicators() {
        return keyFieldSourceIndicators;
    }

    public List<IAType> getKeyFieldTypes() {
        return keyFieldTypes;
    }

    public int getGramLength() {
        return gramLength;
    }

    public IndexType getIndexType() {
        return indexType;
    }

    public boolean isPrimaryIndex() {
        return isPrimaryIndex;
    }

    public boolean isOverridingKeyFieldTypes() {
        return overrideKeyFieldTypes;
    }

    public boolean isEnforced() {
        return isEnforced;
    }

    public int getPendingOp() {
        return pendingOp;
    }

    public void setPendingOp(int pendingOp) {
        this.pendingOp = pendingOp;
    }

    public boolean isSecondaryIndex() {
        return !isPrimaryIndex();
    }

    public static Pair<IAType, Boolean> getNonNullableType(IAType keyType) {
        boolean nullable = false;
        IAType actualKeyType = keyType;
        if (NonTaggedFormatUtil.isOptional(keyType)) {
            actualKeyType = ((AUnionType) keyType).getActualType();
            nullable = true;
        }
        return new Pair<>(actualKeyType, nullable);
    }

    public static Pair<IAType, Boolean> getNonNullableOpenFieldType(IAType fieldType, List<String> fieldName,
            ARecordType recType) throws AlgebricksException {
        Pair<IAType, Boolean> keyPairType = null;
        IAType subType = recType;
        for (int i = 0; i < fieldName.size(); i++) {
            subType = ((ARecordType) subType).getFieldType(fieldName.get(i));
            if (subType == null) {
                keyPairType = Index.getNonNullableType(fieldType);
                break;
            }
        }
        if (subType != null) {
            keyPairType = Index.getNonNullableKeyFieldType(fieldName, recType);
        }
        return keyPairType;
    }

    public static Pair<IAType, Boolean> getNonNullableKeyFieldType(List<String> expr, ARecordType recType)
            throws AlgebricksException {
        IAType keyType = Index.keyFieldType(expr, recType);
        return getNonNullableType(keyType);
    }

    private static IAType keyFieldType(List<String> expr, ARecordType recType) throws AlgebricksException {
        IAType fieldType = recType;
        fieldType = recType.getSubFieldType(expr);
        return fieldType;
    }

    @Override
    public int hashCode() {
        return indexName.hashCode() ^ datasetName.hashCode() ^ dataverseName.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof Index)) {
            return false;
        }
        Index otherIndex = (Index) other;
        if (!indexName.equals(otherIndex.getIndexName())) {
            return false;
        }
        if (!datasetName.equals(otherIndex.getDatasetName())) {
            return false;
        }
        if (!dataverseName.equals(otherIndex.getDataverseName())) {
            return false;
        }
        return true;
    }

    @Override
    public Index addToCache(MetadataCache cache) {
        return cache.addIndexIfNotExists(this);
    }

    @Override
    public Index dropFromCache(MetadataCache cache) {
        return cache.dropIndex(this);
    }

    @Override
    public int compareTo(Index otherIndex) {
        /** Gives a primary index first priority. */
        if (isPrimaryIndex && !otherIndex.isPrimaryIndex) {
            return -1;
        }
        if (!isPrimaryIndex && otherIndex.isPrimaryIndex) {
            return 1;
        }

        /** Gives a B-Tree index the second priority. */
        if (indexType == IndexType.BTREE && otherIndex.indexType != IndexType.BTREE) {
            return -1;
        }
        if (indexType != IndexType.BTREE && otherIndex.indexType == IndexType.BTREE) {
            return 1;
        }

        /** Gives a R-Tree index the third priority */
        if (indexType == IndexType.RTREE && otherIndex.indexType != IndexType.RTREE) {
            return -1;
        }
        if (indexType != IndexType.RTREE && otherIndex.indexType == IndexType.RTREE) {
            return 1;
        }

        /** Finally, compares based on names. */
        int result = indexName.compareTo(otherIndex.getIndexName());
        if (result != 0) {
            return result;
        }
        result = datasetName.compareTo(otherIndex.getDatasetName());
        if (result != 0) {
            return result;
        }
        return dataverseName.compareTo(otherIndex.getDataverseName());
    }

    public boolean hasMetaFields() {
        if (keyFieldSourceIndicators != null) {
            for (Integer indicator : keyFieldSourceIndicators) {
                if (indicator.intValue() != 0) {
                    return true;
                }
            }
        }
        return false;
    }

    public byte resourceType() throws CompilationException {
        switch (indexType) {
            case BTREE:
                return ResourceType.LSM_BTREE;
            case RTREE:
                return ResourceType.LSM_RTREE;
            case LENGTH_PARTITIONED_NGRAM_INVIX:
            case LENGTH_PARTITIONED_WORD_INVIX:
            case SINGLE_PARTITION_NGRAM_INVIX:
            case SINGLE_PARTITION_WORD_INVIX:
                return ResourceType.LSM_INVERTED_INDEX;
            default:
                throw new CompilationException(ErrorCode.COMPILATION_UNKNOWN_INDEX_TYPE, indexType);
        }
    }
}


text:
import {Validate} from '~/src/util/Validate'
import {InputDefinition} from './InputDefinition'

export class InputDefinitionBuilder {

  constructor() {
    this.side = 'left'
    this.ratio = 0.5
  }

  build() {
    return new InputDefinition(this.nameVal, this.validatorVal, this.side, this.ratio)
  }

  name(nameVal) {
    Validate.notBlank(nameVal)

    this.nameVal = nameVal
  }

  validate(validatorVal) {
    Validate.isFunctionWithArity(validatorVal, 1)

    this.validatorVal = validatorVal
  }

  position(side, ratio) {
    Validate.oneOf(side, ['top', 'left', 'bottom', 'right'])
    Validate.numberInRangeIncl(ratio, 0.0, 1.0)

    this.side = side
    this.ratio = ratio
  }
}

redpajama_set_name: RedPajamaGithub


text:
/*!
 *  Copyright (c) 2017 by Contributors
 * \file quantization_utils-inl.h
 */
#ifndef MXNET_OPERATOR_QUANTIZATION_QUANTIZATION_UTILS_H_
#define MXNET_OPERATOR_QUANTIZATION_QUANTIZATION_UTILS_H_

#include <mxnet/base.h>
#include <algorithm>
#include "../mxnet_op.h"
#include "../tensor/broadcast_reduce_op.h"

namespace mxnet {
namespace op {

using mshadow::red::limits::MaxValue;
using mshadow::red::limits::MinValue;

static const float kUint8Range = 255.5;
static const float kInt8Range = 127.5;
static const size_t kInt32Range = 0x7fffffff;

template<typename T>
MSHADOW_XINLINE int Sign(T val) {
  return (val > T(0)) - (val < T(0));
}

template<typename T>
MSHADOW_XINLINE T Abs(T a) {
#ifdef __CUDACC__
  return ::abs(a);
#else
  return std::abs(a);
#endif
}

template<typename T>
MSHADOW_XINLINE T Max(T a, T b) {
#ifdef __CUDACC__
  return ::max(a, b);
#else
  return std::max(a, b);
#endif
}

template<typename T>
MSHADOW_XINLINE T Min(T a, T b) {
#ifdef __CUDACC__
  return ::min(a, b);
#else
  return std::min(a, b);
#endif
}

template<typename T>
MSHADOW_XINLINE float MaxAbs(T a, T b) {
  return Max(Abs(static_cast<float>(a)), Abs(static_cast<float>(b)));
}

template<typename T>
MSHADOW_XINLINE float MinAbs(T a, T b) {
  return Min(Abs(static_cast<float>(a)), Abs(static_cast<float>(b)));
}

template<typename T>
MSHADOW_XINLINE T FloatToQuantized(float input, float min_range, float max_range) {
  float real_range = MaxAbs(min_range, max_range);
  float quantized_range = MinAbs(MaxValue<T>(), MinValue<T>());
  float scale = quantized_range / real_range;
  return Sign(input) * Min(Abs(input) * scale + 0.5f, quantized_range);
}

template <typename T>
MSHADOW_XINLINE float QuantizedToFloat(T input, float min_range, float max_range) {
  float quantized_range = MinAbs(MinValue<T>(), MaxValue<T>());
  float real_range = MaxAbs(min_range, max_range);
  float scale = real_range / quantized_range;
  return input * scale;
}

struct QuantizedToFloatStruct {
  template<typename T>
  MSHADOW_XINLINE static void Map(int i, float *output, const T *input,
                                  const float *range_min, const float *range_max) {
    output[i] = QuantizedToFloat(input[i], *range_min, *range_max);
  }
};

template <class T1, class T2>
MSHADOW_XINLINE T2 RequantizeInNewRange(T1 input, float min_input, float max_input,
                                        float min_new, float max_new) {
  const float input_float = QuantizedToFloat<T1>(input, min_input, max_input);
  return FloatToQuantized<T2>(input_float, min_new, max_new);
}

template <class T1, class T2>
MSHADOW_XINLINE void RequantizeManyInNewRange(size_t count, T2* output, const T1 *input,
                                              float input_min, float input_max,
                                              float actual_min, float actual_max) {
  for (size_t i = 0; i < count; ++i) {
    const float input_float =
        QuantizedToFloat<T1>(input[i], input_min, input_max);
    output[i] = FloatToQuantized<T2>(input_float, actual_min, actual_max);
  }
}

/*!
 * \brief Get the scaling factor for converting type T to float.
 */
template<typename T>
MSHADOW_XINLINE float FloatForOneQuantizedLevel(float range_min, float range_max, bool all_sign) {
  float range_data = MaxAbs(range_min, range_max);
  float range_T = all_sign ? MinAbs(MinValue<T>(), MaxValue<T>()) : MaxValue<T>();
  return range_data / range_T;
}

template <typename TA, typename TB, typename TC>
MSHADOW_XINLINE void QuantizationRangeForMultiplication(float min_a, float max_a, float min_b,
                                                        float max_b, float *min_c, float *max_c,
                                                        bool all_sign) {
  const float a_float_for_one_quant_level = FloatForOneQuantizedLevel<TA>(min_a, max_a, all_sign);
  const float b_float_for_one_quant_level = FloatForOneQuantizedLevel<TB>(min_b, max_b, all_sign);
  const float range_c =
      MinAbs(static_cast<int64_t>(MinValue<TC>()), static_cast<int64_t>(MaxValue<TC>()));
  const float c_float_for_one_quant_level =
      a_float_for_one_quant_level * b_float_for_one_quant_level;
  *max_c = c_float_for_one_quant_level * range_c;
  *min_c = -*max_c;
}

struct QuantizationRangeForS8S8MultiplicationStruct {
  MSHADOW_XINLINE static void Map(int i,
                                  float *min_c,
                                  float *max_c,
                                  const float *min_a,
                                  const float *max_a,
                                  const float *min_b,
                                  const float *max_b) {
  QuantizationRangeForMultiplication<int8_t, int8_t, int32_t>(
    min_a[i], max_a[i], min_b[i], max_b[i], min_c, max_c, true);
  }
};

struct QuantizationRangeForS8U8MultiplicationStruct {
  MSHADOW_XINLINE static void Map(int i,
                                  float *min_c,
                                  float *max_c,
                                  const float *min_a,
                                  const float *max_a,
                                  const float *min_b,
                                  const float *max_b) {
  QuantizationRangeForMultiplication<int8_t, uint8_t, int32_t>(
    min_a[i], max_a[i], min_b[i], max_b[i], min_c, max_c, false);
  }
};

template<typename xpu, typename DType>
inline size_t ConfigReduce(mshadow::Stream<xpu>* s,
                           const mxnet::TShape& data_shape,
                           const mxnet::TShape& out_shape,
                           mxnet::TShape* src_shape,
                           mxnet::TShape* dst_shape) {
  BroadcastReduceShapeCompact(data_shape, out_shape, src_shape, dst_shape);
  constexpr int NDim = 2;
  CHECK_EQ(src_shape->ndim(), NDim);
  CHECK_EQ(dst_shape->ndim(), NDim);

  return broadcast::ReduceWorkspaceSize(s, *dst_shape, kWriteTo, *src_shape, sizeof(DType));
}

enum QuantizeOutType { kAuto = 0, kInt8, kUint8 };

template<typename Param>
static mshadow::TypeFlag GetQuantizeOutputType(const Param &param) {
  auto out_type = mshadow::kInt8;
  if (param.out_type == QuantizeOutType::kAuto) {
    if (param.min_calib_range.has_value() && param.max_calib_range.has_value()) {
      if (param.min_calib_range.value() >= 0.0) {
        out_type = mshadow::kUint8;
      } else {
        out_type = mshadow::kInt8;
      }
    }
  } else if (param.out_type == QuantizeOutType::kInt8) {
    out_type = mshadow::kInt8;
  } else if (param.out_type == QuantizeOutType::kUint8) {
    out_type = mshadow::kUint8;
  } else {
    LOG(FATAL) << "Unsupported out_type in params: " <<param.out_type;
  }
  return out_type;
}

static inline float GetQuantizeScale(const int dtype, const float data_min, const float data_max) {
  const float real_data_range = MaxAbs(data_min, data_max);
  const auto quantized_data_range = (dtype == mshadow::kInt8) ? kInt8Range : kUint8Range;
  // If real_data_range == 0, to avoid `inf` in scale, use a large number here, which is MAX_INT.
  return real_data_range ? quantized_data_range / real_data_range : MaxValue<int32_t>();
}

}  // namespace op
}  // namespace mxnet
#endif  // MXNET_OPERATOR_QUANTIZATION_QUANTIZATION_UTILS_H_


text:
<?php

namespace Pum\Bundle\TypeExtraBundle\Tests\Type;
use Pum\Bundle\TypeExtraBundle\Model\Coordinate;

class CoordinateTest extends \PHPUnit_Framework_TestCase
{
    public function testInterface()
    {
        $coordinate = new Coordinate('48.853', '2.35');
        $this->assertEquals('48.853', $coordinate->getLat());
        $this->assertEquals('2.35', $coordinate->getLng());

        $coordinate = Coordinate::createFromString('48.853,2.35');
        $this->assertEquals('48.853', $coordinate->getLat());
        $this->assertEquals('2.35', $coordinate->getLng());

        $coordinate = Coordinate::createFromString('48.853,2.35')
            ->setLat('25.39')
            ->setLng('7.246')
        ;
        $this->assertEquals('25.39', $coordinate->getLat());
        $this->assertEquals('7.246', $coordinate->getLng());

        $coordinate = new Coordinate('48.853', '2.35');
        $this->assertEquals('48.853,2.35', $coordinate);
    }
}


text:
module FindHelper
  def search_results_suffix(type)
    return " (nationwide)" if @session[only_local_session_key(type)] == 'false'
    return " (near #{session[:location]})"
  end

  def show_prefix_browse
    out = "
"

    if params[:prefix].blank?
      out << "All"
    else
      out << link_to("All", :action => params[:action])
    end

    out << " "

    for letter in 'A'..'Z'
      current = params[:prefix] && params[:prefix].downcase == letter.downcase
      if current
        out << "#{letter}"
      else
        out << link_to(letter, :action => params[:action], :prefix => letter.downcase)
      end

    end

    out << "
"
    out
  end
end


text:
package org.apache.geode.internal.datasource;

import static org.apache.geode.distributed.ConfigurationProperties.*;
import static org.junit.Assert.*;

import java.sql.Connection;
import java.util.Properties;
import javax.naming.Context;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.apache.geode.util.test.TestUtil;

@Category(IntegrationTest.class)
public class DataSourceFactoryJUnitTest {

  private static Properties props = null;
  private static DistributedSystem ds1 = null;
  private static Cache cache = null;

  @Before
  public void setUp() {
    props = new Properties();
    props.setProperty(MCAST_PORT, "0");
    String path = TestUtil.getResourcePath(DataSourceFactoryJUnitTest.class, "/jta/cachejta.xml");
    props.setProperty(CACHE_XML_FILE, path);
    ds1 = DistributedSystem.connect(props);
    cache = CacheFactory.create(ds1);
  }

  @After
  public void tearDown() {
    ds1.disconnect();
  }

  @Test
  public void testGetSimpleDataSource() throws Exception {
    Context ctx = cache.getJNDIContext();
    GemFireBasicDataSource ds = (GemFireBasicDataSource) ctx.lookup("java:/SimpleDataSource");
    Connection conn = ds.getConnection();
    if (conn == null)
      fail(
          "DataSourceFactoryJUnitTest-testGetSimpleDataSource() Error in creating the GemFireBasicDataSource");
  }

  @Test
  public void testGetPooledDataSource() throws Exception {
    Context ctx = cache.getJNDIContext();
    GemFireConnPooledDataSource ds =
        (GemFireConnPooledDataSource) ctx.lookup("java:/PooledDataSource");
    Connection conn = ds.getConnection();
    if (conn == null)
      fail(
          "DataSourceFactoryJUnitTest-testGetPooledDataSource() Error in creating the GemFireConnPooledDataSource");
  }

  @Test
  public void testGetTranxDataSource() throws Exception {
    Context ctx = cache.getJNDIContext();
    GemFireTransactionDataSource ds =
        (GemFireTransactionDataSource) ctx.lookup("java:/XAPooledDataSource");
    // DataSourceFactory dsf = new DataSourceFactory();
    // GemFireTransactionDataSource ds =
    // (GemFireTransactionDataSource)dsf.getTranxDataSource(map);
    Connection conn = ds.getConnection();
    if (conn == null)
      fail(
          "DataSourceFactoryJUnitTest-testGetTranxDataSource() Error in creating the getTranxDataSource");
  }
}


text:
package gov.nih.nci.caintegrator.application.arraydata;

import java.io.File;

/**
 * Used to load Affymetrix array designs.
 */
public class AffymetrixExpressionPlatformSource extends AbstractPlatformSource {

    private static final long serialVersionUID = 1L;

    /**
     * Creates a new instance.
     *
     * @param annotationFile the CSV annotation file.
     */
    public AffymetrixExpressionPlatformSource(File annotationFile) {
        super(annotationFile);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public AbstractPlatformLoader getLoader() throws PlatformLoadingException {
        return new AffymetrixExpressionPlatformLoader(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return "Affymetrix CSV annotation file: " + getAnnotationFileNames();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getPlatformName() throws PlatformLoadingException {
        return getLoader().getPlatformName();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public PlatformTypeEnum getPlatformType() {
        return PlatformTypeEnum.AFFYMETRIX_GENE_EXPRESSION;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public PlatformChannelTypeEnum getPlatformChannelType() {
        return PlatformChannelTypeEnum.ONE_COLOR;
    }

}


text:
layout: post
title: "Mark Jaquith at WordCamp London - Cache Money Business"
date: 2015-03-22 11:31:06 +0000
comments: true
category: liveblog
tags: [caching, wordpress, "wordcamp london"]
---

_I'm at [WordCamp London](http://london.wordcamp.org/2015/) - live-blogging
some of the talks_

![Mark Jaquith talking caching at #wcldn - photo by @davepullig on
twitter](https://pbs.twimg.com/media/CAs0AgdWEAApTMb.jpg)

_photo of [Mark Jaquith](https://twitter.com/markjaquith) by [Dave Pullig](https://twitter.com/davepullig/)_

* Ultimately failing to cache could take your site down: run out of connections
* Caching principles:
    * Do less work - By default WP is Totally dynamic - there's a lot of
      complex stuff going on and it all gets done on every single request
    * Hold onto data as long as it makes sense to do so: this is very specific
      to each individual site (at least for certain kinds of content)
    * Make output generic: the more specific it is to a particular user, the
      less cachable it is
* Page caching:
    * Batcache - if a page gets requested more than 3 times in 3 mins it
      caches that whole page for 6 mins
    * Used by WP.com
    * Unobtrusive - only caches the most frequently requested stuff
    * low-configuration
* W3TotalCache
    * Extremely complex, lots of layers
* WPSuperCache
    * Somewhere in-between
* Varnish or Nginx
    * Cache before it hits the webserver
* CDN
    * geographically distributed caches: people access the cache closest to
      them
    * Very popular for media files, but can be used for the whole site.
    * Will obey cache headers
* Nginx Cache Purging
    * This is tricky
    * There's a third party package which can be compiled from source which
      enables this. But :-P
    * Approach: Configure a 'magic header' ;) - when it's passed with a
      request, it skips getting, but not setting, so overwrites whatever is
      currently in the cache
* Variable cache lengths + proactive cache refreshing:
    * Warm the cache (on cron) more frequently than it's getting expired, to
      make sure that your content is always cached
* Does being logged-in mean you can't cache the page?
    * It's a pain if you have 1000's of logged in users/active commenters etc.
    * Think about how the page varies based on who you are logged in as:
      toolbar, private posts - etc.
    * Choice: remove those things OR make them generic
    * Comment forms: hide them by default, show them with ajax - either when
      hitting a button, or when scrolling to the bottom of the page (!)
    * Remove toolbar for subscribers etc. - it's not very useful!
    * Remove private post fucntionality if it's not used: it makes the queries
      much more complicated anyway
    * Replace moderated comments with a generic "your comment is being
      moderated" message
* Approach if you really need to show logged-in data:
    * Use cookies: by default WP renders user-specific content using php, but
      that's very odd
    * Set JS-readable cookies and use them to populate the content
    * He's just written [Cache Buddy](https://github.com/markjaquith/cache-buddy) - a plugin to do this
* Object Caching
    * APCu, Memcache, or (recommended:) Redis
    * put them in `object-cache.php` - they need to be loaded before plugins
* Transients + Object Cache
    * For just a few values use transients - stores data in the options table
    * For 1000s of values use the object cache
    * Object cache can organise cache keys into groups
* Cache stampedes: What happens when cache expires?
    * One user triggers the remote request
    * then the next user also triggers it (before it's completed)
    * and another... STAMPEDE!
    * `tlc_transient` - handles this problem: soft expiration - data gets
      marked as expired but not deleted until the new data is available (!)
* Html fragment caching
    * e.g. A complex footer that's the same on every page
    * `CWS_Fragment_Cache`


text:
package io.quarkus.resteasy.reactive.server.test.resource.basic.resource;

import java.net.URI;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

import org.jboss.logging.Logger;
import org.junit.jupiter.api.Assertions;

import io.quarkus.resteasy.reactive.server.test.simple.PortProviderUtil;

@Path("UriInfoSimpleSingletonResource")
public class UriInfoSimpleSingletonResource {
    private static Logger LOG = Logger.getLogger(UriInfoSimpleSingletonResource.class);

    @Context
    UriInfo myInfo;

    @Path("/simple")
    @GET
    public String get(@Context UriInfo info, @QueryParam("abs") String abs) {
        LOG.debug("abs query: " + abs);
        URI base = null;
        if (abs == null) {
            base = PortProviderUtil.createURI("/");
        } else {
            base = PortProviderUtil.createURI("/" + abs + "/");
        }

        LOG.debug("BASE URI: " + info.getBaseUri());
        LOG.debug("Request URI: " + info.getRequestUri());
        Assertions.assertEquals(base.getPath(), info.getBaseUri().getPath());
        Assertions.assertEquals("/simple", info.getPath());
        return "CONTENT";
    }

    @Path("/simple/fromField")
    @GET
    public String get(@QueryParam("abs") String abs) {
        LOG.debug("abs query: " + abs);
        URI base = null;
        if (abs == null) {
            base = PortProviderUtil.createURI("/");
        } else {
            base = PortProviderUtil.createURI("/" + abs + "/");
        }

        LOG.debug("BASE URI: " + myInfo.getBaseUri());
        LOG.debug("Request URI: " + myInfo.getRequestUri());
        Assertions.assertEquals(base.getPath(), myInfo.getBaseUri().getPath());
        Assertions.assertEquals("/simple/fromField", myInfo.getPath());
        return "CONTENT";
    }

}


text:
var execSync = require('child_process').execSync;
var fs = require('fs');
var temp = require('temp-fs');
var path = require('path');
var JSONB = require('json-buffer');

module.exports = function (filePath, args) {

	if (args === undefined) {
		args = [];
	}

	if (typeof args !== 'object' || args.length === undefined) {
		throw new Error('Arguments should be an array.');
	}

	var content = null;
	var result = null;
	var error = false;

	var inputFile = temp.name();
	var outputFile = temp.name();

	try {

		// Prepare
		fs.writeFileSync(inputFile, JSONB.stringify(args), {encoding: 'utf8'});
		var workerPath = path.join(__dirname, 'lib', 'worker.js');

		// Execute synchronously
		execSync('node "' + workerPath + '" "' + filePath + '" "' + inputFile + '" "' + outputFile + '"').toString();

	} catch (err) {
		error = true;

	} finally {

		if (fs.existsSync(inputFile)) {
			content = fs.readFileSync(outputFile, {encoding: 'utf8'});
		}
		result = JSONB.parse(content);

		if (fs.existsSync(inputFile)) {
			fs.unlinkSync(inputFile);
		}
		if (fs.existsSync(outputFile)) {
			fs.unlinkSync(outputFile);
		}
	}

	if (error) {
		throw result;
	}

	return result;
};


text:
{% include html_start.html %}

  <body{% if page.body-class %} class="{{ page.body-class }}"{% endif %}{% if page.prettyprint == true %} onload="prettyPrint()"{% endif %}>

    <!--  === MASTHEAD ===  -->
    {% include masthead.html %}

    <!--  === MAIN CONTENT ===  -->
    <section class="g-container" role="main">
      {{ content }}

      {% include footer.html %}
    </section>

{% include html_end.html %}


text:
<?php

class Scalr_UI_Controller_Tools_Aws_Rds_Pg extends Scalr_UI_Controller
{
	public function viewAction()
	{
		$this->response->page('ui/tools/aws/rds/pg/view.js', array(
			'locations'	=> self::loadController('Platforms')->getCloudLocations(SERVER_PLATFORMS::EC2, false)
		));
	}

	public function xListAction()
	{
		$amazonRDSClient = Scalr_Service_Cloud_Aws::newRds(
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY),
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY),
			$this->getParam('cloudLocation')
		);

		// Rows
		$dbParameterGroups = $amazonRDSClient->DescribeDBParameterGroups();
		$groups = (array) $dbParameterGroups->DescribeDBParameterGroupsResult->DBParameterGroups;
		$groups = $groups['DBParameterGroup'];

		if ($groups) {
			if (!is_array($groups))
				$groups = array($groups);
		}

		$response = $this->buildResponseFromData($groups, array('DBParameterGroupDescription', 'DBParameterGroupName'));

		$this->response->data($response);
	}

	public function xCreateAction()
	{
		$amazonRDSClient = Scalr_Service_Cloud_Aws::newRds(
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY),
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY),
			$this->getParam('cloudLocation')
		);

		$amazonRDSClient->CreateDBParameterGroup($this->getParam('dbParameterGroupName'), $this->getParam('Description'), $this->getParam('Engine'));

		$this->response->success("DB parameter group successfully created");
	}

	public function xDeleteAction()
	{
		$amazonRDSClient = Scalr_Service_Cloud_Aws::newRds(
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY),
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY),
			$this->getParam('cloudLocation')
		);

		$amazonRDSClient->DeleteDBParameterGroup($this->getParam('name'));
		$this->response->success("DB parameter group successfully removed");
	}

	public function editAction()
	{
		$amazonRDSClient = Scalr_Service_Cloud_Aws::newRds(
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY),
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY),
			$this->getParam('cloudLocation')
		);

		$response = $amazonRDSClient->DescribeDBParameters($this->getParam('name'));
		$result = json_decode(json_encode($response->DescribeDBParametersResult->Parameters), true);
		$params = $result['Parameter'];
		$dbParameterGroups = $amazonRDSClient->DescribeDBParameterGroups($this->getParam('name'));
		$groups = (array) $dbParameterGroups->DescribeDBParameterGroupsResult->DBParameterGroups;
		$groups = $groups['DBParameterGroup'];

		$items = array();
		foreach ($params as $key => $value) {
			$itemField = new stdClass();
			if(strpos($value['AllowedValues'], ',') && $value['DataType'] != 'boolean')
			{
					$store = explode(',', $value['AllowedValues']);
					$itemField->xtype = 'combo';
					$itemField->allowBlank = true;
					$itemField->editable = false;
					$itemField->queryMode = 'local';
					$itemField->displayField = 'name';
					$itemField->valueField = 'name';
					$itemField->store = $store;
			}
			else if($value['DataType'] == 'boolean')
			{
				$itemField->xtype = 'checkbox';
				$itemField->inputValue = 1;
				$itemField->checked = ($value['ParameterValue'] == 1);
			}
			else {
				if($value['IsModifiable'] == "false")
					$itemField->xtype = 'displayfield';
				else
					$itemField->xtype = 'textfield';
			}
			$itemField->name = $value['Source'] . '[' . $value['ParameterName'] . ']';
			$itemField->fieldLabel = $value['ParameterName'];
			$itemField->value = $value['ParameterValue'];
			$itemField->labelWidth = 250;
			$itemField->width = 790;
			$itemField->readOnly = ($value['IsModifiable'] == "false" && $itemField->xtype != 'displayfield') ? true : false;

			$itemDesc = new stdClass();
			$itemDesc->xtype = 'displayinfofield';
			$itemDesc->width = 16;
			$itemDesc->margin = '0 0 0 5';
			$itemDesc->info = $value['Description'];

			$item = new stdClass();
			$item->xtype = 'fieldcontainer';
			$item->layout = 'hbox';
			$item->items = array(
				$itemField,
				$itemDesc
			);

			$items[$value['Source']][] = $item;
		}
		$this->response->page('ui/tools/aws/rds/pg/edit.js', array('params' => $items, 'group' => $groups));
	}

	public function xSaveAction()
	{
		$amazonRDSClient = Scalr_Service_Cloud_Aws::newRds(
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY),
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY),
			$this->getParam('cloudLocation')
		);

		$response = $amazonRDSClient->DescribeDBParameters($this->getParam('name'));
		$result = json_decode(json_encode($response->DescribeDBParametersResult->Parameters), true);
		$params = $result['Parameter'];

		$modifiedParameters = new ParametersList();
		$newParams = array();

		foreach($this->getParam('system') as $system=>$f) {
			$newParams[] = array(
					'ParameterName' => $system,
					'ParameterValue' => $f
			);
		}
		foreach($this->getParam('engine-default') as $default=>$f) {
			$newParams[] = array(
					'ParameterName' => $default,
					'ParameterValue' => $f
			);
		}
		foreach($this->getParam('user') as $user=>$f) {
			$newParams[] = array(
					'ParameterName' => $user,
					'ParameterValue' => $f
			);
		}
		foreach ($newParams as $newParam){
			foreach($params as $param) {
				if($param['ParameterName'] == $newParam['ParameterName']){
					if(
						(empty($param['ParameterValue']) && !empty($newParam['ParameterValue'])) ||
						(!empty($param['ParameterValue']) && empty($newParam['ParameterValue'])) ||
						($newParam['ParameterValue'] !== $param['ParameterValue'] && !empty($newParam['ParameterValue']) && !empty($param['ParameterValue']))
					){
						if($param['ApplyType'] == 'static')
							$modifiedParameters->AddParameters($newParam['ParameterName'],$newParam['ParameterValue'],"pending-reboot");
						else
							$modifiedParameters->AddParameters($newParam['ParameterName'],$newParam['ParameterValue'],"immediate");
					}
				}
			}
		}
		$oldBoolean = array();
		foreach ($params as $param) {
			if($param['DataType'] == 'boolean' && $param['ParameterValue'] == 1){
				$type = '';
				if($param['ApplyType'] == 'static')
					$type = "pending-reboot";
				else
					$type = "immediate";
				$oldBoolean[] = array(
						'ParameterName' => $param['ParameterName'],
						'ParameterValue' => $param['ParameterValue'],
						'ApplyType' => $type
				);
			}
		}
		foreach ($oldBoolean as $old){
			$found = false;
			foreach ($newParams as $newParam){
				if($old['ParameterName'] == $newParam['ParameterName'])
					$found = true;
			}
			if(!$found){
				$modifiedParameters->AddParameters($old['ParameterName'], 0, $old['ApplyType']);
			}
		}
		//$this->response->data( array('oldboolean' => $oldBoolean));
		$amazonRDSClient->ModifyDBParameterGroup($this->getParam('name'),$modifiedParameters);
		$this->response->success("DB parameter group successfully updated");
	}

	public function xResetAction()
	{
		$amazonRDSClient = Scalr_Service_Cloud_Aws::newRds(
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::ACCESS_KEY),
			$this->getEnvironment()->getPlatformConfigValue(Modules_Platforms_Ec2::SECRET_KEY),
			$this->getParam('cloudLocation')
		);

		$response = $amazonRDSClient->DescribeDBParameters($this->getParam('name'));
		$result = json_decode(json_encode($response->DescribeDBParametersResult->Parameters), true);
		$params = $result['Parameter'];

		$modifiedParameters = new ParametersList();
		foreach ($params as $param){
			if($param['ParameterValue'] && !empty($param['ParameterValue'])){
				if($param['ApplyType'] == 'static')
					$modifiedParameters->AddParameters($param['ParameterName'], $param['ParameterValue'], "pending-reboot");
				else
					$modifiedParameters->AddParameters($param['ParameterName'], $param['ParameterValue'], "immediate");
			}
		}
		$amazonRDSClient->ResetDBParameterGroup($this->getParam('name'), $modifiedParameters);
		$this->response->success("DB parameter group successfully reset to default");
	}
}


text:
import itertools

def _sanitize(q):
    return q.replace('[', '_').replace(']', '')

def generate(api_items, duplicate_api_items, dupe_info):
    content = ''

    if dupe_info:
        content += dupe_info

    for name in sorted(list(api_items.keys())):
        item = api_items[name]

        # Sorting the parameters alphabetically should prevent needless differences
        # when small changes are made in different locations, so the order will be
        # the same regardless as to which parameter is found first.
        item['opt_path_params'].sort()
        item['query_params'].sort()

        path_fmt_args = ', '.join([p + '=' + p for p in item['path_params']])

        argspec = ', '.join(item['path_params'])

        if item['method']:
            if item['method'] in ['POST', 'PUT']:
                if argspec:
                    argspec += ', '
                argspec += 'data'
        else:
            if argspec:
                argspec = 'method, ' + argspec + ', data=None'
            else:
                argspec = 'method, data=None'

        if item['opt_path_params']:
            if argspec:
                argspec += ', '
            argspec += '=None, '.join(item['opt_path_params']) + '=None'

        if item['query_params']:
            if argspec:
                argspec += ', '
            argspec += '=None, '.join(
                [_sanitize(q) for q in item['query_params']]) + '=None'

        if argspec:
            argspec += ', '
        argspec += '**kwargs'

        content += '    def {}(self, {}):\n'.format(name, argspec)
        content += '        "{}"\n'.format(item['docpage'])
        content += '        api_path = "{}"\n'.format(item['path'])

        if item['path_params']:
            content += '        api_path = api_path.format({})\n'.format(
                path_fmt_args)

        if item['opt_path']:
            opt_test = ' and '.join(item['opt_path_params'])
            if path_fmt_args:
                path_fmt_args += ', '
            path_fmt_args = path_fmt_args + \
                ', '.join([p + '=' + p for p in item['opt_path_params']])
            content += '        if {}:\n'.format(opt_test)
            content += '            api_opt_path = "{}"\n'.format(item['opt_path'])
            content += '            api_path = api_opt_path.format({})\n'.format(
                path_fmt_args)

        if item['query_params']:
            content += '        api_query = {}\n'
            content += '        if "query" in kwargs.keys():\n'
            content += '            api_query.update(kwargs["query"])\n'
            content += '            del kwargs["query"]\n'

        for q in item['query_params']:
            content += '        if {}:\n'.format(_sanitize(q))
            content += '            api_query.update({\n'
            content += '                "{}": {},\n'.format(q, _sanitize(q))
            content += '            })\n'

        content += '        return self.call(api_path'

        if item['query_params']:
            content += ', query=api_query'

        if item['method']:
            if item['method'] != 'GET':
                content += ', method="{}"'.format(item['method'])

            if item['method'] in ['POST', 'PUT']:
                content += ', data=data'
        else:
            content += ', method=method, data=data'

        content += ', **kwargs)\n\n'

    return ('zdesk_api.py', content)


text:
package com.baidubce.services.bes.model;

import com.baidubce.model.AbstractBceResponse;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.io.Serializable;

public class BesUpdateAutoRenewRuleResponse extends AbstractBceResponse implements Serializable {
    @JsonProperty
    private Boolean success;
    @JsonProperty
    private int status;
    @JsonProperty
    private String result = " ";

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }
}


text:
function [ name ] = getFName( str )
%GETFNAME Summary of this function goes here
%   Detailed explanation goes here

[~,name,~] = fileparts(str);

end


text:
module Spree
  class FavoritesController < Spree::StoreController

    before_filter :find_favorite, only: [:destroy]

    def index
      if try_spree_current_user
        @favorites = spree_current_user.favorites.page(params[:page]).per(Spree::Config.favorites_per_page)
      elsif cookies.signed[:guest_token].present?
        @favorites = Favorite.by_guest_token(cookies.signed[:guest_token]).page(params[:page]).per(Spree::Config.favorites_per_page)
      else
        @favorites = []
      end
    end

    def create
      @favorable_id   = params[:favorable_id]
      @favorable_type = params[:favorable_type]

      if try_spree_current_user
        @favorite = try_spree_current_user.favorites.new favorable_id: @favorable_id, favorable_type: @favorable_type
      elsif cookies.signed[:guest_token].present?
        @favorite = Favorite.new favorable_id: @favorable_id, favorable_type: @favorable_type, guest_token: cookies.signed[:guest_token]
      else
        guest_token = loop do
          random_token = SecureRandom.urlsafe_base64(nil, false)
          break random_token unless Favorite.exists?(guest_token: random_token)
        end
        cookies.permanent.signed[:guest_token] = guest_token
        @favorite = Favorite.new favorable_id: @favorable_id, favorable_type: @favorable_type, guest_token: cookies.signed[:guest_token]
      end

      if @success = @favorite.save
        @message = Spree.t(:successfully_added_favorite)
      else
        @message = @favorite.errors.full_messages.to_sentence
      end

      respond_to do |format|
        format.js
      end
    end

    def destroy
      if @favorite
        @favorable_id   = @favorite.favorable_id
        @favorable_type = @favorite.favorable_type
        @success        = @favorite.destroy
      end
    end

    private

      def find_favorite
        if try_spree_current_user
          @favorite = try_spree_current_user.favorites.find(params[:id])
        else
          @favorite = Favorite.by_guest_token(cookies.signed[:guest_token]).find(params[:id])
        end
      end

  end
end


text:
/*!
 * \file
 */

#include "ixmldebug.h"
#include "ixmlmembuf.h"
#include "ixmlparser.h"

#include <stdlib.h> /* for free() */
#include <string.h>

/*!
 * \brief Appends a string to a buffer, substituting some characters by escape
 * sequences.
 */
static void copy_with_escape(
	/*! [in,out] The input/output buffer. */
	ixml_membuf *buf,
	/*! [in] The string to copy from. */
	const char *p)
{
	size_t i;
	size_t plen;

	if (p == NULL)
		return;
	plen = strlen(p);
	for (i = (size_t)0; i < plen; ++i) {
		switch (p[i]) {
		case '<':
			ixml_membuf_append_str(buf, "<");
			break;
		case '>':
			ixml_membuf_append_str(buf, ">");
			break;
		case '&':
			ixml_membuf_append_str(buf, "&");
			break;
		case '\'':
			ixml_membuf_append_str(buf, "'");
			break;
		case '\"':
			ixml_membuf_append_str(buf, """);
			break;
		default:
			ixml_membuf_append(buf, &p[i]);
			break;
		}
	}
}

/*!
 * \brief Recursive function to print all the node in a tree.
 * Internal to parser only.
 */
static void ixmlPrintDomTreeRecursive(
	/*! [in] \todo documentation. */
	IXML_Node *nodeptr,
	/*! [in] \todo documentation. */
	ixml_membuf *buf)
{
	const char *nodeName = NULL;
	const char *nodeValue = NULL;
	IXML_Node *child = NULL,
	*sibling = NULL;

	if (nodeptr != NULL) {
		nodeName = (const char *)ixmlNode_getNodeName(nodeptr);
		nodeValue = ixmlNode_getNodeValue(nodeptr);

		switch (ixmlNode_getNodeType(nodeptr)) {
		case eTEXT_NODE:
			copy_with_escape(buf, nodeValue);
			break;

		case eCDATA_SECTION_NODE:
			ixml_membuf_append_str(buf, "<![CDATA[");
			ixml_membuf_append_str(buf, nodeValue);
			ixml_membuf_append_str(buf, "]]>");
			break;

		case ePROCESSING_INSTRUCTION_NODE:
			ixml_membuf_append_str(buf, "<?");
			ixml_membuf_append_str(buf, nodeName);
			ixml_membuf_append_str(buf, " ");
			copy_with_escape(buf, nodeValue);
			ixml_membuf_append_str(buf, "?>\n");
			break;

		case eDOCUMENT_NODE:
			ixmlPrintDomTreeRecursive(
				ixmlNode_getFirstChild(nodeptr), buf);
			break;

		case eATTRIBUTE_NODE:
			ixml_membuf_append_str(buf, nodeName);
			ixml_membuf_append_str(buf, "=\"");
			copy_with_escape(buf, nodeValue);
			ixml_membuf_append_str(buf, "\"");
			if (nodeptr->nextSibling != NULL) {
				ixml_membuf_append_str(buf, " ");
				ixmlPrintDomTreeRecursive(nodeptr->nextSibling, buf);
			}
			break;

		case eELEMENT_NODE:
			ixml_membuf_append_str(buf, "<");
			ixml_membuf_append_str(buf, nodeName);
			if (nodeptr->firstAttr != NULL) {
				ixml_membuf_append_str(buf, " ");
				ixmlPrintDomTreeRecursive(nodeptr->firstAttr, buf);
			}
			child = ixmlNode_getFirstChild(nodeptr);
			if (child != NULL &&
			    ixmlNode_getNodeType(child) == eELEMENT_NODE) {
				ixml_membuf_append_str(buf, ">\r\n");
			} else {
				ixml_membuf_append_str(buf, ">");
			}
			/* output the children */
			ixmlPrintDomTreeRecursive(
				ixmlNode_getFirstChild(nodeptr), buf);

			/* Done with children.  Output the end tag. */
			ixml_membuf_append_str(buf, "</");
			ixml_membuf_append_str(buf, nodeName);

			sibling = ixmlNode_getNextSibling(nodeptr);
			if (sibling != NULL &&
			    ixmlNode_getNodeType(sibling) == eTEXT_NODE) {
				ixml_membuf_append_str( buf, ">" );
			} else {
				ixml_membuf_append_str( buf, ">\r\n" );
			}
			ixmlPrintDomTreeRecursive(
				ixmlNode_getNextSibling(nodeptr), buf);
			break;

		default:
			IxmlPrintf(__FILE__, __LINE__, "ixmlPrintDomTreeRecursive",
				"Warning, unknown node type %d\n",
				(int)ixmlNode_getNodeType(nodeptr));
			break;
		}
	}
}

/*!
 * \brief Print a DOM tree.
 *
 * Element, and Attribute nodes are handled differently. We don't want to print
 * the Element and Attribute nodes' sibling.
 */
static void ixmlPrintDomTree(
	/*! [in] \todo documentation. */
	IXML_Node *nodeptr,
	/*! [in] \todo documentation. */
	ixml_membuf *buf)
{
	const char *nodeName = NULL;
	const char *nodeValue = NULL;
	IXML_Node *child = NULL;

	if (nodeptr == NULL || buf == NULL) {
		return;
	}

	nodeName = (const char *)ixmlNode_getNodeName(nodeptr);
	nodeValue = ixmlNode_getNodeValue(nodeptr);
	switch (ixmlNode_getNodeType(nodeptr)) {
	case eTEXT_NODE:
	case eCDATA_SECTION_NODE:
	case ePROCESSING_INSTRUCTION_NODE:
	case eDOCUMENT_NODE:
		ixmlPrintDomTreeRecursive(nodeptr, buf);
		break;

	case eATTRIBUTE_NODE:
		ixml_membuf_append_str(buf, nodeName);
		ixml_membuf_append_str(buf, "=\"");
		copy_with_escape(buf, nodeValue);
		ixml_membuf_append_str(buf, "\"");
		break;

	case eELEMENT_NODE:
		ixml_membuf_append_str(buf, "<");
		ixml_membuf_append_str(buf, nodeName);
		if (nodeptr->firstAttr != NULL) {
			ixml_membuf_append_str(buf, " ");
			ixmlPrintDomTreeRecursive(nodeptr->firstAttr, buf);
		}
		child = ixmlNode_getFirstChild(nodeptr);
		if (child != NULL &&
		    ixmlNode_getNodeType(child) == eELEMENT_NODE) {
			ixml_membuf_append_str(buf, ">\r\n");
		} else {
			ixml_membuf_append_str(buf, ">");
		}

		/* output the children */
		ixmlPrintDomTreeRecursive(
			ixmlNode_getFirstChild(nodeptr), buf);

		/* Done with children. Output the end tag. */
		ixml_membuf_append_str(buf, "</");
		ixml_membuf_append_str(buf, nodeName);
		ixml_membuf_append_str(buf, ">\r\n");
		break;

	default:
		IxmlPrintf(__FILE__, __LINE__, "ixmlPrintDomTree",
			"Warning, unknown node type %d\n",
			(int)ixmlNode_getNodeType(nodeptr));
		break;
	}
}

/*!
 * \brief Converts a DOM tree into a text string.
 *
 * Element, and Attribute nodes are handled differently. We don't want to print
 * the Element and Attribute nodes' sibling.
 */
static void ixmlDomTreetoString(
	/*! [in] \todo documentation. */
	IXML_Node *nodeptr,
	/*! [in] \todo documentation. */
	ixml_membuf *buf)
{
	const char *nodeName = NULL;
	const char *nodeValue = NULL;
	IXML_Node *child = NULL;

	if (nodeptr == NULL || buf == NULL) {
		return;
	}

	nodeName = (const char *)ixmlNode_getNodeName(nodeptr);
	nodeValue = ixmlNode_getNodeValue(nodeptr);

	switch (ixmlNode_getNodeType(nodeptr)) {
	case eTEXT_NODE:
	case eCDATA_SECTION_NODE:
	case ePROCESSING_INSTRUCTION_NODE:
	case eDOCUMENT_NODE:
		ixmlPrintDomTreeRecursive(nodeptr, buf);
		break;

	case eATTRIBUTE_NODE:
		ixml_membuf_append_str(buf, nodeName);
		ixml_membuf_append_str(buf, "=\"");
		copy_with_escape(buf, nodeValue );
		ixml_membuf_append_str(buf, "\"");
		break;

	case eELEMENT_NODE:
		ixml_membuf_append_str(buf, "<");
		ixml_membuf_append_str(buf, nodeName);
		if (nodeptr->firstAttr != NULL) {
			ixml_membuf_append_str(buf, " ");
			ixmlPrintDomTreeRecursive(nodeptr->firstAttr, buf);
		}
		child = ixmlNode_getFirstChild(nodeptr);
		if (child != NULL &&
		    ixmlNode_getNodeType(child) == eELEMENT_NODE) {
			ixml_membuf_append_str(buf, ">");
		} else {
			ixml_membuf_append_str(buf, ">");
		}

		/* output the children */
		ixmlPrintDomTreeRecursive(ixmlNode_getFirstChild(nodeptr), buf);

		/* Done with children. Output the end tag. */
		ixml_membuf_append_str(buf, "</");
		ixml_membuf_append_str(buf, nodeName);
		ixml_membuf_append_str(buf, ">");
		break;

	default:
		IxmlPrintf(__FILE__, __LINE__, "ixmlPrintDomTreeRecursive",
			"Warning, unknown node type %d\n",
			(int)ixmlNode_getNodeType(nodeptr));
		break;
	}
}

int ixmlLoadDocumentEx(const char *xmlFile, IXML_Document **doc)
{
	if (xmlFile == NULL || doc == NULL) {
		return IXML_INVALID_PARAMETER;
	}

	return Parser_LoadDocument(doc, xmlFile, 1);
}

IXML_Document *ixmlLoadDocument(const char *xmlFile)
{
	IXML_Document *doc = NULL;

	ixmlLoadDocumentEx(xmlFile, &doc);

	return doc;
}

DOMString ixmlPrintDocument(IXML_Document *doc)
{
	IXML_Node* rootNode = (IXML_Node *)doc;
	ixml_membuf memBuf;
	ixml_membuf *buf = &memBuf;

	if(rootNode == NULL) {
		return NULL;
	}

	ixml_membuf_init(buf);
	ixml_membuf_append_str(buf, "<?xml version=\"1.0\"?>\r\n");
	ixmlPrintDomTree(rootNode, buf);

	return buf->buf;
}

DOMString ixmlPrintNode(IXML_Node *node)
{
	ixml_membuf memBuf;
	ixml_membuf *buf = &memBuf;

	if (node == NULL) {
		return NULL;
	}

	ixml_membuf_init(buf);
	ixmlPrintDomTree(node, buf);

	return buf->buf;
}

DOMString ixmlDocumenttoString(IXML_Document *doc)
{
	IXML_Node* rootNode = (IXML_Node *)doc;
	ixml_membuf memBuf;
	ixml_membuf *buf = &memBuf;

	if(rootNode == NULL) {
		return NULL;
	}

	ixml_membuf_init(buf);
	ixml_membuf_append_str(buf, "<?xml version=\"1.0\"?>\r\n");
	ixmlDomTreetoString(rootNode, buf);

	return buf->buf;
}

DOMString ixmlNodetoString(IXML_Node *node)
{
	ixml_membuf memBuf;
	ixml_membuf *buf = &memBuf;

	if (node == NULL) {
		return NULL;
	}

	ixml_membuf_init(buf);
	ixmlDomTreetoString(node, buf);

	return buf->buf;
}

void ixmlRelaxParser(char errorChar)
{
	Parser_setErrorChar(errorChar);
}

#ifdef IXML_HAVE_SCRIPTSUPPORT
void ixmlSetBeforeFree(IXML_BeforeFreeNode_t hndlr)
{
	Parser_setBeforeFree(hndlr);
}
#endif

int ixmlParseBufferEx(const char *buffer, IXML_Document **retDoc)
{
	if (buffer == NULL || retDoc == NULL) {
		return IXML_INVALID_PARAMETER;
	}

	if (buffer[0] == '\0') {
		return IXML_INVALID_PARAMETER;
	}

	return Parser_LoadDocument(retDoc, buffer, 0);
}

IXML_Document *ixmlParseBuffer(const char *buffer)
{
	IXML_Document *doc = NULL;

	ixmlParseBufferEx(buffer, &doc);

	return doc;
}

DOMString ixmlCloneDOMString(const DOMString src)
{
	if (src == NULL) {
		return NULL;
	}

	return strdup(src);
}

void ixmlFreeDOMString(DOMString buf)
{
	if (buf != NULL) {
		free(buf);
	}
}


text:
#ifndef __vsVvqsDatabaseQueryDialog_h
#define __vsVvqsDatabaseQueryDialog_h

#include <QDialog>

#include <qtGlobal.h>

class QDateTime;
class QUrl;

class vsVvqsDatabaseQueryDialogPrivate;

class vsVvqsDatabaseQueryDialog : public QDialog
{
  Q_OBJECT

public:
  vsVvqsDatabaseQueryDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0);
  ~vsVvqsDatabaseQueryDialog();

  QUrl uri() const;

  virtual void accept();

protected slots:
  void updateTimeUpperFromLower();
  void updateTimeLowerFromUpper();

  void editServerUri();

  void validate();

protected:
  QTE_DECLARE_PRIVATE_RPTR(vsVvqsDatabaseQueryDialog)

private:
  QTE_DECLARE_PRIVATE(vsVvqsDatabaseQueryDialog)
  QTE_DISABLE_COPY(vsVvqsDatabaseQueryDialog)
};

#endif


text:
//
//  HFProgressTracker.h
//  HexFiend_2
//
//  Created by peter on 2/12/08.
//  Copyright 2008 ridiculous_fish. All rights reserved.
//

#import <Cocoa/Cocoa.h>

/*!
@class HFProgressTracker
@brief A class that helps handle progress indication and cancellation for long running threaded operations.

  HFProgressTracker is a class that helps handle progress indication and cancellation for long running threaded operations, while imposing minimal overhead.  Operations such as Find/Replace or Save take an HFProgressTracker to provide cancellation and progress reporting.

  The thread is expected to write directly into the public currentProgress field (perhaps with atomic functions) as it makes progress.  Once beginTrackingProgress is called, the HFProgressTracker will poll currentProgress until endTrackingProgress is called.

  The thread is also expected to read directly from cancelRequested, which is set by the requestCancel method.  If requestCancel is set, it should end the operation.

  Lastly, the thread is expected to call noteFinished: when it is done, either through cancellation or completing normally.

  On the client side, you can set a delegate. progressTracker: didChangeProgressTo: is called on your delegate at regular intervals in the main thread, as the progress changes.  Likewise, progressTrackerDidFinish: is called on the main thread after noteFinished: is called.

  There is also a progressIndicator property, which if set to an NSProgressIndicator will cause it to be updated regularly.

*/

@interface HFProgressTracker : NSObject {
    @public
    volatile unsigned long long currentProgress;
    volatile int cancelRequested;
    @private
    unsigned long long maxProgress;
    NSProgressIndicator *progressIndicator;
    NSTimer *progressTimer;
    double lastSetValue;
    id delegate;
}

/*!
  HFProgressTracker determines the progress as an unsigned long long, but passes the progress to the delegate as a double, which is computed as the current progress divided by the max progress.
*/
@property (nonatomic) unsigned long long maxProgress;

/*!
  The userInfo property is a convenience to allow passing information to the thread.  The property is not thread safe - the expectation is that the main thread will set it before the operation starts, and the background thread will read it once after the operation starts.
*/
@property (nonatomic, copy) NSDictionary *userInfo;

/*!
  The progressIndicator property allows an NSProgressIndicator to be associated with the HFProgressTracker.  The progress indicator should have values in the range 0 to 1, and it will be updated with the fraction currentProgress / maxProgress.
*/
@property (nonatomic, strong) NSProgressIndicator *progressIndicator;

/*!
  Called to indicate you want to begin tracking the progress, which means that the progress indicator will be updated, and the delegate callbacks may fire.
*/
- (void)beginTrackingProgress;

/*!
  Called to indicate you want to end tracking progress.  The progress indicator will no longer be updated.
*/
- (void)endTrackingProgress;

/*!
  noteFinished: should be called by the thread when it is done.  It is safe to call this from the background thread.
*/
- (void)noteFinished:(id)sender;

/*!
  requestCancel: may be called to mark the cancelRequested variable.  The thread should poll this variable to determine if it needs to cancel.
*/
- (void)requestCancel:(id)sender;

/*!
  Set and get the delegate, which may implement the optional methods below.
*/
@property (nonatomic, assign) id delegate;

@end

/*!
@protocol HFProgressTrackerDelegate
@brief The delegate methods for the HFProgressTracker class.

The HFProgressTrackerDelegate methods are called on the the HFProgressTracker's delegate.  These are always called on the main thread.
*/
@protocol HFProgressTrackerDelegate <NSObject>

/*!
  Once beginTrackingProgress is called, this is called on the delegate at regular intervals to report on the new progress.
*/
- (void)progressTracker:(HFProgressTracker *)tracker didChangeProgressTo:(double)fraction;

/*!
  Once the thread has called noteFinished:, this is called on the delegate in the main thread to report that the background thread is done.
*/
- (void)progressTrackerDidFinish:(HFProgressTracker *)tracker;

@end


text:
layout: goal
goal: 1
title: Poverty
img:
---
Custom intro or description for this goal goes here


text:
package org.actorsguildframework.internal;

import org.actorsguildframework.internal.util.L;

/**
 * Worker is the Runnable thread that is managed by {@link ControllerImplementation} to
 * execute messages.
 */
public final class Worker implements Runnable {
	private final static L log = new L(Worker.class);
	private final Controller controller;
	private final KeepRunningInterface keepRunning;

	/**
	 * Creates a new instance.
	 * @param controller the Controller to use
	 * @param keepRunning the kill interface
	 */
	public Worker(Controller controller, KeepRunningInterface keepRunning) {
		this.controller = controller;
		this.keepRunning = keepRunning;
	}

	/**
	 * Keeps processing messages until there are no messages left.
	 */
	public void run() {
		ThreadState ts = ThreadState.get();
		ts.initWorker(controller);
		try {
			controller.getActorLock().lock();
			try {
				while (keepRunning.shouldContinue()) {
					ActorState a = controller.getNextFromQueueUnsynchronized();
					if (a == null)
						break;
					int executed = a.executeAllQueuedMessagesUnsynchronized(ts, keepRunning);
					if ((executed == 0) && (keepRunning.shouldContinue()))
						log.error("Warning: actor state on queue had no messages!");
				}
			}
			catch (InterruptedException e) {
				log.info("Got interrupted exception in worker thread:");
				e.printStackTrace();
			}
			finally {
				controller.getActorLock().unlock();
			}
		}
		catch (RuntimeException e) {
			log.error("Got unexpected exception in worker thread:");
			e.printStackTrace();
			throw e;
		}
		finally {
			ts.uninitWorker();
		}
	}
}


text: For Cooper House Members to push their janky code


text:
using UIKit;

namespace Xamarin.iOS.FileExplorer.ViewControllers
{
	public class ErrorViewController : UIViewController
	{
	}
}


text:
package com.github.takayuki.yabcmin

import org.apache.commons.codec.binary.Hex
import scala.util.hashing.MurmurHash3

object UInt256 {
  val bitLength = 256
  val byteLength = bitLength / 8

  def apply() = new UInt256(new Array[Byte](UInt256.byteLength))
  def apply(value : Array[Byte]) = new UInt256(value)
  def apply(value : String) = new UInt256(value)

  def fromCompact(compact : UInt) : UInt256 = {
    val value = {
      val value = new Array[Byte](UInt256.byteLength)
      val exp = compact >>> 24
      val man = compact & UInt(0x7fffff)
      val sign = compact & UInt(0x800000)
      require(exp.toInt > 3)
      require(sign.toInt == 0)
      val offset = exp.toInt - 3
      if (offset < UInt256.byteLength)
        value(offset) = man.toByte
      if (offset + 1 < UInt256.byteLength)
        value(offset + 1) = (man >>> 8).toByte
      if (offset + 2 < UInt256.byteLength)
        value(offset + 2) = ((man >>> 16) & UInt(0x7f)).toByte
      value
    }
    new UInt256(value)
  }
}

class UInt256(digits : Array[Byte]) extends Serializable
    with Ordered[UInt256] {
  require(digits.length == UInt256.byteLength)

  def this(s : String) = this(Hex.decodeHex(s.toCharArray))

  def array : Array[Byte] = digits

  override def compare(that : UInt256) : Int = {
    var i = UInt256.byteLength - 1
    while (i >= 0 && UByte.eq(that.array(i), this.array(i)))
      i -= 1
    if (i >= 0)
      UByte.cmp(this.array(i), that.array(i))
    else
      0
  }

  def canEqual(other : Any) = other.isInstanceOf[UInt256]

  override def equals(other : Any) = other match {
    case that : UInt256 =>
      that.canEqual(this) && this.array.sameElements(that.array)
    case _ =>
      false
  }

  override def hashCode = MurmurHash3.seqHash(digits)

  override def toString = new String(Hex.encodeHex(digits))
}


text:
/***************************************************************************/
/*                                                                         */
/*  fnterrs.h                                                              */
/*                                                                         */
/*    Win FNT/FON error codes (specification only).                        */
/*                                                                         */
/*  Copyright 2001 by                                                      */
/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
/*                                                                         */
/*  This file is part of the FreeType project, and may only be used,       */
/*  modified, and distributed under the terms of the FreeType project      */
/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
/*  this file you indicate that you have read the license and              */
/*  understand and accept it fully.                                        */
/*                                                                         */
/***************************************************************************/

/*************************************************************************/
/*                                                                       */
/* This file is used to define the Windows FNT/FON error enumeration     */
/* constants.                                                            */
/*                                                                       */
/*************************************************************************/

#ifndef __FNTERRS_H__
#define __FNTERRS_H__

#include FT_MODULE_ERRORS_H

#undef __FTERRORS_H__

#define FT_ERR_PREFIX FNT_Err_
#define FT_ERR_BASE FT_Mod_Err_Winfonts

#include FT_ERRORS_H

#endif /* __FNTERRS_H__ */

/* END */


text:
namespace System.Windows
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Diagnostics.Contracts;
    using System.Runtime.InteropServices;
    using System.Windows.Interop;

    /// <summary>
    /// Provides extension methods for the <see cref="Window"/> class.
    /// </summary>
    public static class WindowExtensions
    {
        /// <summary>
        /// Removes the window icon.
        /// </summary>
        /// <param name="window">The <see cref="Window">window</see> to remove the icon from.</param>
        public static void RemoveIcon( this Window window )
        {
            Arg.NotNull( window, nameof( window ) );

            var helper = new WindowInteropHelper( window );
            var hwnd = helper.Handle;

            RemoveIcon( hwnd );
            UpdateNonClientArea( hwnd );
        }

        /// <summary>
        /// Gets the client size of the window.
        /// </summary>
        /// <param name="window">The <see cref="Window">window</see> to get the client size of.</param>
        /// <returns>The client area <see cref="Size">size</see>.</returns>
        [SuppressMessage( "Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "This method only applies to windows." )]
        [SuppressMessage( "Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Validated by a code contract." )]
        public static Size GetClientSize( this Window window )
        {
            Arg.NotNull( window, nameof( window ) );

            var width = window.ActualWidth - ( SystemParameters.ResizeFrameVerticalBorderWidth * 2d );
            var height = window.ActualHeight - ( ( SystemParameters.ResizeFrameHorizontalBorderHeight * 2d ) + SystemParameters.WindowCaptionHeight );

            return new Size( width, height );
        }

        /// <summary>
        /// Sets the enabled state of the window close button.
        /// </summary>
        /// <param name="window">The <see cref="Window">window</see> to set the close button state of.</param>
        /// <param name="value">Indicates whether the close button is enabled.</param>
        public static void SetCloseButtonEnabled( this Window window, bool value )
        {
            Arg.NotNull( window, nameof( window ) );

            var helper = new WindowInteropHelper( window );
            var hwnd = helper.Handle;

            ToggleSystemMenuItem( hwnd, NativeMethods.CloseButton, enabled: value );
        }

        static void RemoveIcon( IntPtr hwnd )
        {
            var extendedStyle = NativeMethods.GetWindowLong( hwnd, NativeMethods.ExtendedStyle );

            if ( NativeMethods.SetWindowLong( hwnd, NativeMethods.ExtendedStyle, extendedStyle | NativeMethods.DialogModalFrame ) == 0 )
            {
                Marshal.ThrowExceptionForHR( Marshal.GetLastWin32Error() );
            }
        }

        static void UpdateNonClientArea( IntPtr hwnd )
        {
            var flags = NativeMethods.NoMove | NativeMethods.NoSize | NativeMethods.NoZOrder | NativeMethods.FrameChanged;

            if ( !NativeMethods.SetWindowPos( hwnd, IntPtr.Zero, 0, 0, 0, 0, flags ) )
            {
                Marshal.ThrowExceptionForHR( Marshal.GetLastWin32Error() );
            }
        }

        static void ToggleSystemMenuItem( IntPtr hwnd, uint menuItemID, bool enabled )
        {
            var menu = NativeMethods.GetSystemMenu( hwnd, false );

            if ( menu == IntPtr.Zero )
            {
                return;
            }

            var flags = enabled ? NativeMethods.EnabledFlag : NativeMethods.GrayedFlag;
            NativeMethods.EnableMenuItem( menu, menuItemID, flags );
        }
    }
}


text:
package ca.uhn.fhir.jpa.entity;

import ca.uhn.fhir.jpa.model.entity.ResourceTable;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "HFJ_SUBSCRIPTION_STATS", uniqueConstraints = {
	@UniqueConstraint(name = "IDX_SUBSC_RESID", columnNames = {"RES_ID"}),
})
public class SubscriptionTable {

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "CREATED_TIME", nullable = false, insertable = true, updatable = false)
	private Date myCreated;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_SUBSCRIPTION_ID")
	@SequenceGenerator(name = "SEQ_SUBSCRIPTION_ID", sequenceName = "SEQ_SUBSCRIPTION_ID")
	@Column(name = "PID", insertable = false, updatable = false)
	private Long myId;

	@Column(name = "RES_ID", insertable = false, updatable = false)
	private Long myResId;

	@OneToOne()
	@JoinColumn(name = "RES_ID", insertable = true, updatable = false, referencedColumnName = "RES_ID",
		foreignKey = @ForeignKey(name = "FK_SUBSC_RESOURCE_ID")
	)
	private ResourceTable mySubscriptionResource;

	/**
	 * Constructor
	 */
	public SubscriptionTable() {
		super();
	}

	public Date getCreated() {
		return myCreated;
	}

	public void setCreated(Date theCreated) {
		myCreated = theCreated;
	}

	public Long getId() {
		return myId;
	}

	public ResourceTable getSubscriptionResource() {
		return mySubscriptionResource;
	}

	public void setSubscriptionResource(ResourceTable theSubscriptionResource) {
		mySubscriptionResource = theSubscriptionResource;
	}

}


text:
package diff

import (
	"github.com/zclconf/go-cty/cty"
)

// Change is an abstract type representing a single change operation as
// part of a Diff.
//
// Change is a closed interface, meaning that the only permitted
// implementations are those within this package.
type Change interface {
	changeSigil() changeImpl
}

// Embed changeImpl into a struct to make it a Change implementation
type changeImpl struct{}

func (c changeImpl) changeSigil() changeImpl {
	return c
}

// ReplaceChange is a Change implementation that represents replacing an
// existing value with an entirely new value.
//
// When adding a new element to a map value, this change type should be used
// with OldValue set to a null value of the appropriate type.
type ReplaceChange struct {
	changeImpl
	Path     cty.Path
	OldValue cty.Value
	NewValue cty.Value
}

// DeleteChange is a Change implementation that represents removing an
// element from an indexable collection.
//
// For a list type, if the deleted element is not the final element in
// the list then the resulting "gap" is closed by renumbering all subsequent
// items. Therefore a Diff containing a sequence of DeleteChange operations
// on the same list must be careful to consider the new state of the element
// indices after each step, or present the deletions in reverse order to
// avoid such complexity.
type DeleteChange struct {
	changeImpl
	Path     cty.Path
	OldValue cty.Value
}

// InsertChange is a Change implementation that represents inserting a new
// element into a list.
//
// When appending to a list, the Path should be to the not-yet-existing index
// and BeforeValue should be a null of the appropriate type.
type InsertChange struct {
	changeImpl
	Path        cty.Path
	NewValue    cty.Value
	BeforeValue cty.Value
}

// AddChange is a Change implementation that represents adding a value to
// a set. The Path is to the set itself, and NewValue is the value to insert.
type AddChange struct {
	changeImpl
	Path     cty.Path
	NewValue cty.Value
}

// RemoveChange is a Change implementation that represents removing a value
// from a set. The path is to the set itself, and OldValue is the value to
// remove.
//
// Note that it is not possible to remove an unknown value from a set
// because no two unknown values are equal, so a diff whose source value
// had sets with unknown members cannot be applied and is useful only
// for presentation to a user. Generally-speaking one should avoid including
// unknowns in the source value when creating a diff.
type RemoveChange struct {
	changeImpl
	Path     cty.Path
	OldValue cty.Value
}

// NestedDiff is a Change implementation that applies a nested diff to a
// value.
//
// A NestedDiff is similar to a ReplaceChange, except that rather than
// providing a literal new value the replacement value is instead the result
// of applying the diff to the old value.
//
// The Paths in the nested diff are relative to the path of the NestedDiff
// node, so the absolute paths of the affected elements are the concatenation
// of the two.
//
// This is primarily useful for representing updates to set elements. Since
// set elements are addressed by their own value, it convenient to specify
// the value path only once and apply a number of other operations to it.
// However, it's acceptable to use NestedDiff on any value type as long as
// the nested diff is valid for that type.
type NestedDiff struct {
	changeImpl
	Path     cty.Path
	OldValue cty.Value
	Diff     Diff
}

// Context is a funny sort of Change implementation that doesn't actually
// change anything but fails if the value at the given path doesn't match
// the given value.
//
// This can be used to add additional context to a diff so that merge
// conflicts can be detected.
type Context struct {
	changeImpl
	Path      cty.Path
	WantValue cty.Value
}


text:
package com.optimalorange.cooltechnologies.ui;

import com.optimalorange.cooltechnologies.R;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class SimpleWebViewActivity extends Activity {

    /**
     * 应当显示的页面的url<br/>
     * Type: {@link String}
     */
    public static final String EXTRA_KEY_LINK =
            SimpleWebViewActivity.class.getName() + ".extra.KEY_VIDEO_LINK";

    /** 用于重置{@link WebView}的空网页 */
    private static final String URL_BLANK = "about:blank";

    private String mLink;

    private WebView mWebView;

    public static Intent buildIntent(Context context, String link) {
        final Intent result = new Intent(context, SimpleWebViewActivity.class);
        result.putExtra(EXTRA_KEY_LINK, link);
        return result;
    }

    public static void start(Context context, String link) {
        context.startActivity(buildIntent(context, link));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_web_view);

        mLink = getIntent().getStringExtra(EXTRA_KEY_LINK);
        if (mLink == null) {
            throw new IllegalStateException("Please set url link with EXTRA_KEY_LINK");
        }

        mWebView = (WebView) findViewById(R.id.web_view);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new WebViewClient());
    }

    @Override
    protected void onStart() {
        super.onStart();
        mWebView.loadUrl(mLink);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // call it because this didn't extend BaseActivity
        MobclickAgent.onResume(this);
        MobclickAgent.onPageStart(getClass().getSimpleName());

        mWebView.onResume();
    }

    @Override
    protected void onPause() {
        mWebView.onPause();

        MobclickAgent.onPageEnd(getClass().getSimpleName());
        MobclickAgent.onPause(this);
        super.onPause();
    }

    @Override
    protected void onStop() {
        mWebView.loadUrl(URL_BLANK);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        final ViewParent parent = mWebView.getParent();
        if (parent != null) {
            ((ViewGroup) parent).removeView(mWebView);
            mWebView.destroy();
        }
        mWebView = null;
        super.onDestroy();
    }

}


text:
'''Fork a child process and inform it of mode changes to each screen.  The
child waits until the parent process dies, and then connects to each X server
with a mode change and restores the mode.

This emulates the behaviour of Windows and Mac, so that resolution changes
made by an application are not permanent after the program exits, even if
the process is terminated uncleanly.

The child process is communicated to via a pipe, and watches for parent
death with a Linux extension signal handler.
'''

import ctypes
import os
import mutex
import signal
import struct

from pyglet.libs.x11 import xlib
try:
    from pyglet.libs.x11 import xf86vmode
except:
    # No xf86vmode... should not be switching modes.
    pass

_restore_mode_child_installed = False
_restorable_screens = set()
_mode_write_pipe = None

# Mode packets tell the child process how to restore a given display and
# screen.  Only one packet should be sent per display/screen (more would
# indicate redundancy or incorrect restoration).  Packet format is:
#   display (max 256 chars),
#   screen
#   width
#   height
#   rate
class ModePacket(object):
    format = '256siHHI'
    size = struct.calcsize(format)
    def __init__(self, display, screen, width, height, rate):
        self.display = display
        self.screen = screen
        self.width = width
        self.height = height
        self.rate = rate

    def encode(self):
        return struct.pack(self.format, self.display, self.screen,
                           self.width, self.height, self.rate)

    @classmethod
    def decode(cls, data):
        display, screen, width, height, rate = \
            struct.unpack(cls.format, data)
        return cls(display.strip('\0'), screen, width, height, rate)

    def __repr__(self):
        return '%s(%r, %r, %r, %r, %r)' % (
            self.__class__.__name__, self.display, self.screen,
            self.width, self.height, self.rate)

    def set(self):
        display = xlib.XOpenDisplay(self.display)
        modes, n_modes = get_modes_array(display, self.screen)
        mode = get_matching_mode(modes, n_modes,
                                 self.width, self.height, self.rate)
        if mode is not None:
            xf86vmode.XF86VidModeSwitchToMode(display, self.screen, mode)
        free_modes_array(modes, n_modes)
        xlib.XCloseDisplay(display)

def get_modes_array(display, screen):
    count = ctypes.c_int()
    modes = ctypes.POINTER(ctypes.POINTER(xf86vmode.XF86VidModeModeInfo))()
    xf86vmode.XF86VidModeGetAllModeLines(display, screen, count, modes)
    return modes, count.value

def get_matching_mode(modes, n_modes, width, height, rate):
    # Copy modes out of list and free list
    for i in range(n_modes):
        mode = modes.contents[i]
        if (mode.hdisplay == width and
            mode.vdisplay == height and
            mode.dotclock == rate):
            return mode
    return None

def free_modes_array(modes, n_modes):
    for i in range(n_modes):
        mode = modes.contents[i]
        if mode.privsize:
            xlib.XFree(mode.private)
    xlib.XFree(modes)

def _install_restore_mode_child():
    global _mode_write_pipe
    global _restore_mode_child_installed

    if _restore_mode_child_installed:
        return

    # Parent communicates to child by sending "mode packets" through a pipe:
    mode_read_pipe, _mode_write_pipe = os.pipe()

    if os.fork() == 0:
        # Child process (watches for parent to die then restores video mode(s).
        os.close(_mode_write_pipe)

        # Set up SIGHUP to be the signal for when the parent dies.
        PR_SET_PDEATHSIG = 1
        libc = ctypes.cdll.LoadLibrary('libc.so.6')
        libc.prctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong,
                               ctypes.c_ulong, ctypes.c_ulong)
        libc.prctl(PR_SET_PDEATHSIG, signal.SIGHUP, 0, 0, 0)

        # SIGHUP indicates the parent has died.  The child mutex is unlocked, it
        # stops reading from the mode packet pipe and restores video modes on
        # all displays/screens it knows about.
        def _sighup(signum, frame):
            parent_wait_mutex.unlock()
        parent_wait_mutex = mutex.mutex()
        parent_wait_mutex.lock(lambda arg: arg, None)
        signal.signal(signal.SIGHUP, _sighup)

        # Wait for parent to die and read packets from parent pipe
        packets = []
        buffer = ''
        while parent_wait_mutex.test():
            try:
                data = os.read(mode_read_pipe, ModePacket.size)
                buffer += data
                # Decode packets
                while len(buffer) >= ModePacket.size:
                    packet = ModePacket.decode(buffer[:ModePacket.size])
                    packets.append(packet)
                    buffer = buffer[ModePacket.size:]
            except OSError:
                pass # Interrupted system call

        for packet in packets:
            packet.set()
        os._exit(0)

    else:
        # Parent process.  Clean up pipe then continue running program as
        # normal.  Send mode packets through pipe as additional
        # displays/screens are mode switched.
        os.close(mode_read_pipe)
        _restore_mode_child_installed = True

def set_initial_mode(mode):
    _install_restore_mode_child()

    display = xlib.XDisplayString(mode.screen.display._display)
    screen = mode.screen.display.x_screen

    # Only store one mode per screen.
    if (display, screen) in _restorable_screens:
        return

    packet = ModePacket(display, screen, mode.width, mode.height, mode.rate)

    os.write(_mode_write_pipe, packet.encode())
    _restorable_screens.add((display, screen))


text:
<?php

namespace rock\validate\locale\en;

use rock\validate\locale\Locale;

class Readable extends Locale
{
    public function defaultTemplates()
    {
        return [
            self::MODE_DEFAULT => [
                self::STANDARD => '{{name}} must be readable',
            ],
            self::MODE_NEGATIVE => [
                self::STANDARD => '{{name}} must not be readable',
            ]
        ];
    }

    public function defaultPlaceholders()
    {
        return ['name' => 'file'];
    }
}


text:
nix-exec
=========

`nix-exec` is a tool to run programs defined in nix expressions. It has
two major goals:

* Provide a common framework for defining libraries for tools that require
  complex interactions with `nix`, such as `hydra` and `nixops` (and arguably
  `nix-env` and `nixos-rebuild`), both to increase ease of development and to
  encourage reusability
* Define a basic minimal bootstrapping environment for `nix`-using tools. For
  example, using `nixops` currently requires you to install `python` and
  several `python` libraries, and `hydra` requires a `perl` web framework. If
  both were rewritten to be `nix-exec` programs, a system containing only
  `nix-exec` and the top-level scripts for `hydra` and `nixops` could
  run either without any futher manual installation.

`nix-exec` is designed to have a minimal interface to keep it usable in as
wide of a context as possible.

Invocation
-----------

    $ nix-exec SCRIPT [ARGS...]

`nix-exec` is meant to be invoked on a `nix` script, with an optional set of
arguments. Any arguments recognized by `nix` passed before the script name
(such as `--verbose`) will be used to initialize `nix`. If the script name
starts with a `-`, the `--` argument can be used to signify the end of
arguments that should be possibly passed to `nix`.

`nix-exec` is designed to be usable in a shebang.

Expression entry point
-----------------------

The top-level script should evaluate to a function of a single argument
that returns a `nix-exec` IO value (see below). The argument will be an
attribute set containing a list `args` of the arguments passed to the script
(including the script name) and an attribute set `lib` containing the IO
monad functions and `nix-exec`'s configuration settings.

IO monad
---------

`nix-exec` provides a [monad][1]
for defining programs which it executes. The `lib` argument contains the monad functions:

* `unit` (AKA `return`) :: a -> m a: Bring a value into the monad
* `map` (AKA `fmap`) :: (a -> b) -> m a -> m b: Apply a function to a monadic
  value
* `join` :: m m a -> m a: 'Flatten' a nested monadic value

For Haskell programmers, note that this is the
['map and join'][2]
definition of a monad, and that the familiar `>>=` can be defined in terms of
`map` and `join`.

dlopen
-------

In addition, the `nix-exec` `lib` argument contains a `dlopen` function to
allow native code to be executed when running the `IO` value. `dlopen` takes
three arguments, `filename`, `symbol`, and `args`.

When running a monadic value resulting from a call `dlopen`, `nix-exec` will
dynamically load the file at `filename`, load a `nix::PrimOpFun` from the DSO
at symbol `symbol`, and pass the values in the `args` list to the `PrimOpFun`.
`PrimOpFun` is defined in `<nix/eval.hh>`.

The `filename` argument can be the result of a derivation, in which case
`nix-exec` will build the derivation before trying to dynamically load it.

Note that the `PrimOpFun` must return a value that is properly forced, i.e.
not a thunk or an un-called function application.

Configuration settings
-----------------------

The `configuration` attribute in the `nix-exec` `lib` argument is a set
containing the following information about the compile-time configuration
of `nix-exec`:

* `prefix`: The installation prefix
* `datadir`:  The data directory
* `version.major`: The major version number
* `version.minor`: The minor version number
* `version.patchlevel`: The version patchlevel.

unsafe-perform-io
------------------

The `builtins` attribute in the `nix-exec` lib contains contains an
`unsafe-perform-io` attribute that is a function that takes an IO value, runs
it, and returns the produced value. It has largely similar pitfalls to Haskell's
`unsafePerformIO` function.

fetchgit
---------

For bootstrapping purposes, the `builtins` attribute in the `nix-exec` lib
contains a `fetchgit` attribute that is a function that takes a set with the
following arguments:

* `url`: The URL of the repository
* `rev`: The desired revision
* `fetchSubmodules`: Whether to fetch submodules (default `true`)
* `cache-dir`: The directory to cache repos and archives in (default
  `$HOME/.cache/fetchgit`).

When called, `fetchgit` returns an IO value that, when run, checks out
the given revision of the given git repository into a directory and yields a
`path` pointing to that directory.

reexec
-------

For bootstrapping purposes, the `builtins` attribute in the `nix-exec` lib
contains a `reexec` attribute that is a function that takes a path to a
`nix-exec` binary and returns an IO value that, when run, reexecutes itself with
the passed in path if and only if the path is different than how `nix-exec` was
originally executed, and yields null otherwise. This allows the use of a fixed
version of `nix-exec` and its dependencies (especially `nix`), though of course
the path to `nix-exec` itself must be evaluatable with the host version of
`nix-exec`.

Global symbols
--------------

`nix-exec` defines a number of external variables in the C header
`<nix-exec.h>` to introspect the execution environment:

* `nixexec_argc`: The number of arguments passed to `nix-exec`
* `nixexec_argv`: A NULL-terminated list of arguments passed to `nix-exec`

In addition, symbols defined in `libnixmain`, `libnixexpr`, and `libnixstore`
are all available.

unsafe-lib.nix
----------------

For cases where the expression author doesn't completely control the invocation
of the evaluator (e.g. `nixops` has no way to specify that it should run
`nix-exec`), `nix-exec` installs `unsafe-lib.nix` in `$(datadir)/nix`. Importing
this file evaluates to the `lib` set passed to normal `nix-exec` programs. This
uses `builtins.importNative` under the hood, so it requires the
`allow-unsafe-native-code-during-evaluation` nix option to be set to true.

Note that when using `unsafe-lib.nix`, `nixexec_argc` will be `0` and
`nixexec_argv` will be `NULL` unless called within an actual `nix-exec`
invocation.

API stability
--------------

The `nix::PrimOpFun` API is not necessarily stable from version to version of
`nix`. As such, scripts should inspect `builtins.nixVersion` to ensure that
loaded dynamic objects are compatible.

Example
-------

This prints out the arguments passed to it, one per line:

```nix
#!/usr/bin/env nix-exec
{ args, lib }: let
  pkgs = import <nixpkgs> {};

  print-args-src = builtins.toFile "print-args.cc" ''
    #include <iostream>
    #include <eval.hh>
    #include <eval-inline.hh>

    extern "C" void print(nix::EvalState & state, const nix::Pos & pos, nix::Value ** args, nix::Value & v) {
      state.forceList(*args[0], pos);
      for (unsigned int index = 0; index < args[0]->list.length; ++index) {
        auto str = state.forceStringNoCtx(*args[0]->list.elems[index], pos);
        std::cout << str << std::endl;
      }
      v.type = nix::tNull;
    }
  '';

  print-args-so = pkgs.runCommand "print-args.so" {} ''
    c++ -shared -fPIC -I${pkgs.nixUnstable}/include/nix -I${pkgs.boehmgc}/include -std=c++11 -O3 ${print-args-src} -o $out
    strip -S $out
  '';

  printArgs = args: lib.dlopen print-args-so "print" [ args ];
in printArgs args
```

[1]: http://en.wikipedia.org/wiki/Monad_(functional_programming)
[2]: http://en.wikipedia.org/wiki/Monad_(functional_programming)#fmap_and_join


text:
// This file is distributed under the MIT license.
// See the LICENSE file for details.

#pragma once

#ifndef VSNRAY_INTERSECTOR_H
#define VSNRAY_INTERSECTOR_H 1

#include <type_traits>
#include <utility>

#include "detail/macros.h"
#include "detail/tags.h"
#include "bvh.h"

namespace visionaray
{

//-------------------------------------------------------------------------------------------------
// Base type for custom intersectors
//

template <typename Derived>
struct basic_intersector
{
    template <size_t N>
    using multi_hit_max = std::integral_constant<size_t, N>;

    template <typename R, typename P, typename ...Args>
    VSNRAY_FUNC
    auto operator()(R const& ray, P const& prim, Args&&... args)
        -> decltype( intersect(ray, prim, std::forward<Args>(args)...) )
    {
        return intersect(ray, prim);
    }

    // BVH ------------------------------------------------

    template <typename R, typename P, typename = typename std::enable_if<is_any_bvh<P>::value>::type>
    VSNRAY_FUNC
    auto operator()(R const& ray, P const& prim)
        -> decltype( intersect(ray, prim, std::declval<Derived&>()) )
    {
        return intersect(ray, prim, *static_cast<Derived*>(this));
    }

    // BVH any hit ----------------------------------------

    template <
        typename R,
        typename P,
        typename Cond,
        typename = typename std::enable_if<is_any_bvh<P>::value>::type
        >
    VSNRAY_FUNC
    auto operator()(
            detail::any_hit_tag     /* */,
            multi_hit_max<1>        /* */,
            R const&                ray,
            P const&                prim,
            typename R::scalar_type max_t,
            Cond                    update_cond = Cond()
            )
        -> decltype( intersect<detail::AnyHit>(ray, prim, std::declval<Derived&>(), max_t, update_cond) )
    {
        return intersect<detail::AnyHit>(ray, prim, *static_cast<Derived*>(this), max_t, update_cond);
    }

    // BVH closest hit ------------------------------------

    template <
        typename R,
        typename P,
        typename Cond,
        typename = typename std::enable_if<is_any_bvh<P>::value>::type
        >
    VSNRAY_FUNC
    auto operator()(
            detail::closest_hit_tag /* */,
            multi_hit_max<1>        /* */,
            R const&                ray,
            P const&                prim,
            typename R::scalar_type max_t,
            Cond                    update_cond = Cond()
            )
        -> decltype( intersect<detail::ClosestHit>(ray, prim, std::declval<Derived&>(), max_t, update_cond) )
    {
        return intersect<detail::ClosestHit>(ray, prim, *static_cast<Derived*>(this), max_t, update_cond);
    }

    // BVH multi hit --------------------------------------

    template <
        size_t   N,
        typename R,
        typename P,
        typename Cond,
        typename = typename std::enable_if<is_any_bvh<P>::value>::type
        >
    VSNRAY_FUNC
    auto operator()(
            detail::multi_hit_tag   /* */,
            multi_hit_max<N>        /* */,
            R const&                ray,
            P const&                prim,
            typename R::scalar_type max_t,
            Cond                    update_cond = Cond()
            )
        -> decltype( intersect<detail::MultiHit, N>(ray, prim, std::declval<Derived&>(), max_t, update_cond) )
    {
        return intersect<detail::MultiHit, N>(ray, prim, *static_cast<Derived*>(this), max_t, update_cond);
    }
};

//-------------------------------------------------------------------------------------------------
// Default intersector
//

struct default_intersector : basic_intersector<default_intersector>
{
};

} // visionaray

#endif // VSNRAY_INTERSECTOR_H


text:
#ifndef FALSECOLOR_H_
#define FALSECOLOR_H_

#include <opencv2/core/core.hpp>
#include <opencv2/contrib/retina.hpp>
#include <boost/shared_ptr.hpp>

class converter_16_8
{
  enum
  {
    histminmembersperbucket = 10,
  };
private:
  double max_;
  double min_;
  static converter_16_8* inst_;
  bool firstframe_;
  boost::shared_ptr<cv::Retina> retina_;
public:
  converter_16_8();
  ~converter_16_8();
  static converter_16_8& Instance()
  {
    if (!inst_)
    {
      inst_ = new converter_16_8;
    }
    return *inst_;
  }
  double getMax();
  double getMin();
  void convert_to8bit(const cv::Mat& img16, cv::Mat& img8, bool doTempConversion);
  void toneMapping(const cv::Mat& img16, cv::Mat& img8);
};

struct color
{
  unsigned char rgbBlue;
  unsigned char rgbGreen;
  unsigned char rgbRed;
  color()
  {
    rgbBlue = rgbGreen = rgbRed = 0;
  }
};

struct palette
{
  enum palettetypes{
    Linear_red_palettes, GammaLog_red_palettes, Inversion_red_palette, Linear_palettes, GammaLog_palettes,
    Inversion_palette, False_color_palette1, False_color_palette2, False_color_palette3, False_color_palette4
  };
  color colors[256];
};

palette GetPalette(palette::palettetypes pal);

void convertFalseColor(const cv::Mat& srcmat, cv::Mat& dstmat, palette::palettetypes paltype, bool drawlegend = false, double mintemp = 0, double maxtemp = 0);

#endif /* FALSECOLOR_H_ */


text:
@interface Artist : MTLModel <MTLJSONSerializing, ARFollowable, ARShareableObject, ARHasImageURLs>

@property (readonly, nonatomic, copy) NSString *artistID;
@property (readonly, nonatomic, copy) NSString *name;
@property (readonly, nonatomic, copy) NSString *years;
@property (readonly, nonatomic, copy) NSString *birthday;
@property (readonly, nonatomic, copy) NSString *nationality;
@property (readonly, nonatomic, copy) NSString *blurb;
@property (readonly, nonatomic, copy) NSNumber *publishedArtworksCount;
@property (readonly, nonatomic, copy) NSNumber *forSaleArtworksCount;

- (instancetype)initWithArtistID:(NSString *)artistID;

- (void)getFollowState:(void (^)(ARHeartStatus status))success failure:(void (^)(NSError *error))failure;
- (AFHTTPRequestOperation *)getArtworksAtPage:(NSInteger)page andParams:(NSDictionary *)params success:(void (^)(NSArray *artworks))success;

- (AFHTTPRequestOperation *)getRelatedPosts:(void (^)(NSArray *posts))success;
- (AFHTTPRequestOperation *)getRelatedArtists:(void (^)(NSArray *artists))success;

- (NSURL *)squareImageURL;

- (NSString *)publicURL;
@end


text:
package org.braddle.tddworkshop.ledger;

public interface Ledger {
    int calculate(String sum);
}


text:
        <button type="button" class="btn btn-sm" ng-click="vm.reset()">

        </button>

            <gantt-tree enabled="true"></gantt-tree>
            <gantt-tooltips enabled="true" date-format="'HH:mm:ss'" delay="100"></gantt-tooltips>

{{n}}

                <nvd3 options="vm.pieOptions" data="vm.pieData[$index]">

            </nvd3>


text:
const {
    readPackageConfig,
    getDedicatedLayerArn,
    getRuntimeVersion
} = require('./common');

const { runtime, profile, region } = readPackageConfig();

const claudiaCommand = [
    "claudia",
    "update",
    `--profile ${profile}`
];

// if runtime is upper than nodejs10.x, need Layer
if (getRuntimeVersion(runtime) >= 10) {
    claudiaCommand.push(`--layers ${getDedicatedLayerArn(region)}`);
}

process.stdout.write(claudiaCommand.join(" "));


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bryologist 111(3): 388 (2008)

#### Original name
Haematomma caperaticum Brodo, W.L. Culb. & C.F. Culb.

### Remarks
null